diff --git a/src/ui/forks.ts b/src/ui/forks.ts new file mode 100644 index 0000000..4b28697 --- /dev/null +++ b/src/ui/forks.ts @@ -0,0 +1,235 @@ +/** + * The panes view's panes as a tree. Each pane may have several children ("forks"), each of which + * continues its own trail to the right and may fork again. Every node remembers which child is + * picked; following the picks from the root gives the focused branch, the trail the keys move along + * (`store.trail`), so there is always exactly one. A plain trail is the tree with one child + * everywhere. + * + * Pure functions on immutable trees: an operation copies the path it changes and shares the rest, + * so a tree that did not change is the same object (the store memoises on identity). A node's `id` + * names the pane for as long as it is open (keys, the hosts of article panes off the branch). + */ + +export interface Tree { + ref: R; + kids: Tree[]; + /** Which child the branch goes on to (0 with none): the focused one, or the one last focused. */ + pick: number; + id: number; + /** Where the reader was when they last left this fork (to come back to). */ + seen?: S; +} + +export type Same = (a: R, b: R) => boolean; + +let ids = 0; +export const leaf = (ref: R): Tree => ({ ref, kids: [], pick: 0, id: ++ids }); + +/** A plain trail as a tree. */ +export function chain(refs: R[]): Tree | null { + let t: Tree | null = null; + for (let i = refs.length - 1; i >= 0; i--) t = { ref: refs[i], kids: t ? [t] : [], pick: 0, id: ++ids }; + return t; +} + +/** The nodes of the focused branch, from the root. */ +export function path(t: Tree | null): Tree[] { + const out: Tree[] = []; + for (let n: Tree | undefined = t ?? undefined; n; n = n.kids[n.pick]) out.push(n); + return out; +} + +/** Replace the node at depth i of the focused branch with f(node), copying the path above it. */ +function at(t: Tree, i: number, f: (n: Tree) => Tree): Tree { + if (i <= 0) return f(t); + const kid = t.kids[t.pick]; + if (!kid) return t; + const kids = t.kids.slice(); + kids[t.pick] = at(kid, i - 1, f); + return { ...t, kids }; +} + +/** The path of nodes from the root to the node with this id, or null. */ +export function trace(t: Tree | null, id: number): Tree[] | null { + if (!t) return null; + if (t.id === id) return [t]; + for (const k of t.kids) { + const p = trace(k, id); + if (p) return [t, ...p]; + } + return null; +} + +/** Every node, depth first, top row first, with its depth (its column). */ +export function all(t: Tree | null, depth = 0, out: { node: Tree; depth: number }[] = []) { + if (!t) return out; + out.push({ node: t, depth }); + for (const k of t.kids) all(k, depth + 1, out); + return out; +} + +/** How many leaves (rows at the far right) a subtree has. */ +export function leaves(t: Tree): number { + return t.kids.length ? t.kids.reduce((n, k) => n + leaves(k), 0) : 1; +} + +/** Change the node with this id, copying the path to it. */ +export function update(t: Tree, id: number, f: (n: Tree) => Tree): Tree { + if (t.id === id) return f(t); + let changed = false; + const kids = t.kids.map((k) => { + const u = update(k, id, f); + if (u !== k) changed = true; + return u; + }); + return changed ? { ...t, kids } : t; +} + +/** + * Open something to the right of pane i of the focused branch. If it is already open there (as any + * of the forks) that fork is picked and kept as it is. Otherwise a fork adds a child below the + * others; a plain open replaces the picked child (and everything right of it), or adds the first. + */ +export function open(t: Tree, i: number, ref: R, fork: boolean, same: Same): Tree { + return at(t, i, (n) => { + const k = n.kids.findIndex((c) => same(c.ref, ref)); + if (k >= 0) return k === n.pick ? n : { ...n, pick: k }; + if (!n.kids.length) return { ...n, kids: [leaf(ref)], pick: 0 }; + if (fork) return { ...n, kids: [...n.kids, leaf(ref)], pick: n.kids.length }; + const kids = n.kids.slice(); + kids[n.pick] = leaf(ref); + return { ...n, kids }; + }); +} + +/** Close everything right of pane i of the focused branch, every fork of it included. */ +export function closeRight(t: Tree, i: number): Tree { + return at(t, i, (n) => (n.kids.length ? { ...n, kids: [], pick: 0 } : n)); +} + +/** Remove a child of a node, picking the one that takes its place (the one below, else the one above). */ +function dropKid(n: Tree, k: number): Tree { + const kids = n.kids.filter((_, j) => j !== k); + const pick = k < n.pick ? n.pick - 1 : Math.max(0, Math.min(n.pick, kids.length - 1)); + return { ...n, kids, pick }; +} + +/** Close pane i of the focused branch (i ≥ 1) and everything right of it. Its siblings stay. */ +export function closeAt(t: Tree, i: number): Tree { + if (i < 1) return t; + return at(t, i - 1, (n) => (n.kids.length ? dropKid(n, n.pick) : n)); +} + +/** Close the child of pane i of the focused branch that shows this (whichever fork it is). */ +export function closeChild(t: Tree, i: number, ref: R, same: Same): Tree { + return at(t, i, (n) => { + const k = n.kids.findIndex((c) => same(c.ref, ref)); + return k < 0 ? n : dropKid(n, k); + }); +} + +/** Make the node with this id lie on the focused branch (its own picks below it kept). */ +export function select(t: Tree, id: number): Tree | null { + if (t.id === id) return t; + for (let k = 0; k < t.kids.length; k++) { + const s = select(t.kids[k], id); + if (s) return s === t.kids[k] && k === t.pick ? t : { ...t, kids: t.kids.map((c, j) => (j === k ? s : c)), pick: k }; + } + return null; +} + +/** + * The fork above (delta −1) or below (+1) the focused branch, in the order the rows are drawn: from + * the branch's last pane leftwards, the nearest pane with a sibling in that direction. Returns the + * tree with that sibling picked and the depth it is at, or null at the top or bottom. + */ +export function sibling(t: Tree, delta: number): { tree: Tree; depth: number } | null { + const p = path(t); + for (let d = p.length - 1; d >= 1; d--) { + const parent = p[d - 1]; + const k = parent.pick + delta; + if (k >= 0 && k < parent.kids.length) return { tree: at(t, d - 1, (n) => ({ ...n, pick: k })), depth: d }; + } + return null; +} + +/** Drop every pane whose ref fails `keep` (with everything right of it). Null if the root goes. Unchanged trees are returned as they are. */ +export function prune(t: Tree | null, keep: (r: R) => boolean): Tree | null { + if (!t || !keep(t.ref)) return null; + let changed = false; + // The picked child, or the one that takes its place: as many kept children before it. + let pick = 0; + const kids: Tree[] = []; + t.kids.forEach((k, j) => { + const p = prune(k, keep); + if (p !== k) changed = true; + if (p) kids.push(p); + if (j === t.pick) pick = kids.length - (p ? 1 : 0); + }); + if (!changed) return t; + return { ...t, kids, pick: Math.max(0, Math.min(pick, kids.length - 1)) }; +} + +/** + * Make the focused branch this list of refs, keeping every pane that is already on the way: where a + * ref is already a child it is picked; where it is not, the picked child is replaced by the rest of + * the list. Panes right of the list's end close. A different root starts again. + */ +export function withBranch(t: Tree | null, refs: R[], same: Same): Tree | null { + if (!refs.length) return null; + if (!t || !same(t.ref, refs[0])) return chain(refs); + const go = (n: Tree, i: number): Tree => { + if (i === refs.length) return n.kids.length ? { ...n, kids: [], pick: 0 } : n; + const k = n.kids.findIndex((c) => same(c.ref, refs[i])); + if (k < 0) { + const rest = chain(refs.slice(i))!; + const kids = n.kids.length ? n.kids.map((c, j) => (j === n.pick ? rest : c)) : [rest]; + return { ...n, kids, pick: n.kids.length ? n.pick : 0 }; + } + const sub = go(n.kids[k], i + 1); + return sub === n.kids[k] && k === n.pick ? n : { ...n, kids: n.kids.map((c, j) => (j === k ? sub : c)), pick: k }; + }; + return go(t, 1); +} + +/** As stored: refs (made storable by the caller), children and picks; no ids, nothing remembered. */ +export interface Saved { + ref: R; + kids?: Saved[]; + pick?: number; +} + +export function save(t: Tree | null, ref: (r: R) => O): Saved | null { + if (!t) return null; + const out: Saved = { ref: ref(t.ref) }; + if (t.kids.length) out.kids = t.kids.map((k) => save(k, ref)!); + if (t.pick) out.pick = t.pick; + return out; +} + +/** Read a stored tree back, dropping whatever does not pass `ok` (and is not shaped like a tree). */ +export function load(o: unknown, ok: (r: unknown) => r is R): Tree | null { + if (!o || typeof o !== "object" || !ok((o as Saved).ref)) return null; + const s = o as Saved; + const kids = (Array.isArray(s.kids) ? s.kids : []).map((k) => load(k, ok)).filter((k): k is Tree => !!k); + const pick = Math.max(0, Math.min(typeof s.pick === "number" ? Math.floor(s.pick) : 0, kids.length - 1)); + return { ref: s.ref as R, kids, pick, id: ++ids }; +} + +/** What was stored: the tree, or, from before there were forks, the trail as a tree with one branch. */ +export function restore(saved: unknown, trail: unknown[] | undefined, ok: (r: unknown) => r is R): Tree | null { + return saved ? load(saved, ok) : chain((trail ?? []).filter(ok)); +} + +/** Whether a tree is well formed: picks in range, no pane twice among siblings, ids unique. */ +export function valid(t: Tree | null, same: Same): boolean { + const seen = new Set(); + const ok = (n: Tree): boolean => { + if (seen.has(n.id)) return false; + seen.add(n.id); + if (n.pick < 0 || n.pick >= Math.max(1, n.kids.length) || !Number.isInteger(n.pick)) return false; + for (let a = 0; a < n.kids.length; a++) for (let b = a + 1; b < n.kids.length; b++) if (same(n.kids[a].ref, n.kids[b].ref)) return false; + return n.kids.every(ok); + }; + return !t || ok(t); +} diff --git a/tests/forks.test.ts b/tests/forks.test.ts new file mode 100644 index 0000000..13fb4d7 --- /dev/null +++ b/tests/forks.test.ts @@ -0,0 +1,185 @@ +/** The panes view's tree of forks (src/ui/forks.ts): each operation, and any sequence of them leaving one well-formed tree with one focused branch. */ +import fc from "fast-check"; +import { describe, expect, it } from "vitest"; +import { all, chain, closeAt, closeChild, closeRight, leaves, load, open, path, prune, restore, save, select, sibling, valid, withBranch, type Tree } from "../src/ui/forks"; + +type T = Tree; +const same = (a: string, b: string) => a === b; +const branch = (t: T | null) => path(t).map((n) => n.ref); +/** The tree drawn as nested lists, the picked child starred. */ +const shape = (t: T | null): unknown => (t ? (t.kids.length ? [t.ref, t.kids.map((k, j) => (j === t.pick ? ["*", shape(k)] : shape(k)))] : t.ref) : null); + +describe("forks", () => { + it("a plain trail is a chain, and a plain open replaces what is right of the pane", () => { + let t = chain(["a", "b", "c"])!; + expect(branch(t)).toEqual(["a", "b", "c"]); + t = open(t, 0, "x", false, same); + expect(branch(t)).toEqual(["a", "x"]); + expect(t.kids).toHaveLength(1); + // Already there: nothing changes, and what is right of it stays. + const u = chain(["a", "b", "c"])!; + expect(open(u, 0, "b", false, same)).toBe(u); + }); + + it("a fork adds a child below the others and picks it; with no child it is a plain open", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + expect(shape(t)).toEqual(["a", [["b", [["*", "c"]]], ["*", "x"]]]); + expect(branch(t)).toEqual(["a", "x"]); + t = open(t, 1, "y", true, same); // x has no child: a plain open + expect(branch(t)).toEqual(["a", "x", "y"]); + expect(t.kids[1].kids).toHaveLength(1); + t = open(t, 0, "z", true, same); + expect(t.kids.map((k) => k.ref)).toEqual(["b", "x", "z"]); + expect(leaves(t)).toBe(3); + }); + + it("opening what is already a fork of the pane picks that fork, plain or not, instead of a duplicate", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + t = open(t, 0, "b", false, same); + expect(branch(t)).toEqual(["a", "b", "c"]); + expect(t.kids.map((k) => k.ref)).toEqual(["b", "x"]); + t = open(t, 0, "x", true, same); + expect(branch(t)).toEqual(["a", "x"]); + expect(t.kids).toHaveLength(2); + }); + + it("a plain open in a fork replaces only that fork", () => { + let t = chain(["a", "b"])!; + t = open(t, 0, "x", true, same); + t = open(t, 0, "y", false, same); + expect(t.kids.map((k) => k.ref)).toEqual(["b", "y"]); + expect(branch(t)).toEqual(["a", "y"]); + }); + + it("moves to the fork above and below in the order rows are drawn, from the deepest pane with one", () => { + // a ─ b ─ b1 rows: b/b1, b/b2, c + // └ b2 + // └ c + let t = chain(["a", "b", "b1"])!; + t = open(t, 1, "b2", true, same); + t = open(t, 0, "c", true, same); + expect(branch(t)).toEqual(["a", "c"]); + let s = sibling(t, -1)!; + expect(s.depth).toBe(1); + expect(branch(s.tree)).toEqual(["a", "b", "b2"]); // b remembers b2 was picked + s = sibling(s.tree, -1)!; + expect(s.depth).toBe(2); + expect(branch(s.tree)).toEqual(["a", "b", "b1"]); + expect(sibling(s.tree, -1)).toBeNull(); + s = sibling(s.tree, 1)!; + expect(branch(s.tree)).toEqual(["a", "b", "b2"]); + s = sibling(s.tree, 1)!; + expect(branch(s.tree)).toEqual(["a", "c"]); + expect(sibling(s.tree, 1)).toBeNull(); + expect(sibling(chain(["a", "b"])!, 1)).toBeNull(); + }); + + it("closes a branch: right of a pane (every fork), a pane and what follows it, or one child", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + t = open(t, 0, "y", true, same); + expect(branch(closeRight(t, 0))).toEqual(["a"]); + // Close the focused fork (y, the last): the one above takes its place. + let u = closeAt(t, 1); + expect(u.kids.map((k) => k.ref)).toEqual(["b", "x"]); + expect(branch(u)).toEqual(["a", "x"]); + // The middle one: the one below takes its place. + u = closeAt(select(t, t.kids[1].id)!, 1); + expect(branch(u)).toEqual(["a", "y"]); + // Closing the last-but-one fork leaves a plain trail. + u = closeAt(closeAt(t, 1), 1); + expect(shape(u)).toEqual(["a", [["*", ["b", [["*", "c"]]]]]]); + // One child by what it shows, whichever fork it is; picks stay on the same pane. + u = closeChild(t, 0, "b", same); + expect(u.kids.map((k) => k.ref)).toEqual(["x", "y"]); + expect(branch(u)).toEqual(["a", "y"]); + expect(closeChild(t, 0, "nope", same)).toBe(t); + expect(closeAt(t, 0)).toBe(t); + }); + + it("drops a deleted node's pane wherever it is, with what is right of it", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + t = open(t, 1, "gone", false, same); + t = open(t, 2, "after", false, same); + expect(branch(t)).toEqual(["a", "x", "gone", "after"]); + const p = prune(t, (r) => r !== "gone")!; + expect(branch(p)).toEqual(["a", "x"]); + expect(branch(select(p, p.kids[0].id))).toEqual(["a", "b", "c"]); + // A deleted fork that is not focused goes without moving the branch. + const q = prune(select(t, t.kids[0].id)!, (r) => r !== "x")!; + expect(branch(q)).toEqual(["a", "b", "c"]); + expect(q.kids).toHaveLength(1); + // Nothing deleted: the same tree. + expect(prune(t, () => true)).toBe(t); + expect(prune(t, (r) => r !== "a")).toBeNull(); + }); + + it("makes a path the branch, keeping the forks off it", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + let u = withBranch(t, ["a", "b", "d"], same)!; + expect(branch(u)).toEqual(["a", "b", "d"]); + expect(u.kids.map((k) => k.ref)).toEqual(["b", "x"]); + u = withBranch(t, ["a", "x"], same)!; + expect(u).toBe(t); + expect(branch(withBranch(t, ["q", "r"], same))).toEqual(["q", "r"]); + expect(branch(withBranch(t, ["a"], same))).toEqual(["a"]); + }); + + it("is stored without ids, and an old stored trail loads as a tree with one branch", () => { + let t = chain(["a", "b", "c"])!; + t = open(t, 0, "x", true, same); + t = open(t, 1, "y", true, same); + const isStr = (r: unknown): r is string => typeof r === "string"; + const back = load(JSON.parse(JSON.stringify(save(t, (r) => r))), isStr); + expect(shape(back)).toEqual(shape(t)); + expect(restore(undefined, ["a", "b"], isStr)!.kids[0].ref).toBe("b"); + expect(branch(restore(undefined, ["a", "b"], isStr))).toEqual(["a", "b"]); + expect(restore(undefined, [], isStr)).toBeNull(); + // Junk is dropped, not trusted. + expect(load({ ref: "a", kids: [{ ref: 3 }, { ref: "b" }], pick: 9 }, isStr)!.kids.map((k) => k.ref)).toEqual(["b"]); + expect(load({ ref: "a", kids: [{ ref: 3 }, { ref: "b" }], pick: 9 }, isStr)!.pick).toBe(0); + expect(load("nonsense", isStr)).toBeNull(); + }); + + it("any sequence of operations leaves a well-formed tree with exactly one focused branch", () => { + const refs = ["a", "b", "c", "d", "e"]; + const op = fc.record({ kind: fc.integer({ min: 0, max: 8 }), i: fc.nat(6), r: fc.integer({ min: 0, max: refs.length - 1 }), d: fc.boolean() }); + fc.assert( + fc.property(fc.array(op, { maxLength: 60 }), (ops) => { + let t: T | null = chain(["root"]); + for (const o of ops) { + if (!t) t = chain(["root"])!; + const depth = path(t).length; + const i = o.i % depth; + const r = refs[o.r]; + switch (o.kind) { + case 0: t = open(t, i, r, false, same); break; + case 1: t = open(t, i, r, true, same); break; + case 2: t = sibling(t, o.d ? 1 : -1)?.tree ?? t; break; + case 3: t = closeRight(t, i); break; + case 4: t = closeAt(t, i); break; + case 5: t = closeChild(t, i, r, same); break; + case 6: t = prune(t, (x) => x !== r); break; + case 7: { + const nodes = all(t); + t = select(t, nodes[o.i % nodes.length].node.id) ?? t; + break; + } + case 8: t = withBranch(t, ["root", ...refs.slice(0, i)], same); break; + } + if (!valid(t, same)) return false; + // One branch, from the root to a pane with nothing right of it, each step a picked child. + const p = path(t); + if (t && (p[0] !== t || p[p.length - 1].kids.length !== 0)) return false; + for (let k = 1; k < p.length; k++) if (p[k - 1].kids[p[k - 1].pick] !== p[k]) return false; + } + return true; + }), + { numRuns: 400 }, + ); + }); +});