diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index c2f2ec6..fa2f876 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -3,8 +3,16 @@ 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 { elementSelectionFor, type ElementSelection } from './edit/element'; +import { + crosswalkHandleFor, + elementSelectionFor, + groupMembers, + orientedBoundsOf, + type ElementSelection, +} from './edit/element'; import { directEditEnabled, intervalEditingSupported } from './edit/flag'; +import type { ElementOutline } from './edit/handle-layer'; +import { rendersSame } from './edit/parameter'; 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'; @@ -169,6 +177,20 @@ function App() { * element box and its controls hang off this. */ const [element, setElement] = useState(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(() => { + if (!directEditEnabled || !element || !state) return null; + const handle = crosswalkHandleFor(element, state.compiled.model.roads, editHandles); + if (!handle?.editable) return null; + const bounds = orientedBoundsOf(groupMembers(state.layers.crosswalks?.features ?? [], element.elementId)); + return bounds ? { handleId: handle.handleId, bounds } : null; + }, [element, editHandles, state]); const sessionRef = useRef(null); if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession(); // Per-frame drag feedback reaches the panel through this rather than through @@ -301,6 +323,14 @@ function App() { }; /** 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(); @@ -570,6 +600,7 @@ function App() { onBackground={() => setElement(null)} handles={editHandles} ranges={editRanges} + element={elementOutline} preview={preview} ghostPending={session?.degraded ?? false} onHandleDrag={(handle, value) => { diff --git a/workbench/client/src/components/MapCanvas.tsx b/workbench/client/src/components/MapCanvas.tsx index 24f9df3..7d5a248 100644 --- a/workbench/client/src/components/MapCanvas.tsx +++ b/workbench/client/src/components/MapCanvas.tsx @@ -8,7 +8,7 @@ import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from ' import { directEditEnabled } from '../edit/flag'; import { createHandleDragInteraction } from '../edit/drag-interaction'; import { EditGhostLayer } from '../edit/ghost-layer'; -import { EditHandleLayer } from '../edit/handle-layer'; +import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer'; import { EditPreviewLayer } from '../edit/preview-layer'; import type { IntervalRangeHandle } from '../edit/selection'; import type { EditHandle, PreviewLayerName, RoadIntervalAnchor } from '../edit/types'; @@ -26,6 +26,8 @@ interface Props { handles?: EditHandle[]; /** The two ends of the affected interval, drawn as squares. */ ranges?: IntervalRangeHandle[]; + /** The selected element's box, grabbable as the control that moves it. */ + element?: ElementOutline | null; /** Authoritative preview geometry; null returns the map to the baseline. */ preview?: Partial> | null; /** Live value during a drag — the caller debounces the preview request. */ @@ -49,6 +51,7 @@ export function MapCanvas({ onBackground, handles, ranges, + element, preview, onHandleDrag, onHandleDragEnd, @@ -179,8 +182,8 @@ export function MapCanvas({ useEffect(() => { // Null when the flag is off, so this whole path is inert on main. // Only the editHandles source is replaced; baseline layers are never touched. - handleLayerRef.current?.render(handles ?? [], ranges ?? []); - }, [handles, ranges]); + handleLayerRef.current?.render(handles ?? [], ranges ?? [], element ?? null); + }, [handles, ranges, element]); useEffect(() => { // A non-degraded answer means the pending ghost has been superseded by real // geometry. Clearing an empty ghost is a no-op, so this is safe mid-drag. diff --git a/workbench/client/src/edit/element.test.ts b/workbench/client/src/edit/element.test.ts index 20a5f46..a77876b 100644 --- a/workbench/client/src/edit/element.test.ts +++ b/workbench/client/src/edit/element.test.ts @@ -1,11 +1,14 @@ import { describe, expect, it } from 'vitest'; +import { azimuthBetween, haversineMeters, offsetCoordinate } from './meters'; import { CROSSWALK_PROVENANCE, STOP_LINE_PROVENANCE, crosswalkElementIdOf, + crosswalkHandleFor, elementSelectionFor, groupMembers, isSameElement, + orientedBoundsOf, type StripeFeature, } from './element'; @@ -112,6 +115,119 @@ describe('elementSelectionFor', () => { }); }); +describe('crosswalkHandleFor', () => { + const roads = [ + { id: 'road:way/-3256:backward', segmentId: 'segment:way/-3256/0', sourceNodeIds: ['9', '1140799725'] }, + { id: 'road:way/-3256:forward', segmentId: 'segment:way/-3256/0', sourceNodeIds: ['9', '1140799919'] }, + ]; + // The measured shape: one segment, two junctions, therefore two handles. + const handles = [ + { kind: 'junction-crosswalk-inset', anchor: { segmentId: 'segment:way/-3256/0', nodeId: '1140799725' } }, + { kind: 'junction-crosswalk-inset', anchor: { segmentId: 'segment:way/-3256/0', nodeId: '1140799919' } }, + { kind: 'junction-stop-line-offset', anchor: { segmentId: 'segment:way/-3256/0', nodeId: '1140799725' } }, + ]; + const select = (roadId: string) => + crosswalkHandleFor( + { kind: 'crosswalk', elementId: 'e', crossingNodeId: 'c', roadId, featureIds: [] }, + roads, + handles, + ); + + it('picks the junction the group actually sits at, not just the segment', () => { + // 15 of 23 segments carry two of these handles; segment alone would move the + // wrong zebra half the time. + expect(select('road:way/-3256:backward')?.anchor.nodeId).toBe('1140799725'); + expect(select('road:way/-3256:forward')?.anchor.nodeId).toBe('1140799919'); + }); + + it('separates two groups sharing one segment by their directional road', () => { + expect(select('road:way/-3256:backward')).not.toBe(select('road:way/-3256:forward')); + }); + + it('does not return a stop-line handle at the same junction', () => { + expect(select('road:way/-3256:backward')?.kind).toBe('junction-crosswalk-inset'); + }); + + it('returns null when the road or handle is missing', () => { + expect(select('road:way/-9999:forward')).toBeNull(); + expect( + crosswalkHandleFor( + { kind: 'crosswalk', elementId: 'e', crossingNodeId: 'c', roadId: roads[0].id, featureIds: [] }, + roads, + [], + ), + ).toBeNull(); + }); + + it('compares node ids across string and number forms', () => { + const numeric = [{ kind: 'junction-crosswalk-inset', anchor: { segmentId: 'segment:s', nodeId: 1140799725 } }]; + const road = [{ id: 'r', segmentId: 'segment:s', sourceNodeIds: ['1140799725'] }]; + expect( + crosswalkHandleFor( + { kind: 'crosswalk', elementId: 'e', crossingNodeId: 'c', roadId: 'r', featureIds: [] }, + road, + numeric, + ), + ).not.toBeNull(); + }); +}); + +describe('orientedBoundsOf', () => { + /** A stripe 3m along the axis and 0.45m across, offset sideways. */ + function stripeAt(azimuthDeg: number, sideOffset: number): StripeFeature { + const origin: [number, number] = [114.1774, 30.495]; + const centre = offsetCoordinate(origin, azimuthDeg + 90, sideOffset); + const corners: [number, number][] = [ + [-1.5, -0.225], + [1.5, -0.225], + [1.5, 0.225], + [-1.5, 0.225], + ].map(([along, across]) => offsetCoordinate(offsetCoordinate(centre, azimuthDeg, along), azimuthDeg + 90, across)); + return { properties: {}, geometry: { type: 'Polygon', coordinates: [[...corners, corners[0]]] } }; + } + + const members = [0, 0.9, 1.8, 2.7, 3.6, 4.5].map((offset) => stripeAt(30, offset - 2.25)); + + it('returns four corners hugging the group', () => { + const bounds = orientedBoundsOf(members); + expect(bounds).toHaveLength(4); + const [a, b, c, d] = bounds!; + // Corners run (minAlong,minAcross) -> (max,min) -> (max,max) -> (min,max): + // 3m along the axis, and six stripes at 0.9m pitch spanning 4.5m + 0.45m. + expect(haversineMeters(a, b)).toBeCloseTo(3, 1); + expect(haversineMeters(a, d)).toBeCloseTo(4.95, 1); + // Opposite sides equal and the diagonal obeys Pythagoras, i.e. a rectangle + // rather than four points that merely span the right extents. + expect(haversineMeters(c, d)).toBeCloseTo(haversineMeters(a, b), 1); + expect(haversineMeters(b, c)).toBeCloseTo(haversineMeters(a, d), 1); + expect(haversineMeters(b, d)).toBeCloseTo(Math.hypot(3, 4.95), 1); + }); + + it('orients the box along the stripes, not along north', () => { + const [a, b] = orientedBoundsOf(members)!; + // Stripes were built at azimuth 30; the box's long-edge direction follows. + const azimuth = azimuthBetween(a, b); + expect(Math.min(Math.abs(azimuth - 30), Math.abs(azimuth - 210))).toBeLessThan(1); + }); + + it('follows the crosswalk angle rather than latitude and longitude', () => { + // An axis-aligned box would have identical extents whatever the angle; an + // oriented one keeps the same 3m x 4.95m no matter how the zebra is turned. + for (const azimuth of [0, 30, 75, 120]) { + const rotated = [0, 0.9, 1.8, 2.7, 3.6, 4.5].map((offset) => stripeAt(azimuth, offset - 2.25)); + const [a, b, , d] = orientedBoundsOf(rotated)!; + expect(haversineMeters(a, b)).toBeCloseTo(3, 1); + expect(haversineMeters(a, d)).toBeCloseTo(4.95, 1); + } + }); + + it('returns null when there is no drawable geometry', () => { + expect(orientedBoundsOf([])).toBeNull(); + expect(orientedBoundsOf([{ properties: {} }])).toBeNull(); + expect(orientedBoundsOf([{ properties: {}, geometry: { type: 'Point', coordinates: [1, 2] } }])).toBeNull(); + }); +}); + describe('isSameElement', () => { it('compares by group, not by identity', () => { const a = elementSelectionFor(stripe(-26452, 1).properties, features); diff --git a/workbench/client/src/edit/element.ts b/workbench/client/src/edit/element.ts index 0997730..00e95f0 100644 --- a/workbench/client/src/edit/element.ts +++ b/workbench/client/src/edit/element.ts @@ -19,6 +19,8 @@ // // No OpenLayers import: same rule as meters.ts / projection.ts / selection.ts. +import { azimuthBetween, eastNorthMeters, haversineMeters, offsetCoordinate, type Coordinate } from './meters'; + /** `provenance` the compiler stamps on every crosswalk stripe. */ export const CROSSWALK_PROVENANCE = 'native-road-crosswalk/v1'; /** Stop lines share `controlFeature()`; kept so the two are never confused. */ @@ -40,6 +42,14 @@ export interface ElementSelection { /** The shape this module needs off a GeoJSON feature; anything else is ignored. */ export interface StripeFeature { properties?: Record | null; + geometry?: { type?: string; coordinates?: unknown } | null; +} + +/** The road fields needed to resolve which junction a group belongs to. */ +export interface RoadRef { + id: string; + segmentId: string; + sourceNodeIds: readonly (string | number)[]; } function text(value: unknown): string | null { @@ -100,3 +110,108 @@ export function elementSelectionFor( export function isSameElement(current: ElementSelection | null, next: ElementSelection | null): boolean { return current?.elementId === next?.elementId; } + +/** + * The `junction-crosswalk-inset` handle that moves this group. + * + * Segment alone is not enough: 15 of 23 segments in a measured area carry two + * such handles, one per junction at either end, and one segment carried two + * crosswalk groups. Picking by segment would move the wrong zebra half the time. + * + * The junction is the road's last source node — which is not a guess but the + * rule the compiler itself applies, in `crossingJunctionInset()`: + * `candidate.road.sourceNodeIds.at(-1)`. Verified to resolve 8/8 groups + * uniquely on a live area, including the segment carrying two groups, where the + * directional road tells them apart. + */ +export function crosswalkHandleFor }>( + element: ElementSelection, + roads: readonly RoadRef[], + handles: readonly T[], +): T | null { + const road = roads.find((item) => item.id === element.roadId); + const nodeId = road?.sourceNodeIds.at(-1); + if (!road || nodeId === undefined) return null; + return ( + handles.find( + (handle) => + handle.kind === 'junction-crosswalk-inset' && + handle.anchor.segmentId === road.segmentId && + String(handle.anchor.nodeId) === String(nodeId), + ) ?? null + ); +} + +/** A ring's corner coordinates, dropping the repeated closing point. */ +function ringOf(feature: StripeFeature): Coordinate[] { + const coordinates = feature.geometry?.coordinates; + if (!Array.isArray(coordinates) || !Array.isArray(coordinates[0])) return []; + const ring = coordinates[0] as unknown[]; + const points = ring.filter( + (point): point is Coordinate => + Array.isArray(point) && point.length >= 2 && Number.isFinite(point[0]) && Number.isFinite(point[1]), + ); + // GeoJSON repeats the first point to close the ring; it carries no extra extent. + if (points.length > 1 && points[0][0] === points.at(-1)?.[0] && points[0][1] === points.at(-1)?.[1]) + return points.slice(0, -1); + return points; +} + +/** + * The four corners of a selection box hugging the group, oriented along the + * crosswalk rather than along latitude and longitude. + * + * An axis-aligned box would sit askew around a zebra that crosses at any angle, + * which reads as a bug rather than as a selection. The axis comes from the + * longest edge of a stripe: stripes are rectangles built along the approach, so + * their long side *is* the approach direction. + * + * This derives an outline, never a value. Position, range and size all still come + * from the server — the same line `selection.ts` draws for range handles, and the + * reason `design.md` allows the box to be computed here at all. + */ +export function orientedBoundsOf(members: readonly StripeFeature[]): Coordinate[] | null { + const rings = members.map(ringOf).filter((ring) => ring.length >= 3); + if (!rings.length) return null; + const first = rings[0]; + // Longest edge of one stripe: its direction is the approach the group follows. + let axisAzimuth = 0; + let longest = -1; + for (let index = 0; index < first.length; index += 1) { + const from = first[index]; + const to = first[(index + 1) % first.length]; + const length = haversineMeters(from, to); + if (length > longest) { + longest = length; + axisAzimuth = azimuthBetween(from, to); + } + } + const origin = first[0]; + const across = axisAzimuth + 90; + const toRadians = (degrees: number) => (degrees * Math.PI) / 180; + const axisVector = [Math.sin(toRadians(axisAzimuth)), Math.cos(toRadians(axisAzimuth))]; + const acrossVector = [Math.sin(toRadians(across)), Math.cos(toRadians(across))]; + let minAlong = Infinity; + let maxAlong = -Infinity; + let minAcross = Infinity; + let maxAcross = -Infinity; + for (const ring of rings) + for (const point of ring) { + const { east, north } = eastNorthMeters(origin, point); + const along = east * axisVector[0] + north * axisVector[1]; + const side = east * acrossVector[0] + north * acrossVector[1]; + minAlong = Math.min(minAlong, along); + maxAlong = Math.max(maxAlong, along); + minAcross = Math.min(minAcross, side); + maxAcross = Math.max(maxAcross, side); + } + if (!Number.isFinite(minAlong) || !Number.isFinite(minAcross)) return null; + const corner = (along: number, side: number) => + offsetCoordinate(offsetCoordinate(origin, axisAzimuth, along), across, side); + return [ + corner(minAlong, minAcross), + corner(maxAlong, minAcross), + corner(maxAlong, maxAcross), + corner(minAlong, maxAcross), + ]; +} diff --git a/workbench/client/src/edit/handle-layer.ts b/workbench/client/src/edit/handle-layer.ts index fa87998..2e3d9c5 100644 --- a/workbench/client/src/edit/handle-layer.ts +++ b/workbench/client/src/edit/handle-layer.ts @@ -10,6 +10,7 @@ import Feature from 'ol/Feature'; import Point from 'ol/geom/Point'; +import Polygon from 'ol/geom/Polygon'; import VectorLayer from 'ol/layer/Vector'; import VectorSource from 'ol/source/Vector'; import CircleStyle from 'ol/style/Circle'; @@ -17,13 +18,25 @@ import Fill from 'ol/style/Fill'; import Stroke from 'ol/style/Stroke'; import RegularShape from 'ol/style/RegularShape'; import Style from 'ol/style/Style'; -import { fromLonLat } from './meters'; +import { fromLonLat, type Coordinate } from './meters'; import { disabledReasonOf, type IntervalRangeHandle } from './selection'; import type { EditHandle } from './types'; /** The only property a handle feature carries. */ export const HANDLE_ID = 'handleId'; +/** + * The selected element, as something to draw and grab. + * + * `handleId` is the id of the control that moves the element, not a new one: + * dragging the box has to be the same gesture as dragging that control. + */ +export interface ElementOutline { + handleId: string; + /** Four corners, EPSG:4326, oriented along the element. */ + bounds: Coordinate[]; +} + const EDITABLE_STYLE: Record = { 'road-edge-offset': handleStyle('#00a5cf'), 'road-sidewalk-width': handleStyle('#d49318'), @@ -57,6 +70,17 @@ const DISABLED_STYLE = new Style({ }), }); +/** + * The selected element's outline. + * + * Dashed, with a faint fill — the fill is not decoration: OpenLayers hit-tests + * rendered pixels, so a fully transparent interior could not be grabbed. + */ +const ELEMENT_STYLE = new Style({ + stroke: new Stroke({ color: '#2f8f5b', width: 2, lineDash: [6, 4] }), + fill: new Fill({ color: 'rgba(47, 143, 91, 0.12)' }), +}); + function handleStyle(color: string): Style { return new Style({ image: new CircleStyle({ @@ -72,6 +96,7 @@ export class EditHandleLayer { private readonly source = new VectorSource(); private index = new Map(); private ranges = new Map(); + private elementIds = new Set(); constructor() { this.layer = new VectorLayer({ @@ -80,6 +105,7 @@ export class EditHandleLayer { zIndex: 100, style: (feature) => { const id = String(feature.get(HANDLE_ID)); + if (this.elementIds.has(id)) return ELEMENT_STYLE; if (this.ranges.has(id)) return RANGE_STYLE; const handle = this.index.get(id); if (!handle) return undefined; @@ -93,12 +119,22 @@ export class EditHandleLayer { * * Range ends live in the same source because design.md allots the map three * edit sources, not four — they are still handles, just handles that move the - * anchor rather than the value. + * anchor rather than the value. The element outline is here for the same + * reason, and it carries the `handleId` of the control that moves it, so + * grabbing the box is the same gesture as grabbing that control's dot. */ - render(handles: EditHandle[], ranges: IntervalRangeHandle[] = []): void { + render(handles: EditHandle[], ranges: IntervalRangeHandle[] = [], element: ElementOutline | null = null): void { this.index = new Map(handles.map((handle) => [handle.handleId, handle])); this.ranges = new Map(ranges.map((range) => [range.handleId, range])); + this.elementIds = new Set(element ? [element.handleId] : []); this.source.clear(); + if (element) + this.source.addFeatures([ + new Feature({ + geometry: new Polygon([[...element.bounds, element.bounds[0]].map(fromLonLat)]), + [HANDLE_ID]: element.handleId, + }), + ]); this.source.addFeatures( [...handles, ...ranges].map( (handle) => @@ -113,6 +149,7 @@ export class EditHandleLayer { clear(): void { this.index = new Map(); this.ranges = new Map(); + this.elementIds = new Set(); this.source.clear(); }