Files
road-compiler/workbench/client/src/junction/JunctionWorkspace.tsx
T

560 lines
23 KiB
TypeScript

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';
import type { EditHandle } from '../edit/types';
import type { ElementSelection } from '../edit/element';
import type { Road } from '../types/state';
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 {
descriptor: JunctionDescriptor;
session: JunctionSession;
dirty?: boolean;
diagnostics?: Array<{ id: string; message: string; rule: string; severity?: string }>;
selectedObjectKey?: string | null;
onSelectObject?: (key: string) => void;
facilitySummary?: { crosswalks: number; stopLines: number; signals: number };
state?: WorkbenchState;
onClose: () => void;
onApply: () => void;
onDiscard: () => void;
onSave: () => void;
onUndo?: () => void;
onRedo?: () => void;
canUndo?: boolean;
canRedo?: boolean;
status?: string;
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;
onSettle?: (handle: EditHandle, value: number) => void;
onSettleGroup?: (handles: EditHandle[], value: number) => void;
onAbandon?: () => void;
onReset?: (handle: EditHandle) => void;
previewPending?: boolean;
roads?: Road[];
junctionCoordinate?: Coordinate;
selectedFacility?: ElementSelection | null;
onSelectFacility?: (facility: {
id: string;
kind: 'crosswalk' | 'stop-line' | 'signal' | 'island';
crossingKey?: string;
}) => void;
signalUids?: readonly string[];
selectedSignalUid?: string | null;
onSignalStatus?: (message: string) => void;
onUpdateSignal?: (features: import('../types/state').GeoFeature[]) => Promise<void>;
}
export function JunctionWorkspace({
descriptor,
session,
dirty = session.dirty,
onClose,
onApply,
onDiscard,
onSave,
onUndo,
onRedo,
canUndo = false,
canRedo = false,
status,
editMode = false,
onEnableEdit,
onEnableComplex,
onUpdateComplexNodes,
onCandidateMarkersChange,
diagnostics = [],
selectedObjectKey = null,
onSelectObject,
facilitySummary = { crosswalks: 0, stopLines: 0, signals: 0 },
state,
handles = [],
onDraft,
onDraftGroup,
onSettle,
onSettleGroup,
onAbandon,
onReset,
previewPending = false,
roads = [],
junctionCoordinate = descriptor.coordinate,
selectedFacility,
onSelectFacility,
signalUids = [],
selectedSignalUid,
onSignalStatus,
onUpdateSignal,
}: Props) {
const editable = useMemo(
() =>
canEditJunction(
descriptor,
handles.some((handle) => handle.editable),
),
[descriptor, handles],
);
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 shapeSummary = useMemo(
() => state?.debug?.junctionShapes?.find((shape) => shape.clusterId === descriptor.ref.id),
[descriptor.ref.id, state?.debug?.junctionShapes],
);
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 [facilitiesOpen, setFacilitiesOpen] = 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],
);
const structure = structureForJunction(state, descriptor.ref);
const standardDiagnostics = state?.standardsDiagnostics || [];
return (
<section className="junction-workspace" aria-label="路口编辑工作区">
<header className="junction-workspace__header">
<div>
<div className="junction-workspace__title-line">
<span className="junction-workspace__eyebrow">JunctionTools</span>
</div>
<p>
{complexEnabled
? editable
? editMode
? '可编辑车行道与路口几何参数'
: '当前按复杂路口渲染,开启编辑后可调整几何参数'
: '当前按复杂路口渲染'
: descriptor.status === 'candidate'
? '当前按普通路口渲染,可切换为复杂路口'
: editable
? editMode
? '可编辑路口几何参数'
: '当前为浏览模式,开启编辑后可调整路口几何参数'
: '只读上下文:当前路口类型暂不支持编辑'}
</p>
</div>
<div className="junction-workspace__header-actions">
{editable && !editMode ? <Button onClick={onEnableEdit}>开启编辑模式</Button> : null}
<Button onClick={onClose}>返回主地图</Button>
</div>
</header>
<div className="junction-workspace__body">
<dl>
{shapeSummary ? (
<>
<dt>路口形态</dt>
<dd>
{shapeSummary.label} · {shapeSummary.armCount} 条有效道路臂
</dd>
</>
) : null}
<dt>组成节点</dt>
<dd>{descriptor.nodeIds.length ? `${descriptor.nodeIds.length} 个路口节点` : '—'}</dd>
<dt>进口道路</dt>
<dd>{roads.length ? roads.map((road) => junctionRoadName(road, roads)).join('、') : '—'}</dd>
<dt>诊断</dt>
<dd>{descriptor.diagnosticIds.length ? `${descriptor.diagnosticIds.length} 条` : '无'}</dd>
<dt>状态</dt>
<dd>
{session.status}
{dirty ? '(有未应用草稿)' : ''}
</dd>
</dl>
<section className="junction-workspace__validation" aria-label="路口验证">
{structure ? (
<section className="junction-workspace__standards" aria-label="结构与标准">
<h3>结构与标准</h3>
<p>
{state?.standardsProfile?.label || '项目默认标准'} · {structure.shape.label} ·{' '}
{structure.shape.effectiveArmCount} 条有效道路臂
</p>
{state?.junctionReference ? (
<p className="junction-workspace__reference-summary">
参考层:{state.junctionReference.coordinateSystem || 'GCJ-02'} → WGS84 ·{' '}
{state.junctionReference.source || '已加载参考文件'}
</p>
) : null}
{structure.capability?.reason ? <p>{junctionCapabilityReason(structure.capability.reason)}</p> : null}
<dl>
<dt>道路臂</dt>
<dd>
{structure.arms.length ? (
<span className="junction-workspace__object-list">
{structure.arms.map((arm) => (
<button
type="button"
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>
))}
</span>
) : (
'无'
)}
</dd>
<dt>角部</dt>
<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 ? (
<details
className="junction-workspace__structure-facilities"
open={facilitiesOpen}
onToggle={(event) => setFacilitiesOpen(event.currentTarget.open)}
>
<summary>已识别 {structure.facilities.length} 项设施</summary>
<ul>
{structure.facilities.map((facility) => (
<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>
) : (
'无'
)}
</dd>
</dl>
{standardDiagnostics.length ? (
<ul aria-label="标准诊断">
{standardDiagnostics.map((item) => (
<li key={item.id} className={`junction-workspace__standard-diagnostic is-${item.severity}`}>
<button type="button" onClick={() => onSelectObject?.(item.objectKey)}>
<strong>
{item.severity === 'pass' ? '通过' : item.severity === 'warning' ? '警告' : '阻塞'}
</strong>{' '}
{item.message}
</button>
</li>
))}
</ul>
) : null}
</section>
) : null}
{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}
</p>
{facilities.length ? (
<ul className="junction-workspace__facilities" aria-label="已有设施">
{facilities.map((facility) => (
<li key={facility.id}>
<button
type="button"
className={
(facility.kind === 'signal' && selectedSignalUid === facility.id.slice('signal:'.length)) ||
(selectedFacility &&
selectedFacility.kind === facility.kind &&
String(selectedFacility.crossingNodeId) ===
(facility.crossingKey ?? facility.id.split(':').slice(1).join(':')))
? 'is-selected'
: undefined
}
aria-current={
(facility.kind === 'signal' && selectedSignalUid === facility.id.slice('signal:'.length)) ||
(selectedFacility &&
selectedFacility.kind === facility.kind &&
String(selectedFacility.crossingNodeId) ===
(facility.crossingKey ?? facility.id.split(':').slice(1).join(':')))
? 'true'
: undefined
}
onClick={() => onSelectFacility?.(facility)}
disabled={facility.kind === 'island'}
>
{facility.label}
</button>
</li>
))}
</ul>
) : null}
{selectedFacility && selectedFacility.kind !== 'lane-maneuver' ? (
<p className="junction-workspace__facility-selection">
当前选中:{selectedFacility.kind === 'crosswalk' ? '斑马线' : '停止线'}。可在下方参数中调整位置。
</p>
) : null}
{selectedSignalUid ? (
<p className="junction-workspace__facility-selection">当前选中:信号灯。可在下方参数中调整。</p>
) : null}
{diagnostics.length ? (
<ul>
{diagnostics.map((item) => (
<li key={item.id} className={item.severity === 'error' ? 'blocking' : ''}>
<strong>{item.severity === 'error' ? '阻塞' : '提示'}</strong> {item.message}
</li>
))}
</ul>
) : (
<p>当前路口没有诊断问题。</p>
)}
</section>
{editable && editMode ? (
<>
<ParameterPanel
handles={handles}
hasSelection
grouped
previewPending={previewPending}
onDraft={onDraft ?? (() => undefined)}
onDraftGroup={onDraftGroup}
onSettle={onSettle ?? (() => undefined)}
onSettleGroup={onSettleGroup}
onAbandon={onAbandon ?? (() => undefined)}
onReset={onReset ?? (() => undefined)}
labelForHandle={(handle) => junctionLabelForHandle(handle, roads, junctionCoordinate)}
highlightedHandleId={
selectedFacility && selectedFacility.kind !== 'lane-maneuver'
? handles.find(
(handle) =>
(handle.anchor.type === 'junction-crossing' &&
String(handle.anchor.crossingId) === String(selectedFacility.crossingNodeId) &&
handle.kind ===
(selectedFacility.kind === 'crosswalk'
? 'junction-crosswalk-inset'
: 'junction-stop-line-offset')) ||
(handle.anchor.type === 'cluster-crossing' &&
String(handle.anchor.crossingKey) === String(selectedFacility.crossingNodeId) &&
handle.kind ===
(selectedFacility.kind === 'crosswalk'
? 'cluster-crossing-inset'
: 'cluster-stop-line-offset')),
)?.handleId
: undefined
}
/>
{onUpdateSignal ? (
<SignalEditor
state={state!}
signal={
selectedSignalUid
? state?.trafficSignals.assemblies.features.find(
(item) => String(item.properties?.signal_uid) === selectedSignalUid,
)
: undefined
}
signalUids={signalUids}
allowDelete={false}
status={onSignalStatus ?? (() => undefined)}
update={onUpdateSignal}
/>
) : null}
{status ? <p role="status">{status}</p> : null}
<div className="junction-workspace__actions">
<Button onClick={onUndo} disabled={!canUndo}>
撤销
</Button>
<Button onClick={onRedo} disabled={!canRedo}>
重做
</Button>
<Button onClick={onApply} disabled={!dirty}>
应用到工作区
</Button>
<Button onClick={onSave} disabled={!dirty}>
保存
</Button>
<Button onClick={onDiscard} disabled={!dirty}>
放弃草稿
</Button>
</div>
</>
) : editable ? (
<p className="junction-workspace__browse-hint">开启编辑模式后,这里会显示可调整的路口几何参数。</p>
) : complexEnabled ? (
<p className="junction-workspace__browse-hint">复杂路口几何已启用;首版仅支持查看,不支持参数拖拽编辑。</p>
) : null}
</div>
</section>
);
}