feat(workbench): stabilize junction tools workspace

This commit is contained in:
que01 committed 2026-09-04 09:46:19 +08:00
1 parent e6b822416d
commit f10a5da325
22 files changed
+1078 -53

No files matched your search

+122 -12
View File
@@ -31,7 +31,7 @@ import {
type Coordinate,
} from './edit/meters';
import { previewArrowFeatures } from './edit/arrow-preview';
import { rendersSame } from './edit/parameter';
import { formatParameterValue, rendersSame } from './edit/parameter';
import { PreviewRequester, type PreviewDraft } from './edit/preview-request';
import { clearEditHistory, recordEdit, takeRedoDomain, takeUndoDomain, type EditHistory } from './edit/edit-history';
import {
@@ -56,6 +56,7 @@ import type { LayerName } from './map/layers';
import type { JunctionRef } from './junction/hotspots';
import { junctionDescriptors, hotspotAt } from './junction/hotspots';
import { JunctionWorkspace } from './junction/JunctionWorkspace';
import { localJunctionPreview, localJunctionState } from './junction/local-state';
import {
applyJunctionDraft,
cancelJunctionSession,
@@ -161,6 +162,7 @@ function App() {
editMode,
state,
selectedSegmentId: selected?.segmentId,
selectedJunctionId: junctionRoute?.type === 'node' ? junctionRoute.id : undefined,
setStatus,
});
const {
@@ -178,6 +180,37 @@ function App() {
() => (state && junctionRoute ? hotspotAt(junctionDescriptors(state), junctionRoute) : null),
[junctionRoute, state],
);
const junctionRoads = useMemo(() => {
if (!state || !junctionDescriptor) return [];
const ids = new Set(junctionDescriptor.approachRoadIds);
// Configured clusters may not carry approach ids yet; derive them from the
// cluster's member nodes so the workspace still stays local to the junction.
if (!ids.size) {
const nodeIds = new Set(junctionDescriptor.nodeIds.map(String));
for (const endpoint of state.compiled.model.endpoints || []) {
if (nodeIds.has(String(endpoint.nodeId))) ids.add(endpoint.roadId);
}
}
const seen = new Set<string>();
return state.compiled.model.roads.filter((road) => {
if (!(ids.has(road.id) || ids.has(road.segmentId))) return false;
const key = road.tags?.name?.trim() || `unnamed:${road.id || road.segmentId}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}, [junctionDescriptor, state]);
const junctionMapState = useMemo(
() => (state && junctionDescriptor && junctionRoute ? localJunctionState(state, junctionDescriptor) : state),
[junctionDescriptor, junctionRoute, state],
);
const junctionMapPreview = useMemo(
() =>
state && junctionDescriptor && junctionRoute
? localJunctionPreview(preview, junctionDescriptor, state.compiled.model.roads)
: preview,
[junctionDescriptor, junctionRoute, preview, state],
);
// A deep link starts without a map click, so it has no selected approach from
// which the existing manifest loader can scope its request. Pick the first
// descriptor-owned approach here as well as in the click path; this is a
@@ -213,7 +246,9 @@ function App() {
(handle) =>
(handle.kind === 'junction-approach-width' ||
handle.kind === 'junction-cutback' ||
handle.kind === 'junction-corner-radius') &&
handle.kind === 'junction-corner-radius' ||
handle.kind === 'junction-crosswalk-inset' ||
handle.kind === 'junction-stop-line-offset') &&
'nodeId' in handle.anchor &&
nodeIds.has(String(handle.anchor.nodeId)),
);
@@ -371,7 +406,16 @@ function App() {
// Read at send time so the requester, built once, always scopes to the current
// selection without being rebuilt.
const selectionRef = useRef<EditSelection | undefined>(undefined);
selectionRef.current = selected?.segmentId ? { segment: selected.segmentId } : undefined;
// An independent JunctionTools page owns the whole junction manifest. Never
// fall back to the approach segment here: doing so makes an accepted preview
// replace the junction manifest with a road-scoped one, which drops the
// width/cutback/radius rows immediately after the first edit.
selectionRef.current =
junctionRoute?.type === 'node'
? { junction: junctionRoute.id }
: selected?.segmentId
? { segment: selected.segmentId }
: undefined;
/**
* One gesture, one operation id. Minted on the first draft of a drag and cleared
* on release: reusing an id across gestures would put two operations with the
@@ -412,8 +456,12 @@ function App() {
// control handles silently returned null and never scheduled a preview.
const roadId = 'roadId' in handle.anchor ? handle.anchor.roadId : null;
const segmentId = 'segmentId' in handle.anchor ? handle.anchor.segmentId : null;
const cornerRoadId = handle.anchor.type === 'junction-corner' ? handle.anchor.incomingRoadId : null;
const road = state?.compiled.model.roads.find(
(item) => (roadId ? item.id === roadId : false) || (segmentId ? item.segmentId === segmentId : false),
(item) =>
(roadId ? item.id === roadId : false) ||
(segmentId ? item.segmentId === segmentId : false) ||
(cornerRoadId ? item.id === cornerRoadId || item.segmentId === cornerRoadId : false),
);
// Without a centerline there is no snapshot to record, so drop the drag rather
// than send a constraint the server would have to reject.
@@ -435,6 +483,47 @@ function App() {
operations: [...base.operations.filter((item) => item.id !== operation.id), operation],
};
};
const draftForGroup = (handles: EditHandle[], value: number): PreviewDraft | null => {
if (!handles.length || !session) return null;
const drafts = handles
.map((handle) => draftFor(handle, value))
.filter((item): item is PreviewDraft => Boolean(item));
if (!drafts.length) return null;
const base = session.fragment();
const constraints = new Map(base.constraints.map((item) => [item.id, item]));
const operations = new Map(base.operations.map((item) => [item.id, item]));
for (const draft of drafts) {
for (const constraint of draft.constraints ?? []) constraints.set(constraint.id, constraint);
for (const operation of draft.operations ?? []) operations.set(operation.id, operation);
}
return { constraints: [...constraints.values()], operations: [...operations.values()] };
};
const settleGroup = (handles: EditHandle[], value: number) => {
// Keep individually customised entries intact: the manifest does not expose
// a separate scope bit, so the dominant current value is the group's default
// and outliers are treated as local overrides.
const frequencies = new Map<string, number>();
for (const handle of handles) {
const key = formatParameterValue(handle.value.current);
frequencies.set(key, (frequencies.get(key) ?? 0) + 1);
}
const defaultKey = [...frequencies.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
const changed = handles.filter(
(handle) =>
formatParameterValue(handle.value.current) === defaultKey && !rendersSame(value, handle.value.current),
);
if (!changed.length) {
abandonGesture();
return;
}
const draft = draftForGroup(changed, value);
if (draft)
commitGesture(
draft,
changed.map((handle) => `constraint:${handle.handleId}`),
);
else abandonGesture();
};
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,
@@ -520,6 +609,14 @@ function App() {
panelRef.current?.clearLive();
previewSession();
};
const discardJunctionDraft = () => {
if (!session) return;
session.discard();
gesture.current = null;
panelRef.current?.clearLive();
previewSession();
setJunctionSession((current) => (current ? cancelJunctionSession(current) : current));
};
/** A settled value from either channel: one undoable command, or nothing. */
const settleValue = (handle: EditHandle, value: number) => {
// A gesture that did not move the value must not become an edit. `handle` was
@@ -765,8 +862,9 @@ function App() {
const choice = window.prompt('路口有未应用草稿:输入 1 应用并返回,2 放弃并返回,3 留在工作区', '3');
if (choice === '3' || !choice) return;
if (choice === '1') setJunctionSession(applyJunctionDraft(junctionSession));
else if (choice === '2') setJunctionSession(cancelJunctionSession(junctionSession));
else return;
else if (choice === '2') {
discardJunctionDraft();
} else return;
}
window.history.pushState({}, '', '/');
setJunctionRoute(null);
@@ -790,7 +888,7 @@ function App() {
else if (properties.effective_style) setStatus('已选中标线,可在右侧暂存样式');
};
return (
<>
<div className={junctionRoute ? 'app junction-page' : 'app'}>
<header>
<strong>道路编译工作台</strong>
<label className="mode-switch">
@@ -906,8 +1004,9 @@ function App() {
</details>
</aside>
<MapCanvas
state={state}
state={junctionMapState!}
editMode={editMode}
focusJunctionId={junctionRoute?.type === 'node' ? junctionRoute.id : null}
selected={selected}
visible={layers}
scene={scene}
@@ -966,7 +1065,7 @@ function App() {
if (draft) commitGesture(draft, [`constraint:handle:lane-maneuver:${element.laneId}`]);
setStatus('箭头位置已暂存;保存并重新生成后应用。');
}}
preview={preview}
preview={junctionMapPreview}
ghostPending={session?.degraded ?? false}
onHandleDrag={(handle, value) => {
// Straight to the DOM, like the ghost writes straight to its source:
@@ -1037,7 +1136,7 @@ function App() {
facilitySummary={junctionFacilitySummary}
onClose={closeJunction}
onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))}
onDiscard={() => setJunctionSession((current) => (current ? cancelJunctionSession(current) : current))}
onDiscard={discardJunctionDraft}
onSave={() => {
try {
void saveDirectEdits().then((saved) => {
@@ -1052,19 +1151,30 @@ function App() {
editMode={editMode}
onEnableEdit={() => setEditMode(true)}
handles={junctionHandles}
onDraft={draftValue}
onDraft={(handle, value) => {
draftValue(handle, value);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onDraftGroup={(handles, value) => {
const draft = draftForGroup(handles, value);
if (draft) requester?.schedule(draft);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onSettle={(handle, value) => {
settleValue(handle, value);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
onSettleGroup={settleGroup}
onAbandon={abandonGesture}
onReset={(handle) => {
resetHandle(handle);
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}}
roads={junctionRoads}
junctionCoordinate={junctionDescriptor.coordinate}
/>
) : null}
</>
</div>
);
}
export default App;
+23 -6
View File
@@ -13,6 +13,7 @@ import CircleStyle from 'ol/style/Circle';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import { createEmpty, extend } from 'ol/extent';
import { click } from 'ol/events/condition';
import type { GeoJson, Road, WorkbenchState } from '../types/state';
import { createLayers, updateJunctionHotspots, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers';
@@ -71,6 +72,8 @@ interface Props {
/** Last solve came back degraded; hold the ghost instead of clearing it. */
ghostPending?: boolean;
editMode?: boolean;
/** When set, fit the map to one junction instead of the whole imported area. */
focusJunctionId?: string | null;
junctionHotspots?: boolean;
onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void;
}
@@ -105,6 +108,7 @@ export function MapCanvas({
onRangeEnd,
ghostPending,
editMode = false,
focusJunctionId = null,
junctionHotspots = true,
onJunctionHotspot,
}: Props) {
@@ -424,14 +428,27 @@ export function MapCanvas({
const layers = layersRef.current;
const map = mapRef.current;
if (!layers || !map) return;
updateLayers(layers, state, selected);
updateLayers(layers, state, selected, Boolean(focusJunctionId));
updateJunctionHotspots(layers, junctionDescriptors(state), junctionHotspots);
const extent = layers.osm.getSource()!.getExtent();
if (fittedAreaIdRef.current !== state.areaId && extent && Number.isFinite(extent[0])) {
map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 });
fittedAreaIdRef.current = state.areaId;
const junctionSource = layers.native.getSource();
const focusExtent = focusJunctionId ? createEmpty() : null;
if (focusExtent && junctionSource) {
junctionSource.getFeatures().forEach((feature) => {
const nativeId = feature.get('native_id');
if (nativeId === `junction:node/${focusJunctionId}`)
extend(focusExtent, feature.getGeometry()?.getExtent() ?? focusExtent);
});
}
}, [state, junctionHotspots]);
const extent = focusExtent && Number.isFinite(focusExtent[0]) ? focusExtent : layers.osm.getSource()!.getExtent();
const fitKey = focusJunctionId ? `${state.areaId}:junction:${focusJunctionId}` : state.areaId;
if (fittedAreaIdRef.current !== fitKey && extent && Number.isFinite(extent[0])) {
map.getView().fit(extent, {
padding: focusJunctionId ? [80, 470, 80, 80] : [48, 48, 48, 48],
maxZoom: focusJunctionId ? 20 : 19,
});
fittedAreaIdRef.current = fitKey;
}
}, [focusJunctionId, state, junctionHotspots]);
useEffect(() => {
const layers = layersRef.current;
if (!layers) return;
@@ -24,6 +24,7 @@
// unnoticed. Same invariant, two devices, two honest ways to say "no".
import { useImperativeHandle, useLayoutEffect, useRef, useState, type Ref } from 'react';
import { Minus, Plus } from 'lucide-react';
import {
formatBoundInward,
formatParameterValue,
@@ -63,6 +64,9 @@ interface RowCallbacks {
onAbandon: () => void;
/** Withdraw the constraint and return the row to the compiler's baseline. */
onReset: (handle: EditHandle) => void;
labelForHandle?: (handle: EditHandle) => string;
onDraftGroup?: (handles: EditHandle[], value: number) => void;
onSettleGroup?: (handles: EditHandle[], value: number) => void;
}
function ParameterRow({
@@ -72,6 +76,7 @@ function ParameterRow({
onSettle,
onAbandon,
onReset,
labelForHandle: resolveLabel,
}: RowCallbacks & {
handle: EditHandle;
register: (handleId: string, node: HTMLInputElement | null) => void;
@@ -92,6 +97,8 @@ function ParameterRow({
// previewable nor an error, so it must not light the field up red.
const verdict = parsed === null ? 'ok' : rangeVerdictOf(parsed, min, max);
const rejected = verdict !== 'ok';
const step = 0.1;
const displayLabel = resolveLabel?.(handle) ?? labelForHandle(handle);
const draft = (next: string) => {
setText(next);
@@ -101,6 +108,12 @@ function ParameterRow({
onDraft(handle, value);
};
const nudge = (direction: -1 | 1) => (event: React.MouseEvent) => {
event.preventDefault();
const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step));
draft(formatParameterValue(next));
};
const settle = () => {
const value = text === null ? null : parseParameterInput(text);
const touched = text !== null && text !== seeded.current;
@@ -140,7 +153,7 @@ function ParameterRow({
return (
<li className={reason ? 'parameter disabled' : 'parameter'}>
<span className="parameter-label">
{labelForHandle(handle)}
{displayLabel}
{isModified(handle) ? (
<>
<b className="parameter-dot" title="已修改" />
@@ -168,6 +181,12 @@ function ParameterRow({
onChange={(event) => draft(event.target.value)}
onBlur={settle}
onKeyDown={(event) => {
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
const direction = event.key === 'ArrowUp' ? 1 : -1;
const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step));
draft(formatParameterValue(next));
}
if (event.key === 'Enter') event.currentTarget.blur();
if (event.key === 'Escape') {
setText(null);
@@ -177,6 +196,14 @@ function ParameterRow({
}}
/>{' '}
<em>m</em>
<span className="parameter-stepper" aria-label={`${displayLabel}步进控制`}>
<button type="button" onMouseDown={nudge(-1)} disabled={Boolean(reason) || current <= min} title="减小">
<Minus size={13} />
</button>
<button type="button" onMouseDown={nudge(1)} disabled={Boolean(reason) || current >= max} title="增大">
<Plus size={13} />
</button>
</span>
</span>
<span className={rejected ? 'parameter-range rejected' : 'parameter-range'}>
{reason ?? (
@@ -200,11 +227,13 @@ function ParameterRow({
export function ParameterPanel({
handles,
hasSelection,
grouped = false,
ref,
...callbacks
}: RowCallbacks & {
handles: EditHandle[];
hasSelection: boolean;
grouped?: boolean;
ref?: Ref<ParameterPanelHandle>;
}) {
const nodes = useRef(new Map<string, HTMLInputElement>());
@@ -264,18 +293,113 @@ export function ParameterPanel({
}
});
const groupedHandles = new Map<string, EditHandle[]>();
for (const handle of handles) {
const list = groupedHandles.get(handle.kind) ?? [];
list.push(handle);
groupedHandles.set(handle.kind, list);
}
return (
<section className="parameters">
<h1>道路参数</h1>
<h1>{grouped ? '路口参数' : '道路参数'}</h1>
{handles.length ? (
<ul>
{handles.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
grouped ? (
<GroupedParameterList groups={[...groupedHandles.entries()]} register={register} {...callbacks} />
) : (
<ul>
{handles.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
)
) : (
<p className="parameter-empty">{hasSelection ? '当前道路无可编辑参数' : '选中道路以显示参数'}</p>
)}
</section>
);
}
function GroupedParameterList({
groups,
register,
...callbacks
}: RowCallbacks & {
groups: Array<[string, EditHandle[]]>;
register: (handleId: string, node: HTMLInputElement | null) => void;
}) {
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
return (
<ul className="parameter-groups">
{groups.map(([kind, items]) => {
const representative = items[0];
const dominant = items
.map((item) => item.value.current)
.sort(
(a, b) =>
items.filter((candidate) => formatParameterValue(candidate.value.current) === formatParameterValue(b))
.length -
items.filter((candidate) => formatParameterValue(candidate.value.current) === formatParameterValue(a))
.length,
)[0];
const globalHandle: EditHandle = {
...representative,
handleId: `group:${kind}`,
constraintId: undefined,
value: {
...representative.value,
current: dominant,
min: Math.max(...items.map((item) => item.value.min)),
max: Math.min(...items.map((item) => item.value.max)),
},
};
const expandedGroup = Boolean(expanded[kind]);
const globalDraft =
callbacks.onDraftGroup ?? ((group: EditHandle[], value: number) => callbacks.onDraft?.(group[0], value));
const globalSettle =
callbacks.onSettleGroup ?? ((group: EditHandle[], value: number) => callbacks.onSettle?.(group[0], value));
return (
<li className="parameter-group" key={kind}>
<div className="parameter-group__header">
<span>
<strong>{groupLabel(kind, representative)}</strong>
<small>统一设置 · {items.length} 项</small>
</span>
<button
type="button"
className="parameter-group__toggle"
onClick={() => setExpanded((current) => ({ ...current, [kind]: !expandedGroup }))}
>
{expandedGroup ? '收起单独定制' : '展开单独定制'}
</button>
</div>
<ParameterRow
handle={globalHandle}
register={register}
{...callbacks}
onDraft={(handle, value) => globalDraft(items, value)}
onSettle={(handle, value) => globalSettle(items, value)}
labelForHandle={() => '统一值'}
/>
{expandedGroup ? (
<ul className="parameter-group__details">
{items.map((handle) => (
<ParameterRow handle={handle} register={register} key={handle.handleId} {...callbacks} />
))}
</ul>
) : null}
</li>
);
})}
</ul>
);
}
function groupLabel(kind: string, handle: EditHandle): string {
if (kind === 'junction-approach-width') return '进口宽度';
if (kind === 'junction-cutback') return '进口 cutback';
if (kind === 'junction-corner-radius') return '角部圆角';
if (kind === 'junction-crosswalk-inset') return '斑马线退让';
if (kind === 'junction-stop-line-offset') return '停止线退距';
return labelForHandle(handle);
}
+1 -1
View File
@@ -206,7 +206,7 @@ describe('labelForHandle', () => {
outgoingRoadId: 'seg:2',
}),
),
).toBe('角部圆角');
).toBe('seg:1 → seg:2 · 角部圆角');
});
});
+7
View File
@@ -130,6 +130,13 @@ const KIND_LABELS: Record<ConstraintKind, string> = {
export function labelForHandle(handle: EditHandle): string {
const base = KIND_LABELS[handle.kind] ?? handle.kind;
const anchor = handle.anchor;
if (
(handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback') &&
anchor.type === 'junction-approach'
)
return `${anchor.segmentId} · ${base}`;
if (handle.kind === 'junction-corner-radius' && anchor.type === 'junction-corner')
return `${anchor.incomingRoadId} → ${anchor.outgoingRoadId} · ${base}`;
if ('boundaryIndex' in anchor && Number.isInteger(anchor.boundaryIndex)) return `${base} #${anchor.boundaryIndex}`;
if ('side' in anchor && anchor.side) return `${base}(${anchor.side === 'left' ? '左' : '右'})`;
return base;
@@ -12,11 +12,13 @@ export function useDirectEditSession({
editMode,
state,
selectedSegmentId,
selectedJunctionId,
setStatus,
}: {
editMode: boolean;
state?: WorkbenchState;
selectedSegmentId?: string;
selectedJunctionId?: string;
setStatus: (status: string) => void;
}) {
const [manifest, setManifest] = useState<HandleManifest | null>(null);
@@ -32,7 +34,13 @@ export function useDirectEditSession({
// Flag off: no manifest request at all, so the network trace matches browse mode.
if (!editMode) return;
api
.editState(selectedSegmentId ? { segment: selectedSegmentId } : undefined)
.editState(
selectedJunctionId
? { junction: selectedJunctionId }
: selectedSegmentId
? { segment: selectedSegmentId }
: undefined,
)
.then((value) => {
if (!('handles' in value)) return;
setManifest(value.handles);
@@ -43,7 +51,7 @@ export function useDirectEditSession({
touch();
})
.catch((error: Error) => setStatus(`直接编辑手柄不可用:${error.message}`));
}, [editMode, selectedSegmentId, setStatus, state]);
}, [editMode, selectedJunctionId, selectedSegmentId, setStatus, state]);
return {
session: sessionRef.current,
@@ -4,6 +4,9 @@ import { canEditJunction, type JunctionSession } from './workspace';
import { Button } from '../ui/button';
import { ParameterPanel } from '../components/ParameterPanel';
import type { EditHandle } from '../edit/types';
import type { Road } from '../types/state';
import type { Coordinate } from '../edit/meters';
import { junctionLabelForHandle, junctionRoadName } from './labels';
interface Props {
descriptor: JunctionDescriptor;
@@ -18,9 +21,13 @@ interface Props {
onEnableEdit?: () => void;
handles?: EditHandle[];
onDraft?: (handle: EditHandle, value: number) => void;
onDraftGroup?: (handles: EditHandle[], value: number) => void;
onSettle?: (handle: EditHandle, value: number) => void;
onSettleGroup?: (handles: EditHandle[], value: number) => void;
onAbandon?: () => void;
onReset?: (handle: EditHandle) => void;
roads?: Road[];
junctionCoordinate?: Coordinate;
}
export function JunctionWorkspace({
@@ -36,19 +43,22 @@ export function JunctionWorkspace({
facilitySummary = { crosswalks: 0, stopLines: 0, signals: 0 },
handles = [],
onDraft,
onDraftGroup,
onSettle,
onSettleGroup,
onAbandon,
onReset,
roads = [],
junctionCoordinate = descriptor.coordinate,
}: Props) {
const editable = useMemo(() => canEditJunction(descriptor), [descriptor]);
return (
<section className="junction-workspace" aria-label="路口编辑工作区">
<header className="junction-workspace__header">
<div>
<span className="junction-workspace__eyebrow">JunctionTools</span>
<h2>
{descriptor.ref.type === 'node' ? '路口节点' : '复杂路口上下文'} {descriptor.ref.id}
</h2>
<div className="junction-workspace__title-line">
<span className="junction-workspace__eyebrow">JunctionTools</span>
</div>
<p>
{editable
? editMode
@@ -65,9 +75,9 @@ export function JunctionWorkspace({
<div className="junction-workspace__body">
<dl>
<dt>组成节点</dt>
<dd>{descriptor.nodeIds.join(', ') || '—'}</dd>
<dd>{descriptor.nodeIds.length ? `${descriptor.nodeIds.length} 个路口节点` : '—'}</dd>
<dt>进口道路</dt>
<dd>{descriptor.approachRoadIds.join(', ') || '—'}</dd>
<dd>{roads.length ? roads.map((road) => junctionRoadName(road, roads)).join('、') : '—'}</dd>
<dt>诊断</dt>
<dd>{descriptor.diagnosticIds.length ? `${descriptor.diagnosticIds.length} 条` : '无'}</dd>
<dt>状态</dt>
@@ -98,10 +108,14 @@ export function JunctionWorkspace({
<ParameterPanel
handles={handles}
hasSelection
grouped
onDraft={onDraft ?? (() => undefined)}
onDraftGroup={onDraftGroup}
onSettle={onSettle ?? (() => undefined)}
onSettleGroup={onSettleGroup}
onAbandon={onAbandon ?? (() => undefined)}
onReset={onReset ?? (() => undefined)}
labelForHandle={(handle) => junctionLabelForHandle(handle, roads, junctionCoordinate)}
/>
<div className="junction-workspace__actions">
<Button onClick={onApply} disabled={!session.dirty}>
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import type { EditHandle } from '../edit/types';
import type { Road } from '../types/state';
import { junctionLabelForHandle } from './labels';
const roads = [
{
id: 'road-north',
segmentId: 'segment:way/-3254/0',
centerline: [
[120, 30],
[120, 30.001],
],
sourceNodeIds: ['junction'],
osmWayIds: [],
tags: { name: '创新大道' },
highway: 'primary',
direction: 'forward',
widthMeters: 7,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
{
id: 'road-east',
segmentId: 'segment:way/-3255/0',
centerline: [
[120, 30],
[120.001, 30],
],
sourceNodeIds: ['junction'],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
] as const;
function handle(anchor: EditHandle['anchor'], kind: EditHandle['kind']): EditHandle {
return {
handleId: 'h',
kind,
anchor,
position: [120, 30],
axisAzimuth: 0,
value: { current: 3, min: 1, max: 8, unit: 'meter' },
affects: [],
editable: true,
};
}
describe('junction handle labels', () => {
it('uses road name and geographic approach direction', () => {
expect(
junctionLabelForHandle(
handle(
{ type: 'junction-approach', nodeId: 'junction', segmentId: roads[0].segmentId },
'junction-approach-width',
),
roads as unknown as Road[],
[120, 30],
),
).toBe('创新大道 · 北进口 · 进口宽度');
});
it('uses a readable fallback when a road has no name', () => {
expect(
junctionLabelForHandle(
handle({ type: 'junction-approach', nodeId: 'junction', segmentId: roads[1].segmentId }, 'junction-cutback'),
roads as unknown as Road[],
[120, 30],
),
).toBe('道路2 · 东进口 · 进口 cutback');
});
});
+62
View File
@@ -0,0 +1,62 @@
import type { EditHandle } from '../edit/types';
import { azimuthBetween, haversineMeters, type Coordinate } from '../edit/meters';
import type { Road } from '../types/state';
import { labelForHandle } from '../edit/parameter';
const DIRECTIONS = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
function directionOf(azimuth: number): string {
return DIRECTIONS[Math.round((((azimuth % 360) + 360) % 360) / 45) % 8];
}
function roadForKey(roads: Road[], key: string): Road | undefined {
return roads.find((road) => road.id === key || road.segmentId === key);
}
function approachDirection(road: Road, junction: Coordinate): string | null {
if (road.centerline.length < 2) return null;
const first = road.centerline[0];
const last = road.centerline[road.centerline.length - 1];
const fromStart = haversineMeters(junction, first) <= haversineMeters(junction, last);
const outside = fromStart ? road.centerline[1] : road.centerline[road.centerline.length - 2];
return directionOf(azimuthBetween(junction, outside));
}
export function junctionRoadName(road: Road | undefined, roads: Road[] = []): string {
const name = road?.tags?.name?.trim();
if (name) return name;
const index = road ? roads.findIndex((item) => item.id === road.id) : -1;
return `道路${index >= 0 ? index + 1 : 1}`;
}
function approachName(road: Road | undefined, roads: Road[], junction: Coordinate): string {
if (!road) return '进口';
const direction = approachDirection(road, junction);
return `${junctionRoadName(road, roads)}${direction ? ` · ${direction}进口` : ' · 进口'}`;
}
/** User-facing labels for JunctionTools. Internal ids never appear in this text. */
export function junctionLabelForHandle(handle: EditHandle, roads: Road[], junction: Coordinate): string {
const base = labelForHandle(handle).replace(/^.* · /, '');
if (
(handle.kind === 'junction-approach-width' || handle.kind === 'junction-cutback') &&
handle.anchor.type === 'junction-approach'
) {
const anchor = handle.anchor;
const road = roads.find((item) => item.segmentId === anchor.segmentId);
return `${approachName(road, roads, junction)} · ${base}`;
}
if (handle.kind === 'junction-corner-radius' && handle.anchor.type === 'junction-corner') {
const incoming = roadForKey(roads, handle.anchor.incomingRoadId);
const outgoing = roadForKey(roads, handle.anchor.outgoingRoadId);
return `${approachName(incoming, roads, junction)} → ${approachName(outgoing, roads, junction)} · ${base}`;
}
if (
(handle.kind === 'junction-crosswalk-inset' || handle.kind === 'junction-stop-line-offset') &&
handle.anchor.type === 'junction-crossing'
) {
const road = roadForKey(roads, handle.anchor.roadId) ?? roadForKey(roads, handle.anchor.segmentId);
return `${approachName(road, roads, junction)} · ${base}`;
}
return base;
}
@@ -0,0 +1,115 @@
import { describe, expect, it } from 'vitest';
import { localJunctionPreview, localJunctionState } from './local-state';
import type { JunctionDescriptor } from './hotspots';
import type { WorkbenchState } from '../types/state';
const descriptor: JunctionDescriptor = {
ref: { type: 'node', id: 'junction-1' },
status: 'editable',
coordinate: [120, 30],
radiusMeters: 10,
nodeIds: ['junction-1'],
approachRoadIds: ['road-a'],
diagnosticIds: [],
source: 'junction-plan',
};
const state = {
areaId: 'test',
compiled: {
model: {
roads: [
{
id: 'road-a',
segmentId: 'segment-a',
sourceNodeIds: ['junction-1', 'end-a'],
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
{
id: 'road-b',
segmentId: 'segment-b',
sourceNodeIds: ['other', 'end-b'],
centerline: [],
osmWayIds: [],
tags: {},
highway: 'residential',
direction: 'forward',
widthMeters: 6,
laneCount: 2,
sidewalkLeft: false,
sidewalkRight: false,
},
],
endpoints: [
{ id: 'endpoint-a', roadId: 'road-a', side: 'end', nodeId: 'junction-1', coordinate: [120, 30] },
{ id: 'endpoint-b', roadId: 'road-b', side: 'end', nodeId: 'other', coordinate: [121, 31] },
],
connections: [{ id: 'connection-a', fromEndpointId: 'endpoint-a', toEndpointId: 'endpoint-a', enabled: true }],
},
movements: [],
diagnostics: [],
},
layers: {
nativeRoadSurface: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { road_id: 'road-a' }, geometry: null },
{ type: 'Feature', properties: { road_id: 'road-b' }, geometry: null },
],
},
crosswalks: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { crossing_node_id: 'junction-1' }, geometry: null },
{ type: 'Feature', properties: { crossing_node_id: 'other' }, geometry: null },
],
},
},
overrides: { schema: 'test', overrides: [] },
trafficSignals: { provenance: 'test', assemblies: { type: 'FeatureCollection', features: [] } },
trafficRuntime: { signals: [] },
comparison: {},
} as unknown as WorkbenchState;
describe('local junction state', () => {
it('keeps only the selected junction roads and related features', () => {
const local = localJunctionState(state, descriptor);
expect(local.compiled.model.roads.map((road) => road.id)).toEqual(['road-a']);
expect(local.layers.nativeRoadSurface?.features).toHaveLength(1);
expect(local.layers.crosswalks?.features).toHaveLength(1);
expect(local.compiled.model.endpoints.map((endpoint) => endpoint.id)).toEqual(['endpoint-a']);
});
it('scopes preview collections to the selected junction', () => {
const preview = localJunctionPreview(
{
roadSurface: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { road_id: 'road-a' }, geometry: null },
{ type: 'Feature', properties: { road_id: 'road-b' }, geometry: null },
],
},
crosswalks: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { crossing_node_id: 'junction-1' }, geometry: null },
{ type: 'Feature', properties: { crossing_node_id: 'other' }, geometry: null },
],
},
},
descriptor,
state.compiled.model.roads,
);
expect(preview?.roadSurface?.features).toHaveLength(1);
expect(preview?.crosswalks?.features).toHaveLength(1);
});
});
@@ -0,0 +1,128 @@
import type { GeoFeature, GeoJson, Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from './hotspots';
import type { PreviewLayerName } from '../edit/types';
const empty: GeoJson = { type: 'FeatureCollection', features: [] };
function text(value: unknown): string | null {
return typeof value === 'string' || typeof value === 'number' ? String(value) : null;
}
function related(feature: GeoFeature, nodeIds: Set<string>, roadIds: Set<string>, segmentIds: Set<string>): boolean {
const props = feature.properties || {};
const nodeKeys = ['node_id', 'osm_node_id', 'crossing_node_id', 'junction_node_id'];
if (
nodeKeys.some((key) => {
const value = text(props[key]);
return value !== null && nodeIds.has(value);
})
)
return true;
const roadKeys = ['road_id', 'source_road_id', 'from_road_id', 'to_road_id', 'roadId'];
if (
roadKeys.some((key) => {
const value = text(props[key]);
return value !== null && roadIds.has(value);
})
)
return true;
const segment = text(props.segment_id);
if (segment && segmentIds.has(segment)) return true;
const directional = text(props.directional_road_ids);
return Boolean(directional && [...roadIds].some((id) => directional.split(',').includes(id)));
}
/**
* Keep server preview collections scoped to the independent junction canvas.
* Preview responses are solved from the junction manifest, but some compiler
* layers still contain the surrounding area; showing those collections would
* make a keyboard edit appear to jump back to the global map.
*/
export function localJunctionPreview(
preview: Partial<Record<PreviewLayerName, GeoJson | null>> | null | undefined,
descriptor: JunctionDescriptor,
roads: Road[],
): Partial<Record<PreviewLayerName, GeoJson | null>> | null {
if (!preview) return preview ?? null;
const nodeIds = new Set(descriptor.nodeIds.map(String));
const selectedRoads = roads.filter((road) => descriptor.approachRoadIds.includes(road.id));
const roadIds = new Set(selectedRoads.map((road) => road.id));
const segmentIds = new Set(selectedRoads.map((road) => road.segmentId));
const scoped = { ...preview };
for (const name of Object.keys(preview) as PreviewLayerName[]) {
const value = preview[name];
if (value === null || value === undefined) continue;
scoped[name] = {
type: 'FeatureCollection',
features: value.features.filter((feature) => related(feature, nodeIds, roadIds, segmentIds)),
};
}
return scoped;
}
/** Build the intentionally small state consumed by the independent junction canvas. */
export function localJunctionState(state: WorkbenchState, descriptor: JunctionDescriptor): WorkbenchState {
const nodeIds = new Set(descriptor.nodeIds.map(String));
const roads = state.compiled.model.roads.filter((road) => descriptor.approachRoadIds.includes(road.id));
const roadIds = new Set(roads.map((road) => road.id));
const segmentIds = new Set(roads.map((road) => road.segmentId));
const keep = (value: GeoJson | null | undefined): GeoJson => ({
type: 'FeatureCollection',
features: (value?.features || []).filter((feature) => related(feature, nodeIds, roadIds, segmentIds)),
});
const layerNames = [
'nativeRoadSurface',
'nativeIntersectionSurface',
'nativeSidewalkSurface',
'laneCenterlines',
'laneSeparators',
'centerLines',
'directionArrows',
'turnArrows',
'crosswalks',
'vehicleStopLines',
'connectors',
'edgeLines',
];
const layers = { ...state.layers } as Record<string, GeoJson | null>;
for (const name of layerNames) layers[name] = keep(state.layers[name]);
layers.nativeRoadSurface = keep(state.layers.nativeRoadSurface);
layers.nativeIntersectionSurface = keep(state.layers.nativeIntersectionSurface);
const signals = state.trafficSignals.assemblies.features.filter((feature) =>
related(feature, nodeIds, roadIds, segmentIds),
);
return {
...state,
compiled: {
...state.compiled,
model: {
...state.compiled.model,
roads,
endpoints: state.compiled.model.endpoints.filter(
(endpoint) => nodeIds.has(String(endpoint.nodeId)) || roadIds.has(endpoint.roadId),
),
connections: state.compiled.model.connections.filter((connection) => {
const endpointIds = new Set(
state.compiled.model.endpoints
.filter((endpoint) => roadIds.has(endpoint.roadId) || nodeIds.has(String(endpoint.nodeId)))
.map((endpoint) => endpoint.id),
);
return endpointIds.has(connection.fromEndpointId) || endpointIds.has(connection.toEndpointId);
}),
},
movements: state.compiled.movements?.filter(
(movement) => roadIds.has(movement.fromRoadId) || roadIds.has(movement.toRoadId),
),
diagnostics: state.compiled.diagnostics.filter((item) =>
related(
{ type: 'Feature', properties: item as unknown as Record<string, unknown>, geometry: item.geometry || null },
nodeIds,
roadIds,
segmentIds,
),
),
},
layers,
trafficSignals: { ...state.trafficSignals, assemblies: { ...state.trafficSignals.assemblies, features: signals } },
};
}
+25 -2
View File
@@ -9,6 +9,7 @@ import Fill from 'ol/style/Fill';
import RegularShape from 'ol/style/RegularShape';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';
import { offsetCoordinate, type Coordinate } from '../edit/meters';
import type { Road, WorkbenchState } from '../types/state';
import type { JunctionDescriptor } from '../junction/hotspots';
@@ -54,6 +55,15 @@ export function createLayers(
color: f.get('road_id') === onRoad()?.id ? '#006e91' : '#263630',
width: f.get('road_id') === onRoad()?.id ? 5 : 2,
}),
text: f.get('road_label_visible')
? new Text({
text: String(f.get('road_label') || ''),
font: '600 12px sans-serif',
fill: new Fill({ color: '#f8fafc' }),
stroke: new Stroke({ color: '#17211f', width: 4 }),
overflow: true,
})
: undefined,
}),
}),
lanes: new VectorLayer({
@@ -185,7 +195,12 @@ function features(value: unknown) {
featureProjection: 'EPSG:3857',
});
}
export function updateLayers(layers: ReturnType<typeof createLayers>, state: WorkbenchState, selected: Road | null) {
export function updateLayers(
layers: ReturnType<typeof createLayers>,
state: WorkbenchState,
selected: Road | null,
showRoadLabels = false,
) {
const get = (name: LayerName) => layers[name].getSource()!;
const put = (name: LayerName, value: unknown) => {
const target = get(name);
@@ -195,9 +210,17 @@ export function updateLayers(layers: ReturnType<typeof createLayers>, state: Wor
put('native', state.layers.nativeRoadSurface);
get('native').addFeatures(features(state.layers.nativeIntersectionSurface));
put('sidewalks', state.layers.nativeSidewalkSurface);
const unnamedRoadNumber = new Map(
state.compiled.model.roads.filter((road) => !road.tags.name?.trim()).map((road, index) => [road.id, index + 1]),
);
const roads = state.compiled.model.roads.map(
(road) =>
new Feature({ geometry: new LineString(road.centerline).transform('EPSG:4326', 'EPSG:3857'), road_id: road.id }),
new Feature({
geometry: new LineString(road.centerline).transform('EPSG:4326', 'EPSG:3857'),
road_id: road.id,
road_label_visible: showRoadLabels,
road_label: road.tags.name?.trim() || `道路${unnamedRoadNumber.get(road.id) || 1}`,
}),
);
put('osm', { type: 'FeatureCollection', features: [] });
get('osm').addFeatures(roads);
+123
View File
@@ -315,6 +315,40 @@ pre {
display: grid;
gap: 6px;
}
.parameter-group {
display: grid;
gap: 6px;
}
.parameter-group__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 7px 8px 0;
color: #52615b;
}
.parameter-group__header span {
display: grid;
gap: 2px;
}
.parameter-group__header small {
color: #7b8a83;
font-size: 11px;
}
.parameter-group__toggle {
border: 0;
background: none;
color: #286956;
cursor: pointer;
font-size: 12px;
padding: 3px 0;
text-decoration: underline;
}
.parameter-group__details {
margin: 0 0 0 12px;
padding-left: 8px;
border-left: 2px solid #dce5e1;
}
.parameter {
display: grid;
grid-template-columns: 1fr auto;
@@ -346,6 +380,26 @@ pre {
font-size: 12px;
font-style: normal;
}
.parameter-stepper {
display: inline-flex;
gap: 2px;
margin-left: 2px;
}
.parameter-stepper button {
display: inline-grid;
width: 22px;
height: 22px;
place-items: center;
padding: 0;
border: 1px solid #b7c8bf;
border-radius: 3px;
background: #f8fbf9;
color: #286956;
}
.parameter-stepper button:disabled {
opacity: 0.45;
cursor: default;
}
.parameter-range {
grid-column: 1 / -1;
color: #7b8a83;
@@ -546,6 +600,57 @@ pre {
box-shadow: 0 14px 40px rgb(15 23 42 / 20%);
padding: 1rem 1.25rem;
}
.junction-page {
min-height: 100vh;
}
.junction-page > header {
display: none;
}
.junction-page > main {
height: 100vh;
grid-template-columns: minmax(0, 1fr);
background: #d7e2de;
}
.junction-page > main > .issues,
.junction-page > main > .inspector {
display: none;
}
.junction-page .junction-workspace {
top: 0;
right: 0;
bottom: 0;
width: min(430px, 38vw);
border-radius: 0;
border-top: 0;
border-right: 0;
border-bottom: 0;
box-shadow: -16px 0 36px rgb(15 23 42 / 18%);
}
.junction-page .junction-workspace__header {
position: sticky;
z-index: 2;
top: -1rem;
margin: -1rem -1.25rem 1.5rem;
padding: 1rem 1.25rem;
align-items: center;
background: #173b32;
color: #f4fbf7;
border-bottom: 1px solid #2e594d;
}
.junction-page .junction-workspace__header p,
.junction-page .junction-workspace__eyebrow {
color: #abc5ba;
}
.junction-page .junction-workspace__header .button {
border-color: #97b5a8;
background: #eff7f2;
}
.junction-page .junction-workspace__header h2 {
font-size: 1.15rem;
}
.junction-page .junction-workspace__body {
max-width: none;
}
.junction-workspace__header {
display: flex;
justify-content: space-between;
@@ -561,6 +666,23 @@ pre {
.junction-workspace__header h2 {
margin: 0.2rem 0;
}
.junction-workspace__title-line {
display: flex;
align-items: baseline;
gap: 0.65rem;
min-width: 0;
}
.junction-workspace__title-line h2 {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.junction-workspace__title-line code {
color: inherit;
font-size: 0.8em;
font-weight: 500;
}
.junction-workspace__header p {
margin: 0;
color: #64748b;
@@ -570,6 +692,7 @@ pre {
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.08em;
white-space: nowrap;
}
.junction-workspace__body {
max-width: 42rem;