From 38ea779d9b6fc726d2454fa58bd9b08d35d18175 Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 4 Sep 2026 17:09:32 +0800 Subject: [PATCH] feat: add complex junction selection markers --- .../09-04-complex-junction-toggle/check.jsonl | 3 + .../09-04-complex-junction-toggle/design.md | 26 +++ .../implement.jsonl | 4 + .../implement.md | 16 ++ .../09-04-complex-junction-toggle/prd.md | 44 +++++ .../09-04-complex-junction-toggle/task.json | 26 +++ bin/road-workbench.js | 2 +- workbench/client/app.js | 10 +- workbench/client/src/App.tsx | 52 +++-- workbench/client/src/components/MapCanvas.tsx | 56 ++++++ .../src/components/WorkbenchInspector.tsx | 5 +- .../client/src/junction/JunctionWorkspace.tsx | 178 +++++++++++++++++- .../client/src/junction/hotspots.test.ts | 97 +++++++++- workbench/client/src/junction/hotspots.ts | 78 +++++++- workbench/client/src/lib/api.ts | 9 +- workbench/client/src/styles.css | 70 +++++++ workbench/client/src/types/state.ts | 8 +- workbench/server.js | 49 ++++- 18 files changed, 685 insertions(+), 48 deletions(-) create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/check.jsonl create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/design.md create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/implement.jsonl create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/implement.md create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/prd.md create mode 100644 .trellis/tasks/09-04-complex-junction-toggle/task.json diff --git a/.trellis/tasks/09-04-complex-junction-toggle/check.jsonl b/.trellis/tasks/09-04-complex-junction-toggle/check.jsonl new file mode 100644 index 0000000..dd59389 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/check.jsonl @@ -0,0 +1,3 @@ +{"file":".trellis/spec/backend/direct-edit-api.md","reason":"质量检查需覆盖 preview/save 的版本保护、原子写入及编译状态一致性。"} +{"file":".trellis/spec/frontend/direct-edit-client.md","reason":"质量检查需确认 preview layer、baseline 和普通路口编辑行为不回归。"} +{"file":".trellis/spec/guides/cross-layer-thinking-guide.md","reason":"质量检查需验证候选配置从 API 到编译和 UI 的完整往返。"} diff --git a/.trellis/tasks/09-04-complex-junction-toggle/design.md b/.trellis/tasks/09-04-complex-junction-toggle/design.md new file mode 100644 index 0000000..6b024d4 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/design.md @@ -0,0 +1,26 @@ +# 技术设计 + +## 边界 + +- 编译层复用 `src/compile/complex-junction.js` 与 `src/compile/native-road.js` 的既有 cluster 几何生成逻辑,不复制几何算法。 +- 服务层负责读取候选、生成目标 cluster 配置、预览编译和持久化;保存遵守现有 revision/document 版本保护与原子写入约束。 +- 前端只在 JunctionTools 独立页面消费候选和 cluster 状态,复用现有地图图层工厂与预览层,不污染普通路口 baseline。 + +## 数据流 + +1. `/api/edit-state` 或现有诊断数据提供候选 cluster 标识、节点集合、道路摘要、建议核心半径及当前启用状态。 +2. 独立页面展示状态;用户点击启用后创建内存 draft,不立即写文件。 +3. 预览请求携带 draft cluster 配置,服务端在临时编译上下文中生成局部复杂路口图层并返回 preview 序列号。 +4. 放弃丢弃 draft 并恢复 baseline;保存经版本校验后原子写入 `nativeRoad.junctionTemplates.clusters`,随后触发正式编译。 +5. 刷新重新从 edit-state/编译状态读取持久化配置。 + +## 兼容性与回滚 + +- 没有启用配置时保持现有普通路口输出字节和交互不变。 +- 保存失败或版本冲突不改变活动配置;预览失败只清除预览并保留 draft 可重试。 +- 不把候选诊断直接转换为启用配置,避免大范围几何变化。 + +## 取舍 + +- 首版只提供独立页面入口,避免主地图状态同步和误操作复杂度。 +- 首版复杂参数只读,先验证渲染质量;后续再以独立约束模型开放编辑。 diff --git a/.trellis/tasks/09-04-complex-junction-toggle/implement.jsonl b/.trellis/tasks/09-04-complex-junction-toggle/implement.jsonl new file mode 100644 index 0000000..3aedf32 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/implement.jsonl @@ -0,0 +1,4 @@ +{"file":".trellis/spec/backend/direct-edit-api.md","reason":"复用现有预览、版本校验、原子保存和编译后状态契约。"} +{"file":".trellis/spec/frontend/direct-edit-client.md","reason":"保证复杂路口预览不覆盖 baseline,并沿用 JunctionTools 的状态与预览边界。"} +{"file":".trellis/spec/guides/cross-layer-thinking-guide.md","reason":"该功能跨编译、服务和前端,需要按数据流和契约检查。"} +{"file":".trellis/spec/guides/code-reuse-thinking-guide.md","reason":"候选状态、预览图层和保存逻辑必须复用现有实现,避免第二套契约。"} diff --git a/.trellis/tasks/09-04-complex-junction-toggle/implement.md b/.trellis/tasks/09-04-complex-junction-toggle/implement.md new file mode 100644 index 0000000..4d02708 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/implement.md @@ -0,0 +1,16 @@ +# 执行清单 + +1. 梳理现有候选诊断、cluster 配置读取、编辑保存和编译入口,确定最小 API 接口。 +2. 后端增加候选 cluster 状态投影及 preview/save 所需的专用数据契约,复用现有版本校验和原子保存。 +3. 前端在独立 JunctionTools 页面增加普通/复杂状态区、启用、预览、放弃、保存和只读提示。 +4. 接入局部复杂路口图层预览,确保 baseline 图层不被覆盖,且只影响目标 cluster。 +5. 为候选样本补充后端单测、HTTP 集成测试和前端/E2E 状态流测试。 +6. 运行类型检查、构建、相关测试和完整质量检查;修复回归后再提交。 + +验证命令: + +- `python3 ./.trellis/scripts/task.py validate 09-04-complex-junction-toggle` +- `npm run test` +- `npm run build` + +回滚点:API 契约、cluster 配置写入、JunctionTools 状态区和 preview 图层分别可独立回退;不得回退用户已有的普通路口编辑修复。 diff --git a/.trellis/tasks/09-04-complex-junction-toggle/prd.md b/.trellis/tasks/09-04-complex-junction-toggle/prd.md new file mode 100644 index 0000000..40a22f3 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/prd.md @@ -0,0 +1,44 @@ +# 复杂路口手动切换与独立浏览 + +## Goal + +让用户可以针对 `枫树二路.osm` 中的复杂路口候选,在独立 JunctionTools 页面中将该候选从普通路口渲染切换为 `complex-junction-v1`,通过局部预览确认效果,并可放弃或保存。首版解决复杂路口当前普通渲染难看的问题,同时保留普通路口既有编辑能力。 + +## Background and Confirmed Facts + +- `/Users/que01/Desktop/枫树二路.osm` 当前编译会产生多组 `complex-junction-candidate` 诊断。 +- 首个验证候选为节点 `8005332807、8024512135、8024512145、8024512147、8613058676`,节点直径约 41.2m,建议核心半径约 32m,关联道路为硃山湖大道、枫树二路。 +- 复杂路口几何由 `src/compile/complex-junction.js` 生成;只有 `nativeRoad.junctionTemplates.enabled=true` 且存在对应 cluster 配置时才会启用。 +- `cluster` 当前在 `src/compile/direct-edit-solver.js` 与 JunctionTools 中为只读,不能通过解除前端限制直接编辑。 +- 候选检测是 advisory,只产生 `complex-junction-candidate` 诊断,不会自动改变几何。 + +## In Scope + +1. 候选复杂路口可进入独立 JunctionTools 页面。 +2. 页面显示当前渲染模式:普通路口或复杂路口;普通模式提供“启用复杂路口渲染”入口。 +3. 切换使用候选诊断提供的 cluster 节点和建议核心半径,并只影响该 cluster。 +4. 切换后提供局部复杂路口几何预览,支持放弃、保存;保存后重新编译,刷新仍保持状态。 +5. 复杂路口页面保持只读参数状态,并明确提示首版暂不支持复杂路口几何拖拽编辑。 +6. 切换入口只放在独立页面状态区,不在主地图候选标记上提供快捷切换。 + +## Out of Scope + +- 不根据候选自动启用或静默切换。 +- 不开放复杂路口核心半径、进口宽度、收口距离、圆角等拖拽编辑。 +- 不修改 OSM 拓扑,不创建或删除道路、信号灯、斑马线、停止线等设施。 +- 不跨多个 cluster 联合编辑。 +- 不改变普通路口现有 JunctionTools 行为。 + +## Acceptance Criteria + +- [ ] 从 `枫树二路.osm` 的目标候选可进入独立 JunctionTools 页面。 +- [ ] 页面明确显示“当前按普通路口渲染”,并提供“启用复杂路口渲染”。 +- [ ] 预览只改变目标 cluster 的局部几何,其他路口保持不变。 +- [ ] 放弃后恢复普通路口渲染;保存并刷新后仍显示复杂路口渲染。 +- [ ] 复杂路口页面不显示可编辑普通 node 控件,未实现的参数编辑明确为只读。 +- [ ] 普通路口既有测试、复杂路口相关测试、类型检查和构建通过。 + +## Risks and Deferred Decisions + +- 复杂 cluster 配置写入现有 `nativeRoad.junctionTemplates.clusters` 语义;若现有保存 API 不能原子更新该配置,需要在 API 层增加最小专用操作,不能从前端直接写派生 GeoJSON。 +- 自动识别和自动切换留待首版验证后另行商议。 diff --git a/.trellis/tasks/09-04-complex-junction-toggle/task.json b/.trellis/tasks/09-04-complex-junction-toggle/task.json new file mode 100644 index 0000000..0a0b140 --- /dev/null +++ b/.trellis/tasks/09-04-complex-junction-toggle/task.json @@ -0,0 +1,26 @@ +{ + "id": "complex-junction-toggle", + "name": "complex-junction-toggle", + "title": "复杂路口手动切换与独立浏览", + "description": "", + "status": "in_progress", + "dev_type": null, + "scope": null, + "package": null, + "priority": "P2", + "creator": "dingkang", + "assignee": "dingkang", + "createdAt": "2026-09-04", + "completedAt": null, + "branch": null, + "base_branch": "main", + "worktree_path": null, + "commit": null, + "pr_url": null, + "subtasks": [], + "children": [], + "parent": null, + "relatedFiles": [], + "notes": "", + "meta": {} +} \ No newline at end of file diff --git a/bin/road-workbench.js b/bin/road-workbench.js index 720c6f6..81b5eef 100755 --- a/bin/road-workbench.js +++ b/bin/road-workbench.js @@ -11,4 +11,4 @@ const inputFile = index >= 0 && args[index + 1] ? path.resolve(args[index + 1]) const input = inputFile ? JSON.parse(fs.readFileSync(inputFile, 'utf8')) : null; const portIndex = args.indexOf('--port'); const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 8787; -startWorkbench({ input, inputFile, repoRoot: path.resolve(__dirname, '..'), port }); +startWorkbench({ input, inputFile, repoRoot: path.resolve(__dirname, '..'), port, debug: args.includes('--debug') }); diff --git a/workbench/client/app.js b/workbench/client/app.js index c928191..3c933fe 100644 --- a/workbench/client/app.js +++ b/workbench/client/app.js @@ -690,7 +690,7 @@ function selectJunctionCandidate(feature) { form.hidden = true; hint.hidden = false; selectedJunctionPanel.hidden = true; - hint.textContent = `复杂路口候选 #${candidate.index}:${candidate.nodeCount} 个节点,直径 ${candidate.diameterMeters} 米。下方是可直接粘贴到 config 的片段。`; + hint.textContent = `当前路口附近检测到 ${candidate.nodeCount} 个相邻节点,范围约 ${candidate.diameterMeters} 米。下方是可直接粘贴到 config 的片段。`; evidence.textContent = JSON.stringify( { 说明: '复制到区域配置文件的 nativeRoad.junctionTemplates.clusters 数组,然后重新编译', @@ -714,7 +714,7 @@ function selectJunctionCandidate(feature) { 2, ); renderCandidateAction(candidate); - message(`已选中复杂路口候选 #${candidate.index}`); + message('已选中当前路口附近的复杂路口候选'); } // The accept button lives beside the snippet so the manual path stays available // if the write is refused; both describe the same cluster. @@ -722,15 +722,15 @@ function renderCandidateAction(candidate) { candidateAction.replaceChildren(); const button = document.createElement('button'); button.type = 'button'; - button.textContent = `把候选 #${candidate.index} 加入配置并重新编译`; + button.textContent = '把当前候选路口加入配置并重新编译'; button.onclick = async () => { button.disabled = true; - message(`正在把候选 #${candidate.index} 写入区域配置...`); + message('正在把当前候选路口写入区域配置...'); try { const response = await fetch('/api/junction-clusters', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ index: candidate.index }), + body: JSON.stringify({ candidateId: candidate.id }), cache: 'no-store', }); const result = await response.json(); diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index 38999b6..d00f6fb 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -54,7 +54,7 @@ import { Button } from './ui/button'; import type { GeoFeature, GeoJson, Road, WorkbenchState } from './types/state'; import type { LayerName } from './map/layers'; import type { JunctionRef } from './junction/hotspots'; -import { junctionDescriptors, hotspotAt } from './junction/hotspots'; +import { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots'; import { JunctionWorkspace } from './junction/JunctionWorkspace'; import { localJunctionPreview, localJunctionState } from './junction/local-state'; import { @@ -211,6 +211,9 @@ function App() { : preview, [junctionDescriptor, junctionRoute, preview, state], ); + const [junctionNodeMarkers, setJunctionNodeMarkers] = useState< + Array<{ coordinate: Coordinate; label: string; selected: boolean }> + >([]); // A deep link starts without a map click, so it has no selected approach from // which the existing manifest loader can scope its request. Pick the first // descriptor-owned approach here as well as in the click path; this is a @@ -891,6 +894,7 @@ function App() { discardJunctionDraft(); } else return; } + setJunctionNodeMarkers([]); window.history.pushState({}, '', '/'); setJunctionRoute(null); }; @@ -991,6 +995,7 @@ function App() { ); })}
+
待检查问题({diagnostics.length})
@@ -1036,6 +1041,7 @@ function App() { visible={layers} scene={scene} junctionHotspots={junctionHotspots} + junctionNodeMarkers={junctionNodeMarkers} onJunctionHotspot={(ref: JunctionRef, _coordinate, descriptor) => { openJunction(ref); const approachRoad = descriptor.approachRoadIds @@ -1128,16 +1134,6 @@ function App() { session={session} onLaneManeuverChange={applyLaneManeuver} updateSignal={updateSignal} - onAcceptCandidate={(index) => - void api - .acceptJunctionCandidate(index) - .then((next) => { - setState(next); - signalSavedRef.current = next.trafficSignals.assemblies.features; - setStatus(`已加入 ${next.added.id} 并重新编译`); - }) - .catch((error: Error) => setStatus(error.message)) - } > {editMode ? ( { + const candidate = candidateForJunction(state, junctionDescriptor); + if (!candidate) { + setStatus('候选已过期,请刷新后重试。'); + return; + } + void api + .acceptJunctionCandidate(candidate.id, selectedNodeIds) + .then((next) => { + setState(next); + signalSavedRef.current = next.trafficSignals.assemblies.features; + const ref = { type: 'cluster' as const, id: next.added.id }; + window.history.replaceState({}, '', `/junction/cluster/${encodeURIComponent(ref.id)}`); + setJunctionRoute(ref); + setStatus('已启用复杂路口渲染'); + }) + .catch((error: Error) => setStatus(`启用失败:${error.message}`)); + } + : undefined + } + onUpdateComplexNodes={(nodeIds) => { + if (junctionDescriptor.ref.type !== 'cluster') return; + void api + .updateJunctionCluster(junctionDescriptor.ref.id, nodeIds) + .then((next) => { + setState(next); + signalSavedRef.current = next.trafficSignals.assemblies.features; + setStatus('已更新复杂路口参与节点并重新编译'); + }) + .catch((error: Error) => setStatus(`更新失败:${error.message}`)); + }} + onCandidateMarkersChange={setJunctionNodeMarkers} onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))} onDiscard={discardJunctionDraft} onSave={() => diff --git a/workbench/client/src/components/MapCanvas.tsx b/workbench/client/src/components/MapCanvas.tsx index 501e268..cdac837 100644 --- a/workbench/client/src/components/MapCanvas.tsx +++ b/workbench/client/src/components/MapCanvas.tsx @@ -13,6 +13,7 @@ import CircleStyle from 'ol/style/Circle'; import Fill from 'ol/style/Fill'; import Stroke from 'ol/style/Stroke'; import Style from 'ol/style/Style'; +import Text from 'ol/style/Text'; import { createEmpty, extend } from 'ol/extent'; import { click } from 'ol/events/condition'; import type { GeoJson, Road, WorkbenchState } from '../types/state'; @@ -76,6 +77,7 @@ interface Props { focusJunctionId?: string | null; junctionHotspots?: boolean; onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void; + junctionNodeMarkers?: Array<{ coordinate: Coordinate; label: string; selected: boolean }>; } export function MapCanvas({ state, @@ -111,6 +113,7 @@ export function MapCanvas({ focusJunctionId = null, junctionHotspots = true, onJunctionHotspot, + junctionNodeMarkers = [], }: Props) { const target = useRef(null); const mapRef = useRef(null); @@ -124,6 +127,7 @@ export function MapCanvas({ const laneSelectionLayerRef = useRef | null>(null); const signalTransformSourceRef = useRef(null); const signalTransformLayerRef = useRef | null>(null); + const junctionNodeMarkerSourceRef = useRef(null); const laneSelectionFeaturesRef = useRef([]); const laneSelectionAnchorRef = useRef(null); const hiddenMarkingIdsRef = useRef>(new Set()); @@ -223,6 +227,28 @@ export function MapCanvas({ }); signalTransformSourceRef.current = signalTransformSource; signalTransformLayerRef.current = signalTransformLayer; + const junctionNodeMarkerSource = new VectorSource(); + const junctionNodeMarkerLayer = new VectorLayer({ + source: junctionNodeMarkerSource, + zIndex: 110, + style: (feature) => { + const selected = feature.get('junction_node_selected') === true; + const color = selected ? '#0e7490' : '#64748b'; + return new Style({ + image: new CircleStyle({ + radius: 12, + fill: new Fill({ color }), + stroke: new Stroke({ color: '#fff', width: 2 }), + }), + text: new Text({ + text: String(feature.get('junction_node_label') || ''), + fill: new Fill({ color: '#fff' }), + font: '700 12px sans-serif', + }), + }); + }, + }); + junctionNodeMarkerSourceRef.current = junctionNodeMarkerSource; // Direct-edit sources are always installed; visibility and hit testing follow // the in-page browser/edit switch. const handleLayer = new EditHandleLayer(); @@ -241,6 +267,7 @@ export function MapCanvas({ ...(previewLayer ? previewLayer.all() : []), laneSelectionLayer, signalTransformLayer, + junctionNodeMarkerLayer, ...(handleLayer ? [handleLayer.layer] : []), ...(ghost ? [ghost.layer] : []), ], @@ -418,12 +445,41 @@ export function MapCanvas({ select.on('select', listener); return () => { select.un('select', listener); + junctionNodeMarkerSourceRef.current = null; map.setTarget(undefined); delete (target.current as HTMLDivElement & { __roadWorkbenchMap?: Map })?.__roadWorkbenchMap; }; // Map construction must be once per mounted canvas; state changes update sources below. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + useEffect(() => { + const source = junctionNodeMarkerSourceRef.current; + if (!source) return; + source.clear(); + source.addFeatures( + junctionNodeMarkers.map((marker) => { + const feature = new Feature({ geometry: new Point(fromLonLat(marker.coordinate)) }); + feature.set('junction_node_label', marker.label); + feature.set('junction_node_selected', marker.selected); + return feature; + }), + ); + const map = mapRef.current; + if (map && junctionNodeMarkers.length) { + const extent = createEmpty(); + junctionNodeMarkers.forEach((marker) => { + const point = fromLonLat(marker.coordinate); + extend(extent, [point[0], point[1], point[0], point[1]]); + }); + if (Number.isFinite(extent[0])) { + map.getView().fit(extent, { + padding: [96, 520, 96, 96], + maxZoom: 20, + duration: 180, + }); + } + } + }, [junctionNodeMarkers]); useEffect(() => { const layers = layersRef.current; const map = mapRef.current; diff --git a/workbench/client/src/components/WorkbenchInspector.tsx b/workbench/client/src/components/WorkbenchInspector.tsx index 638f781..629f6d5 100644 --- a/workbench/client/src/components/WorkbenchInspector.tsx +++ b/workbench/client/src/components/WorkbenchInspector.tsx @@ -1,5 +1,5 @@ import { useEffect, useState, type ReactNode } from 'react'; -import { Candidates, LaneManeuverEditor, MarkingEditor, SignalEditor } from './ElementEditors'; +import { LaneManeuverEditor, MarkingEditor, SignalEditor } from './ElementEditors'; import { InspectorSection } from './InspectorSection'; import type { EditSession } from '../edit/session'; import type { ElementSelection } from '../edit/element'; @@ -19,7 +19,6 @@ export function WorkbenchInspector({ session, onLaneManeuverChange, updateSignal, - onAcceptCandidate, children, }: { road: Road | null; @@ -32,7 +31,6 @@ export function WorkbenchInspector({ session: EditSession | null; onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void; updateSignal: (features: GeoFeature[]) => Promise; - onAcceptCandidate: (index: number) => void; children?: ReactNode; }) { const [width, setWidth] = useState(0); @@ -258,7 +256,6 @@ export function WorkbenchInspector({ })} -
技术详情与来源
diff --git a/workbench/client/src/junction/JunctionWorkspace.tsx b/workbench/client/src/junction/JunctionWorkspace.tsx
index 6a78b07..fbb4253 100644
--- a/workbench/client/src/junction/JunctionWorkspace.tsx
+++ b/workbench/client/src/junction/JunctionWorkspace.tsx
@@ -1,5 +1,5 @@
-import { useMemo } from 'react';
-import type { JunctionDescriptor } from './hotspots';
+import { useEffect, useMemo, useState } from 'react';
+import { candidateForJunction, type JunctionDescriptor } from './hotspots';
 import { canEditJunction, type JunctionSession } from './workspace';
 import { Button } from '../ui/button';
 import { ParameterPanel } from '../components/ParameterPanel';
@@ -25,6 +25,9 @@ interface Props {
   onSave: () => void;
   editMode?: boolean;
   onEnableEdit?: () => void;
+  onEnableComplex?: (nodeIds: string[]) => void;
+  onUpdateComplexNodes?: (nodeIds: string[]) => void;
+  onCandidateMarkersChange?: (markers: Array<{ coordinate: Coordinate; label: string; selected: boolean }>) => void;
   handles?: EditHandle[];
   onDraft?: (handle: EditHandle, value: number) => void;
   onDraftGroup?: (handles: EditHandle[], value: number) => void;
@@ -52,6 +55,9 @@ export function JunctionWorkspace({
   onSave,
   editMode = false,
   onEnableEdit,
+  onEnableComplex,
+  onUpdateComplexNodes,
+  onCandidateMarkersChange,
   diagnostics = [],
   facilitySummary = { crosswalks: 0, stopLines: 0, signals: 0 },
   state,
@@ -72,6 +78,90 @@ export function JunctionWorkspace({
   onUpdateSignal,
 }: Props) {
   const editable = useMemo(() => canEditJunction(descriptor), [descriptor]);
+  const complexEnabled = useMemo(() => {
+    const nodes = new Set(descriptor.nodeIds.map(String));
+    return Boolean(
+      state?.debug?.junctionClusters?.some(
+        (cluster) =>
+          (descriptor.ref.type === 'cluster' && cluster.id === descriptor.ref.id) ||
+          (cluster.nodeIds.length === nodes.size && cluster.nodeIds.every((nodeId) => nodes.has(String(nodeId)))),
+      ),
+    );
+  }, [descriptor, state?.debug?.junctionClusters]);
+  const candidate = useMemo(() => {
+    return candidateForJunction(state, descriptor);
+  }, [descriptor, state]);
+  const configuredNodeIds = useMemo(
+    () =>
+      state?.debug?.junctionClusters?.find((cluster) => cluster.id === descriptor.ref.id)?.nodeIds.map(String) || [],
+    [descriptor.ref.id, state?.debug?.junctionClusters],
+  );
+  const [selectedCandidateNodes, setSelectedCandidateNodes] = useState([]);
+  const [candidateNodePickerOpen, setCandidateNodePickerOpen] = useState(false);
+  const candidateNodes = useMemo(
+    () =>
+      (candidate?.nodeIds?.length
+        ? candidate.nodeIds
+        : descriptor.nodeIds.length
+          ? descriptor.nodeIds
+          : configuredNodeIds
+      ).map(String),
+    [candidate?.nodeIds, configuredNodeIds, descriptor.nodeIds],
+  );
+  const activeCandidateNodes = selectedCandidateNodes.filter((nodeId) => candidateNodes.includes(nodeId)).length
+    ? selectedCandidateNodes.filter((nodeId) => candidateNodes.includes(nodeId))
+    : candidateNodes;
+  const candidateRoadNames = useMemo(() => {
+    if (!state) return [];
+    const nodeIds = new Set((candidate?.nodeIds || descriptor.nodeIds).map(String));
+    return [
+      ...new Set(
+        state.compiled.model.roads
+          .filter((road) => road.sourceNodeIds.some((nodeId) => nodeIds.has(String(nodeId))))
+          .map((road) => junctionRoadName(road, state.compiled.model.roads)),
+      ),
+    ];
+  }, [candidate, descriptor.nodeIds, state]);
+  const candidateNodeLabels = useMemo(() => {
+    if (!state) return [];
+    return candidateNodes.map((nodeId, index) => {
+      const names = [
+        ...new Set(
+          state.compiled.model.roads
+            .filter((road) => road.sourceNodeIds.some((item) => String(item) === nodeId))
+            .map((road) => junctionRoadName(road, state.compiled.model.roads)),
+        ),
+      ];
+      return { nodeId, label: `路口点 ${index + 1}${names.length ? ` · ${names.join('、')}` : ''}` };
+    });
+  }, [candidate, candidateNodes, state]);
+  useEffect(() => {
+    if (!onCandidateMarkersChange || !state || !candidateNodePickerOpen) {
+      onCandidateMarkersChange?.([]);
+      return;
+    }
+    const selectedIds = new Set(activeCandidateNodes);
+    onCandidateMarkersChange(
+      candidateNodes.flatMap((nodeId, index) => {
+        const points = state.compiled.model.endpoints
+          .filter((endpoint) => String(endpoint.nodeId) === nodeId)
+          .map((endpoint) => endpoint.coordinate);
+        return points.length
+          ? [
+              {
+                coordinate: [
+                  points.reduce((sum, point) => sum + point[0], 0) / points.length,
+                  points.reduce((sum, point) => sum + point[1], 0) / points.length,
+                ] as Coordinate,
+                label: String(index + 1),
+                selected: selectedIds.has(nodeId),
+              },
+            ]
+          : [];
+      }),
+    );
+    return () => onCandidateMarkersChange([]);
+  }, [activeCandidateNodes, candidateNodePickerOpen, candidateNodes, onCandidateMarkersChange, state]);
   const facilities = useMemo(
     () => (state ? junctionFacilities(state, descriptor.nodeIds, roads) : []),
     [descriptor.nodeIds, roads, state],
@@ -84,11 +174,15 @@ export function JunctionWorkspace({
             JunctionTools
           

- {editable - ? editMode - ? '可编辑路口几何参数' - : '当前为浏览模式,开启编辑后可调整路口几何参数' - : '只读上下文:当前路口类型暂不支持编辑'} + {complexEnabled + ? '当前按复杂路口渲染' + : descriptor.status === 'candidate' + ? '当前按普通路口渲染,可切换为复杂路口' + : editable + ? editMode + ? '可编辑路口几何参数' + : '当前为浏览模式,开启编辑后可调整路口几何参数' + : '只读上下文:当前路口类型暂不支持编辑'}

@@ -111,6 +205,74 @@ export function JunctionWorkspace({
+ {candidate || complexEnabled ? ( +
+ {complexEnabled ? '当前复杂路口组成' : '附近可合并节点'} + {candidate ? ( + + 已根据当前路口附近路网动态检测到 {candidate.nodeCount} 个相邻节点,范围约 {candidate.diameterMeters}{' '} + 米。 + {candidateRoadNames.length ? ` 关联道路:${candidateRoadNames.join('、')}。` : ''} 建议核心半径{' '} + {candidate.coreRadiusMeters} 米。 + + ) : ( + 当前复杂路口包含 {candidateNodes.length} 个路口点。 + )} + {candidateNodes.length > 2 ? ( + <> + + {candidateNodePickerOpen ? ( +
+ 参与合并的路口点 + {candidateNodeLabels.map(({ nodeId, label }, index) => ( + + ))} +
+ ) : null} + + ) : null} + {!complexEnabled && onEnableComplex ? ( + + ) : null} + {complexEnabled && onUpdateComplexNodes ? ( + + ) : null} +
+ ) : null}

设施与验证

斑马线 {facilitySummary.crosswalks} · 停止线 {facilitySummary.stopLines} · 信号灯 {facilitySummary.signals} @@ -224,6 +386,8 @@ export function JunctionWorkspace({

开启编辑模式后,这里会显示进口宽度、进口收口距离和角部圆角控件。

+ ) : complexEnabled ? ( +

复杂路口几何已启用;首版仅支持查看,不支持参数拖拽编辑。

) : null}
diff --git a/workbench/client/src/junction/hotspots.test.ts b/workbench/client/src/junction/hotspots.test.ts index 5619e98..69d6ba5 100644 --- a/workbench/client/src/junction/hotspots.test.ts +++ b/workbench/client/src/junction/hotspots.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { junctionDescriptors, hotspotAt } from './hotspots'; +import { candidateForJunction, junctionDescriptors, hotspotAt } from './hotspots'; import type { WorkbenchState } from '../types/state'; const state = (overrides: Partial = {}): WorkbenchState => ({ @@ -24,6 +24,64 @@ const state = (overrides: Partial = {}): WorkbenchState => ({ }); describe('junction hotspots', () => { + it('matches a node only to a candidate that contains that node', () => { + const value = state({ + debug: { + junctionCandidates: [ + { + index: 1, + id: 'first', + nodeIds: ['n2', 'n3'], + nodeCount: 2, + diameterMeters: 8, + template: 'complex-junction-v1', + coreRadiusMeters: 12, + }, + { + index: 2, + id: 'second', + nodeIds: ['n1', 'n4'], + nodeCount: 2, + diameterMeters: 9, + template: 'complex-junction-v1', + coreRadiusMeters: 13, + }, + ], + }, + }); + expect(candidateForJunction(value, { ref: { type: 'node', id: 'n1' }, nodeIds: ['n1'] })?.id).toBe('second'); + }); + + it('matches a cluster only when the complete node set is equal', () => { + const value = state({ + debug: { + junctionCandidates: [ + { + index: 1, + id: 'wide', + nodeIds: ['n1', 'n2', 'n3'], + nodeCount: 3, + diameterMeters: 8, + template: 'complex-junction-v1', + coreRadiusMeters: 12, + }, + { + index: 2, + id: 'exact', + nodeIds: ['n1', 'n2'], + nodeCount: 2, + diameterMeters: 9, + template: 'complex-junction-v1', + coreRadiusMeters: 13, + }, + ], + }, + }); + expect(candidateForJunction(value, { ref: { type: 'cluster', id: 'cluster' }, nodeIds: ['n2', 'n1'] })?.id).toBe( + 'exact', + ); + }); + it('derives stable editable node descriptor', () => { const first = junctionDescriptors(state()); const second = junctionDescriptors(state()); @@ -83,4 +141,41 @@ describe('junction hotspots', () => { expect(hotspotAt(descriptors, { type: 'cluster', id: 'c1' })?.status).toBe('readonly'); expect(hotspotAt(descriptors, { type: 'cluster', id: 'd1' })?.status).toBe('candidate'); }); + + it('promotes a candidate to the configured cluster descriptor after enabling it', () => { + const value = state({ + debug: { + junctionCandidates: [ + { + index: 1, + id: 'diagnostic-1', + nodeIds: ['n1', 'n2'], + nodeCount: 2, + diameterMeters: 10, + template: 'complex-junction-v1', + coreRadiusMeters: 8, + }, + ], + junctionClusters: [{ id: 'cluster-n1', template: 'complex-junction-v1', nodeIds: ['n1', 'n2'] }], + }, + compiled: { + ...state().compiled, + diagnostics: [ + { + id: 'diagnostic-1', + rule: 'complex-junction-candidate', + message: 'candidate', + geometry: { type: 'Point', coordinates: [3, 3] }, + }, + ], + }, + }); + const descriptors = junctionDescriptors(value); + expect(descriptors.filter((item) => item.ref.type === 'cluster')).toHaveLength(1); + expect(hotspotAt(descriptors, { type: 'cluster', id: 'cluster-n1' })).toMatchObject({ + status: 'readonly', + source: 'cluster-config', + }); + expect(hotspotAt(descriptors, { type: 'cluster', id: 'diagnostic-1' })).toBeNull(); + }); }); diff --git a/workbench/client/src/junction/hotspots.ts b/workbench/client/src/junction/hotspots.ts index 93f741c..1faef0f 100644 --- a/workbench/client/src/junction/hotspots.ts +++ b/workbench/client/src/junction/hotspots.ts @@ -1,4 +1,4 @@ -import type { Diagnostic, JunctionCandidate, Position, WorkbenchState } from '../types/state'; +import type { Diagnostic, JunctionCandidate, Position, WorkbenchState, JunctionClusterConfig } from '../types/state'; export type JunctionRef = { type: 'node' | 'cluster'; id: string }; export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate'; @@ -13,6 +13,28 @@ export interface JunctionDescriptor { source: 'junction-plan' | 'cluster-config' | 'candidate'; } +/** Resolve the candidate belonging to the currently opened JunctionTools target. */ +export function candidateForJunction( + state: WorkbenchState | undefined, + descriptor: Pick, +): JunctionCandidate | null { + const candidates = state?.debug?.junctionCandidates || []; + if (descriptor.ref.type === 'cluster') { + const wanted = new Set(descriptor.nodeIds.map(String)); + return ( + candidates.find( + (candidate) => + candidate.nodeIds.length === wanted.size && candidate.nodeIds.every((nodeId) => wanted.has(String(nodeId))), + ) || null + ); + } + const nodeId = String(descriptor.ref.id); + return ( + candidates.find((candidate) => candidate.nodeIds.some((candidateNodeId) => String(candidateNodeId) === nodeId)) || + null + ); +} + function average(points: Position[]): Position | null { if (!points.length) return null; return [ @@ -21,21 +43,25 @@ function average(points: Position[]): Position | null { ]; } -function candidateDescriptor(candidate: JunctionCandidate, diagnostics: Diagnostic): JunctionDescriptor | null { +function candidateDescriptor( + candidate: JunctionCandidate, + diagnostics: Diagnostic, + configured?: JunctionClusterConfig, +): JunctionDescriptor | null { const coordinate = diagnostics.geometry?.type === 'Point' && Array.isArray(diagnostics.geometry.coordinates) ? (diagnostics.geometry.coordinates as Position) : null; if (!coordinate || coordinate.length < 2) return null; return { - ref: { type: 'cluster', id: candidate.id }, - status: 'candidate', + ref: { type: 'cluster', id: configured?.id || candidate.id }, + status: configured ? 'readonly' : 'candidate', coordinate, radiusMeters: Math.max(8, Number(candidate.coreRadiusMeters) || 12), nodeIds: candidate.nodeIds.map(String).sort(), approachRoadIds: [], - diagnosticIds: [diagnostics.id], - source: 'candidate', + diagnosticIds: configured ? [] : [diagnostics.id], + source: configured ? 'cluster-config' : 'candidate', }; } @@ -85,8 +111,10 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[] if (typeof nodeId === 'string') current.nodeIds.push(nodeId); configured.set(clusterId, current); } + const configuredClusters = new Map((state.debug?.junctionClusters || []).map((cluster) => [cluster.id, cluster])); for (const [clusterId, value] of configured) { - const nodeIds = [...new Set(value.nodeIds)].sort(); + const configuredCluster = configuredClusters.get(clusterId); + const nodeIds = [...new Set(configuredCluster?.nodeIds || value.nodeIds)].sort(); result.push({ ref: { type: 'cluster', id: clusterId }, status: 'readonly', @@ -98,13 +126,45 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[] source: 'cluster-config', }); } + for (const cluster of state.debug?.junctionClusters || []) { + if (configured.has(cluster.id)) continue; + const nodeIds = cluster.nodeIds.map(String).sort(); + const points = nodeIds.flatMap((nodeId) => + (state.compiled.model.endpoints || []) + .filter((endpoint) => String(endpoint.nodeId) === nodeId) + .map((endpoint) => endpoint.coordinate), + ); + const coordinate = average(points); + if (!coordinate) continue; + result.push({ + ref: { type: 'cluster', id: cluster.id }, + status: 'readonly', + coordinate, + radiusMeters: Math.max(8, Number(cluster.coreRadiusMeters) || 12), + nodeIds, + approachRoadIds: [], + diagnosticIds: [], + source: 'cluster-config', + }); + } for (const candidate of state.debug?.junctionCandidates || []) { const diagnostic = diagnostics.find((item) => item.id === candidate.id); if (!diagnostic) continue; - const descriptor = candidateDescriptor(candidate, diagnostic); + const configured = (state.debug?.junctionClusters || []).find( + (cluster) => + cluster.nodeIds.length === candidate.nodeIds.length && + cluster.nodeIds.every((nodeId) => candidate.nodeIds.map(String).includes(String(nodeId))), + ); + const descriptor = candidateDescriptor(candidate, diagnostic, configured); if (descriptor) result.push(descriptor); } - return result.sort((a, b) => `${a.ref.type}:${a.ref.id}`.localeCompare(`${b.ref.type}:${b.ref.id}`)); + const unique = new Map(); + for (const descriptor of result) { + const key = `${descriptor.ref.type}:${descriptor.ref.id}`; + const current = unique.get(key); + if (!current || (current.status === 'candidate' && descriptor.status !== 'candidate')) unique.set(key, descriptor); + } + return [...unique.values()].sort((a, b) => `${a.ref.type}:${a.ref.id}`.localeCompare(`${b.ref.type}:${b.ref.id}`)); } export function hotspotAt(descriptors: JunctionDescriptor[], ref: JunctionRef): JunctionDescriptor | null { diff --git a/workbench/client/src/lib/api.ts b/workbench/client/src/lib/api.ts index 4b7cb33..eb23096 100644 --- a/workbench/client/src/lib/api.ts +++ b/workbench/client/src/lib/api.ts @@ -69,8 +69,13 @@ export const api = { request>('/api/traffic-signals/generate', { method: 'POST', }), - acceptJunctionCandidate: (index: number) => - request('/api/junction-clusters', json({ index })), + acceptJunctionCandidate: (candidateId: string, nodeIds?: string[]) => + request( + '/api/junction-clusters', + json({ candidateId, ...(nodeIds ? { nodeIds } : {}) }), + ), + updateJunctionCluster: (clusterId: string, nodeIds: string[]) => + request('/api/junction-clusters', json({ clusterId, nodeIds })), // Direct-edit endpoints used by the in-page browser/edit switch. editState: (selection?: EditSelection) => { diff --git a/workbench/client/src/styles.css b/workbench/client/src/styles.css index 4ac8cef..69b3837 100644 --- a/workbench/client/src/styles.css +++ b/workbench/client/src/styles.css @@ -771,6 +771,76 @@ pre { background: #f8fafc; color: #475569; } +.junction-workspace__candidate { + display: grid; + gap: 0.25rem; + margin-bottom: 1rem; + padding: 0.65rem 0.75rem; + border-left: 3px solid #d49318; + background: #fffaf0; + color: #5d4a21; +} +.junction-workspace__candidate span { + color: #63736c; + font-size: 12px; +} +.junction-workspace__candidate-toggle { + justify-self: start; + margin-top: 0.25rem; +} +.junction-workspace__candidate-nodes { + display: grid; + gap: 0.35rem; + margin: 0.35rem 0 0; + padding: 0.55rem 0.65rem; + border: 1px solid #ead9ac; + background: #fffdf7; +} +.junction-workspace__candidate-nodes legend { + padding: 0 0.25rem; + color: #5d4a21; + font-size: 12px; +} +.junction-workspace__candidate-nodes label { + display: flex; + gap: 0.45rem; + align-items: center; + color: #475569; + font-size: 12px; +} +.junction-workspace__candidate-node-badge { + display: inline-grid; + flex: 0 0 1.5rem; + width: 1.5rem; + height: 1.5rem; + place-items: center; + border: 2px solid currentColor; + border-radius: 50%; + font-size: 11px; + font-weight: 800; + line-height: 1; +} +.junction-workspace__candidate-nodes label.is-included { + color: #0e7490; +} +.junction-workspace__candidate-nodes label.is-included .junction-workspace__candidate-node-badge { + color: #fff; + background: #0e7490; +} +.junction-workspace__candidate-nodes label.is-included input { + accent-color: #0e7490; +} +.junction-workspace__candidate-nodes label.is-excluded input { + accent-color: #94a3b8; +} +.junction-workspace__candidate-nodes label.is-excluded .junction-workspace__candidate-node-badge { + color: #94a3b8; + background: transparent; +} +.junction-workspace__candidate-nodes label.is-excluded { + color: #94a3b8; + text-decoration: line-through; +} @media (max-width: 900px) { .junction-workspace { top: auto; diff --git a/workbench/client/src/types/state.ts b/workbench/client/src/types/state.ts index f03c006..3455efc 100644 --- a/workbench/client/src/types/state.ts +++ b/workbench/client/src/types/state.ts @@ -64,6 +64,12 @@ export interface JunctionCandidate { template: string; coreRadiusMeters: number; } +export interface JunctionClusterConfig { + id: string; + template: string; + nodeIds: string[]; + coreRadiusMeters?: number; +} export interface Diagnostic { id: string; message: string; @@ -88,5 +94,5 @@ export interface WorkbenchState { comparison: Record; layers: Record; junctionReference?: { converted: GeoJson }; - debug?: { junctionCandidates: JunctionCandidate[] } | null; + debug?: { junctionCandidates: JunctionCandidate[]; junctionClusters?: JunctionClusterConfig[] } | null; } diff --git a/workbench/server.js b/workbench/server.js index 6c8880d..07106fd 100644 --- a/workbench/server.js +++ b/workbench/server.js @@ -249,7 +249,17 @@ function state(area, junctionReference = null, debug = false) { areaId: area.id, activeRevisionId: revisionStore.active.activeRevisionId, documentVersion: revisionStore.active.documentVersion, - debug: debug ? { junctionCandidates: junctionCandidates(compiled) } : null, + debug: debug + ? { + junctionCandidates: junctionCandidates(compiled), + junctionClusters: (area.nativeRoad?.junctionTemplates?.clusters || []).map((cluster) => ({ + id: cluster.id, + template: cluster.template, + nodeIds: (cluster.nodeIds || []).map(String), + coreRadiusMeters: cluster.coreRadiusMeters, + })), + } + : null, compiled, overrides: loadOverrides(area.outputs.nativeRoadOverrides), trafficSignals, @@ -434,24 +444,49 @@ function rebaseEdits(area, revisionId) { // write a cluster that no longer exists. The external config remains untouched; // the response carries a copyable snippet while future compiles use the snapshot. function addJunctionCluster(body, compiled, options) { + const clusterId = typeof body?.clusterId === 'string' ? body.clusterId : null; + if (clusterId) { + const templates = options?.junctionTemplates; + const clusters = Array.isArray(templates?.clusters) ? templates.clusters : []; + const current = clusters.find((cluster) => cluster.id === clusterId); + if (!current) throw new Error('当前复杂路口配置已不存在,请刷新页面后重试。'); + const nodeIds = [...new Set(Array.isArray(body?.nodeIds) ? body.nodeIds.map(String) : [])]; + const allowed = new Set((current.nodeIds || []).map(String)); + if (nodeIds.length < 2 || nodeIds.some((nodeId) => !allowed.has(nodeId))) + throw new Error('参与合并的路口点必须是当前复杂路口中的至少两个节点。'); + const nextClusters = clusters.map((cluster) => (cluster.id === clusterId ? { ...cluster, nodeIds } : cluster)); + const nextOptions = { + ...options, + junctionTemplates: { ...templates, enabled: true, clusters: nextClusters }, + }; + return { cluster: { ...current, nodeIds }, options: nextOptions }; + } + const candidateId = typeof body?.candidateId === 'string' ? body.candidateId : null; const index = Number(body?.index); - if (!Number.isInteger(index)) throw new Error('请求缺少候选编号 index。'); - const candidate = junctionCandidates(compiled).find((item) => item.index === index); - if (!candidate) throw new Error(`候选 #${index} 不在最新一次编译结果里,请刷新页面后重试。`); + if (!candidateId && !Number.isInteger(index)) throw new Error('请求缺少复杂路口候选标识。'); + const candidate = junctionCandidates(compiled).find((item) => + candidateId ? item.id === candidateId : item.index === index, + ); + if (!candidate) throw new Error('当前路口候选已不在最新编译结果里,请刷新页面后重试。'); + const requestedNodeIds = Array.isArray(body?.nodeIds) ? body.nodeIds.map(String) : candidate.nodeIds.map(String); + const candidateNodeSet = new Set(candidate.nodeIds.map(String)); + const nodeIds = [...new Set(requestedNodeIds)]; + if (nodeIds.length < 2 || nodeIds.some((nodeId) => !candidateNodeSet.has(nodeId))) + throw new Error('参与合并的路口点必须是当前候选中的至少两个节点。'); const templates = options?.junctionTemplates; if (!templates) throw new Error('区域配置缺少 nativeRoad.junctionTemplates,请先手工建立该节点。'); const clusters = Array.isArray(templates.clusters) ? templates.clusters : []; const taken = new Set(clusters.flatMap((cluster) => (cluster.nodeIds || []).map(String))); - const clash = candidate.nodeIds.filter((nodeId) => taken.has(String(nodeId))); + const clash = nodeIds.filter((nodeId) => taken.has(String(nodeId))); if (clash.length) throw new Error(`节点 ${clash.join('、')} 已属于其他复杂路口配置。`); - const id = uniqueClusterId(`cluster-${candidate.nodeIds[0]}`, new Set(clusters.map((cluster) => cluster.id))); + const id = uniqueClusterId(`cluster-${nodeIds[0]}`, new Set(clusters.map((cluster) => cluster.id))); const cluster = { id, template: candidate.template, coreRadiusMeters: candidate.coreRadiusMeters, cornerRadiusMeters: 12, outerRadiusExtraMeters: 18, - nodeIds: candidate.nodeIds.map(String), + nodeIds, }; const nextOptions = { ...options,