feat(workbench): unify lane maneuver edits in v2
This commit is contained in:
1 parent
118dc8e9aa
commit
c804a373ca
15 files changed
+337
-263
No files matched your search
@@ -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,
|
||||
};
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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');
|
||||
@@ -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 --------------------------------------------------
|
||||
|
||||
+129
-157
@@ -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<WorkbenchState>();
|
||||
const [selected, setSelected] = useState<Road | null>(null);
|
||||
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 [scene, setScene] = useState(false);
|
||||
const [status, setStatus] = useState('正在加载工作台...');
|
||||
const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all');
|
||||
const [marking, setMarking] = useState<Record<string, unknown> | null>(null);
|
||||
const [editMode, setEditMode] = useState(directEditEnabled);
|
||||
useEffect(() => {
|
||||
api
|
||||
.state()
|
||||
@@ -129,7 +132,7 @@ function App() {
|
||||
const loadedDocument = useRef<string | null>(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<Partial<Record<PreviewLayerName, GeoJson | null>> | null>(null);
|
||||
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.
|
||||
*
|
||||
@@ -194,7 +202,7 @@ function App() {
|
||||
* dot — no second drag path, no second constraint.
|
||||
*/
|
||||
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);
|
||||
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<Coordinate[] | null>(() => {
|
||||
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<EditSession | null>(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<ParameterPanelHandle>(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<EditSelection | undefined>(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<AbortController | null>(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() {
|
||||
<>
|
||||
<header>
|
||||
<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>{status}</span>
|
||||
<span className={staged.length ? 'dirty' : ''}>
|
||||
{staged.length ? `未保存修改 ${staged.length} 项` : '所有修改已保存'}
|
||||
</span>
|
||||
{directEditEnabled ? (
|
||||
{editMode ? (
|
||||
<span className={editDiagnostics.some((item) => item.severity === 'error') ? 'dirty' : ''}>
|
||||
{editDiagnostics.find((item) => item.severity === 'error')?.message ||
|
||||
(element
|
||||
@@ -688,15 +673,15 @@ function App() {
|
||||
<Button onClick={() => void compile()}>
|
||||
<RefreshCw size={15} /> 保存并重新生成
|
||||
</Button>
|
||||
{directEditEnabled ? (
|
||||
{editMode ? (
|
||||
<>
|
||||
<Button onClick={() => void saveDirectEdits()} disabled={!session?.dirty}>
|
||||
<Save size={15} /> 保存直接编辑
|
||||
</Button>
|
||||
<Button onClick={undoEdit} disabled={!session?.canUndo && !overrideUndoRef.current.length}>
|
||||
<Button onClick={undoEdit} disabled={!session?.canUndo}>
|
||||
撤销
|
||||
</Button>
|
||||
<Button onClick={redoEdit} disabled={!session?.canRedo && !overrideRedoRef.current.length}>
|
||||
<Button onClick={redoEdit} disabled={!session?.canRedo}>
|
||||
重做
|
||||
</Button>
|
||||
<Button onClick={discardEdits} disabled={!session?.dirty && !staged.length}>
|
||||
@@ -765,6 +750,7 @@ function App() {
|
||||
</aside>
|
||||
<MapCanvas
|
||||
state={state}
|
||||
editMode={editMode}
|
||||
selected={selected}
|
||||
visible={layers}
|
||||
scene={scene}
|
||||
@@ -789,17 +775,8 @@ function App() {
|
||||
const along = metersAlongPolyline(line, toLonLat(to));
|
||||
const length = polylineLengthMeters(line);
|
||||
if (along === null || !(length > 0)) return;
|
||||
const existing = [...state.overrides.overrides, ...staged]
|
||||
.reverse()
|
||||
.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]);
|
||||
const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along));
|
||||
if (draft) requester?.schedule(draft);
|
||||
}}
|
||||
onLaneSelectionDragEnd={(from, to) => {
|
||||
if (!element || element.kind !== 'lane-maneuver') return;
|
||||
@@ -811,16 +788,8 @@ function App() {
|
||||
const along = metersAlongPolyline(line, toLonLat(to));
|
||||
const length = polylineLengthMeters(line);
|
||||
if (along === null || !(length > 0)) return;
|
||||
const existing = [...state.overrides.overrides, ...staged]
|
||||
.reverse()
|
||||
.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),
|
||||
});
|
||||
const draft = draftLane(element.laneId, element.maneuver, Math.max(0, length - along));
|
||||
if (draft) commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]);
|
||||
setStatus('箭头位置已暂存;保存并重新生成后应用。');
|
||||
}}
|
||||
preview={preview}
|
||||
@@ -859,8 +828,10 @@ function App() {
|
||||
stage={stage}
|
||||
status={setStatus}
|
||||
setState={setState}
|
||||
session={session}
|
||||
onLaneManeuverChange={applyLaneManeuver}
|
||||
>
|
||||
{directEditEnabled ? (
|
||||
{editMode ? (
|
||||
<ParameterPanel
|
||||
handles={editHandles}
|
||||
hasSelection={Boolean(selected)}
|
||||
@@ -920,6 +891,8 @@ function Inspector({
|
||||
stage,
|
||||
status,
|
||||
setState,
|
||||
session,
|
||||
onLaneManeuverChange,
|
||||
children,
|
||||
}: {
|
||||
road: Road | null;
|
||||
@@ -930,6 +903,8 @@ function Inspector({
|
||||
stage: (item: Override) => void;
|
||||
status: (value: string) => void;
|
||||
setState: (next: WorkbenchState) => void;
|
||||
session: EditSession | null;
|
||||
onLaneManeuverChange: (maneuver: string, placementDistanceMeters: number) => void;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const [width, setWidth] = useState(0);
|
||||
@@ -1067,7 +1042,22 @@ function Inspector({
|
||||
open={open === '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} />
|
||||
<SignalEditor state={state} signal={signal} status={status} update={updateSignal} />
|
||||
</InspectorSection>
|
||||
@@ -1176,41 +1166,23 @@ const MANEUVER_OPTIONS: Array<[string, string]> = [
|
||||
];
|
||||
function LaneManeuverEditor({
|
||||
element,
|
||||
overrides,
|
||||
stage,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
element: ElementSelection | null;
|
||||
overrides: Override[];
|
||||
stage: (item: Override) => void;
|
||||
value?: { maneuver?: string; placementDistanceMeters?: number };
|
||||
onChange: (maneuver: string, placementDistanceMeters: number) => void;
|
||||
}) {
|
||||
if (!element || element.kind !== 'lane-maneuver') return null;
|
||||
// Old override files may use arbitrary ids. Reuse the latest matching entry
|
||||
// so staging replaces it instead of leaving two conflicting maneuvers on one lane.
|
||||
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,
|
||||
});
|
||||
const maneuver = value?.maneuver ?? element.maneuver;
|
||||
const placementDistanceMeters = value?.placementDistanceMeters ?? element.placementDistanceMeters ?? 6;
|
||||
return (
|
||||
<form className="element-form">
|
||||
<h2>车道转向箭头</h2>
|
||||
<p className="form-context">第 {laneIndex(element.laneId)} 车道。拖曳地图中的虚线箭头可粗调位置。</p>
|
||||
<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]) => (
|
||||
<option value={value} key={value}>
|
||||
{label}
|
||||
@@ -1227,7 +1199,7 @@ function LaneManeuverEditor({
|
||||
value={placementDistanceMeters}
|
||||
onChange={(event) => {
|
||||
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>
|
||||
|
||||
@@ -13,7 +13,6 @@ import Style from 'ol/style/Style';
|
||||
import { click } from 'ol/events/condition';
|
||||
import type { GeoJson, Road, WorkbenchState } from '../types/state';
|
||||
import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers';
|
||||
import { directEditEnabled } from '../edit/flag';
|
||||
import { createHandleDragInteraction } from '../edit/drag-interaction';
|
||||
import { EditGhostLayer } from '../edit/ghost-layer';
|
||||
import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer';
|
||||
@@ -60,6 +59,7 @@ interface Props {
|
||||
onRangeEnd?: (range: IntervalRangeHandle, anchor: RoadIntervalAnchor) => void;
|
||||
/** Last solve came back degraded; hold the ghost instead of clearing it. */
|
||||
ghostPending?: boolean;
|
||||
editMode?: boolean;
|
||||
}
|
||||
export function MapCanvas({
|
||||
state,
|
||||
@@ -86,6 +86,7 @@ export function MapCanvas({
|
||||
onRangeDrag,
|
||||
onRangeEnd,
|
||||
ghostPending,
|
||||
editMode = false,
|
||||
}: Props) {
|
||||
const target = useRef<HTMLDivElement>(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. */
|
||||
const fittedAreaIdRef = useRef<string | null>(null);
|
||||
const laneSelectionSourceRef = useRef<VectorSource | null>(null);
|
||||
const laneSelectionLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
|
||||
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
|
||||
const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
|
||||
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
|
||||
@@ -133,9 +135,11 @@ export function MapCanvas({
|
||||
const selectedRef = useRef<Road | null>(selected);
|
||||
const stateRef = useRef(state);
|
||||
const sceneRef = useRef(scene);
|
||||
const editModeRef = useRef(editMode);
|
||||
selectedRef.current = selected;
|
||||
stateRef.current = state;
|
||||
sceneRef.current = scene;
|
||||
editModeRef.current = editMode;
|
||||
hiddenMarkingIdsRef.current = new Set(
|
||||
laneSelectionHiddenIds ??
|
||||
(laneSelectionFeatures ?? [])
|
||||
@@ -164,16 +168,15 @@ export function MapCanvas({
|
||||
}),
|
||||
});
|
||||
laneSelectionSourceRef.current = laneSelectionSource;
|
||||
laneSelectionLayerRef.current = laneSelectionLayer;
|
||||
// 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.
|
||||
const handleLayer = directEditEnabled ? new EditHandleLayer() : null;
|
||||
const ghost = directEditEnabled ? new EditGhostLayer() : null;
|
||||
const previewLayer = directEditEnabled
|
||||
? new EditPreviewLayer(
|
||||
() => selectedRef.current,
|
||||
() => sceneRef.current,
|
||||
)
|
||||
: null;
|
||||
const handleLayer = new EditHandleLayer();
|
||||
const ghost = new EditGhostLayer();
|
||||
const previewLayer = new EditPreviewLayer(
|
||||
() => selectedRef.current,
|
||||
() => sceneRef.current,
|
||||
);
|
||||
handleLayerRef.current = handleLayer;
|
||||
ghostRef.current = ghost;
|
||||
previewRef.current = previewLayer;
|
||||
@@ -204,6 +207,7 @@ export function MapCanvas({
|
||||
map.addInteraction(
|
||||
new PointerInteraction({
|
||||
handleDownEvent: (event) => {
|
||||
if (!editModeRef.current) return false;
|
||||
const hit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
|
||||
layerFilter: (layer) => layer === laneSelectionLayer,
|
||||
hitTolerance: 10,
|
||||
@@ -258,8 +262,8 @@ export function MapCanvas({
|
||||
createHandleDragInteraction({
|
||||
layer: handleLayer.layer,
|
||||
ghost,
|
||||
handleAt: (handleId) => handleLayer.handle(handleId),
|
||||
rangeAt: (handleId) => handleLayer.range(handleId),
|
||||
handleAt: (handleId) => (editModeRef.current ? handleLayer.handle(handleId) : undefined),
|
||||
rangeAt: (handleId) => (editModeRef.current ? handleLayer.range(handleId) : undefined),
|
||||
onDrag: (handle, value) => dragRef.current.onHandleDrag?.(handle, value),
|
||||
onEnd: (handle, value) => dragRef.current.onHandleDragEnd?.(handle, value),
|
||||
onRangeDrag: (range, anchor) => dragRef.current.onRangeDrag?.(range, anchor),
|
||||
@@ -320,6 +324,7 @@ export function MapCanvas({
|
||||
useEffect(() => {
|
||||
const source = laneSelectionSourceRef.current;
|
||||
if (!source) return;
|
||||
laneSelectionLayerRef.current?.setVisible(editMode);
|
||||
source.clear();
|
||||
const parts = (laneSelectionFeatures ?? []).flatMap((feature) => {
|
||||
const coordinates = feature.geometry?.coordinates;
|
||||
|
||||
@@ -28,6 +28,7 @@ function readFlag(): boolean {
|
||||
* Resolved once at module load so a single render pass cannot see the flag flip
|
||||
* 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();
|
||||
|
||||
/**
|
||||
|
||||
@@ -108,6 +108,7 @@ export function metersToStation(meters: number, roadLengthMeters: number): numbe
|
||||
}
|
||||
|
||||
const KIND_LABELS: Record<ConstraintKind, string> = {
|
||||
'lane-maneuver': '导向箭头位置',
|
||||
'road-edge-offset': '外缘偏移',
|
||||
'road-sidewalk-width': '步行带宽度',
|
||||
'road-lane-divider': '车道分隔',
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import type {
|
||||
AnchorSnapshot,
|
||||
ConstraintValue,
|
||||
LaneManeuverValue,
|
||||
EditHandle,
|
||||
JunctionReserve,
|
||||
RoadConstraint,
|
||||
@@ -92,6 +93,8 @@ export function constraintValueFor(
|
||||
transition: Transition = 'smoothstep',
|
||||
): ConstraintValue {
|
||||
switch (handle.kind) {
|
||||
case 'lane-maneuver':
|
||||
throw new Error('lane-maneuver requires laneManeuverValueFor');
|
||||
case 'road-edge-offset':
|
||||
return { offsetMeters: scalar, transition };
|
||||
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
|
||||
* junction reserves. Mirrors the window `makeRoadHandles()` centres its handles
|
||||
|
||||
@@ -9,6 +9,7 @@ import { reserveWindow, type IntervalWindow } from './projection';
|
||||
import {
|
||||
isControlKind,
|
||||
isRoadKind,
|
||||
LANE_KINDS,
|
||||
type EditHandle,
|
||||
type HandleManifest,
|
||||
type JunctionReserve,
|
||||
@@ -35,6 +36,10 @@ export function handlesForSegment(
|
||||
): EditHandle[] {
|
||||
if (!manifest || !segmentId) return [];
|
||||
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 (!isRoadKind(handle.kind)) return false;
|
||||
const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : undefined;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// imports from here rather than casting response fields locally, so there is one
|
||||
// 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 Transition = 'smoothstep' | 'linear';
|
||||
@@ -34,15 +34,18 @@ export const JUNCTION_KINDS = [
|
||||
// the panel when the corner grips exist to drive it.
|
||||
'junction-crosswalk-size',
|
||||
] as const;
|
||||
export const LANE_KINDS = ['lane-maneuver'] as const;
|
||||
|
||||
export type RoadConstraintKind = (typeof ROAD_KINDS)[number];
|
||||
export type ControlConstraintKind = (typeof CONTROL_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 SemanticAnchor =
|
||||
| { type: 'lane'; laneId: string; roadId?: string }
|
||||
| { type: 'road-station'; roadId: string; station: number; side?: Side }
|
||||
| {
|
||||
type: 'road-interval';
|
||||
@@ -99,6 +102,7 @@ export interface AnchorSnapshot {
|
||||
}
|
||||
|
||||
export type ConstraintValue =
|
||||
| { maneuver: string; placementDistanceMeters?: number }
|
||||
| { offsetMeters: number; transition?: Transition }
|
||||
| { widthMeters: number; transition?: Transition }
|
||||
| { boundaryIndex: number; offsetMeters: number; transition?: Transition }
|
||||
@@ -106,13 +110,18 @@ export type ConstraintValue =
|
||||
| { cutbackMeters: number }
|
||||
| { radiusMeters: number }
|
||||
| { insetMeters: number };
|
||||
export interface LaneManeuverValue {
|
||||
maneuver: string;
|
||||
placementDistanceMeters: number;
|
||||
}
|
||||
export type ConstraintValueWithLane = ConstraintValue | LaneManeuverValue;
|
||||
|
||||
export interface RoadConstraint {
|
||||
id: string;
|
||||
kind: ConstraintKind;
|
||||
anchor: SemanticAnchor;
|
||||
anchorSnapshot: AnchorSnapshot;
|
||||
value: ConstraintValue;
|
||||
value: ConstraintValueWithLane;
|
||||
enabled: boolean;
|
||||
status: ConstraintStatus;
|
||||
provenance: { operationId: string; createdAt: string; author?: string };
|
||||
@@ -207,7 +216,6 @@ export type EditSelection = { segment: string } | { junction: string };
|
||||
*/
|
||||
export interface EditPreviewRequest {
|
||||
previewSeq: number;
|
||||
overrides?: Override[];
|
||||
constraints?: RoadConstraint[];
|
||||
operations?: RoadEditOperation[];
|
||||
document?: RoadEditDocument;
|
||||
|
||||
@@ -73,6 +73,46 @@ aside {
|
||||
header .button {
|
||||
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 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 8px;
|
||||
|
||||
+1
-4
@@ -333,9 +333,6 @@ function editPreview(area, body = {}) {
|
||||
const activeState = readJson(activeStateFile);
|
||||
const persistedOverrides = loadOverrides(area.outputs.nativeRoadOverrides);
|
||||
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 resolution = resolveDirectEditConstraints(model, draft, {
|
||||
revisionId: activeState.activeRevisionId,
|
||||
@@ -343,7 +340,7 @@ function editPreview(area, body = {}) {
|
||||
compilerGeometryVersion: GEOMETRY_VERSION,
|
||||
selection: selectionFrom(body.selection),
|
||||
});
|
||||
const compiled = compileGeometry(model, previewOverrides, {
|
||||
const compiled = compileGeometry(model, persistedOverrides, {
|
||||
edgeLines: area.nativeRoad.edgeLines,
|
||||
junctionTemplates: area.nativeRoad.junctionTemplates,
|
||||
directEdit: resolution,
|
||||
|
||||
Reference in new issue
Block a user