From f10a5da3252eddb49fba28803f84c7b27bc7cc79 Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 4 Sep 2026 09:46:19 +0800 Subject: [PATCH] feat(workbench): stabilize junction tools workspace --- .../08-26-direct-edit-junction-tools/prd.md | 16 +- .../task.json | 2 +- .../ui-prototype.html | 154 ++++++++++++++++++ .../design.md | 3 +- .../prd.md | 11 ++ src/compile/direct-edit-solver.js | 15 +- src/compile/native-road.js | 17 +- test/direct-edit-solver.js | 24 +++ test/e2e/workbench.spec.ts | 7 +- workbench/client/src/App.tsx | 134 +++++++++++++-- workbench/client/src/components/MapCanvas.tsx | 29 +++- .../client/src/components/ParameterPanel.tsx | 138 +++++++++++++++- workbench/client/src/edit/parameter.test.ts | 2 +- workbench/client/src/edit/parameter.ts | 7 + .../client/src/hooks/useDirectEditSession.ts | 12 +- .../client/src/junction/JunctionWorkspace.tsx | 26 ++- workbench/client/src/junction/labels.test.ts | 79 +++++++++ workbench/client/src/junction/labels.ts | 62 +++++++ .../client/src/junction/local-state.test.ts | 115 +++++++++++++ workbench/client/src/junction/local-state.ts | 128 +++++++++++++++ workbench/client/src/map/layers.ts | 27 ++- workbench/client/src/styles.css | 123 ++++++++++++++ 22 files changed, 1078 insertions(+), 53 deletions(-) create mode 100644 .trellis/tasks/08-26-direct-edit-junction-tools/ui-prototype.html create mode 100644 workbench/client/src/junction/labels.test.ts create mode 100644 workbench/client/src/junction/labels.ts create mode 100644 workbench/client/src/junction/local-state.test.ts create mode 100644 workbench/client/src/junction/local-state.ts diff --git a/.trellis/tasks/08-26-direct-edit-junction-tools/prd.md b/.trellis/tasks/08-26-direct-edit-junction-tools/prd.md index 47cc8b5..3eb2516 100644 --- a/.trellis/tasks/08-26-direct-edit-junction-tools/prd.md +++ b/.trellis/tasks/08-26-direct-edit-junction-tools/prd.md @@ -4,13 +4,13 @@ ## 目标 -用地图上的可识别路口区域作为入口,进入专用的局部 JunctionTools 工作区,在不破坏主地图编辑状态的前提下逐步承载路口几何、进口、控制设施和诊断编辑。远景参考 MATLAB RoadRunner 的路口局部编辑体验,但首期只建立可靠的识别、热区、进入/返回和单路口编辑基础,不追求一次实现完整路口建模。 +用地图上的可识别路口区域作为入口,进入一个独立的 JunctionTools 路口编辑页面。页面专注展示单个路口及其完整局部上下文,在同一可视化画布和同一编辑会话中同时承载路口几何、已有设施、参数双向联动、预览和诊断。主地图只负责发现、导航和返回,不承载完整路口编辑体验。 ## 当前产品设想 - 主地图识别普通路口和已配置的复杂路口 cluster,并以可点击热区表达,而不是依赖点击某一条道路或控制柄。 - 点击热区后进入独立 JunctionTools 编辑器,聚焦路口局部上下文;返回主地图时保留原地图视角、选中对象和未保存编辑。 -- 编辑器逐步扩展为路口专用工作区:进口宽度、cutback、角部圆角、路口面、车道/connector、斑马线、停止线和诊断在同一 session 中协调。 +- 编辑器首版即作为一体化路口工作区:进口宽度、cutback、角部圆角、路口面、车道/connector、斑马线、停止线、信号灯和诊断在同一 session 中协调;内部可以分区,但用户不需要跨页面切换。 - 所有编辑复用现有 direct-edit 文档、preview、revision、undo/redo 和导出契约,不建立第二套持久化几何。 ## RoadRunner 对标拆解 @@ -27,8 +27,8 @@ RoadRunner 的路口能力不能简化成几个拖拽手柄。对本项目有价 ## 分阶段方向 - 阶段 A:派生路口热区和识别状态(普通 node、已确认 cluster、候选 cluster),点击后进入/返回工作区。 -- 阶段 B:单路口局部上下文和现有 `junction-approach-width`、`junction-cutback`、`junction-corner-radius` 编辑闭环。 -- 阶段 C:车道/connector、斑马线、停止线、信号灯的联动编辑和冲突诊断。 +- 阶段 B:独立单路口页面、局部上下文和现有三项几何参数编辑闭环。 +- 阶段 C:在同一页面接入车道/connector、斑马线、停止线、信号灯的联动编辑和冲突诊断;这是实现顺序,不是拆开的产品功能。 - 阶段 D:cluster 多节点、多进口、多角部及更接近 RoadRunner 的拓扑创作能力。 阶段 A 不应把热区写成新的几何事实;它应由编译模型和 junction plan 派生,避免出现 UI 有路口而编译器不认的第二套数据。 @@ -91,6 +91,14 @@ RoadRunner 的路口能力不能简化成几个拖拽手柄。对本项目有价 ## 验收标准 +### 独立一体化页面方向(2026-09-03) + +- [ ] `/junction/:type/:id` 是独立路口编辑页面,进入后自动聚焦单个路口;主地图只作为入口和返回目标。 +- [ ] 页面画布持续展示路口几何与已有斑马线、停止线、信号灯,参数面板不得遮挡主要路口视图。 +- [ ] 几何参数和已有设施调整在同一页面、同一 draft/preview/undo/apply/save/cancel 链路中完成。 +- [ ] 表单与地图操作双向同步:表单修改反映到画布,地图拖拽回写参数;失败预览保留最后有效几何并显示诊断。 +- [ ] 首版支持已有设施的移动或已有字段修改,不创建、删除或跨路口迁移设施;cluster 与 candidate 继续只读。 + - [ ] 从路口面或诊断可进入工作区,并能带位置返回主地图。 - [ ] 三项能力各自可拖,首次拖拽即有 ghost,防抖后显示服务端权威几何。 - [ ] 预览包含全部受影响派生对象:道路面、路口面、步行带、车道中心线、connector/movement、停止线、斑马线、标线。 diff --git a/.trellis/tasks/08-26-direct-edit-junction-tools/task.json b/.trellis/tasks/08-26-direct-edit-junction-tools/task.json index bd024aa..fbeb33c 100644 --- a/.trellis/tasks/08-26-direct-edit-junction-tools/task.json +++ b/.trellis/tasks/08-26-direct-edit-junction-tools/task.json @@ -3,7 +3,7 @@ "name": "direct-edit-junction-tools", "title": "最小 JunctionTools", "description": "单一普通路口的进口宽度、cutback、单角部圆角与预览/应用/取消", - "status": "planning", + "status": "in_progress", "dev_type": null, "scope": null, "package": null, diff --git a/.trellis/tasks/08-26-direct-edit-junction-tools/ui-prototype.html b/.trellis/tasks/08-26-direct-edit-junction-tools/ui-prototype.html new file mode 100644 index 0000000..bdb15f7 --- /dev/null +++ b/.trellis/tasks/08-26-direct-edit-junction-tools/ui-prototype.html @@ -0,0 +1,154 @@ + + + + + + JunctionTools UI Prototype + + + +
+
+ JunctionTools + 路口节点 1140799919 + 独立编辑页面 / 普通路口 + + + + + +
+ +
+
+
+ 路口几何 + 斑马线 + 停止线 + 信号灯 +
+ + + + + + + + + + + + + + + + + + + + + 北进口东进口南进口西进口 + 预览中 · 路口边界 + +
拖动绿色控制点调整几何;橙色设施可单独移动或编辑
+
+ + +
+ +
+ 草稿 · 3 项未应用 + 路口面、斑马线、停止线将随本次预览同步更新 +
几何控制设施控制
+
+
+ + diff --git a/.trellis/tasks/08-26-direct-manipulation-road-editor/design.md b/.trellis/tasks/08-26-direct-manipulation-road-editor/design.md index 585d040..a16160b 100644 --- a/.trellis/tasks/08-26-direct-manipulation-road-editor/design.md +++ b/.trellis/tasks/08-26-direct-manipulation-road-editor/design.md @@ -221,7 +221,7 @@ workbench-data/import-/ 主地图 Road editor 只编辑两个 junction reserve 之间的道路内部 interval。reserve 内的 approach width、transition、cutback 和 corner 由 `JunctionTools` 独占。同一进口上 `junction-approach-width` 显式约束优先于道路 profile,求解器负责边界连续。 -`JunctionTools` 是单 `JunctionRef` session(`{type:'node'|'cluster', id}`):拖拽立即 ghost,服务端返回完整局部派生图层;"应用到工作区"把有效草稿合并为活动副本的未保存约束,"保存"才持久化,"取消"回到进入前状态。切换相邻路口前必须应用或取消。首个交付仅支持普通 node junction 的进口宽度、cutback 与一个角部圆角。 +`JunctionTools` 是独立的单 `JunctionRef` 页面(`{type:'node'|'cluster', id}`):主地图只负责发现和导航,页面自身负责路口自动居中、完整可视化画布、几何与已有设施编辑。页面不得被参数面板遮挡;路口面、进口、车道/connector、斑马线、停止线和信号灯都必须保持可见,编辑控件覆盖在同一画布上。拖拽立即 ghost,服务端返回完整局部派生图层;"应用到工作区"把有效草稿合并为活动副本的未保存约束,"保存"才持久化,"取消"回到进入前状态。切换相邻路口前必须应用或取消。 ## 不变量 @@ -270,4 +270,3 @@ workbench-data/import-/ - diff --git a/.trellis/tasks/08-26-direct-manipulation-road-editor/prd.md b/.trellis/tasks/08-26-direct-manipulation-road-editor/prd.md index 3f25895..555854f 100644 --- a/.trellis/tasks/08-26-direct-manipulation-road-editor/prd.md +++ b/.trellis/tasks/08-26-direct-manipulation-road-editor/prd.md @@ -91,6 +91,17 @@ ## 验收标准(交付阶段) +### 独立 JunctionTools 页面(重新确认,2026-09-03) + +JunctionTools 必须是一个独立的路口编辑页面,而不是覆盖在主地图上的参数弹层。主地图只负责发现路口、显示入口和返回导航;进入 `/junction/:type/:id` 后,页面主要视觉对象是当前单个路口,不能被编辑面板遮挡。 + +- [ ] 页面自动聚焦并适配当前路口,持续显示路口面、进口道路、圆角、cutback、斑马线、停止线和信号灯。 +- [ ] 几何编辑与已有设施编辑在同一页面完成,使用同一份 draft、preview、undo/redo、apply、save、cancel 状态。 +- [ ] 参数输入和地图拖拽是同一参数的两个输入通道:任一通道变化都会在路口画布上显示权威预览,另一通道同步当前值。 +- [ ] 预览失败时保留最后一个有效几何并显示结构化诊断;非法值不得显示成已应用几何。 +- [ ] 首版支持已有斑马线、停止线、信号灯的可视化调整和已有字段编辑;设施创建、删除和跨路口迁移不在首版范围。 +- [ ] 主地图的道路级编辑能力不因进入独立页面而消失;离开页面前必须明确应用、保存、放弃或继续停留。 + 每条都必须可执行验证,不接受"看起来对了"。 - [ ] 拖动道路外缘 → 保存 → 重新编译,道路面、步行带、车道线、标线与 connector 一致更新,约束状态为 `exact`。 diff --git a/src/compile/direct-edit-solver.js b/src/compile/direct-edit-solver.js index bbace7a..a781902 100644 --- a/src/compile/direct-edit-solver.js +++ b/src/compile/direct-edit-solver.js @@ -961,7 +961,12 @@ function makeJunctionHandles(model, junctionData, constraints) { const road = match.road; const line = approach.endpoint.side === 'start' ? road.centerline : [...road.centerline].reverse(); const tangent = tangentAzimuth(line, Math.min(0.95, approach.cutback / approach.length)); - const placementAzimuth = tangent; + // `line` is oriented from the junction outward. Native control geometry + // follows the road centerline orientation, which is outward for a `start` + // endpoint and inward for an `end` endpoint. Derive this per approach; + // assuming every arm has the same endpoint side reverses half the handles. + const approachAzimuth = approach.endpoint.side === 'start' ? tangent : (tangent + 180) % 360; + const placementAzimuth = approachAzimuth; const anchorBase = { type: 'junction-crossing', crossingId: String(crossing.id), @@ -990,7 +995,8 @@ function makeJunctionHandles(model, junctionData, constraints) { // along the approach, not a reliable screen station from the junction; // deriving the point from junction distance put the knob off the zebra. position: offsetCoordinate(crossing.coordinate, placementAzimuth, insetApplied), - axisAzimuth: (tangent + 180) % 360, + // Increasing inset moves the crossing toward the junction. + axisAzimuth: approachAzimuth, value: { current: insetValue, min: 0, max: insetMax, unit: 'meter' }, ...(insetConstraint ? { constraintId: insetConstraint.id } : {}), affects: [`crosswalk:node/${crossing.id}`], @@ -1010,8 +1016,9 @@ function makeJunctionHandles(model, junctionData, constraints) { -stopValue, ), // The compiled stop line applies `-offset` along the approach axis, so - // this tangent is the positive drag direction for increasing offset. - axisAzimuth: tangent, + // Increasing the offset moves away from the junction, opposite to the + // approach axis used by the compiled stop-line geometry. + axisAzimuth: (approachAzimuth + 180) % 360, value: { current: stopValue, min: MIN_STOP_LINE_OFFSET_METERS, diff --git a/src/compile/native-road.js b/src/compile/native-road.js index ea3b7bb..6cdaecd 100644 --- a/src/compile/native-road.js +++ b/src/compile/native-road.js @@ -894,10 +894,12 @@ function applyDirectJunctionPlans(plans, directEdit) { if (requestedRadii.length) changed = true; if (!changed) continue; const referenceWidth = Math.max(...plan.approaches.map((approach) => approach.widthMeters), 1); - const cornerRadiusMultiplier = requestedRadii.length - ? Math.max(0.1, Math.min(3, requestedRadii[0] / referenceWidth)) - : 1; - const boundary = junctionBoundary(plan.approaches, plan.node, plan.cutbackMeters, cornerRadiusMultiplier, 1); + const cornerRadiusMultipliers = Object.fromEntries( + Object.entries(directPlan.corners || {}) + .filter(([, radius]) => Number.isFinite(radius)) + .map(([key, radius]) => [key, Math.max(0.1, Math.min(3, radius / referenceWidth))]), + ); + const boundary = junctionBoundary(plan.approaches, plan.node, plan.cutbackMeters, cornerRadiusMultipliers, 1); plan.boundary = boundary.points; plan.boundaryMode = boundary.mode; plan.boundaryFallbacks = boundary.fallbacks; @@ -2892,13 +2894,18 @@ function junctionBoundary(approaches, node, cutbackMeters, cornerRadiusMultiplie // bends the far side of a T junction and exposes junction asphalt beyond // the pedestrian strip. if (first.segmentId === second.segmentId || isStraightJunctionEdge(first, second)) continue; + const cornerKey = `${first.segmentId}->${second.segmentId}`; + const multiplier = + cornerRadiusMultiplier && typeof cornerRadiusMultiplier === 'object' + ? (cornerRadiusMultiplier[cornerKey] ?? 1) + : cornerRadiusMultiplier; const curve = roundedCorner( node, first.point, second.point, first.outwardHeading, second.outwardHeading, - cornerRadiusMultiplier, + multiplier, ); if (!curve) { fallbacks += 1; diff --git a/test/direct-edit-solver.js b/test/direct-edit-solver.js index 31d9cf6..a361b4b 100644 --- a/test/direct-edit-solver.js +++ b/test/direct-edit-solver.js @@ -122,6 +122,11 @@ assert.notEqual( stopLineHandle.axisAzimuth, 'crosswalk inset and stop-line offset use opposite positive directions along the approach', ); +assert.equal( + (crosswalkHandle.axisAzimuth + 180) % 360, + stopLineHandle.axisAzimuth, + 'increasing crosswalk inset moves toward the junction while increasing stop-line offset moves away', +); // A selection scopes the manifest to the object being edited. The whole-area // manifest is 844 KB on a 41-road workspace, 89% of it `affects` id lists, while @@ -324,6 +329,25 @@ assert.equal(allKindsResolution.junctionPlans.get('junction').approaches['segmen assert.equal(allKindsResolution.junctionPlans.get('junction').approaches['segment:a'].cutbackMeters, 2); assert.equal(allKindsResolution.junctionPlans.get('junction').corners['segment:a->segment:b'], 4); assert.equal(allKindsResolution.effectiveJunctionPlans.get('node:junction').approaches['segment:a'].widthMeters, 7); +const independentCorners = resolveDirectEditConstraints( + junctionModel, + document([ + constraint({ + id: 'corner-radius-a', + kind: 'junction-corner-radius', + anchor: { type: 'junction-corner', nodeId: 'junction', incomingRoadId: 'segment:a', outgoingRoadId: 'segment:b' }, + value: { radiusMeters: 4 }, + }), + constraint({ + id: 'corner-radius-b', + kind: 'junction-corner-radius', + anchor: { type: 'junction-corner', nodeId: 'junction', incomingRoadId: 'segment:b', outgoingRoadId: 'segment:c' }, + value: { radiusMeters: 10 }, + }), + ]), +); +assert.equal(independentCorners.junctionPlans.get('junction').corners['segment:a->segment:b'], 4); +assert.equal(independentCorners.junctionPlans.get('junction').corners['segment:b->segment:c'], 10); const clusterResolution = resolveDirectEditConstraints(junctionModel, document(allKinds), { junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }], diff --git a/test/e2e/workbench.spec.ts b/test/e2e/workbench.spec.ts index b230788..c289677 100644 --- a/test/e2e/workbench.spec.ts +++ b/test/e2e/workbench.spec.ts @@ -121,7 +121,12 @@ test.describe('workbench editing shell', () => { await expect(page.getByText('设施与验证', { exact: true })).toBeVisible(); await expect(page.getByText('当前为浏览模式,开启编辑后可调整路口几何参数')).toBeVisible(); await page.getByRole('button', { name: '开启编辑模式' }).click(); - await expect(page.getByRole('switch', { name: '编辑模式' })).toBeChecked(); await expect(page.getByLabel('路口编辑工作区').getByText('道路参数', { exact: true })).toBeVisible(); + await expect( + page + .getByLabel('路口编辑工作区') + .getByText(/进口宽度/) + .first(), + ).toBeVisible(); }); }); diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index 475b231..8f9000f 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -31,7 +31,7 @@ import { type Coordinate, } from './edit/meters'; import { previewArrowFeatures } from './edit/arrow-preview'; -import { rendersSame } from './edit/parameter'; +import { formatParameterValue, rendersSame } from './edit/parameter'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; import { clearEditHistory, recordEdit, takeRedoDomain, takeUndoDomain, type EditHistory } from './edit/edit-history'; import { @@ -56,6 +56,7 @@ import type { LayerName } from './map/layers'; import type { JunctionRef } from './junction/hotspots'; import { junctionDescriptors, hotspotAt } from './junction/hotspots'; import { JunctionWorkspace } from './junction/JunctionWorkspace'; +import { localJunctionPreview, localJunctionState } from './junction/local-state'; import { applyJunctionDraft, cancelJunctionSession, @@ -161,6 +162,7 @@ function App() { editMode, state, selectedSegmentId: selected?.segmentId, + selectedJunctionId: junctionRoute?.type === 'node' ? junctionRoute.id : undefined, setStatus, }); const { @@ -178,6 +180,37 @@ function App() { () => (state && junctionRoute ? hotspotAt(junctionDescriptors(state), junctionRoute) : null), [junctionRoute, state], ); + const junctionRoads = useMemo(() => { + if (!state || !junctionDescriptor) return []; + const ids = new Set(junctionDescriptor.approachRoadIds); + // Configured clusters may not carry approach ids yet; derive them from the + // cluster's member nodes so the workspace still stays local to the junction. + if (!ids.size) { + const nodeIds = new Set(junctionDescriptor.nodeIds.map(String)); + for (const endpoint of state.compiled.model.endpoints || []) { + if (nodeIds.has(String(endpoint.nodeId))) ids.add(endpoint.roadId); + } + } + const seen = new Set(); + return state.compiled.model.roads.filter((road) => { + if (!(ids.has(road.id) || ids.has(road.segmentId))) return false; + const key = road.tags?.name?.trim() || `unnamed:${road.id || road.segmentId}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + }, [junctionDescriptor, state]); + const junctionMapState = useMemo( + () => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state), + [junctionDescriptor, junctionRoute, state], + ); + const junctionMapPreview = useMemo( + () => + state && junctionDescriptor && junctionRoute + ? localJunctionPreview(preview, junctionDescriptor, state.compiled.model.roads) + : preview, + [junctionDescriptor, junctionRoute, preview, state], + ); // 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 @@ -213,7 +246,9 @@ function App() { (handle) => (handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback' || - handle.kind === 'junction-corner-radius') && + handle.kind === 'junction-corner-radius' || + handle.kind === 'junction-crosswalk-inset' || + handle.kind === 'junction-stop-line-offset') && 'nodeId' in handle.anchor && nodeIds.has(String(handle.anchor.nodeId)), ); @@ -371,7 +406,16 @@ function App() { // Read at send time so the requester, built once, always scopes to the current // selection without being rebuilt. const selectionRef = useRef(undefined); - selectionRef.current = selected?.segmentId ? { segment: selected.segmentId } : undefined; + // An independent JunctionTools page owns the whole junction manifest. Never + // fall back to the approach segment here: doing so makes an accepted preview + // replace the junction manifest with a road-scoped one, which drops the + // width/cutback/radius rows immediately after the first edit. + selectionRef.current = + junctionRoute?.type === 'node' + ? { junction: junctionRoute.id } + : selected?.segmentId + ? { segment: selected.segmentId } + : undefined; /** * One gesture, one operation id. Minted on the first draft of a drag and cleared * on release: reusing an id across gestures would put two operations with the @@ -412,8 +456,12 @@ function App() { // control handles silently returned null and never scheduled a preview. const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : null; const segmentId = 'segmentId' in handle.anchor ? handle.anchor.segmentId : null; + const cornerRoadId = handle.anchor.type === 'junction-corner' ? handle.anchor.incomingRoadId : null; const road = state?.compiled.model.roads.find( - (item) => (roadId ? item.id === roadId : false) || (segmentId ? item.segmentId === segmentId : false), + (item) => + (roadId ? item.id === roadId : false) || + (segmentId ? item.segmentId === segmentId : false) || + (cornerRoadId ? item.id === cornerRoadId || item.segmentId === cornerRoadId : false), ); // Without a centerline there is no snapshot to record, so drop the drag rather // than send a constraint the server would have to reject. @@ -435,6 +483,47 @@ function App() { operations: [...base.operations.filter((item) => item.id !== operation.id), operation], }; }; + const draftForGroup = (handles: EditHandle[], value: number): PreviewDraft | null => { + if (!handles.length || !session) return null; + const drafts = handles + .map((handle) => draftFor(handle, value)) + .filter((item): item is PreviewDraft => Boolean(item)); + if (!drafts.length) return null; + const base = session.fragment(); + const constraints = new Map(base.constraints.map((item) => [item.id, item])); + const operations = new Map(base.operations.map((item) => [item.id, item])); + for (const draft of drafts) { + for (const constraint of draft.constraints ?? []) constraints.set(constraint.id, constraint); + for (const operation of draft.operations ?? []) operations.set(operation.id, operation); + } + return { constraints: [...constraints.values()], operations: [...operations.values()] }; + }; + const settleGroup = (handles: EditHandle[], value: number) => { + // Keep individually customised entries intact: the manifest does not expose + // a separate scope bit, so the dominant current value is the group's default + // and outliers are treated as local overrides. + const frequencies = new Map(); + for (const handle of handles) { + const key = formatParameterValue(handle.value.current); + frequencies.set(key, (frequencies.get(key) ?? 0) + 1); + } + const defaultKey = [...frequencies.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + const changed = handles.filter( + (handle) => + formatParameterValue(handle.value.current) === defaultKey && !rendersSame(value, handle.value.current), + ); + if (!changed.length) { + abandonGesture(); + return; + } + const draft = draftForGroup(changed, value); + if (draft) + commitGesture( + draft, + changed.map((handle) => `constraint:${handle.handleId}`), + ); + else abandonGesture(); + }; const draftLane = (laneId: string, maneuver: string, placementDistanceMeters: number): PreviewDraft | null => { const handle = manifest?.handles.find( (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === laneId, @@ -520,6 +609,14 @@ function App() { panelRef.current?.clearLive(); previewSession(); }; + const discardJunctionDraft = () => { + if (!session) return; + session.discard(); + gesture.current = null; + panelRef.current?.clearLive(); + previewSession(); + setJunctionSession((current) => (current ? cancelJunctionSession(current) : current)); + }; /** A settled value from either channel: one undoable command, or nothing. */ const settleValue = (handle: EditHandle, value: number) => { // A gesture that did not move the value must not become an edit. `handle` was @@ -765,8 +862,9 @@ function App() { const choice = window.prompt('路口有未应用草稿:输入 1 应用并返回,2 放弃并返回,3 留在工作区', '3'); if (choice === '3' || !choice) return; if (choice === '1') setJunctionSession(applyJunctionDraft(junctionSession)); - else if (choice === '2') setJunctionSession(cancelJunctionSession(junctionSession)); - else return; + else if (choice === '2') { + discardJunctionDraft(); + } else return; } window.history.pushState({}, '', '/'); setJunctionRoute(null); @@ -790,7 +888,7 @@ function App() { else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); }; return ( - <> +
道路编译工作台
); } export default App; diff --git a/workbench/client/src/components/MapCanvas.tsx b/workbench/client/src/components/MapCanvas.tsx index 1126246..3adb831 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 { createEmpty, extend } from 'ol/extent'; import { click } from 'ol/events/condition'; import type { GeoJson, Road, WorkbenchState } from '../types/state'; import { createLayers, updateJunctionHotspots, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers'; @@ -71,6 +72,8 @@ interface Props { /** Last solve came back degraded; hold the ghost instead of clearing it. */ ghostPending?: boolean; editMode?: boolean; + /** When set, fit the map to one junction instead of the whole imported area. */ + focusJunctionId?: string | null; junctionHotspots?: boolean; onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void; } @@ -105,6 +108,7 @@ export function MapCanvas({ onRangeEnd, ghostPending, editMode = false, + focusJunctionId = null, junctionHotspots = true, onJunctionHotspot, }: Props) { @@ -424,14 +428,27 @@ export function MapCanvas({ const layers = layersRef.current; const map = mapRef.current; if (!layers || !map) return; - updateLayers(layers, state, selected); + updateLayers(layers, state, selected, Boolean(focusJunctionId)); updateJunctionHotspots(layers, junctionDescriptors(state), junctionHotspots); - const extent = layers.osm.getSource()!.getExtent(); - if (fittedAreaIdRef.current !== state.areaId && extent && Number.isFinite(extent[0])) { - map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 }); - fittedAreaIdRef.current = state.areaId; + const junctionSource = layers.native.getSource(); + const focusExtent = focusJunctionId ? createEmpty() : null; + if (focusExtent && junctionSource) { + junctionSource.getFeatures().forEach((feature) => { + const nativeId = feature.get('native_id'); + if (nativeId === `junction:node/${focusJunctionId}`) + extend(focusExtent, feature.getGeometry()?.getExtent() ?? focusExtent); + }); } - }, [state, junctionHotspots]); + const extent = focusExtent && Number.isFinite(focusExtent[0]) ? focusExtent : layers.osm.getSource()!.getExtent(); + const fitKey = focusJunctionId ? `${state.areaId}:junction:${focusJunctionId}` : state.areaId; + if (fittedAreaIdRef.current !== fitKey && extent && Number.isFinite(extent[0])) { + map.getView().fit(extent, { + padding: focusJunctionId ? [80, 470, 80, 80] : [48, 48, 48, 48], + maxZoom: focusJunctionId ? 20 : 19, + }); + fittedAreaIdRef.current = fitKey; + } + }, [focusJunctionId, state, junctionHotspots]); useEffect(() => { const layers = layersRef.current; if (!layers) return; diff --git a/workbench/client/src/components/ParameterPanel.tsx b/workbench/client/src/components/ParameterPanel.tsx index e41e5ae..1487f22 100644 --- a/workbench/client/src/components/ParameterPanel.tsx +++ b/workbench/client/src/components/ParameterPanel.tsx @@ -24,6 +24,7 @@ // unnoticed. Same invariant, two devices, two honest ways to say "no". import { useImperativeHandle, useLayoutEffect, useRef, useState, type Ref } from 'react'; +import { Minus, Plus } from 'lucide-react'; import { formatBoundInward, formatParameterValue, @@ -63,6 +64,9 @@ interface RowCallbacks { onAbandon: () => void; /** Withdraw the constraint and return the row to the compiler's baseline. */ onReset: (handle: EditHandle) => void; + labelForHandle?: (handle: EditHandle) => string; + onDraftGroup?: (handles: EditHandle[], value: number) => void; + onSettleGroup?: (handles: EditHandle[], value: number) => void; } function ParameterRow({ @@ -72,6 +76,7 @@ function ParameterRow({ onSettle, onAbandon, onReset, + labelForHandle: resolveLabel, }: RowCallbacks & { handle: EditHandle; register: (handleId: string, node: HTMLInputElement | null) => void; @@ -92,6 +97,8 @@ function ParameterRow({ // previewable nor an error, so it must not light the field up red. const verdict = parsed === null ? 'ok' : rangeVerdictOf(parsed, min, max); const rejected = verdict !== 'ok'; + const step = 0.1; + const displayLabel = resolveLabel?.(handle) ?? labelForHandle(handle); const draft = (next: string) => { setText(next); @@ -101,6 +108,12 @@ function ParameterRow({ onDraft(handle, value); }; + const nudge = (direction: -1 | 1) => (event: React.MouseEvent) => { + event.preventDefault(); + const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step)); + draft(formatParameterValue(next)); + }; + const settle = () => { const value = text === null ? null : parseParameterInput(text); const touched = text !== null && text !== seeded.current; @@ -140,7 +153,7 @@ function ParameterRow({ return (
  • - {labelForHandle(handle)} + {displayLabel} {isModified(handle) ? ( <> @@ -168,6 +181,12 @@ function ParameterRow({ onChange={(event) => draft(event.target.value)} onBlur={settle} onKeyDown={(event) => { + if (event.key === 'ArrowUp' || event.key === 'ArrowDown') { + event.preventDefault(); + const direction = event.key === 'ArrowUp' ? 1 : -1; + const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step)); + draft(formatParameterValue(next)); + } if (event.key === 'Enter') event.currentTarget.blur(); if (event.key === 'Escape') { setText(null); @@ -177,6 +196,14 @@ function ParameterRow({ }} />{' '} m + + + + {reason ?? ( @@ -200,11 +227,13 @@ function ParameterRow({ export function ParameterPanel({ handles, hasSelection, + grouped = false, ref, ...callbacks }: RowCallbacks & { handles: EditHandle[]; hasSelection: boolean; + grouped?: boolean; ref?: Ref; }) { const nodes = useRef(new Map()); @@ -264,18 +293,113 @@ export function ParameterPanel({ } }); + const groupedHandles = new Map(); + for (const handle of handles) { + const list = groupedHandles.get(handle.kind) ?? []; + list.push(handle); + groupedHandles.set(handle.kind, list); + } + return (
    -

    道路参数

    +

    {grouped ? '路口参数' : '道路参数'}

    {handles.length ? ( -
      - {handles.map((handle) => ( - - ))} -
    + grouped ? ( + + ) : ( +
      + {handles.map((handle) => ( + + ))} +
    + ) ) : (

    {hasSelection ? '当前道路无可编辑参数' : '选中道路以显示参数'}

    )}
    ); } + +function GroupedParameterList({ + groups, + register, + ...callbacks +}: RowCallbacks & { + groups: Array<[string, EditHandle[]]>; + register: (handleId: string, node: HTMLInputElement | null) => void; +}) { + const [expanded, setExpanded] = useState>({}); + return ( +
      + {groups.map(([kind, items]) => { + const representative = items[0]; + const dominant = items + .map((item) => item.value.current) + .sort( + (a, b) => + items.filter((candidate) => formatParameterValue(candidate.value.current) === formatParameterValue(b)) + .length - + items.filter((candidate) => formatParameterValue(candidate.value.current) === formatParameterValue(a)) + .length, + )[0]; + const globalHandle: EditHandle = { + ...representative, + handleId: `group:${kind}`, + constraintId: undefined, + value: { + ...representative.value, + current: dominant, + min: Math.max(...items.map((item) => item.value.min)), + max: Math.min(...items.map((item) => item.value.max)), + }, + }; + const expandedGroup = Boolean(expanded[kind]); + const globalDraft = + callbacks.onDraftGroup ?? ((group: EditHandle[], value: number) => callbacks.onDraft?.(group[0], value)); + const globalSettle = + callbacks.onSettleGroup ?? ((group: EditHandle[], value: number) => callbacks.onSettle?.(group[0], value)); + return ( +
    • +
      + + {groupLabel(kind, representative)} + 统一设置 · {items.length} 项 + + +
      + globalDraft(items, value)} + onSettle={(handle, value) => globalSettle(items, value)} + labelForHandle={() => '统一值'} + /> + {expandedGroup ? ( +
        + {items.map((handle) => ( + + ))} +
      + ) : null} +
    • + ); + })} +
    + ); +} + +function groupLabel(kind: string, handle: EditHandle): string { + if (kind === 'junction-approach-width') return '进口宽度'; + if (kind === 'junction-cutback') return '进口 cutback'; + if (kind === 'junction-corner-radius') return '角部圆角'; + if (kind === 'junction-crosswalk-inset') return '斑马线退让'; + if (kind === 'junction-stop-line-offset') return '停止线退距'; + return labelForHandle(handle); +} diff --git a/workbench/client/src/edit/parameter.test.ts b/workbench/client/src/edit/parameter.test.ts index 84ccaa6..1208571 100644 --- a/workbench/client/src/edit/parameter.test.ts +++ b/workbench/client/src/edit/parameter.test.ts @@ -206,7 +206,7 @@ describe('labelForHandle', () => { outgoingRoadId: 'seg:2', }), ), - ).toBe('角部圆角'); + ).toBe('seg:1 → seg:2 · 角部圆角'); }); }); diff --git a/workbench/client/src/edit/parameter.ts b/workbench/client/src/edit/parameter.ts index 486bbed..fab974a 100644 --- a/workbench/client/src/edit/parameter.ts +++ b/workbench/client/src/edit/parameter.ts @@ -130,6 +130,13 @@ const KIND_LABELS: Record = { export function labelForHandle(handle: EditHandle): string { const base = KIND_LABELS[handle.kind] ?? handle.kind; const anchor = handle.anchor; + if ( + (handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback') && + anchor.type === 'junction-approach' + ) + return `${anchor.segmentId} · ${base}`; + if (handle.kind === 'junction-corner-radius' && anchor.type === 'junction-corner') + return `${anchor.incomingRoadId} → ${anchor.outgoingRoadId} · ${base}`; if ('boundaryIndex' in anchor && Number.isInteger(anchor.boundaryIndex)) return `${base} #${anchor.boundaryIndex}`; if ('side' in anchor && anchor.side) return `${base}(${anchor.side === 'left' ? '左' : '右'})`; return base; diff --git a/workbench/client/src/hooks/useDirectEditSession.ts b/workbench/client/src/hooks/useDirectEditSession.ts index fa3aad8..f41f32a 100644 --- a/workbench/client/src/hooks/useDirectEditSession.ts +++ b/workbench/client/src/hooks/useDirectEditSession.ts @@ -12,11 +12,13 @@ export function useDirectEditSession({ editMode, state, selectedSegmentId, + selectedJunctionId, setStatus, }: { editMode: boolean; state?: WorkbenchState; selectedSegmentId?: string; + selectedJunctionId?: string; setStatus: (status: string) => void; }) { const [manifest, setManifest] = useState(null); @@ -32,7 +34,13 @@ export function useDirectEditSession({ // Flag off: no manifest request at all, so the network trace matches browse mode. if (!editMode) return; api - .editState(selectedSegmentId ? { segment: selectedSegmentId } : undefined) + .editState( + selectedJunctionId + ? { junction: selectedJunctionId } + : selectedSegmentId + ? { segment: selectedSegmentId } + : undefined, + ) .then((value) => { if (!('handles' in value)) return; setManifest(value.handles); @@ -43,7 +51,7 @@ export function useDirectEditSession({ touch(); }) .catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`)); - }, [editMode, selectedSegmentId, setStatus, state]); + }, [editMode, selectedJunctionId, selectedSegmentId, setStatus, state]); return { session: sessionRef.current, diff --git a/workbench/client/src/junction/JunctionWorkspace.tsx b/workbench/client/src/junction/JunctionWorkspace.tsx index 7d3efb6..2262ab7 100644 --- a/workbench/client/src/junction/JunctionWorkspace.tsx +++ b/workbench/client/src/junction/JunctionWorkspace.tsx @@ -4,6 +4,9 @@ import { canEditJunction, type JunctionSession } from './workspace'; import { Button } from '../ui/button'; import { ParameterPanel } from '../components/ParameterPanel'; import type { EditHandle } from '../edit/types'; +import type { Road } from '../types/state'; +import type { Coordinate } from '../edit/meters'; +import { junctionLabelForHandle, junctionRoadName } from './labels'; interface Props { descriptor: JunctionDescriptor; @@ -18,9 +21,13 @@ interface Props { onEnableEdit?: () => void; handles?: EditHandle[]; onDraft?: (handle: EditHandle, value: number) => void; + onDraftGroup?: (handles: EditHandle[], value: number) => void; onSettle?: (handle: EditHandle, value: number) => void; + onSettleGroup?: (handles: EditHandle[], value: number) => void; onAbandon?: () => void; onReset?: (handle: EditHandle) => void; + roads?: Road[]; + junctionCoordinate?: Coordinate; } export function JunctionWorkspace({ @@ -36,19 +43,22 @@ export function JunctionWorkspace({ facilitySummary = { crosswalks: 0, stopLines: 0, signals: 0 }, handles = [], onDraft, + onDraftGroup, onSettle, + onSettleGroup, onAbandon, onReset, + roads = [], + junctionCoordinate = descriptor.coordinate, }: Props) { const editable = useMemo(() => canEditJunction(descriptor), [descriptor]); return (
    - JunctionTools -

    - {descriptor.ref.type === 'node' ? '路口节点' : '复杂路口上下文'} {descriptor.ref.id} -

    +
    + JunctionTools +

    {editable ? editMode @@ -65,9 +75,9 @@ export function JunctionWorkspace({

    组成节点
    -
    {descriptor.nodeIds.join(', ') || '—'}
    +
    {descriptor.nodeIds.length ? `${descriptor.nodeIds.length} 个路口节点` : '—'}
    进口道路
    -
    {descriptor.approachRoadIds.join(', ') || '—'}
    +
    {roads.length ? roads.map((road) => junctionRoadName(road, roads)).join('、') : '—'}
    诊断
    {descriptor.diagnosticIds.length ? `${descriptor.diagnosticIds.length} 条` : '无'}
    状态
    @@ -98,10 +108,14 @@ export function JunctionWorkspace({ undefined)} + onDraftGroup={onDraftGroup} onSettle={onSettle ?? (() => undefined)} + onSettleGroup={onSettleGroup} onAbandon={onAbandon ?? (() => undefined)} onReset={onReset ?? (() => undefined)} + labelForHandle={(handle) => junctionLabelForHandle(handle, roads, junctionCoordinate)} />