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

@@ -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 {