diff --git a/src/compile/direct-edit-solver.js b/src/compile/direct-edit-solver.js index c01b0ae..0e991d2 100644 --- a/src/compile/direct-edit-solver.js +++ b/src/compile/direct-edit-solver.js @@ -27,6 +27,7 @@ const SOLVED_KINDS = new Set([ 'junction-crosswalk-inset', 'junction-crosswalk-size', 'junction-stop-line-offset', + 'lane-maneuver', ]); const KINDS = [ 'road-edge-offset', @@ -38,7 +39,17 @@ const KINDS = [ 'junction-crosswalk-inset', 'junction-crosswalk-size', 'junction-stop-line-offset', + 'lane-maneuver', ]; +const SUPPORTED_MANEUVERS = new Set([ + '', + 'through', + 'left', + 'right', + 'through;left', + 'through;right', + 'through;left;right', +]); const MIN_LANE_WIDTH_METERS = 2.4; // Bounds for the control-marking offsets. The crosswalk may sit anywhere from the // junction boundary out to a few metres; the stop line must stay clear of the @@ -214,6 +225,15 @@ function snapshotCandidates(model, constraint) { return roads; } +function roadForLaneAnchor(model, laneAnchorId) { + if (typeof laneAnchorId !== 'string') return null; + for (const road of model.roads || []) { + const count = Number(road.laneCount) || 0; + for (let index = 1; index <= count; index += 1) if (laneId(road.id, index) === laneAnchorId) return road; + } + return null; +} + function reconcileConstraints(model, constraints, base, junctionData, context) { const versionChanged = Boolean( context.compilerGeometryVersion && @@ -224,6 +244,12 @@ function reconcileConstraints(model, constraints, base, junctionData, context) { if (!constraint.enabled || !constraint.anchor || !['exact', 'recheck'].includes(constraint.status)) return constraint; let matched = false; + if (constraint.kind === 'lane-maneuver') { + if (!roadForLaneAnchor(model, constraint.anchor.laneId)) + return { ...constraint, status: 'stale', replayReason: 'anchor-missing' }; + if (versionChanged) return { ...constraint, status: 'recheck' }; + return constraint; + } if (constraint.kind.startsWith('road-')) { const road = roadForAnchor(model, constraint.anchor.roadId); matched = Boolean(road); @@ -537,6 +563,7 @@ function applyJunctionConstraint(model, constraint, junctionPlans, junctionData, function solveConstraints(model, constraints, junctionData, diagnostics) { const roadProfiles = new Map(); const junctionPlans = new Map(); + const laneManeuvers = new Map(); const states = []; for (const constraint of constraints) { if (!constraint.enabled) { @@ -564,6 +591,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics) { }, ]), ); + const laneSnapshot = new Map(laneManeuvers); const junctionSnapshot = new Map( [...junctionPlans].map(([key, plan]) => [ key, @@ -574,18 +602,44 @@ function solveConstraints(model, constraints, junctionData, diagnostics) { }, ]), ); - const applied = constraint.kind.startsWith('road-') - ? applyRoadConstraint(model, constraint, roadProfiles, diagnostics) - : applyJunctionConstraint(model, constraint, junctionPlans, junctionData, diagnostics); + let applied; + if (constraint.kind === 'lane-maneuver') { + const laneId = constraint.anchor?.laneId; + const laneExists = Boolean(roadForLaneAnchor(model, laneId)); + const maneuver = constraint.value?.maneuver; + const placement = constraint.value?.placementDistanceMeters; + if (!laneExists) { + blocking(diagnostics, constraint, 'direct-edit-lane-anchor-missing', '导向箭头车道锚点不存在。'); + applied = false; + } else if (!SUPPORTED_MANEUVERS.has(maneuver)) { + blocking(diagnostics, constraint, 'direct-edit-lane-maneuver-invalid', '导向箭头 maneuver 不受支持。'); + applied = false; + } else if (placement !== undefined && (!Number.isFinite(placement) || placement < 0)) { + blocking(diagnostics, constraint, 'direct-edit-lane-placement-invalid', '导向箭头位置必须是非负米数。'); + applied = false; + } else { + laneManeuvers.set(laneId, { + maneuver, + ...(placement === undefined ? {} : { placementDistanceMeters: placement }), + }); + applied = true; + } + } else { + applied = constraint.kind.startsWith('road-') + ? applyRoadConstraint(model, constraint, roadProfiles, diagnostics) + : applyJunctionConstraint(model, constraint, junctionPlans, junctionData, diagnostics); + } if (!applied) { roadProfiles.clear(); for (const [key, profile] of roadSnapshot) roadProfiles.set(key, profile); junctionPlans.clear(); for (const [key, plan] of junctionSnapshot) junctionPlans.set(key, plan); + laneManeuvers.clear(); + for (const [key, value] of laneSnapshot) laneManeuvers.set(key, value); } states.push(constraintState(constraint, applied, applied ? null : 'invalid')); } - return { roadProfiles, junctionPlans, states }; + return { roadProfiles, junctionPlans, laneManeuvers, states }; } function roadAffects(roads, model, side, boundaryIndex) { @@ -717,6 +771,38 @@ function makeRoadHandles(model, groups, reserves, constraints, roadProfiles) { return handles; } +function makeLaneManeuverHandles(model, constraints) { + const handles = []; + for (const road of model.roads || []) { + const laneCount = Number(road.laneCount) || 0; + const length = polylineLength(road.centerline); + if (!(length > 0) || road.centerline.length < 2) continue; + for (let index = 1; index <= laneCount; index += 1) { + const laneAnchorId = laneId(road.id, index); + const constraint = constraints.find( + (item) => item.kind === 'lane-maneuver' && item.anchor?.type === 'lane' && item.anchor.laneId === laneAnchorId, + ); + const value = constraint?.value || {}; + const placement = Number.isFinite(value.placementDistanceMeters) ? value.placementDistanceMeters : 6; + const station = Math.max(0, Math.min(1, 1 - placement / length)); + const position = coordinateAt(road.centerline, station); + const axis = tangentAzimuth(road.centerline, station); + handles.push({ + handleId: `handle:lane-maneuver:${laneAnchorId}`, + kind: 'lane-maneuver', + anchor: { type: 'lane', laneId: laneAnchorId, roadId: road.id }, + position, + axisAzimuth: axis, + value: { current: placement, min: 0, max: length, unit: 'meter' }, + ...(constraint ? { constraintId: constraint.id } : {}), + affects: [`turn-arrow:${laneAnchorId}`], + editable: true, + }); + } + } + return handles; +} + function junctionAffects(model, nodeId, segmentIds) { const roads = (model.roads || []).filter((road) => segmentIds.has(road.segmentId)); const ids = [junctionSurfaceId(nodeId), ...roadAffects(roads, model)]; @@ -927,6 +1013,9 @@ function selectHandles(handles, model, selection) { // they name their segment directly. Junction *shape* kinds stay out: those // are JunctionTools', and the main map must not offer a second way in. if (CONTROL_KINDS.has(handle.kind)) return handle.anchor.segmentId === wanted; + if (handle.kind === 'lane-maneuver') { + return handle.anchor?.type === 'lane' && segmentOf.get(handle.anchor.roadId) === wanted; + } return handle.kind.startsWith('road-') && segmentOf.get(handle.anchor.roadId) === wanted; }); } @@ -950,6 +1039,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {}) [ ...makeRoadHandles(model || {}, groups, handles.reserves, reconciled, solved.roadProfiles), ...makeJunctionHandles(model || {}, junctionData, reconciled), + ...makeLaneManeuverHandles(model || {}, reconciled), ], model || {}, context.selection, @@ -958,6 +1048,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {}) schema: RESOLUTION_SCHEMA, roadProfiles: solved.roadProfiles, junctionPlans: solved.junctionPlans, + laneManeuvers: solved.laneManeuvers, handles, constraintStates: solved.states, diagnostics, @@ -979,5 +1070,6 @@ module.exports = { KINDS, GEOMETRY_VERSION, roadEdgeOffsetRange, + SUPPORTED_MANEUVERS, resolveDirectEditConstraints, }; diff --git a/src/compile/native-road-edits.js b/src/compile/native-road-edits.js index 0bc584c..e9c009a 100644 --- a/src/compile/native-road-edits.js +++ b/src/compile/native-road-edits.js @@ -18,9 +18,10 @@ const CONSTRAINT_ANCHORS = { 'junction-crosswalk-inset': 'junction-approach', 'junction-crosswalk-size': 'junction-approach', 'junction-stop-line-offset': 'junction-approach', + 'lane-maneuver': 'lane', }; const CONSTRAINT_KINDS = Object.freeze(Object.keys(CONSTRAINT_ANCHORS)); -const ANCHOR_TYPES = new Set(['road-station', 'road-interval', 'junction-approach', 'junction-corner']); +const ANCHOR_TYPES = new Set(['road-station', 'road-interval', 'junction-approach', 'junction-corner', 'lane']); const CONSTRAINT_STATUSES = new Set(['exact', 'recheck', 'pending', 'conflicted', 'stale']); const TRANSITIONS = new Set(['smoothstep', 'linear']); const SIDES = new Set(['left', 'right']); @@ -80,6 +81,8 @@ function validateAnchor(scope, kind, anchor) { requireString(scope, 'anchor.nodeId', anchor.nodeId); requireString(scope, 'anchor.incomingRoadId', anchor.incomingRoadId); requireString(scope, 'anchor.outgoingRoadId', anchor.outgoingRoadId); + } else if (expected === 'lane') { + requireString(scope, 'anchor.laneId', anchor.laneId); } } @@ -134,6 +137,15 @@ function validateValue(scope, kind, value) { // line on the crosswalk itself. if (!isFiniteNumber(value.offsetMeters) || value.offsetMeters <= 0) fail(scope, 'value.offsetMeters', 'must be a positive number of meters'); + } else if (kind === 'lane-maneuver') { + const supported = new Set(['', 'through', 'left', 'right', 'through;left', 'through;right', 'through;left;right']); + if (typeof value.maneuver !== 'string' || !supported.has(value.maneuver)) + fail(scope, 'value.maneuver', `must be one of ${[...supported].filter(Boolean).join(', ')} or an empty string`); + if ( + value.placementDistanceMeters !== undefined && + (!isFiniteNumber(value.placementDistanceMeters) || value.placementDistanceMeters < 0) + ) + fail(scope, 'value.placementDistanceMeters', 'must be a non-negative number of meters'); } } diff --git a/src/compile/native-road.js b/src/compile/native-road.js index f71ec39..bee74fd 100644 --- a/src/compile/native-road.js +++ b/src/compile/native-road.js @@ -54,14 +54,6 @@ const DEFAULT_SIDEWALK_WIDTH_METERS = 2; // The maneuvers `turn-lane-arrows.js` has templates for. `normalizeManeuver()` // returns unknown input unchanged rather than failing, so an override has to be // checked here — it cannot lean on normalisation to reject a typo. -const SUPPORTED_MANEUVERS = new Set([ - 'through', - 'left', - 'right', - 'through;left', - 'through;right', - 'through;left;right', -]); const DIRECTION_ARROW_INTERVAL_METERS = 32; const DIRECTION_ARROW_ENDPOINT_BUFFER_METERS = 14; const STOP_LINE_MAX_APPROACH_DISTANCE_METERS = 25; @@ -275,8 +267,6 @@ function staleOverrideTarget(item, sets) { if (item.kind === 'road' && typeof item.roadId === 'string' && !sets.roadIds.has(item.roadId)) return item.roadId; if (item.kind === 'lane-separator-style' && typeof item.roadId === 'string' && !sets.roadIds.has(item.roadId)) return item.roadId; - if (item.kind === 'lane-maneuver' && typeof item.laneId === 'string' && !sets.laneIds.has(item.laneId)) - return item.laneId; if (item.kind === 'edge-line-style' && typeof item.roadId === 'string' && !sets.directionalRoadIds.has(item.roadId)) return item.roadId; if (item.kind === 'center-line-style' && typeof item.segmentId === 'string' && !sets.segmentIds.has(item.segmentId)) @@ -338,21 +328,6 @@ function validateOverrides(value, model, options = {}) { throw new Error(`Invalid road override ${key}.`); for (const key of ['sidewalkLeft', 'sidewalkRight']) if (item[key] !== undefined && typeof item[key] !== 'boolean') throw new Error(`Invalid road override ${key}.`); - } else if (item.kind === 'lane-maneuver') { - if (typeof item.laneId !== 'string' || (laneIds && !laneIds.has(item.laneId))) - throw new Error(`Unknown lane maneuver override target: ${item.laneId}`); - // '' is meaningful: it removes an arrow OSM asked for. Anything else must be - // a maneuver there is a template for. - if (typeof item.maneuver !== 'string' || (item.maneuver !== '' && !SUPPORTED_MANEUVERS.has(item.maneuver))) - throw new Error( - `Invalid lane maneuver override: ${item.maneuver}. Use '' to remove an arrow, or one of ` + - `${[...SUPPORTED_MANEUVERS].join(', ')} — components must be in that order.`, - ); - if ( - item.placementDistanceMeters !== undefined && - (!Number.isFinite(item.placementDistanceMeters) || item.placementDistanceMeters < 0) - ) - throw new Error(`Invalid lane maneuver placement: ${item.placementDistanceMeters}.`); } else if (item.kind === 'junction-connection') { if ( typeof item.fromEndpointId !== 'string' || @@ -1553,7 +1528,8 @@ function compileLaneMarkings(model, overrides, lanes, diagnostics, junctionPlans // marked — the tag being absent is exactly the case a user needs to fix. // An empty string is a deliberate "no arrow here", so it is distinguished // from "no override" rather than falling through to the tag. - const override = lane ? laneManeuverOverride(overrides, lane.id) : undefined; + const v2Override = lane ? options.directEdit?.laneManeuvers?.get?.(lane.id) : undefined; + const override = v2Override; const explicitManeuver = override ? override.maneuver : maneuvers[index]; if (!explicitManeuver) continue; const maneuver = normalizeManeuver(explicitManeuver); @@ -2375,9 +2351,6 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans) return { features, movements }; } /** The maneuver an override sets for a lane, or `undefined` when none applies. */ -function laneManeuverOverride(overrides, laneId) { - return (overrides?.overrides || []).find((entry) => entry.kind === 'lane-maneuver' && entry.laneId === laneId); -} function safeTurnArrowPlacement(line, maneuver, axis, distance, controls) { return ( diff --git a/test/direct-edit-solver.js b/test/direct-edit-solver.js index 7ff2bc5..02a5a89 100644 --- a/test/direct-edit-solver.js +++ b/test/direct-edit-solver.js @@ -81,7 +81,7 @@ const junctionModel = { }; const junctionResolution = resolveDirectEditConstraints(junctionModel, document([]), { revisionId: 'rev-junction' }); assert.equal(junctionResolution.handles.reserves.length, 3); -assert.equal(new Set(junctionResolution.handles.handles.map((handle) => handle.kind)).size, 8); +assert.equal(new Set(junctionResolution.handles.handles.map((handle) => handle.kind)).size, 9); assert.ok(junctionResolution.handles.handles.every((handle) => handle.position.every(Number.isFinite))); assert.ok(junctionResolution.handles.handles.every((handle) => Number.isFinite(handle.axisAzimuth))); assert.ok(junctionResolution.handles.handles.some((handle) => handle.affects.includes('junction:node/junction'))); @@ -145,7 +145,11 @@ assert.ok( ); assert.ok( segmentScoped.every((handle) => - handle.kind.startsWith('road-') ? handle.anchor.roadId === 'road:a' : handle.anchor.segmentId === 'segment:a', + handle.kind.startsWith('road-') + ? handle.anchor.roadId === 'road:a' + : handle.kind === 'lane-maneuver' + ? handle.anchor.roadId === 'road:a' + : handle.anchor.segmentId === 'segment:a', ), 'a segment selection must only carry that segment’s handles', ); @@ -154,7 +158,9 @@ assert.deepEqual( segmentScoped.map((handle) => handle.handleId).sort(), unscoped .filter((handle) => - handle.kind.startsWith('road-') ? handle.anchor.roadId === 'road:a' : handle.anchor.segmentId === 'segment:a', + handle.kind.startsWith('road-') || handle.kind === 'lane-maneuver' + ? handle.anchor.roadId === 'road:a' + : handle.anchor.segmentId === 'segment:a', ) .filter((handle) => !SHAPE_KINDS.includes(handle.kind)) .map((handle) => handle.handleId) diff --git a/test/index.js b/test/index.js index 32f70c3..d71e986 100644 --- a/test/index.js +++ b/test/index.js @@ -28,54 +28,4 @@ const model = compiler.nativeRoad.compileRoadModel(fs.readFileSync(fixture, 'utf overrides: [], }); assert.equal(model.roads.length, 24); -// --- lane maneuver override --------------------------------------------------- -// -// The arrow a lane shows comes from the OSM `turn:lanes` tag, so overriding it is -// a v1 override like `laneCount`, not a v2 positional constraint: "which arrow" -// has no station to anchor to. -{ - const { validateOverrides } = require('../src/compile/native-road'); - const laneModel = { - roads: [{ id: 'road:way/1:forward', sourceRoadId: 'way/1', segmentId: 'segment:way/1/0', laneCount: 2 }], - endpoints: [], - connections: [], - }; - const wrap = (item) => ({ schema: 'native-road-overrides/v1', overrides: [item] }); - const maneuver = (value, laneId = 'lane:road:way/1:forward:1') => ({ - id: 'm', - kind: 'lane-maneuver', - laneId, - maneuver: value, - }); - - assert.doesNotThrow(() => validateOverrides(wrap(maneuver('through;left')), laneModel)); - assert.doesNotThrow(() => - validateOverrides(wrap({ ...maneuver('through;left'), placementDistanceMeters: 12.5 }), laneModel), - ); - // '' is not "no override": it removes an arrow the tag asked for. - assert.doesNotThrow(() => validateOverrides(wrap(maneuver('')), laneModel)); - assert.throws(() => validateOverrides(wrap(maneuver('u-turn')), laneModel), /Invalid lane maneuver/); - // normalizeManeuver() returns unknown input unchanged, so the override layer is - // the only thing standing between a typo and a silently missing arrow. - assert.throws(() => validateOverrides(wrap(maneuver('left;through')), laneModel), /Invalid lane maneuver/); - assert.throws(() => validateOverrides(wrap(maneuver(3)), laneModel), /Invalid lane maneuver/); - assert.throws( - () => validateOverrides(wrap({ ...maneuver('left'), placementDistanceMeters: -1 }), laneModel), - /Invalid lane maneuver placement/, - ); - assert.throws( - () => validateOverrides(wrap({ ...maneuver('left'), placementDistanceMeters: '12' }), laneModel), - /Invalid lane maneuver placement/, - ); - assert.throws( - () => validateOverrides(wrap(maneuver('left', 'lane:road:way/1:forward:9')), laneModel), - /Unknown lane maneuver override target/, - ); - // An unknown target retires like any other stale override rather than throwing. - const stale = validateOverrides(wrap(maneuver('left', 'lane:road:way/9:forward:1')), laneModel, { - skipStaleTargets: true, - }); - assert.equal(stale.stale.length, 1); -} - console.log('road compiler package tests passed'); diff --git a/test/native-road-edits.js b/test/native-road-edits.js index 3604667..c1d1c71 100644 --- a/test/native-road-edits.js +++ b/test/native-road-edits.js @@ -25,6 +25,7 @@ function anchorFor(kind) { if (type === 'road-interval') return { type, roadId: 'road:way/1:forward', startStation: 0.25, endStation: 0.75, side: 'left' }; if (type === 'junction-approach') return { type, nodeId: 'node/9', segmentId: 'road:way/1:segment/0' }; + if (type === 'lane') return { type, laneId: 'lane:road:way/1:forward:1' }; return { type, nodeId: 'node/9', incomingRoadId: 'road:way/1:forward', outgoingRoadId: 'road:way/2:forward' }; } @@ -51,6 +52,8 @@ function valueFor(kind) { return { depthMeters: 3, stripeCount: 8 }; case 'junction-stop-line-offset': return { offsetMeters: 2.7 }; + case 'lane-maneuver': + return { maneuver: 'left', placementDistanceMeters: 8 }; default: throw new Error(`valueFor has no case for ${kind}; the taxonomy grew without this fixture`); } @@ -104,6 +107,7 @@ assert.deepEqual(CONSTRAINT_KINDS, [ 'junction-crosswalk-inset', 'junction-crosswalk-size', 'junction-stop-line-offset', + 'lane-maneuver', ]); // --- round trip is lossless -------------------------------------------------- diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index e3b19c5..911d48e 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -27,7 +27,13 @@ import { import { previewArrowFeatures } from './edit/arrow-preview'; import { rendersSame } from './edit/parameter'; import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; -import { anchorSnapshotFor, constraintValueFor, draftConstraint, operationFor } from './edit/projection'; +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 { @@ -104,15 +110,12 @@ function App() { const [state, setState] = useState(); const [selected, setSelected] = useState(null); const [staged, setStaged] = useState([]); - const stagedRef = useRef([]); - const overrideUndoRef = useRef([]); - const overrideRedoRef = useRef([]); - stagedRef.current = staged; 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 | null>(null); + const [editMode, setEditMode] = useState(directEditEnabled); useEffect(() => { api .state() @@ -129,7 +132,7 @@ function App() { const loadedDocument = useRef(null); useEffect(() => { // Flag off: no manifest request at all, so the network trace matches main. - if (!directEditEnabled) return; + 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. @@ -153,14 +156,14 @@ function App() { // 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, selected?.segmentId]); + }, [editMode, state, selected?.segmentId]); const editHandles = useMemo(() => { - if (!directEditEnabled || !state) return []; + 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); - }, [manifest, selected, state]); + }, [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); @@ -169,15 +172,20 @@ function App() { // 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 []; + 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, manifest, selected, state]); + }, [editHandles, editMode, manifest, selected, state]); const [preview, setPreview] = useState> | null>(null); const [editDiagnostics, setEditDiagnostics] = useState([]); + const sessionRef = useRef(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. * @@ -194,7 +202,7 @@ function App() { * dot — no second drag path, no second constraint. */ const elementOutline = useMemo(() => { - if (!directEditEnabled || !element || !isControlElement(element) || !state) return 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* @@ -206,7 +214,7 @@ function App() { const drawn = preview?.[layer] ?? state.layers[layer]; const bounds = orientedBoundsOf(groupMembers(drawn?.features ?? [], element.elementId)); return bounds ? { handleId: handle.handleId, bounds } : null; - }, [element, editHandles, state, preview]); + }, [editMode, element, editHandles, state, preview]); const laneSelectionBounds = useMemo(() => { if (!element || element.kind !== 'lane-maneuver' || !state || !element.featureIds.length) return null; const ids = new Set(element.featureIds); @@ -230,14 +238,13 @@ function App() { const nativeId = feature.properties?.native_id; return typeof nativeId === 'string' && ids.has(nativeId); }) ?? []; - const effective = [...state.overrides.overrides, ...staged] - .reverse() - .find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId); - const maneuver = typeof effective?.maneuver === 'string' ? effective.maneuver : element.maneuver; - const placementDistanceMeters = - typeof effective?.placementDistanceMeters === 'number' - ? effective.placementDistanceMeters - : element.placementDistanceMeters; + 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( @@ -247,7 +254,7 @@ function App() { const distance = placementDistanceMeters ?? 6; if (!line || line.length < 2 || !maneuver) return []; return previewArrowFeatures(element.laneId, maneuver, line, distance); - }, [element, preview, staged, state]); + }, [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); @@ -262,27 +269,21 @@ function App() { ); const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null; if (!line || line.length < 2) return null; - const effective = [...state.overrides.overrides, ...staged] - .reverse() - .find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId); - const distance = - typeof effective?.placementDistanceMeters === 'number' - ? effective.placementDistanceMeters - : (element.placementDistanceMeters ?? 6); + 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; - }, [element, staged, state]); - const sessionRef = useRef(null); - if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession(); + }, [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(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. - const [editRevision, setEditRevision] = useState(0); - const touch = () => setEditRevision((value) => value + 1); - const session = sessionRef.current; // Read at send time so the requester, built once, always scopes to the current // selection without being rebuilt. const selectionRef = useRef(undefined); @@ -293,7 +294,6 @@ function App() { * same id in the document, which `validateEditDocument()` rejects outright. */ const gesture = useRef<{ operationId: string; createdAt: string } | null>(null); - const overridePreviewRef = useRef(null); const gestureIdentity = () => { if (!gesture.current) gesture.current = { @@ -319,7 +319,7 @@ function App() { }, 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 @@ -351,6 +351,31 @@ function App() { 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 @@ -381,6 +406,13 @@ function App() { 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(); @@ -451,14 +483,6 @@ function App() { 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 && overrideUndoRef.current.length) { - const previous = overrideUndoRef.current.pop() || []; - overrideRedoRef.current.push([...stagedRef.current]); - setStaged(previous); - previewOverrides([...state!.overrides.overrides, ...previous]); - touch(); - return; - } const reversed = session?.undo({ operationId: `operation:undo:${Date.now()}`, createdAt: new Date().toISOString(), @@ -468,14 +492,6 @@ function App() { previewSession(); }; const redoEdit = () => { - if (!session?.canRedo && overrideRedoRef.current.length) { - const next = overrideRedoRef.current.pop() || []; - overrideUndoRef.current.push([...stagedRef.current]); - setStaged(next); - previewOverrides([...state!.overrides.overrides, ...next]); - touch(); - return; - } if (!session?.redo()) return; touch(); previewSession(); @@ -483,21 +499,16 @@ function App() { const discardEdits = () => { if (!session) return; requester?.cancel(); - overridePreviewRef.current?.abort(); - overridePreviewRef.current = null; session.discard(); setStaged([]); - stagedRef.current = []; - overrideUndoRef.current = []; - overrideRedoRef.current = []; gesture.current = null; touch(); setPreview(null); setEditDiagnostics([]); setStatus('已放弃未保存的直接编辑'); }; - const saveDirectEdits = async () => { - if (!session) return; + 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. @@ -516,7 +527,7 @@ function App() { } catch (error) { if (!isVersionConflict(error)) { setStatus(`保存失败:${(error as Error).message}`); - return; + 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 @@ -525,12 +536,13 @@ function App() { if (Number.isInteger(current)) session.setDocumentVersion(current as number); touch(); setStatus(`保存冲突:文档已被改到版本 ${current ?? '未知'},请刷新后重做本次编辑。`); - return; + 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(); @@ -542,52 +554,15 @@ function App() { } catch (error) { setStatus(`直接编辑已保存(版本 ${version}),但重新生成失败:${(error as Error).message}`); } - }; - const previewOverrides = (overrides: Override[]) => { - if (!session) return; - const fragment = session.fragment(); - overridePreviewRef.current?.abort(); - const controller = new AbortController(); - overridePreviewRef.current = controller; - void api - .editPreview( - { - previewSeq: session.nextPreviewSeq(), - constraints: fragment.constraints, - operations: fragment.operations, - overrides, - selection: selectionRef.current, - }, - controller.signal, - ) - .then((response) => { - setEditDiagnostics(response.diagnostics); - setManifest(response.handles); - setPreview(response.layers); - }) - .catch((error) => { - if ((error as Error)?.name !== 'AbortError') setStatus(`箭头预览失败:${(error as Error).message}`); - }) - .finally(() => { - if (overridePreviewRef.current === controller) overridePreviewRef.current = null; - }); + return true; }; const stage = (change: Override) => setStaged((current) => { const next = [...current.filter((item) => item.id !== change.id), change]; - if (change.kind === 'lane-maneuver') { - overrideUndoRef.current.push([...current.filter((item) => item.kind === 'lane-maneuver')]); - overrideRedoRef.current = []; - if (state) previewOverrides([...state.overrides.overrides, ...next]); - } return next; }); const save = async () => { if (!state || !staged.length) return true; - overridePreviewRef.current?.abort(); - overridePreviewRef.current = null; - overrideUndoRef.current = []; - overrideRedoRef.current = []; try { const overrides = [ ...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)), @@ -605,11 +580,13 @@ function App() { }; const compile = async () => { if (!(await save())) return; + if (!(await saveDirectEdits(false))) 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); @@ -644,10 +621,7 @@ function App() { properties, spec ? (state.layers[spec.layer]?.features ?? []) : (state.layers.laneCenterlines?.features ?? []), ); - // lane-maneuver is a regular v1 override, not a direct-edit constraint, so - // it remains available in the shipped workbench. The flag still contains - // control-marking outlines and all v2 handles behind the experimental path. - setElement(directEditEnabled || nextElement?.kind === 'lane-maneuver' ? nextElement : null); + setElement(editMode ? nextElement : null); const uid = properties.signal_uid; if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`); else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); @@ -656,12 +630,23 @@ function App() { <>
道路编译工作台 + {state.areaId} {status} {staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'} - {directEditEnabled ? ( + {editMode ? ( item.severity === 'error') ? 'dirty' : ''}> {editDiagnostics.find((item) => item.severity === 'error')?.message || (element @@ -688,15 +673,15 @@ function App() { - {directEditEnabled ? ( + {editMode ? ( <> - -