feat(junction): establish stable complex junction structure

This commit is contained in:
que01 committed 2026-09-08 11:25:57 +08:00
1 parent bd8b55e58b
commit 0a5a229ce3
22 files changed
+1386 -125

No files matched your search

+57
View File
@@ -298,3 +298,60 @@ document byte-identical; warnings remain saveable. This prevents a client from
skipping preview and persisting a width, corner radius, crossing offset, or
stop-line value that the compiler rejects. Version conflicts are checked first
and continue to return HTTP 409 without invoking geometry validation writes.
## 16. Scoped complex junction identity
### Scope and signatures
Stage 1 establishes the read model consumed by later cluster editing. Use
`resolveComplexJunctionTopology(model, cluster, helpers)` in complex geometry,
then `structureFromTopology(topology, shape, center, features)`. Projection is
`projectJunctionStructure({ model, layers, trafficSignals, junctionRef })`.
### Contracts
- `junctionRef` is `{ type: 'node' | 'cluster', id }`. Explicit `null` means no
junction projection; unknown references return `null`, never the first core.
- `GET /api/state` returns `junctionStructures`, keyed by `node:<id>` and
`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.
- 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.
- Stable keys derive from cluster and sorted source node/segment/road IDs, with
corner keys derived from adjacent arms. Display indices and headings are not
object identities. `topologyFingerprint` detects source topology changes.
- Root provenance lists member nodes and external road/segment IDs. Arms point
to carriageways, corners to arms, facilities to feature IDs; normalizers must
preserve these fields and readonly capabilities across JSON round trips.
- Signal projection joins exact member `node_id` / `control_id`, retaining the
existing `signal_uid` as `geometryRef` and `provenance.featureIds`. It does not
rewrite the separately persisted signal document or guess from UID substrings.
### Validation matrix
| Input | Result |
| --- | --- |
| Multiple selection keys or repeated query keys | 400, no implicit priority |
| Empty/object-valued ID | 400 |
| Unknown node/cluster or missing compiled complex structure | null structure, empty diagnostics |
| Missing/ambiguous object source | readonly capability with reason |
| Explicit cluster selection | empty handles; never all-area or member-node handles |
### Cases and tests
Good: reorder member/road arrays and retain semantic IDs; delete a source and
change its identity/fingerprint. Base: legacy node editing still works. Bad:
opening cluster B while rendering cluster A's first core. Test the 3/4/offset/5+
arm matrix, two-cluster isolation, internal-link exclusion, grouped crossings,
scoped signals, JSON round trips, and persisted/preview projection equality.
```js
// Wrong: chooses an arbitrary junction and loses the selected scope.
projectJunctionStructure({ model, layers });
// Correct for a scoped editor:
projectJunctionStructure({ model, layers, trafficSignals,
junctionRef: { type: 'cluster', id: selectedClusterId } });
```
@@ -271,3 +271,28 @@ The same internal node layout can resolve to different external-arm topology.
If no summary exists, omit the shape row and retain normal cluster context; do
not show an inferred fallback. The compiler's safe fallback has no complex core
and therefore no summary.
## 16. Scoped structure and semantic map selection
Use `structureForJunction(state, ref)` to read `state.junctionStructures`; do not
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.
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
and corner features that do not carry member node IDs and excludes neighboring
clusters even if a connecting road is shared.
Map/list selection goes through `junctionObjectKeyForFeature` and
`junctionObjectFeatures`: compiler keys identify arms/corners/crossing groups;
signal UIDs resolve through scoped facility provenance. Display labels and row
indices are never parsed into IDs. Highlighting is a read-only overlay, allocated
when selecting an object; it must not mutate baseline features or rebuild the
map. On scope changes clear object selection and ignore obsolete manifest loads.
Map capability reason codes into user-facing Chinese descriptions.
Required checks: opposite node/cluster scopes with equal raw IDs, unknown scope,
list-to-feature grouping and feature-to-list identity, foreign-cluster exclusion,
raw signal UID selection, map identity preservation, and reload stability.
+114 -27
View File
@@ -1,6 +1,7 @@
'use strict';
const fs = require('fs');
const { topologyIdentity, structureFromTopology } = require('./junction-topology');
const { convertGeoJson, boundsOf } = require('../reference/gaode');
const metricsCache = new WeakMap();
const CORNER_FILLET_SEGMENTS = 12;
@@ -12,6 +13,82 @@ const SIDEWALK_WIDTH_METERS = 2;
// past that end and let the two overlap rather than chase an exact seam.
const SIDEWALK_CORNER_OVERRUN_METERS = 6;
// Geometry and the durable structure use this single external topology.
function resolveComplexJunctionTopology(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = [...nodeIds]
.sort()
.map((id) => helpers.junctionPlans.get(id)?.node)
.filter(Boolean);
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches) {
const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean);
// Source topology is authoritative; geometric proximity is only a fallback
// for legacy plans with no source-node metadata.
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))),
)
: nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4);
if (internal) continue;
carriageways.push({
nodeId: String(nodeId),
approach,
plan,
roads,
heading: helpers.headingAtEndpoint(approach.line),
length: helpers.lineLengthMeters(approach.line),
});
}
}
// Stable source ordering makes heading grouping independent of plan/road order.
carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b)));
const duplicateSources = new Set();
const seenSources = new Set();
for (const item of carriageways) {
const identity = topologyIdentity(item);
if (seenSources.has(identity)) duplicateSources.add(identity);
seenSources.add(identity);
}
for (let index = carriageways.length - 1; index > 0; index -= 1)
if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1]))
carriageways.splice(index, 1);
const arms = [];
for (const item of carriageways) {
item.ambiguousSource = duplicateSources.has(topologyIdentity(item));
let arm = arms.find(
(candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20,
);
if (!arm) {
arm = { representative: item, members: [] };
arms.push(arm);
}
arm.members.push(item);
}
for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading));
for (const item of carriageways)
if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1)
item.ambiguousSource = true;
arms.sort(
(a, b) =>
a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)),
);
const scope = `cluster:${encodeURIComponent(cluster.id)}`;
for (const arm of arms) {
arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`;
for (const item of arm.members) {
item.key = `${scope}:carriageway:${topologyIdentity(item)}`;
item.armKey = arm.key;
}
}
for (let index = 0; index < arms.length; index += 1)
arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`;
return { cluster, nodeIds: [...nodeIds].sort(), carriageways, arms };
}
function buildComplexJunctionGeometry(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = cluster.nodeIds.map((id) => helpers.junctionPlans.get(String(id))?.node).filter(Boolean);
@@ -33,20 +110,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
(sum, point) => [sum[0] + point[0] / nodes.length, sum[1] + point[1] / nodes.length],
[0, 0],
);
const approaches = [];
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches) {
const endpoint = approach.line.at(-1);
if (nodes.some((node) => node !== plan.node && helpers.distanceMeters(endpoint, node) < 4)) continue;
const heading = helpers.headingAtEndpoint(approach.line);
const length = helpers.lineLengthMeters(approach.line);
carriageways.push({ nodeId, approach, plan, heading, length });
if (approaches.some((item) => Math.abs(normalizeHeading(item.heading - heading)) < 20)) continue;
approaches.push({ nodeId, approach, plan, heading, length });
}
}
const topology = resolveComplexJunctionTopology(model, cluster, helpers);
const { carriageways, arms } = topology;
const approaches = arms.map((arm) => arm.representative);
if (approaches.length < 3)
return {
features: [],
@@ -62,18 +128,7 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
],
};
const { calibration, coreRadius } = complexJunctionMetrics(cluster);
const sorted = [...approaches].sort((a, b) => a.heading - b.heading);
const arms = sorted.map((representative) => ({
representative,
heading: averageHeading(
carriageways
.filter((candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20)
.map((candidate) => candidate.heading),
),
members: carriageways.filter(
(candidate) => Math.abs(normalizeHeading(candidate.heading - representative.heading)) < 20,
),
}));
const sorted = approaches;
const shape = classifyJunctionShape(arms, center, helpers);
if (shape.kind === 'unsupported')
return {
@@ -141,6 +196,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
type: 'Feature',
properties: {
native_id: `complex-stop-line:${cluster.id}:${item.approach.segmentId}`,
object_key: `stop-line:${item.key}`,
arm_key: item.armKey,
carriageway_key: item.key,
cluster_id: cluster.id,
kind: 'complex-stop-line',
road_id: incomingRoad.id,
@@ -223,6 +281,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
type: 'Feature',
properties: {
native_id: `complex-crosswalk:${cluster.id}:${item.nodeId}:${item.approach.segmentId}:${stripe + 1}`,
object_key: `crossing:${arm.key}`,
arm_key: arm.key,
cluster_id: cluster.id,
kind: 'complex-crosswalk',
crossing_node_id: item.nodeId,
@@ -290,6 +350,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-corner-island:${cluster.id}:${index + 1}`,
cluster_id: cluster.id,
kind: 'complex-corner-island',
object_key: `island:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1,
from_heading: first.heading,
to_heading: second.heading,
@@ -332,6 +394,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-corner-crosswalk:${cluster.id}:${index + 1}:${stripe + 1}`,
cluster_id: cluster.id,
kind: 'complex-corner-crosswalk',
object_key: `crossing:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1,
direction: bisector,
radial_distance_m: stripeRadius,
@@ -394,6 +458,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-corner-fillet:${cluster.id}:${index + 1}`,
cluster_id: cluster.id,
kind: 'complex-corner-fillet',
object_key: first.cornerKey,
corner_key: first.cornerKey,
complex_part: 'corner-fillet',
corner_index: index + 1,
from_heading: first.heading,
@@ -453,6 +519,8 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-sidewalk-corner:${cluster.id}:${index + 1}`,
cluster_id: cluster.id,
kind: 'complex-sidewalk-corner',
object_key: `sidewalk-turn:${first.cornerKey}`,
corner_key: first.cornerKey,
corner_index: index + 1,
from_heading: first.heading,
to_heading: second.heading,
@@ -530,6 +598,9 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
native_id: `complex-junction:${cluster.id}:carriageway:${item.approach.segmentId}`,
cluster_id: cluster.id,
kind: 'complex-approach',
object_key: item.key,
carriageway_key: item.key,
arm_key: item.armKey,
complex_part: 'carriageway',
heading_deg: item.heading,
lane_count: item.approach.roadIds.reduce(
@@ -562,7 +633,18 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
),
]
: [];
const allFeatures = [...features, ...islands, ...sidewalkCorners, ...crosswalks, ...stopLines];
const structure = structureFromTopology(topology, shape, center, allFeatures);
for (const feature of allFeatures) {
feature.properties.junction_key = structure.junctionKey;
feature.properties.topology_fingerprint = structure.topologyFingerprint;
}
// Persist the compiler authority with a generated road surface, including the
// supported-shape case where only the central polygon had to be skipped.
const carrier = features.find((feature) => feature.properties.kind === 'complex-core') || features[0];
if (carrier) carrier.properties.junction_structure = structure;
return {
structure,
features,
islands: [...islands, ...sidewalkCorners],
crosswalks,
@@ -907,4 +989,9 @@ function interpolateCoordinate(first, second, ratio) {
return [first[0] + (second[0] - first[0]) * ratio, first[1] + (second[1] - first[1]) * ratio];
}
module.exports = { buildComplexJunctionGeometry, classifyJunctionShape, complexJunctionMetrics };
module.exports = {
resolveComplexJunctionTopology,
buildComplexJunctionGeometry,
classifyJunctionShape,
complexJunctionMetrics,
};
+2
View File
@@ -1093,6 +1093,8 @@ 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 === 'segment') {
const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId]));
const wanted = String(selection.id);
+94 -46
View File
@@ -11,30 +11,57 @@ function heading(from, to) {
return (Math.atan2(to[0] - from[0], to[1] - from[1]) * 180) / Math.PI;
}
function pointOf(feature) {
const coordinates = feature?.geometry?.coordinates;
if (feature?.geometry?.type === 'Point' && Array.isArray(coordinates)) return coordinates;
if (Array.isArray(coordinates?.[0]?.[0])) return coordinates[0][0];
if (Array.isArray(coordinates?.[0])) return coordinates[0];
return null;
}
function projectJunctionStructure({
model = {},
layers = {},
trafficSignals = null,
shape = null,
junctionKey = null,
junctionRef = undefined,
} = {}) {
if (junctionRef === null) return null;
const roads = Array.isArray(model.roads) ? model.roads : [];
const endpoints = Array.isArray(model.endpoints) ? model.endpoints : [];
const core = featureCollection(layers.intersectionSurface).find(
(feature) => feature.properties?.kind === 'complex-core',
);
const properties = core?.properties || {};
const key = String(junctionKey || properties.cluster_id || endpoints[0]?.nodeId || 'junction:area');
const center = pointOf(core) || endpoints[0]?.coordinate || [0, 0];
const junctionNodeId = String(junctionKey || properties.cluster_id ? endpoints[0]?.nodeId || '' : key);
if (junctionRef && !['node', 'cluster'].includes(junctionRef.type))
throw new Error('Invalid junction reference type');
if (junctionRef?.type === 'cluster') {
const carrier = featureCollection(layers.roadSurface || layers.nativeRoadSurface || layers.road_surface).find(
(feature) =>
String(feature.properties?.cluster_id) === String(junctionRef.id) && feature.properties?.junction_structure,
);
if (!carrier) return null;
const structure = buildJunctionStructure(carrier.properties.junction_structure);
const nodeIds = new Set(structure.provenance?.nodeIds || []);
const signals = new Map();
for (const feature of featureCollection(trafficSignals?.assemblies)) {
const p = feature.properties || {};
const nodeId = p.node_id ?? p.control_id;
if (nodeId == null || !nodeIds.has(String(nodeId)) || !p.signal_uid) continue;
const uid = String(p.signal_uid);
if (signals.has(uid)) {
signals.get(uid).capability.reason = 'source-ambiguous';
continue;
}
signals.set(uid, {
key: `cluster:${encodeURIComponent(junctionRef.id)}:signal:${encodeURIComponent(uid)}`,
kind: 'signal',
label: '信号灯',
geometryRef: uid,
editable: false,
capability: { editable: false, reason: 'complex-geometry-editing-not-implemented' },
provenance: { nodeIds: [String(nodeId)], featureIds: [uid] },
});
}
return buildJunctionStructure({
...structure,
facilities: [...structure.facilities, ...signals.values()].sort((a, b) => a.key.localeCompare(b.key)),
});
}
const properties = {};
const key = String(junctionRef?.id || junctionKey || endpoints[0]?.nodeId || 'junction:area');
const junctionNodeId = key;
if ((junctionRef || junctionKey) && !endpoints.some((endpoint) => String(endpoint.nodeId) === key)) return null;
const center = endpoints.find((endpoint) => String(endpoint.nodeId) === key)?.coordinate || [0, 0];
const endpointByNode = new Map();
for (const endpoint of endpoints) endpointByNode.set(String(endpoint.nodeId), endpoint);
const arms = roads
@@ -48,7 +75,13 @@ function projectJunctionStructure({
return {
key: `road-arm:${road.id || index + 1}`,
label: String(road.tags?.name || road.name || `道路 ${index + 1}`),
heading: heading(center, endpoint.coordinate),
heading:
road.centerline?.length > 1
? heading(
center,
String(road.sourceNodeIds?.[0]) === junctionNodeId ? road.centerline[1] : road.centerline.at(-2),
)
: heading(center, endpoint.coordinate),
directionality:
road.direction === 'oneway' || road.direction === 'one-way'
? 'one-way'
@@ -64,41 +97,53 @@ function projectJunctionStructure({
sourceRoadId: String(road.id || ''),
};
})
.filter(Boolean);
.filter(Boolean)
.sort((a, b) => a.heading - b.heading);
const corners =
arms.length > 1
? arms.map((arm, index) => {
const next = arms[(index + 1) % arms.length];
return {
key: `corner:${index + 1}`,
key: `corner:${arm.key}>${next.key}`,
label: `角部 ${index + 1}`,
fromArmKey: arm.key,
toArmKey: next.key,
geometryRef: `${key}:corner:${index + 1}`,
geometryRef: `corner:${arm.key}>${next.key}`,
};
})
: [];
const inScope = (feature) => {
if (!junctionRef && !junctionKey) return true;
const p = feature.properties || {};
if (p.cluster_id) return false;
const node = p.node_id ?? p.osm_node_id ?? p.crossing_node_id;
if (node !== undefined) return String(node) === junctionNodeId;
return p.road_id && arms.some((arm) => arm.sourceRoadId === String(p.road_id));
};
const facilities = [];
const crossingKeys = [];
for (const [kind, collection] of [
['crossing', layers.crosswalks],
['stop-line', layers.vehicleStopLines],
]) {
featureCollection(collection).forEach((feature, index) => {
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({
key: String(id),
kind,
label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`,
geometryRef: String(id),
featureCollection(collection)
.filter(inScope)
.forEach((feature, index) => {
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({
key: String(id),
kind,
label: kind === 'crossing' ? `人行横道 ${index + 1}` : `停止线 ${index + 1}`,
geometryRef: String(id),
});
});
if (kind === 'crossing') crossingKeys.push(String(id));
});
}
for (const [index, feature] of featureCollection(trafficSignals?.assemblies).entries()) {
for (const [index, feature] of featureCollection(trafficSignals?.assemblies).filter(inScope).entries()) {
const id = feature.properties?.signal_uid || feature.properties?.id || `signal:${index + 1}`;
const signalNode = feature.properties?.node_id || feature.properties?.control_id;
const related = crossingKeys.find((crossingKey) => String(crossingKey).includes(String(signalNode || '')));
const related = featureCollection(layers.crosswalks)
.filter(inScope)
.find((crossing) => signalNode != null && String(crossing.properties?.crossing_node_id) === String(signalNode))
?.properties?.native_id;
facilities.push({
key: String(id),
kind: 'signal',
@@ -112,21 +157,23 @@ function projectJunctionStructure({
['median', layers.medians],
['sidewalk-turn', layers.sidewalkTurns],
]) {
featureCollection(collection).forEach((feature, index) => {
if (feature.properties?.kind !== kind) return;
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({
key: String(id),
kind,
label:
kind === 'island'
? `导流岛 ${index + 1}`
: kind === 'median'
? `中央分隔 ${index + 1}`
: `人行道转角 ${index + 1}`,
geometryRef: String(id),
featureCollection(collection)
.filter(inScope)
.forEach((feature, index) => {
if (feature.properties?.kind !== kind) return;
const id = feature.properties?.native_id || feature.properties?.id || `${kind}:${index + 1}`;
facilities.push({
key: String(id),
kind,
label:
kind === 'island'
? `导流岛 ${index + 1}`
: kind === 'median'
? `中央分隔 ${index + 1}`
: `人行道转角 ${index + 1}`,
geometryRef: String(id),
});
});
});
}
const shapeKind =
shape?.kind ||
@@ -134,6 +181,7 @@ function projectJunctionStructure({
(arms.length === 3 ? 't-junction' : arms.length >= 5 ? 'multi-arm' : arms.length === 4 ? 'cross' : 'unsupported');
return buildJunctionStructure({
junctionKey: key,
junctionRef: { type: 'node', id: junctionNodeId },
label: properties.shape_label || '路口',
center,
shape: {
@@ -151,7 +199,7 @@ function projectJunctionStructure({
function standardsDiagnostics(structure, profile = CN_URBAN_DEFAULT_PROFILE) {
const diagnostics = [];
for (const arm of structure.arms) {
for (const arm of structure?.arms || []) {
const rule = profile.rules.find((item) => item.id === 'effective-carriageway-width');
const severity = evaluateRange(arm.carriageway.effectiveWidthMeters, rule);
diagnostics.push({
+55
View File
@@ -35,6 +35,34 @@ function overrideState(input = {}) {
};
}
function metadata(input) {
const result = {};
if (input.provenance !== undefined) {
if (!input.provenance || typeof input.provenance !== 'object' || Array.isArray(input.provenance))
throw new Error('Junction provenance must be an object');
for (const field of ['nodeIds', 'segmentIds', 'roadIds', 'osmWayIds', 'carriagewayKeys', 'armKeys', 'featureIds']) {
const values = input.provenance[field];
if (values !== undefined && (!Array.isArray(values) || values.some((value) => typeof value !== 'string')))
throw new Error(`Junction provenance.${field} must be an array of strings`);
}
result.provenance = JSON.parse(JSON.stringify(input.provenance));
}
if (input.capability !== undefined) {
if (
typeof input.capability?.editable !== 'boolean' ||
(input.capability.reason !== undefined &&
(typeof input.capability.reason !== 'string' || !input.capability.reason.trim())) ||
(!input.capability.editable && !input.capability.reason)
)
throw new Error('Junction readonly capability requires a reason');
result.capability = {
editable: input.capability.editable,
...(input.capability.reason ? { reason: String(input.capability.reason) } : {}),
};
}
return result;
}
function normalizeRoadArm(input, index) {
const key = objectKey(input.key, `road-arm:${index + 1}`);
const label = readableLabel(input.label, `道路 ${index + 1}`);
@@ -43,9 +71,22 @@ function normalizeRoadArm(input, index) {
const carriageway = input.carriageway || {};
const normalized = {
key,
...metadata(input),
label,
heading: finiteNumber(input.heading ?? 0, 'arm heading'),
directionality,
...(input.sourceRoadId ? { sourceRoadId: String(input.sourceRoadId) } : {}),
...(input.carriageways
? {
carriageways: input.carriageways.map((item) => ({
key: objectKey(item.key),
geometryRef: objectKey(item.geometryRef, item.key),
...metadata(item),
laneCount: finiteNumber(item.laneCount, 'carriageway lane count', { integer: true, minimum: 0 }),
effectiveWidthMeters: finiteNumber(item.effectiveWidthMeters, 'carriageway width', { minimum: 0 }),
})),
}
: {}),
carriageway: {
...(carriageway.laneCount === undefined
? {}
@@ -77,6 +118,7 @@ function normalizeCorner(input, index) {
if (fromArmKey === toArmKey) throw new Error(`Junction corner ${key} must connect two different road arms`);
return {
key,
...metadata(input),
label: readableLabel(input.label, `角部 ${index + 1}`),
fromArmKey,
toArmKey,
@@ -95,6 +137,7 @@ function normalizeFacility(input, index) {
const key = objectKey(input.key, `${kind}:${index + 1}`);
return {
key,
...metadata(input),
kind,
label: readableLabel(input.label, kind === 'crossing' ? `人行横道 ${index + 1}` : `设施 ${index + 1}`),
...(input.armKey ? { armKey: String(input.armKey) } : {}),
@@ -121,6 +164,10 @@ function buildJunctionStructure(input = {}) {
const kind = String(shape.kind || 'unsupported');
if (!SHAPE_KINDS.has(kind)) throw new Error(`Unsupported junction shape kind: ${kind}`);
const arms = (input.arms || []).map(normalizeRoadArm);
assertUniqueKeys(
arms.flatMap((arm) => arm.carriageways || []),
'carriageway',
);
const armKeys = assertUniqueKeys(arms, 'road arm');
const corners = (input.corners || []).map(normalizeCorner);
const cornerKeys = assertUniqueKeys(corners, 'corner');
@@ -141,7 +188,15 @@ function buildJunctionStructure(input = {}) {
finiteNumber(effectiveArmCount, 'effective arm count', { integer: true, minimum: 0 });
if (effectiveArmCount !== arms.length)
throw new Error('Junction effective arm count must match the supplied road arms');
if (
input.junctionRef &&
(!['node', 'cluster'].includes(input.junctionRef.type) || !String(input.junctionRef.id || '').trim())
)
throw new Error('Junction reference requires a node or cluster type and id');
return {
...metadata(input),
...(input.junctionRef ? { junctionRef: { type: input.junctionRef.type, id: String(input.junctionRef.id) } } : {}),
...(input.topologyFingerprint ? { topologyFingerprint: String(input.topologyFingerprint) } : {}),
schema: JUNCTION_STRUCTURE_SCHEMA,
junctionKey: objectKey(input.junctionKey, 'junction:unknown'),
label: readableLabel(input.label, '未命名路口'),
+130
View File
@@ -0,0 +1,130 @@
'use strict';
const { createHash } = require('crypto');
const { buildJunctionStructure } = require('./junction-structure');
function topologyIdentity(item) {
return [item.nodeId, item.approach.segmentId || '', ...item.approach.roadIds.map(String).sort()]
.map(encodeURIComponent)
.join('/');
}
function sourceOf(item) {
return {
nodeIds: [String(item.nodeId)],
segmentIds: [String(item.approach.segmentId || '')],
roadIds: item.approach.roadIds.map(String).sort(),
osmWayIds: [...new Set(item.roads.flatMap((road) => (road.osmWayIds || []).map(String)))].sort(),
};
}
function capability(reason = 'complex-geometry-editing-not-implemented') {
return { editable: false, reason };
}
function structureFromTopology(topology, shape, center, features) {
const { cluster } = topology;
const arms = topology.arms.map((arm, index) => {
const carriageways = arm.members.map((item) => ({
key: item.key,
geometryRef: item.key,
provenance: sourceOf(item),
capability: capability(
item.ambiguousSource
? 'source-ambiguous'
: item.approach.segmentId &&
item.roads.length > 0 &&
item.roads.length === item.approach.roadIds.length &&
item.roads.every((road) => road.sourceNodeIds?.length >= 2)
? undefined
: 'source-missing',
),
laneCount: item.roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0),
effectiveWidthMeters: item.approach.widthMeters,
}));
return {
key: arm.key,
label: arm.members[0].roads[0]?.tags?.name || `道路 ${index + 1}`,
heading: arm.heading,
directionality: arm.members.some((item) => item.roads.length > 1) ? 'two-way' : 'one-way',
carriageway: {
laneCount: carriageways.reduce((sum, item) => sum + item.laneCount, 0),
effectiveWidthMeters: carriageways.reduce((sum, item) => sum + item.effectiveWidthMeters, 0),
},
carriageways,
geometryRef: arm.key,
provenance: { carriagewayKeys: carriageways.map((item) => item.key) },
capability: capability(),
};
});
const corners =
topology.arms.length > 1
? topology.arms.map((arm, index) => ({
key: arm.cornerKey,
label: `角部 ${index + 1}`,
fromArmKey: arm.key,
toArmKey: topology.arms[(index + 1) % topology.arms.length].key,
geometryRef: arm.cornerKey,
provenance: { armKeys: [arm.key, topology.arms[(index + 1) % topology.arms.length].key] },
capability: capability(),
}))
: [];
const facilitiesByKey = new Map();
for (const feature of features) {
const p = feature.properties;
const kind = {
'complex-crosswalk': 'crossing',
'complex-corner-crosswalk': 'crossing',
'complex-stop-line': 'stop-line',
'complex-corner-island': 'island',
'complex-sidewalk-corner': 'sidewalk-turn',
}[p.kind];
if (!kind || !p.object_key) continue;
if (!facilitiesByKey.has(p.object_key))
facilitiesByKey.set(p.object_key, {
key: p.object_key,
kind,
label: `${{ crossing: '人行横道', 'stop-line': '停止线', island: '导流岛', 'sidewalk-turn': '人行道转角' }[kind]}`,
geometryRef: p.object_key,
...(p.arm_key ? { armKey: p.arm_key } : {}),
...(p.corner_key ? { cornerKey: p.corner_key } : {}),
...(kind === 'stop-line' && features.some((f) => f.properties.object_key === `crossing:${p.arm_key}`)
? { relatedFacilityKey: `crossing:${p.arm_key}` }
: {}),
editable: false,
capability: capability(),
provenance: { featureIds: [], ...(p.road_id ? { roadIds: [String(p.road_id)] } : {}) },
});
facilitiesByKey.get(p.object_key).provenance.featureIds.push(String(p.native_id));
}
const facilities = [...facilitiesByKey.values()].sort((a, b) => a.key.localeCompare(b.key));
for (const facility of facilities) facility.provenance.featureIds.sort();
const fingerprint = createHash('sha256')
.update(
JSON.stringify({
nodeIds: topology.nodeIds,
arms: arms.map((arm) => arm.key).sort(),
corners: corners.map((corner) => corner.key).sort(),
}),
)
.digest('hex');
return buildJunctionStructure({
junctionKey: `cluster:${cluster.id}`,
junctionRef: { type: 'cluster', id: String(cluster.id) },
label: shape.label,
center,
topologyFingerprint: fingerprint,
provenance: {
nodeIds: topology.nodeIds,
roadIds: [...new Set(topology.carriageways.flatMap((item) => sourceOf(item).roadIds))].sort(),
segmentIds: [...new Set(topology.carriageways.flatMap((item) => sourceOf(item).segmentIds))].sort(),
},
capability: capability(),
shape: { ...shape, effectiveArmCount: arms.length },
arms,
corners,
facilities,
});
}
module.exports = { topologyIdentity, structureFromTopology };
+7 -1
View File
@@ -24,7 +24,13 @@ fs.writeFileSync(
fs.readFileSync(path.join(__dirname, '..', 'outputs', 'fengshu-er-road', 'native-traffic-signals.json')),
);
const server = startWorkbench({ input, repoRoot: path.resolve(__dirname, '..'), dataRoot: root, port: 8899 });
const server = startWorkbench({
input,
repoRoot: path.resolve(__dirname, '..'),
dataRoot: root,
debug: true,
port: 8899,
});
const cleanup = () => {
server.close(() => fs.rmSync(root, { recursive: true, force: true }));
};
+60
View File
@@ -1,6 +1,9 @@
import fs from 'node:fs';
import { expect, test } from '@playwright/test';
import { strFromU8, unzipSync } from 'fflate';
import type OLMap from 'ol/Map';
import type VectorLayer from 'ol/layer/Vector';
import type VectorSource from 'ol/source/Vector';
test.describe('workbench editing shell', () => {
test.beforeEach(async ({ page }) => {
@@ -194,4 +197,61 @@ test.describe('workbench editing shell', () => {
await page.getByRole('button', { name: '放弃草稿' }).click();
await expect(heading).toHaveValue(original);
});
test('keeps complex junction structure and map selection linked across reload', async ({ page }) => {
const initial = await page.request.get('/api/state').then((response) => response.json());
const candidate = initial.debug.junctionCandidates.find((item: { nodeIds: string[] }) => item.nodeIds.length >= 3);
expect(candidate).toBeTruthy();
const acceptedResponse = await page.request.post('/api/junction-clusters', {
data: { candidateId: candidate.id, nodeIds: candidate.nodeIds },
});
expect(acceptedResponse.ok()).toBe(true);
const accepted = await acceptedResponse.json();
const id = accepted.added.id;
const structure = accepted.junctionStructures[`cluster:${id}`];
expect(structure.arms.length).toBeGreaterThanOrEqual(3);
await page.goto(`/junction/cluster/${encodeURIComponent(id)}`);
const workspace = page.getByLabel('路口编辑工作区');
await expect(workspace).toBeVisible();
const armButtons = workspace.locator('.junction-workspace__object-list').first().getByRole('button');
await expect(armButtons).toHaveCount(structure.arms.length);
const map = await page
.getByLabel('道路地图')
.evaluateHandle((element) => (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap);
await armButtons.first().click();
await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'true');
await expect
.poll(async () =>
page.getByLabel('道路地图').evaluate((element) => {
const map = (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap;
const layer = map
.getLayers()
.getArray()
.find((item) => item.getZIndex() === 89) as VectorLayer<VectorSource> | undefined;
return layer?.getSource()?.getFeatures().length || 0;
}),
)
.toBeGreaterThan(0);
const sameMap = await page
.getByLabel('道路地图')
.evaluate(
(element, original) =>
(element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap === original,
map,
);
expect(sameMap).toBe(true);
await expect(workspace.getByText('路口参数', { exact: true })).toHaveCount(0);
const scoped = await page.request
.get(`/api/edit-state?cluster=${encodeURIComponent(id)}`)
.then((response) => response.json());
expect(scoped.handles.handles).toEqual([]);
expect(scoped.junctionStructure.topologyFingerprint).toBe(structure.topologyFingerprint);
await page.reload();
await expect(armButtons).toHaveCount(structure.arms.length);
await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'false');
const refreshed = await page.request.get('/api/state').then((response) => response.json());
expect(refreshed.junctionStructures[`cluster:${id}`].arms.map((arm: { key: string }) => arm.key)).toEqual(
structure.arms.map((arm: { key: string }) => arm.key),
);
});
});
+211
View File
@@ -93,3 +93,214 @@ assert.equal(diagnostics[1].severity, 'warning');
assert.equal(diagnostics[1].objectKey, 'road-arm:road:east');
console.log('junction projection tests passed');
// Real geographic topology survives input and persisted-layer ordering changes.
const fs = require('fs');
const path = require('path');
const { compileRoadModel, compileGeometry } = require('../src/compile/native-road');
const { buildJunctionStructure } = require('../src/compile/junction-structure');
const overrides = { schema: 'native-road-overrides/v1', overrides: [] };
const baseline = compileRoadModel(
fs.readFileSync(path.join(__dirname, 'fixtures/fengshu-er-road.osm'), 'utf8'),
overrides,
);
const cluster = {
id: 'identity',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
};
function compileCluster(input, config) {
return compileGeometry(input, overrides, {
edgeLines: false,
junctionTemplates: { enabled: true, clusters: [config] },
});
}
const layers = compileCluster(baseline, cluster);
const ref = { type: 'cluster', id: cluster.id };
const authoritative = projectJunctionStructure({ model: baseline, layers, junctionRef: ref });
assert.equal(authoritative.arms.length, 5);
assert.equal(authoritative.junctionRef.type, 'cluster');
assert.equal(authoritative.capability.editable, false);
assert.ok(authoritative.arms.every((arm) => arm.carriageways.length && arm.capability.reason));
assert.deepEqual(buildJunctionStructure(JSON.parse(JSON.stringify(authoritative))), authoritative);
assert.throws(
() => buildJunctionStructure({ ...authoritative, provenance: { nodeIds: 'invalid' } }),
/array of strings/,
);
assert.throws(
() => buildJunctionStructure({ ...authoritative, capability: { editable: false, reason: ' ' } }),
/requires a reason/,
);
const reversed = structuredClone(baseline);
reversed.roads.reverse();
reversed.endpoints.reverse();
const reorderedLayers = compileCluster(reversed, { ...cluster, nodeIds: [...cluster.nodeIds].reverse() });
reorderedLayers.roadSurface.features.reverse();
const reordered = projectJunctionStructure({ model: reversed, layers: reorderedLayers, junctionRef: ref });
for (const kind of ['arms', 'corners', 'facilities'])
assert.deepEqual(reordered[kind].map((item) => item.key).sort(), authoritative[kind].map((item) => item.key).sort());
assert.equal(reordered.topologyFingerprint, authoritative.topologyFingerprint);
function closeCoordinates(actual, expected) {
assert.equal(actual.length, expected.length);
actual.forEach((value, index) => {
if (Array.isArray(value)) closeCoordinates(value, expected[index]);
else assert.ok(Math.abs(value - expected[index]) < 1e-9, `${value} != ${expected[index]}`);
});
}
for (const [name, collection] of Object.entries(layers)) {
const originalFeatures = (collection?.features || []).filter((feature) => feature.properties?.object_key);
const recompiledFeatures = new Map(
(reorderedLayers[name]?.features || []).map((feature) => [feature.properties?.native_id, feature]),
);
for (const feature of originalFeatures) {
const recompiled = recompiledFeatures.get(feature.properties.native_id);
assert.ok(recompiled, feature.properties.native_id);
assert.equal(recompiled.properties.object_key, feature.properties.object_key);
closeCoordinates(recompiled.geometry.coordinates, feature.geometry.coordinates);
}
}
assert.equal(
projectJunctionStructure({ model: baseline, layers, junctionRef: { type: 'cluster', id: 'missing' } }),
null,
);
const otherLayers = compileCluster(baseline, { ...cluster, id: 'other' });
const combined = {
roadSurface: {
type: 'FeatureCollection',
features: [...otherLayers.roadSurface.features, ...layers.roadSurface.features],
},
};
assert.equal(projectJunctionStructure({ layers: combined, junctionRef: ref }).junctionKey, 'cluster:identity');
assert.equal(
projectJunctionStructure({ layers: combined, junctionRef: { type: 'cluster', id: 'other' } }).junctionKey,
'cluster:other',
);
const objectKeys = new Set(
[
...authoritative.arms,
...authoritative.corners,
...authoritative.facilities,
...authoritative.arms.flatMap((arm) => arm.carriageways),
].map((item) => item.key),
);
for (const collection of Object.values(layers)) {
for (const feature of collection?.features || []) {
if (feature.properties?.cluster_id !== cluster.id || !feature.properties.object_key) continue;
assert.ok(objectKeys.has(feature.properties.object_key), feature.properties.object_key);
}
}
const sources = authoritative.arms.flatMap((arm) => arm.carriageways).flatMap((item) => item.provenance.roadIds);
for (const id of sources) {
const road = baseline.roads.find((item) => item.id === id);
assert.ok(
!(
cluster.nodeIds.includes(String(road.sourceNodeIds[0])) &&
cluster.nodeIds.includes(String(road.sourceNodeIds.at(-1)))
),
);
}
const removedId = sources[0];
const removed = structuredClone(baseline);
removed.roads = removed.roads.filter((road) => road.id !== removedId);
removed.endpoints = removed.endpoints.filter((endpoint) => endpoint.roadId !== removedId);
const afterRemoval = projectJunctionStructure({ layers: compileCluster(removed, cluster), junctionRef: ref });
assert.notEqual(afterRemoval.topologyFingerprint, authoritative.topologyFingerprint);
assert.ok(
!afterRemoval.arms.flatMap((arm) => arm.carriageways).some((item) => item.provenance.roadIds.includes(removedId)),
);
assert.deepEqual(standardsDiagnostics(null), []);
console.log('complex junction identity and provenance tests passed');
const signalFeatures = [
{ properties: { signal_uid: 'signal:member', control_id: cluster.nodeIds[0] } },
{ properties: { signal_uid: 'signal:node', node_id: cluster.nodeIds[1] } },
{ properties: { signal_uid: `signal:${cluster.nodeIds[0]}`, control_id: 'elsewhere' } },
{ properties: { signal_uid: 'signal:unscoped' } },
];
const withSignals = (features) =>
projectJunctionStructure({ layers, junctionRef: ref, trafficSignals: { assemblies: { features } } });
const signalStructure = withSignals(signalFeatures);
const projectedSignals = signalStructure.facilities.filter((item) => item.kind === 'signal');
assert.equal(projectedSignals.length, 2);
assert.ok(projectedSignals.every((item) => !item.editable && !item.capability.editable));
assert.deepEqual(
projectedSignals.map((item) => item.provenance.featureIds),
[['signal:member'], ['signal:node']],
);
assert.deepEqual(withSignals([...signalFeatures].reverse()), signalStructure);
assert.deepEqual(buildJunctionStructure(JSON.parse(JSON.stringify(signalStructure))), signalStructure);
assert.equal(withSignals([]).facilities.filter((item) => item.kind === 'signal').length, 0);
assert.equal(
withSignals([...signalFeatures, signalFeatures[0]]).facilities.find((item) => item.geometryRef === 'signal:member')
.capability.reason,
'source-ambiguous',
);
const { resolveComplexJunctionTopology, classifyJunctionShape } = require('../src/compile/complex-junction');
const { structureFromTopology } = require('../src/compile/junction-topology');
for (const headings of [
[0, 90, 180],
[0, 90, 180, 270],
[0, 60, 120, 180, 240, 300],
]) {
const syntheticModel = {
roads: headings.map((angle) => ({ id: `road:${angle}`, sourceNodeIds: ['a', `outer:${angle}`], laneCount: 1 })),
};
const approaches = headings.map((angle) => ({
segmentId: `segment:${angle}`,
roadIds: [`road:${angle}`],
widthMeters: 3.5,
line: [
[0, 0],
[Math.sin((angle * Math.PI) / 180) * 30, Math.cos((angle * Math.PI) / 180) * 30],
],
}));
const plans = new Map([
['a', { node: [0, 0], approaches }],
['b', { node: [1, 1], approaches: [] }],
]);
const helpers = {
junctionPlans: plans,
headingAtEndpoint: (line) => (Math.atan2(line[1][0], line[1][1]) * 180) / Math.PI,
lineLengthMeters: () => 30,
distanceMeters: (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]),
};
const topology = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
assert.equal(topology.arms.length, headings.length);
const shape = classifyJunctionShape(topology.arms, [0, 0], helpers);
assert.equal(structureFromTopology(topology, shape, [0, 0], []).shape.effectiveArmCount, headings.length);
if (headings.length === 4) {
approaches[0].line[1] = [0, 50];
const offset = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
const offsetShape = classifyJunctionShape(offset.arms, [0, 0], helpers);
assert.equal(offsetShape.kind, 'offset-cross');
const offsetStructure = structureFromTopology(offset, offsetShape, [0, 0], []);
assert.equal(offsetStructure.arms.length, 4);
assert.deepEqual(
offsetStructure.arms.map((arm) => arm.key),
structureFromTopology(topology, shape, [0, 0], []).arms.map((arm) => arm.key),
);
}
// Duplicate provenance never invents another editable object.
approaches.push(approaches[0]);
const duplicate = resolveComplexJunctionTopology(syntheticModel, { id: 'synthetic', nodeIds: ['a', 'b'] }, helpers);
const duplicateStructure = structureFromTopology(duplicate, shape, [0, 0], []);
assert.equal(duplicateStructure.arms.length, headings.length);
assert.ok(
duplicateStructure.arms
.flatMap((arm) => arm.carriageways)
.some((item) => item.capability.reason === 'source-ambiguous'),
);
syntheticModel.roads[1].sourceNodeIds = [];
const missingSource = resolveComplexJunctionTopology(
syntheticModel,
{ id: 'synthetic', nodeIds: ['a', 'b'] },
helpers,
);
assert.ok(
structureFromTopology(missingSource, shape, [0, 0], [])
.arms.flatMap((arm) => arm.carriageways)
.some((item) => item.capability.reason === 'source-missing'),
);
}
+103 -1
View File
@@ -7,7 +7,14 @@ const path = require('path');
const { compileInput } = require('../src/compile/compiler');
const { compileRoadModel, loadOverrides } = require('../src/compile/native-road');
const { ensureRevisionStore } = require('../src/compile/road-revisions');
const { editPreview, editState, rebaseEdits, saveEdits } = require('../workbench/server');
const {
editPreview,
editState,
rebaseEdits,
saveEdits,
state: browseState,
selectionFrom,
} = require('../workbench/server');
const { snapshot: outputSnapshot } = require('./fixture-baseline');
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'workbench-edit-api-'));
@@ -219,5 +226,100 @@ assert.notDeepEqual(
'a saved constraint must change the compiled output, or saving cannot survive a refresh',
);
// Typed scope must survive parsing and cannot silently choose the first key.
assert.deepEqual(selectionFrom(new URLSearchParams('cluster=fixture-five-arm')), {
type: 'cluster',
id: 'fixture-five-arm',
});
assert.deepEqual(selectionFrom({ junction: '8005332807' }), { type: 'junction', id: '8005332807' });
for (const invalid of [
{ cluster: 'one', junction: 'two' },
{ cluster: '' },
{ cluster: {} },
new URLSearchParams('cluster=one&cluster=two'),
]) {
assert.throws(() => selectionFrom(invalid), /selection/);
}
assert.throws(() => editPreview(area, { selection: { cluster: 'one', segment: 'two' } }), /selection/);
const cluster = {
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
};
const complexInput = {
...input,
outDir: path.join(workspace, 'outputs', 'complex'),
stagingDir: path.join(workspace, 'outputs', '_complex'),
options: { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } },
};
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.deepEqual(clusterState.junctionStructure.junctionRef, { type: 'cluster', id: cluster.id });
assert.equal(clusterState.junctionStructure.shape.effectiveArmCount, 5);
assert.equal(clusterState.junctionStructure.capability.editable, false);
const complexTracked = trackedFiles.map(({ file }) => ({
file,
bytes: fs.readFileSync(file),
mtimeMs: fs.statSync(file).mtimeMs,
}));
const emptyDocument = { ...clusterState.document, constraints: [], operations: [] };
const clusterPreview = editPreview(complexArea, { document: emptyDocument, selection: { cluster: cluster.id } });
assert.deepEqual(clusterPreview.handles.handles, []);
assert.deepEqual(
clusterPreview.junctionStructure,
clusterState.junctionStructure,
'preview and persisted compiler structure agree',
);
const browsing = browseState(complexArea);
const unavailableStructureState = browseState({
...complexArea,
nativeRoad: {
...complexArea.nativeRoad,
junctionTemplates: {
...complexArea.nativeRoad.junctionTemplates,
clusters: [
...complexArea.nativeRoad.junctionTemplates.clusters,
{ id: 'not-compiled', template: 'complex-junction-v1', nodeIds: ['missing-1', 'missing-2'] },
],
},
},
});
assert.equal(unavailableStructureState.junctionStructures['cluster:not-compiled'], undefined);
assert.ok(browsing.standardsDiagnostics.length, 'browse state retains structure diagnostics');
assert.equal(new Set(browsing.standardsDiagnostics.map((item) => item.id)).size, browsing.standardsDiagnostics.length);
assert.ok(
Object.values(browsing.junctionStructures).every(Boolean),
'the structure index contains only available structures',
);
assert.deepEqual(browsing.junctionStructures[`cluster:${cluster.id}`], clusterState.junctionStructure);
const simpleKey = Object.keys(browsing.junctionStructures).find(
(key) => key.startsWith('node:') && !cluster.nodeIds.includes(key.slice(5)),
);
assert.ok(simpleKey, 'fixture includes a simple junction outside the cluster');
const simpleState = editState(complexArea, selectionFrom({ junction: simpleKey.slice(5) }));
assert.deepEqual(simpleState.junctionStructure, browsing.junctionStructures[simpleKey]);
assert.equal(simpleState.junctionStructure.junctionRef.type, 'node');
for (const item of clusterState.standardsDiagnostics) {
assert.ok(browsing.standardsDiagnostics.some((candidate) => candidate.id === item.id));
}
assert.ok(simpleState.handles.handles.length);
for (const type of ['cluster', 'junction']) {
const missing = editState(complexArea, selectionFrom({ [type]: 'missing-junction' }));
assert.equal(missing.junctionStructure, null);
assert.deepEqual(missing.handles.handles, []);
assert.deepEqual(missing.standardsDiagnostics, []);
assert.equal(
editPreview(complexArea, { document: emptyDocument, selection: { [type]: 'missing-junction' } }).junctionStructure,
null,
);
}
for (const tracked of complexTracked) {
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, 'scoped reads and previews preserve active files');
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs);
}
fs.rmSync(workspace, { recursive: true, force: true });
console.log('workbench edit API tests passed');
+35 -15
View File
@@ -57,6 +57,12 @@ import type { JunctionRef } from './junction/hotspots';
import { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots';
import { JunctionWorkspace } from './junction/JunctionWorkspace';
import { localJunctionPreview, localJunctionState } from './junction/local-state';
import {
junctionEditSelection,
junctionObjectFeatures,
junctionObjectKeyForFeature,
structureForJunction,
} from './junction/structure';
import {
applyJunctionDraft,
cancelJunctionSession,
@@ -164,7 +170,7 @@ function App() {
editMode,
state,
selectedSegmentId: selected?.segmentId,
selectedJunctionId: junctionRoute?.type === 'node' ? junctionRoute.id : undefined,
selectedJunction: junctionRoute,
setStatus,
});
const {
@@ -206,6 +212,17 @@ function App() {
() => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state),
[junctionDescriptor, junctionRoute, state],
);
const junctionStructure = useMemo(
() => (junctionRoute ? structureForJunction(state, junctionRoute) : null),
[junctionRoute, state],
);
const junctionSelectionFeatures = useMemo(
() => junctionObjectFeatures(state, junctionStructure, selectedObjectKey),
[state, junctionStructure, selectedObjectKey],
);
useEffect(() => {
setSelectedObjectKey(null);
}, [junctionRoute]);
const junctionMapPreview = useMemo(
() =>
state && junctionDescriptor && junctionRoute
@@ -417,12 +434,11 @@ function App() {
// 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;
selectionRef.current = junctionRoute
? junctionEditSelection(junctionRoute)
: 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
@@ -902,13 +918,15 @@ function App() {
};
const handleFeature = (properties: Record<string, unknown>) => {
setMarking(properties);
const objectKey = properties.signal_uid
? `signal:${String(properties.signal_uid)}`
: properties.crossing_node_id
? `${properties.provenance === 'stop-line' ? 'stop-line' : 'crossing'}:${String(properties.crossing_node_id)}`
: properties.road_id
? `road-arm:${String(properties.road_id)}`
: null;
const objectKey = junctionStructure
? junctionObjectKeyForFeature(junctionStructure, properties)
: properties.signal_uid
? `signal:${String(properties.signal_uid)}`
: properties.crossing_node_id
? `${properties.provenance === 'stop-line' ? 'stop-line' : 'crossing'}:${String(properties.crossing_node_id)}`
: properties.road_id
? `road-arm:${String(properties.road_id)}`
: null;
setSelectedObjectKey(objectKey);
// A crosswalk is six features but one editable thing; a stop line is one.
// `provenance` picks which, and therefore which layer holds its siblings —
@@ -1065,6 +1083,7 @@ function App() {
scene={scene}
junctionHotspots={junctionHotspots}
junctionNodeMarkers={junctionNodeMarkers}
junctionSelectionFeatures={junctionSelectionFeatures}
referenceOpacity={referenceOpacity}
onJunctionHotspot={(ref: JunctionRef, _coordinate, descriptor) => {
openJunction(ref);
@@ -1080,6 +1099,7 @@ function App() {
onBackground={() => {
setElement(null);
setMarking(null);
setSelectedObjectKey(null);
}}
onSignalDrag={moveSignal}
onSignalDragEnd={finishSignalMove}
@@ -1178,7 +1198,7 @@ function App() {
descriptor={junctionDescriptor}
session={junctionSession}
dirty={Boolean(junctionSession.dirty || signalDirty)}
state={state}
state={junctionMapState}
diagnostics={junctionDiagnostics}
selectedObjectKey={selectedObjectKey}
onSelectObject={(key) => setSelectedObjectKey(key)}
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react';
import Feature from 'ol/Feature';
import GeoJSON from 'ol/format/GeoJSON';
import LineString from 'ol/geom/LineString';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
@@ -78,6 +79,8 @@ interface Props {
junctionHotspots?: boolean;
onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void;
junctionNodeMarkers?: Array<{ coordinate: Coordinate; label: string; selected: boolean }>;
/** Read-only semantic object selection from the compiler's stable object keys. */
junctionSelectionFeatures?: GeoJson['features'];
referenceOpacity?: number;
}
export function MapCanvas({
@@ -115,6 +118,7 @@ export function MapCanvas({
junctionHotspots = true,
onJunctionHotspot,
junctionNodeMarkers = [],
junctionSelectionFeatures,
referenceOpacity = 0.55,
}: Props) {
const target = useRef<HTMLDivElement>(null);
@@ -129,6 +133,7 @@ export function MapCanvas({
const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const signalTransformSourceRef = useRef<VectorSource | null>(null);
const signalTransformLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const junctionSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const junctionNodeMarkerSourceRef = useRef<VectorSource | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
@@ -285,6 +290,7 @@ export function MapCanvas({
// road inspector, and dragging is owned by the edit interaction.
layers: (layer) =>
layer !== layers.selectedRoad &&
layer !== junctionSelectionLayerRef.current &&
layer !== handleLayer?.layer &&
layer !== laneSelectionLayer &&
layer !== signalTransformLayer &&
@@ -448,12 +454,40 @@ export function MapCanvas({
return () => {
select.un('select', listener);
junctionNodeMarkerSourceRef.current = null;
junctionSelectionLayerRef.current = null;
map.setTarget(undefined);
delete (target.current as HTMLDivElement & { __roadWorkbenchMap?: Map })?.__roadWorkbenchMap;
};
// Map construction must be once per mounted canvas; state changes update sources below.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const map = mapRef.current;
if (!map) return;
let layer = junctionSelectionLayerRef.current;
if (!layer && junctionSelectionFeatures?.length) {
layer = new VectorLayer({
source: new VectorSource(),
zIndex: 89,
style: new Style({
stroke: new Stroke({ color: '#0891b2', width: 3 }),
fill: new Fill({ color: 'rgba(8,145,178,0.16)' }),
image: new CircleStyle({ radius: 8, stroke: new Stroke({ color: '#0891b2', width: 3 }) }),
}),
});
junctionSelectionLayerRef.current = layer;
map.addLayer(layer);
}
const source = layer?.getSource();
if (!source) return;
source.clear();
source.addFeatures(
new GeoJSON().readFeatures(
{ type: 'FeatureCollection', features: junctionSelectionFeatures || [] },
{ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' },
),
);
}, [junctionSelectionFeatures]);
useEffect(() => {
const source = junctionNodeMarkerSourceRef.current;
if (!source) return;
+1 -1
View File
@@ -214,7 +214,7 @@ export interface EditStateResponse {
* renders about six handles. Wire form matches the `?segment=` / `?junction=`
* query the GET route accepts.
*/
export type EditSelection = { segment: string } | { junction: string };
export type EditSelection = { segment: string } | { junction: string } | { cluster: string };
/**
* `POST /api/edit-preview`. Sending `constraints` alone lets the server merge
@@ -2,7 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { api } from '../lib/api';
import { EditSession } from '../edit/session';
import type { EditDiagnostic, HandleManifest, PreviewLayerName } from '../edit/types';
import type { GeoJson, WorkbenchState } from '../types/state';
import type { GeoJson, JunctionRef, WorkbenchState } from '../types/state';
import { junctionEditSelection } from '../junction/structure';
/**
* Owns the stable v2 session and the server state that surrounds it. Gesture
@@ -12,13 +13,13 @@ export function useDirectEditSession({
editMode,
state,
selectedSegmentId,
selectedJunctionId,
selectedJunction,
setStatus,
}: {
editMode: boolean;
state?: WorkbenchState;
selectedSegmentId?: string;
selectedJunctionId?: string;
selectedJunction?: JunctionRef | null;
setStatus: (status: string) => void;
}) {
const [manifest, setManifest] = useState<HandleManifest | null>(null);
@@ -33,16 +34,18 @@ export function useDirectEditSession({
useEffect(() => {
// Flag off: no manifest request at all, so the network trace matches browse mode.
if (!editMode) return;
let current = true;
setManifest(null);
api
.editState(
selectedJunctionId
? { junction: selectedJunctionId }
selectedJunction
? junctionEditSelection(selectedJunction)
: selectedSegmentId
? { segment: selectedSegmentId }
: undefined,
)
.then((value) => {
if (!('handles' in value)) return;
if (!current || !('handles' in value)) return;
setManifest(value.handles);
const key = `${value.areaId}:${value.documentVersion}`;
if (loadedDocument.current === key) return;
@@ -50,8 +53,13 @@ export function useDirectEditSession({
sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion);
touch();
})
.catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`));
}, [editMode, selectedJunctionId, selectedSegmentId, setStatus, state]);
.catch((error: Error) => {
if (current) setStatus(`直接编辑手柄不可用:${error.message}`);
});
return () => {
current = false;
};
}, [editMode, selectedJunction, selectedSegmentId, setStatus, state]);
return {
session: sessionRef.current,
@@ -10,6 +10,7 @@ import type { WorkbenchState } from '../types/state';
import type { Coordinate } from '../edit/meters';
import { junctionLabelForHandle, junctionRoadName } from './labels';
import { junctionFacilities } from './facilities';
import { junctionCapabilityReason, structureForJunction } from './structure';
import { SignalEditor } from '../components/ElementEditors';
interface Props {
@@ -175,7 +176,7 @@ export function JunctionWorkspace({
() => (state ? junctionFacilities(state, descriptor.nodeIds, roads) : []),
[descriptor.nodeIds, roads, state],
);
const structure = state?.junctionStructure;
const structure = structureForJunction(state, descriptor.ref);
const standardDiagnostics = state?.standardsDiagnostics || [];
return (
<section className="junction-workspace" aria-label="路口编辑工作区">
@@ -237,6 +238,7 @@ export function JunctionWorkspace({
{state.junctionReference.source || '已加载参考文件'}
</p>
) : null}
{structure.capability?.reason ? <p>{junctionCapabilityReason(structure.capability.reason)}</p> : null}
<dl>
<dt>道路臂</dt>
<dd>
@@ -248,6 +250,8 @@ export function JunctionWorkspace({
key={arm.key}
className={selectedObjectKey === arm.key ? 'is-selected' : undefined}
onClick={() => onSelectObject?.(arm.key)}
aria-pressed={selectedObjectKey === arm.key}
title={junctionCapabilityReason(arm.capability?.reason)}
>
{arm.label}
</button>
@@ -258,7 +262,26 @@ export function JunctionWorkspace({
)}
</dd>
<dt>角部</dt>
<dd>{structure.corners.length ? structure.corners.map((corner) => corner.label).join('、') : '无'}</dd>
<dd>
{structure.corners.length ? (
<span className="junction-workspace__object-list">
{structure.corners.map((corner) => (
<button
type="button"
key={corner.key}
className={selectedObjectKey === corner.key ? 'is-selected' : undefined}
aria-pressed={selectedObjectKey === corner.key}
title={junctionCapabilityReason(corner.capability?.reason)}
onClick={() => onSelectObject?.(corner.key)}
>
{corner.label}
</button>
))}
</span>
) : (
'无'
)}
</dd>
<dt>设施</dt>
<dd>
{structure.facilities.length ? (
@@ -270,7 +293,16 @@ export function JunctionWorkspace({
<summary>已识别 {structure.facilities.length} 项设施</summary>
<ul>
{structure.facilities.map((facility) => (
<li key={facility.key}>{facility.label}</li>
<li key={facility.key}>
<button
type="button"
aria-pressed={selectedObjectKey === facility.key}
title={junctionCapabilityReason(facility.capability?.reason)}
onClick={() => onSelectObject?.(facility.key)}
>
{facility.label}
</button>
</li>
))}
</ul>
</details>
+20 -1
View File
@@ -1,6 +1,7 @@
import type { Diagnostic, JunctionCandidate, Position, WorkbenchState, JunctionClusterConfig } from '../types/state';
export type JunctionRef = { type: 'node' | 'cluster'; id: string };
export type { JunctionRef } from '../types/state';
import type { JunctionRef } from '../types/state';
export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate';
export interface JunctionDescriptor {
ref: JunctionRef;
@@ -158,6 +159,24 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[]
const descriptor = candidateDescriptor(candidate, diagnostic, configured);
if (descriptor) result.push(descriptor);
}
// Compiler-owned topology replaces heuristic cluster footprints when available.
// This also works outside debug mode and excludes cluster-internal connections.
for (const structure of Object.values(state.junctionStructures || {})) {
if (structure.junctionRef?.type !== 'cluster' || !structure.center || !structure.provenance) continue;
const descriptor: JunctionDescriptor = {
ref: structure.junctionRef,
status: 'readonly',
coordinate: structure.center,
radiusMeters: 16,
nodeIds: structure.provenance.nodeIds,
approachRoadIds: structure.provenance.roadIds,
diagnosticIds: [],
source: 'cluster-config',
};
const existing = result.findIndex((item) => item.ref.type === 'cluster' && item.ref.id === descriptor.ref.id);
if (existing >= 0) result[existing] = descriptor;
else result.push(descriptor);
}
const unique = new Map<string, JunctionDescriptor>();
for (const descriptor of result) {
const key = `${descriptor.ref.type}:${descriptor.ref.id}`;
+19 -4
View File
@@ -1,6 +1,7 @@
import type { GeoFeature, GeoJson, Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from './hotspots';
import type { PreviewLayerName } from '../edit/types';
import { structureForJunction } from './structure';
const empty: GeoJson = { type: 'FeatureCollection', features: [] };
@@ -28,8 +29,16 @@ 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 {
function related(
feature: GeoFeature,
nodeIds: Set<string>,
roadIds: Set<string>,
segmentIds: Set<string>,
descriptor?: JunctionDescriptor,
): boolean {
const props = feature.properties || {};
if (descriptor && props.junction_key) return props.junction_key === `${descriptor.ref.type}:${descriptor.ref.id}`;
if (descriptor?.ref.type === 'cluster' && props.cluster_id) return String(props.cluster_id) === descriptor.ref.id;
const nodeKeys = ['node_id', 'osm_node_id', 'control_id', 'crossing_node_id', 'junction_node_id'];
if (
nodeKeys.some((key) => {
@@ -75,7 +84,7 @@ export function localJunctionPreview(
if (value === null || value === undefined) continue;
scoped[name] = {
type: 'FeatureCollection',
features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds)),
features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds, descriptor)),
};
}
return scoped;
@@ -92,7 +101,7 @@ export function localJunctionState(state: WorkbenchState, descriptor: JunctionDe
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)),
features: (value?.features || []).filter((feature) => related(feature, nodeIds, roadIds, segmentIds, descriptor)),
});
const layerNames = [
'nativeRoadSurface',
@@ -113,10 +122,16 @@ export function localJunctionState(state: WorkbenchState, descriptor: JunctionDe
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),
related(feature, nodeIds, roadIds, segmentIds, descriptor),
);
const structure = structureForJunction(state, descriptor.ref);
const objectKeys = new Set(
structure ? [...structure.arms, ...structure.corners, ...structure.facilities].map((object) => object.key) : [],
);
return {
...state,
junctionStructure: structure,
standardsDiagnostics: state.standardsDiagnostics?.filter((item) => objectKeys.has(item.objectKey)),
compiled: {
...state.compiled,
model: {
@@ -0,0 +1,144 @@
import { describe, expect, it } from 'vitest';
import type { GeoFeature, JunctionStructure, WorkbenchState } from '../types/state';
import { junctionDescriptors } from './hotspots';
import { localJunctionPreview, localJunctionState } from './local-state';
import {
junctionEditSelection,
junctionObjectFeatures,
junctionObjectKeyForFeature,
structureForJunction,
} from './structure';
const structure: JunctionStructure = {
schema: 'junction-structure/v1',
junctionKey: 'cluster:a',
junctionRef: { type: 'cluster', id: 'a' },
label: '路口 A',
center: [120, 30],
provenance: { nodeIds: ['1', '2'], roadIds: ['external'], segmentIds: ['external-segment'] },
capability: { editable: false, reason: 'complex-geometry-editing-not-implemented' },
shape: { kind: 't-junction', label: 'T 字', effectiveArmCount: 3, throughPairCount: 1 },
arms: ['a', 'b', 'c'].map((id) => ({ key: `arm:${id}`, label: `道路 ${id}`, directionality: 'two-way' })),
corners: [{ key: 'corner:a', label: '角部 A', fromArmKey: 'arm:a', toArmKey: 'arm:b' }],
facilities: [{ key: 'crossing:a', label: '过街 A', kind: 'crossing' }],
};
const feature = (object: string, junction = 'cluster:a', arm?: string): GeoFeature => ({
type: 'Feature',
properties: { junction_key: junction, object_key: object, arm_key: arm },
geometry: {
type: 'Polygon',
coordinates: [
[
[120, 30],
[120.001, 30],
[120, 30.001],
[120, 30],
],
],
},
});
const road = (id: string, nodes: string[]) => ({
id,
sourceNodeIds: nodes,
segmentId: `${id}-segment`,
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 7,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
});
const state: WorkbenchState = {
areaId: 'test',
compiled: {
model: { roads: [road('external', ['1', '3']), road('internal', ['1', '2'])], endpoints: [], connections: [] },
diagnostics: [],
},
overrides: { schema: 'native-road-overrides/v1', overrides: [] },
trafficSignals: { provenance: 'empty', assemblies: { type: 'FeatureCollection', features: [] } },
trafficRuntime: { signals: [] },
comparison: {},
junctionStructures: { 'cluster:a': structure },
junctionStructure: structure,
layers: {
nativeRoadSurface: {
type: 'FeatureCollection',
features: [feature('carriageway:a', 'cluster:a', 'arm:a'), feature('carriageway:b', 'cluster:b', 'arm:a')],
},
crosswalks: {
type: 'FeatureCollection',
features: [feature('crossing:a'), feature('crossing:a'), feature('crossing:b', 'cluster:b')],
},
nativeIntersectionSurface: { type: 'FeatureCollection', features: [feature('corner:a')] },
},
};
describe('authoritative junction structures', () => {
it('uses typed scopes without leaking the legacy first structure', () => {
expect(junctionEditSelection({ type: 'cluster', id: 'a' })).toEqual({ cluster: 'a' });
expect(junctionEditSelection({ type: 'node', id: 'a' })).toEqual({ junction: 'a' });
expect(structureForJunction(state, { type: 'cluster', id: 'a' })).toBe(structure);
expect(structureForJunction(state, { type: 'node', id: 'a' })).toBeNull();
expect(structureForJunction(state, { type: 'cluster', id: 'missing' })).toBeNull();
});
it('makes map and list select the same arm, corner and crossing group', () => {
expect(junctionObjectKeyForFeature(structure, feature('carriageway:a', 'cluster:a', 'arm:a').properties!)).toBe(
'arm:a',
);
expect(junctionObjectKeyForFeature(structure, feature('corner:a').properties!)).toBe('corner:a');
expect(junctionObjectKeyForFeature(structure, feature('crossing:a').properties!)).toBe('crossing:a');
expect(junctionObjectKeyForFeature(structure, feature('crossing:a', 'cluster:b').properties!)).toBeNull();
expect(junctionObjectFeatures(state, structure, 'arm:a')).toHaveLength(1);
expect(junctionObjectFeatures(state, structure, 'crossing:a')).toHaveLength(2);
expect(junctionObjectFeatures(state, structure, 'corner:a')).toHaveLength(1);
expect(junctionObjectFeatures(state, structure, 'deleted')).toEqual([]);
});
it('scopes the canvas and preview using cluster ownership, retaining core features without node IDs', () => {
const descriptor = junctionDescriptors(state).find((item) => item.ref.type === 'cluster')!;
expect(descriptor.status).toBe('readonly');
expect(descriptor.approachRoadIds).toEqual(['external']);
const local = localJunctionState(state, descriptor);
expect(local.compiled.model.roads.map((item) => item.id)).toEqual(['external']);
expect(local.junctionStructure).toBe(structure);
expect(local.layers.nativeRoadSurface?.features).toHaveLength(1);
expect(local.layers.nativeIntersectionSurface?.features).toHaveLength(1);
const preview = localJunctionPreview(
{ roadSurface: state.layers.nativeRoadSurface },
descriptor,
state.compiled.model.roads,
);
expect(preview?.roadSurface?.features).toHaveLength(1);
});
it('resolves separately persisted signals through scoped provenance without parsing their IDs', () => {
const signal = { ...feature('unused'), properties: { signal_uid: 'raw:signal:uid' } };
const withSignal = {
...structure,
facilities: [
...structure.facilities,
{
key: 'cluster:a:signal:raw',
kind: 'signal',
label: '信号灯',
geometryRef: 'raw:signal:uid',
provenance: { featureIds: ['raw:signal:uid'] },
},
],
};
const signalState = {
...state,
trafficSignals: {
...state.trafficSignals,
assemblies: { ...state.trafficSignals.assemblies, features: [signal] },
},
};
expect(junctionObjectKeyForFeature(withSignal, signal.properties)).toBe('cluster:a:signal:raw');
expect(junctionObjectFeatures(signalState, withSignal, 'cluster:a:signal:raw')).toEqual([signal]);
expect(junctionObjectKeyForFeature(structure, signal.properties)).toBeNull();
});
});
@@ -0,0 +1,79 @@
import type { GeoFeature, JunctionRef, JunctionStructure, WorkbenchState } from '../types/state';
import type { EditSelection } from '../edit/types';
export function junctionEditSelection(ref: JunctionRef): EditSelection {
return ref.type === 'cluster' ? { cluster: ref.id } : { junction: ref.id };
}
/** A missing scoped structure must never show another junction's first result. */
export function structureForJunction(state: WorkbenchState | undefined, ref: JunctionRef): JunctionStructure | null {
const structure = state?.junctionStructures?.[`${ref.type}:${ref.id}`] ?? state?.junctionStructure;
if (!structure) return null;
return structure.junctionRef?.type === ref.type && structure.junctionRef.id === ref.id ? structure : null;
}
function objects(structure: JunctionStructure) {
return [...structure.arms, ...structure.corners, ...structure.facilities];
}
export function junctionCapabilityReason(reason: string | undefined): string | undefined {
if (!reason) return undefined;
switch (reason) {
case 'complex-geometry-editing-not-implemented':
return '当前可查看和选择,参数编辑将在后续阶段开放。';
case 'source-missing':
return '对象来源已缺失,暂不可编辑。';
case 'source-ambiguous':
return '对象来源存在歧义,暂不可编辑。';
default:
return '当前对象暂不可编辑。';
}
}
export function junctionObjectKeyForFeature(
structure: JunctionStructure | null,
properties: Record<string, unknown>,
): string | null {
if (!structure) return null;
if (properties.junction_key && properties.junction_key !== structure.junctionKey) return null;
const keys = [properties.object_key, properties.facility_key, properties.corner_key, properties.arm_key];
const candidates = objects(structure);
for (const key of keys) {
if (typeof key === 'string' && candidates.some((object) => object.key === key)) return key;
}
// Signals are a separate persisted layer. The server attaches their existing
// UID to the scoped structure without rewriting the signal document.
if (typeof properties.signal_uid === 'string') {
return (
structure.facilities.find(
(object) => object.kind === 'signal' && object.provenance?.featureIds?.includes(String(properties.signal_uid)),
)?.key ?? null
);
}
if (structure.junctionRef?.type === 'node') {
const ids = [properties.native_id, properties.signal_uid, properties.road_id];
return candidates.find((object) => object.geometryRef && ids.includes(object.geometryRef))?.key ?? null;
}
return null;
}
/** Resolve the selected semantic object to its published map features. */
export function junctionObjectFeatures(
state: WorkbenchState | undefined,
structure: JunctionStructure | null,
key: string | null,
): GeoFeature[] {
if (!state || !structure || !key || !objects(structure).some((object) => object.key === key)) return [];
const seen = new Set<GeoFeature>();
return [...Object.values(state.layers), state.trafficSignals.assemblies].flatMap((layer) =>
(layer?.features ?? []).filter((feature) => {
if (seen.has(feature)) return false;
seen.add(feature);
const properties = feature.properties || {};
if (typeof properties.signal_uid === 'string') return junctionObjectKeyForFeature(structure, properties) === key;
if (structure.junctionRef?.type === 'node') return junctionObjectKeyForFeature(structure, properties) === key;
if (properties.junction_key !== structure.junctionKey) return false;
return [properties.object_key, properties.arm_key, properties.corner_key, properties.facility_key].includes(key);
}),
);
}
+52 -8
View File
@@ -87,19 +87,62 @@ export interface Diagnostic {
geometry?: { type: string; coordinates: unknown };
manualCandidates?: Array<{ roadId: string; distanceMeters: number }>;
}
export type JunctionRef = { type: 'node' | 'cluster'; id: string };
export interface JunctionProvenance {
nodeIds?: string[];
segmentIds?: string[];
roadIds?: string[];
osmWayIds?: string[];
carriagewayKeys?: string[];
armKeys?: string[];
featureIds?: string[];
}
export interface JunctionSource extends JunctionProvenance {
nodeIds: string[];
segmentIds: string[];
roadIds: string[];
}
export interface JunctionCapability {
editable: boolean;
reason?: string;
}
export interface JunctionObject {
key: string;
label: string;
geometryRef?: string;
geometryRefs?: string[];
provenance?: JunctionProvenance;
capability?: JunctionCapability;
}
export interface JunctionStructure {
schema: string;
junctionKey: string;
junctionRef?: JunctionRef;
topologyFingerprint?: string;
provenance?: JunctionSource;
capability?: JunctionCapability;
center?: Position;
label: string;
shape: { kind: string; label: string; effectiveArmCount: number; throughPairCount: number };
arms: Array<{
key: string;
label: string;
directionality: string;
carriageway?: { laneCount?: number; effectiveWidthMeters?: number };
}>;
corners: Array<{ key: string; label: string; fromArmKey: string; toArmKey: string }>;
facilities: Array<{ key: string; kind: string; label: string }>;
arms: Array<
JunctionObject & {
heading?: number;
directionality: string;
carriageway?: { laneCount?: number; effectiveWidthMeters?: number };
carriageways?: Array<{
key: string;
geometryRef: string;
laneCount: number;
effectiveWidthMeters: number;
provenance: JunctionSource;
capability: JunctionCapability;
}>;
}
>;
corners: Array<JunctionObject & { fromArmKey: string; toArmKey: string }>;
facilities: Array<
JunctionObject & { kind: string; armKey?: string; cornerKey?: string; relatedFacilityKey?: string }
>;
}
export interface StandardsDiagnostic {
id: string;
@@ -133,6 +176,7 @@ export interface WorkbenchState {
junctionShapes?: JunctionShapeSummary[];
} | null;
junctionStructure?: JunctionStructure | null;
junctionStructures?: Record<string, JunctionStructure>;
standardsProfile?: { id: string; label: string };
standardsDiagnostics?: StandardsDiagnostic[];
}
+93 -10
View File
@@ -247,7 +247,38 @@ function state(area, junctionReference = null, debug = false) {
const trafficRuntime = runtime(trafficSignals);
const compiled = readCompiled(area);
const layers = readWorkbenchLayers(nativeDir, osm2streetsRoadSurface);
const junctionStructure = projectJunctionStructure({ model: compiled.model, layers, trafficSignals });
const clusters = area.nativeRoad?.junctionTemplates?.clusters || [];
const nodeSegments = new Map();
const roadsById = new Map((compiled.model.roads || []).map((road) => [road.id, road]));
for (const endpoint of compiled.model.endpoints || []) {
const id = String(endpoint.nodeId);
if (!nodeSegments.has(id)) nodeSegments.set(id, new Set());
nodeSegments.get(id).add(roadsById.get(endpoint.roadId)?.segmentId || endpoint.roadId);
}
const refs = [
...[...nodeSegments].filter(([, segments]) => segments.size >= 2).map(([id]) => ({ type: 'node', id })),
...clusters.map((cluster) => ({ type: 'cluster', id: String(cluster.id) })),
];
const junctionStructures = Object.fromEntries(
refs
.map((junctionRef) => [
`${junctionRef.type}:${junctionRef.id}`,
projectJunctionStructure({
model: compiled.model,
layers: {
...layers,
roadSurface: layers.nativeRoadSurface,
intersectionSurface: layers.nativeIntersectionSurface,
sidewalkSurface: layers.nativeSidewalkSurface,
},
trafficSignals,
junctionRef,
clusters,
}),
])
.filter(([, structure]) => structure !== null),
);
const junctionStructure = null;
const junctionShapes = debug
? (readLayer(path.join(nativeDir, 'layers', 'road_surface.geojson')).features || [])
.filter((feature) => feature.properties?.kind === 'complex-core' && feature.properties?.cluster_id)
@@ -276,9 +307,16 @@ function state(area, junctionReference = null, debug = false) {
}
: null,
compiled,
junctionStructures,
junctionStructure,
standardsProfile: { id: 'cn-urban-default', label: '中国城市道路(项目默认)' },
standardsDiagnostics: standardsDiagnostics(junctionStructure),
standardsDiagnostics: [
...new Map(
Object.values(junctionStructures)
.flatMap((structure) => standardsDiagnostics(structure))
.map((item) => [item.id, item]),
).values(),
],
overrides: loadOverrides(area.outputs.nativeRoadOverrides),
trafficSignals,
trafficRuntime,
@@ -323,11 +361,28 @@ function activeRevisionFields(area) {
// while the map renders about six handles. Omitting it keeps the full manifest for
// callers that want it.
function selectionFrom(source) {
if (!source) return null;
const segment = source.segment ?? source.get?.('segment');
if (segment) return { type: 'segment', id: String(segment) };
const junction = source.junction ?? source.get?.('junction');
if (junction) return { type: 'junction', id: String(junction) };
if (source == null) return null;
if (typeof source !== 'object' || Array.isArray(source)) throw new Error('selection must be an object.');
const keys = ['segment', 'junction', 'cluster'];
const entries = keys.flatMap((key) => {
if (typeof source.getAll === 'function') return source.getAll(key).map((value) => [key, value]);
return Object.hasOwn(source, key) ? [[key, source[key]]] : [];
});
if (entries.length > 1) throw new Error('selection must specify only one of segment, junction, or cluster.');
if (!entries.length) return null;
const [key, value] = entries[0];
if (
(typeof value !== 'string' && typeof value !== 'number') ||
!String(value).trim() ||
(typeof value === 'number' && !Number.isFinite(value))
)
throw new Error(`selection.${key} must be a non-empty ID.`);
return { type: key, id: String(value).trim() };
}
function junctionRefFromSelection(selection) {
if (selection?.type === 'junction') return { type: 'node', id: selection.id };
if (selection?.type === 'cluster') return { type: 'cluster', id: selection.id };
return null;
}
@@ -339,13 +394,21 @@ function editState(area, selection = null) {
const resolution = resolveDirectEditConstraints(model, directEdits, {
revisionId: initialized.active.activeRevisionId,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
selection,
});
const compiled = readCompiled(area);
const layers = readWorkbenchLayers(area.outputs.nativeRoadDir, null);
const junctionStructure = projectJunctionStructure({
model: compiled.model,
layers,
junctionRef: junctionRefFromSelection(selection),
clusters: area.nativeRoad?.junctionTemplates?.clusters || [],
layers: {
...layers,
roadSurface: layers.nativeRoadSurface,
intersectionSurface: layers.nativeIntersectionSurface,
sidewalkSurface: layers.nativeSidewalkSurface,
},
trafficSignals: readJson(area.outputs.nativeTrafficSignals),
});
return {
@@ -381,12 +444,14 @@ function editPreview(area, body = {}) {
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, {
revisionId: activeState.activeRevisionId,
previewSeq,
compilerGeometryVersion: GEOMETRY_VERSION,
selection: selectionFrom(body.selection),
junctionTemplates: area.nativeRoad?.junctionTemplates,
selection,
});
const compiled = compileGeometry(model, persistedOverrides, {
edgeLines: area.nativeRoad.edgeLines,
@@ -396,7 +461,14 @@ function editPreview(area, body = {}) {
const diagnostics = [...compiled.diagnostics, ...resolution.diagnostics];
const junctionStructure = projectJunctionStructure({
model,
junctionRef: junctionRefFromSelection(selection),
clusters: area.nativeRoad?.junctionTemplates?.clusters || [],
layers: {
roadSurface: compiled.roadSurface,
sidewalkSurface: compiled.sidewalkSurface,
islands: compiled.intersectionSurface,
medians: compiled.intersectionSurface,
sidewalkTurns: compiled.sidewalkSurface,
crosswalks: compiled.crosswalks,
vehicleStopLines: compiled.vehicleStopLines,
intersectionSurface: compiled.intersectionSurface,
@@ -456,6 +528,7 @@ function saveEdits(area, body = {}) {
const resolution = resolveDirectEditConstraints(model, candidate, {
revisionId: initialized.active.activeRevisionId,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
});
const blockingDiagnostic = resolution.diagnostics.find((item) => item.severity === 'error');
if (blockingDiagnostic) {
@@ -484,6 +557,7 @@ function rebaseEdits(area, revisionId) {
const resolution = resolveDirectEditConstraints(model, revision.directEdits, {
revisionId,
compilerGeometryVersion: GEOMETRY_VERSION,
junctionTemplates: area.nativeRoad?.junctionTemplates,
replay: true,
});
const counts = Object.fromEntries(
@@ -750,4 +824,13 @@ function sendJson(response, status, value) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
response.end(`${JSON.stringify(value)}\n`);
}
module.exports = { startWorkbench, readMultipart, editState, editPreview, saveEdits, rebaseEdits };
module.exports = {
startWorkbench,
readMultipart,
state,
selectionFrom,
editState,
editPreview,
saveEdits,
rebaseEdits,
};