# zhadao/bili-watchlater_history-_manager- architecture

> Architecture diagram of the GitHub repository zhadao/bili-watchlater_history-_manager-, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/zhadao/bili-watchlater_history-_manager-
- Repository: https://github.com/zhadao/bili-watchlater_history-_manager-

## Overview

##### 项目类型与目的（从 README + 文件树推断）
这是一个 **Chrome 浏览器扩展（Extension）**，面向 **Bilibili 网页** 的“稍后再看/历史记录”页面做增强。核心目标两块：
##### 本地词频/注意力分析：抓取“稍后再看/历史记录”页面上的视频标题做分词/词频统计，支持停用词、字典、自定义短语、黑名单、主题切换、交互筛选等。
强调点：**纯前端本地分析、无后端、无数据库、配置本地持久化（README 提到 LocalStorage）**。

##### 文件结构拆解（用来决定图里该画哪些“组件”）
顶层文件极少，典型 MV3/MV2 扩展结构（是否 MV3 由 manifest.json 决定，你画图时要读它确认 service worker / background page 形态）：

- `manifest.json`
**在架构图里它不是运行时组件，但它决定运行时组件连接方式**（谁注入谁、权限边界）。

- `background.js`
扩展后台常驻/半常驻逻辑：通常负责
- 监听浏览器事件（tab、消息、安装）
- 与 content script 做消息总线（chrome.runtime.onMessage / sendMessage）
- 可能处理跨域请求/权限更高的 API（若需要）
你的系统图中它是一个**独立进程/上下文**（“Extension Background”）。

- `content.js`
注入到 bilibili 页面，直接操作 DOM：
- 在“稍后再看播放页”插入悬浮按钮
- 在“列表页/历史页”插入分析面板、读取标题列表、渲染词云/榜单/右侧过滤列表、高亮
- 与 background 通信（若有）
- 与 LocalStorage/Chrome Storage 交互（README写 LocalStorage；也可能部分走 chrome.storage，需查代码或 manifest 权限）
系统图中它是**Page Context/Content Script**（与网页 DOM 紧密绑定）。

- `style.css`
注入 UI 的样式（分析面板、主题色等）。
系统图中可作为 content script 的“UI 资源/静态资源”。

- `stopwords.txt`
内置停用词库：用于过滤高频无意义词；README提到可在线编辑并保存。
图中作为 **“内置数据资源（可被用户覆盖/编辑后的版本持久化）”**。

扩展图标资源；通常不进入系统交互图的核心流程，但可在“静态资源”里归类。

> 结论：这是一个 **“Browser Extension + DOM 注入 + 本地存储 + 纯前端算法”** 的单体结构，不涉及服务端部署，也没有传统数据库、队列等。

##### 从 README 提炼运行时“主流程”（建议画成数据流）
你要画“最准确”的系统设计图，建议至少覆盖 3 条关键用户路径（每条都对应一组组件交互箭头）：

##### `content.js` 解析当前视频 BV/AV 或链接 → `window.open` 新标签打开普通播放页
（如果需要权限或统一打开策略，也可能把“打开新标签”交给 `background.js` 通过 `chrome.tabs.create` 执行——你需要看实现决定箭头是否经过 background。）

##### 读取停用词：
- 内置 `stopwords.txt`（默认）
- 用户编辑后的版本（持久化）

##### 建议你画的“最贴近真实架构”的图：分 3 个层级
对 Principal 工程师来说，最清晰的方式不是一张“巨图”，而是 **三张互相一致的图**（或一张图分 3 个泳道/层）：

目的：回答“这个扩展和外部世界怎么交互？”
包含组件（尽量细分）：
- **User / Browser (Chrome)**
- **Bilibili Web Pages**（至少拆两类框：
- WatchLater Player Page（列表播放页）
- WatchLater List / History Page（列表页/历史页））
- **Extension**（一个大框，内部先不展开）
- **Local Persistence**（LocalStorage / chrome.storage，画成浏览器本地存储）
- （可选）**External Network**：理论上无；如果代码有 fetch 到 bilibili API 或其他域名，再补上

