feat: add direct edit handles behind directEdit flag

Steps 1-3 of the main map road interval editor.

EditSession keeps the command stack, undo/redo and previewSeq arbitration as
pure logic with no OpenLayers reference, so all of it is unit-tested in node.
Pointer displacement converts to meters through EPSG:4326 and spherical
distance: treating a 3857 delta as meters desyncs the geometry from the cursor
by 1/cos(latitude). Handle drags project onto the axis the manifest declares
and clamp to its range, so the client never writes a coordinate into a road
polygon.

All of it sits behind a directEdit flag that defaults to off. With the flag off
the workbench requests no manifest, creates no extra source and registers no
interaction, so behaviour matches main.

The ol-ext probe passed its three gates but is not adopted for road handles.
Transform translates by the raw pointer delta, so a handle detaches from its
clamped constraint value: a drag reading -24.1 m produced a draft of -5.4 m.
Production needs the handle position derived from the constraint instead, which
means owning the position update, so native OL PointerInteraction will carry
the drag. ol-ext stays out of package.json; the probe is kept as a manual
harness. Reserve handles are unreachable with the current solver, recorded in
research/ rather than worked around.

Also names the dead backend when an API response is empty, instead of
surfacing "Unexpected end of JSON input" from response.json().

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
que01andClaude Opus 5 committed 2026-08-27 14:59:11 +08:00
1 parent e25c564bb9
commit bc4b9a9717
25 files changed
+2463 -22

No files matched your search

