feat: drag lane turn arrows along their lanes

This commit is contained in:
que01 committed 2026-09-01 10:24:59 +08:00
1 parent 5457f960ff
commit 9cb715a592
12 files changed
+335 -24

No files matched your search

@@ -0,0 +1,2 @@
{"file": ".trellis/spec/frontend/direct-edit-client.md", "reason": "Check no baseline writes, per-pointermove React churn, or accidental rotation path."}
{"file": ".trellis/spec/guides/cross-layer-thinking-guide.md", "reason": "Check position serialization, validation, and recompile behavior across layers."}
@@ -0,0 +1,28 @@
# Design: Lane Maneuver Position Drag
## Selection And Gesture
The selected arrow group remains one logical target: `lane_id + maneuver`. A new
display-only selection layer will become the drag hit target, while its members are
never moved independently. Pointer coordinates are projected onto the lane centerline
and converted to a distance from the lane's junction end, matching the compiler's
`placement_distance_meters` convention.
## Contract
The existing `lane-maneuver` override gains optional finite, non-negative
`placementDistanceMeters`, measured from the lane's junction end. The compiler uses
it when present, otherwise keeps its current candidate-placement algorithm
byte-for-byte. Maneuver and position are updated together by lane id so an old
maneuver override cannot shadow a newer position entry.
## Validation And Preview
The server remains authoritative for collision checks and final geometry. The client
may project and clamp the ghost for responsive feedback, but it must submit the
position through the existing save/recompile boundary and never mutate baseline
GeoJSON. The candidate position must clear control features and leave the compiler's
endpoint safety buffer.
Rotation is intentionally absent from the contract; adding it later must not require
reinterpretation of the position field.
@@ -0,0 +1,2 @@
{"file": ".trellis/spec/frontend/direct-edit-client.md", "reason": "Reuse the existing projection, ghost, baseline ownership, and save-boundary rules for a new lane-arrow gesture."}
{"file": ".trellis/spec/guides/cross-layer-thinking-guide.md", "reason": "Trace the new position field from UI through override validation and compiler placement."}
@@ -0,0 +1,14 @@
# Implementation Plan
1. Resolve invalid-position behavior and freeze the wire field name/units in the PRD.
2. Add compiler validation and placement override handling with empty-override parity tests.
3. Add a lane-arrow drag interaction that projects along the lane and moves the complete part group.
4. Add authoritative save/recompile wiring and focused client/server regression tests.
5. Run format, server tests, client type/unit tests, and production build; manually verify
an existing and a newly-added arrow in the workbench.
## Explicit Non-Goals
- Arrow rotation or arbitrary lateral movement.
- Position editing for `native-road-direction-arrow/v1`.
- Per-part dragging or a second undo/preview protocol.
@@ -0,0 +1,59 @@
# 车道转向箭头位置拖曳
## Goal
TBD.
## Requirements
- TBD
## Acceptance Criteria
- [ ] TBD
## Notes
- Keep `prd.md` focused on requirements, constraints, and acceptance criteria.
- Lightweight tasks can remain PRD-only.
- For complex tasks, add `design.md` for technical design and `implement.md` for execution planning before `task.py start`.
# 车道转向箭头位置拖曳
## 目标
让用户可以把一个完整的路口转向箭头沿所属车道拖到新的位置。箭头的 polygon
part 必须整体平移,内部形状、part 顺序和 `maneuver` 不变;旋转和箭头内容修改
不属于本任务。
## 已确认事实
- 一个视觉箭头由同一 `lane_id + maneuver` 下的 3 或 5 个 polygon part 组成,点击
任一 part 已能选中整组。
- 编译器目前以 `placement_distance_meters` 记录箭头距路口端的距离,并在 6/10/14/18/22m
候选位置中避开斑马线和停止线。该字段目前是输出值,还没有 override 合同。
- 车道中心线已作为无箭头车道的选择入口;位置拖曳必须同时适用于已有箭头和刚新增的箭头。
- 现有 v2 拖曳链路按车道轴投影、以服务端预览为准;箭头位置属于新的离散/连续混合
override,不能伪装成道路宽度或路口偏移 constraint。
## 范围
1. 拖曳完整 `lane_id + maneuver` 箭头组,保持 part 相对几何不变。
2. 将拖曳位置保存为 `lane-maneuver.placementDistanceMeters`(从车道驶入路口端量起的米数),
并在保存/重新生成后由编译器读取。
3. 位置必须沿车道中心线投影,不能改变横向位置;不能越过车道有效端点或与斑马线、停止线重叠。
4. 已有的 maneuver 下拉框继续有效;旋转手柄、角度字段和沿路 `directionArrows` 不在范围内。
## 验收标准
- [ ] 拖曳任一箭头 part 会整体移动同组所有 part,不拆散、不改变形状和旋转。
- [ ] 拖曳释放时位置按车道轴投影并受有效范围约束;服务端正式编译输出的
`placement_distance_meters` 反映新位置。
- [ ] 新增箭头后也能拖曳其位置;刷新或重新编译不会回到旧位置。
- [ ] 箭头不能落在斑马线/停止线范围内,也不能超出车道安全端点。
- [ ] 未设置位置覆盖时,输出与现有编译结果字节一致。
- [ ] 旋转、沿路重复方向箭头和既有 v2 控件行为不回归。
## 关键决策
当用户把箭头拖向无效区域(控制设施或安全端点)时,连续夹紧到最近合法位置,
并在拖动过程中让完整箭头组停在该位置。这个行为与现有 v2 数值拖曳一致。
@@ -0,0 +1,26 @@
{
"id": "lane-maneuver-position-drag",
"name": "lane-maneuver-position-drag",
"title": "车道转向箭头位置拖曳",
"description": "",
"status": "in_progress",
"dev_type": null,
"scope": null,
"package": null,
"priority": "P2",
"creator": "dingkang",
"assignee": "dingkang",
"createdAt": "2026-09-01",
"completedAt": null,
"branch": null,
"base_branch": "main",
"worktree_path": null,
"commit": null,
"pr_url": null,
"subtasks": [],
"children": [],
"parent": null,
"relatedFiles": [],
"notes": "",
"meta": {}
}
+38 -11
View File
@@ -348,6 +348,11 @@ function validateOverrides(value, model, options = {}) {
`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' ||
@@ -1549,7 +1554,7 @@ function compileLaneMarkings(model, overrides, lanes, diagnostics, junctionPlans
// 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 explicitManeuver = override !== undefined ? override : maneuvers[index];
const explicitManeuver = override ? override.maneuver : maneuvers[index];
if (!explicitManeuver) continue;
const maneuver = normalizeManeuver(explicitManeuver);
if (!lane) {
@@ -1598,14 +1603,17 @@ function compileLaneMarkings(model, overrides, lanes, diagnostics, junctionPlans
const length = Math.hypot(-vector[0], -vector[1]);
const axis = length ? [-vector[0] / length, -vector[1] / length] : null;
const placement = axis
? [6, 10, 14, 18, 22].find(
(distance) =>
distance < lineLengthMeters(lane.coordinates) - 2 &&
!ringsOverlapControl(
arrowRingsAt(maneuver, pointAlongLine([...lane.coordinates].reverse(), distance), axis),
controlFeatures,
),
)
? override?.placementDistanceMeters !== undefined
? nearestSafeTurnArrowPlacement(
lane.coordinates,
maneuver,
axis,
override.placementDistanceMeters,
controlFeatures,
)
: [6, 10, 14, 18, 22].find((distance) =>
safeTurnArrowPlacement(lane.coordinates, maneuver, axis, distance, controlFeatures),
)
: null;
if (!placement) {
diagnostics.push(
@@ -2368,8 +2376,27 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans)
}
/** The maneuver an override sets for a lane, or `undefined` when none applies. */
function laneManeuverOverride(overrides, laneId) {
const item = (overrides?.overrides || []).find((entry) => entry.kind === 'lane-maneuver' && entry.laneId === laneId);
return item ? item.maneuver : undefined;
return (overrides?.overrides || []).find((entry) => entry.kind === 'lane-maneuver' && entry.laneId === laneId);
}
function safeTurnArrowPlacement(line, maneuver, axis, distance, controls) {
return (
distance >= 2 &&
distance < lineLengthMeters(line) - 2 &&
!ringsOverlapControl(arrowRingsAt(maneuver, pointAlongLine([...line].reverse(), distance), axis), controls)
);
}
/** Clamp a dragged placement to the nearest 25cm safe position along its lane. */
function nearestSafeTurnArrowPlacement(line, maneuver, axis, desired, controls) {
const step = 0.25;
const limit = Math.max(0, lineLengthMeters(line) - 2);
const target = Math.max(2, Math.min(limit, desired));
for (let offset = 0; offset <= limit; offset += step) {
for (const distance of offset ? [target - offset, target + offset] : [target])
if (safeTurnArrowPlacement(line, maneuver, axis, distance, controls)) return Math.round(distance * 100) / 100;
}
return null;
}
function laneOverride(overrides, fromLaneId, toLaneId) {
+11
View File
@@ -49,6 +49,9 @@ assert.equal(model.roads.length, 24);
});
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/);
@@ -56,6 +59,14 @@ assert.equal(model.roads.length, 24);
// 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/,
+48 -2
View File
@@ -15,7 +15,7 @@ import {
} from './edit/element';
import { directEditEnabled, intervalEditingSupported } from './edit/flag';
import type { ElementOutline } from './edit/handle-layer';
import type { Coordinate } from './edit/meters';
import { azimuthBetween, signedMetersAlongAxis, type Coordinate } from './edit/meters';
import { rendersSame } from './edit/parameter';
import { PreviewRequester, type PreviewDraft } from './edit/preview-request';
import { anchorSnapshotFor, constraintValueFor, draftConstraint, operationFor } from './edit/projection';
@@ -212,6 +212,23 @@ function App() {
}) ?? [],
);
}, [element, state]);
const laneSelectionFeatures = useMemo(() => {
if (!element || element.kind !== 'lane-maneuver' || !state) return [];
const ids = new Set(element.featureIds);
return (
state.layers.turnArrows?.features.filter((feature) => {
const nativeId = feature.properties?.native_id;
return typeof nativeId === 'string' && ids.has(nativeId);
}) ?? []
);
}, [element, 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);
const previous = road?.centerline.at(-2);
const end = road?.centerline.at(-1);
return previous && end ? azimuthBetween(previous, end) : null;
}, [element, 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
@@ -635,6 +652,27 @@ function App() {
ranges={editRanges}
element={elementOutline}
laneSelectionBounds={laneSelectionBounds}
laneSelectionFeatures={laneSelectionFeatures}
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));
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, element.placementDistanceMeters - deltaTowardJunction),
});
setStatus('箭头位置已暂存;保存并重新生成后应用。');
}}
preview={preview}
ghostPending={session?.degraded ?? false}
onHandleDrag={(handle, value) => {
@@ -967,7 +1005,15 @@ function LaneManeuverEditor({
<select
value={maneuver}
onChange={(event) =>
stage({ id, kind: 'lane-maneuver', laneId: element.laneId, maneuver: event.target.value })
stage({
id,
kind: 'lane-maneuver',
laneId: element.laneId,
maneuver: event.target.value,
...(typeof override?.placementDistanceMeters === 'number'
? { placementDistanceMeters: override.placementDistanceMeters }
: {}),
})
}
>
{MANEUVER_OPTIONS.map(([value, label]) => (
+95 -9
View File
@@ -4,6 +4,7 @@ import Map from 'ol/Map';
import Polygon from 'ol/geom/Polygon';
import View from 'ol/View';
import Select from 'ol/interaction/Select';
import PointerInteraction from 'ol/interaction/Pointer';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
@@ -17,7 +18,7 @@ import { createHandleDragInteraction } from '../edit/drag-interaction';
import { EditGhostLayer } from '../edit/ghost-layer';
import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer';
import { EditPreviewLayer } from '../edit/preview-layer';
import { fromLonLat, type Coordinate } from '../edit/meters';
import { fromLonLat, offsetCoordinate, signedMetersAlongAxis, toLonLat, type Coordinate } from '../edit/meters';
import type { IntervalRangeHandle } from '../edit/selection';
import type { EditHandle, PreviewLayerName, RoadIntervalAnchor } from '../edit/types';
@@ -38,6 +39,10 @@ interface Props {
element?: ElementOutline | null;
/** A display-only outline for the selected v1 turn arrow. */
laneSelectionBounds?: Coordinate[] | null;
/** Polygon parts copied to the drag feedback layer; baseline parts are hidden by id. */
laneSelectionFeatures?: GeoJson['features'];
laneSelectionAxisAzimuth?: number | null;
onLaneSelectionDragEnd?: (from: Coordinate, to: Coordinate) => void;
/** Authoritative preview geometry; null returns the map to the baseline. */
preview?: Partial<Record<PreviewLayerName, GeoJson | null>> | null;
/** Live value during a drag — the caller debounces the preview request. */
@@ -63,6 +68,9 @@ export function MapCanvas({
ranges,
element,
laneSelectionBounds,
laneSelectionFeatures,
laneSelectionAxisAzimuth,
onLaneSelectionDragEnd,
preview,
onHandleDrag,
onHandleDragEnd,
@@ -78,6 +86,8 @@ export function MapCanvas({
const ghostRef = useRef<EditGhostLayer | null>(null);
const previewRef = useRef<EditPreviewLayer | null>(null);
const laneSelectionSourceRef = useRef<VectorSource | null>(null);
const laneSelectionFeaturesRef = useRef<Feature[]>([]);
const hiddenMarkingIdsRef = useRef<ReadonlySet<string>>(new Set());
const visibleRef = useRef(visible);
visibleRef.current = visible;
// Callbacks live in refs so the map is built once and never rebuilt when a
@@ -85,8 +95,26 @@ export function MapCanvas({
// the listener is registered once, so without a ref it would keep calling the
// first render's closure — harmless while those only called stable setters,
// but not once one of them reads current state.
const dragRef = useRef({ onHandleDrag, onHandleDragEnd, onHandleBlocked, onRangeDrag, onRangeEnd, ghostPending });
dragRef.current = { onHandleDrag, onHandleDragEnd, onHandleBlocked, onRangeDrag, onRangeEnd, ghostPending };
const dragRef = useRef({
onHandleDrag,
onHandleDragEnd,
onHandleBlocked,
onRangeDrag,
onRangeEnd,
onLaneSelectionDragEnd,
laneSelectionAxisAzimuth,
ghostPending,
});
dragRef.current = {
onHandleDrag,
onHandleDragEnd,
onHandleBlocked,
onRangeDrag,
onRangeEnd,
onLaneSelectionDragEnd,
laneSelectionAxisAzimuth,
ghostPending,
};
const selectRef = useRef({ onSelectRoad, onFeature, onBackground });
selectRef.current = { onSelectRoad, onFeature, onBackground };
const selectedRef = useRef<Road | null>(selected);
@@ -95,11 +123,17 @@ export function MapCanvas({
selectedRef.current = selected;
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'),
);
useEffect(() => {
if (!target.current) return;
const layers = createLayers(
() => selectedRef.current,
() => sceneRef.current,
() => hiddenMarkingIdsRef.current,
);
layersRef.current = layers;
const laneSelectionSource = new VectorSource();
@@ -108,7 +142,7 @@ export function MapCanvas({
zIndex: 90,
style: new Style({
stroke: new Stroke({ color: '#d49318', width: 2, lineDash: [6, 4] }),
fill: new Fill({ color: 'rgba(212, 147, 24, 0.12)' }),
fill: new Fill({ color: '#f5f6ee' }),
}),
});
laneSelectionSourceRef.current = laneSelectionSource;
@@ -146,6 +180,47 @@ export function MapCanvas({
style: null,
});
map.addInteraction(select);
let laneDragOrigin: Coordinate | null = null;
let laneDragFeatures: Feature[] = [];
map.addInteraction(
new PointerInteraction({
handleDownEvent: (event) => {
const hit = event.map.forEachFeatureAtPixel(event.pixel, (feature) => feature, {
layerFilter: (layer) => layer === laneSelectionLayer,
hitTolerance: 10,
});
if (!hit) return false;
laneDragOrigin = event.coordinate as Coordinate;
laneDragFeatures = laneSelectionFeaturesRef.current.map((feature) => feature.clone());
return true;
},
handleDragEvent: (event) => {
const axis = dragRef.current.laneSelectionAxisAzimuth;
if (!laneDragOrigin || axis === null || axis === undefined || !laneDragFeatures.length) return;
const origin = fromLonLat(toLonLat(laneDragOrigin));
const moved = fromLonLat(
offsetCoordinate(
toLonLat(laneDragOrigin),
axis,
signedMetersAlongAxis(laneDragOrigin, event.coordinate as Coordinate, axis),
),
);
const dx = moved[0] - origin[0];
const dy = moved[1] - origin[1];
laneSelectionFeaturesRef.current.forEach((feature, index) => {
const geometry = laneDragFeatures[index]?.getGeometry()?.clone();
geometry?.translate(dx, dy);
feature.setGeometry(geometry);
});
},
handleUpEvent: (event) => {
if (laneDragOrigin) dragRef.current.onLaneSelectionDragEnd?.(laneDragOrigin, event.coordinate as Coordinate);
laneDragOrigin = null;
laneDragFeatures = [];
return false;
},
}),
);
if (handleLayer && ghost) {
map.addInteraction(
createHandleDragInteraction({
@@ -211,13 +286,24 @@ export function MapCanvas({
const source = laneSelectionSourceRef.current;
if (!source) return;
source.clear();
if (laneSelectionBounds && laneSelectionBounds.length >= 3)
const parts = (laneSelectionFeatures ?? []).flatMap((feature) => {
const coordinates = feature.geometry?.coordinates;
if (feature.geometry?.type !== 'Polygon' || !Array.isArray(coordinates) || !Array.isArray(coordinates[0]))
return [];
const ring = coordinates[0] as Coordinate[];
return [new Feature({ geometry: new Polygon([ring.map(fromLonLat)]) })];
});
if (parts.length) source.addFeatures(parts);
else if (laneSelectionBounds && laneSelectionBounds.length >= 3)
source.addFeature(
new Feature({
geometry: new Polygon([[...laneSelectionBounds, laneSelectionBounds[0]].map(fromLonLat)]),
}),
new Feature({ geometry: new Polygon([[...laneSelectionBounds, laneSelectionBounds[0]].map(fromLonLat)]) }),
);
}, [laneSelectionBounds]);
laneSelectionFeaturesRef.current = parts;
}, [laneSelectionBounds, laneSelectionFeatures]);
useEffect(() => {
// Selection changes only affect presentation; compiler GeoJSON stays untouched.
layersRef.current?.markings.changed();
}, [laneSelectionFeatures]);
useEffect(() => {
// A non-degraded answer means the pending ghost has been superseded by real
// geometry. Clearing an empty ghost is a no-op, so this is safe mid-drag.
+3
View File
@@ -118,6 +118,7 @@ export interface LaneManeuverSelection {
laneId: string;
/** The current rendered maneuver; empty when the lane has no turn arrow. */
maneuver: string;
placementDistanceMeters?: number;
roadId: string;
featureIds: string[];
}
@@ -203,6 +204,8 @@ export function elementSelectionFor(
kind: 'lane-maneuver',
laneId,
maneuver,
placementDistanceMeters:
typeof first.placement_distance_meters === 'number' ? first.placement_distance_meters : undefined,
roadId,
featureIds: members
.map((member) => text(member.properties?.native_id))
+9 -2
View File
@@ -28,7 +28,11 @@ export type LayerName =
| 'connectors'
| 'diagnostics'
| 'selectedRoad';
export function createLayers(onRoad: () => Road | null, scene: () => boolean) {
export function createLayers(
onRoad: () => Road | null,
scene: () => boolean,
hiddenMarkingIds: () => ReadonlySet<string> = () => new Set(),
) {
const simple = (color: string, width = 1) =>
new Style({ fill: new Fill({ color: `${color}55` }), stroke: new Stroke({ color, width }) });
const layers: Record<LayerName, VectorLayer<VectorSource>> = {
@@ -66,7 +70,10 @@ export function createLayers(onRoad: () => Road | null, scene: () => boolean) {
}),
markings: new VectorLayer({
source: source(),
style: new Style({ fill: new Fill({ color: '#f5f6ee' }), stroke: new Stroke({ color: '#d9dacf', width: 1 }) }),
style: (feature) =>
hiddenMarkingIds().has(String(feature.get('native_id')))
? undefined
: new Style({ fill: new Fill({ color: '#f5f6ee' }), stroke: new Stroke({ color: '#d9dacf', width: 1 }) }),
}),
centerLines: new VectorLayer({
source: source(),