import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Download, RefreshCw, Save, Upload } from 'lucide-react'; import { api, isVersionConflict } from './lib/api'; import { MapCanvas } from './components/MapCanvas'; import { ParameterPanel, type ParameterPanelHandle } from './components/ParameterPanel'; import { InspectorSection } from './components/InspectorSection'; import { elementSelectionFor, groupMembers, handleForElement, isControlElement, orientedBoundsOf, specFor, specOfKind, type ElementSelection, } from './edit/element'; import { intervalEditingSupported } from './edit/flag'; import type { ElementOutline } from './edit/handle-layer'; import { azimuthBetween, coordinateAtStation, metersAlongPolyline, polylineLengthMeters, toLonLat, type Coordinate, } from './edit/meters'; import { previewArrowFeatures } from './edit/arrow-preview'; import { rendersSame } from './edit/parameter'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; import { anchorSnapshotFor, constraintValueFor, draftConstraint, laneManeuverValueFor, operationFor, } from './edit/projection'; import { disabledReasonOf, handlesForSegment, intervalRangeHandles, type IntervalRangeHandle } from './edit/selection'; import { EditSession } from './edit/session'; import type { EditDiagnostic, EditHandle, HandleManifest, PreviewLayerName, RoadConstraint, RoadEditOperation, EditSelection, RoadIntervalAnchor, VersionConflict, } from './edit/types'; import { Button } from './ui/button'; import type { GeoFeature, GeoJson, Override, Road, WorkbenchState } from './types/state'; import type { LayerName } from './map/layers'; const layerLabels: Array<[LayerName, string]> = [ ['osm', '方向道路参考线'], ['native', '自研道路与路口面'], ['sidewalks', '路缘与步行带'], ['lanes', '车道与转向路径'], ['directionArrows', '道路方向箭头'], ['markings', '车道分隔线与路口转向箭头'], ['centerLines', '道路中央标线'], ['edgeLines', '道路外缘线'], ['controls', '斑马线与停止线'], ['signals', '红绿灯设施'], ]; const defaultLayers = Object.fromEntries(layerLabels.map(([key]) => [key, key !== 'edgeLines'])) as Record< LayerName, boolean >; const direction = (road: Road) => (road.direction === 'forward' ? '沿 OSM 方向' : '逆 OSM 方向'); const label = (road: Road) => road.tags.name || `${road.highway}(OSM ${road.osmWayIds.join(', ')})`; const laneIndex = (id: string) => Number(id.split(':').at(-1)); const overviewMetrics = [ ['nativeRoadCount', '方向道路'], ['nativeRoadSurfaceFeatures', '道路面'], ['nativeJunctionSurfaceFeatures', '路口面'], ['nativeLaneCenterlineFeatures', '车道中心线'], ['nativeCenterLineFeatures', '道路中心线'], ['nativeConnectorFeatures', '连接路径'], ['nativeCrosswalkFeatures', '斑马线'], ['nativeVehicleStopLineFeatures', '停止线'], ['unconnectedInteriorRoadEnds', '未连接端点'], ] as const; function Overview({ comparison }: { comparison: Record }) { const severity = comparison.diagnosticsBySeverity as Record | undefined; return (
{overviewMetrics.map(([key, label]) => (
{label} {Number(comparison[key] || 0).toLocaleString('zh-CN')}
))}
{severity && (
编译诊断 {Object.entries(severity).map(([level, count]) => ( {level === 'error' ? '错误' : level === 'warning' ? '警告' : '提示'} {count} ))}
)}
); } function App() { const [state, setState] = useState(); const [selected, setSelected] = useState(null); const [staged, setStaged] = useState([]); const [signalDirty, setSignalDirty] = useState(false); const signalDraftRef = useRef(null); const signalUndoRef = useRef([]); const signalRedoRef = useRef([]); const signalSavedRef = useRef(null); const signalMoveActiveRef = useRef(false); const [layers, setLayers] = useState(defaultLayers); const [scene, setScene] = useState(false); const [status, setStatus] = useState('正在加载工作台...'); const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all'); const [marking, setMarking] = useState | null>(null); const [editMode, setEditMode] = useState(() => { if (typeof window === 'undefined') return false; try { return window.localStorage.getItem('workbench-mode') === 'edit'; } catch { return false; } }); useEffect(() => { try { window.localStorage.setItem('workbench-mode', editMode ? 'edit' : 'browse'); } catch { // Storage may be unavailable in private browsing; the switch still works for this page. } }, [editMode]); useEffect(() => { api .state() .then((value) => { if ('compiled' in value) { setState(value); signalSavedRef.current = value.trafficSignals.assemblies.features; setStatus(`已加载 ${value.compiled.model.roads.length} 条方向道路`); } else setStatus('请导入 OSM 文件以开始'); }) .catch((error: Error) => setStatus(error.message)); }, []); const [manifest, setManifest] = useState(null); /** Which compiled document the session already adopted, so a re-fetch cannot discard edits. */ const loadedDocument = useRef(null); useEffect(() => { // Flag off: no manifest request at all, so the network trace matches main. if (!editMode) return; api // Scoped to the selection: the whole-area manifest is 844 KB on a 41-road // workspace, 89% of it `affects` id lists, and the map renders about six. .editState(selected?.segmentId ? { segment: selected.segmentId } : undefined) .then((value) => { if (!('handles' in value)) return; setManifest(value.handles); // Adopt the document only when it actually changed. This effect also runs on // every selection change, and reloading there would silently discard the // session's unsaved edits. const key = `${value.areaId}:${value.documentVersion}`; if (loadedDocument.current === key) return; loadedDocument.current = key; sessionRef.current?.load(value.document.constraints, value.document.operations, value.documentVersion); touch(); }) // A manifest failure must not take the workbench down with it; the map just // shows no handles. .catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`)); // Keyed on `state`, not mounted once: on a fresh import the first attempt runs // before any area exists and comes back inactive, so the handles never appeared // until a manual reload. A recompile also moves the geometry the manifest // describes, so the manifest has to be refetched with it. }, [editMode, state, selected?.segmentId]); const editHandles = useMemo(() => { if (!editMode || !state) return []; // Handle anchors carry a directional road id while reserves are keyed by // segment, so resolve through the compiled model rather than parsing ids. const segmentOf = (roadId: string) => state.compiled.model.roads.find((road) => road.id === roadId)?.segmentId; return handlesForSegment(manifest, selected?.segmentId ?? null, segmentOf); }, [editMode, manifest, selected, state]); // A greyed handle without a reason reads as a bug rather than an ownership // boundary, so the first blocked handle explains itself in the header. const blockedHandle = editHandles.find((handle) => !handle.editable); const blockedReason = blockedHandle ? disabledReasonOf(blockedHandle) : undefined; // Every road handle on a segment shares one interval — `makeRoadHandles()` builds // it once per segment — so one pair of range ends covers the whole selection. const editRanges = useMemo(() => { // Hidden until compileGeometry() honours profile.interval; see flag.ts. if (!editMode || !intervalEditingSupported || !state || !selected || !manifest) return []; const parent = editHandles.find((handle) => handle.editable && handle.anchor.type === 'road-interval'); const roadId = parent && 'roadId' in parent.anchor ? parent.anchor.roadId : null; const road = roadId ? state.compiled.model.roads.find((item) => item.id === roadId) : undefined; if (!parent || !road) return []; return intervalRangeHandles(parent, road.centerline, manifest.reserves, selected.segmentId); }, [editHandles, editMode, manifest, selected, state]); const [preview, setPreview] = useState> | null>(null); const [editDiagnostics, setEditDiagnostics] = useState([]); const sessionRef = useRef(null); if (editMode && !sessionRef.current) sessionRef.current = new EditSession(); const session = sessionRef.current; const [editRevision, setEditRevision] = useState(0); const touch = () => setEditRevision((value) => value + 1); /** * The crosswalk group under selection, if any. * * Element selection is independent of road selection: clicking a stripe also * selects its road, because the road-level handles stay useful. Only the * element box and its controls hang off this. */ const [element, setElement] = useState(null); /** * The selected element as something to draw and grab. * * The box carries the id of the control that moves it rather than an id of its * own, so grabbing the zebra runs the same gesture as grabbing that control's * dot — no second drag path, no second constraint. */ const elementOutline = useMemo(() => { if (!editMode || !element || !isControlElement(element) || !state) return null; const handle = handleForElement(element, state.compiled.model.roads, editHandles); if (!handle?.editable) return null; // Read the preview when there is one. `state.layers` is the last *compiled* // output and does not move during editing, so measuring the box there left it // behind at the baseline while the marking itself — drawn from the preview — // slid out from under it. A null preview layer means "back to baseline", // which is what the fallback expresses. const layer = specOfKind(element.kind).layer; const drawn = preview?.[layer] ?? state.layers[layer]; const bounds = orientedBoundsOf(groupMembers(drawn?.features ?? [], element.elementId)); return bounds ? { handleId: handle.handleId, bounds } : null; }, [editMode, element, editHandles, state, preview]); const laneSelectionBounds = useMemo(() => { if (!element || element.kind !== 'lane-maneuver' || !state || !element.featureIds.length) return null; const ids = new Set(element.featureIds); return orientedBoundsOf( state.layers.turnArrows?.features.filter((feature) => { const nativeId = feature.properties?.native_id; return typeof nativeId === 'string' && ids.has(nativeId); }) ?? [], ); }, [element, state]); const laneSelectionFeatures = useMemo(() => { if (!element || element.kind !== 'lane-maneuver' || !state) return []; const ids = new Set(element.featureIds); const previewFeatures = preview?.turnArrows?.features.filter((feature) => { const nativeId = feature.properties?.native_id; return typeof nativeId === 'string' && ids.has(nativeId); }); if (previewFeatures?.length) return previewFeatures; const existing = state.layers.turnArrows?.features.filter((feature) => { const nativeId = feature.properties?.native_id; return typeof nativeId === 'string' && ids.has(nativeId); }) ?? []; const effective = session ?.constraints() .find( (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === element.laneId, )?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined; const maneuver = effective?.maneuver ?? element.maneuver; const placementDistanceMeters = effective?.placementDistanceMeters ?? element.placementDistanceMeters; if (existing.length && maneuver === element.maneuver && placementDistanceMeters === element.placementDistanceMeters) return existing; const lane = state.layers.laneCenterlines?.features.find( (feature) => feature.properties?.native_id === element.laneId, ); const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null; const distance = placementDistanceMeters ?? 6; if (!line || line.length < 2 || !maneuver) return []; return previewArrowFeatures(element.laneId, maneuver, line, distance); }, [editRevision, element, preview, session, state]); const laneSelectionAxisAzimuth = useMemo(() => { if (!element || element.kind !== 'lane-maneuver' || !state) return null; const road = state.compiled.model.roads.find((item) => item.id === element.roadId); const previous = road?.centerline.at(-2); const end = road?.centerline.at(-1); return previous && end ? azimuthBetween(previous, end) : null; }, [element, state]); const laneSelectionAnchor = useMemo(() => { if (!element || element.kind !== 'lane-maneuver' || !state) return null; const lane = state.layers.laneCenterlines?.features.find( (feature) => feature.properties?.native_id === element.laneId, ); const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null; if (!line || line.length < 2) return null; const effective = session ?.constraints() .find( (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === element.laneId, )?.value as { placementDistanceMeters?: number } | undefined; const distance = effective?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6; const length = polylineLengthMeters(line); return length > 0 ? coordinateAtStation(line, 1 - distance / length) : null; }, [editRevision, element, session, state]); // Per-frame drag feedback reaches the panel through this rather than through // state, for the same reason the ghost writes its own source: a setState on // every pointermove re-renders all of App. const panelRef = useRef(null); // The session is a mutable object in a ref, so React cannot see it change. // Bumping this after every mutation is what keeps the buttons in step with it. // Read at send time so the requester, built once, always scopes to the current // selection without being rebuilt. const selectionRef = useRef(undefined); selectionRef.current = 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 * same id in the document, which `validateEditDocument()` rejects outright. */ const gesture = useRef<{ operationId: string; createdAt: string } | null>(null); const gestureIdentity = () => { if (!gesture.current) gesture.current = { operationId: `operation:${editRevision}:${Date.now()}`, createdAt: new Date().toISOString(), }; return gesture.current; }; const requester = useMemo(() => { const owner = sessionRef.current; if (!owner) return null; return new PreviewRequester({ session: owner, send: (request, signal) => api.editPreview({ ...request, selection: selectionRef.current }, signal), onSettled: (outcome, response) => { setEditDiagnostics(response.diagnostics); // The response carries a re-solved manifest. Keeping the stale one made the // handles snap back to their pre-drag positions the moment the ghost cleared. setManifest(response.handles); // A rejected draft leaves the last valid preview on screen; the session // has already decided that, so this only mirrors its verdict. if (!outcome.blocked) setPreview(response.layers); }, onError: (error) => setStatus(`预览失败:${(error as Error).message}`), }); }, [session]); /** A drag becomes one drafted constraint layered over the session's document. */ const draftFor = (handle: EditHandle, value: number): PreviewDraft | null => { // Road-anchored edits carry a directional road id. Junction-approach // controls are keyed by segment instead, so resolve them through the // compiled model before building the anchor snapshot. Without this branch // control handles silently returned null and never scheduled a preview. const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : null; const segmentId = 'segmentId' in handle.anchor ? handle.anchor.segmentId : null; const road = state?.compiled.model.roads.find( (item) => (roadId ? item.id === roadId : false) || (segmentId ? item.segmentId === segmentId : false), ); // Without a centerline there is no snapshot to record, so drop the drag rather // than send a constraint the server would have to reject. if (!session || !road || road.centerline.length < 2) return null; const constraint = draftConstraint( handle, handle.anchor, constraintValueFor(handle, value), anchorSnapshotFor(handle, road.centerline, road.sourceNodeIds), { constraintId: `constraint:${handle.handleId}`, ...gestureIdentity() }, ); const operation = operationFor(constraint); const base = session.fragment(); // Both halves travel: validateEditDocument() rejects a constraint whose // provenance.operationId is not a recorded operation, and that check covers the // already-saved constraints too, not just the one being dragged. return { constraints: [...base.constraints.filter((item) => item.id !== constraint.id), constraint], operations: [...base.operations.filter((item) => item.id !== operation.id), operation], }; }; const draftLane = (laneId: string, maneuver: string, placementDistanceMeters: number): PreviewDraft | null => { const handle = manifest?.handles.find( (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === laneId, ); if (!handle || !state || !session) return null; const roadId = handle.anchor.type === 'lane' ? handle.anchor.roadId : null; const laneIndex = laneId.split(':').at(-1); const road = state.compiled.model.roads.find( (item) => item.id === roadId || `lane:${item.id}:${laneIndex}` === laneId, ); if (!road || road.centerline.length < 2) return null; const constraint = draftConstraint( handle, handle.anchor, laneManeuverValueFor(maneuver, placementDistanceMeters), anchorSnapshotFor(handle, road.centerline, road.sourceNodeIds), { constraintId: `constraint:${handle.handleId}`, ...gestureIdentity() }, ); const operation = operationFor(constraint); const base = session.fragment(); return { constraints: [...base.constraints.filter((item) => item.id !== constraint.id), constraint], operations: [...base.operations.filter((item) => item.id !== operation.id), operation], }; }; /** * A range drag re-anchors the constraints already on this road rather than * creating one: the interval is a property of the road's edit, shared by every * constraint on it. With no constraint yet there is nothing to re-anchor. */ const rangeDraftFor = (range: IntervalRangeHandle, anchor: RoadIntervalAnchor): PreviewDraft | null => { const base = session?.fragment(); const onRoad = (item: RoadConstraint) => item.anchor.type === 'road-interval' && item.anchor.roadId === range.roadId; if (!base || !base.constraints.some(onRoad)) return null; return { constraints: base.constraints.map((item) => onRoad(item) ? { ...item, anchor: { ...item.anchor, startStation: anchor.startStation, endStation: anchor.endStation } } : item, ), operations: base.operations, }; }; /** * Pointerup closes the gesture: one undoable command, then the id is released so * the next drag mints its own. An abandoned drag commits nothing. */ const commitGesture = (draft: PreviewDraft | null, constraintIds: string[]) => { if (!draft || !session) return; requester?.flush(draft); session.commit(draft.constraints ?? [], constraintIds, gestureIdentity()); gesture.current = null; touch(); }; const applyLaneManeuver = (maneuver: string, placementDistanceMeters: number) => { if (!element || element.kind !== 'lane-maneuver') return; const draft = draftLane(element.laneId, maneuver, placementDistanceMeters); if (!draft) return; commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]); setStatus('导向箭头修改已暂存;保存直接编辑后应用。'); }; /** Re-previews whatever the session now holds, after undo/redo moved the cursor. */ const previewSession = () => { const fragment = session?.fragment(); if (fragment) requester?.flush(fragment); }; /** * A live value from either channel: preview it, do not commit. * * Dragging and typing differ only in how the number is made. From here down the * two share everything — the draft, the debounce, the previewSeq arbitration — * so there is one implementation rather than a parallel one per input device. */ const draftValue = (handle: EditHandle, value: number) => { const draft = draftFor(handle, value); if (draft) requester?.schedule(draft); }; /** Neither channel committed: release the id and put the settled state back. */ const abandonGesture = () => { gesture.current = null; panelRef.current?.clearLive(); previewSession(); }; /** A settled value from either channel: one undoable command, or nothing. */ const settleValue = (handle: EditHandle, value: number) => { // A gesture that did not move the value must not become an edit. `handle` was // captured at pointerdown, so this compares against the pre-drag value. The // element box is a large hit target, which makes a click-without-drag common // rather than an edge case — but the same applies to a tapped handle dot. if (rendersSame(value, handle.value.current)) { abandonGesture(); return; } const draft = draftFor(handle, value); if (draft) commitGesture(draft, [`constraint:${handle.handleId}`]); else abandonGesture(); }; /** * Reset: put a parameter back on the compiler's baseline. * * The constraint is disabled rather than removed. `validateEditDocument()` * rejects an operation naming a constraint that is not in the document, so a * deletion would have to record an operation about nothing; disabling is also * what design.md already sanctions for undoing saved work, and it keeps the * history readable. The solver skips `enabled === false` and then publishes the * handle without a `constraintId`, so the row reports itself unmodified again. * * This is the one edit dragging cannot express — a drag can set a value, never * withdraw one. */ const resetHandle = (handle: EditHandle) => { const base = session?.fragment(); const constraintId = handle.constraintId; if (!session || !base || !constraintId) return; const identity = gestureIdentity(); const operation = { id: identity.operationId, createdAt: identity.createdAt, constraintIds: [constraintId], }; commitGesture( { constraints: base.constraints.map((item) => (item.id === constraintId ? { ...item, enabled: false } : item)), operations: [...base.operations.filter((item) => item.id !== operation.id), operation], }, [constraintId], ); }; const undoEdit = () => { // A saved gesture cannot be un-applied — persisted history is append-only — so // it is reversed by an inverse operation, which needs its own identity. if (!session?.canUndo && signalUndoRef.current.length) { const previous = signalUndoRef.current.pop()!; signalRedoRef.current.push(state?.trafficSignals.assemblies.features || []); setState((current) => current ? { ...current, trafficSignals: { ...current.trafficSignals, assemblies: { ...current.trafficSignals.assemblies, features: previous }, }, } : current, ); signalDraftRef.current = previous; setSignalDirty(true); return; } const reversed = session?.undo({ operationId: `operation:undo:${Date.now()}`, createdAt: new Date().toISOString(), }); if (!reversed) return; touch(); previewSession(); }; const redoEdit = () => { if (!session?.canRedo && signalRedoRef.current.length) { const next = signalRedoRef.current.pop()!; signalUndoRef.current.push(state?.trafficSignals.assemblies.features || []); setState((current) => current ? { ...current, trafficSignals: { ...current.trafficSignals, assemblies: { ...current.trafficSignals.assemblies, features: next }, }, } : current, ); signalDraftRef.current = next; setSignalDirty(true); return; } if (!session?.redo()) return; touch(); previewSession(); }; const discardEdits = () => { requester?.cancel(); session?.discard(); if (signalDirty && signalSavedRef.current) { setState((current) => current ? { ...current, trafficSignals: { ...current.trafficSignals, assemblies: { ...current.trafficSignals.assemblies, features: signalSavedRef.current! }, }, } : current, ); } signalDraftRef.current = null; signalUndoRef.current = []; signalRedoRef.current = []; setSignalDirty(false); setStaged([]); gesture.current = null; touch(); setPreview(null); setEditDiagnostics([]); setStatus('已放弃未保存的直接编辑'); }; const saveDirectEdits = async (recompile = true) => { if (!session || !session.dirty) return true; // A field still being typed in holds an uncommitted value. Blur fires before // click so the button press would settle it anyway, but that ordering is not // something to depend on for whether an edit is persisted. panelRef.current?.settleOpenEdit(); const fragment = session.fragment(); let version: number; try { const result = await api.saveEdits({ expectedDocumentVersion: session.documentVersion, constraints: fragment.constraints, operations: fragment.operations, }); version = result.documentVersion; session.markSaved(version); touch(); } catch (error) { if (!isVersionConflict(error)) { setStatus(`保存失败:${(error as Error).message}`); return false; } // Single-writer protection fired: another tab moved the document. Adopt the // server's version so the next attempt is checked against reality, and say so // rather than failing silently. const current = (error.body as VersionConflict | null)?.current?.documentVersion; if (Number.isInteger(current)) session.setDocumentVersion(current as number); touch(); setStatus(`保存冲突:文档已被改到版本 ${current ?? '未知'},请刷新后重做本次编辑。`); return false; } // The document is written, but `/api/state` serves the outputs of the last // compile — without recompiling, a refresh shows the pre-edit geometry and a // successful save is indistinguishable from a failed one. Reported separately // because at this point the save has already succeeded. if (!recompile) return true; try { setStatus('直接编辑已保存,正在重新生成几何...'); const next = await api.compile(); setState(next); setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); // The baseline now carries the edit, so the preview overlay would draw it twice. setPreview(null); setStatus(`直接编辑已保存并重新生成,文档版本 ${version}`); } catch (error) { setStatus(`直接编辑已保存(版本 ${version}),但重新生成失败:${(error as Error).message}`); } return true; }; const stage = (change: Override) => setStaged((current) => { const next = [...current.filter((item) => item.id !== change.id), change]; return next; }); const save = async () => { if (!state || !staged.length) return true; try { const overrides = [ ...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)), ...staged, ]; const result = await api.overrides(overrides); setState({ ...state, overrides: result.overrides }); setStaged([]); setStatus('已保存,点击“保存并重新生成”写入几何'); return true; } catch (error) { setStatus((error as Error).message); return false; } }; const compile = async () => { if (!(await save())) return; if (!(await saveDirectEdits(false))) return; if (signalDirty && signalDraftRef.current && state) { try { const result = await api.signals({ ...state.trafficSignals, assemblies: { ...state.trafficSignals.assemblies, features: signalDraftRef.current }, }); setState((value) => (value ? { ...value, ...result } : value)); signalSavedRef.current = signalDraftRef.current; signalDraftRef.current = null; setSignalDirty(false); } catch (error) { setStatus(`红绿灯保存失败:${(error as Error).message}`); return; } } try { setStatus('正在重新生成...'); const next = await api.compile(); setState(next); setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); setPreview(null); setStatus('已保存并重新生成'); } catch (error) { setStatus((error as Error).message); } }; const updateSignal = async (features: GeoFeature[]) => { if (state) signalUndoRef.current.push(state.trafficSignals.assemblies.features); signalRedoRef.current = []; signalDraftRef.current = features; setSignalDirty(true); setState((current) => current ? { ...current, trafficSignals: { ...current.trafficSignals, assemblies: { ...current.trafficSignals.assemblies, features }, }, } : current, ); }; if (!state) return ( { setState(next); setStatus(`已导入 ${next.areaId}`); }} /> ); const diagnostics = state.compiled.diagnostics.filter( (item) => item.rule !== 'ordinary-junction-surface' && (filter === 'all' || (filter === 'candidates' ? Boolean(item.manualCandidates?.length) : !item.manualCandidates?.length)), ); const handleFeature = (properties: Record) => { setMarking(properties); // A crosswalk is six features but one editable thing; a stop line is one. // `provenance` picks which, and therefore which layer holds its siblings — // the two share `crossing_node_id`, so keying on that alone would merge a // zebra with the stop line protecting it. Clicking anything else drops the // selection, because a box left around what the user navigated away from // reads as a stuck UI. const spec = specFor(properties); const nextElement = elementSelectionFor( properties, spec ? (state.layers[spec.layer]?.features ?? []) : (state.layers.laneCenterlines?.features ?? []), ); setElement(editMode ? nextElement : null); const uid = properties.signal_uid; if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`); else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); }; const moveSignal = (uid: string, coordinate: Coordinate) => { setState((current) => { if (!current) return current; if (!signalMoveActiveRef.current) { signalUndoRef.current.push(current.trafficSignals.assemblies.features); signalRedoRef.current = []; signalMoveActiveRef.current = true; } return { ...current, trafficSignals: { ...current.trafficSignals, assemblies: { ...current.trafficSignals.assemblies, features: current.trafficSignals.assemblies.features.map((feature) => feature.properties?.signal_uid === uid ? { ...feature, geometry: { type: 'Point', coordinates: coordinate } } : feature, ), }, }, }; }); setSignalDirty(true); }; const finishSignalMove = (uid: string, coordinate: Coordinate) => { const current = state; if (!current) return; const features = current.trafficSignals.assemblies.features.map((feature) => feature.properties?.signal_uid === uid ? { ...feature, geometry: { type: 'Point', coordinates: coordinate } } : feature, ); signalDraftRef.current = features; signalMoveActiveRef.current = false; setSignalDirty(true); }; return ( <>
道路编译工作台 {state.areaId} {status} {staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'} {editMode ? ( item.severity === 'error') ? 'dirty' : ''}> {editDiagnostics.find((item) => item.severity === 'error')?.message || (element ? element.kind === 'lane-maneuver' ? `已选中第 ${laneIndex(element.laneId)} 车道(${element.featureIds.length} 个箭头 part)` : `已选中${specOfKind(element.kind).label} ${element.crossingNodeId}(${element.featureIds.length} 条)` : editHandles.length ? `手柄 ${editHandles.length} 个` : selected ? '当前道路无可编辑手柄' : '选中道路以显示手柄')} {blockedReason ? `|${blockedReason}` : ''} ) : null} 导出道路包 {editMode ? ( <> ) : null}
setElement(null)} onSignalDrag={moveSignal} onSignalDragEnd={finishSignalMove} handles={editHandles} ranges={editRanges} element={elementOutline} laneSelectionBounds={laneSelectionBounds} laneSelectionFeatures={laneSelectionFeatures} laneSelectionHiddenIds={element?.kind === 'lane-maneuver' ? element.featureIds : []} laneSelectionAnchor={laneSelectionAnchor} laneSelectionAxisAzimuth={laneSelectionAxisAzimuth} onLaneSelectionDrag={(from, to) => { if (!element || element.kind !== 'lane-maneuver') return; const lane = state.layers.laneCenterlines?.features.find( (feature) => feature.properties?.native_id === element.laneId, ); const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null; if (!line || line.length < 2) return; const along = metersAlongPolyline(line, toLonLat(to)); const length = polylineLengthMeters(line); if (along === null || !(length > 0)) return; const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along)); if (draft) requester?.schedule(draft); }} onLaneSelectionDragEnd={(from, to) => { if (!element || element.kind !== 'lane-maneuver') return; const lane = state.layers.laneCenterlines?.features.find( (feature) => feature.properties?.native_id === element.laneId, ); const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null; if (!line || line.length < 2) return; const along = metersAlongPolyline(line, toLonLat(to)); const length = polylineLengthMeters(line); if (along === null || !(length > 0)) return; const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along)); if (draft) commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]); setStatus('箭头位置已暂存;保存并重新生成后应用。'); }} preview={preview} ghostPending={session?.degraded ?? false} onHandleDrag={(handle, value) => { // Straight to the DOM, like the ghost writes straight to its source: // a per-pointermove setState re-renders this whole component. panelRef.current?.showLive(handle.handleId, value); draftValue(handle, value); }} onHandleDragEnd={settleValue} onHandleBlocked={(_handle, reason) => setStatus(reason)} onRangeDrag={(range, anchor) => { const draft = rangeDraftFor(range, anchor); if (draft) requester?.schedule(draft); }} onRangeEnd={(range, anchor) => { const draft = rangeDraftFor(range, anchor); if (!draft) { setStatus('先拖动路缘、步行带或车道分隔手柄产生一次编辑,范围手柄才有可调整的区间。'); return; } const touched = (draft.constraints ?? []) .filter((item) => item.anchor.type === 'road-interval' && item.anchor.roadId === range.roadId) .map((item) => item.id); commitGesture(draft, touched); }} />
); } function ImportScreen({ status, onImported }: { status: string; onImported: (state: WorkbenchState) => void }) { const [file, setFile] = useState(); const [busy, setBusy] = useState(false); return (
{ event.preventDefault(); if (!file) return; setBusy(true); try { onImported(await api.import(file)); } catch (error) { console.error(error); } finally { setBusy(false); } }} >

导入 OSM 地图

{status}

setFile(event.target.files?.[0])} required />
); } function Inspector({ road, state, staged, marking, element, stage, status, setState, session, onLaneManeuverChange, updateSignal, children, }: { road: Road | null; state: WorkbenchState; staged: Override[]; marking: Record | null; element: ElementSelection | null; stage: (item: Override) => void; status: (value: string) => void; setState: (next: WorkbenchState) => void; session: EditSession | null; onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void; updateSignal: (features: GeoFeature[]) => Promise; children?: ReactNode; }) { const [width, setWidth] = useState(0); const [lanes, setLanes] = useState(1); const [left, setLeft] = useState(false); const [right, setRight] = useState(false); useEffect(() => { if (road) { setWidth(road.widthMeters); setLanes(road.laneCount); setLeft(road.sidewalkLeft); setRight(road.sidewalkRight); } }, [road]); const endpoint = state.compiled.model.endpoints.find((item) => item.roadId === road?.id && item.side === 'end'); const movements = state.compiled.movements?.filter((item) => item.fromRoadId === road?.id) || []; const effective = (id: string, fallback: boolean) => ((staged.find((item) => item.id === id) || state.overrides.overrides.find((item) => item.id === id))?.enabled as boolean | undefined) ?? fallback; const signalUid = typeof marking?.signal_uid === 'string' ? marking.signal_uid : ''; const signal = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === signalUid); const [open, setOpen] = useState<'road' | 'element' | 'connections' | 'advanced' | null>('road'); useEffect(() => { if (element || marking) setOpen('element'); else if (road) setOpen('road'); }, [element, marking, road]); const section = (name: NonNullable) => () => setOpen((current) => (current === name ? null : name)); const selectedLabel = element?.kind === 'lane-maneuver' ? `第 ${laneIndex(element.laneId)} 车道` : marking ? '已选标线或设施' : road ? label(road) : '未选择对象'; return (
编辑工作台 {selectedLabel} {staged.length ? `已暂存 ${staged.length} 项修改` : '没有待保存的覆盖修改'}
{road ? (
{ event.preventDefault(); stage({ id: `道路:${road.id}`, kind: 'road', roadId: road.id, widthMeters: width, laneCount: lanes, sidewalkLeft: left, sidewalkRight: right, }); const opposite = state.compiled.model.roads.find( (item) => item.id !== road.id && item.segmentId === road.segmentId, ); if (opposite) stage({ id: `道路:${opposite.id}`, kind: 'road', roadId: opposite.id, sidewalkLeft: right, sidewalkRight: left, }); status('有未保存修改'); }} > {label(road)}({direction(road)}) {movements.length ? `已识别 ${movements.length} 个行驶动作,${movements.filter((item) => item.geometryPublished).length} 条已绘制路径` : '当前方向没有已识别的行驶动作'}
) : (

点击道路、车道、标线、转向路径或路口面以查看详情。

)} {children}
item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === element.laneId, )?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined) : undefined } onChange={onLaneManeuverChange} /> {road ? (
{state.compiled.model.connections .filter((connection) => connection.fromEndpointId === endpoint?.id) .map((connection) => ( ))} {movements.map((movement) => ( ))}
) : (

选择一条道路以管理其驶入路口的连接。

)} {endpoint && state.compiled.diagnostics .find((item) => item.endpointId === endpoint.id) ?.manualCandidates?.map((candidate) => { const target = state.compiled.model.roads.find((item) => item.id === candidate.roadId); const targetEndpoint = state.compiled.model.endpoints.find( (item) => item.roadId === candidate.roadId && item.side === 'start', ); return target && targetEndpoint ? ( ) : null; })}
技术详情与来源
            {JSON.stringify(
              road ? { OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 原始标签: road.tags } : marking,
              null,
              2,
            )}
          
); } const MANEUVER_OPTIONS: Array<[string, string]> = [ ['', '无箭头'], ['through', '直行'], ['left', '左转'], ['right', '右转'], ['through;left', '直行或左转'], ['through;right', '直行或右转'], ['through;left;right', '直行、左转或右转'], ]; function LaneManeuverEditor({ element, value, onChange, }: { element: ElementSelection | null; value?: { maneuver?: string; placementDistanceMeters?: number }; onChange: (maneuver: string, placementDistanceMeters: number) => void; }) { if (!element || element.kind !== 'lane-maneuver') return null; const maneuver = value?.maneuver ?? element.maneuver; const placementDistanceMeters = value?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6; return (

车道转向箭头

第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。

保存并重新生成时会避开停止线、斑马线和车道端点。

); } function MarkingEditor({ marking, stage, }: { marking: Record | null; stage: (item: Override) => void; }) { const style = typeof marking?.effective_style === 'string' ? marking.effective_style : ''; const [value, setValue] = useState(style || 'yellow-dashed'); useEffect(() => setValue(style || 'yellow-dashed'), [style]); if (!style || !marking) return null; const roadId = String(marking.road_id); const segment = marking.segment_id; const kind = String(marking.provenance || ''); const save = () => { const [color, pattern] = value.replace('double-', '').split('-'); if (segment) stage({ id: `道路中心线:${segment}`, kind: 'center-line-style', segmentId: segment, color, pattern, double: value.startsWith('double-'), }); else if (kind.includes('edge-line')) stage({ id: `道路外缘线:${roadId}:${marking.side}`, kind: 'edge-line-style', roadId, side: marking.side, color, pattern, }); else stage({ id: `车道分隔线:${roadId}:${marking.left_lane_index}-${marking.right_lane_index}`, kind: 'lane-separator-style', roadId, leftLaneIndex: marking.left_lane_index, rightLaneIndex: marking.right_lane_index, color, pattern, }); }; return (
{ event.preventDefault(); save(); }} >

标线样式

); } function SignalEditor({ state, signal, status, update, }: { state: WorkbenchState; signal?: GeoFeature; status: (text: string) => void; update: (features: GeoFeature[]) => Promise; }) { const [selected, setSelected] = useState(''); useEffect(() => setSelected(String(signal?.properties?.signal_uid || '')), [signal]); const feature = state.trafficSignals.assemblies.features.find((item) => item.properties?.signal_uid === selected); const coordinates = feature?.geometry?.type === 'Point' && Array.isArray(feature.geometry.coordinates) ? (feature.geometry.coordinates as [number, number]) : null; const saveField = (key: string, value: unknown) => { if (!feature) return; void update( state.trafficSignals.assemblies.features.map((item) => item === feature ? { ...item, properties: { ...item.properties, [key]: value } } : item, ), ); }; const saveCoordinate = (index: 0 | 1, value: number) => { if (!feature || !coordinates || !Number.isFinite(value)) return; const nextCoordinates: [number, number] = [...coordinates]; nextCoordinates[index] = value; void update( state.trafficSignals.assemblies.features.map((item) => item === feature ? { ...item, geometry: { ...item.geometry, type: 'Point', coordinates: nextCoordinates } } : item, ), ); }; return (

原生红绿灯

{feature ? ( <>

控制进口:{String(feature.properties?.approach_id || '未绑定')}
来源道路:{String(feature.properties?.source_way_id || '未绑定')}

) : null}
); } function Candidates({ state, setState, status, }: { state: WorkbenchState; setState: (state: WorkbenchState) => void; status: (text: string) => void; }) { const candidates = state.debug?.junctionCandidates || []; if (!candidates.length) return null; return (

复杂路口候选(debug)

{candidates.map((candidate) => ( ))}
); } export default App;