diff --git a/README.md b/README.md index 1a78e881..b3c17f06 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [心屿 / Xinyu Island](plugins/yujiachen-y/xinyu-daily/) | A cozy daily-mood island that plays like an indie game: an inspiration card shaped by your answers, mood stickers, a joy jar, a decision slot machine, a Book of Answers, and 20 hidden secrets guarded by a grumpy crab. Optionally, Xiaoyu writes you a daily letter and chats with you using your model. Requires MiniMax Code 3.1.2 or later | [yujiachen-y](https://github.com/yujiachen-y) | | [MoMo Collab](plugins/amszuidas/momo-collab/) | A project steward that turns stray thoughts, screenshots, and links into ideas, writes clear ideas up as tasks, runs each task in its own Agent session with a full handoff, checks the result against your done criteria, and tracks everything on a board. Requires MiniMax Code 3.1.2 or later | [amszuidas](https://github.com/amszuidas) | | [Anatomy Gallery](plugins/zch0227/anatomy-gallery/) | A gallery for interactive isometric figures made with the anatomy skill: hang them in rooms you organize, view light and dark editions full screen, keep every version, and have an Agent create or edit figures from the gallery with a per-run process log. The anatomy skill is bundled. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | -| [仓库透视 / Repo X-Ray](plugins/yujiachen-y/repo-xray/) | Understand a codebase from its Git history: a code map you can drill into, hotspots and bug magnets, high-risk files, owners and knowledge loss, commit rhythm and firefighting, and the tech stack. Works with GitHub, GitLab, and local repositories; analysis runs on your machine | [yujiachen-y](https://github.com/yujiachen-y) | +| [仓库透视 / Repo X-Ray](plugins/yujiachen-y/repo-xray/) | Understand a codebase from its Git history: a code map you can drill into, hotspots and bug magnets, high-risk files, owners and knowledge loss, commit rhythm and firefighting, and the tech stack. Works with GitHub, GitLab, and local repositories; analysis runs on your machine. The interface is in Chinese and English | [yujiachen-y](https://github.com/yujiachen-y) | | [OpenViking Mini Studio](plugins/openviking/mini-studio/) | Browse and search your OpenViking context read-only, preview it, and add selected URIs or content to the chat | OpenViking | | [Disk Insight](plugins/zch0227/disk-insight/) | See where disk space went on macOS and Windows with a sunburst space map, find junk files sorted into three safety tiers, large and duplicate files, and how much code repositories and Git worktrees take; ask an Agent about any item, and permanently delete what you select after a confirmation that lists every item. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | | [A/时差保安 / Timezone Guard](plugins/liuchen19960902/timezone-guard/) | Check the other side's local time before you message: the target city's clock turns into a green "now is fine", yellow "keep it short", or red "go to sleep" verdict. Requires MiniMax Code 3.1.2 or later | [FineCat](https://github.com/LiuChen19960902) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 19c1ac99..77db0dc7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -78,7 +78,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [心屿](plugins/yujiachen-y/xinyu-daily/README.zh-CN.md) | 像独立小游戏的每日心情小岛:由你的回答决定的今日灵感卡、心情贴纸、小确幸罐子、纠结老虎机、答案之书,还有坏脾气螃蟹藏起来的 20 个秘密;可选开启小屿陪伴,借用你的模型每天写信、陪你聊天。需要 MiniMax Code 3.1.2 或更高版本 | [yujiachen-y](https://github.com/yujiachen-y) | | [协作 · MoMo](plugins/amszuidas/momo-collab/README.zh-CN.md) | 项目管家 MoMo:把随手的想法、截图和链接攒成想法,写清后变成任务,派 Agent 会话带着完整背景去执行,按验收标准核对结果后交你审核,进展在看板上一眼可见。需要 MiniMax Code 3.1.2 或更高版本 | [amszuidas](https://github.com/amszuidas) | | [Anatomy 画廊](plugins/zch0227/anatomy-gallery/README.zh-CN.md) | 集中展示 anatomy 技能做出的交互式等距图解:按自建展区挂墙,全屏查看明暗两版,保留全部历史版本;在画廊里让 Agent 新建或修改作品,每次运行都有过程记录。自带 anatomy 技能。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | -| [仓库透视](plugins/yujiachen-y/repo-xray/README.zh-CN.md) | 从 Git 历史看懂一个代码仓库:可逐层下钻的代码地图、热点与 Bug 磁铁、高风险文件、负责人与知识流失、提交节奏与救火记录、技术栈;支持 GitHub、GitLab 和本机仓库,全部在本机分析 | [yujiachen-y](https://github.com/yujiachen-y) | +| [仓库透视](plugins/yujiachen-y/repo-xray/README.zh-CN.md) | 从 Git 历史看懂一个代码仓库:可逐层下钻的代码地图、热点与 Bug 磁铁、高风险文件、负责人与知识流失、提交节奏与救火记录、技术栈;支持 GitHub、GitLab 和本机仓库,全部在本机分析。界面提供中文和英文,可在侧边栏切换 | [yujiachen-y](https://github.com/yujiachen-y) | | [OpenViking Mini Studio](plugins/openviking/mini-studio/) | 只读浏览和搜索 OpenViking 上下文、预览内容,并把选中的 URI 或内容加入对话 | OpenViking | | [磁盘透视](plugins/zch0227/disk-insight/README.zh-CN.md) | 查看 macOS 和 Windows 的磁盘空间去向:旭日图空间地图,按三档风险分类的垃圾文件,大文件和重复文件,代码仓库和 Git worktree 的占用;任何条目都可以问 Agent,选中的条目在确认框里逐一列出,确认后直接永久删除。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | | [A/时差保安](plugins/liuchen19960902/timezone-guard/README.zh-CN.md) | 发消息前先看对方那边几点:按对方城市当地时间给出「现在可以聊 / 短聊就好 / 先睡,别发」三档判定。需要 MiniMax Code 3.1.2 或更高版本 | [FineCat](https://github.com/LiuChen19960902) | diff --git a/plugins/yujiachen-y/repo-xray/.minimax-plugin/plugin.json b/plugins/yujiachen-y/repo-xray/.minimax-plugin/plugin.json index 745ac83e..ebcd15c4 100644 --- a/plugins/yujiachen-y/repo-xray/.minimax-plugin/plugin.json +++ b/plugins/yujiachen-y/repo-xray/.minimax-plugin/plugin.json @@ -2,12 +2,12 @@ "schemaVersion": 1, "name": "repo-xray", "displayName": "仓库透视", - "version": "1.0.0", - "description": "从 Git 历史看懂一个代码仓库:代码地图、热点与 bug 磁铁、高风险文件、负责人与知识流失、提交节奏和技术栈。支持 GitHub / GitLab 仓库和本地仓库,全部在本机计算。", + "version": "1.1.0", + "description": "从 Git 历史看懂一个代码仓库:代码地图、热点与 bug 磁铁、高风险文件、负责人与知识流失、提交节奏和技术栈。支持 GitHub / GitLab 仓库和本地仓库,全部在本机计算。界面提供中文和英文,可在侧边栏切换。英文界面名为 Repo X-Ray。", "author": "yujiachen-y", "icon": "icon.png", "category": "Code", - "exampleQueries": ["打开仓库透视", "打开仓库透视,看看这个仓库的代码地图和高风险文件", "用仓库透视看看这个仓库主要是谁在维护"], + "exampleQueries": ["打开仓库透视", "打开仓库透视,看看这个仓库的代码地图和高风险文件", "用仓库透视看看这个仓库主要是谁在维护", "Open Repo X-Ray", "Open Repo X-Ray and show the code map and high-risk files", "Show who maintains this repository"], "apps": [], "mcpServers": [], "skills": [] diff --git a/plugins/yujiachen-y/repo-xray/README.md b/plugins/yujiachen-y/repo-xray/README.md index f27f701a..c2694d37 100644 --- a/plugins/yujiachen-y/repo-xray/README.md +++ b/plugins/yujiachen-y/repo-xray/README.md @@ -10,7 +10,7 @@ what the project is built with. Analysis runs locally with your own `git`. Nothing is uploaded, and the page loads no remote resources. The metrics follow the rules of [codebase-recon-skill](https://github.com/yujiachen-y/codebase-recon-skill), and the Markdown export -uses that skill's report format. The interface is in Chinese. +uses that skill's report format. The interface is in Chinese and English: the language button in the sidebar switches between them. Chinese is the default, and the choice is remembered for the next launch. ![Repo X-Ray code map with synthetic data](docs/preview.jpg) @@ -38,6 +38,8 @@ uses that skill's report format. The interface is in Chinese. files for you; you review the text and send it yourself. - Suggestions of recently used local repositories, light and dark themes, keyboard shortcuts (press `?`), and `prefers-reduced-motion` support. +- **Language**: switch the interface between Chinese and English from the sidebar. Chinese is the + default; the choice is remembered for the next launch. ## Requirements @@ -50,8 +52,8 @@ uses that skill's report format. The interface is in Chinese. Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins directory as `repo-xray/` (`~/.minimax/plugins/repo-xray/` by default; see the root README's Install -section). Restart MiniMax Code, then open 仓库透视 from the Mini App entry in the right panel or ask -the Agent to "打开仓库透视". +section). Restart MiniMax Code, then open the Mini App listed as 仓库透视 (the page itself is titled +"Repo X-Ray") from the right panel, or ask the Agent to open Repo X-Ray. ## Tested environment @@ -61,9 +63,23 @@ the Agent to "打开仓库透视". local repositories, including re-analysis; every tab; every code-map colouring, size, and time option, drilling in and out with the mouse and the keyboard; the ⌘K search; the Markdown export; light and dark themes. No console errors or failed requests. -- Not exercised: popping the page out into its own window (`surface.window`, sized 1360×900); the - append into the conversation input, which asks the Host for confirmation; `prefers-reduced-motion`; - Windows and Linux. +- Windows 11 Pro (build 26300) with Git 2.56.1 and Node 26.14.0, in MiniMax Code 3.1.21.235: the + package installs from the repository directory, `npm run check` reports the package as OK there, and + the package tests pass 22/22. Both interfaces were walked on that machine: the language control + switches the whole interface, the English interface shows `(root)` in the New files list and in the + contributors' Top directories column with no Chinese left on any of the six views, an error message + is in English, switching back to Chinese shows `(根目录)` in the same two places, the choice + survives a reload, the page pops out into its own window, a repository removed just before a language + switch still goes with its undo still on offer, and the console and network are clean. +- Not exercised: the append into the conversation input, which asks the Host for confirmation; + `prefers-reduced-motion`; Linux. The Chinese and English interfaces were both checked in + MiniMax Code on a local build: the landing page, the keyboard shortcut list, the local repository + scan, both themes, and a full analysis of a local repository read in each language, including the + language button and the choice surviving a reload. The Overview, Code Map, Contributors and Rhythm + and Firefighting panels were read in both languages, and the server was asked for both languages at + the same time. Popping the page out into its own window (`surface.window`, sized 1360×900) works on + that local build. The High-Risk Files panel, the Markdown export, the search palette and the + settings were not walked in both languages. ## Data & access @@ -118,15 +134,23 @@ the Agent to "打开仓库透视". you added; a repository that redirects (renamed or moved) has to be added again with its new address. Tokens from `gh` and `glab` are cached in memory only. Git credential helpers and interactive prompts are turned off for these commands. -- Agent turns: none. No `agentAccess` and no MCP endpoints. "发到对话…", "让 Agent 讲解…", and - "让 Agent 读高风险文件…" call `window.mcode.miniapp.message.append` to place a prepared prompt (a +- Agent turns: none. No `agentAccess` and no MCP endpoints. "Send to chat…", "Have the Agent + explain…", and "Send to chat — have the Agent read the high-risk files…" call + `window.mcode.miniapp.message.append` to place a prepared prompt (a summary of the report and some file paths) in the conversation input after the Host asks you to confirm; you decide whether to send it. Where that API is unavailable, the text is copied to the clipboard instead. - Clipboard: written only when you click a copy action (a SHA, a path, the Markdown report). -- Browser storage: `localStorage` keeps only the theme, the last opened repository, and the identity - merge preference. -- Reset: remove a repository with 移除 on its page; access tokens can be cleared in Settings. Deleting +- Browser storage: `localStorage` keeps only the theme, the last opened repository, the identity + merge preference, and the interface language under the key `rr-lang` (`zh` or `en`); when the + browser will not write to `localStorage`, `sessionStorage` takes the language over and the stale + `localStorage` entry is dropped so it cannot shadow the new one. `sessionStorage` also holds the + repositories whose removal is waiting out its undo window, under the key `rr-pending-removals`, so that + a reload does not cancel a removal that was already asked for. The page states that language in + the `x-rr-lang` header of every request it makes to the local server, and in the + `lang` query parameter of the event stream; the server writes its messages in that language. +- Reset: remove a repository with the Remove button on its page; access tokens can be cleared in + Settings. Deleting the app's data directory removes everything it stored. ## Files @@ -139,18 +163,29 @@ miniapp/client/index.html Page shell served at /dashboard miniapp/client/app.js Page logic: routing, tabs, code map, dialogs (no dependencies) miniapp/client/charts.js Hand-written SVG charts and the treemap layout miniapp/client/styles.css Styles, light and dark themes +miniapp/client/i18n.js Language selection: which language, remembered in localStorage +miniapp/client/strings.js The English for every Chinese string the page shows miniapp/client/icon.svg App icon used inside the page miniapp/node/server.mjs Node entry: start(context) → { dispose }, routes, jobs, SSE miniapp/node/git.mjs git runner, address parsing, clone and fetch, credentials and proxy miniapp/node/analyze.mjs Reads the history and computes the report miniapp/node/codemap.mjs Code map: directory tree, colourings, directory descriptions miniapp/node/techstack.mjs Tech stack detection from manifests +miniapp/node/i18n.mjs Bilingual messages for the Node side miniapp/node/util.mjs Date helpers, JSON read and atomic write miniapp/node/miniapp-api.ts Type declarations for the runtime context icon.png Plugin icon docs/preview.jpg README preview (synthetic data) +tests/i18n.test.mjs Checks that every string the page and the Node side show has a translation ``` +## Development + +`node --test tests/` checks that every string the page and the Node side show has a translation, that +the two layers word the messages they share the same way, and that the queue of repositories waiting +to be deleted survives a reload. The repository CI checks the package manifest, not these tests, so +run them yourself before you open a pull request. + ## License [MIT](./LICENSE) diff --git a/plugins/yujiachen-y/repo-xray/README.zh-CN.md b/plugins/yujiachen-y/repo-xray/README.zh-CN.md index 8573ca68..36d75aae 100644 --- a/plugins/yujiachen-y/repo-xray/README.zh-CN.md +++ b/plugins/yujiachen-y/repo-xray/README.zh-CN.md @@ -4,7 +4,7 @@ 读代码之前,先从 Git 历史看懂一个陌生的代码仓库。添加一个 GitHub / GitLab 仓库,或者选一个本机仓库,仓库透视会把提交记录变成一张可以逐层下钻的代码地图、一份高风险文件清单,告诉你谁在维护哪里、团队怎么交付、项目用了哪些技术。 -分析用你本机的 `git` 在本地完成:不上传任何内容,页面也不加载任何远程资源。指标口径沿用 [codebase-recon-skill](https://github.com/yujiachen-y/codebase-recon-skill),导出的 Markdown 也是这个 skill 的报告格式。界面为中文。 +分析用你本机的 `git` 在本地完成:不上传任何内容,页面也不加载任何远程资源。指标口径沿用 [codebase-recon-skill](https://github.com/yujiachen-y/codebase-recon-skill),导出的 Markdown 也是这个 skill 的报告格式。界面有中文和英文两种:侧边栏的按钮可以切换。默认中文,选择会被记住,下次启动仍然生效。 ![仓库透视代码地图(虚构数据)](docs/preview.jpg) @@ -20,6 +20,7 @@ - **技术栈**:从 `package.json`、`go.mod`、`Cargo.toml`、`pyproject.toml`、`pom.xml`、`Gemfile` 等清单文件识别语言、框架和工具。 - ⌘K 搜索仓库、全部历史文件和贡献者;把报告复制或下载为 Markdown;或者把一段准备好的提示词放进对话输入框,让 Agent 帮你读最高风险的文件,内容由你确认后自己发送。 - 推荐最近用过的本机仓库,支持浅色和深色主题、键盘快捷键(按 `?` 查看),以及系统的“减弱动态效果”设置。 +- **语言**:在侧边栏切换中文和英文界面。默认中文,选择会被记住,下次启动仍然生效。 ## 运行要求 @@ -28,13 +29,14 @@ ## 安装 -把整个目录(包括隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,命名为 `repo-xray/`(默认是 `~/.minimax/plugins/repo-xray/`,详见根目录 README 的安装说明)。重启 MiniMax Code,然后从右侧面板的 Mini App 入口打开仓库透视,或者对 Agent 说“打开仓库透视”。 +把整个目录(包括隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,命名为 `repo-xray/`(默认是 `~/.minimax/plugins/repo-xray/`,详见根目录 README 的安装说明)。重启 MiniMax Code,然后从右侧面板的 Mini App 入口打开仓库透视(Repo X-Ray),或者对 Agent 说“打开仓库透视”(Open Repo X-Ray)。 ## Tested environment - 在 macOS 27 上的 MiniMax Code 3.1.3-preview.4675 中测试,Git 版本 2.54:通过宿主的发布流程安装(也从本仓库目录重新安装过),在右侧面板打开。 - 实测过:一个公开的 GitHub 仓库、一个通过 `glab` 登录访问的自建 GitLab 仓库和本机仓库,包括重新分析;所有分区;代码地图的全部着色、面积和时间范围选项,用鼠标和键盘逐层进入与返回;⌘K 搜索;Markdown 导出;浅色和深色主题。控制台没有报错,也没有失败的请求。 -- 未实测:把页面弹出到独立窗口(`surface.window`,尺寸 1360×900);追加到对话输入框(需要宿主弹窗确认);“减弱动态效果”;Windows 和 Linux。 +- 在 Microsoft Windows 11 Pro(内部版本 26300)上,配合 Git 2.56.1 和 Node 26.14.0,在 MiniMax Code 3.1.21.235 中:包可以从仓库目录安装,`npm run check` 在那台机器上报告该包为 OK,包内测试 22/22 通过。两种界面都在那台机器上走过:语言按钮切换整个界面,英文界面在“新增文件”列表和贡献者的“主要目录”一栏显示 `(root)`,六个分区都没有残留中文,错误提示是英文,切回中文后同样两处显示 `(根目录)`,刷新后仍然记住选择,把页面弹出到独立窗口也能正常显示,在删除的撤销窗口内切换语言,仓库照样会被删掉、撤销也照样可用,控制台和网络都没有异常。 +- 未实测:追加到对话输入框(需要宿主弹窗确认);“减弱动态效果”;Linux。中英文两种界面都在 MiniMax Code 里验证过(本地构建):落地页、快捷键面板、本机仓库扫描、深浅两套主题,以及分别用两种语言读同一个本机仓库的完整分析报告,包括语言按钮和刷新后仍然记住选择;概览、代码地图、贡献者、节奏与救火这几个分区都分别用两种语言读过,并发请求也分别用两种语言测过;把页面弹出到独立窗口(`surface.window`,尺寸 1360×900)也能正常工作。风险文件分区、Markdown 导出、搜索面板和设置没有在两种语言下逐个走一遍。 ## Data & access @@ -55,10 +57,10 @@ - `gh auth token --hostname `(`github.com` 和 `gh` 的 `hosts.yml` 里的主机)和 `glab config get token --host `(`glab` 配置里的主机),仅在装了这两个 CLI 时调用,用来复用已有登录。 - macOS 上的 `/usr/sbin/scutil --proxy`,仅在设置和环境变量里都没有代理时调用。 - 凭据:来自 `gh`、`glab` 或设置的令牌只留在 Node 进程里,通过 `GIT_CONFIG_*` 环境变量以 `http.extraHeader` 的形式交给 git,不会出现在命令行参数、仓库配置、页面、日志或事件流里。带着令牌时 git 不跟随 HTTP 跳转(`http.followRedirects=false`),令牌只会发给你添加的那台主机;会跳转的仓库(改名或迁移过)需要用新地址重新添加。来自 `gh` 和 `glab` 的令牌只缓存在内存中。这些 git 命令会关闭凭据助手和交互式提示。 -- Agent:不运行 Agent,没有声明 `agentAccess`,也没有 MCP 端点。“发到对话…”“让 Agent 讲解…”“让 Agent 读高风险文件…”会调用 `window.mcode.miniapp.message.append`,在宿主弹窗确认后把一段准备好的提示词(报告摘要和部分文件路径)放进对话输入框,由你决定是否发送。环境不支持这个接口时,改为复制到剪贴板。 +- Agent:不运行 Agent,没有声明 `agentAccess`,也没有 MCP 端点。“发到对话…”(Send to chat…)、“让 Agent 讲解…”(Have the Agent explain…)、“发到对话,让 Agent 读高风险文件…”(Send to chat — have the Agent read the high-risk files…)会调用 `window.mcode.miniapp.message.append`,在宿主弹窗确认后把一段准备好的提示词(报告摘要和部分文件路径)放进对话输入框,由你决定是否发送。环境不支持这个接口时,改为复制到剪贴板。 - 剪贴板:只在你点击复制类操作(SHA、路径、Markdown 报告)时写入。 -- 浏览器存储:`localStorage` 只保存主题、上次打开的仓库和身份合并偏好。 -- 重置:在仓库页面点“移除”删除单个仓库;访问令牌可以在设置里清除。删除应用的数据目录即可清空它保存的全部内容。 +- 浏览器存储:`localStorage` 只保存主题、上次打开的仓库、身份合并偏好,以及界面语言(键名 `rr-lang`,值为 `zh` 或 `en`);浏览器不肯写入 `localStorage` 时改用 `sessionStorage`,并删掉 `localStorage` 里的旧值,免得它盖住新选择。`sessionStorage` 还保存等待撤销窗口结束的待删除仓库(键名 `rr-pending-removals`),这样刷新页面不会取消已经提出的删除。页面会在每次请求本机服务时用 `x-rr-lang` 头说明当前语言,事件流则用 `lang` 查询参数说明;服务端按这个语言给出提示。 +- 重置:在仓库页面点“移除”(Remove)删除单个仓库;访问令牌可以在设置里清除。删除应用的数据目录即可清空它保存的全部内容。 ## License diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/app.js b/plugins/yujiachen-y/repo-xray/miniapp/client/app.js index d85ddc43..294ae6b5 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/client/app.js +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/app.js @@ -1,4 +1,6 @@ import * as C from './charts.js'; +import { displayText, getLang, localeTag, plainName, t as tr, tAlt as trAlt, toggleLang } from './i18n.js'; +import { PENDING_KEY, UNDO_MS, decodePending, encodePending, pendingLeft } from './pending.js'; const { esc, fmt } = C; const $ = (s, r = document) => r.querySelector(s); @@ -30,21 +32,21 @@ const ICON = { play: '', pause: '', }; -const TREND = { rising: '上升', declining: '下降', erratic: '波动', stable: '平稳', insufficient: '数据不足' }; -const WINDOW_ZH = { '6 months ago': '近 6 个月', '1 year ago': '近 1 年', 'all time': '全部历史' }; +const TREND = { rising: tr("上升"), declining: tr("下降"), erratic: tr("波动"), stable: tr("平稳"), insufficient: tr("数据不足") }; +const WINDOW_LANG = { '6 months ago': tr("近 6 个月"), '1 year ago': tr("近 1 年"), 'all time': tr("全部历史") }; const TREND_GLYPH = { rising: '↗', declining: '↘', erratic: '↯', stable: '→', insufficient: '·' }; const TREND_COLOR = { rising: 'var(--mcode-success)', declining: 'var(--mcode-danger)', erratic: 'var(--mcode-warning)', stable: 'var(--k-code)', insufficient: 'var(--k-other)' }; const reducedMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches; -const TIER = { small: '小型', medium: '中型', large: '大型' }; -const STAGE = { queued: '排队', sync: '同步仓库', analyze: '分析提交历史', tech: '识别技术栈与目录说明' }; +const TIER = { small: tr("小型"), medium: tr("中型"), large: tr("大型") }; +const STAGE = { queued: tr("排队"), sync: tr("同步仓库"), analyze: tr("分析提交历史"), tech: tr("识别技术栈与目录说明") }; const LANG_COLORS = ['var(--k-code)', 'var(--k-mr)', 'var(--k-merge)', 'var(--k-review)', 'var(--k-comment)', 'var(--k-issue)', 'var(--k-other)']; const TABS = [ - ['overview', '概览'], - ['map', '代码地图'], - ['risk', '风险文件'], - ['people', '贡献者'], - ['momentum', '节奏与救火'], - ['tech', '技术栈'], + ['overview', tr("概览")], + ['map', tr("代码地图")], + ['risk', tr("风险文件")], + ['people', tr("贡献者")], + ['momentum', tr("节奏与救火")], + ['tech', tr("技术栈")], ]; const TAB_OF_ANCHOR = { risk: 'risk', people: 'people', momentum: 'momentum', fire: 'momentum', vitals: 'overview' }; @@ -69,34 +71,40 @@ let route = readRoute(); // Utilities // --------------------------------------------------------------------------- async function api(path, opts = {}) { - const res = await fetch(path, { method: opts.method || 'GET', headers: opts.body ? { 'content-type': 'application/json' } : {}, body: opts.body ? JSON.stringify(opts.body) : undefined }); + const headers = { 'x-rr-lang': getLang() }; + if (opts.body) headers['content-type'] = 'application/json'; + const res = await fetch(path, { method: opts.method || 'GET', headers, body: opts.body ? JSON.stringify(opts.body) : undefined }); let data = null; try { data = await res.json(); } catch {} - if (!res.ok) throw Object.assign(new Error(data?.error?.message || (res.status === 401 ? '页面会话已过期,请刷新页面' : `请求失败(${res.status})`)), { code: data?.error?.code, status: res.status }); + if (!res.ok) throw Object.assign(new Error(data?.error?.message || (res.status === 401 ? tr("页面会话已过期,请刷新页面") : tr("请求失败({0})", res.status))), { code: data?.error?.code, status: res.status }); return data; } const repoById = (id) => state.repos.find((r) => r.id === id) || null; +/** A list the report carries in one language, or in both. */ +const langList = (v) => (Array.isArray(v) ? v : (v?.[getLang()] ?? [])); +/** A field that carries one string, or the same string in both languages. */ +const pick = (v) => (v && typeof v === 'object' ? (v[getLang()] ?? v.zh ?? '') : v); const current = () => (route.repo ? repoById(route.repo) : null); -const dtf = new Intl.DateTimeFormat('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }); +const dtf = new Intl.DateTimeFormat(localeTag(), { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }); function relTime(ts) { - if (!ts) return '从未'; + if (!ts) return tr("从未"); const d = Date.now() - ts; - if (d < 60_000) return '刚刚'; - if (d < 3_600_000) return `${Math.floor(d / 60_000)} 分钟前`; - if (d < 86_400_000) return `${Math.floor(d / 3_600_000)} 小时前`; - if (d < 30 * 86_400_000) return `${Math.floor(d / 86_400_000)} 天前`; + if (d < 60_000) return tr("刚刚"); + if (d < 3_600_000) return tr("{0} 分钟前", Math.floor(d / 60_000)); + if (d < 86_400_000) return tr("{0} 小时前", Math.floor(d / 3_600_000)); + if (d < 30 * 86_400_000) return tr("{0} 天前", Math.floor(d / 86_400_000)); return dtf.format(ts); } function relDay(ymd) { if (!ymd) return '–'; const d = Math.round((new Date().setHours(0, 0, 0, 0) - C.parseYmd(ymd)) / 86_400_000); - if (d <= 0) return '今天'; - if (d === 1) return '昨天'; - if (d < 30) return `${d} 天前`; - if (d < 365) return `${Math.floor(d / 30)} 个月前`; - return `${Math.floor(d / 365)} 年前`; + if (d <= 0) return tr("今天"); + if (d === 1) return tr("昨天"); + if (d < 30) return tr("{0} 天前", d); + if (d < 365) return tr("{0} 个月前", Math.floor(d / 30)); + return tr("{0} 年前", Math.floor(d / 365)); } const pct = (x, d = 0) => `${(x * 100).toFixed(d)}%`; const secs = (ms) => (ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`); @@ -129,7 +137,7 @@ function flashCopied(el) { el._icon = null; }, 1300); } -async function copyText(text, label = '已复制', el = null) { +async function copyText(text, label = tr("已复制"), el = null) { try { await navigator.clipboard.writeText(text); } catch { @@ -152,13 +160,14 @@ function pathHtml(p, { link = true, baseFirst = true } = {}) { const inner = baseFirst ? `${base} ${dir}` : `${dir}${base}`; - return link ? `${inner}` : inner; + return link ? tr("{2}", esc(href({ file: p, person: null })), esc(p), inner) : inner; } function personLink(name, { bot = false } = {}) { - return `${esc(name)}${bot ? ' 机器人' : ''}`; + return tr("{1}{2}", esc(href({ person: name, file: null })), esc(displayText(name)), bot ? tr(" 机器人") : ''); } function avatar(name, cls = '', color = null) { - const initial = /^[\x00-\x7f]/.test(name) ? name.slice(0, 2).toUpperCase() : name.slice(0, 1); + const label = plainName(name); + const initial = /^[\x00-\x7f]/.test(label) ? label.slice(0, 2).toUpperCase() : label.slice(0, 1); return ``; } function webLink(kind, ref) { @@ -255,7 +264,7 @@ function updateTitle() { const r = current(); const tab = TABS.find(([t]) => t === route.tab)?.[1]; const where = route.tab === 'map' && route.focus ? ` · ${route.focus}/` : ''; - document.title = r ? `${r.job?.running ? '分析中… ' : ''}${r.name}${route.tab !== 'overview' ? ` · ${tab}` : ''}${where} · 仓库透视` : '仓库透视'; + document.title = r ? tr("{0}{1}{2}{3} · 仓库透视", r.job?.running ? tr("分析中… ") : '', r.name, route.tab !== 'overview' ? ` · ${tab}` : '', where) : tr("仓库透视"); } // --------------------------------------------------------------------------- @@ -268,7 +277,7 @@ function applyTheme() { document.documentElement.dataset.theme = dark ? 'dark' : 'light'; $('meta[name="theme-color"]')?.setAttribute('content', dark ? '#0a0a0b' : '#fafafa'); const b = $('#theme-btn'); - if (b) b.lastChild.textContent = { system: ' 主题:跟随系统', light: ' 主题:浅色', dark: ' 主题:深色' }[pref]; + if (b) b.lastChild.textContent = { system: tr(" 主题:跟随系统"), light: tr(" 主题:浅色"), dark: tr(" 主题:深色") }[pref]; colorCache.clear(); } function repaintForTheme() { @@ -286,6 +295,27 @@ function cycleTheme() { } matchMedia('(prefers-color-scheme: dark)').addEventListener('change', repaintForTheme); +// --------------------------------------------------------------------------- +// Language +// --------------------------------------------------------------------------- +/** Apply the active language to the document and to the static shell markup. */ +function applyLang() { + document.documentElement.lang = getLang() === 'en' ? 'en' : 'zh-CN'; + const b = $('#lang-btn'); + if (b) { + b.lastChild.textContent = getLang() === 'en' ? ' Language: English' : ' 语言:中文'; + b.setAttribute('title', getLang() === 'en' ? tr("切换到中文") : tr("切换到英文")); + } + for (const el of document.querySelectorAll('[data-i18n]')) el.textContent = tr(el.dataset.i18n); + for (const el of document.querySelectorAll('[data-i18n-aria]')) el.setAttribute('aria-label', tr(el.dataset.i18nAria)); +} +// Switch language and reload, so every string on the page - including the ones +// built while the modules load - is produced in the new language. +function cycleLang() { + toggleLang(); + location.reload(); +} + // --------------------------------------------------------------------------- // Sidebar // --------------------------------------------------------------------------- @@ -300,95 +330,71 @@ function renderSidebar() { const s = r.summary; const spark = s?.spark ? `${C.sparkline(s.spark, { w: 44, h: 12, color: TREND_COLOR[s.trend] || 'var(--k-code)' })}` : ''; const sub = running - ? `分析中` + ? tr("分析中") : err - ? '分析失败' + ? tr("分析失败") : s - ? `${spark}${relDay(s.latest)}` - : '尚未分析'; - const badge = !running && !err && s ? `高风险文件 ${s.risk}` : ''; + ? tr("{1}{2}", esc(s.latest), spark, relDay(s.latest)) + : tr("尚未分析"); + const badge = !running && !err && s ? tr("高风险文件 {2}", s.risk ? ' warn' : '', s.risk, s.risk) : ''; return `
  • ${ICON[r.provider] || ICON.other}${esc(r.name)}${sub}${badge}
  • `; }) .join('') - : '
  • 还没有分析过仓库
  • '; + : tr("
  • 还没有分析过仓库
  • "); $('.brand-mark')?.classList.toggle('busy', state.repos.some((r) => r.job?.running)); } function setLive(on) { const el = $('#live'); if (!el) return; el.classList.toggle('off', !on); - $('#live-text').textContent = on ? '已连接 · 实时更新' : '连接中断,正在重连…'; + $('#live-text').textContent = on ? tr("已连接 · 实时更新") : tr("连接中断,正在重连…"); } // --------------------------------------------------------------------------- // Welcome // --------------------------------------------------------------------------- +/** What the input would analyse: the preview, and whether the input cannot be used. */ function parsePreview(input) { const v = input.trim(); - if (!v) return ''; - if (/^(\/|~|[A-Za-z]:[\\/])/.test(v)) return `本地仓库 · ${v}`; + if (!v) return { text: '', error: false }; + if (/^(\/|~|[A-Za-z]:[\\/])/.test(v)) return { text: tr("本地仓库 · {0}", v), error: false }; let m; - if ((m = v.match(/^git@([^:]+):(.+?)(\.git)?$/))) return `${m[1]} · ${m[2]}`; + if ((m = v.match(/^git@([^:]+):(.+?)(\.git)?$/))) return { text: `${m[1]} · ${m[2]}`, error: false }; if (/^https?:\/\//i.test(v)) { try { const u = new URL(v); - return `${u.host} · ${u.pathname.replace(/^\/|\/$/g, '').replace(/\.git$/, '').split('/-/')[0]}`; + return { text: `${u.host} · ${u.pathname.replace(/^\/|\/$/g, '').replace(/\.git$/, '').split('/-/')[0]}`, error: false }; } catch { - return '地址格式不对'; + return { text: tr("地址格式不对"), error: true }; } } - if ((m = v.match(/^([\w-]+)\/([\w.-]+)$/))) return `github.com · ${m[1]}/${m[2]}`; - return '无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径'; + if ((m = v.match(/^([\w-]+)\/([\w.-]+)$/))) return { text: `github.com · ${m[1]}/${m[2]}`, error: false }; + return { text: tr("无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径"), error: true }; } function analyzeBar(value = '') { - return ` -
    `; + return tr("
    \n ❯\n
    \n
    \n \n
    \n
    ", esc(value), ICON.search); } const EXAMPLES = ['sindresorhus/got', 'https://github.com/expressjs/express', '~/Workspace/my-repo']; const METRICS = [ - ['代码热点', '窗口内改得最多的文件', 'git log --name-only'], - ['Bug 磁铁', '修 bug 时最常碰的文件', '--grep="fix|bug|broken"'], - ['知识集中度', '一半提交出自几个人', 'git shortlog -sn'], - ['节奏与救火', '月度趋势、revert / hotfix', '--since · uniq -c'], + [tr("代码热点"), tr("窗口内改得最多的文件"), 'git log --name-only'], + [tr("Bug 磁铁"), tr("修 bug 时最常碰的文件"), '--grep="fix|bug|broken"'], + [tr("知识集中度"), tr("一半提交出自几个人"), 'git shortlog -sn'], + [tr("节奏与救火"), tr("月度趋势、revert / hotfix"), '--since · uniq -c'], ]; function renderWelcome() { const s = state.suggest; - main.innerHTML = `
    -
    - -

    读代码之前,先看一遍它的 git 历史

    -

    找出最常被改、最常出 bug 的文件,谁在维护它们,项目节奏是升是降,以及它用了哪些技术。指标定义和 codebase-recon skill 保持一致,全部在本机计算。

    -
    -
    - - ${analyzeBar()} -
    试试${EXAMPLES.map((x) => ``).join('')}
    -
    -
    ${METRICS.map(([t, d, c]) => `
    ${t}${d}
    ${esc(c)}
    `).join('')}
    -
    -

    本机仓库

    只读扫描常用目录下的 git 仓库,按最近活动排序;扫描目录可在设置里修改
    -
    - ${ + main.innerHTML = tr("
    \n
    \n \"\"\n

    读代码之前,先看一遍它的 git 历史

    \n

    找出最常被改、最常出 bug 的文件,谁在维护它们,项目节奏是升是降,以及它用了哪些技术。指标定义和 codebase-recon skill 保持一致,全部在本机计算。

    \n
    \n
    \n
    repo-xray — 新的分析只读 · 不修改仓库
    \n {0}\n
    试试{1}
    \n
    \n
    {2}
    \n
    \n

    本机仓库

    只读扫描常用目录下的 git 仓库,按最近活动排序;扫描目录可在设置里修改
    \n
    \n {4}\n
    \n
    ", analyzeBar(), EXAMPLES.map((x) => ``).join(''), METRICS.map(([t, d, c]) => `
    ${t}${d}
    ${esc(c)}
    `).join(''), ICON.sync, !s ? '
    ' : s.length - ? `
      ${s + ? tr("
        {0}
      ", s .map( - (x, i) => `
    • `, + (x, i) => tr("
    • ", Math.min(i, 12), esc(x.path), ICON.local, esc(x.name), esc(x.path), x.analyzed ? tr("已分析") : '', esc(new Date(x.mtime).toLocaleString(localeTag())), relTime(x.mtime), ICON.arrow), ) - .join('')}
    ` - : '

    没有在常用目录里找到 git 仓库。可以在设置里添加扫描目录,或直接在上面输入路径。

    ' - } -
    -
    `; + .join('')) + : tr("

    没有在常用目录里找到 git 仓库。可以在设置里添加扫描目录,或直接在上面输入路径。

    ") + ); $('#target-input')?.focus(); } async function loadSuggest(refresh = false) { @@ -408,33 +414,15 @@ function headerHtml(r, rep) { const v = rep?.vitals; const web = r.webUrl || rep?.web?.url; const at = r.lastSync?.at; - return `
    -
    -

    ${ICON[r.provider] || ICON.other}${esc(r.name)}

    -
    - ${esc(r.display)} - ${rep ? `` : ''} - ${r.kind === 'local' ? '本地仓库 · 分析当前 HEAD,不 fetch' : ''} - ${running ? ' 正在分析…' : ` 上次分析 ${relTime(at)}`} -
    - ${v ? `
    ${v.first} → ${v.latest}${fmt(v.commits)} commits${fmt(v.branches)} 个分支${fmt(v.files)} 个文件${TIER[v.tier]} · 窗口 ${esc(v.window)} · Top ${v.N}
    ` : ''} -
    -
    - ${rep ? `` : ''} - ${web ? `${ICON.ext}打开网页` : ''} - - -
    -
    -
    `; + return tr("
    \n
    \n

    {0}{1}{2}

    \n
    \n {4}\n {5}\n {6}\n {8}\n
    \n {9}\n
    \n
    \n {10}\n {11}\n \n \n
    \n
    \n
    ", ICON[r.provider] || ICON.other, esc(r.name), esc(r.name), esc(r.display), esc(r.display), rep ? tr("", esc(rep.head), esc(rep.head), ICON.copy.replace('本地仓库 · 分析当前 HEAD,不 fetch") : '', at ? tr("title=\"{0}\"", esc(new Date(at).toLocaleString(localeTag()))) : '', running ? tr(" 正在分析…") : tr(" 上次分析 {0}", relTime(at)), v ? tr("
    {0} → {1}{2} commits{3} 个分支{4} 个文件{5} · 窗口 {6} · Top {7}
    ", v.first, v.latest, fmt(v.commits), fmt(v.branches), fmt(v.files), TIER[v.tier], esc(v.window), v.N) : '', rep ? tr("", ICON.download) : '', web ? tr("{1}打开网页", esc(web), ICON.ext) : '', running ? 'disabled' : '', running ? '' : ICON.sync, r.kind === 'local' ? tr("重新分析") : tr("同步并分析")); } function tabsHtml(rep) { const counts = rep ? { risk: rep.highRisk.length, people: rep.busFactor.total } : {}; // Coming back to the map tab returns to where it was left for this repo. const patch = (t) => ({ tab: t, filter: null, file: null, person: null, ...(t === 'map' && route.tab !== 'map' ? mapPlaceFor(route.repo) : {}) }); - return ``; + ).join('')); } function renderRepo() { const r = current(); @@ -445,7 +433,7 @@ function renderRepo() { else if (!rep) { const err = r.lastSync?.error && !r.job?.running; body = err - ? `
    ${ICON.alert}

    分析失败

    ${esc(r.lastSync.error.message)}

    ` + ? tr("
    {0}

    分析失败

    {1}

    ", ICON.alert, esc(r.lastSync.error.message), ICON.sync) : skeletonFor(route.tab); } else body = tabBody(rep) + statusLine(r, rep); main.innerHTML = `${headerHtml(r, rep)}${tabsHtml(rep)}
    ${body}
    `; @@ -526,14 +514,7 @@ function afterRender(r, rep) { function statusLine(r, rep) { const steps = r.lastSync?.head === rep.head ? r.lastSync?.steps || [] : []; const an = steps.find((x) => x.stage === 'analyze'); - return `
    - HEAD ${esc(rep.head.slice(0, 8))} - 算法 v${rep.algo} - 口径 ${rep.identity === 'raw' ? '原始' : '合并身份'} - 解析 ${fmt(rep.vitals.commits)} commits${an ? ` · 用时 ${secs(an.ms)}` : ''}${r.lastSync?.ms && r.lastSync?.head === rep.head ? ` · 全程 ${secs(r.lastSync.ms)}` : ''} - 生成于 ${relTime(rep.generatedAt)} - ⌘K 搜索 · ? 快捷键 -
    `; + return tr("
    \n HEAD {0}\n 算法 v{1}\n 口径 {2}\n 解析 {3} commits{4}{5}\n 生成于 {6}\n ⌘K 搜索 · ? 快捷键\n
    ", esc(rep.head.slice(0, 8)), rep.algo, rep.identity === 'raw' ? tr("原始") : tr("合并身份"), fmt(rep.vitals.commits), an ? tr(" · 用时 {0}", secs(an.ms)) : '', r.lastSync?.ms && r.lastSync?.head === rep.head ? tr(" · 全程 {0}", secs(r.lastSync.ms)) : '', relTime(rep.generatedAt)); } function skeletonFor(tab) { if (tab === 'overview') return `
    ${'
    '.repeat(6)}
    `; @@ -565,19 +546,19 @@ function explainFor(key, rep) { const mSince = mo.range === 'all' ? '' : ` --since="${mo.range} months ago"`; const cp = mp.view?.couple || { maxChangeset: 30, minRevs: 5, minShared: 5, minDegree: 0.3 }; const E = { - window: ['按 skill 的规则给仓库分档:<500 个 commit 看全部历史,500–10k 看 1 年,>10k 看 6 个月。', `git rev-list --count HEAD\ngit log --oneline${since} | wc -l`], - risk: [`同时出现在“代码热点 Top ${v.N}”和“Bug 磁铁 Top ${v.N}”里的文件。`, `git log --format=format: --name-only${since} | sort | uniq -c | sort -nr | head -${v.N}\ngit log -i -E --grep="fix|bug|broken" --name-only --format=''${since} | sort | uniq -c | sort -nr | head -${v.N}`], - active: [`近 3 个月有非合并提交的人数 / 历史总人数,低于 30% 时告警。${rep.identity === 'merged' ? '当前为“合并身份”口径:大小写不同的同名账号与同邮箱账号视为一人,机器人不计入。' : '当前为原始口径,与 shortlog 完全一致。'}`, 'git shortlog -sn --no-merges --since="3 months ago" HEAD | wc -l\ngit shortlog -sn --no-merges HEAD | wc -l'], - half: ['按非合并提交数从高到低累加,达到总数一半时的人数。数字越小,知识越集中。', 'git shortlog -sn --no-merges HEAD'], - trend: ['比较最近 3 个完整月和之前 3 个月的月均提交数:高 20% 以上为上升,低 20% 以上为下降;环比平均波动超过 50% 为波动。当月未结束不计入。', "git log --format='%ad' --date=format:'%Y-%m' | sort | uniq -c"], - fire: ['窗口内标题含 revert / hotfix / emergency / rollback 的提交占比,≥5% 判为偏高(skill 未给阈值)。', `git log --oneline${since} | grep -iE 'revert|hotfix|emergency|rollback'`], - map: ['缩略图只画第一层:面积是 HEAD 中的文件数,颜色是窗口内的修改次数(与“代码热点”同一口径),按分位数分成 5 档。大目录逐层展开,过小的子项合并成“其他 N 项”。点任意一块,会在“代码地图”分区里打开并定位到那里。', `git ls-tree -r --name-only HEAD | cut -d/ -f1 | sort | uniq -c | sort -nr\ngit log --format=format: --name-only${since} | sort | uniq -c | sort -nr`], - mapview: ['把 HEAD 的目录树画成方块。面积默认是文件数,可以切换成所选时间范围内的修改次数;颜色按上方选择的视角。大目录逐层展开,小于 0.5% 的子项合并成“其他 N 项”。已删除文件的修改,算到它最深的、仍然存在的目录上。时间范围从今天往前算;仓库已经停更时,从最后一次提交往前算。', `git ls-tree -r --name-only HEAD\ngit log -M100% --name-status --format='%H %aN %ct %s'${mSince} HEAD`], - couple: [`“A 常和 B 一起改”指改了 A 的提交里,同时也改了 B 的比例。这个比例有方向,A→B 和 B→A 可能不同(code-maat 用两边提交数的平均值做分母)。只统计所选时间范围内的非合并提交,超过 ${cp.maxChangeset} 个文件的大提交不计。门槛沿用 code-maat 的默认值:两边各至少 ${cp.minRevs} 个提交、一起改过至少 ${cp.minShared} 次、比例 ≥${Math.round(cp.minDegree * 100)}%。changelog、lock 文件这类几乎随每次修改一起改的流程文件单独列出,不画线;测试目录和同一个包里的代码一起改,标为“测试同步”。`, `git log --no-merges --numstat --date=short --pretty=format:'--%h--%ad--%aN' --no-renames${mSince} HEAD > logfile.log\njava -jar code-maat.jar -l logfile.log -c git2 -a coupling -s ${cp.maxChangeset} -n ${cp.minRevs} -m ${cp.minShared} -i ${Math.round(cp.minDegree * 100)}`], - cal: ['近 365 天每天的提交数,按作者日期统计,含合并提交(与“提交节奏”同一口径)。', "git log --since='1 year ago' --date=short --format='%ad' | sort | uniq -c"], + window: [tr("按 skill 的规则给仓库分档:<500 个 commit 看全部历史,500–10k 看 1 年,>10k 看 6 个月。"), `git rev-list --count HEAD\ngit log --oneline${since} | wc -l`], + risk: [tr("同时出现在“代码热点 Top {0}”和“Bug 磁铁 Top {1}”里的文件。", v.N, v.N), `git log --format=format: --name-only${since} | sort | uniq -c | sort -nr | head -${v.N}\ngit log -i -E --grep="fix|bug|broken" --name-only --format=''${since} | sort | uniq -c | sort -nr | head -${v.N}`], + active: [tr("近 3 个月有非合并提交的人数 / 历史总人数,低于 30% 时告警。{0}", rep.identity === 'merged' ? tr("当前为“合并身份”口径:大小写不同的同名账号与同邮箱账号视为一人,机器人不计入。") : tr("当前为原始口径,与 shortlog 完全一致。")), 'git shortlog -sn --no-merges --since="3 months ago" HEAD | wc -l\ngit shortlog -sn --no-merges HEAD | wc -l'], + half: [tr("按非合并提交数从高到低累加,达到总数一半时的人数。数字越小,知识越集中。"), 'git shortlog -sn --no-merges HEAD'], + trend: [tr("比较最近 3 个完整月和之前 3 个月的月均提交数:高 20% 以上为上升,低 20% 以上为下降;环比平均波动超过 50% 为波动。当月未结束不计入。"), "git log --format='%ad' --date=format:'%Y-%m' | sort | uniq -c"], + fire: [tr("窗口内标题含 revert / hotfix / emergency / rollback 的提交占比,≥5% 判为偏高(skill 未给阈值)。"), `git log --oneline${since} | grep -iE 'revert|hotfix|emergency|rollback'`], + map: [tr("缩略图只画第一层:面积是 HEAD 中的文件数,颜色是窗口内的修改次数(与“代码热点”同一口径),按分位数分成 5 档。大目录逐层展开,过小的子项合并成“其他 N 项”。点任意一块,会在“代码地图”分区里打开并定位到那里。"), `git ls-tree -r --name-only HEAD | cut -d/ -f1 | sort | uniq -c | sort -nr\ngit log --format=format: --name-only${since} | sort | uniq -c | sort -nr`], + mapview: [tr("把 HEAD 的目录树画成方块。面积默认是文件数,可以切换成所选时间范围内的修改次数;颜色按上方选择的视角。大目录逐层展开,小于 0.5% 的子项合并成“其他 N 项”。已删除文件的修改,算到它最深的、仍然存在的目录上。时间范围从今天往前算;仓库已经停更时,从最后一次提交往前算。"), `git ls-tree -r --name-only HEAD\ngit log -M100% --name-status --format='%H %aN %ct %s'${mSince} HEAD`], + couple: [tr("“A 常和 B 一起改”指改了 A 的提交里,同时也改了 B 的比例。这个比例有方向,A→B 和 B→A 可能不同(code-maat 用两边提交数的平均值做分母)。只统计所选时间范围内的非合并提交,超过 {0} 个文件的大提交不计。门槛沿用 code-maat 的默认值:两边各至少 {1} 个提交、一起改过至少 {2} 次、比例 ≥{3}%。changelog、lock 文件这类几乎随每次修改一起改的流程文件单独列出,不画线;测试目录和同一个包里的代码一起改,标为“测试同步”。", cp.maxChangeset, cp.minRevs, cp.minShared, Math.round(cp.minDegree * 100)), `git log --no-merges --numstat --date=short --pretty=format:'--%h--%ad--%aN' --no-renames${mSince} HEAD > logfile.log\njava -jar code-maat.jar -l logfile.log -c git2 -a coupling -s ${cp.maxChangeset} -n ${cp.minRevs} -m ${cp.minShared} -i ${Math.round(cp.minDegree * 100)}`], + cal: [tr("近 365 天每天的提交数,按作者日期统计,含合并提交(与“提交节奏”同一口径)。"), "git log --since='1 year ago' --date=short --format='%ad' | sort | uniq -c"], }[key]; if (!E) return ''; - return ``; + return tr("", key, ICON.info, key, esc(E[0]), esc(E[1]), esc(E[1]), ICON.copy); } function kpi({ label, value, sub, accent, i, key, rep, viz = '', tip = '' }) { return `
    ${label}${key ? explainFor(key, rep) : ''}
    ${value}
    ${sub}
    ${viz}
    `; @@ -595,67 +576,36 @@ function kpisHtml(rep) { const shares = top.map((c) => ({ value: c.share, color: C.memberColor(c.name) })); shares.push({ value: Math.max(0, 1 - top.reduce((s2, c) => s2 + c.share, 0)), color: 'var(--k-other)' }); const ffMax = Math.max(0.1, ff.rate * 1.4); - return `
    ${[ - kpi({ i: 0, rep, key: 'window', label: '窗口内提交', value: num(v.windowCommits), sub: `${WINDOW_ZH[v.window] || v.window} · 全部 ${fmt(v.commits)}`, accent: 'var(--k-code)', viz: C.sparkline(months, { w: 120, h: 26, stretch: true, color: 'var(--k-code)' }), tip: `近 12 个月每月提交数\n${mo.months.slice(-12).map((x) => `${x.m} ${fmt(x.n)}`).join('\n')}` }), - kpi({ i: 1, rep, key: 'risk', label: '高风险文件', value: num(rep.highRisk.length), sub: `热点 Top ${v.N} 中有 ${rep.highRisk.length} 个也是 Bug 磁铁`, accent: 'var(--mcode-danger)', viz: C.dots(v.N, riskRanks) }), - kpi({ i: 2, rep, key: 'active', label: '活跃贡献者', value: `${num(bf.active3m)}/ ${fmt(bf.total)}`, sub: `近 3 个月 · ${pct(bf.ratio)}${bf.warn ? ' · 低于 30%' : ''}`, accent: 'var(--k-merge)', viz: C.meter({ value: bf.ratio, threshold: 0.3, tick: '30%', color: bf.warn ? 'var(--mcode-danger)' : 'var(--k-merge)' }) }), - kpi({ i: 3, rep, key: 'half', label: '一半提交来自', value: `${num(bf.halfCount)}人`, sub: `第一名占 ${pct(bf.topShare)}`, accent: 'var(--k-mr)', viz: C.stackMeter(shares, { mark: 0.5, tick: '50%' }) }), - kpi({ i: 4, rep, key: 'trend', label: '提交节奏', value: `${TREND[mo.trend]} ${TREND_GLYPH[mo.trend]}`, sub: mo.trend === 'insufficient' ? '历史不足 6 个月' : `月均 ${fmt(Math.round(mo.lastAvg))} ← ${fmt(Math.round(mo.prevAvg))}`, accent: 'var(--k-review)', viz: C.miniBars(done.map((x) => x.n), { hi: 3, color: TREND_COLOR[mo.trend] }), tip: done.map((x) => `${x.m} ${fmt(x.n)}`).join('\n') }), - kpi({ i: 5, rep, key: 'fire', label: '救火提交', value: num((ff.rate * 100).toFixed(1), 'pct1'), sub: `${fmt(ff.count)} / ${fmt(ff.total)}${ff.rate >= 0.05 ? ' · 偏高' : ''}`, accent: 'var(--k-comment)', viz: C.meter({ value: ff.rate, max: ffMax, threshold: 0.05, tick: '5%', color: ff.rate >= 0.05 ? 'var(--mcode-warning)' : 'var(--k-comment)' }) }), - ].join('')}
    `; + return tr("
    {0}
    ", [ + kpi({ i: 0, rep, key: 'window', label: tr("窗口内提交"), value: num(v.windowCommits), sub: tr("{0} · 全部 {1}", WINDOW_LANG[v.window] || v.window, fmt(v.commits)), accent: 'var(--k-code)', viz: C.sparkline(months, { w: 120, h: 26, stretch: true, color: 'var(--k-code)' }), tip: tr("近 12 个月每月提交数\n{0}", mo.months.slice(-12).map((x) => `${x.m} ${fmt(x.n)}`).join('\n')) }), + kpi({ i: 1, rep, key: 'risk', label: tr("高风险文件"), value: num(rep.highRisk.length), sub: tr("热点 Top {0} 中有 {1} 个也是 Bug 磁铁", v.N, rep.highRisk.length), accent: 'var(--mcode-danger)', viz: C.dots(v.N, riskRanks) }), + kpi({ i: 2, rep, key: 'active', label: tr("活跃贡献者"), value: `${num(bf.active3m)}/ ${fmt(bf.total)}`, sub: tr("近 3 个月 · {0}{1}", pct(bf.ratio), bf.warn ? tr(" · 低于 30%") : ''), accent: 'var(--k-merge)', viz: C.meter({ value: bf.ratio, threshold: 0.3, tick: '30%', color: bf.warn ? 'var(--mcode-danger)' : 'var(--k-merge)' }) }), + kpi({ i: 3, rep, key: 'half', label: tr("一半提交来自"), value: tr("{0}人", num(bf.halfCount)), sub: tr("第一名占 {0}", pct(bf.topShare)), accent: 'var(--k-mr)', viz: C.stackMeter(shares, { mark: 0.5, tick: '50%' }) }), + kpi({ i: 4, rep, key: 'trend', label: tr("提交节奏"), value: `${TREND[mo.trend]} ${TREND_GLYPH[mo.trend]}`, sub: mo.trend === 'insufficient' ? tr("历史不足 6 个月") : tr("月均 {0} ← {1}", fmt(Math.round(mo.lastAvg)), fmt(Math.round(mo.prevAvg))), accent: 'var(--k-review)', viz: C.miniBars(done.map((x) => x.n), { hi: 3, color: TREND_COLOR[mo.trend] }), tip: done.map((x) => `${x.m} ${fmt(x.n)}`).join('\n') }), + kpi({ i: 5, rep, key: 'fire', label: tr("救火提交"), value: num((ff.rate * 100).toFixed(1), 'pct1'), sub: tr("{0} / {1}{2}", fmt(ff.count), fmt(ff.total), ff.rate >= 0.05 ? tr(" · 偏高") : ''), accent: 'var(--k-comment)', viz: C.meter({ value: ff.rate, max: ffMax, threshold: 0.05, tick: '5%', color: ff.rate >= 0.05 ? 'var(--mcode-warning)' : 'var(--k-comment)' }) }), + ].join('')); } function deltaHtml(rep) { const d = rep.delta; if (!d) return ''; - const parts = [`${d.commits >= 0 ? '+' : ''}${fmt(d.commits)} 个 commit`]; - if (d.riskAdded?.length) parts.push(`高风险新增 ${d.riskAdded.slice(0, 3).map((p) => pathHtml(p)).join('、')}${d.riskAdded.length > 3 ? ` 等 ${d.riskAdded.length} 个` : ''}`); - if (d.riskRemoved?.length) parts.push(`移出 ${d.riskRemoved.length} 个`); - if (d.trendFrom && d.trendFrom !== d.trendTo) parts.push(`节奏 ${TREND[d.trendFrom]} → ${TREND[d.trendTo]}`); - return `
    ${ICON.bolt}自上次分析(${esc(d.fromHead.slice(0, 8))},${relTime(d.fromAt)})以来:${parts.join(' · ')}
    `; + const parts = [tr("{0}{1} 个 commit", d.commits >= 0 ? '+' : '', fmt(d.commits))]; + if (d.riskAdded?.length) parts.push(tr("高风险新增 {0}{1}", d.riskAdded.slice(0, 3).map((p) => pathHtml(p)).join(tr("、")), d.riskAdded.length > 3 ? tr(" 等 {0} 个", d.riskAdded.length) : '')); + if (d.riskRemoved?.length) parts.push(tr("移出 {0} 个", d.riskRemoved.length)); + if (d.trendFrom && d.trendFrom !== d.trendTo) parts.push(tr("节奏 {0} → {1}", TREND[d.trendFrom], TREND[d.trendTo])); + return tr("
    {0}自上次分析({1},{2})以来:{3}
    ", ICON.bolt, esc(d.fromHead.slice(0, 8)), relTime(d.fromAt), parts.join(' · ')); } -const seeAll = (tab, label = '查看全部') => `${label}${ICON.arrow}`; +const seeAll = (tab, label = tr("查看全部")) => `${label}${ICON.arrow}`; // ---- overview ------------------------------------------------------------- function overviewTab(rep) { const mo = rep.momentum; const cm = liteMap(rep); - return `${deltaHtml(rep)}${kpisHtml(rep)} -
    -
    -

    主要问题

    由提交历史上的确定性规则得出,点击进入对应分区
    - ${problemsHtml(rep)} -
    -
    -

    建议

    对应 skill 报告的 Recommendations
    - ${recHtml(rep)} -
    -
    -

    代码地图 ${explainFor('map', rep)}

    ${cm ? `面积是 HEAD 中的文件数,颜色是窗口内的修改次数。点任意一块,进入代码地图并定位到那里` : '这份报告来自旧版本,缩略图会在后台重新分析完成后出现;代码地图分区现在就能用'}
    ${cm ? C.heatLegend() : ''}${seeAll('map', '打开代码地图')}
    - ${cm ? `
    ${cm.blocks.some((b) => b.risk) ? '含高风险文件' : ''}${cm.blocks.some((b) => b.kind === 'other') ? '合并在一起的小项' : ''}${fmt(cm.totals.files)} 个文件 · 窗口内修改 ${fmt(cm.totals.churn)} 次 · ${fmt(cm.blocks.length)} 块
    ` : ''} -
    -
    -

    高风险文件

    前 5 个,按热点排名
    ${seeAll('risk', `全部 ${rep.highRisk.length} 个`)}
    - ${rep.highRisk.length ? `
      ${rep.highRisk.slice(0, 5).map((h, i) => `
    1. ${i + 1}${pathHtml(h.path)}${h.owner ? esc(h.owner.name) : '–'}${fmt(h.bugCount)}/${fmt(h.hotCount)}
    2. `).join('')}
    ` : `

    ${ICON.ok} 没有文件同时出现在两个榜单里。

    `} -
    -
    -

    主要贡献者

    非合并提交占比
    ${seeAll('people', `全部 ${fmt(rep.busFactor.total)} 人`)}
    - ${shareOfContributors(rep, 8)} -
      ${rep.contributors.slice(0, 5).map((c) => `
    1. ${c.rank}${avatar(c.name)}${personLink(c.name)}${fmt(c.commits)}${pct(c.share)}
    2. `).join('')}
    -
    -
    -

    提交节奏 ${TREND[mo.trend]}

    近 12 个月
    ${seeAll('momentum')}
    - ${momentumChart(rep, 12, 180)} -
    -
    -

    技术栈

    ${rep.tech ? '语言构成与主要框架' : '正在识别…'}
    ${rep.tech ? seeAll('tech') : ''}
    - ${rep.tech ? techSummary(rep.tech) : '
    '} -
    -
    `; + return tr("{0}{1}\n
    \n
    \n

    主要问题

    由提交历史上的确定性规则得出,点击进入对应分区
    \n {2}\n
    \n
    \n

    建议

    对应 skill 报告的 Recommendations
    \n {3}\n
    \n
    \n

    代码地图 {4}

    {5}
    {6}{7}
    \n {8}\n
    \n
    \n

    高风险文件

    前 5 个,按热点排名
    {9}
    \n {10}\n
    \n
    \n

    主要贡献者

    非合并提交占比
    {11}
    \n {12}\n
      {13}
    \n
    \n
    \n

    提交节奏 {15}

    近 12 个月
    {16}
    \n {17}\n
    \n
    \n

    技术栈

    {18}
    {19}
    \n {20}\n
    \n
    ", deltaHtml(rep), kpisHtml(rep), problemsHtml(rep), recHtml(rep), explainFor('map', rep), cm ? tr("面积是 HEAD 中的文件数,颜色是窗口内的修改次数。点任意一块,进入代码地图并定位到那里") : tr("这份报告来自旧版本,缩略图会在后台重新分析完成后出现;代码地图分区现在就能用"), cm ? C.heatLegend() : '', seeAll('map', tr("打开代码地图")), cm ? tr("
    {0}{1}{2} 个文件 · 窗口内修改 {3} 次 · {4} 块
    ", cm.blocks.some((b) => b.risk) ? tr("含高风险文件") : '', cm.blocks.some((b) => b.kind === 'other') ? tr("合并在一起的小项") : '', fmt(cm.totals.files), fmt(cm.totals.churn), fmt(cm.blocks.length)) : '', seeAll('risk', tr("全部 {0} 个", rep.highRisk.length)), rep.highRisk.length ? tr("
      {0}
    ", rep.highRisk.slice(0, 5).map((h, i) => tr("
  • {0}{1}{2}{4}/{5}
  • ", i + 1, pathHtml(h.path), h.owner ? esc(h.owner.name) : '–', esc(tr("修 bug {0} 次 / 共修改 {1} 次", h.bugCount, h.hotCount)), fmt(h.bugCount), fmt(h.hotCount))).join('')) : tr("

    {0} 没有文件同时出现在两个榜单里。

    ", ICON.ok), seeAll('people', tr("全部 {0} 人", fmt(rep.busFactor.total))), shareOfContributors(rep, 8), rep.contributors.slice(0, 5).map((c) => `
  • ${c.rank}${avatar(c.name)}${personLink(c.name)}${fmt(c.commits)}${pct(c.share)}
  • `).join(''), mo.trend, TREND[mo.trend], seeAll('momentum'), momentumChart(rep, 12, 180), rep.tech ? tr("语言构成与主要框架") : tr("正在识别…"), rep.tech ? seeAll('tech') : '', rep.tech ? techSummary(rep.tech) : '
    '); } function problemsHtml(rep) { const icon = { warn: ICON.alert, good: ICON.ok, info: ICON.info }; - const lvl = { warn: '提醒', good: '良好', info: '信息' }; - return `
      ${rep.problems + const lvl = { warn: tr("提醒"), good: tr("良好"), info: tr("信息") }; + return `
        ${langList(rep.problems) .map((p) => { const tab = TAB_OF_ANCHOR[p.anchor] || 'overview'; const inner = `${icon[p.level]}
        ${esc(p.title)}
        ${esc(p.detail)}
        ${tab !== 'overview' ? `` : ''}`; @@ -665,34 +615,23 @@ function problemsHtml(rep) { } function recHtml(rep) { const r = rep.recommendations; - return `
          -
        • 先读${r.startReading.length ? r.startReading.map((p) => `${pathHtml(p)}${fileActions(p, { compact: true })}`).join('') : '暂无'}
        • -
        • 找谁聊${r.talkTo ? `${avatar(r.talkTo.name)}${personLink(r.talkTo.name)}${pct(r.talkTo.share)} 的修改负责 ${pathHtml(r.talkTo.file)}` : '暂无'}
        • -
        • 注意${r.watchOut.length ? r.watchOut.map((w) => `${esc(w)}`).join('') : '没有明显的趋势风险'}
        • -
        • 继续
        • -
        `; + return tr("
          \n
        • 先读{0}
        • \n
        • 找谁聊{1}
        • \n
        • 注意{2}
        • \n
        • 继续
        • \n
        ", r.startReading.length ? r.startReading.map((p) => `${pathHtml(p)}${fileActions(p, { compact: true })}`).join('') : tr("暂无"), r.talkTo ? tr("{0}{1}{2} 的修改负责 {3}", avatar(r.talkTo.name), personLink(r.talkTo.name), pct(r.talkTo.share), pathHtml(r.talkTo.file)) : tr("暂无"), langList(r.watchOut).length ? langList(r.watchOut).map((w) => `${esc(w)}`).join('') : tr("没有明显的趋势风险"), ICON.chat); } function fileActions(path, { compact = false, exists = true } = {}) { const web = exists ? webLink('file', path) : null; const ed = exists ? editorLink(path) : null; const cls = compact ? 'icon-btn btn-ghost btn-sm mini' : 'btn-sm'; - return ` - - ${web ? `${ICON.ext}${compact ? '' : '网页'}` : ''} - ${ed ? `${ICON.code}${compact ? '' : 'VS Code'}` : ''} - `; + return tr("\n \n {4}\n {5}\n ", cls, esc(path), ICON.copy, compact ? '' : tr("复制路径"), web ? tr("{2}{3}", cls, esc(web), ICON.ext, compact ? '' : tr("网页")) : '', ed ? tr("{2}{3}", cls, esc(ed), ICON.code, compact ? '' : 'VS Code') : ''); } function shareOfContributors(rep, n) { const total = rep.contributors[0] ? Math.round(rep.contributors[0].commits / rep.contributors[0].share) : 0; const top = rep.contributors.slice(0, n); - return C.shareBar([...top.map((c) => ({ label: c.name, value: c.commits, color: C.memberColor(c.name) })), { label: '其他贡献者', value: Math.max(0, total - top.reduce((s, c) => s + c.commits, 0)), color: 'var(--k-other)' }], { height: 12, label: '提交占比' }); + return C.shareBar([...top.map((c) => ({ label: displayText(c.name), value: c.commits, color: C.memberColor(c.name) })), { label: tr("其他贡献者"), value: Math.max(0, total - top.reduce((s, c) => s + c.commits, 0)), color: 'var(--k-other)' }], { height: 12, label: tr("提交占比") }); } function techSummary(t) { const items = langItems(t); const groups = t.groups.filter((g) => !['语言与运行时', '工程实践', '代码质量'].includes(g.category)).slice(0, 4); - return `${C.shareBar(items, { height: 12, label: '语言构成' })} -
          ${items.slice(0, 4).map((i) => `
        • ${esc(i.label)}${pct(i.value / items.reduce((s, x) => s + x.value, 0))}
        • `).join('')}
        -
        ${groups.map((g) => `
        ${esc(g.category)}
        ${g.items.slice(0, 5).map((i) => esc(i.name)).join(' · ')}
        `).join('')}
        `; + return tr("{0}\n
          {1}
        \n
        {2}
        ", C.shareBar(items, { height: 12, label: tr("语言构成") }), items.slice(0, 4).map((i) => `
      • ${esc(i.label)}${pct(i.value / items.reduce((s, x) => s + x.value, 0))}
      • `).join(''), groups.map((g) => `
        ${esc(tr(g.category))}
        ${g.items.slice(0, 5).map((i) => esc(tr(i.name))).join(' · ')}
        `).join('')); } // ---- risk tab ------------------------------------------------------------- @@ -704,91 +643,54 @@ function riskTab(rep) { const soloN = rep.highRisk.filter((h) => h.exists && h.owner && h.owner.share >= 0.8).length; const deletedN = rep.hotspots.filter((h) => !h.exists).length; const chips = [ - [null, `全部 ${rep.highRisk.length}`], - ['solo', `单人维护 ${soloN}`], - ['deleted', `已删除的热点 ${deletedN}`], + [null, tr("全部 {0}", rep.highRisk.length)], + ['solo', tr("单人维护 {0}", soloN)], + ['deleted', tr("已删除的热点 {0}", deletedN)], ]; - return `
        -

        高风险文件 ${explainFor('risk', rep)}

        同时出现在代码热点和 bug 磁铁里的文件;负责人按全部历史中改动它的非合并提交计算${rep.identity === 'merged' ? ',不含机器人' : ''}
        -
        ${chips.map(([k, l]) => `${l}`).join('')}
        - ${riskTable(list, rep)} -
        -
        -

        代码热点

        窗口内被修改次数最多的文件,红底表示同时是 bug 磁铁
        ${barListHtml(rep.hotspots, rep, 'var(--k-code)')}
        -

        Bug 磁铁

        提交说明含 fix / bug / broken 的提交最常改动的文件
        ${barListHtml(rep.bugMagnets, rep, 'var(--mcode-danger)')}
        -

        新增文件

        窗口内新增 ${fmt(rep.recentlyAdded.total)} 个文件,按目录看哪里在长新代码
        ${dirBars(rep.recentlyAdded.dirs)}
        -
        `; + return tr("
        \n

        高风险文件 {0}

        同时出现在代码热点和 bug 磁铁里的文件;负责人按全部历史中改动它的非合并提交计算{1}
        \n
        {2}
        \n {3}\n
        \n
        \n

        代码热点

        窗口内被修改次数最多的文件,红底表示同时是 bug 磁铁
        {4}
        \n

        Bug 磁铁

        提交说明含 fix / bug / broken 的提交最常改动的文件
        {5}
        \n

        新增文件

        窗口内新增 {6} 个文件,按目录看哪里在长新代码
        {7}
        \n
        ", explainFor('risk', rep), rep.identity === 'merged' ? tr(",不含机器人") : '', chips.map(([k, l]) => `${l}`).join(''), riskTable(list, rep), barListHtml(rep.hotspots, rep, 'var(--k-code)'), barListHtml(rep.bugMagnets, rep, 'var(--mcode-danger)'), fmt(rep.recentlyAdded.total), dirBars(rep.recentlyAdded.dirs)); } function riskTable(list, rep) { - if (!list.length) return route.filter ? '

        没有符合筛选条件的文件。

        ' : `
        ${ICON.ok}

        没有文件同时出现在两个榜单里

        No files appear in both lists — good sign.

        `; + if (!list.length) return route.filter ? tr("

        没有符合筛选条件的文件。

        ") : tr("
        {0}

        没有文件同时出现在两个榜单里

        No files appear in both lists — good sign.

        ", ICON.ok); const maxHot = Math.max(...list.map((h) => h.hotCount || 0), 1); - return `
        - ${list + return tr("
        高风险文件
        文件热点修改次数磁铁修 bug主要负责人其他维护者操作
        \n {0}
        高风险文件
        文件热点修改次数磁铁修 bug主要负责人其他维护者操作
        ", list .map( - (h) => ` - ${pathHtml(h.path)}${h.exists ? '' : ' 已删除'} - #${h.hotRank} -
        ${fmt(h.hotCount)}
        - ${h.bugRank ? `#${h.bugRank}` : '–'}${h.bugCount != null ? `${fmt(h.bugCount)} ${pct(h.bugCount / h.hotCount)}` : '–'} - ${h.owner ? `
        ${avatar(h.owner.name)}
        ${personLink(h.owner.name)}
        ${pct(h.owner.share)} 的修改${h.owner.share >= 0.8 ? ' · 单人维护' : ''}
        ` : '–'} - ${(h.owners || []).slice(1, 4).map((o) => `${esc(o.name)} ${pct(o.share)}`).join('、') || '–'} - ${fileActions(h.path, { compact: true, exists: h.exists })}`, + (h) => tr("\n {0}{1}\n #{2}\n
        {4}
        \n {5}{6}\n {7}\n {8}\n {9}", pathHtml(h.path), h.exists ? '' : tr(" 已删除"), h.hotRank, ((100 * (h.hotCount || 0)) / maxHot).toFixed(1), fmt(h.hotCount), h.bugRank ? `#${h.bugRank}` : '–', h.bugCount != null ? `${fmt(h.bugCount)} ${pct(h.bugCount / h.hotCount)}` : '–', h.owner ? tr("
        {0}
        {1}
        {2} 的修改{3}
        ", avatar(h.owner.name), personLink(h.owner.name), pct(h.owner.share), h.owner.share >= 0.8 ? tr(" · 单人维护") : '') : '–', (h.owners || []).slice(1, 4).map((o) => `${esc(displayText(o.name))} ${pct(o.share)}`).join(tr("、")) || '–', fileActions(h.path, { compact: true, exists: h.exists })), ) - .join('')}`; + .join('')); } function barListHtml(list, rep, color) { - if (!list.length) return '

        窗口内没有数据。

        '; + if (!list.length) return tr("

        窗口内没有数据。

        "); const risk = new Set(rep.highRisk.map((h) => h.path)); const max = list[0].count; return `
          ${list.map((x) => `
        1. ${x.rank}${pathHtml(x.path)}
          ${fmt(x.count)}
        2. `).join('')}
        `; } function dirBars(dirs) { - if (!dirs.length) return '

        窗口内没有新增文件。

        '; + if (!dirs.length) return tr("

        窗口内没有新增文件。

        "); const max = dirs[0][1]; - return `
          ${dirs.map(([d, n], i) => `
        1. ${i + 1}${esc(d)}
          ${fmt(n)}
        2. `).join('')}
        `; + return `
          ${dirs.map(([d, n], i) => `
        1. ${i + 1}${esc(displayText(d))}
          ${fmt(n)}
        2. `).join('')}
        `; } // ---- people tab ----------------------------------------------------------- function peopleTab(rep) { const bf = rep.busFactor; - return `
        -

        贡献者排名 ${explainFor('half', rep)}

        按全部历史的非合并提交数排序,共 ${fmt(bf.total)} 人;近 3 个月活跃 ${bf.active3m} 人${explainFor('active', rep)}
        -
        -
        - - -
        -
        - ${shareOfContributors(rep, 8)} -
        ${contribHtml(rep)}
        -
        - ${ + return tr("
        \n

        贡献者排名 {0}

        按全部历史的非合并提交数排序,共 {1} 人;近 3 个月活跃 {2} 人{3}
        \n
        \n
        \n \n \n
        \n
        \n {7}\n
        {8}
        \n
        \n {9}", explainFor('half', rep), fmt(bf.total), bf.active3m, explainFor('active', rep), state.identity === 'merged', state.identity === 'raw', esc(state.contribFilter), shareOfContributors(rep, 8), contribHtml(rep), rep.identity === 'merged' && rep.bots.length - ? `

        机器人与令牌账号

        按名字和邮箱识别(如 [bot]、project_*_bot、agent 账号),不参与排名、活跃比例和负责人计算;切到“原始口径”可看 skill 的原始结果
        -
        ${rep.bots.map((b) => `${esc(b.name)}${fmt(b.commits)}`).join('')}
        ` + ? tr("

        机器人与令牌账号

        按名字和邮箱识别(如 [bot]、project_*_bot、agent 账号),不参与排名、活跃比例和负责人计算;切到“原始口径”可看 skill 的原始结果
        \n
        {0}
        ", rep.bots.map((b) => `${esc(displayText(b.name))}${fmt(b.commits)}`).join('')) : '' - }`; + ); } function contribHtml(rep) { const q = state.contribFilter.trim().toLowerCase(); const matched = rep.contributors.filter((c) => !q || [c.name, ...(c.aliases || [])].some((n) => n.toLowerCase().includes(q))); const list = state.contribAll || q ? matched : matched.slice(0, 20); const max = rep.contributors[0]?.commits || 1; - return ` - ${ + return tr("
        贡献者排名
        #贡献者提交数占比窗口内修 bug近 12 个月首次 → 最近状态主要目录
        \n {0}
        贡献者排名
        #贡献者提交数占比窗口内修 bug近 12 个月首次 → 最近状态主要目录
        {1}", list .map( - (c) => `${c.rank} -
        ${avatar(c.name)}
        ${personLink(c.name)}${c.aliases?.length ? `
        也作 ${esc(c.aliases.join('、'))}
        ` : ''}
        -
        ${fmt(c.commits)}
        - ${pct(c.share, 1)}${fmt(c.window)}${fmt(c.fixes)} - ${C.sparkline(c.monthly, { color: C.memberColor(c.name) })} - ${c.first} → ${c.last} - ${c.active ? '活跃' : '近 3 月无提交'} - ${c.dirs.slice(0, 2).map(([d]) => `${esc(d)}`).join('、')}`, + (c) => tr("{0}\n
        {1}
        {2}{3}
        \n
        {6}
        \n {7}{8}{9}\n {10}\n {11} → {12}\n {13}\n {15}", c.rank, avatar(c.name), personLink(c.name), c.aliases?.length ? tr("
        也作 {0}
        ", esc(c.aliases.join(tr("、")))) : '', ((100 * c.commits) / max).toFixed(1), C.memberColor(c.name), fmt(c.commits), pct(c.share, 1), fmt(c.window), fmt(c.fixes), C.sparkline(c.monthly, { color: C.memberColor(c.name) }), c.first, c.last, c.active ? tr("活跃") : tr("近 3 月无提交"), esc(c.dirs.map(([d, n]) => `${displayText(d)} ${n}`).join('\n')), c.dirs.slice(0, 2).map(([d]) => `${esc(displayText(d))}`).join(tr("、"))), ) - .join('') || `没有匹配的贡献者` - }${!q && matched.length > 20 ? `
        ` : ''}`; + .join('') || tr("没有匹配的贡献者") + , !q && matched.length > 20 ? tr("
        ", state.contribAll ? tr("收起") : tr("展开全部 {0} 人", matched.length)) : ''); } // ---- momentum tab --------------------------------------------------------- @@ -799,8 +701,8 @@ function momentumChart(rep, last, height = 220) { const last3 = done.slice(-3); const prev3 = done.slice(-6, -3); const bands = []; - if (prev3.length === 3) bands.push({ from: prev3[0].m, to: prev3[2].m, value: mo.prevAvg, label: `之前月均 ${fmt(Math.round(mo.prevAvg))}`, color: 'var(--k-other)' }); - if (last3.length) bands.push({ from: last3[0].m, to: last3[last3.length - 1].m, value: mo.lastAvg, label: `近 3 月 ${fmt(Math.round(mo.lastAvg))}`, color: mo.trend === 'declining' ? 'var(--mcode-danger)' : mo.trend === 'rising' ? 'var(--mcode-success)' : 'var(--k-review)' }); + if (prev3.length === 3) bands.push({ from: prev3[0].m, to: prev3[2].m, value: mo.prevAvg, label: tr("之前月均 {0}", fmt(Math.round(mo.prevAvg))), color: 'var(--k-other)' }); + if (last3.length) bands.push({ from: last3[0].m, to: last3[last3.length - 1].m, value: mo.lastAvg, label: tr("近 3 月 {0}", fmt(Math.round(mo.lastAvg))), color: mo.trend === 'declining' ? 'var(--mcode-danger)' : mo.trend === 'rising' ? 'var(--mcode-success)' : 'var(--k-review)' }); return C.monthBars({ months, partial: mo.partialMonth, bands, height }); } function calStats(a) { @@ -829,74 +731,50 @@ function calendarCard(rep) { const a = rep.activity; if (!a) return ''; const st = calStats(a); - return `
        -

        提交日历 ${explainFor('cal', rep)}

        近 365 天,共 ${fmt(st.total)} 个 commit;颜色越深当天提交越多
        ${C.heatLegend()}
        -
        ${C.calendar({ daily: a.daily, start: a.start, end: a.end, cell: 13, gap: 3, label: `提交日历:近 365 天有 ${st.active} 天有提交`, unit: '个 commit' })}
        -
        -
        ${st.active} / ${st.span}
        有提交的天数
        -
        ${st.best} 天
        最长连续${st.bestEnd ? `,止于 ${st.bestEnd.slice(5)}` : ''}
        -
        ${fmt(st.peak[1])}
        单日最多${st.peak[0] ? `(${st.peak[0]})` : ''}
        -
        ${pct(st.weekend)}
        周末提交占比
        -
        -
        `; + return tr("
        \n

        提交日历 {0}

        近 365 天,共 {1} 个 commit;颜色越深当天提交越多
        {2}
        \n
        {3}
        \n
        \n
        {4} / {5}
        有提交的天数
        \n
        {6} 天
        最长连续{7}
        \n
        {8}
        单日最多{9}
        \n
        {10}
        周末提交占比
        \n
        \n
        ", explainFor('cal', rep), fmt(st.total), C.heatLegend(), C.calendar({ daily: a.daily, start: a.start, end: a.end, cell: 13, gap: 3, label: tr("提交日历:近 365 天有 {0} 天有提交", st.active), unit: tr("个 commit") }), st.active, st.span, st.best, st.bestEnd ? tr(",止于 {0}", st.bestEnd.slice(5)) : '', fmt(st.peak[1]), st.peak[0] ? tr("({0})", st.peak[0]) : '', pct(st.weekend)); } function momentumTab(rep) { const mo = rep.momentum; const ff = rep.firefighting; - return `${calendarCard(rep)}
        -

        提交节奏 ${TREND[mo.trend]} ${explainFor('trend', rep)}

        每月提交数(含合并提交)。虚线是近 3 个月和之前 3 个月的月均${mo.partialMonth ? `;${mo.partialMonth} 尚未结束,浅色显示` : ''}
        -
        -
        ${momentumChart(rep, state.momentumAll ? 0 : 24)}
        -
        -
        -

        救火记录 ${explainFor('fire', rep)}

        窗口内 ${fmt(ff.count)} 次,占 ${pct(ff.rate, 1)}${ff.count > ff.list.length ? `,显示最近 ${ff.list.length} 条` : ''}
        -
        ${ff.kinds.map(([k, n]) => `${esc(k)} ${fmt(n)}`).join('')}
        - ${ff.list.length ? `
          ${ff.list.map((c) => commitRow(c)).join('')}
        ` : '

        窗口内没有救火类提交。

        '} -
        `; + return tr("{0}
        \n

        提交节奏 {2} {3}

        每月提交数(含合并提交)。虚线是近 3 个月和之前 3 个月的月均{4}
        \n
        \n
        {7}
        \n
        \n
        \n

        救火记录 {8}

        窗口内 {9} 次,占 {10}{11}
        \n
        {12}
        \n {13}\n
        ", calendarCard(rep), mo.trend, TREND[mo.trend], explainFor('trend', rep), mo.partialMonth ? tr(";{0} 尚未结束,浅色显示", mo.partialMonth) : '', !state.momentumAll, state.momentumAll, momentumChart(rep, state.momentumAll ? 0 : 24), explainFor('fire', rep), fmt(ff.count), pct(ff.rate, 1), ff.count > ff.list.length ? tr(",显示最近 {0} 条", ff.list.length) : '', ff.kinds.map(([k, n]) => `${esc(k)} ${fmt(n)}`).join(''), ff.list.length ? `
          ${ff.list.map((c) => commitRow(c)).join('')}
        ` : tr("

        窗口内没有救火类提交。

        ")); } function commitRow(c, extra = '') { const link = webLink('commit', c.sha); const subj = link ? `${esc(c.subj)}` : `${esc(c.subj)}`; - return `
      • ${esc(c.date)}${extra}${subj}${c.author ? ` · ${esc(c.author)}` : ''}
      • `; + return tr("
      • {0}{1}{2}{5}
      • ", esc(c.date), extra, subj, esc(c.sha), esc(c.sha.slice(0, 7)), c.author ? ` · ${esc(displayText(c.author))}` : ''); } // ---- tech tab ------------------------------------------------------------- function langItems(t) { const langs = t.languages.slice(0, 6); const rest = t.languages.slice(6).reduce((s, l) => s + l.files, 0); - return [...langs.map((l, i) => ({ label: l.name, value: l.files, color: LANG_COLORS[i] })), ...(rest ? [{ label: '其他', value: rest, color: 'var(--heat-1)' }] : [])]; + return [...langs.map((l, i) => ({ label: l.name, value: l.files, color: LANG_COLORS[i] })), ...(rest ? [{ label: tr("其他"), value: rest, color: 'var(--heat-1)' }] : [])]; } function techTab(rep) { const t = rep.tech; - if (!t) return '

        正在识别技术栈…

        '; + if (!t) return tr("

        正在识别技术栈…

        "); const items = langItems(t); const total = items.reduce((s, x) => s + x.value, 0) || 1; - const pms = t.packageManagers.length ? `

        包管理

        ${t.packageManagers.map((p) => `${esc(p.name)}`).join('')}
        ` : ''; - const other = t.otherDeps.length ? `

        其他常用依赖(未归类,按被多少个 manifest 引用排序)

        ${t.otherDeps.map((d) => `${esc(d.name)}${d.n}`).join('')}
        ` : ''; - return `
        -

        技术栈

        语言按 HEAD 中的文件数统计;框架和工具来自 ${fmt(t.manifests.reduce((s, m) => s + m.n, 0))} 个 manifest 与配置文件,悬停或聚焦可看依据
        - ${items.length ? C.shareBar(items, { height: 14, label: '语言构成' }) : '

        没有识别到代码文件。

        '} -
          ${items.map((i) => `
        • ${esc(i.label)}${fmt(i.value)} · ${pct(i.value / total)}
        • `).join('')}
        -
        ${t.groups - .map((g) => `

        ${esc(g.category)}

        ${g.items.slice(0, 14).map((i) => `${esc(i.name)}${i.count > 1 ? `${i.count}` : ''}`).join('')}
        `) - .join('')}${pms}${other}
        - ${t.packages > 1 ? `

        共识别到 ${t.packages} 个 package.json。

        ` : ''} -
        `; + const pms = t.packageManagers.length ? tr("

        包管理

        {0}
        ", t.packageManagers.map((p) => `${esc(p.name)}`).join('')) : ''; + const other = t.otherDeps.length ? tr("

        其他常用依赖(未归类,按被多少个 manifest 引用排序)

        {0}
        ", t.otherDeps.map((d) => `${esc(displayText(d.name))}${d.n}`).join('')) : ''; + return tr("
        \n

        技术栈

        语言按 HEAD 中的文件数统计;框架和工具来自 {0} 个 manifest 与配置文件,悬停或聚焦可看依据
        \n {1}\n
          {2}
        \n
        {3}{4}{5}
        \n {6}\n
        ", fmt(t.manifests.reduce((s, m) => s + m.n, 0)), items.length ? C.shareBar(items, { height: 14, label: tr("语言构成") }) : tr("

        没有识别到代码文件。

        "), items.map((i) => `
      • ${esc(i.label)}${fmt(i.value)} · ${pct(i.value / total)}
      • `).join(''), t.groups + .map((g) => `

        ${esc(tr(g.category))}

        ${g.items.slice(0, 14).map((i) => `${esc(tr(i.name))}${i.count > 1 ? `${i.count}` : ''}`).join('')}
        `) + .join(''), pms, other, t.packages > 1 ? tr("

        共识别到 {0} 个 package.json。

        ", t.packages) : ''); } // --------------------------------------------------------------------------- // Code map tab // --------------------------------------------------------------------------- const LENSES = [ - ['heat', '热度', '所选时间范围内,这块里的文件一共被修改了多少次(与“代码热点”同一口径)。'], - ['bug', 'Bug 占比', '这些修改里,提交说明含 fix / bug / broken 的比例(与“Bug 磁铁”同一口径)。修改少于 5 次的块不着色。'], - ['owner', '负责人', '所选时间范围内在这块提交最多的人(非合并提交,不含机器人)。颜色越淡越是多人共有,第一名不到 25% 的标为“多人共有”。'], - ['age', '最近修改', '这块里最近一次提交距离仓库最新提交多久,看哪里还在演进、哪里已经稳定。不受时间范围影响。'], - ['loss', '知识流失', '这块全部历史提交中,来自近 3 个月没有任何提交的人的比例。比例高的地方,最熟悉它的人可能已经不在了。不受时间范围影响。'], - ['type', '文件类型', '按 HEAD 中的扩展名归类:颜色是占比最多的一类,块底部的细条是构成。没有说明的目录,可以靠它判断是代码、文档还是资源。'], + ['heat', tr("热度"), tr("所选时间范围内,这块里的文件一共被修改了多少次(与“代码热点”同一口径)。")], + ['bug', tr("Bug 占比"), tr("这些修改里,提交说明含 fix / bug / broken 的比例(与“Bug 磁铁”同一口径)。修改少于 5 次的块不着色。")], + ['owner', tr("负责人"), tr("所选时间范围内在这块提交最多的人(非合并提交,不含机器人)。颜色越淡越是多人共有,第一名不到 25% 的标为“多人共有”。")], + ['age', tr("最近修改"), tr("这块里最近一次提交距离仓库最新提交多久,看哪里还在演进、哪里已经稳定。不受时间范围影响。")], + ['loss', tr("知识流失"), tr("这块全部历史提交中,来自近 3 个月没有任何提交的人的比例。比例高的地方,最熟悉它的人可能已经不在了。不受时间范围影响。")], + ['type', tr("文件类型"), tr("按 HEAD 中的扩展名归类:颜色是占比最多的一类,块底部的细条是构成。没有说明的目录,可以靠它判断是代码、文档还是资源。")], ]; const PLAYABLE = new Set(['heat', 'bug', 'owner']); -const RANGES = [['3', '近 3 个月'], ['6', '近 6 个月'], ['12', '近 12 个月'], ['all', '全部历史']]; +const RANGES = [['3', tr("近 3 个月")], ['6', tr("近 6 个月")], ['12', tr("近 12 个月")], ['all', tr("全部历史")]]; const TYPE_META = { ts: ['TypeScript', 'hsl(210 65% 52%)'], js: ['JavaScript', 'hsl(45 85% 50%)'], @@ -909,16 +787,16 @@ const TYPE_META = { rb: ['Ruby', 'hsl(352 62% 52%)'], php: ['PHP', 'hsl(200 38% 40%)'], dotnet: ['.NET', 'hsl(140 45% 42%)'], - style: ['样式', 'hsl(340 65% 62%)'], - markup: ['HTML / 模板', 'hsl(26 85% 58%)'], - shell: ['脚本', 'hsl(95 40% 44%)'], - doc: ['文档', 'hsl(205 18% 58%)'], - config: ['配置 / 数据', 'hsl(48 24% 52%)'], - asset: ['图片 / 字体 / 二进制', 'hsl(0 0% 50%)'], - other: ['其他', 'hsl(0 0% 36%)'], + style: [tr("样式"), 'hsl(340 65% 62%)'], + markup: [tr("HTML / 模板"), 'hsl(26 85% 58%)'], + shell: [tr("脚本"), 'hsl(95 40% 44%)'], + doc: [tr("文档"), 'hsl(205 18% 58%)'], + config: [tr("配置 / 数据"), 'hsl(48 24% 52%)'], + asset: [tr("图片 / 字体 / 二进制"), 'hsl(0 0% 50%)'], + other: [tr("其他"), 'hsl(0 0% 36%)'], }; const OWNER_COLORS = ['#2f9e8f', '#f08a4b', '#3b8fd9', '#e5b72f', '#5bb85b', '#e5576f', '#22b8cf', '#b8875a']; -const AGE_LABELS = ['1 周内', '1 个月内', '3 个月内', '1 年内', '更早']; +const AGE_LABELS = [tr("1 周内"), tr("1 个月内"), tr("3 个月内"), tr("1 年内"), tr("更早")]; const LOSS_LABELS = ['<20%', '20–40%', '40–60%', '60–80%', '≥80%']; const NEUTRAL = 'var(--mcode-surface-muted)'; const DAY_S = 86_400; @@ -942,13 +820,13 @@ const mapPlaceFor = (id) => ({ focus: null, sel: null, lens: null, size: null, r const mapHeight = (w) => Math.round(Math.max(340, Math.min(620, w * 0.62))); const maxBlocksFor = (w, h) => Math.max(10, Math.min(44, Math.round((w * h) / 6500))); const parentOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : ''); -const rangeText = (v) => (v.range === 'custom' ? '分析窗口内' : { 3: '近 3 个月', 6: '近 6 个月', 12: '近 12 个月', all: '全部历史上' }[v.range] || ''); +const rangeText = (v) => (v.range === 'custom' ? tr("分析窗口内") : { 3: tr("近 3 个月"), 6: tr("近 6 个月"), 12: tr("近 12 个月"), all: tr("全部历史上") }[v.range] || ''); const ymdOfSec = (sec) => C.ymd(new Date(sec * 1000)); function agoText(days) { - if (days < 1) return '当天'; - if (days < 30) return `${Math.round(days)} 天前`; - if (days < 365) return `${Math.max(1, Math.round(days / 30))} 个月前`; - return `${(days / 365).toFixed(1)} 年前`; + if (days < 1) return tr("当天"); + if (days < 30) return tr("{0} 天前", Math.round(days)); + if (days < 365) return tr("{0} 个月前", Math.max(1, Math.round(days / 30))); + return tr("{0} 年前", (days / 365).toFixed(1)); } function quantiles(values) { const s = values.filter((x) => x > 0).sort((a, b) => a - b); @@ -990,29 +868,30 @@ function inkFor(fill, opacity = 1) { const bg = rgbOf('var(--mcode-surface)'); rgb = rgb.map((v, i) => v * opacity + bg[i] * (1 - opacity)); } - const t = (v) => { + const lin = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }; - return 0.2126 * t(rgb[0]) + 0.7152 * t(rgb[1]) + 0.0722 * t(rgb[2]) > 0.36 ? 'dark' : 'light'; + return 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]) > 0.36 ? 'dark' : 'light'; } // ---- names ---------------------------------------------------------------- function blockTitle(v, b) { if (b.kind === 'dir') return `${b.path}/`; - if (b.kind === 'other') return `${b.path ? `${b.path}/` : ''}${b.name}`; + if (b.kind === 'other') return `${b.path ? `${b.path}/` : ''}${pick(b.name)}`; return b.path; } function blockLabels(focus, b) { if (b.kind === 'other') { - const n = b.name.match(/\d+/)?.[0] || ''; - return [b.name, `${n} 项`, `+${n}`]; + const name = pick(b.name); + const n = name.match(/\d+/)?.[0] || ''; + return [name, tr("{0} 项", n), `+${n}`]; } if (b.kind === 'file') return [b.name, b.name.replace(/\.[^.]+$/, '')]; const rel = b.group && b.path.startsWith(`${b.group}/`) ? b.path.slice(b.group.length + 1) : focus && b.path.startsWith(`${focus}/`) ? b.path.slice(focus.length + 1) : b.path; return C.dirLabels(rel); } -const groupLabel = (focus, k) => (k === '' ? (focus ? '本层' : '根目录') : `${focus && k.startsWith(`${focus}/`) ? k.slice(focus.length + 1) : k}/`); +const groupLabel = (focus, k) => (k === '' ? (focus ? tr("本层") : tr("根目录")) : `${focus && k.startsWith(`${focus}/`) ? k.slice(focus.length + 1) : k}/`); // Selection key in the URL: the path, except merged blocks ("其他 N 项"), whose path is their parent's // (possibly the root, ''), so they get "/*". const selKey = (b) => (b.kind === 'other' ? `${b.path ? `${b.path}/` : ''}*` : b.path); @@ -1043,7 +922,7 @@ function selIndex(v, sel) { function crumbsHtml(focus) { const r = current(); const segs = focus ? focus.split('/') : []; - const items = [['', r ? r.name.split('/').pop() : '根目录'], ...segs.map((s, i) => [segs.slice(0, i + 1).join('/'), s])]; + const items = [['', r ? r.name.split('/').pop() : tr("根目录")], ...segs.map((s, i) => [segs.slice(0, i + 1).join('/'), s])]; return items .map(([p, label], i) => i === items.length - 1 @@ -1055,26 +934,7 @@ function crumbsHtml(focus) { const segBtns = (action, items, cur, label) => `
        ${items.map(([k, l]) => ``).join('')}
        `; function mapTab(rep) { const o = mapOpts(rep); - return `
        -
        -

        代码地图 ${explainFor('mapview', rep)}

        -
        ${segBtns('map-size', [['files', '按文件数'], ['churn', '按修改次数']], o.size, '面积代表')}${segBtns('map-range', [['3', '3 个月'], ['6', '6 个月'], ['12', '12 个月'], ['all', '全部']], o.range, '时间范围')}
        -
        -
        ${LENSES.map(([k, l]) => ``).join('')}
        -
        -
        -
        -
        -
        -

        -
        - -
        -
        -

        区域列表

        与地图同一批区域,可排序;点击区域名在地图上选中
        -
        -
        -
        `; + return tr("
        \n
        \n

        代码地图 {0}

        \n
        {2}{3}
        \n
        \n
        {4}
        \n
        \n
        \n
        \n
        \n
        \n

        \n
        \n \n
        \n
        \n

        区域列表

        与地图同一批区域,可排序;点击区域名在地图上选中
        \n
        \n
        \n
        ", explainFor('mapview', rep), crumbsHtml(o.focus), segBtns('map-size', [['files', tr("按文件数")], ['churn', tr("按修改次数")]], o.size, tr("面积代表")), segBtns('map-range', [['3', tr("3 个月")], ['6', tr("6 个月")], ['12', tr("12 个月")], ['all', tr("全部")]], o.range, tr("时间范围")), LENSES.map(([k, l]) => ``).join('')); } function syncMapControls() { const o = mapOpts(); @@ -1083,7 +943,7 @@ function syncMapControls() { } // The explain popover's command embeds the time range. const h = $('#h-maptab'); - if (h && state.report && !h.querySelector('[aria-expanded="true"]')) h.innerHTML = `代码地图 ${explainFor('mapview', state.report)}`; + if (h && state.report && !h.querySelector('[aria-expanded="true"]')) h.innerHTML = tr("代码地图 {0}", explainFor('mapview', state.report)); } // Links rendered with the map's settings in their URL (the current tab, breadcrumbs) would bring // back old settings after an in-place change, so rebuild them from the current route. @@ -1180,9 +1040,9 @@ function drawMap() { box.setAttribute('aria-busy', String(mp.loading)); if (mp.error) { mp.refocus = false; - box.innerHTML = `
        ${ICON.alert}

        代码地图加载失败

        ${esc(mp.error.message)}

        ${route.focus ? `回到根目录` : ''}

        `; + box.innerHTML = tr("
        {0}

        代码地图加载失败

        {1}

        {2}

        ", ICON.alert, esc(mp.error.message), route.focus ? tr("回到根目录", esc(href({ focus: null, sel: null }))) : '', ICON.sync); for (const id of ['#map-legend', '#map-time', '#map-note', '#map-table']) if ($(id)) $(id).innerHTML = ''; - $('#map-detail').innerHTML = '

        没有可显示的区域。

        '; + $('#map-detail').innerHTML = tr("

        没有可显示的区域。

        "); return; } if (!v) { @@ -1191,11 +1051,11 @@ function drawMap() { } mp.layout = null; if (!v.blocks.length) { - box.innerHTML = `
        ${ICON.map}

        ${v.size === 'churn' ? `${rangeText(v)}这里没有修改` : '这里没有文件'}

        ${v.size === 'churn' ? '面积按修改次数时,没有修改的区域不会出现。可以切换到“按文件数”或更长的时间范围。' : ''}

        `; + box.innerHTML = tr("
        {0}

        {1}

        {2}

        ", ICON.map, v.size === 'churn' ? tr("{0}这里没有修改", rangeText(v)) : tr("这里没有文件"), v.size === 'churn' ? tr("面积按修改次数时,没有修改的区域不会出现。可以切换到“按文件数”或更长的时间范围。") : ''); } else { mp.layout = C.mapLayout(v.blocks, { width: mp.w, height: mapHeight(mp.w), value: (b) => (v.size === 'churn' ? b.churn : b.files) }); mp.cellOf = new Map(mp.layout.cells.map((c) => [c.i, c])); - box.innerHTML = C.mapSvg(mp.layout, { blocks: v.blocks, groupLabel: (k) => groupLabel(v.focus, k), groupValue: (n) => `${C.fmtK(n)} ${v.size === 'churn' ? '次' : '个文件'}`, nameOf: (b) => blockLabels(v.focus, b), label: `代码地图:${v.focus ? `${v.focus}/` : '仓库根目录'},${v.blocks.length} 个区域。方向键在区域间移动,空格或单击选中,回车或双击进入` }); + box.innerHTML = C.mapSvg(mp.layout, { blocks: v.blocks, groupLabel: (k) => groupLabel(v.focus, k), groupValue: (n) => tr("{0} {1}", C.fmtK(n), v.size === 'churn' ? tr("次") : tr("个文件")), nameOf: (b) => blockLabels(v.focus, b), label: tr("代码地图:{0},{1} 个区域。方向键在区域间移动,空格或单击选中,回车或双击进入", v.focus ? `${v.focus}/` : tr("仓库根目录"), v.blocks.length) }); } paintMap(); renderMapLegend(); @@ -1216,51 +1076,52 @@ function lensPaint(v, b, lens, f) { case 'bug': { const n = f == null ? b.churn : b.m[f]; const k = f == null ? b.bug : b.mb[f]; - if (n < (f == null ? 5 : 3)) return none(n ? '样本少' : '无修改', `${range}修改 ${fmt(n)} 次,太少,不计算占比`); + if (n < (f == null ? 5 : 3)) return none(n ? tr("样本少") : tr("无修改"), tr("{0}修改 {1} 次,太少,不计算占比", range, fmt(n))); const ratio = k / n; const fill = `var(--risk-${C.riskLevel(ratio)})`; - return { fill, ink: inkFor(fill), val: pct(ratio), tip: [`${range}修改 ${fmt(n)} 次,其中修 bug ${fmt(k)} 次(${pct(ratio)})`], aria: `修 bug 占 ${pct(ratio)}` }; + return { fill, ink: inkFor(fill), val: pct(ratio), tip: [tr("{0}修改 {1} 次,其中修 bug {2} 次({3})", range, fmt(n), fmt(k), pct(ratio))], aria: tr("修 bug 占 {0}", pct(ratio)) }; } case 'owner': { if (f != null) { const a = b.mo[f]; - if (a < 0) return none('无人修改', `${range}没有人修改`); + if (a < 0) return none(tr("无人修改"), tr("{0}没有人修改", range)); const fill = v.palette.get(a) || 'var(--k-other)'; - return { fill, opacity: 0.92, ink: inkFor(fill, 0.92), val: v.authors[a], tip: [`${range}提交最多:${v.authors[a]}`], aria: `本月提交最多 ${v.authors[a]}` }; + const who = displayText(v.authors[a]); + return { fill, opacity: 0.92, ink: inkFor(fill, 0.92), val: who, tip: [tr("{0}提交最多:{1}", range, who)], aria: tr("本月提交最多 {0}", who) }; } const top = b.owners[0]; - if (!top) return none('无人修改', `${range}没有人修改`); + if (!top) return none(tr("无人修改"), tr("{0}没有人修改", range)); const share = top[1] / b.ownerSum; - const list = b.owners.slice(0, 3).map(([a, n]) => `${v.authors[a]} ${pct(n / b.ownerSum)}`).join('、'); - if (share < 0.25) return { ...none('多人共有', `${range}共 ${fmt(b.ownerSum)} 次提交,没有人超过 25%:${list}`), aria: '多人共有' }; + const list = b.owners.slice(0, 3).map(([a, n]) => `${displayText(v.authors[a])} ${pct(n / b.ownerSum)}`).join(tr("、")); + if (share < 0.25) return { ...none(tr("多人共有"), tr("{0}共 {1} 次提交,没有人超过 25%:{2}", range, fmt(b.ownerSum), list)), aria: tr("多人共有") }; const fill = v.palette.get(top[0]) || 'var(--k-other)'; const opacity = Math.min(1, 0.4 + share); - return { fill, opacity, ink: inkFor(fill, opacity), val: `${v.authors[top[0]]} ${pct(share)}`, tip: [`${range}的提交:${list}`], aria: `主要负责人 ${v.authors[top[0]]},占 ${pct(share)}` }; + return { fill, opacity, ink: inkFor(fill, opacity), val: `${displayText(v.authors[top[0]])} ${pct(share)}`, tip: [tr("{0}的提交:{1}", range, list)], aria: tr("主要负责人 {0},占 {1}", displayText(v.authors[top[0]]), pct(share)) }; } case 'age': { - if (!b.last) return none('无记录', '历史里没有这块的提交'); + if (!b.last) return none(tr("无记录"), tr("历史里没有这块的提交")); const days = Math.max(0, (v.latest - b.last) / DAY_S); const fill = `var(--age-${days <= 7 ? 0 : days <= 30 ? 1 : days <= 90 ? 2 : days <= 365 ? 3 : 4})`; - return { fill, ink: inkFor(fill), val: agoText(days), tip: [`最近一次修改:${ymdOfSec(b.last)}(相对仓库最新提交 ${agoText(days)})`], aria: `最近一次修改在 ${agoText(days)}` }; + return { fill, ink: inkFor(fill), val: agoText(days), tip: [tr("最近一次修改:{0}(相对仓库最新提交 {1})", ymdOfSec(b.last), agoText(days))], aria: tr("最近一次修改在 {0}", agoText(days)) }; } case 'loss': { - if (b.loss == null) return none('无记录', '没有可统计的提交'); + if (b.loss == null) return none(tr("无记录"), tr("没有可统计的提交")); const fill = `var(--loss-${b.loss < 0.2 ? 0 : b.loss < 0.4 ? 1 : b.loss < 0.6 ? 2 : b.loss < 0.8 ? 3 : 4})`; - const who = b.lossTop.map((a) => v.authors[a]).join('、'); - return { fill, ink: inkFor(fill), val: pct(b.loss), tip: [`${pct(b.loss)} 的历史提交来自近 3 个月没有提交的人${who ? `(主要是 ${who})` : ''}`], aria: `知识流失 ${pct(b.loss)}` }; + const who = b.lossTop.map((a) => displayText(v.authors[a])).join(tr("、")); + return { fill, ink: inkFor(fill), val: pct(b.loss), tip: [tr("{0} 的历史提交来自近 3 个月没有提交的人{1}", pct(b.loss), who ? tr("(主要是 {0})", who) : '')], aria: tr("知识流失 {0}", pct(b.loss)) }; } case 'type': { const t = b.types[0]; - if (!t) return none('—', '没有文件'); + if (!t) return none('—', tr("没有文件")); const [label, fill] = TYPE_META[t[0]] || TYPE_META.other; const total = b.types.reduce((s, x) => s + x[1], 0); - return { fill, ink: inkFor(fill), val: `${label} ${pct(t[1] / total)}`, tip: [`构成:${b.types.slice(0, 4).map(([k, n]) => `${(TYPE_META[k] || TYPE_META.other)[0]} ${pct(n / total)}`).join('、')}`], aria: `主要是 ${label}` }; + return { fill, ink: inkFor(fill), val: `${label} ${pct(t[1] / total)}`, tip: [tr("构成:{0}", b.types.slice(0, 4).map(([k, n]) => `${(TYPE_META[k] || TYPE_META.other)[0]} ${pct(n / total)}`).join(tr("、")))], aria: tr("主要是 {0}", label) }; } default: { const n = f == null ? b.churn : b.m[f]; const fill = `var(--heat-${levelOf(f == null ? v.qHeat : v.qHeatM, n)})`; - const avg = f == null && n && b.files > 1 ? `,平均每个文件 ${(n / b.files).toFixed(1)} 次` : ''; - return { fill, ink: inkFor(fill), val: n ? `${C.fmtK(n)} 次` : '无修改', tip: [`${range}修改 ${fmt(n)} 次${avg}`], aria: n ? `修改 ${n} 次` : '没有修改' }; + const avg = f == null && n && b.files > 1 ? tr(",平均每个文件 {0} 次", (n / b.files).toFixed(1)) : ''; + return { fill, ink: inkFor(fill), val: n ? tr("{0} 次", C.fmtK(n)) : tr("无修改"), tip: [tr("{0}修改 {1} 次{2}", range, fmt(n), avg)], aria: n ? tr("修改 {0} 次", n) : tr("没有修改") }; } } } @@ -1292,9 +1153,9 @@ function paintMap() { const cell = mp.cellOf?.get(i); if (mix) mix.innerHTML = o.lens === 'type' && cell && cell.w > 24 && cell.h > 18 ? typeStrip(b, cell) : ''; const p = partners.get(i); - const head = [blockTitle(v, b), b.kind === 'file' ? '' : `${fmt(b.files)} 个文件`, b.desc ? b.desc.text.slice(0, 60) + (b.desc.text.length > 60 ? '…' : '') : '', b.risk ? `含 ${b.risk} 个高风险文件` : ''].filter(Boolean); - g.dataset.tip = [...head, ...L.tip, p ? `改选中区域的提交里 ${pct(p.degree)} 也改了这里(${p.shared} 次)` : '', b.kind === 'file' ? '双击或回车:查看文件历史' : b.zoom ? '双击或回车:进入这块' : ''].filter(Boolean).join('\n'); - g.setAttribute('aria-label', `${blockTitle(v, b)},${b.kind === 'file' ? '' : `${b.files} 个文件,`}${L.aria}${b.risk ? `,含 ${b.risk} 个高风险文件` : ''}`); + const head = [blockTitle(v, b), b.kind === 'file' ? '' : tr("{0} 个文件", fmt(b.files)), b.desc ? b.desc.text.slice(0, 60) + (b.desc.text.length > 60 ? '…' : '') : '', b.risk ? tr("含 {0} 个高风险文件", b.risk) : ''].filter(Boolean); + g.dataset.tip = [...head, ...L.tip, p ? tr("改选中区域的提交里 {0} 也改了这里({1} 次)", pct(p.degree), p.shared) : '', b.kind === 'file' ? tr("双击或回车:查看文件历史") : b.zoom ? tr("双击或回车:进入这块") : ''].filter(Boolean).join('\n'); + g.setAttribute('aria-label', tr("{0},{1}{2}{3}", blockTitle(v, b), b.kind === 'file' ? '' : tr("{0} 个文件,", b.files), L.aria, b.risk ? tr(",含 {0} 个高风险文件", b.risk) : '')); } drawLines(svg, v, selIdx); // Tab lands on the selected tile unless the keyboard is already inside the map; with a selection @@ -1397,9 +1258,9 @@ function renderMapLegend() { let keys = ''; if (o.lens === 'heat') { const q = f == null ? v.qHeat : v.qHeatM; - keys = `${f == null ? '少' : '当月少'} ${[0, 1, 2, 3, 4].map((l) => ``).join('')} 多${q[2] ? `≤${q[0]} / ≤${q[1]} / ≤${q[2]} / >${q[2]} 次` : ''}`; - } else if (o.lens === 'bug') keys = C.riskLegend() + key(NEUTRAL, '修改太少'); - else if (o.lens === 'owner') keys = [...v.palette].map(([a, c]) => key(c, `${esc(v.authors[a])}`)).join('') + key('var(--k-other)', '其他人') + key(NEUTRAL, '多人共有 / 无人修改'); + keys = tr("{0} {1} 多{2}", f == null ? tr("少") : tr("当月少"), [0, 1, 2, 3, 4].map((l) => ``).join(''), q[2] ? tr("≤{0} / ≤{1} / ≤{2} / >{3} 次", q[0], q[1], q[2], q[2]) : ''); + } else if (o.lens === 'bug') keys = C.riskLegend() + key(NEUTRAL, tr("修改太少")); + else if (o.lens === 'owner') keys = [...v.palette].map(([a, c]) => key(c, `${esc(displayText(v.authors[a]))}`)).join('') + key('var(--k-other)', tr("其他人")) + key(NEUTRAL, tr("多人共有 / 无人修改")); else if (o.lens === 'age') keys = AGE_LABELS.map((l, i) => key(`var(--age-${i})`, l)).join(''); else if (o.lens === 'loss') keys = LOSS_LABELS.map((l, i) => key(`var(--loss-${i})`, l)).join(''); else { @@ -1407,7 +1268,7 @@ function renderMapLegend() { for (const b of v.blocks) for (const [k, n] of b.types) present.set(k, (present.get(k) || 0) + n); keys = [...present].sort((a, b) => b[1] - a[1]).slice(0, 9).map(([k]) => key((TYPE_META[k] || TYPE_META.other)[1], (TYPE_META[k] || TYPE_META.other)[0])).join(''); } - const extra = `${v.blocks.some((b) => b.risk) ? '含高风险文件' : ''}${v.blocks.some((b) => b.kind === 'other') ? '合并的小目录' : ''}`; + const extra = tr("{0}{1}", v.blocks.some((b) => b.risk) ? tr("含高风险文件") : '', v.blocks.some((b) => b.kind === 'other') ? tr("合并的小目录") : ''); el.innerHTML = `

        ${esc(LENSES.find(([k]) => k === o.lens)[2])}

        `; } function renderMapTime() { @@ -1420,13 +1281,8 @@ function renderMapTime() { const tot = v.focusInfo.m; const max = Math.max(1, ...tot); const part = tot.map((_, i) => Boolean(frameSpan(v, i))); - const hint = !PLAYABLE.has(o.lens) ? '逐月播放适用于热度、Bug 占比、负责人三种着色' : v.size === 'churn' ? '播放时会改为按文件数排布,让布局保持不动' : `${v.months.length} 个月,结构不动、颜色逐月变化`; - el.innerHTML = ` -
        -
        -
        - - ${hint}${part.some(Boolean) ? ' · 虚线框的柱子是不完整的月份' : ''}`; + const hint = !PLAYABLE.has(o.lens) ? tr("逐月播放适用于热度、Bug 占比、负责人三种着色") : v.size === 'churn' ? tr("播放时会改为按文件数排布,让布局保持不动") : tr("{0} 个月,结构不动、颜色逐月变化", v.months.length); + el.innerHTML = tr("\n
        {1}
        \n
        \n
        \n \n {4}{5}", can ? '' : 'disabled', tot.map((n, i) => ``).join(''), Math.max(0, v.months.length - 1), can ? '' : 'disabled', hint, part.some(Boolean) ? tr(" · 虚线框的柱子是不完整的月份") : ''); syncMapTime(); } // The first frame usually starts mid-month (the range is counted back from today, or the history @@ -1437,13 +1293,13 @@ function frameSpan(v, f) { const start = v.start ?? v.since; if (f === 0 && start != null) { const s = ymdOfSec(start); - if (s.slice(0, 7) === v.months[0] && !s.endsWith('-01')) parts.push(`${s.slice(5)} 起`); + if (s.slice(0, 7) === v.months[0] && !s.endsWith('-01')) parts.push(tr("{0} 起", s.slice(5))); } if (f === v.months.length - 1 && v.latest) { const d = new Date(v.latest * 1000); - if (d.getDate() < new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()) parts.push(`截至 ${ymdOfSec(v.latest).slice(5)}`); + if (d.getDate() < new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()) parts.push(tr("截至 {0}", ymdOfSec(v.latest).slice(5))); } - return parts.join(','); + return parts.join(tr(",")); } function syncMapTime() { const v = mp.view; @@ -1452,14 +1308,14 @@ function syncMapTime() { const o = mapOpts(); const f = PLAYABLE.has(o.lens) ? mp.frame : null; const M = v.months.length; - btn.innerHTML = `${mp.playing ? ICON.pause : ICON.play}${mp.playing ? '暂停' : f != null && f < M - 1 ? '继续播放' : '逐月播放'}`; + btn.innerHTML = tr("{0}{1}", mp.playing ? ICON.pause : ICON.play, mp.playing ? tr("暂停") : f != null && f < M - 1 ? tr("继续播放") : tr("逐月播放")); btn.setAttribute('aria-pressed', String(mp.playing)); const input = $('#map-month'); const span = f == null ? '' : frameSpan(v, f); input.value = String(f ?? M - 1); - input.setAttribute('aria-valuetext', f == null ? `${rangeText(v)}汇总` : `${v.months[f]}${span ? `(${span})` : ''}`); + input.setAttribute('aria-valuetext', f == null ? tr("{0}汇总", rangeText(v)) : tr("{0}{1}", v.months[f], span ? tr("({0})", span) : '')); $('#mt-month').textContent = f == null ? `${v.months[0]} → ${v.months[M - 1]}` : v.months[f]; - $('#mt-sub').textContent = f == null ? `${rangeText(v)}汇总 · ${fmt(v.totals.churn)} 次修改` : `${span ? `${span} · ` : '当月 '}${fmt(v.focusInfo.m[f])} 次修改`; + $('#mt-sub').textContent = f == null ? tr("{0}汇总 · {1} 次修改", rangeText(v), fmt(v.totals.churn)) : tr("{0}{1} 次修改", span ? `${span} · ` : tr("当月 "), fmt(v.focusInfo.m[f])); $('#mt-clear').hidden = f == null; $('#map-time').classList.toggle('framed', f != null); [...$('#map-time .mt-bars').children].forEach((bar, i) => bar.classList.toggle('on', i === f)); @@ -1468,10 +1324,10 @@ function renderMapNote() { const el = $('#map-note'); const v = mp.view; if (!el || !v) return; - const parts = [`${v.size === 'churn' ? `面积:${rangeText(v)}的修改次数` : '面积:HEAD 中的文件数'} · ${v.blocks.length} 个区域`]; - if (v.totals.delChurn) parts.push(`另有 ${fmt(v.totals.delChurn)} 次修改落在已删除、且所在目录也不在了的路径上,没有画进图里`); - if (v.process.length) parts.push(`流程文件 ${v.process.map(esc).join('、')} 几乎随每次修改一起改,不参与连线`); - parts.push('单击选中 · 双击或回车进入 · Backspace 返回上一层 · 方向键移动'); + const parts = [tr("{0} · {1} 个区域", v.size === 'churn' ? tr("面积:{0}的修改次数", rangeText(v)) : tr("面积:HEAD 中的文件数"), v.blocks.length)]; + if (v.totals.delChurn) parts.push(tr("另有 {0} 次修改落在已删除、且所在目录也不在了的路径上,没有画进图里", fmt(v.totals.delChurn))); + if (v.process.length) parts.push(tr("流程文件 {0} 几乎随每次修改一起改,不参与连线", v.process.map(esc).join(tr("、")))); + parts.push(tr("单击选中 · 双击或回车进入 · Backspace 返回上一层 · 方向键移动")); el.innerHTML = parts.join(' · '); } @@ -1563,24 +1419,24 @@ function inferDesc(b) { const total = b.types.reduce((s, x) => s + x[1], 0); if (!total) return ''; const [k1, n1] = b.types[0]; - const second = b.types[1] && b.types[1][1] / total >= 0.15 ? `,其次是${(TYPE_META[b.types[1][0]] || TYPE_META.other)[0]}(${pct(b.types[1][1] / total)})` : ''; - return `主要是${(TYPE_META[k1] || TYPE_META.other)[0]}(${pct(n1 / total)})${second}。仓库里没有找到这块的说明`; + const second = b.types[1] && b.types[1][1] / total >= 0.15 ? tr(",其次是{0}({1})", (TYPE_META[b.types[1][0]] || TYPE_META.other)[0], pct(b.types[1][1] / total)) : ''; + return tr("主要是{0}({1}){2}。仓库里没有找到这块的说明", (TYPE_META[k1] || TYPE_META.other)[0], pct(n1 / total), second); } function summaryOf(v, b, isFocus) { const range = rangeText(v); const parts = []; if (b.churn) { const share = !isFocus && v.totals.churn ? b.churn / v.totals.churn : null; - parts.push(`${range}修改 ${fmt(b.churn)} 次${share != null ? `,占${v.focus ? '这一层' : '全仓'}的 ${pct(share)}` : ''}`); - if (b.churn >= 5) parts.push(`其中 ${pct(b.bug / b.churn)} 是修 bug`); - } else parts.push(`${range}没有修改`); - if (b.owners.length) parts.push(`主要由 ${b.owners.slice(0, 2).map(([a, n]) => `${v.authors[a]}(${pct(n / b.ownerSum)})`).join('、')} 维护`); + parts.push(tr("{0}修改 {1} 次{2}", range, fmt(b.churn), share != null ? tr(",占{0}的 {1}", v.focus ? tr("这一层") : tr("全仓"), pct(share)) : '')); + if (b.churn >= 5) parts.push(tr("其中 {0} 是修 bug", pct(b.bug / b.churn))); + } else parts.push(tr("{0}没有修改", range)); + if (b.owners.length) parts.push(tr("主要由 {0} 维护", b.owners.slice(0, 2).map(([a, n]) => tr("{0}({1})", displayText(v.authors[a]), pct(n / b.ownerSum))).join(tr("、")))); if (b.last) { const days = (v.latest - b.last) / DAY_S; - parts.push(days <= 30 ? `${agoText(days)}还有人改` : `最近一次修改在 ${ymdOfSec(b.last)}`); + parts.push(days <= 30 ? tr("{0}还有人改", agoText(days)) : trAlt("最近一次修改在 {0}", ymdOfSec(b.last))); } - if (b.loss != null && b.loss >= 0.4) parts.push(`${pct(b.loss)} 的历史提交来自近 3 个月不再提交的人`); - return `${parts.join(';')}。`; + if (b.loss != null && b.loss >= 0.4) parts.push(tr("{0} 的历史提交来自近 3 个月不再提交的人", pct(b.loss))); + return tr("{0}。", parts.join(tr(";"))); } /** Split two titles at their shared directory prefix: ('a/b/test/', 'a/b/src/') → ['a/b/', 'test/', 'src/']. */ function splitCommon(a, b) { @@ -1599,14 +1455,14 @@ function coItem(v, c, base) { const link = t ? `` : `${esc(short)}`; - return `
      • ${Math.round(c.degree * 100)}%${link}${pre ? `` : ''}${fmt(c.shared)} 次${t ? '' : ' · 视图外'}${c.kind === 'test' ? ' · 测试同步' : ''}
      • `; + return tr("
      • {0}%{1}{2}{3} 次{4}{5}
      • ", Math.round(c.degree * 100), link, pre ? `` : '', fmt(c.shared), t ? '' : tr(" · 视图外"), c.kind === 'test' ? tr(" · 测试同步") : '', (c.degree * 100).toFixed(0)); } function pairItem(v, p) { const a = blockTitle(v, v.blocks[p.from]); const b = blockTitle(v, v.blocks[p.to]); const [pre, sa, sb] = splitCommon(a, b); const btn = (i, full, short) => ``; - return `
      • ${Math.round(p.degree * 100)}%${btn(p.from, a, sa)}→${btn(p.to, b, sb)}${pre ? `` : ''}${fmt(p.shared)} 次${p.kind === 'test' ? ' · 测试同步' : ''}
      • `; + return tr("
      • {0}%{1}→{2}{3}{4} 次{5}
      • ", Math.round(p.degree * 100), btn(p.from, a, sa), btn(p.to, b, sb), pre ? `` : '', fmt(p.shared), p.kind === 'test' ? tr(" · 测试同步") : '', (p.degree * 100).toFixed(0)); } function syncDetailFrame() { const el = $('#md-frame'); @@ -1618,8 +1474,8 @@ function syncDetailFrame() { const b = i >= 0 ? v.blocks[i] : v.focusInfo; el.hidden = f == null; if (f == null) return; - const owner = b.mo[f] >= 0 ? `,提交最多的是 ${v.authors[b.mo[f]]}` : ''; - el.textContent = `${v.months[f]}:修改 ${fmt(b.m[f])} 次,修 bug ${fmt(b.mb[f])} 次${owner}`; + const owner = b.mo[f] >= 0 ? tr(",提交最多的是 {0}", displayText(v.authors[b.mo[f]])) : ''; + el.textContent = tr("{0}:修改 {1} 次,修 bug {2} 次{3}", v.months[f], fmt(b.m[f]), fmt(b.mb[f]), owner); } function renderMapDetail() { const el = $('#map-detail'); @@ -1637,7 +1493,7 @@ function renderMapDetail() { const range = rangeText(v); const path = isFocus ? v.focus : b.path; const title = isFocus ? (v.focus ? `${v.focus}/` : r.name) : blockTitle(v, b); - const kicker = isFocus ? (v.focus ? '当前目录' : '整个仓库') : { dir: '目录', file: '文件', other: '合并的小项' }[b.kind]; + const kicker = isFocus ? (v.focus ? tr("当前目录") : tr("整个仓库")) : { dir: tr("目录"), file: trAlt("文件"), other: tr("合并的小项") }[b.kind]; const icon = b.kind === 'file' ? ICON.file : ICON.map; const desc = b.desc ? `${esc(b.desc.text)} — ${esc(b.desc.source)}` : b.kind === 'file' ? '' : inferDesc(b); const stat = (k, val, sub = '') => `
        ${val}
        ${k}${sub}
        `; @@ -1645,40 +1501,31 @@ function renderMapDetail() { // Within the map one person is one colour: avatar and bar use the owner lens palette. const owners = b.owners.length ? `
          ${b.owners.map(([a, n]) => `
        • ${avatar(v.authors[a], '', v.palette.get(a) || 'var(--k-other)')}${personLink(v.authors[a])}${fmt(n)} · ${pct(n / b.ownerSum)}
        • `).join('')}
        ` - : `

        ${range}没有人修改。

        `; - const lossNote = b.loss != null && b.loss >= 0.3 && b.lossTop.length ? `

        知识流失 ${pct(b.loss)}:${b.lossTop.map((a) => `${esc(v.authors[a])}`).join('、')} 写过这里的大量提交,但近 3 个月没有任何提交。

        ` : ''; + : tr("

        {0}没有人修改。

        ", range); + const lossNote = b.loss != null && b.loss >= 0.3 && b.lossTop.length ? tr("

        知识流失 {0}:{1} 写过这里的大量提交,但近 3 个月没有任何提交。

        ", pct(b.loss), b.lossTop.map((a) => `${esc(displayText(v.authors[a]))}`).join(tr("、"))) : ''; const tops = b.top.length - ? `
          ${b.top.map(([p, n, k, ex], j) => `
        1. ${j + 1}${pathHtml(p)}${ex ? '' : '已删除'}${fmt(n)}${k ? ` · ${pct(k / n)}` : ''}
        2. `).join('')}
        ` - : `

        ${range}没有修改。

        `; + ? tr("
          {0}
        ", b.top.map(([p, n, k, ex], j) => tr("
      • {0}{1}{2}{4}{5}
      • ", j + 1, pathHtml(p), ex ? '' : tr("已删除"), k, fmt(n), k ? ` · ${pct(k / n)}` : '')).join('')) + : tr("

        {0}没有修改。

        ", range); let co; if (isFocus && !b.couple.length && v.pairs.length) { - co = `

        这一层里最强的关系(改左边的提交里,有多少也改了右边):

          ${v.pairs + co = tr("

          这一层里最强的关系(改左边的提交里,有多少也改了右边):

            {0}
          ", v.pairs .slice(0, 6) .map((p) => pairItem(v, p)) - .join('')}
        `; - } else if (b.couple.length) co = `

        改${isFocus ? '这一层' : '它'}的 ${fmt(b.revs)} 个提交里(不含超过 ${v.couple.maxChangeset} 个文件的大提交):

          ${b.couple.map((c) => coItem(v, c, title)).join('')}
        `; - else co = `

        ${b.revs < v.couple.minRevs ? `${range}只有 ${fmt(b.revs)} 个相关提交,还看不出稳定的关系。` : `没有达到门槛的关系(至少一起改过 ${v.couple.minShared} 次、占比 ≥${pct(v.couple.minDegree)})。`}

        `; - const proc = b.processWith.length ? `

        另外 ${b.processWith.map((p) => `${esc(p.path)}`).join('、')} 几乎随每次修改一起改(流程文件),没有列出。

        ` : ''; - const items = b.kind === 'other' && b.items?.length ? `

        包含的 ${b.items.length} 项

        ` : ''; + .join('')); + } else if (b.couple.length) co = tr("

        改{0}的 {1} 个提交里(不含超过 {2} 个文件的大提交):

          {3}
        ", isFocus ? tr("这一层") : tr("它"), fmt(b.revs), v.couple.maxChangeset, b.couple.map((c) => coItem(v, c, title)).join('')); + else co = tr("

        {0}

        ", b.revs < v.couple.minRevs ? tr("{0}只有 {1} 个相关提交,还看不出稳定的关系。", range, fmt(b.revs)) : tr("没有达到门槛的关系(至少一起改过 {0} 次、占比 ≥{1})。", v.couple.minShared, pct(v.couple.minDegree))); + const proc = b.processWith.length ? tr("

        另外 {0} 几乎随每次修改一起改(流程文件),没有列出。

        ", b.processWith.map((p) => `${esc(p.path)}`).join(tr("、"))) : ''; + const items = b.kind === 'other' && b.items?.length ? tr("

        包含的 {0} 项

          {1}
        ", b.items.length, b.items.map(([p, k, n]) => tr("
      • {0}{1}
      • ", k === 'dir' ? `${esc(p.split('/').pop())}/` : `${esc(p.split('/').pop())}`, k === 'dir' ? tr("{0} 个文件", fmt(n)) : trAlt("文件"))).join('')) : ''; const acts = []; - if (!isFocus && b.zoom) acts.push(`${ICON.arrow}进入这块`); - if (!isFocus && b.kind === 'file') acts.push(`${ICON.file}查看文件历史`); - if (isFocus && v.focus) acts.push(`${ICON.up}返回上一层`); - if (b.kind !== 'other') acts.push(``); - if (path) acts.push(``); + if (!isFocus && b.zoom) acts.push(tr("{1}进入这块", esc(href({ focus: b.zoom, sel: null })), ICON.arrow)); + if (!isFocus && b.kind === 'file') acts.push(tr("{1}查看文件历史", esc(href({ file: b.path, person: null })), ICON.file)); + if (isFocus && v.focus) acts.push(tr("{1}返回上一层", esc(href({ focus: parentOf(v.focus) || null, sel: v.focus })), ICON.up)); + if (b.kind !== 'other') acts.push(tr("", ICON.chat, isFocus && !v.focus ? tr("这个仓库") : tr("这块"))); + if (path) acts.push(tr("", esc(path), ICON.copy)); const web = path ? (b.kind === 'file' ? webLink('file', path) : webTree(path)) : null; - if (web) acts.push(`${ICON.ext}网页`); + if (web) acts.push(tr("{1}网页", esc(web), ICON.ext)); if (b.kind === 'file' && editorLink(path)) acts.push(`${ICON.code}VS Code`); - el.innerHTML = `
        ${kicker}${b.test ? ' · 测试' : ''}${b.process ? ' · 流程文件' : ''}

        ${esc(title)}

        ${isFocus ? '' : ``}
        - ${desc ? `

        ${desc}

        ` : ''} -

        ${esc(summaryOf(v, b, isFocus))}

        - -
        ${stat('文件', fmt(b.files))}${stat('修改', fmt(b.churn), `
        ${range.replace(/上$/, '')}`)}${stat('修 bug', b.churn >= 5 ? pct(b.bug / b.churn) : '–')}${stat('最近修改', days == null ? '–' : agoText(days))}
        - ${items} -

        负责人 ${range},按提交数

        ${owners}${lossNote}
        -

        最常改的文件 ${range}

        ${tops}
        -

        常和${isFocus ? '这一层' : '它'}一起改 ${explainFor('couple', state.report)}

        ${co}${proc}
        -
        ${acts.join('')}
        `; + el.innerHTML = tr("
        {0}
        {1}{2}{3}

        {4}

        {5}
        \n {6}\n

        {7}

        \n \n
        {8}{9}{10}{11}
        \n {12}\n

        负责人 {13},按提交数

        {14}{15}
        \n

        最常改的文件 {16}

        {17}
        \n

        常和{18}一起改 {19}

        {20}{21}
        \n
        {22}
        ", icon, kicker, b.test ? tr(" · 测试") : '', b.process ? tr(" · 流程文件") : '', esc(title), isFocus ? '' : tr("", v.focus ? tr("当前目录") : tr("整个仓库"), ICON.close), desc ? `

        ${desc}

        ` : '', esc(summaryOf(v, b, isFocus)), stat(tr("文件"), fmt(b.files)), stat(tr("修改"), fmt(b.churn), `
        ${range.replace(/上$/, '')}`), stat(tr("修 bug"), b.churn >= 5 ? pct(b.bug / b.churn) : '–'), stat(tr("最近修改"), days == null ? '–' : agoText(days)), items, range, owners, lossNote, range, tops, isFocus ? tr("这一层") : tr("它"), explainFor('couple', state.report), co, proc, acts.join('')); syncDetailFrame(); } @@ -1687,23 +1534,23 @@ function renderMapTable() { const el = $('#map-table'); const v = mp.view; if (!el) return; - if (!v || !v.blocks.length) return void (el.innerHTML = v ? '

        没有区域。

        ' : ''); + if (!v || !v.blocks.length) return void (el.innerHTML = v ? tr("

        没有区域。

        ") : ''); const cols = [ - ['name', '区域'], - ['size', v.size === 'churn' ? '修改' : '文件'], - ['churn', v.size === 'churn' ? '文件' : '修改'], - ['bug', '修 bug'], - ['owner', '负责人'], - ['last', '最近修改'], - ['loss', '知识流失'], - ['type', '主要类型'], + ['name', tr("区域")], + ['size', v.size === 'churn' ? tr("修改") : tr("文件")], + ['churn', v.size === 'churn' ? tr("文件") : tr("修改")], + ['bug', tr("修 bug")], + ['owner', tr("负责人")], + ['last', tr("最近修改")], + ['loss', tr("知识流失")], + ['type', tr("主要类型")], ]; const val = { name: (b) => blockTitle(v, b), size: (b) => (v.size === 'churn' ? b.churn : b.files), churn: (b) => (v.size === 'churn' ? b.files : b.churn), bug: (b) => (b.churn >= 5 ? b.bug / b.churn : -1), - owner: (b) => (b.owners[0] ? v.authors[b.owners[0][0]] : ''), + owner: (b) => (b.owners[0] ? displayText(v.authors[b.owners[0][0]]) : ''), last: (b) => b.last || 0, loss: (b) => b.loss ?? -1, type: (b) => (b.types[0] ? (TYPE_META[b.types[0][0]] || TYPE_META.other)[0] : ''), @@ -1715,15 +1562,12 @@ function renderMapTable() { return (typeof x === 'string' ? x.localeCompare(y) : x - y) * dir; }); const sel = selIndex(v, mapOpts().sel); - el.innerHTML = `${cols.map(([k, l]) => ``).join('')}${rows + el.innerHTML = tr("
        代码地图的区域列表
        {0}{1}
        代码地图的区域列表
        ", cols.map(([k, l]) => ``).join(''), rows .map(([b, i]) => { const own = b.owners[0]; - return `${b.risk ? ` 高风险 ${b.risk}` : ''}${b.desc ? `
        ${esc(b.desc.text)}
        ` : ''} - ${fmt(val.size(b))}${fmt(val.churn(b))}${b.churn >= 5 ? pct(b.bug / b.churn) : '–'} - ${own ? `${esc(v.authors[own[0]])} ${pct(own[1] / b.ownerSum)}` : '–'} - ${b.last ? agoText((v.latest - b.last) / DAY_S) : '–'}${b.loss == null ? '–' : pct(b.loss)}${val.type(b) || '–'}`; + return tr("{4}{5}\n {6}{7}{8}\n {9}\n {10}{11}{12}", i, i === sel ? ' class="is-sel" aria-current="true"' : '', i, esc(blockTitle(v, b)), b.risk ? tr(" 高风险 {0}", b.risk) : '', b.desc ? `
        ${esc(b.desc.text)}
        ` : '', fmt(val.size(b)), fmt(val.churn(b)), b.churn >= 5 ? pct(b.bug / b.churn) : '–', own ? `${esc(displayText(v.authors[own[0]]))} ${pct(own[1] / b.ownerSum)}` : '–', b.last ? agoText((v.latest - b.last) / DAY_S) : '–', b.loss == null ? '–' : pct(b.loss), val.type(b) || '–'); }) - .join('')}`; + .join('')); } function markTableSel() { const sel = selIndex(mp.view, mapOpts().sel); @@ -1744,27 +1588,27 @@ function mapAgentPrompt() { const isFocus = i < 0; const b = isFocus ? v.focusInfo : v.blocks[i]; const path = isFocus ? v.focus : b.path; - const title = isFocus ? (v.focus ? `${v.focus}/` : '整个仓库') : blockTitle(v, b); + const title = isFocus ? (v.focus ? `${v.focus}/` : tr("整个仓库")) : blockTitle(v, b); const web = path ? (b.kind === 'file' ? webLink('file', path) : webTree(path)) : r.webUrl; - const where = r.kind === 'local' ? `本地路径:${r.localDir}${path ? `/${path}` : ''}` : `网页:${web || r.webUrl}(若本地没有 checkout,请先 clone ${r.webUrl})`; + const where = r.kind === 'local' ? tr("本地路径:{0}{1}", r.localDir, path ? `/${path}` : '') : tr("网页:{0}(若本地没有 checkout,请先 clone {1})", web || r.webUrl, r.webUrl); const range = rangeText(v); - const owners = b.owners.slice(0, 3).map(([a, n]) => `${v.authors[a]}(${pct(n / b.ownerSum)})`).join('、') || '无'; - const top = b.top.slice(0, 5).map(([p, n]) => `${p}(${n} 次)`).join('、') || '无'; - const co = b.couple.slice(0, 5).map((c) => `${c.path}(改这里的提交里 ${pct(c.degree)} 也改了它)`).join('、') || '无'; + const owners = b.owners.slice(0, 3).map(([a, n]) => tr("{0}({1})", displayText(v.authors[a]), pct(n / b.ownerSum))).join(tr("、")) || tr("无"); + const top = b.top.slice(0, 5).map(([p, n]) => tr("{0}({1} 次)", p, n)).join(tr("、")) || tr("无"); + const co = b.couple.slice(0, 5).map((c) => tr("{0}(改这里的提交里 {1} 也改了它)", c.path, pct(c.degree))).join(tr("、")) || tr("无"); return [ - `请帮我讲解仓库 ${r.display} 里的 \`${title}\`${b.kind === 'file' ? '' : `(${fmt(b.files)} 个文件)`}是做什么的。`, + tr("请帮我讲解仓库 {0} 里的 `{1}`{2}是做什么的。", r.display, title, b.kind === 'file' ? '' : tr("({0} 个文件)", fmt(b.files))), where, '', - `仓库透视的数据(${range},HEAD ${rep.head.slice(0, 12)}):`, - `- 修改 ${fmt(b.churn)} 次,其中修 bug ${b.churn ? pct(b.bug / b.churn) : '0%'};最近一次修改 ${b.last ? ymdOfSec(b.last) : '–'}`, - `- 主要负责人:${owners}`, - `- 最常改的文件:${top}`, - `- 常一起改:${co}`, - ...(b.desc ? [`- 仓库自带的说明(${b.desc.source}):${b.desc.text}`] : []), + tr("仓库透视的数据({0},HEAD {1}):", range, rep.head.slice(0, 12)), + tr("- 修改 {0} 次,其中修 bug {1};最近一次修改 {2}", fmt(b.churn), b.churn ? pct(b.bug / b.churn) : '0%', b.last ? ymdOfSec(b.last) : '–'), + tr("- 主要负责人:{0}", owners), + tr("- 最常改的文件:{0}", top), + tr("- 常一起改:{0}", co), + ...(b.desc ? [tr("- 仓库自带的说明({0}):{1}", b.desc.source, b.desc.text)] : []), '', b.kind === 'file' - ? '请阅读这个文件,说明它负责什么、对外提供什么、被谁调用,以及为什么常和上面那些文件一起改。只读分析,不要修改代码。' - : '请先读这个目录的 README(如果有)和入口文件,说明:它负责什么、由哪几个主要部分组成、对外提供什么接口,以及和上面那些“常一起改”的区域是什么关系。只读分析,不要修改代码。', + ? tr("请阅读这个文件,说明它负责什么、对外提供什么、被谁调用,以及为什么常和上面那些文件一起改。只读分析,不要修改代码。") + : tr("请先读这个目录的 README(如果有)和入口文件,说明:它负责什么、由哪几个主要部分组成、对外提供什么接口,以及和上面那些“常一起改”的区域是什么关系。只读分析,不要修改代码。"), ].join('\n'); } @@ -1784,16 +1628,16 @@ function mountThumb(rep) { if (!w || Math.abs(w - lastW) < 24) return; lastW = w; const layout = C.mapLayout(cm.blocks, { width: w, height: Math.round(Math.max(240, Math.min(380, w * 0.36))), value: (b) => b.files }); - box.innerHTML = C.mapSvg(layout, { blocks: cm.blocks, groupLabel: (k) => groupLabel('', k), groupValue: (n) => `${C.fmtK(n)} 个文件`, nameOf: (b) => blockLabels('', b), action: 'thumb-open', label: '代码地图缩略图:点任意一块,在代码地图里打开' }); + box.innerHTML = C.mapSvg(layout, { blocks: cm.blocks, groupLabel: (k) => groupLabel('', k), groupValue: (n) => tr("{0} 个文件", C.fmtK(n)), nameOf: (b) => blockLabels('', b), action: 'thumb-open', label: tr("代码地图缩略图:点任意一块,在代码地图里打开") }); for (const g of box.querySelectorAll('.tm-cell')) { const b = cm.blocks[g.dataset.i]; const fill = `var(--heat-${levelOf(q, b.churn)})`; g.querySelector('.tm-r').style.fill = fill; g.classList.toggle('ink-light', inkFor(fill) === 'light'); const val = g.querySelector('.tm-val'); - if (val) val.textContent = C.fitLabel([`${C.fmtK(b.files)} 个文件`], Number(val.dataset.w) || 0, 10); - g.dataset.tip = `${blockTitle({}, b)}\n${fmt(b.files)} 个文件 · 窗口内修改 ${fmt(b.churn)} 次${b.risk ? `\n含 ${b.risk} 个高风险文件` : ''}\n点击:在代码地图中打开`; - g.setAttribute('aria-label', `${blockTitle({}, b)},${b.files} 个文件,窗口内修改 ${b.churn} 次,打开代码地图`); + if (val) val.textContent = C.fitLabel([tr("{0} 个文件", C.fmtK(b.files))], Number(val.dataset.w) || 0, 10); + g.dataset.tip = tr("{0}\n{1} 个文件 · 窗口内修改 {2} 次{3}\n点击:在代码地图中打开", blockTitle({}, b), fmt(b.files), fmt(b.churn), b.risk ? tr("\n含 {0} 个高风险文件", b.risk) : ''); + g.setAttribute('aria-label', tr("{0},{1} 个文件,窗口内修改 {2} 次,打开代码地图", blockTitle({}, b), b.files, b.churn)); } }; draw(); @@ -1829,19 +1673,19 @@ function renderProgress() { stopProgress(); const showErr = j && j.stage === 'error' && Date.now() - (j.finishedAt || 0) < 60_000 && state.report; el.className = ''; - el.innerHTML = showErr ? `` : ''; + el.innerHTML = showErr ? tr("
        {0},下面显示的是上一次的结果。
        ", esc(pick(j.error?.message) || tr("分析失败"))) : ''; return; } const key = `${r.id}:${j.startedAt}`; if (pg.key !== key || !el.querySelector('#pg-body')) { pg.key = key; el.className = 'progress-log term'; - el.innerHTML = `
        xray ${esc(r.kind === 'local' ? r.display : r.name)}
        `; + el.innerHTML = tr("
        xray {0}
        ", esc(r.kind === 'local' ? r.display : r.name)); } if (pg.stage !== j.stage) { pg.stage = j.stage; const sr = $('#pg-sr'); - if (sr) sr.textContent = j.stage === 'queued' ? '排队等待分析' : `正在${STAGE[j.stage] || '分析'}`; + if (sr) sr.textContent = j.stage === 'queued' ? tr("排队等待分析") : tr("正在{0}", STAGE[j.stage] || tr("分析")); } drawProgress(); if (!pg.timer) pg.timer = setInterval(drawProgress, reducedMotion() ? 1000 : 90); @@ -1856,7 +1700,7 @@ function drawProgress() { const done = new Map((j.steps || []).map((x) => [x.stage, x.ms])); const spin = reducedMotion() ? '›' : SPIN[pg.f % SPIN.length]; body.innerHTML = - (j.stage === 'queued' ? `
        ${spin}等待空闲的网络通道…${secs(Date.now() - j.startedAt)}
        ` : '') + + (j.stage === 'queued' ? tr("
        {0}等待空闲的网络通道…{1}
        ", spin, secs(Date.now() - j.startedAt)) : '') + order .map((st) => { const ms = done.get(st); @@ -1864,9 +1708,10 @@ function drawProgress() { const icon = ms != null ? '✓' : isCur ? `${spin}` : '·'; const time = ms != null ? secs(ms) : isCur ? secs(Date.now() - (j.stageStartedAt || Date.now())) : ''; let detail = ''; - if (isCur && st === 'sync' && j.detail) detail = ` ${esc(j.detail)}${j.pct || 0}%`; - else if (isCur && j.detail) detail = ` · ${esc(j.detail)}`; - if (st === 'tech' && isCur && j.reportHead) detail += ' · 报告已可查看'; + const jd = pick(j.detail); + if (isCur && st === 'sync' && jd) detail = ` ${esc(jd)}${j.pct || 0}%`; + else if (isCur && jd) detail = ` · ${esc(jd)}`; + if (st === 'tech' && isCur && j.reportHead) detail += tr(" · 报告已可查看"); return `
        ${icon}${STAGE[st]}${detail}${isCur ? '' : ''}${time}
        `; }) .join(''); @@ -1920,7 +1765,7 @@ async function loadReport({ quiet = false } = {}) { } async function analyze(input) { const v = input.trim(); - if (!v) return toast('请输入仓库地址或本地路径'); + if (!v) return toast(tr("请输入仓库地址或本地路径")); const btn = $('#analyze-form [type=submit]'); if (btn) { btn.disabled = true; @@ -1945,7 +1790,7 @@ async function analyze(input) { } } function connect() { - const es = new EventSource('/api/stream'); + const es = new EventSource('/api/stream?lang=' + getLang()); es.addEventListener('open', () => setLive(true)); es.addEventListener('error', () => setLive(es.readyState === EventSource.OPEN)); es.addEventListener('job', async (ev) => { @@ -1965,8 +1810,8 @@ function connect() { if (isCur) { await loadReport({ quiet: true }); updateTitle(); - const took = j.finishedAt && j.startedAt ? ` · 用时 ${secs(j.finishedAt - j.startedAt)}` : ''; - toast(j.stage === 'done' ? `分析完成${took}` : j.stage === 'cancelled' ? '已取消' : j.error?.message || '分析失败', null, { ok: j.stage === 'done' }); + const took = j.finishedAt && j.startedAt ? tr(" · 用时 {0}", secs(j.finishedAt - j.startedAt)) : ''; + toast(j.stage === 'done' ? tr("分析完成{0}", took) : j.stage === 'cancelled' ? tr("已取消") : pick(j.error?.message) || tr("分析失败"), null, { ok: j.stage === 'done' }); } return; } @@ -2006,7 +1851,7 @@ function closeDrawer() { else go({ file: null, person: null }, { replace: true }); } function drawerShell(title, sub) { - return `
        ${title}${sub ? `
        ${sub}
        ` : ''}
        `; + return tr("
        {0}{1}
        ", title, sub ? `
        ${sub}
        ` : '', ICON.close); } function fileBadges(path) { const rep = state.report; @@ -2015,29 +1860,29 @@ function fileBadges(path) { const bug = rep.bugMagnets.find((h) => h.path === path); const risk = rep.highRisk.some((h) => h.path === path); const b = []; - if (risk) b.push('高风险'); - if (hot) b.push(`热点 #${hot.rank} / ${rep.vitals.N}`); - if (bug) b.push(`Bug 磁铁 #${bug.rank}`); - if (!b.length) b.push('不在窗口内的 Top 榜单'); + if (risk) b.push(tr("高风险")); + if (hot) b.push(tr("热点 #{0} / {1}", hot.rank, rep.vitals.N)); + if (bug) b.push(tr("Bug 磁铁 #{0}", bug.rank)); + if (!b.length) b.push(tr("不在窗口内的 Top 榜单")); return `
        ${b.join('')}
        `; } function personBadges(name) { const rep = state.report; const c = rep?.contributors.find((x) => x.name === name); if (!c) return ''; - return `
        排名 #${c.rank} / ${fmt(rep.busFactor.total)}占 ${pct(c.share, 1)}${c.active ? '近 3 个月活跃' : '近 3 个月无提交'}
        `; + return tr("
        排名 #{0} / {1}占 {2}{3}
        ", c.rank, fmt(rep.busFactor.total), pct(c.share, 1), c.active ? tr("近 3 个月活跃") : tr("近 3 个月无提交")); } /** File-level co-change, all history (code-maat thresholds; weak candidates only when nothing passes). */ function couplingHtml(c) { if (!c) return ''; const strong = c.strong.length > 0; const list = strong ? c.strong : c.weak; - const head = `

        常一起改的文件 全部历史上改它的 ${fmt(c.revs)} 个提交里,同时也改了这些文件的比例(不含合并提交和超过 ${c.maxChangeset} 个文件的大提交)

        `; - if (!list.length) return `
        ${head}

        ${c.revs < c.minRevs ? `只有 ${fmt(c.revs)} 个相关提交,还看不出稳定的关系。` : '没有经常和它一起改的文件。'}

        `; - const note = strong ? '' : `

        没有达到门槛(一起改过至少 ${c.minShared} 次、占比 ≥${pct(c.minDegree)})的文件。下面是一起改过 3 次以上的,仅供参考:

        `; - return `
        ${head}${note}
          ${list - .map((x) => `
        • ${Math.round(x.degree * 100)}%${pathHtml(x.path)}${fmt(x.shared)} 次${x.kind === 'test' ? ' · 测试同步' : x.kind === 'process' ? ' · 流程文件' : ''}${x.exists ? '' : ' · 已删除'}
        • `) - .join('')}
        `; + const head = tr("

        常一起改的文件 全部历史上改它的 {0} 个提交里,同时也改了这些文件的比例(不含合并提交和超过 {1} 个文件的大提交)

        ", fmt(c.revs), c.maxChangeset); + if (!list.length) return tr("
        {0}

        {1}

        ", head, c.revs < c.minRevs ? tr("只有 {0} 个相关提交,还看不出稳定的关系。", fmt(c.revs)) : tr("没有经常和它一起改的文件。")); + const note = strong ? '' : tr("

        没有达到门槛(一起改过至少 {0} 次、占比 ≥{1})的文件。下面是一起改过 3 次以上的,仅供参考:

        ", c.minShared, pct(c.minDegree)); + return tr("
        {0}{1}
          {3}
        ", head, note, strong ? '' : ' weak', list + .map((x) => tr("
      • {0}%{1}{2} 次{3}{4}
      • ", Math.round(x.degree * 100), pathHtml(x.path), fmt(x.shared), x.kind === 'test' ? tr(" · 测试同步") : x.kind === 'process' ? tr(" · 流程文件") : '', x.exists ? '' : tr(" · 已删除"), (x.degree * 100).toFixed(0))) + .join('')); } async function openFile(path) { const r = current(); @@ -2050,20 +1895,7 @@ async function openFile(path) { const d = await api(`/api/repos/${encodeURIComponent(r.id)}/file?path=${encodeURIComponent(path)}&identity=${state.identity}`); if (drawerKey !== `f:${path}`) return; const max = d.owners[0]?.commits || 1; - dlg.innerHTML = `${drawerShell(`

        ${pathHtml(path, { link: false, baseFirst: false })}

        `, `${d.exists ? '在 HEAD 中存在' : '已在 HEAD 中删除或改名'}${d.firstAdd ? ` · 首次加入 ${d.firstAdd}` : ''}${fileBadges(path)}`)} -
        -
        ${fileActions(path, { exists: d.exists })}
        -
        -
        全部修改
        ${fmt(d.total)}
        -
        修 bug 的提交
        ${fmt(d.fixes)}
        -
        维护者
        ${fmt(d.ownerCount)}
        -
        -

        每月修改次数

        ${C.monthBars({ months: d.months.slice(-24).map(([m, n]) => ({ m, n })), height: 170, color: 'var(--k-mr)' })}
        -

        维护者 等同 git shortlog -sn -- <file>${state.identity === 'merged' ? ',不含机器人' : ''}

        -
          ${d.owners.map((o) => `
        • ${avatar(o.name)}${personLink(o.name)}
          ${fmt(o.commits)} · ${pct(o.share)}
        • `).join('')}
        - ${couplingHtml(d.coupling)} -

        最近 ${d.commits.length} 次修改

          ${d.commits.map((c) => commitRow(c, `${c.fix ? 'fix ' : ''}${c.fire ? '救火 ' : ''}${c.status === 'A' ? '新增 ' : c.status === 'D' ? '删除 ' : ''}`)).join('')}
        -
        `; + dlg.innerHTML = tr("{0}\n
        \n
        {1}
        \n
        \n
        全部修改
        {2}
        \n
        修 bug 的提交
        {3}
        \n
        维护者
        {4}
        \n
        \n

        每月修改次数

        {5}
        \n

        维护者 等同 git shortlog -sn -- <file>{6}

        \n
          {7}
        \n {8}\n

        最近 {9} 次修改

          {10}
        \n
        ", drawerShell(`

        ${pathHtml(path, { link: false, baseFirst: false })}

        `, tr("{0}{1}{2}", d.exists ? tr("在 HEAD 中存在") : tr("已在 HEAD 中删除或改名"), d.firstAdd ? tr(" · 首次加入 {0}", d.firstAdd) : '', fileBadges(path))), fileActions(path, { exists: d.exists }), fmt(d.total), fmt(d.fixes), fmt(d.ownerCount), C.monthBars({ months: d.months.slice(-24).map(([m, n]) => ({ m, n })), height: 170, color: 'var(--k-mr)' }), state.identity === 'merged' ? tr(",不含机器人") : '', d.owners.map((o) => `
      • ${avatar(o.name)}${personLink(o.name)}
        ${fmt(o.commits)} · ${pct(o.share)}
      • `).join(''), couplingHtml(d.coupling), d.commits.length, d.commits.map((c) => commitRow(c, tr("{0}{1}{2}", c.fix ? 'fix ' : '', c.fire ? tr("救火 ") : '', c.status === 'A' ? tr("新增 ") : c.status === 'D' ? tr("删除 ") : ''))).join('')); } catch (e) { dlg.querySelector('.dlg-body').innerHTML = ``; } @@ -2072,24 +1904,14 @@ async function openPerson(name) { const r = current(); const dlg = $('#drawer'); if (!r) return; - dlg.innerHTML = `${drawerShell(`

        ${esc(name)}

        `)}
        `; + dlg.innerHTML = `${drawerShell(`

        ${esc(displayText(name))}

        `)}
        `; dlg.setAttribute('aria-labelledby', 'drawer-title'); if (!dlg.open) dlg.showModal(); try { const d = await api(`/api/repos/${encodeURIComponent(r.id)}/person?name=${encodeURIComponent(name)}&identity=${state.identity}`); if (drawerKey !== `p:${name}`) return; const maxF = d.files[0]?.count || 1; - dlg.innerHTML = `${drawerShell(`
        ${avatar(d.name, 'lg')}

        ${esc(d.name)}${d.bot ? ' 机器人' : ''}

        `, `${d.first || '–'} → ${d.last || '–'}${d.aliases.length ? ` · 也作 ${esc(d.aliases.join('、'))}` : ''}${d.emails.length ? ` · ${esc(d.emails.join(', '))}` : ''}${personBadges(d.name)}`)} -
        -
        -
        非合并提交
        ${fmt(d.commits)}
        -
        修 bug
        ${fmt(d.fixes)}
        -
        合并提交
        ${fmt(d.merges)}
        -
        -

        每月提交

        ${C.monthBars({ months: d.months.slice(-24).map(([m, n]) => ({ m, n })), height: 170, color: C.memberColor(d.name) })}
        -

        改得最多的文件

          ${d.files.map((f, i) => `
        1. ${i + 1}${pathHtml(f.path)}
          ${fmt(f.count)}
        2. `).join('')}
        -

        最近提交

          ${d.recent.map((c) => commitRow(c, `${c.fix ? 'fix ' : ''}${c.fire ? '救火 ' : ''}`)).join('')}
        -
        `; + dlg.innerHTML = tr("{0}\n
        \n
        \n
        非合并提交
        {1}
        \n
        修 bug
        {2}
        \n
        合并提交
        {3}
        \n
        \n

        每月提交

        {4}
        \n

        改得最多的文件

          {5}
        \n

        最近提交

          {6}
        \n
        ", drawerShell(tr("
        {0}

        {1}{2}

        ", avatar(d.name, 'lg'), esc(displayText(d.name)), d.bot ? tr(" 机器人") : ''), tr("{0} → {1}{2}{3}{4}", d.first || '–', d.last || '–', d.aliases.length ? tr(" · 也作 {0}", esc(d.aliases.join(tr("、")))) : '', d.emails.length ? ` · ${esc(d.emails.join(', '))}` : '', personBadges(d.name))), fmt(d.commits), fmt(d.fixes), fmt(d.merges), C.monthBars({ months: d.months.slice(-24).map(([m, n]) => ({ m, n })), height: 170, color: C.memberColor(d.name) }), d.files.map((f, i) => `
      • ${i + 1}${pathHtml(f.path)}
        ${fmt(f.count)}
      • `).join(''), d.recent.map((c) => commitRow(c, tr("{0}{1}", c.fix ? 'fix ' : '', c.fire ? tr("救火 ") : ''))).join('')); } catch (e) { dlg.querySelector('.dlg-body').innerHTML = ``; } @@ -2102,39 +1924,39 @@ function buildMarkdown(rep, r) { const v = rep.vitals; const L = []; L.push(`# Codebase Recon Report — ${r.display}`, ''); - L.push(`> 由仓库透视(Repo X-Ray)生成于 ${new Date().toLocaleString('zh-CN')},HEAD \`${rep.head.slice(0, 12)}\`(${rep.branch || 'HEAD'}),身份口径:${rep.identity === 'raw' ? '原始(与 shortlog 一致)' : '合并身份,机器人除外'}`, ''); + L.push(tr("> 由仓库透视(Repo X-Ray)生成于 {0},HEAD `{1}`({2}),身份口径:{3}", new Date().toLocaleString(localeTag()), rep.head.slice(0, 12), rep.branch || 'HEAD', rep.identity === 'raw' ? tr("原始(与 shortlog 一致)") : tr("合并身份,机器人除外")), ''); L.push('## Repo Vitals', `Age: ${v.first} to ${v.latest} | Commits: ${v.commits} | Branches: ${v.branches} | Analysis window: ${v.window}`, ''); L.push('## 1. Code Hotspots', ...rep.hotspots.map((h) => `- ${h.count} \`${h.path}\``), ''); L.push('## 2. Bug Magnets', ...rep.bugMagnets.map((h) => `- ${h.count} \`${h.path}\``), ''); L.push('## 3. High-Risk Files'); - if (rep.highRisk.length) L.push(...rep.highRisk.map((h) => `- \`${h.path}\` — hotspot rank #${h.hotRank}, bug magnet rank #${h.bugRank}, primary owner: ${h.owner ? `${h.owner.name} (${pct(h.owner.share)})` : '–'}`)); + if (rep.highRisk.length) L.push(...rep.highRisk.map((h) => `- \`${h.path}\` — hotspot rank #${h.hotRank}, bug magnet rank #${h.bugRank}, primary owner: ${h.owner ? `${displayText(h.owner.name)} (${pct(h.owner.share)})` : '–'}`)); else L.push('No files appear in both lists — good sign.'); - L.push('', '## 4. Bus Factor', ...rep.contributors.slice(0, 10).map((c) => `- ${c.commits} ${c.name}`), `Active (last 3 months): ${rep.busFactor.active3m} of ${rep.busFactor.total} total contributors`); + L.push('', '## 4. Bus Factor', ...rep.contributors.slice(0, 10).map((c) => `- ${c.commits} ${displayText(c.name)}`), `Active (last 3 months): ${rep.busFactor.active3m} of ${rep.busFactor.total} total contributors`); if (rep.busFactor.warn) L.push('Warning: low active contributor ratio — knowledge concentration risk'); L.push('', '## 5. Team Momentum', ...rep.momentum.months.slice(-12).map((m) => `- ${m.m}: ${m.n}`), `Trend: ${rep.momentum.trend}`, ''); L.push('## 6. Firefighting Frequency', ...(rep.firefighting.list.length ? rep.firefighting.list.slice(0, 20).map((c) => `- ${c.sha.slice(0, 7)} ${c.subj}`) : ['None found']), `Rate: ${rep.firefighting.count} emergency commits out of ${rep.firefighting.total} total in window (${pct(rep.firefighting.rate, 1)})`, ''); L.push('## 7. Recently Added Files', ...rep.recentlyAdded.files.map((f) => `- ${f.count} \`${f.path}\``), ''); if (rep.tech) { L.push('## Tech Stack', `Languages: ${rep.tech.languages.slice(0, 6).map((l) => `${l.name} ${pct(l.share)}`).join(', ')}`); - for (const g of rep.tech.groups) L.push(`- ${g.category}: ${g.items.map((i) => i.name).join(', ')}`); + for (const g of rep.tech.groups) L.push(`- ${tr(g.category)}: ${g.items.map((i) => tr(i.name)).join(', ')}`); L.push(''); } const rec = rep.recommendations; - L.push('## 8. Recommendations', `- Start reading: ${rec.startReading.map((p) => `\`${p}\``).join(', ') || '–'}`, `- Talk to: ${rec.talkTo ? `${rec.talkTo.name} (owner of \`${rec.talkTo.file}\`)` : '–'}`, `- Watch out: ${rec.watchOut.join('; ') || 'nothing notable'}`, ''); + L.push('## 8. Recommendations', `- Start reading: ${rec.startReading.map((p) => `\`${p}\``).join(', ') || '–'}`, `- Talk to: ${rec.talkTo ? `${displayText(rec.talkTo.name)} (owner of \`${rec.talkTo.file}\`)` : '–'}`, `- Watch out: ${langList(rec.watchOut).join('; ') || 'nothing notable'}`, ''); return L.join('\n'); } function chatPrompt(rep, r) { - const loc = r.kind === 'local' ? `本地仓库 ${r.localDir}` : `${r.webUrl}(若本地没有 checkout,请先 clone)`; - const risk = rep.highRisk.slice(0, 5).map((h, i) => `${i + 1}. ${h.path}(热点 #${h.hotRank},修 bug ${h.bugCount}/${h.hotCount} 次,主要负责人 ${h.owner?.name || '–'})`); + const loc = r.kind === 'local' ? tr("本地仓库 {0}", r.localDir) : tr("{0}(若本地没有 checkout,请先 clone)", r.webUrl); + const risk = rep.highRisk.slice(0, 5).map((h, i) => tr("{0}. {1}(热点 #{2},修 bug {3}/{4} 次,主要负责人 {5})", i + 1, h.path, h.hotRank, h.bugCount, h.hotCount, h.owner?.name || '–')); return [ - `请基于下面这份仓库透视报告,帮我深入看一下 ${loc}。`, + tr("请基于下面这份仓库透视报告,帮我深入看一下 {0}。", loc), '', - `HEAD ${rep.head.slice(0, 12)};${rep.vitals.commits} 个 commit;节奏${TREND[rep.momentum.trend]};救火占比 ${pct(rep.firefighting.rate, 1)};近 3 个月活跃 ${rep.busFactor.active3m}/${rep.busFactor.total} 人。`, + tr("HEAD {0};{1} 个 commit;节奏{2};救火占比 {3};近 3 个月活跃 {4}/{5} 人。", rep.head.slice(0, 12), rep.vitals.commits, TREND[rep.momentum.trend], pct(rep.firefighting.rate, 1), rep.busFactor.active3m, rep.busFactor.total), '', - '高风险文件(热点 ∩ bug 磁铁):', - ...(risk.length ? risk : ['(无)']), + tr("高风险文件(热点 ∩ bug 磁铁):"), + ...(risk.length ? risk : [tr("(无)")]), '', - '请先阅读前 3 个高风险文件,回答:它们为什么反复出 bug(结构、耦合、职责、测试覆盖),有哪些具体可落地的拆分或加固建议。只读分析,不要修改代码。', + tr("请先阅读前 3 个高风险文件,回答:它们为什么反复出 bug(结构、耦合、职责、测试覆盖),有哪些具体可落地的拆分或加固建议。只读分析,不要修改代码。"), ].join('\n'); } async function sendToChat(btn, custom = null) { @@ -2144,16 +1966,16 @@ async function sendToChat(btn, custom = null) { const message = window.mcode?.miniapp?.message; const text = custom ?? chatPrompt(rep, r); if (!message?.append) { - await copyText(text, '当前环境不支持直接发到对话,已复制到剪贴板'); + await copyText(text, tr("当前环境不支持直接发到对话,已复制到剪贴板")); return; } if (btn) btn.disabled = true; try { await message.append(text); - toast('已追加到对话输入框,确认后按发送即可'); + toast(tr("已追加到对话输入框,确认后按发送即可")); } catch (e) { const code = e?.message; - toast(code === 'user_cancelled' ? '已取消,没有追加内容' : code === 'result_unknown' ? '结果未知,请先检查对话输入框再重试' : code === 'target_unavailable' ? '找不到可追加的对话,请从对话里打开这个 Mini App' : '追加失败,请稍后重试'); + toast(code === 'user_cancelled' ? tr("已取消,没有追加内容") : code === 'result_unknown' ? tr("结果未知,请先检查对话输入框再重试") : code === 'target_unavailable' ? tr("找不到可追加的对话,请从对话里打开这个 Mini App") : tr("追加失败,请稍后重试")); } finally { if (btn?.isConnected) btn.disabled = false; } @@ -2173,9 +1995,7 @@ function openExportMenu(btn) { const menu = document.createElement('div'); menu.className = 'menu'; menu.setAttribute('role', 'menu'); - menu.innerHTML = ` - - `; + menu.innerHTML = tr("\n \n ", ICON.copy, ICON.download, ICON.chat); document.body.append(menu); const b = btn.getBoundingClientRect(); menu.style.top = `${b.bottom + 6}px`; @@ -2203,7 +2023,7 @@ function toggleExplain(btn) { const pop = document.createElement('div'); pop.className = 'popover'; pop.setAttribute('role', 'dialog'); - pop.setAttribute('aria-label', '指标说明'); + pop.setAttribute('aria-label', tr("指标说明")); pop.append(tpl.content.cloneNode(true)); document.body.append(pop); const b = btn.getBoundingClientRect(); @@ -2226,10 +2046,7 @@ function closePopovers() { const pal = { items: [], active: 0, seq: 0, timer: null }; function openPalette(prefill = '') { const dlg = $('#palette'); - dlg.innerHTML = `
        -
        ${ICON.search}Esc
        -
          -
          ↑↓ 选择↵ 打开Esc 关闭
          `; + dlg.innerHTML = tr("
          \n
          {0}Esc
          \n
            \n
            ↑↓ 选择↵ 打开Esc 关闭
            ", ICON.search, current()?.lastSync?.at ? tr("搜索仓库、{0} 里的文件和贡献者…", esc(current().name)) : tr("搜索仓库或执行操作…")); if (!dlg.open) dlg.showModal(); const q = $('#pal-q'); q.value = prefill; @@ -2245,17 +2062,17 @@ function hl(text, needle) { } function palActions() { const r = current(); - const A = [{ kind: 'action', label: '分析新仓库…', icon: ICON.search, run: () => go({ repo: null, tab: 'overview', file: null, person: null, filter: null }) }]; + const A = [{ kind: 'action', label: tr("分析新仓库…"), icon: ICON.search, run: () => go({ repo: null, tab: 'overview', file: null, person: null, filter: null }) }]; if (r) { - A.push({ kind: 'action', label: r.kind === 'local' ? '重新分析当前仓库' : '同步并分析当前仓库', icon: ICON.sync, run: () => syncCurrent() }); + A.push({ kind: 'action', label: r.kind === 'local' ? tr("重新分析当前仓库") : tr("同步并分析当前仓库"), icon: ICON.sync, run: () => syncCurrent() }); if (state.report) { - A.push({ kind: 'action', label: '复制 Markdown 报告', icon: ICON.copy, run: () => copyText(buildMarkdown(state.report, r), '报告已复制') }); - A.push({ kind: 'action', label: '发到对话…', icon: ICON.chat, run: () => sendToChat() }); + A.push({ kind: 'action', label: tr("复制 Markdown 报告"), icon: ICON.copy, run: () => copyText(buildMarkdown(state.report, r), tr("报告已复制")) }); + A.push({ kind: 'action', label: tr("发到对话…"), icon: ICON.chat, run: () => sendToChat() }); } - for (const [t, l] of TABS) A.push({ kind: 'action', label: `转到:${l}`, icon: ICON.arrow, run: () => go({ tab: t, filter: null, file: null, person: null }) }); + for (const [t, l] of TABS) A.push({ kind: 'action', label: tr("转到:{0}", l), icon: ICON.arrow, run: () => go({ tab: t, filter: null, file: null, person: null }) }); } - A.push({ kind: 'action', label: '切换主题', icon: '', run: cycleTheme }); - A.push({ kind: 'action', label: '打开设置', icon: ICON.info, run: openSettings }); + A.push({ kind: 'action', label: tr("切换主题"), icon: '', run: cycleTheme }); + A.push({ kind: 'action', label: tr("打开设置"), icon: ICON.info, run: openSettings }); return A; } function palQuery(q) { @@ -2280,7 +2097,7 @@ function palQuery(q) { if (my !== pal.seq) return; pal.remote = [ ...res.files.map((f) => ({ kind: 'file', label: f.path, count: f.count, exists: f.exists, icon: ICON.file, run: () => go({ file: f.path, person: null }) })), - ...res.people.map((p) => ({ kind: 'person', label: p.name, count: p.commits, bot: p.bot, icon: ICON.user, run: () => go({ person: p.name, file: null }) })), + ...res.people.map((p) => ({ kind: 'person', label: displayText(p.name), count: p.commits, bot: p.bot, icon: ICON.user, run: () => go({ person: p.name, file: null }) })), ]; } catch {} pal.loading = false; @@ -2292,7 +2109,7 @@ function renderPal() { if (!list) return; pal.items = [...pal.base.filter((x) => x.kind !== 'action' || !pal.remote.length), ...pal.remote, ...(pal.remote.length ? pal.base.filter((x) => x.kind === 'action') : [])]; pal.active = Math.min(pal.active, Math.max(0, pal.items.length - 1)); - const GROUP = { action: '操作', repo: '仓库', file: '文件', person: '贡献者' }; + const GROUP = { action: tr("操作"), repo: tr("仓库"), file: tr("文件"), person: tr("贡献者") }; const needle = ($('#pal-q')?.value || '').trim().toLowerCase(); let last = ''; list.innerHTML = @@ -2305,13 +2122,13 @@ function renderPal() { const k = it.label.lastIndexOf('/'); label = `${hl(it.label.slice(k + 1), needle)} ${hl(it.label.slice(0, k + 1), needle)}`; } else label = `${hl(it.label, needle)}`; - const meta = it.kind === 'file' ? `${fmt(it.count)} 次修改${it.exists ? '' : ' · 已删除'}` : it.kind === 'person' ? `${fmt(it.count)} 个提交${it.bot ? ' · 机器人' : ''}` : it.sub ? esc(it.sub) : ''; + const meta = it.kind === 'file' ? tr("{0} 次修改{1}", fmt(it.count), it.exists ? '' : tr(" · 已删除")) : it.kind === 'person' ? tr("{0} 个提交{1}", fmt(it.count), it.bot ? tr(" · 机器人") : '') : it.sub ? esc(it.sub) : ''; return `${head}
          • ${it.icon}${label}${meta}
          • `; }) - .join('') + (pal.loading ? '' : !pal.items.length ? '' : ''); + .join('') + (pal.loading ? tr("
          • 搜索中…
          • ") : !pal.items.length ? tr("
          • 没有匹配的结果
          • ") : ''); $('#pal-q')?.setAttribute('aria-activedescendant', pal.items.length ? `pal-${pal.active}` : ''); const cnt = $('#pal-count'); - if (cnt) cnt.textContent = pal.items.length ? `${pal.items.length} 项` : ''; + if (cnt) cnt.textContent = pal.items.length ? tr("{0} 项", pal.items.length) : ''; $(`#pal-${pal.active}`)?.scrollIntoView({ block: 'nearest' }); } function palRun(i) { @@ -2326,29 +2143,9 @@ function palRun(i) { // --------------------------------------------------------------------------- function openSettings() { const s = state.settings; - const src = { gh: 'gh 登录', glab: 'glab 登录', token: '手动令牌', none: '未找到凭据(按公开仓库访问)' }; + const src = { gh: tr("gh 登录"), glab: tr("glab 登录"), token: tr("手动令牌"), none: tr("未找到凭据(按公开仓库访问)") }; const dlg = $('#settings'); - dlg.innerHTML = `

            设置

            -
            -

            凭据

            默认复用本机 gh / glab 的登录;令牌只保存在这个 Mini App 的数据目录里,不会发送到页面,也不会写进仓库配置。

            -
              ${(s.hosts || []).map((h) => `
            • ${esc(h.host)}
              ${src[h.source] || h.source}
              ${s.tokenHosts?.includes(h.host) ? `` : ''}
            • `).join('') || '
            • 分析远程仓库后,这里会列出用到的主机。
            • '}
            -
            -

            为某个主机填写访问令牌

            -
            -
            -
            -
            -

            本机仓库扫描目录

            -
            -
            -
            -
            -

            网络代理

            -
            - 当前:${{ settings: '使用这里的设置', env: '使用环境变量里的代理', system: '使用系统代理', none: '直连' }[s.proxyActive] || '直连'}
            -
            -
            -
            `; + dlg.innerHTML = tr("

            设置

            \n
            \n

            凭据

            默认复用本机 gh / glab 的登录;令牌只保存在这个 Mini App 的数据目录里,不会发送到页面,也不会写进仓库配置。

            \n
              {1}
            \n
            \n

            为某个主机填写访问令牌

            \n
            \n
            \n
            \n
            \n

            本机仓库扫描目录

            \n
            \n
            \n
            \n
            \n

            网络代理

            \n
            \n 当前:{4}
            \n
            \n
            \n
            ", ICON.close, (s.hosts || []).map((h) => tr("
          • {0}
            {1}
            {2}
          • ", esc(h.host), src[h.source] || h.source, s.tokenHosts?.includes(h.host) ? tr("", esc(h.host)) : '')).join('') || tr("
          • 分析远程仓库后,这里会列出用到的主机。
          • "), esc((s.scanRoots || []).join('\n')), esc(s.proxy || ''), { settings: tr("使用这里的设置"), env: tr("使用环境变量里的代理"), system: tr("使用系统代理"), none: tr("直连") }[s.proxyActive] || tr("直连")); dlg.setAttribute('aria-labelledby', 'set-title'); if (!dlg.open) dlg.showModal(); } @@ -2365,31 +2162,71 @@ async function syncCurrent() { toast(e.message); } } +// Write the queue of pending removals where a reload can find it. The page can +// be reloaded at any time - the language switch reloads it, and the Host may +// reload it on its own - and the reload would otherwise drop the timer and +// the queued DELETE, leaving the repository and its cached clone in place. +function savePendingRemovals() { + try { + if (state.pendingRemoval.size) sessionStorage.setItem(PENDING_KEY, encodePending(state.pendingRemoval)); + else sessionStorage.removeItem(PENDING_KEY); + } catch {} +} +// Delete a repository for good, once its undo window has closed. +async function commitRemoval(id) { + state.pendingRemoval.delete(id); + savePendingRemovals(); + try { + await api(`/api/repos/${encodeURIComponent(id)}`, { method: 'DELETE' }); + await loadState(); + } catch (e) { + toast(e.message); + await loadState().catch(() => {}); + } +} +// Queue a removal, and keep it until it is deleted or undone. +function queueRemoval(repo, until) { + const id = repo.id; + const left = pendingLeft(until); + state.pendingRemoval.set(id, { until }); + savePendingRemovals(); + const timer = setTimeout(() => commitRemoval(id), left); + toast(repo.kind === 'local' ? tr("已移除 {0}(不会动本地仓库)", repo.name) : tr("已移除 {0},8 秒后删除缓存的 clone", repo.name), { + label: tr("撤销"), + ms: Math.max(left, 1), + run: () => { + clearTimeout(timer); + state.pendingRemoval.delete(id); + savePendingRemovals(); + go({ repo: id, tab: 'overview', file: null, person: null, filter: null }); + }, + }); +} +// Pick up the queue a reload left behind, and finish what it started. +function resumePendingRemovals() { + let saved = []; + try { + saved = decodePending(sessionStorage.getItem(PENDING_KEY)); + } catch { + saved = []; + } + for (const { id, until } of saved) { + const repo = state.repos.find((r) => r.id === id); + if (!repo) { + state.pendingRemoval.delete(id); + continue; + } + queueRemoval(repo, until); + } + savePendingRemovals(); + renderSidebar(); +} function removeCurrent() { const r = current(); if (!r) return; - state.pendingRemoval.set(r.id, true); + queueRemoval(r, Date.now() + UNDO_MS); const next = visibleRepos()[0]; go({ repo: next?.id || null, tab: 'overview', file: null, person: null, filter: null }); - const timer = setTimeout(async () => { - state.pendingRemoval.delete(r.id); - try { - await api(`/api/repos/${encodeURIComponent(r.id)}`, { method: 'DELETE' }); - await loadState(); - } catch (e) { - toast(e.message); - await loadState().catch(() => {}); - } - }, 8000); - toast(r.kind === 'local' ? `已移除 ${r.name}(不会动本地仓库)` : `已移除 ${r.name},8 秒后删除缓存的 clone`, { - label: '撤销', - ms: 8000, - run: () => { - clearTimeout(timer); - state.pendingRemoval.delete(r.id); - go({ repo: r.id, tab: 'overview', file: null, person: null, filter: null }); - }, - }); } async function setIdentity(v) { if (state.identity === v) return; @@ -2405,22 +2242,7 @@ async function setIdentity(v) { function openKeys() { const dlg = $('#keys'); const row = (keys, text) => `
            ${keys}
            ${text}
            `; - dlg.innerHTML = `

            键盘快捷键

            -
            - ${row('⌘K', '搜索仓库、全部历史文件、贡献者和操作')} - ${row('/', '聚焦贡献者筛选框或仓库地址输入框')} - ${row(`1–${TABS.length}`, '切换报告分区')} - ${row('[]', '切换到上一个 / 下一个仓库')} - ${row('Esc', '关闭抽屉、弹层和菜单;在代码地图上取消选择')} - ${row('?', '显示这份列表')} -
            -

            代码地图

            -
            - ${row('←↑→↓', '在方块之间移动')} - ${row('Space / 单击', '选中,查看详情和“常一起改”的连线')} - ${row('↵ / 双击', '进入目录,或打开文件历史')} - ${row('⌫', '返回上一层(浏览器后退也可以)')} -
            `; + dlg.innerHTML = tr("

            键盘快捷键

            \n
            \n {1}\n {2}\n {3}\n {4}\n {5}\n {6}\n
            \n

            代码地图

            \n
            \n {7}\n {8}\n {9}\n {10}\n
            ", ICON.close, row('⌘K', tr("搜索仓库、全部历史文件、贡献者和操作")), row('/', tr("聚焦贡献者筛选框或仓库地址输入框")), row(`1–${TABS.length}`, tr("切换报告分区")), row('[]', tr("切换到上一个 / 下一个仓库")), row('Esc', tr("关闭抽屉、弹层和菜单;在代码地图上取消选择")), row('?', tr("显示这份列表")), row('←↑→↓', tr("在方块之间移动")), row(tr("Space / 单击"), tr("选中,查看详情和“常一起改”的连线")), row(tr("↵ / 双击"), tr("进入目录,或打开文件历史")), row('⌫', tr("返回上一层(浏览器后退也可以)"))); if (!dlg.open) dlg.showModal(); } document.addEventListener('click', async (e) => { @@ -2476,7 +2298,7 @@ document.addEventListener('click', async (e) => { case 'explain': return toggleExplain(el); case 'copy': - return copyText(el.dataset.text, '已复制', el); + return copyText(el.dataset.text, tr("已复制"), el); case 'map-cell': return mp.view?.blocks[el.dataset.i] && setSel(selKey(mp.view.blocks[el.dataset.i])); case 'thumb-open': @@ -2527,12 +2349,12 @@ document.addEventListener('click', async (e) => { return el.getAttribute('aria-expanded') === 'true' ? closeMenus() : openExportMenu(el); case 'export-copy': closeMenus(); - return state.report && copyText(buildMarkdown(state.report, r), 'Markdown 报告已复制'); + return state.report && copyText(buildMarkdown(state.report, r), tr("Markdown 报告已复制")); case 'export-download': closeMenus(); if (!state.report) return; download(`${r.name.replace(/[^\w.-]+/g, '-')}-xray-${state.report.head.slice(0, 8)}.md`, buildMarkdown(state.report, r)); - return toast('已开始下载'); + return toast(tr("已开始下载")); case 'to-chat': closeMenus(); return sendToChat(el); @@ -2556,6 +2378,8 @@ document.addEventListener('click', async (e) => { return; case 'theme': return cycleTheme(); + case 'lang': + return cycleLang(); } }); $('#drawer').addEventListener('cancel', (e) => { @@ -2657,8 +2481,8 @@ document.addEventListener('input', (e) => { } else if (e.target.id === 'target-input') { const h = $('#parse-hint'); const p = parsePreview(e.target.value); - h.textContent = p ? `将分析:${p}` : ''; - h.className = `parse-hint${p.startsWith('无法识别') || p.startsWith('地址格式') ? ' err' : ''}`; + h.textContent = p.text ? tr("将分析:{0}", p.text) : ''; + h.className = `parse-hint${p.error ? ' err' : ''}`; } else if (e.target.id === 'pal-q') { pal.active = 0; palQuery(e.target.value); @@ -2687,7 +2511,7 @@ document.addEventListener('submit', async (e) => { await api('/api/settings', { method: 'POST', body }); await loadState(); openSettings(); - msg(id, '已保存', true); + msg(id, tr("已保存"), true); return true; } catch (err) { msg(id, err.message); @@ -2765,9 +2589,11 @@ window.addEventListener('scroll', hideTip, { passive: true }); // Boot // --------------------------------------------------------------------------- applyTheme(); +applyLang(); (async () => { try { await loadState(); + resumePendingRemovals(); connect(); if (!route.repo && !location.search) { const last = localStorage.getItem('rr-repo'); @@ -2775,6 +2601,6 @@ applyTheme(); } await applyRoute(); } catch (e) { - main.innerHTML = ``; + main.innerHTML = tr("
            加载失败:{0}
            ", esc(e.message)); } })(); diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/charts.js b/plugins/yujiachen-y/repo-xray/miniapp/client/charts.js index c30a45d0..ce743535 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/client/charts.js +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/charts.js @@ -1,5 +1,7 @@ // Hand-written SVG charts. Every function returns markup; tooltips use data-tip. +import { localeTag, t as tr } from './i18n.js'; + export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); @@ -15,8 +17,8 @@ export const addDays = (s, n) => { }; export const dayDiff = (a, b) => Math.round((parseYmd(b) - parseYmd(a)) / 86_400_000); export const mondayOf = (s) => addDays(s, -((parseYmd(s).getDay() + 6) % 7)); -export const WD = ['日', '一', '二', '三', '四', '五', '六']; -export const fmt = (n) => (n == null ? '–' : Number(n).toLocaleString('zh-CN')); +export const WD = [tr("日"), tr("一"), tr("二"), tr("三"), tr("四"), tr("五"), tr("六")]; +export const fmt = (n) => (n == null ? '–' : Number(n).toLocaleString(localeTag())); let uid = 0; const nextId = (p) => `${p}${++uid}`; @@ -38,11 +40,11 @@ function quantiles(values) { const levelOf = (t, v) => (!v ? 0 : v <= t[0] ? 1 : v <= t[1] ? 2 : v <= t[2] ? 3 : 4); export function heatLegend() { - return ``; + return tr("少 {0} 多", [0, 1, 2, 3, 4].map((l) => ``).join('')); } /** GitHub-style calendar, Monday-first rows. */ -export function calendar({ daily, start, end, cell = 12, gap = 3, label = '活动热力图', unit = '条活动' }) { +export function calendar({ daily, start, end, cell = 12, gap = 3, label = tr("活动热力图"), unit = tr("条活动") }) { const startMon = mondayOf(start); const nWeeks = Math.floor(dayDiff(startMon, end) / 7) + 1; const t = quantiles(Object.values(daily)); @@ -65,11 +67,11 @@ export function calendar({ daily, start, end, cell = 12, gap = 3, label = '活 const inRange = date >= start; const v = daily[date] || 0; const lv = inRange ? levelOf(t, v) : 0; - cells += ``; + cells += tr("", w, lv, left + w * stepX, top + d * step, cw, cell, inRange ? '' : ' opacity="0.3"', date, WD[parseYmd(date).getDay()], inRange ? `${fmt(v)} ${unit}` : tr("不在统计范围内")); } const mDate = parseYmd(weekStart); if (mDate.getMonth() !== lastMonth && (w - lastLabelW) * stepX >= 3 * step) { - months += `${mDate.getMonth() + 1}月`; + months += tr("{1}月", left + w * stepX, mDate.getMonth() + 1); lastLabelW = w; } lastMonth = mDate.getMonth(); @@ -164,7 +166,7 @@ export function stackedArea({ weeks, series, kinds, labels, colors, hidden, end, weeks.forEach((wk, i) => { const m = parseYmd(wk).getMonth(); if (m !== lastM && x(i) - lastX > 34) { - xl += `${m + 1}月`; + xl += tr("{2}月", x(i), H - 6, m + 1); lastX = x(i); } lastM = m; @@ -174,13 +176,13 @@ export function stackedArea({ weeks, series, kinds, labels, colors, hidden, end, .map((wk, i) => { const wEnd = addDays(wk, 6) > end ? end : addDays(wk, 6); const lines = vis.filter(([, k]) => series[i][k] > 0).map(([k, ki]) => `${labels[k]} ${fmt(series[i][ki])}`); - const tip = `${wk.slice(5)} – ${wEnd.slice(5)} 共 ${fmt(totals[i])}${lines.length ? ' ' + lines.join(' ') : ''}`; + const tip = tr("{0} – {1} 共 {2}{3}", wk.slice(5), wEnd.slice(5), fmt(totals[i]), lines.length ? ' ' + lines.join(' ') : ''); return ``; }) .join(''); const peak = totals.indexOf(Math.max(...totals)); - const peakMark = totals[peak] > 0 ? `峰值 ${fmt(totals[peak])}` : ''; - return `${defs}${grid}${layers}${line}${peakMark}${xl}${hits}`; + const peakMark = totals[peak] > 0 ? tr("峰值 {4}", x(peak), y(totals[peak]), x(peak), y(totals[peak]) - 8, fmt(totals[peak])) : ''; + return tr("{3}{4}{5}{6}{7}{8}{9}", W, H, fmt(totals[peak] || 0), defs, grid, layers, line, peakMark, xl, hits); } export function donut({ items, center, sub }) { @@ -197,12 +199,12 @@ export function donut({ items, center, sub }) { const p = (a, rad) => `${(75 + rad * Math.cos(a)).toFixed(2)},${(75 + rad * Math.sin(a)).toFixed(2)}`; paths += frac >= 0.999 - ? `` - : ``; + ? tr("", (R + r) / 2, it.color, R - r, esc(it.label), fmt(it.value)) + : tr("", p(a0, R), R, R, large, p(a1, R), p(a1, r), r, r, large, p(a0, r), it.color, esc(it.label), fmt(it.value), Math.round(frac * 100)); a0 += frac * Math.PI * 2; } if (!total) paths = ``; - return `${paths}${esc(center)}${esc(sub)}`; + return tr("{0}{1}{2}", paths, esc(center), esc(sub)); } /** Members × weeks matrix. rows: [{ username, label, weekly }] */ @@ -223,7 +225,7 @@ export function swimlane({ rows, weeks, end }) { const m = parseYmd(wk).getMonth(); const xx = labelW + i * (cell + gap); if (m !== lastM && xx - lastX > 30) { - out += `${m + 1}月`; + out += tr("{1}月", xx, m + 1); lastX = xx; } lastM = m; @@ -233,15 +235,15 @@ export function swimlane({ rows, weeks, end }) { out += `${esc(r.label.length > 9 ? r.label.slice(0, 8) + '…' : r.label)}`; r.weekly.forEach((v, i) => { const wEnd = addDays(weeks[i], 6) > end ? end : addDays(weeks[i], 6); - out += ``; + out += tr("", i, levelOf(t, v), labelW + i * (cell + gap), yy, cell, ch, esc(r.label), weeks[i].slice(5), wEnd.slice(5), fmt(v)); }); out += ''; }); - return `${out}`; + return tr("{5}", W, H, Math.min(W, 640), Math.round(W * 1.25), rows.length, out); } /** 7 × 24 punch card, Monday-first rows. */ -export function punchcard({ punch, color = 'var(--k-code)', label = '作息打卡图' }) { +export function punchcard({ punch, color = 'var(--k-code)', label = tr("作息打卡图") }) { const L = 22; const T = 6; const step = 26; @@ -257,10 +259,10 @@ export function punchcard({ punch, color = 'var(--k-code)', label = '作息打 const v = punch[d * 24 + h] || 0; const r = v ? 2 + Math.sqrt(v / max) * 8.5 : 1.2; const night = h >= 22 || h < 6; - out += ``; + out += tr("", L + h * step + step / 2, yy, r.toFixed(1), v ? (night ? 'var(--k-mr)' : color) : 'var(--heat-0)', v ? (0.35 + 0.65 * (v / max)).toFixed(2) : 1, WD[(d + 1) % 7], h, h + 1, fmt(v)); } } - for (let h = 0; h < 24; h += 3) out += `${h}时`; + for (let h = 0; h < 24; h += 3) out += tr("{2}时", L + h * step + step / 2, H - 2, h); return `${out}`; } @@ -288,14 +290,14 @@ export function scatter({ points }) { const qy = Y(my); let out = ``; out += ``; - const q = (x, y, anchor, t) => `${t}`; - out += q(W - R, T - 10, 'end', '全能型 ↗') + q(L, T - 10, 'start', '协作型') + q(W - R, H - 4, 'end', '产出型') + q(L, H - 4, 'start', '轻量参与'); - out += `产出(推送 + 发起 + 合入)→协作(Review + 评论)→`; + const q = (x, y, anchor, label) => `${label}`; + out += q(W - R, T - 10, 'end', tr("全能型 ↗")) + q(L, T - 10, 'start', tr("协作型")) + q(W - R, H - 4, 'end', tr("产出型")) + q(L, H - 4, 'start', tr("轻量参与")); + out += tr("产出(推送 + 发起 + 合入)→协作(Review + 评论)→", (L + W - R) / 2, H - 4, (T + H - B) / 2, (T + H - B) / 2); const placed = []; const nodes = [...points].sort((a, b) => b.r - a.r).map((p) => ({ ...p, cx: X(p.x), cy: Y(p.y), rad: 4 + 12 * Math.sqrt(p.r / maxR) })); let circles = ''; for (const p of nodes) { - circles += ``; + circles += tr("", esc(p.username), p.cx.toFixed(1), p.cy.toFixed(1), p.rad.toFixed(1), p.color, p.color, esc(p.label), fmt(p.x), fmt(p.y), fmt(p.r)); } let labels = ''; const byImportance = [...nodes].sort((a, b) => b.x + b.y - (a.x + a.y)); @@ -319,7 +321,7 @@ export function scatter({ points }) { break; } } - return `${out}${circles}${labels}`; + return tr("{2}{3}{4}", W, H, out, circles, labels); } export function sparkline(values, { w = 96, h = 26, color = 'var(--k-code)', stretch = false } = {}) { @@ -361,7 +363,7 @@ export function monthBars({ months, partial, bands = [], height = 220, color = ' const h = y(0) - y(x.n); const isPartial = x.m === partial; const gap = Math.min(3, bw * 0.25); - out += ``; + out += tr("", (L + i * bw + gap / 2).toFixed(1), y(x.n).toFixed(1), Math.max(1, bw - gap).toFixed(1), Math.max(0, h).toFixed(1), Math.min(3, bw / 4).toFixed(1), gid, isPartial ? 0.35 : 1, x.m, isPartial ? tr("(当月未结束)") : '', fmt(x.n)); }); const placed = []; for (const b of bands) { @@ -380,9 +382,9 @@ export function monthBars({ months, partial, bands = [], height = 220, color = ' months.forEach((x, i) => { if (i % every && i !== n - 1) return; const [yy, mm] = x.m.split('-'); - out += `${mm === '01' || i === 0 ? `${yy.slice(2)}/` : ''}${Number(mm)}月`; + out += tr("{2}{3}月", L + i * bw + bw / 2, H - 6, mm === '01' || i === 0 ? `${yy.slice(2)}/` : '', Number(mm)); }); - return `${out}`; + return tr("{2}", W, H, out); } export function niceMaxPublic(v) { @@ -393,12 +395,12 @@ export function niceMaxPublic(v) { } /** Stacked horizontal share bar. items: [{label, value, color}] */ -export function shareBar(items, { height = 14, label = '占比' } = {}) { +export function shareBar(items, { height = 14, label = tr("占比") } = {}) { const total = items.reduce((s, i) => s + i.value, 0) || 1; - return ``; + .map((i) => tr("", ((100 * i.value) / total).toFixed(2), i.color, esc(i.label), fmt(i.value), ((100 * i.value) / total).toFixed(1))) + .join('')); } // --------------------------------------------------------------------------- @@ -488,7 +490,7 @@ const RISK_BINS = [0.1, 0.2, 0.3, 0.4]; const RISK_LABELS = ['<10%', '10–20%', '20–30%', '30–40%', '≥40%']; export const riskLevel = (ratio) => RISK_BINS.filter((b) => ratio >= b).length; export function riskLegend() { - return ``; + return tr("修 bug 占比 {0}{1}{2}", RISK_LABELS[0], RISK_LABELS.map((l, i) => ``).join(''), RISK_LABELS[4]); } /** @@ -522,7 +524,7 @@ export function mapLayout(blocks, { width, height, value }) { } /** Structure only (frames, tiles, labels); colours, values and tooltips are painted by the caller. */ -export function mapSvg(layout, { blocks, groupLabel, groupValue = fmtK, nameOf, action = 'map-cell', label = '代码地图' }) { +export function mapSvg(layout, { blocks, groupLabel, groupValue = fmtK, nameOf, action = 'map-cell', label = tr("代码地图") }) { const id = nextId('mp'); let frames = ''; const heads = new Set(); diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/i18n.js b/plugins/yujiachen-y/repo-xray/miniapp/client/i18n.js new file mode 100644 index 00000000..8291edb2 --- /dev/null +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/i18n.js @@ -0,0 +1,93 @@ +/** + * Language selection for the Repo X-Ray page. + * + * Chinese stays in the code as the default; this module holds the English for + * every user-visible string and swaps between them. The choice is remembered in + * localStorage, so it survives a reload and the next launch; sessionStorage + * takes over when the browser will not write to localStorage. + */ +import { STRINGS } from './strings.js'; + +const DEFAULT_LANG = 'zh'; +export const STORAGE_KEY = 'rr-lang'; + +function readStored() { + try { + const saved = localStorage.getItem(STORAGE_KEY); + if (saved === 'en' || saved === 'zh') return saved; + } catch {} + try { + const saved = sessionStorage.getItem(STORAGE_KEY); + if (saved === 'en' || saved === 'zh') return saved; + } catch {} + return DEFAULT_LANG; +} + +// Read at module load: the page's own constants call t() while this module is +// still initialising, so the language has to be known before that happens. +let lang = readStored(); + +/** The active language. */ +export const getLang = () => lang; + +function setLang(next) { + lang = next === 'en' ? 'en' : 'zh'; + try { + localStorage.setItem(STORAGE_KEY, lang); + } catch { + try { + sessionStorage.setItem(STORAGE_KEY, lang); + // The old value would shadow the new one on the next load, so drop it. + localStorage.removeItem(STORAGE_KEY); + } catch {} + } + return lang; +} + +/** Switch between the two languages and remember the choice. */ +export function toggleLang() { + return setLang(lang === 'en' ? 'zh' : 'en'); +} + + + +/** BCP 47 tag for dates and numbers, so they follow the interface language. */ +export const localeTag = () => (lang === 'en' ? 'en-US' : 'zh-CN'); + +/** Fill the placeholders in one pass, so a value that looks like one is left alone. */ +function fill(template, args) { + return template.replace(/\{(\d+)\}/g, (whole, i) => (Number(i) < args.length ? String(args[Number(i)]) : whole)); +} + +/** The English for a key; a key with two readings gives the first. */ +const reading = (entry, i) => (Array.isArray(entry) ? entry[i] : entry); + +/** The string for the active language; the key is the Chinese text, {0} placeholders filled in order. */ +export function t(key, ...args) { + return fill(lang === 'en' ? (reading(STRINGS[key], 0) ?? key) : key, args); +} + +/** The second English reading of a Chinese text that needs two; the Chinese is the same. */ +export function tAlt(key, ...args) { + return fill(lang === 'en' ? (reading(STRINGS[key], 1) ?? key) : key, args); +} + +// The history is language-neutral, so two labels that the Node side bakes into +// a name or a path are marked in Chinese and swapped for display. +const MARKERS = { '(令牌)': ' (token)', '(根目录)': ' (root)' }; + +/** A name without the markers the history bakes in, for showing its first letters. */ +export function plainName(s) { + if (typeof s !== 'string') return ''; + let out = s; + for (const zh of Object.keys(MARKERS)) out = out.split(zh).join(''); + return out.trim(); +} + +/** A name or path from the report, with the markers the history bakes in shown in the active language. */ +export function displayText(s) { + if (typeof s !== 'string' || lang === 'zh') return typeof s === 'string' ? s : ''; + let out = s; + for (const [zh, en] of Object.entries(MARKERS)) out = out.split(zh).join(en); + return out; +} diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/index.html b/plugins/yujiachen-y/repo-xray/miniapp/client/index.html index c2360d3b..942ee14a 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/client/index.html +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/index.html @@ -9,34 +9,35 @@ - +
            -
            - + diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/pending.js b/plugins/yujiachen-y/repo-xray/miniapp/client/pending.js new file mode 100644 index 00000000..780c4bf1 --- /dev/null +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/pending.js @@ -0,0 +1,38 @@ +/** + * The queue of repositories whose removal is waiting out its undo window. + * + * The page can be reloaded at any time - the language switch reloads it, and + * the Host may reload it on its own - so the queue is kept in sessionStorage + * as well. Without it, a reload would drop the timer and the queued DELETE, + * and the repository would come back with its cached clone still in place. + */ + +/** Where the queue is kept, for the length of the browser session. */ +export const PENDING_KEY = 'rr-pending-removals'; + +/** How long a queued removal can still be undone. */ +export const UNDO_MS = 8000; + +/** The queue as it is written to storage: a list of { id, until }. */ +export function encodePending(queue) { + return JSON.stringify([...queue].map(([id, entry]) => ({ id, until: entry.until }))); +} + +/** The queue as it is read back from storage; anything unreadable is dropped. */ +export function decodePending(raw) { + let list; + try { + list = JSON.parse(raw || '[]'); + } catch { + return []; + } + if (!Array.isArray(list)) return []; + return list + .filter((item) => item && typeof item.id === 'string' && item.id) + .map((item) => ({ id: item.id, until: Number(item.until) || 0 })); +} + +/** How much of the undo window is left, in milliseconds. */ +export function pendingLeft(until, now = Date.now()) { + return Math.max(0, until - now); +} diff --git a/plugins/yujiachen-y/repo-xray/miniapp/client/strings.js b/plugins/yujiachen-y/repo-xray/miniapp/client/strings.js new file mode 100644 index 00000000..60d0eca8 --- /dev/null +++ b/plugins/yujiachen-y/repo-xray/miniapp/client/strings.js @@ -0,0 +1,586 @@ +/** + * The English for every Chinese string the page shows. + * + * The key is the Chinese text exactly as it reads in the source, with {0}, {1} + * standing in for interpolated values; the value is the English. A key that is + * missing here shows its Chinese text, so an untranslated string falls back + * instead of breaking the page. + */ +export const STRINGS = { + " · 低于 30%": " · below 30%", + " · 偏高": " · high", + " · 单人维护": " · Solo-maintained", + " · 测试": " · Test", + " · 测试同步": " · test sync", + " · 机器人": " · bot", + " · 流程文件": " · Workflow file", + " · 全程 {0}": " · total {0}", + " · 视图外": " · outside this view", + " · 首次加入 {0}": " · First added {0}", + " · 虚线框的柱子是不完整的月份": " · Dashed-outline bars are incomplete months", + " · 也作 {0}": " · Also known as {0}", + " · 已删除": " · Deleted", + " · 用时 {0}": " · took {0}", + " · 用时 {0}": " · took {0}", + " · 报告已可查看": " · Report is viewable", + " 高风险 {0}": " High-risk {0}", + " 机器人": " bot", + " 已删除": " Deleted", + " 等 {0} 个": " ({0} in total)", + " 主题:跟随系统": " Theme: System", + " 主题:浅色": " Theme: Light", + " 主题:深色": " Theme: Dark", + "- 仓库自带的说明({0}):{1}": "- Description from the repository itself ({0}): {1}", + "- 常一起改:{0}": "- Often changed together: {0}", + "- 修改 {0} 次,其中修 bug {1};最近一次修改 {2}": "- {0} changes, bug fixes {1}; last change {2}", + "- 主要负责人:{0}": "- Main owners: {0}", + "- 最常改的文件:{0}": "- Most-changed files: {0}", + ",": ", ", + ",不含机器人": ", excluding bots", + ",含 {0} 个高风险文件": ", contains high-risk files ({0})", + ",平均每个文件 {0} 次": ", {0} changes per file on average", + ",其次是{0}({1})": ", then {0} ({1})", + ",提交最多的是 {0}": ", most commits by {0}", + ",显示最近 {0} 条": "; showing the latest {0}", + ",占{0}的 {1}": ", {1} of {0}", + ",止于 {0}": ", ending {0}", + "、": ", ", + ";": "; ", + ";{0} 尚未结束,浅色显示": "; {0} has not finished, shown faded", + "“A 常和 B 一起改”指改了 A 的提交里,同时也改了 B 的比例。这个比例有方向,A→B 和 B→A 可能不同(code-maat 用两边提交数的平均值做分母)。只统计所选时间范围内的非合并提交,超过 {0} 个文件的大提交不计。门槛沿用 code-maat 的默认值:两边各至少 {1} 个提交、一起改过至少 {2} 次、比例 ≥{3}%。changelog、lock 文件这类几乎随每次修改一起改的流程文件单独列出,不画线;测试目录和同一个包里的代码一起改,标为“测试同步”。": "\"A is often changed with B\" means the share of commits that changed A and also changed B. The ratio is directional — A→B and B→A can differ (code-maat uses the average of both sides' commit counts as the denominator). Only non-merge commits in the selected time range count; commits touching more than {0} files are excluded. Thresholds follow code-maat defaults: at least {1} commits on each side, changed together at least {2} times, ratio ≥{3}%. Workflow files such as changelogs and lock files, which change with almost every edit, are listed separately and not drawn as lines; test directories changed together with code in the same package are marked \"test sync\".", + "({0} 个文件)": "({0} files)", + "({0})": "({0})", + "(当月未结束)": " (month not finished)", + "(无)": "(none)", + "(主要是 {0})": " (mainly {0})", + "{0}\n
            \n
            \n
            非合并提交
            {1}
            \n
            修 bug
            {2}
            \n
            合并提交
            {3}
            \n
            \n

            每月提交

            {4}
            \n

            改得最多的文件

              {5}
            \n

            最近提交

              {6}
            \n
            ": "{0}\n
            \n
            \n
            Non-merge commits
            {1}
            \n
            Bug fixes
            {2}
            \n
            Merge commits
            {3}
            \n
            \n

            Commits per month

            {4}
            \n

            Most-changed files

              {5}
            \n

            Latest commits

              {6}
            \n
            ", + "{0}\n
            \n
            {1}
            \n
            \n
            全部修改
            {2}
            \n
            修 bug 的提交
            {3}
            \n
            维护者
            {4}
            \n
            \n

            每月修改次数

            {5}
            \n

            维护者 等同 git shortlog -sn -- <file>{6}

            \n
              {7}
            \n {8}\n

            最近 {9} 次修改

              {10}
            \n
            ": "{0}\n
            \n
            {1}
            \n
            \n
            All changes
            {2}
            \n
            Bug-fix commits
            {3}
            \n
            Maintainers
            {4}
            \n
            \n

            Changes per month

            {5}
            \n

            Maintainers Same as git shortlog -sn -- <file>{6}

            \n
              {7}
            \n {8}\n

            Latest {9} changes

              {10}
            \n
            ", + "{0}\n
              {1}
            \n
            {2}
            ": "{0}\n
              {1}
            \n
            {2}
            ", + "{0} – {1} 共 {2}{3}": "{0} – {1} {2} total{3}", + "{0} · {1} 个区域": "{0} · {1} areas", + "{0} · 全部 {1}": "{0} · total {1}", + "{0} {1}": "{0} {1}", + "{0} / {1}{2}": "{0} / {1}{2}", + "{0} → {1}{2}{3}{4}": "{0} → {1}{2}{3}{4}", + "{0} 次": "{0} changes", + "{0} 次修改{1}": "{0} changes{1}", + "{0} 的历史提交来自近 3 个月不再提交的人": "{0} of historical commits are from people who no longer commit (none in the last 3 months)", + "{0} 的历史提交来自近 3 个月没有提交的人{1}": "{0} of historical commits are from people with no commits in the last 3 months{1}", + "{0} 分钟前": "{0} min ago", + "{0} 个提交{1}": "{0} commits{1}", + "{0} 个文件": "{0} files", + "{0} 个文件,": "{0} files, ", + "{0} 个月,结构不动、颜色逐月变化": "{0} months; structure stays put, colours change month by month", + "{0} 个月前": "{0} mo ago", + "{0} 年前": "{0} y ago", + "{0} 起": "{0} onward", + "{0} 天前": "{0} d ago", + "{0} 项": "{0} items", + "{0} 小时前": "{0} h ago", + "{0},{1} 个文件,窗口内修改 {2} 次,打开代码地图": "{0}, {1} files, {2} changes in the window, open the Code Map", + "{0},{1}{2}{3}": "{0}, {1}{2}{3}", + "{0}:修改 {1} 次,修 bug {2} 次{3}": "{0}: {1} changes, bug fixes × {2}{3}", + "{0}. {1}(热点 #{2},修 bug {3}/{4} 次,主要负责人 {5})": "{0}. {1}(Hotspot #{2}, bug fixes × {3}/{4}, main owner {5})", + "{0}。": "{0}.", + "{0}({1} 次)": "{0} ({1} changes)", + "{0}({1})": "{0}({1})", + "{0}(改这里的提交里 {1} 也改了它)": "{0}({1} of commits that changed this also changed it)", + "{0}(若本地没有 checkout,请先 clone)": "{0} (if there is no local checkout, clone it first)", + "{0}{1}": "{0}{1}", + "{0}{1}\n
            \n
            \n

            主要问题

            由提交历史上的确定性规则得出,点击进入对应分区
            \n {2}\n
            \n
            \n

            建议

            对应 skill 报告的 Recommendations
            \n {3}\n
            \n
            \n

            代码地图 {4}

            {5}
            {6}{7}
            \n {8}\n
            \n
            \n

            高风险文件

            前 5 个,按热点排名
            {9}
            \n {10}\n
            \n
            \n

            主要贡献者

            非合并提交占比
            {11}
            \n {12}\n
              {13}
            \n
            \n
            \n

            提交节奏 {15}

            近 12 个月
            {16}
            \n {17}\n
            \n
            \n

            技术栈

            {18}
            {19}
            \n {20}\n
            \n
            ": "{0}{1}\n
            \n
            \n

            Main problems

            From deterministic rules over the commit history; click to open the matching section
            \n {2}\n
            \n
            \n

            Recommendations

            Matches the Recommendations in the skill report
            \n {3}\n
            \n
            \n

            Code Map {4}

            {5}
            {6}{7}
            \n {8}\n
            \n
            \n

            High-Risk Files

            Top 5, by hotspot rank
            {9}
            \n {10}\n
            \n
            \n

            Top contributors

            Share of non-merge commits
            {11}
            \n {12}\n
              {13}
            \n
            \n
            \n

            Commit Rhythm {15}

            Last 12 months
            {16}
            \n {17}\n
            \n
            \n

            Tech Stack

            {18}
            {19}
            \n {20}\n
            \n
            ", + "{0}{1} 次修改": "{0}{1} changes", + "{0}{1}{2}": "{0}{1}{2}", + "{0}{1}{2}{3} · 仓库透视": "{0}{1}{2}{3} · Repo X-Ray", + "{0}\n{1} 个文件 · 窗口内修改 {2} 次{3}\n点击:在代码地图中打开": "{0}\n{1} files · {2} changes{3}\nClick: open in the Code Map", + "{0}
            \n

            提交节奏 {2} {3}

            每月提交数(含合并提交)。虚线是近 3 个月和之前 3 个月的月均{4}
            \n
            \n
            {7}
            \n
            \n
            \n

            救火记录 {8}

            窗口内 {9} 次,占 {10}{11}
            \n
            {12}
            \n {13}\n
            ": "{0}
            \n

            Commit Rhythm {2} {3}

            Commits per month (including merges). Dashed lines are the monthly averages for the last 3 months and the 3 months before{4}
            \n
            \n
            {7}
            \n
            \n
            \n

            Firefighting log {8}

            In the window: {9}, {10}{11}
            \n
            {12}
            \n {13}\n
            ", + "{0}人": "{0} people", + "{0}{1}": "{0}{1}", + "{0}的提交:{1}": "{0} commits: {1}", + "{0}共 {1} 次提交,没有人超过 25%:{2}": "{0}: {1} commits, no one over 25%: {2}", + "{0}还有人改": "Still changed {0}", + "{0}汇总": "{0} summary", + "{0}汇总 · {1} 次修改": "{0} summary · {1} changes", + "{0}没有人修改": "{0}: no one changed this", + "{0}没有修改": "{0}: no changes", + "{0}提交最多:{1}": "{0}: most commits by {1}", + "{0}修改 {1} 次,其中修 bug {2} 次({3})": "{0}: {1} changes, bug fixes × {2} ({3})", + "{0}修改 {1} 次,太少,不计算占比": "{0}: {1} changes — too few to compute a share", + "{0}修改 {1} 次{2}": "{0}: {1} changes{2}", + "{0}这里没有修改": "{0}: no changes here", + "{0}只有 {1} 个相关提交,还看不出稳定的关系。": "{0}: only {1} related commits — no stable link yet.", + "\n含 {0} 个高风险文件": "\ncontains high-risk files ({0})", + "{2}{3}": "{2}{3}", + "{2}{3}": "{2}{3}", + "{1}网页": "{1}Web", + "{1}查看文件历史": "{1}View file history", + "{1}进入这块": "{1}Open this block", + "{1}返回上一层": "{1}Up a level", + "回到根目录": "Back to root", + "{1}打开网页": "{1}Open web page", + "{1}{2}": "{1}{2}", + "{2}": "{2}", + "{0}{1} 个 commit": "{0}{1} commits", + "": "", + "\n \n ": "\n \n ", + "": "", + "": "", + "\n
            {1}
            \n
            \n
            \n \n {4}{5}": "\n
            {1}
            \n
            \n
            \n \n {4}{5}", + "": "", + "": "", + "": "", + "": "", + "": "", + "峰值 {4}": "Peak {4}", + "": "", + "
            {0},下面显示的是上一次的结果。
            ": "
            {0}; showing the previous result below.
            ", + "
            加载失败:{0}
            ": "
            Failed to load: {0}
            ", + "
            {0}自上次分析({1},{2})以来:{3}
            ": "
            {0}Since the last analysis ({1}, {2}): {3}
            ", + "
            {0}{1}
            ": "
            {0}{1}
            ", + "

            键盘快捷键

            \n
            \n {1}\n {2}\n {3}\n {4}\n {5}\n {6}\n
            \n

            代码地图

            \n
            \n {7}\n {8}\n {9}\n {10}\n
            ": "

            Keyboard shortcuts

            \n
            \n {1}\n {2}\n {3}\n {4}\n {5}\n {6}\n
            \n

            Code Map

            \n
            \n {7}\n {8}\n {9}\n {10}\n
            ", + "

            设置

            \n
            \n

            凭据

            默认复用本机 gh / glab 的登录;令牌只保存在这个 Mini App 的数据目录里,不会发送到页面,也不会写进仓库配置。

            \n
              {1}
            \n
            \n

            为某个主机填写访问令牌

            \n
            \n
            \n
            \n
            \n

            本机仓库扫描目录

            \n
            \n
            \n
            \n
            \n

            网络代理

            \n
            \n 当前:{4}
            \n
            \n
            \n
            ": "

            Settings

            \n
            \n

            Credentials

            By default this reuses your local gh / glab login. Tokens are stored only in this Mini App's data directory; they are never sent to the page or written into repository config.

            \n
              {1}
            \n
            \n

            Enter an access token for a host

            \n
            \n
            \n
            \n
            \n

            Local repository scan directories

            \n
            \n
            \n
            \n
            \n

            Network proxy

            \n
            \n Current: {4}
            \n
            \n
            \n
            ", + "
            排名 #{0} / {1}占 {2}{3}
            ": "
            Rank #{0} / {1}{2} share{3}
            ", + "
            {0}

            {1}

            {2}

            ": "
            {0}

            {1}

            {2}

            ", + "
            {0}

            代码地图加载失败

            {1}

            {2}

            ": "
            {0}

            Code Map failed to load

            {1}

            {2}

            ", + "
            {0}

            没有文件同时出现在两个榜单里

            No files appear in both lists — good sign.

            ": "
            {0}

            Nothing in both lists

            No files appear in both lists — good sign.

            ", + "
            {0}

            分析失败

            {1}

            ": "
            {0}

            Analysis failed

            {1}

            ", + "
            {0}等待空闲的网络通道…{1}
            ": "
            {0}Waiting for a free network slot…{1}
            ", + "
            {0}
            {1}{2}{3}

            {4}

            {5}
            \n {6}\n

            {7}

            \n \n
            {8}{9}{10}{11}
            \n {12}\n

            负责人 {13},按提交数

            {14}{15}
            \n

            最常改的文件 {16}

            {17}
            \n

            常和{18}一起改 {19}

            {20}{21}
            \n
            {22}
            ": "
            {0}
            {1}{2}{3}

            {4}

            {5}
            \n {6}\n

            {7}

            \n \n
            {8}{9}{10}{11}
            \n {12}\n

            Owner {13}, by commits

            {14}{15}
            \n

            Most-changed files {16}

            {17}
            \n

            Often changed with {18} {19}

            {20}{21}
            \n
            {22}
            ", + "
            {0} → {1}{2} commits{3} 个分支{4} 个文件{5} · 窗口 {6} · Top {7}
            ": "
            {0} → {1}Commits: {2}Branches: {3}Files: {4}{5} · Window: {6} · Top {7}
            ", + "
            \n
            {0}Esc
            \n
              \n
              ↑↓ 选择↵ 打开Esc 关闭
              ": "
              \n
              {0}Esc
              \n
                \n
                ↑↓ Select↵ OpenEsc Close
                ", + "
                {0}

                {1}{2}

                ": "
                {0}

                {1}{2}

                ", + "
                {2}
                ": "
                {2}
                ", + "
                \n {0}
                高风险文件
                文件热点修改次数磁铁修 bug主要负责人其他维护者操作
                ": "
                \n {0}
                High-Risk Files
                FileHotspotChangesMagnetBug fixesMain ownerOther maintainersActions
                ", + "

                其他常用依赖(未归类,按被多少个 manifest 引用排序)

                {0}
                ": "

                Other common dependencies (uncategorized, sorted by how many manifests reference them)

                {0}
                ", + "

                包管理

                {0}
                ": "

                Package managers

                {0}
                ", + "
                xray {0}
                ": "
                xray {0}
                ", + "
                也作 {0}
                ": "
                Also known as {0}
                ", + "
                {0}
                {1}
                {2} 的修改{3}
                ": "
                {0}
                {1}
                {2} of the changes{3}
                ", + "
                {0}{1}{2} 个文件 · 窗口内修改 {3} 次 · {4} 块
                ": "
                {0}{1}{2} files · {3} changes in window · {4} blocks
                ", + "
                ": "
                ", + "
                \n HEAD {0}\n 算法 v{1}\n 口径 {2}\n 解析 {3} commits{4}{5}\n 生成于 {6}\n ⌘K 搜索 · ? 快捷键\n
                ": "
                \n HEAD {0}\n Algorithm v{1}\n Identity {2}\n Parsed commits: {3}{4}{5}\n Generated {6}\n ⌘K Search · ? Shortcuts\n
                ", + "
                \n ❯\n
                \n
                \n \n
                \n
                ": "
                \n ❯\n
                \n
                \n \n
                \n
                ", + "": "", + "

                常一起改的文件 全部历史上改它的 {0} 个提交里,同时也改了这些文件的比例(不含合并提交和超过 {1} 个文件的大提交)

                ": "

                Files often changed together Of the {0} commits that changed it across all history, the share that also changed these files (excluding merge commits and large commits touching more than {1} files)

                ", + "
                \n
                \n

                {0}{1}{2}

                \n
                \n {4}\n {5}\n {6}\n {8}\n
                \n {9}\n
                \n
                \n {10}\n {11}\n \n \n
                \n
                \n
                ": "
                \n
                \n

                {0}{1}{2}

                \n
                \n {4}\n {5}\n {6}\n {8}\n
                \n {9}\n
                \n
                \n {10}\n {11}\n \n \n
                \n
                \n
                ", + "↵ / 双击": "↵ / double-click", + "Space / 单击": "Space / click", + "
              • ": "
              • ", + "
              • 还没有分析过仓库
              • ": "
              • No repositories analyzed yet
              • ", + "
              • 分析远程仓库后,这里会列出用到的主机。
              • ": "
              • After you analyze a remote repository, the hosts used appear here.
              • ", + "
              • {0}%{1}→{2}{3}{4} 次{5}
              • ": "
              • {0}%{1}→{2}{3}{4} times{5}
              • ", + "
              • 没有匹配的结果
              • ": "
              • No matching results
              • ", + "
              • 搜索中…
              • ": "
              • Searching…
              • ", + "
              • {0}
                {1}
                {2}
              • ": "
              • {0}
                {1}
                {2}
              • ", + "
              • {0}{1}
              • ": "
              • {0}{1}
              • ", + "
              • {0}%{1}{2} 次{3}{4}
              • ": "
              • {0}%{1}{2} times{3}{4}
              • ", + "
              • {0}%{1}{2}{3} 次{4}{5}
              • ": "
              • {0}%{1}{2}{3} times{4}{5}
              • ", + "
              • {0}{1}{2}{5}
              • ": "
              • {0}{1}{2}{5}
              • ", + "
              • {0}{1}{2}{4}{5}
              • ": "
              • {0}{1}{2}{4}{5}
              • ", + "
              • {0}{1}{2}{4}/{5}
              • ": "
              • {0}{1}{2}{4}/{5}
              • ", + "": "", + "
                  {0}
                ": "
                  {0}
                ", + "
                  {0}
                ": "
                  {0}
                ", + "

                改{0}的 {1} 个提交里(不含超过 {2} 个文件的大提交):

                  {3}
                ": "

                Commits that changed {0} — {1} in total (excluding large commits touching more than {2} files):

                  {3}
                ", + "

                这一层里最强的关系(改左边的提交里,有多少也改了右边):

                  {0}
                ": "

                Strongest links at this level (of the commits that changed the left side, how many also changed the right):

                  {0}
                ", + "

                知识流失 {0}:{1} 写过这里的大量提交,但近 3 个月没有任何提交。

                ": "

                Knowledge loss {0}: {1} wrote much of the history here but have had no commits in the last 3 months.

                ", + "

                共识别到 {0} 个 package.json。

                ": "

                {0} package.json files detected.

                ", + "

                {0} 没有文件同时出现在两个榜单里。

                ": "

                {0} No files appear in both lists.

                ", + "

                {0}

                ": "

                {0}

                ", + "

                {0}没有人修改。

                ": "

                {0}: no one changed this.

                ", + "

                {0}没有修改。

                ": "

                No changes in {0}.

                ", + "

                窗口内没有救火类提交。

                ": "

                No firefighting commits in this window.

                ", + "

                窗口内没有数据。

                ": "

                No data in this window.

                ", + "

                窗口内没有新增文件。

                ": "

                No files added in this window.

                ", + "

                另外 {0} 几乎随每次修改一起改(流程文件),没有列出。

                ": "

                Also: {0} change with almost every edit (workflow files) and are not listed.

                ", + "

                没有达到门槛(一起改过至少 {0} 次、占比 ≥{1})的文件。下面是一起改过 3 次以上的,仅供参考:

                ": "

                No files meet the threshold (changed together at least {0} times, share ≥{1}). Below are those changed together 3 or more times, for reference only:

                ", + "

                没有符合筛选条件的文件。

                ": "

                No files match this filter.

                ", + "

                没有可显示的区域。

                ": "

                No areas to show.

                ", + "

                没有区域。

                ": "

                No areas.

                ", + "

                没有识别到代码文件。

                ": "

                No code files detected.

                ", + "

                没有在常用目录里找到 git 仓库。可以在设置里添加扫描目录,或直接在上面输入路径。

                ": "

                No git repositories found under the usual directories. Add scan directories in Settings, or enter a path above.

                ", + "": "", + "": "", + "": "", + "": "", + "
                \n

                提交日历 {0}

                近 365 天,共 {1} 个 commit;颜色越深当天提交越多
                {2}
                \n
                {3}
                \n
                \n
                {4} / {5}
                有提交的天数
                \n
                {6} 天
                最长连续{7}
                \n
                {8}
                单日最多{9}
                \n
                {10}
                周末提交占比
                \n
                \n
                ": "
                \n

                Commit calendar {0}

                Last 365 days; {1} commits; darker means more commits that day
                {2}
                \n
                {3}
                \n
                \n
                {4} / {5}
                Days with commits
                \n
                {6} days
                Longest streak{7}
                \n
                {8}
                Most in one day{9}
                \n
                {10}
                Weekend commit share
                \n
                \n
                ", + "
                \n

                贡献者排名 {0}

                按全部历史的非合并提交数排序,共 {1} 人;近 3 个月活跃 {2} 人{3}
                \n
                \n
                \n \n \n
                \n
                \n {7}\n
                {8}
                \n
                \n {9}": "
                \n

                Contributor ranking {0}

                Ranked by non-merge commits across all history, {1} people; active in the last 3 months: {2}{3}
                \n
                \n
                \n \n \n
                \n
                \n {7}\n
                {8}
                \n
                \n {9}", + "
                \n

                高风险文件 {0}

                同时出现在代码热点和 bug 磁铁里的文件;负责人按全部历史中改动它的非合并提交计算{1}
                \n
                {2}
                \n {3}\n
                \n
                \n

                代码热点

                窗口内被修改次数最多的文件,红底表示同时是 bug 磁铁
                {4}
                \n

                Bug 磁铁

                提交说明含 fix / bug / broken 的提交最常改动的文件
                {5}
                \n

                新增文件

                窗口内新增 {6} 个文件,按目录看哪里在长新代码
                {7}
                \n
                ": "
                \n

                High-Risk Files {0}

                Files in both Code Hotspots and Bug Magnets; owners are computed from non-merge commits that touched the file across all history{1}
                \n
                {2}
                \n {3}\n
                \n
                \n

                Code Hotspots

                Files changed most in the window; a red background also marks Bug Magnets
                {4}
                \n

                Bug Magnets

                Files most often changed by commits whose commit message mentions fix / bug / broken
                {5}
                \n

                New files

                {6} files added in the window, by directory — where new code is growing
                {7}
                \n
                ", + "
                \n

                技术栈

                语言按 HEAD 中的文件数统计;框架和工具来自 {0} 个 manifest 与配置文件,悬停或聚焦可看依据
                \n {1}\n
                  {2}
                \n
                {3}{4}{5}
                \n {6}\n
                ": "
                \n

                Tech Stack

                Languages by file count at HEAD; frameworks and tools come from {0} manifests and config files — hover or focus for the evidence
                \n {1}\n
                  {2}
                \n
                {3}{4}{5}
                \n {6}\n
                ", + "

                机器人与令牌账号

                按名字和邮箱识别(如 [bot]、project_*_bot、agent 账号),不参与排名、活跃比例和负责人计算;切到“原始口径”可看 skill 的原始结果
                \n
                {0}
                ": "

                Bots and token accounts

                Identified by name and email (e.g. [bot], project_*_bot, agent accounts); excluded from ranking, active ratio and owner calculations. Switch to Raw to see the skill's raw result
                \n
                {0}
                ", + "

                正在识别技术栈…

                ": "

                Detecting tech stack…

                ", + "
                {0}
                ": "
                {0}
                ", + "
                \n
                \n

                代码地图 {0}

                \n
                {2}{3}
                \n
                \n
                {4}
                \n
                \n
                \n
                \n
                \n
                \n

                \n
                \n \n
                \n
                \n

                区域列表

                与地图同一批区域,可排序;点击区域名在地图上选中
                \n
                \n
                \n
                ": "
                \n
                \n

                Code Map {0}

                \n
                {2}{3}
                \n
                \n
                {4}
                \n
                \n
                \n
                \n
                \n
                \n

                \n
                \n \n
                \n
                \n

                Area list

                The same areas as the map, sortable; click an area name to select it on the map
                \n
                \n
                \n
                ", + "

                包含的 {0} 项

                  {1}
                ": "

                {0} items included

                  {1}
                ", + "
                \n
                \n \"\"\n

                读代码之前,先看一遍它的 git 历史

                \n

                找出最常被改、最常出 bug 的文件,谁在维护它们,项目节奏是升是降,以及它用了哪些技术。指标定义和 codebase-recon skill 保持一致,全部在本机计算。

                \n
                \n
                \n
                repo-xray — 新的分析只读 · 不修改仓库
                \n {0}\n
                试试{1}
                \n
                \n
                {2}
                \n
                \n

                本机仓库

                只读扫描常用目录下的 git 仓库,按最近活动排序;扫描目录可在设置里修改
                \n
                \n {4}\n
                \n
                ": "
                \n
                \n \"\"\n

                Before you read the code, take a look at its git history

                \n

                Find the files that change most and break most, who maintains them, whether the project's pace is rising or falling, and what it is built with. Metric definitions match the codebase-recon skill, and everything is computed locally.

                \n
                \n
                \n
                repo-xray — New analysisRead-only · Repository untouched
                \n {0}\n
                Try{1}
                \n
                \n
                {2}
                \n
                \n

                Local repositories

                Read-only scan of git repositories under the usual directories, sorted by recent activity; scan directories can be changed in Settings
                \n
                \n {4}\n
                \n
                ", + "
                {0}{1}
                  {3}
                ": "
                {0}{1}
                  {3}
                ", + "
                {0}

                {1}

                ": "
                {0}

                {1}

                ", + "\n \n {4}\n {5}\n ": "\n \n {4}\n {5}\n ", + "少 {0} 多": "Less {0} More", + "修 bug 占比 {0}{1}{2}": "Bug-fix share {0}{1}{2}", + "≤{0} / ≤{1} / ≤{2} / >{3} 次": "≤{0} / ≤{1} / ≤{2} / >{3} changes", + "暂无": "None", + "合并在一起的小项": "Small items merged together", + "含高风险文件": "Contains high-risk files", + "合并的小目录": "Small directories merged", + "含高风险文件": "Contains high-risk files", + "{0} {1} 多{2}": "{0} {1} More{2}", + " 上次分析 {0}": " Last analyzed {0}", + "高风险": "High-risk", + "不在窗口内的 Top 榜单": "Not in the window Top lists", + "热点 #{0} / {1}": "Hotspot #{0} / {1}", + "Bug 磁铁 #{0}": "Bug Magnets #{0}", + " 正在分析…": " Analyzing…", + "近 3 个月无提交": "No commits in the last 3 months", + "近 3 月无提交": "No commits in last 3 months", + "活跃": "Active", + "近 3 个月活跃": "Active in the last 3 months", + "没有明显的趋势风险": "No obvious trend risk", + "新增 ": "Added ", + "已分析": "Analyzed", + "救火 ": "Firefighting ", + "本地仓库 · 分析当前 HEAD,不 fetch": "Local repository · Analyzes current HEAD, no fetch", + "删除 ": "Deleted ", + "已删除": "Deleted", + "已在 HEAD 中删除或改名": "Deleted or renamed at HEAD", + "高风险文件 {2}": "High-Risk Files {2}", + "分析失败": "Analysis failed", + "{1}{2}": "{1}{2}", + "分析中": "Analyzing", + "尚未分析": "Not analyzed yet", + "{0}{1}{2} 的修改负责 {3}": "{0}{1}{2} of the changesOwns {3}", + "": "", + "复制路径": "Copy path", + "网页": "Web", + "{2}": "{2}", + "{2}{3}{4}": "{2}{3}{4}", + "{3}{4}{5}{6}{7}{8}{9}": "{3}{4}{5}{6}{7}{8}{9}", + "{5}": "{5}", + "{0}{1}{2}": "{0}{1}{2}", + "\n {0}
                贡献者排名
                #贡献者提交数占比窗口内修 bug近 12 个月首次 → 最近状态主要目录
                {1}": "\n {0}
                Contributor ranking
                #ContributorsCommitsShareIn windowBug fixesLast 12 monthsFirst → LastStatusTop directories
                {1}", + "{0}{1}
                代码地图的区域列表
                ": "{0}{1}
                Code Map area list
                ", + "{2}{3}月": "{2}{3}", + "{2}时": "{2}:00", + "{2}月": "{2}", + "产出(推送 + 发起 + 合入)→协作(Review + 评论)→": "Output (pushes + opened + merged) →Collaboration (reviews + comments) →", + "{1}月": "{1}", + "{4}{5}\n {6}{7}{8}\n {9}\n {10}{11}{12}": "{4}{5}\n {6}{7}{8}\n {9}\n {10}{11}{12}", + "\n {0}{1}\n #{2}\n
                {4}
                \n {5}{6}\n {7}\n {8}\n {9}": "\n {0}{1}\n #{2}\n
                {4}
                \n {5}{6}\n {7}\n {8}\n {9}", + "{0}\n
                {1}
                {2}{3}
                \n
                {6}
                \n {7}{8}{9}\n {10}\n {11} → {12}\n {13}\n {15}": "{0}\n
                {1}
                {2}{3}
                \n
                {6}
                \n {7}{8}{9}\n {10}\n {11} → {12}\n {13}\n {15}", + "没有匹配的贡献者": "No matching contributors", + "
                  \n
                • 先读{0}
                • \n
                • 找谁聊{1}
                • \n
                • 注意{2}
                • \n
                • 继续
                • \n
                ": "
                  \n
                • Start reading{0}
                • \n
                • Talk to{1}
                • \n
                • Watch out{2}
                • \n
                • Next
                • \n
                ", + "
                  {0}
                ": "
                  {0}
                ", + "> 由仓库透视(Repo X-Ray)生成于 {0},HEAD `{1}`({2}),身份口径:{3}": "> Generated by Repo X-Ray {0}, HEAD `{1}` ({2}), Identity mode: {3}", + "1 个月内": "Within 1 month", + "1 年内": "Within 1 year", + "1 周内": "Within 1 week", + "12 个月": "12 months", + "3 个月": "3 months", + "3 个月内": "Within 3 months", + "6 个月": "6 months", + "按 HEAD 中的扩展名归类:颜色是占比最多的一类,块底部的细条是构成。没有说明的目录,可以靠它判断是代码、文档还是资源。": "Grouped by extension at HEAD: colour is the largest type, and the thin strip at the bottom of a block is its makeup. For directories without a description, use this to tell code from docs or assets.", + "按 skill 的规则给仓库分档:<500 个 commit 看全部历史,500–10k 看 1 年,>10k 看 6 个月。": "Tier the repository by the skill rules: <500 commits look at all history, 500–10k look at 1 year, >10k look at 6 months.", + "按非合并提交数从高到低累加,达到总数一半时的人数。数字越小,知识越集中。": "Accumulate non-merge commits from highest to lowest; the number of people it takes to reach half the total. Smaller means knowledge is more concentrated.", + "按文件数": "By file count", + "地址格式不对": "Invalid address format", + "按修改次数": "By changes", + "把 HEAD 的目录树画成方块。面积默认是文件数,可以切换成所选时间范围内的修改次数;颜色按上方选择的视角。大目录逐层展开,小于 0.5% 的子项合并成“其他 N 项”。已删除文件的修改,算到它最深的、仍然存在的目录上。时间范围从今天往前算;仓库已经停更时,从最后一次提交往前算。": "Draw the HEAD directory tree as blocks. Area is file count by default and can switch to changes in the selected time range; colour follows the lens chosen above. Large directories expand level by level; children under 0.5% merge into \"Other N items\". Changes to deleted files count toward their deepest directory that still exists. Time ranges count back from today; for a repository that has stopped, they count back from the last commit.", + "报告已复制": "Report copied", + "本层": "This level", + "本地仓库 · {0}": "Local repository · {0}", + "本地仓库 {0}": "the local repository {0}", + "本地路径:{0}{1}": "Local path: {0}{1}", + "本月提交最多 {0}": "Most commits this month: {0}", + "比较最近 3 个完整月和之前 3 个月的月均提交数:高 20% 以上为上升,低 20% 以上为下降;环比平均波动超过 50% 为波动。当月未结束不计入。": "Compare average monthly commits over the last 3 complete months with the 3 months before: more than 20% higher is rising, more than 20% lower is declining; average month-over-month swing over 50% is erratic. The current unfinished month is excluded.", + "波动": "erratic", + "播放时会改为按文件数排布,让布局保持不动": "During playback the layout switches to file count so it stays put", + "不在统计范围内": "Out of range", + "仓库": "Repositories", + "仓库根目录": "repository root", + "仓库透视": "Repo X-Ray", + "仓库透视的数据({0},HEAD {1}):": "Repo X-Ray data ({0}, HEAD {1}): ", + "操作": "Actions", + "测试": "Testing", + "查看全部": "View all", + "产出型": "Producer", + "撤销": "Undo", + "窗口内标题含 revert / hotfix / emergency / rollback 的提交占比,≥5% 判为偏高(skill 未给阈值)。": "Share of commits in the window whose subject contains revert / hotfix / emergency / rollback; ≥5% counts as high (the skill gives no threshold).", + "窗口内改得最多的文件": "Files changed most in the window", + "窗口内提交": "Commits in window", + "次": " changes", + "从未": "never", + "打开代码地图": "Open Code Map", + "打开设置": "Open settings", + "大型": "Large", + "代码地图": "Code Map", + "代码地图 {0}": "Code Map {0}", + "代码地图:{0},{1} 个区域。方向键在区域间移动,空格或单击选中,回车或双击进入": "Code Map: {0}, {1} areas. Arrow keys move between areas, Space or click selects, Enter or double-click opens", + "代码地图缩略图:点任意一块,在代码地图里打开": "Code Map thumbnail: click any block to open it in the Code Map", + "代码热点": "Code Hotspots", + "代码质量": "Code Quality", + "单击选中 · 双击或回车进入 · Backspace 返回上一层 · 方向键移动": "Click to select · Double-click or Enter to open · Backspace goes up a level · Arrow keys move", + "单人维护 {0}": "Solo-maintained {0}", + "当前环境不支持直接发到对话,已复制到剪贴板": "This environment cannot send to the chat directly; copied to the clipboard", + "当前目录": "Current directory", + "当前为“合并身份”口径:大小写不同的同名账号与同邮箱账号视为一人,机器人不计入。": "Currently merged identities: same-name accounts differing only in case and same-email accounts count as one person; bots are not counted.", + "当前为原始口径,与 shortlog 完全一致。": "Currently raw identities, exactly matching shortlog.", + "当天": "Same day", + "当月 ": "This month: ", + "当月少": "Less this month", + "地址格式": "Invalid address", + "第一名占 {0}": "Top contributor has {0}", + "多人共有": "Shared", + "多人共有 / 无人修改": "Shared / no one changed this", + "二": "Tu", + "发到对话…": "Send to chat…", + "返回上一层(浏览器后退也可以)": "Up a level (browser Back also works)", + "分析": "Analyzing", + "分析窗口内": "In the analysis window", + "分析失败": "Analysis failed", + "分析提交历史": "Analyzing commit history", + "分析完成{0}": "Analysis complete{0}", + "分析新仓库": "Analyze a new repository", + "分析新仓库…": "Analyze a new repository…", + "分析中… ": "Analyzing… ", + "风险文件": "Risk Files", + "负责人": "Owner", + "复制 Markdown 报告": "Copy Markdown report", + "改选中区域的提交里 {0} 也改了这里({1} 次)": "{0} of commits that changed the selected area also changed this ({1} times)", + "概览": "Overview", + "刚刚": "just now", + "高风险文件": "High-Risk Files", + "高风险文件(热点 ∩ bug 磁铁):": "High-risk files (hotspots ∩ bug magnets):", + "高风险新增 {0}{1}": "New high-risk {0}{1}", + "个 commit": "commits", + "个文件": " files", + "根目录": "Root", + "更早": "Earlier", + "工程实践": "Engineering Practices", + "工具库": "Libraries", + "贡献者": "Contributors", + "构成:{0}": "Makeup: {0}", + "构建工具": "Build Tools", + "构建与部署": "Build & Deployment", + "关闭抽屉、弹层和菜单;在代码地图上取消选择": "Close drawer, popover and menu; on the Code Map, clear the selection", + "含 {0} 个高风险文件": "contains high-risk files ({0})", + "合并的小项": "Merged small items", + "合并身份": "Merged identities", + "合并身份,机器人除外": "Merged identities, bots excluded", + "后端": "Backend", + "活动热力图": "Activity heatmap", + "活跃贡献者": "Active contributors", + "技术栈": "Tech Stack", + "继续播放": "Resume", + "将分析:{0}": "Will analyze: {0}", + "脚本": "Scripts", + "接口定义": "API Definitions", + "节奏 {0} → {1}": "Rhythm {0} → {1}", + "节奏与救火": "Rhythm & Firefighting", + "结果未知,请先检查对话输入框再重试": "Result unknown — check the chat input before retrying", + "截至 {0}": "through {0}", + "今天": "today", + "近 1 年": "Last year", + "近 12 个月": "Last 12 months", + "近 12 个月每月提交数\n{0}": "Commits per month, last 12 months\n{0}", + "近 3 个月": "Last 3 months", + "近 3 个月 · {0}{1}": "Last 3 months · {0}{1}", + "近 3 个月有非合并提交的人数 / 历史总人数,低于 30% 时告警。{0}": "People with non-merge commits in the last 3 months / total people in history; warns below 30%. {0}", + "近 3 月 {0}": "Last 3 months {0}", + "近 365 天每天的提交数,按作者日期统计,含合并提交(与“提交节奏”同一口径)。": "Commits per day over the last 365 days, by author date, including merges (same measure as Commit Rhythm).", + "近 6 个月": "Last 6 months", + "进入目录,或打开文件历史": "Enter a directory, or open file history", + "救火提交": "Firefighting Commits", + "聚焦贡献者筛选框或仓库地址输入框": "Focus the contributor filter or the repository address input", + "可观测性": "Observability", + "快捷键": "Shortcuts", + "历史不足 6 个月": "Less than 6 months of history", + "历史里没有这块的提交": "No commits for this block in history", + "连接中断,正在重连…": "Connection lost, reconnecting…", + "连接中…": "Connecting…", + "良好": "Good", + "另有 {0} 次修改落在已删除、且所在目录也不在了的路径上,没有画进图里": "Another {0} changes touched paths that were deleted along with their directories and are not drawn", + "流程文件 {0} 几乎随每次修改一起改,不参与连线": "Workflow files {0} change with almost every edit and are not drawn as lines", + "六": "Sa", + "没有达到门槛的关系(至少一起改过 {0} 次、占比 ≥{1})。": "No link meets the threshold (changed together at least {0} times, share ≥{1}).", + "没有经常和它一起改的文件。": "No files are often changed together with it.", + "没有可统计的提交": "No commits to count", + "没有文件": "No files", + "没有修改": "No changes", + "面积:{0}的修改次数": "Area: {0} changes", + "面积:HEAD 中的文件数": "Area: file count at HEAD", + "面积按修改次数时,没有修改的区域不会出现。可以切换到“按文件数”或更长的时间范围。": "When area is by changes, areas with no changes do not appear. Switch to \"By file count\" or a longer time range.", + "面积代表": "Area means", + "面积是 HEAD 中的文件数,颜色是窗口内的修改次数。点任意一块,进入代码地图并定位到那里": "Area is the file count at HEAD, colour is changes in the window. Click any block to open Code Map and jump there", + "命令面板": "Command palette", + "目录": "Directory", + "排队": "Queued", + "排队等待分析": "Queued for analysis", + "配置 / 数据": "Config / Data", + "平稳": "stable", + "其他": "Other", + "其他贡献者": "Other contributors", + "其他人": "Other people", + "其中 {0} 是修 bug": "{0} of them bug fixes", + "前端": "Frontend", + "切换报告分区": "Switch report section", + "切换到上一个 / 下一个仓库": "Switch to the previous / next repository", + "切换主题": "Switch theme", + "轻量参与": "Light Participant", + "请帮我讲解仓库 {0} 里的 `{1}`{2}是做什么的。": "In the repository {0}, please explain what `{1}`{2} does.", + "请基于下面这份仓库透视报告,帮我深入看一下 {0}。": "Using the Repo X-Ray report below, please take a deep look at {0} for me.", + "请求失败({0})": "Request failed ({0})", + "请输入仓库地址或本地路径": "Enter a repository URL or a local path", + "请先读这个目录的 README(如果有)和入口文件,说明:它负责什么、由哪几个主要部分组成、对外提供什么接口,以及和上面那些“常一起改”的区域是什么关系。只读分析,不要修改代码。": "First read this directory's README (if any) and its entry files, and explain: what it is responsible for, its main parts, what interface it provides to others, and how it relates to the \"often changed together\" areas above. Read-only analysis; do not modify any code.", + "请先阅读前 3 个高风险文件,回答:它们为什么反复出 bug(结构、耦合、职责、测试覆盖),有哪些具体可落地的拆分或加固建议。只读分析,不要修改代码。": "Read the first 3 high-risk files and answer: why do they keep breaking (structure, coupling, responsibilities, test coverage), and what concrete, actionable splits or hardening do you suggest? Read-only analysis; do not modify any code.", + "请阅读这个文件,说明它负责什么、对外提供什么、被谁调用,以及为什么常和上面那些文件一起改。只读分析,不要修改代码。": "Read this file and explain what it is responsible for, what it provides to others, who calls it, and why it so often changes together with the files above. Read-only analysis; do not modify any code.", + "区域": "Area", + "全部": "All", + "全部 {0} 个": "All {0}", + "全部 {0} 人": "All {0} people", + "全部 {0}": "All {0}", + "全部历史": "All history", + "全部历史上": "In all history", + "全仓": "the whole repository", + "全能型 ↗": "All-Rounder ↗", + "热点 Top {0} 中有 {1} 个也是 Bug 磁铁": "Of the Hotspot Top {0}, {1} are also Bug Magnets", + "热度": "Heat", + "日": "Su", + "三": "We", + "上升": "rising", + "少": "Less", + "设置": "Settings", + "时间范围": "Time range", + "识别技术栈与目录说明": "Detecting tech stack and directory notes", + "使用环境变量里的代理": "Using the proxy from environment variables", + "使用系统代理": "Using the system proxy", + "使用这里的设置": "Using the setting here", + "收起": "Collapse", + "手动令牌": "Manual token", + "数据": "Data", + "数据不足": "insufficient", + "双击或回车:查看文件历史": "Double-click or Enter: view file history", + "双击或回车:进入这块": "Double-click or Enter: open this block", + "四": "Th", + "搜索…": "Search…", + "搜索仓库、{0} 里的文件和贡献者…": "Search repositories, files and contributors in {0}…", + "搜索仓库、全部历史文件、贡献者和操作": "Search repositories, all historical files, contributors and actions", + "搜索仓库、文件和贡献者(⌘K)": "Search repositories, files and contributors (⌘K)", + "搜索仓库或执行操作…": "Search repositories or run an action…", + "缩略图只画第一层:面积是 HEAD 中的文件数,颜色是窗口内的修改次数(与“代码热点”同一口径),按分位数分成 5 档。大目录逐层展开,过小的子项合并成“其他 N 项”。点任意一块,会在“代码地图”分区里打开并定位到那里。": "The thumbnail draws only the first level: area is the file count at HEAD, colour is changes in the window (same measure as Code Hotspots), split into 5 quantile bands. Large directories expand level by level; tiny children are merged into \"Other N items\". Click any block to open it in the Code Map section and jump there.", + "所选时间范围内,这块里的文件一共被修改了多少次(与“代码热点”同一口径)。": "How many times the files in this block changed in the selected time range (same measure as Code Hotspots).", + "所选时间范围内在这块提交最多的人(非合并提交,不含机器人)。颜色越淡越是多人共有,第一名不到 25% 的标为“多人共有”。": "The person with the most commits in this block in the selected time range (non-merge commits, excluding bots). Paler means more shared; a top share under 25% is marked \"Shared\".", + "它": "it", + "提交节奏": "Commit Rhythm", + "提交日历:近 365 天有 {0} 天有提交": "Commit calendar: commits on {0} days in the last 365 days", + "提交占比": "Commit share", + "提醒": "Warning", + "条活动": "events", + "跳到主要内容": "Skip to main content", + "同步并分析": "Sync and analyze", + "同步并分析当前仓库": "Sync and analyze this repository", + "同步仓库": "Syncing repository", + "同时出现在“代码热点 Top {0}”和“Bug 磁铁 Top {1}”里的文件。": "Files that appear in both the \"Code Hotspots Top {0}\" and the \"Bug Magnets Top {1}\" lists.", + "图片 / 字体 / 二进制": "Images / Fonts / Binary", + "网页:{0}(若本地没有 checkout,请先 clone {1})": "Web page: {0} (if there is no local checkout, clone {1} first)", + "未找到凭据(按公开仓库访问)": "No credentials found (public repository access)", + "文档": "Docs", + "文件": ["Files", "File"], + "文件类型": "File Type", + "无": "none", + "无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径": "Unrecognized input: enter an https URL, owner/repo, or the absolute path to a local repository", + "无记录": "No record", + "无人修改": "No one changed this", + "无修改": "No changes", + "五": "Fr", + "下降": "declining", + "显示这份列表": "Show this list", + "小型": "Small", + "协作型": "Collaborator", + "信息": "Info", + "修 bug": "Bug fixes", + "修 bug {0} 次 / 共修改 {1} 次": "bug fixes × {0} / {1} changes total", + "修 bug 时最常碰的文件": "Files touched most by bug fixes", + "修 bug 占 {0}": "Bug fixes are {0}", + "修改": "Changes", + "修改 {0} 次": "{0} changes", + "修改太少": "Too few changes", + "选中,查看详情和“常一起改”的连线": "Select; view details and \"often changed together\" links", + "样本少": "Small sample", + "样式": "Styles", + "页面会话已过期,请刷新页面": "Session expired, reload the page", + "一": "Mo", + "一半提交出自几个人": "Half of all commits come from a handful of people", + "一半提交来自": "Half of commits come from", + "移出 {0} 个": "Removed {0}", + "移动端": "Mobile", + "已保存": "Saved", + "已复制": "Copied", + "已开始下载": "Download started", + "已连接 · 实时更新": "Connected · Live updates", + "已取消": "Cancelled", + "已取消,没有追加内容": "Cancelled; nothing was added", + "已删除的热点 {0}": "Deleted hotspots {0}", + "已移除 {0},8 秒后删除缓存的 clone": "Removed {0}; the cached clone is deleted in 8 seconds", + "已移除 {0}(不会动本地仓库)": "Removed {0} (the local repository is untouched)", + "已追加到对话输入框,确认后按发送即可": "Added to the chat input — check it and press Send", + "语言构成": "Language mix", + "语言构成与主要框架": "Language mix and main frameworks", + "语言与运行时": "Languages & Runtimes", + "原始": "Raw", + "原始(与 shortlog 一致)": "Raw (matches shortlog)", + "月度趋势、revert / hotfix": "Monthly trend, revert / hotfix", + "月均 {0} ← {1}": "Monthly avg {0} ← {1}", + "在 HEAD 中存在": "Exists at HEAD", + "在方块之间移动": "Move between blocks", + "暂停": "Pause", + "展开全部 {0} 人": "Show all {0} people", + "占比": "Share", + "找不到可追加的对话,请从对话里打开这个 Mini App": "No chat found to append to; open this Mini App from a chat", + "这份报告来自旧版本,缩略图会在后台重新分析完成后出现;代码地图分区现在就能用": "This report is from an older version; the thumbnail appears once the background Re-analyze finishes. Code Map section works now", + "这个仓库": "this repository", + "这块": "this block", + "这块里最近一次提交距离仓库最新提交多久,看哪里还在演进、哪里已经稳定。不受时间范围影响。": "How long since this block's latest commit relative to the repository's latest commit — where things still evolve and where they have settled. Not affected by the time range.", + "这块全部历史提交中,来自近 3 个月没有任何提交的人的比例。比例高的地方,最熟悉它的人可能已经不在了。不受时间范围影响。": "The share of all historical commits in this block from people with no commits in the last 3 months. Where this is high, the people who knew it best may be gone. Not affected by the time range.", + "这里没有文件": "No files here", + "这些修改里,提交说明含 fix / bug / broken 的比例(与“Bug 磁铁”同一口径)。修改少于 5 次的块不着色。": "The share of those changes whose commit message mentions fix / bug / broken (same measure as Bug Magnets). Blocks with fewer than 5 changes are not coloured.", + "这一层": "this level", + "整个仓库": "Whole repository", + "正在{0}": "{0}", + "正在识别…": "Detecting…", + "之前月均 {0}": "Previous monthly avg {0}", + "知识集中度": "Bus Factor", + "知识流失": "Knowledge Loss", + "知识流失 {0}": "Knowledge Loss {0}", + "直连": "Direct connection", + "只有 {0} 个相关提交,还看不出稳定的关系。": "Only {0} related commits — no stable link yet.", + "指标说明": "Metric details", + "中型": "Medium", + "重新分析": "Re-analyze", + "重新分析当前仓库": "Re-analyze this repository", + "逐月播放": "Play by month", + "逐月播放适用于热度、Bug 占比、负责人三种着色": "Month-by-month playback works with the Heat, Bug Share and Owner colourings", + "主要负责人 {0},占 {1}": "Main owner {0}, {1}", + "主要类型": "Main type", + "主要是 {0}": "Mostly {0}", + "主要是{0}({1}){2}。仓库里没有找到这块的说明": "Mostly {0} ({1}){2}.No description found in the repository for this block", + "主要由 {0} 维护": "Maintained mainly by {0}", + "转到:{0}": "Go to: {0}", + "追加失败,请稍后重试": "Append failed; try again later", + "桌面端": "Desktop", + "最近修改": "Last Change", + "最近一次修改:{0}(相对仓库最新提交 {1})": "Last change: {0} ({1} before the repository's latest commit)", + "最近一次修改在 {0}": ["Last change: {0}", "Last change on {0}"], + "昨天": "yesterday", + "作息打卡图": "Punch card", + "AI Agent 指令(AGENTS.md / CLAUDE.md)": "AI Agent Instructions (AGENTS.md / CLAUDE.md)", + "Bug 磁铁": "Bug Magnets", + "Bug 占比": "Bug Share", + "Electron 打包": "Electron Packaging", + "gh 登录": "gh login", + "glab 登录": "glab login", + "HEAD {0};{1} 个 commit;节奏{2};救火占比 {3};近 3 个月活跃 {4}/{5} 人。": "HEAD {0}; {1} commits; rhythm: {2}; firefighting share {3}; Active in the last 3 months {4}/{5} people.", + "HTML / 模板": "HTML / Templates", + "Markdown 报告已复制": "Markdown report copied", + "title=\"{0}\"": "title=\"{0}\"", + "切换到中文": "Switch to Chinese", + "切换到英文": "Switch to English", +}; diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/analyze.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/analyze.mjs index 7ab4b631..5a586097 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/node/analyze.mjs +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/analyze.mjs @@ -1,8 +1,9 @@ // @ts-check import { COUPLE, coKind, mapView } from './codemap.mjs'; import { git } from './git.mjs'; +import { msg, msgBoth, msgIn } from './i18n.mjs'; -export const ALGO_VERSION = 8; +export const ALGO_VERSION = 10; const FIX_RE = 'fix|bug|broken'; // skill 2c (git --grep, case-insensitive, full message) const FIRE_RE = /revert|hotfix|emergency|rollback/i; // skill 2e (oneline subject) const SEP = '\x1f'; @@ -79,7 +80,7 @@ export async function buildModel(dir, { signal, onProgress } = {}) { }, ); if (rest) handleLine(rest); - if (!commits.length) throw Object.assign(new Error('仓库还没有任何提交'), { code: 'empty' }); + if (!commits.length) throw Object.assign(new Error(msg('仓库还没有任何提交')), { code: 'empty', messages: msgBoth('仓库还没有任何提交') }); const fixOut = await git(['-C', dir, 'log', '-i', '-E', `--grep=${FIX_RE}`, '--format=%H', 'HEAD'], { signal, timeout: 5 * 60_000 }); const fix = new Set(fixOut.split('\n').filter(Boolean)); @@ -414,34 +415,44 @@ export function buildReport(model, { now = Math.floor(Date.now() / 1000), identi }; // Problems (deterministic signals) - const problems = []; - if (highRisk.length) { - problems.push({ level: 'warn', anchor: 'risk', title: `${highRisk.length} 个高风险文件:既是热点,又频繁被修 bug`, detail: highRisk.slice(0, 3).map((h) => h.path.split('/').pop()).join('、') }); - const solo = highRisk.filter((h) => h.exists && h.owner && h.owner.share >= 0.8); - if (solo.length) problems.push({ level: 'warn', anchor: 'risk', filter: 'solo', title: `${solo.length} 个高风险文件主要由一个人维护(≥80% 提交)`, detail: solo.slice(0, 3).map((h) => `${h.path.split('/').pop()} → ${h.owner.name}`).join('、') }); - } else { - problems.push({ level: 'good', anchor: 'risk', title: '热点文件和 bug 磁铁没有重叠', detail: 'skill 原话:No files appear in both lists — good sign.' }); - } - if (busFactor.warn) problems.push({ level: 'warn', anchor: 'people', title: `活跃贡献者比例偏低:${active3m} / ${totalContributors}(${Math.round(busFactor.ratio * 100)}%)`, detail: '近 3 个月活跃的人不足历史总人数的 30%,知识可能集中在少数人身上' }); - if (busFactor.halfCount <= 2 && totalContributors >= 4) problems.push({ level: 'warn', anchor: 'people', title: `${busFactor.halfCount} 个人贡献了一半以上的提交`, detail: `${contributors.slice(0, busFactor.halfCount).map((c) => c.name).join('、')}` }); - if (trend === 'declining') problems.push({ level: 'warn', anchor: 'momentum', title: `提交节奏在下降:近 3 个月月均 ${Math.round(lastAvg)},之前 3 个月 ${Math.round(prevAvg)}`, detail: '降幅超过 20%' }); - if (trend === 'erratic') problems.push({ level: 'info', anchor: 'momentum', title: '提交节奏波动大', detail: '近几个月环比变化平均超过 50%' }); - if (trend === 'rising') problems.push({ level: 'good', anchor: 'momentum', title: `提交节奏在上升:近 3 个月月均 ${Math.round(lastAvg)},之前 3 个月 ${Math.round(prevAvg)}`, detail: '增幅超过 20%' }); - if (firefighting.rate >= 0.05) problems.push({ level: 'warn', anchor: 'fire', title: `救火提交占 ${(firefighting.rate * 100).toFixed(1)}%(${firefighting.count} / ${windowCommits})`, detail: firefighting.kinds.map(([k, n]) => `${k} ${n}`).join('、') }); - else if (firefighting.count) problems.push({ level: 'info', anchor: 'fire', title: `窗口内有 ${firefighting.count} 次 revert / hotfix 类提交(${(firefighting.rate * 100).toFixed(1)}%)`, detail: firefighting.kinds.map(([k, n]) => `${k} ${n}`).join('、') }); - if (anchorFallback) problems.push({ level: 'info', anchor: 'vitals', title: `仓库最近 ${windowMonths === 12 ? '一年' : '半年'}没有提交`, detail: `最后一次提交在 ${latest},分析窗口改为以它为终点` }); - const deletedHot = hotspots.filter((h) => !h.exists).length; - if (deletedHot >= Math.max(3, N / 4)) problems.push({ level: 'info', anchor: 'risk', filter: 'deleted', title: `${deletedHot} 个热点文件已在 HEAD 中删除或改名`, detail: '它们的历史仍算在热点里,阅读时以现存文件为准' }); + /** @param {'zh' | 'en'} lang */ + const buildProblems = (lang) => { + const problems = []; + if (highRisk.length) { + problems.push({ level: 'warn', anchor: 'risk', title: msgIn(lang, '{0} 个高风险文件:既是热点,又频繁被修 bug', highRisk.length), detail: highRisk.slice(0, 3).map((h) => h.path.split('/').pop()).join(msgIn(lang, '、')) }); + const solo = highRisk.filter((h) => h.exists && h.owner && h.owner.share >= 0.8); + if (solo.length) problems.push({ level: 'warn', anchor: 'risk', filter: 'solo', title: msgIn(lang, '{0} 个高风险文件主要由一个人维护(≥80% 提交)', solo.length), detail: solo.slice(0, 3).map((h) => `${h.path.split('/').pop()} → ${h.owner.name}`).join(msgIn(lang, '、')) }); + } else { + problems.push({ level: 'good', anchor: 'risk', title: msgIn(lang, '热点文件和 bug 磁铁没有重叠'), detail: msgIn(lang, 'skill 原话:No files appear in both lists — good sign.') }); + } + if (busFactor.warn) problems.push({ level: 'warn', anchor: 'people', title: msgIn(lang, '活跃贡献者比例偏低:{0} / {1}({2}%)', active3m, totalContributors, Math.round(busFactor.ratio * 100)), detail: msgIn(lang, '近 3 个月活跃的人不足历史总人数的 30%,知识可能集中在少数人身上') }); + if (busFactor.halfCount <= 2 && totalContributors >= 4) problems.push({ level: 'warn', anchor: 'people', title: msgIn(lang, '{0} 个人贡献了一半以上的提交', busFactor.halfCount), detail: `${contributors.slice(0, busFactor.halfCount).map((c) => c.name).join(msgIn(lang, '、'))}` }); + if (trend === 'declining') problems.push({ level: 'warn', anchor: 'momentum', title: msgIn(lang, '提交节奏在下降:近 3 个月月均 {0},之前 3 个月 {1}', Math.round(lastAvg), Math.round(prevAvg)), detail: msgIn(lang, '降幅超过 20%') }); + if (trend === 'erratic') problems.push({ level: 'info', anchor: 'momentum', title: msgIn(lang, '提交节奏波动大'), detail: msgIn(lang, '近几个月环比变化平均超过 50%') }); + if (trend === 'rising') problems.push({ level: 'good', anchor: 'momentum', title: msgIn(lang, '提交节奏在上升:近 3 个月月均 {0},之前 3 个月 {1}', Math.round(lastAvg), Math.round(prevAvg)), detail: msgIn(lang, '增幅超过 20%') }); + if (firefighting.rate >= 0.05) problems.push({ level: 'warn', anchor: 'fire', title: msgIn(lang, '救火提交占 {0}%({1} / {2})', (firefighting.rate * 100).toFixed(1), firefighting.count, windowCommits), detail: firefighting.kinds.map(([k, n]) => `${k} ${n}`).join(msgIn(lang, '、')) }); + else if (firefighting.count) problems.push({ level: 'info', anchor: 'fire', title: msgIn(lang, '窗口内有 {0} 次 revert / hotfix 类提交({1}%)', firefighting.count, (firefighting.rate * 100).toFixed(1)), detail: firefighting.kinds.map(([k, n]) => `${k} ${n}`).join(msgIn(lang, '、')) }); + if (anchorFallback) problems.push({ level: 'info', anchor: 'vitals', title: msgIn(lang, '仓库最近 {0}没有提交', windowMonths === 12 ? msgIn(lang, '一年') : msgIn(lang, '半年')), detail: msgIn(lang, '最后一次提交在 {0},分析窗口改为以它为终点', latest) }); + const deletedHot = hotspots.filter((h) => !h.exists).length; + if (deletedHot >= Math.max(3, N / 4)) problems.push({ level: 'info', anchor: 'risk', filter: 'deleted', title: msgIn(lang, '{0} 个热点文件已在 HEAD 中删除或改名', deletedHot), detail: msgIn(lang, '它们的历史仍算在热点里,阅读时以现存文件为准') }); + return problems; + }; + const problems = { zh: buildProblems('zh'), en: buildProblems('en') }; // Recommendations (skill template) const readList = (highRisk.length ? highRisk : hotspots).filter((x) => x.exists !== false).slice(0, 3).map((x) => x.path); const talkFile = (highRisk[0] || hotspots.find((h) => h.exists) || hotspots[0])?.path; const talkOwner = talkFile ? (highRisk[0]?.owner || ownersOf(talkFile)[0]) : null; - const watchOut = []; - if (trend === 'declining') watchOut.push('提交节奏在下降'); - if (trend === 'erratic') watchOut.push('提交节奏不稳定'); - if (busFactor.warn) watchOut.push('活跃贡献者比例低,存在知识集中风险'); - if (firefighting.rate >= 0.05) watchOut.push('救火提交比例高'); + /** @param {'zh' | 'en'} lang */ + const buildWatchOut = (lang) => { + const watchOut = []; + if (trend === 'declining') watchOut.push(msgIn(lang, '提交节奏在下降')); + if (trend === 'erratic') watchOut.push(msgIn(lang, '提交节奏不稳定')); + if (busFactor.warn) watchOut.push(msgIn(lang, '活跃贡献者比例低,存在知识集中风险')); + if (firefighting.rate >= 0.05) watchOut.push(msgIn(lang, '救火提交比例高')); + return watchOut; + }; + const watchOut = { zh: buildWatchOut('zh'), en: buildWatchOut('en') }; const recommendations = { startReading: readList, talkTo: talkOwner ? { name: talkOwner.name, file: talkFile, share: talkOwner.share } : null, watchOut }; return { diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/codemap.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/codemap.mjs index 0e83c63e..fcd5c349 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/node/codemap.mjs +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/codemap.mjs @@ -8,6 +8,8 @@ * - per-directory descriptions taken from the repository's own manifests and READMEs */ +import { msgBoth } from './i18n.mjs'; + /** code-maat defaults: --max-changeset-size 30, --min-revs 5, --min-shared-revs 5, --min-coupling 30 */ export const COUPLE = Object.freeze({ maxChangeset: 30, minRevs: 5, minShared: 5, minDegree: 0.3 }); const RANGE_MONTHS = { 3: 3, 6: 6, 12: 12 }; @@ -474,7 +476,7 @@ export function mapView(model, o = {}) { const kind = l.other ? 'other' : node.file ? 'file' : 'dir'; const b = { path: node.path, - name: l.other ? `其他 ${l.rest.length} 项` : node.name, + name: l.other ? msgBoth('其他 {0} 项', l.rest.length) : node.name, kind, group: groupOf(l.other ? l.parent : l), zoom: kind === 'dir' ? node.path : kind === 'other' && l.parent !== fnode ? l.parent.path : null, diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/git.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/git.mjs index bf480173..a2fbec7b 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/node/git.mjs +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/git.mjs @@ -4,15 +4,28 @@ import { createHash } from 'node:crypto'; import { realpath, stat } from 'node:fs/promises'; import { homedir } from 'node:os'; import { isAbsolute, join, resolve } from 'node:path'; +import { getLang, msgBoth } from './i18n.mjs'; export class GitError extends Error { - /** @param {string} code @param {string} message */ - constructor(code, message) { + /** + * @param {string} code + * @param {string} message + * @param {{ zh: string, en: string }} [messages] The message in both languages. + */ + constructor(code, message, messages) { super(message); this.code = code; + /** The message in both languages, for text that outlives the request that asked for it. */ + this.messages = messages || null; } } +/** An error whose message the server can also show in the other language. */ +const fail = (code, key, ...args) => { + const messages = msgBoth(key, ...args); + return new GitError(code, messages[getLang() === 'en' ? 'en' : 'zh'], messages); +}; + /** Child processes owned by this runtime (killed on dispose). */ export const children = new Set(); @@ -58,7 +71,7 @@ export function killTree(child) { */ export function git(args, opts = {}) { return new Promise((resolvePromise, reject) => { - if (opts.signal?.aborted) return reject(new GitError('aborted', '已取消')); + if (opts.signal?.aborted) return reject(fail('aborted', '已取消')); const env = { ...inheritedEnv(), GIT_TERMINAL_PROMPT: '0', @@ -102,16 +115,19 @@ export function git(args, opts = {}) { child.on('error', (e) => { clearTimeout(timer); children.delete(child); - reject(new GitError(e.code === 'ENOENT' ? 'git_missing' : 'git', e.code === 'ENOENT' ? '本机没有找到 git,请先安装 git' : 'git 启动失败')); + reject(e.code === 'ENOENT' ? fail('git_missing', '本机没有找到 git,请先安装 git') : fail('git', 'git 启动失败')); }); child.on('close', (code) => { clearTimeout(timer); children.delete(child); opts.signal?.removeEventListener('abort', onAbort); - if (killedFor === 'aborted') return reject(new GitError('aborted', '已取消')); - if (killedFor === 'timeout') return reject(new GitError('timeout', 'git 执行超时')); - if (killedFor === 'overflow') return reject(new GitError('overflow', 'git 输出过大')); - if (code !== 0) return reject(new GitError(classify(err), friendly(err))); + if (killedFor === 'aborted') return reject(fail('aborted', '已取消')); + if (killedFor === 'timeout') return reject(fail('timeout', 'git 执行超时')); + if (killedFor === 'overflow') return reject(fail('overflow', 'git 输出过大')); + if (code !== 0) { + const f = friendly(err); + return reject(new GitError(f.code, f.messages[getLang() === 'en' ? 'en' : 'zh'], f.messages)); + } resolvePromise(Buffer.concat(out).toString('utf8')); }); if (opts.input != null) child.stdin.end(opts.input); @@ -130,16 +146,18 @@ function classify(stderr) { return 'git'; } +/** The message for a failed git command, in both languages. */ function friendly(stderr) { const code = classify(stderr); - if (code === 'redirect') return '服务器要求跳转到另一个地址(仓库可能改名或迁移了)。带着访问令牌时不会跟随跳转,以免令牌发到别处:请在网页上确认仓库的新地址,用新地址重新添加'; - if (code === 'auth') return '没有权限访问这个仓库:请确认已用 gh / glab 登录,或在设置里为这个主机填写访问令牌'; - if (code === 'not_found') return '仓库不存在,或当前账号看不到它'; - if (code === 'network') return '网络连接失败:内网地址可能需要在设置里配置代理'; - if (code === 'not_repo') return '这个目录不是 git 仓库'; - if (code === 'empty') return '仓库还没有任何提交'; + if (code === 'redirect') return { code, messages: msgBoth('服务器要求跳转到另一个地址(仓库可能改名或迁移了)。带着访问令牌时不会跟随跳转,以免令牌发到别处:请在网页上确认仓库的新地址,用新地址重新添加') }; + if (code === 'auth') return { code, messages: msgBoth('没有权限访问这个仓库:请确认已用 gh / glab 登录,或在设置里为这个主机填写访问令牌') }; + if (code === 'not_found') return { code, messages: msgBoth('仓库不存在,或当前账号看不到它') }; + if (code === 'network') return { code, messages: msgBoth('网络连接失败:内网地址可能需要在设置里配置代理') }; + if (code === 'not_repo') return { code, messages: msgBoth('这个目录不是 git 仓库') }; + if (code === 'empty') return { code, messages: msgBoth('仓库还没有任何提交') }; const line = stderr.split('\n').map((s) => s.trim()).filter((s) => /^(fatal|error):/.test(s))[0]; - return line ? line.replace(/https?:\/\/[^\s@]*@/g, 'https://').slice(0, 200) : 'git 执行失败'; + const text = line ? line.replace(/https?:\/\/[^\s@]*@/g, 'https://').slice(0, 200) : null; + return { code, messages: text ? { zh: text, en: text } : msgBoth('git 执行失败') }; } // --------------------------------------------------------------------------- @@ -152,8 +170,8 @@ function friendly(stderr) { */ export async function parseTarget(raw) { const input = String(raw || '').trim(); - if (!input) throw new GitError('invalid', '请输入仓库地址或本地路径'); - if (input.length > 500) throw new GitError('invalid', '输入过长'); + if (!input) throw fail('invalid', '请输入仓库地址或本地路径'); + if (input.length > 500) throw fail('invalid', '输入过长'); // Local path if (input.startsWith('/') || input.startsWith('~') || /^[A-Za-z]:[\\/]/.test(input)) { @@ -163,7 +181,7 @@ export async function parseTarget(raw) { dir = await realpath(dir); if (!(await stat(dir)).isDirectory()) throw new Error(); } catch { - throw new GitError('invalid', '找不到这个目录'); + throw fail('invalid', '找不到这个目录'); } let top; try { @@ -175,7 +193,7 @@ export async function parseTarget(raw) { if (isBare !== 'true') throw new Error(); top = dir; } catch { - throw new GitError('not_repo', '这个目录不是 git 仓库'); + throw fail('not_repo', '这个目录不是 git 仓库'); } } const name = top.split(/[\\/]/).filter(Boolean).pop() || top; @@ -196,7 +214,7 @@ export async function parseTarget(raw) { try { u = new URL(input); } catch { - throw new GitError('invalid', '地址格式不对'); + throw fail('invalid', '地址格式不对'); } host = u.host; path = decodeURIComponent(u.pathname); @@ -207,18 +225,18 @@ export async function parseTarget(raw) { host = m[1]; path = m[2]; } else { - throw new GitError('invalid', '无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径'); + throw fail('invalid', '无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径'); } host = host.toLowerCase(); // One rule for every form: rejects "git@github.com@evil.example:…" and similar. - if (!HOST_RE.test(host)) throw new GitError('invalid', '主机名不合法'); + if (!HOST_RE.test(host)) throw fail('invalid', '主机名不合法'); path = path.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, ''); // Strip web UI suffixes. path = path.split('/-/')[0]; const provider = host === 'github.com' || host.startsWith('github.') ? 'github' : host.includes('gitlab') ? 'gitlab' : 'other'; if (provider === 'github') path = path.split('/').slice(0, 2).join('/'); else path = path.replace(/\/(tree|blob|commits?|merge_requests|issues)(\/.*)?$/, ''); - if (!/^[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)+$/.test(path)) throw new GitError('invalid', '仓库路径不合法'); + if (!/^[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)+$/.test(path)) throw fail('invalid', '仓库路径不合法'); const key = `${host}/${path}`.toLowerCase(); return { kind: 'remote', diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/i18n.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/i18n.mjs new file mode 100644 index 00000000..06b700b8 --- /dev/null +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/i18n.mjs @@ -0,0 +1,144 @@ +// @ts-check +import { AsyncLocalStorage } from 'node:async_hooks'; +/** + * Bilingual messages for the Node side. + * + * The Chinese text is the key, the way it reads in the source; the value is the + * English. Templates use {0}, {1} placeholders, filled in order. The active + * language comes from the page, which sends it with every request. + */ + +/** @type {Record} */ +const M = { + "、": ["、", ", "], + "{0} 个 package.json": ["{0} 个 package.json", "{0} package.json"], + "其他 {0} 项": ["其他 {0} 项", "{0} other items"], + "{0} 个高风险文件:既是热点,又频繁被修 bug": ["{0} 个高风险文件:既是热点,又频繁被修 bug", "High-risk files ({0}): hotspots with frequent bug fixes"], + "{0} 个高风险文件主要由一个人维护(≥80% 提交)": ["{0} 个高风险文件主要由一个人维护(≥80% 提交)", "High-risk files ({0}) primarily maintained by one person (≥80% of commits)"], + "{0} 个热点文件已在 HEAD 中删除或改名": ["{0} 个热点文件已在 HEAD 中删除或改名", "{0} hotspot files were deleted or renamed in HEAD"], + "{0} 个人贡献了一半以上的提交": ["{0} 个人贡献了一半以上的提交", "{0} people contributed at least half of the commits"], + "半年": ["半年", "6 months"], + "本机没有找到 git,请先安装 git": ["本机没有找到 git,请先安装 git", "git was not found on this machine. Install git first."], + "仓库 ID 不合法": ["仓库 ID 不合法", "Invalid repository ID"], + "仓库不存在,或当前账号看不到它": ["仓库不存在,或当前账号看不到它", "The repository does not exist or is not visible to the current account"], + "仓库不在列表里": ["仓库不在列表里", "Repository is not in the list"], + "仓库还没有任何提交": ["仓库还没有任何提交", "The repository has no commits yet"], + "仓库路径不合法": ["仓库路径不合法", "Invalid repository path"], + "仓库最近 {0}没有提交": ["仓库最近 {0}没有提交", "No repository commits in the last {0}"], + "窗口内有 {0} 次 revert / hotfix 类提交({1}%)": ["窗口内有 {0} 次 revert / hotfix 类提交({1}%)", "This window has {0} revert or hotfix commits ({1}%)"], + "代理地址应类似 http://127.0.0.1:7890": ["代理地址应类似 http://127.0.0.1:7890", "The proxy address should look like http://127.0.0.1:7890"], + "地址格式不对": ["地址格式不对", "Invalid address format"], + "分析失败": ["分析失败", "Analysis failed"], + "服务器要求跳转到另一个地址(仓库可能改名或迁移了)。带着访问令牌时不会跟随跳转,以免令牌发到别处:请在网页上确认仓库的新地址,用新地址重新添加": ["服务器要求跳转到另一个地址(仓库可能改名或迁移了)。带着访问令牌时不会跟随跳转,以免令牌发到别处:请在网页上确认仓库的新地址,用新地址重新添加", "The server requested a redirect to another address (the repository may have been renamed or moved). Redirects are not followed when using an access token to avoid sending it elsewhere. Confirm the new repository URL in your browser and use it to add the repository again"], + "还没有分析结果": ["还没有分析结果", "No analysis yet"], + "活跃贡献者比例低,存在知识集中风险": ["活跃贡献者比例低,存在知识集中风险", "low active contributor ratio — knowledge concentration risk"], + "活跃贡献者比例偏低:{0} / {1}({2}%)": ["活跃贡献者比例偏低:{0} / {1}({2}%)", "Low share of active contributors: {0} / {1} ({2}%)"], + "降幅超过 20%": ["降幅超过 20%", "Down more than 20%"], + "接口不存在": ["接口不存在", "Unknown endpoint"], + "解析增量": ["解析增量", "Resolving deltas"], + "近 3 个月活跃的人不足历史总人数的 30%,知识可能集中在少数人身上": ["近 3 个月活跃的人不足历史总人数的 30%,知识可能集中在少数人身上", "Fewer than 30% of all-time contributors committed in the last 3 months — knowledge may be concentrated in a few people"], + "近几个月环比变化平均超过 50%": ["近几个月环比变化平均超过 50%", "Month-over-month changes averaged more than 50% in recent months"], + "救火提交比例高": ["救火提交比例高", "high firefighting rate"], + "救火提交占 {0}%({1} / {2})": ["救火提交占 {0}%({1} / {2})", "Firefighting commits account for {0}% ({1} / {2})"], + "历史里没有这个贡献者": ["历史里没有这个贡献者", "This contributor is not in the history"], + "历史里没有这个文件": ["历史里没有这个文件", "This file is not in the history"], + "没有权限访问这个仓库:请确认已用 gh / glab 登录,或在设置里为这个主机填写访问令牌": ["没有权限访问这个仓库:请确认已用 gh / glab 登录,或在设置里为这个主机填写访问令牌", "Access denied: confirm that you are signed in with gh or glab, or enter an access token for this host in settings"], + "目录路径不合法": ["目录路径不合法", "Invalid directory path"], + "内部错误": ["内部错误", "Internal error"], + "请求体不是 JSON": ["请求体不是 JSON", "Request body is not JSON"], + "请求体过大": ["请求体过大", "Request body too large"], + "请输入仓库地址或本地路径": ["请输入仓库地址或本地路径", "Enter a repository URL or a local path"], + "热点文件和 bug 磁铁没有重叠": ["热点文件和 bug 磁铁没有重叠", "No overlap between code hotspots and bug magnets"], + "输入过长": ["输入过长", "Input is too long"], + "它们的历史仍算在热点里,阅读时以现存文件为准": ["它们的历史仍算在热点里,阅读时以现存文件为准", "Their history still counts toward hotspots. Read the files that still exist."], + "提交节奏波动大": ["提交节奏波动大", "Commit rhythm is erratic"], + "提交节奏不稳定": ["提交节奏不稳定", "commit rhythm is unstable"], + "提交节奏在上升:近 3 个月月均 {0},之前 3 个月 {1}": ["提交节奏在上升:近 3 个月月均 {0},之前 3 个月 {1}", "Commit rhythm is rising: {0} per month over the last 3 months vs. {1} over the previous 3 months"], + "提交节奏在下降": ["提交节奏在下降", "commit rhythm is declining"], + "提交节奏在下降:近 3 个月月均 {0},之前 3 个月 {1}": ["提交节奏在下降:近 3 个月月均 {0},之前 3 个月 {1}", "Commit rhythm is declining: {0} per month over the last 3 months vs. {1} over the previous 3 months"], + "统计对象": ["统计对象", "Counting objects"], + "网络连接失败:内网地址可能需要在设置里配置代理": ["网络连接失败:内网地址可能需要在设置里配置代理", "Network connection failed: internal addresses may require a proxy in settings"], + "文件路径不合法": ["文件路径不合法", "Invalid file path"], + "无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径": ["无法识别:请输入 https 地址、owner/repo,或本地仓库的绝对路径", "Unrecognized input: enter an https URL, owner/repo, or the absolute path to a local repository"], + "下载对象": ["下载对象", "Receiving objects"], + "压缩对象": ["压缩对象", "Compressing objects"], + "一年": ["一年", "1 year"], + "已取消": ["已取消", "Cancelled"], + "增幅超过 20%": ["增幅超过 20%", "Up more than 20%"], + "找不到这个目录": ["找不到这个目录", "That directory was not found"], + "这个目录不是 git 仓库": ["这个目录不是 git 仓库", "This directory is not a git repository"], + "只接受本机页面的请求": ["只接受本机页面的请求", "Only requests from this page are accepted"], + "主机名不合法": ["主机名不合法", "Invalid host name"], + "最后一次提交在 {0},分析窗口改为以它为终点": ["最后一次提交在 {0},分析窗口改为以它为终点", "Last commit: {0}. The analysis window now ends at that commit."], + "git 启动失败": ["git 启动失败", "Failed to start git"], + "git 输出过大": ["git 输出过大", "git produced too much output"], + "git 执行超时": ["git 执行超时", "git timed out"], + "git 执行失败": ["git 执行失败", "git failed"], + "HEAD 中没有这个目录(可能已删除或改名)": ["HEAD 中没有这个目录(可能已删除或改名)", "This directory is not in HEAD (it may have been deleted or renamed)"], + "skill 原话:No files appear in both lists — good sign.": ["skill 原话:No files appear in both lists — good sign.", "From the skill: No files appear in both lists — good sign."], +}; + +/** The language of the request being served; each request runs in its own context. */ +const store = new AsyncLocalStorage(); + +/** + * Run a handler in a language. + * @param {string | undefined} l 'en' or 'zh'; anything else falls back to Chinese. + * @param {() => void} fn + * @returns {void} + */ +export function withLang(l, fn) { + store.run(l === 'en' ? 'en' : 'zh', fn); +} + +/** + * The language of the running request. + * @returns {'en' | 'zh'} + */ +export function getLang() { + return store.getStore() === 'en' ? 'en' : 'zh'; +} + +/** + * Fill the placeholders in one pass, so a value that looks like one is left alone. + * @param {string} template + * @param {unknown[]} args + * @returns {string} + */ +function fill(template, args) { + return template.replace(/\{(\d+)\}/g, (whole, i) => (Number(i) < args.length ? String(args[Number(i)]) : whole)); +} + +/** + * The message for the language of the running request. + * @param {string} key Chinese text, or a template using {0}, {1} placeholders. + * @param {...unknown} args Values for the placeholders. + * @returns {string} + */ +export function msg(key, ...args) { + const e = M[key]; + return fill(e ? e[getLang() === 'en' ? 1 : 0] : key, args); +} + +/** + * The message for a given language, whatever the running one is. + * @param {'en' | 'zh'} l + * @param {string} key + * @param {...unknown} args + * @returns {string} + */ +export function msgIn(l, key, ...args) { + const e = M[key]; + return fill(e ? e[l === 'en' ? 1 : 0] : key, args); +} + +/** + * The message in both languages, for text that outlives the request that asked for it. + * @param {string} key + * @param {...unknown} args + * @returns {{ zh: string, en: string }} + */ +export function msgBoth(key, ...args) { + const e = M[key]; + return { zh: fill(e ? e[0] : key, args), en: fill(e ? e[1] : key, args) }; +} diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/server.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/server.mjs index 30586432..3a9f43aa 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/node/server.mjs +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/server.mjs @@ -9,6 +9,7 @@ import { delimiter, join } from 'node:path'; import { ALGO_VERSION, buildModel, buildReport, diffReports, fileDetail, personDetail, search } from './analyze.mjs'; import { buildDescs, mapView, pickDescFiles } from './codemap.mjs'; import { GitError, HOST_RE, children, git, killTree, netEnv, parseTarget, prefetchBlobs, readBlobs, syncRemote } from './git.mjs'; +import { getLang, msg, msgBoth, withLang } from './i18n.mjs'; import { buildTechStack, pickManifests } from './techstack.mjs'; import { readJson, sleep, writeJsonAtomic } from './util.mjs'; @@ -18,6 +19,9 @@ import { readJson, sleep, writeJsonAtomic } from './util.mjs'; const CLIENT_FILES = { '/assets/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/assets/charts.js': ['charts.js', 'text/javascript; charset=utf-8'], + '/assets/i18n.js': ['i18n.js', 'text/javascript; charset=utf-8'], + '/assets/pending.js': ['pending.js', 'text/javascript; charset=utf-8'], + '/assets/strings.js': ['strings.js', 'text/javascript; charset=utf-8'], '/assets/styles.css': ['styles.css', 'text/css; charset=utf-8'], '/assets/icon.svg': ['icon.svg', 'image/svg+xml'], }; @@ -188,12 +192,13 @@ export async function start(context) { // --------------------------------------------------------------------------- // SSE // --------------------------------------------------------------------------- - const streams = new Set(); + /** Every open stream, with the language it asked for. */ + const streams = new Map(); const broadcast = (event, data) => { - const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; - for (const res of streams) { + for (const [res, lang] of streams) { try { - res.write(payload); + const body = event === 'job' ? publicJob(data, lang) : data; + res.write(`event: ${event}\ndata: ${JSON.stringify(body)}\n\n`); } catch {} } }; @@ -230,12 +235,27 @@ export async function start(context) { } const jobs = new Map(); - const publicJob = (j) => j && { repoId: j.repoId, running: j.running, stage: j.stage, pct: j.pct, detail: j.detail, error: j.error, startedAt: j.startedAt, finishedAt: j.finishedAt || null, steps: j.steps, stageStartedAt: j.stageStartedAt, reportHead: j.reportHead || null }; + /** A field that carries one string, or the same string in both languages. */ + const pick = (v, lang) => (v && typeof v === 'object' ? (v[lang] ?? v.zh ?? '') : v); + const publicJob = (j, lang = 'zh') => + j && { + repoId: j.repoId, + running: j.running, + stage: j.stage, + pct: j.pct, + detail: pick(j.detail, lang), + error: j.error ? { ...j.error, message: pick(j.error.message, lang) } : null, + startedAt: j.startedAt, + finishedAt: j.finishedAt || null, + steps: j.steps, + stageStartedAt: j.stageStartedAt, + reportHead: j.reportHead || null, + }; let lastTick = 0; const tick = (j, force) => { if (!force && Date.now() - lastTick < 200) return; lastTick = Date.now(); - broadcast('job', publicJob(j)); + broadcast('job', j); }; let activeNet = 0; const netQueue = []; @@ -289,7 +309,7 @@ export async function start(context) { env, signal: ac.signal, onProgress: ({ phase, pct }) => { - job.detail = { 'Counting objects': '统计对象', 'Compressing objects': '压缩对象', 'Receiving objects': '下载对象', 'Resolving deltas': '解析增量' }[phase] || phase; + job.detail = { 'Counting objects': msgBoth('统计对象'), 'Compressing objects': msgBoth('压缩对象'), 'Receiving objects': msgBoth('下载对象'), 'Resolving deltas': msgBoth('解析增量') }[phase] || phase; job.pct = pct; tick(job); }, @@ -354,7 +374,8 @@ export async function start(context) { await saveConfig(); })() .catch(async (e) => { - job.error = e?.code === 'aborted' ? null : { code: e?.code || 'error', message: e instanceof GitError || e?.code === 'empty' ? e.message : '分析失败' }; + const text = e?.messages || (e instanceof GitError || e?.code === 'empty' ? { zh: e.message, en: e.message } : msgBoth('分析失败')); + job.error = e?.code === 'aborted' ? null : { code: e?.code || 'error', message: text }; job.stage = e?.code === 'aborted' ? 'cancelled' : 'error'; if (!(e instanceof GitError)) log.error('job.failed', { reason: String(e?.message || e).slice(0, 160) }); if (job.error) { @@ -439,30 +460,31 @@ export async function start(context) { const code = e?.code || 'error'; const status = { invalid: 400, not_repo: 400, not_found: 404, conflict: 409 }[code] || (e instanceof GitError ? 502 : 500); if (!(e instanceof GitError)) log.error('request.failed', { reason: String(e?.message || e).slice(0, 160) }); - send(res, status, { error: { code, message: e instanceof GitError ? e.message : '内部错误' } }); + const message = e instanceof GitError ? (e.messages ? pick(e.messages, getLang()) : e.message) : msg('内部错误'); + send(res, status, { error: { code, message } }); }; async function body(req) { const chunks = []; let size = 0; for await (const c of req) { size += c.length; - if (size > 64 * 1024) throw new GitError('invalid', '请求体过大'); + if (size > 64 * 1024) throw new GitError('invalid', msg('请求体过大')); chunks.push(c); } if (!chunks.length) return {}; try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { - throw new GitError('invalid', '请求体不是 JSON'); + throw new GitError('invalid', msg('请求体不是 JSON')); } } const findRepo = (id) => { - if (!ID_RE.test(id)) throw new GitError('invalid', '仓库 ID 不合法'); + if (!ID_RE.test(id)) throw new GitError('invalid', msg('仓库 ID 不合法')); const r = config.repos.find((x) => x.id === id); - if (!r) throw new GitError('not_found', '仓库不在列表里'); + if (!r) throw new GitError('not_found', msg('仓库不在列表里')); return r; }; - const publicRepo = (r) => ({ + const publicRepo = (r, lang = 'zh') => ({ id: r.id, name: r.name, kind: r.target.kind, @@ -471,20 +493,20 @@ export async function start(context) { webUrl: r.target.kind === 'remote' ? r.target.webUrl : null, localDir: r.target.kind === 'local' ? r.target.dir : null, addedAt: r.addedAt, - lastSync: r.lastSync || null, + lastSync: r.lastSync ? { ...r.lastSync, error: r.lastSync.error ? { ...r.lastSync.error, message: pick(r.lastSync.error.message, lang) } : null } : null, summary: r.summary || null, - job: publicJob(jobs.get(r.id)) || null, + job: publicJob(jobs.get(r.id), lang) || null, }); async function stateBody() { await resolveProxy(); const hosts = [...new Set(config.repos.filter((r) => r.target.kind === 'remote').map((r) => r.target.host))]; const cred = await Promise.all(hosts.map(async (h) => ({ host: h, source: (await credentialFor(h)).source }))); - return { repos: config.repos.map(publicRepo), settings: { proxy: config.settings.proxy, proxyActive: proxy.origin, hosts: cred, tokenHosts: Object.keys(config.settings.tokens), scanRoots: scanRoots().map((r) => r.replace(homedir(), '~')) } }; + return { repos: config.repos.map((r) => publicRepo(r, getLang())), settings: { proxy: config.settings.proxy, proxyActive: proxy.origin, hosts: cred, tokenHosts: Object.keys(config.settings.tokens), scanRoots: scanRoots().map((r) => r.replace(homedir(), '~')) } }; } async function handle(req, res) { // Every route: the Host names this machine and a browser Origin, if any, is this page. - if (!isLoopbackRequest(req, context.listen.port)) return send(res, 403, { error: { code: 'forbidden', message: '只接受本机页面的请求' } }); + if (!isLoopbackRequest(req, context.listen.port)) return send(res, 403, { error: { code: 'forbidden', message: msg('只接受本机页面的请求') } }); const url = new URL(req.url ?? '/', 'http://miniapp.local'); const p = url.pathname; const method = req.method || 'GET'; @@ -499,9 +521,11 @@ export async function start(context) { return res.end(await readFile(join(clientDir, f))); } if (method === 'GET' && p === '/api/stream') { + // EventSource cannot send headers, so the page states its language here. + const lang = url.searchParams.get('lang') === 'en' ? 'en' : 'zh'; res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' }); res.write(': connected\n\n'); - streams.add(res); + streams.set(res, lang); req.on('close', () => streams.delete(res)); return; } @@ -516,11 +540,11 @@ export async function start(context) { await saveConfig(); } startJob(repo); - return send(res, 200, { repo: publicRepo(repo) }); + return send(res, 200, { repo: publicRepo(repo, getLang()) }); } if ((m = p.match(/^\/api\/repos\/([^/]+)\/sync$/))) { const repo = findRepo(m[1]); - if (method === 'POST') return send(res, 202, { job: publicJob(startJob(repo)) }); + if (method === 'POST') return send(res, 202, { job: publicJob(startJob(repo), getLang()) }); if (method === 'DELETE') { jobs.get(repo.id)?.ac.abort(); return send(res, 200, { ok: true }); @@ -545,7 +569,7 @@ export async function start(context) { if ((m = p.match(/^\/api\/repos\/([^/]+)\/report$/)) && method === 'GET') { const repo = findRepo(m[1]); const file = await readJson(reportFile(repo.id), null); - if (!file?.merged) return send(res, 404, { error: { code: 'no_report', message: '还没有分析结果' } }); + if (!file?.merged) return send(res, 404, { error: { code: 'no_report', message: msg('还没有分析结果') } }); const identity = url.searchParams.get('identity') === 'raw' ? 'raw' : 'merged'; // A report from an older algorithm is still served (no blank page); the client re-analyzes in the background. return send(res, 200, { ...file[identity], tech: file.tech, web: file.web, delta: file.delta, about: file.descs?.[''] || null, stale: file.algo !== ALGO_VERSION }); @@ -553,10 +577,10 @@ export async function start(context) { if ((m = p.match(/^\/api\/repos\/([^/]+)\/file$/)) && method === 'GET') { const repo = findRepo(m[1]); const path = url.searchParams.get('path') || ''; - if (!path || path.length > 1000) throw new GitError('invalid', '文件路径不合法'); + if (!path || path.length > 1000) throw new GitError('invalid', msg('文件路径不合法')); const model = await modelFor(repo, AbortSignal.timeout(120_000)); const d = fileDetail(model, path, { identity: identityOf(url) }); - if (!d) throw new GitError('not_found', '历史里没有这个文件'); + if (!d) throw new GitError('not_found', msg('历史里没有这个文件')); return send(res, 200, d); } if ((m = p.match(/^\/api\/repos\/([^/]+)\/person$/)) && method === 'GET') { @@ -564,15 +588,15 @@ export async function start(context) { const name = (url.searchParams.get('name') || '').slice(0, 200); const model = await modelFor(repo, AbortSignal.timeout(120_000)); const d = personDetail(model, name, { identity: identityOf(url) }); - if (!d) throw new GitError('not_found', '历史里没有这个贡献者'); + if (!d) throw new GitError('not_found', msg('历史里没有这个贡献者')); return send(res, 200, d); } if ((m = p.match(/^\/api\/repos\/([^/]+)\/map$/)) && method === 'GET') { const repo = findRepo(m[1]); - if (!repo.lastSync?.at) throw new GitError('not_found', '还没有分析结果'); + if (!repo.lastSync?.at) throw new GitError('not_found', msg('还没有分析结果')); const q = url.searchParams; const focus = (q.get('focus') || '').replace(/^\/+|\/+$/g, ''); - if (focus.length > 1000) throw new GitError('invalid', '目录路径不合法'); + if (focus.length > 1000) throw new GitError('invalid', msg('目录路径不合法')); const range = ['3', '6', '12', 'all'].includes(q.get('range') || '') ? q.get('range') : 'all'; const model = await modelFor(repo, AbortSignal.timeout(120_000)); const file = await readJson(reportFile(repo.id), null); @@ -585,7 +609,7 @@ export async function start(context) { risk: new Set((file?.merged?.highRisk || []).map((h) => h.path)), descs: file?.descs || {}, }); - if (!view) throw new GitError('not_found', 'HEAD 中没有这个目录(可能已删除或改名)'); + if (!view) throw new GitError('not_found', msg('HEAD 中没有这个目录(可能已删除或改名)')); return send(res, 200, view); } if ((m = p.match(/^\/api\/repos\/([^/]+)\/search$/)) && method === 'GET') { @@ -599,7 +623,7 @@ export async function start(context) { const b = await body(req); if (typeof b.proxy === 'string') { const px = b.proxy.trim(); - if (px && !/^(https?|socks5h?):\/\/[^\s]+$/i.test(px)) throw new GitError('invalid', '代理地址应类似 http://127.0.0.1:7890'); + if (px && !/^(https?|socks5h?):\/\/[^\s]+$/i.test(px)) throw new GitError('invalid', msg('代理地址应类似 http://127.0.0.1:7890')); config.settings.proxy = px; } if (Array.isArray(b.scanRoots)) { @@ -608,7 +632,7 @@ export async function start(context) { } if (b.token && typeof b.token.host === 'string') { const host = b.token.host.trim().toLowerCase(); - if (!HOST_RE.test(host)) throw new GitError('invalid', '主机名不合法'); + if (!HOST_RE.test(host)) throw new GitError('invalid', msg('主机名不合法')); const t = String(b.token.value || '').trim(); if (t) config.settings.tokens[host] = t; else delete config.settings.tokens[host]; @@ -617,12 +641,16 @@ export async function start(context) { await saveConfig(); return send(res, 200, await stateBody()); } - send(res, 404, { error: { code: 'not_found', message: '接口不存在' } }); + send(res, 404, { error: { code: 'not_found', message: msg('接口不存在') } }); } await resolveProxy(); const server = createServer((req, res) => { - handle(req, res).catch((e) => (res.headersSent ? res.end() : fail(res, e))); + // Each request runs in its own language, so a slow one keeps the language it + // started with while other requests are being served. + withLang(req.headers['x-rr-lang'], () => { + handle(req, res).catch((e) => (res.headersSent ? res.end() : fail(res, e))); + }); }); await new Promise((resolve, reject) => { server.once('error', reject); @@ -641,7 +669,7 @@ export async function start(context) { clearInterval(heartbeat); for (const j of jobs.values()) j.ac?.abort(); for (const c of children) killTree(c); - for (const s of streams) { + for (const s of streams.keys()) { try { s.end(); } catch {} diff --git a/plugins/yujiachen-y/repo-xray/miniapp/node/techstack.mjs b/plugins/yujiachen-y/repo-xray/miniapp/node/techstack.mjs index d5dc7120..cd7e9ed2 100644 --- a/plugins/yujiachen-y/repo-xray/miniapp/node/techstack.mjs +++ b/plugins/yujiachen-y/repo-xray/miniapp/node/techstack.mjs @@ -1,4 +1,5 @@ // @ts-check +import { msgBoth } from './i18n.mjs'; const IGNORE_DIR = /(^|\/)(node_modules|vendor|third_party|3rdparty|dist|build|out|target|\.next|\.nuxt|coverage|__pycache__|Pods|\.yarn|bower_components|\.venv|venv)\//; @@ -340,7 +341,7 @@ export function buildTechStack(tree, blobs, manifests) { depCount.set(d, (depCount.get(d) || 0) + 1); } } - if (workspaces || pkgCount > 3) add('npm workspaces / monorepo', 'Monorepo', `${pkgCount} 个 package.json`); + if (workspaces || pkgCount > 3) add('npm workspaces / monorepo', 'Monorepo', msgBoth('{0} 个 package.json', pkgCount)); if (goVersion) add(`Go ${goVersion}`, '语言与运行时', 'go.mod'); for (const e of engines) add(e, '语言与运行时', 'package.json engines'); diff --git a/plugins/yujiachen-y/repo-xray/package.json b/plugins/yujiachen-y/repo-xray/package.json index aab6b8dc..3f3d4156 100644 --- a/plugins/yujiachen-y/repo-xray/package.json +++ b/plugins/yujiachen-y/repo-xray/package.json @@ -1,4 +1,5 @@ { + "type": "module", "mcode": { "schemaVersion": 2, "miniApp": "./miniapp/miniapp.json" diff --git a/plugins/yujiachen-y/repo-xray/tests/i18n.test.mjs b/plugins/yujiachen-y/repo-xray/tests/i18n.test.mjs new file mode 100644 index 00000000..f9ae79de --- /dev/null +++ b/plugins/yujiachen-y/repo-xray/tests/i18n.test.mjs @@ -0,0 +1,368 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const read = (p) => readFileSync(join(root, p), 'utf8'); + +const CLIENT = ['miniapp/client/app.js', 'miniapp/client/charts.js', 'miniapp/client/pending.js']; +const NODE = ['miniapp/node/git.mjs', 'miniapp/node/server.mjs', 'miniapp/node/analyze.mjs']; +// These two carry the canonical Chinese category names and the punctuation the page +// translates by name, so their Chinese is not a message of their own. +const NODE_CATEGORIES = ['miniapp/node/codemap.mjs', 'miniapp/node/techstack.mjs']; + +const CJK = /[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]/; + +/** Placeholder names used in a template, e.g. "{0} files" -> ["0"]. */ +const placeholders = (s) => [...s.matchAll(/\{(\d+)\}/g)].map((m) => m[1]); + +/** The value a string literal has at runtime, with its JavaScript escapes resolved. */ +function unescape(s, quote) { + let out = ''; + for (let i = 0; i < s.length; i += 1) { + const c = s[i]; + if (c !== '\\') { out += c; continue; } + const n = s[++i]; + if (n === 'u') { + if (s[i + 1] === '{') { const j = s.indexOf('}', i + 1); out += String.fromCodePoint(parseInt(s.slice(i + 2, j), 16)); i = j; continue; } + out += String.fromCharCode(parseInt(s.slice(i + 1, i + 5), 16)); i += 4; continue; + } + if (n === 'x') { out += String.fromCharCode(parseInt(s.slice(i + 1, i + 3), 16)); i += 2; continue; } + if (n === quote) { out += n; continue; } + if (n === 'n') { out += '\n'; continue; } + if (n === 't') { out += '\t'; continue; } + if (n === 'r') { out += '\r'; continue; } + if (n === '\n') continue; + out += n; + } + return out; +} + +/** + * Every literal in a source file, with the text it shows and the quote it uses. + * Template literals report their literal-text chunks; the expressions inside + * ${...} are scanned too, so nested literals are found as well. + */ +function literals(src) { + const out = []; + const n = src.length; + + const scanTemplate = (start) => { + let j = start + 1; + let text = ''; + while (j < n) { + const c = src[j]; + if (c === '\\') { text += c + src[j + 1]; j += 2; continue; } + if (c === '`') return { end: j + 1, text }; + if (c === '$' && src[j + 1] === '{') { + let depth = 1, k = j + 2; + while (k < n && depth > 0) { + const d = src[k]; + if (d === "'" || d === '"') { + const q = d; const s0 = k; k++; + while (k < n) { if (src[k] === '\\') { k += 2; continue; } if (src[k] === q) break; k++; } + out.push({ start: s0, end: k + 1, text: unescape(src.slice(s0 + 1, k), q), quote: q }); + k++; continue; + } + if (d === '`') { const t = scanTemplate(k); out.push({ start: k, end: t.end, text: unescape(t.text, '`'), quote: '`' }); k = t.end; continue; } + if (d === '{') depth++; + else if (d === '}') { depth--; if (depth === 0) { k++; break; } } + k++; + } + j = k; continue; + } + text += c; j++; + } + return { end: n, text }; + }; + + const REGEX_PRE = new Set(['(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '~', '^', '<', '>']); + let lastSig = ''; + const regexAllowed = () => (lastSig === '' ? true : /[A-Za-z0-9_$]/.test(lastSig) ? false : REGEX_PRE.has(lastSig)); + const scanRegex = (k) => { + let j = k + 1, inClass = false; + while (j < n) { + const c = src[j]; + if (c === '\\') { j += 2; continue; } + if (c === '[') inClass = true; + else if (c === ']') inClass = false; + else if (c === '/' && !inClass) { j++; break; } + j++; + } + while (j < n && /[a-z]/.test(src[j])) j++; + return j; + }; + + let i = 0; + while (i < n) { + const c = src[i], c2 = src[i + 1]; + if (c === '/' && c2 === '/') { const e = src.indexOf('\n', i); i = e === -1 ? n : e; continue; } + if (c === '/' && c2 === '*') { const e = src.indexOf('*/', i + 2); i = e === -1 ? n : e + 2; continue; } + if (c === '/' && regexAllowed()) { const e = scanRegex(i); lastSig = src[e - 1]; i = e; continue; } + if (c === "'" || c === '"') { + const q = c, start = i; + let j = i + 1; + while (j < n) { if (src[j] === '\\') { j += 2; continue; } if (src[j] === q) break; j++; } + out.push({ start, end: j + 1, text: unescape(src.slice(start + 1, j), q), quote: q }); + lastSig = q; + i = j + 1; continue; + } + if (c === '`') { + const t = scanTemplate(i); + out.push({ start: i, end: t.end, text: unescape(t.text, '`'), quote: '`' }); + lastSig = 'x'; + i = t.end; continue; + } + if (!/\s/.test(c)) lastSig = c; + i++; + } + return out; +} + +/** The code right before a literal, with whitespace trimmed. */ +const before = (src, at) => src.slice(0, at).replace(/\s+$/, ''); + +/** Every entry of the catalogue: the Chinese key and the English reading or readings. */ +const catalog = read('miniapp/client/strings.js'); +// The trailing comma is optional, so the last entry cannot drop out of the checks. +const catalogEntries = [...catalog.matchAll(/^ {2}("(?:[^"\\]|\\.)*"): (.+?)(?:,)?$/gm)].map((m) => ({ + key: JSON.parse(m[1]), + readings: [...m[2].matchAll(/"(?:[^"\\]|\\.)*"/g)].map((v) => JSON.parse(v[0])), +})); +const catalogKeys = new Set(catalogEntries.map((e) => e.key)); + +test('the client catalog covers every string the page shows', () => { + const missing = []; + let checked = 0; + for (const file of CLIENT) { + const src = read(file); + for (const lit of literals(src)) { + if (!/\btr(Alt)?\($/.test(before(src, lit.start))) continue; + checked += 1; + if (!catalogKeys.has(lit.text)) missing.push(`${file}: ${JSON.stringify(lit.text)}`); + } + } + assert.ok(checked > 100, `the scanner only found ${checked} strings`); + assert.deepEqual(missing, [], `strings the page asks for but the catalog does not have:\n${missing.join('\n')}`); +}); + +test('the client catalog covers the static labels in the page shell', () => { + const html = read('miniapp/client/index.html'); + const missing = []; + for (const m of html.matchAll(/data-i18n(?:-aria)?="([^"]*)"/g)) { + if (!catalogKeys.has(m[1])) missing.push(JSON.stringify(m[1])); + } + assert.deepEqual(missing, [], `static labels with no translation:\n${missing.join('\n')}`); +}); + +// One entry reorders its arguments on purpose: the Chinese puts the count first. +const REORDERED = new Set([',占{0}的 {1}']); + +test('the client catalog and the page agree on the placeholders', () => { + const wrong = []; + for (const { key, readings } of catalogEntries) { + const sorted = placeholders(key).slice().sort().join(','); + for (const value of readings) { + const b = placeholders(value); + if (b.slice().sort().join(',') !== sorted) { + wrong.push(`${JSON.stringify(key)} has [${sorted}] but its English has [${b.join(',')}]`); + continue; + } + if (b.join(',') !== placeholders(key).join(',') && !REORDERED.has(key)) { + wrong.push(`${JSON.stringify(key)} reorders its arguments as [${b.join(',')}]`); + } + } + } + assert.deepEqual(wrong, [], `placeholders that do not line up:\n${wrong.join('\n')}`); +}); + +test('the catalog does not number a key to tell two readings apart', () => { + const numbered = [...catalogKeys].filter((k) => /#\d+\s*$/.test(k)); + assert.deepEqual(numbered, [], `keys that disambiguate with a number:\n${numbered.join('\n')}`); +}); + +test('the client modules import what they use', () => { + for (const file of CLIENT) { + const src = read(file); + const imported = /import \{([^}]*)\} from '\.\/i18n\.js'/.exec(src); + const names = imported ? imported[1].split(',').map((s) => s.trim().replace(/^\w+\s+as\s+/, '')) : []; + for (const fn of ['tr', 'trAlt', 'localeTag', 'getLang', 'langIsStored', 'displayText', 'toggleLang']) { + const uses = new RegExp(`(? { + // the language switcher's own labels, and the canonical Chinese category names + // the Node side sends, are Chinese on purpose + const KEEP = [' 语言:中文', '语言与运行时', '工程实践', '代码质量']; + const unwrapped = []; + for (const file of CLIENT) { + const src = read(file); + for (const lit of literals(src)) { + if (!CJK.test(lit.text)) continue; + if (KEEP.includes(lit.text)) continue; + if (/tr(Alt)?\($/.test(before(src, lit.start))) continue; + unwrapped.push(`${file}: ${JSON.stringify(lit.text).slice(0, 70)}`); + } + } + assert.deepEqual(unwrapped, [], `Chinese strings that are never translated:\n${unwrapped.join('\n')}`); +}); + +test('the Node message table holds a Chinese and an English string', () => { + const table = read('miniapp/node/i18n.mjs'); + const entries = [...table.matchAll(/^ {2}("(?:[^"\\]|\\.)*"): \[("(?:[^"\\]|\\.)*"), ("(?:[^"\\]|\\.)*")\],?/gm)]; + assert.ok(entries.length > 0, 'the Node message table is empty'); + const bad = []; + for (const [, k, zh, en] of entries) { + const key = JSON.parse(k); + if (JSON.parse(zh) !== key) bad.push(`${JSON.stringify(key)} does not list itself as the Chinese text`); + const a = placeholders(key).join(','); + const b = placeholders(JSON.parse(en)).join(','); + if (a !== b) bad.push(`${JSON.stringify(key)} has [${a}] but its English has [${b}]`); + } + assert.deepEqual(bad, [], `malformed Node messages:\n${bad.join('\n')}`); +}); + +test('the Node modules only ask for messages the table has', () => { + const table = read('miniapp/node/i18n.mjs'); + const keys = new Set([...table.matchAll(/^ {2}("(?:[^"\\]|\\.)*"): \[/gm)].map((m) => JSON.parse(m[1]))); + const missing = []; + let checked = 0; + for (const file of [...NODE, ...NODE_CATEGORIES]) { + const src = read(file); + for (const lit of literals(src)) { + const b = before(src, lit.start); + // The key is the literal itself when the call takes it first, or second after + // the language or the error code. + const one = /\b(?:msg|msgBoth)\($/.test(b); + const two = /\b(?:msgIn|fail)\([^,()]*,\s*$/.test(b); + if (!one && !two) continue; + const key = lit.text; + checked += 1; + if (!keys.has(key)) missing.push(`${file}: ${JSON.stringify(key)}`); + } + } + assert.ok(checked > 40, `the scanner only found ${checked} messages`); + assert.deepEqual(missing, [], `Node messages with no translation:\n${missing.join('\n')}`); +}); + +test('no Chinese string is left unwrapped in the Node modules', () => { + // two labels are baked into the history on purpose: the page swaps them for display + const KEEP = ['(令牌)', '(根目录)']; + const unwrapped = []; + for (const file of NODE) { + const src = read(file); + for (const lit of literals(src)) { + if (!CJK.test(lit.text)) continue; + if (KEEP.includes(lit.text)) continue; + if (/\b(?:msg|msgIn|msgBoth|fail)\((?:[^,()]*,\s*)?$/.test(before(src, lit.start))) continue; + unwrapped.push(`${file}: ${JSON.stringify(lit.text).slice(0, 70)}`); + } + } + assert.deepEqual(unwrapped, [], `Chinese strings that are never translated:\n${unwrapped.join('\n')}`); +}); + +test('the page and the Node side word the messages they share the same way', () => { + const table = read('miniapp/node/i18n.mjs'); + const node = new Map([...table.matchAll(/^ {2}("(?:[^"\\]|\\.)*"): \["(?:[^"\\]|\\.)*", ("(?:[^"\\]|\\.)*")\],?/gm)].map((m) => [JSON.parse(m[1]), JSON.parse(m[2])])); + const client = new Map(catalogEntries.map((e) => [e.key, e.readings[0]])); + const shared = [...node.keys()].filter((k) => client.has(k)); + const differ = shared.filter((k) => client.get(k) !== node.get(k)); + assert.deepEqual(differ, [], `messages the two layers word differently:\n${differ.join('\n')}`); +}); + +test('the page tells the server which language it is in', () => { + const src = read('miniapp/client/app.js'); + const api = /async function api\([^)]*\) \{([\s\S]*?)\n\}/.exec(src); + assert.ok(api, 'the api() helper is not there'); + assert.match(api[1], /'x-rr-lang':\s*getLang\(\)/, 'api() does not send the language header'); + // EventSource cannot send headers, so the stream states its language in the URL. + assert.match(src, /new EventSource\('\/api\/stream\?lang=' \+ getLang\(\)\)/, 'the event stream does not state its language'); +}); + +test('every string read with tAlt has a second English reading', () => { + const alt = []; + for (const file of CLIENT) { + const src = read(file); + for (const lit of literals(src)) { + if (!/\btrAlt\($/.test(before(src, lit.start))) continue; + alt.push({ file, key: lit.text }); + } + } + assert.ok(alt.length > 0, 'no tAlt() call found in the client'); + const bad = []; + for (const { file, key } of alt) { + const entry = catalogEntries.find((e) => e.key === key); + if (!entry) { + bad.push(`${file}: ${JSON.stringify(key)} is not in the catalog`); + continue; + } + if (entry.readings.length < 2) bad.push(`${file}: ${JSON.stringify(key)} has only one reading`); + } + assert.deepEqual(bad, [], `strings read with tAlt() that have no second reading:\n${bad.join('\n')}`); +}); + +test('the catalog scanner finds a string whatever quote it uses', () => { + // A scanner that matches nothing passes every catalog check; prove it bites. + const src = 'const a = tr(\'未翻译的中文\');'; + const found = []; + for (const lit of literals(src)) { + if (!/\btr(Alt)?\($/.test(before(src, lit.start))) continue; + found.push(lit.text); + } + assert.deepEqual(found, ['未翻译的中文']); + assert.ok(!catalogKeys.has('未翻译的中文')); +}); + +test('tAlt gives the second English reading and leaves the Chinese alone', async () => { + const i18n = await import('../miniapp/client/i18n.js'); + const before = i18n.getLang(); + i18n.toggleLang(); + try { + assert.equal(i18n.getLang(), 'en'); + assert.equal(i18n.t('文件'), 'Files'); + assert.equal(i18n.tAlt('文件'), 'File'); + assert.equal(i18n.tAlt('最近一次修改在 {0}', '2 days ago'), 'Last change on 2 days ago'); + } finally { + if (i18n.getLang() !== before) i18n.toggleLang(); + } + assert.equal(i18n.t('文件'), '文件'); + assert.equal(i18n.tAlt('文件'), '文件'); +}); + +test('every tech-stack label the Node side sends has an English reading', () => { + const table = read('miniapp/node/i18n.mjs'); + // A literal that is a message key is translated by the Node table, not by the page. + const messageKeys = new Set([...table.matchAll(/^ {2}("(?:[^"\\]|\\.)*"): \[/gm)].map((m) => JSON.parse(m[1]))); + const src = read('miniapp/node/techstack.mjs'); + const labels = new Set(); + for (const m of src.matchAll(/'(?:[^'\\]|\\.)*'/g)) { + const value = m[0].slice(1, -1); + if (CJK.test(value) && !messageKeys.has(value)) labels.add(value); + } + assert.ok(labels.size > 0, 'no tech-stack labels found'); + const missing = [...labels].filter((l) => !catalogKeys.has(l)); + assert.deepEqual(missing, [], `tech-stack labels with no English reading:\n${missing.join('\n')}`); +}); + +test('the client localises the names it renders', () => { + const src = read('miniapp/client/app.js'); + assert.ok(src.includes('esc(displayText(c.author))'), 'the commit row shows the raw author name'); + assert.ok(src.includes('esc(displayText(name))'), 'the person drawer shows the raw name'); + assert.ok(src.includes('plainName(name)'), 'the avatar slices the marked name'); +}); + +test('the charts render', async () => { + const charts = await import('../miniapp/client/charts.js'); + const point = { x: 3, y: 4, r: 2, label: 'a', color: '#fff', username: 'a' }; + const out = charts.scatter({ points: [point] }); + assert.ok(out.includes(' readFileSync(join(root, p), 'utf8'); + +test('the pending removal queue round-trips through storage', () => { + const queue = new Map([ + ['r-1', { until: 1000 }], + ['r-2', { until: 2000 }], + ]); + assert.deepEqual(decodePending(encodePending(queue)), [ + { id: 'r-1', until: 1000 }, + { id: 'r-2', until: 2000 }, + ]); +}); + +test('a queue that cannot be read is dropped rather than guessed at', () => { + assert.deepEqual(decodePending(''), []); + assert.deepEqual(decodePending('not json'), []); + assert.deepEqual(decodePending('{"id":"r-1"}'), []); + assert.deepEqual(decodePending('[{"until":1000}]'), []); + assert.deepEqual(decodePending('[{"id":"r-1","until":"soon"}]'), [{ id: 'r-1', until: 0 }]); +}); + +test('the undo window keeps its length and never runs backwards', () => { + assert.equal(UNDO_MS, 8000); + assert.equal(pendingLeft(1000, 500), 500); + assert.equal(pendingLeft(1000, 1000), 0); + assert.equal(pendingLeft(500, 1000), 0); +}); + +test('every client file is served by the server', () => { + const server = read('miniapp/node/server.mjs'); + const served = new Set([...server.matchAll(/'\/assets\/([^']+)':/g)].map((m) => m[1])); + const files = readdirSync(join(root, 'miniapp/client')).filter((f) => f !== 'index.html'); + const missing = files.filter((f) => !served.has(f)); + const stale = [...served].filter((f) => !files.includes(f)); + assert.deepEqual(missing, [], `client files the server does not serve: ${missing.join(', ')}`); + assert.deepEqual(stale, [], `served client files that are gone: ${stale.join(', ')}`); +}); + +test('the page keeps the queue where a reload can find it', () => { + const app = read('miniapp/client/app.js'); + assert.match(app, /sessionStorage\.setItem\(PENDING_KEY, encodePending\(state\.pendingRemoval\)\)/); + assert.match(app, /decodePending\(sessionStorage\.getItem\(PENDING_KEY\)\)/); + assert.match(read('miniapp/client/pending.js'), /export const PENDING_KEY = 'rr-pending-removals';/); + // The boot path restores the queue after the state is loaded and before the + // route is applied, so the repository stays hidden and the DELETE still runs. + const boot = app.slice(app.lastIndexOf('(async () => {')); + assert.ok(boot.indexOf('await loadState();') < boot.indexOf('resumePendingRemovals();')); + assert.ok(boot.indexOf('resumePendingRemovals();') < boot.indexOf('await applyRoute();')); +});