refactor(workbench): split editor state and components

This commit is contained in:
que01 committed 2026-09-02 15:04:58 +08:00
1 parent caa3cb843f
commit 834470cfa1
23 files changed
+1219 -878

No files matched your search

@@ -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.
+8 -10
View File
@@ -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.
---
+10 -2
View File
@@ -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.
@@ -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.
+6 -6
View File
@@ -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 |
---
@@ -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.
+10 -1
View File
@@ -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.
+2
View File
@@ -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.
@@ -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": [
@@ -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."}
@@ -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 实例稳定性。
@@ -0,0 +1 @@
{"_example": "Fill with {\"file\": \"<path>\", \"reason\": \"<why>\"}. 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."}
@@ -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 触发重建。
@@ -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` 通过。
## 关键决定
- 本轮严格保持已有功能、交互和视觉效果。每项迁移必须以现有行为为基线;发现未确认问题只记录,不随重构修改。
@@ -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": {}
}
File diff suppressed because it is too large. Load diff
@@ -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 (
<form className="element-form">
<h2>车道转向箭头</h2>
<p className="form-context">第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。</p>
<label>
转向
<select value={maneuver} onChange={(event) => onChange(event.target.value, placementDistanceMeters)}>
{maneuverOptions.map(([optionValue, label]) => (
<option value={optionValue} key={optionValue}>
{label}
</option>
))}
</select>
</label>
<label>
距路口端(米)
<input
type="number"
min="0"
step="0.25"
value={placementDistanceMeters}
onChange={(event) => {
const next = Number(event.target.value);
if (Number.isFinite(next) && next >= 0) onChange(maneuver, next);
}}
/>
</label>
<p className="form-hint">保存并重新生成时会避开停止线、斑马线和车道端点。</p>
</form>
);
}
export function MarkingEditor({
marking,
stage,
}: {
marking: Record<string, unknown> | 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 (
<form
className="element-form"
onSubmit={(event) => {
event.preventDefault();
save();
}}
>
<h2>标线样式</h2>
<label>
样式
<select value={value} onChange={(event) => setValue(event.target.value)}>
<option value="yellow-dashed">黄色虚线</option>
<option value="white-dashed">白色虚线</option>
<option value="yellow-solid">黄色实线</option>
<option value="white-solid">白色实线</option>
{segment ? <option value="double-yellow-solid">双黄实线</option> : null}
</select>
</label>
<Button type="submit">暂存标线样式</Button>
</form>
);
}
export function SignalEditor({
state,
signal,
status,
update,
}: {
state: WorkbenchState;
signal?: GeoFeature;
status: (text: string) => void;
update: (features: GeoFeature[]) => Promise<void>;
}) {
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 (
<section className="element-form">
<h2>原生红绿灯</h2>
<label>
检查信号灯
<select value={selected} onChange={(event) => setSelected(event.target.value)}>
<option value="">选择设施</option>
{state.trafficSignals.assemblies.features.map((item) => (
<option key={String(item.properties?.signal_uid)} value={String(item.properties?.signal_uid)}>
{String(item.properties?.display_id || item.properties?.signal_uid)}
</option>
))}
</select>
</label>
{feature ? (
<>
<label>
灯杆经度
<input
type="number"
step="0.000001"
value={coordinates?.[0] ?? 0}
onChange={(event) => saveCoordinate(0, Number(event.target.value))}
/>
</label>
<label>
灯杆纬度
<input
type="number"
step="0.000001"
value={coordinates?.[1] ?? 0}
onChange={(event) => saveCoordinate(1, Number(event.target.value))}
/>
</label>
<label>
横杆方向(度)
<input
type="number"
value={Number(feature.properties?.mast_heading_deg || 0)}
onChange={(event) => saveField('mast_heading_deg', Number(event.target.value))}
/>
</label>
<label>
横杆长度(米)
<input
type="number"
value={Number(feature.properties?.mast_reach_m || 0)}
onChange={(event) => saveField('mast_reach_m', Number(event.target.value))}
/>
</label>
<label>
灯面朝向(度)
<input type="number" value={Number(feature.properties?.face_heading_deg || 0)} readOnly />
</label>
<label>
相位组
<select
value={Number(feature.properties?.phase_group || 0)}
onChange={(event) => saveField('phase_group', Number(event.target.value))}
>
<option value={0}>组 0</option>
<option value={1}>组 1</option>
</select>
</label>
<label>
高程偏移(米)
<input
type="number"
step="0.1"
min="-20"
max="100"
value={Number(feature.properties?.z_offset_m || 0)}
onChange={(event) => saveField('z_offset_m', Number(event.target.value))}
/>
</label>
<p className="form-hint">
控制进口:{String(feature.properties?.approach_id || '未绑定')}
<br />
来源道路:{String(feature.properties?.source_way_id || '未绑定')}
</p>
<label>
<input
type="checkbox"
checked={Boolean(feature.properties?.enabled)}
onChange={(event) => saveField('enabled', event.target.checked)}
/>{' '}
启用
</label>
<Button
onClick={() =>
void update(state.trafficSignals.assemblies.features.filter((item) => item !== feature)).then(() => {
setSelected('');
status('红绿灯已删除');
})
}
>
删除信号灯
</Button>
</>
) : null}
</section>
);
}
export function Candidates({ state, onAccept }: { state: WorkbenchState; onAccept: (index: number) => void }) {
const candidates = state.debug?.junctionCandidates || [];
if (!candidates.length) return null;
return (
<section>
<hr />
<h2>复杂路口候选(debug)</h2>
{candidates.map((candidate) => (
<Button key={candidate.id} onClick={() => onAccept(candidate.index)}>
加入候选 #{candidate.index}({candidate.nodeCount} 节点,{candidate.diameterMeters} 米)
</Button>
))}
</section>
);
}
@@ -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<WorkbenchState>;
}) {
const [file, setFile] = useState<File>();
const [busy, setBusy] = useState(false);
return (
<section className="import-screen">
<form
onSubmit={async (event) => {
event.preventDefault();
if (!file) return;
setBusy(true);
try {
await onImport(file);
} catch (error) {
console.error(error);
} finally {
setBusy(false);
}
}}
>
<h1>导入 OSM 地图</h1>
<p>{status}</p>
<input
type="file"
accept=".osm,application/xml,text/xml"
onChange={(event) => setFile(event.target.files?.[0])}
required
/>
<Button type="submit" disabled={!file || busy}>
<Upload size={16} /> {busy ? '正在导入并编译...' : '导入并编译'}
</Button>
</form>
</section>
);
}
@@ -0,0 +1,36 @@
const metrics = [
['nativeRoadCount', '方向道路'],
['nativeRoadSurfaceFeatures', '道路面'],
['nativeJunctionSurfaceFeatures', '路口面'],
['nativeCenterLineFeatures', '道路中心线'],
['nativeConnectorFeatures', '连接路径'],
['nativeCrosswalkFeatures', '斑马线'],
['nativeVehicleStopLineFeatures', '停止线'],
['unconnectedInteriorRoadEnds', '未连接端点'],
] as const;
export function Overview({ comparison }: { comparison: Record<string, unknown> }) {
const severity = comparison.diagnosticsBySeverity as Record<string, number> | undefined;
return (
<section className="overview">
<div className="overview-grid">
{metrics.map(([key, label]) => (
<div key={key}>
<span>{label}</span>
<strong>{Number(comparison[key] || 0).toLocaleString('zh-CN')}</strong>
</div>
))}
</div>
{severity && (
<div className="overview-diagnostics">
<span>编译诊断</span>
{Object.entries(severity).map(([level, count]) => (
<strong key={level}>
{level === 'error' ? '错误' : level === 'warning' ? '警告' : '提示'} {count}
</strong>
))}
</div>
)}
</section>
);
}
@@ -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<string, unknown> | 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<void>;
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<typeof open>) => () => setOpen((current) => (current === name ? null : name));
const selectedLabel =
element?.kind === 'lane-maneuver'
? `第 ${laneIndex(element.laneId)} 车道`
: marking
? '已选标线或设施'
: road
? label(road)
: '未选择对象';
return (
<section className="workbench-inspector">
<div className="inspector-summary">
<span>编辑工作台</span>
<strong>{selectedLabel}</strong>
<small>{staged.length ? `已暂存 ${staged.length} 项修改` : '没有待保存的覆盖修改'}</small>
</div>
<InspectorSection
title="道路"
summary={road ? `${road.laneCount} 车道` : '选择道路'}
open={open === 'road'}
onToggle={section('road')}
>
{road ? (
<form
onSubmit={(event) => {
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>道路</label>
<output>
{label(road)}({direction(road)})
</output>
<output>
{movements.length
? `已识别 ${movements.length} 个行驶动作,${movements.filter((item) => item.geometryPublished).length} 条已绘制路径`
: '当前方向没有已识别的行驶动作'}
</output>
<label>
本方向道路宽度(米)
<input
type="number"
min="1"
step="0.01"
value={width}
onChange={(event) => setWidth(Number(event.target.value))}
/>
</label>
<label>
本方向车道数
<input
type="number"
min="1"
step="1"
value={lanes}
onChange={(event) => setLanes(Number(event.target.value))}
/>
</label>
<label>
<input type="checkbox" checked={left} onChange={(event) => setLeft(event.target.checked)} />{' '}
左侧有路缘与步行带
</label>
<label>
<input type="checkbox" checked={right} onChange={(event) => setRight(event.target.checked)} />{' '}
右侧有路缘与步行带
</label>
<Button type="submit">暂存本道路修改</Button>
</form>
) : (
<p>点击道路、车道、标线、转向路径或路口面以查看详情。</p>
)}
{children}
</InspectorSection>
<InspectorSection
title="元素"
summary={element ? selectedLabel : '箭头、标线与信号'}
open={open === 'element'}
onToggle={section('element')}
>
<LaneManeuverEditor
element={element}
value={
element?.kind === 'lane-maneuver'
? (session
?.constraints()
.find(
(item) =>
item.kind === 'lane-maneuver' &&
item.anchor.type === 'lane' &&
item.anchor.laneId === element.laneId,
)?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined)
: undefined
}
onChange={onLaneManeuverChange}
/>
<MarkingEditor marking={marking} stage={stage} />
<SignalEditor state={state} signal={signal} status={status} update={updateSignal} />
</InspectorSection>
<InspectorSection
title="连接"
summary={road ? `${movements.length} 个行驶动作` : '选择道路'}
open={open === 'connections'}
onToggle={section('connections')}
>
{road ? (
<div className="connections-list">
{state.compiled.model.connections
.filter((connection) => connection.fromEndpointId === endpoint?.id)
.map((connection) => (
<label key={connection.id}>
<input
type="checkbox"
checked={effective(`连接:${connection.id}`, connection.enabled)}
onChange={(event) =>
stage({
id: `连接:${connection.id}`,
kind: 'junction-connection',
fromEndpointId: connection.fromEndpointId,
toEndpointId: connection.toEndpointId,
enabled: event.target.checked,
})
}
/>{' '}
{connection.id}
</label>
))}
{movements.map((movement) => (
<label key={movement.id}>
<input
type="checkbox"
checked={effective(`车道连接:${movement.fromLaneId}->${movement.toLaneId}`, true)}
onChange={(event) =>
stage({
id: `车道连接:${movement.fromLaneId}->${movement.toLaneId}`,
kind: 'lane-connection',
fromLaneId: movement.fromLaneId,
toLaneId: movement.toLaneId,
enabled: event.target.checked,
})
}
/>{' '}
{movement.turn}:第 {laneIndex(movement.fromLaneId)} 车道 → 第 {laneIndex(movement.toLaneId)} 车道(
{movement.geometryStatus || 'connector'})
</label>
))}
</div>
) : (
<p className="form-context">选择一条道路以管理其驶入路口的连接。</p>
)}
{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 ? (
<Button
key={candidate.roadId}
onClick={() => {
stage({
id: `连接:connection:${endpoint.id}:${targetEndpoint.id}`,
kind: 'junction-connection',
fromEndpointId: endpoint.id,
toEndpointId: targetEndpoint.id,
enabled: true,
});
status('手工连接已暂存;保存并重新生成后会出现转向路径');
}}
>
新增:{label(target)}({candidate.distanceMeters} 米)
</Button>
) : null;
})}
</InspectorSection>
<InspectorSection title="高级" summary="候选与来源" open={open === 'advanced'} onToggle={section('advanced')}>
<Candidates state={state} onAccept={onAcceptCandidate} />
<details>
<summary>技术详情与来源</summary>
<pre>
{JSON.stringify(
road ? { OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 原始标签: road.tags } : marking,
null,
2,
)}
</pre>
</details>
</InspectorSection>
</section>
);
}
@@ -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<HandleManifest | null>(null);
const [preview, setPreview] = useState<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
const [diagnostics, setDiagnostics] = useState<EditDiagnostic[]>([]);
const [revision, setRevision] = useState(0);
const sessionRef = useRef<EditSession | null>(null);
const loadedDocument = useRef<string | null>(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,
};
}
@@ -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<Override[]>([]);
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 };
}
@@ -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<SetStateAction<WorkbenchState | undefined>>;
}) {
const [dirty, setDirty] = useState(false);
const draftRef = useRef<GeoFeature[] | null>(null);
const undoRef = useRef<GeoFeature[][]>([]);
const redoRef = useRef<GeoFeature[][]>([]);
const savedRef = useRef<GeoFeature[] | null>(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,
};
}