tests/composing.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  declaration,
5  Stack,
6  Shelf,
7  Switcher,
8  type Composition,
9  type LeafKind,
10  type Primitive,
11} from "../documentation/components/source/composition.ts";
12import {
13  arrangeGroup,
14  arrangements,
15} from "../documentation/components/source/arrangement.ts";
16import { atPath } from "../documentation/components/source/grouping.ts";
17import { movesFor } from "../documentation/components/source/movement.ts";
18import { spacingLevels } from "../documentation/components/source/primitives.ts";
19import {
20  addGroup,
21  addText,
22  blankComposition,
23  commitEdit,
24  contentKinds,
25  editContentKind,
26  editsFor,
27  editText,
28  isContentKind,
29  restoreWorkingCopy,
30  restoreWorkingTree,
31  startWorkingCopy,
32  undoEdit,
33  workingCopyLimits,
34  type Content,
35  type Edited,
36  type Insertion,
37  type WorkingCopy,
38} from "../documentation/components/source/working-copy.ts";
39
40const stored = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
41const content = (kind: LeafKind, text: string): Content => ({ kind, text });
42const text = (value: string) => content("Text", value);
43const [a, b, c] = ["a", "b", "c"].map(text) as [
44  Composition,
45  Composition,
46  Composition,
47];
48const to = (parent: string, index: number): Insertion => ({ parent, index });
49function at(tree: Composition, path: string): Composition {
50  const node = atPath(tree, path);
51  if (!node) throw new Error(`Nothing at ${path}`);
52  return node;
53}
54const printed = (tree: Composition) =>
55  declaration(tree)
56    .map((line) => line.tokens.map((token) => token.text).join(""))
57    .join("\n");
58/** A chain of `levels` Stacks, the innermost empty. */
59const nested = (levels: number): Composition =>
60  levels === 1 ? Stack() : Stack(nested(levels - 1));
61/** A value the type system would refuse, as a control's value arrives. */
62const untyped = <T>(value: string) => value as unknown as T;
63
64test("content has one of three roles, and nothing else is one", () => {
65  assert.deepEqual(contentKinds, ["Text", "Heading", "Meta"]);
66  for (const kind of contentKinds) assert.equal(isContentKind(kind), true);
67  for (const other of [
68    ...arrangements,
69    "text",
70    "Title",
71    "",
72    7,
73    null,
74    undefined,
75  ])
76    assert.equal(isContentKind(other), false, String(other));
77});
78
79test("changing a role keeps the wording, the place and everything around it", () => {
80  const update = content("Text", "Updated Nov 18, 10:34 AM");
81  const inner = Shelf(update, b);
82  const title = content("Heading", "Request-log queries");
83  const tree = Stack(title, Switcher(a, inner), c);
84  const before = stored(tree);
85
86  const edited = editContentKind(tree, "0.1.1.0", "Meta");
87  assert.deepEqual(
88    edited,
89    Stack(
90      title,
91      Switcher(a, Shelf(content("Meta", "Updated Nov 18, 10:34 AM"), b)),
92      c,
93    ),
94  );
95  // Nodes the edit did not pass through are the same objects as before.
96  assert.equal(at(edited, "0.0"), title);
97  assert.equal(at(edited, "0.1.0"), a);
98  assert.equal(at(edited, "0.1.1.1"), b);
99  assert.equal(at(edited, "0.2"), c);
100  assert.deepEqual(tree, before, "the original is not rewritten");
101
102  assert.equal(
103    editContentKind(tree, "0.0", "Heading"),
104    tree,
105    "nothing changed",
106  );
107  // Through every role and back: the wording never depended on the role.
108  let cycled = tree;
109  for (const kind of ["Heading", "Meta", "Text"] as const) {
110    cycled = editContentKind(cycled, "0.1.1.0", kind);
111    assert.deepEqual(at(cycled, "0.1.1.0"), content(kind, update.text));
112  }
113  assert.deepEqual(cycled, tree);
114  assert.deepEqual(
115    at(editContentKind(Stack(text("")), "0.0", "Heading"), "0.0"),
116    content("Heading", ""),
117    "wording may be empty",
118  );
119});
120
121test("a role belongs to content and an arrangement to a group", () => {
122  const tree = Stack(a, Switcher(b, c));
123  // A group has no role, and an arrangement is not one.
124  assert.throws(() => editContentKind(tree, "0.1", "Heading"));
125  assert.throws(() => editContentKind(tree, "0", "Text"));
126  assert.throws(() => editContentKind(tree, "0.7", "Meta"), "nothing there");
127  assert.throws(() => editContentKind(tree, "0.0", untyped("Stack")));
128  assert.throws(() => editContentKind(tree, "0.0", untyped("Title")));
129  // Content has no arrangement.
130  assert.throws(() => arrangeGroup(tree, "0.0", "Shelf"));
131
132  // Every role sits in every arrangement, and each changes without the other.
133  for (const arrangement of arrangements) {
134    for (const role of contentKinds) {
135      const group = Stack({ kind: arrangement, children: [a, b] });
136      const asRole = editContentKind(group, "0.0.0", role);
137      assert.equal(at(asRole, "0.0").kind, arrangement);
138      assert.equal(at(asRole, "0.0.1"), b, "its neighbor is untouched");
139      for (const next of arrangements) {
140        const arranged = arrangeGroup(asRole, "0.0", next);
141        assert.deepEqual(at(arranged, "0.0.0"), content(role, "a"));
142        assert.equal(at(arranged, "0.0.0"), at(asRole, "0.0.0"));
143      }
144    }
145  }
146});
147
148test("a role changes nothing about grouping: spacing, selection and moves stay the same", () => {
149  const tree = Stack(Stack(a, Switcher(b, c)), Shelf(a), b);
150  const selections = [["0.0.0"], ["0.0.1.0"], ["0.1.0"], ["0.2"]];
151  for (const role of contentKinds) {
152    let roled = tree;
153    for (const [path] of selections)
154      roled = editContentKind(roled, path!, role);
155    // Structural spacing is computed from nesting alone.
156    assert.deepEqual(spacingLevels(roled), spacingLevels(tree), role);
157    for (const chosen of selections) {
158      const { text: was, ...before } = editsFor(tree, chosen);
159      const { text: is, ...after } = editsFor(roled, chosen);
160      assert.deepEqual(after, before, `${role} at ${chosen}`);
161      assert.equal(is?.path, was?.path);
162      assert.equal(is?.content.kind, role);
163      assert.deepEqual(
164        movesFor(roled, chosen)!.places.map((place) => [
165          place.parent,
166          place.index,
167        ]),
168        movesFor(tree, chosen)!.places.map((place) => [
169          place.parent,
170          place.index,
171        ]),
172      );
173    }
174  }
175  // The declaration names the role and keeps the wording.
176  assert.equal(
177    printed(editContentKind(Stack(a, b), "0.1", "Meta")),
178    'Stack(Text("a"), Meta("b"))',
179  );
180});
181
182test("an empty group is added in place, with its arrangement, and is selected", () => {
183  const tree = Stack(a, Switcher(b), Shelf());
184  for (const kind of arrangements) {
185    const empty: Composition = { kind, children: [] };
186    const inside = addGroup(tree, to("0.2", 0), kind);
187    assert.deepEqual(inside.tree, Stack(a, Switcher(b), Shelf(empty)));
188    assert.deepEqual(inside.chosen, ["0.2.0"]);
189
190    const between = addGroup(tree, to("0", 1), kind);
191    assert.deepEqual(between.tree, Stack(a, empty, Switcher(b), Shelf()));
192    assert.deepEqual(between.chosen, ["0.1"]);
193    assert.equal(at(between.tree, "0.0"), a);
194    assert.equal(
195      at(between.tree, "0.2"),
196      at(tree, "0.1"),
197      "moved along, intact",
198    );
199
200    const first = addGroup(tree, to("0.1", 0), kind);
201    assert.deepEqual(first.tree, Stack(a, Switcher(empty, b), Shelf()));
202    assert.equal(
203      at(first.tree, "0.1").kind,
204      "Switcher",
205      "its parent is unchanged",
206    );
207
208    assert.deepEqual(addGroup(Stack(), to("0", 0), kind).tree, Stack(empty));
209    assert.deepEqual(restoreWorkingTree(stored(inside.tree)), inside.tree);
210  }
211  assert.deepEqual(tree, Stack(a, Switcher(b), Shelf()), "the original stays");
212});
213
214test("a new empty group is an authored group: it can be filled, arranged, removed or left empty", () => {
215  const added = addGroup(Stack(a), to("0", 1), "Switcher");
216  const edits = editsFor(added.tree, added.chosen);
217  assert.deepEqual(edits.arrange, { path: "0.1", group: Switcher() });
218  assert.deepEqual(edits.inside && [edits.inside.parent, edits.inside.index], [
219    "0.1",
220    0,
221  ]);
222  assert.equal(edits.remove, "0.1");
223  assert.equal(edits.text, undefined, "a group has no wording or role");
224
225  const filled = addText(added.tree, edits.inside!, "first");
226  assert.deepEqual(filled.tree, Stack(a, Switcher(text("first"))));
227  assert.deepEqual(filled.chosen, ["0.1.0"]);
228  // A group can hold a group before either holds any content.
229  const nestedGroup = addGroup(added.tree, edits.inside!, "Shelf");
230  assert.deepEqual(nestedGroup.tree, Stack(a, Switcher(Shelf())));
231  assert.deepEqual(
232    arrangeGroup(added.tree, "0.1", "Stack"),
233    Stack(a, Stack()),
234    "arranged while empty",
235  );
236  // Left alone, it is saved and reopened as it is.
237  assert.deepEqual(restoreWorkingTree(stored(added.tree)), added.tree);
238});
239
240test("a new member is refused where there is no such place or arrangement", () => {
241  const tree = Stack(a, Switcher(b));
242  const before = stored(tree);
243  for (const [place, why] of [
244    [to("0.0", 0), "content has no members"],
245    [to("0.9", 0), "no such group"],
246    [to("", 0), "no group at all"],
247    [to("0.1", 2), "past the end"],
248    [to("0", -1), "before the start"],
249    [to("0", 0.5), "between positions"],
250    [to("0", Number.NaN), "not a position"],
251  ] as const) {
252    assert.throws(() => addGroup(tree, place, "Stack"), why);
253    assert.throws(() => addText(tree, place), why);
254  }
255  assert.throws(() => addGroup(tree, to("0", 0), untyped<Primitive>("Grid")));
256  assert.throws(
257    () => addGroup(tree, to("0", 0), untyped<Primitive>("Text")),
258    "a role is not an arrangement",
259  );
260  assert.deepEqual(stored(tree), before, "a refused edit leaves no trace");
261});
262
263test("a new member is offered and accepted only within the size and nesting limits", () => {
264  const { nodes, ancestors } = workingCopyLimits;
265  const offered = (tree: Composition, chosen: readonly string[]) => {
266    const edits = editsFor(tree, chosen);
267    return [edits.inside, edits.after].filter((place) => place !== undefined);
268  };
269  /** Wherever a place is offered, content and an empty group both fit. */
270  const accepts = (tree: Composition, chosen: readonly string[]) => {
271    for (const place of offered(tree, chosen)) {
272      for (const edited of [
273        addText(tree, place),
274        addGroup(tree, place, "Switcher"),
275      ])
276        assert.deepEqual(restoreWorkingTree(stored(edited.tree)), edited.tree);
277    }
278    return offered(tree, chosen).length;
279  };
280
281  // One node of room left, then none.
282  const roomy = Stack(...Array.from({ length: nodes - 2 }, () => a));
283  assert.equal(accepts(roomy, ["0"]), 1);
284  assert.equal(accepts(roomy, ["0.0"]), 1);
285  const full = addGroup(roomy, to("0", 0), "Shelf").tree;
286  assert.equal(editsFor(full, ["0"]).full, true);
287  assert.deepEqual(offered(full, ["0"]), []);
288  assert.deepEqual(
289    offered(full, ["0.0"]),
290    [],
291    "not inside or after the new group",
292  );
293  assert.throws(() => addGroup(full, to("0", 0), "Stack"));
294  assert.throws(() => addText(full, to("0.0", 0)));
295
296  // The innermost group has one level left below it, then none.
297  const deep = nested(ancestors);
298  const innermost = `0${".0".repeat(ancestors - 1)}`;
299  assert.deepEqual(at(deep, innermost), Stack());
300  assert.equal(accepts(deep, [innermost]), 2, "inside it and after it");
301  const deepest = addGroup(deep, to(innermost, 0), "Switcher");
302  assert.deepEqual(at(deepest.tree, deepest.chosen[0]!), Switcher());
303  const edits = editsFor(deepest.tree, deepest.chosen);
304  assert.equal(
305    edits.inside,
306    undefined,
307    "nothing fits inside the deepest group",
308  );
309  assert.equal(edits.full, true);
310  assert.throws(() =>
311    addGroup(deepest.tree, to(deepest.chosen[0]!, 0), "Stack"),
312  );
313  assert.throws(() => addText(deepest.tree, to(deepest.chosen[0]!, 0)));
314  // Beside it adds no level.
315  assert.equal(accepts(deepest.tree, deepest.chosen), 1);
316});
317
318test("a blank start is an empty Stack with the whole composition selected", () => {
319  const tree = Stack(content("Heading", "Title"), Switcher(a, b));
320  const blank = blankComposition(tree);
321  assert.deepEqual(blank, { tree: Stack(), chosen: ["0"] });
322  assert.deepEqual(tree, Stack(content("Heading", "Title"), Switcher(a, b)));
323  // Another arrangement's empty root is still replaced by a Stack.
324  assert.deepEqual(blankComposition(Switcher()).tree, Stack());
325  // Already blank: the same composition, so there is nothing to commit.
326  const empty = Stack();
327  assert.equal(blankComposition(empty).tree, empty);
328  assert.deepEqual(blankComposition(empty).chosen, ["0"]);
329
330  const edits = editsFor(blank.tree, blank.chosen);
331  assert.deepEqual(
332    edits.inside && [edits.inside.parent, edits.inside.index],
333    ["0", 0],
334    "ready to be added to",
335  );
336  assert.deepEqual(edits.arrange, { path: "0", group: Stack() });
337  for (const edit of ["text", "after", "wrap", "release", "remove"] as const)
338    assert.equal(edits[edit], undefined, edit);
339  assert.equal(movesFor(blank.tree, blank.chosen), undefined);
340});
341
342test("starting over is one step for Undo, which restores the composition and its selection", () => {
343  const model = Stack(content("Heading", "Title"), Switcher(a, b), c);
344  const earlier = Stack(a);
345  const before: WorkingCopy = {
346    model,
347    chosen: ["0.1.1", "0.1.0"],
348    undo: [{ model: earlier, chosen: ["0.0"] }],
349  };
350  const blank = blankComposition(before.model);
351  const after = commitEdit(before, blank.tree, blank.chosen);
352  assert.deepEqual(after.model, Stack());
353  assert.deepEqual(after.chosen, ["0"]);
354  assert.equal(after.undo.length, 2);
355  assert.deepEqual(
356    restoreWorkingCopy(stored(after)),
357    after,
358    "saved and reopened",
359  );
360
361  const undone = undoEdit(after)!;
362  assert.equal(undone.model, model, "the composition that was replaced");
363  assert.deepEqual(undone.chosen, ["0.1.1", "0.1.0"], "and its selection");
364  assert.deepEqual(undone.undo, before.undo, "earlier history is intact");
365  // Reopened from storage, Undo still restores it.
366  const reopened = undoEdit(restoreWorkingCopy(stored(after))!)!;
367  assert.deepEqual(reopened.model, model);
368  assert.deepEqual(reopened.chosen, ["0.1.1", "0.1.0"]);
369
370  // The first blank start has nothing before it.
371  const first: WorkingCopy = { ...startWorkingCopy(Stack()), chosen: ["0"] };
372  assert.deepEqual(restoreWorkingCopy(stored(first)), first);
373  assert.equal(undoEdit(first), undefined);
374});
375
376test("an edit that changes nothing returns the same composition, so a caller commits nothing", () => {
377  const model = Stack(content("Meta", "aside"));
378  const copy: WorkingCopy = { ...startWorkingCopy(model), chosen: ["0.0"] };
379  /** How a caller applies an edit: only a changed composition is history. */
380  const apply = (from: WorkingCopy, edited: Edited) =>
381    edited.tree === from.model
382      ? from
383      : commitEdit(from, edited.tree, edited.chosen);
384
385  const sameRole = editContentKind(copy.model, "0.0", "Meta");
386  assert.equal(apply(copy, { tree: sameRole, chosen: ["0.0"] }), copy);
387  const blank = apply(copy, blankComposition(copy.model));
388  assert.equal(blank.undo.length, 1);
389  assert.equal(apply(blank, blankComposition(blank.model)), blank);
390  assert.equal(blank.undo.length, 1, "blank again is not a second step");
391});
392
393test("a composition can be built from nothing, and every step can be saved and undone", () => {
394  let copy: WorkingCopy = { ...startWorkingCopy(Stack()), chosen: ["0"] };
395  let steps = 0;
396  const step = (
397    edit: (tree: Composition, edits: ReturnType<typeof editsFor>) => Edited,
398  ) => {
399    const edited = edit(copy.model, editsFor(copy.model, copy.chosen));
400    assert.notEqual(edited.tree, copy.model);
401    copy = commitEdit(copy, edited.tree, edited.chosen);
402    steps++;
403    assert.deepEqual(
404      restoreWorkingCopy(stored(copy)),
405      copy,
406      printed(copy.model),
407    );
408  };
409  const reword = (wording: string) =>
410    step((tree) => ({
411      tree: editText(tree, copy.chosen[0]!, wording),
412      chosen: copy.chosen,
413    }));
414  const role = (kind: LeafKind) =>
415    step((tree) => ({
416      tree: editContentKind(tree, copy.chosen[0]!, kind),
417      chosen: copy.chosen,
418    }));
419
420  step((tree, edits) => addText(tree, edits.inside!));
421  reword("Order shipped");
422  role("Heading");
423  step((tree, edits) => addGroup(tree, edits.after!, "Switcher"));
424  step((tree, edits) => addText(tree, edits.inside!));
425  reword("Arrives Thursday");
426  step((tree, edits) => addText(tree, edits.after!));
427  reword("Updated 9:14 am");
428  role("Meta");
429  copy = { ...copy, chosen: ["0"] };
430  step((tree, edits) => addGroup(tree, edits.inside!, "Shelf"));
431
432  assert.deepEqual(
433    copy.model,
434    Stack(
435      content("Heading", "Order shipped"),
436      Switcher(text("Arrives Thursday"), content("Meta", "Updated 9:14 am")),
437      Shelf(),
438    ),
439  );
440  assert.deepEqual(copy.chosen, ["0.2"], "the group just added");
441  for (let undone = 0; undone < steps; undone++) copy = undoEdit(copy)!;
442  assert.deepEqual(copy.model, Stack());
443  assert.deepEqual(copy.chosen, ["0"]);
444  assert.equal(undoEdit(copy), undefined);
445});