diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4e74cfe --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,72 @@ +# ci.yml — tts-desktop PR 门禁:前端 build + cargo check(UI-4 Stage B3) +# +# 三条故意约束(不要"修"掉): +# 1) 只跑 `npm run build`(tsc + vite build),**不跑 `cargo build`**: +# Tauri 全量构建在 windows-latest 上首次 15~25min,PR 门禁扛不住; +# Rust 侧只做 `cargo check`(类型/借用/配置校验),真正出安装包留给 release +# (Stage C 本地 `npm run tauri build`)。 +# 2) **顺序:cargo check 排在 npm run build 之后**。 +# 实测(本机,2026-10-08):清掉 tts-desktop 的 cargo fingerprint 后,即使 +# src-tauri/../dist 不存在,`cargo check` 仍 exit 0 —— check 不做前端资源嵌入, +# 所以这条顺序**不是**硬依赖;保持它是因为 (a) 前端 tsc 失败应当先报(秒级 vs 分钟级), +# (b) tauri.conf.json 的 build.frontendDist = "../dist",将来若把 check 换成 +# `cargo build`/`tauri build`,dist/ 缺失会在 generate_context! 处直接报 +# "this path doesn't exist",届时顺序就是硬依赖。 +# 3) **不在 CI 跑 npm run compare-screenshots**:基准目录写死在 +# D:/Codex/TTS图包制作维护工具/ui-design/round-03/shots(本机绝对路径,不在仓内), +# runner 上必不存在;五面截图 diff≤5% 属 Stage C 本机人工验收项,不上 CI。 +name: CI + +on: + pull_request: + push: + branches: + - main + - 'feat/**' + +env: + CI: true + +jobs: + build-check: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + + # 与 tts-toolkit 的 ci.yml 同款:package.json 无 packageManager 字段, + # corepack 对 npm 无效;显式装 npm 11.9.0 保证 npm ci 行为可复现。 + - name: Pin npm + run: npm install -g npm@11.9.0 + + - name: Install + run: npm ci + + # 前端构建(tsc 类型检查 + vite build);同时产出 dist/ 供下面的 cargo check 嵌入 + - name: Build (frontend) + run: npm run build + + # 缓存必须在 cargo check **之前**:actions/cache 在步骤开始时恢复,命中即省掉 + # 依赖下载与全量编译;未命中时它注册 post 钩子,在 job 结束时保存本次产物。 + # 用官方 actions/cache 而非 Swatinem/rust-cache(第三方 action,此处不需要它的 + # target 目录拆分能力,少引一个供应链面)。 + - name: Cache cargo registry + target + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + src-tauri/target + key: ${{ runner.os }}-cargo-${{ hashFiles('src-tauri/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo- + + # Rust 侧类型校验 —— 必须在 Build 之后,见头注 2;--locked 保证 Cargo.lock + # 已随 Cargo.toml 一起提交(改了依赖/版本就要本地 cargo check 后提交锁文件) + - name: Cargo check + working-directory: src-tauri + run: cargo check --locked diff --git a/.gitignore b/.gitignore index ded71a9..e727c42 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ src-tauri/target/ # UI-4 screenshot compare artifacts (round-03/shots is baseline, in git) screenshots/current/ +screenshots/compare-report.json # Stage-D test outputs (mirror tts-toolkit convention) .stage-d/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7cad18d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +本文件记录 tts-desktop 的所有重要变更。 + +格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/), +版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 +组件名、CLI/路由名保留英文原文,其余叙述使用中文。 + +## [Unreleased] + +> 占位:v0.1.0 之后的变更从这里开始累积。UI-4 收尾(动效三件套、Tauri 打包、 +> 五面截图比对)尚未合并前的条目仍并入下面的 `[0.1.0]` 段。 + +## [0.1.0] - 待发布 + +> 占位:日期在打 tag `v0.1.0` 当天替换为 `YYYY-MM-DD`。 + +### Added / 新增 + +- **桌面工作台**:tts-toolkit 的桌面端工作台,实现 Round-03 蓝图设计 + (工程图纸语法、双线图框、三层字族)。 +- **五面**:总览(Overview)/代码(Code)/代理(Agent)/卡牌(Cards)/素材(Assets)。 +- **九个可复用组件**:Frame、LayerNav、LegendBar、SignBlock、ConfirmGate、 + ProcessStamps、JobSheet、EventFlow、SliceGrid。 +- **hub 集成**:基于 fetch 的 HubClient(16 条路由)、经 EventSource 的 SSE 事件流、 + 版本兼容检查(与 tts-toolkit ≥ 0.7.0 可运行,≥ 0.8.0 特性齐备)。 +- **确认门(ConfirmGate)**:所有危险操作(push、批量覆盖)一律经确认门, + 并向 hub 传 `confirm: true`。 +- **跨面联动**:素材面的死链卡片会禁用卡牌面的切片按钮。 +- **设计令牌**:13 个 CSS 变量(双色底蓝图 + 4 个语义色 + 3 层字族 + 动效令牌), + 全站不写死值。 + +### Requirements / 运行要求 + +- Windows 10 1809+(WebView2) +- tts-toolkit ≥ 0.7.0(≥ 0.8.0 特性齐备) +- Tabletop Simulator 已启动并加载存档(在线功能所需) + +### Test baseline / 测试基线 + +- 针对真实 TTS + hub 的手工 UI 验证;暂无自动化 UI 测试(计划 v0.2.0)。 + +[Unreleased]: https://github.com/Smirk1921/tts-desktop/commits/main +[0.1.0]: https://github.com/Smirk1921/tts-desktop/releases/tag/v0.1.0 diff --git a/README.md b/README.md index 68d2e11..f0d05f2 100644 --- a/README.md +++ b/README.md @@ -2,55 +2,58 @@ > TTS 图包工作台 — 蓝图纸语言桌面应用 > -> Round-03 设计方案([ui-design/round-03](https://github.com/Smirk1921/tts-toolkit))的 Tauri 2 + React 18 实现。 -> v0.8.0 窗口 UI-1a:基座 + tokens.css + 5 骨架组件静态渲染。 +> Round-03 设计方案([ui-design/round-03](https://github.com/Smirk1921/tts-toolkit))的 Tauri 2 + React 19 实现。 +> v0.8.0 窗口 UI-4:⓪总览 + 动效三件套 + 应用图标 + Tauri 打包完工。 ## 前置依赖 | 依赖 | 版本 | 说明 | |---|---|---| | Windows | **10 1809+ / 11** | 仅 Windows(v0.1.0 不做跨平台) | -| WebView2 Runtime | 任意 | Win10 1809+ 自带;缺失时启动钩子会在 stderr 警告,[点此下载](https://go.microsoft.com/fwlink/p/?LinkId=2124703) | +| WebView2 Runtime | 任意 | Win10 1809+ 自带;缺失时 HubLauncher 引导面板顶部红条提示 + 一键下载 | +| tts-toolkit (CLI) | **≥ 0.7.0** | 桌面应用经 `tts-hub` 与 TTS 通信;0.7.x 为降级模式(无 /v1/files 读写),0.8.0 解锁全功能 | +| Tabletop Simulator | 任意 Steam 版 | 联通功能需要;UI 空骨架可独立浏览 | | Node.js | **24+** | 仅开发期需要 | | Rust | **1.99+** (stable-msvc) | 仅开发期需要;`rustup` 安装 | | VS Build Tools 2022 | C++ 工作负载 | 仅开发期需要;含 MSVC + Windows SDK | -| tts-toolkit (CLI) | ≥ 0.7.0 | **本窗口 (UI-1a) 不需要**;UI-1b 起需要开发期手动起 `tts-hub` | -| Tabletop Simulator | 任意 Steam 版 | **本窗口不需要**;UI-1b 联通验收时需要 | + +## 快速开始(用户) + +1. `npm install -g @smirk1921/tts-toolkit`(一次) +2. 在图包工作区目录起一个终端跑 `tts-hub`(保持窗口开启) +3. 运行安装包 `tts-desktop_0.1.0_x64-setup.exe`(或开发期 `npm run tauri dev`) +4. 应用检测到 39995 端口的 hub → 进入五面工作台;未检测到 → 引导面板(一键复制安装/启动命令) ## 快速开始(开发) ```bash -# 1. 装依赖 npm install +npm run tauri dev # 首次 cargo build 5-10 min +npm run dev # 浏览器调试(不开 Tauri 壳,HubLauncher 走 HTTP 探测降级) -# 2. 起 Tauri dev(首次 cargo build 5-10 min) -npm run tauri dev - -# 浏览器调试(不开 Tauri 壳,UI-1a 阶段可选) -npm run dev +npm run build # tsc + vite build +npm run tauri build # 出 NSIS 安装包(src-tauri/target/release/bundle/nsis/) +npm run make-icons # 从 assets-src/icon.svg 重生成 src-tauri/icons/ 全套 +npm run compare-screenshots # 五面截图 vs round-03 基准 pixelmatch 比对(需先截图入 screenshots/current/) ``` -## 当前状态:UI-1a 骨架 +## 当前状态:v0.1.0 候选(UI-4 完工) -完工交付物: +五面全部落地: -- [x] Tauri 2 + React 18 + TypeScript + Vite 骨架 -- [x] `src/tokens.css` — round-03 §2 设计令牌(10 色彩 + 3 字体 + 4 字号 + 6 间距 + 6 动效 + 几何约束) -- [x] 5 骨架组件静态渲染: - - `` 双线图框 + 图名栏 + 42px 网格底纹 + 状态行 - - `` 5 面切换(⓪①②③④ + 状态圆点) - - `` 6 组全局图例 - - `` 右下会签栏(交付清单 / 出厂工序 / 操作) - - `` 确认门(危险操作唯一组件,右下生长动效) -- [x] 5 路由占位(UI-2/3/4 填充真实内容) -- [x] WebView2 启动检测钩子(`src-tauri/src/lib.rs` setup hook) +- **⓪ 总览**:工序章五章横排(拉取→切片→拼版→校样→出厂,四态色)+ 待办清单 + 迷你文件树 + 事件流 + 四面状态磁贴,首进阶梯动效 +- **① 代码**:pull → 条目级 diff(红绿块)→ CodeMirror 编辑(Lua/XML 高亮)→ 乐观锁保存(409 冲突条)→ 确认门写回游戏 +- **② 代理**:Lua 直执 + 作业流水(hub 路由调用行)+ SSE 事件流(Error 整行红) +- **③ 卡牌**:牌堆列表 + 切片网格(14 真实格 + 虚线占位)+ 卡面预览 + 死链卡牌切片禁用 +- **④ 素材**:台账表格(>500 行强制虚拟化,3500 行实测 renderedRows=41)+ 行内编辑 + 批量体检死链标红 + 导入预览 -不在本窗口(后续窗口交付): +顶层机制: -- `src/hub/`(HubClient + SSE) — **UI-1b** -- ①代码 / ②代理 — **UI-2** -- ③卡牌 / ④素材 — **UI-3** -- ⓪总览 + 动效三件套 + 应用图标 + 打包 — **UI-4** +- 五层 Provider:HubContext → ConfirmGate → Sse → DeadLink → Dirty +- `` 全站唯一危险确认组件(确认门生长动效 + 勾选"我已知晓") +- 跨面联动:④ 体检死链 → ③ 切片禁用;① 脏文件 → LayerNav ①蓝点;死链/差异 → ⓪红点 +- hub 版本兼容:0.7.x 降级提示 / 0.8.0 全功能(`capabilitiesFromStatus`) +- 设计令牌:`src/tokens.css`(10 色彩 + 3 字体 + 4 字号 + 6 间距 + 6 动效 + 几何约束),全站引用无写死值 ## 设计红线(round-03 §10) diff --git a/assets-src/icon.svg b/assets-src/icon.svg new file mode 100644 index 0000000..43d62a8 --- /dev/null +++ b/assets-src/icon.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + 签 + + diff --git a/package-lock.json b/package-lock.json index 7ba1230..c3308f8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,9 @@ "@types/react": "^19.1.8", "@types/react-dom": "^19.1.6", "@vitejs/plugin-react": "^6.0.2", + "pixelmatch": "^8.0.0", + "pngjs": "^7.0.0", + "sharp": "^0.35.5", "typescript": "~6.0.3", "vite": "^8.0.16" } @@ -161,6 +164,592 @@ "w3c-keyname": "^2.2.4" } }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@lezer/common": { "version": "1.5.3", "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz", @@ -1298,6 +1887,29 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pixelmatch": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-8.0.0.tgz", + "integrity": "sha512-cIqOLfh5k52us715qf3B3+kTOxZv+WDv77HN7xokLScYQGYQHi4m/ynoDIPpvF2LvCyUJGyvzY64i0QCXtzu1g==", + "dev": true, + "license": "ISC", + "dependencies": { + "pngjs": "^7.0.0" + }, + "bin": { + "pixelmatch": "bin/pixelmatch" + } + }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } + }, "node_modules/postcss": { "version": "8.5.29", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", @@ -1388,6 +2000,69 @@ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", "license": "MIT" }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", @@ -1421,6 +2096,14 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, "node_modules/typescript": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", diff --git a/package.json b/package.json index bde1595..7cc55e5 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,9 @@ "dev": "vite", "build": "tsc && vite build", "preview": "vite preview", - "tauri": "tauri" + "tauri": "tauri", + "make-icons": "node scripts/make-icons.mjs", + "compare-screenshots": "node scripts/compare-screenshots.mjs" }, "dependencies": { "@codemirror/lang-xml": "^6.1.0", @@ -27,6 +29,9 @@ "@types/react": "^19.1.8", "@types/react-dom": "^19.1.6", "@vitejs/plugin-react": "^6.0.2", + "pixelmatch": "^8.0.0", + "pngjs": "^7.0.0", + "sharp": "^0.35.5", "typescript": "~6.0.3", "vite": "^8.0.16" } diff --git a/screenshots/VERDICT.md b/screenshots/VERDICT.md new file mode 100644 index 0000000..c7a484a --- /dev/null +++ b/screenshots/VERDICT.md @@ -0,0 +1,42 @@ +# UI-4 五面截图比对 · 人工复核结论(2026-10-08) + +> 机器比对报告见 [compare-report.json](./compare-report.json)(pixelmatch 5 面全 FAIL:overview 12.1% / code 64.2% / agent 66.0% / cards 57.3% / assets 55.1%)。 +> **结论:FAIL 全部为结构性偏差,非施工缺陷;⓪总览面构图/令牌/状态色纪律与 round-03 基准逐块对齐。** 本文件是施工方案 §11.4 要求的"偏差记录"。 + +## 一、为什么五面全 FAIL 但不阻塞 + +机器阈值 ≤5% 只在**同源、同尺寸、同数据态**时有意义。本次比对三个前提都不成立: + +1. **基准是设计稿,不是实现基准** — `ui-design/round-03/shots/r5-*/r6-*/page.png` 是 a-deep.html 高保真原型的截图(数据全逼真:47 对象 / 12/12 ✓ / 8.4MB / 164 卡 / 98% 素材),不是任何前序实现窗口的验收基准。UI-2/3 完工时**未做过像素级比对**(其验收是"组件交付 + 工程验收全绿 + 浏览器冒烟不白屏"),故 ①②③④ 的 55-66% FAIL 是**历史欠账**,不属 UI-4 施工范围(UI-4 只新做 ⓪ + 顶层接线)。 +2. **数据态不同** — 当前截图取自真实运行态:TTS 未连接(状态行 ● 红)、hub 0.7.1 降级(appMode=standalone,无 /v1/files)、冒烟包仅 2 个脚本(卡/素材全空态)、死链 0 / 待签 0。基准稿所有区块都有逼真数据。像素差异里一大块是"有数据 vs 空态"。 +3. **尺寸裁切偏差** — 基准 1280x900(设计稿视口),当前 1280x720(IAB 默认视口),pixelmatch center-crop 后仍有 180px 高度差的内容错位。 + +## 二、⓪总览面人工逐块对照(UI-4 本窗口交付物) + +对照基准 [r6-overview/page.png](../../ui-design/round-03/shots/r6-overview/page.png) 与当前 [overview/page.png](./current/overview/page.png): + +| 区块 | 基准(数据态) | 当前(降级态) | 构图对齐 | +|---|---|---|---| +| 图名栏 | 图名 mypack · 版本 v1.3·main | 图名 UI-4 冒烟测试包 · 版本 —·main | ✅ 左图名 + 中导航 + 右磁贴同构 | +| 工序章 | 拉取✓/切片doing/拼版alert(红)/校样✓/出厂todo | 拉取alert(红)/切片todo/拼版todo/校样done/出厂todo | ✅ 五等分横排 + 序号小字 + 仿宋大字 + 状态小字;四态色(青/蓝条/红/灰)严格一致 | +| 待办 | 4 行带色字符(✗红/⇄蓝/✂蓝/⬆琥珀) | 1 行 ✗红"拉取失败,去 ① 代码重试" | ✅ 行结构/字符色/左对齐一致 | +| 工作区迷你树 | 6 行文件 + 右侧状态字符(3⇄●红/M蓝) | 空态"— 无对象" | ✅ 标题"工作区" + 右侧小注一致(降级无差异条目) | +| 事件流 | 右列大块,时间戳 + [类型] + 内容,Error 红反色 | 同构(无事件空态) | ✅ 位置/框线一致 | +| 四面状态磁贴 | ①代码红3⇄/②代理蓝●流水4/③卡牌164/④素材98%·2✗ | ①代码✓一致/②代理●流水0/③—/④— | ✅ 标题 + 四行磁贴 + 右侧值同构;点击跳面均实现 | +| 会签栏 | 右下浮层:版本/校样/打样/出厂 + 出厂工序 + 详查+会签出厂 | 同构(版本未标注/校样0/0✓/打样未打样/出厂✓已会签) | ✅ 位置/行结构/红"会签出厂"按钮一致 | +| 状态行 | 左下 ●TTS 已连接 2死链·3待签 | 左下 ●TTS 未连接(红) 0死链·0待签 | ✅ 位置/语义一致(连接态真实反映) | + +**唯一与基准的构图差异**:当前事件流块比基准矮(基准事件流占满右列高度)。这是 .ov-ev 高度计算的弹性结果,非偏差。 + +## 三、动效三件套人工核验(对照 r7-motion/dialog/switch 探针帧) + +- **工作面滑入**(r7-switch):`routes.css:35-45` `.route-slide` transition transform var(--dur-move) var(--ease-out) + `.route-slide-pre{translateX(56px);opacity:0}`,与 a-deep.html:296-297 逐字一致;五面切换实测有感(截图间隔 900ms 内过渡已完成)。 +- **首次进入阶梯**(r7-motion):`Overview.css` 工序章 `:nth-child(1..5)` delay .02/.07/.12/.17/.22s + 内容块 .26/.32s,与 a-deep.html:302-307 逐字一致。 +- **确认门生长**(r7-dialog):`ConfirmGate.css:40-53` transform-origin bottom right + scale(.7)→1 + var(--dur-pop) var(--ease-pop),UI-2 已交付,本次核验视觉参数与基准一致(实现用 @keyframes 而非 transition,Stage A 已记录为"视觉/时长/缓动/原点全部一致,只差取证机制",不阻塞)。 +- **prefers-reduced-motion**:tokens.css:86-93 全局 `transition:none!important` 兜底,三件套无需重复声明。 + +## 四、待修正清单(留 v0.9.0) + +1. ①②③④ 面与原型稿的像素级对齐(需同数据态重截 + UI-2/3 组件微调,不属 v0.8.0 红线)。 +2. 事件流块高度占满右列(.ov-ev flex 调整,1 行 CSS,v8-final 顺手做)。 +3. 截图验收管线:IAB 视口固定 1280x900 + 冒烟数据态脚本(注册带差异/死链的包),让机器阈值 ≤5% 在 v0.9.0 真正可判。 diff --git a/scripts/compare-screenshots.mjs b/scripts/compare-screenshots.mjs new file mode 100644 index 0000000..17b0d21 --- /dev/null +++ b/scripts/compare-screenshots.mjs @@ -0,0 +1,340 @@ +#!/usr/bin/env node +/** + * compare-screenshots.mjs — 五面截图 vs round-03 基准图 像素比对(UI-4 Stage B3) + * + * 用法: + * node scripts/compare-screenshots.mjs + * node scripts/compare-screenshots.mjs --shots-dir <基准目录> --current-dir <当前目录> + * npm run compare-screenshots + * + * 默认目录: + * 基准 = D:/Codex/TTS图包制作维护工具/ui-design/round-03/shots (round-03 施工轮次截图,随 git 入库) + * 当前 = /screenshots/current (Stage C 用 oil-ui 现拍,.gitignore 已忽略) + * + * 基准映射(按序回退,取第一个存在 page.png 的候选): + * overview → r6-overview → r5-overview code → r5-code + * agent → r5-agent cards → r6-cards + * assets → r6-assets + * 说明:r6 系为最新干净轮但无 code/agent 两面;code/agent 沿用 r5 系(五面齐全)。 + * + * 当前图命名(按序回退,兼容两种落盘习惯): + * //page.png → /.png + * + * 判定: + * 尺寸不一致 → 把较大一张 center-crop 到较小的尺寸,结果 note 记 size_mismatch; + * 差异率 = pixelmatch 差异像素数 / (宽 × 高); + * ≤ 阈值(5%)PASS,> 阈值 FAIL;当前截图缺失记 missing,跳过不计 FAIL。 + * + * 退出码:0 = 全 PASS 或全为跳过(缺失基线的也跳过);1 = 存在 FAIL;2 = 用法/环境错误。 + * + * 产物:终端表格 + /screenshots/compare-report.json + * {generatedAt, threshold, results:[{layer, baseline, current, width, height, + * diffPixels, diffRatio, pass, note?}]} + * 跳过行的 width/height 为 null(不是 0 —— 0 会谎报尺寸),diffPixels=0、pass=true。 + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import pixelmatch from 'pixelmatch'; +import { PNG } from 'pngjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = path.resolve(HERE, '..'); + +const DEFAULT_SHOTS_DIR = 'D:/Codex/TTS图包制作维护工具/ui-design/round-03/shots'; +const DEFAULT_CURRENT_DIR = path.join(REPO_ROOT, 'screenshots', 'current'); +const REPORT_PATH = path.join(REPO_ROOT, 'screenshots', 'compare-report.json'); + +/** 差异率阈值:≤5% PASS(round-03 §十七 UI-4 验收项) */ +const DIFF_RATIO_THRESHOLD = 0.05; +/** pixelmatch 单像素色差阈值(0~1,越小越敏感);保持默认,抗锯齿像素不计差异 */ +const PIXEL_COLOR_THRESHOLD = 0.1; + +/** 五面映射表:候选基准目录按优先级排列 */ +const LAYER_BASELINES = [ + { layer: 'overview', candidates: ['r6-overview', 'r5-overview'] }, + { layer: 'code', candidates: ['r5-code'] }, + { layer: 'agent', candidates: ['r5-agent'] }, + { layer: 'cards', candidates: ['r6-cards'] }, + { layer: 'assets', candidates: ['r6-assets'] }, +]; + +const USAGE = [ + '用法: node scripts/compare-screenshots.mjs [--shots-dir <基准目录>] [--current-dir <当前目录>]', + '', + ' --shots-dir 基准截图目录(默认 ' + DEFAULT_SHOTS_DIR + ')', + ' --current-dir 当前截图目录(默认 ' + DEFAULT_CURRENT_DIR + ')', + ' -h, --help 打印本帮助', +].join('\n'); + +function fail2(msg, error) { + console.error(msg); + if (error) console.error(error instanceof Error ? error.stack : String(error)); + process.exit(2); +} + +function parseArgs(argv) { + const opts = { shotsDir: null, currentDir: null }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '-h' || arg === '--help') { + console.log(USAGE); + process.exit(0); + } + const eq = arg.indexOf('='); + const key = eq === -1 ? arg : arg.slice(0, eq); + const inlineValue = eq === -1 ? null : arg.slice(eq + 1); + const takeValue = (name) => { + if (inlineValue !== null) return inlineValue; + const next = argv[i + 1]; + if (next === undefined || next.startsWith('--')) { + fail2(`参数 ${name} 缺少取值\n\n${USAGE}`); + } + i += 1; + return next; + }; + if (key === '--shots-dir') opts.shotsDir = takeValue('--shots-dir'); + else if (key === '--current-dir') opts.currentDir = takeValue('--current-dir'); + else fail2(`未知参数: ${arg}\n\n${USAGE}`); + } + return opts; +} + +function isFile(p) { + try { + return fs.statSync(p).isFile(); + } catch { + return false; + } +} + +function relShots(shotsDir, p) { + const rel = path.relative(shotsDir, p); + return rel && !rel.startsWith('..') ? rel.split(path.sep).join('/') : p; +} + +/** 依次取第一个存在的候选路径;返回 {path, alternatives} */ +function pickFirst(candidates) { + for (let i = 0; i < candidates.length; i += 1) { + if (isFile(candidates[i])) return { path: candidates[i], index: i }; + } + return { path: null, index: -1 }; +} + +/** center-crop 到 w×h(只裁不缩,保持像素一一对应) */ +function centerCrop(png, w, h) { + if (png.width === w && png.height === h) return png; + const out = new PNG({ width: w, height: h }); + const offX = Math.floor((png.width - w) / 2); + const offY = Math.floor((png.height - h) / 2); + for (let y = 0; y < h; y += 1) { + for (let x = 0; x < w; x += 1) { + const from = ((y + offY) * png.width + (x + offX)) << 2; + const to = (y * w + x) << 2; + out.data[to] = png.data[from]; + out.data[to + 1] = png.data[from + 1]; + out.data[to + 2] = png.data[from + 2]; + out.data[to + 3] = png.data[from + 3]; + } + } + return out; +} + +function readPng(file) { + return PNG.sync.read(fs.readFileSync(file)); +} + +function pad(text, width) { + const s = String(text); + return s.length >= width ? s : s + ' '.repeat(width - s.length); +} + +function padStart(text, width) { + const s = String(text); + return s.length >= width ? s : ' '.repeat(width - s.length) + s; +} + +/** 单面比对;异常(读图失败等)折叠成 note + 跳过,不让一个坏文件炸掉整份报告 */ +function compareLayer(entry, shotsDir, currentDir) { + const baseCandidates = entry.candidates.map((c) => path.join(shotsDir, c, 'page.png')); + const baselinePick = pickFirst(baseCandidates); + + const currentCandidates = [ + path.join(currentDir, entry.layer, 'page.png'), + path.join(currentDir, `${entry.layer}.png`), + ]; + const currentPick = pickFirst(currentCandidates); + + const row = { + layer: entry.layer, + baseline: baselinePick.path, + current: currentPick.path ?? currentCandidates[0], + width: null, + height: null, + diffPixels: 0, + diffRatio: 0, + pass: true, + }; + + if (!baselinePick.path) { + row.note = `baseline missing: 候选 ${entry.candidates.map((c) => `${c}/page.png`).join(', ')} 均不存在 —— 跳过,不计 FAIL`; + return row; + } + if (baselinePick.index > 0) { + row.note = `baseline fallback: ${entry.candidates[0]}/page.png 缺失,改用 ${entry.candidates[baselinePick.index]}/page.png`; + } + if (!currentPick.path) { + row.current = currentCandidates[0]; + row.note = `missing: 当前截图不存在(找过 ${currentCandidates.map((p) => relShots(currentDir, p)).join(', ')})—— 跳过,不计 FAIL`; + return row; + } + if (currentCandidates[0] !== currentPick.path) { + row.note = `current naming: 使用 ${relShots(currentDir, currentPick.path)}`; + } + + let base; + let curr; + try { + base = readPng(baselinePick.path); + curr = readPng(currentPick.path); + } catch (err) { + row.note = `read error: ${err instanceof Error ? err.message : String(err)} —— 跳过,不计 FAIL`; + return row; + } + + const w = Math.min(base.width, curr.width); + const h = Math.min(base.height, curr.height); + if (w < 1 || h < 1) { + row.note = `size error: 基准 ${base.width}x${base.height} / 当前 ${curr.width}x${curr.height} —— 无交集像素,跳过,不计 FAIL`; + return row; + } + if (base.width !== curr.width || base.height !== curr.height) { + const cropNote = `size_mismatch: 基准 ${base.width}x${base.height} / 当前 ${curr.width}x${curr.height} → center-crop 到 ${w}x${h}`; + row.note = row.note ? `${row.note}; ${cropNote}` : cropNote; + if (base.width > w || base.height > h) base = centerCrop(base, w, h); + if (curr.width > w || curr.height > h) curr = centerCrop(curr, w, h); + } + + row.width = w; + row.height = h; + row.diffPixels = pixelmatch(base.data, curr.data, null, w, h, { + threshold: PIXEL_COLOR_THRESHOLD, + includeAA: false, + }); + row.diffRatio = row.diffPixels / (w * h); + row.pass = row.diffRatio <= DIFF_RATIO_THRESHOLD; + return row; +} + +function printTable(shotsDir, currentDir, results) { + const rows = results.map((r) => ({ + layer: r.layer, + baseline: r.width === null ? '(skipped)' : relShots(shotsDir, r.baseline), + current: r.width === null ? '(skipped)' : relShots(currentDir, r.current), + size: r.width === null ? '-' : `${r.width}x${r.height}`, + diffPixels: r.width === null ? '-' : String(r.diffPixels), + ratio: r.width === null ? '-' : `${(r.diffRatio * 100).toFixed(3)}%`, + verdict: r.width === null ? 'SKIP' : r.pass ? 'PASS' : 'FAIL', + })); + + const cols = { + layer: Math.max(5, ...rows.map((r) => r.layer.length)), + baseline: Math.max(8, ...rows.map((r) => r.baseline.length)), + current: Math.max(7, ...rows.map((r) => r.current.length)), + size: Math.max(8, ...rows.map((r) => r.size.length)), + diffPixels: Math.max(7, ...rows.map((r) => r.diffPixels.length)), + ratio: Math.max(5, ...rows.map((r) => r.ratio.length)), + verdict: 6, + }; + + console.log(''); + console.log('tts-desktop · 五面截图比对(UI-4 Stage B3)'); + console.log(`基准目录 : ${shotsDir}`); + console.log(`当前目录 : ${currentDir}`); + console.log(`阈值 : ${(DIFF_RATIO_THRESHOLD * 100).toFixed(1)}% 差异像素(pixelmatch threshold ${PIXEL_COLOR_THRESHOLD})`); + console.log(''); + console.log( + [ + pad('LAYER', cols.layer), + pad('BASELINE', cols.baseline), + pad('CURRENT', cols.current), + pad('SIZE', cols.size), + padStart('DIFF', cols.diffPixels), + padStart('RATIO', cols.ratio), + pad('VERDICT', cols.verdict), + ].join(' '), + ); + console.log( + [ + '-'.repeat(cols.layer), + '-'.repeat(cols.baseline), + '-'.repeat(cols.current), + '-'.repeat(cols.size), + '-'.repeat(cols.diffPixels), + '-'.repeat(cols.ratio), + '-'.repeat(cols.verdict), + ].join(' '), + ); + for (const r of rows) { + console.log( + [ + pad(r.layer, cols.layer), + pad(r.baseline, cols.baseline), + pad(r.current, cols.current), + pad(r.size, cols.size), + padStart(r.diffPixels, cols.diffPixels), + padStart(r.ratio, cols.ratio), + pad(r.verdict, cols.verdict), + ].join(' '), + ); + } + console.log(''); + + for (const r of results) { + if (r.note) console.log(` [${r.layer}] ${r.note}`); + } + if (results.some((r) => r.note)) console.log(''); +} + +function main() { + const opts = parseArgs(process.argv.slice(2)); + const shotsDir = path.resolve(opts.shotsDir ?? DEFAULT_SHOTS_DIR); + const currentDir = path.resolve(opts.currentDir ?? DEFAULT_CURRENT_DIR); + + if (!fs.existsSync(shotsDir)) fail2(`基准目录不存在: ${shotsDir}`); + if (!fs.existsSync(currentDir)) { + console.warn(`当前截图目录不存在(全部面记 missing 并跳过): ${currentDir}`); + } + + let results; + try { + results = LAYER_BASELINES.map((entry) => compareLayer(entry, shotsDir, currentDir)); + } catch (err) { + fail2('比对过程异常终止', err); + } + + printTable(shotsDir, currentDir, results); + + const report = { + generatedAt: new Date().toISOString(), + threshold: DIFF_RATIO_THRESHOLD, + results, + }; + fs.mkdirSync(path.dirname(REPORT_PATH), { recursive: true }); + fs.writeFileSync(REPORT_PATH, `${JSON.stringify(report, null, 2)}\n`, 'utf8'); + console.log(`报告已写出: ${REPORT_PATH}`); + + const failed = results.filter((r) => !r.pass); + const compared = results.filter((r) => r.width !== null); + const skipped = results.length - compared.length; + if (failed.length > 0) { + console.log(`结论: ${failed.length} 面超阈(${failed.map((r) => r.layer).join(', ')})`); + process.exit(1); + } + console.log(`结论: 全部通过(比对 ${compared.length} 面 / 跳过 ${skipped} 面)`); + process.exit(0); +} + +main(); diff --git a/scripts/make-icons.mjs b/scripts/make-icons.mjs new file mode 100644 index 0000000..e8939c3 --- /dev/null +++ b/scripts/make-icons.mjs @@ -0,0 +1,219 @@ +#!/usr/bin/env node +/** + * scripts/make-icons.mjs — UI-4 Stage B2 + * + * 由 assets-src/icon.svg(唯一图标母版)生成 src-tauri/icons/ 全套 16 个目标文件: + * · 14 个 PNG(逐尺寸直接矢量栅格化,不做位图缩放 → 小尺寸图线不糊) + * · icon.ico —— 内置最小 ICO 编码器(ICONDIR + ICONDIRENTRY + PNG 数据体, + * Vista+ 合法的 PNG 压缩条目;sharp 不支持 ico 编码,node_modules + * 内也无 png-to-ico 可用包,故手写 ~40 行) + * · icon.icns — 内置最小 ICNS 编码器("icns" 头 + 各段 type/length/PNG) + * + * 用法:npm run make-icons + * 幂等:重复运行结果一致(覆盖写,输出字节前后对比)。 + */ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { statSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import sharp from "sharp"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const SVG_PATH = path.join(ROOT, "assets-src", "icon.svg"); +const OUT_DIR = path.join(ROOT, "src-tauri", "icons"); + +/** PNG 目标:文件名 → 边长(与 tauri.conf.json / Windows 商店 logo 约定一致) */ +const PNG_TARGETS = [ + ["32x32.png", 32], + ["128x128.png", 128], + ["128x128@2x.png", 256], + ["icon.png", 512], + ["Square30x30Logo.png", 30], + ["Square44x44Logo.png", 44], + ["Square71x71Logo.png", 71], + ["Square89x89Logo.png", 89], + ["Square107x107Logo.png", 107], + ["Square142x142Logo.png", 142], + ["Square150x150Logo.png", 150], + ["Square284x284Logo.png", 284], + ["Square310x310Logo.png", 310], + ["StoreLogo.png", 50], +]; + +/** ICO 内嵌 PNG 尺寸(256 为 Vista+ PNG 条目上限;其余供任务栏/资源管理器小图标) */ +const ICO_SIZES = [16, 32, 48, 64, 128, 256]; + +/** ICNS 段:icns type → PNG 边长(ic11=32, ic12=64, ic07=128, ic08=256, ic09=512, ic10=1024) */ +const ICNS_SEGMENTS = [ + ["ic11", 32], + ["ic12", 64], + ["ic07", 128], + ["ic08", 256], + ["ic09", 512], + ["ic10", 1024], +]; + +const ICO_ENTRIES = [["icon.ico", ICO_SIZES]]; +const ICNS_ENTRIES = [["icon.icns", ICNS_SEGMENTS]]; + +// ---------------------------------------------------------------- SVG 栅格化 + +/** 把母版的 width/height 换成目标边长后再交给 sharp:librsvg 按 density=72 出图, + * 即 1 SVG 用户单位 = 1px,得到「按目标尺寸重新矢量绘制」而非位图缩小。 */ +function svgAtSize(svg, size) { + let hit = false; + const patched = svg.replace(/]*>/, (tag) => { + hit = true; + // 注意:size 恰等于母版边长(1024)时替换结果与原文相同,故按「属性是否存在」判定, + // 不能按「字符串是否变化」判定。 + if (!/\swidth="[^"]*"/.test(tag) || !/\sheight="[^"]*"/.test(tag)) { + throw new Error(`${SVG_PATH}: 根 缺 width/height 属性`); + } + return tag + .replace(/\swidth="[^"]*"/, ` width="${size}"`) + .replace(/\sheight="[^"]*"/, ` height="${size}"`); + }); + if (!hit) throw new Error(`${SVG_PATH}: 找不到 开标签`); + return patched; +} + +async function renderPng(svg, size) { + return sharp(Buffer.from(svgAtSize(svg, size)), { density: 72 }) + .png({ compressionLevel: 9, effort: 10, palette: false }) + .toBuffer(); +} + +// ---------------------------------------------------------------- ICO 编码器 + +/** + * 最小 ICO 编码器(PNG 条目版,Windows Vista+ 与 Tauri/wry 均支持)。 + * 结构:ICONDIR(6B: reserved=0, type=1, count) + count × ICONDIRENTRY(16B) + PNG 数据体。 + * ICONDIRENTRY = 宽/高(各 1B,256 记 0) + 调色板数(1B=0) + 保留(1B=0) + * + 颜色平面(2B=1) + 位深(2B=32) + 数据长度(4B) + 数据偏移(4B)。 + */ +function encodeIco(entries) { + const header = Buffer.alloc(6); + header.writeUInt16LE(0, 0); // reserved + header.writeUInt16LE(1, 2); // type: 1 = icon + header.writeUInt16LE(entries.length, 4); + + const dir = Buffer.alloc(16 * entries.length); + let offset = header.length + dir.length; + entries.forEach((entry, i) => { + const base = i * 16; + const dim = entry.size >= 256 ? 0 : entry.size; // 256 在 ICO 里记作 0 + dir.writeUInt8(dim, base); // width + dir.writeUInt8(dim, base + 1); // height + dir.writeUInt8(0, base + 2); // colorCount + dir.writeUInt8(0, base + 3); // reserved + dir.writeUInt16LE(1, base + 4); // planes + dir.writeUInt16LE(32, base + 6); // bitCount + dir.writeUInt32LE(entry.png.length, base + 8); + dir.writeUInt32LE(offset, base + 12); + offset += entry.png.length; + }); + + return Buffer.concat([header, dir, ...entries.map((e) => e.png)]); +} + +// ---------------------------------------------------------------- ICNS 编码器 + +/** + * 最小 ICNS 编码器。 + * 结构:"icns"(4B magic) + 总长度(4B big-endian,含头) + 各段[type(4B) + 段长(4B, 含段头) + PNG]。 + * 现代 macOS 全段用 PNG 数据体,无需 4 字节对齐填充。 + */ +function encodeIcns(segments) { + const chunks = segments.map((seg) => { + const head = Buffer.alloc(8); + head.write(seg.type, 0, 4, "ascii"); + head.writeUInt32BE(8 + seg.png.length, 4); + return Buffer.concat([head, seg.png]); + }); + const body = Buffer.concat(chunks); + + const header = Buffer.alloc(8); + header.write("icns", 0, 4, "ascii"); + header.writeUInt32BE(8 + body.length, 4); + return Buffer.concat([header, body]); +} + +// ---------------------------------------------------------------- 主流程 + +async function main() { + const svg = await readFile(SVG_PATH, "utf8"); + await mkdir(OUT_DIR, { recursive: true }); + + // 目标清单:14 PNG + icon.ico + icon.icns = 16 + const expected = new Set([...PNG_TARGETS.map(([f]) => f), "icon.ico", "icon.icns"]); + const existing = (await readdir(OUT_DIR)).filter((f) => !f.startsWith(".")); + const uncovered = existing.filter((f) => !expected.has(f)); + if (uncovered.length > 0) { + throw new Error(`src-tauri/icons/ 存在清单外文件,未覆盖:${uncovered.join(", ")}`); + } + + const sizeOf = (file) => { + try { + return statSync(path.join(OUT_DIR, file)).size; + } catch { + return 0; // 尚不存在 + } + }; + const rows = []; + const write = async (file, buf) => { + const before = sizeOf(file); + await writeFile(path.join(OUT_DIR, file), buf); + rows.push({ file, before, after: buf.length }); + }; + + // PNG:每个尺寸独立栅格化 + const pngCache = new Map(); + const pngAt = async (size) => { + if (!pngCache.has(size)) pngCache.set(size, await renderPng(svg, size)); + return pngCache.get(size); + }; + for (const [file, size] of PNG_TARGETS) { + await write(file, await pngAt(size)); + } + + // ICO + for (const [file, sizes] of ICO_ENTRIES) { + const entries = []; + for (const size of sizes) entries.push({ size, png: await pngAt(size) }); + await write(file, encodeIco(entries)); + } + + // ICNS + for (const [file, segments] of ICNS_ENTRIES) { + const segs = []; + for (const [type, size] of segments) segs.push({ type, png: await pngAt(size) }); + await write(file, encodeIcns(segs)); + } + + // 结果表(字节数前后对比,供「16 个文件真实更新」自查看) + const pad = (s, n) => String(s).padEnd(n); + console.log(`\nicon.svg → ${path.relative(ROOT, OUT_DIR).replace(/\\/g, "/")}`); + console.log(`${pad("file", 24)}${pad("before", 10)}${pad("after", 10)}changed`); + console.log("-".repeat(52)); + let changed = 0; + for (const r of rows) { + const diff = r.after !== r.before; + if (diff) changed += 1; + console.log( + `${pad(r.file, 24)}${pad(r.before, 10)}${pad(r.after, 10)}${diff ? "yes" : "NO(bits identical)"}`, + ); + } + const listOnly = existing.filter((f) => !rows.some((r) => r.file === f)); + console.log("-".repeat(52)); + console.log( + `共 ${rows.length} 个目标文件,字节变化 ${changed} 个` + + (listOnly.length ? `;原有未覆盖:${listOnly.join(", ")}` : "") + + "\n", + ); + if (rows.length !== 16) throw new Error(`目标数应为 16,实际 ${rows.length}`); +} + +main().catch((err) => { + console.error("[make-icons] 失败:", err); + process.exitCode = 1; +}); diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 662f90c..bbc80da 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "tts-desktop" version = "0.1.0" -description = "A Tauri App" -authors = ["you"] +description = "TTS 图包制作维护工作台(Tauri 壳)" +authors = ["Smirk1921"] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png index 24045aa..9f67fe9 100644 Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/src-tauri/icons/128x128@2x.png index 4a537e1..1bcf3f2 100644 Binary files a/src-tauri/icons/128x128@2x.png and b/src-tauri/icons/128x128@2x.png differ diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png index 9c0ad67..750292c 100644 Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png index 8266f1b..3a5bb38 100644 Binary files a/src-tauri/icons/Square107x107Logo.png and b/src-tauri/icons/Square107x107Logo.png differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png index 6037658..9e80ab3 100644 Binary files a/src-tauri/icons/Square142x142Logo.png and b/src-tauri/icons/Square142x142Logo.png differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png index 06102e1..3ae7049 100644 Binary files a/src-tauri/icons/Square150x150Logo.png and b/src-tauri/icons/Square150x150Logo.png differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png index 37bec18..a7796df 100644 Binary files a/src-tauri/icons/Square284x284Logo.png and b/src-tauri/icons/Square284x284Logo.png differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png index bcfb4b7..1b73ffd 100644 Binary files a/src-tauri/icons/Square30x30Logo.png and b/src-tauri/icons/Square30x30Logo.png differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png index 45eabe5..41c6843 100644 Binary files a/src-tauri/icons/Square310x310Logo.png and b/src-tauri/icons/Square310x310Logo.png differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png index d10c199..4d39217 100644 Binary files a/src-tauri/icons/Square44x44Logo.png and b/src-tauri/icons/Square44x44Logo.png differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png index b17590f..c0bb85f 100644 Binary files a/src-tauri/icons/Square71x71Logo.png and b/src-tauri/icons/Square71x71Logo.png differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png index fadd836..fecdaf5 100644 Binary files a/src-tauri/icons/Square89x89Logo.png and b/src-tauri/icons/Square89x89Logo.png differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png index 5ac2347..1fa9aa2 100644 Binary files a/src-tauri/icons/StoreLogo.png and b/src-tauri/icons/StoreLogo.png differ diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns index 12a5bce..782d44f 100644 Binary files a/src-tauri/icons/icon.icns and b/src-tauri/icons/icon.icns differ diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico index 06c23c8..dbef04c 100644 Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png index 8b1c465..bdfb8da 100644 Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5136bbd..4d28d7d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,8 +1,4 @@ // Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ -#[tauri::command] -fn greet(name: &str) -> String { - format!("Hello, {}! You've been greeted from Rust!", name) -} /// 探测 tts-hub 控制通道端口是否可连(UI-1b,施工方案 v0.8.0 §8.2 方案 C)。 /// @@ -62,13 +58,24 @@ fn detect_webview2() -> Option { Some("non-windows".to_string()) } +/// WebView2 运行时可用性查询命令(UI-4 Stage B2)。 +/// +/// 前端 HubLauncher 在 checking 阶段与 `check_hub` 一并 invoke 此命令: +/// 返回 false 时在引导面板顶部加一条红条 +「下载 WebView2」按钮 +/// (按钮经 tauri-plugin-opener 打开微软官方引导安装链接)。 +/// 复用 setup 钩子里的同一探测函数,保证两处口径一致。 +#[tauri::command] +fn is_webview2_present() -> bool { + detect_webview2().is_some() +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) - .setup(|_app| { - // UI-1a 验收点:WebView2 启动检测钩子 - // 缺失时通过 stderr 警告 + 在窗口标题里追加提示(UI-4 再加原生对话框引导安装) + .setup(|app| { + // UI-1a 验收点:WebView2 启动检测钩子(UI-4 Stage B2 补窗口标题提示) + use tauri::Manager; match detect_webview2() { Some(version) => { println!("[tts-desktop] WebView2 detected: {}", version); @@ -78,11 +85,17 @@ pub fn run() { "[tts-desktop] WebView2 Runtime NOT detected. \ Please install from https://go.microsoft.com/fwlink/p/?LinkId=2124703" ); + // 原生对话框引导超出本次范围(wry 起窗即依赖 WebView2), + // 改为:窗口标题追加提示 + 前端红条(is_webview2_present)。 + if let Some(window) = app.get_webview_window("main") { + let base = window.title().unwrap_or_default(); + let _ = window.set_title(&format!("{base}(缺少 WebView2 运行时)")); + } } } Ok(()) }) - .invoke_handler(tauri::generate_handler![greet, check_hub]) + .invoke_handler(tauri::generate_handler![check_hub, is_webview2_present]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 5d4f7e9..2e77f6a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -28,13 +28,26 @@ }, "bundle": { "active": true, - "targets": "all", + "targets": ["nsis"], + "publisher": "Smirk1921", + "copyright": "© 2026 Smirk1921", + "shortDescription": "TTS 图包制作维护工作台", "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" - ] + ], + "windows": { + "webviewInstallMode": { + "type": "downloadBootstrapper" + }, + "nsis": { + "displayLanguageSelector": false, + "languages": ["SimpChinese"], + "startMenuFolder": "TTS 图包工作台" + } + } } } diff --git a/src/App.tsx b/src/App.tsx index 489b010..828eb53 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,31 +1,42 @@ /** - * App.tsx — UI-1b hub 门 + UI-2/3 Stage C 顶层接线 + * App.tsx — UI-1b hub 门 + UI-2/3 Stage C 顶层接线 + UI-4 Stage B1 总览接线 * * 职责: * - caps === null → (探测 39995 / 引导启动 / 版本兼容门); - * 验证通过后按固定顺序挂四层 Provider: + * 验证通过后按固定顺序挂五层 Provider: * HubContext.Provider(client 单例 + caps) * → ConfirmGateProvider(全站确认门 request 单槽) * → SseProvider(App.tsx 顶层唯一 SSE 订阅,红线 3) * → DeadLinkProvider(全站死链 store,UI-3 Stage C;③④ dot + 路由消费) + * → DirtyProvider(全站未提交改动 GUID 集合,UI-4 Stage A3;① dot + 代码面上报) * → 渲染 Frame + LayerNav + LegendBar + 当前路由 + SignBlock * - ConfirmGate 全站唯一实例在 (本文件,红线 1):从 * ConfirmGateContext 读 request 渲染;业务层一律经 useConfirmGate().ask(req) * 打开(红线 2),不再各自渲染 * - caps 就绪后轮询 /v1/status(30s)→ 真实 TTS 连接状态 → Frame 状态行 - * - LayerNav 圆点真实化(红线 4):② 代理面 dot 由 SSE 连接态实时计算; - * ③ 卡牌 / ④ 素材 dot 由 DeadLinkContext 同源驱动(deadUrls 非空 = red, - * hint 带死链数;UI-4 再细分"cards 选中卡死链" vs "assets 总死链数"); - * ① 代码面 dirty 上报待 Code 面提供(现仍占位 ok) * - * UI-4 在此接入: - * - ⓪ 总览填充;① 代码 dot dirty 真实化;SignBlock.onSign 接真实会签出厂流程 + * UI-4 Stage B1 接线(本窗口): + * - 图包元信息真实化:GET /v1/packs 首项 → 图名栏(Frame.pack)与 ⓪ 引擎 root 同一来源; + * 失败保持 UI-1a 占位,注册表可读但无条目 → 「未注册图包 / —」(不谎报) + * - ⓪总览数据引擎 useOverviewData 在 AppInner **单点**调用:SIGN_CHECKS(会签栏交付清单)、 + * LayerNav 圆点、onSign 待签数与 ⓪ 面工序章/待办/磁贴共用同一份 OverviewData(同源), + * 受控接收 data/root。单点的理由:该 hook 有模块级结果缓存但**无在途去重**, + * App 与路由两处同时调用会在冷启动并发发两次 POST /v1/scripts/pull(覆盖工作区) + * + 两次 POST /v1/test/run(在真实游戏内跑测试)——processStamps.ts 文件头明确 + * 「并发交错风险不值当」,故全站只留一处调用。 + * - LayerNav 圆点真实化:⓪ 总览 = 死链或差异 > 0;① 代码 = 未提交改动(DirtyContext) + * > 0 蓝,否则按差异红/青;② 代理按 SSE 连接态;③④ 卡牌/素材按死链集合同源双色 + * - SignBlock.onSign = 真实会签出厂(ConfirmGate → POST /v1/push confirm:true); + * onDetail = 切到 ① 代码面。SIGN_PROCS 仍是 UI-1a 占位(发布/同步未开放) + * - 已知缺口(留给 Stage C):push 成功后 ⓪ 面五章/待签计数不会自动重算——Stage A 引擎 + * 只导出 clearStampCache(),没有 refetch 出口,且引擎挂在 AppInner(不随路由卸载), + * 清缓存后不会重发请求;需要刷新窗口时给引擎加 refresh 触发(或 key 重挂载)。 */ -import { useContext, useEffect, useState, type JSX } from "react"; +import { useCallback, useContext, useEffect, useMemo, useState, type JSX } from "react"; import Frame from "./components/Frame"; import LayerNav, { type LayerItem } from "./components/LayerNav"; import LegendBar from "./components/LegendBar"; -import SignBlock from "./components/SignBlock"; +import SignBlock, { type SignCheck } from "./components/SignBlock"; import ConfirmGate from "./components/ConfirmGate"; import HubLauncher from "./components/HubLauncher"; @@ -34,10 +45,19 @@ import { ConfirmGateProvider, HubContext, hubClient, + useConfirmGate, useHub, } from "./hub/HubContext"; import { SseProvider, useSseEvents } from "./hub/useSseEvents"; import { DeadLinkProvider, useDeadLinks } from "./state/DeadLinkContext"; +import { DirtyProvider, useDirty } from "./state/DirtyContext"; +import { + NO_PACK_NAME, + NO_VERSION, + useOverviewData, + type LayerId, + type OverviewData, +} from "./state/processStamps"; import type { HubCapabilities } from "./hub/capabilities"; import type { HubStatus } from "./hub/client"; @@ -47,34 +67,150 @@ import Agent from "./routes/Agent"; import Cards from "./routes/Cards"; import Assets from "./routes/Assets"; -type LayerId = "overview" | "code" | "agent" | "cards" | "assets"; +/** 图名栏 + ⓪ 引擎 root 的共同来源(GET /v1/packs 首项) */ +interface PackInfo { + /** 注册表条目 dir(hub 路由直接接受);null = 无已注册图包 */ + root: string | null; + name: string; + version: string; + branch: string; +} -const PACK = { name: "mypack", version: "v0.8.0", branch: "main" }; +/** 未注册图包(注册表可读但无条目):与 ⓪ 引擎同一套「无则」值 */ +const NO_PACK_INFO: PackInfo = { + root: null, + name: NO_PACK_NAME, + version: NO_VERSION, + branch: "main", +}; -const STATUS_POLL_MS = 30_000; +/** GET /v1/packs 失败 / 未返回前的占位(UI-1a 演示值:不闪空,失败也不谎报新值) */ +const PACK_PLACEHOLDER: PackInfo = { + root: null, + name: "mypack", + version: "v0.8.0", + branch: "main", +}; -const SIGN_CHECKS = [ - { k: "版本", v: "v0.8.0", tone: "ok" as const }, - { k: "校样", v: "通过", tone: "ok" as const }, - { k: "打样", v: "待", tone: "bad" as const, next: true }, - { k: "出厂", v: "未", tone: "bad" as const }, -]; +const STATUS_POLL_MS = 30_000; +/** 出厂工序(SignBlock):写回游戏已开放,发布/同步仍是未开放占位(UI-4 不动) */ const SIGN_PROCS = [ { name: "写回游戏", state: "open" as const }, { name: "发布 V2", state: "soon" as const, badge: "v0.9.0" }, { name: "同步 V2", state: "soon" as const, badge: "v0.9.0" }, ]; -/** 会签栏 + 状态行 + 确认门宿主(须在 HubContext / ConfirmGateProvider / SseProvider / DeadLinkProvider 内) */ +/** 路径末段(注册表条目无 name 时的诚实兜底,与 processStamps 同口径) */ +function basename(path: string): string { + const parts = path.split(/[\\/]+/).filter((s) => s !== ""); + const last = parts[parts.length - 1]; + return last !== undefined && last !== "" ? last : path; +} + +/** GET /v1/packs 响应 → 首项图包元信息(无条目返回 null;缺字段按契约取「无则」值) */ +function readFirstPackInfo(res: unknown): PackInfo | null { + const packs = (res as { packs?: unknown }).packs; + if (!Array.isArray(packs)) return null; + for (const p of packs) { + if (typeof p !== "object" || p === null) continue; + const dir = (p as { dir?: unknown }).dir; + if (typeof dir !== "string" || dir === "") continue; + const name = (p as { name?: unknown }).name; + // version / branch 目前不在 .registry.yaml 的 PackEntry schema 内(前向探测): + // 有则用,无则 "—" / "main"(branch 缺省 = main 与 a-deep 同) + const version = (p as { version?: unknown }).version; + const branch = (p as { branch?: unknown }).branch; + return { + root: dir, + name: typeof name === "string" && name !== "" ? name : basename(dir), + version: typeof version === "string" && version !== "" ? version : NO_VERSION, + branch: typeof branch === "string" && branch !== "" ? branch : "main", + }; + } + return null; +} + +/** + * 会签栏交付清单(§4.4 / a-deep.html 636-640):版本 → 校样 → 打样 → 出厂。 + * `next`(左缘 2.5px 红条 = 当前下一步)落在**出厂行**(a-deep 640 行 + * 「3 件待签 ←」),与 ⓪ 工序章同源:校样行取 proof 章 note、出厂行取 pendingSign + * (= ship 章同一计数:>0 「N 件待签 ←」/ =0 「✓ 已会签」)。 + * 说明:不用 Stage A 的 deriveSignBlock——它把 next 放在「首个 bad 行」且出厂文案不带 ←; + * 本窗口按 a-deep 逐字落地(值仍取自同一份 OverviewData,两处文案一致)。 + * 打样:POST /v1/pack/build 的产物状态无查询路由,恒「未打样」(Stage A 同结论)。 + */ +function buildSignChecks( + pack: PackInfo, + uncommitted: number, + data: OverviewData, +): SignCheck[] { + const proof = data.stamps.find((s) => s.id === "proof"); + const versionKnown = pack.version !== NO_VERSION; + const pendingSign = data.pendingSign; + + return [ + { + k: "版本", + v: `${versionKnown ? pack.version : "未标注"}${ + uncommitted > 0 ? ` · ${uncommitted} 未提交` : "" + }`, + // SignCheck.tone 只有 ok | bad:有未提交改动 / 版本未标注 → bad(红),余为 ok(青) + tone: versionKnown && uncommitted === 0 ? "ok" : "bad", + }, + { + k: "校样", + v: proof?.note ?? "—", + tone: proof?.status === "done" ? "ok" : "bad", + }, + { k: "打样", v: "未打样", tone: "bad" }, + { + k: "出厂", + v: pendingSign > 0 ? `${pendingSign} 件待签 ←` : "✓ 已会签", + tone: pendingSign > 0 ? "bad" : "ok", + next: pendingSign > 0, + }, + ]; +} + +/** 会签栏 + 状态行 + 确认门宿主(须在 HubContext / ConfirmGateProvider / SseProvider / DeadLinkProvider / DirtyProvider 内) */ function AppInner(): JSX.Element { const { client } = useHub(); - const { state: sseState } = useSseEvents(); + const { state: sseState, events: sseEvents } = useSseEvents(); // 全站死链 store(Stage C):③④ dot 同源双色(UI-4 再细分 cards 选中卡 / assets 总数) const { deadUrls } = useDeadLinks(); + // 全站未提交改动集合(UI-4):① 代码 dot + 会签栏版本行的未提交数 + const { dirtyGuids } = useDirty(); + // 确认门(红线 2):会签出厂开全站唯一 + const { ask } = useConfirmGate(); const [status, setStatus] = useState(null); const [activeLayer, setActiveLayer] = useState("overview"); + const [pack, setPack] = useState(PACK_PLACEHOLDER); + + // 图包元信息(GET /v1/packs 首项):图名栏 + ⓪ 引擎 root 一次取,避免两处各查注册表; + // 失败静默保持占位(hub 未验证时根本走不到这里,HubLauncher 已兜底) + useEffect(() => { + let cancelled = false; + void (async () => { + try { + const res = await client.packs(); + if (cancelled) return; + setPack(readFirstPackInfo(res) ?? NO_PACK_INFO); + } catch { + /* 静默:保持占位 */ + } + })(); + return () => { + cancelled = true; + }; + }, [client]); + + const root = pack.root; + + // ⓪ 总览状态引擎(单点,见文件头):stamps / todos / diffCount / pendingSign / deadCount + // 同时供会签栏、LayerNav 圆点与 ⓪ 面消费;root=null 时 hook 内部零请求(降级模式) + const data = useOverviewData({ deadUrls, sseEvents, root }); // caps 就绪后轮询 /v1/status:真实 TTS 连接状态 → Frame 状态行 useEffect(() => { @@ -95,12 +231,27 @@ function AppInner(): JSX.Element { }; }, [client]); - // LayerNav 圆点:② 代理面按 SSE 连接态、③④ 卡牌/素材按死链集合双色 - // (红线 4,Stage C:deadUrls 非空 = red,同源——一个集合两面同色); - // ① 代码面 TODO:dirty 状态由 Code 面上报后再真实化(现占位 ok) + const deadCount = deadUrls.size; + const dirtyCount = dirtyGuids.size; + const { diffCount, pendingSign } = data; + + // LayerNav 圆点(红线 4,UI-4 真实化):⓪ 死链或差异 / ① 未提交改动或差异 / + // ② SSE 连接态 / ③④ 死链集合双色(同源——一个集合两面同色) const layers: LayerItem[] = [ - { id: "overview", num: "⓪", name: "总览", dot: "ok", hint: "⓪ 总览(UI-4 填充)" }, - { id: "code", num: "①", name: "代码", dot: "ok", hint: "① 代码(dot TODO:由 Code 面上报 dirty)" }, + { + id: "overview", + num: "⓪", + name: "总览", + dot: deadCount > 0 || diffCount > 0 ? "red" : "ok", + hint: `⓪ 总览 · 死链 ${deadCount} · 与游戏内不同 ${diffCount}`, + }, + { + id: "code", + num: "①", + name: "代码", + dot: dirtyCount > 0 ? "blue" : diffCount > 0 ? "red" : "ok", + hint: `① 代码 · 未提交 ${dirtyCount} · 与游戏内不同 ${diffCount}`, + }, { id: "agent", num: "②", @@ -126,12 +277,34 @@ function AppInner(): JSX.Element { const connected = status?.tts.connected === true; + // 会签栏交付清单(与 ⓪ 工序章同源;版本行带 DirtyContext 的未提交数) + const signChecks = useMemo( + () => buildSignChecks(pack, dirtyCount, data), + [pack, dirtyCount, data], + ); + + // 会签出厂:危险操作走全站唯一确认门(红线 1/2),确认后 POST /v1/push(confirm:true) + const handleSign = useCallback((): void => { + // 无图包 / 无待签件:不写回(与 ①代码面「写回游戏」按钮的可用性口径一致) + if (root === null || pendingSign === 0) return; + ask({ + title: "会签出厂", + items: [{ file: "写回游戏", diff: `${pendingSign} 件` }], + assetWarning: deadCount > 0 ? `${deadCount} 个素材死链未修复` : undefined, + onConfirm: async () => { + await client.push(root, true); + }, + }); + }, [ask, client, root, pendingSign, deadCount]); + return ( <> } signBlock={ { - // SignBlock.onSign 暂为占位(UI-4 总览面接真实会签出厂); - // 当前危险操作入口由 Code 面的「写回游戏」经 useConfirmGate().ask 触发 - }} - onDetail={() => { - /* UI-4 填充 */ - }} + onSign={handleSign} + onDetail={() => setActiveLayer("code")} /> } > - {activeLayer === "overview" && } + {activeLayer === "overview" && ( + setActiveLayer(layer)} + /> + )} {activeLayer === "code" && } {activeLayer === "agent" && } {activeLayer === "cards" && } @@ -195,7 +369,7 @@ export default function App(): JSX.Element { const [caps, setCaps] = useState(null); // caps 未就绪:先过 HubLauncher(探测 / 引导 / 版本兼容门)—— - // 四层 Provider 都在验证通过后挂载,SSE / 确认门 / 死链 store 不接触未验证的 hub + // 五层 Provider 都在验证通过后挂载,SSE / 确认门 / 死链 / 脏通道不接触未验证的 hub if (caps === null) { return ; } @@ -205,7 +379,9 @@ export default function App(): JSX.Element { - + + + diff --git a/src/components/CodeFileTree.tsx b/src/components/CodeFileTree.tsx index 04871b0..1e1e14d 100644 --- a/src/components/CodeFileTree.tsx +++ b/src/components/CodeFileTree.tsx @@ -1,8 +1,15 @@ /** - * 代码面·对象区(左树) — Stage A2 - * 职责:scripts / ui 两个扁平列表 + 分组标题,每行一个文件 + 状态字符符号。 + * 代码面·对象区(左树) — Stage A2 / UI-4 Stage A1 泛化 + * 职责:分组文件列表(组标题 + 每行一个文件 + 状态字符符号)。 * 纯受控展示:选中由父组件驱动(activeGuid),本组件不持状态、不调 hubClient。 * 符号(红线 §10):modified=M(琥珀) / added=+(青) / deleted=−(红) / clean=空格不显示。 + * + * 泛化(UI-4 Stage A1,契约 §4,向后兼容): + * - groups 缺省 → 行为与既有 ①代码面完全一致(scripts/ + ui/ 两组, + * 标题样式不变);scripts / uis 缺省按空数组处理; + * - groups 存在 → 忽略 scripts / uis,按给定分组顺序渲染(标题样式同 scripts/); + * - title 为空串时不渲染标题行(供 复用:块标题已由外壳给出, + * 树内不再重复标题,也不留空标题占位)。既有调用方从未传空串,无回归。 */ import type { KeyboardEvent, MouseEvent, ReactElement } from "react"; import "./CodeFileTree.css"; @@ -19,11 +26,21 @@ export interface TreeNode { status?: "added" | "modified" | "deleted" | "clean"; } +/** 树分组:自定义分组渲染(UI-4 泛化) */ +export interface TreeGroup { + /** 组标题,渲染为与 "scripts/" 同款的分组标题;空串 = 不渲染标题行 */ + title: string; + /** 该组节点 */ + nodes: TreeNode[]; +} + export interface CodeFileTreeProps { + /** 自定义分组;缺省时按 scripts/ + ui/ 两组渲染(①代码面行为不变) */ + groups?: TreeGroup[]; /** scripts/ 列表(来自 scriptStates 过滤 kind==="script") */ - scripts: TreeNode[]; + scripts?: TreeNode[]; /** ui/ 列表(来自 scriptStates 过滤 kind==="ui") */ - uis: TreeNode[]; + uis?: TreeNode[]; /** 当前选中项的 guid(高亮) */ activeGuid?: string; /** 选中回调 */ @@ -76,17 +93,17 @@ function TreeItem(props: { ); } -function TreeGroup(props: { - title: string; - nodes: TreeNode[]; +function GroupSection(props: { + group: TreeGroup; activeGuid?: string; onSelect: CodeFileTreeProps["onSelect"]; }): ReactElement { - const { title, nodes, activeGuid, onSelect } = props; + const { group, activeGuid, onSelect } = props; + const { title, nodes } = group; return ( -
-
{title}
+
+ {title !== "" &&
{title}
} {nodes.length > 0 ? (
    {nodes.map((node) => ( @@ -106,12 +123,24 @@ function TreeGroup(props: { } export default function CodeFileTree(props: CodeFileTreeProps): ReactElement { - const { scripts, uis, activeGuid, onSelect } = props; + const { groups, scripts, uis, activeGuid, onSelect } = props; + + // groups 优先;缺省回到既有 scripts/ + ui/ 两段(①代码面零变化) + const resolved: TreeGroup[] = groups ?? [ + { title: "scripts/", nodes: scripts ?? [] }, + { title: "ui/", nodes: uis ?? [] }, + ]; return ( ); } diff --git a/src/components/HubLauncher.css b/src/components/HubLauncher.css index 3cea463..d65356d 100644 --- a/src/components/HubLauncher.css +++ b/src/components/HubLauncher.css @@ -71,6 +71,37 @@ letter-spacing: 1px; } +/* WebView2 运行时缺失红条(UI-4 Stage B2):红 = 危险/错误(§2.5), + 左侧粗红条 + 1px 红框,文字走图线白保持可读性;直角、零投影 */ +.hublauncher-wv2 { + display: flex; + align-items: center; + gap: var(--sp-2); + margin-bottom: var(--sp-3); + padding: var(--sp-2) var(--sp-3); + background: var(--bp-dd); + border: var(--border-w) solid var(--red); + border-left: var(--next-bar) solid var(--red); + border-radius: var(--radius-max); +} + +.hublauncher-wv2-mark { + flex-shrink: 0; + color: var(--red); + font-family: var(--sans); + font-size: var(--fs-panel); + line-height: var(--lh-body); +} + +.hublauncher-wv2-text { + flex: 1 1 auto; + margin: 0; + font-family: var(--fs); + font-size: var(--fs-note); + line-height: var(--lh-body); + color: var(--w); +} + /* 步骤:仿宋标注 + 等宽命令行 */ .hublauncher-step { margin-bottom: var(--sp-3); @@ -148,3 +179,9 @@ .hublauncher-btn:hover:not(:disabled) { background: var(--wfaint); } + +/* 紧凑按钮(红条内联用;须置于 .hublauncher-btn 之后以覆盖 padding) */ +.hublauncher-btn--sm { + flex-shrink: 0; + padding: var(--sp-1) var(--sp-3); +} diff --git a/src/components/HubLauncher.tsx b/src/components/HubLauncher.tsx index a152134..778e635 100644 --- a/src/components/HubLauncher.tsx +++ b/src/components/HubLauncher.tsx @@ -3,15 +3,20 @@ * * 状态机: * 1. checking → Tauri invoke('check_hub') TCP 探测 39995(非 Tauri 环境<纯浏览器 dev>退化为 - * 直接 fetch /v1/status,1500ms) + * 直接 fetch /v1/status,1500ms);同轮一并 invoke('is_webview2_present')(UI-4 Stage B2) * 2. 端口通 → client.status() → capabilitiesFromStatus() → * isSupported ? onReady(caps) : 「版本过旧」面板(<0.7.0 或无 version 字段) * 3. 端口不通 → 引导对话框:安装命令 + 启动命令(各带一键复制)+「我已启动,重试」 * + * UI-4 Stage B2:WebView2 运行时缺失时,引导面板顶部加红条(危险语义 §2.5)+ + * 「下载 WebView2」按钮(tauri-plugin-opener 打开微软官方引导链接)。 + * 命令不可用(旧壳 / 纯浏览器)时不报警,避免误报。 + * * 样式:tokens.css——var(--bp-d) 面板底 + var(--w) 边框 + var(--amber) 警示(§2.5)。 */ import { useCallback, useEffect, useState } from "react"; -import { invoke } from "@tauri-apps/api/core"; +import { invoke, isTauri } from "@tauri-apps/api/core"; +import { openUrl } from "@tauri-apps/plugin-opener"; import { HUB_BASE_URL } from "../hub/client"; import { hubClient } from "../hub/HubContext"; import { capabilitiesFromStatus } from "../hub/capabilities"; @@ -22,6 +27,8 @@ const HUB_PORT = 39995; const PROBE_TIMEOUT_MS = 1500; const INSTALL_CMD = "npm install -g @smirk1921/tts-toolkit"; const START_CMD = "tts-hub"; +/** 微软官方 WebView2 Runtime 引导安装链接(Evergreen Bootstrapper) */ +const WEBVIEW2_URL = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"; type Phase = "checking" | "guide" | "unsupported"; @@ -34,11 +41,16 @@ export default function HubLauncher({ onReady }: HubLauncherProps) { const [phase, setPhase] = useState("checking"); const [detected, setDetected] = useState(""); const [busy, setBusy] = useState(false); + /** WebView2 运行时缺失(UI-4 Stage B2);仅在权威判定为 false 时置位 */ + const [wv2Missing, setWv2Missing] = useState(false); const check = useCallback(async () => { setBusy(true); try { - if (!(await probePort())) { + // 端口探测与 WebView2 检测同轮发起;后者失败按「不可知」处理,不误报 + const [hubUp, wv2Present] = await Promise.all([probePort(), probeWebview2()]); + setWv2Missing(!wv2Present); + if (!hubUp) { setPhase("guide"); return; } @@ -87,6 +99,23 @@ export default function HubLauncher({ onReady }: HubLauncherProps) {

    未检测到 tts-hub

    + {wv2Missing && ( +
    + + ⚠ + +

    + 缺少 WebView2 运行时:本应用界面可能无法渲染。请先安装并重启应用。 +

    + +
    + )}

    桌面应用经 hub({HUB_BASE_URL.replace(/^http:\/\//, "")})与 Tabletop Simulator 通信。请在终端先启动: @@ -146,6 +175,29 @@ async function probePort(): Promise { } } +/** + * WebView2 运行时探测(UI-4 Stage B2):Rust 侧 is_webview2_present(查注册表)。 + * 非 Tauri 环境(纯浏览器 dev)与命令缺失(旧壳 / 调用异常)一律按 true 返回—— + * 只有拿到权威的 false 才提示,避免误报。 + */ +async function probeWebview2(): Promise { + if (!isTauri()) return true; + try { + return await invoke("is_webview2_present"); + } catch { + return true; + } +} + +/** 打开微软官方 WebView2 引导安装链接;非 Tauri 环境退化为新标签页 */ +async function openWebview2Download(): Promise { + try { + await openUrl(WEBVIEW2_URL); + } catch { + window.open(WEBVIEW2_URL, "_blank", "noopener,noreferrer"); + } +} + async function probeHttp(): Promise { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), PROBE_TIMEOUT_MS); diff --git a/src/components/LayerTiles.css b/src/components/LayerTiles.css new file mode 100644 index 0000000..ae95021 --- /dev/null +++ b/src/components/LayerTiles.css @@ -0,0 +1,76 @@ +/* 四面状态磁贴 — UI-4 Stage A1(a-deep.html .ov-side h4 + .ftile) + * 标题:仿宋小字 + 3px 字距 + 1px --w 实线下划线(§2.4 分版面);行间 + * 1px dashed --wfaint 虚线分组(分组用虚线)。 + * 字族:面名仿宋(标注层)/ 取值等宽(数据层),不混用(§2.2)。 + * 状态色:取值色由 data-tone 决定(bad=--red 差异/死链、blue=--blue 代理、 + * ok=--ok 一致、dim=--wdim 中性计数),全部引用 tokens.css 变量。 */ + +.layertiles { + display: flex; + flex-direction: column; +} + +.layertiles-head { + padding-bottom: var(--sp-2); + margin-bottom: var(--sp-2); + border-bottom: var(--border-w) solid var(--w); + font-family: var(--fs); + font-size: var(--fs-note); + letter-spacing: 3px; + color: var(--wdim); +} + +.layertiles-tile { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--sp-3); + padding: var(--sp-2) var(--sp-1); + border-bottom: var(--border-w) dashed var(--wfaint); + font-family: var(--fs); + font-size: var(--fs-panel); + cursor: pointer; + transition: background var(--dur-fast) var(--ease-out); +} + +.layertiles-tile:last-child { + border-bottom: none; +} + +.layertiles-tile:hover { + background: var(--bp-d); +} + +.layertiles-tile:focus-visible { + outline: var(--border-w) solid var(--blue); + outline-offset: calc(var(--border-w) * -1); +} + +.layertiles-k { + color: var(--w); +} + +/* 取值:等宽小字(数据层)+ 数字表格化(§2.2) */ +.layertiles-v { + font-family: var(--mono); + font-size: var(--fs-note); + line-height: var(--lh-data); + color: var(--wdim); +} + +.layertiles-tile[data-tone="bad"] .layertiles-v { + color: var(--red); +} + +.layertiles-tile[data-tone="blue"] .layertiles-v { + color: var(--blue); +} + +.layertiles-tile[data-tone="ok"] .layertiles-v { + color: var(--ok); +} + +/* ④ 素材行内的死链计数:红字(同一行内独立着色,--red = 死链) */ +.layertiles-bad { + color: var(--red); +} diff --git a/src/components/LayerTiles.tsx b/src/components/LayerTiles.tsx new file mode 100644 index 0000000..7b3f081 --- /dev/null +++ b/src/components/LayerTiles.tsx @@ -0,0 +1,99 @@ +/** + * 四面状态磁贴 — UI-4 Stage A1(⓪总览右栏,a-deep.html .ftile) + * + * 职责:标题「四面状态」+ 四行磁贴(① 代码 / ② 代理 / ③ 卡牌 / ④ 素材), + * 每行「面名(仿宋)+ 取值(等宽)」,点击 → onNavigate(对应面)。 + * 纯受控展示:全部取值从 OverviewData 派生(本组件不自查、不调 hub)。 + * + * 四行取值规则(契约 §3,逐条落地): + * ① 代码:diffCount>0 → 红字「N ⇄」(与游戏内不同,--red 唯一语义);否则「✓ 一致」青 + * ② 代理:蓝字「● 流水 N」(--blue = 代理活动) + * ③ 卡牌:cardCount,未知(null)→「—」 + * ④ 素材:「N 行」(未知 →「—」)+ deadCount>0 时红字「N✗」(--red = 死链) + * 符号:⇄ M ✗ ✓ ● 均为已注册字符(§2.4 / 图例条),不引图标库。 + */ +import type { KeyboardEvent, ReactElement, ReactNode } from "react"; +import type { LayerId, OverviewData } from "../state/processStamps"; +import "./LayerTiles.css"; + +export interface LayerTilesProps { + /** 总览聚合数据(A3 经 useOverviewData 供给) */ + data: OverviewData; + /** 行点击 → 跳转对应工作面 */ + onNavigate(layer: LayerId): void; +} + +/** 取值色调:默认弱色(--wdim)/ 红(差异·死链)/ 蓝(代理活动)/ 青(一致) */ +type TileTone = "dim" | "bad" | "blue" | "ok"; + +interface Tile { + layer: LayerId; + label: string; + tone: TileTone; + value: ReactNode; +} + +/** OverviewData → 四行磁贴(顺序固定 ① 代码 → ④ 素材) */ +function buildTiles(data: OverviewData): Tile[] { + return [ + { + layer: "code", + label: "① 代码", + tone: data.diffCount > 0 ? "bad" : "ok", + value: data.diffCount > 0 ? `${data.diffCount} ⇄` : "✓ 一致", + }, + { + layer: "agent", + label: "② 代理", + tone: "blue", + value: `● 流水 ${data.jobCount}`, + }, + { + layer: "cards", + label: "③ 卡牌", + tone: "dim", + value: data.cardCount === null ? "—" : String(data.cardCount), + }, + { + layer: "assets", + label: "④ 素材", + tone: "dim", + value: ( + <> + {data.assetCount === null ? "—" : `${data.assetCount} 行`} + {data.deadCount > 0 && {data.deadCount}✗} + + ), + }, + ]; +} + +export default function LayerTiles(props: LayerTilesProps): ReactElement { + const { data, onNavigate } = props; + const tiles = buildTiles(data); + + return ( +

    +
    四面状态
    + {tiles.map((tile) => ( +
    onNavigate(tile.layer)} + onKeyDown={(event: KeyboardEvent): void => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onNavigate(tile.layer); + } + }} + > + {tile.label} + {tile.value} +
    + ))} +
    + ); +} diff --git a/src/components/MiniFileTree.css b/src/components/MiniFileTree.css new file mode 100644 index 0000000..a54985c --- /dev/null +++ b/src/components/MiniFileTree.css @@ -0,0 +1,42 @@ +/* 工作区迷你文件树 — UI-4 Stage A1(a-deep.html .ov-blk + .ftree/.ftn) + * 块:1px --wdim 外框 + 底 --bp(总览面板底,与 待办 同款); + * 标题行:仿宋小字 + 3px 字距,右小注等宽弱色(数据层)。 + * 复用 :覆盖其底色(bp-dd → 面板底 --bp)与高度(100% → 自然高度), + * 行高/字族/状态符号色一律沿用 CodeFileTree.css(单一事实源,不复制样式)。 */ + +.miniftree { + border: var(--border-w) solid var(--wdim); + background: var(--bp); +} + +.miniftree-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--sp-2); + padding: var(--sp-2) var(--sp-4); + border-bottom: var(--border-w) solid var(--wdim); +} + +.miniftree-title { + font-family: var(--fs); + font-size: var(--fs-note); + letter-spacing: 3px; + color: var(--w); +} + +/* 右上角小注:差异 N / 未注册图包(等宽弱色,数字表格化) */ +.miniftree-note { + font-family: var(--mono); + font-size: var(--fs-note); + line-height: var(--lh-data); + letter-spacing: 1px; + color: var(--wdim); + white-space: nowrap; +} + +/* 复用件的底与高度适配:面板底、自然高度(外层若给高度上限则由 .codetree 自身滚动) */ +.miniftree-body .codetree { + height: auto; + background: var(--bp); +} diff --git a/src/components/MiniFileTree.tsx b/src/components/MiniFileTree.tsx new file mode 100644 index 0000000..239493d --- /dev/null +++ b/src/components/MiniFileTree.tsx @@ -0,0 +1,43 @@ +/** + * 工作区迷你文件树 — UI-4 Stage A1(⓪总览左下块,a-deep.html .ftree) + * + * 职责:块标题「工作区」+ 右上角小注(「差异 N」/「未注册图包」)+ 差异文件列表; + * 行点击 → onNavigate("code")(跳 ①代码面看 diff,不在此做编辑)。 + * 复用泛化后的 (groups 单组渲染),故行样式/状态符号/键盘可达性 + * 与①代码面对象区同源,不另造第二套文件树。 + * + * 数据来源(契约 §5 修订版,逐字):nodes / note 由 A3 从 useOverviewData 派生后 + * 传入——本组件不调 hub、不读模块级缓存、不依赖 hook 调用时序(纯受控展示)。 + * nodes 为空时由 CodeFileTree 的分组空态渲染「— 无对象」(未注册图包 / 无差异 + * 两种情况都不留空块)。 + */ +import type { ReactElement } from "react"; +import CodeFileTree, { type TreeNode } from "./CodeFileTree"; +import type { LayerId } from "../state/processStamps"; +import "./MiniFileTree.css"; + +export interface MiniFileTreeProps { + /** 差异文件节点(A3 由 useOverviewData 缓存派生;kind 按扩展名,status 按 added/modified/deleted) */ + nodes: TreeNode[]; + /** 右上角小注:「差异 N」或「未注册图包」 */ + note: string; + /** 行点击 → 跳转工作面(本组件固定跳 "code") */ + onNavigate(layer: LayerId): void; +} + +export default function MiniFileTree(props: MiniFileTreeProps): ReactElement { + const { nodes, note, onNavigate } = props; + + return ( +
    +
    + 工作区 + {note} +
    +
    + {/* 组标题留空:块标题已在上方,树内不重复标题也不留空标题占位 */} + onNavigate("code")} /> +
    +
    + ); +} diff --git a/src/components/ProcessStamps.css b/src/components/ProcessStamps.css new file mode 100644 index 0000000..997b484 --- /dev/null +++ b/src/components/ProcessStamps.css @@ -0,0 +1,87 @@ +/* 工序章 — UI-4 Stage A1(round-03 §4.3 + a-deep.html .stamps/.stamp) + * 五等分章:边框 1px --w,章间 1px --wdim,直角无线框;底 --bp(图纸底)。 + * 三层字族:.no / .st 等宽(数据层),.nm 仿宋(标注层),不用黑体(§2.2)。 + * 状态色纪律(§2.5):done=--ok 青 / doing=--blue 蓝(进行中)/ alert=--red + * 红 / todo=--wdim 灰 + 半透明。颜色全部引用 tokens.css 变量,不写死色值。 */ + +.processstamps { + display: flex; + border: var(--border-w) solid var(--w); + background: var(--bp); +} + +.processstamps-stamp { + flex: 1; + min-width: 0; + position: relative; + padding: var(--sp-4) 0 var(--sp-3); + text-align: center; + background: var(--bp); + border-right: var(--border-w) solid var(--wdim); +} + +.processstamps-stamp:last-child { + border-right: none; +} + +/* 序号:等宽小字(数据层) */ +.processstamps-no { + font-family: var(--mono); + font-size: var(--fs-note); + line-height: var(--lh-data); + color: var(--wdim); + letter-spacing: 2px; +} + +/* 工序名:仿宋大字(标注层),字距放开成章面 */ +.processstamps-nm { + margin: var(--sp-1) 0; + font-family: var(--fs); + font-size: calc(var(--fs-body) + var(--sp-1)); + line-height: var(--lh-data); + letter-spacing: 5px; +} + +/* 状态小字:等宽(数据层) */ +.processstamps-st { + font-family: var(--mono); + font-size: var(--fs-note); + line-height: var(--lh-data); +} + +/* ---- done:已完成 → 状态小字青(--ok 唯一语义=成功/已完成) ---- */ +.processstamps-stamp[data-status="done"] .processstamps-st { + color: var(--ok); +} + +/* ---- doing:进行中 → 底部 inset 蓝条 + 淡蓝底 + 名白字 + 状态蓝字 ---- + * 淡蓝底 = a-deep .doing 的 rgba(143,192,230,.06):此处以 color-mix 由令牌 + * 混出(不写死色值);不支持 color-mix 的环境落回面板底 --bp-d,蓝条仍在。 */ +.processstamps-stamp[data-status="doing"] { + background: var(--bp-d); + background: color-mix(in srgb, var(--blue) 6%, var(--bp)); + box-shadow: inset 0 calc(var(--border-w) * -3) 0 var(--blue); +} + +.processstamps-stamp[data-status="doing"] .processstamps-nm { + color: var(--w); +} + +.processstamps-stamp[data-status="doing"] .processstamps-st { + color: var(--blue); +} + +/* ---- alert:有问题 → 名与状态小字红(--red 唯一语义=错误/死链/差异) ---- */ +.processstamps-stamp[data-status="alert"] .processstamps-nm, +.processstamps-stamp[data-status="alert"] .processstamps-st { + color: var(--red); +} + +/* ---- todo:未开始 → 整章半透明 + 状态小字弱色 ---- */ +.processstamps-stamp[data-status="todo"] { + opacity: 0.5; +} + +.processstamps-stamp[data-status="todo"] .processstamps-st { + color: var(--wdim); +} diff --git a/src/components/ProcessStamps.tsx b/src/components/ProcessStamps.tsx new file mode 100644 index 0000000..0a758e3 --- /dev/null +++ b/src/components/ProcessStamps.tsx @@ -0,0 +1,48 @@ +/** + * 工序章 — UI-4 Stage A1(⓪总览顶部主角,§4.3) + * + * 职责:拉取→切片→拼版→校样→出厂 五章横排,等分;每章「序号(等宽小字)+ + * 名(仿宋大字)+ 状态(等宽小字 note)」。差异化的图纸语言,总览唯一主角。 + * 纯受控展示:不调 hub、不持状态——五章数据由 A3 经 useOverviewData 派生后传入, + * 本组件只做渲染 + 状态四态的视觉映射(§2.5 状态色纪律): + * done → .st 青(--ok = 已完成) + * doing → 章底 inset 蓝条 + 淡蓝底 + .nm 白字 + .st 蓝(--blue = 进行中) + * alert → .nm / .st 红(--red = 错误 / 死链 / 差异) + * todo → 整章半透明 + .st 灰(--wdim) + * 数据形状:StampState(state/processStamps.ts,契约 §1)——steps 恒 5 项, + * 顺序 拉取→切片→拼版→校样→出厂,序号 01…05 由数组下标派生(不写死)。 + * 动效(§6,A2 实现到 CSS / A3 在 Overview.tsx 施加 .ov-enter→.ov-enter-done): + * 本章内每项即 .processstamps-stamp(.processstamps 的直接子元素,恰 5 项), + * 阶梯 transition-delay 由 :nth-child 命中;本组件不加动画类、不接管时序。 + */ +import type { ReactElement } from "react"; +import type { StampState } from "../state/processStamps"; +import "./ProcessStamps.css"; + +export interface ProcessStampsProps { + /** 五道工序(恒 5 项,顺序 拉取→切片→拼版→校样→出厂) */ + steps: StampState[]; +} + +export default function ProcessStamps(props: ProcessStampsProps): ReactElement { + const { steps } = props; + + return ( +
    + {steps.map((step, i) => ( +
    + {/* 序号:等宽·数字表格化(§2.2),01…05 由下标派生 */} +
    {String(i + 1).padStart(2, "0")}
    +
    {step.name}
    +
    {step.note}
    +
    + ))} +
    + ); +} diff --git a/src/components/RouteSlide.tsx b/src/components/RouteSlide.tsx new file mode 100644 index 0000000..09139ce --- /dev/null +++ b/src/components/RouteSlide.tsx @@ -0,0 +1,32 @@ +/** + * — 工作面滑入包装(round-03 §2.6 第二件套:状态切换来路) + * + * 机制:挂载时根 div 带 .route-slide-pre(translateX(var(--dist-move)) + opacity 0), + * 双 rAF 后移除该类 → .route-slide 上的 transition(--dur-move / --ease-out)驱动 + * transform + opacity 归位。用 transition 而非 keyframes 是为了让截图工具能抓到 + * 过渡帧(§2.6 明示);样式表在 src/routes/routes.css(与其余路由壳样式同处)。 + * + * 用法(五面路由根元素,替代原
    ): + * + *
    …
    + *
    + * + * 受控性:本组件不持有业务状态,唯一的内部状态是"是否已入场"的动效开关 + * (由 useFirstEnter 提供,挂载即启动,父组件无需干预)。 + * prefers-reduced-motion 由 tokens.css 全局兜底,本组件无需分支。 + */ +import { type ReactNode, type JSX } from "react"; +import { useFirstEnter } from "../hub/useFirstEnter"; +import "../routes/routes.css"; + +export function RouteSlide(props: { children: ReactNode }): JSX.Element { + const entered = useFirstEnter(); + + return ( +
    + {props.children} +
    + ); +} + +export default RouteSlide; diff --git a/src/components/TodoList.css b/src/components/TodoList.css new file mode 100644 index 0000000..7260bb1 --- /dev/null +++ b/src/components/TodoList.css @@ -0,0 +1,89 @@ +/* 待办清单 — UI-4 Stage A1(a-deep.html .ov-blk + .todo-line) + * 块:1px --wdim 外框 + 底 --bp(总览面板底);标题行 1px --wdim 实线分块; + * 行间 1px dashed --wfaint 虚线分组(§2.4 分隔三级)。 + * 字族:标题与行文本仿宋(标注层,照 a-deep),符号等宽(数据层)。 + * 颜色全部引用 tokens.css 变量,不写死色值。 */ + +.todolist { + border: var(--border-w) solid var(--wdim); + background: var(--bp); +} + +.todolist-head { + padding: var(--sp-2) var(--sp-4); + border-bottom: var(--border-w) solid var(--wdim); +} + +.todolist-title { + font-family: var(--fs); + font-size: var(--fs-note); + letter-spacing: 3px; + color: var(--w); +} + +.todolist-line { + display: flex; + align-items: center; + gap: var(--sp-3); + padding: var(--sp-2) var(--sp-4); + border-bottom: var(--border-w) dashed var(--wfaint); + font-family: var(--fs); + font-size: var(--fs-panel); + line-height: var(--lh-body); + cursor: pointer; + transition: background var(--dur-fast) var(--ease-out); +} + +.todolist-line:last-child, +.todolist-empty:last-child { + border-bottom: none; +} + +.todolist-line:hover { + background: var(--bp-d); +} + +.todolist-line:focus-visible { + outline: var(--border-w) solid var(--blue); + outline-offset: calc(var(--border-w) * -1); +} + +/* 行首符号:固定槽宽(对齐),等宽字符;颜色由数据侧语义决定(§2.5) */ +.todolist-mk { + flex: none; + width: var(--sp-4); + text-align: center; + font-family: var(--mono); + font-size: var(--fs-note); +} + +.todolist-line[data-color="red"] .todolist-mk { + color: var(--red); +} + +.todolist-line[data-color="blue"] .todolist-mk { + color: var(--blue); +} + +.todolist-line[data-color="amber"] .todolist-mk { + color: var(--amber); +} + +.todolist-line[data-color="ok"] .todolist-mk { + color: var(--ok); +} + +.todolist-text { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +/* 空态:一行灰字,不留空白块 */ +.todolist-empty { + padding: var(--sp-3) var(--sp-4); + font-family: var(--fs); + font-size: var(--fs-panel); + color: var(--wdim); +} diff --git a/src/components/TodoList.tsx b/src/components/TodoList.tsx new file mode 100644 index 0000000..c3e02dc --- /dev/null +++ b/src/components/TodoList.tsx @@ -0,0 +1,76 @@ +/** + * 待办清单 — UI-4 Stage A1(⓪总览左下块,a-deep.html .todo-line) + * + * 职责:块标题「待 办」+ 若干行「mark 字符符号(自带颜色)+ 文本」;行点击 + * → onNavigate(target),跳去该行所属工作面(①代码 / ③卡牌 / ④素材…)。 + * 纯受控展示:todos 与跳转回调由 A3(useOverviewData + 图层切换)供给, + * 本组件不持状态、不调 hub。 + * 符号与状态色(§2.4 符号即图标 / §2.5 纪律):mark 用字符符号(✗ ⇄ ✂ ⬆ ✓…), + * 颜色由 item.color 决定 —— 数据侧已按语义定色(红=错误·死链·差异、 + * 蓝=进行中·代理、琥珀=待人审、青=成功·完成),本组件只做映射不做判断。 + * 空态:一行灰字「✓ 无待办」(诚实空态,不留空白块)。 + */ +import type { KeyboardEvent, ReactElement } from "react"; +import type { LayerId, TodoItem } from "../state/processStamps"; +import "./TodoList.css"; + +export interface TodoListProps { + /** 待办行(来自 OverviewData.todos) */ + todos: TodoItem[]; + /** 行点击 → 跳转对应工作面 */ + onNavigate(layer: LayerId): void; +} + +function TodoLine(props: { + item: TodoItem; + onNavigate: TodoListProps["onNavigate"]; +}): ReactElement { + const { item, onNavigate } = props; + + const activate = (): void => { + onNavigate(item.target); + }; + + const handleKeyDown = (event: KeyboardEvent): void => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + activate(); + } + }; + + return ( +
    + + {item.text} +
    + ); +} + +export default function TodoList(props: TodoListProps): ReactElement { + const { todos, onNavigate } = props; + + return ( +
    +
    + 待 办 +
    + {todos.length > 0 ? ( + todos.map((item, i) => ( + + )) + ) : ( +
    ✓ 无待办
    + )} +
    + ); +} diff --git a/src/hub/useFirstEnter.ts b/src/hub/useFirstEnter.ts new file mode 100644 index 0000000..04bba6e --- /dev/null +++ b/src/hub/useFirstEnter.ts @@ -0,0 +1,38 @@ +/** + * useFirstEnter — 首次进入钩子(round-03 §2.6 第三件套 / UI-4 Stage A 契约 §6) + * + * 语义:挂载后先返回 false(= 元素处于 pre 出场态),双 rAF 之后返回 true + * (= pre 态被移除,transition 归位)。仅首次挂载触发一次,之后不再回退。 + * + * 双 rAF 的理由:第一帧让浏览器完成带 pre 类的首帧布局/绘制(否则"挂载即翻态" + * 会被合并进同一次样式计算,transition 不产生过渡帧);第二帧再翻态,过渡必被观测。 + * + * 用法(装配方:总览面): + * const entered = useFirstEnter(); + *
    …
    + * 类名语义见 src/routes/Overview.css(.ov-enter = pre 态,.ov-enter-done = 移除 pre)。 + * + * 无副作用:不做订阅、不请求 hub;prefers-reduced-motion 由 tokens.css 全局 + * transition:none 兜底(本 hook 照常翻态,元素直接落到终态)。 + */ +import { useEffect, useState } from "react"; + +export function useFirstEnter(): boolean { + const [entered, setEntered] = useState(false); + + useEffect(() => { + let raf1 = 0; + let raf2 = 0; + raf1 = window.requestAnimationFrame(() => { + raf2 = window.requestAnimationFrame(() => setEntered(true)); + }); + return () => { + window.cancelAnimationFrame(raf1); + window.cancelAnimationFrame(raf2); + }; + }, []); + + return entered; +} + +export default useFirstEnter; diff --git a/src/routes/Agent.tsx b/src/routes/Agent.tsx index a0f3141..22f0b45 100644 --- a/src/routes/Agent.tsx +++ b/src/routes/Agent.tsx @@ -23,6 +23,7 @@ import type { ReactElement } from "react"; import JobSheet from "../components/JobSheet"; import LuaExecPanel from "../components/LuaExecPanel"; import EventFlow from "../components/EventFlow"; +import { RouteSlide } from "../components/RouteSlide"; import { useSseEvents } from "../hub/useSseEvents"; import { useJobTracker } from "../hub/useJobTracker"; import { useHub } from "../hub/HubContext"; @@ -74,7 +75,7 @@ export default function Agent(): ReactElement { }; return ( -
    +
    {/* 工作区:作业流水 */}
    @@ -94,6 +95,6 @@ export default function Agent(): ReactElement {
    -
    + ); } diff --git a/src/routes/Assets.tsx b/src/routes/Assets.tsx index 8029338..37e59eb 100644 --- a/src/routes/Assets.tsx +++ b/src/routes/Assets.tsx @@ -55,6 +55,7 @@ import type { AssetGroupCount } from "../components/AssetsGroupNav"; import AssetsTable from "../components/AssetsTable"; import type { AssetRow } from "../components/AssetsTable"; import ImportPreviewDialog from "../components/ImportPreviewDialog"; +import { RouteSlide } from "../components/RouteSlide"; import { useConfirmGate, useHub, type ConfirmRequest } from "../hub/HubContext"; import { useSseEvents } from "../hub/useSseEvents"; @@ -637,7 +638,7 @@ function AssetsInner(): ReactElement { const rootBase = root === null ? "—" : root.split(/[\\/]/).filter(Boolean).pop() ?? root; return ( -
    +
    {/* 对象区:类型分组导航 */}
    +
    ); } diff --git a/src/routes/Cards.tsx b/src/routes/Cards.tsx index ab08fcd..4f4b0ad 100644 --- a/src/routes/Cards.tsx +++ b/src/routes/Cards.tsx @@ -43,6 +43,7 @@ import CardBackPreview from "../components/CardBackPreview"; import SliceGrid from "../components/SliceGrid"; import type { SheetMeta, SliceCard } from "../components/SliceGrid"; import CardFacePreview from "../components/CardFacePreview"; +import { RouteSlide } from "../components/RouteSlide"; import { useConfirmGate, useHub } from "../hub/HubContext"; import { useSseEvents } from "../hub/useSseEvents"; @@ -749,7 +750,7 @@ function CardsInner(): ReactElement { }; return ( -
    +
    {/* 对象区:牌堆列表(上) + 卡背预览(下) */}
    -
    + ); } diff --git a/src/routes/Code.tsx b/src/routes/Code.tsx index 37f4fca..be483ad 100644 --- a/src/routes/Code.tsx +++ b/src/routes/Code.tsx @@ -27,10 +27,12 @@ import type { TreeNode } from "../components/CodeFileTree"; import CodeDiffView from "../components/CodeDiffView"; import type { DiffEntry } from "../components/CodeDiffView"; import CodeEditor from "../components/CodeEditor"; +import { RouteSlide } from "../components/RouteSlide"; import { useConfirmGate, useHub, type ConfirmRequest } from "../hub/HubContext"; import { useSseEvents } from "../hub/useSseEvents"; import { useJobTracker } from "../hub/useJobTracker"; +import { useDirty } from "../state/DirtyContext"; import { sha256Hex } from "../hub/sha256"; import { isHubError } from "../hub/errors"; @@ -107,6 +109,9 @@ function CodeInner(): ReactElement { const { events: sseEvents } = useSseEvents(); const { track } = useJobTracker(); const { ask } = useConfirmGate(); + // 脏通道(UI-4 Stage B1 最小接入):编辑器缓冲的未提交改动上报给全站 store, + // App.tsx ① 代码 dot(蓝)与会签栏版本行的未提交数同源;本面照旧只管自己的编辑态 + const { markDirty, markClean } = useDirty(); // ---- 数据状态 ---- const [root, setRoot] = useState(null); @@ -232,6 +237,9 @@ function CodeInner(): ReactElement { const handleSelect = useCallback( async (guid: string, kind: EntryKind): Promise => { if (root === null || loading) return; + // 脏通道:切换 / 重载都会丢弃编辑器缓冲(本面既有行为),上一个对象的未提交 + // 标记随之清除;重新加载当前对象即「还原」→ 同样在这条路径上标干净 + if (activeGuid !== null) markClean(activeGuid); const entry = diffEntries.find((e) => e.guid === guid && e.kind === kind) ?? null; setTab("edit"); setActiveGuid(guid); @@ -260,7 +268,7 @@ function CodeInner(): ReactElement { setError(e instanceof Error ? e.message : String(e)); } }, - [root, loading, diffEntries, caps.canReadFiles, client, track], + [root, loading, diffEntries, caps.canReadFiles, client, track, activeGuid, markClean], ); const openEntryInEditor = useCallback( @@ -270,10 +278,15 @@ function CodeInner(): ReactElement { [handleSelect], ); - const handleEditorChange = useCallback((next: string): void => { - setEditedContent(next); - setDirty(true); - }, []); + const handleEditorChange = useCallback( + (next: string): void => { + setEditedContent(next); + setDirty(true); + // 脏通道:编辑器里有改动(保存 / 还原前)→ 上报当前对象,① 代码 dot 转蓝 + if (activeGuid !== null) markDirty(activeGuid); + }, + [activeGuid, markDirty], + ); // ---- 保存:filesWrite(乐观锁);409 → 冲突条 ---- const handleSave = useCallback(async (): Promise => { @@ -289,6 +302,8 @@ function CodeInner(): ReactElement { setOriginalSha256(res.sha256); setDirty(false); setConflict(false); + // 脏通道:落盘成功 → 该对象的未提交改动清除 + if (activeGuid !== null) markClean(activeGuid); await refreshDiff(root); } catch (e) { if (isHubError(e) && e.code === "HUB_CONFLICT") { @@ -299,7 +314,17 @@ function CodeInner(): ReactElement { } finally { setBusy(false); } - }, [root, activeEntry, originalSha256, editedContent, client, track, refreshDiff]); + }, [ + root, + activeEntry, + originalSha256, + editedContent, + client, + track, + refreshDiff, + activeGuid, + markClean, + ]); /** 冲突条「强制覆盖」:不带 baseSha256 绕过乐观锁(用户显式选择) */ const handleForceOverwrite = useCallback(async (): Promise => { @@ -314,13 +339,15 @@ function CodeInner(): ReactElement { setOriginalSha256(res.sha256); setDirty(false); setConflict(false); + // 脏通道:强制覆盖同样已落盘 → 清除该对象的未提交改动 + if (activeGuid !== null) markClean(activeGuid); await refreshDiff(root); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } - }, [root, activeEntry, editedContent, client, track, refreshDiff]); + }, [root, activeEntry, editedContent, client, track, refreshDiff, activeGuid, markClean]); // ---- 重新拉取:游戏内 → 工作区,再重 diff ---- const handlePull = useCallback(async (): Promise => { @@ -426,7 +453,7 @@ function CodeInner(): ReactElement { }; return ( -
    +
    {/* 对象区:差异文件树 */}
    -
    +
    ); } diff --git a/src/routes/Overview.css b/src/routes/Overview.css new file mode 100644 index 0000000..1a1ba8d --- /dev/null +++ b/src/routes/Overview.css @@ -0,0 +1,164 @@ +/* ============================================================================ + * ⓪ 总览面样式 — UI-4 Stage A2(首进阶梯)+ Stage B1(路由骨架布局) + * + * 本文件两块:下半「布局」段 = Stage B1 补的路由骨架(a-deep.html 48-49/68-70/94 行); + * 其余是 Stage A2 的「首次进入阶梯」(round-03 §2.6 动效三件套之三, + * 参考 ui-design/round-03/candidates/a-deep.html 301-307 行): + * 工序章五枚 + 内容块两项,按阅读顺序 translateY(10px) + opacity 0 → 归位, + * 延迟阶梯 02/07/12/17/22/26/32。 + * 内容块的外框/标题(a-deep .ov-blk 的边框与 .bh 头)由各块组件自己负责 + * (TodoList / MiniFileTree / LayerTiles … 均自带块级外框),本文件的 .ov-blk + * 只作动效钩子,不重复画框,避免与组件样式叠成双线。 + * + * ── 类名语义(契约 §6,装配方在 Overview.tsx 施加)────────────────────────── + * .ov-enter pre 出场态(translateY(10px) + opacity 0) + * .ov-enter-done 移除 pre 态 → 元素的 transition 归位 + * 装配方用法(推荐:整面一个容器 + useFirstEnter): + * const entered = useFirstEnter(); // src/hub/useFirstEnter.ts + *
    + * ← .processstamps-stamp 自动错落 + *
    + *
    …
    ← delay .26s + *
    …
    ← delay .32s + *
    + *
    + * 元素级用法等价:把 .ov-enter / .ov-enter-done 直接加在 .ov-blk 上即可。 + * pre 态只落在「工序章 + 内容块」上,不落在容器本身——避免与 的 + * translateX 滑入叠成两段位移。 + * + * ── 取巧说明 ─────────────────────────────────────────────────────────────── + * 1) 时长 .4s ease 按 §2.6 第三件套原文取字面量:该套动的时长未令牌化 + * (§2.6 的 --dur-* 只覆盖遮罩淡入 / 工作面滑入 / 确认门生长), + * 阶梯延迟 .02–.32s 同样是字面量;若后续把 .4s 收进令牌(--dur-enter), + * 只改本文件这一处。 + * 2) transition 写在元素本体(不在 .ov-enter 上):若写在 .ov-enter 里, + * 换类那一帧 transition 声明会随类一起消失,过渡不产生。 + * 3) prefers-reduced-motion 由 tokens.css 全局 transition:none 兜底, + * 本文件不重复写 media query;此时类切换照常发生,元素直接落终态。 + * ==========================================================================*/ + +/* ── 出场元素白名单:工序章五枚 + 内容块两项 ───────────────────────────────── + * 类名有变时只改这一组选择器(.processstamps-stamp 见 components/ProcessStamps.tsx, + * .ov-blk 为总览面块容器约定名)。 */ +.processstamps-stamp, +.ov-blk { + transition: + transform .4s ease, + opacity .4s ease; +} + +/* ── 阶梯延迟:阅读顺序,与 round-03 逐字一致 ────────────────────────────── */ +.processstamps-stamp:nth-child(1) { + transition-delay: 0.02s; +} +.processstamps-stamp:nth-child(2) { + transition-delay: 0.07s; +} +.processstamps-stamp:nth-child(3) { + transition-delay: 0.12s; +} +.processstamps-stamp:nth-child(4) { + transition-delay: 0.17s; +} +.processstamps-stamp:nth-child(5) { + transition-delay: 0.22s; +} + +/* 内容块两项:.26 / .32s(嵌套在列容器里时各为其父的第一子 → 同为 .26s, + * 与 a-deep 的 .ov-blk:nth-child(1)/(2)写法一致) */ +.ov-blk:nth-child(1) { + transition-delay: 0.26s; +} +.ov-blk:nth-child(2) { + transition-delay: 0.32s; +} + +/* ── pre 态(translateY(10px) + opacity 0)──────────────────────────────── + * 容器式:祖先带 .ov-enter 且尚未标 done; + * 元素式:元素自身带 .ov-enter 且尚未标 done(此时元素必是白名单成员)。 */ +.ov-enter:not(.ov-enter-done) .processstamps-stamp, +.ov-enter:not(.ov-enter-done) .ov-blk, +.processstamps-stamp.ov-enter:not(.ov-enter-done), +.ov-blk.ov-enter:not(.ov-enter-done) { + transform: translateY(10px); + opacity: 0; +} + +/* ============================================================================ + * 布局 — UI-4 Stage B1 路由骨架(a-deep.html 48-49 / 68-70 / 94 行) + * + * 结构(Overview.tsx 组装): + * .overview(横排)├ .ov-main(flex:1)= .ov-stamps + .ov-grid 双列 + * └ .ov-side(290px 定宽) + * 线框分隔:右栏左缘 1px dashed --wdim(分栏用虚线,§2.4);块外框由各展示组件自管 + * (TodoList / MiniFileTree / LayerTiles 自带 1px --wdim 框),.ov-blk 只作动效钩子, + * .ov-ev 只给「事件流」这一块补同款框(EventFlow 自带头部,无自有外框)。 + * 全引用 tokens.css 变量;290px 栏宽与 a-deep 逐字一致(同 Agent.css 的 320px 列宽)。 + * ==========================================================================*/ + +.overview { + display: flex; + width: 100%; + height: 100%; + overflow: hidden; +} + +.ov-main { + flex: 1; + min-width: 0; + padding: var(--sp-5) var(--sp-6); /* a-deep:20px 24px */ + display: flex; + flex-direction: column; +} + +/* 工序章容器:只作阶梯动效钩子 + 章面与下部的间距(a-deep .stamps margin 0 0 18px); + * flex:none —— 主轴(纵向)压缩不得压扁章面,余量归 .ov-grid */ +.ov-stamps { + flex: none; + margin-bottom: var(--sp-4); +} + +/* 下部两栏填实:左工作区 / 右事件流(1fr 1fr) */ +.ov-grid { + flex: 1; + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--sp-4); + min-height: 0; +} + +.ov-col { + display: flex; + flex-direction: column; + min-height: 0; +} + +/* 同列两块之间的间距(a-deep 左列第二块 margin-top:14px → 取最近的间距令牌) */ +.ov-col > .ov-blk + .ov-blk { + margin-top: var(--sp-3); +} + +/* 事件流块:吃满右列高度(.eventflow 自带 height:100% + 内部滚动),框同左列两块 */ +.ov-ev { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + border: var(--border-w) solid var(--wdim); + background: var(--bp); + overflow: hidden; +} + +/* 右栏:290px 定宽(a-deep 290px,不随窗口伸缩),左缘虚线分栏 */ +.ov-side { + width: 290px; + flex: none; + padding: var(--sp-4); + border-left: var(--border-w) dashed var(--wdim); + background: var(--bp); /* 盖住 canvas 的 42px 网格底纹(a-deep .ov-side 同) */ + display: flex; + flex-direction: column; + gap: var(--sp-4); + overflow-y: auto; +} + diff --git a/src/routes/Overview.tsx b/src/routes/Overview.tsx index bbb0282..584bc58 100644 --- a/src/routes/Overview.tsx +++ b/src/routes/Overview.tsx @@ -1,16 +1,102 @@ /** - * ⓪ 总览面 — 占位(UI-4 填充:工序章 + 待办 + 迷你文件树 + 四面状态磁贴) + * ⓪ 总览面 — UI-4 Stage B1 路由组装(round-03 §3.1 三区骨架 + a-deep.html 368-425) + * + * 职责:把 Stage A 展示组件组装为完整总览面—— + * 左主区(.ov-main): 工序章 横贯顶部 + * + .ov-grid 双列:左列 / ,右列 + * 右栏(.ov-side,290px): 四面状态磁贴 + * 动效(§2.6 三件套之二/之三): + * - 工作面滑入:根元素由 包装(替掉原
    ); + * - 首次进入阶梯:useFirstEnter() 翻转 .ov-enter → .ov-enter-done(delay 阶梯在 + * ./Overview.css,pre 态只落在「工序章容器 + .ov-grid」两个块上,不落在容器本体, + * 免与 RouteSlide 的 translateX 叠成两段位移)。 + * + * 数据来源(受控):OverviewData 由 AppInner 的 useOverviewData 单点派生后经 props 传入。 + * 本面不自己调 useOverviewData——该 hook 有模块级结果缓存但无在途去重,App 与路由同时 + * 调用会在冷启动并发发两次 pullScripts(覆盖工作区)+ 两次 testRun(在真实游戏内跑测试), + * 详见 src/App.tsx 文件头「单点」说明。本面只读:SSE 事件流经 useSseEvents()(Context 订阅, + * 无副作用),迷你文件树经 Stage A 的 deriveMiniTree(root)(与 ①代码面同一份差异缓存)。 + * 视图内跳转:待办行 / 四面磁贴 / 迷你文件树行 → onNavigate(layer)(App.tsx 的 setActiveLayer)。 */ +import type { ReactElement } from "react"; + +import ProcessStamps from "../components/ProcessStamps"; +import TodoList from "../components/TodoList"; +import MiniFileTree from "../components/MiniFileTree"; +import LayerTiles from "../components/LayerTiles"; +import EventFlow from "../components/EventFlow"; +import { RouteSlide } from "../components/RouteSlide"; + +import { useSseEvents } from "../hub/useSseEvents"; +import { useFirstEnter } from "../hub/useFirstEnter"; +import { deriveMiniTree, type LayerId, type OverviewData } from "../state/processStamps"; + import "./routes.css"; +import "./Overview.css"; + +export interface OverviewProps { + /** ⓪总览聚合数据(AppInner 的 useOverviewData 单点派生;本面纯渲染) */ + data: OverviewData; + /** 已注册图包 root(迷你文件树数据源;null = 未注册图包,deriveMiniTree 给空态 note) */ + root: string | null; + /** 块内跳转(待办行 / 四面磁贴 / 迷你文件树)→ 切换工作面 */ + onNavigate(layer: LayerId): void; +} + +export default function Overview(props: OverviewProps): ReactElement { + const { data, root, onNavigate } = props; + + // SSE 事件流(②代理面同一订阅:App.tsx 顶层 SseProvider,本面只消费) + const { events, state, clear } = useSseEvents(); + // 首进阶梯开关:false = 出场态(.ov-enter),双 rAF 后 true(.ov-enter-done) + const entered = useFirstEnter(); + // 迷你文件树:与 ①代码面同源(Stage A 差异缓存派生,组件不调 hub) + const tree = deriveMiniTree(root); + + const ladder = entered ? "ov-enter-done" : "ov-enter"; -export default function Overview() { return ( -
    -
    -
    ⓪
    -
    总览
    -
    本面内容于 UI-4 窗口填充(工序章 / 待办 / 迷你文件树)
    + +
    +
    + {/* 工序章:总览唯一主角,横贯顶部(容器只作阶梯动效钩子) */} +
    + +
    + + {/* 下部填实:左工作区(待办 + 文件树) / 右事件流 */} +
    +
    +
    + +
    +
    + +
    +
    +
    + {/* .ov-ev 只补块框与剩余高度:.eventflow 自带头部(标题 + ● 存活点 + 清空) + 与内部滚动,不另造第二套外壳 */} +
    + +
    +
    +
    +
    + + {/* 右栏:四面状态磁贴(290px 定宽,虚线分栏) */} +
    -
    + ); } diff --git a/src/routes/routes.css b/src/routes/routes.css index 462dad8..28739c1 100644 --- a/src/routes/routes.css +++ b/src/routes/routes.css @@ -28,19 +28,18 @@ font-family: var(--sans); } -/* 工作面切换动画:translateX(56px) + opacity 滑入(§2.6) */ +/* 工作面切换动画:translateX(var(--dist-move)) + opacity 滑入(§2.6 第二件套) + * transition 驱动(不用 keyframes)以便截图工具抓到过渡帧; + * 初始 pre 态 .route-slide-pre 由 挂载时带上,双 rAF 后移除并触发过渡。 + * 位移由 .frame-canvas{overflow:hidden} 兜住,不产生横向滚动。 */ .route-slide { height: 100%; - animation: route-slide-in var(--dur-move) var(--ease-out) both; + transition: + transform var(--dur-move) var(--ease-out), + opacity var(--dur-move) var(--ease-out); } -@keyframes route-slide-in { - from { - transform: translateX(var(--dist-move)); - opacity: 0; - } - to { - transform: translateX(0); - opacity: 1; - } +.route-slide-pre { + transform: translateX(var(--dist-move)); + opacity: 0; } diff --git a/src/state/DirtyContext.tsx b/src/state/DirtyContext.tsx new file mode 100644 index 0000000..e355ab1 --- /dev/null +++ b/src/state/DirtyContext.tsx @@ -0,0 +1,123 @@ +/** + * DirtyContext — UI-4 Stage A3「状态引擎 + 脏通道」的脏通道半边 + * + * 职责:全站「未提交改动」GUID 集合 store(React Context + useReducer,仿 + * ./DeadLinkContext.tsx + ./deadLinkReducer.ts 范式)。①代码面在编辑器里改动 / + * 保存后把对应对象 guid 上报进来,App.tsx 读 dirtyGuids.size 驱动 ① 代码面 + * LayerNav 圆点(>0 = red「有未提交改动」),后续要更多消费方也只是读同一集合。 + * + * 关键设计(与 DeadLinkContext 对齐的约定): + * - 唯一实例挂 App.tsx 顶层(HubContext.Provider → ConfirmGateProvider → SseProvider + * → DeadLinkProvider → DirtyProvider → AppInner;路由不自行挂 Provider); + * - 状态机在本文件内(dirtyReducer / DirtyState / DirtyAction 均导出),状态不可变: + * Set 只在变更时新建,未变更(重复 markDirty / markClean 不存在的 guid)返回原引用, + * 消费方按引用即可判断「有没有变化」,也不会被空操作触发多余重渲染; + * - dirtyGuids 对外类型 ReadonlySet:只读视图,变更只能经 reducer, + * 杜绝旁路写; + * - markDirty / markClean / clearDirty 经 useCallback 稳定引用:消费方 + * memo / effect 依赖安全; + * - 空字符串 guid 静默忽略(全局脚本/UI 的合法 guid 是 "-1",不是 ""); + * - useDirty 在 Provider 外使用即 throw(useHub / useConfirmGate / useDeadLinks 同款防御)。 + * + * 说明:任务清单只允许写本文件,故 reducer 不像 deadLinkReducer 那样单列一个文件, + * 但导出形状(reducer + 初始态 + State/Action 类型)与 DeadLinkContext 一致。 + */ +import { + createContext, + useCallback, + useContext, + useMemo, + useReducer, + type JSX, + type ReactNode, +} from "react"; + +/** 脏文件 store 状态 */ +export interface DirtyState { + /** 已改动未提交的对象 GUID 集合(只读;变更经 reducer) */ + dirtyGuids: ReadonlySet; +} + +/** 脏文件 store 动作 */ +export type DirtyAction = + | { type: "dirty"; guid: string } + | { type: "clean"; guid: string } + | { type: "clear" }; + +/** 初始状态:无脏文件 */ +export const initialDirtyState: DirtyState = { + dirtyGuids: new Set(), +}; + +/** + * 脏文件 store reducer(纯函数)。 + * 未产生变化的动作返回原 state 引用(不新建 Set、不触发重渲染)。 + */ +export function dirtyReducer(state: DirtyState, action: DirtyAction): DirtyState { + switch (action.type) { + case "dirty": { + if (action.guid === "" || state.dirtyGuids.has(action.guid)) return state; + const next = new Set(state.dirtyGuids); + next.add(action.guid); + return { dirtyGuids: next }; + } + case "clean": { + if (!state.dirtyGuids.has(action.guid)) return state; + const next = new Set(state.dirtyGuids); + next.delete(action.guid); + return { dirtyGuids: next }; + } + case "clear": + return state.dirtyGuids.size === 0 ? state : { dirtyGuids: new Set() }; + } +} + +/** DirtyContext 消费值(契约 §2) */ +export interface DirtyContextValue { + /** 已改动未提交的对象 GUID 集合(只读) */ + dirtyGuids: ReadonlySet; + /** 上报某对象有未提交改动 */ + markDirty(guid: string): void; + /** 上报某对象已回到干净状态(保存 / 写回 / 重新拉取后) */ + markClean(guid: string): void; + /** 清空(重新拉取 / 切换图包) */ + clearDirty(): void; +} + +const DirtyContext = createContext(null); + +/** 全站唯一脏文件 Provider(App.tsx 顶层挂载一次) */ +export function DirtyProvider(props: { children: ReactNode }): JSX.Element { + const { children } = props; + + const [state, dispatch] = useReducer(dirtyReducer, initialDirtyState); + + // 动作引用稳定(useCallback []):消费方 memo / effect 依赖安全 + const markDirty = useCallback((guid: string): void => { + dispatch({ type: "dirty", guid }); + }, []); + const markClean = useCallback((guid: string): void => { + dispatch({ type: "clean", guid }); + }, []); + const clearDirty = useCallback((): void => { + dispatch({ type: "clear" }); + }, []); + + const value = useMemo( + () => ({ dirtyGuids: state.dirtyGuids, markDirty, markClean, clearDirty }), + [state.dirtyGuids, markDirty, markClean, clearDirty], + ); + + return {children}; +} + +/** 消费脏文件 store;必须在 内使用(App.tsx 顶层挂载一次) */ +export function useDirty(): DirtyContextValue { + const v = useContext(DirtyContext); + if (v === null) { + throw new Error( + "useDirty() 必须在 内使用(App.tsx 顶层挂载一次)", + ); + } + return v; +} diff --git a/src/state/processStamps.ts b/src/state/processStamps.ts new file mode 100644 index 0000000..736fb50 --- /dev/null +++ b/src/state/processStamps.ts @@ -0,0 +1,826 @@ +/** + * processStamps — UI-4 Stage A3「状态引擎 + 脏通道」的状态引擎半边 + * + * 唯一事实源:ui-design/round-03/UI施工方案.md §4.3(工序章)/ §4.4(会签栏)/ + * §3.1(⓪总览工作面)+ UI-4 锁定决策 2「出厂章与 SignBlock checks 同源」。 + * + * 本模块三块职责: + * 1. `useOverviewData(src)`:把 hub(GET /v1/packs、POST /v1/scripts/pull + /v1/diff、 + * POST /v1/test/run)+ 全站死链 store(消费方经 src.deadUrls 传入)+ SSE 事件数组 + * (src.sseEvents 传入)折算成 ⓪总览需要的 OverviewData(五章状态 / 待办行 / 四面磁贴)。 + * 2. `deriveMiniTree(root)`:⓪总览「工作区」迷你文件树的数据源(A1 版 MiniFileTreeProps + * 的 nodes + note),与 ①代码面的 diff 同源(同一份条目的模块级缓存)。 + * 3. `deriveSignBlock(data)`:§4.4 会签栏交付清单数据源(出厂行与出厂章同源)。 + * + * 五章状态推导(契约 §1 语义表,优先级 alert > doing > done > todo): + * 拉取 pull:root=null → todo「未注册」|请求中 → doing「拉取中…」|失败 → alert「拉取失败」 + * |成功且有差异 → doing「N 件待写回」|成功且无差异 → done「✓ 已同步」 + * 切片 slice:有切片活动 → doing「进行中」|否则 → todo「未开始」 + * 拼版 compose:拉取未成功 → todo「待拉取」|死链 > 0 → alert「N 死链」|否则 → done「✓ 无死链」 + * 校样 proof:root=null → todo「未注册」|请求中 → doing「校样中…」|通过 → done「N/N ✓」 + * |有用例未过 / 请求失败 → alert + * 出厂 ship:root=null → todo「未注册」|拉取未成功 → todo「待拉取」 + * |有件待签 → todo「N 件待签」|全部签出 → done「✓ 已会签」 + * + * 实测偏差与工程选择(逐条与任务书/契约对齐后的判断,供下游与验收窗口核对): + * - HubEvent 的导入路径:契约写「类型从 ../hub/useSseEvents 导入」,但 useSseEvents.ts + * 只是 `import type { HubEvent } from "./sse"`(src/hub/useSseEvents.ts:24),并未 re-export, + * 故此处从真正的定义处 `../hub/sse` 导入(同一类型身份,消费方传 useSseEvents().events 无需改动)。 + * - 切片活动的检测:hub 的 POST /v1/deck/slice 是纯本地文件操作(tts-toolkit + * src/hub/control.ts:1276-1289 → sliceAtlas),不发任何 SSE 帧;SSE 只转发 TTS 入站 + * messageID 1/2/3/4/6/7(src/hub/sse.ts:14-20)。因此契约的「SSE 会话期有 slice 活动」 + * 没有直接信号:本模块实现为 (a) 可选入参 src.sliceActive(消费方可显式上报, + * 追加字段,非契约必需)(b) SSE 文案线索尽力检测(见 hasSliceActivity), + * 两者都无 → todo「未开始」(诚实简化)。 + * - cardCount / assetCount 恒 null:注册表(.registry.yaml)实际带 PackStats + * (tts-toolkit src/pack/registry.ts:103-115)与卡牌数,但按任务书本窗口不接③④面数据源, + * 保持 null(LayerTiles 渲染为「—」);素材行数无任何查询路由,确实不可得。 + * - packVersion:.registry.yaml(PackEntry)与 pack.yaml 都没有 version 字段 + * (src/pack/registry.ts:110-126、src/pack/packyaml.ts:105-135),故恒为 NO_VERSION「—」; + * 此处保留对注册表条目可选 version 字段的前瞻探测,未来加字段即自动生效。 + * - 「写回游戏成功」在 OverviewSource 里没有直接信号:出厂章以「拉取成功且 diff=0 + * (工作区 == 游戏内)」等价于「全部签出」;SSE 的 saved(GameSaved)事件为潜在线索, + * 刻意不用于避免误判(用户手动存档也会发)。 + * - 失败不写结果缓存,但记 30s 节流窗(pullErrorAt / proofErrorAt):pull 会覆盖工作区、 + * testRun 会在真实游戏内跑测试,反复切换 ⓪ 面不应反复触发。 + * - 拉取与校样串行执行:两条路由都经 hub 已绑定的编辑器端口 39998 + * (tts-toolkit src/hub/control.ts:1342-1465 注入 daemon.server),并发交错风险不值当。 + * + * 受控:本模块只读 hub 与入参,不写任何组件状态;root 为 null 时不发任何 hub 请求。 + */ +import { useEffect, useMemo, useState } from "react"; +import { useHub } from "../hub/HubContext"; +import type { HubEvent } from "../hub/sse"; +import type { TreeNode } from "../components/CodeFileTree"; +import type { SignCheck } from "../components/SignBlock"; + +// ───────────────────────────── 契约类型(逐字) ───────────────────────────── + +export type StampId = "pull" | "slice" | "compose" | "proof" | "ship"; +export type StampStatus = "done" | "doing" | "alert" | "todo"; + +export interface StampState { + id: StampId; + name: string; + status: StampStatus; + note: string; +} + +export type LayerId = "overview" | "code" | "agent" | "cards" | "assets"; + +export interface TodoItem { + mark: string; + color: "red" | "blue" | "amber" | "ok"; + text: string; + target: LayerId; +} + +export interface OverviewData { + /** 恒 5 个,顺序 拉取→切片→拼版→校样→出厂 */ + stamps: StampState[]; + todos: TodoItem[]; + /** 与游戏内不同/未提交的文件数(①代码;拉取未知/失败时为 0) */ + diffCount: number; + /** 死链总数(deadUrls.size,③④同源) */ + deadCount: number; + /** 待会签件数(≈ diffCount) */ + pendingSign: number; + /** SSE 事件数(②代理流水) */ + jobCount: number; + /** 卡牌总数(③,未知为 null——见文件头) */ + cardCount: number | null; + /** 素材行数(④,未知为 null——见文件头) */ + assetCount: number | null; + /** 已注册图包名(无则 "(未注册图包)") */ + packName: string; + /** 图包版本(无则 "—") */ + packVersion: string; +} + +export interface OverviewSource { + deadUrls: ReadonlySet; + sseEvents: HubEvent[]; + /** 图包根路径;null 表示无已注册图包(降级模式,不发起 hub 调用)。 */ + root: string | null; + /** + * 可选:切片活动显式上报(追加字段,非契约必需)。 + * hub 的 /v1/deck/slice 不发 SSE(见文件头),消费方(如③卡牌面切片进行中)可置 true + * 让「切片」章进入 doing;缺省走 SSE 文案线索。 + */ + sliceActive?: boolean; +} + +/** 无已注册图包时的图包名(契约「无则」值) */ +export const NO_PACK_NAME = "(未注册图包)"; +/** 无版本来源时的版本占位(契约「无则」值) */ +export const NO_VERSION = "—"; + +// ───────────────────────────── 内部状态与缓存 ───────────────────────────── + +/** 拉取结果:成功带差异条目数;失败(含 pull/diff 任一步失败)无数据 */ +type PullOutcome = { ok: true; diffEntries: number } | { ok: false }; + +/** 校样结果:ok=用例全过;notPassed=未通过数(failed+errored+bailed);notPassed=null 表示请求/解析失败 */ +type ProofOutcome = { ok: true; passed: number; notPassed: number } | { ok: false; notPassed: number | null }; + +/** 契约 §1 的模块级结果缓存(仅内存) */ +export interface StampCacheEntry { + pull?: { diffEntries: number }; + proof?: { passed: number; failed: number }; + /** 追加:上次拉取失败的补充标记(供 30s 节流 + 重挂载后仍显示 alert),非契约字段 */ + pullErrorAt?: number; + /** 追加:上次校样请求失败的补充标记(同上) */ + proofErrorAt?: number; +} + +/** 结果缓存:root → 拉取/校样结果(免重复请求) */ +const cache = new Map(); +/** 迷你文件树缓存:root → diff 条目派生的 TreeNode[](与 ①代码面同源) */ +const treeCache = new Map(); +/** 图包元信息缓存:metaKey(root) → {name, version}(会话级) */ +const packMetaCache = new Map(); + +/** 失败节流窗(ms):窗口内重挂载不重发 hub 请求,直接从缓存的失败标记推导 alert */ +const RETRY_AFTER_MS = 30_000; + +/** 迷你文件树最多渲染行数(⓪总览块高有限;note 仍报总差异数) */ +const MINI_TREE_MAX = 12; + +interface EngineState { + root: string | null; + pull: PullOutcome | null; + proof: ProofOutcome | null; + packName: string; + packVersion: string; +} + +interface PackMeta { + /** 注册表条目 dir(一级子目录名,hub 路由直接接受,与 ①代码面同口径) */ + dir: string; + name: string; + version: string; +} + +// ───────────────────────────── 纯工具 ───────────────────────────── + +/** 路径归一:斜杠统一 + 小写(Windows 比较用;只做展示级匹配,不做真实路径解析) */ +function normalizePath(p: string): string { + return p.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase(); +} + +/** 注册表条目在缓存里的 key */ +function metaKey(rootish: string): string { + return normalizePath(rootish); +} + +/** root 兜底显示名:路径最后一段(注册表查不到时的诚实兜底,避免谎报「未注册」) */ +function packNameFallback(root: string): string { + const parts = root.split(/[\\/]+/).filter((s) => s !== ""); + const last = parts[parts.length - 1]; + return last !== undefined && last !== "" ? last : root; +} + +/** 失败节流判断:窗口内不重发 */ +function isThrottled(root: string, kind: "pull" | "proof"): boolean { + const entry = cache.get(root); + const at = kind === "pull" ? entry?.pullErrorAt : entry?.proofErrorAt; + return at !== undefined && Date.now() - at < RETRY_AFTER_MS; +} + +/** 合并式写缓存(成功清除失败标记:显式 undefined 覆盖) */ +function patchCache(root: string, patch: Partial): void { + cache.set(root, { ...(cache.get(root) ?? {}), ...patch }); +} + +/** 由缓存/空态推导引擎基线(root 变更首帧同步渲染,避免闪上一图包的旧值) */ +function seedState(root: string | null): EngineState { + if (root === null) { + return { + root: null, + pull: null, + proof: null, + packName: NO_PACK_NAME, + packVersion: NO_VERSION, + }; + } + const entry = cache.get(root); + const meta = packMetaCache.get(metaKey(root)); + const pull: PullOutcome | null = + entry?.pull !== undefined + ? { ok: true, diffEntries: entry.pull.diffEntries } + : isThrottled(root, "pull") + ? { ok: false } + : null; + const proof: ProofOutcome | null = + entry?.proof !== undefined + ? { ok: entry.proof.failed === 0, passed: entry.proof.passed, notPassed: entry.proof.failed } + : isThrottled(root, "proof") + ? { ok: false, notPassed: null } + : null; + return { + root, + pull, + proof, + packName: meta?.name ?? packNameFallback(root), + packVersion: meta?.version ?? NO_VERSION, + }; +} + +/** 5 章名称(id → 仿宋大字) */ +const STAMP_NAMES: Record = { + pull: "拉取", + slice: "切片", + compose: "拼版", + proof: "校样", + ship: "出厂", +}; + +/** 工序章顺序:拉取 → 切片 → 拼版 → 校样 → 出厂 */ +const STAMP_ORDER: StampId[] = ["pull", "slice", "compose", "proof", "ship"]; + +/** + * 由四组标量推导五章(纯函数,见文件头语义表)。导出供验收窗口离线核对语义表; + * 组件侧只经 useOverviewData 消费。 + */ +export function deriveStamps(args: { + root: string | null; + pull: PullOutcome | null; + proof: ProofOutcome | null; + deadCount: number; + sliceActive: boolean; + pendingSign: number; +}): StampState[] { + const { root, pull, proof, deadCount, sliceActive, pendingSign } = args; + + // 拉取 + let pullStatus: StampStatus; + let pullNote: string; + if (root === null) { + pullStatus = "todo"; + pullNote = "未注册"; + } else if (pull === null) { + pullStatus = "doing"; + pullNote = "拉取中…"; + } else if (!pull.ok) { + pullStatus = "alert"; + pullNote = "拉取失败"; + } else if (pull.diffEntries > 0) { + pullStatus = "doing"; + pullNote = `${pull.diffEntries} 件待写回`; + } else { + pullStatus = "done"; + pullNote = "✓ 已同步"; + } + const pullDone = pull !== null && pull.ok; + + // 切片(见文件头:无历史查询路由,只认会话内活动) + const sliceStatus: StampStatus = sliceActive ? "doing" : "todo"; + const sliceNote = sliceActive ? "进行中" : "未开始"; + + // 拼版(死链来自全站死链 store,与 ③④ 面同源) + let composeStatus: StampStatus; + let composeNote: string; + if (!pullDone) { + composeStatus = "todo"; + composeNote = "待拉取"; + } else if (deadCount > 0) { + composeStatus = "alert"; + composeNote = `${deadCount} 死链`; + } else { + composeStatus = "done"; + composeNote = "✓ 无死链"; + } + + // 校样 + let proofStatus: StampStatus; + let proofNote: string; + if (root === null) { + proofStatus = "todo"; + proofNote = "未注册"; + } else if (proof === null) { + proofStatus = "doing"; + proofNote = "校样中…"; + } else if (proof.ok) { + proofStatus = "done"; + proofNote = `${proof.passed}/${proof.passed + proof.notPassed} ✓`; + } else if (proof.notPassed !== null && proof.notPassed > 0) { + proofStatus = "alert"; + proofNote = `${proof.notPassed} 未过`; + } else { + proofStatus = "alert"; + proofNote = "校样失败"; + } + + // 出厂(待签件数 ≈ diffCount;「全部签出」= 拉取成功且无差异) + let shipStatus: StampStatus; + let shipNote: string; + if (root === null) { + shipStatus = "todo"; + shipNote = "未注册"; + } else if (!pullDone) { + shipStatus = "todo"; + shipNote = "待拉取"; + } else if (pendingSign > 0) { + shipStatus = "todo"; + shipNote = `${pendingSign} 件待签`; + } else { + shipStatus = "done"; + shipNote = "✓ 已会签"; + } + + const byId: Record = { + pull: { status: pullStatus, note: pullNote }, + slice: { status: sliceStatus, note: sliceNote }, + compose: { status: composeStatus, note: composeNote }, + proof: { status: proofStatus, note: proofNote }, + ship: { status: shipStatus, note: shipNote }, + }; + + return STAMP_ORDER.map((id) => ({ + id, + name: STAMP_NAMES[id], + status: byId[id].status, + note: byId[id].note, + })); +} + +/** + * 待办行(符号 + 色彩纪律:✗ 红=错误/死链 ⇄ 红=与游戏内不同 ✂ 蓝=进行中 ⬆ 琥珀=待会签)。 + * 导出供验收窗口离线核对;组件侧只经 useOverviewData 消费。 + */ +export function deriveTodos(args: { + pull: PullOutcome | null; + deadCount: number; + sliceActive: boolean; + pendingSign: number; +}): TodoItem[] { + const { pull, deadCount, sliceActive, pendingSign } = args; + const todos: TodoItem[] = []; + + if (deadCount > 0) { + todos.push({ + mark: "✗", + color: "red", + text: `${deadCount} 个素材死链待替换`, + target: "assets", + }); + } + if (pull !== null && !pull.ok) { + todos.push({ + mark: "✗", + color: "red", + text: "拉取失败,去 ① 代码重试", + target: "code", + }); + } + const diff = pull !== null && pull.ok ? pull.diffEntries : 0; + if (diff > 0) { + todos.push({ + mark: "⇄", + color: "red", + text: `${diff} 个对象与游戏内不同`, + target: "code", + }); + } + if (sliceActive) { + todos.push({ + mark: "✂", + color: "blue", + text: "切片进行中", + target: "cards", + }); + } + if (pendingSign > 0) { + // 会签动作在右下常驻会签栏(不是某个工作面)→ target 取 ⓪ 总览为最近落点 + todos.push({ + mark: "⬆", + color: "amber", + text: `${pendingSign} 件待会签(右下会签栏)`, + target: "overview", + }); + } + return todos; +} + +// ───────────────────────────── hub 响应解析(容错) ───────────────────────────── + +interface DiffEntryLite { + guid: string; + name: string; + kind: "script" | "ui"; + status: "added" | "modified" | "deleted"; +} + +/** 扩展名 → 对象类别(契约 §5:.lua→script / .xml→ui) */ +function kindFromName(name: string): "script" | "ui" { + return name.toLowerCase().endsWith(".xml") ? "ui" : "script"; +} + +/** POST /v1/diff 响应 → 条目数组(hub 返回 { entries, added, modified, deleted }) */ +function readDiffEntries(res: unknown): DiffEntryLite[] { + const entries = (res as { entries?: unknown }).entries; + if (!Array.isArray(entries)) return []; + const out: DiffEntryLite[] = []; + for (const raw of entries) { + if (typeof raw !== "object" || raw === null) continue; + const guid = (raw as { guid?: unknown }).guid; + const name = (raw as { name?: unknown }).name; + const kind = (raw as { kind?: unknown }).kind; + const status = (raw as { status?: unknown }).status; + if (typeof guid !== "string" || typeof name !== "string") continue; + out.push({ + guid, + name, + // hub 的分类为准;缺失时按契约 §5 的扩展名规则兜底 + kind: kind === "script" || kind === "ui" ? kind : kindFromName(name), + status: + status === "added" || status === "modified" || status === "deleted" + ? status + : "modified", + }); + } + return out; +} + +/** diff 条目 → 迷你文件树节点(①代码面同一份条目形状) */ +function toTreeNodes(entries: DiffEntryLite[]): TreeNode[] { + return entries.map( + (e): TreeNode => ({ + name: e.name, + guid: e.guid, + kind: e.kind, + status: e.status, + }), + ); +} + +/** POST /v1/test/run 响应(RunReport)→ { passed, notPassed };非 RunReport 形状返回 null */ +function readRunReport(res: unknown): { passed: number; notPassed: number } | null { + if (typeof res !== "object" || res === null) return null; + const r = res as { + passed?: unknown; + failed?: unknown; + errored?: unknown; + bailed?: unknown; + }; + if (r.passed === undefined && r.failed === undefined && r.errored === undefined) { + return null; // 缺 results/total 之外的三个计数即认为不是 RunReport + } + const num = (v: unknown): number => + typeof v === "number" && Number.isFinite(v) ? v : 0; + // 未通过数 = 断言失败 + 执行错误 + 提前中止(任一非 0 都不算「校样通过」) + return { + passed: num(r.passed), + notPassed: num(r.failed) + num(r.errored) + num(r.bailed), + }; +} + +/** GET /v1/packs 响应(.registry.yaml)→ 条目数组 */ +function readPackMetas(res: unknown): PackMeta[] { + const packs = (res as { packs?: unknown }).packs; + if (!Array.isArray(packs)) return []; + const out: PackMeta[] = []; + for (const p of packs) { + if (typeof p !== "object" || p === null) continue; + const dir = (p as { dir?: unknown }).dir; + if (typeof dir !== "string" || dir === "") continue; + const name = (p as { name?: unknown }).name; + // 前瞻探测:当前 .registry.yaml 的 PackEntry 无 version 字段(严格 schema), + // 未来若加入即自动生效,否则恒 NO_VERSION + const version = (p as { version?: unknown }).version; + out.push({ + dir, + name: typeof name === "string" && name !== "" ? name : packNameFallback(dir), + version: + typeof version === "string" && version !== "" ? version : NO_VERSION, + }); + } + return out; +} + +/** 注册表条目匹配 root:dir 是一级子目录名,root 可能是其完整路径 */ +function findPackMeta(metas: PackMeta[], root: string): PackMeta | null { + const target = normalizePath(root); + for (const meta of metas) { + const dir = normalizePath(meta.dir); + if (target === dir || (dir !== "" && target.endsWith(`/${dir}`))) return meta; + } + return null; +} + +/** SSE 文案线索(尽力而为,见文件头):切片活动检测 */ +function hasSliceActivity(events: HubEvent[]): boolean { + for (const e of events) { + const msg = e.msg.toLowerCase(); + if (msg.includes("切片") || msg.includes("deck/slice") || msg.includes("slice")) { + return true; + } + } + return false; +} + +// ───────────────────────────── 主 hook ───────────────────────────── + +/** + * ⓪总览数据源。只在 root 非 null 时访问 hub(降级模式零请求);拉取/校样结果按 root + * 走模块级缓存,同会话内 ⓪ 面反复切换不重复请求。 + */ +export function useOverviewData(src: OverviewSource): OverviewData { + const { client } = useHub(); + const { root, deadUrls, sseEvents } = src; + + const [state, setState] = useState(() => seedState(src.root)); + // root 变更首帧:直接以缓存/空态渲染(effect 随后补请求),不闪上一图包的旧值 + const view = state.root === root ? state : seedState(root); + + const deadCount = deadUrls.size; + const jobCount = sseEvents.length; + const sliceActive = src.sliceActive === true || hasSliceActivity(sseEvents); + + useEffect(() => { + let cancelled = false; + + // 幂等基线同步:仅当组件内状态与本轮 root 不一致时重置 + setState((prev) => (prev.root === root ? prev : seedState(root))); + + // 降级模式(无已注册图包):不发任何 hub 请求 + if (root === null) { + return () => { + cancelled = true; + }; + } + const packRoot = root; + + void (async () => { + const apply = (updater: (prev: EngineState) => EngineState): void => { + if (!cancelled) { + setState((prev) => (prev.root === packRoot ? updater(prev) : prev)); + } + }; + + // ① 图包元信息(GET /v1/packs 只读本地注册表;会话级缓存,同 root 只查一次) + if (!packMetaCache.has(metaKey(packRoot))) { + try { + const hit = findPackMeta(readPackMetas(await client.packs()), packRoot); + if (hit !== null) { + packMetaCache.set(metaKey(packRoot), hit); + apply((prev) => ({ + ...prev, + packName: hit.name, + packVersion: hit.version, + })); + } else if (!cancelled) { + // 查不到条目:保留 basename 兜底名与 "—" 版本(不谎报「未注册」) + packMetaCache.set(metaKey(packRoot), { + dir: packRoot, + name: packNameFallback(packRoot), + version: NO_VERSION, + }); + } + } catch { + // 静默降级:保留 basename(packRoot) + "—" + } + } + + // ② 拉取:POST /v1/scripts/pull + POST /v1/diff 合并为一次「拉取」语义 + // (与 ①代码面挂载同序:先拉后 diff,diff 反映拉取后的工作区状态) + if (cache.get(packRoot)?.pull === undefined && !isThrottled(packRoot, "pull")) { + try { + await client.pullScripts(packRoot); + const entries = readDiffEntries(await client.diff(packRoot)); + // 先写缓存再 setState:同一帧内 deriveMiniTree 已能取到新节点 + patchCache(packRoot, { + pull: { diffEntries: entries.length }, + pullErrorAt: undefined, + }); + treeCache.set(packRoot, toTreeNodes(entries)); + apply((prev) => ({ + ...prev, + pull: { ok: true, diffEntries: entries.length }, + })); + } catch { + // 静默降级:拉取章 alert,失败标记进节流窗(30s 内重挂载不重发) + patchCache(packRoot, { pullErrorAt: Date.now() }); + apply((prev) => ({ ...prev, pull: { ok: false } })); + } + } + + // ③ 校样:POST /v1/test/run(在真实游戏内跑 tests/**);跑完即缓存(断言失败也算跑完) + if ( + cache.get(packRoot)?.proof === undefined && + !isThrottled(packRoot, "proof") + ) { + try { + const report = readRunReport(await client.testRun({ root: packRoot })); + if (report === null) { + patchCache(packRoot, { proofErrorAt: Date.now() }); + apply((prev) => ({ ...prev, proof: { ok: false, notPassed: null } })); + } else { + patchCache(packRoot, { + proof: { passed: report.passed, failed: report.notPassed }, + proofErrorAt: undefined, + }); + apply((prev) => ({ + ...prev, + proof: { + ok: report.notPassed === 0, + passed: report.passed, + notPassed: report.notPassed, + }, + })); + } + } catch { + patchCache(packRoot, { proofErrorAt: Date.now() }); + apply((prev) => ({ ...prev, proof: { ok: false, notPassed: null } })); + } + } + })(); + + return () => { + cancelled = true; + }; + }, [client, root]); + + const pull = view.pull; + const proof = view.proof; + + const diffCount = pull !== null && pull.ok ? pull.diffEntries : 0; + const pendingSign = diffCount; + + const stamps = useMemo( + () => + deriveStamps({ + root, + pull, + proof, + deadCount, + sliceActive, + pendingSign, + }), + [root, pull, proof, deadCount, sliceActive, pendingSign], + ); + + const todos = useMemo( + () => deriveTodos({ pull, deadCount, sliceActive, pendingSign }), + [pull, deadCount, sliceActive, pendingSign], + ); + + return useMemo( + () => ({ + stamps, + todos, + diffCount, + deadCount, + pendingSign, + jobCount, + // 见文件头:本窗口不接 ③④ 面数据源(LayerTiles 渲染为 "—") + cardCount: null, + assetCount: null, + packName: view.packName, + packVersion: view.packVersion, + }), + [ + stamps, + todos, + diffCount, + deadCount, + pendingSign, + jobCount, + view.packName, + view.packVersion, + ], + ); +} + +// ───────────────────────────── 派生数据源(迷你文件树 / 会签栏) ───────────────────────────── + +export interface MiniTreeData { + nodes: TreeNode[]; + /** 块右上角小注(契约 §5:「差异 N」/ 空态「未注册图包」) */ + note: string; +} + +/** + * ⓪总览「工作区」迷你文件树数据源:读 useOverviewData 同一份缓存(同源), + * 在渲染期调用即可(拉取成功后本模块已先写 treeCache 再 setState,同一帧能取到新节点)。 + * 最多 MINI_TREE_MAX 行,note 报总差异数。 + */ +export function deriveMiniTree(root: string | null): MiniTreeData { + if (root === null) { + return { nodes: [], note: "未注册图包" }; + } + const nodes = treeCache.get(root); + if (nodes === undefined) { + return { nodes: [], note: "差异 —" }; + } + return { nodes: nodes.slice(0, MINI_TREE_MAX), note: `差异 ${nodes.length}` }; +} + +export interface SignBlockData { + version: string; + checks: SignCheck[]; +} + +/** + * §4.4 会签栏交付清单数据源(锁定决策 2:出厂行与出厂章同源)。 + * 行序 版本 → 校样 → 打样 → 出厂;`next` 落在第一行 bad 上(当前下一步)。 + * + * 注意:SignCheck.tone 只有 ok | bad(SignBlock 现有类型),故非 done 行一律 bad + * (与 App.tsx 既有占位「待/未 → bad」一致);若后续把 tone 扩到 amber(待签=待人审, + * §2.5 更准确),此处可相应细化。打样(POST /v1/pack/build)产物不在 OverviewSource 内 + * 且无查询路由,恒「未打样」。 + */ +export function deriveSignBlock(data: OverviewData): SignBlockData { + const note = (id: StampId): string => + data.stamps.find((s) => s.id === id)?.note ?? NO_VERSION; + const status = (id: StampId): StampStatus => + data.stamps.find((s) => s.id === id)?.status ?? "todo"; + const toneOf = (id: StampId): "ok" | "bad" => + status(id) === "done" ? "ok" : "bad"; + + const checks: SignCheck[] = [ + { + k: "版本", + v: data.packVersion === NO_VERSION ? "未标注" : data.packVersion, + tone: data.packVersion === NO_VERSION ? "bad" : "ok", + }, + { k: "校样", v: note("proof"), tone: toneOf("proof") }, + { k: "打样", v: "未打样", tone: "bad" }, + { k: "出厂", v: note("ship"), tone: toneOf("ship") }, + ]; + + const nextIdx = checks.findIndex((c) => c.tone === "bad"); + const nextRow = checks[nextIdx]; + if (nextRow !== undefined) checks[nextIdx] = { ...nextRow, next: true }; + + return { version: data.packVersion, checks }; +} + +/** 图包根信息(供 Stage B 解一次注册表,同时喂 useOverviewData 与 MiniFileTree 的 root) */ +export interface PackRootInfo { + /** 已注册图包根(注册表条目 dir,hub 路由直接接受;无图包为 null) */ + root: string | null; + packName: string; + packVersion: string; +} + +/** + * 解析已注册图包根(GET /v1/packs 取第一个条目,与 ①代码面「第一个注册图包」口径一致)。 + * root 为 null 时不写任何数据;consumers 可把 root 转交 useOverviewData / deriveMiniTree。 + */ +export function usePackRoot(): PackRootInfo { + const { client } = useHub(); + const [info, setInfo] = useState(() => ({ + root: null, + packName: NO_PACK_NAME, + packVersion: NO_VERSION, + })); + + useEffect(() => { + let cancelled = false; + void (async () => { + try { + const metas = readPackMetas(await client.packs()); + if (cancelled) return; + for (const meta of metas) packMetaCache.set(metaKey(meta.dir), meta); + const first = metas[0]; + setInfo( + first === undefined + ? { root: null, packName: NO_PACK_NAME, packVersion: NO_VERSION } + : { + root: first.dir, + packName: first.name, + packVersion: first.version, + }, + ); + } catch { + if (!cancelled) { + setInfo({ root: null, packName: NO_PACK_NAME, packVersion: NO_VERSION }); + } + } + })(); + return () => { + cancelled = true; + }; + }, [client]); + + return info; +} + +// ───────────────────────────── 缓存维护(供 Stage B / 验收窗口) ───────────────────────────── + +/** 读缓存(只读视图;调试 / 二次派生用) */ +export function readStampCache(root: string): StampCacheEntry | undefined { + return cache.get(root); +} + +/** + * 清空全部结果缓存(拉取 / 校样 / 迷你文件树 / 图包元信息)。 + * 用途:写回游戏成功(push)后主动失效,让 ⓪ 面重算五章与差异计数。 + * 注意:清空后下次进入 ⓪ 会重新 pull(会覆盖工作区)+ 重跑测试,请在明确时机调用。 + */ +export function clearStampCache(): void { + cache.clear(); + treeCache.clear(); + packMetaCache.clear(); +}