箭头要画清：
- User → Browser → Bilibili page（浏览）
- Extension ↔ Bilibili page（DOM 注入、读取标题、打开新页）
- Extension ↔ Local Persistence（读写配置）

把 Extension 这个大框拆成“真实运行上下文”：
- **Content Script (`content.js`)**
子模块可以再拆：
- Page Detector（判断 watchlater/history）
- DOM Scraper（提取标题列表）
- Analyzer（分词/词频/归一化）
- UI Renderer（面板/词云/榜单/右侧列表）
- Interaction Controller（双击筛选、高亮、跳转）
- Config Manager（字典/黑名单/自定义短语/主题）
- **Background (`background.js`)**
- Message Router（runtime messaging）
- Tabs/Window Ops（如果存在）
- Lifecycle hooks（install/update）
- **Static Resources**
- `style.css`
- `stopwords.txt`（内置）
- **Storage**
- LocalStorage (per-origin, page context) 或 chrome.storage (extension scope)——用你实际读到的实现来标注准确
- “Edited stopwords / user config”作为逻辑数据表述出来（例如：`dictionary[]`, `customPhrases[]`, `blacklist[]`, `theme`, `stopwordsOverrideText`）

关键关系箭头：
- Content Script → Bilibili DOM（read/write）
- Content Script → Storage（read/write）
- Content Script ↔ Background（messages；仅在实际用到时画）
- Content Script → `stopwords.txt`（加载默认停用词；如果通过 fetch/chrome.runtime.getURL 读取，就标注“Resource load”）
- Content Script → Browser Tabs API（若通过 background 才能用，就画 Content → Background → Tabs API）

##### (3) Component/Sequence（用时序图或数据流图表达算法路径）
在扩展里，“词频分析”其实是主要复杂度。建议补一张：
- 时序图：User click “Analyze” → content.js collect titles → tokenize → apply dictionary → normalize case → remove stopwords/blacklist → count → render → bind events.
- 或 DFD：Titles → Preprocess → Tokenize → Filter → Count → Sort TopN → UI.

##### 两种页面场景：
- “稍后再看播放页”侧重按钮跳转
- “列表页/历史页”侧重分析面板
这会影响 content script 的触发条件与 DOM 结构依赖，建议在图中把目标页面拆开画。
##### 本地持久化边界：
README写 LocalStorage，但扩展更常用 chrome.storage。你在图里用中性写法：
- “Browser Local Persistence (LocalStorage / chrome.storage)”
##### stopwords.txt 的双态：内置静态资源 + 用户可编辑覆盖后的版本（持久化）。这对“数据源”非常关键，建议画成两层：
- Default Stopwords (stopwords.txt)
- User Override Stopwords (stored)
5. **安全/权限边界**：扩展 = 特权环境；网页 = 非特权环境；content script 是桥梁。Principal 视角通常会要求你在图上标出这个 trust boundary。

##### 画图规范与表达建议（让图“可读且可审计”）
你要“尽量细分组件”，但仍保持可读性，建议这样编码：

##### 组件形状与颜色（建议）
- **矩形（蓝色）**：运行时代码模块（background/content script）
- **圆柱（绿色）**：存储（LocalStorage/chrome.storage）
- **网页框（橙色）**：Bilibili 页面（按页面类型拆分）
- **虚线边框**：权限/信任边界（Browser Extension vs Web Page）

##### 箭头标注（必须写清“数据/动作”）
不要只画“连线”，要在箭头上写：
- “Inject UI / CSS”
- “Read DOM titles”
- “Open normal video page (new tab)”
- “Load stopwords (default)”
- “Read/Write config (theme/dictionary/blacklist/custom phrases)”
- “Message: analyze request / openTab request”（如果有 background 通信）

##### 在图角落放一个“小表格”列关键技术
- Chrome Extension (manifest.json)
- background.js / content.js
- LocalStorage / (chrome.storage)
- DOM scraping + tokenization + frequency count
- stopwords.txt dictionary/blacklist mechanisms
- CSS themes

