tests/composition-editing.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  example,
5  Stack,
6  Shelf,
7  Switcher,
8  type Composition,
9} from "../documentation/components/source/composition.ts";
10import {
11  chooseMember,
12  restoreComposition,
13  restoreSelection,
14  selectionOf,
15} from "../documentation/components/source/composition-editing.ts";
16import {
17  arrangeGroup,
18  restoreArrangement,
19} from "../documentation/components/source/arrangement.ts";
20import {
21  atPath,
22  groupMembers,
23  ungroupMembers,
24  restoreGrouping,
25} from "../documentation/components/source/grouping.ts";
26
27const stored = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
28const text = (value: string): Composition => ({ kind: "Text", text: value });
29function members(tree: Composition | undefined): readonly Composition[] {
30  if (!tree || !("children" in tree)) throw new Error("Expected a group");
31  return tree.children;
32}
33/** A saved group as storage holds it: no promise that it is a composition. */
34const group = (kind: string, ...children: unknown[]) => ({ kind, children });
35function run(tree: Composition, chosen: readonly string[]) {
36  const selection = selectionOf(tree, chosen);
37  if (selection.selected !== "members") throw new Error("Expected members");
38  return selection;
39}
40function content(tree: Composition): Composition[] {
41  return "children" in tree ? tree.children.flatMap(content) : [tree];
42}
43function paths(tree: Composition, path = "0"): string[] {
44  return "children" in tree
45    ? [
46        path,
47        ...tree.children.flatMap((child, index) =>
48          paths(child, `${path}.${index}`),
49        ),
50      ]
51    : [path];
52}
53
54// The investigation's facts: one flat group of six.
55const initial = example("investigation");
56const [finding, completed, updated, plan, approval, destination] = members(
57  initial,
58) as [
59  Composition,
60  Composition,
61  Composition,
62  Composition,
63  Composition,
64  Composition,
65];
66assert.equal(members(initial).length, 6);
67
68/** Switcher(Stack(finding, Switcher(completed, updated)), Shelf(plan, approval), destination),
69 * reached with the editor's own edits. */
70function authored(): Composition {
71  let tree = groupMembers(initial, ["0.1", "0.2"]);
72  tree = arrangeGroup(tree, "0.1", "Switcher");
73  tree = groupMembers(tree, ["0.0", "0.1"]);
74  tree = groupMembers(tree, ["0.1", "0.2"]);
75  tree = arrangeGroup(tree, "0.1", "Shelf");
76  return arrangeGroup(tree, "0", "Switcher");
77}
78
79test("a saved regrouping with its arrangements restores onto the supplied content", () => {
80  const tree = authored();
81  assert.deepEqual(
82    tree,
83    Switcher(
84      Stack(finding, Switcher(completed, updated)),
85      Shelf(plan, approval),
86      destination,
87    ),
88  );
89  const restored = restoreComposition(stored(tree), initial);
90  assert.deepEqual(restored, tree);
91  // The content is the starting composition's own, in its order.
92  content(restored!).forEach((leaf, index) =>
93    assert.equal(leaf, content(initial)[index]),
94  );
95  assert.deepEqual(restoreComposition(stored(initial), initial), initial);
96
97  // Only structure is read. Anything else a saved node carries is dropped,
98  // including members attached to a piece of content.
99  const decorated = stored(tree) as { children: Record<string, unknown>[] };
100  Object.assign(decorated, { style: "position: fixed", path: "0.9" });
101  Object.assign(decorated.children[2]!, {
102    children: [stored(finding), stored(finding)],
103    href: "https://example.com",
104  });
105  assert.deepEqual(restoreComposition(decorated, initial), tree);
106});
107
108test("saved state cannot change, reorder, drop, repeat or add content", () => {
109  const first = Stack(finding, Switcher(completed, updated));
110  const second = Shelf(plan, approval);
111  const tampered: [string, unknown][] = [
112    [
113      "changed text",
114      Stack(
115        finding,
116        text("Investigation failed"),
117        updated,
118        plan,
119        approval,
120        destination,
121      ),
122    ],
123    [
124      "changed kind",
125      Stack(
126        text((finding as { text: string }).text),
127        completed,
128        updated,
129        plan,
130        approval,
131        destination,
132      ),
133    ],
134    [
135      "swapped neighbors",
136      Stack(finding, updated, completed, plan, approval, destination),
137    ],
138    [
139      "swapped inside a group",
140      Stack(finding, Switcher(updated, completed), second, destination),
141    ],
142    ["swapped groups", Stack(second, first, destination)],
143    [
144      "moved across a boundary",
145      Stack(
146        Stack(finding, completed),
147        Stack(plan, updated),
148        approval,
149        destination,
150      ),
151    ],
152    ["dropped content", Stack(first, second)],
153    [
154      "dropped the first",
155      Stack(completed, updated, plan, approval, destination),
156    ],
157    ["repeated content", Stack(first, second, destination, destination)],
158    [
159      "repeated in place",
160      Stack(finding, completed, completed, plan, approval, destination),
161    ],
162    [
163      "added content",
164      Stack(first, second, destination, text("Open the session")),
165    ],
166    ["another exercise's content", example("event")],
167    ["content without text", group("Stack", first, second, { kind: "Text" })],
168    [
169      "text that is not a string",
170      group("Stack", first, second, { kind: "Text", text: 7 }),
171    ],
172    [
173      "text held in a list",
174      group("Stack", first, second, {
175        kind: "Text",
176        text: ["Destination: investigation session"],
177      }),
178    ],
179  ];
180  for (const [label, value] of tampered)
181    assert.equal(restoreComposition(stored(value), initial), undefined, label);
182});
183
184test("saved state needs a group at its root and two members in every group", () => {
185  const six = [finding, completed, updated, plan, approval, destination];
186  const invalid: [string, unknown][] = [
187    ["content at the root", finding],
188    ["a root around one group", Stack(initial)],
189    [
190      "a group of one",
191      Stack(Stack(finding), completed, updated, plan, approval, destination),
192    ],
193    [
194      "a nested group of one",
195      Stack(
196        finding,
197        Stack(Stack(completed, updated)),
198        plan,
199        approval,
200        destination,
201      ),
202    ],
203    ["an empty group beside the content", Stack(...six, Stack())],
204    ["an empty root", Stack()],
205    ["an unknown root arrangement", { kind: "Grid", children: six }],
206    [
207      "an unknown nested arrangement",
208      group(
209        "Stack",
210        finding,
211        group("Row", completed, updated),
212        plan,
213        approval,
214        destination,
215      ),
216    ],
217    [
218      "a content kind holding members",
219      group(
220        "Stack",
221        group("Text", finding, completed),
222        updated,
223        plan,
224        approval,
225        destination,
226      ),
227    ],
228    [
229      "members that are not a list",
230      { kind: "Stack", children: { 0: finding, 1: completed, length: 2 } },
231    ],
232    ["members given as text", { kind: "Stack", children: "ab" }],
233    ["a group with text for members", { kind: "Stack", text: "Stack" }],
234    ["a list at the root", six],
235    ["nothing", null],
236    ["a name", "Stack"],
237    ["a number", 6],
238  ];
239  for (const [label, value] of invalid)
240    assert.equal(restoreComposition(stored(value), initial), undefined, label);
241  assert.equal(restoreComposition(undefined, initial), undefined);
242  // A single piece of content has no regrouping to restore.
243  assert.equal(restoreComposition(stored(finding), finding), undefined);
244  assert.equal(restoreComposition(stored(Stack(finding)), finding), undefined);
245});
246
247test("saved state is bounded in depth and size", () => {
248  const facts = (count: number) =>
249    Array.from({ length: count }, (_, index) => text(`Fact ${index + 1}`));
250  /** `groups` groups, each inside the one before; the last holds the rest. */
251  function chain(leaves: Composition[], groups: number): Composition {
252    const innermost = leaves.length - groups + 1;
253    let tree = Stack(...leaves.slice(-innermost));
254    for (let index = leaves.length - innermost - 1; index >= 0; index--)
255      tree = Stack(leaves[index]!, tree);
256    return tree;
257  }
258  const fourteen = facts(14);
259  const deepest = chain(fourteen, 12);
260  assert.deepEqual(
261    restoreComposition(stored(deepest), Stack(...fourteen)),
262    deepest,
263    "content twelve levels below the root",
264  );
265  assert.equal(
266    restoreComposition(stored(chain(fourteen, 13)), Stack(...fourteen)),
267    undefined,
268    "content thirteen levels below the root",
269  );
270
271  const widest = Stack(...facts(99));
272  assert.deepEqual(
273    restoreComposition(stored(widest), widest),
274    widest,
275    "one hundred nodes",
276  );
277  const wider = Stack(...facts(100));
278  assert.equal(
279    restoreComposition(stored(wider), wider),
280    undefined,
281    "one hundred and one nodes",
282  );
283
284  // Reading stops at the bound, however much more the value holds.
285  const endless = stored(finding);
286  const children: unknown[] = Array.from({ length: 5000 }, () => endless);
287  Object.defineProperty(children, 150, {
288    get() {
289      throw new Error("Read past the node bound");
290    },
291  });
292  assert.equal(
293    restoreComposition({ kind: "Stack", children }, initial),
294    undefined,
295  );
296  let nested: unknown = stored(Stack(finding, completed));
297  for (let depth = 0; depth < 5000; depth++)
298    nested = { kind: "Stack", children: [nested, endless] };
299  assert.equal(restoreComposition(nested, initial), undefined);
300});
301
302test("the combined rule is wider than the focused exercises' rules, which stay as strict", () => {
303  // Whatever a focused exercise accepts, the combined rule restores the same.
304  const flat = example("flat");
305  const regrouped = groupMembers(flat, ["0.1", "0.2"]);
306  assert.deepEqual(restoreGrouping(stored(regrouped), flat), regrouped);
307  assert.deepEqual(restoreComposition(stored(regrouped), flat), regrouped);
308  const grouped = example("grouped");
309  const rearranged = arrangeGroup(grouped, "0.0", "Switcher");
310  assert.deepEqual(restoreArrangement(stored(rearranged), grouped), rearranged);
311  assert.deepEqual(restoreComposition(stored(rearranged), grouped), rearranged);
312
313  // A state with both edits belongs to the combined exercise alone.
314  const both = stored(authored());
315  assert.ok(restoreComposition(both, initial));
316  assert.equal(restoreGrouping(both, initial), undefined);
317  assert.equal(restoreArrangement(both, initial), undefined);
318  const arrangedFlat = stored(arrangeGroup(initial, "0", "Shelf"));
319  assert.equal(restoreGrouping(arrangedFlat, initial), undefined);
320  const regroupedOnly = stored(groupMembers(initial, ["0.3", "0.4"]));
321  assert.equal(restoreArrangement(regroupedOnly, initial), undefined);
322});
323
324test("the root can be selected and arranged, alone, and never ungrouped", () => {
325  assert.deepEqual(selectionOf(initial, ["0"]), {
326    selected: "group",
327    path: "0",
328    group: initial,
329    canUngroup: false,
330  });
331  assert.throws(() => ungroupMembers(initial, "0"), /inner group/);
332  const shelf = arrangeGroup(initial, "0", "Shelf");
333  assert.equal(members(shelf), members(initial));
334  assert.deepEqual(restoreComposition(stored(shelf), initial), shelf);
335
336  // The root has no neighbors: it replaces a selection and is replaced by one.
337  assert.deepEqual(chooseMember(initial, [], "0"), ["0"]);
338  assert.deepEqual(chooseMember(initial, ["0.2", "0.3"], "0"), ["0"]);
339  assert.deepEqual(chooseMember(initial, ["0"], "0.2"), ["0.2"]);
340  assert.deepEqual(chooseMember(initial, ["0"], "0"), []);
341  assert.deepEqual(selectionOf(initial, ["0", "0.0"]), { selected: "nothing" });
342});
343
344test("all the members of a group can be selected, but only their group can be arranged", () => {
345  let chosen: readonly string[] = [];
346  for (const path of ["0.2", "0.3", "0.1", "0.4", "0.0", "0.5"])
347    chosen = chooseMember(initial, chosen, path);
348  assert.deepEqual(selectionOf(initial, chosen), {
349    selected: "members",
350    paths: ["0.0", "0.1", "0.2", "0.3", "0.4", "0.5"],
351    parent: "0",
352    canGroup: false,
353  });
354  assert.throws(() => groupMembers(initial, chosen), /all the members/);
355  // Leaving one neighbor outside makes a group a reader can see.
356  const fewer = chooseMember(initial, chosen, "0.5");
357  assert.ok(run(initial, fewer).canGroup);
358
359  // The same holds for a pair inside a nested group.
360  const tree = authored();
361  assert.deepEqual(selectionOf(tree, ["0.1.1", "0.1.0"]), {
362    selected: "members",
363    paths: ["0.1.0", "0.1.1"],
364    parent: "0.1",
365    canGroup: false,
366  });
367  const parent = selectionOf(tree, ["0.1"]);
368  assert.equal(parent.selected, "group");
369  assert.equal(parent.selected === "group" && parent.group.kind, "Shelf");
370});
371
372test("groups and content select, group and ungroup together as neighbors", () => {
373  // Stack(finding, Switcher(completed, updated), plan, approval, destination)
374  const tree = arrangeGroup(
375    groupMembers(initial, ["0.1", "0.2"]),
376    "0.1",
377    "Switcher",
378  );
379  const inner = atPath(tree, "0.1");
380
381  let chosen = chooseMember(tree, [], "0.1");
382  assert.equal(selectionOf(tree, chosen).selected, "group");
383  chosen = chooseMember(tree, chosen, "0.2");
384  assert.deepEqual(selectionOf(tree, chosen), {
385    selected: "members",
386    paths: ["0.1", "0.2"],
387    parent: "0",
388    canGroup: true,
389  });
390  const three = chooseMember(tree, chosen, "0.0");
391  assert.deepEqual(three, ["0.1", "0.2", "0.0"], "in the order chosen");
392  assert.deepEqual(
393    run(tree, three).paths,
394    ["0.0", "0.1", "0.2"],
395    "read in reading order",
396  );
397
398  // Anything that is not a neighbor starts a new selection, at any level.
399  assert.deepEqual(chooseMember(tree, chosen, "0.4"), ["0.4"]);
400  assert.deepEqual(chooseMember(tree, chosen, "0.1.0"), ["0.1.0"]);
401  assert.deepEqual(chooseMember(tree, ["0.1.0"], "0.1"), ["0.1"]);
402  assert.deepEqual(selectionOf(tree, ["0.1.0"]), {
403    selected: "content",
404    path: "0.1.0",
405  });
406  // Choosing a selected member leaves it out.
407  assert.deepEqual(chooseMember(tree, three, "0.0"), ["0.1", "0.2"]);
408  assert.deepEqual(chooseMember(tree, chosen, "0.1"), ["0.2"]);
409  assert.deepEqual(
410    chooseMember(tree, three, "0.1"),
411    ["0.2"],
412    "from the middle",
413  );
414  assert.equal(chooseMember(tree, chosen, "0.9"), chosen, "no such member");
415
416  // The order of choosing does not matter to the group. The inner group
417  // keeps its arrangement and its members; the new group is a Stack.
418  const grouped = groupMembers(tree, ["0.2", "0.1"]);
419  assert.equal(atPath(grouped, "0.1")?.kind, "Stack");
420  assert.equal(atPath(grouped, "0.1.0"), inner);
421  assert.equal(atPath(grouped, "0.1.1"), plan);
422  content(grouped).forEach((leaf, index) =>
423    assert.equal(leaf, content(initial)[index]),
424  );
425  const released = ungroupMembers(grouped, "0.1");
426  assert.deepEqual(released, tree);
427  assert.equal(atPath(released, "0.1"), inner);
428});
429
430test("any sequence of edits keeps the content, its order, and a restorable state", () => {
431  let seed = 20261120;
432  const random = (below: number) => {
433    seed = (seed * 1664525 + 1013904223) >>> 0;
434    return Math.floor((seed / 2 ** 32) * below);
435  };
436  const supplied = content(initial);
437  const made = { Group: 0, Ungroup: 0, Arrange: 0 };
438  let deepest = 0;
439  let tree = initial;
440  let chosen: readonly string[] = [];
441  for (let step = 0; step < 4000; step++) {
442    const all = paths(tree);
443    chosen = chooseMember(tree, chosen, all[random(all.length)]!);
444    const selection = selectionOf(tree, chosen);
445    assert.ok(
446      chosen.length === 0 || selection.selected !== "nothing",
447      "choosing always leaves a selection the editor can read",
448    );
449    if (selection.selected === "members" && selection.canGroup && random(4)) {
450      tree = groupMembers(tree, chosen);
451      made.Group++;
452      // The new group stands where its first member stood, and can be undone
453      // by hand.
454      chosen = [selection.paths[0]!];
455      const group = selectionOf(tree, chosen);
456      assert.ok(group.selected === "group" && group.canUngroup);
457      assert.equal(group.group.kind, "Stack");
458    } else if (selection.selected === "group") {
459      if (selection.canUngroup && random(4) === 0) {
460        const count = selection.group.children.length;
461        const first = Number(selection.path.split(".").at(-1));
462        const parent = selection.path.slice(0, selection.path.lastIndexOf("."));
463        tree = ungroupMembers(tree, selection.path);
464        made.Ungroup++;
465        // The released members are a run that can be grouped again.
466        chosen = Array.from(
467          { length: count },
468          (_, index) => `${parent}.${first + index}`,
469        );
470        const run = selectionOf(tree, chosen);
471        assert.ok(run.selected === "members" && run.canGroup);
472      } else {
473        const kind = (["Stack", "Shelf", "Switcher"] as const)[random(3)]!;
474        const next = arrangeGroup(tree, selection.path, kind);
475        if (next !== tree) made.Arrange++;
476        tree = next;
477        assert.deepEqual(selectionOf(tree, chosen), {
478          ...selection,
479          group: atPath(tree, selection.path),
480        });
481      }
482    }
483    const now = content(tree);
484    assert.equal(now.length, supplied.length);
485    now.forEach((leaf, index) => assert.equal(leaf, supplied[index]));
486    for (const path of paths(tree)) {
487      const node = atPath(tree, path)!;
488      if ("children" in node) assert.ok(node.children.length >= 2, path);
489      deepest = Math.max(deepest, path.split(".").length - 1);
490    }
491    assert.deepEqual(restoreComposition(stored(tree), initial), tree);
492  }
493  // The walk exercised every edit and reached the deepest nesting six facts allow.
494  assert.ok(made.Group > 100 && made.Ungroup > 100 && made.Arrange > 100);
495  assert.equal(deepest, 5);
496});
497
498test("Undo returns to a composition in which the edit's own selection still applies", () => {
499  // Each entry is what the component keeps: the composition and selection an
500  // edit was made from.
501  const history: [Composition, string[]][] = [];
502  let tree = initial;
503  const edit = (chosen: string[], next: Composition) => {
504    history.push([tree, chosen]);
505    tree = next;
506  };
507  edit(["0.2", "0.1"], groupMembers(tree, ["0.2", "0.1"]));
508  edit(["0.1"], arrangeGroup(tree, "0.1", "Switcher"));
509  edit(["0.1"], ungroupMembers(tree, "0.1"));
510  edit(["0"], arrangeGroup(tree, "0", "Shelf"));
511
512  const restored = history.reverse().map(([before, chosen]) => {
513    assert.deepEqual(restoreSelection(stored(chosen), before), chosen);
514    const selection = selectionOf(before, chosen);
515    return selection.selected === "group"
516      ? `${selection.path} ${selection.group.kind}${selection.canUngroup ? ", can ungroup" : ""}`
517      : selection.selected === "members"
518        ? `${selection.paths.join(" ")}${selection.canGroup ? ", can group" : ""}`
519        : selection.selected;
520  });
521  assert.deepEqual(restored, [
522    "0 Stack",
523    "0.1 Switcher, can ungroup",
524    "0.1 Stack, can ungroup",
525    "0.1 0.2, can group",
526  ]);
527});
528
529test("a saved selection restores only if the reader could have made it there", () => {
530  const tree = authored();
531  for (const chosen of [
532    [],
533    ["0"],
534    ["0.2"],
535    ["0.0.1"],
536    ["0.1", "0.0"],
537    ["0.0", "0.1", "0.2"],
538    ["0.0.1.0", "0.0.1.1"],
539  ])
540    assert.deepEqual(restoreSelection(stored(chosen), tree), chosen);
541
542  const invalid: [string, unknown][] = [
543    ["a stale member", ["0.3"]],
544    ["a stale run", ["0.2", "0.3"]],
545    ["members that skip a neighbor", ["0.0", "0.2"]],
546    ["members of different groups", ["0.0.0", "0.1.0"]],
547    ["a group and its own member", ["0.0", "0.0.0"]],
548    ["the root with a member", ["0", "0.0"]],
549    ["a member twice", ["0.1", "0.1"]],
550    ["a path that is not canonical", ["0.01"]],
551    ["a negative index", ["0.-1"]],
552    ["an empty path", [""]],
553    ["numbers", [0, 1]],
554    ["a nested list", [["0.0"]]],
555    ["a path, not a list", "0.0"],
556    ["an object shaped like a list", { 0: "0.0", length: 1 }],
557    ["nothing", null],
558  ];
559  for (const [label, value] of invalid)
560    assert.deepEqual(restoreSelection(value, tree), [], label);
561
562  // A selection belongs to one composition: valid in one, stale in another.
563  assert.deepEqual(restoreSelection(["0.0.1.0"], tree), ["0.0.1.0"]);
564  assert.deepEqual(restoreSelection(["0.0.1.0"], initial), []);
565});