feat: add complex junction selection markers

This commit is contained in:
que01 committed 2026-09-04 17:09:32 +08:00
1 parent 57248f1aa4
commit 38ea779d9b
18 files changed
+685 -48

No files matched your search

+41 -11
View File
@@ -54,7 +54,7 @@ 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';
import { junctionDescriptors, hotspotAt } from './junction/hotspots';
import { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots';
import { JunctionWorkspace } from './junction/JunctionWorkspace';
import { localJunctionPreview, localJunctionState } from './junction/local-state';
import {
@@ -211,6 +211,9 @@ function App() {
: preview,
[junctionDescriptor, junctionRoute, preview, state],
);
const [junctionNodeMarkers, setJunctionNodeMarkers] = useState<
Array<{ coordinate: Coordinate; label: string; selected: boolean }>
>([]);
// A deep link starts without a map click, so it has no selected approach from
// which the existing manifest loader can scope its request. Pick the first
// descriptor-owned approach here as well as in the click path; this is a
@@ -891,6 +894,7 @@ function App() {
discardJunctionDraft();
} else return;
}
setJunctionNodeMarkers([]);
window.history.pushState({}, '', '/');
setJunctionRoute(null);
};
@@ -991,6 +995,7 @@ function App() {
);
})}
<hr />
<hr />
<details className="issues-details">
<summary>待检查问题({diagnostics.length})</summary>
<div className="issue-tabs" role="tablist" aria-label="问题筛选">
@@ -1036,6 +1041,7 @@ function App() {
visible={layers}
scene={scene}
junctionHotspots={junctionHotspots}
junctionNodeMarkers={junctionNodeMarkers}
onJunctionHotspot={(ref: JunctionRef, _coordinate, descriptor) => {
openJunction(ref);
const approachRoad = descriptor.approachRoadIds
@@ -1128,16 +1134,6 @@ function App() {
session={session}
onLaneManeuverChange={applyLaneManeuver}
updateSignal={updateSignal}
onAcceptCandidate={(index) =>
void api
.acceptJunctionCandidate(index)
.then((next) => {
setState(next);
signalSavedRef.current = next.trafficSignals.assemblies.features;
setStatus(`已加入 ${next.added.id} 并重新编译`);
})
.catch((error: Error) => setStatus(error.message))
}
>
{editMode ? (
<ParameterPanel
@@ -1162,6 +1158,40 @@ function App() {
diagnostics={junctionDiagnostics}
facilitySummary={junctionFacilitySummary}
onClose={closeJunction}
onEnableComplex={
candidateForJunction(state, junctionDescriptor)
? (selectedNodeIds) => {
const candidate = candidateForJunction(state, junctionDescriptor);
if (!candidate) {
setStatus('候选已过期,请刷新后重试。');
return;
}
void api
.acceptJunctionCandidate(candidate.id, selectedNodeIds)
.then((next) => {
setState(next);
signalSavedRef.current = next.trafficSignals.assemblies.features;
const ref = { type: 'cluster' as const, id: next.added.id };
window.history.replaceState({}, '', `/junction/cluster/${encodeURIComponent(ref.id)}`);
setJunctionRoute(ref);
setStatus('已启用复杂路口渲染');
})
.catch((error: Error) => setStatus(`启用失败:${error.message}`));
}
: undefined
}
onUpdateComplexNodes={(nodeIds) => {
if (junctionDescriptor.ref.type !== 'cluster') return;
void api
.updateJunctionCluster(junctionDescriptor.ref.id, nodeIds)
.then((next) => {
setState(next);
signalSavedRef.current = next.trafficSignals.assemblies.features;
setStatus('已更新复杂路口参与节点并重新编译');
})
.catch((error: Error) => setStatus(`更新失败:${error.message}`));
}}
onCandidateMarkersChange={setJunctionNodeMarkers}
onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))}
onDiscard={discardJunctionDraft}
onSave={() =>
@@ -13,6 +13,7 @@ import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';
import { createEmpty, extend } from 'ol/extent';
import { click } from 'ol/events/condition';
import type { GeoJson, Road, WorkbenchState } from '../types/state';
@@ -76,6 +77,7 @@ interface Props {
focusJunctionId?: string | null;
junctionHotspots?: boolean;
onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void;
junctionNodeMarkers?: Array<{ coordinate: Coordinate; label: string; selected: boolean }>;
}
export function MapCanvas({
state,
@@ -111,6 +113,7 @@ export function MapCanvas({
focusJunctionId = null,
junctionHotspots = true,
onJunctionHotspot,
junctionNodeMarkers = [],
}: Props) {
const target = useRef<HTMLDivElement>(null);
const mapRef = useRef<Map | null>(null);
@@ -124,6 +127,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 junctionNodeMarkerSourceRef = useRef<VectorSource | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
@@ -223,6 +227,28 @@ export function MapCanvas({
});
signalTransformSourceRef.current = signalTransformSource;
signalTransformLayerRef.current = signalTransformLayer;
const junctionNodeMarkerSource = new VectorSource();
const junctionNodeMarkerLayer = new VectorLayer({
source: junctionNodeMarkerSource,
zIndex: 110,
style: (feature) => {
const selected = feature.get('junction_node_selected') === true;
const color = selected ? '#0e7490' : '#64748b';
return new Style({
image: new CircleStyle({
radius: 12,
fill: new Fill({ color }),
stroke: new Stroke({ color: '#fff', width: 2 }),
}),
text: new Text({
text: String(feature.get('junction_node_label') || ''),
fill: new Fill({ color: '#fff' }),
font: '700 12px sans-serif',
}),
});
},
});
junctionNodeMarkerSourceRef.current = junctionNodeMarkerSource;
// Direct-edit sources are always installed; visibility and hit testing follow
// the in-page browser/edit switch.
const handleLayer = new EditHandleLayer();
@@ -241,6 +267,7 @@ export function MapCanvas({
...(previewLayer ? previewLayer.all() : []),
laneSelectionLayer,
signalTransformLayer,
junctionNodeMarkerLayer,
...(handleLayer ? [handleLayer.layer] : []),
...(ghost ? [ghost.layer] : []),
],
@@ -418,12 +445,41 @@ export function MapCanvas({
select.on('select', listener);
return () => {
select.un('select', listener);
junctionNodeMarkerSourceRef.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 source = junctionNodeMarkerSourceRef.current;
if (!source) return;
source.clear();
source.addFeatures(
junctionNodeMarkers.map((marker) => {
const feature = new Feature({ geometry: new Point(fromLonLat(marker.coordinate)) });
feature.set('junction_node_label', marker.label);
feature.set('junction_node_selected', marker.selected);
return feature;
}),
);
const map = mapRef.current;
if (map && junctionNodeMarkers.length) {
const extent = createEmpty();
junctionNodeMarkers.forEach((marker) => {
const point = fromLonLat(marker.coordinate);
extend(extent, [point[0], point[1], point[0], point[1]]);
});
if (Number.isFinite(extent[0])) {
map.getView().fit(extent, {
padding: [96, 520, 96, 96],
maxZoom: 20,
duration: 180,
});
}
}
}, [junctionNodeMarkers]);
useEffect(() => {
const layers = layersRef.current;
const map = mapRef.current;
@@ -1,5 +1,5 @@
import { useEffect, useState, type ReactNode } from 'react';
import { Candidates, LaneManeuverEditor, MarkingEditor, SignalEditor } from './ElementEditors';
import { LaneManeuverEditor, MarkingEditor, SignalEditor } from './ElementEditors';
import { InspectorSection } from './InspectorSection';
import type { EditSession } from '../edit/session';
import type { ElementSelection } from '../edit/element';
@@ -19,7 +19,6 @@ export function WorkbenchInspector({
session,
onLaneManeuverChange,
updateSignal,
onAcceptCandidate,
children,
}: {
road: Road | null;
@@ -32,7 +31,6 @@ export function WorkbenchInspector({
session: EditSession | null;
onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void;
updateSignal: (features: GeoFeature[]) => Promise<void>;
onAcceptCandidate: (index: number) => void;
children?: ReactNode;
}) {
const [width, setWidth] = useState(0);
@@ -258,7 +256,6 @@ export function WorkbenchInspector({
})}
</InspectorSection>
<InspectorSection title="高级" summary="候选与来源" open={open === 'advanced'} onToggle={section('advanced')}>
<Candidates state={state} onAccept={onAcceptCandidate} />
<details>
<summary>技术详情与来源</summary>
<pre>
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import type { JunctionDescriptor } from './hotspots';
import { useEffect, useMemo, useState } from 'react';
import { candidateForJunction, type JunctionDescriptor } from './hotspots';
import { canEditJunction, type JunctionSession } from './workspace';
import { Button } from '../ui/button';
import { ParameterPanel } from '../components/ParameterPanel';
@@ -25,6 +25,9 @@ interface Props {
onSave: () => void;
editMode?: boolean;
onEnableEdit?: () => void;
onEnableComplex?: (nodeIds: string[]) => void;
onUpdateComplexNodes?: (nodeIds: string[]) => void;
onCandidateMarkersChange?: (markers: Array<{ coordinate: Coordinate; label: string; selected: boolean }>) => void;
handles?: EditHandle[];
onDraft?: (handle: EditHandle, value: number) => void;
onDraftGroup?: (handles: EditHandle[], value: number) => void;
@@ -52,6 +55,9 @@ export function JunctionWorkspace({
onSave,
editMode = false,
onEnableEdit,
onEnableComplex,
onUpdateComplexNodes,
onCandidateMarkersChange,
diagnostics = [],
facilitySummary = { crosswalks: 0, stopLines: 0, signals: 0 },
state,
@@ -72,6 +78,90 @@ export function JunctionWorkspace({
onUpdateSignal,
}: Props) {
const editable = useMemo(() => canEditJunction(descriptor), [descriptor]);
const complexEnabled = useMemo(() => {
const nodes = new Set(descriptor.nodeIds.map(String));
return Boolean(
state?.debug?.junctionClusters?.some(
(cluster) =>
(descriptor.ref.type === 'cluster' && cluster.id === descriptor.ref.id) ||
(cluster.nodeIds.length === nodes.size && cluster.nodeIds.every((nodeId) => nodes.has(String(nodeId)))),
),
);
}, [descriptor, state?.debug?.junctionClusters]);
const candidate = useMemo(() => {
return candidateForJunction(state, descriptor);
}, [descriptor, state]);
const configuredNodeIds = useMemo(
() =>
state?.debug?.junctionClusters?.find((cluster) => cluster.id === descriptor.ref.id)?.nodeIds.map(String) || [],
[descriptor.ref.id, state?.debug?.junctionClusters],
);
const [selectedCandidateNodes, setSelectedCandidateNodes] = useState<string[]>([]);
const [candidateNodePickerOpen, setCandidateNodePickerOpen] = useState(false);
const candidateNodes = useMemo(
() =>
(candidate?.nodeIds?.length
? candidate.nodeIds
: descriptor.nodeIds.length
? descriptor.nodeIds
: configuredNodeIds
).map(String),
[candidate?.nodeIds, configuredNodeIds, descriptor.nodeIds],
);
const activeCandidateNodes = selectedCandidateNodes.filter((nodeId) => candidateNodes.includes(nodeId)).length
? selectedCandidateNodes.filter((nodeId) => candidateNodes.includes(nodeId))
: candidateNodes;
const candidateRoadNames = useMemo(() => {
if (!state) return [];
const nodeIds = new Set((candidate?.nodeIds || descriptor.nodeIds).map(String));
return [
...new Set(
state.compiled.model.roads
.filter((road) => road.sourceNodeIds.some((nodeId) => nodeIds.has(String(nodeId))))
.map((road) => junctionRoadName(road, state.compiled.model.roads)),
),
];
}, [candidate, descriptor.nodeIds, state]);
const candidateNodeLabels = useMemo(() => {
if (!state) return [];
return candidateNodes.map((nodeId, index) => {
const names = [
...new Set(
state.compiled.model.roads
.filter((road) => road.sourceNodeIds.some((item) => String(item) === nodeId))
.map((road) => junctionRoadName(road, state.compiled.model.roads)),
),
];
return { nodeId, label: `路口点 ${index + 1}${names.length ? ` · ${names.join('、')}` : ''}` };
});
}, [candidate, candidateNodes, state]);
useEffect(() => {
if (!onCandidateMarkersChange || !state || !candidateNodePickerOpen) {
onCandidateMarkersChange?.([]);
return;
}
const selectedIds = new Set(activeCandidateNodes);
onCandidateMarkersChange(
candidateNodes.flatMap((nodeId, index) => {
const points = state.compiled.model.endpoints
.filter((endpoint) => String(endpoint.nodeId) === nodeId)
.map((endpoint) => endpoint.coordinate);
return points.length
? [
{
coordinate: [
points.reduce((sum, point) => sum + point[0], 0) / points.length,
points.reduce((sum, point) => sum + point[1], 0) / points.length,
] as Coordinate,
label: String(index + 1),
selected: selectedIds.has(nodeId),
},
]
: [];
}),
);
return () => onCandidateMarkersChange([]);
}, [activeCandidateNodes, candidateNodePickerOpen, candidateNodes, onCandidateMarkersChange, state]);
const facilities = useMemo(
() => (state ? junctionFacilities(state, descriptor.nodeIds, roads) : []),
[descriptor.nodeIds, roads, state],
@@ -84,11 +174,15 @@ export function JunctionWorkspace({
<span className="junction-workspace__eyebrow">JunctionTools</span>
</div>
<p>
{editable
? editMode
? '可编辑路口几何参数'
: '当前为浏览模式,开启编辑后可调整路口几何参数'
: '只读上下文:当前路口类型暂不支持编辑'}
{complexEnabled
? '当前按复杂路口渲染'
: descriptor.status === 'candidate'
? '当前按普通路口渲染,可切换为复杂路口'
: editable
? editMode
? '可编辑路口几何参数'
: '当前为浏览模式,开启编辑后可调整路口几何参数'
: '只读上下文:当前路口类型暂不支持编辑'}
</p>
</div>
<div className="junction-workspace__header-actions">
@@ -111,6 +205,74 @@ export function JunctionWorkspace({
</dd>
</dl>
<section className="junction-workspace__validation" aria-label="路口验证">
{candidate || complexEnabled ? (
<div className="junction-workspace__candidate" aria-label="复杂路口候选信息">
<strong>{complexEnabled ? '当前复杂路口组成' : '附近可合并节点'}</strong>
{candidate ? (
<span>
已根据当前路口附近路网动态检测到 {candidate.nodeCount} 个相邻节点,范围约 {candidate.diameterMeters}{' '}
米。
{candidateRoadNames.length ? ` 关联道路:${candidateRoadNames.join('、')}。` : ''} 建议核心半径{' '}
{candidate.coreRadiusMeters} 米。
</span>
) : (
<span>当前复杂路口包含 {candidateNodes.length} 个路口点。</span>
)}
{candidateNodes.length > 2 ? (
<>
<Button
type="button"
className="junction-workspace__candidate-toggle"
aria-expanded={candidateNodePickerOpen}
onClick={() => setCandidateNodePickerOpen((open) => !open)}
>
{candidateNodePickerOpen ? '收起路口点选择' : '调整参与路口点'}
</Button>
{candidateNodePickerOpen ? (
<fieldset className="junction-workspace__candidate-nodes">
<legend>参与合并的路口点</legend>
{candidateNodeLabels.map(({ nodeId, label }, index) => (
<label
key={nodeId}
className={activeCandidateNodes.includes(nodeId) ? 'is-included' : 'is-excluded'}
>
<input
type="checkbox"
checked={activeCandidateNodes.includes(nodeId)}
disabled={activeCandidateNodes.length <= 2 && activeCandidateNodes.includes(nodeId)}
onChange={(event) => {
const next = event.target.checked
? [...new Set([...activeCandidateNodes, nodeId])]
: activeCandidateNodes.filter((item) => item !== nodeId);
setSelectedCandidateNodes(next);
}}
/>
<span className="junction-workspace__candidate-node-badge" aria-hidden="true">
{index + 1}
</span>
<span className="junction-workspace__candidate-node-label">{label}</span>
</label>
))}
</fieldset>
) : null}
</>
) : null}
{!complexEnabled && onEnableComplex ? (
<Button
type="button"
disabled={activeCandidateNodes.length < 2}
onClick={() => onEnableComplex(activeCandidateNodes)}
>
启用复杂路口渲染
</Button>
) : null}
{complexEnabled && onUpdateComplexNodes ? (
<Button type="button" onClick={() => onUpdateComplexNodes(activeCandidateNodes)}>
应用路口点调整
</Button>
) : null}
</div>
) : null}
<h3>设施与验证</h3>
<p>
斑马线 {facilitySummary.crosswalks} · 停止线 {facilitySummary.stopLines} · 信号灯 {facilitySummary.signals}
@@ -224,6 +386,8 @@ export function JunctionWorkspace({
<p className="junction-workspace__browse-hint">
开启编辑模式后,这里会显示进口宽度、进口收口距离和角部圆角控件。
</p>
) : complexEnabled ? (
<p className="junction-workspace__browse-hint">复杂路口几何已启用;首版仅支持查看,不支持参数拖拽编辑。</p>
) : null}
</div>
</section>
+96 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { junctionDescriptors, hotspotAt } from './hotspots';
import { candidateForJunction, junctionDescriptors, hotspotAt } from './hotspots';
import type { WorkbenchState } from '../types/state';
const state = (overrides: Partial<WorkbenchState> = {}): WorkbenchState => ({
@@ -24,6 +24,64 @@ const state = (overrides: Partial<WorkbenchState> = {}): WorkbenchState => ({
});
describe('junction hotspots', () => {
it('matches a node only to a candidate that contains that node', () => {
const value = state({
debug: {
junctionCandidates: [
{
index: 1,
id: 'first',
nodeIds: ['n2', 'n3'],
nodeCount: 2,
diameterMeters: 8,
template: 'complex-junction-v1',
coreRadiusMeters: 12,
},
{
index: 2,
id: 'second',
nodeIds: ['n1', 'n4'],
nodeCount: 2,
diameterMeters: 9,
template: 'complex-junction-v1',
coreRadiusMeters: 13,
},
],
},
});
expect(candidateForJunction(value, { ref: { type: 'node', id: 'n1' }, nodeIds: ['n1'] })?.id).toBe('second');
});
it('matches a cluster only when the complete node set is equal', () => {
const value = state({
debug: {
junctionCandidates: [
{
index: 1,
id: 'wide',
nodeIds: ['n1', 'n2', 'n3'],
nodeCount: 3,
diameterMeters: 8,
template: 'complex-junction-v1',
coreRadiusMeters: 12,
},
{
index: 2,
id: 'exact',
nodeIds: ['n1', 'n2'],
nodeCount: 2,
diameterMeters: 9,
template: 'complex-junction-v1',
coreRadiusMeters: 13,
},
],
},
});
expect(candidateForJunction(value, { ref: { type: 'cluster', id: 'cluster' }, nodeIds: ['n2', 'n1'] })?.id).toBe(
'exact',
);
});
it('derives stable editable node descriptor', () => {
const first = junctionDescriptors(state());
const second = junctionDescriptors(state());
@@ -83,4 +141,41 @@ describe('junction hotspots', () => {
expect(hotspotAt(descriptors, { type: 'cluster', id: 'c1' })?.status).toBe('readonly');
expect(hotspotAt(descriptors, { type: 'cluster', id: 'd1' })?.status).toBe('candidate');
});
it('promotes a candidate to the configured cluster descriptor after enabling it', () => {
const value = state({
debug: {
junctionCandidates: [
{
index: 1,
id: 'diagnostic-1',
nodeIds: ['n1', 'n2'],
nodeCount: 2,
diameterMeters: 10,
template: 'complex-junction-v1',
coreRadiusMeters: 8,
},
],
junctionClusters: [{ id: 'cluster-n1', template: 'complex-junction-v1', nodeIds: ['n1', 'n2'] }],
},
compiled: {
...state().compiled,
diagnostics: [
{
id: 'diagnostic-1',
rule: 'complex-junction-candidate',
message: 'candidate',
geometry: { type: 'Point', coordinates: [3, 3] },
},
],
},
});
const descriptors = junctionDescriptors(value);
expect(descriptors.filter((item) => item.ref.type === 'cluster')).toHaveLength(1);
expect(hotspotAt(descriptors, { type: 'cluster', id: 'cluster-n1' })).toMatchObject({
status: 'readonly',
source: 'cluster-config',
});
expect(hotspotAt(descriptors, { type: 'cluster', id: 'diagnostic-1' })).toBeNull();
});
});
+69 -9
View File
@@ -1,4 +1,4 @@
import type { Diagnostic, JunctionCandidate, Position, WorkbenchState } from '../types/state';
import type { Diagnostic, JunctionCandidate, Position, WorkbenchState, JunctionClusterConfig } from '../types/state';
export type JunctionRef = { type: 'node' | 'cluster'; id: string };
export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate';
@@ -13,6 +13,28 @@ export interface JunctionDescriptor {
source: 'junction-plan' | 'cluster-config' | 'candidate';
}
/** Resolve the candidate belonging to the currently opened JunctionTools target. */
export function candidateForJunction(
state: WorkbenchState | undefined,
descriptor: Pick<JunctionDescriptor, 'ref' | 'nodeIds'>,
): JunctionCandidate | null {
const candidates = state?.debug?.junctionCandidates || [];
if (descriptor.ref.type === 'cluster') {
const wanted = new Set(descriptor.nodeIds.map(String));
return (
candidates.find(
(candidate) =>
candidate.nodeIds.length === wanted.size && candidate.nodeIds.every((nodeId) => wanted.has(String(nodeId))),
) || null
);
}
const nodeId = String(descriptor.ref.id);
return (
candidates.find((candidate) => candidate.nodeIds.some((candidateNodeId) => String(candidateNodeId) === nodeId)) ||
null
);
}
function average(points: Position[]): Position | null {
if (!points.length) return null;
return [
@@ -21,21 +43,25 @@ function average(points: Position[]): Position | null {
];
}
function candidateDescriptor(candidate: JunctionCandidate, diagnostics: Diagnostic): JunctionDescriptor | null {
function candidateDescriptor(
candidate: JunctionCandidate,
diagnostics: Diagnostic,
configured?: JunctionClusterConfig,
): 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',
ref: { type: 'cluster', id: configured?.id || candidate.id },
status: configured ? 'readonly' : 'candidate',
coordinate,
radiusMeters: Math.max(8, Number(candidate.coreRadiusMeters) || 12),
nodeIds: candidate.nodeIds.map(String).sort(),
approachRoadIds: [],
diagnosticIds: [diagnostics.id],
source: 'candidate',
diagnosticIds: configured ? [] : [diagnostics.id],
source: configured ? 'cluster-config' : 'candidate',
};
}
@@ -85,8 +111,10 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[]
if (typeof nodeId === 'string') current.nodeIds.push(nodeId);
configured.set(clusterId, current);
}
const configuredClusters = new Map((state.debug?.junctionClusters || []).map((cluster) => [cluster.id, cluster]));
for (const [clusterId, value] of configured) {
const nodeIds = [...new Set(value.nodeIds)].sort();
const configuredCluster = configuredClusters.get(clusterId);
const nodeIds = [...new Set(configuredCluster?.nodeIds || value.nodeIds)].sort();
result.push({
ref: { type: 'cluster', id: clusterId },
status: 'readonly',
@@ -98,13 +126,45 @@ export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[]
source: 'cluster-config',
});
}
for (const cluster of state.debug?.junctionClusters || []) {
if (configured.has(cluster.id)) continue;
const nodeIds = cluster.nodeIds.map(String).sort();
const points = nodeIds.flatMap((nodeId) =>
(state.compiled.model.endpoints || [])
.filter((endpoint) => String(endpoint.nodeId) === nodeId)
.map((endpoint) => endpoint.coordinate),
);
const coordinate = average(points);
if (!coordinate) continue;
result.push({
ref: { type: 'cluster', id: cluster.id },
status: 'readonly',
coordinate,
radiusMeters: Math.max(8, Number(cluster.coreRadiusMeters) || 12),
nodeIds,
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);
const configured = (state.debug?.junctionClusters || []).find(
(cluster) =>
cluster.nodeIds.length === candidate.nodeIds.length &&
cluster.nodeIds.every((nodeId) => candidate.nodeIds.map(String).includes(String(nodeId))),
);
const descriptor = candidateDescriptor(candidate, diagnostic, configured);
if (descriptor) result.push(descriptor);
}
return result.sort((a, b) => `${a.ref.type}:${a.ref.id}`.localeCompare(`${b.ref.type}:${b.ref.id}`));
const unique = new Map<string, JunctionDescriptor>();
for (const descriptor of result) {
const key = `${descriptor.ref.type}:${descriptor.ref.id}`;
const current = unique.get(key);
if (!current || (current.status === 'candidate' && descriptor.status !== 'candidate')) unique.set(key, descriptor);
}
return [...unique.values()].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 {
+7 -2
View File
@@ -69,8 +69,13 @@ export const api = {
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals/generate', {
method: 'POST',
}),
acceptJunctionCandidate: (index: number) =>
request<WorkbenchState & { added: { id: string } }>('/api/junction-clusters', json({ index })),
acceptJunctionCandidate: (candidateId: string, nodeIds?: string[]) =>
request<WorkbenchState & { added: { id: string } }>(
'/api/junction-clusters',
json({ candidateId, ...(nodeIds ? { nodeIds } : {}) }),
),
updateJunctionCluster: (clusterId: string, nodeIds: string[]) =>
request<WorkbenchState & { added: { id: string } }>('/api/junction-clusters', json({ clusterId, nodeIds })),
// Direct-edit endpoints used by the in-page browser/edit switch.
editState: (selection?: EditSelection) => {
+70
View File
@@ -771,6 +771,76 @@ pre {
background: #f8fafc;
color: #475569;
}
.junction-workspace__candidate {
display: grid;
gap: 0.25rem;
margin-bottom: 1rem;
padding: 0.65rem 0.75rem;
border-left: 3px solid #d49318;
background: #fffaf0;
color: #5d4a21;
}
.junction-workspace__candidate span {
color: #63736c;
font-size: 12px;
}
.junction-workspace__candidate-toggle {
justify-self: start;
margin-top: 0.25rem;
}
.junction-workspace__candidate-nodes {
display: grid;
gap: 0.35rem;
margin: 0.35rem 0 0;
padding: 0.55rem 0.65rem;
border: 1px solid #ead9ac;
background: #fffdf7;
}
.junction-workspace__candidate-nodes legend {
padding: 0 0.25rem;
color: #5d4a21;
font-size: 12px;
}
.junction-workspace__candidate-nodes label {
display: flex;
gap: 0.45rem;
align-items: center;
color: #475569;
font-size: 12px;
}
.junction-workspace__candidate-node-badge {
display: inline-grid;
flex: 0 0 1.5rem;
width: 1.5rem;
height: 1.5rem;
place-items: center;
border: 2px solid currentColor;
border-radius: 50%;
font-size: 11px;
font-weight: 800;
line-height: 1;
}
.junction-workspace__candidate-nodes label.is-included {
color: #0e7490;
}
.junction-workspace__candidate-nodes label.is-included .junction-workspace__candidate-node-badge {
color: #fff;
background: #0e7490;
}
.junction-workspace__candidate-nodes label.is-included input {
accent-color: #0e7490;
}
.junction-workspace__candidate-nodes label.is-excluded input {
accent-color: #94a3b8;
}
.junction-workspace__candidate-nodes label.is-excluded .junction-workspace__candidate-node-badge {
color: #94a3b8;
background: transparent;
}
.junction-workspace__candidate-nodes label.is-excluded {
color: #94a3b8;
text-decoration: line-through;
}
@media (max-width: 900px) {
.junction-workspace {
top: auto;
+7 -1
View File
@@ -64,6 +64,12 @@ export interface JunctionCandidate {
template: string;
coreRadiusMeters: number;
}
export interface JunctionClusterConfig {
id: string;
template: string;
nodeIds: string[];
coreRadiusMeters?: number;
}
export interface Diagnostic {
id: string;
message: string;
@@ -88,5 +94,5 @@ export interface WorkbenchState {
comparison: Record<string, unknown>;
layers: Record<string, GeoJson | null>;
junctionReference?: { converted: GeoJson };
debug?: { junctionCandidates: JunctionCandidate[] } | null;
debug?: { junctionCandidates: JunctionCandidate[]; junctionClusters?: JunctionClusterConfig[] } | null;
}