feat(workbench): preview and drag lane turn arrows

This commit is contained in:
que01 committed 2026-09-01 11:47:35 +08:00
1 parent 9cb715a592
commit 6d80597642
8 files changed
+260 -17

No files matched your search

+57 -11
View File
@@ -15,7 +15,15 @@ import {
} from './edit/element';
import { directEditEnabled, intervalEditingSupported } from './edit/flag';
import type { ElementOutline } from './edit/handle-layer';
import { azimuthBetween, signedMetersAlongAxis, type Coordinate } from './edit/meters';
import {
azimuthBetween,
coordinateAtStation,
metersAlongPolyline,
polylineLengthMeters,
toLonLat,
type Coordinate,
} from './edit/meters';
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';
@@ -215,13 +223,29 @@ function App() {
const laneSelectionFeatures = useMemo(() => {
if (!element || element.kind !== 'lane-maneuver' || !state) return [];
const ids = new Set(element.featureIds);
return (
const existing =
state.layers.turnArrows?.features.filter((feature) => {
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;
if (existing.length && maneuver === element.maneuver && placementDistanceMeters === element.placementDistanceMeters)
return existing;
const lane = state.layers.laneCenterlines?.features.find(
(feature) => feature.properties?.native_id === element.laneId,
);
}, [element, state]);
const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null;
const distance = placementDistanceMeters ?? 6;
if (!line || line.length < 2 || !maneuver) return [];
return previewArrowFeatures(element.laneId, maneuver, line, distance);
}, [element, staged, 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);
@@ -229,6 +253,23 @@ function App() {
const end = road?.centerline.at(-1);
return previous && end ? azimuthBetween(previous, end) : null;
}, [element, state]);
const laneSelectionAnchor = useMemo<Coordinate | null>(() => {
if (!element || element.kind !== 'lane-maneuver' || !state) return null;
const lane = state.layers.laneCenterlines?.features.find(
(feature) => feature.properties?.native_id === element.laneId,
);
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 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();
// Per-frame drag feedback reaches the panel through this rather than through
@@ -653,14 +694,19 @@ function App() {
element={elementOutline}
laneSelectionBounds={laneSelectionBounds}
laneSelectionFeatures={laneSelectionFeatures}
laneSelectionHiddenIds={element?.kind === 'lane-maneuver' ? element.featureIds : []}
laneSelectionAnchor={laneSelectionAnchor}
laneSelectionAxisAzimuth={laneSelectionAxisAzimuth}
onLaneSelectionDragEnd={(from, to) => {
if (!element || element.kind !== 'lane-maneuver' || element.placementDistanceMeters === undefined) return;
const road = state.compiled.model.roads.find((item) => item.id === element.roadId);
const previous = road?.centerline.at(-2);
const end = road?.centerline.at(-1);
if (!previous || !end) return;
const deltaTowardJunction = signedMetersAlongAxis(from, to, azimuthBetween(previous, end));
if (!element || element.kind !== 'lane-maneuver') return;
const lane = state.layers.laneCenterlines?.features.find(
(feature) => feature.properties?.native_id === element.laneId,
);
const line = lane?.geometry?.type === 'LineString' ? (lane.geometry.coordinates as Coordinate[]) : null;
if (!line || line.length < 2) return;
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);
@@ -669,7 +715,7 @@ function App() {
kind: 'lane-maneuver',
laneId: element.laneId,
maneuver: typeof existing?.maneuver === 'string' ? existing.maneuver : element.maneuver,
placementDistanceMeters: Math.max(0, element.placementDistanceMeters - deltaTowardJunction),
placementDistanceMeters: Math.max(0, length - along),
});
setStatus('箭头位置已暂存;保存并重新生成后应用。');
}}
+26 -5
View File
@@ -41,7 +41,11 @@ interface Props {
laneSelectionBounds?: Coordinate[] | null;
/** Polygon parts copied to the drag feedback layer; baseline parts are hidden by id. */
laneSelectionFeatures?: GeoJson['features'];
laneSelectionHiddenIds?: string[];
/** The lane centerline point that anchors every part of the selected arrow. */
laneSelectionAnchor?: Coordinate | null;
laneSelectionAxisAzimuth?: number | null;
/** Receives the axis-projected final map coordinate. */
onLaneSelectionDragEnd?: (from: Coordinate, to: Coordinate) => void;
/** Authoritative preview geometry; null returns the map to the baseline. */
preview?: Partial<Record<PreviewLayerName, GeoJson | null>> | null;
@@ -69,6 +73,8 @@ export function MapCanvas({
element,
laneSelectionBounds,
laneSelectionFeatures,
laneSelectionHiddenIds,
laneSelectionAnchor,
laneSelectionAxisAzimuth,
onLaneSelectionDragEnd,
preview,
@@ -87,6 +93,7 @@ export function MapCanvas({
const previewRef = useRef<EditPreviewLayer | null>(null);
const laneSelectionSourceRef = useRef<VectorSource | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const laneSelectionAnchorRef = useRef<Coordinate | null>(null);
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
const visibleRef = useRef(visible);
visibleRef.current = visible;
@@ -124,10 +131,12 @@ export function MapCanvas({
stateRef.current = state;
sceneRef.current = scene;
hiddenMarkingIdsRef.current = new Set(
(laneSelectionFeatures ?? [])
.map((feature) => feature.properties?.native_id)
.filter((id): id is string => typeof id === 'string'),
laneSelectionHiddenIds ??
(laneSelectionFeatures ?? [])
.map((feature) => feature.properties?.native_id)
.filter((id): id is string => typeof id === 'string'),
);
laneSelectionAnchorRef.current = laneSelectionAnchor ?? null;
useEffect(() => {
if (!target.current) return;
const layers = createLayers(
@@ -181,6 +190,7 @@ export function MapCanvas({
});
map.addInteraction(select);
let laneDragOrigin: Coordinate | null = null;
let laneDragAnchor: Coordinate | null = null;
let laneDragFeatures: Feature[] = [];
map.addInteraction(
new PointerInteraction({
@@ -191,8 +201,9 @@ export function MapCanvas({
});
if (!hit) return false;
laneDragOrigin = event.coordinate as Coordinate;
laneDragAnchor = laneSelectionAnchorRef.current ? fromLonLat(laneSelectionAnchorRef.current) : null;
laneDragFeatures = laneSelectionFeaturesRef.current.map((feature) => feature.clone());
return true;
return Boolean(laneDragAnchor);
},
handleDragEvent: (event) => {
const axis = dragRef.current.laneSelectionAxisAzimuth;
@@ -214,8 +225,18 @@ export function MapCanvas({
});
},
handleUpEvent: (event) => {
if (laneDragOrigin) dragRef.current.onLaneSelectionDragEnd?.(laneDragOrigin, event.coordinate as Coordinate);
const axis = dragRef.current.laneSelectionAxisAzimuth;
if (laneDragOrigin && laneDragAnchor && axis !== null && axis !== undefined) {
const to = event.coordinate as Coordinate;
const projectedPointer = fromLonLat(
offsetCoordinate(toLonLat(laneDragOrigin), axis, signedMetersAlongAxis(laneDragOrigin, to, axis)),
);
const dx = projectedPointer[0] - laneDragOrigin[0];
const dy = projectedPointer[1] - laneDragOrigin[1];
dragRef.current.onLaneSelectionDragEnd?.(laneDragOrigin, [laneDragAnchor[0] + dx, laneDragAnchor[1] + dy]);
}
laneDragOrigin = null;
laneDragAnchor = null;
laneDragFeatures = [];
return false;
},
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import { arrowPreviewRings, previewArrowFeatures } from './arrow-preview';
import { coordinateAtStation, polylineLengthMeters, type Coordinate } from './meters';
const lane: Coordinate[] = [
[116.397, 39.9],
[116.397, 39.91],
];
describe('arrow preview geometry', () => {
it('uses the compiler part counts for each maneuver', () => {
expect(arrowPreviewRings('through', lane, 6)).toHaveLength(1);
expect(arrowPreviewRings('left', lane, 6)).toHaveLength(3);
expect(arrowPreviewRings('right', lane, 6)).toHaveLength(3);
expect(arrowPreviewRings('through;left', lane, 6)).toHaveLength(3);
expect(arrowPreviewRings('through;right', lane, 6)).toHaveLength(3);
expect(arrowPreviewRings('through;left;right', lane, 6)).toHaveLength(5);
});
it('keeps angular parts instead of replacing them with rectangles', () => {
const [head] = arrowPreviewRings('through', lane, 6);
expect(new Set(head.map(([lon, lat]) => `${lon.toFixed(8)}:${lat.toFixed(8)}`)).size).toBeGreaterThan(4);
expect(head[0]).toEqual(head.at(-1));
});
it('points the arrow tip toward the lane junction end', () => {
const distance = 6;
const [head] = arrowPreviewRings('through', lane, distance);
const total = polylineLengthMeters(lane);
const center = coordinateAtStation(lane, 1 - distance / total)!;
expect(head[0][1]).toBeGreaterThan(center[1]);
});
it('assigns stable preview ids to every part', () => {
const features = previewArrowFeatures('lane:1', 'left', lane, 6);
expect(features.map((feature) => feature.properties?.native_id)).toEqual([
'lane-preview:lane:1:left:0',
'lane-preview:lane:1:left:1',
'lane-preview:lane:1:left:2',
]);
});
});
@@ -0,0 +1,90 @@
import { azimuthBetween, coordinateAtStation, offsetCoordinate, polylineLengthMeters, type Coordinate } from './meters';
import type { GeoFeature } from '../types/state';
type Ring = Coordinate[];
const angularTemplate = (assetId: string): Ring[] => {
const shaftWidth = 0.3;
const shaftHalf = shaftWidth / 2;
const straightBase = 1.18;
const straightTip = 1.92;
const throughHead = (): Ring => [
[0, straightTip],
[-0.42, straightBase],
[-shaftHalf, straightBase],
[-shaftHalf, 0],
[shaftHalf, 0],
[shaftHalf, straightBase],
[0.42, straightBase],
[0, straightTip],
];
const diagonalShaft = (side: number): Ring => {
const start: Coordinate = [0, 0.56];
const end: Coordinate = [side * 0.72, 0.96];
const length = Math.hypot(end[0] - start[0], end[1] - start[1]);
const normal = [(-(end[1] - start[1]) / length) * shaftHalf, ((end[0] - start[0]) / length) * shaftHalf];
return [
[start[0] + normal[0], start[1] + normal[1]],
[end[0] + normal[0], end[1] + normal[1]],
[end[0] - normal[0], end[1] - normal[1]],
[start[0] - normal[0], start[1] - normal[1]],
[start[0] + normal[0], start[1] + normal[1]],
];
};
const diagonalHead = (side: number): Ring => {
const base: Coordinate = [side * 0.6, 0.89];
const tip: Coordinate = [side * 1.22, 1.24];
const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]);
const normal = [(-(tip[1] - base[1]) / length) * 0.36, ((tip[0] - base[0]) / length) * 0.36];
return [tip, [base[0] + normal[0], base[1] + normal[1]], [base[0] - normal[0], base[1] - normal[1]], tip];
};
const turnStem = (side: number): Ring => {
const cutMidpoint = 0.73;
const cutRise = side * 0.084;
return [
[-shaftHalf, 0],
[shaftHalf, 0],
[shaftHalf, cutMidpoint + cutRise],
[-shaftHalf, cutMidpoint - cutRise],
[-shaftHalf, 0],
];
};
if (assetId === 'through') return [throughHead()];
if (assetId === 'right') return [turnStem(1), diagonalShaft(1), diagonalHead(1)];
if (assetId === 'left') return [turnStem(-1), diagonalShaft(-1), diagonalHead(-1)];
if (assetId === 'through;right') return [throughHead(), diagonalShaft(1), diagonalHead(1)];
if (assetId === 'through;left') return [throughHead(), diagonalShaft(-1), diagonalHead(-1)];
if (assetId === 'through;left;right')
return [throughHead(), diagonalShaft(-1), diagonalHead(-1), diagonalShaft(1), diagonalHead(1)];
return [];
};
/** Build the same angular arrow parts used by the compiler, at a lane station. */
export function arrowPreviewRings(maneuver: string, line: Coordinate[], distance: number): Ring[] {
const total = polylineLengthMeters(line);
if (line.length < 2 || !(total > 0)) return [];
const station = Math.max(0, Math.min(1, 1 - distance / total));
const center = coordinateAtStation(line, station);
if (!center) return [];
const before = coordinateAtStation(line, Math.max(0, station - Math.min(0.01, station))) || line[0];
const axis = azimuthBetween(before, center);
return angularTemplate(maneuver).map((template) => {
const ring = template.map(([side, forward]) =>
offsetCoordinate(offsetCoordinate(center, axis, forward), axis + 90, side),
);
return ring;
});
}
export function previewArrowFeatures(
laneId: string,
maneuver: string,
line: Coordinate[],
distance: number,
): GeoFeature[] {
return arrowPreviewRings(maneuver, line, distance).map((ring, part) => ({
type: 'Feature',
properties: { native_id: `lane-preview:${laneId}:${maneuver}:${part}` },
geometry: { type: 'Polygon', coordinates: [ring] },
}));
}
@@ -172,6 +172,7 @@ describe('elementSelectionFor', () => {
kind: 'lane-maneuver',
laneId: 'lane:road:way/-3246:forward:2',
maneuver: '',
placementDistanceMeters: 6,
roadId: 'road:way/-3246:forward',
featureIds: ['lane:road:way/-3246:forward:2'],
});
+3 -1
View File
@@ -184,7 +184,9 @@ export function elementSelectionFor(
if (!spec && properties?.source === LANE_CENTERLINE_SOURCE) {
const laneId = text(properties.native_id);
const roadId = text(properties.road_id);
return laneId && roadId ? { kind: 'lane-maneuver', laneId, maneuver: '', roadId, featureIds: [laneId] } : null;
return laneId && roadId
? { kind: 'lane-maneuver', laneId, maneuver: '', placementDistanceMeters: 6, roadId, featureIds: [laneId] }
: null;
}
const elementId = elementIdOf(properties);
if (!spec || !elementId) return null;
+18
View File
@@ -4,6 +4,7 @@ import {
coordinateAtStation,
fromLonLat,
haversineMeters,
metersAlongPolyline,
mercatorUnitsForMeters,
offsetCoordinate,
polylineLengthMeters,
@@ -141,6 +142,23 @@ describe('station interpolation', () => {
});
});
describe('polyline projection', () => {
const bent: Coordinate[] = [
[0, 0],
[0, 0.001],
[0.001, 0.001],
];
it('uses the closest segment rather than a road-wide drag axis', () => {
const along = metersAlongPolyline(bent, [0.00075, 0.00102]);
expect(along).toBeCloseTo(polylineLengthMeters(bent) * 0.875, 1);
});
it('returns null when there is no usable segment', () => {
expect(metersAlongPolyline([[0, 0]], [0, 0])).toBeNull();
});
});
describe('bearings', () => {
it('reads the cardinal directions', () => {
expect(azimuthBetween([0, 0], [0, 0.001])).toBeCloseTo(0, 4);
+23
View File
@@ -55,6 +55,29 @@ export function polylineLengthMeters(line: Coordinate[]): number {
return total;
}
/**
* Arc distance to the closest point on a polyline, in meters from its first
* coordinate. Drag release uses this to turn a map point back into a lane
* placement without assuming the lane is straight.
*/
export function metersAlongPolyline(line: Coordinate[], point: Coordinate): number | null {
let traversed = 0;
let best: { distance: number; along: number } | null = null;
for (let index = 1; index < line.length; index += 1) {
const start = line[index - 1];
const end = line[index];
const { east: dx, north: dy } = eastNorthMeters(start, end);
const { east: px, north: py } = eastNorthMeters(start, point);
const length = Math.hypot(dx, dy);
if (length < 0.001) continue;
const ratio = clamp((px * dx + py * dy) / (length * length), 0, 1);
const distance = Math.hypot(px - dx * ratio, py - dy * ratio);
if (!best || distance < best.distance) best = { distance, along: traversed + length * ratio };
traversed += length;
}
return best?.along ?? null;
}
/**
* Local east/north components of a displacement, in meters. Each component is a
* spherical distance measured along a parallel or a meridian, so the result