feat(workbench): stabilize junction tools workspace

This commit is contained in:
que01 committed 2026-09-04 09:46:19 +08:00
1 parent e6b822416d
commit f10a5da325
22 files changed
+1078 -53

No files matched your search

@@ -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、停止线、斑马线、标线。
@@ -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,
@@ -0,0 +1,154 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>JunctionTools UI Prototype</title>
<style>
:root {
color: #dfe9e5;
background: #101a18;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
body { margin: 0; min-width: 1080px; }
button, input { font: inherit; }
button { cursor: pointer; }
.app { min-height: 100vh; display: grid; grid-template-rows: 64px 1fr 38px; }
.topbar { display: flex; align-items: center; gap: 22px; padding: 0 22px; background: #173b32; border-bottom: 1px solid #2d594d; }
.brand { letter-spacing: .14em; font-size: 12px; color: #95b5aa; text-transform: uppercase; }
.title { font-size: 18px; font-weight: 700; color: #f5fbf8; }
.crumb { color: #9eb9ae; font-size: 13px; }
.topbar-spacer { flex: 1; }
.top-action { border: 1px solid #6d988a; color: #e9f4ef; background: transparent; padding: 8px 12px; border-radius: 4px; }
.top-action.primary { background: #d3e9df; border-color: #d3e9df; color: #183a31; font-weight: 700; }
.workspace { min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) 360px; }
.canvas { position: relative; overflow: hidden; background: #d9dfda; }
.canvas-head { position: absolute; z-index: 2; left: 20px; top: 18px; display: flex; gap: 8px; }
.chip { border: 1px solid #b3c0ba; background: #eff4f0e8; color: #29483e; border-radius: 4px; padding: 7px 10px; font-size: 12px; box-shadow: 0 2px 8px #263b3222; }
.chip.active { border-color: #2f755d; background: #e0f1e8; color: #205a45; }
.map-svg { position: absolute; inset: 0; width: 100%; height: 100%; }
.map-label { font-size: 13px; fill: #345448; font-weight: 700; }
.map-note { position: absolute; left: 20px; bottom: 18px; padding: 9px 12px; color: #3c574d; background: #eef3efdf; border: 1px solid #b8c7bf; border-radius: 4px; font-size: 12px; }
.inspector { overflow: auto; padding: 20px 18px; background: #f7faf8; color: #20352d; border-left: 1px solid #cad9d1; }
.section { padding-bottom: 18px; margin-bottom: 18px; border-bottom: 1px solid #dbe6e0; }
.section:last-child { border-bottom: 0; }
.section-title { margin: 0 0 12px; font-size: 14px; color: #173b32; }
.section-subtitle { margin: -5px 0 12px; color: #71847b; font-size: 12px; }
.field { display: grid; grid-template-columns: 1fr 104px; gap: 10px; align-items: center; margin: 11px 0; }
.field label { font-size: 13px; }
.field small { display: block; color: #82938b; font-size: 11px; margin-top: 3px; }
.field input { width: 100%; border: 1px solid #aabdb3; border-radius: 3px; padding: 7px 8px; color: #173b32; background: white; text-align: right; }
.unit { position: relative; }
.unit span { position: absolute; right: 8px; top: 8px; color: #7c9187; font-size: 12px; pointer-events: none; }
.unit input { padding-right: 28px; }
.range { height: 4px; margin: 6px 0 0; border-radius: 10px; background: #c9d9d1; }
.range i { display: block; width: 57%; height: 100%; background: #3d8b6c; border-radius: 10px; }
.facility { display: flex; justify-content: space-between; align-items: center; padding: 9px 0; border-top: 1px solid #e5ede8; font-size: 13px; }
.facility:first-of-type { border-top: 0; }
.facility strong { color: #245b47; }
.status { display: flex; align-items: center; gap: 8px; color: #2e7558; font-size: 12px; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: #3d9a6c; }
.diagnostic { padding: 9px 10px; background: #edf5f0; border-left: 3px solid #3d8b6c; color: #45665a; font-size: 12px; line-height: 1.5; }
.actions { display: flex; gap: 8px; }
.action { flex: 1; padding: 9px 8px; border: 1px solid #9bb2a7; border-radius: 3px; background: white; color: #245241; }
.action.main { background: #286b52; color: white; border-color: #286b52; }
.footer { display: flex; align-items: center; gap: 18px; padding: 0 20px; background: #18322b; color: #b7cdc3; font-size: 12px; }
.footer strong { color: #e1f1ea; }
.legend { margin-left: auto; display: flex; gap: 14px; }
.legend span::before { content: ''; display: inline-block; width: 9px; height: 9px; margin-right: 5px; border-radius: 50%; background: currentColor; }
.legend .geometry { color: #2f7e61; }
.legend .facility-dot { color: #b1783c; }
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<span class="brand">JunctionTools</span>
<span class="title">路口节点 1140799919</span>
<span class="crumb">独立编辑页面 / 普通路口</span>
<span class="topbar-spacer"></span>
<button class="top-action">撤销</button>
<button class="top-action">重做</button>
<button class="top-action">返回主地图</button>
<button class="top-action primary">保存并重新生成</button>
</header>
<main class="workspace">
<section class="canvas" aria-label="路口可视化画布">
<div class="canvas-head">
<span class="chip active">路口几何</span>
<span class="chip">斑马线</span>
<span class="chip">停止线</span>
<span class="chip">信号灯</span>
</div>
<svg class="map-svg" viewBox="0 0 900 700" role="img" aria-label="单个路口及其设施预览">
<rect width="900" height="700" fill="#d9dfda" />
<path d="M0 285 H900 V415 H0 Z" fill="#7e8987" />
<path d="M385 0 H515 V700 H385 Z" fill="#7e8987" />
<path d="M0 280 H900 M0 420 H900 M380 0 V700 M520 0 V700" stroke="#d5dcda" stroke-width="3" />
<path d="M0 350 H900 M450 0 V700" stroke="#f4f5ed" stroke-width="2" stroke-dasharray="14 13" opacity=".7" />
<path d="M320 285 H580 V415 H320 Z" fill="#697673" stroke="#286b52" stroke-width="4" stroke-dasharray="9 7" />
<g fill="#f5f8ef">
<path d="M346 265 h75 v12 h-75z M346 423 h75 v12 h-75z" />
<path d="M479 265 h75 v12 h-75z M479 423 h75 v12 h-75z" />
<path d="M305 305 h12 v90 h-12z M573 305 h12 v90 h-12z" />
</g>
<g stroke="#e8eee9" stroke-width="9" opacity=".95">
<path d="M347 286 V330 M365 286 V330 M383 286 V330 M401 286 V330" />
<path d="M499 370 V414 M517 370 V414 M535 370 V414 M553 370 V414" />
</g>
<g fill="none" stroke="#b1783c" stroke-width="6"><path d="M330 275 H430" /><path d="M470 425 H570" /></g>
<g fill="#d4934b" stroke="#704c2b" stroke-width="2"><circle cx="300" cy="270" r="9" /><circle cx="600" cy="430" r="9" /><circle cx="565" cy="270" r="9" /></g>
<g fill="#2f7e61" stroke="#f2fff8" stroke-width="3"><circle cx="450" cy="285" r="11" /><circle cx="385" cy="350" r="11" /><circle cx="515" cy="350" r="11" /><circle cx="450" cy="415" r="11" /></g>
<g stroke="#2f7e61" stroke-width="2" fill="none"><path d="M450 285 L450 210" /><path d="M385 350 L300 350" /><path d="M515 350 L600 350" /><path d="M450 415 L450 490" /></g>
<g class="map-label"><text x="30" y="80">北进口</text><text x="680" y="80">东进口</text><text x="30" y="635">南进口</text><text x="680" y="635">西进口</text></g>
<g fill="#173b32"><text x="655" y="520" class="map-label">预览中 · 路口边界</text></g>
</svg>
<div class="map-note">拖动绿色控制点调整几何;橙色设施可单独移动或编辑</div>
</section>
<aside class="inspector" aria-label="路口配置与诊断">
<section class="section">
<h2 class="section-title">路口几何</h2>
<p class="section-subtitle">修改后立即在画布显示服务端预览</p>
<div class="field"><label>北进口宽度<small>合法范围 3.6–12.0 m</small></label><div class="unit"><input value="7.20" /><span>m</span></div></div>
<div class="range"><i></i></div>
<div class="field"><label>东进口 cutback<small>合法范围 1.0–18.0 m</small></label><div class="unit"><input value="5.40" /><span>m</span></div></div>
<div class="range"><i style="width: 32%"></i></div>
<div class="field"><label>北→东角部圆角<small>合法范围 1.0–12.0 m</small></label><div class="unit"><input value="4.00" /><span>m</span></div></div>
<div class="range"><i style="width: 40%"></i></div>
</section>
<section class="section">
<h2 class="section-title">已有设施</h2>
<p class="section-subtitle">选择画布中的设施可编辑其语义参数</p>
<div class="facility"><span>斑马线 · 北侧</span><strong>6 条带 · 退让 1.5 m</strong></div>
<div class="facility"><span>停止线 · 北侧</span><strong>偏移 2.7 m</strong></div>
<div class="facility"><span>信号灯组 · 3 组</span><strong>可移动 / 可旋转</strong></div>
</section>
<section class="section">
<h2 class="section-title">验证诊断</h2>
<div class="diagnostic">当前几何合法,进口截面连续,路口面无自交。所有预览对象均落在所属道路范围内。</div>
</section>
<section class="section">
<div class="status"><span class="dot"></span><strong>预览已同步</strong><span>preview #18 · 142 ms</span></div>
</section>
<div class="actions">
<button class="action">放弃草稿</button>
<button class="action main">应用到工作区</button>
</div>
</aside>
</main>
<footer class="footer">
<strong>草稿 · 3 项未应用</strong>
<span>路口面、斑马线、停止线将随本次预览同步更新</span>
<div class="legend"><span class="geometry">几何控制</span><span class="facility-dot">设施控制</span></div>
</footer>
</div>
</body>
</html>
@@ -221,7 +221,7 @@ workbench-data/import-<id>/
主地图 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-<id>/
@@ -91,6 +91,17 @@
## 验收标准(交付阶段)
### 独立 JunctionTools 页面(重新确认,2026-09-03)
JunctionTools 必须是一个独立的路口编辑页面,而不是覆盖在主地图上的参数弹层。主地图只负责发现路口、显示入口和返回导航;进入 `/junction/:type/:id` 后,页面主要视觉对象是当前单个路口,不能被编辑面板遮挡。
- [ ] 页面自动聚焦并适配当前路口,持续显示路口面、进口道路、圆角、cutback、斑马线、停止线和信号灯。
- [ ] 几何编辑与已有设施编辑在同一页面完成,使用同一份 draft、preview、undo/redo、apply、save、cancel 状态。
- [ ] 参数输入和地图拖拽是同一参数的两个输入通道:任一通道变化都会在路口画布上显示权威预览,另一通道同步当前值。
- [ ] 预览失败时保留最后一个有效几何并显示结构化诊断;非法值不得显示成已应用几何。
- [ ] 首版支持已有斑马线、停止线、信号灯的可视化调整和已有字段编辑;设施创建、删除和跨路口迁移不在首版范围。
- [ ] 主地图的道路级编辑能力不因进入独立页面而消失;离开页面前必须明确应用、保存、放弃或继续停留。
每条都必须可执行验证,不接受"看起来对了"。
- [ ] 拖动道路外缘 → 保存 → 重新编译,道路面、步行带、车道线、标线与 connector 一致更新,约束状态为 `exact`。
+11 -4
View File
@@ -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,
+12 -5
View File
@@ -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;
+24
View File
@@ -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'] }],
+6 -1
View File
@@ -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();
});
});
+122 -12
View File
@@ -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<string>();
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<EditSelection | undefined>(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<string, number>();
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 (
<>
<div className={junctionRoute ? 'app junction-page' : 'app'}>
<header>
<strong>道路编译工作台</strong>
<label className="mode-switch">
@@ -906,8 +1004,9 @@ function App() {
</details>
</aside>
<MapCanvas
state={state}
state={junctionMapState!}
editMode={editMode}
focusJunctionId={junctionRoute?.type === 'node' ? junctionRoute.id : null}
selected={selected}
visible={layers}
scene={scene}
@@ -966,7 +1065,7 @@ function App() {
if (draft) commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]);
setStatus('箭头位置已暂存;保存并重新生成后应用。');
}}
preview={preview}
preview={junctionMapPreview}
ghostPending={session?.degraded ?? false}
onHandleDrag={(handle, value) => {
// Straight to the DOM, like the ghost writes straight to its source:
@@ -1037,7 +1136,7 @@ function App() {
facilitySummary={junctionFacilitySummary}
onClose={closeJunction}
onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))}
onDiscard={() => setJunctionSession((current) => (current ? cancelJunctionSession(current) : current))}
onDiscard={discardJunctionDraft}
onSave={() => {
try {
void saveDirectEdits().then((saved) => {
@@ -1052,19 +1151,30 @@ function App() {
editMode={editMode}
onEnableEdit={() => setEditMode(true)}
handles={junctionHandles}
onDraft={draftValue}
onDraft={(handle, value) => {
draftValue(handle, value);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onDraftGroup={(handles, value) => {
const draft = draftForGroup(handles, value);
if (draft) requester?.schedule(draft);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onSettle={(handle, value) => {
settleValue(handle, value);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onSettleGroup={settleGroup}
onAbandon={abandonGesture}
onReset={(handle) => {
resetHandle(handle);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
roads={junctionRoads}
junctionCoordinate={junctionDescriptor.coordinate}
/>
) : null}
</>
</div>
);
}
export default App;
+23 -6
View File
@@ -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;
@@ -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 (
<li className={reason ? 'parameter disabled' : 'parameter'}>
<span className="parameter-label">
{labelForHandle(handle)}
{displayLabel}
{isModified(handle) ? (
<>
<b className="parameter-dot" title="已修改" />
@@ -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({
}}
/>{' '}
<em>m</em>
<span className="parameter-stepper" aria-label={`${displayLabel}步进控制`}>
<button type="button" onMouseDown={nudge(-1)} disabled={Boolean(reason) || current <= min} title="减小">
<Minus size={13} />
</button>
<button type="button" onMouseDown={nudge(1)} disabled={Boolean(reason) || current >= max} title="增大">
<Plus size={13} />
</button>
</span>
</span>
<span className={rejected ? 'parameter-range rejected' : 'parameter-range'}>
{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<ParameterPanelHandle>;
}) {
const nodes = useRef(new Map<string, HTMLInputElement>());
@@ -264,18 +293,113 @@ export function ParameterPanel({
}
});
const groupedHandles = new Map<string, EditHandle[]>();
for (const handle of handles) {
const list = groupedHandles.get(handle.kind) ?? [];
list.push(handle);
groupedHandles.set(handle.kind, list);
}
return (
<section className="parameters">
<h1>道路参数</h1>
<h1>{grouped ? '路口参数' : '道路参数'}</h1>
{handles.length ? (
<ul>
{handles.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
grouped ? (
<GroupedParameterList groups={[...groupedHandles.entries()]} register={register} {...callbacks} />
) : (
<ul>
{handles.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
)
) : (
<p className="parameter-empty">{hasSelection ? '当前道路无可编辑参数' : '选中道路以显示参数'}</p>
)}
</section>
);
}
function GroupedParameterList({
groups,
register,
...callbacks
}: RowCallbacks & {
groups: Array<[string, EditHandle[]]>;
register: (handleId: string, node: HTMLInputElement | null) => void;
}) {
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
return (
<ul className="parameter-groups">
{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 (
<li className="parameter-group" key={kind}>
<div className="parameter-group__header">
<span>
<strong>{groupLabel(kind, representative)}</strong>
<small>统一设置 · {items.length} 项</small>
</span>
<button
type="button"
className="parameter-group__toggle"
onClick={() => setExpanded((current) => ({ ...current, [kind]: !expandedGroup }))}
>
{expandedGroup ? '收起单独定制' : '展开单独定制'}
</button>
</div>
<ParameterRow
handle={globalHandle}
register={register}
{...callbacks}
onDraft={(handle, value) => globalDraft(items, value)}
onSettle={(handle, value) => globalSettle(items, value)}
labelForHandle={() => '统一值'}
/>
{expandedGroup ? (
<ul className="parameter-group__details">
{items.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
) : null}
</li>
);
})}
</ul>
);
}
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);
}
+1 -1
View File
@@ -206,7 +206,7 @@ describe('labelForHandle', () => {
outgoingRoadId: 'seg:2',
}),
),
).toBe('角部圆角');
).toBe('seg:1 → seg:2 · 角部圆角');
});
});
+7
View File
@@ -130,6 +130,13 @@ const KIND_LABELS: Record<ConstraintKind, string> = {
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;
@@ -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<HandleManifest | null>(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,
@@ -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 (
<section className="junction-workspace" aria-label="路口编辑工作区">
<header className="junction-workspace__header">
<div>
<span className="junction-workspace__eyebrow">JunctionTools</span>
<h2>
{descriptor.ref.type === 'node' ? '路口节点' : '复杂路口上下文'} {descriptor.ref.id}
</h2>
<div className="junction-workspace__title-line">
<span className="junction-workspace__eyebrow">JunctionTools</span>
</div>
<p>
{editable
? editMode
@@ -65,9 +75,9 @@ export function JunctionWorkspace({
<div className="junction-workspace__body">
<dl>
<dt>组成节点</dt>
<dd>{descriptor.nodeIds.join(', ') || '—'}</dd>
<dd>{descriptor.nodeIds.length ? `${descriptor.nodeIds.length} 个路口节点` : '—'}</dd>
<dt>进口道路</dt>
<dd>{descriptor.approachRoadIds.join(', ') || '—'}</dd>
<dd>{roads.length ? roads.map((road) => junctionRoadName(road, roads)).join('、') : '—'}</dd>
<dt>诊断</dt>
<dd>{descriptor.diagnosticIds.length ? `${descriptor.diagnosticIds.length} 条` : '无'}</dd>
<dt>状态</dt>
@@ -98,10 +108,14 @@ export function JunctionWorkspace({
<ParameterPanel
handles={handles}
hasSelection
grouped
onDraft={onDraft ?? (() => undefined)}
onDraftGroup={onDraftGroup}
onSettle={onSettle ?? (() => undefined)}
onSettleGroup={onSettleGroup}
onAbandon={onAbandon ?? (() => undefined)}
onReset={onReset ?? (() => undefined)}
labelForHandle={(handle) => junctionLabelForHandle(handle, roads, junctionCoordinate)}
/>
<div className="junction-workspace__actions">
<Button onClick={onApply} disabled={!session.dirty}>
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import type { EditHandle } from '../edit/types';
import type { Road } from '../types/state';
import { junctionLabelForHandle } from './labels';
const roads = [
{
id: 'road-north',
segmentId: 'segment:way/-3254/0',
centerline: [
[120, 30],
[120, 30.001],
],
sourceNodeIds: ['junction'],
osmWayIds: [],
tags: { name: '创新大道' },
highway: 'primary',
direction: 'forward',
widthMeters: 7,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
{
id: 'road-east',
segmentId: 'segment:way/-3255/0',
centerline: [
[120, 30],
[120.001, 30],
],
sourceNodeIds: ['junction'],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
] as const;
function handle(anchor: EditHandle['anchor'], kind: EditHandle['kind']): EditHandle {
return {
handleId: 'h',
kind,
anchor,
position: [120, 30],
axisAzimuth: 0,
value: { current: 3, min: 1, max: 8, unit: 'meter' },
affects: [],
editable: true,
};
}
describe('junction handle labels', () => {
it('uses road name and geographic approach direction', () => {
expect(
junctionLabelForHandle(
handle(
{ type: 'junction-approach', nodeId: 'junction', segmentId: roads[0].segmentId },
'junction-approach-width',
),
roads as unknown as Road[],
[120, 30],
),
).toBe('创新大道 · 北进口 · 进口宽度');
});
it('uses a readable fallback when a road has no name', () => {
expect(
junctionLabelForHandle(
handle({ type: 'junction-approach', nodeId: 'junction', segmentId: roads[1].segmentId }, 'junction-cutback'),
roads as unknown as Road[],
[120, 30],
),
).toBe('道路2 · 东进口 · 进口 cutback');
});
});
+62
View File
@@ -0,0 +1,62 @@
import type { EditHandle } from '../edit/types';
import { azimuthBetween, haversineMeters, type Coordinate } from '../edit/meters';
import type { Road } from '../types/state';
import { labelForHandle } from '../edit/parameter';
const DIRECTIONS = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
function directionOf(azimuth: number): string {
return DIRECTIONS[Math.round((((azimuth % 360) + 360) % 360) / 45) % 8];
}
function roadForKey(roads: Road[], key: string): Road | undefined {
return roads.find((road) => road.id === key || road.segmentId === key);
}
function approachDirection(road: Road, junction: Coordinate): string | null {
if (road.centerline.length < 2) return null;
const first = road.centerline[0];
const last = road.centerline[road.centerline.length - 1];
const fromStart = haversineMeters(junction, first) <= haversineMeters(junction, last);
const outside = fromStart ? road.centerline[1] : road.centerline[road.centerline.length - 2];
return directionOf(azimuthBetween(junction, outside));
}
export function junctionRoadName(road: Road | undefined, roads: Road[] = []): string {
const name = road?.tags?.name?.trim();
if (name) return name;
const index = road ? roads.findIndex((item) => item.id === road.id) : -1;
return `道路${index >= 0 ? index + 1 : 1}`;
}
function approachName(road: Road | undefined, roads: Road[], junction: Coordinate): string {
if (!road) return '进口';
const direction = approachDirection(road, junction);
return `${junctionRoadName(road, roads)}${direction ? ` · ${direction}进口` : ' · 进口'}`;
}
/** User-facing labels for JunctionTools. Internal ids never appear in this text. */
export function junctionLabelForHandle(handle: EditHandle, roads: Road[], junction: Coordinate): string {
const base = labelForHandle(handle).replace(/^.* · /, '');
if (
(handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback') &&
handle.anchor.type === 'junction-approach'
) {
const anchor = handle.anchor;
const road = roads.find((item) => item.segmentId === anchor.segmentId);
return `${approachName(road, roads, junction)} · ${base}`;
}
if (handle.kind === 'junction-corner-radius' && handle.anchor.type === 'junction-corner') {
const incoming = roadForKey(roads, handle.anchor.incomingRoadId);
const outgoing = roadForKey(roads, handle.anchor.outgoingRoadId);
return `${approachName(incoming, roads, junction)} → ${approachName(outgoing, roads, junction)} · ${base}`;
}
if (
(handle.kind === 'junction-crosswalk-inset' || handle.kind === 'junction-stop-line-offset') &&
handle.anchor.type === 'junction-crossing'
) {
const road = roadForKey(roads, handle.anchor.roadId) ?? roadForKey(roads, handle.anchor.segmentId);
return `${approachName(road, roads, junction)} · ${base}`;
}
return base;
}
@@ -0,0 +1,115 @@
import { describe, expect, it } from 'vitest';
import { localJunctionPreview, localJunctionState } from './local-state';
import type { JunctionDescriptor } from './hotspots';
import type { WorkbenchState } from '../types/state';
const descriptor: JunctionDescriptor = {
ref: { type: 'node', id: 'junction-1' },
status: 'editable',
coordinate: [120, 30],
radiusMeters: 10,
nodeIds: ['junction-1'],
approachRoadIds: ['road-a'],
diagnosticIds: [],
source: 'junction-plan',
};
const state = {
areaId: 'test',
compiled: {
model: {
roads: [
{
id: 'road-a',
segmentId: 'segment-a',
sourceNodeIds: ['junction-1', 'end-a'],
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
{
id: 'road-b',
segmentId: 'segment-b',
sourceNodeIds: ['other', 'end-b'],
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
],
endpoints: [
{ id: 'endpoint-a', roadId: 'road-a', side: 'end', nodeId: 'junction-1', coordinate: [120, 30] },
{ id: 'endpoint-b', roadId: 'road-b', side: 'end', nodeId: 'other', coordinate: [121, 31] },
],
connections: [{ id: 'connection-a', fromEndpointId: 'endpoint-a', toEndpointId: 'endpoint-a', enabled: true }],
},
movements: [],
diagnostics: [],
},
layers: {
nativeRoadSurface: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { road_id: 'road-a' }, geometry: null },
{ type: 'Feature', properties: { road_id: 'road-b' }, geometry: null },
],
},
crosswalks: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { crossing_node_id: 'junction-1' }, geometry: null },
{ type: 'Feature', properties: { crossing_node_id: 'other' }, geometry: null },
],
},
},
overrides: { schema: 'test', overrides: [] },
trafficSignals: { provenance: 'test', assemblies: { type: 'FeatureCollection', features: [] } },
trafficRuntime: { signals: [] },
comparison: {},
} as unknown as WorkbenchState;
describe('local junction state', () => {
it('keeps only the selected junction roads and related features', () => {
const local = localJunctionState(state, descriptor);
expect(local.compiled.model.roads.map((road) => road.id)).toEqual(['road-a']);
expect(local.layers.nativeRoadSurface?.features).toHaveLength(1);
expect(local.layers.crosswalks?.features).toHaveLength(1);
expect(local.compiled.model.endpoints.map((endpoint) => endpoint.id)).toEqual(['endpoint-a']);
});
it('scopes preview collections to the selected junction', () => {
const preview = localJunctionPreview(
{
roadSurface: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { road_id: 'road-a' }, geometry: null },
{ type: 'Feature', properties: { road_id: 'road-b' }, geometry: null },
],
},
crosswalks: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { crossing_node_id: 'junction-1' }, geometry: null },
{ type: 'Feature', properties: { crossing_node_id: 'other' }, geometry: null },
],
},
},
descriptor,
state.compiled.model.roads,
);
expect(preview?.roadSurface?.features).toHaveLength(1);
expect(preview?.crosswalks?.features).toHaveLength(1);
});
});
@@ -0,0 +1,128 @@
import type { GeoFeature, GeoJson, Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from './hotspots';
import type { PreviewLayerName } from '../edit/types';
const empty: GeoJson = { type: 'FeatureCollection', features: [] };
function text(value: unknown): string | null {
return typeof value === 'string' || typeof value === 'number' ? String(value) : null;
}
function related(feature: GeoFeature, nodeIds: Set<string>, roadIds: Set<string>, segmentIds: Set<string>): boolean {
const props = feature.properties || {};
const nodeKeys = ['node_id', 'osm_node_id', 'crossing_node_id', 'junction_node_id'];
if (
nodeKeys.some((key) => {
const value = text(props[key]);
return value !== null && nodeIds.has(value);
})
)
return true;
const roadKeys = ['road_id', 'source_road_id', 'from_road_id', 'to_road_id', 'roadId'];
if (
roadKeys.some((key) => {
const value = text(props[key]);
return value !== null && roadIds.has(value);
})
)
return true;
const segment = text(props.segment_id);
if (segment && segmentIds.has(segment)) return true;
const directional = text(props.directional_road_ids);
return Boolean(directional && [...roadIds].some((id) => directional.split(',').includes(id)));
}
/**
* Keep server preview collections scoped to the independent junction canvas.
* Preview responses are solved from the junction manifest, but some compiler
* layers still contain the surrounding area; showing those collections would
* make a keyboard edit appear to jump back to the global map.
*/
export function localJunctionPreview(
preview: Partial<Record<PreviewLayerName, GeoJson | null>> | null | undefined,
descriptor: JunctionDescriptor,
roads: Road[],
): Partial<Record<PreviewLayerName, GeoJson | null>> | null {
if (!preview) return preview ?? null;
const nodeIds = new Set(descriptor.nodeIds.map(String));
const selectedRoads = roads.filter((road) => descriptor.approachRoadIds.includes(road.id));
const roadIds = new Set(selectedRoads.map((road) => road.id));
const segmentIds = new Set(selectedRoads.map((road) => road.segmentId));
const scoped = { ...preview };
for (const name of Object.keys(preview) as PreviewLayerName[]) {
const value = preview[name];
if (value === null || value === undefined) continue;
scoped[name] = {
type: 'FeatureCollection',
features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds)),
};
}
return scoped;
}
/** Build the intentionally small state consumed by the independent junction canvas. */
export function localJunctionState(state: WorkbenchState, descriptor: JunctionDescriptor): WorkbenchState {
const nodeIds = new Set(descriptor.nodeIds.map(String));
const roads = state.compiled.model.roads.filter((road) => descriptor.approachRoadIds.includes(road.id));
const roadIds = new Set(roads.map((road) => road.id));
const segmentIds = new Set(roads.map((road) => road.segmentId));
const keep = (value: GeoJson | null | undefined): GeoJson => ({
type: 'FeatureCollection',
features: (value?.features || []).filter((feature) => related(feature, nodeIds, roadIds, segmentIds)),
});
const layerNames = [
'nativeRoadSurface',
'nativeIntersectionSurface',
'nativeSidewalkSurface',
'laneCenterlines',
'laneSeparators',
'centerLines',
'directionArrows',
'turnArrows',
'crosswalks',
'vehicleStopLines',
'connectors',
'edgeLines',
];
const layers = { ...state.layers } as Record<string, GeoJson | null>;
for (const name of layerNames) layers[name] = keep(state.layers[name]);
layers.nativeRoadSurface = keep(state.layers.nativeRoadSurface);
layers.nativeIntersectionSurface = keep(state.layers.nativeIntersectionSurface);
const signals = state.trafficSignals.assemblies.features.filter((feature) =>
related(feature, nodeIds, roadIds, segmentIds),
);
return {
...state,
compiled: {
...state.compiled,
model: {
...state.compiled.model,
roads,
endpoints: state.compiled.model.endpoints.filter(
(endpoint) => nodeIds.has(String(endpoint.nodeId)) || roadIds.has(endpoint.roadId),
),
connections: state.compiled.model.connections.filter((connection) => {
const endpointIds = new Set(
state.compiled.model.endpoints
.filter((endpoint) => roadIds.has(endpoint.roadId) || nodeIds.has(String(endpoint.nodeId)))
.map((endpoint) => endpoint.id),
);
return endpointIds.has(connection.fromEndpointId) || endpointIds.has(connection.toEndpointId);
}),
},
movements: state.compiled.movements?.filter(
(movement) => roadIds.has(movement.fromRoadId) || roadIds.has(movement.toRoadId),
),
diagnostics: state.compiled.diagnostics.filter((item) =>
related(
{ type: 'Feature', properties: item as unknown as Record<string, unknown>, geometry: item.geometry || null },
nodeIds,
roadIds,
segmentIds,
),
),
},
layers,
trafficSignals: { ...state.trafficSignals, assemblies: { ...state.trafficSignals.assemblies, features: signals } },
};
}
+25 -2
View File
@@ -9,6 +9,7 @@ import Fill from 'ol/style/Fill';
import RegularShape from 'ol/style/RegularShape';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';
import { offsetCoordinate, type Coordinate } from '../edit/meters';
import type { Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from '../junction/hotspots';
@@ -54,6 +55,15 @@ export function createLayers(
color: f.get('road_id') === onRoad()?.id ? '#006e91' : '#263630',
width: f.get('road_id') === onRoad()?.id ? 5 : 2,
}),
text: f.get('road_label_visible')
? new Text({
text: String(f.get('road_label') || ''),
font: '600 12px sans-serif',
fill: new Fill({ color: '#f8fafc' }),
stroke: new Stroke({ color: '#17211f', width: 4 }),
overflow: true,
})
: undefined,
}),
}),
lanes: new VectorLayer({
@@ -185,7 +195,12 @@ function features(value: unknown) {
featureProjection: 'EPSG:3857',
});
}
export function updateLayers(layers: ReturnType<typeof createLayers>, state: WorkbenchState, selected: Road | null) {
export function updateLayers(
layers: ReturnType<typeof createLayers>,
state: WorkbenchState,
selected: Road | null,
showRoadLabels = false,
) {
const get = (name: LayerName) => layers[name].getSource()!;
const put = (name: LayerName, value: unknown) => {
const target = get(name);
@@ -195,9 +210,17 @@ export function updateLayers(layers: ReturnType<typeof createLayers>, state: Wor
put('native', state.layers.nativeRoadSurface);
get('native').addFeatures(features(state.layers.nativeIntersectionSurface));
put('sidewalks', state.layers.nativeSidewalkSurface);
const unnamedRoadNumber = new Map(
state.compiled.model.roads.filter((road) => !road.tags.name?.trim()).map((road, index) => [road.id, index + 1]),
);
const roads = state.compiled.model.roads.map(
(road) =>
new Feature({ geometry: new LineString(road.centerline).transform('EPSG:4326', 'EPSG:3857'), road_id: road.id }),
new Feature({
geometry: new LineString(road.centerline).transform('EPSG:4326', 'EPSG:3857'),
road_id: road.id,
road_label_visible: showRoadLabels,
road_label: road.tags.name?.trim() || `道路${unnamedRoadNumber.get(road.id) || 1}`,
}),
);
put('osm', { type: 'FeatureCollection', features: [] });
get('osm').addFeatures(roads);
+123
View File
@@ -315,6 +315,40 @@ pre {
display: grid;
gap: 6px;
}
.parameter-group {
display: grid;
gap: 6px;
}
.parameter-group__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 7px 8px 0;
color: #52615b;
}
.parameter-group__header span {
display: grid;
gap: 2px;
}
.parameter-group__header small {
color: #7b8a83;
font-size: 11px;
}
.parameter-group__toggle {
border: 0;
background: none;
color: #286956;
cursor: pointer;
font-size: 12px;
padding: 3px 0;
text-decoration: underline;
}
.parameter-group__details {
margin: 0 0 0 12px;
padding-left: 8px;
border-left: 2px solid #dce5e1;
}
.parameter {
display: grid;
grid-template-columns: 1fr auto;
@@ -346,6 +380,26 @@ pre {
font-size: 12px;
font-style: normal;
}
.parameter-stepper {
display: inline-flex;
gap: 2px;
margin-left: 2px;
}
.parameter-stepper button {
display: inline-grid;
width: 22px;
height: 22px;
place-items: center;
padding: 0;
border: 1px solid #b7c8bf;
border-radius: 3px;
background: #f8fbf9;
color: #286956;
}
.parameter-stepper button:disabled {
opacity: 0.45;
cursor: default;
}
.parameter-range {
grid-column: 1 / -1;
color: #7b8a83;
@@ -546,6 +600,57 @@ pre {
box-shadow: 0 14px 40px rgb(15 23 42 / 20%);
padding: 1rem 1.25rem;
}
.junction-page {
min-height: 100vh;
}
.junction-page > header {
display: none;
}
.junction-page > main {
height: 100vh;
grid-template-columns: minmax(0, 1fr);
background: #d7e2de;
}
.junction-page > main > .issues,
.junction-page > main > .inspector {
display: none;
}
.junction-page .junction-workspace {
top: 0;
right: 0;
bottom: 0;
width: min(430px, 38vw);
border-radius: 0;
border-top: 0;
border-right: 0;
border-bottom: 0;
box-shadow: -16px 0 36px rgb(15 23 42 / 18%);
}
.junction-page .junction-workspace__header {
position: sticky;
z-index: 2;
top: -1rem;
margin: -1rem -1.25rem 1.5rem;
padding: 1rem 1.25rem;
align-items: center;
background: #173b32;
color: #f4fbf7;
border-bottom: 1px solid #2e594d;
}
.junction-page .junction-workspace__header p,
.junction-page .junction-workspace__eyebrow {
color: #abc5ba;
}
.junction-page .junction-workspace__header .button {
border-color: #97b5a8;
background: #eff7f2;
}
.junction-page .junction-workspace__header h2 {
font-size: 1.15rem;
}
.junction-page .junction-workspace__body {
max-width: none;
}
.junction-workspace__header {
display: flex;
justify-content: space-between;
@@ -561,6 +666,23 @@ pre {
.junction-workspace__header h2 {
margin: 0.2rem 0;
}
.junction-workspace__title-line {
display: flex;
align-items: baseline;
gap: 0.65rem;
min-width: 0;
}
.junction-workspace__title-line h2 {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.junction-workspace__title-line code {
color: inherit;
font-size: 0.8em;
font-weight: 500;
}
.junction-workspace__header p {
margin: 0;
color: #64748b;
@@ -570,6 +692,7 @@ pre {
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.08em;
white-space: nowrap;
}
.junction-workspace__body {
max-width: 42rem;