##### 一张“建议的最终架构图”应该长什么样（你可以照着画）

**左侧：User + Chrome**
**中间：Bilibili Web Pages（两个框）**
- WatchLater Player Page
- WatchLater List / History Page

**右侧：Extension（大框，内部拆四块）**
##### Content Script (content.js)
- Page Detector
- DOM Scraper
- Analyzer (Tokenizer + stopwords + dictionary + case merge)
- UI Renderer + Interaction
##### Background (background.js)
- Messaging hub
- Tabs ops (optional)
##### Static Resources
- style.css
- stopwords.txt
##### Storage
- User Config (dictionary/custom phrases/blacklist/theme)
- stopwords override text

**箭头**
- Content Script → Bilibili Pages：Read DOM titles / Inject panel / Inject floating button
- User → UI Panel：filter/dblclick/config edit/theme toggle
- Content Script ↔ Storage：load/save config + stopwords override
- Content Script → Static Resources：load css + default stopwords
- (optional) Content Script ↔ Background：request open tab / privileged calls
- Content Script / Background → Chrome Tabs API（如果使用）

##### 先打开 `manifest.json`，把以下信息抄到图上（这是扩展架构的事实来源）：
- content_scripts 的 matches（注入哪些 bilibili URL）
- background 形态（service_worker 还是 background page）
- permissions / host_permissions
- web_accessible_resources（是否需要加载 stopwords/css）
##### 再读 `content.js` 顶部逻辑，确认：
- 页面识别条件（URL path? DOM selector?）
- stopwords.txt 加载方式（fetch? runtime.getURL?）
- 配置存储方式（localStorage vs chrome.storage）
- 是否真的需要 background 参与“打开新页”
##### 用“实际交互路径”校验图：你至少能把 README 的 5 大功能在图中都找到对应模块与箭头。

