Files
road-compiler/workbench/client/src/App.tsx
T

990 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { 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 { junctionDescriptors, hotspotAt } from './junction/hotspots';
import { JunctionWorkspace } from './junction/JunctionWorkspace';
import {
applyJunctionDraft,
cancelJunctionSession,
createJunctionSession,
saveJunctionSession,
type JunctionSession,
} from './junction/workspace';
const layerLabels: Array<[LayerName, string]> = [
['osm', '方向道路参考线'],
['native', '自研道路与路口面'],
['sidewalks', '路缘与步行带'],
['lanes', '车道与转向路径'],
['directionArrows', '道路方向箭头'],
['markings', '车道分隔线与路口转向箭头'],
['centerLines', '道路中央标线'],
['edgeLines', '道路外缘线'],
['controls', '斑马线与停止线'],
['signals', '红绿灯设施'],
['junctionHotspots', '路口编辑热区'],
];
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));
function App() {
const [state, setState] = useState<WorkbenchState>();
const [selected, setSelected] = useState<Road | null>(null);
const [layers, setLayers] = useState(defaultLayers);
const [scene, setScene] = useState(false);
const [junctionHotspots, setJunctionHotspots] = useState(true);
const [status, setStatus] = useState('正在加载工作台...');
const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all');
const [marking, setMarking] = useState<Record<string, unknown> | null>(null);
const [junctionRoute, setJunctionRoute] = useState<JunctionRef | null>(() => {
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<JunctionSession | null>(null);
const editHistoryRef = useRef<EditHistory>({ 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,
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],
);
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]);
// 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<ElementSelection | null>(null);
const visibleEditHandles = useMemo(() => {
if (!element || element.kind === 'lane-maneuver') return editHandles;
const 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 === constraintKind &&
handle.anchor.type === 'junction-crossing' &&
String(handle.anchor.crossingId) === String(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<ElementOutline | null>(() => {
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<Coordinate[] | null>(() => {
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<Coordinate | null>(() => {
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<ParameterPanelHandle>(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<EditSelection | undefined>(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 = session;
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());
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();
};
/** 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 () => {
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);
signalSavedRef.current = next.trafficSignals.assemblies.features;
setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null);
setPreview(null);
setStatus('已保存并重新生成');
} catch (error) {
setStatus((error as Error).message);
}
};
if (!state)
return (
<ImportScreen
status={status}
onImport={async (file) => {
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) => {
window.history.pushState({}, '', `/junction/${ref.type}/${encodeURIComponent(ref.id)}`);
setJunctionRoute(ref);
};
const closeJunction = () => {
if (junctionSession?.dirty) {
const choice = window.confirm('路口有未应用草稿。确定放弃并返回主地图吗?');
if (!choice) return;
setJunctionSession(cancelJunctionSession(junctionSession));
}
window.history.pushState({}, '', '/');
setJunctionRoute(null);
};
const handleFeature = (properties: Record<string, unknown>) => {
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('已选中标线,可在右侧暂存样式');
};
return (
<>
<header>
<strong>道路编译工作台</strong>
<label className="mode-switch">
<span>浏览</span>
<input
type="checkbox"
role="switch"
aria-label="编辑模式"
checked={editMode}
onChange={(event) => setEditMode(event.target.checked)}
/>
<span>编辑</span>
</label>
<span>{state.areaId}</span>
<span>{status}</span>
<span className={staged.length ? 'dirty' : ''}>
{staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'}
</span>
{editMode ? (
<span className={editDiagnostics.some((item) => 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}` : ''}
</span>
) : null}
<label className="scene">
<input type="checkbox" checked={scene} onChange={(event) => setScene(event.target.checked)} /> 场景效果
</label>
<a className="button" href="/api/export.zip" download>
<Download size={15} /> 导出道路包
</a>
<Button onClick={() => void compile()}>
<RefreshCw size={15} /> 保存并重新生成
</Button>
{editMode ? (
<>
<Button onClick={undoEdit} disabled={!session?.canUndo && !signalUndoRef.current.length}>
撤销
</Button>
<Button onClick={redoEdit} disabled={!session?.canRedo && !signalRedoRef.current.length}>
重做
</Button>
<Button onClick={discardEdits} disabled={!session?.dirty && !staged.length && !signalDirty}>
放弃
</Button>
</>
) : null}
</header>
<main>
<aside className="issues">
<h1>图层</h1>
{layerLabels
.filter(([key]) => key !== 'edgeLines' || Boolean(state.layers.edgeLines?.features.length))
.map(([key, text]) => {
const hiddenInScene = scene && ['osm', 'lanes', 'connectors'].includes(key);
return (
<label key={key}>
<input
type="checkbox"
checked={layers[key]}
disabled={hiddenInScene}
onChange={(event) => setLayers({ ...layers, [key]: event.target.checked })}
/>{' '}
{text}
{hiddenInScene ? '(场景模式中隐藏)' : ''}
</label>
);
})}
<hr />
<details className="issues-details">
<summary>待检查问题({diagnostics.length})</summary>
<div className="issue-tabs" role="tablist" aria-label="问题筛选">
{(['all', 'candidates', 'other'] as const).map((kind) => (
<Button
className={filter === kind ? 'active' : ''}
role="tab"
aria-selected={filter === kind}
onClick={() => setFilter(kind)}
key={kind}
>
{kind === 'all' ? '全部' : kind === 'candidates' ? '可连接' : '其他'}
</Button>
))}
</div>
<ul>
{diagnostics.map((item) => (
<li key={item.id}>
<Button
onClick={() => {
const road = state.compiled.model.roads.find((itemRoad) => itemRoad.id === item.subjectId);
if (road) setSelected(road);
setStatus(item.message);
}}
>
{item.message}
</Button>
</li>
))}
</ul>
</details>
<hr />
<details className="overview-details">
<summary>当前编译概览</summary>
<Overview comparison={state.comparison} />
</details>
</aside>
<MapCanvas
state={state}
editMode={editMode}
selected={selected}
visible={layers}
scene={scene}
junctionHotspots={junctionHotspots}
onJunctionHotspot={(ref: JunctionRef) => {
openJunction(ref);
setStatus(ref.type === 'node' ? `已定位路口节点 ${ref.id}(可编辑)` : `已定位路口 ${ref.id}(只读)`);
}}
onSelectRoad={setSelected}
onFeature={handleFeature}
signalSelectionUid={typeof marking?.signal_uid === 'string' ? marking.signal_uid : null}
onBackground={() => {
setElement(null);
setMarking(null);
}}
onSignalDrag={moveSignal}
onSignalDragEnd={finishSignalMove}
onSignalRotate={rotateSignal}
onSignalRotateEnd={finishSignalRotate}
handles={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={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);
}}
/>
<aside className="inspector">
<WorkbenchInspector
road={selected}
state={state}
staged={staged}
marking={marking}
element={element}
stage={stage}
status={setStatus}
session={session}
onLaneManeuverChange={applyLaneManeuver}
updateSignal={updateSignal}
onAcceptCandidate={(index) =>
void api
.acceptJunctionCandidate(index)
.then((next) => {
setState(next);
signalSavedRef.current = next.trafficSignals.assemblies.features;
setStatus(`已加入 ${next.added.id} 并重新编译`);
})
.catch((error: Error) => setStatus(error.message))
}
>
{editMode ? (
<ParameterPanel
handles={editHandles}
hasSelection={Boolean(selected)}
ref={panelRef}
onDraft={draftValue}
onSettle={settleValue}
onAbandon={abandonGesture}
onReset={resetHandle}
/>
) : null}
</WorkbenchInspector>
</aside>
</main>
{junctionRoute && junctionDescriptor && junctionSession ? (
<JunctionWorkspace
descriptor={junctionDescriptor}
session={junctionSession}
onClose={closeJunction}
onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))}
onDiscard={() => setJunctionSession((current) => (current ? cancelJunctionSession(current) : current))}
onSave={() => {
try {
setJunctionSession((current) => (current ? saveJunctionSession(current, editRevision) : current));
setStatus('路口草稿已保存');
} catch (error) {
setStatus((error as Error).message);
}
}}
/>
) : null}
</>
);
}
export default App;