feat(workbench): add junction hotspot entry points

This commit is contained in:
que01 committed 2026-09-03 11:12:22 +08:00
1 parent bd7b049930
commit 7d9b0f46d4
6 files changed
+288 -6

No files matched your search

+7
View File
@@ -53,6 +53,7 @@ import type {
import { Button } from './ui/button';
import type { GeoFeature, GeoJson, Road, WorkbenchState } from './types/state';
import type { LayerName } from './map/layers';
import type { JunctionRef } from './junction/hotspots';
const layerLabels: Array<[LayerName, string]> = [
['osm', '方向道路参考线'],
@@ -65,6 +66,7 @@ const layerLabels: Array<[LayerName, string]> = [
['edgeLines', '道路外缘线'],
['controls', '斑马线与停止线'],
['signals', '红绿灯设施'],
['junctionHotspots', '路口编辑热区'],
];
const defaultLayers = Object.fromEntries(layerLabels.map(([key]) => [key, key !== 'edgeLines'])) as Record<
LayerName,
@@ -78,6 +80,7 @@ function App() {
const [selected, setSelected] = useState<Road | null>(null);
const [layers, setLayers] = useState(defaultLayers);
const [scene, setScene] = useState(false);
const [junctionHotspots, setJunctionHotspots] = useState(true);
const [status, setStatus] = useState('正在加载工作台...');
const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all');
const [marking, setMarking] = useState<Record<string, unknown> | null>(null);
@@ -802,6 +805,10 @@ function App() {
selected={selected}
visible={layers}
scene={scene}
junctionHotspots={junctionHotspots}
onJunctionHotspot={(ref: JunctionRef) => {
setStatus(ref.type === 'node' ? `已定位路口节点 ${ref.id}(可编辑)` : `已定位路口 ${ref.id}(只读)`);
}}
onSelectRoad={setSelected}
onFeature={handleFeature}
signalSelectionUid={typeof marking?.signal_uid === 'string' ? marking.signal_uid : null}
+22 -5
View File
@@ -15,7 +15,8 @@ import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import { click } from 'ol/events/condition';
import type { GeoJson, Road, WorkbenchState } from '../types/state';
import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers';
import { createLayers, updateJunctionHotspots, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers';
import { junctionDescriptors, type JunctionDescriptor, type JunctionRef } from '../junction/hotspots';
import { createHandleDragInteraction } from '../edit/drag-interaction';
import { EditGhostLayer } from '../edit/ghost-layer';
import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer';
@@ -70,6 +71,8 @@ interface Props {
/** Last solve came back degraded; hold the ghost instead of clearing it. */
ghostPending?: boolean;
editMode?: boolean;
junctionHotspots?: boolean;
onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void;
}
export function MapCanvas({
state,
@@ -102,6 +105,8 @@ export function MapCanvas({
onRangeEnd,
ghostPending,
editMode = false,
junctionHotspots = true,
onJunctionHotspot,
}: Props) {
const target = useRef<HTMLDivElement>(null);
const mapRef = useRef<Map | null>(null);
@@ -155,8 +160,8 @@ export function MapCanvas({
laneSelectionAxisAzimuth,
ghostPending,
};
const selectRef = useRef({ onSelectRoad, onFeature, onBackground });
selectRef.current = { onSelectRoad, onFeature, onBackground };
const selectRef = useRef({ onSelectRoad, onFeature, onBackground, onJunctionHotspot });
selectRef.current = { onSelectRoad, onFeature, onBackground, onJunctionHotspot };
const selectedRef = useRef<Road | null>(selected);
const stateRef = useRef(state);
const sceneRef = useRef(scene);
@@ -249,11 +254,22 @@ export function MapCanvas({
layer !== layers.selectedRoad &&
layer !== handleLayer?.layer &&
layer !== laneSelectionLayer &&
layer !== signalTransformLayer,
layer !== signalTransformLayer &&
layer !== layers.junctionHotspots,
hitTolerance: 12,
style: null,
});
map.addInteraction(select);
map.on('singleclick', (event) => {
const hit = map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
layerFilter: (layer) => layer === layers.junctionHotspots,
hitTolerance: 12,
});
const ref = hit?.get('junction_ref');
const descriptor = hit?.get('junction_descriptor');
if (!ref || !descriptor) return;
selectRef.current.onJunctionHotspot?.(ref, toLonLat(event.coordinate as Coordinate), descriptor);
});
let signalUid: string | null = null;
let rotatePivot: Coordinate | null = null;
map.addInteraction(
@@ -409,12 +425,13 @@ export function MapCanvas({
const map = mapRef.current;
if (!layers || !map) return;
updateLayers(layers, state, selected);
updateJunctionHotspots(layers, junctionDescriptors(state), junctionHotspots);
const extent = layers.osm.getSource()!.getExtent();
if (fittedAreaIdRef.current !== state.areaId && extent && Number.isFinite(extent[0])) {
map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 });
fittedAreaIdRef.current = state.areaId;
}
}, [state]);
}, [state, junctionHotspots]);
useEffect(() => {
const layers = layersRef.current;
if (!layers) return;
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest';
import { junctionDescriptors, hotspotAt } from './hotspots';
import type { WorkbenchState } from '../types/state';
const state = (overrides: Partial<WorkbenchState> = {}): WorkbenchState => ({
areaId: 'a',
compiled: {
model: {
roads: [],
endpoints: [
{ id: 'e2', roadId: 'r2', side: 'start', nodeId: 'n1', coordinate: [2, 2] },
{ id: 'e1', roadId: 'r1', side: 'end', nodeId: 'n1', coordinate: [0, 0] },
],
connections: [],
},
diagnostics: [],
},
overrides: { schema: 'x', overrides: [] },
trafficSignals: { provenance: 'x', assemblies: { type: 'FeatureCollection', features: [] } },
trafficRuntime: { signals: [] },
comparison: {},
layers: {},
...overrides,
});
describe('junction hotspots', () => {
it('derives stable editable node descriptor', () => {
const first = junctionDescriptors(state());
const second = junctionDescriptors(state());
expect(first).toEqual(second);
expect(first[0]).toMatchObject({ ref: { type: 'node', id: 'n1' }, status: 'editable', coordinate: [1, 1] });
});
it('marks configured clusters readonly and candidates as candidate', () => {
const value = state({
layers: {
nativeIntersectionSurface: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
],
},
properties: { cluster_id: 'c1' },
},
],
},
},
debug: {
junctionCandidates: [
{
index: 1,
id: 'd1',
nodeIds: ['n1', 'n2'],
nodeCount: 2,
diameterMeters: 10,
template: 'complex-junction-v1',
coreRadiusMeters: 8,
},
],
},
compiled: {
...state().compiled,
diagnostics: [
{
id: 'd1',
rule: 'complex-junction-candidate',
message: 'candidate',
geometry: { type: 'Point', coordinates: [3, 3] },
},
],
},
});
const descriptors = junctionDescriptors(value);
expect(hotspotAt(descriptors, { type: 'cluster', id: 'c1' })?.status).toBe('readonly');
expect(hotspotAt(descriptors, { type: 'cluster', id: 'd1' })?.status).toBe('candidate');
});
});
+112
View File
@@ -0,0 +1,112 @@
import type { Diagnostic, JunctionCandidate, Position, WorkbenchState } from '../types/state';
export type JunctionRef = { type: 'node' | 'cluster'; id: string };
export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate';
export interface JunctionDescriptor {
ref: JunctionRef;
status: JunctionHotspotStatus;
coordinate: Position;
radiusMeters: number;
nodeIds: string[];
approachRoadIds: string[];
diagnosticIds: string[];
source: 'junction-plan' | 'cluster-config' | 'candidate';
}
function average(points: Position[]): Position | null {
if (!points.length) return null;
return [
points.reduce((sum, point) => sum + point[0], 0) / points.length,
points.reduce((sum, point) => sum + point[1], 0) / points.length,
];
}
function candidateDescriptor(candidate: JunctionCandidate, diagnostics: Diagnostic): JunctionDescriptor | null {
const coordinate =
diagnostics.geometry?.type === 'Point' && Array.isArray(diagnostics.geometry.coordinates)
? (diagnostics.geometry.coordinates as Position)
: null;
if (!coordinate || coordinate.length < 2) return null;
return {
ref: { type: 'cluster', id: candidate.id },
status: 'candidate',
coordinate,
radiusMeters: Math.max(8, Number(candidate.coreRadiusMeters) || 12),
nodeIds: candidate.nodeIds.map(String).sort(),
approachRoadIds: [],
diagnosticIds: [diagnostics.id],
source: 'candidate',
};
}
/** Derive stable, read-only hotspots from the compiled state. */
export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[] {
const diagnostics = state.compiled.diagnostics || [];
const result: JunctionDescriptor[] = [];
const endpointsByNode = new Map<string, typeof state.compiled.model.endpoints>();
for (const endpoint of state.compiled.model.endpoints || []) {
const list = endpointsByNode.get(String(endpoint.nodeId)) || [];
list.push(endpoint);
endpointsByNode.set(String(endpoint.nodeId), list);
}
for (const [nodeId, endpoints] of endpointsByNode) {
if (endpoints.length < 2) continue;
const coordinate = average(endpoints.map((endpoint) => endpoint.coordinate));
if (!coordinate) continue;
const related = diagnostics.filter(
(item) =>
item.subjectId === nodeId || (item.endpointId && endpoints.some((endpoint) => endpoint.id === item.endpointId)),
);
result.push({
ref: { type: 'node', id: nodeId },
status: 'editable',
coordinate,
radiusMeters: 10,
nodeIds: [nodeId],
approachRoadIds: [...new Set(endpoints.map((endpoint) => endpoint.roadId))].sort(),
diagnosticIds: related.map((item) => item.id).sort(),
source: 'junction-plan',
});
}
const configured = new Map<string, { nodeIds: string[]; coordinate: Position; approachRoadIds: string[] }>();
for (const feature of state.layers.nativeIntersectionSurface?.features || []) {
const clusterId = feature.properties?.cluster_id;
if (typeof clusterId !== 'string' || !clusterId) continue;
const geometry = feature.geometry;
const coordinates =
geometry && geometry.type === 'Polygon' && Array.isArray(geometry.coordinates)
? (geometry.coordinates as Position[][])[0]
: [];
const center = average(coordinates || []);
if (!center) continue;
const current = configured.get(clusterId) || { nodeIds: [], coordinate: center, approachRoadIds: [] };
current.coordinate = center;
const nodeId = feature.properties?.node_id;
if (typeof nodeId === 'string') current.nodeIds.push(nodeId);
configured.set(clusterId, current);
}
for (const [clusterId, value] of configured) {
const nodeIds = [...new Set(value.nodeIds)].sort();
result.push({
ref: { type: 'cluster', id: clusterId },
status: 'readonly',
coordinate: value.coordinate,
radiusMeters: 16,
nodeIds,
approachRoadIds: value.approachRoadIds,
diagnosticIds: [],
source: 'cluster-config',
});
}
for (const candidate of state.debug?.junctionCandidates || []) {
const diagnostic = diagnostics.find((item) => item.id === candidate.id);
if (!diagnostic) continue;
const descriptor = candidateDescriptor(candidate, diagnostic);
if (descriptor) result.push(descriptor);
}
return result.sort((a, b) => `${a.ref.type}:${a.ref.id}`.localeCompare(`${b.ref.type}:${b.ref.id}`));
}
export function hotspotAt(descriptors: JunctionDescriptor[], ref: JunctionRef): JunctionDescriptor | null {
return descriptors.find((item) => item.ref.type === ref.type && item.ref.id === ref.id) || null;
}
+40 -1
View File
@@ -11,6 +11,7 @@ import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import { offsetCoordinate, type Coordinate } from '../edit/meters';
import type { Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from '../junction/hotspots';
const geojson = new GeoJSON();
const source = () => new VectorSource();
@@ -27,7 +28,8 @@ export type LayerName =
| 'signals'
| 'connectors'
| 'diagnostics'
| 'selectedRoad';
| 'selectedRoad'
| 'junctionHotspots';
export function createLayers(
onRoad: () => Road | null,
scene: () => boolean,
@@ -137,9 +139,46 @@ export function createLayers(
source: source(),
style: new Style({ stroke: new Stroke({ color: '#00a5cf', width: 8 }) }),
}),
junctionHotspots: new VectorLayer({
source: source(),
zIndex: 80,
style: (feature) => {
const status = feature.get('junction_status');
const color = status === 'editable' ? '#0e7490' : status === 'candidate' ? '#d49318' : '#64748b';
return new Style({
image: new CircleStyle({
radius: status === 'candidate' ? 9 : 8,
fill: new Fill({ color: `${color}33` }),
stroke: new Stroke({ color, width: 2 }),
}),
});
},
}),
};
return layers;
}
export function updateJunctionHotspots(
layers: ReturnType<typeof createLayers>,
descriptors: JunctionDescriptor[],
visible = true,
) {
const target = layers.junctionHotspots;
target.setVisible(visible);
const source = target.getSource()!;
source.clear();
source.addFeatures(
descriptors.map(
(descriptor) =>
new Feature({
geometry: new Point([descriptor.coordinate[0], descriptor.coordinate[1]]).transform('EPSG:4326', 'EPSG:3857'),
junction_ref: descriptor.ref,
junction_status: descriptor.status,
junction_descriptor: descriptor,
}),
),
);
}
function features(value: unknown) {
return geojson.readFeatures((value || { type: 'FeatureCollection', features: [] }) as object, {
dataProjection: 'EPSG:4326',