feat(workbench): unify lane maneuver edits in v2

This commit is contained in:
que01 committed 2026-09-01 16:46:22 +08:00
1 parent 118dc8e9aa
commit c804a373ca
15 files changed
+337 -263

No files matched your search

+96 -4
View File
@@ -27,6 +27,7 @@ const SOLVED_KINDS = new Set([
'junction-crosswalk-inset', 'junction-crosswalk-inset',
'junction-crosswalk-size', 'junction-crosswalk-size',
'junction-stop-line-offset', 'junction-stop-line-offset',
'lane-maneuver',
]); ]);
const KINDS = [ const KINDS = [
'road-edge-offset', 'road-edge-offset',
@@ -38,7 +39,17 @@ const KINDS = [
'junction-crosswalk-inset', 'junction-crosswalk-inset',
'junction-crosswalk-size', 'junction-crosswalk-size',
'junction-stop-line-offset', '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; const MIN_LANE_WIDTH_METERS = 2.4;
// Bounds for the control-marking offsets. The crosswalk may sit anywhere from the // 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 // 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; 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) { function reconcileConstraints(model, constraints, base, junctionData, context) {
const versionChanged = Boolean( const versionChanged = Boolean(
context.compilerGeometryVersion && context.compilerGeometryVersion &&
@@ -224,6 +244,12 @@ function reconcileConstraints(model, constraints, base, junctionData, context) {
if (!constraint.enabled || !constraint.anchor || !['exact', 'recheck'].includes(constraint.status)) if (!constraint.enabled || !constraint.anchor || !['exact', 'recheck'].includes(constraint.status))
return constraint; return constraint;
let matched = false; 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-')) { if (constraint.kind.startsWith('road-')) {
const road = roadForAnchor(model, constraint.anchor.roadId); const road = roadForAnchor(model, constraint.anchor.roadId);
matched = Boolean(road); matched = Boolean(road);
@@ -537,6 +563,7 @@ function applyJunctionConstraint(model, constraint, junctionPlans, junctionData,
function solveConstraints(model, constraints, junctionData, diagnostics) { function solveConstraints(model, constraints, junctionData, diagnostics) {
const roadProfiles = new Map(); const roadProfiles = new Map();
const junctionPlans = new Map(); const junctionPlans = new Map();
const laneManeuvers = new Map();
const states = []; const states = [];
for (const constraint of constraints) { for (const constraint of constraints) {
if (!constraint.enabled) { if (!constraint.enabled) {
@@ -564,6 +591,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics) {
}, },
]), ]),
); );
const laneSnapshot = new Map(laneManeuvers);
const junctionSnapshot = new Map( const junctionSnapshot = new Map(
[...junctionPlans].map(([key, plan]) => [ [...junctionPlans].map(([key, plan]) => [
key, key,
@@ -574,18 +602,44 @@ function solveConstraints(model, constraints, junctionData, diagnostics) {
}, },
]), ]),
); );
const applied = constraint.kind.startsWith('road-') let applied;
? applyRoadConstraint(model, constraint, roadProfiles, diagnostics) if (constraint.kind === 'lane-maneuver') {
: applyJunctionConstraint(model, constraint, junctionPlans, junctionData, diagnostics); 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) { if (!applied) {
roadProfiles.clear(); roadProfiles.clear();
for (const [key, profile] of roadSnapshot) roadProfiles.set(key, profile); for (const [key, profile] of roadSnapshot) roadProfiles.set(key, profile);
junctionPlans.clear(); junctionPlans.clear();
for (const [key, plan] of junctionSnapshot) junctionPlans.set(key, plan); 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')); states.push(constraintState(constraint, applied, applied ? null : 'invalid'));
} }
return { roadProfiles, junctionPlans, states }; return { roadProfiles, junctionPlans, laneManeuvers, states };
} }
function roadAffects(roads, model, side, boundaryIndex) { function roadAffects(roads, model, side, boundaryIndex) {
@@ -717,6 +771,38 @@ function makeRoadHandles(model, groups, reserves, constraints, roadProfiles) {
return handles; 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) { function junctionAffects(model, nodeId, segmentIds) {
const roads = (model.roads || []).filter((road) => segmentIds.has(road.segmentId)); const roads = (model.roads || []).filter((road) => segmentIds.has(road.segmentId));
const ids = [junctionSurfaceId(nodeId), ...roadAffects(roads, model)]; 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 // they name their segment directly. Junction *shape* kinds stay out: those
// are JunctionTools', and the main map must not offer a second way in. // 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 (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; 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), ...makeRoadHandles(model || {}, groups, handles.reserves, reconciled, solved.roadProfiles),
...makeJunctionHandles(model || {}, junctionData, reconciled), ...makeJunctionHandles(model || {}, junctionData, reconciled),
...makeLaneManeuverHandles(model || {}, reconciled),
], ],
model || {}, model || {},
context.selection, context.selection,
@@ -958,6 +1048,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
schema: RESOLUTION_SCHEMA, schema: RESOLUTION_SCHEMA,
roadProfiles: solved.roadProfiles, roadProfiles: solved.roadProfiles,
junctionPlans: solved.junctionPlans, junctionPlans: solved.junctionPlans,
laneManeuvers: solved.laneManeuvers,
handles, handles,
constraintStates: solved.states, constraintStates: solved.states,
diagnostics, diagnostics,
@@ -979,5 +1070,6 @@ module.exports = {
KINDS, KINDS,
GEOMETRY_VERSION, GEOMETRY_VERSION,
roadEdgeOffsetRange, roadEdgeOffsetRange,
SUPPORTED_MANEUVERS,
resolveDirectEditConstraints, resolveDirectEditConstraints,
}; };
+13 -1
View File
@@ -18,9 +18,10 @@ const CONSTRAINT_ANCHORS = {
'junction-crosswalk-inset': 'junction-approach', 'junction-crosswalk-inset': 'junction-approach',
'junction-crosswalk-size': 'junction-approach', 'junction-crosswalk-size': 'junction-approach',
'junction-stop-line-offset': 'junction-approach', 'junction-stop-line-offset': 'junction-approach',
'lane-maneuver': 'lane',
}; };
const CONSTRAINT_KINDS = Object.freeze(Object.keys(CONSTRAINT_ANCHORS)); 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 CONSTRAINT_STATUSES = new Set(['exact', 'recheck', 'pending', 'conflicted', 'stale']);
const TRANSITIONS = new Set(['smoothstep', 'linear']); const TRANSITIONS = new Set(['smoothstep', 'linear']);
const SIDES = new Set(['left', 'right']); const SIDES = new Set(['left', 'right']);
@@ -80,6 +81,8 @@ function validateAnchor(scope, kind, anchor) {
requireString(scope, 'anchor.nodeId', anchor.nodeId); requireString(scope, 'anchor.nodeId', anchor.nodeId);
requireString(scope, 'anchor.incomingRoadId', anchor.incomingRoadId); requireString(scope, 'anchor.incomingRoadId', anchor.incomingRoadId);
requireString(scope, 'anchor.outgoingRoadId', anchor.outgoingRoadId); 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. // line on the crosswalk itself.
if (!isFiniteNumber(value.offsetMeters) || value.offsetMeters <= 0) if (!isFiniteNumber(value.offsetMeters) || value.offsetMeters <= 0)
fail(scope, 'value.offsetMeters', 'must be a positive number of meters'); 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');
} }
} }
+2 -29
View File
@@ -54,14 +54,6 @@ const DEFAULT_SIDEWALK_WIDTH_METERS = 2;
// The maneuvers `turn-lane-arrows.js` has templates for. `normalizeManeuver()` // The maneuvers `turn-lane-arrows.js` has templates for. `normalizeManeuver()`
// returns unknown input unchanged rather than failing, so an override has to be // returns unknown input unchanged rather than failing, so an override has to be
// checked here — it cannot lean on normalisation to reject a typo. // 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_INTERVAL_METERS = 32;
const DIRECTION_ARROW_ENDPOINT_BUFFER_METERS = 14; const DIRECTION_ARROW_ENDPOINT_BUFFER_METERS = 14;
const STOP_LINE_MAX_APPROACH_DISTANCE_METERS = 25; 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 === '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)) if (item.kind === 'lane-separator-style' && typeof item.roadId === 'string' && !sets.roadIds.has(item.roadId))
return 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)) if (item.kind === 'edge-line-style' && typeof item.roadId === 'string' && !sets.directionalRoadIds.has(item.roadId))
return item.roadId; return item.roadId;
if (item.kind === 'center-line-style' && typeof item.segmentId === 'string' && !sets.segmentIds.has(item.segmentId)) 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}.`); throw new Error(`Invalid road override ${key}.`);
for (const key of ['sidewalkLeft', 'sidewalkRight']) for (const key of ['sidewalkLeft', 'sidewalkRight'])
if (item[key] !== undefined && typeof item[key] !== 'boolean') throw new Error(`Invalid road override ${key}.`); 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') { } else if (item.kind === 'junction-connection') {
if ( if (
typeof item.fromEndpointId !== 'string' || 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. // 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 // An empty string is a deliberate "no arrow here", so it is distinguished
// from "no override" rather than falling through to the tag. // 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]; const explicitManeuver = override ? override.maneuver : maneuvers[index];
if (!explicitManeuver) continue; if (!explicitManeuver) continue;
const maneuver = normalizeManeuver(explicitManeuver); const maneuver = normalizeManeuver(explicitManeuver);
@@ -2375,9 +2351,6 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans)
return { features, movements }; return { features, movements };
} }
/** The maneuver an override sets for a lane, or `undefined` when none applies. */ /** 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) { function safeTurnArrowPlacement(line, maneuver, axis, distance, controls) {
return ( return (
+9 -3
View File
@@ -81,7 +81,7 @@ const junctionModel = {
}; };
const junctionResolution = resolveDirectEditConstraints(junctionModel, document([]), { revisionId: 'rev-junction' }); const junctionResolution = resolveDirectEditConstraints(junctionModel, document([]), { revisionId: 'rev-junction' });
assert.equal(junctionResolution.handles.reserves.length, 3); 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) => handle.position.every(Number.isFinite)));
assert.ok(junctionResolution.handles.handles.every((handle) => Number.isFinite(handle.axisAzimuth))); assert.ok(junctionResolution.handles.handles.every((handle) => Number.isFinite(handle.axisAzimuth)));
assert.ok(junctionResolution.handles.handles.some((handle) => handle.affects.includes('junction:node/junction'))); assert.ok(junctionResolution.handles.handles.some((handle) => handle.affects.includes('junction:node/junction')));
@@ -145,7 +145,11 @@ assert.ok(
); );
assert.ok( assert.ok(
segmentScoped.every((handle) => 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', 'a segment selection must only carry that segment’s handles',
); );
@@ -154,7 +158,9 @@ assert.deepEqual(
segmentScoped.map((handle) => handle.handleId).sort(), segmentScoped.map((handle) => handle.handleId).sort(),
unscoped unscoped
.filter((handle) => .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)) .filter((handle) => !SHAPE_KINDS.includes(handle.kind))
.map((handle) => handle.handleId) .map((handle) => handle.handleId)
-50
View File
@@ -28,54 +28,4 @@ const model = compiler.nativeRoad.compileRoadModel(fs.readFileSync(fixture, 'utf
overrides: [], overrides: [],
}); });
assert.equal(model.roads.length, 24); 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'); console.log('road compiler package tests passed');
+4
View File
@@ -25,6 +25,7 @@ function anchorFor(kind) {
if (type === 'road-interval') if (type === 'road-interval')
return { type, roadId: 'road:way/1:forward', startStation: 0.25, endStation: 0.75, side: 'left' }; 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 === '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' }; 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 }; return { depthMeters: 3, stripeCount: 8 };
case 'junction-stop-line-offset': case 'junction-stop-line-offset':
return { offsetMeters: 2.7 }; return { offsetMeters: 2.7 };
case 'lane-maneuver':
return { maneuver: 'left', placementDistanceMeters: 8 };
default: default:
throw new Error(`valueFor has no case for ${kind}; the taxonomy grew without this fixture`); 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-inset',
'junction-crosswalk-size', 'junction-crosswalk-size',
'junction-stop-line-offset', 'junction-stop-line-offset',
'lane-maneuver',
]); ]);
// --- round trip is lossless -------------------------------------------------- // --- round trip is lossless --------------------------------------------------
+129 -157
View File
@@ -27,7 +27,13 @@ import {
import { previewArrowFeatures } from './edit/arrow-preview'; import { previewArrowFeatures } from './edit/arrow-preview';
import { rendersSame } from './edit/parameter'; import { rendersSame } from './edit/parameter';
import { PreviewRequester, type PreviewDraft } from './edit/preview-request'; 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 { disabledReasonOf, handlesForSegment, intervalRangeHandles, type IntervalRangeHandle } from './edit/selection';
import { EditSession } from './edit/session'; import { EditSession } from './edit/session';
import type { import type {
@@ -104,15 +110,12 @@ function App() {
const [state, setState] = useState<WorkbenchState>(); const [state, setState] = useState<WorkbenchState>();
const [selected, setSelected] = useState<Road | null>(null); const [selected, setSelected] = useState<Road | null>(null);
const [staged, setStaged] = useState<Override[]>([]); const [staged, setStaged] = useState<Override[]>([]);
const stagedRef = useRef<Override[]>([]);
const overrideUndoRef = useRef<Override[][]>([]);
const overrideRedoRef = useRef<Override[][]>([]);
stagedRef.current = staged;
const [layers, setLayers] = useState(defaultLayers); const [layers, setLayers] = useState(defaultLayers);
const [scene, setScene] = useState(false); const [scene, setScene] = useState(false);
const [status, setStatus] = useState('正在加载工作台...'); const [status, setStatus] = useState('正在加载工作台...');
const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all'); const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all');
const [marking, setMarking] = useState<Record<string, unknown> | null>(null); const [marking, setMarking] = useState<Record<string, unknown> | null>(null);
const [editMode, setEditMode] = useState(directEditEnabled);
useEffect(() => { useEffect(() => {
api api
.state() .state()
@@ -129,7 +132,7 @@ function App() {
const loadedDocument = useRef<string | null>(null); const loadedDocument = useRef<string | null>(null);
useEffect(() => { useEffect(() => {
// Flag off: no manifest request at all, so the network trace matches main. // Flag off: no manifest request at all, so the network trace matches main.
if (!directEditEnabled) return; if (!editMode) return;
api api
// Scoped to the selection: the whole-area manifest is 844 KB on a 41-road // 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. // 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 // 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 // until a manual reload. A recompile also moves the geometry the manifest
// describes, so the manifest has to be refetched with it. // describes, so the manifest has to be refetched with it.
}, [state, selected?.segmentId]); }, [editMode, state, selected?.segmentId]);
const editHandles = useMemo(() => { const editHandles = useMemo(() => {
if (!directEditEnabled || !state) return []; if (!editMode || !state) return [];
// Handle anchors carry a directional road id while reserves are keyed by // Handle anchors carry a directional road id while reserves are keyed by
// segment, so resolve through the compiled model rather than parsing ids. // 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; const segmentOf = (roadId: string) => state.compiled.model.roads.find((road) => road.id === roadId)?.segmentId;
return handlesForSegment(manifest, selected?.segmentId ?? null, segmentOf); 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 // 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. // boundary, so the first blocked handle explains itself in the header.
const blockedHandle = editHandles.find((handle) => !handle.editable); 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. // it once per segment — so one pair of range ends covers the whole selection.
const editRanges = useMemo(() => { const editRanges = useMemo(() => {
// Hidden until compileGeometry() honours profile.interval; see flag.ts. // 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 parent = editHandles.find((handle) => handle.editable && handle.anchor.type === 'road-interval');
const roadId = parent && 'roadId' in parent.anchor ? parent.anchor.roadId : null; const roadId = parent && 'roadId' in parent.anchor ? parent.anchor.roadId : null;
const road = roadId ? state.compiled.model.roads.find((item) => item.id === roadId) : undefined; const road = roadId ? state.compiled.model.roads.find((item) => item.id === roadId) : undefined;
if (!parent || !road) return []; if (!parent || !road) return [];
return intervalRangeHandles(parent, road.centerline, manifest.reserves, selected.segmentId); return intervalRangeHandles(parent, road.centerline, manifest.reserves, selected.segmentId);
}, [editHandles, manifest, selected, state]); }, [editHandles, editMode, manifest, selected, state]);
const [preview, setPreview] = useState<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null); const [preview, setPreview] = useState<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
const [editDiagnostics, setEditDiagnostics] = useState<EditDiagnostic[]>([]); const [editDiagnostics, setEditDiagnostics] = useState<EditDiagnostic[]>([]);
const sessionRef = useRef<EditSession | null>(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. * The crosswalk group under selection, if any.
* *
@@ -194,7 +202,7 @@ function App() {
* dot — no second drag path, no second constraint. * dot — no second drag path, no second constraint.
*/ */
const elementOutline = useMemo<ElementOutline | null>(() => { const elementOutline = useMemo<ElementOutline | null>(() => {
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); const handle = handleForElement(element, state.compiled.model.roads, editHandles);
if (!handle?.editable) return null; if (!handle?.editable) return null;
// Read the preview when there is one. `state.layers` is the last *compiled* // 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 drawn = preview?.[layer] ?? state.layers[layer];
const bounds = orientedBoundsOf(groupMembers(drawn?.features ?? [], element.elementId)); const bounds = orientedBoundsOf(groupMembers(drawn?.features ?? [], element.elementId));
return bounds ? { handleId: handle.handleId, bounds } : null; return bounds ? { handleId: handle.handleId, bounds } : null;
}, [element, editHandles, state, preview]); }, [editMode, element, editHandles, state, preview]);
const laneSelectionBounds = useMemo<Coordinate[] | null>(() => { const laneSelectionBounds = useMemo<Coordinate[] | null>(() => {
if (!element || element.kind !== 'lane-maneuver' || !state || !element.featureIds.length) return null; if (!element || element.kind !== 'lane-maneuver' || !state || !element.featureIds.length) return null;
const ids = new Set(element.featureIds); const ids = new Set(element.featureIds);
@@ -230,14 +238,13 @@ function App() {
const nativeId = feature.properties?.native_id; const nativeId = feature.properties?.native_id;
return typeof nativeId === 'string' && ids.has(nativeId); return typeof nativeId === 'string' && ids.has(nativeId);
}) ?? []; }) ?? [];
const effective = [...state.overrides.overrides, ...staged] const effective = session
.reverse() ?.constraints()
.find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId); .find(
const maneuver = typeof effective?.maneuver === 'string' ? effective.maneuver : element.maneuver; (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === element.laneId,
const placementDistanceMeters = )?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined;
typeof effective?.placementDistanceMeters === 'number' const maneuver = effective?.maneuver ?? element.maneuver;
? effective.placementDistanceMeters const placementDistanceMeters = effective?.placementDistanceMeters ?? element.placementDistanceMeters;
: element.placementDistanceMeters;
if (existing.length && maneuver === element.maneuver && placementDistanceMeters === element.placementDistanceMeters) if (existing.length && maneuver === element.maneuver && placementDistanceMeters === element.placementDistanceMeters)
return existing; return existing;
const lane = state.layers.laneCenterlines?.features.find( const lane = state.layers.laneCenterlines?.features.find(
@@ -247,7 +254,7 @@ function App() {
const distance = placementDistanceMeters ?? 6; const distance = placementDistanceMeters ?? 6;
if (!line || line.length < 2 || !maneuver) return []; if (!line || line.length < 2 || !maneuver) return [];
return previewArrowFeatures(element.laneId, maneuver, line, distance); return previewArrowFeatures(element.laneId, maneuver, line, distance);
}, [element, preview, staged, state]); }, [editRevision, element, preview, session, state]);
const laneSelectionAxisAzimuth = useMemo(() => { const laneSelectionAxisAzimuth = useMemo(() => {
if (!element || element.kind !== 'lane-maneuver' || !state) return null; if (!element || element.kind !== 'lane-maneuver' || !state) return null;
const road = state.compiled.model.roads.find((item) => item.id === element.roadId); 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; const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null;
if (!line || line.length < 2) return null; if (!line || line.length < 2) return null;
const effective = [...state.overrides.overrides, ...staged] const effective = session
.reverse() ?.constraints()
.find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId); .find(
const distance = (item) => item.kind === 'lane-maneuver' && item.anchor.type === 'lane' && item.anchor.laneId === element.laneId,
typeof effective?.placementDistanceMeters === 'number' )?.value as { placementDistanceMeters?: number } | undefined;
? effective.placementDistanceMeters const distance = effective?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6;
: (element.placementDistanceMeters ?? 6);
const length = polylineLengthMeters(line); const length = polylineLengthMeters(line);
return length > 0 ? coordinateAtStation(line, 1 - distance / length) : null; return length > 0 ? coordinateAtStation(line, 1 - distance / length) : null;
}, [element, staged, state]); }, [editRevision, element, session, state]);
const sessionRef = useRef<EditSession | null>(null);
if (directEditEnabled && !sessionRef.current) sessionRef.current = new EditSession();
// Per-frame drag feedback reaches the panel through this rather than through // 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 // state, for the same reason the ghost writes its own source: a setState on
// every pointermove re-renders all of App. // every pointermove re-renders all of App.
const panelRef = useRef<ParameterPanelHandle>(null); const panelRef = useRef<ParameterPanelHandle>(null);
// The session is a mutable object in a ref, so React cannot see it change. // 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. // 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 // Read at send time so the requester, built once, always scopes to the current
// selection without being rebuilt. // selection without being rebuilt.
const selectionRef = useRef<EditSelection | undefined>(undefined); const selectionRef = useRef<EditSelection | undefined>(undefined);
@@ -293,7 +294,6 @@ function App() {
* same id in the document, which `validateEditDocument()` rejects outright. * same id in the document, which `validateEditDocument()` rejects outright.
*/ */
const gesture = useRef<{ operationId: string; createdAt: string } | null>(null); const gesture = useRef<{ operationId: string; createdAt: string } | null>(null);
const overridePreviewRef = useRef<AbortController | null>(null);
const gestureIdentity = () => { const gestureIdentity = () => {
if (!gesture.current) if (!gesture.current)
gesture.current = { gesture.current = {
@@ -319,7 +319,7 @@ function App() {
}, },
onError: (error) => setStatus(`预览失败:${(error as Error).message}`), onError: (error) => setStatus(`预览失败:${(error as Error).message}`),
}); });
}, []); }, [session]);
/** A drag becomes one drafted constraint layered over the session's document. */ /** A drag becomes one drafted constraint layered over the session's document. */
const draftFor = (handle: EditHandle, value: number): PreviewDraft | null => { const draftFor = (handle: EditHandle, value: number): PreviewDraft | null => {
// Road-anchored edits carry a directional road id. Junction-approach // 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], 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 * 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 * creating one: the interval is a property of the road's edit, shared by every
@@ -381,6 +406,13 @@ function App() {
gesture.current = null; gesture.current = null;
touch(); 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. */ /** Re-previews whatever the session now holds, after undo/redo moved the cursor. */
const previewSession = () => { const previewSession = () => {
const fragment = session?.fragment(); const fragment = session?.fragment();
@@ -451,14 +483,6 @@ function App() {
const undoEdit = () => { const undoEdit = () => {
// A saved gesture cannot be un-applied — persisted history is append-only — so // 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. // 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({ const reversed = session?.undo({
operationId: `operation:undo:${Date.now()}`, operationId: `operation:undo:${Date.now()}`,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
@@ -468,14 +492,6 @@ function App() {
previewSession(); previewSession();
}; };
const redoEdit = () => { 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; if (!session?.redo()) return;
touch(); touch();
previewSession(); previewSession();
@@ -483,21 +499,16 @@ function App() {
const discardEdits = () => { const discardEdits = () => {
if (!session) return; if (!session) return;
requester?.cancel(); requester?.cancel();
overridePreviewRef.current?.abort();
overridePreviewRef.current = null;
session.discard(); session.discard();
setStaged([]); setStaged([]);
stagedRef.current = [];
overrideUndoRef.current = [];
overrideRedoRef.current = [];
gesture.current = null; gesture.current = null;
touch(); touch();
setPreview(null); setPreview(null);
setEditDiagnostics([]); setEditDiagnostics([]);
setStatus('已放弃未保存的直接编辑'); setStatus('已放弃未保存的直接编辑');
}; };
const saveDirectEdits = async () => { const saveDirectEdits = async (recompile = true) => {
if (!session) return; if (!session || !session.dirty) return true;
// A field still being typed in holds an uncommitted value. Blur fires before // 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 // click so the button press would settle it anyway, but that ordering is not
// something to depend on for whether an edit is persisted. // something to depend on for whether an edit is persisted.
@@ -516,7 +527,7 @@ function App() {
} catch (error) { } catch (error) {
if (!isVersionConflict(error)) { if (!isVersionConflict(error)) {
setStatus(`保存失败:${(error as Error).message}`); setStatus(`保存失败:${(error as Error).message}`);
return; return false;
} }
// Single-writer protection fired: another tab moved the document. Adopt the // 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 // 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); if (Number.isInteger(current)) session.setDocumentVersion(current as number);
touch(); touch();
setStatus(`保存冲突:文档已被改到版本 ${current ?? '未知'},请刷新后重做本次编辑。`); setStatus(`保存冲突:文档已被改到版本 ${current ?? '未知'},请刷新后重做本次编辑。`);
return; return false;
} }
// The document is written, but `/api/state` serves the outputs of the last // 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 // compile — without recompiling, a refresh shows the pre-edit geometry and a
// successful save is indistinguishable from a failed one. Reported separately // successful save is indistinguishable from a failed one. Reported separately
// because at this point the save has already succeeded. // because at this point the save has already succeeded.
if (!recompile) return true;
try { try {
setStatus('直接编辑已保存,正在重新生成几何...'); setStatus('直接编辑已保存,正在重新生成几何...');
const next = await api.compile(); const next = await api.compile();
@@ -542,52 +554,15 @@ function App() {
} catch (error) { } catch (error) {
setStatus(`直接编辑已保存(版本 ${version}),但重新生成失败:${(error as Error).message}`); setStatus(`直接编辑已保存(版本 ${version}),但重新生成失败:${(error as Error).message}`);
} }
}; return true;
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;
});
}; };
const stage = (change: Override) => const stage = (change: Override) =>
setStaged((current) => { setStaged((current) => {
const next = [...current.filter((item) => item.id !== change.id), change]; 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; return next;
}); });
const save = async () => { const save = async () => {
if (!state || !staged.length) return true; if (!state || !staged.length) return true;
overridePreviewRef.current?.abort();
overridePreviewRef.current = null;
overrideUndoRef.current = [];
overrideRedoRef.current = [];
try { try {
const overrides = [ const overrides = [
...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)), ...state.overrides.overrides.filter((item) => !staged.some((change) => change.id === item.id)),
@@ -605,11 +580,13 @@ function App() {
}; };
const compile = async () => { const compile = async () => {
if (!(await save())) return; if (!(await save())) return;
if (!(await saveDirectEdits(false))) return;
try { try {
setStatus('正在重新生成...'); setStatus('正在重新生成...');
const next = await api.compile(); const next = await api.compile();
setState(next); setState(next);
setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null); setSelected((current) => next.compiled.model.roads.find((road) => road.id === current?.id) || null);
setPreview(null);
setStatus('已保存并重新生成'); setStatus('已保存并重新生成');
} catch (error) { } catch (error) {
setStatus((error as Error).message); setStatus((error as Error).message);
@@ -644,10 +621,7 @@ function App() {
properties, properties,
spec ? (state.layers[spec.layer]?.features ?? []) : (state.layers.laneCenterlines?.features ?? []), spec ? (state.layers[spec.layer]?.features ?? []) : (state.layers.laneCenterlines?.features ?? []),
); );
// lane-maneuver is a regular v1 override, not a direct-edit constraint, so setElement(editMode ? nextElement : null);
// 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);
const uid = properties.signal_uid; const uid = properties.signal_uid;
if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`); if (typeof uid === 'string') setStatus(`已选中原生红绿灯 ${uid}`);
else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式'); else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式');
@@ -656,12 +630,23 @@ function App() {
<> <>
<header> <header>
<strong>道路编译工作台</strong> <strong>道路编译工作台</strong>
<label className="mode-switch">
<span>浏览</span>
<input
type="checkbox"
role="switch"
aria-label="编辑模式"
checked={editMode}
onChange={(event) => setEditMode(event.target.checked)}
/>
<span>编辑</span>
</label>
<span>{state.areaId}</span> <span>{state.areaId}</span>
<span>{status}</span> <span>{status}</span>
<span className={staged.length ? 'dirty' : ''}> <span className={staged.length ? 'dirty' : ''}>
{staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'} {staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'}
</span> </span>
{directEditEnabled ? ( {editMode ? (
<span className={editDiagnostics.some((item) => item.severity === 'error') ? 'dirty' : ''}> <span className={editDiagnostics.some((item) => item.severity === 'error') ? 'dirty' : ''}>
{editDiagnostics.find((item) => item.severity === 'error')?.message || {editDiagnostics.find((item) => item.severity === 'error')?.message ||
(element (element
@@ -688,15 +673,15 @@ function App() {
<Button onClick={() => void compile()}> <Button onClick={() => void compile()}>
<RefreshCw size={15} /> 保存并重新生成 <RefreshCw size={15} /> 保存并重新生成
</Button> </Button>
{directEditEnabled ? ( {editMode ? (
<> <>
<Button onClick={() => void saveDirectEdits()} disabled={!session?.dirty}> <Button onClick={() => void saveDirectEdits()} disabled={!session?.dirty}>
<Save size={15} /> 保存直接编辑 <Save size={15} /> 保存直接编辑
</Button> </Button>
<Button onClick={undoEdit} disabled={!session?.canUndo && !overrideUndoRef.current.length}> <Button onClick={undoEdit} disabled={!session?.canUndo}>
撤销 撤销
</Button> </Button>
<Button onClick={redoEdit} disabled={!session?.canRedo && !overrideRedoRef.current.length}> <Button onClick={redoEdit} disabled={!session?.canRedo}>
重做 重做
</Button> </Button>
<Button onClick={discardEdits} disabled={!session?.dirty && !staged.length}> <Button onClick={discardEdits} disabled={!session?.dirty && !staged.length}>
@@ -765,6 +750,7 @@ function App() {
</aside> </aside>
<MapCanvas <MapCanvas
state={state} state={state}
editMode={editMode}
selected={selected} selected={selected}
visible={layers} visible={layers}
scene={scene} scene={scene}
@@ -789,17 +775,8 @@ function App() {
const along = metersAlongPolyline(line, toLonLat(to)); const along = metersAlongPolyline(line, toLonLat(to));
const length = polylineLengthMeters(line); const length = polylineLengthMeters(line);
if (along === null || !(length > 0)) return; if (along === null || !(length > 0)) return;
const existing = [...state.overrides.overrides, ...staged] const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along));
.reverse() if (draft) requester?.schedule(draft);
.find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId);
const next: Override = {
id: existing?.id || `车道转向:${element.laneId}`,
kind: 'lane-maneuver',
laneId: element.laneId,
maneuver: typeof existing?.maneuver === 'string' ? existing.maneuver : element.maneuver,
placementDistanceMeters: Math.max(0, length - along),
};
previewOverrides([...state.overrides.overrides, ...staged.filter((item) => item.id !== next.id), next]);
}} }}
onLaneSelectionDragEnd={(from, to) => { onLaneSelectionDragEnd={(from, to) => {
if (!element || element.kind !== 'lane-maneuver') return; if (!element || element.kind !== 'lane-maneuver') return;
@@ -811,16 +788,8 @@ function App() {
const along = metersAlongPolyline(line, toLonLat(to)); const along = metersAlongPolyline(line, toLonLat(to));
const length = polylineLengthMeters(line); const length = polylineLengthMeters(line);
if (along === null || !(length > 0)) return; if (along === null || !(length > 0)) return;
const existing = [...state.overrides.overrides, ...staged] const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along));
.reverse() if (draft) commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]);
.find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId);
stage({
id: existing?.id || `车道转向:${element.laneId}`,
kind: 'lane-maneuver',
laneId: element.laneId,
maneuver: typeof existing?.maneuver === 'string' ? existing.maneuver : element.maneuver,
placementDistanceMeters: Math.max(0, length - along),
});
setStatus('箭头位置已暂存;保存并重新生成后应用。'); setStatus('箭头位置已暂存;保存并重新生成后应用。');
}} }}
preview={preview} preview={preview}
@@ -859,8 +828,10 @@ function App() {
stage={stage} stage={stage}
status={setStatus} status={setStatus}
setState={setState} setState={setState}
session={session}
onLaneManeuverChange={applyLaneManeuver}
> >
{directEditEnabled ? ( {editMode ? (
<ParameterPanel <ParameterPanel
handles={editHandles} handles={editHandles}
hasSelection={Boolean(selected)} hasSelection={Boolean(selected)}
@@ -920,6 +891,8 @@ function Inspector({
stage, stage,
status, status,
setState, setState,
session,
onLaneManeuverChange,
children, children,
}: { }: {
road: Road | null; road: Road | null;
@@ -930,6 +903,8 @@ function Inspector({
stage: (item: Override) => void; stage: (item: Override) => void;
status: (value: string) => void; status: (value: string) => void;
setState: (next: WorkbenchState) => void; setState: (next: WorkbenchState) => void;
session: EditSession | null;
onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void;
children?: ReactNode; children?: ReactNode;
}) { }) {
const [width, setWidth] = useState(0); const [width, setWidth] = useState(0);
@@ -1067,7 +1042,22 @@ function Inspector({
open={open === 'element'} open={open === 'element'}
onToggle={section('element')} onToggle={section('element')}
> >
<LaneManeuverEditor element={element} overrides={[...state.overrides.overrides, ...staged]} stage={stage} /> <LaneManeuverEditor
element={element}
value={
element?.kind === 'lane-maneuver'
? (session
?.constraints()
.find(
(item) =>
item.kind === 'lane-maneuver' &&
item.anchor.type === 'lane' &&
item.anchor.laneId === element.laneId,
)?.value as { maneuver?: string; placementDistanceMeters?: number } | undefined)
: undefined
}
onChange={onLaneManeuverChange}
/>
<MarkingEditor marking={marking} stage={stage} /> <MarkingEditor marking={marking} stage={stage} />
<SignalEditor state={state} signal={signal} status={status} update={updateSignal} /> <SignalEditor state={state} signal={signal} status={status} update={updateSignal} />
</InspectorSection> </InspectorSection>
@@ -1176,41 +1166,23 @@ const MANEUVER_OPTIONS: Array<[string, string]> = [
]; ];
function LaneManeuverEditor({ function LaneManeuverEditor({
element, element,
overrides, value,
stage, onChange,
}: { }: {
element: ElementSelection | null; element: ElementSelection | null;
overrides: Override[]; value?: { maneuver?: string; placementDistanceMeters?: number };
stage: (item: Override) => void; onChange: (maneuver: string, placementDistanceMeters: number) => void;
}) { }) {
if (!element || element.kind !== 'lane-maneuver') return null; if (!element || element.kind !== 'lane-maneuver') return null;
// Old override files may use arbitrary ids. Reuse the latest matching entry const maneuver = value?.maneuver ?? element.maneuver;
// so staging replaces it instead of leaving two conflicting maneuvers on one lane. const placementDistanceMeters = value?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6;
const override = [...overrides]
.reverse()
.find((item) => item.kind === 'lane-maneuver' && item.laneId === element.laneId);
const id = override?.id || `车道转向:${element.laneId}`;
const maneuver = typeof override?.maneuver === 'string' ? override.maneuver : element.maneuver;
const placementDistanceMeters =
typeof override?.placementDistanceMeters === 'number'
? override.placementDistanceMeters
: (element.placementDistanceMeters ?? 6);
const update = (next: Partial<Pick<Override, 'maneuver' | 'placementDistanceMeters'>>) =>
stage({
id,
kind: 'lane-maneuver',
laneId: element.laneId,
maneuver: typeof next.maneuver === 'string' ? next.maneuver : maneuver,
placementDistanceMeters:
typeof next.placementDistanceMeters === 'number' ? next.placementDistanceMeters : placementDistanceMeters,
});
return ( return (
<form className="element-form"> <form className="element-form">
<h2>车道转向箭头</h2> <h2>车道转向箭头</h2>
<p className="form-context">第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。</p> <p className="form-context">第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。</p>
<label> <label>
转向 转向
<select value={maneuver} onChange={(event) => update({ maneuver: event.target.value })}> <select value={maneuver} onChange={(event) => onChange(event.target.value, placementDistanceMeters)}>
{MANEUVER_OPTIONS.map(([value, label]) => ( {MANEUVER_OPTIONS.map(([value, label]) => (
<option value={value} key={value}> <option value={value} key={value}>
{label} {label}
@@ -1227,7 +1199,7 @@ function LaneManeuverEditor({
value={placementDistanceMeters} value={placementDistanceMeters}
onChange={(event) => { onChange={(event) => {
const next = Number(event.target.value); const next = Number(event.target.value);
if (Number.isFinite(next) && next >= 0) update({ placementDistanceMeters: next }); if (Number.isFinite(next) && next >= 0) onChange(maneuver, next);
}} }}
/> />
</label> </label>
+16 -11
View File
@@ -13,7 +13,6 @@ import Style from 'ol/style/Style';
import { click } from 'ol/events/condition'; import { click } from 'ol/events/condition';
import type { GeoJson, Road, WorkbenchState } from '../types/state'; import type { GeoJson, Road, WorkbenchState } from '../types/state';
import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers'; import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers';
import { directEditEnabled } from '../edit/flag';
import { createHandleDragInteraction } from '../edit/drag-interaction'; import { createHandleDragInteraction } from '../edit/drag-interaction';
import { EditGhostLayer } from '../edit/ghost-layer'; import { EditGhostLayer } from '../edit/ghost-layer';
import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer'; import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer';
@@ -60,6 +59,7 @@ interface Props {
onRangeEnd?: (range: IntervalRangeHandle, anchor: RoadIntervalAnchor) => void; onRangeEnd?: (range: IntervalRangeHandle, anchor: RoadIntervalAnchor) => void;
/** Last solve came back degraded; hold the ghost instead of clearing it. */ /** Last solve came back degraded; hold the ghost instead of clearing it. */
ghostPending?: boolean; ghostPending?: boolean;
editMode?: boolean;
} }
export function MapCanvas({ export function MapCanvas({
state, state,
@@ -86,6 +86,7 @@ export function MapCanvas({
onRangeDrag, onRangeDrag,
onRangeEnd, onRangeEnd,
ghostPending, ghostPending,
editMode = false,
}: Props) { }: Props) {
const target = useRef<HTMLDivElement>(null); const target = useRef<HTMLDivElement>(null);
const mapRef = useRef<Map | null>(null); const mapRef = useRef<Map | null>(null);
@@ -96,6 +97,7 @@ export function MapCanvas({
/** Auto-fit is for a newly loaded area, never for a recompile of the same one. */ /** Auto-fit is for a newly loaded area, never for a recompile of the same one. */
const fittedAreaIdRef = useRef<string | null>(null); const fittedAreaIdRef = useRef<string | null>(null);
const laneSelectionSourceRef = useRef<VectorSource | null>(null); const laneSelectionSourceRef = useRef<VectorSource | null>(null);
const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]); const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null); const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set()); const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
@@ -133,9 +135,11 @@ export function MapCanvas({
const selectedRef = useRef<Road | null>(selected); const selectedRef = useRef<Road | null>(selected);
const stateRef = useRef(state); const stateRef = useRef(state);
const sceneRef = useRef(scene); const sceneRef = useRef(scene);
const editModeRef = useRef(editMode);
selectedRef.current = selected; selectedRef.current = selected;
stateRef.current = state; stateRef.current = state;
sceneRef.current = scene; sceneRef.current = scene;
editModeRef.current = editMode;
hiddenMarkingIdsRef.current = new Set( hiddenMarkingIdsRef.current = new Set(
laneSelectionHiddenIds ?? laneSelectionHiddenIds ??
(laneSelectionFeatures ?? []) (laneSelectionFeatures ?? [])
@@ -164,16 +168,15 @@ export function MapCanvas({
}), }),
}); });
laneSelectionSourceRef.current = laneSelectionSource; laneSelectionSourceRef.current = laneSelectionSource;
laneSelectionLayerRef.current = laneSelectionLayer;
// The v2 direct-edit sources below remain absent with the flag off. The lane // The v2 direct-edit sources below remain absent with the flag off. The lane
// selection layer above is a regular v1 override affordance, not an edit source. // selection layer above is a regular v1 override affordance, not an edit source.
const handleLayer = directEditEnabled ? new EditHandleLayer() : null; const handleLayer = new EditHandleLayer();
const ghost = directEditEnabled ? new EditGhostLayer() : null; const ghost = new EditGhostLayer();
const previewLayer = directEditEnabled const previewLayer = new EditPreviewLayer(
? new EditPreviewLayer( () => selectedRef.current,
() => selectedRef.current, () => sceneRef.current,
() => sceneRef.current, );
)
: null;
handleLayerRef.current = handleLayer; handleLayerRef.current = handleLayer;
ghostRef.current = ghost; ghostRef.current = ghost;
previewRef.current = previewLayer; previewRef.current = previewLayer;
@@ -204,6 +207,7 @@ export function MapCanvas({
map.addInteraction( map.addInteraction(
new PointerInteraction({ new PointerInteraction({
handleDownEvent: (event) => { handleDownEvent: (event) => {
if (!editModeRef.current) return false;
const hit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, { const hit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
layerFilter: (layer) => layer === laneSelectionLayer, layerFilter: (layer) => layer === laneSelectionLayer,
hitTolerance: 10, hitTolerance: 10,
@@ -258,8 +262,8 @@ export function MapCanvas({
createHandleDragInteraction({ createHandleDragInteraction({
layer: handleLayer.layer, layer: handleLayer.layer,
ghost, ghost,
handleAt: (handleId) => handleLayer.handle(handleId), handleAt: (handleId) => (editModeRef.current ? handleLayer.handle(handleId) : undefined),
rangeAt: (handleId) => handleLayer.range(handleId), rangeAt: (handleId) => (editModeRef.current ? handleLayer.range(handleId) : undefined),
onDrag: (handle, value) => dragRef.current.onHandleDrag?.(handle, value), onDrag: (handle, value) => dragRef.current.onHandleDrag?.(handle, value),
onEnd: (handle, value) => dragRef.current.onHandleDragEnd?.(handle, value), onEnd: (handle, value) => dragRef.current.onHandleDragEnd?.(handle, value),
onRangeDrag: (range, anchor) => dragRef.current.onRangeDrag?.(range, anchor), onRangeDrag: (range, anchor) => dragRef.current.onRangeDrag?.(range, anchor),
@@ -320,6 +324,7 @@ export function MapCanvas({
useEffect(() => { useEffect(() => {
const source = laneSelectionSourceRef.current; const source = laneSelectionSourceRef.current;
if (!source) return; if (!source) return;
laneSelectionLayerRef.current?.setVisible(editMode);
source.clear(); source.clear();
const parts = (laneSelectionFeatures ?? []).flatMap((feature) => { const parts = (laneSelectionFeatures ?? []).flatMap((feature) => {
const coordinates = feature.geometry?.coordinates; const coordinates = feature.geometry?.coordinates;
+1
View File
@@ -28,6 +28,7 @@ function readFlag(): boolean {
* Resolved once at module load so a single render pass cannot see the flag flip * Resolved once at module load so a single render pass cannot see the flag flip
* halfway through and build a half-wired map. * halfway through and build a half-wired map.
*/ */
/** Initial mode for compatibility with the old URL opt-in. The UI may switch it at runtime. */
export const directEditEnabled = readFlag(); export const directEditEnabled = readFlag();
/** /**
+1
View File
@@ -108,6 +108,7 @@ export function metersToStation(meters: number, roadLengthMeters: number): numbe
} }
const KIND_LABELS: Record<ConstraintKind, string> = { const KIND_LABELS: Record<ConstraintKind, string> = {
'lane-maneuver': '导向箭头位置',
'road-edge-offset': '外缘偏移', 'road-edge-offset': '外缘偏移',
'road-sidewalk-width': '步行带宽度', 'road-sidewalk-width': '步行带宽度',
'road-lane-divider': '车道分隔', 'road-lane-divider': '车道分隔',
+8
View File
@@ -17,6 +17,7 @@ import {
import type { import type {
AnchorSnapshot, AnchorSnapshot,
ConstraintValue, ConstraintValue,
LaneManeuverValue,
EditHandle, EditHandle,
JunctionReserve, JunctionReserve,
RoadConstraint, RoadConstraint,
@@ -92,6 +93,8 @@ export function constraintValueFor(
transition: Transition = 'smoothstep', transition: Transition = 'smoothstep',
): ConstraintValue { ): ConstraintValue {
switch (handle.kind) { switch (handle.kind) {
case 'lane-maneuver':
throw new Error('lane-maneuver requires laneManeuverValueFor');
case 'road-edge-offset': case 'road-edge-offset':
return { offsetMeters: scalar, transition }; return { offsetMeters: scalar, transition };
case 'road-sidewalk-width': case 'road-sidewalk-width':
@@ -117,6 +120,11 @@ export function constraintValueFor(
} }
} }
/** Packages the two-field lane arrow edit as one direct-edit value. */
export function laneManeuverValueFor(maneuver: string, placementDistanceMeters: number): LaneManeuverValue {
return { maneuver, placementDistanceMeters };
}
/** /**
* The station range a road interval may occupy, i.e. everything outside the * The station range a road interval may occupy, i.e. everything outside the
* junction reserves. Mirrors the window `makeRoadHandles()` centres its handles * junction reserves. Mirrors the window `makeRoadHandles()` centres its handles
+5
View File
@@ -9,6 +9,7 @@ import { reserveWindow, type IntervalWindow } from './projection';
import { import {
isControlKind, isControlKind,
isRoadKind, isRoadKind,
LANE_KINDS,
type EditHandle, type EditHandle,
type HandleManifest, type HandleManifest,
type JunctionReserve, type JunctionReserve,
@@ -35,6 +36,10 @@ export function handlesForSegment(
): EditHandle[] { ): EditHandle[] {
if (!manifest || !segmentId) return []; if (!manifest || !segmentId) return [];
return manifest.handles.filter((handle) => { return manifest.handles.filter((handle) => {
if ((LANE_KINDS as readonly string[]).includes(handle.kind)) {
const roadId = handle.anchor.type === 'lane' ? handle.anchor.roadId : undefined;
return typeof roadId === 'string' && segmentOf(roadId) === segmentId;
}
if (isControlKind(handle.kind)) return 'segmentId' in handle.anchor && handle.anchor.segmentId === segmentId; if (isControlKind(handle.kind)) return 'segmentId' in handle.anchor && handle.anchor.segmentId === segmentId;
if (!isRoadKind(handle.kind)) return false; if (!isRoadKind(handle.kind)) return false;
const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : undefined; const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : undefined;
+12 -4
View File
@@ -6,7 +6,7 @@
// imports from here rather than casting response fields locally, so there is one // imports from here rather than casting response fields locally, so there is one
// definition of "a valid manifest" on this side of the wire. // definition of "a valid manifest" on this side of the wire.
import type { GeoJson, Override } from '../types/state'; import type { GeoJson } from '../types/state';
export type Side = 'left' | 'right'; export type Side = 'left' | 'right';
export type Transition = 'smoothstep' | 'linear'; export type Transition = 'smoothstep' | 'linear';
@@ -34,15 +34,18 @@ export const JUNCTION_KINDS = [
// the panel when the corner grips exist to drive it. // the panel when the corner grips exist to drive it.
'junction-crosswalk-size', 'junction-crosswalk-size',
] as const; ] as const;
export const LANE_KINDS = ['lane-maneuver'] as const;
export type RoadConstraintKind = (typeof ROAD_KINDS)[number]; export type RoadConstraintKind = (typeof ROAD_KINDS)[number];
export type ControlConstraintKind = (typeof CONTROL_KINDS)[number]; export type ControlConstraintKind = (typeof CONTROL_KINDS)[number];
export type JunctionConstraintKind = (typeof JUNCTION_KINDS)[number]; export type JunctionConstraintKind = (typeof JUNCTION_KINDS)[number];
export type ConstraintKind = RoadConstraintKind | JunctionConstraintKind; export type LaneConstraintKind = (typeof LANE_KINDS)[number];
export type ConstraintKind = RoadConstraintKind | JunctionConstraintKind | LaneConstraintKind;
export type ConstraintStatus = 'exact' | 'recheck' | 'pending' | 'conflicted' | 'stale'; export type ConstraintStatus = 'exact' | 'recheck' | 'pending' | 'conflicted' | 'stale';
export type SemanticAnchor = export type SemanticAnchor =
| { type: 'lane'; laneId: string; roadId?: string }
| { type: 'road-station'; roadId: string; station: number; side?: Side } | { type: 'road-station'; roadId: string; station: number; side?: Side }
| { | {
type: 'road-interval'; type: 'road-interval';
@@ -99,6 +102,7 @@ export interface AnchorSnapshot {
} }
export type ConstraintValue = export type ConstraintValue =
| { maneuver: string; placementDistanceMeters?: number }
| { offsetMeters: number; transition?: Transition } | { offsetMeters: number; transition?: Transition }
| { widthMeters: number; transition?: Transition } | { widthMeters: number; transition?: Transition }
| { boundaryIndex: number; offsetMeters: number; transition?: Transition } | { boundaryIndex: number; offsetMeters: number; transition?: Transition }
@@ -106,13 +110,18 @@ export type ConstraintValue =
| { cutbackMeters: number } | { cutbackMeters: number }
| { radiusMeters: number } | { radiusMeters: number }
| { insetMeters: number }; | { insetMeters: number };
export interface LaneManeuverValue {
maneuver: string;
placementDistanceMeters: number;
}
export type ConstraintValueWithLane = ConstraintValue | LaneManeuverValue;
export interface RoadConstraint { export interface RoadConstraint {
id: string; id: string;
kind: ConstraintKind; kind: ConstraintKind;
anchor: SemanticAnchor; anchor: SemanticAnchor;
anchorSnapshot: AnchorSnapshot; anchorSnapshot: AnchorSnapshot;
value: ConstraintValue; value: ConstraintValueWithLane;
enabled: boolean; enabled: boolean;
status: ConstraintStatus; status: ConstraintStatus;
provenance: { operationId: string; createdAt: string; author?: string }; provenance: { operationId: string; createdAt: string; author?: string };
@@ -207,7 +216,6 @@ export type EditSelection = { segment: string } | { junction: string };
*/ */
export interface EditPreviewRequest { export interface EditPreviewRequest {
previewSeq: number; previewSeq: number;
overrides?: Override[];
constraints?: RoadConstraint[]; constraints?: RoadConstraint[];
operations?: RoadEditOperation[]; operations?: RoadEditOperation[];
document?: RoadEditDocument; document?: RoadEditDocument;
+40
View File
@@ -73,6 +73,46 @@ aside {
header .button { header .button {
white-space: nowrap; white-space: nowrap;
} }
.mode-switch {
display: inline-flex;
align-items: center;
gap: 8px;
white-space: nowrap;
font-size: 12px;
}
.mode-switch input[type='checkbox'] {
appearance: none;
width: 34px;
height: 18px;
margin: 0;
border-radius: 999px;
border: 1px solid #9aa6b2;
background: #dfe5eb;
position: relative;
cursor: pointer;
transition:
background 0.15s ease,
border-color 0.15s ease;
}
.mode-switch input[type='checkbox']::after {
content: '';
position: absolute;
width: 14px;
height: 14px;
top: 1px;
left: 1px;
border-radius: 50%;
background: #fff;
box-shadow: 0 1px 2px rgb(0 0 0 / 20%);
transition: transform 0.15s ease;
}
.mode-switch input[type='checkbox']:checked {
background: #2563eb;
border-color: #2563eb;
}
.mode-switch input[type='checkbox']:checked::after {
transform: translateX(16px);
}
h1 { h1 {
font-size: 16px; font-size: 16px;
margin: 0 0 8px; margin: 0 0 8px;
+1 -4
View File
@@ -333,9 +333,6 @@ function editPreview(area, body = {}) {
const activeState = readJson(activeStateFile); const activeState = readJson(activeStateFile);
const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides); const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides);
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides); const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), persistedOverrides);
const previewOverrides = Array.isArray(body.overrides)
? validateOverrides({ schema: 'native-road-overrides/v1', overrides: body.overrides }, model)
: persistedOverrides;
const previewSeq = Number.isInteger(body.previewSeq) ? body.previewSeq : 0; const previewSeq = Number.isInteger(body.previewSeq) ? body.previewSeq : 0;
const resolution = resolveDirectEditConstraints(model, draft, { const resolution = resolveDirectEditConstraints(model, draft, {
revisionId: activeState.activeRevisionId, revisionId: activeState.activeRevisionId,
@@ -343,7 +340,7 @@ function editPreview(area, body = {}) {
compilerGeometryVersion: GEOMETRY_VERSION, compilerGeometryVersion: GEOMETRY_VERSION,
selection: selectionFrom(body.selection), selection: selectionFrom(body.selection),
}); });
const compiled = compileGeometry(model, previewOverrides, { const compiled = compileGeometry(model, persistedOverrides, {
edgeLines: area.nativeRoad.edgeLines, edgeLines: area.nativeRoad.edgeLines,
junctionTemplates: area.nativeRoad.junctionTemplates, junctionTemplates: area.nativeRoad.junctionTemplates,
directEdit: resolution, directEdit: resolution,