按这个方式画出来的图，会非常贴合这个项目的真实运行结构（扩展的多上下文模型 + DOM 注入 + 本地分析/存储），并且组件拆分足够细，便于后续维护或二次开发。

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% Context / Actors
  %% =========================
  User(("User")):::external
  Chrome["Chrome Browser"]:::platform

  subgraph "Bilibili Web (Untrusted Page Context)"
    direction TB
    WLPlayer["WatchLater Player Page\n(稍后再看播放页)"]:::web
    WLListHist["WatchLater List / History Page\n(稍后再看列表页 / 历史记录页)"]:::web
    DOM["Bilibili Page DOM\n(titles,links,UI host)"]:::web
    WLPlayer --> DOM
    WLListHist --> DOM
  end

  subgraph "Browser Local Persistence"
    direction TB
    Storage[("Local Persistence\n(LocalStorage / chrome.storage)")]:::storage
    UserConfig[("User Config\n(dictionary,customPhrases,blacklist,theme)")]:::storage
    StopOverride[("Stopwords Override\n(user edited text)")]:::storage
    Storage --> UserConfig
    Storage --> StopOverride
  end

  %% =========================
  %% Extension (Trusted)
  %% =========================
  subgraph "Chrome Extension (Trusted Extension Context)"
    direction TB

    Manifest["manifest.json\n(Permissions,Matches,Wiring)"]:::meta

    subgraph "Runtime: Content Script"
      direction TB
      CS["content.js\n(Content Script)"]:::runtime

      PageDetector["Page Detector\n(URL/DOM checks)"]:::module
      DomScraper["DOM Scraper\n(extract video titles/links)"]:::module
      Analyzer["Analyzer\n(tokenize,normalize,merge case,count)"]:::module
      Filters["Filters\n(stopwords,dictionary,blacklist,phrases)"]:::module
      UIRenderer["UI Renderer\n(panel,word list,cloud/topN)"]:::module
      Interaction["Interaction Controller\n(dblclick filter,highlight,theme toggle,edit config)"]:::module
      JumpLogic["Jump to Normal Player\n(open standard video page)"]:::module

      CS --> PageDetector
      CS --> DomScraper
      CS --> Analyzer
      Analyzer --> Filters
      CS --> UIRenderer
      CS --> Interaction
      CS --> JumpLogic
    end

    subgraph "Runtime: Background"
      direction TB
      BG["background.js\n(Background Context)"]:::runtime
      MsgHub["Message Router\n(runtime messaging)"]:::module
      TabsOps["Tabs/Window Ops\n(chrome.tabs.* optional)"]:::module
      Lifecycle["Lifecycle Hooks\n(install/update)"]:::module

      BG --> MsgHub
      BG --> TabsOps
      BG --> Lifecycle
    end

    subgraph "Static Resources"
      direction TB
      CSS["style.css\n(Injected UI Styles/Themes)"]:::asset
      Stopwords["stopwords.txt\n(Default Stopwords)"]:::asset
      Icons["icons/\n(Extension Icons)"]:::asset
      Readme["README.md\n(Features/Flows/Notes)"]:::doc
    end
  end

  %% =========================
  %% High-level interactions (vertical)
  %% =========================
  User -->|"browse"| Chrome
  Chrome -->|"loads"| WLPlayer
  Chrome -->|"loads"| WLListHist

  %% Injection & DOM interaction
  CS -->|"inject UI/CSS"| DOM
  CSS -->|"style applied to injected UI"| DOM
  CS -->|"read DOM titles/links"| DOM
  CS -->|"render panel/list/highlights"| DOM

  %% Flow A: WatchLater player -> normal player
  WLPlayer -->|"content script runs on match"| CS
  User -->|"click floating button"| Interaction
  JumpLogic -->|"open normal video page\n(window.open or request background)"| Chrome

  %% Optional privileged open-tab path
  CS <-->|"message: openTab request (optional)"| MsgHub
  TabsOps -->|"chrome.tabs.create (optional)"| Chrome

  %% Flow B: list/history -> analysis
  WLListHist -->|"content script runs on match"| CS
  DomScraper -->|"titles[]"| Analyzer
  Stopwords -->|"load default stopwords"| Filters
  StopOverride -->|"load user override stopwords"| Filters
  UserConfig -->|"load config (dict/phrases/blacklist/theme)"| Filters
  Filters -->|"tokens -> freq map -> topN"| UIRenderer

  %% Flow C: edit config + persistence
  Interaction -->|"save edits\n(theme/dict/phrases/blacklist)"| Storage
  Interaction -->|"edit stopwords + save"| Storage
  Storage -->|"restore on next page load"| CS

  %% Trust boundary note
  DOM -.->|"Untrusted page boundary"| CS

  %% =========================
  %% Click events (mapped paths only)
  %% =========================
  click Manifest "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/manifest.json"
  click BG "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/background.js"
  click CS "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/content.js"
  click CSS "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/style.css"
  click Stopwords "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/stopwords.txt"
  click Icons "https://github.com/zhadao/bili-watchlater_history-_manager-/tree/main/icons/"
  click Readme "https://github.com/zhadao/bili-watchlater_history-_manager-/blob/main/README.md"

  %% =========================
  %% Styles (color is required)
  %% =========================
  classDef external fill:#ffffff,stroke:#111827,stroke-width:2,color:#111827
  classDef platform fill:#eef2ff,stroke:#4338ca,stroke-width:2,color:#111827
  classDef web fill:#ffedd5,stroke:#c2410c,stroke-width:2,color:#111827
  classDef runtime fill:#dbeafe,stroke:#1d4ed8,stroke-width:2,color:#111827
  classDef module fill:#bfdbfe,stroke:#1d4ed8,stroke-width:1.5,color:#111827
  classDef storage fill:#dcfce7,stroke:#166534,stroke-width:2,color:#052e16
  classDef asset fill:#e5e7eb,stroke:#374151,stroke-width:2,color:#111827
  classDef meta fill:#fef9c3,stroke:#a16207,stroke-width:2,color:#111827
  classDef doc fill:#f3e8ff,stroke:#6b21a8,stroke-width:2,color:#111827
```