+179
View File
@@ -0,0 +1,179 @@
// Handle drag -> constraint value. The only place a pointer position becomes a
// number the server will solve with.
//
// Nothing here touches OpenLayers or geometry output: a drag is projected onto
// the axis the manifest declared, converted to meters, clamped to the manifest's
// own range, and packaged as a `native-road-edits/v2` value. The client never
// writes a coordinate into a road polygon.
import { clamp, haversineMeters, polylineLengthMeters, signedMetersAlongAxis, type Coordinate } from './meters';
import type {
AnchorSnapshot,
ConstraintValue,
EditHandle,
JunctionReserve,
RoadConstraint,
RoadIntervalAnchor,
Transition,
} from './types';
/** Smallest interval the range handles may collapse to, in normalized station. */
export const MIN_INTERVAL_STATION = 0.02;
export interface IntervalWindow {
minStation: number;
maxStation: number;
}
/**
* Turns "along axisAzimuth" into "outward" for a handle.
*
* `makeRoadHandles()` places the left handle at `tangent + 90` and the right one
* at `tangent - 90`, but reports `axisAzimuth = tangent + 90` for both. Since a
* positive `offsetMeters` / `widthMeters` always widens the road, a right-side
* drag measured along that axis has to be negated. Lane dividers are the
* exception: their offset is a signed lateral position already measured along
* the same axis, so the raw projection is the value.
*/
function outwardSign(handle: EditHandle): number {
if (handle.kind === 'road-lane-divider') return 1;
const side = 'side' in handle.anchor ? handle.anchor.side : undefined;
return side === 'right' ? -1 : 1;
}
/**
* The scalar a drag produces for `handle`, clamped to the range the manifest
* declared. `from` / `to` are EPSG:3857 map coordinates.
*/
export function projectHandleValue(handle: EditHandle, from: Coordinate, to: Coordinate): number {
const delta = signedMetersAlongAxis(from, to, handle.axisAzimuth) * outwardSign(handle);
return clamp(handle.value.current + delta, handle.value.min, handle.value.max);
}
/** The manifest hangs `boundaryIndex` on the anchor; the document needs it in `value`. */
function boundaryIndexOf(handle: EditHandle): number {
const index = 'boundaryIndex' in handle.anchor ? handle.anchor.boundaryIndex : undefined;
if (!Number.isInteger(index) || (index as number) < 1)
throw new Error(`handle ${handle.handleId} is a lane divider without an anchor boundaryIndex`);
return index as number;
}
/** Packages a projected scalar as the `value` the server validates. */
export function constraintValueFor(
handle: EditHandle,
scalar: number,
transition: Transition = 'smoothstep',
): ConstraintValue {
switch (handle.kind) {
case 'road-edge-offset':
return { offsetMeters: scalar, transition };
case 'road-sidewalk-width':
return { widthMeters: Math.max(0, scalar), transition };
case 'road-lane-divider':
return { boundaryIndex: boundaryIndexOf(handle), offsetMeters: scalar, transition };
case 'junction-approach-width':
return { widthMeters: Math.max(0, scalar) };
case 'junction-cutback':
return { cutbackMeters: Math.max(0, scalar) };
case 'junction-corner-radius':
return { radiusMeters: Math.max(0, scalar) };
}
}
/**
* The station range a road interval may occupy, i.e. everything outside the
* junction reserves. Mirrors the window `makeRoadHandles()` centres its handles
* in. `reserves` are keyed by segment id, not by directional road id.
*/
export function reserveWindow(reserves: JunctionReserve[], segmentId: string): IntervalWindow {
let minStation = 0;
let maxStation = 1;
for (const reserve of reserves) {
if (reserve.roadId !== segmentId) continue;
if (reserve.fromStation <= 0) minStation = Math.max(minStation, reserve.toStation);
else maxStation = Math.min(maxStation, reserve.fromStation);
}
return { minStation, maxStation };
}
/** True when the station sits inside a junction reserve, where the main map may not edit. */
export function insideReserve(reserves: JunctionReserve[], segmentId: string, station: number): boolean {
return reserves.some(
(reserve) => reserve.roadId === segmentId && station >= reserve.fromStation && station <= reserve.toStation,
);
}
/**
* Moves one end of the affected interval. The dragged end stays inside the
* reserve-free window and never crosses the other end, so the solver always
* receives `startStation < endStation` and both ends keep a transition back to
* the baseline.
*/
export function projectIntervalEnd(
anchor: RoadIntervalAnchor,
end: 'start' | 'end',
from: Coordinate,
to: Coordinate,
tangentAzimuth: number,
roadLengthMeters: number,
window: IntervalWindow,
): RoadIntervalAnchor {
if (!(roadLengthMeters > 0)) return anchor;
const deltaStation = signedMetersAlongAxis(from, to, tangentAzimuth) / roadLengthMeters;
if (end === 'start') {
const limit = Math.max(window.minStation, anchor.endStation - MIN_INTERVAL_STATION);
return { ...anchor, startStation: clamp(anchor.startStation + deltaStation, window.minStation, limit) };
}
const limit = Math.min(window.maxStation, anchor.startStation + MIN_INTERVAL_STATION);
return { ...anchor, endStation: clamp(anchor.endStation + deltaStation, limit, window.maxStation) };
}
/**
* Evidence a later reimport uses to relocate this anchor. `centerline` is the
* road's EPSG:4326 centerline from the compiled model.
*/
export function anchorSnapshotFor(handle: EditHandle, centerline: Coordinate[], osmNodeIds: string[]): AnchorSnapshot {
return {
coordinate: [handle.position[0], handle.position[1]],
tangentAzimuth: (((handle.axisAzimuth - 90) % 360) + 360) % 360,
roadLengthMeters: polylineLengthMeters(centerline) || haversineMeters(centerline[0], centerline.at(-1)!) || 1,
osmNodeIds: [...osmNodeIds],
};
}
export interface DraftIdentity {
constraintId: string;
operationId: string;
createdAt: string;
author?: string;
}
/**
* Builds the constraint a drag drafts. `anchor` is passed separately so a range
* drag can widen the interval while the value stays put, and vice versa.
*
* A drafted constraint is always `exact`: it was just authored against the model
* currently on screen. Only a reimport or a compiler upgrade can demote it.
*/
export function draftConstraint(
handle: EditHandle,
anchor: RoadConstraint['anchor'],
value: ConstraintValue,
snapshot: AnchorSnapshot,
identity: DraftIdentity,
): RoadConstraint {
return {
id: handle.constraintId || identity.constraintId,
kind: handle.kind,
anchor,
anchorSnapshot: snapshot,
value,
enabled: true,
status: 'exact',
provenance: {
operationId: identity.operationId,
createdAt: identity.createdAt,
...(identity.author ? { author: identity.author } : {}),
},
};
}