feat(junction): enable complex carriageway width editing

This commit is contained in:
que01 committed 2026-09-08 12:09:44 +08:00
1 parent 56647fcdaa
commit c4bcbe8ff9
22 files changed
+449 -52

No files matched your search

+12 -2
View File
@@ -10,7 +10,7 @@ It is required because the feature crosses compiler, storage, and HTTP layers.
```js
resolveDirectEditConstraints(model, editDocument, context)
// -> { roadProfiles, junctionPlans, constraintStates, handles, diagnostics }
// -> { roadProfiles, junctionPlans, clusterPlans, constraintStates, handles, diagnostics }
GET /api/edit-state
POST /api/edit-preview
@@ -316,7 +316,17 @@ then `structureFromTopology(topology, shape, center, features)`. Projection is
`cluster:<id>`. The legacy singular field is null at this unscoped entry point.
- `GET /api/edit-state?junction=<node>` preserves the node selection contract;
`?cluster=<id>` selects a cluster. Preview uses the equivalent `selection`
object. Cluster handle manifests are empty until a future writable contract.
object. A selected editable cluster publishes only `cluster-carriageway-width`
handles for its external carriageways.
- A `cluster-carriageway-width` anchor contains `clusterId`, stable
`carriagewayKey`, `sourceNodeIds`, and `sourceRoadIds`. Replay matches all
source identity; a missing or changed source is stale with `anchor-missing`.
The solver stores accepted values in `clusterPlans`, and `compileGeometry()`
applies them to the matching complex-junction approach before geometry is
generated. It must not widen unrelated member-node approaches.
- Preview and save both evaluate the same candidate through the resolver and
`compileGeometry()`. Save rejects every `severity: error` diagnostic before
writing the edit document.
- Complex road-surface features carry `junction_key`, `object_key` and relevant
`arm_key`, `carriageway_key`, `corner_key`. Core (or the first remaining
approach when the core fails) carries `junction_structure` for persisted reads.
+14 -1
View File
@@ -256,7 +256,9 @@ one. `handle.constraintId` — present only when a constraint exists — is also
- [ ] Constraints sent with their operations
- [ ] No geometry or OL reads inside a `setState` updater
- [ ] No per-`pointermove` React state updates
- [ ] Flag off ⇒ no sources, no layers, no interactions, no requests
- [ ] Flag off ⇒ no sources, layers, or interactions. A selected complex
JunctionTools workspace may request its scoped manifest solely to discover
server-published edit capability before the edit switch is enabled.
- [ ] Every input channel meets at the shared exits, not a parallel path
- [ ] Displayed bounds round inward, so an offered extreme is accepted
- [ ] A focused field is not rewritten by an arriving preview
@@ -279,6 +281,17 @@ reuse the unscoped singular structure when its ref differs. A missing structure
stays unavailable. Use `junctionEditSelection(ref)` for edit-state and preview
requests so a cluster never falls back to the last selected road or node.
## 17. Complex carriageway width editing
Complex JunctionTools consumes the same v2 `EditSession`, `PreviewRequester`,
`ParameterPanel`, and map handle callbacks as ordinary junctions. The only
editable handle in this stage is `cluster-carriageway-width` with a
`cluster-carriageway` anchor. Before edit mode, a selected cluster loads its
scoped manifest so `canEditJunction()` can use an editable server handle as the
capability signal. Once enabled, those same handles are rendered on the map and
in the panel; `App.tsx` resolves the anchor snapshot from `sourceRoadIds[0]`.
Do not add a cluster-local draft, preview, undo, or save flow.
Compiler structure provenance supplies cluster hotspots and external road IDs.
`localJunctionState` and `localJunctionPreview` recognize explicit `junction_key`
(and legacy `cluster_id`) before testing node/road references. This keeps core
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "cj-02-width",
"title": "复杂路口 02:宽度编辑端到端闭环",
"description": "完成第一条可用的复杂路口宽度编辑链路,让用户能看到真实几何变化并保存保留。",
"status": "planning",
"status": "in_progress",
"dev_type": "fullstack",
"scope": "junction",
"package": null,
@@ -32,4 +32,4 @@
],
"notes": "依赖:01 验收通过。规划已补齐,等待最终评审后启动;不表示实现已完成。",
"meta": {}
}
}
+164 -9
View File
@@ -13,6 +13,7 @@ const {
junctionSurfaceId,
connectionConnectorId,
} = require('./native-ids');
const { topologyIdentity } = require('./junction-topology');
const RESOLUTION_SCHEMA = 'road-edit-resolution/v1';
const HANDLE_MANIFEST_SCHEMA = 'road-edit-handles/v1';
@@ -22,6 +23,7 @@ const SOLVED_KINDS = new Set([
'road-sidewalk-width',
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
@@ -34,6 +36,7 @@ const KINDS = [
'road-sidewalk-width',
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
@@ -154,6 +157,12 @@ function constraintFor(constraints, kind, anchor) {
item.anchor.incomingRoadId === anchor.incomingRoadId &&
item.anchor.outgoingRoadId === anchor.outgoingRoadId
);
if (kind === 'cluster-carriageway-width')
return (
item.anchor.type === 'cluster-carriageway' &&
item.anchor.clusterId === anchor.clusterId &&
item.anchor.carriagewayKey === anchor.carriagewayKey
);
if (kind === 'junction-crosswalk-inset' || kind === 'junction-stop-line-offset')
return (
item.anchor.type === 'junction-crossing' &&
@@ -171,6 +180,49 @@ function constraintFor(constraints, kind, anchor) {
});
}
function clusterCarriageways(model, junctionData, clusters) {
const result = new Map();
for (const cluster of Array.isArray(clusters) ? clusters : []) {
if (!cluster?.id || !Array.isArray(cluster.nodeIds)) continue;
const nodeIds = new Set(cluster.nodeIds.map(String));
const items = [];
for (const nodeId of nodeIds) {
for (const approach of junctionData.approaches.get(nodeId) || []) {
const roads = approach.items.map((item) => item.road);
const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2);
const internal =
sourced.length &&
sourced.every(
(road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))),
);
if (internal || !roads.length) continue;
const source = {
nodeId: String(nodeId),
approach: { segmentId: approach.segmentId, roadIds: roads.map((road) => road.id) },
roads,
};
items.push({
clusterId: String(cluster.id),
nodeId: String(nodeId),
approach,
roads,
key: `cluster:${encodeURIComponent(cluster.id)}:carriageway:${topologyIdentity(source)}`,
sourceNodeIds: [...new Set(roads.flatMap((road) => (road.sourceNodeIds || []).map(String)))].sort(),
sourceRoadIds: roads.map((road) => String(road.id)).sort(),
widthMeters: approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0),
laneCount: roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0),
});
}
}
const seen = new Set();
result.set(
String(cluster.id),
items.filter((item) => !seen.has(item.key) && seen.add(item.key)),
);
}
return result;
}
function numericValue(constraint, key, fallback) {
const value = constraint?.value?.[key];
return Number.isFinite(value) ? value : fallback;
@@ -243,6 +295,11 @@ function roadForLaneAnchor(model, laneAnchorId) {
}
function reconcileConstraints(model, constraints, base, junctionData, context) {
const clusterItems = clusterCarriageways(
model,
junctionData,
context.junctionTemplates?.clusters || context.junctionClusters || [],
);
const versionChanged = Boolean(
context.compilerGeometryVersion &&
base?.compilerGeometryVersion &&
@@ -258,6 +315,19 @@ function reconcileConstraints(model, constraints, base, junctionData, context) {
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind === 'cluster-carriageway-width') {
const item = clusterItems
.get(String(constraint.anchor.clusterId))
?.find((candidate) => candidate.key === constraint.anchor.carriagewayKey);
const sourcesMatch =
item &&
JSON.stringify(item.sourceNodeIds) ===
JSON.stringify([...constraint.anchor.sourceNodeIds].map(String).sort()) &&
JSON.stringify(item.sourceRoadIds) === JSON.stringify([...constraint.anchor.sourceRoadIds].map(String).sort());
if (!sourcesMatch) return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind.startsWith('road-')) {
const road = roadForAnchor(model, constraint.anchor.roadId);
matched = Boolean(road);
@@ -600,11 +670,13 @@ function applyJunctionConstraint(model, constraint, junctionPlans, junctionData,
}
}
function solveConstraints(model, constraints, junctionData, diagnostics) {
function solveConstraints(model, constraints, junctionData, diagnostics, clusters = []) {
const roadProfiles = new Map();
const junctionPlans = new Map();
const laneManeuvers = new Map();
const crossingControls = new Map();
const clusterPlans = new Map();
const clusterItems = clusterCarriageways(model, junctionData, clusters);
const states = [];
for (const constraint of constraints) {
if (!constraint.enabled) {
@@ -634,6 +706,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics) {
);
const laneSnapshot = new Map(laneManeuvers);
const crossingSnapshot = new Map([...crossingControls].map(([key, value]) => [key, { ...value }]));
const clusterSnapshot = new Map([...clusterPlans].map(([key, value]) => [key, new Map(value)]));
const junctionSnapshot = new Map(
[...junctionPlans].map(([key, plan]) => [
key,
@@ -645,7 +718,32 @@ function solveConstraints(model, constraints, junctionData, diagnostics) {
]),
);
let applied;
if (constraint.kind === 'lane-maneuver') {
if (constraint.kind === 'cluster-carriageway-width') {
const item = clusterItems
.get(String(constraint.anchor?.clusterId))
?.find((candidate) => candidate.key === constraint.anchor?.carriagewayKey);
const width = Number(constraint.value?.widthMeters);
if (!item) {
blocking(diagnostics, constraint, 'direct-edit-cluster-carriageway-missing', '复杂路口车行道锚点不存在。');
applied = false;
} else if (
!Number.isFinite(width) ||
width < Math.max(MIN_LANE_WIDTH_METERS, item.laneCount * MIN_LANE_WIDTH_METERS) ||
width > item.widthMeters * 2
) {
blocking(
diagnostics,
constraint,
'direct-edit-cluster-carriageway-width-invalid',
'复杂路口车行道宽度超出当前可用范围。',
);
applied = false;
} else {
if (!clusterPlans.has(item.clusterId)) clusterPlans.set(item.clusterId, new Map());
clusterPlans.get(item.clusterId).set(item.key, width);
applied = true;
}
} else if (constraint.kind === 'lane-maneuver') {
const laneId = constraint.anchor?.laneId;
const laneExists = Boolean(roadForLaneAnchor(model, laneId));
const maneuver = constraint.value?.maneuver;
@@ -680,10 +778,12 @@ function solveConstraints(model, constraints, junctionData, diagnostics) {
for (const [key, value] of laneSnapshot) laneManeuvers.set(key, value);
crossingControls.clear();
for (const [key, value] of crossingSnapshot) crossingControls.set(key, value);
clusterPlans.clear();
for (const [key, value] of clusterSnapshot) clusterPlans.set(key, value);
}
states.push(constraintState(constraint, applied, applied ? null : 'invalid'));
}
return { roadProfiles, junctionPlans, laneManeuvers, crossingControls, states };
return { roadProfiles, junctionPlans, laneManeuvers, crossingControls, clusterPlans, states };
}
function roadAffects(roads, model, side, boundaryIndex) {
@@ -1079,6 +1179,45 @@ function makeJunctionHandles(model, junctionData, constraints) {
return handles;
}
function makeClusterCarriagewayHandles(model, junctionData, constraints, clusters) {
const handles = [];
for (const [clusterId, items] of clusterCarriageways(model, junctionData, clusters)) {
for (const item of items) {
const road = item.roads[0];
const line = item.approach.endpoint.side === 'start' ? road.centerline : [...road.centerline].reverse();
const station = Math.min(0.95, Math.max(0.05, item.approach.cutback / Math.max(item.approach.length, 1)));
const point = coordinateAt(line, station);
const constraint = constraintFor(constraints, 'cluster-carriageway-width', {
clusterId,
carriagewayKey: item.key,
});
handles.push({
handleId: `handle:cluster-carriageway-width:${item.key}`,
kind: 'cluster-carriageway-width',
anchor: {
type: 'cluster-carriageway',
clusterId,
carriagewayKey: item.key,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
},
position: point,
axisAzimuth: (tangentAzimuth(line, station) + 90) % 360,
value: {
current: numericValue(constraint, 'widthMeters', item.widthMeters),
min: Math.max(MIN_LANE_WIDTH_METERS, item.laneCount * MIN_LANE_WIDTH_METERS),
max: Math.max(item.widthMeters * 2, item.laneCount * MIN_LANE_WIDTH_METERS),
unit: 'meter',
},
...(constraint ? { constraintId: constraint.id } : {}),
affects: [`complex-junction:${clusterId}:carriageway:${item.approach.segmentId}`],
editable: true,
});
}
}
return handles;
}
/**
* Which handles a selection wants.
*
@@ -1093,8 +1232,10 @@ function makeJunctionHandles(model, junctionData, constraints) {
*/
function selectHandles(handles, model, selection) {
if (!selection || !selection.type) return handles;
// Cluster object identities are read-only until their geometry edit path exists.
if (selection.type === 'cluster') return [];
if (selection.type === 'cluster')
return handles.filter(
(handle) => handle.kind === 'cluster-carriageway-width' && handle.anchor?.clusterId === String(selection.id),
);
if (selection.type === 'segment') {
const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId]));
const wanted = String(selection.id);
@@ -1124,18 +1265,21 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
const groups = roadGroups(model || {});
const junctionData = junctionReserves(model || {});
const reconciled = reconcileConstraints(model || {}, constraints, editDocument?.base, junctionData, context);
const solved = solveConstraints(model || {}, reconciled, junctionData, diagnostics);
const clusters = context.junctionTemplates?.clusters || context.junctionClusters || [];
const solved = solveConstraints(model || {}, reconciled, junctionData, diagnostics, clusters);
const effectiveJunctionPlans = buildEffectiveJunctionPlans(
model || {},
solved.junctionPlans,
junctionData,
context.junctionTemplates?.clusters || context.junctionClusters || [],
clusters,
solved.clusterPlans,
);
handles.reserves = junctionData.reserves;
handles.handles = selectHandles(
[
...makeRoadHandles(model || {}, groups, handles.reserves, reconciled, solved.roadProfiles),
...makeJunctionHandles(model || {}, junctionData, reconciled),
...makeClusterCarriagewayHandles(model || {}, junctionData, reconciled, clusters),
...makeLaneManeuverHandles(model || {}, reconciled),
],
model || {},
@@ -1147,6 +1291,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
junctionPlans: solved.junctionPlans,
effectiveJunctionPlans,
crossingControls: solved.crossingControls,
clusterPlans: solved.clusterPlans,
laneManeuvers: solved.laneManeuvers,
handles,
constraintStates: solved.states,
@@ -1158,7 +1303,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
// JunctionTools. Clusters deliberately remain read-only in this phase: their
// effective plan is assembled from member nodes without rewriting constraints or
// silently splitting the cluster into independent editors.
function buildEffectiveJunctionPlans(model, solvedPlans, junctionData, clusters = []) {
function buildEffectiveJunctionPlans(model, solvedPlans, junctionData, clusters = [], clusterPlans = new Map()) {
const nodePlan = (nodeId) => {
const id = String(nodeId);
const solved = solvedPlans.get(id);
@@ -1206,13 +1351,23 @@ function buildEffectiveJunctionPlans(model, solvedPlans, junctionData, clusters
})),
);
const corners = Object.assign({}, ...members.map((member) => member.corners || {}));
const carriageways = clusterCarriageways(model, junctionData, [cluster]).get(String(cluster.id)) || [];
const widths = clusterPlans.get(String(cluster.id)) || new Map();
result.set(`cluster:${cluster.id}`, {
schema: 'junction-effective-plan/v1',
junctionRef: { type: 'cluster', id: String(cluster.id) },
nodeIds: cluster.nodeIds.map(String),
approaches,
carriageways: carriageways.map((item) => ({
key: item.key,
nodeId: item.nodeId,
segmentId: item.approach.segmentId,
widthMeters: widths.get(item.key) ?? item.widthMeters,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
})),
corners,
readOnly: true,
readOnly: false,
});
}
return result;
+18 -1
View File
@@ -13,6 +13,7 @@ const CONSTRAINT_ANCHORS = {
'road-sidewalk-width': 'road-interval',
'road-lane-divider': 'road-interval',
'junction-approach-width': 'junction-approach',
'cluster-carriageway-width': 'cluster-carriageway',
'junction-cutback': 'junction-approach',
'junction-corner-radius': 'junction-corner',
'junction-crosswalk-inset': 'junction-approach',
@@ -27,6 +28,7 @@ const ANCHOR_TYPES = new Set([
'junction-approach',
'junction-crossing',
'junction-corner',
'cluster-carriageway',
'lane',
]);
const CONSTRAINT_STATUSES = new Set(['exact', 'recheck', 'pending', 'conflicted', 'stale']);
@@ -93,6 +95,21 @@ function validateAnchor(scope, kind, anchor) {
} else if (expected === 'junction-approach') {
requireString(scope, 'anchor.nodeId', anchor.nodeId);
requireString(scope, 'anchor.segmentId', anchor.segmentId);
} else if (expected === 'cluster-carriageway') {
requireString(scope, 'anchor.clusterId', anchor.clusterId);
requireString(scope, 'anchor.carriagewayKey', anchor.carriagewayKey);
if (
!Array.isArray(anchor.sourceNodeIds) ||
!anchor.sourceNodeIds.length ||
!anchor.sourceNodeIds.every((id) => typeof id === 'string' && id)
)
fail(scope, 'anchor.sourceNodeIds', 'must be a non-empty array of source node IDs');
if (
!Array.isArray(anchor.sourceRoadIds) ||
!anchor.sourceRoadIds.length ||
!anchor.sourceRoadIds.every((id) => typeof id === 'string' && id)
)
fail(scope, 'anchor.sourceRoadIds', 'must be a non-empty array of source road IDs');
} else if (expected === 'junction-crossing') {
requireString(scope, 'anchor.crossingId', anchor.crossingId);
requireString(scope, 'anchor.nodeId', anchor.nodeId);
@@ -131,7 +148,7 @@ function validateValue(scope, kind, value) {
if (!isFiniteNumber(value.offsetMeters))
fail(scope, 'value.offsetMeters', 'must be a finite signed offset from the centerline');
validateTransition(scope, value);
} else if (kind === 'junction-approach-width') {
} else if (kind === 'junction-approach-width' || kind === 'cluster-carriageway-width') {
if (!isFiniteNumber(value.widthMeters) || value.widthMeters <= 0)
fail(scope, 'value.widthMeters', 'must be a positive number of meters');
} else if (kind === 'junction-cutback') {
+24 -1
View File
@@ -3,7 +3,11 @@
const fs = require('fs');
const path = require('path');
const { arrowRingsAt, normalizeManeuver } = require('./turn-lane-arrows');
const { buildComplexJunctionGeometry, complexJunctionMetrics } = require('./complex-junction');
const {
buildComplexJunctionGeometry,
complexJunctionMetrics,
resolveComplexJunctionTopology,
} = require('./complex-junction');
const { diagnostic } = require('./diagnostics');
// Default marking placement lives with the constraint bounds in the solver, which
// is the IO-free module; importing the other way would drag fs into it.
@@ -624,6 +628,7 @@ function compileGeometry(model, overrides = { overrides: [] }, options = {}) {
const diagnostics = [...model.diagnostics];
const junctionPlans = compileJunctionPlans(model, options, diagnostics);
applyDirectJunctionPlans(junctionPlans, options.directEdit);
applyDirectClusterPlans(model, junctionPlans, options.directEdit, options.junctionTemplates?.clusters || []);
detectComplexJunctionCandidates(model, junctionPlans, options, diagnostics);
const features = [];
const activeClusters = options.junctionTemplates?.enabled ? options.junctionTemplates.clusters || [] : [];
@@ -906,6 +911,24 @@ function applyDirectJunctionPlans(plans, directEdit) {
}
}
function applyDirectClusterPlans(model, junctionPlans, directEdit, clusters) {
if (!directEdit?.clusterPlans?.size) return;
for (const [clusterId, widths] of directEdit.clusterPlans) {
const cluster = clusters.find((item) => String(item.id) === String(clusterId));
if (!cluster || cluster.template !== 'complex-junction-v1') continue;
const topology = resolveComplexJunctionTopology(model, cluster, {
junctionPlans,
distanceMeters,
lineLengthMeters,
headingAtEndpoint,
});
for (const item of topology.carriageways) {
const width = widths.get(item.key);
if (Number.isFinite(width)) item.approach.widthMeters = width;
}
}
}
function compileComplexPreviewArrows(features, stopLines) {
const result = [];
for (const feature of features) {
+33 -1
View File
@@ -354,10 +354,42 @@ const clusterResolution = resolveDirectEditConstraints(junctionModel, document(a
});
const clusterPlan = clusterResolution.effectiveJunctionPlans.get('cluster:cluster-1');
assert.ok(clusterPlan);
assert.equal(clusterPlan.readOnly, true);
assert.equal(clusterPlan.readOnly, false);
assert.deepEqual(clusterPlan.junctionRef, { type: 'cluster', id: 'cluster-1' });
assert.equal(clusterPlan.approaches.find((item) => item.segmentId === 'segment:a').widthMeters, 7);
const clusterHandleResolution = resolveDirectEditConstraints(junctionModel, document([]), {
junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }],
selection: { type: 'cluster', id: 'cluster-1' },
});
const clusterWidthHandle = clusterHandleResolution.handles.handles.find(
(handle) => handle.kind === 'cluster-carriageway-width',
);
assert.ok(clusterWidthHandle, 'a cluster selection publishes only its external carriageway widths');
const widenedCluster = resolveDirectEditConstraints(
junctionModel,
document([
constraint({
id: 'cluster-carriageway-width',
kind: 'cluster-carriageway-width',
anchor: clusterWidthHandle.anchor,
value: { widthMeters: clusterWidthHandle.value.current + 0.5 },
}),
]),
{ junctionClusters: [{ id: 'cluster-1', nodeIds: ['junction'] }] },
);
assert.equal(widenedCluster.constraintStates[0].applied, true);
assert.equal(
widenedCluster.clusterPlans.get('cluster-1').get(clusterWidthHandle.anchor.carriagewayKey),
clusterWidthHandle.value.current + 0.5,
);
assert.equal(
widenedCluster.effectiveJunctionPlans
.get('cluster:cluster-1')
.carriageways.find((item) => item.key === clusterWidthHandle.anchor.carriagewayKey).widthMeters,
clusterWidthHandle.value.current + 0.5,
);
const recheckResolution = resolveDirectEditConstraints(
junctionModel,
{ ...document([anchored]), base: { compilerGeometryVersion: 'old-geometry' } },
+9 -1
View File
@@ -244,8 +244,16 @@ test.describe('workbench editing shell', () => {
const scoped = await page.request
.get(`/api/edit-state?cluster=${encodeURIComponent(id)}`)
.then((response) => response.json());
expect(scoped.handles.handles).toEqual([]);
expect(scoped.handles.handles.length).toBeGreaterThan(0);
expect(
scoped.handles.handles.every(
(handle: { kind: string; editable: boolean }) => handle.kind === 'cluster-carriageway-width' && handle.editable,
),
).toBe(true);
expect(scoped.junctionStructure.topologyFingerprint).toBe(structure.topologyFingerprint);
await page.getByRole('button', { name: '开启编辑模式' }).click();
await expect(workspace.getByText('路口参数', { exact: true })).toBeVisible();
await expect(workspace.getByText(/车行道宽度/).first()).toBeVisible();
await page.reload();
await expect(armButtons).toHaveCount(structure.arms.length);
await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'false');
+11
View File
@@ -25,6 +25,14 @@ function anchorFor(kind) {
if (type === 'road-interval')
return { type, roadId: 'road:way/1:forward', startStation: 0.25, endStation: 0.75, side: 'left' };
if (type === 'junction-approach') return { type, nodeId: 'node/9', segmentId: 'road:way/1:segment/0' };
if (type === 'cluster-carriageway')
return {
type,
clusterId: 'cluster/9',
carriagewayKey: 'cluster:cluster%2F9:carriageway:node%2F9/road%3Away%2F1%3Asegment%2F0/road%3Away%2F1%3Aforward',
sourceNodeIds: ['node/9', 'node/10'],
sourceRoadIds: ['road:way/1:forward'],
};
if (type === 'lane') return { type, laneId: 'lane:road:way/1:forward:1' };
return { type, nodeId: 'node/9', incomingRoadId: 'road:way/1:forward', outgoingRoadId: 'road:way/2:forward' };
}
@@ -42,6 +50,8 @@ function valueFor(kind) {
return { boundaryIndex: 2, offsetMeters: -1.6, transition: 'smoothstep' };
case 'junction-approach-width':
return { widthMeters: 12.5 };
case 'cluster-carriageway-width':
return { widthMeters: 12.5 };
case 'junction-cutback':
return { cutbackMeters: 4 };
case 'junction-corner-radius':
@@ -102,6 +112,7 @@ assert.deepEqual(CONSTRAINT_KINDS, [
'road-sidewalk-width',
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
+50 -3
View File
@@ -256,10 +256,18 @@ const complexInput = {
};
const complexArea = compileInput(complexInput).area;
const clusterState = editState(complexArea, selectionFrom({ cluster: cluster.id }));
assert.deepEqual(clusterState.handles.handles, [], 'cluster selection must never fall through to node handles');
assert.ok(
clusterState.handles.handles.every((handle) => handle.kind === 'cluster-carriageway-width'),
'cluster selection publishes only scoped complex carriageway width handles',
);
assert.ok(clusterState.handles.handles.length, 'the complex fixture must publish editable carriageways');
assert.deepEqual(clusterState.junctionStructure.junctionRef, { type: 'cluster', id: cluster.id });
assert.equal(clusterState.junctionStructure.shape.effectiveArmCount, 5);
assert.equal(clusterState.junctionStructure.capability.editable, false);
assert.equal(
clusterState.junctionStructure.capability.editable,
false,
'structure capability opens with the frontend stage',
);
const complexTracked = trackedFiles.map(({ file }) => ({
file,
bytes: fs.readFileSync(file),
@@ -267,12 +275,51 @@ const complexTracked = trackedFiles.map(({ file }) => ({
}));
const emptyDocument = { ...clusterState.document, constraints: [], operations: [] };
const clusterPreview = editPreview(complexArea, { document: emptyDocument, selection: { cluster: cluster.id } });
assert.deepEqual(clusterPreview.handles.handles, []);
assert.deepEqual(clusterPreview.handles.handles, clusterState.handles.handles);
assert.deepEqual(
clusterPreview.junctionStructure,
clusterState.junctionStructure,
'preview and persisted compiler structure agree',
);
const complexWidthHandle = clusterState.handles.handles[0];
const complexWidthConstraint = {
id: 'constraint:complex-width',
kind: 'cluster-carriageway-width',
anchor: complexWidthHandle.anchor,
anchorSnapshot: {
coordinate: complexWidthHandle.position,
tangentAzimuth: complexWidthHandle.axisAzimuth,
roadLengthMeters: 120,
osmNodeIds: complexWidthHandle.anchor.sourceNodeIds,
},
value: { widthMeters: complexWidthHandle.value.current + 0.25 },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:complex-width', createdAt: '2026-09-08T00:00:00.000Z' },
};
const widenedClusterPreview = editPreview(complexArea, {
document: {
...emptyDocument,
constraints: [complexWidthConstraint],
operations: [
{
id: 'operation:complex-width',
createdAt: '2026-09-08T00:00:00.000Z',
constraintIds: [complexWidthConstraint.id],
},
],
},
selection: { cluster: cluster.id },
});
const complexSurface = (preview) =>
preview.layers.roadSurface.features.find(
(feature) => feature.properties.carriageway_key === complexWidthHandle.anchor.carriagewayKey,
);
assert.notDeepEqual(
complexSurface(widenedClusterPreview).geometry,
complexSurface(clusterPreview).geometry,
'a cluster carriageway constraint must change compiled complex geometry',
);
const browsing = browseState(complexArea);
const unavailableStructureState = browseState({
...complexArea,
+12 -3
View File
@@ -262,7 +262,14 @@ function App() {
// the same manifest objects and callbacks as the main parameter panel so
// number entry and dragging share one preview/undo protocol.
const junctionHandles = useMemo(() => {
if (!editMode || !junctionDescriptor || junctionDescriptor.ref.type !== 'node' || !manifest) return [];
if (!junctionDescriptor || !manifest) return [];
if (junctionDescriptor.ref.type === 'cluster')
return manifest.handles.filter(
(handle) =>
handle.kind === 'cluster-carriageway-width' &&
handle.anchor.type === 'cluster-carriageway' &&
handle.anchor.clusterId === junctionDescriptor.ref.id,
);
const nodeIds = new Set(junctionDescriptor.nodeIds.map(String));
return manifest.handles.filter(
(handle) =>
@@ -274,7 +281,7 @@ function App() {
'nodeId' in handle.anchor &&
nodeIds.has(String(handle.anchor.nodeId)),
);
}, [editMode, junctionDescriptor, manifest]);
}, [junctionDescriptor, manifest]);
const junctionFacilitySummary = useMemo(() => {
if (!junctionDescriptor || !state) return { crosswalks: 0, stopLines: 0, signals: 0 };
const nodeIds = new Set(junctionDescriptor.nodeIds.map(String));
@@ -478,11 +485,13 @@ function App() {
// compiled model before building the anchor snapshot. Without this branch
// control handles silently returned null and never scheduled a preview.
const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : null;
const sourceRoadId = handle.anchor.type === 'cluster-carriageway' ? handle.anchor.sourceRoadIds[0] : 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) ||
(sourceRoadId ? item.id === sourceRoadId : false) ||
(segmentId ? item.segmentId === segmentId : false) ||
(cornerRoadId ? item.id === cornerRoadId || item.segmentId === cornerRoadId : false),
);
@@ -1105,7 +1114,7 @@ function App() {
onSignalDragEnd={finishSignalMove}
onSignalRotate={rotateSignal}
onSignalRotateEnd={finishSignalRotate}
handles={visibleEditHandles}
handles={junctionRoute ? junctionHandles : visibleEditHandles}
ranges={editRanges}
element={elementOutline}
laneSelectionBounds={laneSelectionBounds}
+1
View File
@@ -113,6 +113,7 @@ const KIND_LABELS: Record<ConstraintKind, string> = {
'road-sidewalk-width': '步行带宽度',
'road-lane-divider': '车道分隔',
'junction-approach-width': '进口宽度',
'cluster-carriageway-width': '车行道宽度',
'junction-cutback': '进口收口距离',
'junction-corner-radius': '角部圆角',
'junction-crosswalk-inset': '斑马线退让',
+21 -2
View File
@@ -12,7 +12,7 @@ import {
projectIntervalEnd,
reserveWindow,
} from './projection';
import type { ConstraintKind, EditHandle, JunctionReserve, RoadIntervalAnchor, Side } from './types';
import type { ConstraintKind, EditHandle, JunctionReserve, RoadIntervalAnchor, SemanticAnchor, Side } from './types';
const CENTER: Coordinate = [116.397, 39.908];
/** The road heads due north, so the manifest reports normal = tangent + 90 = east. */
@@ -38,7 +38,7 @@ function interval(side?: Side, boundaryIndex?: number): RoadIntervalAnchor {
};
}
function makeHandle(kind: ConstraintKind, anchor: RoadIntervalAnchor, current = 0, min = -5, max = 5): EditHandle {
function makeHandle(kind: ConstraintKind, anchor: SemanticAnchor, current = 0, min = -5, max = 5): EditHandle {
return {
handleId: `handle:${kind}`,
kind,
@@ -110,6 +110,25 @@ describe('road-sidewalk-width projection', () => {
});
});
describe('complex carriageway width projection', () => {
it('writes the shared width value shape', () => {
const handle = makeHandle(
'cluster-carriageway-width',
{
type: 'cluster-carriageway',
clusterId: 'cluster-1',
carriagewayKey: 'cluster:cluster-1:carriageway:stable',
sourceNodeIds: ['node-1'],
sourceRoadIds: ['road-1'],
},
6,
4.8,
12,
);
expect(constraintValueFor(handle, 7.5)).toEqual({ widthMeters: 7.5 });
});
});
describe('road-lane-divider projection', () => {
it('is a signed lateral offset, with no side flip', () => {
const handle = makeHandle('road-lane-divider', interval(undefined, 2), 0, -1.2, 1.2);
+1
View File
@@ -102,6 +102,7 @@ export function constraintValueFor(
case 'road-lane-divider':
return { boundaryIndex: boundaryIndexOf(handle), offsetMeters: scalar, transition };
case 'junction-approach-width':
case 'cluster-carriageway-width':
return { widthMeters: Math.max(0, scalar) };
case 'junction-cutback':
return { cutbackMeters: Math.max(0, scalar) };
+8
View File
@@ -26,6 +26,7 @@ export const ROAD_KINDS = ['road-edge-offset', 'road-sidewalk-width', 'road-lane
export const CONTROL_KINDS = ['junction-crosswalk-inset', 'junction-stop-line-offset'] as const;
export const JUNCTION_KINDS = [
'junction-approach-width',
'cluster-carriageway-width',
'junction-cutback',
'junction-corner-radius',
...CONTROL_KINDS,
@@ -59,6 +60,13 @@ export type SemanticAnchor =
boundaryIndex?: number;
}
| { type: 'junction-approach'; nodeId: string; segmentId: string; side?: Side }
| {
type: 'cluster-carriageway';
clusterId: string;
carriagewayKey: string;
sourceNodeIds: string[];
sourceRoadIds: string[];
}
| { type: 'junction-crossing'; crossingId: string; nodeId: string; segmentId: string; roadId: string }
| { type: 'junction-corner'; nodeId: string; incomingRoadId: string; outgoingRoadId: string };
@@ -32,8 +32,9 @@ export function useDirectEditSession({
const touch = () => setRevision((value) => value + 1);
useEffect(() => {
// Flag off: no manifest request at all, so the network trace matches browse mode.
if (!editMode) return;
// Complex junction capability is published by the server as scoped handles,
// so its workspace needs that manifest to expose the edit entry point.
if (!editMode && selectedJunction?.type !== 'cluster') return;
let current = true;
setManifest(null);
api
@@ -82,7 +82,14 @@ export function JunctionWorkspace({
onSignalStatus,
onUpdateSignal,
}: Props) {
const editable = useMemo(() => canEditJunction(descriptor), [descriptor]);
const editable = useMemo(
() =>
canEditJunction(
descriptor,
handles.some((handle) => handle.editable),
),
[descriptor, handles],
);
const complexEnabled = useMemo(() => {
const nodes = new Set(descriptor.nodeIds.map(String));
return Boolean(
@@ -187,7 +194,11 @@ export function JunctionWorkspace({
</div>
<p>
{complexEnabled
? '当前按复杂路口渲染'
? editable
? editMode
? '可编辑外部车行道宽度'
: '当前按复杂路口渲染,开启编辑后可调整外部车行道宽度'
: '当前按复杂路口渲染'
: descriptor.status === 'candidate'
? '当前按普通路口渲染,可切换为复杂路口'
: editable
@@ -505,9 +516,7 @@ export function JunctionWorkspace({
</div>
</>
) : editable ? (
<p className="junction-workspace__browse-hint">
开启编辑模式后,这里会显示进口宽度、进口收口距离和角部圆角控件。
</p>
<p className="junction-workspace__browse-hint">开启编辑模式后,这里会显示可调整的路口几何参数。</p>
) : complexEnabled ? (
<p className="junction-workspace__browse-hint">复杂路口几何已启用;首版仅支持查看,不支持参数拖拽编辑。</p>
) : null}
@@ -76,4 +76,23 @@ describe('junction handle labels', () => {
),
).toBe('道路2 · 东进口 · 进口收口距离');
});
it('names a complex carriageway by its source road', () => {
expect(
junctionLabelForHandle(
handle(
{
type: 'cluster-carriageway',
clusterId: 'cluster-1',
carriagewayKey: 'cluster:cluster-1:carriageway:stable',
sourceNodeIds: ['junction'],
sourceRoadIds: ['road-north'],
},
'cluster-carriageway-width',
),
roads as unknown as Road[],
[120, 30],
),
).toBe('创新大道 · 北进口 · 车行道宽度');
});
});
+5
View File
@@ -58,5 +58,10 @@ export function junctionLabelForHandle(handle: EditHandle, roads: Road[], juncti
const road = roadForKey(roads, handle.anchor.roadId) ?? roadForKey(roads, handle.anchor.segmentId);
return `${approachName(road, roads, junction)} · ${base}`;
}
const clusterAnchor = handle.anchor;
if (handle.kind === 'cluster-carriageway-width' && clusterAnchor.type === 'cluster-carriageway') {
const road = roads.find((item) => clusterAnchor.sourceRoadIds.includes(item.id));
return `${approachName(road, roads, junction)} · ${base}`;
}
return base;
}
@@ -32,8 +32,9 @@ describe('junction workspace session', () => {
expect(leaveJunctionSession(session, 'apply')?.status).toBe('applied');
});
it('only ordinary editable nodes can be changed', () => {
it('opens a cluster when the server published editable handles', () => {
expect(canEditJunction(node as never)).toBe(true);
expect(canEditJunction(cluster as never)).toBe(false);
expect(canEditJunction(cluster as never, true)).toBe(true);
});
});
+2 -2
View File
@@ -46,6 +46,6 @@ export function leaveJunctionSession(session: JunctionSession, action: LeaveActi
return applyJunctionDraft(session);
}
export function canEditJunction(descriptor: JunctionDescriptor): boolean {
return descriptor.ref.type === 'node' && descriptor.status === 'editable';
export function canEditJunction(descriptor: JunctionDescriptor, hasEditableHandles = false): boolean {
return (descriptor.ref.type === 'node' && descriptor.status === 'editable') || hasEditableHandles;
}
+24 -16
View File
@@ -442,23 +442,14 @@ function editPreview(area, body = {}) {
...(Array.isArray(body.operations) ? { operations: body.operations } : {}),
});
const activeState = readJson(activeStateFile);
const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides);
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides);
const selection = selectionFrom(body.selection);
const previewSeq = Number.isInteger(body.previewSeq) ? body.previewSeq : 0;
const resolution = resolveDirectEditConstraints(model, draft, {
const candidate = compileEditCandidate(area, draft, {
revisionId: activeState.activeRevisionId,
previewSeq,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
selection,
});
const compiled = compileGeometry(model, persistedOverrides, {
edgeLines: area.nativeRoad.edgeLines,
junctionTemplates: area.nativeRoad.junctionTemplates,
directEdit: resolution,
});
const diagnostics = [...compiled.diagnostics, ...resolution.diagnostics];
const { model, resolution, compiled, diagnostics } = candidate;
const junctionStructure = projectJunctionStructure({
model,
junctionRef: junctionRefFromSelection(selection),
@@ -505,6 +496,24 @@ function editPreview(area, body = {}) {
};
}
function compileEditCandidate(area, draft, { revisionId, previewSeq = 0, selection = null } = {}) {
const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides);
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides);
const resolution = resolveDirectEditConstraints(model, draft, {
revisionId,
previewSeq,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
selection,
});
const compiled = compileGeometry(model, persistedOverrides, {
edgeLines: area.nativeRoad.edgeLines,
junctionTemplates: area.nativeRoad.junctionTemplates,
directEdit: resolution,
});
return { model, resolution, compiled, diagnostics: [...compiled.diagnostics, ...resolution.diagnostics] };
}
function saveEdits(area, body = {}) {
const workspace = path.dirname(area.input);
const initialized = ensureRevisionStore(workspace, area.nativeRoad);
@@ -524,20 +533,19 @@ function saveEdits(area, body = {}) {
...(Array.isArray(body.operations) ? { operations: body.operations } : {}),
documentVersion: current.documentVersion,
};
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), loadOverrides(area.outputs.nativeRoadOverrides));
const resolution = resolveDirectEditConstraints(model, candidate, {
const checked = validateEditDocument(candidate);
const evaluation = compileEditCandidate(area, checked, {
revisionId: initialized.active.activeRevisionId,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
});
const blockingDiagnostic = resolution.diagnostics.find((item) => item.severity === 'error');
const blockingDiagnostic = evaluation.diagnostics.find((item) => item.severity === 'error');
if (blockingDiagnostic) {
const error = new Error(blockingDiagnostic.message);
error.statusCode = 400;
error.diagnostic = blockingDiagnostic;
throw error;
}
const saved = saveEditDocument(initialized.paths.activeEdits, candidate);
const saved = saveEditDocument(initialized.paths.activeEdits, checked);
writeJsonAtomic(initialized.paths.activeState, {
...initialized.active,
documentVersion: saved.documentVersion,