1598 lines
64 KiB
TypeScript
1598 lines
64 KiB
TypeScript
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<string, unknown> }) {
|
||
const severity = comparison.diagnosticsBySeverity as Record<string, number> | undefined;
|
||
return (
|
||
<section className="overview">
|
||
<div className="overview-grid">
|
||
{overviewMetrics.map(([key, label]) => (
|
||
<div key={key}>
|
||
<span>{label}</span>
|
||
<strong>{Number(comparison[key] || 0).toLocaleString('zh-CN')}</strong>
|
||
</div>
|
||
))}
|
||
</div>
|
||
{severity && (
|
||
<div className="overview-diagnostics">
|
||
<span>编译诊断</span>
|
||
{Object.entries(severity).map(([level, count]) => (
|
||
<strong key={level}>
|
||
{level === 'error' ? '错误' : level === 'warning' ? '警告' : '提示'} {count}
|
||
</strong>
|
||
))}
|
||
</div>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|
||
function App() {
|
||
const [state, setState] = useState<WorkbenchState>();
|
||
const [selected, setSelected] = useState<Road | null>(null);
|
||
const [staged, setStaged] = useState<Override[]>([]);
|
||
const [signalDirty, setSignalDirty] = useState(false);
|
||
const signalDraftRef = useRef<GeoFeature[] | null>(null);
|
||
const signalUndoRef = useRef<GeoFeature[][]>([]);
|
||
const signalRedoRef = useRef<GeoFeature[][]>([]);
|
||
const signalSavedRef = useRef<GeoFeature[] | null>(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<Record<string, unknown> | 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<HandleManifest | null>(null);
|
||
/** Which compiled document the session already adopted, so a re-fetch cannot discard edits. */
|
||
const loadedDocument = useRef<string | null>(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<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
|
||
const [editDiagnostics, setEditDiagnostics] = useState<EditDiagnostic[]>([]);
|
||
const sessionRef = useRef<EditSession | null>(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<ElementSelection | null>(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<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 } : 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 = 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 (
|
||
<ImportScreen
|
||
status={status}
|
||
onImported={(next) => {
|
||
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<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('已选中标线,可在右侧暂存样式');
|
||
};
|
||
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 (
|
||
<>
|
||
<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 save()} disabled={!staged.length}>
|
||
<Save size={15} /> 保存修改
|
||
</Button>
|
||
<Button onClick={() => void compile()}>
|
||
<RefreshCw size={15} /> 保存并重新生成
|
||
</Button>
|
||
{editMode ? (
|
||
<>
|
||
<Button onClick={() => void saveDirectEdits()} disabled={!session?.dirty}>
|
||
<Save size={15} /> 保存直接编辑
|
||
</Button>
|
||
<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}
|
||
onSelectRoad={setSelected}
|
||
onFeature={handleFeature}
|
||
onBackground={() => 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);
|
||
}}
|
||
/>
|
||
<aside className="inspector">
|
||
<Inspector
|
||
road={selected}
|
||
state={state}
|
||
staged={staged}
|
||
marking={marking}
|
||
element={element}
|
||
stage={stage}
|
||
status={setStatus}
|
||
setState={setState}
|
||
session={session}
|
||
onLaneManeuverChange={applyLaneManeuver}
|
||
updateSignal={updateSignal}
|
||
>
|
||
{editMode ? (
|
||
<ParameterPanel
|
||
handles={editHandles}
|
||
hasSelection={Boolean(selected)}
|
||
ref={panelRef}
|
||
onDraft={draftValue}
|
||
onSettle={settleValue}
|
||
onAbandon={abandonGesture}
|
||
onReset={resetHandle}
|
||
/>
|
||
) : null}
|
||
</Inspector>
|
||
</aside>
|
||
</main>
|
||
</>
|
||
);
|
||
}
|
||
function ImportScreen({ status, onImported }: { status: string; onImported: (state: WorkbenchState) => void }) {
|
||
const [file, setFile] = useState<File>();
|
||
const [busy, setBusy] = useState(false);
|
||
return (
|
||
<section className="import-screen">
|
||
<form
|
||
onSubmit={async (event) => {
|
||
event.preventDefault();
|
||
if (!file) return;
|
||
setBusy(true);
|
||
try {
|
||
onImported(await api.import(file));
|
||
} catch (error) {
|
||
console.error(error);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}}
|
||
>
|
||
<h1>导入 OSM 地图</h1>
|
||
<p>{status}</p>
|
||
<input
|
||
type="file"
|
||
accept=".osm,application/xml,text/xml"
|
||
onChange={(event) => setFile(event.target.files?.[0])}
|
||
required
|
||
/>
|
||
<Button type="submit" disabled={!file || busy}>
|
||
<Upload size={16} /> {busy ? '正在导入并编译...' : '导入并编译'}
|
||
</Button>
|
||
</form>
|
||
</section>
|
||
);
|
||
}
|
||
function Inspector({
|
||
road,
|
||
state,
|
||
staged,
|
||
marking,
|
||
element,
|
||
stage,
|
||
status,
|
||
setState,
|
||
session,
|
||
onLaneManeuverChange,
|
||
updateSignal,
|
||
children,
|
||
}: {
|
||
road: Road | null;
|
||
state: WorkbenchState;
|
||
staged: Override[];
|
||
marking: Record<string, unknown> | 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<void>;
|
||
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<typeof open>) => () => setOpen((current) => (current === name ? null : name));
|
||
const selectedLabel =
|
||
element?.kind === 'lane-maneuver'
|
||
? `第 ${laneIndex(element.laneId)} 车道`
|
||
: marking
|
||
? '已选标线或设施'
|
||
: road
|
||
? label(road)
|
||
: '未选择对象';
|
||
return (
|
||
<section className="workbench-inspector">
|
||
<div className="inspector-summary">
|
||
<span>编辑工作台</span>
|
||
<strong>{selectedLabel}</strong>
|
||
<small>{staged.length ? `已暂存 ${staged.length} 项修改` : '没有待保存的覆盖修改'}</small>
|
||
</div>
|
||
<InspectorSection
|
||
title="道路"
|
||
summary={road ? `${road.laneCount} 车道` : '选择道路'}
|
||
open={open === 'road'}
|
||
onToggle={section('road')}
|
||
>
|
||
{road ? (
|
||
<form
|
||
onSubmit={(event) => {
|
||
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>道路</label>
|
||
<output>
|
||
{label(road)}({direction(road)})
|
||
</output>
|
||
<output>
|
||
{movements.length
|
||
? `已识别 ${movements.length} 个行驶动作,${movements.filter((item) => item.geometryPublished).length} 条已绘制路径`
|
||
: '当前方向没有已识别的行驶动作'}
|
||
</output>
|
||
<label>
|
||
本方向道路宽度(米)
|
||
<input
|
||
type="number"
|
||
min="1"
|
||
step="0.01"
|
||
value={width}
|
||
onChange={(event) => setWidth(Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
本方向车道数
|
||
<input
|
||
type="number"
|
||
min="1"
|
||
step="1"
|
||
value={lanes}
|
||
onChange={(event) => setLanes(Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
<input type="checkbox" checked={left} onChange={(event) => setLeft(event.target.checked)} />{' '}
|
||
左侧有路缘与步行带
|
||
</label>
|
||
<label>
|
||
<input type="checkbox" checked={right} onChange={(event) => setRight(event.target.checked)} />{' '}
|
||
右侧有路缘与步行带
|
||
</label>
|
||
<Button type="submit">暂存本道路修改</Button>
|
||
</form>
|
||
) : (
|
||
<p>点击道路、车道、标线、转向路径或路口面以查看详情。</p>
|
||
)}
|
||
{children}
|
||
</InspectorSection>
|
||
<InspectorSection
|
||
title="元素"
|
||
summary={element ? selectedLabel : '箭头、标线与信号'}
|
||
open={open === 'element'}
|
||
onToggle={section('element')}
|
||
>
|
||
<LaneManeuverEditor
|
||
element={element}
|
||
value={
|
||
element?.kind === 'lane-maneuver'
|
||
? (session
|
||
?.constraints()
|
||
.find(
|
||
(item) =>
|
||
item.kind === 'lane-maneuver' &&
|
||
item.anchor.type === 'lane' &&
|
||
item.anchor.laneId === element.laneId,
|
||
)?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined)
|
||
: undefined
|
||
}
|
||
onChange={onLaneManeuverChange}
|
||
/>
|
||
<MarkingEditor marking={marking} stage={stage} />
|
||
<SignalEditor state={state} signal={signal} status={status} update={updateSignal} />
|
||
</InspectorSection>
|
||
<InspectorSection
|
||
title="连接"
|
||
summary={road ? `${movements.length} 个行驶动作` : '选择道路'}
|
||
open={open === 'connections'}
|
||
onToggle={section('connections')}
|
||
>
|
||
{road ? (
|
||
<div className="connections-list">
|
||
{state.compiled.model.connections
|
||
.filter((connection) => connection.fromEndpointId === endpoint?.id)
|
||
.map((connection) => (
|
||
<label key={connection.id}>
|
||
<input
|
||
type="checkbox"
|
||
checked={effective(`连接:${connection.id}`, connection.enabled)}
|
||
onChange={(event) =>
|
||
stage({
|
||
id: `连接:${connection.id}`,
|
||
kind: 'junction-connection',
|
||
fromEndpointId: connection.fromEndpointId,
|
||
toEndpointId: connection.toEndpointId,
|
||
enabled: event.target.checked,
|
||
})
|
||
}
|
||
/>{' '}
|
||
{connection.id}
|
||
</label>
|
||
))}
|
||
{movements.map((movement) => (
|
||
<label key={movement.id}>
|
||
<input
|
||
type="checkbox"
|
||
checked={effective(`车道连接:${movement.fromLaneId}->${movement.toLaneId}`, true)}
|
||
onChange={(event) =>
|
||
stage({
|
||
id: `车道连接:${movement.fromLaneId}->${movement.toLaneId}`,
|
||
kind: 'lane-connection',
|
||
fromLaneId: movement.fromLaneId,
|
||
toLaneId: movement.toLaneId,
|
||
enabled: event.target.checked,
|
||
})
|
||
}
|
||
/>{' '}
|
||
{movement.turn}:第 {laneIndex(movement.fromLaneId)} 车道 → 第 {laneIndex(movement.toLaneId)} 车道(
|
||
{movement.geometryStatus || 'connector'})
|
||
</label>
|
||
))}
|
||
</div>
|
||
) : (
|
||
<p className="form-context">选择一条道路以管理其驶入路口的连接。</p>
|
||
)}
|
||
{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 ? (
|
||
<Button
|
||
key={candidate.roadId}
|
||
onClick={() => {
|
||
stage({
|
||
id: `连接:connection:${endpoint.id}:${targetEndpoint.id}`,
|
||
kind: 'junction-connection',
|
||
fromEndpointId: endpoint.id,
|
||
toEndpointId: targetEndpoint.id,
|
||
enabled: true,
|
||
});
|
||
status('手工连接已暂存;保存并重新生成后会出现转向路径');
|
||
}}
|
||
>
|
||
新增:{label(target)}({candidate.distanceMeters} 米)
|
||
</Button>
|
||
) : null;
|
||
})}
|
||
</InspectorSection>
|
||
<InspectorSection title="高级" summary="候选与来源" open={open === 'advanced'} onToggle={section('advanced')}>
|
||
<Candidates state={state} setState={setState} status={status} />
|
||
<details>
|
||
<summary>技术详情与来源</summary>
|
||
<pre>
|
||
{JSON.stringify(
|
||
road ? { OSM道路: road.osmWayIds, 当前方向节点顺序: road.sourceNodeIds, 原始标签: road.tags } : marking,
|
||
null,
|
||
2,
|
||
)}
|
||
</pre>
|
||
</details>
|
||
</InspectorSection>
|
||
</section>
|
||
);
|
||
}
|
||
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 (
|
||
<form className="element-form">
|
||
<h2>车道转向箭头</h2>
|
||
<p className="form-context">第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。</p>
|
||
<label>
|
||
转向
|
||
<select value={maneuver} onChange={(event) => onChange(event.target.value, placementDistanceMeters)}>
|
||
{MANEUVER_OPTIONS.map(([value, label]) => (
|
||
<option value={value} key={value}>
|
||
{label}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label>
|
||
距路口端(米)
|
||
<input
|
||
type="number"
|
||
min="0"
|
||
step="0.25"
|
||
value={placementDistanceMeters}
|
||
onChange={(event) => {
|
||
const next = Number(event.target.value);
|
||
if (Number.isFinite(next) && next >= 0) onChange(maneuver, next);
|
||
}}
|
||
/>
|
||
</label>
|
||
<p className="form-hint">保存并重新生成时会避开停止线、斑马线和车道端点。</p>
|
||
</form>
|
||
);
|
||
}
|
||
function MarkingEditor({
|
||
marking,
|
||
stage,
|
||
}: {
|
||
marking: Record<string, unknown> | 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 (
|
||
<form
|
||
className="element-form"
|
||
onSubmit={(event) => {
|
||
event.preventDefault();
|
||
save();
|
||
}}
|
||
>
|
||
<h2>标线样式</h2>
|
||
<label>
|
||
样式
|
||
<select
|
||
value={value}
|
||
onChange={(event) => {
|
||
setValue(event.target.value);
|
||
}}
|
||
>
|
||
<option value="yellow-dashed">黄色虚线</option>
|
||
<option value="white-dashed">白色虚线</option>
|
||
<option value="yellow-solid">黄色实线</option>
|
||
<option value="white-solid">白色实线</option>
|
||
{segment ? <option value="double-yellow-solid">双黄实线</option> : null}
|
||
</select>
|
||
</label>
|
||
<Button type="submit">暂存标线样式</Button>
|
||
</form>
|
||
);
|
||
}
|
||
function SignalEditor({
|
||
state,
|
||
signal,
|
||
status,
|
||
update,
|
||
}: {
|
||
state: WorkbenchState;
|
||
signal?: GeoFeature;
|
||
status: (text: string) => void;
|
||
update: (features: GeoFeature[]) => Promise<void>;
|
||
}) {
|
||
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 (
|
||
<section className="element-form">
|
||
<h2>原生红绿灯</h2>
|
||
<label>
|
||
检查信号灯
|
||
<select value={selected} onChange={(event) => setSelected(event.target.value)}>
|
||
<option value="">选择设施</option>
|
||
{state.trafficSignals.assemblies.features.map((item) => (
|
||
<option key={String(item.properties?.signal_uid)} value={String(item.properties?.signal_uid)}>
|
||
{String(item.properties?.display_id || item.properties?.signal_uid)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
{feature ? (
|
||
<>
|
||
<label>
|
||
灯杆经度
|
||
<input
|
||
type="number"
|
||
step="0.000001"
|
||
value={coordinates?.[0] ?? 0}
|
||
onChange={(event) => saveCoordinate(0, Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
灯杆纬度
|
||
<input
|
||
type="number"
|
||
step="0.000001"
|
||
value={coordinates?.[1] ?? 0}
|
||
onChange={(event) => saveCoordinate(1, Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
横杆方向(度)
|
||
<input
|
||
type="number"
|
||
value={Number(feature.properties?.mast_heading_deg || 0)}
|
||
onChange={(event) => saveField('mast_heading_deg', Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
横杆长度(米)
|
||
<input
|
||
type="number"
|
||
value={Number(feature.properties?.mast_reach_m || 0)}
|
||
onChange={(event) => saveField('mast_reach_m', Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
灯面朝向(度)
|
||
<input
|
||
type="number"
|
||
value={Number(feature.properties?.face_heading_deg || 0)}
|
||
onChange={(event) => saveField('face_heading_deg', Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<label>
|
||
相位组
|
||
<select
|
||
value={Number(feature.properties?.phase_group || 0)}
|
||
onChange={(event) => saveField('phase_group', Number(event.target.value))}
|
||
>
|
||
<option value={0}>组 0</option>
|
||
<option value={1}>组 1</option>
|
||
</select>
|
||
</label>
|
||
<label>
|
||
高程偏移(米)
|
||
<input
|
||
type="number"
|
||
step="0.1"
|
||
min="-20"
|
||
max="100"
|
||
value={Number(feature.properties?.z_offset_m || 0)}
|
||
onChange={(event) => saveField('z_offset_m', Number(event.target.value))}
|
||
/>
|
||
</label>
|
||
<p className="form-hint">
|
||
控制进口:{String(feature.properties?.approach_id || '未绑定')}
|
||
<br />
|
||
来源道路:{String(feature.properties?.source_way_id || '未绑定')}
|
||
</p>
|
||
<label>
|
||
<input
|
||
type="checkbox"
|
||
checked={Boolean(feature.properties?.enabled)}
|
||
onChange={(event) => saveField('enabled', event.target.checked)}
|
||
/>{' '}
|
||
启用
|
||
</label>
|
||
<Button
|
||
onClick={() =>
|
||
void update(state.trafficSignals.assemblies.features.filter((item) => item !== feature)).then(() => {
|
||
setSelected('');
|
||
status('红绿灯已删除');
|
||
})
|
||
}
|
||
>
|
||
删除信号灯
|
||
</Button>
|
||
</>
|
||
) : null}
|
||
</section>
|
||
);
|
||
}
|
||
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 (
|
||
<section>
|
||
<hr />
|
||
<h2>复杂路口候选(debug)</h2>
|
||
{candidates.map((candidate) => (
|
||
<Button
|
||
key={candidate.id}
|
||
onClick={() =>
|
||
void api
|
||
.acceptJunctionCandidate(candidate.index)
|
||
.then((next) => {
|
||
setState(next);
|
||
status(`已加入 ${next.added.id} 并重新编译`);
|
||
})
|
||
.catch((error: Error) => status(error.message))
|
||
}
|
||
>
|
||
加入候选 #{candidate.index}({candidate.nodeCount} 节点,{candidate.diameterMeters} 米)
|
||
</Button>
|
||
))}
|
||
</section>
|
||
);
|
||
}
|
||
export default App;
|