From 834470cfa1b3bec05a258e415edd88b4fc404879 Mon Sep 17 00:00:00 2001 From: que01 Date: Wed, 2 Sep 2026 15:04:58 +0800 Subject: [PATCH] refactor(workbench): split editor state and components --- .../spec/frontend/component-guidelines.md | 6 +- .trellis/spec/frontend/direct-edit-client.md | 18 +- .trellis/spec/frontend/directory-structure.md | 12 +- .trellis/spec/frontend/hook-guidelines.md | 6 + .trellis/spec/frontend/index.md | 12 +- .trellis/spec/frontend/quality-guidelines.md | 5 + .trellis/spec/frontend/state-management.md | 11 +- .trellis/spec/frontend/type-safety.md | 2 + .../task.json | 3 +- .../check.jsonl | 2 + .../design.md | 74 ++ .../implement.jsonl | 1 + .../implement.md | 29 + .../prd.md | 49 + .../task.json | 26 + workbench/client/src/App.tsx | 919 ++---------------- .../client/src/components/ElementEditors.tsx | 297 ++++++ .../client/src/components/ImportScreen.tsx | 45 + workbench/client/src/components/Overview.tsx | 36 + .../src/components/WorkbenchInspector.tsx | 273 ++++++ .../client/src/hooks/useDirectEditSession.ts | 59 ++ .../client/src/hooks/useOverrideDraft.ts | 37 + .../client/src/hooks/useTrafficSignalDraft.ts | 175 ++++ 23 files changed, 1219 insertions(+), 878 deletions(-) create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/check.jsonl create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/design.md create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/implement.jsonl create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/implement.md create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/prd.md create mode 100644 .trellis/tasks/09-02-workbench-component-boundaries/task.json create mode 100644 workbench/client/src/components/ElementEditors.tsx create mode 100644 workbench/client/src/components/ImportScreen.tsx create mode 100644 workbench/client/src/components/Overview.tsx create mode 100644 workbench/client/src/components/WorkbenchInspector.tsx create mode 100644 workbench/client/src/hooks/useDirectEditSession.ts create mode 100644 workbench/client/src/hooks/useOverrideDraft.ts create mode 100644 workbench/client/src/hooks/useTrafficSignalDraft.ts diff --git a/.trellis/spec/frontend/component-guidelines.md b/.trellis/spec/frontend/component-guidelines.md index 5c50e2f..845ff14 100644 --- a/.trellis/spec/frontend/component-guidelines.md +++ b/.trellis/spec/frontend/component-guidelines.md @@ -2,4 +2,8 @@ Use typed React function components. `App.tsx` owns session/editor composition, while reusable map and UI concerns live in named components. Prefer the shared `ui/button.tsx` primitive for commands. Do not create business UI with `querySelector` or `innerHTML`. -Forms use controlled inputs and submit handlers. Keep map canvas DOM owned by OpenLayers and surrounding controls owned by React. +Components expose explicit props for values and callbacks. A form component may own presentation-local state such as a select value, but it must not import `api`, mutate `WorkbenchState` directly, or implement save/preview/undo behavior. The composition root passes commands such as `stage`, `updateSignal`, or `onAccept`. + +The inspector is composed from independent sections. Section components must preserve existing write semantics: ordinary v1 forms stage overrides, `lane-maneuver` uses the v2 session, and signal forms update the signal draft command. Do not make a generic form abstraction that hides these boundaries. + +Forms use controlled inputs and submit handlers. Keep map canvas DOM owned by OpenLayers and surrounding controls owned by React. Extracting a component must preserve labels, default values, event ordering, and the current accordion behavior unless a separate product task approves a change. diff --git a/.trellis/spec/frontend/direct-edit-client.md b/.trellis/spec/frontend/direct-edit-client.md index 83d6cfe..1d911e4 100644 --- a/.trellis/spec/frontend/direct-edit-client.md +++ b/.trellis/spec/frontend/direct-edit-client.md @@ -140,18 +140,16 @@ match `main` exactly. Guard once at construction, not per call site. while `compileGeometry()` ignores `profile.interval`. A control whose drag changes nothing is worse than no control. -### V1 override selection is not direct edit +### Lane maneuver is v2 direct edit only -`lane-maneuver` is a saved v1 override for a discrete lane attribute, not a spatial -constraint. Its click selection and inspector selector are intentionally available -without `directEdit`: they stage `{ kind: 'lane-maneuver', laneId, maneuver }` and -wait for the existing save/recompile path. Do not route them through `EditSession`, -the preview endpoint, or a draggable element outline. +`lane-maneuver` is a spatial direct-edit constraint. Its selector and draggable +outline are available only in edit mode and must be routed through `EditSession` and +the preview endpoint. It must never be added to the ordinary v1 staged override +array, which is reserved for road, connector, and marking style overrides. -The distinction is observable: the ordinary workbench may select a turn-arrow part -or lane centerline and show this selector, while the `directEdit` flag still means -there are no edit sources, manifest requests, handles, ghosts, previews, or control -marking outlines. +With edit mode off, selecting a turn-arrow part may still show read-only element +information, but it must not create a manifest request, ghost, preview, handle, or +staged lane-maneuver override. --- diff --git a/.trellis/spec/frontend/directory-structure.md b/.trellis/spec/frontend/directory-structure.md index b28e060..4e448c6 100644 --- a/.trellis/spec/frontend/directory-structure.md +++ b/.trellis/spec/frontend/directory-structure.md @@ -1,5 +1,13 @@ # Directory Structure -The Vite workbench lives in `workbench/client/`. Application code is under `src/`: `components/` for UI, `map/` for OpenLayers adapters, `lib/` for API clients, `types/` for API contracts, and `ui/` for shared primitives. The Node HTTP server remains `workbench/server.js`. +The Vite workbench lives in `workbench/client/`. Application code is under `src/`: -Keep OpenLayers construction and source mutation outside page components; `src/components/MapCanvas.tsx` owns lifecycle and `src/map/layers.ts` owns the layer registry. +- `components/` contains typed React view components and form sections. Components receive domain data and commands through props; they do not own cross-page persistence. +- `hooks/` contains one stateful editing domain per hook (`useOverrideDraft`, `useDirectEditSession`, or `useTrafficSignalDraft`). Hooks may call the API boundary through injected commands, but must not share mutable module state. +- `edit/` contains pure direct-edit models, projections, sessions, preview arbitration and geometry-unit helpers. +- `map/` contains OpenLayers adapters. `MapCanvas.tsx` owns map lifecycle and `map/layers.ts` owns the layer registry and source updates. +- `lib/` is the browser HTTP boundary; `types/` owns API and workbench contracts; `ui/` contains shared primitives. + +`App.tsx` is the composition root: it loads server state, owns selection and page-level commands, and connects editing domains to the map and inspector. It must not contain substantial form implementations or a second copy of an editing protocol. + +Keep OpenLayers construction and source mutation outside page components. The map is constructed once per mounted canvas; React re-renders and inspector extraction must not rebuild it or reset its view. diff --git a/.trellis/spec/frontend/hook-guidelines.md b/.trellis/spec/frontend/hook-guidelines.md index 082307a..9d1863e 100644 --- a/.trellis/spec/frontend/hook-guidelines.md +++ b/.trellis/spec/frontend/hook-guidelines.md @@ -1,3 +1,9 @@ # Hook Guidelines Use effects for imperative OpenLayers lifecycle only. `MapCanvas.tsx` constructs one map on mount, updates sources when server state changes, and updates visibility separately. Store callback-sensitive values such as selected road and scene mode in refs so stable OpenLayers style callbacks see current values. + +Each custom hook owns one domain and exposes a typed command surface. The three existing edit domains are distinct: ordinary v1 staged overrides, v2 direct-edit session/preview, and traffic-signal drafts. A hook must not create a second undo stack or preview path for another domain. + +Keep `EditSession`, `PreviewRequester`, signal history, and gesture refs stable across renders. Effects may synchronize external state, but a hook must not recreate a session or requester from ordinary state changes. Callback dependencies that are consumed by a stable OpenLayers listener belong in refs. + +Hooks should return data and callbacks; they should not render JSX. API errors are converted to the existing status/reporting command at the composition boundary unless the hook owns a self-contained async view. diff --git a/.trellis/spec/frontend/index.md b/.trellis/spec/frontend/index.md index 5753c4f..6938611 100644 --- a/.trellis/spec/frontend/index.md +++ b/.trellis/spec/frontend/index.md @@ -15,12 +15,12 @@ This directory contains guidelines for frontend development. Fill in each file w | Guide | Description | Status | |-------|-------------|--------| | [Direct Edit Client](./direct-edit-client.md) | Handle/ghost/preview layer ownership, drag projection, session and save contracts | Filled | -| [Directory Structure](./directory-structure.md) | Module organization and file layout | To fill | -| [Component Guidelines](./component-guidelines.md) | Component patterns, props, composition | To fill | -| [Hook Guidelines](./hook-guidelines.md) | Custom hooks, data fetching patterns | To fill | -| [State Management](./state-management.md) | Local state, global state, server state | To fill | -| [Quality Guidelines](./quality-guidelines.md) | Code standards, forbidden patterns | To fill | -| [Type Safety](./type-safety.md) | Type patterns, validation | To fill | +| [Directory Structure](./directory-structure.md) | Module organization and file layout | Filled | +| [Component Guidelines](./component-guidelines.md) | Component patterns, props, composition | Filled | +| [Hook Guidelines](./hook-guidelines.md) | Custom hooks, data fetching patterns | Filled | +| [State Management](./state-management.md) | Local state, global state, server state | Filled | +| [Quality Guidelines](./quality-guidelines.md) | Code standards, forbidden patterns | Filled | +| [Type Safety](./type-safety.md) | Type patterns, validation | Filled | --- diff --git a/.trellis/spec/frontend/quality-guidelines.md b/.trellis/spec/frontend/quality-guidelines.md index 2003aa4..a9498de 100644 --- a/.trellis/spec/frontend/quality-guidelines.md +++ b/.trellis/spec/frontend/quality-guidelines.md @@ -14,6 +14,8 @@ The workbench frontend uses Prettier as the source formatting authority. Code is - Do not commit dense, manually minified, or single-line JSX/TypeScript. - Do not hand-format around Prettier output. +- Do not leave a page component responsible for unrelated form implementations, API calls, and multiple edit histories after a named component or hook boundary exists. +- Do not duplicate an edit protocol while extracting it. Move ownership and update call sites in one change so there is only one active path. --- @@ -22,6 +24,8 @@ The workbench frontend uses Prettier as the source formatting authority. Code is - Run `npm run format` after editing frontend files. - Run `npm run format:check` in the validation gate. - Keep React components, hooks, types, and API clients in separately formatted modules once a component becomes non-trivial. +- Keep `App.tsx` as a composition root. New domain behavior belongs in a hook or named component with typed props. +- Refactors must preserve API call order, DOM-visible labels/defaults, and OpenLayers map identity unless the task explicitly changes them. --- @@ -35,3 +39,4 @@ The workbench frontend uses Prettier as the source formatting authority. Code is - Formatting check passes. - UI behavior changes do not rebuild the OpenLayers map unless the map lifecycle explicitly requires it. +- Verify ordinary v1 staged, v2 direct-edit, and traffic-signal draft flows independently; passing one flow does not prove the others survived extraction. diff --git a/.trellis/spec/frontend/state-management.md b/.trellis/spec/frontend/state-management.md index 2383e76..f3e68c8 100644 --- a/.trellis/spec/frontend/state-management.md +++ b/.trellis/spec/frontend/state-management.md @@ -1,3 +1,12 @@ # State Management -Use component `useState` for server state, selection, staged overrides, layer visibility and UI filters. `src/lib/api.ts` is the sole browser HTTP boundary. Keep staged overrides separate from persisted `WorkbenchState.overrides`; save them before compile. +Use component `useState` for server state, selection, layer visibility and UI filters. Domain hooks own their draft state: ordinary v1 staged overrides remain separate from persisted `WorkbenchState.overrides`; v2 constraints remain inside `EditSession`; signal drafts remain separate until the signal save step. + +`src/lib/api.ts` is the sole browser HTTP boundary. Presentational components never call it directly. `App` coordinates the fixed save order: ordinary v1 overrides, v2 document, signal draft, then compile and replace server state. + +Whenever App accepts a fresh server `WorkbenchState` (initial load, import, compile, +signal generation, or an accepted junction candidate), it must also refresh the +signal draft's saved baseline. Otherwise discard can restore an older signal geometry +after a later rotation or move. + +Do not duplicate the whole `WorkbenchState` in multiple hooks. Hooks may use `setState` to update their owned slice and refs for non-serializable history, but there must be one current server state and one owner for each undo/redo stack. `lane-maneuver` belongs exclusively to v2 direct edit; it must not re-enter the v1 staged array. diff --git a/.trellis/spec/frontend/type-safety.md b/.trellis/spec/frontend/type-safety.md index f299754..886d1ae 100644 --- a/.trellis/spec/frontend/type-safety.md +++ b/.trellis/spec/frontend/type-safety.md @@ -1,3 +1,5 @@ # Type Safety Define browser contracts in `src/types/state.ts` from actual workbench API payloads. Use `unknown` for extensible GeoJSON properties and comparison payloads, then narrow locally. Run `npm run test:client` after TypeScript changes; avoid `any` and broad assertions. + +Component and hook boundaries must define named prop/return types for commands and domain data. Do not pass an untyped bag of callbacks or expose mutable refs as public props. Keep API payload narrowing in `lib/` or the owning domain adapter, not in each presentational component. diff --git a/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json b/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json index 02470ef..8581975 100644 --- a/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json +++ b/.trellis/tasks/08-26-direct-manipulation-road-editor/task.json @@ -29,7 +29,8 @@ "08-28-crosswalk-element-editor", "08-31-parameter-panel-binding", "08-31-constraint-range-validation", - "08-31-lane-maneuver-override" + "08-31-lane-maneuver-override", + "09-02-workbench-component-boundaries" ], "parent": null, "relatedFiles": [ diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/check.jsonl b/.trellis/tasks/09-02-workbench-component-boundaries/check.jsonl new file mode 100644 index 0000000..7ca7d4b --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/check.jsonl @@ -0,0 +1,2 @@ +{"file":".trellis/spec/frontend/direct-edit-client.md","reason":"The direct-edit contract defines lane-maneuver ownership and preview/session invariants used by this refactor."} +{"file":".trellis/spec/frontend/state-management.md","reason":"The state ownership and fixed save order govern the extracted hooks and App composition."} diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/design.md b/.trellis/tasks/09-02-workbench-component-boundaries/design.md new file mode 100644 index 0000000..9ca5510 --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/design.md @@ -0,0 +1,74 @@ +# 工作台组件边界重构设计 + +## 原则 + +这是一项严格的行为保持重构。API 调用顺序、保存语义、地图层、状态展示、文案和 DOM +结构在可观察层面保持不变;新模块只重新分配已有代码的所有权。 + +## 目标边界 + +```text +App + ├─ 应用装载、页面布局、顶层命令 + ├─ useDirectEditSession + │ └─ v2 EditSession / manifest / preview lifecycle + ├─ useTrafficSignalDraft + │ └─ signal local draft / undo-redo / move-rotate / save-discard + ├─ WorkbenchInspector + │ ├─ RoadOverrideForm + │ ├─ LaneManeuverEditor + │ ├─ MarkingEditor + │ ├─ SignalEditor + │ └─ CandidateList / technical details + └─ MapCanvas + └─ OpenLayers lifecycle and display-only interactions +``` + +`App` 保留跨域的组合责任:取得 `WorkbenchState`、挂接 map props、派发统一的“保存并重新生成”、 +以及把各编辑域的状态/命令传给头部和右栏。它不再包含具体表单实现,也不内嵌某一编辑域的 +预览或草稿算法。 + +## 状态所有权和数据流 + +| 域 | 唯一所有者 | 公开给 App 的内容 | 不可改变的规则 | +| --- | --- | --- | --- | +| 普通 v1 覆盖 | `useOverrideDraft` | `staged`, `stage`, `save`, `discard` | 只经 `/api/overrides` 保存 | +| v2 direct edit | `useDirectEditSession` + App orchestration | manifest、preview、session lifecycle; App retains gesture commands | 只经 `EditSession` 与 preview API;`lane-maneuver` 只在此处 | +| 红绿灯 | `useTrafficSignalDraft` | dirty、move/rotate、undo/redo、save/discard、`draftedState` | 本地草稿不提前写 API;保存时保持 40m 限制 | +| 选择与呈现 | `App` | selected road、element、marking、layers、scene | MapCanvas 只接收 props,不能自行持久化编辑状态 | +| 右栏 | `WorkbenchInspector` | typed props 和局部折叠状态 | 不直接调用 API,不拥有跨域草稿 | + +为避免在同一次渲染中存在两份 `WorkbenchState`,编辑 hooks 不复制整个状态;它们接收当前 +state 和 `setState`,只将各自领域的不可序列化控制信息保留在 hook ref 中。统一保存仍固定为: + +```text +save normal overrides -> save v2 document (no compile) -> save signal draft -> compile -> replace state +``` + +## 迁移策略 + +1. 先提取无状态右栏编辑器及其明确 props,保持 `App` 原有 state/command 实现不动。 +2. 提取普通 v1 覆盖草稿,并以现有保存/放弃逻辑测试锁定行为。 +3. 提取 v2 直接编辑协调 hook;保持 `EditSession` 的实例生命周期、`PreviewRequester` 的 + previewSeq 仲裁和 `ParameterPanel` ref 入口不变。 +4. 提取红绿灯草稿 hook;移动、旋转和表单更新进入同一历史栈,保存仍由顶层统一编排。 +5. 最后删除 App 内的旧实现,验证每一个 map prop 与原来等价。 + +每一步单独可编译、可测试;不做“先复制全部再删除”的并行机制。若某 hook 提取导致行为难以 +保持,则停在已有边界并记录原因,而不是创造新的共享全局状态。 + +## 兼容性和回滚 + +- 不改动 `src/`、`workbench/server.js` 或任何请求/响应类型,导出包契约天然不受影响。 +- 不修改 `MapCanvas` 的建图 effect 依赖;其现有 refs 和临时图层保持所有权。 +- 每次迁移使用 Git 提交作为回滚点;回滚只移除新模块并恢复原调用点,不触及工作区数据。 + +## 规范更新 + +更新前端目录、组件、hook、状态和质量规范,写入以下可执行约束: + +- hook 只能拥有一个编辑域,跨域保存由 App 编排; +- 组件通过 typed props 接受命令,不导入 API client 直接写入; +- 不复制 `WorkbenchState`,不可序列化 session/history 仅在所属 hook ref; +- MapCanvas 生命周期不得因 UI 抽取改变; +- 重构 PR 必须覆盖保存顺序、discard/undo 和 map 实例稳定性。 diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/implement.jsonl b/.trellis/tasks/09-02-workbench-component-boundaries/implement.jsonl new file mode 100644 index 0000000..9dd3234 --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/implement.jsonl @@ -0,0 +1 @@ +{"_example": "Fill with {\"file\": \"\", \"reason\": \"\"}. Put spec/research files only — no code paths. Run `python3 .trellis/scripts/get_context.py --mode packages` to list available specs. Delete this line once real entries are added."} diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/implement.md b/.trellis/tasks/09-02-workbench-component-boundaries/implement.md new file mode 100644 index 0000000..f785fbc --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/implement.md @@ -0,0 +1,29 @@ +# 实施计划 + +1. 建立组件与 hook 的类型边界,提取右栏编辑器和 `WorkbenchInspector`;逐项比对现有 props、 + 文案和折叠默认状态。 +2. 提取 `useOverrideDraft`,为 staged 合并、覆盖保存和放弃建立纯函数或聚焦测试。 +3. 提取 `useDirectEditSession`,集中拥有现有 `EditSession`、manifest、preview 和 diagnostics + 生命周期;手柄/lane 派生、undo/redo 与统一保存入口仍由 App 编排,以避免改变预览时序。 +4. 提取 `useTrafficSignalDraft`,收拢 signal 草稿、移动、旋转、撤销/重做、放弃和保存;复用现有 + 距离限制与 heading 派生,不重写几何算法。 +5. 将 App 缩至页面编排与命令组合,运行 map 交互回归;删除不再使用的内嵌实现。 +6. 更新 `.trellis/spec/frontend/`:`directory-structure.md`、`component-guidelines.md`、 + `hook-guidelines.md`、`state-management.md`、`quality-guidelines.md`。 +7. 运行格式、完整服务器测试、客户端类型/单测、生产构建和 diff 检查;人工核验保存/放弃/撤销及 + 地图视角稳定性。 + +## 验证命令 + +- `npm run format:check` +- `npm run test` +- `npm run test:client` +- `npm run test:client:unit -- --run` +- `npm run build` +- `git diff --check` + +## 高风险点 + +- `EditSession` 和 `PreviewRequester` 依赖稳定对象身份;提取时不可在每次渲染重建。 +- 红绿灯草稿与 v2 document 都参与顶部撤销/放弃命令;优先级与现有分支必须保持。 +- `MapCanvas` 的 OpenLayers effect 必须仍只在 mount 时建图,不能让 hook 或 inspector props 触发重建。 diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/prd.md b/.trellis/tasks/09-02-workbench-component-boundaries/prd.md new file mode 100644 index 0000000..fbc945a --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/prd.md @@ -0,0 +1,49 @@ +# 前端工作台组件边界重构 + +## 目标 + +在继续增加地图编辑能力前,将 React 工作台从单个过大的 `App.tsx` 中拆出清晰、可测的 +应用编排、编辑状态、地图选择和右侧检查器边界。重构后继续沿用现有工作流,而非借重构 +改变已确认的编辑行为。 + +## 已确认事实 + +- `workbench/client/src/App.tsx` 为 1,684 行,既装载 API 状态,又维护普通 v1 staged override、 + v2 `EditSession`/preview、红绿灯本地草稿历史、地图选择、页面命令和右侧表单。导向箭头 + `lane-maneuver` 已只走 v2,不属于 v1 staged。 +- `MapCanvas.tsx` 已拥有 OpenLayers 生命周期与临时地图叠加层;`ParameterPanel.tsx` 已拥有 + 参数输入文本与 DOM 级实时显示;`InspectorSection.tsx` 已拥有受控手风琴段落。 +- 右栏内嵌的 `Inspector`、`LaneManeuverEditor`、`MarkingEditor`、`SignalEditor`、`Candidates` + 不可独立复用或单测,且其依赖由 `App.tsx` 的闭包隐式提供。 +- 当前保存语义不可改变:普通 v1 覆盖(道路、连接、标线样式)暂存;v2 直接编辑(含 + `lane-maneuver`)经 session/preview/document;红绿灯 + 通过本地草稿、独立撤销栈和信号 API;“保存并重新生成”按既有顺序保存三者后正式编译。 +- `MapCanvas` 必须只构造一次,不能因 React 组件拆分或状态变更重新初始化地图。 + +## 范围 + +1. 将应用数据装载、工作台编辑协调、选择/图层展示、右侧检查器表单划分为具名模块或 hooks。 +2. 将右栏编辑器从 `App.tsx` 迁入 `components/`,通过明确的 typed props 传入状态和命令。 +3. 抽出直接编辑和红绿灯草稿生命周期的状态所有权,避免页面组件同时维护多组可变 refs。 +4. 为新增边界补充前端规范:目录职责、hook 规则、状态所有权、组件 props 和回归验证要求。 +5. 为关键纯派生与保存顺序补充聚焦测试;保留现有 API 和导出包契约。 + +## 非范围 + +- 不新增或删除地图编辑能力,不改变红绿灯、斑马线、导向箭头的交互。 +- 不修改服务端 API、导出包字段、v1/v2 文档协议或编译器。 +- 不在本任务重新设计右侧视觉样式、引入新的 UI 库,或处理未实现的旋转/新元素功能。 +- 不顺手修复任何尚未由用户确认的 UI 或交互问题;这类问题另立任务处理。 + +## 验收标准 + +- [ ] `App.tsx` 只保留页面组合、顶层状态连接和明确的命令入口,不再内嵌右栏编辑器或大段编辑会话实现。 +- [ ] 每个 extracted component/hook 有单一所有权,props 和返回值均为显式 TypeScript 合约;没有通过 module mutable state 或 DOM 查询传递业务数据。 +- [ ] 普通 v1 staged、v2 direct-edit(含 `lane-maneuver`)、traffic-signal 三条编辑/撤销/放弃/保存并重新生成流程与重构前一致。 +- [ ] 地图在选择、保存、放弃、撤销与右栏重渲染时不被重新创建,也不丢失视角。 +- [ ] 选中元素仍自动展开对应右栏段;取消选择仍清理临时元素/红绿灯操纵控件。 +- [ ] `npm run format:check`、`npm run test`、`npm run test:client`、`npm run test:client:unit -- --run`、`npm run build` 通过。 + +## 关键决定 + +- 本轮严格保持已有功能、交互和视觉效果。每项迁移必须以现有行为为基线;发现未确认问题只记录,不随重构修改。 diff --git a/.trellis/tasks/09-02-workbench-component-boundaries/task.json b/.trellis/tasks/09-02-workbench-component-boundaries/task.json new file mode 100644 index 0000000..a1713b8 --- /dev/null +++ b/.trellis/tasks/09-02-workbench-component-boundaries/task.json @@ -0,0 +1,26 @@ +{ + "id": "workbench-component-boundaries", + "name": "workbench-component-boundaries", + "title": "前端工作台组件边界重构", + "description": "拆分 App.tsx 的应用编排、编辑状态和右侧检查器,建立可执行前端 React 组件边界规范。", + "status": "completed", + "dev_type": null, + "scope": null, + "package": null, + "priority": "P2", + "creator": "dingkang", + "assignee": "dingkang", + "createdAt": "2026-09-02", + "completedAt": "2026-09-02", + "branch": null, + "base_branch": "main", + "worktree_path": null, + "commit": null, + "pr_url": null, + "subtasks": [], + "children": [], + "parent": "08-26-direct-manipulation-road-editor", + "relatedFiles": [], + "notes": "", + "meta": {} +} diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index bea2625..588093b 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -1,9 +1,14 @@ -import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; -import { Download, RefreshCw, Upload } from 'lucide-react'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Download, RefreshCw } from 'lucide-react'; +import { ImportScreen } from './components/ImportScreen'; +import { Overview } from './components/Overview'; +import { WorkbenchInspector } from './components/WorkbenchInspector'; +import { useOverrideDraft } from './hooks/useOverrideDraft'; +import { useDirectEditSession } from './hooks/useDirectEditSession'; +import { useTrafficSignalDraft } from './hooks/useTrafficSignalDraft'; import { api, isVersionConflict } from './lib/api'; import { MapCanvas } from './components/MapCanvas'; import { ParameterPanel, type ParameterPanelHandle } from './components/ParameterPanel'; -import { InspectorSection } from './components/InspectorSection'; import { elementSelectionFor, groupMembers, @@ -36,20 +41,16 @@ import { operationFor, } from './edit/projection'; import { disabledReasonOf, handlesForSegment, intervalRangeHandles, type IntervalRangeHandle } from './edit/selection'; -import { EditSession } from './edit/session'; import type { - EditDiagnostic, EditHandle, - HandleManifest, PreviewLayerName, RoadConstraint, - RoadEditOperation, EditSelection, RoadIntervalAnchor, VersionConflict, } from './edit/types'; import { Button } from './ui/button'; -import type { GeoFeature, GeoJson, Override, Road, WorkbenchState } from './types/state'; +import type { GeoFeature, GeoJson, Road, WorkbenchState } from './types/state'; import type { LayerName } from './map/layers'; const layerLabels: Array<[LayerName, string]> = [ @@ -71,53 +72,9 @@ const defaultLayers = Object.fromEntries(layerLabels.map(([key]) => [key, key != const direction = (road: Road) => (road.direction === 'forward' ? '沿 OSM 方向' : '逆 OSM 方向'); const label = (road: Road) => road.tags.name || `${road.highway}(OSM ${road.osmWayIds.join(', ')})`; const laneIndex = (id: string) => Number(id.split(':').at(-1)); -const overviewMetrics = [ - ['nativeRoadCount', '方向道路'], - ['nativeRoadSurfaceFeatures', '道路面'], - ['nativeJunctionSurfaceFeatures', '路口面'], - ['nativeLaneCenterlineFeatures', '车道中心线'], - ['nativeCenterLineFeatures', '道路中心线'], - ['nativeConnectorFeatures', '连接路径'], - ['nativeCrosswalkFeatures', '斑马线'], - ['nativeVehicleStopLineFeatures', '停止线'], - ['unconnectedInteriorRoadEnds', '未连接端点'], -] as const; -function Overview({ comparison }: { comparison: Record }) { - const severity = comparison.diagnosticsBySeverity as Record | undefined; - return ( -
-
- {overviewMetrics.map(([key, label]) => ( -
- {label} - {Number(comparison[key] || 0).toLocaleString('zh-CN')} -
- ))} -
- {severity && ( -
- 编译诊断 - {Object.entries(severity).map(([level, count]) => ( - - {level === 'error' ? '错误' : level === 'warning' ? '警告' : '提示'} {count} - - ))} -
- )} -
- ); -} function App() { const [state, setState] = useState(); const [selected, setSelected] = useState(null); - const [staged, setStaged] = useState([]); - const [signalDirty, setSignalDirty] = useState(false); - const signalDraftRef = useRef(null); - const signalUndoRef = useRef([]); - const signalRedoRef = useRef([]); - const signalSavedRef = useRef(null); - const signalMoveActiveRef = useRef(false); - const signalRotateActiveRef = useRef(false); const [layers, setLayers] = useState(defaultLayers); const [scene, setScene] = useState(false); const [status, setStatus] = useState('正在加载工作台...'); @@ -131,6 +88,22 @@ function App() { return false; } }); + const overrideDraft = useOverrideDraft({ state, setState, setStatus }); + const { staged, stage, save, clear: clearStaged } = overrideDraft; + const signalDraft = useTrafficSignalDraft({ state, setState }); + const { + dirty: signalDirty, + setDirty: setSignalDirty, + draftRef: signalDraftRef, + undoRef: signalUndoRef, + redoRef: signalRedoRef, + savedRef: signalSavedRef, + update: updateSignal, + move: moveSignal, + finishMove: finishSignalMove, + rotate: rotateSignal, + finishRotate: finishSignalRotate, + } = signalDraft; useEffect(() => { try { window.localStorage.setItem('workbench-mode', editMode ? 'edit' : 'browse'); @@ -150,36 +123,23 @@ function App() { }) .catch((error: Error) => setStatus(error.message)); }, []); - const [manifest, setManifest] = useState(null); - /** Which compiled document the session already adopted, so a re-fetch cannot discard edits. */ - const loadedDocument = useRef(null); - useEffect(() => { - // Flag off: no manifest request at all, so the network trace matches main. - if (!editMode) return; - api - // Scoped to the selection: the whole-area manifest is 844 KB on a 41-road - // workspace, 89% of it `affects` id lists, and the map renders about six. - .editState(selected?.segmentId ? { segment: selected.segmentId } : undefined) - .then((value) => { - if (!('handles' in value)) return; - setManifest(value.handles); - // Adopt the document only when it actually changed. This effect also runs on - // every selection change, and reloading there would silently discard the - // session's unsaved edits. - const key = `${value.areaId}:${value.documentVersion}`; - if (loadedDocument.current === key) return; - loadedDocument.current = key; - sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion); - touch(); - }) - // A manifest failure must not take the workbench down with it; the map just - // shows no handles. - .catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`)); - // Keyed on `state`, not mounted once: on a fresh import the first attempt runs - // before any area exists and comes back inactive, so the handles never appeared - // until a manual reload. A recompile also moves the geometry the manifest - // describes, so the manifest has to be refetched with it. - }, [editMode, state, selected?.segmentId]); + const directEdit = useDirectEditSession({ + editMode, + state, + selectedSegmentId: selected?.segmentId, + setStatus, + }); + const { + session, + manifest, + setManifest, + preview, + setPreview, + diagnostics: editDiagnostics, + setDiagnostics: setEditDiagnostics, + revision: editRevision, + touch, + } = directEdit; const editHandles = useMemo(() => { if (!editMode || !state) return []; // Handle anchors carry a directional road id while reserves are keyed by @@ -202,13 +162,6 @@ function App() { if (!parent || !road) return []; return intervalRangeHandles(parent, road.centerline, manifest.reserves, selected.segmentId); }, [editHandles, editMode, manifest, selected, state]); - const [preview, setPreview] = useState> | null>(null); - const [editDiagnostics, setEditDiagnostics] = useState([]); - const sessionRef = useRef(null); - if (editMode && !sessionRef.current) sessionRef.current = new EditSession(); - const session = sessionRef.current; - const [editRevision, setEditRevision] = useState(0); - const touch = () => setEditRevision((value) => value + 1); /** * The crosswalk group under selection, if any. * @@ -326,7 +279,7 @@ function App() { return gesture.current; }; const requester = useMemo(() => { - const owner = sessionRef.current; + const owner = session; if (!owner) return null; return new PreviewRequester({ session: owner, @@ -575,7 +528,7 @@ function App() { signalUndoRef.current = []; signalRedoRef.current = []; setSignalDirty(false); - setStaged([]); + clearStaged(); gesture.current = null; touch(); setPreview(null); @@ -622,6 +575,7 @@ function App() { setStatus('直接编辑已保存,正在重新生成几何...'); const next = await api.compile(); setState(next); + signalSavedRef.current = next.trafficSignals.assemblies.features; setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); // The baseline now carries the edit, so the preview overlay would draw it twice. setPreview(null); @@ -631,28 +585,6 @@ function App() { } return true; }; - const stage = (change: Override) => - setStaged((current) => { - const next = [...current.filter((item) => item.id !== change.id), change]; - return next; - }); - const save = async () => { - if (!state || !staged.length) return true; - try { - const overrides = [ - ...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)), - ...staged, - ]; - const result = await api.overrides(overrides); - setState({ ...state, overrides: result.overrides }); - setStaged([]); - setStatus('已保存,点击“保存并重新生成”写入几何'); - return true; - } catch (error) { - setStatus((error as Error).message); - return false; - } - }; const compile = async () => { if (!(await save())) return; if (!(await saveDirectEdits(false))) return; @@ -675,6 +607,7 @@ function App() { setStatus('正在重新生成...'); const next = await api.compile(); setState(next); + signalSavedRef.current = next.trafficSignals.assemblies.features; setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); setPreview(null); setStatus('已保存并重新生成'); @@ -682,30 +615,16 @@ function App() { setStatus((error as Error).message); } }; - const updateSignal = async (features: GeoFeature[]) => { - if (state) signalUndoRef.current.push(state.trafficSignals.assemblies.features); - signalRedoRef.current = []; - signalDraftRef.current = features; - setSignalDirty(true); - setState((current) => - current - ? { - ...current, - trafficSignals: { - ...current.trafficSignals, - assemblies: { ...current.trafficSignals.assemblies, features }, - }, - } - : current, - ); - }; if (!state) return ( { + onImport={async (file) => { + const next = await api.import(file); setState(next); + signalSavedRef.current = next.trafficSignals.assemblies.features; setStatus(`已导入 ${next.areaId}`); + return next; }} /> ); @@ -733,122 +652,6 @@ function App() { if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`); else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); }; - const moveSignal = (uid: string, coordinate: Coordinate) => { - setState((current) => { - if (!current) return current; - if (!signalMoveActiveRef.current) { - signalUndoRef.current.push(current.trafficSignals.assemblies.features); - signalRedoRef.current = []; - signalMoveActiveRef.current = true; - } - const currentFeature = current.trafficSignals.assemblies.features.find( - (feature) => feature.properties?.signal_uid === uid, - ); - const stop: Coordinate | null = currentFeature - ? [Number(currentFeature.properties?.stop_lon), Number(currentFeature.properties?.stop_lat)] - : null; - let nextCoordinate = coordinate; - if (stop && stop.every(Number.isFinite)) { - const distance = haversineMeters(stop, coordinate); - if (distance > 40) { - const ratio = 40 / distance; - nextCoordinate = [stop[0] + (coordinate[0] - stop[0]) * ratio, stop[1] + (coordinate[1] - stop[1]) * ratio]; - } - } - return { - ...current, - trafficSignals: { - ...current.trafficSignals, - assemblies: { - ...current.trafficSignals.assemblies, - features: current.trafficSignals.assemblies.features.map((feature) => - feature.properties?.signal_uid === uid - ? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } } - : feature, - ), - }, - }, - }; - }); - setSignalDirty(true); - }; - const finishSignalMove = (uid: string, coordinate: Coordinate) => { - const current = state; - if (!current) return; - const source = current.trafficSignals.assemblies.features.find((feature) => feature.properties?.signal_uid === uid); - const stop: Coordinate | null = source - ? [Number(source.properties?.stop_lon), Number(source.properties?.stop_lat)] - : null; - let nextCoordinate = coordinate; - if (stop && stop.every(Number.isFinite)) { - const distance = haversineMeters(stop, coordinate); - if (distance > 40) { - const ratio = 40 / distance; - nextCoordinate = [stop[0] + (coordinate[0] - stop[0]) * ratio, stop[1] + (coordinate[1] - stop[1]) * ratio]; - } - } - const features = current.trafficSignals.assemblies.features.map((feature) => - feature.properties?.signal_uid === uid - ? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } } - : feature, - ); - signalDraftRef.current = features; - signalMoveActiveRef.current = false; - setSignalDirty(true); - }; - const rotateSignal = (uid: string, mastHeading: number) => { - const heading = ((mastHeading % 360) + 360) % 360; - setState((current) => { - if (!current) return current; - if (!signalRotateActiveRef.current) { - signalUndoRef.current.push(current.trafficSignals.assemblies.features); - signalRedoRef.current = []; - signalRotateActiveRef.current = true; - } - return { - ...current, - trafficSignals: { - ...current.trafficSignals, - assemblies: { - ...current.trafficSignals.assemblies, - features: current.trafficSignals.assemblies.features.map((feature) => - feature.properties?.signal_uid === uid - ? { - ...feature, - properties: { - ...feature.properties, - mast_heading_deg: heading, - face_heading_deg: (((heading - 90) % 360) + 360) % 360, - }, - } - : feature, - ), - }, - }, - }; - }); - setSignalDirty(true); - }; - const finishSignalRotate = (uid: string, mastHeading: number) => { - const current = state; - if (!current) return; - const heading = ((mastHeading % 360) + 360) % 360; - const features = current.trafficSignals.assemblies.features.map((feature) => - feature.properties?.signal_uid === uid - ? { - ...feature, - properties: { - ...feature.properties, - mast_heading_deg: heading, - face_heading_deg: (((heading - 90) % 360) + 360) % 360, - }, - } - : feature, - ); - signalDraftRef.current = features; - signalRotateActiveRef.current = false; - setSignalDirty(true); - }; return ( <>
@@ -1044,7 +847,7 @@ function App() { }} /> ); } -function ImportScreen({ status, onImported }: { status: string; onImported: (state: WorkbenchState) => void }) { - const [file, setFile] = useState(); - const [busy, setBusy] = useState(false); - return ( -
-
{ - event.preventDefault(); - if (!file) return; - setBusy(true); - try { - onImported(await api.import(file)); - } catch (error) { - console.error(error); - } finally { - setBusy(false); - } - }} - > -

导入 OSM 地图

-

{status}

- setFile(event.target.files?.[0])} - required - /> - -
-
- ); -} -function Inspector({ - road, - state, - staged, - marking, - element, - stage, - status, - setState, - session, - onLaneManeuverChange, - updateSignal, - children, -}: { - road: Road | null; - state: WorkbenchState; - staged: Override[]; - marking: Record | null; - element: ElementSelection | null; - stage: (item: Override) => void; - status: (value: string) => void; - setState: (next: WorkbenchState) => void; - session: EditSession | null; - onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void; - updateSignal: (features: GeoFeature[]) => Promise; - children?: ReactNode; -}) { - const [width, setWidth] = useState(0); - const [lanes, setLanes] = useState(1); - const [left, setLeft] = useState(false); - const [right, setRight] = useState(false); - useEffect(() => { - if (road) { - setWidth(road.widthMeters); - setLanes(road.laneCount); - setLeft(road.sidewalkLeft); - setRight(road.sidewalkRight); - } - }, [road]); - const endpoint = state.compiled.model.endpoints.find((item) => item.roadId === road?.id && item.side === 'end'); - const movements = state.compiled.movements?.filter((item) => item.fromRoadId === road?.id) || []; - const effective = (id: string, fallback: boolean) => - ((staged.find((item) => item.id === id) || state.overrides.overrides.find((item) => item.id === id))?.enabled as - boolean | undefined) ?? fallback; - const signalUid = typeof marking?.signal_uid === 'string' ? marking.signal_uid : ''; - const signal = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === signalUid); - const [open, setOpen] = useState<'road' | 'element' | 'connections' | 'advanced' | null>('road'); - useEffect(() => { - if (element || marking) setOpen('element'); - else if (road) setOpen('road'); - }, [element, marking, road]); - const section = (name: NonNullable) => () => setOpen((current) => (current === name ? null : name)); - const selectedLabel = - element?.kind === 'lane-maneuver' - ? `第 ${laneIndex(element.laneId)} 车道` - : marking - ? '已选标线或设施' - : road - ? label(road) - : '未选择对象'; - return ( -
-
- 编辑工作台 - {selectedLabel} - {staged.length ? `已暂存 ${staged.length} 项修改` : '没有待保存的覆盖修改'} -
- - {road ? ( -
{ - event.preventDefault(); - stage({ - id: `道路:${road.id}`, - kind: 'road', - roadId: road.id, - widthMeters: width, - laneCount: lanes, - sidewalkLeft: left, - sidewalkRight: right, - }); - const opposite = state.compiled.model.roads.find( - (item) => item.id !== road.id && item.segmentId === road.segmentId, - ); - if (opposite) - stage({ - id: `道路:${opposite.id}`, - kind: 'road', - roadId: opposite.id, - sidewalkLeft: right, - sidewalkRight: left, - }); - status('有未保存修改'); - }} - > - - - {label(road)}({direction(road)}) - - - {movements.length - ? `已识别 ${movements.length} 个行驶动作,${movements.filter((item) => item.geometryPublished).length} 条已绘制路径` - : '当前方向没有已识别的行驶动作'} - - - - - - -
- ) : ( -

点击道路、车道、标线、转向路径或路口面以查看详情。

- )} - {children} -
- - - item.kind === 'lane-maneuver' && - item.anchor.type === 'lane' && - item.anchor.laneId === element.laneId, - )?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined) - : undefined - } - onChange={onLaneManeuverChange} - /> - - - - - {road ? ( -
- {state.compiled.model.connections - .filter((connection) => connection.fromEndpointId === endpoint?.id) - .map((connection) => ( - - ))} - {movements.map((movement) => ( - - ))} -
- ) : ( -

选择一条道路以管理其驶入路口的连接。

- )} - {endpoint && - state.compiled.diagnostics - .find((item) => item.endpointId === endpoint.id) - ?.manualCandidates?.map((candidate) => { - const target = state.compiled.model.roads.find((item) => item.id === candidate.roadId); - const targetEndpoint = state.compiled.model.endpoints.find( - (item) => item.roadId === candidate.roadId && item.side === 'start', - ); - return target && targetEndpoint ? ( - - ) : null; - })} -
- - -
- 技术详情与来源 -
-            {JSON.stringify(
-              road ? { OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 原始标签: road.tags } : marking,
-              null,
-              2,
-            )}
-          
-
-
-
- ); -} -const MANEUVER_OPTIONS: Array<[string, string]> = [ - ['', '无箭头'], - ['through', '直行'], - ['left', '左转'], - ['right', '右转'], - ['through;left', '直行或左转'], - ['through;right', '直行或右转'], - ['through;left;right', '直行、左转或右转'], -]; -function LaneManeuverEditor({ - element, - value, - onChange, -}: { - element: ElementSelection | null; - value?: { maneuver?: string; placementDistanceMeters?: number }; - onChange: (maneuver: string, placementDistanceMeters: number) => void; -}) { - if (!element || element.kind !== 'lane-maneuver') return null; - const maneuver = value?.maneuver ?? element.maneuver; - const placementDistanceMeters = value?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6; - return ( -
-

车道转向箭头

-

第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。

- - -

保存并重新生成时会避开停止线、斑马线和车道端点。

-
- ); -} -function MarkingEditor({ - marking, - stage, -}: { - marking: Record | null; - stage: (item: Override) => void; -}) { - const style = typeof marking?.effective_style === 'string' ? marking.effective_style : ''; - const [value, setValue] = useState(style || 'yellow-dashed'); - useEffect(() => setValue(style || 'yellow-dashed'), [style]); - if (!style || !marking) return null; - const roadId = String(marking.road_id); - const segment = marking.segment_id; - const kind = String(marking.provenance || ''); - const save = () => { - const [color, pattern] = value.replace('double-', '').split('-'); - if (segment) - stage({ - id: `道路中心线:${segment}`, - kind: 'center-line-style', - segmentId: segment, - color, - pattern, - double: value.startsWith('double-'), - }); - else if (kind.includes('edge-line')) - stage({ - id: `道路外缘线:${roadId}:${marking.side}`, - kind: 'edge-line-style', - roadId, - side: marking.side, - color, - pattern, - }); - else - stage({ - id: `车道分隔线:${roadId}:${marking.left_lane_index}-${marking.right_lane_index}`, - kind: 'lane-separator-style', - roadId, - leftLaneIndex: marking.left_lane_index, - rightLaneIndex: marking.right_lane_index, - color, - pattern, - }); - }; - return ( -
{ - event.preventDefault(); - save(); - }} - > -

标线样式

- - -
- ); -} -function SignalEditor({ - state, - signal, - status, - update, -}: { - state: WorkbenchState; - signal?: GeoFeature; - status: (text: string) => void; - update: (features: GeoFeature[]) => Promise; -}) { - const [selected, setSelected] = useState(''); - useEffect(() => setSelected(String(signal?.properties?.signal_uid || '')), [signal]); - const feature = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === selected); - const coordinates = - feature?.geometry?.type === 'Point' && Array.isArray(feature.geometry.coordinates) - ? (feature.geometry.coordinates as [number, number]) - : null; - const saveField = (key: string, value: unknown) => { - if (!feature) return; - const mastHeading = key === 'mast_heading_deg' ? ((Number(value) % 360) + 360) % 360 : null; - void update( - state.trafficSignals.assemblies.features.map((item) => - item === feature - ? { - ...item, - properties: { - ...item.properties, - [key]: mastHeading ?? value, - ...(mastHeading === null ? {} : { face_heading_deg: (((mastHeading - 90) % 360) + 360) % 360 }), - }, - } - : item, - ), - ); - }; - const saveCoordinate = (index: 0 | 1, value: number) => { - if (!feature || !coordinates || !Number.isFinite(value)) return; - const nextCoordinates: [number, number] = [...coordinates]; - nextCoordinates[index] = value; - void update( - state.trafficSignals.assemblies.features.map((item) => - item === feature - ? { ...item, geometry: { ...item.geometry, type: 'Point', coordinates: nextCoordinates } } - : item, - ), - ); - }; - return ( -
-

原生红绿灯

- - {feature ? ( - <> - - - - - - - -

- 控制进口:{String(feature.properties?.approach_id || '未绑定')} -
- 来源道路:{String(feature.properties?.source_way_id || '未绑定')} -

- - - - ) : null} -
- ); -} -function Candidates({ - state, - setState, - status, -}: { - state: WorkbenchState; - setState: (state: WorkbenchState) => void; - status: (text: string) => void; -}) { - const candidates = state.debug?.junctionCandidates || []; - if (!candidates.length) return null; - return ( -
-
-

复杂路口候选(debug)

- {candidates.map((candidate) => ( - - ))} -
- ); -} export default App; diff --git a/workbench/client/src/components/ElementEditors.tsx b/workbench/client/src/components/ElementEditors.tsx new file mode 100644 index 0000000..e2c9bcc --- /dev/null +++ b/workbench/client/src/components/ElementEditors.tsx @@ -0,0 +1,297 @@ +import { useEffect, useState } from 'react'; +import type { ElementSelection } from '../edit/element'; +import type { GeoFeature, Override, WorkbenchState } from '../types/state'; +import { Button } from '../ui/button'; + +const maneuverOptions: Array<[string, string]> = [ + ['', '无箭头'], + ['through', '直行'], + ['left', '左转'], + ['right', '右转'], + ['through;left', '直行或左转'], + ['through;right', '直行或右转'], + ['through;left;right', '直行、左转或右转'], +]; + +const laneIndex = (id: string) => Number(id.split(':').at(-1)); + +export function LaneManeuverEditor({ + element, + value, + onChange, +}: { + element: ElementSelection | null; + value?: { maneuver?: string; placementDistanceMeters?: number }; + onChange: (maneuver: string, placementDistanceMeters: number) => void; +}) { + if (!element || element.kind !== 'lane-maneuver') return null; + const maneuver = value?.maneuver ?? element.maneuver; + const placementDistanceMeters = value?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6; + return ( +
+

车道转向箭头

+

第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。

+ + +

保存并重新生成时会避开停止线、斑马线和车道端点。

+
+ ); +} + +export function MarkingEditor({ + marking, + stage, +}: { + marking: Record | null; + stage: (item: Override) => void; +}) { + const style = typeof marking?.effective_style === 'string' ? marking.effective_style : ''; + const [value, setValue] = useState(style || 'yellow-dashed'); + useEffect(() => setValue(style || 'yellow-dashed'), [style]); + if (!style || !marking) return null; + const roadId = String(marking.road_id); + const segment = marking.segment_id; + const kind = String(marking.provenance || ''); + const save = () => { + const [color, pattern] = value.replace('double-', '').split('-'); + if (segment) + stage({ + id: `道路中心线:${segment}`, + kind: 'center-line-style', + segmentId: segment, + color, + pattern, + double: value.startsWith('double-'), + }); + else if (kind.includes('edge-line')) + stage({ + id: `道路外缘线:${roadId}:${marking.side}`, + kind: 'edge-line-style', + roadId, + side: marking.side, + color, + pattern, + }); + else + stage({ + id: `车道分隔线:${roadId}:${marking.left_lane_index}-${marking.right_lane_index}`, + kind: 'lane-separator-style', + roadId, + leftLaneIndex: marking.left_lane_index, + rightLaneIndex: marking.right_lane_index, + color, + pattern, + }); + }; + return ( +
{ + event.preventDefault(); + save(); + }} + > +

标线样式

+ + +
+ ); +} + +export function SignalEditor({ + state, + signal, + status, + update, +}: { + state: WorkbenchState; + signal?: GeoFeature; + status: (text: string) => void; + update: (features: GeoFeature[]) => Promise; +}) { + const [selected, setSelected] = useState(''); + useEffect(() => setSelected(String(signal?.properties?.signal_uid || '')), [signal]); + const feature = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === selected); + const coordinates = + feature?.geometry?.type === 'Point' && Array.isArray(feature.geometry.coordinates) + ? (feature.geometry.coordinates as [number, number]) + : null; + const saveField = (key: string, value: unknown) => { + if (!feature) return; + const mastHeading = key === 'mast_heading_deg' ? ((Number(value) % 360) + 360) % 360 : null; + void update( + state.trafficSignals.assemblies.features.map((item) => + item === feature + ? { + ...item, + properties: { + ...item.properties, + [key]: mastHeading ?? value, + ...(mastHeading === null ? {} : { face_heading_deg: (((mastHeading - 90) % 360) + 360) % 360 }), + }, + } + : item, + ), + ); + }; + const saveCoordinate = (index: 0 | 1, value: number) => { + if (!feature || !coordinates || !Number.isFinite(value)) return; + const nextCoordinates: [number, number] = [...coordinates]; + nextCoordinates[index] = value; + void update( + state.trafficSignals.assemblies.features.map((item) => + item === feature + ? { ...item, geometry: { ...item.geometry, type: 'Point', coordinates: nextCoordinates } } + : item, + ), + ); + }; + return ( +
+

原生红绿灯

+ + {feature ? ( + <> + + + + + + + +

+ 控制进口:{String(feature.properties?.approach_id || '未绑定')} +
+ 来源道路:{String(feature.properties?.source_way_id || '未绑定')} +

+ + + + ) : null} +
+ ); +} + +export function Candidates({ state, onAccept }: { state: WorkbenchState; onAccept: (index: number) => void }) { + const candidates = state.debug?.junctionCandidates || []; + if (!candidates.length) return null; + return ( +
+
+

复杂路口候选(debug)

+ {candidates.map((candidate) => ( + + ))} +
+ ); +} diff --git a/workbench/client/src/components/ImportScreen.tsx b/workbench/client/src/components/ImportScreen.tsx new file mode 100644 index 0000000..4cb7307 --- /dev/null +++ b/workbench/client/src/components/ImportScreen.tsx @@ -0,0 +1,45 @@ +import { useState } from 'react'; +import { Upload } from 'lucide-react'; +import type { WorkbenchState } from '../types/state'; +import { Button } from '../ui/button'; + +export function ImportScreen({ + status, + onImport, +}: { + status: string; + onImport: (file: File) => Promise; +}) { + const [file, setFile] = useState(); + const [busy, setBusy] = useState(false); + return ( +
+
{ + event.preventDefault(); + if (!file) return; + setBusy(true); + try { + await onImport(file); + } catch (error) { + console.error(error); + } finally { + setBusy(false); + } + }} + > +

导入 OSM 地图

+

{status}

+ setFile(event.target.files?.[0])} + required + /> + +
+
+ ); +} diff --git a/workbench/client/src/components/Overview.tsx b/workbench/client/src/components/Overview.tsx new file mode 100644 index 0000000..953318b --- /dev/null +++ b/workbench/client/src/components/Overview.tsx @@ -0,0 +1,36 @@ +const metrics = [ + ['nativeRoadCount', '方向道路'], + ['nativeRoadSurfaceFeatures', '道路面'], + ['nativeJunctionSurfaceFeatures', '路口面'], + ['nativeCenterLineFeatures', '道路中心线'], + ['nativeConnectorFeatures', '连接路径'], + ['nativeCrosswalkFeatures', '斑马线'], + ['nativeVehicleStopLineFeatures', '停止线'], + ['unconnectedInteriorRoadEnds', '未连接端点'], +] as const; + +export function Overview({ comparison }: { comparison: Record }) { + const severity = comparison.diagnosticsBySeverity as Record | undefined; + return ( +
+
+ {metrics.map(([key, label]) => ( +
+ {label} + {Number(comparison[key] || 0).toLocaleString('zh-CN')} +
+ ))} +
+ {severity && ( +
+ 编译诊断 + {Object.entries(severity).map(([level, count]) => ( + + {level === 'error' ? '错误' : level === 'warning' ? '警告' : '提示'} {count} + + ))} +
+ )} +
+ ); +} diff --git a/workbench/client/src/components/WorkbenchInspector.tsx b/workbench/client/src/components/WorkbenchInspector.tsx new file mode 100644 index 0000000..6415b3a --- /dev/null +++ b/workbench/client/src/components/WorkbenchInspector.tsx @@ -0,0 +1,273 @@ +import { useEffect, useState, type ReactNode } from 'react'; +import { Candidates, LaneManeuverEditor, MarkingEditor, SignalEditor } from './ElementEditors'; +import { InspectorSection } from './InspectorSection'; +import type { EditSession } from '../edit/session'; +import type { ElementSelection } from '../edit/element'; +import type { Override, GeoFeature, Road, WorkbenchState } from '../types/state'; +import { Button } from '../ui/button'; +const laneIndex = (id: string) => Number(id.split(':').at(-1)); +const direction = (road: Road) => (road.direction === 'forward' ? '沿 OSM 方向' : '逆 OSM 方向'); +const label = (road: Road) => road.tags.name || `${road.highway}(OSM ${road.osmWayIds.join(', ')})`; +export function WorkbenchInspector({ + road, + state, + staged, + marking, + element, + stage, + status, + session, + onLaneManeuverChange, + updateSignal, + onAcceptCandidate, + children, +}: { + road: Road | null; + state: WorkbenchState; + staged: Override[]; + marking: Record | null; + element: ElementSelection | null; + stage: (item: Override) => void; + status: (value: string) => void; + session: EditSession | null; + onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void; + updateSignal: (features: GeoFeature[]) => Promise; + onAcceptCandidate: (index: number) => void; + children?: ReactNode; +}) { + const [width, setWidth] = useState(0); + const [lanes, setLanes] = useState(1); + const [left, setLeft] = useState(false); + const [right, setRight] = useState(false); + useEffect(() => { + if (road) { + setWidth(road.widthMeters); + setLanes(road.laneCount); + setLeft(road.sidewalkLeft); + setRight(road.sidewalkRight); + } + }, [road]); + const endpoint = state.compiled.model.endpoints.find((item) => item.roadId === road?.id && item.side === 'end'); + const movements = state.compiled.movements?.filter((item) => item.fromRoadId === road?.id) || []; + const effective = (id: string, fallback: boolean) => + ((staged.find((item) => item.id === id) || state.overrides.overrides.find((item) => item.id === id))?.enabled as + boolean | undefined) ?? fallback; + const signalUid = typeof marking?.signal_uid === 'string' ? marking.signal_uid : ''; + const signal = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === signalUid); + const [open, setOpen] = useState<'road' | 'element' | 'connections' | 'advanced' | null>('road'); + useEffect(() => { + if (element || marking) setOpen('element'); + else if (road) setOpen('road'); + }, [element, marking, road]); + const section = (name: NonNullable) => () => setOpen((current) => (current === name ? null : name)); + const selectedLabel = + element?.kind === 'lane-maneuver' + ? `第 ${laneIndex(element.laneId)} 车道` + : marking + ? '已选标线或设施' + : road + ? label(road) + : '未选择对象'; + return ( +
+
+ 编辑工作台 + {selectedLabel} + {staged.length ? `已暂存 ${staged.length} 项修改` : '没有待保存的覆盖修改'} +
+ + {road ? ( +
{ + event.preventDefault(); + stage({ + id: `道路:${road.id}`, + kind: 'road', + roadId: road.id, + widthMeters: width, + laneCount: lanes, + sidewalkLeft: left, + sidewalkRight: right, + }); + const opposite = state.compiled.model.roads.find( + (item) => item.id !== road.id && item.segmentId === road.segmentId, + ); + if (opposite) + stage({ + id: `道路:${opposite.id}`, + kind: 'road', + roadId: opposite.id, + sidewalkLeft: right, + sidewalkRight: left, + }); + status('有未保存修改'); + }} + > + + + {label(road)}({direction(road)}) + + + {movements.length + ? `已识别 ${movements.length} 个行驶动作,${movements.filter((item) => item.geometryPublished).length} 条已绘制路径` + : '当前方向没有已识别的行驶动作'} + + + + + + +
+ ) : ( +

点击道路、车道、标线、转向路径或路口面以查看详情。

+ )} + {children} +
+ + + item.kind === 'lane-maneuver' && + item.anchor.type === 'lane' && + item.anchor.laneId === element.laneId, + )?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined) + : undefined + } + onChange={onLaneManeuverChange} + /> + + + + + {road ? ( +
+ {state.compiled.model.connections + .filter((connection) => connection.fromEndpointId === endpoint?.id) + .map((connection) => ( + + ))} + {movements.map((movement) => ( + + ))} +
+ ) : ( +

选择一条道路以管理其驶入路口的连接。

+ )} + {endpoint && + state.compiled.diagnostics + .find((item) => item.endpointId === endpoint.id) + ?.manualCandidates?.map((candidate) => { + const target = state.compiled.model.roads.find((item) => item.id === candidate.roadId); + const targetEndpoint = state.compiled.model.endpoints.find( + (item) => item.roadId === candidate.roadId && item.side === 'start', + ); + return target && targetEndpoint ? ( + + ) : null; + })} +
+ + +
+ 技术详情与来源 +
+            {JSON.stringify(
+              road ? { OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 原始标签: road.tags } : marking,
+              null,
+              2,
+            )}
+          
+
+
+
+ ); +} diff --git a/workbench/client/src/hooks/useDirectEditSession.ts b/workbench/client/src/hooks/useDirectEditSession.ts new file mode 100644 index 0000000..fa3aad8 --- /dev/null +++ b/workbench/client/src/hooks/useDirectEditSession.ts @@ -0,0 +1,59 @@ +import { useEffect, useRef, useState } from 'react'; +import { api } from '../lib/api'; +import { EditSession } from '../edit/session'; +import type { EditDiagnostic, HandleManifest, PreviewLayerName } from '../edit/types'; +import type { GeoJson, WorkbenchState } from '../types/state'; + +/** + * Owns the stable v2 session and the server state that surrounds it. Gesture + * construction and map interaction stay with the composition root for now. + */ +export function useDirectEditSession({ + editMode, + state, + selectedSegmentId, + setStatus, +}: { + editMode: boolean; + state?: WorkbenchState; + selectedSegmentId?: string; + setStatus: (status: string) => void; +}) { + const [manifest, setManifest] = useState(null); + const [preview, setPreview] = useState> | null>(null); + const [diagnostics, setDiagnostics] = useState([]); + const [revision, setRevision] = useState(0); + const sessionRef = useRef(null); + const loadedDocument = useRef(null); + if (editMode && !sessionRef.current) sessionRef.current = new EditSession(); + const touch = () => setRevision((value) => value + 1); + + useEffect(() => { + // Flag off: no manifest request at all, so the network trace matches browse mode. + if (!editMode) return; + api + .editState(selectedSegmentId ? { segment: selectedSegmentId } : undefined) + .then((value) => { + if (!('handles' in value)) return; + setManifest(value.handles); + const key = `${value.areaId}:${value.documentVersion}`; + if (loadedDocument.current === key) return; + loadedDocument.current = key; + sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion); + touch(); + }) + .catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`)); + }, [editMode, selectedSegmentId, setStatus, state]); + + return { + session: sessionRef.current, + manifest, + setManifest, + preview, + setPreview, + diagnostics, + setDiagnostics, + revision, + touch, + }; +} diff --git a/workbench/client/src/hooks/useOverrideDraft.ts b/workbench/client/src/hooks/useOverrideDraft.ts new file mode 100644 index 0000000..eff3973 --- /dev/null +++ b/workbench/client/src/hooks/useOverrideDraft.ts @@ -0,0 +1,37 @@ +import { useCallback, useState } from 'react'; +import { api } from '../lib/api'; +import type { Override, WorkbenchState } from '../types/state'; + +export function useOverrideDraft({ + state, + setState, + setStatus, +}: { + state?: WorkbenchState; + setState: (state: WorkbenchState) => void; + setStatus: (status: string) => void; +}) { + const [staged, setStaged] = useState([]); + const stage = useCallback((change: Override) => { + setStaged((current) => [...current.filter((item) => item.id !== change.id), change]); + }, []); + const save = useCallback(async () => { + if (!state || !staged.length) return true; + try { + const overrides = [ + ...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)), + ...staged, + ]; + const result = await api.overrides(overrides); + setState({ ...state, overrides: result.overrides }); + setStaged([]); + setStatus('已保存,点击“保存并重新生成”写入几何'); + return true; + } catch (error) { + setStatus((error as Error).message); + return false; + } + }, [setState, setStatus, staged, state]); + const clear = useCallback(() => setStaged([]), []); + return { staged, stage, save, clear }; +} diff --git a/workbench/client/src/hooks/useTrafficSignalDraft.ts b/workbench/client/src/hooks/useTrafficSignalDraft.ts new file mode 100644 index 0000000..dd8cfbc --- /dev/null +++ b/workbench/client/src/hooks/useTrafficSignalDraft.ts @@ -0,0 +1,175 @@ +import { useCallback, useRef, useState, type Dispatch, type SetStateAction } from 'react'; +import { haversineMeters, type Coordinate } from '../edit/meters'; +import type { GeoFeature, WorkbenchState } from '../types/state'; + +const limitPole = (feature: GeoFeature | undefined, coordinate: Coordinate): Coordinate => { + const stop: Coordinate | null = feature + ? [Number(feature.properties?.stop_lon), Number(feature.properties?.stop_lat)] + : null; + if (!stop || !stop.every(Number.isFinite)) return coordinate; + const distance = haversineMeters(stop, coordinate); + if (distance <= 40) return coordinate; + const ratio = 40 / distance; + return [stop[0] + (coordinate[0] - stop[0]) * ratio, stop[1] + (coordinate[1] - stop[1]) * ratio]; +}; + +const rotateFeatures = (features: GeoFeature[], uid: string, mastHeading: number): GeoFeature[] => { + const heading = ((mastHeading % 360) + 360) % 360; + return features.map((feature) => + feature.properties?.signal_uid === uid + ? { + ...feature, + properties: { + ...feature.properties, + mast_heading_deg: heading, + face_heading_deg: (((heading - 90) % 360) + 360) % 360, + }, + } + : feature, + ); +}; + +export function useTrafficSignalDraft({ + state, + setState, +}: { + state?: WorkbenchState; + setState: Dispatch>; +}) { + const [dirty, setDirty] = useState(false); + const draftRef = useRef(null); + const undoRef = useRef([]); + const redoRef = useRef([]); + const savedRef = useRef(null); + const moveActiveRef = useRef(false); + const rotateActiveRef = useRef(false); + + const update = useCallback( + async (features: GeoFeature[]) => { + if (state) undoRef.current.push(state.trafficSignals.assemblies.features); + redoRef.current = []; + draftRef.current = features; + setDirty(true); + setState((current) => + current + ? { + ...current, + trafficSignals: { + ...current.trafficSignals, + assemblies: { ...current.trafficSignals.assemblies, features }, + }, + } + : current, + ); + }, + [setState, state], + ); + + const move = useCallback( + (uid: string, coordinate: Coordinate) => { + setState((current) => { + if (!current) return current; + if (!moveActiveRef.current) { + undoRef.current.push(current.trafficSignals.assemblies.features); + redoRef.current = []; + moveActiveRef.current = true; + } + const source = current.trafficSignals.assemblies.features.find( + (feature) => feature.properties?.signal_uid === uid, + ); + const nextCoordinate = limitPole(source, coordinate); + return { + ...current, + trafficSignals: { + ...current.trafficSignals, + assemblies: { + ...current.trafficSignals.assemblies, + features: current.trafficSignals.assemblies.features.map((feature) => + feature.properties?.signal_uid === uid + ? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } } + : feature, + ), + }, + }, + }; + }); + setDirty(true); + }, + [setState], + ); + + const finishMove = useCallback( + (uid: string, coordinate: Coordinate) => { + if (!state) return; + const source = state.trafficSignals.assemblies.features.find((feature) => feature.properties?.signal_uid === uid); + const nextCoordinate = limitPole(source, coordinate); + draftRef.current = state.trafficSignals.assemblies.features.map((feature) => + feature.properties?.signal_uid === uid + ? { ...feature, geometry: { type: 'Point', coordinates: nextCoordinate } } + : feature, + ); + moveActiveRef.current = false; + setDirty(true); + }, + [state], + ); + + const rotate = useCallback( + (uid: string, mastHeading: number) => { + setState((current) => { + if (!current) return current; + if (!rotateActiveRef.current) { + undoRef.current.push(current.trafficSignals.assemblies.features); + redoRef.current = []; + rotateActiveRef.current = true; + } + return { + ...current, + trafficSignals: { + ...current.trafficSignals, + assemblies: { + ...current.trafficSignals.assemblies, + features: rotateFeatures(current.trafficSignals.assemblies.features, uid, mastHeading), + }, + }, + }; + }); + setDirty(true); + }, + [setState], + ); + + const finishRotate = useCallback( + (uid: string, mastHeading: number) => { + if (!state) return; + draftRef.current = rotateFeatures(state.trafficSignals.assemblies.features, uid, mastHeading); + rotateActiveRef.current = false; + setDirty(true); + }, + [state], + ); + + const reset = useCallback(() => { + draftRef.current = null; + undoRef.current = []; + redoRef.current = []; + moveActiveRef.current = false; + rotateActiveRef.current = false; + setDirty(false); + }, []); + + return { + dirty, + setDirty, + draftRef, + undoRef, + redoRef, + savedRef, + update, + move, + finishMove, + rotate, + finishRotate, + reset, + }; +}