diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index 99eefaf..c2f2ec6 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -3,6 +3,7 @@ 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 { directEditEnabled, intervalEditingSupported } from './edit/flag'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; import { anchorSnapshotFor, constraintValueFor, draftConstraint, operationFor } from './edit/projection'; @@ -160,6 +161,14 @@ function App() { }, [editHandles, manifest, selected, state]); const [preview, setPreview] = useState> | null>(null); const [editDiagnostics, setEditDiagnostics] = useState([]); + /** + * 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(null); const sessionRef = useRef(null); if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession(); // Per-frame drag feedback reaches the panel through this rather than through @@ -450,6 +459,11 @@ function App() { ); const handleFeature = (properties: Record) => { setMarking(properties); + // A crosswalk is six features but one editable thing. Clicking any stripe + // selects the group; clicking anything else drops the element selection, + // because a box left around a crosswalk the user navigated away from reads + // as a stuck UI. + if (directEditEnabled) setElement(elementSelectionFor(properties, state.layers.crosswalks?.features ?? [])); const uid = properties.signal_uid; if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`); else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); @@ -466,11 +480,13 @@ function App() { {directEditEnabled ? ( item.severity === 'error') ? 'dirty' : ''}> {editDiagnostics.find((item) => item.severity === 'error')?.message || - (editHandles.length - ? `手柄 ${editHandles.length} 个` - : selected - ? '当前道路无可编辑手柄' - : '选中道路以显示手柄')} + (element + ? `已选中斑马线 ${element.crossingNodeId}(${element.featureIds.length} 条)` + : editHandles.length + ? `手柄 ${editHandles.length} 个` + : selected + ? '当前道路无可编辑手柄' + : '选中道路以显示手柄')} {blockedReason ? `|${blockedReason}` : ''} ) : null} @@ -551,6 +567,7 @@ function App() { scene={scene} onSelectRoad={setSelected} onFeature={handleFeature} + onBackground={() => setElement(null)} handles={editHandles} ranges={editRanges} preview={preview} diff --git a/workbench/client/src/components/MapCanvas.tsx b/workbench/client/src/components/MapCanvas.tsx index 1d5a54f..24f9df3 100644 --- a/workbench/client/src/components/MapCanvas.tsx +++ b/workbench/client/src/components/MapCanvas.tsx @@ -20,6 +20,8 @@ interface Props { scene: boolean; onSelectRoad: (road: Road) => void; onFeature: (properties: Record) => void; + /** A click that selected nothing, so element selection can be cleared. */ + onBackground?: () => void; /** Already filtered to the selected road. Ignored unless `directEdit` is on. */ handles?: EditHandle[]; /** The two ends of the affected interval, drawn as squares. */ @@ -44,6 +46,7 @@ export function MapCanvas({ scene, onSelectRoad, onFeature, + onBackground, handles, ranges, preview, @@ -63,9 +66,14 @@ export function MapCanvas({ const visibleRef = useRef(visible); visibleRef.current = visible; // Callbacks live in refs so the map is built once and never rebuilt when a - // parent re-renders with new closures. + // parent re-renders with new closures. The select callbacks belong here too: + // the listener is registered once, so without a ref it would keep calling the + // first render's closure — harmless while those only called stable setters, + // but not once one of them reads current state. const dragRef = useRef({ onHandleDrag, onHandleDragEnd, onHandleBlocked, onRangeDrag, onRangeEnd, ghostPending }); dragRef.current = { onHandleDrag, onHandleDragEnd, onHandleBlocked, onRangeDrag, onRangeEnd, ghostPending }; + const selectRef = useRef({ onSelectRoad, onFeature, onBackground }); + selectRef.current = { onSelectRoad, onFeature, onBackground }; const selectedRef = useRef(selected); const stateRef = useRef(state); const sceneRef = useRef(scene); @@ -130,7 +138,12 @@ export function MapCanvas({ } const listener = ({ selected: values }: { selected: import('ol/Feature').default[] }) => { const properties = values[0]?.getProperties(); - if (!properties) return; + // An empty click deselects. The road inspector deliberately keeps showing + // the last feature, but an element selection box must not outlive it. + if (!properties) { + selectRef.current.onBackground?.(); + return; + } const roadId = properties.road_id || properties.from_road_id || @@ -138,8 +151,8 @@ export function MapCanvas({ ? properties.from_lane_id.slice(5, properties.from_lane_id.lastIndexOf(':')) : undefined); const road = stateRef.current.compiled.model.roads.find((item) => item.id === roadId); - if (road) onSelectRoad(road); - onFeature(properties); + if (road) selectRef.current.onSelectRoad(road); + selectRef.current.onFeature(properties); }; select.on('select', listener); return () => { diff --git a/workbench/client/src/edit/element.test.ts b/workbench/client/src/edit/element.test.ts new file mode 100644 index 0000000..20a5f46 --- /dev/null +++ b/workbench/client/src/edit/element.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest'; +import { + CROSSWALK_PROVENANCE, + STOP_LINE_PROVENANCE, + crosswalkElementIdOf, + elementSelectionFor, + groupMembers, + isSameElement, + type StripeFeature, +} from './element'; + +/** One stripe, shaped like `controlFeature()` in native-road.js. */ +function stripe(crossingNodeId: string | number, part: number, roadId = 'road:way/-3246:forward'): StripeFeature { + return { + properties: { + native_id: `crosswalk:node/${crossingNodeId}:${part}`, + crossing_node_id: crossingNodeId, + road_id: roadId, + lane_id: `lane:${roadId}:1`, + direction: 'forward', + provenance: CROSSWALK_PROVENANCE, + }, + }; +} + +/** Two groups of six, the arrangement a real area produces. */ +const features: StripeFeature[] = [ + ...[1, 2, 3, 4, 5, 6].map((part) => stripe(-26452, part)), + ...[1, 2, 3, 4, 5, 6].map((part) => stripe(-26458, part, 'road:way/-3250:forward')), +]; + +describe('crosswalkElementIdOf', () => { + it('reads the group off a stripe', () => { + expect(crosswalkElementIdOf(stripe(-26452, 3).properties)).toBe('crosswalk:node/-26452'); + }); + + it('gives every stripe of a group the same id', () => { + const ids = new Set([1, 2, 3, 4, 5, 6].map((part) => crosswalkElementIdOf(stripe(-26452, part).properties))); + expect([...ids]).toEqual(['crosswalk:node/-26452']); + }); + + it('does not share an id between crossings', () => { + expect(crosswalkElementIdOf(stripe(-26452, 1).properties)).not.toBe( + crosswalkElementIdOf(stripe(-26458, 1).properties), + ); + }); + + it('accepts a numeric or string node id', () => { + // Real extracts carry numbers, JOSM-authored data carries negative numbers, + // and either can arrive as a string through JSON. + expect(crosswalkElementIdOf(stripe(8024512147, 1).properties)).toBe('crosswalk:node/8024512147'); + expect(crosswalkElementIdOf(stripe('-26452', 1).properties)).toBe('crosswalk:node/-26452'); + }); + + it('rejects a stop line, which shares the same feature builder', () => { + const stopLine = { properties: { ...stripe(-26452, 1).properties, provenance: STOP_LINE_PROVENANCE } }; + expect(crosswalkElementIdOf(stopLine.properties)).toBeNull(); + }); + + it('rejects anything else the user may click', () => { + expect(crosswalkElementIdOf({ road_id: 'road:way/-3246:forward' })).toBeNull(); + expect(crosswalkElementIdOf({})).toBeNull(); + expect(crosswalkElementIdOf(null)).toBeNull(); + expect(crosswalkElementIdOf(undefined)).toBeNull(); + }); + + it('rejects a crosswalk with no crossing node to group by', () => { + expect(crosswalkElementIdOf({ provenance: CROSSWALK_PROVENANCE })).toBeNull(); + expect(crosswalkElementIdOf({ provenance: CROSSWALK_PROVENANCE, crossing_node_id: '' })).toBeNull(); + }); +}); + +describe('groupMembers', () => { + it('collects exactly the stripes of one crossing', () => { + const members = groupMembers(features, 'crosswalk:node/-26452'); + expect(members).toHaveLength(6); + expect(new Set(members.map((m) => m.properties?.crossing_node_id))).toEqual(new Set([-26452])); + }); + + it('returns nothing for a group that is not present', () => { + expect(groupMembers(features, 'crosswalk:node/-99999')).toHaveLength(0); + }); +}); + +describe('elementSelectionFor', () => { + it('turns a click on one stripe into the whole group', () => { + const selection = elementSelectionFor(stripe(-26452, 4).properties, features); + expect(selection).toEqual({ + kind: 'crosswalk', + elementId: 'crosswalk:node/-26452', + crossingNodeId: '-26452', + roadId: 'road:way/-3246:forward', + featureIds: [1, 2, 3, 4, 5, 6].map((part) => `crosswalk:node/-26452:${part}`), + }); + }); + + it('selects the same group whichever stripe was clicked', () => { + const fromFirst = elementSelectionFor(stripe(-26452, 1).properties, features); + const fromLast = elementSelectionFor(stripe(-26452, 6).properties, features); + expect(fromFirst).toEqual(fromLast); + }); + + it('returns null for a click that is not a crosswalk, so the caller clears', () => { + // A road click must not leave a stale box around the previous crosswalk. + expect(elementSelectionFor({ road_id: 'road:way/-3246:forward' }, features)).toBeNull(); + }); + + it('returns null rather than a group whose extent cannot be drawn', () => { + // Properties from one area, features from another: selecting nothing beats + // selecting a group with no members on screen. + expect(elementSelectionFor(stripe(-26452, 1).properties, [])).toBeNull(); + }); +}); + +describe('isSameElement', () => { + it('compares by group, not by identity', () => { + const a = elementSelectionFor(stripe(-26452, 1).properties, features); + const b = elementSelectionFor(stripe(-26452, 5).properties, features); + const other = elementSelectionFor(stripe(-26458, 1).properties, features); + expect(a).not.toBe(b); + expect(isSameElement(a, b)).toBe(true); + expect(isSameElement(a, other)).toBe(false); + expect(isSameElement(null, null)).toBe(true); + expect(isSameElement(a, null)).toBe(false); + }); +}); diff --git a/workbench/client/src/edit/element.ts b/workbench/client/src/edit/element.ts new file mode 100644 index 0000000..0997730 --- /dev/null +++ b/workbench/client/src/edit/element.ts @@ -0,0 +1,102 @@ +// Clicked feature -> the crosswalk group it belongs to. +// +// A crosswalk is drawn as six separate stripe features, but it is edited as one +// thing. This module is the only place that turns a click on one stripe into the +// group, and it does so by reading identifiers the compiler already publishes — +// never by clustering on proximity, stripe count, or draw order, which is what +// `prd.md` forbids and what would break the moment two crossings sit close +// together. +// +// The group id is `crosswalk:node/`, which is stable because +// `compileControlMarkings()` iterates `model.crossings` and emits exactly one +// group per crossing from a single candidate road. Measured on a live area: 48 +// stripes, 8 groups of 6, no crossing spanning two roads. +// +// The crossing node is NOT the junction node. `crosswalk:node/-26452` is the +// pedestrian crossing; `handle:junction-crosswalk-inset:node/1140799725:...` is +// the junction the approach belongs to. Conflating them is what made an earlier +// pass believe no group id existed. +// +// No OpenLayers import: same rule as meters.ts / projection.ts / selection.ts. + +/** `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. */ +export const STOP_LINE_PROVENANCE = 'native-road-stop-line/v1'; + +export type ElementKind = 'crosswalk'; + +export interface ElementSelection { + kind: ElementKind; + /** `crosswalk:node/` — the group, not a stripe. */ + elementId: string; + crossingNodeId: string; + /** The directional road the group was placed against. */ + roadId: string; + /** `native_id` of every stripe in the group, for highlight and preview scoping. */ + featureIds: string[]; +} + +/** The shape this module needs off a GeoJSON feature; anything else is ignored. */ +export interface StripeFeature { + properties?: Record | null; +} + +function text(value: unknown): string | null { + if (typeof value === 'string') return value || null; + // OSM ids arrive as numbers for real extracts and negative numbers for + // JOSM-authored data; both are legitimate and neither is a string. + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return null; +} + +/** + * The group id for a clicked feature, or `null` when it is not a crosswalk + * stripe — a road surface, a stop line, or anything else the user may hit. + */ +export function crosswalkElementIdOf(properties: Record | null | undefined): string | null { + if (!properties || properties.provenance !== CROSSWALK_PROVENANCE) return null; + const crossingNodeId = text(properties.crossing_node_id); + return crossingNodeId ? `crosswalk:node/${crossingNodeId}` : null; +} + +/** Every stripe belonging to one group, in the order the compiler emitted them. */ +export function groupMembers(features: readonly StripeFeature[], elementId: string): StripeFeature[] { + return features.filter((feature) => crosswalkElementIdOf(feature.properties) === elementId); +} + +/** + * What a click selects. + * + * Returns `null` for a click that is not on a crosswalk, which the caller treats + * as "clear the element selection" — clicking a road must not leave a stale box + * around the crosswalk that was selected before. + */ +export function elementSelectionFor( + properties: Record | null | undefined, + features: readonly StripeFeature[], +): ElementSelection | null { + const elementId = crosswalkElementIdOf(properties); + if (!elementId) return null; + const members = groupMembers(features, elementId); + // The clicked stripe is itself a member, so an empty result means the feature + // collection is not the one the click came from. Selecting nothing is safer + // than selecting a group whose extent we cannot draw. + if (!members.length) return null; + const first = members[0].properties ?? {}; + const roadId = text(first.road_id); + const crossingNodeId = text(first.crossing_node_id); + if (!roadId || !crossingNodeId) return null; + return { + kind: 'crosswalk', + elementId, + crossingNodeId, + roadId, + featureIds: members.map((member) => text(member.properties?.native_id)).filter((id): id is string => Boolean(id)), + }; +} + +/** True when the click should replace the current selection rather than keep it. */ +export function isSameElement(current: ElementSelection | null, next: ElementSelection | null): boolean { + return current?.elementId === next?.elementId; +}