# Editing model — v2 design (the target) The agreed API and behaviour for the reworked editing/commit lifecycle. Companion to [EditingModel-current.md](EditingModel-current.md) (the current-behaviour baseline). Both are temporary working docs; fold into the README / migration guide and delete when the model lands. > **Status:** API + behaviour **locked** (§1–§7). Architecture + vocabulary **agreed** (§8 + Terminology below). State shape + transitions drafted (§10), being walked against the current-model §12 table. --- ## Terminology Layers are kept distinct by name; `editorRef.*` methods are always written in full form. - **Provider transitions** (store methods the nodes call): `open` · `submit` · `cancel` (+ bookkeeping `setTabDirection`, `recordPreviouslyEdited`). Plain verbs — never the same string as an event. - **Events** (`onEditEvent` strings — pure outputs): `startEdit`/`submitEdit`/`commitEdit`/`cancelEdit` (+ `…Rename`/`…Add` families) · `delete` · `move` · `updateSuccess` · `updateError`. - **`editorRef` methods** (consumer, imperative): always written in full — `editorRef.startEdit` / `editorRef.cancel` / `editorRef.confirm` / `editorRef.collapse`. - **Consumer callbacks** (passed into `onUpdate`): `hold()` → returns `release()`. - **Provider internals** (never called by nodes): `apply` (apply value + close + register `settling` + fire `commit*`) · `reconcile` (token-gated settlement) · `buildInput` · `emit`/`fire`. - **JsonEditor-supplied primitives** (refs the Provider calls): `runUpdate` (= `onUpdate`) · `applyValue(path,value)` · `getLatestData` · `buildNodeData`. - **State:** `active {path,op,phase,force} | null` · `phase: editing|held` · `settling: Record` · `token` · `cancelOp` · `tabDirection` · `previouslyEdited` · node-local **buffer**. - **Selectors:** `isEditing` / `isEditingKey` / `isAddingHere` / `isHeld` / `isSettling`. Transition → the event it fires: `open → startEdit` · `submit → submitEdit` · `apply → commitEdit` · `cancel → cancelEdit`. --- ## 1. Core concept A commit is **optimistic by default**: on submit the editor closes and the UI updates immediately; the consumer's `onUpdate` runs and only matters if it **fails** (revert + signal). Two independent, optional twists ride on top: - **The gate (decide):** an optional pre-commit decision — a confirmation dialog, async validation — during which the originating UI stays **open** and the rest of the tree is **blocked**. A falsy/`null` decision cancels the operation (nothing was applied). - **Settlement timing:** the durable write (`onUpdate`) may resolve instantly or after a slow round-trip. Either way the UI already updated optimistically; a *delayed* failure just means the revert lands later. The unifying idea: there is exactly **one "apply + close" moment** per commit. By default it is at **submit**. A gate moves that moment to **after the gate passes**. Everything after it is optimistic and reconciled in the background. --- ## 2. The `onUpdate` API (locked) A single `onUpdate` prop — no separate gate prop. The model passes a control object whose `hold()` opts that one commit out of the default optimistic close. ```ts type UpdateResult = | void | undefined | true // commit | { value: unknown } // commit, overriding the edited NODE's value (edit/add only) | { data: JsonData } // commit, overriding the WHOLE document | null // silent cancel — revert (if already applied), no error | false // reject — revert + default error message | { error: string | JerError } // reject — revert + this message interface UpdateControl { /** Keep the editor open ("gate"); blocks the tree. Returns `release`. * MUST be called synchronously, before the first `await`. */ hold: () => () => void // returns `release` } onUpdate?: (input: NodeData & { newData, newValue, event }, control: UpdateControl) => UpdateResult | Promise ``` ### `hold()` / `release()` - **No `hold()`** → optimistic: the value applies and the editor closes at submit; `onUpdate` settles in the background. - **`hold()` then `release()`** → editor stays open through the gate, then applies + closes at `release()`; `onUpdate` settles in the background after that. - **`hold()` without `release()`** → editor stays open until `onUpdate` settles, then applies/closes on the result (a fully **pessimistic** path, for free). **`hold()` must be synchronous** (before the first `await`). The model decides "apply+close now vs stay open" the instant `onUpdate` returns its promise, so it can only observe a `hold()` that ran in the synchronous prefix. A late call is too late (already applied). A dev-time warning should catch a late call. In practice `hold()` is the first line, and `useConfirmOnUpdate` calls it for you, so consumers rarely touch it. `release()` = apply the value optimistically + close the editor + unblock the tree, now. From that point the edit **session** is over; the `return` value is purely the **settlement** outcome. **Instant operations** (delete, array-add, move) have no editor, but `hold()` still works — it gates the *commit*: defer the optimistic apply and block the tree until `release()`. This is the confirm-before-delete case (the node stays visible until confirmed). `release()` then applies (e.g. removes the node). ### The four scenarios | # | Gate? | Settle | `onUpdate` body | Editor behaviour | |---|---|---|---|---| | 1 | no | instant | *(omit `onUpdate`)* | closes + applies at submit | | 2 | yes | instant | `const r=hold(); if(!await confirm()) return null; r(); return true` | open during confirm → applies when confirmed | | 3 | no | slow | `return await save(input)` | applies at submit; reverts + errors if the write later fails | | 4 | yes | slow | `const r=hold(); if(!await confirm()) return null; r(); return await save(input)` | open during confirm → applies when confirmed → reverts + errors if it later fails | --- ## 3. Blocking & concurrency - **Gate window only** (held, before `release`/commit): the tree is **blocked** — no other node can start editing; the held node + the consumer's dialog are the only interactive surface. Exactly one held operation at a time. - **Settlement window** (after commit, background): **not** blocked. The editor is closed and the user is free to edit/Tab elsewhere, so **multiple settlements can be in flight concurrently.** - Concurrency therefore requires a **per-commit token / version** so that: a late failure reverts the *right* node, and for the same node, **latest edit wins** — a newer commit makes an older in-flight settlement stale, so its result is ignored. (The held regime needs no token: the tree is locked → only ever one pending commit.) - **Cancellation of a held op flows through the gate:** since the tree is blocked, the only way a held op resolves is `onUpdate` settling, so "user cancelled the dialog" is just `onUpdate → null`. No promise-aborting, no Esc-out-of-pending. --- ## 4. Type changes Changing a node's type is special: today it runs `setData` mid-edit and can remount a structurally different node. It's reclassified by **whether the target requires a different node**, so it slots into the locked lifecycle instead of being a "commit that stays open": - **Stays a value node** (`string` ↔ `number` ↔ `boolean` ↔ `enum`): **local only.** Adjust the node's local `dataType` + coerce the local buffer. **No `onUpdate`, no settlement, no token, no event.** The editor stays open rendering the new type's input. The single commit happens on the *real* submit, carrying the final type + value together. - **Becomes a collection or custom node** (`→ object` / `array` / custom component): a **normal commit that closes the session** — `commitEdit` + remount as the new node + settlement (+ gate if `hold()`). Because the editor closes on this path, a settlement failure just remounts the old node in the background — no open editor to disturb. This is cleaner than today: the `previousValue` snapshot machinery (which exists purely to revert committed mid-edit type changes) largely disappears — primitives revert by dropping the local buffer; collections revert via the settlement's token'd revert-value. **Behaviour change (accepted):** a primitive type-change no longer fires `onUpdate` the instant it changes — it defers to submit. More correct (the type isn't final until submit), but a contract change to note in the migration guide. **To verify when building:** `enum` coercion (pick a valid option, render `