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

@@ -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);
}),
);
}