feat: drag road handles with ghost and server preview

Three things, kept in one commit because they touch overlapping hunks of the
same two files and this environment has no interactive hunk staging. Splitting
them by file would have drawn boundaries that misrepresent what changed.

1. Step 4 of the map editor. A native OpenLayers PointerInteraction turns a
   drag into a clamped constraint value, the ghost source shows it immediately,
   and the solver's answer replaces a parallel set of preview layers while the
   baseline layers are hidden rather than overwritten. Preview requests debounce
   at 80 ms, pointerup flushes without waiting, and a newer request aborts the
   one in flight; EditSession decides which answers count. Handle positions come
   from the clamped value, so a handle stops at its limit instead of following
   the cursor. Three of the four drag capabilities are live: edge offset,
   sidewalk width, lane divider.

2. Road edge handles were drawn on the wrong side. offsetLine() offsets
   counter-clockwise from the direction of travel and sidewalks use
   `heading + (side === 'left' ? -90 : 90)`, so left is `tangent - 90`;
   makeRoadHandles() placed the left handle at `tangent + 90`, over the right
   kerb. Dragging the visually-left handle moved the right edge. Fixed on both
   sides of the wire, with regression tests that name the sides geographically
   rather than by axis sign.

3. Roads the junctions geometrically fill are now read-only. The 0.45 cap per
   reserve made the existing `unavailable` branch unreachable, so a 14.5 m stub
   between two junctions was offered a 1.5 m editable band with no room for the
   transitions a road-interval constraint needs. Greying only affects the
   manifest: constraints already saved against such a road keep being solved, so
   the geometry output is unchanged and the fixture baselines do not move.

Range handles are built and unit-tested but hidden behind
`intervalEditingSupported`: compileGeometry() reads neither profile.interval nor
profile.transitions, so every edit applies to the whole road and the control
would have had no effect. Recorded in research/interval-not-applied.md, which
also blocks one PRD acceptance criterion.

The ol-ext probe stays in the tree as a manual harness; ol-ext is still not a
dependency.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
que01andClaude Opus 5 committed 2026-08-27 17:38:34 +08:00
1 parent bc4b9a9717
commit 92297270f1
25 files changed
+1826 -58

No files matched your search

+150 -13
View File
@@ -1,12 +1,23 @@
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Download, RefreshCw, Save, Upload } from 'lucide-react';
import { api } from './lib/api';
import { MapCanvas } from './components/MapCanvas';
import { directEditEnabled } from './edit/flag';
import { disabledReasonOf, handlesForSegment } from './edit/selection';
import type { HandleManifest } from './edit/types';
import { directEditEnabled, intervalEditingSupported } from './edit/flag';
import { PreviewRequester, type PreviewDraft } from './edit/preview-request';
import { anchorSnapshotFor, constraintValueFor, draftConstraint, 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,
RoadIntervalAnchor,
} from './edit/types';
import { Button } from './ui/button';
import type { GeoFeature, Override, Road, WorkbenchState } from './types/state';
import type { GeoFeature, GeoJson, Override, Road, WorkbenchState } from './types/state';
import type { LayerName } from './map/layers';
const layerLabels: Array<[LayerName, string]> = [
@@ -99,12 +110,21 @@ function App() {
api
.editState()
.then((value) => {
if ('handles' in value) setManifest(value.handles);
if (!('handles' in value)) return;
setManifest(value.handles);
// A drag drafts on top of whatever is already saved, so keep the active
// document's constraints rather than sending a lone constraint.
savedConstraints.current = value.document.constraints;
savedOperations.current = value.document.operations;
})
// 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.
}, [state]);
const editHandles = useMemo(() => {
if (!directEditEnabled || !state) return [];
// Handle anchors carry a directional road id while reserves are keyed by
@@ -116,6 +136,96 @@ function App() {
// 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 (!directEditEnabled || !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, manifest, selected, state]);
const [preview, setPreview] = useState<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
const [editDiagnostics, setEditDiagnostics] = useState<EditDiagnostic[]>([]);
// The working set: the saved document plus whatever this session has drafted.
// Advanced on pointerup, not on every move, so an abandoned drag leaves nothing
// behind — and so a later range drag can re-anchor the edit a value drag made.
const savedConstraints = useRef<RoadConstraint[]>([]);
/** Their operations. A constraint without its operation is rejected as a 400. */
const savedOperations = useRef<RoadEditOperation[]>([]);
const sessionRef = useRef<EditSession | null>(null);
if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession();
const requester = useMemo(() => {
const session = sessionRef.current;
if (!session) return null;
return new PreviewRequester({
session,
send: (request, signal) => api.editPreview(request, 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}`),
});
}, []);
/** A drag becomes one drafted constraint layered over the saved document. */
const draftFor = (handle: EditHandle, value: number): PreviewDraft | null => {
const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : null;
const road = roadId ? state?.compiled.model.roads.find((item) => item.id === roadId) : undefined;
// 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 (!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}`,
operationId: `operation:${handle.handleId}`,
createdAt: new Date().toISOString(),
},
);
const operation = operationFor(constraint);
// 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: [...savedConstraints.current.filter((item) => item.id !== constraint.id), constraint],
operations: [...savedOperations.current.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 onRoad = (item: RoadConstraint) =>
item.anchor.type === 'road-interval' && item.anchor.roadId === range.roadId;
if (!savedConstraints.current.some(onRoad)) return null;
return {
constraints: savedConstraints.current.map((item) =>
onRoad(item)
? { ...item, anchor: { ...item.anchor, startStation: anchor.startStation, endStation: anchor.endStation } }
: item,
),
operations: savedOperations.current,
};
};
/** Both drag kinds commit their result here so the next drag builds on it. */
const advance = (draft: PreviewDraft | null) => {
if (!draft) return;
savedConstraints.current = draft.constraints ?? savedConstraints.current;
savedOperations.current = draft.operations ?? savedOperations.current;
};
const stage = (change: Override) =>
setStaged((current) => [...current.filter((item) => item.id !== change.id), change]);
const save = async () => {
@@ -180,12 +290,13 @@ function App() {
{staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'}
</span>
{directEditEnabled ? (
<span>
{editHandles.length
? `手柄 ${editHandles.length} 个`
: selected
? '当前道路无可编辑手柄'
: '选中道路以显示手柄'}
<span className={editDiagnostics.some((item) => item.severity === 'error') ? 'dirty' : ''}>
{editDiagnostics.find((item) => item.severity === 'error')?.message ||
(editHandles.length
? `手柄 ${editHandles.length} 个`
: selected
? '当前道路无可编辑手柄'
: '选中道路以显示手柄')}
{blockedReason ? `|${blockedReason}` : ''}
</span>
) : null}
@@ -251,6 +362,32 @@ function App() {
onSelectRoad={setSelected}
onFeature={handleFeature}
handles={editHandles}
ranges={editRanges}
preview={preview}
onHandleDrag={(handle, value) => {
const draft = draftFor(handle, value);
if (draft) requester?.schedule(draft);
}}
onHandleDragEnd={(handle, value) => {
const draft = draftFor(handle, value);
if (!draft) return;
requester?.flush(draft);
advance(draft);
}}
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;
}
requester?.flush(draft);
advance(draft);
}}
/>
<Inspector
road={selected}