Files
road-compiler/.trellis/spec/frontend/direct-edit-client.md
T

335 lines
15 KiB
Markdown

# Direct Edit Client
> Trigger: any change under `workbench/client/src/edit/`, `MapCanvas.tsx`, or the
> direct-edit wiring in `App.tsx`. Read this before editing handles, ghosts,
> previews, or the save path.
Related: [Direct Edit Solver And API](../backend/direct-edit-api.md) for the wire
contract this client consumes.
---
## 1. Layer ownership
Four layer groups, and only three of them are ever written by the client:
| Group | Written by | Rule |
| --- | --- | --- |
| baseline (`createLayers()`) | `updateLayers()` only | **Never** written by edit code |
| `editHandles` | `EditHandleLayer.render()` | Handle features carry only `handleId` |
| `editGhost` | `EditGhostLayer` | Client-side, non-authoritative |
| `editPreview` | `EditPreviewLayer.show()` | Server geometry; **hides** baseline, never overwrites it |
`EditPreviewLayer` builds its own layer set from the same `createLayers()` factory
so preview and baseline cannot drift in styling, and `show()` hides only the
baseline layers it actually supersedes. `clear()` restores visibility from the
layer switches, never from a hardcoded default.
**Forbidden**: writing compiler output into a baseline source. It is the invariant
the whole split exists to protect, and nothing in the type system enforces it.
---
## 2. A handle carries nothing but its id
Handle features hold `handleId` and nothing else. Kind, anchor, axis, range and
disabled reason are looked up in the manifest. That is why `EditHandleLayer` owns
both the source and the index — they cannot fall out of step.
**Forbidden**: copying manifest fields onto the feature. It creates a second
constraint model on the client, which is the failure the cross-layer guide warns
about.
---
## 3. Handle position comes from the value, never the cursor
`handlePositionFor(handle, value)` is the inverse of `projectHandleValue()`. A
drag projects onto the manifest's axis, clamps to the manifest's range, and the
handle is then placed from the clamped value.
This is not cosmetic. The ol-ext probe translated its proxy by the raw pointer
delta, and a drag reading `-24.146 m` left the handle 24 m out while the
constraint clamped at `-5.400 m` — the handle pointed at a road shape that cannot
exist. Any input adapter must own the position update for this reason.
---
## 4. Sides: left is `tangent - 90`
The manifest reports `axisAzimuth = tangent + 90` for **both** sides, and that
azimuth is the geometry compiler's *right*. See the backend spec for why. On the
client this means `outwardSign()` negates the left side, and a test that asserts a
side must name the direction geographically (`OUTWARD_LEFT` / `OUTWARD_RIGHT`)
rather than by axis sign.
**Mistake made**: the first implementation assumed left was the positive axis, so
dragging the visually-left handle moved the right kerb. Both the server placement
and the client sign were wrong together, so neither side's tests caught it.
---
## 5. A constraint must travel with its operation
`validateEditDocument()` rejects any constraint whose `provenance.operationId` is
not a recorded operation, and the check covers already-saved constraints too.
Build the pair with `draftConstraint()` + `operationFor()`, and send
`EditSession.fragment()`, which assembles both halves.
One gesture mints one operation id, released on pointerup. Reusing an id across
gestures puts two operations with the same id in the document, which is also
rejected.
**Mistake made**: sending `constraints` alone returned HTTP 400 on every drag.
---
## 6. Never compute inside a `setState` updater
React defers updater functions and, under StrictMode, calls them more than once.
By the time one runs, closure variables captured during the gesture may already be
cleared.
```ts
// WRONG — threw `toLonLat(null)` and white-screened the page
setReport((current) => ({ ...current, meters: projectHandleValue(handle, start!, now) }));
// RIGHT — compute in the event handler, pass plain values in
const meters = projectHandleValue(handle, start, now);
setReport((current) => ({ ...current, meters }));
```
The `start!` non-null assertion is what hid the runtime problem from the type
checker. The same rule covers reading live OpenLayers state inside an updater: it
samples a different moment than the event did.
---
## 7. Per-frame feedback does not go through React
The ghost writes its OpenLayers source directly. Driving a readout from state on
every `pointermove` produced ~1600 renders in a single probe session.
`requestAnimationFrame` coalescing is the minimum; writing straight to the source
is the rule for production.
---
## 8. `EditSession` owns the constraint set, and is mutated in place
`EditSession` holds the saved baseline, its operations, the command stack, and the
`previewSeq` watermark. `PreviewRequester` captures the session object once, so
adopting a server document uses `load()` rather than constructing a new session —
a swapped object would leave the requester arbitrating for a session nobody reads.
`previewSeq` arbitration lives in `acceptPreview()`, not in the request layer: the
request layer only sends and cancels. The discard rule is worth unit-testing and
must not depend on network timing.
Selection changes are a second freshness boundary. `PreviewRequester.invalidate()`
must cancel the active request and advance its generation; `dispatch()` checks
that captured generation before giving a response to `EditSession`. Abort alone
is insufficient because a transport may resolve after receiving its abort signal.
When changing junction/segment scope, clear scoped preview geometry before the
new manifest arrives, so an A-scope result cannot render while B is selected.
Undo of a **saved** gesture appends an inverse operation; persisted history is
never rewritten. Undo of an unsaved one just moves the cursor.
---
## 9. The `directEdit` flag means nothing exists
With the flag off: no edit source is created, no layer is added, no interaction is
registered, and no manifest request is made. The network trace and the canvas must
match `main` exactly. Guard once at construction, not per call site.
`intervalEditingSupported` is a second, narrower switch: range handles stay hidden
while `compileGeometry()` ignores `profile.interval`. A control whose drag changes
nothing is worse than no control.
### Lane maneuver is v2 direct edit only
`lane-maneuver` is a spatial direct-edit constraint. Its selector and draggable
outline are available only in edit mode and must be routed through `EditSession` and
the preview endpoint. It must never be added to the ordinary v1 staged override
array, which is reserved for road, connector, and marking style overrides.
With edit mode off, selecting a turn-arrow part may still show read-only element
information, but it must not create a manifest request, ghost, preview, handle, or
staged lane-maneuver override.
Crosswalk inset and stop-line offset follow the same element ownership rule. New
manifests use a `junction-crossing` anchor containing `crossingId` plus its road
context; legacy `junction-approach` anchors remain readable for document replay.
The crossing values must be kept separate from junction approach width/cutback
plans so editing one crossing cannot move the road geometry or another crossing.
---
## 10. Saving is not the same as applying
`POST /api/edits` writes the document; `/api/state` serves the outputs of the last
compile. Saving without recompiling leaves a refresh showing the pre-edit geometry,
which is indistinguishable from a failed save. Report the save and the recompile
separately — if the recompile fails, the save still succeeded and the message must
say so.
---
## 11. Two input channels, three shared exits
A value can come from a drag or from a number field. They differ only in how the
scalar is produced and when the gesture closes; everything downstream is shared:
| Exit | Meaning |
| --- | --- |
| `draftValue(handle, value)` | preview, do not commit |
| `settleValue(handle, value)` | one undoable command, or abandon if it drafts nothing |
| `abandonGesture()` | release the id, clear live overrides, re-preview the settled state |
`EditSession` needs no change to accept a second channel: `gestureIdentity()` is
minted lazily by the first draft and released by `commitGesture()`, so `focus` /
`blur` land on the same boundary `pointerdown` / `pointerup` already used. That is
what makes typing `1.53` one undo step instead of four.
**Forbidden**: a second preview path, debounce, or undo stack per input device.
---
## 12. Continuous input clamps; discrete input refuses
The invariant is shared — a constraint value never leaves `[min, max]` — but the
two devices express it differently.
- A drag **clamps**. A pointer cannot state an intent it never reached, and the
handle has to stay on a road shape that can exist (§3). The clamp is visible in
the moment: the handle stops while the cursor keeps going.
- A number field **refuses**: mark it invalid, send no preview, add no undo step,
keep the last valid preview. Typed text *is* an intent, so rewriting it is a
retroactive edit — and the failure modes are asymmetric. A clamped typo (24
becoming 5.4) reads as a plausible value and can go unnoticed; a refusal cannot.
Offer the extremes as one click, but round them **inward**: a real max of `2.925`
renders as `2.93` under nearest-rounding, which the range it came from rejects.
`formatBoundInward()` exists for this.
**Mistake made**: the first draft of the panel displayed and filled
`formatParameterValue(min)`, which produced a value its own range check refused.
---
## 13. A field being typed in owns its own text
Every settled preview replaces the manifest, so a controlled input bound to
`handle.value.current` is rewritten mid-keystroke: typing `1.` fires a preview for
`1`, and the response resets the field to `1`, dropping the decimal point.
The field therefore holds local text while focused and follows the manifest only
when it is not:
```ts
value={text ?? formatParameterValue(handle.value.current)}
```
There is no second number to reconcile: `numericValue()` in the solver reads the
constraint back out, so `value.current` is the request echoed, never a solved
substitute. Seed the local text from what is on screen at focus, not from the
manifest — after a drag the row can legitimately be ahead of the last settled
preview.
---
## 14. Reset disables the constraint; it does not delete it
`validateEditDocument()` rejects an operation whose `constraintIds` name a
constraint that is not in the document, so removing one would mean recording an
operation about nothing. Setting `enabled: false` is what design.md already
sanctions for undoing saved work, and `constraintFor()` skips disabled
constraints, so the handle comes back without a `constraintId` and the row reports
itself unmodified again.
This is the one edit a drag cannot express: a drag can set a value, never withdraw
one. `handle.constraintId` — present only when a constraint exists — is also how
"untouched" is told apart from "explicitly set to the baseline number".
---
## Checklist before committing edit-client changes
- [ ] No baseline source is written
- [ ] No manifest field is copied onto a feature
- [ ] Handle positions derive from clamped values
- [ ] Sides asserted geographically, not by axis sign
- [ ] Constraints sent with their operations
- [ ] No geometry or OL reads inside a `setState` updater
- [ ] No per-`pointermove` React state updates
- [ ] Flag off ⇒ no sources, layers, or interactions. A selected complex
JunctionTools workspace may request its scoped manifest solely to discover
server-published edit capability before the edit switch is enabled.
- [ ] Every input channel meets at the shared exits, not a parallel path
- [ ] Displayed bounds round inward, so an offered extreme is accepted
- [ ] A focused field is not rewritten by an arriving preview
## 15. Complex shape display is server-owned
`WorkbenchState.debug.junctionShapes` is a debug-only read model keyed by
`clusterId`. JunctionTools may display `label` and `armCount` for the currently
opened cluster, but it must not derive T/十字/偏置 shapes from `nodeIds.length`.
The same internal node layout can resolve to different external-arm topology.
If no summary exists, omit the shape row and retain normal cluster context; do
not show an inferred fallback. The compiler's safe fallback has no complex core
and therefore no summary.
## 16. Scoped structure and semantic map selection
Use `structureForJunction(state, ref)` to read `state.junctionStructures`; do not
reuse the unscoped singular structure when its ref differs. A missing structure
stays unavailable. Use `junctionEditSelection(ref)` for edit-state and preview
requests so a cluster never falls back to the last selected road or node.
## 17. Complex geometry editing
Complex JunctionTools consumes the same v2 `EditSession`, `PreviewRequester`,
`ParameterPanel`, and map handle callbacks as ordinary junctions. Editable
handles include `cluster-carriageway-width`, `cluster-carriageway-cutback`,
`cluster-corner-radius`, `cluster-crossing-inset`, and
`cluster-stop-line-offset`. The first two use a `cluster-carriageway` anchor; a
corner anchor is resolved to its representative carriageway only to create the
snapshot; crossing controls use `cluster-crossing` and its stable
`crossingKey`. Before edit mode, a selected cluster loads its scoped manifest so
`canEditJunction()` can use an editable server handle as the capability signal.
Do not add a cluster-local draft, preview, undo, or save flow.
Compiler structure provenance supplies cluster hotspots and external road IDs.
`localJunctionState` and `localJunctionPreview` recognize explicit `junction_key`
(and legacy `cluster_id`) before testing node/road references. This keeps core
and corner features that do not carry member node IDs and excludes neighboring
clusters even if a connecting road is shared.
Map/list selection goes through `junctionObjectKeyForFeature` and
`junctionObjectFeatures`: compiler keys identify arms/corners/crossing groups;
signal UIDs resolve through scoped facility provenance. Display labels and row
indices are never parsed into IDs. Highlighting is a read-only overlay, allocated
when selecting an object; it must not mutate baseline features or rebuild the
map. On scope changes clear object selection and ignore obsolete manifest loads.
Map capability reason codes into user-facing Chinese descriptions.
Required checks: opposite node/cluster scopes with equal raw IDs, unknown scope,
list-to-feature grouping and feature-to-list identity, foreign-cluster exclusion,
raw signal UID selection, map identity preservation, and reload stability.
### Junction workspace save and grouped ranges
Workspace actions must include `EditSession.dirty`, `canUndo`, and `canRedo`;
`JunctionSession.dirty` alone misses settled grouped edits. Reuse the global
commands and expose save status in the junction route, where the main header is
hidden. The edit render revision is not a persisted document version: a save
changes it, so comparing a captured render revision after saving can crash React.
The API owns version conflict checks.
A grouped scalar is available only if the individual ranges intersect. Otherwise
show why a common value is unavailable and expand individual controls; never
render a minimum larger than the maximum. Transition length uses the same input,
preview, history, and persistence path as other geometry parameters.