library
Prebuilt pebble components: drop-in custom elements, no compiler needed
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runAucun
0Étoiles
0Forks
2Issues
| 1 | /** |
| 2 | * The sequence as a pure value: a tree of steps, the edits on it, and the |
| 3 | * element's editing state folded by one reducer. No DOM here: the element |
| 4 | * (index.tsx) reads the page's markup into these values and renders them. |
| 5 | * |
| 6 | * A step is linear (it has `next`) or branching (it has `branches`, one |
| 7 | * slot per outcome its kind names, in order). The value posted with the form |
| 8 | * is `{ "root": Step | null }`: the wrapper leaves room for later additions |
| 9 | * (detached fragments, a version) without breaking a server's decoder. |
| 10 | * |
| 11 | * { "root": { "id": "s1", "kind": "invite", "fields": {}, "next": |
| 12 | * { "id": "s2", "kind": "connected", "fields": { "days": 7 }, "branches": [ |
| 13 | * { "id": "s3", "kind": "message", "fields": { "text": "Hi" }, "next": null }, |
| 14 | * null ] } } } |
| 15 | * |
| 16 | * Every edit is structural sharing: only the steps on the path to the change |
| 17 | * are new objects, so keyed rows of unchanged steps keep their DOM. |
| 18 | */ |
| 19 | |
| 20 | /** A field's value, as read off its control: text, a number, a checkbox, or absent. */ |
| 21 | export type Field = string | number | boolean | null; |
| 22 | export type Fields = Record<string, Field>; |
| 23 | |
| 24 | export interface Step { |
| 25 | id: string; |
| 26 | kind: string; |
| 27 | fields: Fields; |
| 28 | /** A linear step's continuation. Absent on a branching step. */ |
| 29 | next?: Step | null; |
| 30 | /** A branching step's outcomes, one slot each. Absent on a linear step. */ |
| 31 | branches?: (Step | null)[]; |
| 32 | } |
| 33 | |
| 34 | export interface Sequence { |
| 35 | root: Step | null; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Where a step sits: the root (parent null), a linear parent's `next` |
| 40 | * (branch null), or one of a branching parent's `branches`. |
| 41 | */ |
| 42 | export interface Slot { |
| 43 | parent: string | null; |
| 44 | branch: number | null; |
| 45 | } |
| 46 | |
| 47 | export const ROOT: Slot = { parent: null, branch: null }; |
| 48 | |
| 49 | export const slotKey = (slot: Slot): string => `${slot.parent ?? ""}/${slot.branch ?? "next"}`; |
| 50 | |
| 51 | export const isBranching = (step: Step): boolean => Array.isArray(step.branches); |
| 52 | |
| 53 | /** The steps a step leads to, in order. */ |
| 54 | export const childrenOf = (step: Step): (Step | null)[] => (isBranching(step) ? step.branches! : [step.next ?? null]); |
| 55 | |
| 56 | /** What takes a removed step's place: its next, or its first non-empty branch. */ |
| 57 | export const successorOf = (step: Step): Step | null => childrenOf(step).find(child => child !== null) ?? null; |
| 58 | |
| 59 | /** The number of steps in a subtree. */ |
| 60 | export function size(step: Step | null): number { |
| 61 | if (!step) return 0; |
| 62 | let n = 1; |
| 63 | for (const child of childrenOf(step)) n += size(child); |
| 64 | return n; |
| 65 | } |
| 66 | |
| 67 | /** Every step id in the sequence. */ |
| 68 | export function idsOf(sequence: Sequence): Set<string> { |
| 69 | const ids = new Set<string>(); |
| 70 | const walk = (step: Step | null) => { |
| 71 | if (!step) return; |
| 72 | ids.add(step.id); |
| 73 | childrenOf(step).forEach(walk); |
| 74 | }; |
| 75 | walk(sequence.root); |
| 76 | return ids; |
| 77 | } |
| 78 | |
| 79 | /** The step with this id. */ |
| 80 | export function find(sequence: Sequence, id: string): Step | null { |
| 81 | const walk = (step: Step | null): Step | null => { |
| 82 | if (!step) return null; |
| 83 | if (step.id === id) return step; |
| 84 | for (const child of childrenOf(step)) { |
| 85 | const found = walk(child); |
| 86 | if (found) return found; |
| 87 | } |
| 88 | return null; |
| 89 | }; |
| 90 | return walk(sequence.root); |
| 91 | } |
| 92 | |
| 93 | /** Where the step with this id sits, or null when there is none. */ |
| 94 | export function slotOf(sequence: Sequence, id: string): Slot | null { |
| 95 | if (sequence.root?.id === id) return ROOT; |
| 96 | const walk = (step: Step | null): Slot | null => { |
| 97 | if (!step) return null; |
| 98 | const children = childrenOf(step); |
| 99 | for (let i = 0; i < children.length; i++) { |
| 100 | if (children[i]?.id === id) return { parent: step.id, branch: isBranching(step) ? i : null }; |
| 101 | const found = walk(children[i]); |
| 102 | if (found) return found; |
| 103 | } |
| 104 | return null; |
| 105 | }; |
| 106 | return walk(sequence.root); |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * A linear run: the head, then each `next`, up to and including the first |
| 111 | * branching step (whose branches are runs of their own). |
| 112 | */ |
| 113 | export function runOf(head: Step | null): Step[] { |
| 114 | const run: Step[] = []; |
| 115 | const seen = new Set<string>(); |
| 116 | for (let step = head; step && !seen.has(step.id); step = isBranching(step) ? null : (step.next ?? null)) { |
| 117 | seen.add(step.id); |
| 118 | run.push(step); |
| 119 | } |
| 120 | return run; |
| 121 | } |
| 122 | |
| 123 | /** The step in a slot. */ |
| 124 | export function childAt(sequence: Sequence, slot: Slot): Step | null { |
| 125 | if (slot.parent === null) return sequence.root; |
| 126 | const parent = find(sequence, slot.parent); |
| 127 | if (!parent) return null; |
| 128 | return slot.branch === null ? (parent.next ?? null) : (parent.branches?.[slot.branch] ?? null); |
| 129 | } |
| 130 | |
| 131 | /** The step with this id replaced by `f(step)` (null removes it), sharing everything off the path. */ |
| 132 | function rewrite(step: Step | null, id: string, f: (step: Step) => Step | null): Step | null { |
| 133 | if (!step) return step; |
| 134 | if (step.id === id) return f(step); |
| 135 | if (isBranching(step)) { |
| 136 | const branches = step.branches!.map(child => rewrite(child, id, f)); |
| 137 | return branches.every((child, i) => child === step.branches![i]) ? step : { ...step, branches }; |
| 138 | } |
| 139 | const next = step.next ?? null; |
| 140 | const rewritten = rewrite(next, id, f); |
| 141 | return rewritten === next ? step : { ...step, next: rewritten }; |
| 142 | } |
| 143 | |
| 144 | /** The sequence with the step in `slot` replaced. */ |
| 145 | function setChildAt(sequence: Sequence, slot: Slot, child: Step | null): Sequence { |
| 146 | if (slot.parent === null) return { ...sequence, root: child }; |
| 147 | const root = rewrite(sequence.root, slot.parent, parent => { |
| 148 | if (slot.branch === null) return isBranching(parent) ? parent : { ...parent, next: child }; |
| 149 | if (!isBranching(parent)) return parent; |
| 150 | const branches = parent.branches!.slice(); |
| 151 | branches[slot.branch] = child; |
| 152 | return { ...parent, branches }; |
| 153 | }); |
| 154 | return root === sequence.root ? sequence : { ...sequence, root }; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * The sequence with `step` inserted in `slot`. What was in the slot moves |
| 159 | * after it: into a linear step's `next`, or a branching step's first branch. |
| 160 | */ |
| 161 | export function insert(sequence: Sequence, slot: Slot, step: Step): Sequence { |
| 162 | const occupant = childAt(sequence, slot); |
| 163 | const placed: Step = isBranching(step) |
| 164 | ? { ...step, branches: step.branches!.map((branch, i) => (i === 0 ? occupant : branch)) } |
| 165 | : { ...step, next: occupant }; |
| 166 | return setChildAt(sequence, slot, placed); |
| 167 | } |
| 168 | |
| 169 | /** The sequence with the step's fields replaced. */ |
| 170 | export function update(sequence: Sequence, id: string, fields: Fields): Sequence { |
| 171 | const root = rewrite(sequence.root, id, step => ({ ...step, fields })); |
| 172 | return root === sequence.root ? sequence : { ...sequence, root }; |
| 173 | } |
| 174 | |
| 175 | /** The sequence without the step: its successor takes its place, its other branches go with it. */ |
| 176 | export function remove(sequence: Sequence, id: string): Sequence { |
| 177 | const root = rewrite(sequence.root, id, successorOf); |
| 178 | return root === sequence.root ? sequence : { ...sequence, root }; |
| 179 | } |
| 180 | |
| 181 | /** How many steps removing this one would discard besides itself. */ |
| 182 | export function discarded(sequence: Sequence, id: string): number { |
| 183 | const step = find(sequence, id); |
| 184 | return step ? size(step) - 1 - size(successorOf(step)) : 0; |
| 185 | } |
| 186 | |
| 187 | /** A step id not already taken. */ |
| 188 | export function freshId(taken: Set<string>, random: () => number = Math.random): string { |
| 189 | for (;;) { |
| 190 | const id = `s${Math.floor(random() * 36 ** 6) |
| 191 | .toString(36) |
| 192 | .padStart(6, "0")}`; |
| 193 | if (!taken.has(id)) return id; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * The value from the field's text. Steps without an id get a fresh one; a |
| 199 | * missing `fields` is `{}`; a step of a kind with `branchCounts` outcomes gets |
| 200 | * that many branch slots (padded with null, never truncated: data is not |
| 201 | * dropped). Throws an Error naming the first malformed step. |
| 202 | */ |
| 203 | export function parse(text: string, branchCounts: ReadonlyMap<string, number> = new Map()): Sequence { |
| 204 | const trimmed = text.trim(); |
| 205 | if (trimmed === "") return { root: null }; |
| 206 | const data: unknown = JSON.parse(trimmed); |
| 207 | if (!isRecord(data) || !("root" in data)) throw new Error('the value must be an object with a "root"'); |
| 208 | const taken = new Set<string>(); |
| 209 | const pending: Step[] = []; |
| 210 | |
| 211 | const read = (raw: unknown, path: string): Step | null => { |
| 212 | if (raw === null || raw === undefined) return null; |
| 213 | if (!isRecord(raw)) throw new Error(`${path}: a step must be an object`); |
| 214 | if (typeof raw.kind !== "string" || raw.kind === "") throw new Error(`${path}: a step needs a "kind"`); |
| 215 | if (raw.fields !== undefined && !isFields(raw.fields)) throw new Error(`${path}: "fields" must map names to text, numbers, booleans or null`); |
| 216 | const id = typeof raw.id === "string" && raw.id !== "" ? raw.id : null; |
| 217 | if (id !== null) { |
| 218 | if (taken.has(id)) throw new Error(`${path}: the id "${id}" is used twice`); |
| 219 | taken.add(id); |
| 220 | } |
| 221 | const step: Step = { id: id ?? "", kind: raw.kind, fields: { ...((raw.fields as Fields | undefined) ?? {}) } }; |
| 222 | const count = branchCounts.get(raw.kind) ?? (Array.isArray(raw.branches) ? raw.branches.length : 0); |
| 223 | if (count > 0 || Array.isArray(raw.branches)) { |
| 224 | const given = Array.isArray(raw.branches) ? raw.branches : []; |
| 225 | const branches = given.map((child, i) => read(child, `${path}.branches[${i}]`)); |
| 226 | while (branches.length < count) branches.push(null); |
| 227 | step.branches = branches; |
| 228 | } else { |
| 229 | step.next = read(raw.next, `${path}.next`); |
| 230 | } |
| 231 | if (id === null) pending.push(step); |
| 232 | return step; |
| 233 | }; |
| 234 | |
| 235 | const root = read(data.root, "root"); |
| 236 | for (const step of pending) { |
| 237 | step.id = freshId(taken); |
| 238 | taken.add(step.id); |
| 239 | } |
| 240 | return { root }; |
| 241 | } |
| 242 | |
| 243 | /** The value as the field's text. Keys in a fixed order: id, kind, fields, then next or branches. */ |
| 244 | export function serialize(sequence: Sequence): string { |
| 245 | const plain = (step: Step | null): unknown => |
| 246 | step === null |
| 247 | ? null |
| 248 | : isBranching(step) |
| 249 | ? { id: step.id, kind: step.kind, fields: step.fields, branches: step.branches!.map(plain) } |
| 250 | : { id: step.id, kind: step.kind, fields: step.fields, next: plain(step.next ?? null) }; |
| 251 | return JSON.stringify({ root: plain(sequence.root) }); |
| 252 | } |
| 253 | |
| 254 | const isRecord = (value: unknown): value is Record<string, unknown> => |
| 255 | typeof value === "object" && value !== null && !Array.isArray(value); |
| 256 | |
| 257 | const isFields = (value: unknown): value is Fields => |
| 258 | isRecord(value) && Object.values(value).every(v => v === null || ["string", "number", "boolean"].includes(typeof v)); |
| 259 | |
| 260 | // ── The element's state ──────────────────────────────────────────────────── |
| 261 | |
| 262 | export interface Model { |
| 263 | value: Sequence; |
| 264 | /** The step whose editor is open. */ |
| 265 | editing: string | null; |
| 266 | /** The open editor belongs to a step just added: canceling it removes the step. */ |
| 267 | fresh: boolean; |
| 268 | /** The slot whose "add a step" menu is open, by slotKey. */ |
| 269 | adding: string | null; |
| 270 | /** The step whose removal waits for a second press (it would discard others). */ |
| 271 | confirming: string | null; |
| 272 | } |
| 273 | |
| 274 | export type Action = |
| 275 | | { type: "menu"; slot: Slot | null } |
| 276 | | { type: "insert"; slot: Slot; step: Step; edit: boolean } |
| 277 | | { type: "edit"; id: string } |
| 278 | | { type: "commit"; id: string; fields: Fields } |
| 279 | | { type: "cancel" } |
| 280 | | { type: "remove"; id: string } |
| 281 | | { type: "load"; value: Sequence }; |
| 282 | |
| 283 | export const start = (value: Sequence): Model => ({ value, editing: null, fresh: false, adding: null, confirming: null }); |
| 284 | |
| 285 | export function step(model: Model, action: Action): Model { |
| 286 | switch (action.type) { |
| 287 | case "menu": |
| 288 | return { ...model, adding: action.slot ? slotKey(action.slot) : null, confirming: null }; |
| 289 | case "insert": |
| 290 | return { |
| 291 | value: insert(model.value, action.slot, action.step), |
| 292 | editing: action.edit ? action.step.id : null, |
| 293 | fresh: action.edit, |
| 294 | adding: null, |
| 295 | confirming: null, |
| 296 | }; |
| 297 | case "edit": |
| 298 | return find(model.value, action.id) ? { ...model, editing: action.id, fresh: false, adding: null, confirming: null } : model; |
| 299 | case "commit": |
| 300 | return { ...model, value: update(model.value, action.id, action.fields), editing: null, fresh: false }; |
| 301 | case "cancel": { |
| 302 | const value = model.fresh && model.editing ? remove(model.value, model.editing) : model.value; |
| 303 | return { value, editing: null, fresh: false, adding: null, confirming: null }; |
| 304 | } |
| 305 | case "remove": |
| 306 | if (discarded(model.value, action.id) > 0 && model.confirming !== action.id) return { ...model, adding: null, confirming: action.id }; |
| 307 | return { |
| 308 | value: remove(model.value, action.id), |
| 309 | editing: model.editing === action.id ? null : model.editing, |
| 310 | fresh: model.editing === action.id ? false : model.fresh, |
| 311 | adding: null, |
| 312 | confirming: null, |
| 313 | }; |
| 314 | case "load": |
| 315 | return start(action.value); |
| 316 | } |
| 317 | } |