Repository navigation
refactor: land 27 code-review solutions (P0/P1/P2) - #24
Merged
Merged
Conversation
Add docs/code-review-report.md (27-point architecture audit) and docs/solutions/01-27 (per-point solutions with source-verified corrections to the report's erroneous premises).
- eslint blockers: empty catch blocks and control-char regex (7.1) - undo snapshot: strip font Base64, rehydrate via session binary map (5.3) - print geometry: unify three duplicated calc sites into printGeometry.ts (3.2) - usePreview: decouple from full pages array, stabilize observer effect (5.2) - zod validation: validate imported project files at db and store boundaries (6.3) - template single source: remove 36 orphan TS schemas, drop dead preload (3.1) - baseline closure: commit uncommitted baseline on page index/pages set (4.1) - keystroke rerender: memo TopNav/Sidebar/PreviewArea/EditorPanel, stabilize callbacks (5.1)
…pes/db split
- P1-A: remove dead code (fontCalculator/Manager, ImageEditPreview, useImagePreload, imagePreloader + tests); rewrite 8 doc references as Knuth-Plass pipeline
- P1-R: dimensionCache in useAssetUrl uses LRUCache(100) instead of unbounded Map
- P1-Q: collapse 7 shallow text-field wrappers into FieldRenderer textFieldPresets + default rule; schema-layer props now override presets
- P1-B: split monolith src/types.ts into src/types/{core,tokens,print,page,project,index}.ts; 156 import sites unchanged via barrel
- P1-C: split monolith src/utils/db.ts into storage/{projectDb,assetHasher,assetStore}, media/canvasCompressor, archive/zipArchive, dom/fileDownload; __SLIDEGRID_DB__ fixture moved to projectDb; update 8 production + 6 test import paths; add split unit tests
test:unit:run 726 green, tsc clean, lint 0 errors
…custom event callback, error boundary, zine atom merge, dual subscription unify, any cleanup 落地 P1 第二批方案 (solutions 02/05/08/10/12/13/14/17/18/21/22/23/24/27): - P1-K (#13) GlobalSettings 直连 Zustand store 订阅 11 状态 + 6 action, 删除 GlobalSettingsProps 接口与 EditorPage 18 行 props 透传 - P1-L (#14) 删除 show-export-modal/trigger-import 两个死 CustomEvent 通道, open-layout-browser 改 callback prop (Editor -> EditorPanel -> EditorPage) - P1-S (#24) 新增 EditorErrorBoundary, 仅降级 400px 编辑面板, 保留 PreviewArea/Sidebar/TopNav/store, key={currentPage.id} 切页复位 - P1-N (#8) ZineTextAtom 三合一, ZineBody/Caption/Display 退化为声明式薄包装 - P1-O (#12) useModularStyle 接收 designSystem/theme 参数移除 useStore 直连, 11 个 Zine 原子改 props 接收消除双轨订阅 - P1-H (#22) PageData extends Record<string, unknown> 索引签名 + getPageField<T> helper 收敛 (page as any)[key] 逃逸, GlobalField 字面量联合保留拼写校验 - P1-I (#21) any 治理: RecentProjectEntry 强类型, useStore/registry/types AST 节点收窄, expressionEvaluator EvaluationResult 联合 - P1-D (#10) templateDefaults applyTemplateDefaults(target, tpl, mode) fill/override 双语义 - P1-F (#18) reorderPages(newPages, isCommit) 二态化, 模块级 reorderBaseline 防拖拽历史污染 - 顺带修复 EditorPage offscreen 15s 定时器泄漏 (offscreenResolveRef 绑定 timer, resolve/finally/unmount 三处 clearTimeout) Test gate: 735 unit tests green, tsc clean, lint 0 errors (469 warnings), 26 e2e tests green.
按方案 02 拆分 useStore.ts (660 行单文件) 为组合根 + 3 slice + 1 IO 管道: - useStore.ts 降至 22 行组合根,聚合三个 StateCreator, 保留 isEqualSnapshot/HistorySnapshot 命名导出与 __SLIDEGRID_STORE__ window 挂载 - slices/historySlice.ts: buildSnapshot/isEqualSnapshot/pushHistory/undo/redo + uncommittedBaseline/reorderBaseline/fontBinaryMap 模块作用域单例, 快照字体剥离元数据,导出 commit/capture/take/discard 基准操作函数 - slices/projectSlice.ts: pages/projectTitle/currentPageIndex/isLoaded/ activeProjectId/currentFilePath/hasUnsavedChanges + 13 个 action, loadProject 委托 projectLoader,updatePage GLOBAL_FIELDS 同步逻辑保留 - slices/styleSlice.ts: theme/designSystem/customFonts/imageQuality/ minimalCounter/counterStyle/printSettings + 7 个 setter, setCustomFonts 只写 state 并登记字体二进制缓存,DOM 注册移出 - projectLoader.ts: loadProjectPipeline 纯 IO 管道 (读取 -> 迁移 -> 校验 -> IPC 同步 -> 字体二进制登记) 副作用移出 store: - 字体 DOM 注册改由 useProject 的 useEffect 订阅 customFonts 承担 - EditorPage document.title effect 删除 nativeFs.setCurrentProject 重复调用, IPC 同步由 loadProject 单点负责 否决项 (遵从方案 02): - 不引入 immer middleware (项目零 middleware,引入属投机抽象) - 不拆 printSlice (单字段单 setter 过度拆分,归入 styleSlice) - 不引入 undoMiddleware.ts (零 middleware,搬迁双倍工作量) - 不加 NODE_ENV/__PLAYWRIGHT_TEST__ 环境守卫 (会剥掉 6 套 e2e 入口) Test gate: 735 unit tests green, tsc clean, lint 0 errors (469 warnings), 26 e2e tests green (含 08 持久化 / 09 undo-redo / 02 editor-workflow).
按方案 01 拆分 EditorPage.tsx (473 行上帝组件) 为薄容器 + 4 Hook + 2 服务 + 2 模态框: - EditorPage.tsx 降至 180 行布局装配,仅保留路由解析 + useProject + usePreview + 4 新 hook 调用 + 文档标题/新工程占位 effect + 布局 JSX - hooks/useProjectPersistence.ts: 自动保存防抖 + handleSmartSave/ handleSaveAs/handleNativeOpen,接收 useProject 返回值不内部调避免双重订阅; 附带 useCustomFontsDom 副作用 hook (customFonts -> document.fonts) - hooks/useOffscreenExport.ts: 离屏渲染协调 + 15s 定时器泄漏修复 (resolve/reject/unmount 三路径 clearTimeout,跨页导出清理上一个等待) - hooks/useExportPipeline.ts: 导出 state + 调用 runExportPipeline, 内部组合 useOffscreenExport,卸载时取消进行中导出 - hooks/useEditorShortcuts.ts: Ctrl+S/Ctrl+Shift+S/Ctrl+Z/Y 键盘绑定, 依赖项收敛为稳定 callback - hooks/useLayoutCreationWizard.ts: 3 步状态机 (orientation/ratio/template) + openForCreate/openForChange/finalize,finalize 内调 applyTemplateDefaults - services/exportGeometry.ts: getExportDimensions 纯函数 (printSettings -> 像素尺寸) - services/exportPipeline.ts: runExportPipeline 纯函数编排 PDF/PNG/ZIP 四分支, DOM 链接爬取封装为 attachResumeLinks,renderOffscreen 由 Hook 注入 - components/editor/modals/LayoutBrowserModal.tsx: 3 步模板创建弹窗 UI (含 OrientationCard) - components/editor/modals/ExportModal.tsx: 导出格式选择弹窗 不保留向后兼容 (遵从方案 01): - 删除 handleOpenExportModal/handleOpenAddPageModal 内联包装 (改用 set 直连) - OrientationCard 移入 LayoutBrowserModal - exportCancelledRef/offscreenTarget/offscreenResolveRef 移入对应 hook 不为 handleSaveAs 生成新 id (方案 01 事实核对:报告所称 IndexedDB 覆写冲突不成立, Web 分支只下载 JSON、Electron 分支只写文件,均不触碰 IndexedDB) Test gate: 735 unit tests green, tsc clean, lint 0 errors (462 warnings), 26 e2e tests green.
P2-C 注释合规治理 (方案 26): - AGENTS.md 补判定边界: 英文译名非技术事实,与技术坐标/参数/字体名区别处理, 文件头双语标题属文档可读性例外 - AGENTS.md 示例段补 A/B/C 三类正确写法 (A 删英文译名, B 拆两行, C 中文意图+英文技术规格) - 改写 7 处违规: ZineStylePanel/theme.ts/basePropsResolver/types.ts/ imageGeometry/v2-to-v3,全部按 A/B/C 策略分两行或删译名 - 新增 scripts/fix-comment-mixed.mjs: 一次性窄匹配脚本, 仅处理 A 类 (序号+中文+(英文译名)), 保留 B/C 类人工处理 - 新增 scripts/check-comment-mixed.mjs: CI 守护脚本, 匹配中文注释内的英文括号片段,排除 (Rows|Cols) 技术坐标与 __tests__ P2-D CI 门禁硬化 (方案 8.3): - package.json 加 typecheck (tsc --noEmit) 与 lint:comments 脚本 - ci.yml 在 test:ci 前加三步: Lint (0 error) + Typecheck + Comment style guard, 与注释守卫同 PR 一次性启用,避免 CI 首次启用即红的中间态 Test gate: 735 unit tests green, tsc clean, lint 0 errors (462 warnings), lint:comments 0 violations, 26 e2e tests green.
Converge any escapes in the core data flow, template renderer, expression evaluator, and field components to precise types or unknown with guards. - expressionEvaluator: EvaluationResult union for parser methods, EvaluationContext index signature narrowed to unknown, parseMember guarded with type-narrowed member access, catch clauses use unknown - types/page: styleOverrides/mosaic/gallery narrowed from Record<string, any> to Record<string, unknown> containers - v2-to-v3 migration: migrateFields/ensureTheme/ensureCollectionIds use unknown with narrowed source access - logger: any args swapped for unknown, global attach typed via Window intersection - zineStyleUtils: typed NodeWithProps interface replaces recursive any - useModularStyle/useDataConnector: Record<string, unknown> containers with CSSProperties-typed casts at assignment sites - comparison: shallowEqual/deepEqual take unknown and narrow internally - renderer layer (basePropsResolver/componentRenderer/containerRenderer/ repepeaterRenderer): typed layout props replace as-any casts - field components: styleOverrides reads narrowed with Number()/as casts - componentRegistry/FieldRenderer: heterogeneous component maps keep React.ComponentType<any> with scoped eslint-disable (props shapes vary across atoms; Record<string, unknown> breaks assignment) - ProjectData gains index signature to satisfy tightened loadProject param - eslint.config.js: escalate no-explicit-any to error for cleaned production paths; test files retain warn for fixture flexibility - .gitignore: add .agents/ Gates: tsc 0 errors, lint 0 errors (332 warnings), lint:comments pass, 735 unit + 26 e2e green.
CI 自 7b83b47 引入 Electron e2e 起连续失败,根因是 workflow 缺少 build 步骤:electron.launch 找不到 dist-electron/main.js,报 'Cannot find module ... Please verify that the package.json has a valid "main" entry'。这不是 P2 重构的回归,而是 e2e 入库时 test:ci 改为 'vitest --coverage --run && playwright test' 后 CI 一直未补 build 步骤所致的既有基础设施漏洞。 - 在 lint/typecheck 之后、test:ci 之前加 'pnpm build',产出 dist/ 与 dist-electron/{main,preload}.js - 用 xvfb-run 包裹 pnpm test:ci,为 Electron 在无头 ubuntu 提供 虚拟 X server(原本 --no-sandbox/--disable-gpu 已在 fixtures)
首次修复(xvfb-run 包裹)后,e2e 仍报 'ERROR:ui/ozone/platform/x11/ozone_platform_x11.cc:249] Missing X server or $DISPLAY' + SIGSEGV。xvfb-run 经 pnpm -> vitest -> playwright -> electron 多层 spawn,在 ubuntu runner 上它设置的 DISPLAY 未能传到 electron 子进程。 改用更底层的方式:直接启动 Xvfb :99 作为后台进程,显式 export DISPLAY=:99,使环境变量被所有子进程继承。
E2E 08-project-persistence 在 page.reload() 后,EditorPage 的 loadProject effect 是异步的:React 首次渲染时 store 仍为空 (pages=[], currentPage=undefined),而 EditorPanel 直接读 currentPage.id 作为 EditorErrorBoundary 的 key,抛出 'Cannot read properties of undefined (reading 'id')'。该错误 冒泡越过局部 Boundary(它还未挂载,key 计算就先崩了)抵达 顶层 ErrorBoundary,渲染全屏 'Something went wrong',随后 loadProject 虽完成恢复但 UI 已被错误态占满,断言失败。 - EditorPanelProps.currentPage 改为可选 - key 改用 currentPage?.id - Editor 仅在 currentPage 存在时挂载 reload 场景:首帧空挂载 -> effect 跑完 loadProject -> pages 回填 -> 重新渲染 Editor,恢复正常。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Lands all 27 refactoring solutions from docs/solutions/01-.md through 27-.md into actual code, staged across three phases with test gates between each.
Phases:
Skipped: #19 event listener lifecycle, superseded by #14 (CustomEvent bus removal eliminates the listener effect entirely).
Test gates all green: unit 735/735, tsc 0 errors, lint 0 errors (332 warnings), lint:comments pass, e2e 26/26.