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

+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[];
}