import { useEffect, useMemo, useRef, useState } from 'react'; import { Download, RefreshCw } from 'lucide-react'; import { ImportScreen } from './components/ImportScreen'; import { Overview } from './components/Overview'; import { WorkbenchInspector } from './components/WorkbenchInspector'; import { useOverrideDraft } from './hooks/useOverrideDraft'; import { useDirectEditSession } from './hooks/useDirectEditSession'; import { useTrafficSignalDraft } from './hooks/useTrafficSignalDraft'; import { api, isVersionConflict } from './lib/api'; import { MapCanvas } from './components/MapCanvas'; import { ParameterPanel, type ParameterPanelHandle } from './components/ParameterPanel'; 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, haversineMeters, metersAlongPolyline, polylineLengthMeters, toLonLat, type Coordinate, } from './edit/meters'; import { previewArrowFeatures } from './edit/arrow-preview'; import { formatParameterValue, rendersSame } from './edit/parameter'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; import { clearEditHistory, recordEdit, takeRedoDomain, takeUndoDomain, type EditHistory } from './edit/edit-history'; import { anchorSnapshotFor, constraintValueFor, draftConstraint, laneManeuverValueFor, operationFor, } from './edit/projection'; import { disabledReasonOf, handlesForSegment, intervalRangeHandles, type IntervalRangeHandle } from './edit/selection'; import type { EditHandle, PreviewLayerName, RoadConstraint, EditSelection, RoadIntervalAnchor, VersionConflict, } from './edit/types'; 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 { candidateForJunction, junctionDescriptors, hotspotAt } from './junction/hotspots'; import { JunctionWorkspace } from './junction/JunctionWorkspace'; import { localJunctionPreview, localJunctionState } from './junction/local-state'; import { junctionEditSelection, junctionObjectFeatures, junctionObjectKeyForFeature, structureForJunction, } from './junction/structure'; import { applyJunctionDraft, cancelJunctionSession, createJunctionSession, saveJunctionSession, type JunctionSession, } from './junction/workspace'; const layerLabels: Array<[LayerName, string]> = [ ['osm', '方向道路参考线'], ['reference', '参考几何叠加'], ['native', '自研道路与路口面'], ['sidewalks', '路缘与步行带'], ['lanes', '车道与转向路径'], ['directionArrows', '道路方向箭头'], ['markings', '车道分隔线与路口转向箭头'], ['centerLines', '道路中央标线'], ['edgeLines', '道路外缘线'], ['controls', '斑马线与停止线'], ['signals', '红绿灯设施'], ['junctionHotspots', '路口编辑热区'], ]; const defaultLayers = Object.fromEntries( layerLabels.map(([key]) => [key, key !== 'edgeLines' && key !== 'reference']), ) as Record; 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)); function App() { const [state, setState] = useState(); const [selected, setSelected] = useState(null); const [layers, setLayers] = useState(defaultLayers); const [referenceOpacity, setReferenceOpacity] = useState(0.55); const [scene, setScene] = useState(false); const [junctionHotspots, setJunctionHotspots] = useState(true); const [status, setStatus] = useState('正在加载工作台...'); const [previewPending, setPreviewPending] = useState(false); const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all'); const [marking, setMarking] = useState | null>(null); const [selectedObjectKey, setSelectedObjectKey] = useState(null); const [junctionRoute, setJunctionRoute] = useState(() => { if (typeof window === 'undefined') return null; const match = window.location.pathname.match(/^\/junction\/(node|cluster)\/([^/]+)$/); return match ? { type: match[1] as JunctionRef['type'], id: decodeURIComponent(match[2]) } : null; }); const [junctionSession, setJunctionSession] = useState(null); const editHistoryRef = useRef({ undo: [], redo: [] }); const recordSignalEdit = useMemo( () => () => { recordEdit(editHistoryRef.current, 'signal'); }, [], ); const [editMode, setEditMode] = useState(() => { if (typeof window === 'undefined') return false; try { return window.localStorage.getItem('workbench-mode') === 'edit'; } catch { return false; } }); const overrideDraft = useOverrideDraft({ state, setState, setStatus }); const { staged, stage, save, clear: clearStaged } = overrideDraft; const signalDraft = useTrafficSignalDraft({ state, setState, onEdit: recordSignalEdit }); const { dirty: signalDirty, setDirty: setSignalDirty, draftRef: signalDraftRef, undoRef: signalUndoRef, redoRef: signalRedoRef, savedRef: signalSavedRef, update: updateSignal, move: moveSignal, finishMove: finishSignalMove, rotate: rotateSignal, finishRotate: finishSignalRotate, } = signalDraft; 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(() => { const onPopState = () => { const match = window.location.pathname.match(/^\/junction\/(node|cluster)\/([^/]+)$/); setJunctionRoute(match ? { type: match[1] as JunctionRef['type'], id: decodeURIComponent(match[2]) } : null); }; window.addEventListener('popstate', onPopState); return () => window.removeEventListener('popstate', onPopState); }, []); 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 directEdit = useDirectEditSession({ editMode, state, selectedSegmentId: selected?.segmentId, selectedJunction: junctionRoute, setStatus, }); const { session, manifest, setManifest, preview, setPreview, diagnostics: editDiagnostics, setDiagnostics: setEditDiagnostics, revision: editRevision, touch, } = directEdit; const junctionDescriptor = useMemo( () => (state && junctionRoute ? hotspotAt(junctionDescriptors(state), junctionRoute) : null), [junctionRoute, state], ); const junctionRoads = useMemo(() => { if (!state || !junctionDescriptor) return []; const ids = new Set(junctionDescriptor.approachRoadIds); // Configured clusters may not carry approach ids yet; derive them from the // cluster's member nodes so the workspace still stays local to the junction. if (!ids.size) { const nodeIds = new Set(junctionDescriptor.nodeIds.map(String)); for (const endpoint of state.compiled.model.endpoints || []) { if (nodeIds.has(String(endpoint.nodeId))) ids.add(endpoint.roadId); } } const seen = new Set(); return state.compiled.model.roads.filter((road) => { if (!(ids.has(road.id) || ids.has(road.segmentId))) return false; const key = road.tags?.name?.trim() || `unnamed:${road.id || road.segmentId}`; if (seen.has(key)) return false; seen.add(key); return true; }); }, [junctionDescriptor, state]); const junctionMapState = useMemo( () => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state), [junctionDescriptor, junctionRoute, state], ); const junctionStructure = useMemo( () => (junctionRoute ? structureForJunction(state, junctionRoute) : null), [junctionRoute, state], ); const junctionSelectionFeatures = useMemo( () => junctionObjectFeatures(state, junctionStructure, selectedObjectKey), [state, junctionStructure, selectedObjectKey], ); useEffect(() => { setSelectedObjectKey(null); }, [junctionRoute]); const junctionMapPreview = useMemo( () => state && junctionDescriptor && junctionRoute ? localJunctionPreview(preview, junctionDescriptor, state.compiled.model.roads) : 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 // selection convenience only, never a second JunctionTools data source. useEffect(() => { if (!junctionDescriptor || !state || junctionDescriptor.ref.type !== 'node') return; const approach = junctionDescriptor.approachRoadIds .map((roadId) => state.compiled.model.roads.find((road) => road.id === roadId)) .find((road): road is Road => Boolean(road)); if (approach) setSelected(approach); }, [junctionDescriptor, state]); useEffect(() => { if (!junctionRoute) { setJunctionSession(null); return; } setJunctionSession(createJunctionSession(junctionRoute, editRevision)); }, [editRevision, junctionRoute]); 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]); // JunctionTools owns the three shape constraints for an ordinary node. Keep // the same manifest objects and callbacks as the main parameter panel so // number entry and dragging share one preview/undo protocol. const junctionHandles = useMemo(() => { if (!junctionDescriptor || !manifest) return []; if (junctionDescriptor.ref.type === 'cluster') return manifest.handles.filter( (handle) => (handle.kind === 'cluster-carriageway-width' || handle.kind === 'cluster-carriageway-cutback' || handle.kind === 'cluster-carriageway-transition-length' || handle.kind === 'cluster-carriageway-position' || handle.kind === 'cluster-carriageway-direction' || handle.kind === 'cluster-carriageway-edge-offset' || handle.kind === 'cluster-corner-radius' || handle.kind === 'cluster-crossing-inset' || handle.kind === 'cluster-stop-line-offset') && 'clusterId' in handle.anchor && handle.anchor.clusterId === junctionDescriptor.ref.id, ); const nodeIds = new Set(junctionDescriptor.nodeIds.map(String)); return manifest.handles.filter( (handle) => (handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback' || handle.kind === 'junction-corner-radius' || handle.kind === 'junction-crosswalk-inset' || handle.kind === 'junction-stop-line-offset') && 'nodeId' in handle.anchor && nodeIds.has(String(handle.anchor.nodeId)), ); }, [junctionDescriptor, manifest]); const junctionFacilitySummary = useMemo(() => { if (!junctionDescriptor || !state) return { crosswalks: 0, stopLines: 0, signals: 0 }; const nodeIds = new Set(junctionDescriptor.nodeIds.map(String)); const crossingIds = new Set( (state.layers.crosswalks?.features ?? []) .filter((feature) => nodeIds.has(String(feature.properties?.crossing_node_id))) .map((feature) => String(feature.properties?.crossing_node_id)), ); const stopLines = (state.layers.vehicleStopLines?.features ?? []).filter((feature) => nodeIds.has(String(feature.properties?.crossing_node_id)), ).length; const signals = state.trafficSignals.assemblies.features.filter((feature) => [feature.properties?.node_id, feature.properties?.control_id].some( (value) => value !== undefined && value !== null && nodeIds.has(String(value)), ), ).length; return { crosswalks: crossingIds.size, stopLines, signals }; }, [junctionDescriptor, state]); const junctionDiagnostics = useMemo(() => { if (!junctionDescriptor || !state) return []; const ids = new Set(junctionDescriptor.diagnosticIds); return state.compiled.diagnostics.filter( (item) => ids.has(item.id) || item.subjectId === junctionDescriptor.ref.id, ); }, [junctionDescriptor, 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]); /** * 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); const visibleEditHandles = useMemo(() => { if (!element || element.kind === 'lane-maneuver') return editHandles; const constraintKind = element.constraintKind ?? specOfKind(element.kind).constraintKind; // Control markings use the selected outline itself as their drag target, // exactly like lane-maneuver. Keep the selected control in the index so the // outline can resolve its semantics, while the layer hides its duplicate dot. return editHandles.filter( (handle) => (!handle.kind.startsWith('junction-cross') && !handle.kind.startsWith('cluster-cross')) || (handle.kind === constraintKind && ((handle.anchor.type === 'junction-crossing' && String(handle.anchor.crossingId) === String(element.crossingNodeId)) || (handle.anchor.type === 'cluster-crossing' && handle.anchor.crossingKey === element.crossingNodeId))), ); }, [editHandles, element]); /** * 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, hideOtherHandles: true } : 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); // An independent JunctionTools page owns the whole junction manifest. Never // fall back to the approach segment here: doing so makes an accepted preview // replace the junction manifest with a road-scoped one, which drops the // width/cutback/radius rows immediately after the first edit. selectionRef.current = junctionRoute ? junctionEditSelection(junctionRoute) : 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 = session; if (!owner) return null; return new PreviewRequester({ session: owner, send: (request, signal) => api.editPreview({ ...request, selection: selectionRef.current }, signal), onPendingChange: setPreviewPending, 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]); const previewScopeKey = junctionRoute ? `${junctionRoute.type}:${junctionRoute.id}` : selected?.segmentId ? `segment:${selected.segmentId}` : 'area'; useEffect(() => { requester?.invalidate(); setPreviewPending(false); // Preview geometry is scoped server output. Retaining it during an A -> B // transition would draw A while B's manifest is loading. setPreview(null); setEditDiagnostics([]); gesture.current = null; }, [previewScopeKey, requester]); /** 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 sourceRoadId = handle.anchor.type === 'cluster-carriageway' ? handle.anchor.sourceRoadIds[0] : null; const cornerAnchor = handle.anchor.type === 'cluster-corner' ? handle.anchor : null; const crossingAnchor = handle.anchor.type === 'cluster-crossing' ? handle.anchor : null; const cornerHandle = cornerAnchor ? manifest?.handles.find( (candidate) => candidate.anchor.type === 'cluster-carriageway' && cornerAnchor.carriagewayKeys.includes(candidate.anchor.carriagewayKey), ) : undefined; const crossingHandle = crossingAnchor ? manifest?.handles.find( (candidate) => candidate.anchor.type === 'cluster-carriageway' && crossingAnchor.carriagewayKeys.includes(candidate.anchor.carriagewayKey), ) : undefined; const cornerSourceRoadId = cornerHandle?.anchor.type === 'cluster-carriageway' ? cornerHandle.anchor.sourceRoadIds[0] : null; const crossingSourceRoadId = crossingHandle?.anchor.type === 'cluster-carriageway' ? crossingHandle.anchor.sourceRoadIds[0] : null; const segmentId = 'segmentId' in handle.anchor ? handle.anchor.segmentId : null; const cornerRoadId = handle.anchor.type === 'junction-corner' ? handle.anchor.incomingRoadId : null; const road = state?.compiled.model.roads.find( (item) => (roadId ? item.id === roadId : false) || (sourceRoadId ? item.id === sourceRoadId : false) || (cornerSourceRoadId ? item.id === cornerSourceRoadId : false) || (crossingSourceRoadId ? item.id === crossingSourceRoadId : false) || (segmentId ? item.segmentId === segmentId : false) || (cornerRoadId ? item.id === cornerRoadId || item.segmentId === cornerRoadId : 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 draftForGroup = (handles: EditHandle[], value: number): PreviewDraft | null => { if (!handles.length || !session) return null; const drafts = handles .map((handle) => draftFor(handle, value)) .filter((item): item is PreviewDraft => Boolean(item)); if (!drafts.length) return null; const base = session.fragment(); const constraints = new Map(base.constraints.map((item) => [item.id, item])); const operations = new Map(base.operations.map((item) => [item.id, item])); for (const draft of drafts) { for (const constraint of draft.constraints ?? []) constraints.set(constraint.id, constraint); for (const operation of draft.operations ?? []) operations.set(operation.id, operation); } return { constraints: [...constraints.values()], operations: [...operations.values()] }; }; const settleGroup = (handles: EditHandle[], value: number) => { // Keep individually customised entries intact: the manifest does not expose // a separate scope bit, so the dominant current value is the group's default // and outliers are treated as local overrides. const frequencies = new Map(); for (const handle of handles) { const key = formatParameterValue(handle.value.current); frequencies.set(key, (frequencies.get(key) ?? 0) + 1); } const defaultKey = [...frequencies.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; const changed = handles.filter( (handle) => formatParameterValue(handle.value.current) === defaultKey && !rendersSame(value, handle.value.current), ); if (!changed.length) { abandonGesture(); return; } const draft = draftForGroup(changed, value); if (draft) commitGesture( draft, changed.map((handle) => `constraint:${handle.handleId}`), ); else abandonGesture(); }; 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()); recordEdit(editHistoryRef.current, 'session'); 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(); }; const discardJunctionDraft = () => { 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); } gesture.current = null; panelRef.current?.clearLive(); if (session) previewSession(); setJunctionSession((current) => (current ? cancelJunctionSession(current) : current)); }; /** 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 = () => { const domain = takeUndoDomain(editHistoryRef.current); // 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 (domain === 'signal' && 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; } if (domain !== 'session') return; const reversed = session?.undo({ operationId: `operation:undo:${Date.now()}`, createdAt: new Date().toISOString(), }); if (!reversed) return; touch(); previewSession(); }; const redoEdit = () => { const domain = takeRedoDomain(editHistoryRef.current); if (domain === 'signal' && 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 (domain !== 'session') 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 = []; clearEditHistory(editHistoryRef.current); setSignalDirty(false); clearStaged(); 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); signalSavedRef.current = next.trafficSignals.assemblies.features; 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 compile = async (): Promise => { if (!(await save())) return false; const savedDirectEdits = Boolean(session?.dirty); if (!(await saveDirectEdits(false))) return false; 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 false; } } try { setStatus('正在重新生成...'); const next = await api.compile(); setState(next); signalSavedRef.current = next.trafficSignals.assemblies.features; setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); setPreview(null); setStatus('已保存并重新生成'); return true; } catch (error) { setStatus( savedDirectEdits ? `直接编辑已保存,但重新生成失败:${(error as Error).message}` : `重新生成失败:${(error as Error).message}`, ); return false; } }; if (!state) return ( { const next = await api.import(file); setState(next); signalSavedRef.current = next.trafficSignals.assemblies.features; setStatus(`已导入 ${next.areaId}`); return next; }} /> ); const diagnostics = state.compiled.diagnostics.filter( (item) => item.rule !== 'ordinary-junction-surface' && (filter === 'all' || (filter === 'candidates' ? Boolean(item.manualCandidates?.length) : !item.manualCandidates?.length)), ); const openJunction = (ref: JunctionRef) => { // Seed direct-edit selection with the first approach so the existing // manifest request loads junction shape handles before the workspace opens. const descriptor = state ? hotspotAt(junctionDescriptors(state), ref) : null; const approach = descriptor?.approachRoadIds[0]; if (approach) { const road = state?.compiled.model.roads.find((item) => item.id === approach); if (road) setSelected(road); } window.history.pushState({}, '', `/junction/${ref.type}/${encodeURIComponent(ref.id)}`); setJunctionRoute(ref); }; const closeJunction = () => { if (junctionSession?.dirty || signalDirty) { const choice = window.prompt('路口有未应用草稿:输入 1 应用并返回,2 放弃并返回,3 留在工作区', '3'); if (choice === '3' || !choice) return; if (choice === '1') { if (signalDirty) { setStatus('信号灯草稿仍未保存,请在工作区内完成保存或放弃。'); return; } if (junctionSession) setJunctionSession(applyJunctionDraft(junctionSession)); } else if (choice === '2') { discardJunctionDraft(); } else return; } setJunctionNodeMarkers([]); window.history.pushState({}, '', '/'); setJunctionRoute(null); }; const prepareTopologyChange = (): boolean => { if (!junctionSession?.dirty && !signalDirty) return true; const choice = window.prompt('路口有未应用草稿:输入 1 应用,2 放弃,3 留在工作区', '3'); if (choice === '3' || !choice) return false; if (choice === '1') { if (signalDirty) { setStatus('信号灯草稿仍未保存,请在工作区内完成保存或放弃。'); return false; } setJunctionSession((current) => (current ? applyJunctionDraft(current) : current)); return true; } if (choice === '2') { discardJunctionDraft(); return true; } return false; }; const handleFeature = (properties: Record) => { setMarking(properties); const objectKey = junctionStructure ? junctionObjectKeyForFeature(junctionStructure, properties) : properties.signal_uid ? `signal:${String(properties.signal_uid)}` : properties.crossing_node_id ? `${properties.provenance === 'stop-line' ? 'stop-line' : 'crossing'}:${String(properties.crossing_node_id)}` : properties.road_id ? `road-arm:${String(properties.road_id)}` : null; setSelectedObjectKey(objectKey); // 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('已选中标线,可在右侧暂存样式'); }; 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}
{ openJunction(ref); const approachRoad = descriptor.approachRoadIds .map((roadId) => state.compiled.model.roads.find((road) => road.id === roadId)) .find((road): road is Road => Boolean(road)); if (approachRoad) setSelected(approachRoad); setStatus(ref.type === 'node' ? `已定位路口节点 ${ref.id}(可编辑)` : `已定位路口 ${ref.id}(只读)`); }} onSelectRoad={setSelected} onFeature={handleFeature} signalSelectionUid={marking?.signal_uid == null ? null : String(marking.signal_uid)} onBackground={() => { setElement(null); setMarking(null); setSelectedObjectKey(null); }} onSignalDrag={moveSignal} onSignalDragEnd={finishSignalMove} onSignalRotate={rotateSignal} onSignalRotateEnd={finishSignalRotate} handles={junctionRoute ? junctionHandles : visibleEditHandles} 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={junctionMapPreview} 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); }} />
{junctionRoute && junctionDescriptor && junctionSession ? ( setSelectedObjectKey(key)} 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; if (!prepareTopologyChange()) 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={() => void compile().then((ok) => { // The API checks documentVersion. editRevision is only a render counter // and advances during this save, so it cannot validate its completion. if (ok) setJunctionSession((current) => current?.ref.type === junctionDescriptor.ref.type && current.ref.id === junctionDescriptor.ref.id ? saveJunctionSession(current) : current, ); }) } editMode={editMode} onEnableEdit={() => setEditMode(true)} handles={junctionHandles} onDraft={(handle, value) => { draftValue(handle, value); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); }} onDraftGroup={(handles, value) => { const draft = draftForGroup(handles, value); if (draft) requester?.schedule(draft); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); }} onSettle={(handle, value) => { settleValue(handle, value); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); }} onSettleGroup={settleGroup} onAbandon={abandonGesture} onReset={(handle) => { resetHandle(handle); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); }} previewPending={previewPending} roads={junctionRoads} junctionCoordinate={junctionDescriptor.coordinate} selectedFacility={element} selectedSignalUid={marking?.signal_uid == null ? null : String(marking.signal_uid)} signalUids={state.trafficSignals.assemblies.features .filter((item) => [item.properties?.node_id, item.properties?.control_id].some( (value) => value !== undefined && value !== null && junctionDescriptor.nodeIds.includes(String(value)), ), ) .map((item) => String(item.properties?.signal_uid ?? '')) .filter(Boolean)} onSignalStatus={setStatus} onUpdateSignal={updateSignal} onSelectFacility={(facility) => { setSelectedObjectKey( `${facility.kind === 'crosswalk' ? 'crossing' : facility.kind}:${facility.id.split(':').slice(1).join(':')}`, ); const source = facility.kind === 'crosswalk' ? state.layers.crosswalks : facility.kind === 'stop-line' ? state.layers.vehicleStopLines : state.trafficSignals.assemblies; const feature = source?.features.find((item) => { if (facility.kind === 'signal') return String(item.properties?.signal_uid) === facility.id.slice('signal:'.length); if (facility.crossingKey) return String(item.properties?.crossing_key) === facility.crossingKey; return String(item.properties?.crossing_node_id) === facility.id.split(':').slice(1).join(':'); }); if (feature) handleFeature(feature.properties ?? {}); }} /> ) : null}
); } export default App;