/** * The sequence as a pure value: a tree of steps, the edits on it, and the * element's editing state folded by one reducer. No DOM here: the element * (index.tsx) reads the page's markup into these values and renders them. * * A step is linear (it has `next`) or branching (it has `branches`, one * slot per outcome its kind names, in order). The value posted with the form * is `{ "root": Step | null }`: the wrapper leaves room for later additions * (detached fragments, a version) without breaking a server's decoder. * * { "root": { "id": "s1", "kind": "invite", "fields": {}, "next": * { "id": "s2", "kind": "connected", "fields": { "days": 7 }, "branches": [ * { "id": "s3", "kind": "message", "fields": { "text": "Hi" }, "next": null }, * null ] } } } * * Every edit is structural sharing: only the steps on the path to the change * are new objects, so keyed rows of unchanged steps keep their DOM. */ /** A field's value, as read off its control: text, a number, a checkbox, or absent. */ export type Field = string | number | boolean | null; export type Fields = Record; export interface Step { id: string; kind: string; fields: Fields; /** A linear step's continuation. Absent on a branching step. */ next?: Step | null; /** A branching step's outcomes, one slot each. Absent on a linear step. */ branches?: (Step | null)[]; } export interface Sequence { root: Step | null; } /** * Where a step sits: the root (parent null), a linear parent's `next` * (branch null), or one of a branching parent's `branches`. */ export interface Slot { parent: string | null; branch: number | null; } export const ROOT: Slot = { parent: null, branch: null }; export const slotKey = (slot: Slot): string => `${slot.parent ?? ""}/${slot.branch ?? "next"}`; export const isBranching = (step: Step): boolean => Array.isArray(step.branches); /** The steps a step leads to, in order. */ export const childrenOf = (step: Step): (Step | null)[] => (isBranching(step) ? step.branches! : [step.next ?? null]); /** What takes a removed step's place: its next, or its first non-empty branch. */ export const successorOf = (step: Step): Step | null => childrenOf(step).find(child => child !== null) ?? null; /** The number of steps in a subtree. */ export function size(step: Step | null): number { if (!step) return 0; let n = 1; for (const child of childrenOf(step)) n += size(child); return n; } /** Every step id in the sequence. */ export function idsOf(sequence: Sequence): Set { const ids = new Set(); const walk = (step: Step | null) => { if (!step) return; ids.add(step.id); childrenOf(step).forEach(walk); }; walk(sequence.root); return ids; } /** The step with this id. */ export function find(sequence: Sequence, id: string): Step | null { const walk = (step: Step | null): Step | null => { if (!step) return null; if (step.id === id) return step; for (const child of childrenOf(step)) { const found = walk(child); if (found) return found; } return null; }; return walk(sequence.root); } /** Where the step with this id sits, or null when there is none. */ export function slotOf(sequence: Sequence, id: string): Slot | null { if (sequence.root?.id === id) return ROOT; const walk = (step: Step | null): Slot | null => { if (!step) return null; const children = childrenOf(step); for (let i = 0; i < children.length; i++) { if (children[i]?.id === id) return { parent: step.id, branch: isBranching(step) ? i : null }; const found = walk(children[i]); if (found) return found; } return null; }; return walk(sequence.root); } /** * A linear run: the head, then each `next`, up to and including the first * branching step (whose branches are runs of their own). */ export function runOf(head: Step | null): Step[] { const run: Step[] = []; const seen = new Set(); for (let step = head; step && !seen.has(step.id); step = isBranching(step) ? null : (step.next ?? null)) { seen.add(step.id); run.push(step); } return run; } /** The step in a slot. */ export function childAt(sequence: Sequence, slot: Slot): Step | null { if (slot.parent === null) return sequence.root; const parent = find(sequence, slot.parent); if (!parent) return null; return slot.branch === null ? (parent.next ?? null) : (parent.branches?.[slot.branch] ?? null); } /** The step with this id replaced by `f(step)` (null removes it), sharing everything off the path. */ function rewrite(step: Step | null, id: string, f: (step: Step) => Step | null): Step | null { if (!step) return step; if (step.id === id) return f(step); if (isBranching(step)) { const branches = step.branches!.map(child => rewrite(child, id, f)); return branches.every((child, i) => child === step.branches![i]) ? step : { ...step, branches }; } const next = step.next ?? null; const rewritten = rewrite(next, id, f); return rewritten === next ? step : { ...step, next: rewritten }; } /** The sequence with the step in `slot` replaced. */ function setChildAt(sequence: Sequence, slot: Slot, child: Step | null): Sequence { if (slot.parent === null) return { ...sequence, root: child }; const root = rewrite(sequence.root, slot.parent, parent => { if (slot.branch === null) return isBranching(parent) ? parent : { ...parent, next: child }; if (!isBranching(parent)) return parent; const branches = parent.branches!.slice(); branches[slot.branch] = child; return { ...parent, branches }; }); return root === sequence.root ? sequence : { ...sequence, root }; } /** * The sequence with `step` inserted in `slot`. What was in the slot moves * after it: into a linear step's `next`, or a branching step's first branch. */ export function insert(sequence: Sequence, slot: Slot, step: Step): Sequence { const occupant = childAt(sequence, slot); const placed: Step = isBranching(step) ? { ...step, branches: step.branches!.map((branch, i) => (i === 0 ? occupant : branch)) } : { ...step, next: occupant }; return setChildAt(sequence, slot, placed); } /** The sequence with the step's fields replaced. */ export function update(sequence: Sequence, id: string, fields: Fields): Sequence { const root = rewrite(sequence.root, id, step => ({ ...step, fields })); return root === sequence.root ? sequence : { ...sequence, root }; } /** The sequence without the step: its successor takes its place, its other branches go with it. */ export function remove(sequence: Sequence, id: string): Sequence { const root = rewrite(sequence.root, id, successorOf); return root === sequence.root ? sequence : { ...sequence, root }; } /** How many steps removing this one would discard besides itself. */ export function discarded(sequence: Sequence, id: string): number { const step = find(sequence, id); return step ? size(step) - 1 - size(successorOf(step)) : 0; } /** A step id not already taken. */ export function freshId(taken: Set, random: () => number = Math.random): string { for (;;) { const id = `s${Math.floor(random() * 36 ** 6) .toString(36) .padStart(6, "0")}`; if (!taken.has(id)) return id; } } /** * The value from the field's text. Steps without an id get a fresh one; a * missing `fields` is `{}`; a step of a kind with `branchCounts` outcomes gets * that many branch slots (padded with null, never truncated: data is not * dropped). Throws an Error naming the first malformed step. */ export function parse(text: string, branchCounts: ReadonlyMap = new Map()): Sequence { const trimmed = text.trim(); if (trimmed === "") return { root: null }; const data: unknown = JSON.parse(trimmed); if (!isRecord(data) || !("root" in data)) throw new Error('the value must be an object with a "root"'); const taken = new Set(); const pending: Step[] = []; const read = (raw: unknown, path: string): Step | null => { if (raw === null || raw === undefined) return null; if (!isRecord(raw)) throw new Error(`${path}: a step must be an object`); if (typeof raw.kind !== "string" || raw.kind === "") throw new Error(`${path}: a step needs a "kind"`); if (raw.fields !== undefined && !isFields(raw.fields)) throw new Error(`${path}: "fields" must map names to text, numbers, booleans or null`); const id = typeof raw.id === "string" && raw.id !== "" ? raw.id : null; if (id !== null) { if (taken.has(id)) throw new Error(`${path}: the id "${id}" is used twice`); taken.add(id); } const step: Step = { id: id ?? "", kind: raw.kind, fields: { ...((raw.fields as Fields | undefined) ?? {}) } }; const count = branchCounts.get(raw.kind) ?? (Array.isArray(raw.branches) ? raw.branches.length : 0); if (count > 0 || Array.isArray(raw.branches)) { const given = Array.isArray(raw.branches) ? raw.branches : []; const branches = given.map((child, i) => read(child, `${path}.branches[${i}]`)); while (branches.length < count) branches.push(null); step.branches = branches; } else { step.next = read(raw.next, `${path}.next`); } if (id === null) pending.push(step); return step; }; const root = read(data.root, "root"); for (const step of pending) { step.id = freshId(taken); taken.add(step.id); } return { root }; } /** The value as the field's text. Keys in a fixed order: id, kind, fields, then next or branches. */ export function serialize(sequence: Sequence): string { const plain = (step: Step | null): unknown => step === null ? null : isBranching(step) ? { id: step.id, kind: step.kind, fields: step.fields, branches: step.branches!.map(plain) } : { id: step.id, kind: step.kind, fields: step.fields, next: plain(step.next ?? null) }; return JSON.stringify({ root: plain(sequence.root) }); } const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); const isFields = (value: unknown): value is Fields => isRecord(value) && Object.values(value).every(v => v === null || ["string", "number", "boolean"].includes(typeof v)); // ── The element's state ──────────────────────────────────────────────────── export interface Model { value: Sequence; /** The step whose editor is open. */ editing: string | null; /** The open editor belongs to a step just added: canceling it removes the step. */ fresh: boolean; /** The slot whose "add a step" menu is open, by slotKey. */ adding: string | null; /** The step whose removal waits for a second press (it would discard others). */ confirming: string | null; } export type Action = | { type: "menu"; slot: Slot | null } | { type: "insert"; slot: Slot; step: Step; edit: boolean } | { type: "edit"; id: string } | { type: "commit"; id: string; fields: Fields } | { type: "cancel" } | { type: "remove"; id: string } | { type: "load"; value: Sequence }; export const start = (value: Sequence): Model => ({ value, editing: null, fresh: false, adding: null, confirming: null }); export function step(model: Model, action: Action): Model { switch (action.type) { case "menu": return { ...model, adding: action.slot ? slotKey(action.slot) : null, confirming: null }; case "insert": return { value: insert(model.value, action.slot, action.step), editing: action.edit ? action.step.id : null, fresh: action.edit, adding: null, confirming: null, }; case "edit": return find(model.value, action.id) ? { ...model, editing: action.id, fresh: false, adding: null, confirming: null } : model; case "commit": return { ...model, value: update(model.value, action.id, action.fields), editing: null, fresh: false }; case "cancel": { const value = model.fresh && model.editing ? remove(model.value, model.editing) : model.value; return { value, editing: null, fresh: false, adding: null, confirming: null }; } case "remove": if (discarded(model.value, action.id) > 0 && model.confirming !== action.id) return { ...model, adding: null, confirming: action.id }; return { value: remove(model.value, action.id), editing: model.editing === action.id ? null : model.editing, fresh: model.editing === action.id ? false : model.fresh, adding: null, confirming: null, }; case "load": return start(action.value); } }