feat: add direct edit handles behind directEdit flag

Steps 1-3 of the main map road interval editor.

EditSession keeps the command stack, undo/redo and previewSeq arbitration as
pure logic with no OpenLayers reference, so all of it is unit-tested in node.
Pointer displacement converts to meters through EPSG:4326 and spherical
distance: treating a 3857 delta as meters desyncs the geometry from the cursor
by 1/cos(latitude). Handle drags project onto the axis the manifest declares
and clamp to its range, so the client never writes a coordinate into a road
polygon.

All of it sits behind a directEdit flag that defaults to off. With the flag off
the workbench requests no manifest, creates no extra source and registers no
interaction, so behaviour matches main.

The ol-ext probe passed its three gates but is not adopted for road handles.
Transform translates by the raw pointer delta, so a handle detaches from its
clamped constraint value: a drag reading -24.1 m produced a draft of -5.4 m.
Production needs the handle position derived from the constraint instead, which
means owning the position update, so native OL PointerInteraction will carry
the drag. ol-ext stays out of package.json; the probe is kept as a manual
harness. Reserve handles are unreachable with the current solver, recorded in
research/ rather than worked around.

Also names the dead backend when an API response is empty, instead of
surfacing "Unexpected end of JSON input" from response.json().

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
que01andClaude Opus 5 committed 2026-08-27 14:59:11 +08:00
1 parent e25c564bb9
commit bc4b9a9717
25 files changed
+2463 -22

No files matched your search

+62 -17
View File
@@ -1,12 +1,54 @@
import type { WorkbenchState } from '../types/state';
import type {
EditPreviewRequest,
EditPreviewResponse,
EditStateResponse,
SaveEditsRequest,
SaveEditsResponse,
} from '../edit/types';
/** Carries the status and parsed body so callers can branch on 409 rather than on message text. */
export class ApiError extends Error {
constructor(
message: string,
readonly status: number,
readonly body: unknown,
) {
super(message);
this.name = 'ApiError';
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(path, { cache: 'no-store', ...init });
const value = (await response.json()) as T & { ok?: boolean; error?: string };
if (!response.ok || value.ok === false) throw new Error(value.error || `HTTP ${response.status}`);
// Read as text first. A dead backend behind the dev proxy answers with an empty
// body, and `response.json()` then throws "Unexpected end of JSON input" —
// which says nothing about the actual problem.
const text = await response.text();
if (!text) throw new ApiError(`${path} 返回空响应(HTTP ${response.status}),后端可能未启动`, response.status, null);
let value: T & { ok?: boolean; error?: string };
try {
value = JSON.parse(text) as T & { ok?: boolean; error?: string };
} catch {
throw new ApiError(`${path} 返回了非 JSON 响应(HTTP ${response.status})`, response.status, text);
}
if (!response.ok || value.ok === false)
throw new ApiError(value.error || `HTTP ${response.status}`, response.status, value);
return value;
}
const json = (body: unknown, signal?: AbortSignal): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
...(signal ? { signal } : {}),
});
/** A save lost the single-writer race; `body.current.documentVersion` holds the server's version. */
export function isVersionConflict(error: unknown): error is ApiError {
return error instanceof ApiError && error.status === 409;
}
export const api = {
state: () => request<WorkbenchState | { active: false }>('/api/state'),
import: (file: File) => {
@@ -15,26 +57,29 @@ export const api = {
return request<WorkbenchState>('/api/import', { method: 'POST', body });
},
overrides: (overrides: unknown[]) =>
request<{ overrides: WorkbenchState['overrides'] }>('/api/overrides', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ schema: 'native-road-overrides/v1', overrides }),
}),
request<{ overrides: WorkbenchState['overrides'] }>(
'/api/overrides',
json({ schema: 'native-road-overrides/v1', overrides }),
),
compile: () => request<WorkbenchState>('/api/compile', { method: 'POST' }),
signals: (document: unknown) =>
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(document),
}),
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals', json(document)),
generateSignals: () =>
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals/generate', {
method: 'POST',
}),
acceptJunctionCandidate: (index: number) =>
request<WorkbenchState & { added: { id: string } }>('/api/junction-clusters', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ index }),
}),
request<WorkbenchState & { added: { id: string } }>('/api/junction-clusters', json({ index })),
// Direct edit. Only reached when the `directEdit` flag is on; with it off the
// workbench never touches these routes, so behaviour matches main exactly.
editState: () => request<EditStateResponse | { active: false }>('/api/edit-state'),
/**
* `signal` comes from the caller's AbortController: the request layer only
* sends and cancels, while `EditSession` decides which responses to keep.
*/
editPreview: (body: EditPreviewRequest, signal?: AbortSignal) =>
request<EditPreviewResponse>('/api/edit-preview', json(body, signal)),
/** Throws an `ApiError` with status 409 when another writer moved the version. */
saveEdits: (body: SaveEditsRequest) => request<SaveEditsResponse>('/api/edits', json(body)),
};