tests/movement.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4  Stack,
5  Shelf,
6  Switcher,
7  type Composition,
8} from "../documentation/components/source/composition.ts";
9import {
10  atPath,
11  parentPath,
12} from "../documentation/components/source/grouping.ts";
13import {
14  moveMembers,
15  moveObstacle,
16  movesFor,
17  placeAfter,
18  placeAtEnd,
19  placeAtStart,
20  placeBefore,
21} from "../documentation/components/source/movement.ts";
22import {
23  commitEdit,
24  removeMember,
25  restoreWorkingCopy,
26  restoreWorkingTree,
27  startWorkingCopy,
28  undoEdit,
29  workingCopyLimits,
30  type Insertion,
31  type WorkingCopy,
32} from "../documentation/components/source/working-copy.ts";
33
34const stored = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
35const text = (value: string): Composition => ({ kind: "Text", text: value });
36const heading: Composition = { kind: "Heading", text: "Title" };
37const meta: Composition = { kind: "Meta", text: "aside" };
38const [a, b, c, d] = ["a", "b", "c", "d"].map(text) as [
39  Composition,
40  Composition,
41  Composition,
42  Composition,
43];
44function at(tree: Composition, path: string): Composition {
45  const node = atPath(tree, path);
46  if (!node) throw new Error(`Nothing at ${path}`);
47  return node;
48}
49const to = (parent: string, index: number): Insertion => ({ parent, index });
50/** Every path below the root, in reading order. */
51function memberPaths(tree: Composition, path = "0"): string[] {
52  return "children" in tree
53    ? tree.children.flatMap((child, index) => [
54        `${path}.${index}`,
55        ...memberPaths(child, `${path}.${index}`),
56      ])
57    : [];
58}
59/** Every place among the members of every group. */
60function everyPlace(tree: Composition, path = "0"): Insertion[] {
61  return "children" in tree
62    ? [
63        ...Array.from({ length: tree.children.length + 1 }, (_, index) =>
64          to(path, index),
65        ),
66        ...tree.children.flatMap((child, index) =>
67          everyPlace(child, `${path}.${index}`),
68        ),
69      ]
70    : [];
71}
72/** The composition with a run of neighbors taken out. */
73function without(tree: Composition, run: readonly string[]): Composition {
74  const position = (path: string) => Number(path.split(".").at(-1));
75  // Last first, so each removal leaves the earlier paths as they were.
76  return [...run]
77    .sort((x, y) => position(y) - position(x))
78    .reduce((rest, path) => removeMember(rest, path).tree, tree);
79}
80/** A Stack whose innermost Stack, holding `inner`, has `ancestors` groups above it. */
81const chain = (ancestors: number, ...inner: Composition[]): Composition =>
82  ancestors === 0 ? Stack(...inner) : Stack(chain(ancestors - 1, ...inner));
83
84test("a member moves to another group, whichever of the two comes first", () => {
85  const tree = Stack(Switcher(a, b), Shelf(c));
86  const later = moveMembers(tree, ["0.0.0"], to("0.1", 1));
87  assert.deepEqual(later.tree, Stack(Switcher(b), Shelf(c, a)));
88  assert.deepEqual(later.chosen, ["0.1.1"]);
89  assert.equal(later.from, "0.0");
90
91  const earlier = moveMembers(tree, ["0.1.0"], to("0.0", 1));
92  assert.deepEqual(earlier.tree, Stack(Switcher(a, c, b), Shelf()));
93  assert.deepEqual(earlier.chosen, ["0.0.1"]);
94  assert.equal(earlier.from, "0.1");
95  assert.deepEqual(tree, Stack(Switcher(a, b), Shelf(c)), "the original stays");
96});
97
98test("a place stated before the move is found again after the members leave", () => {
99  // The receiving group stands after the member in the same parent, so its
100  // own path closes up by one.
101  const sibling = Stack(a, Stack(b), Shelf(c));
102  const first = moveMembers(sibling, ["0.0"], to("0.2", 0));
103  assert.deepEqual(first.tree, Stack(Stack(b), Shelf(a, c)));
104  assert.deepEqual(first.chosen, ["0.1.0"]);
105
106  // The same, with the receiving group nested inside that later sibling.
107  const nested = Stack(a, b, Switcher(Stack(c), Shelf(d)));
108  const second = moveMembers(nested, ["0.0", "0.1"], to("0.2.1", 1));
109  assert.deepEqual(second.tree, Stack(Switcher(Stack(c), Shelf(d, a, b))));
110  assert.deepEqual(second.chosen, ["0.0.1.1", "0.0.1.2"]);
111
112  // A group before the member, or in another branch, keeps its path.
113  const before = Stack(Stack(b), a, Stack(Shelf(c)));
114  assert.deepEqual(moveMembers(before, ["0.1"], to("0.0", 0)).chosen, [
115    "0.0.0",
116  ]);
117  const branches = Stack(Stack(a, b), Stack(Shelf(c)));
118  const third = moveMembers(branches, ["0.0.0"], to("0.1.0", 0));
119  assert.deepEqual(third.tree, Stack(Stack(b), Stack(Shelf(a, c))));
120  assert.deepEqual(third.chosen, ["0.1.0.0"]);
121});
122
123test("a member moves out to an enclosing group, before or after the group it left", () => {
124  const tree = Stack(a, Switcher(b, c));
125  const after = moveMembers(tree, ["0.1.1"], to("0", 2));
126  assert.deepEqual(after.tree, Stack(a, Switcher(b), c));
127  assert.deepEqual(after.chosen, ["0.2"]);
128  assert.equal(after.from, "0.1");
129
130  // Arriving ahead of the group it left moves that group along.
131  const ahead = moveMembers(tree, ["0.1.1"], to("0", 0));
132  assert.deepEqual(ahead.tree, Stack(c, a, Switcher(b)));
133  assert.deepEqual(ahead.chosen, ["0.0"]);
134  assert.equal(ahead.from, "0.2");
135  assert.deepEqual(at(ahead.tree, ahead.from), Switcher(b), "one member left");
136
137  const emptied = moveMembers(Stack(Stack(Shelf(a))), ["0.0.0.0"], to("0", 0));
138  assert.deepEqual(emptied.tree, Stack(a, Stack(Shelf())));
139  assert.equal(emptied.from, "0.1.0");
140  assert.deepEqual(
141    at(emptied.tree, emptied.from),
142    Shelf(),
143    "the emptied group keeps its arrangement and its place",
144  );
145});
146
147test("a member moves into a more deeply nested group, even an empty one", () => {
148  const tree = Stack(a, Stack(Shelf(b), Switcher()));
149  const deeper = moveMembers(tree, ["0.0"], to("0.1.0", 1));
150  assert.deepEqual(deeper.tree, Stack(Stack(Shelf(b, a), Switcher())));
151  assert.deepEqual(deeper.chosen, ["0.0.0.1"]);
152  const empty = moveMembers(tree, ["0.0"], to("0.1.1", 0));
153  assert.deepEqual(empty.tree, Stack(Stack(Shelf(b), Switcher(a))));
154  assert.deepEqual(empty.chosen, ["0.0.1.0"]);
155});
156
157test("what moves is intact, and what it does not pass through is untouched", () => {
158  const inner = Shelf(meta, a);
159  const moving = Switcher(heading, inner);
160  const bystander = Stack(b, Shelf(c));
161  const tree = Stack(Stack(moving, d), Stack(), bystander);
162  const moved = moveMembers(tree, ["0.0.0"], to("0.1", 0));
163  assert.deepEqual(
164    moved.tree,
165    Stack(Stack(d), Stack(Switcher(heading, Shelf(meta, a))), bystander),
166  );
167  // The same objects, not copies: arrangement, members, kinds and wording.
168  assert.equal(at(moved.tree, moved.chosen[0]!), moving);
169  assert.equal(at(moved.tree, "0.1.0.1"), inner);
170  assert.equal(at(moved.tree, "0.1.0.0"), heading);
171  assert.equal(at(moved.tree, "0.2"), bystander);
172  assert.equal(at(moved.tree, "0.0.0"), d);
173  // The groups it left and joined keep their own arrangements.
174  const kinds = Stack(Switcher(a, b), Shelf(c));
175  const joined = moveMembers(kinds, ["0.0.1"], to("0.1", 0)).tree;
176  assert.equal(at(joined, "0.0").kind, "Switcher");
177  assert.equal(at(joined, "0.1").kind, "Shelf");
178});
179
180test("a member changes its place among the same neighbors, in either direction", () => {
181  const tree = Switcher(a, b, c, d);
182  const last = moveMembers(tree, ["0.1"], to("0", 4));
183  assert.deepEqual(last.tree, Switcher(a, c, d, b));
184  assert.deepEqual(last.chosen, ["0.3"]);
185  assert.equal(last.from, "0");
186
187  const first = moveMembers(tree, ["0.2"], to("0", 0));
188  assert.deepEqual(first.tree, Switcher(c, a, b, d));
189  assert.deepEqual(first.chosen, ["0.0"]);
190
191  // The place between c and d, stated before b leaves.
192  const between = moveMembers(tree, ["0.1"], to("0", 3));
193  assert.deepEqual(between.tree, Switcher(a, c, b, d));
194  assert.deepEqual(between.chosen, ["0.2"]);
195});
196
197test("a run of neighbors moves as one, in reading order", () => {
198  const tree = Stack(a, b, c, Shelf(d));
199  // Chosen out of order, as a selection can be.
200  const within = moveMembers(tree, ["0.2", "0.1"], to("0", 0));
201  assert.deepEqual(within.tree, Stack(b, c, a, Shelf(d)));
202  assert.deepEqual(within.chosen, ["0.0", "0.1"]);
203
204  const across = moveMembers(tree, ["0.1", "0.0"], to("0.3", 0));
205  assert.deepEqual(across.tree, Stack(c, Shelf(a, b, d)));
206  assert.deepEqual(across.chosen, ["0.1.0", "0.1.1"]);
207
208  const all = moveMembers(Stack(Switcher(a, b), Stack()), ["0.0.0", "0.0.1"], {
209    parent: "0.1",
210    index: 0,
211  });
212  assert.deepEqual(all.tree, Stack(Switcher(), Stack(a, b)));
213  assert.equal(all.from, "0.0");
214});
215
216test("moving members to where they already are changes nothing", () => {
217  const tree = Stack(a, b, c, d);
218  // Before the run, between its members, and after it.
219  for (const index of [1, 2, 3]) {
220    assert.equal(
221      moveObstacle(tree, ["0.1", "0.2"], to("0", index)),
222      "already-there",
223    );
224    const moved = moveMembers(tree, ["0.2", "0.1"], to("0", index));
225    assert.equal(moved.tree, tree, "the same composition, not a copy");
226    assert.deepEqual(moved.chosen, ["0.1", "0.2"]);
227    assert.equal(moved.from, "0");
228  }
229  for (const index of [0, 4])
230    assert.equal(moveObstacle(tree, ["0.1", "0.2"], to("0", index)), undefined);
231  const only = Stack(Switcher(a));
232  assert.equal(moveMembers(only, ["0.0.0"], to("0.0", 1)).tree, only);
233});
234
235test("a move that cannot happen is refused with its reason", () => {
236  const tree = Stack(a, Switcher(b, Stack(c)), d);
237  const before = stored(tree);
238  for (const [members, place, reason] of [
239    [["0"], to("0", 0), "root"],
240    [["0", "0.0"], to("0.1", 0), "root"],
241    [[], to("0", 0), "not-members"],
242    [["0.0", "0.2"], to("0.1", 0), "not-members"],
243    [["0.0", "0.0"], to("0.1", 0), "not-members"],
244    [["0.0", "0.1.0"], to("0", 3), "not-members"],
245    [["0.7"], to("0", 0), "not-members"],
246    [["0.1"], to("0.1", 0), "inside-itself"],
247    [["0.1"], to("0.1.1", 1), "inside-itself"],
248    [["0.0", "0.1"], to("0.1.1", 0), "inside-itself"],
249    [["0.0"], to("0.2", 0), "not-a-place"],
250    [["0.0"], to("0.9", 0), "not-a-place"],
251    [["0.0"], to("", 0), "not-a-place"],
252    [["0.0"], to("0.1", 3), "not-a-place"],
253    [["0.0"], to("0.1", -1), "not-a-place"],
254    [["0.0"], to("0.1", 0.5), "not-a-place"],
255    [["0.0"], to("0.1", Number.NaN), "not-a-place"],
256  ] as const) {
257    assert.equal(moveObstacle(tree, members, place), reason);
258    assert.throws(() => moveMembers(tree, members, place));
259  }
260  assert.deepEqual(stored(tree), before, "a refused move leaves no trace");
261});
262
263test("members move only where nothing would be nested past the limit", () => {
264  const deepest = workingCopyLimits.ancestors;
265  // The innermost Stack has one group fewer above it than text may have.
266  const tree = Stack(chain(deepest - 2), a, Stack(b));
267  const innermost = `0.0${".0".repeat(deepest - 2)}`;
268  assert.deepEqual(at(tree, innermost), Stack());
269  const above = innermost.slice(0, -2);
270
271  const moved = moveMembers(tree, ["0.1"], to(innermost, 0));
272  assert.equal(at(moved.tree, moved.chosen[0]!), a);
273  assert.deepEqual(restoreWorkingTree(stored(moved.tree)), moved.tree);
274
275  // A group brings its own levels with it.
276  assert.equal(moveObstacle(tree, ["0.2"], to(innermost, 0)), "too-deep");
277  assert.throws(() => moveMembers(tree, ["0.2"], to(innermost, 0)));
278  assert.equal(
279    moveObstacle(tree, ["0.1", "0.2"], to(innermost, 0)),
280    "too-deep",
281  );
282  const higher = moveMembers(tree, ["0.2"], to(above, 0));
283  assert.deepEqual(restoreWorkingTree(stored(higher.tree)), higher.tree);
284
285  assert.equal(movesFor(tree, ["0.2"])!.limited, true);
286  assert.ok(
287    movesFor(tree, ["0.2"])!.places.every(
288      (place) => place.parent !== innermost,
289    ),
290  );
291  assert.equal(movesFor(tree, ["0.1"])!.limited, false);
292
293  // At the limit, reading order can still change.
294  const full = Stack(chain(deepest - 2, a, b));
295  const reordered = moveMembers(full, [`${innermost}.0`], to(innermost, 2));
296  assert.deepEqual(at(reordered.tree, innermost), Stack(b, a));
297});
298
299test("a selection's places are listed in reading order, split around where it is", () => {
300  const tree = Stack(a, Switcher(b, c), Shelf(), d);
301  const listed = (chosen: readonly string[]) => {
302    const moves = movesFor(tree, chosen)!;
303    return {
304      members: moves.members,
305      places: moves.places.map((place) => [place.parent, place.index]),
306      earlier: moves.earlier,
307    };
308  };
309  assert.deepEqual(listed(["0.0"]), {
310    members: ["0.0"],
311    places: [
312      ["0.1", 0],
313      ["0.1", 1],
314      ["0.1", 2],
315      ["0", 2],
316      ["0.2", 0],
317      ["0", 3],
318      ["0", 4],
319    ],
320    earlier: 0,
321  });
322  assert.deepEqual(
323    listed(["0.1"]),
324    {
325      members: ["0.1"],
326      places: [
327        ["0", 0],
328        ["0.2", 0],
329        ["0", 3],
330        ["0", 4],
331      ],
332      earlier: 1,
333    },
334    "a group has no place inside itself",
335  );
336  assert.deepEqual(listed(["0.1.1"]), {
337    members: ["0.1.1"],
338    places: [
339      ["0", 0],
340      ["0", 1],
341      ["0.1", 0],
342      ["0", 2],
343      ["0.2", 0],
344      ["0", 3],
345      ["0", 4],
346    ],
347    earlier: 3,
348  });
349  assert.deepEqual(listed(["0.3", "0.2"]), {
350    members: ["0.2", "0.3"],
351    places: [
352      ["0", 0],
353      ["0", 1],
354      ["0.1", 0],
355      ["0.1", 1],
356      ["0.1", 2],
357    ],
358    earlier: 5,
359  });
360  // Each place names the group that would receive the members.
361  const places = movesFor(tree, ["0.0"])!.places;
362  assert.equal(places[0]!.group, at(tree, "0.1"));
363  assert.equal(places[4]!.group, at(tree, "0.2"));
364
365  assert.equal(movesFor(tree, []), undefined, "nothing selected");
366  assert.equal(movesFor(tree, ["0"]), undefined, "the root has nowhere to go");
367  assert.equal(movesFor(tree, ["0.0", "0.2"]), undefined, "not a selection");
368  assert.deepEqual(
369    movesFor(Stack(a), ["0.0"]),
370    { members: ["0.0"], places: [], earlier: 0, limited: false },
371    "a lone member can be selected and has no other place",
372  );
373});
374
375test("every listed place is a move that leaves everything else as it was", () => {
376  const tree = Stack(
377    heading,
378    Switcher(a, Shelf(b, meta), c),
379    Stack(),
380    Shelf(Stack(d)),
381  );
382  const selections = [
383    ...memberPaths(tree).map((path) => [path]),
384    ["0.0", "0.1"],
385    ["0.1.0", "0.1.1", "0.1.2"],
386    ["0.2", "0.3"],
387  ];
388  let moves = 0;
389  for (const chosen of selections) {
390    const { members, places } = movesFor(tree, chosen)!;
391    const moving = members.map((path) => at(tree, path));
392    // The list and the single judgment agree about every place there is.
393    for (const place of everyPlace(tree))
394      assert.equal(
395        moveObstacle(tree, members, place) === undefined,
396        places.some(
397          (listed) =>
398            listed.parent === place.parent && listed.index === place.index,
399        ),
400        `${members} to ${place.parent}:${place.index}`,
401      );
402    for (const place of places) {
403      moves++;
404      const moved = moveMembers(tree, members, place);
405      const label = `${members} to ${place.parent}:${place.index}`;
406      assert.notEqual(moved.tree, tree, label);
407      assert.deepEqual(
408        moved.chosen.map((path) => at(moved.tree, path)),
409        moving,
410        label,
411      );
412      moved.chosen.forEach((path, index) =>
413        assert.equal(at(moved.tree, path), moving[index], label),
414      );
415      // Take the members out of both: nothing else differs.
416      assert.deepEqual(
417        without(moved.tree, moved.chosen),
418        without(tree, members),
419        label,
420      );
421      assert.equal(
422        at(moved.tree, parentPath(moved.chosen[0]!)).kind,
423        place.group.kind,
424        label,
425      );
426      assert.deepEqual(
427        restoreWorkingTree(stored(moved.tree)),
428        moved.tree,
429        label,
430      );
431      // The moved selection is one the author could have made there.
432      assert.deepEqual(
433        movesFor(moved.tree, moved.chosen)!.members,
434        moved.chosen,
435      );
436    }
437  }
438  assert.ok(moves > 80, `${moves} moves checked`);
439});
440
441test("stepping to the nearest place carries a member through the composition and back", () => {
442  const start = Stack(a, Switcher(b, Stack(c)), Shelf(), d);
443  let tree = start;
444  let chosen: readonly string[] = ["0.0"];
445  const step = (direction: "later" | "earlier") => {
446    const moves = movesFor(tree, chosen)!;
447    const place =
448      moves.places[direction === "later" ? moves.earlier : moves.earlier - 1];
449    if (!place) return false;
450    ({ tree, chosen } = moveMembers(tree, moves.members, place));
451    assert.equal(at(tree, chosen[0]!), a);
452    return true;
453  };
454  // Every step reaches a new place, so there are as many steps as places.
455  const places = movesFor(start, ["0.0"])!.places.length;
456  let forward = 0;
457  while (forward <= places && step("later")) forward++;
458  assert.equal(forward, places);
459  assert.deepEqual(tree, Stack(Switcher(b, Stack(c)), Shelf(), d, a));
460  let back = 0;
461  while (back <= places && step("earlier")) back++;
462  assert.equal(back, places);
463  assert.deepEqual(tree, start);
464});
465
466test("a place can be named by a neighbor or by a group's start and end", () => {
467  const tree = Stack(a, Switcher(b, c), Shelf());
468  assert.deepEqual(placeBefore("0.1.1"), to("0.1", 1));
469  assert.deepEqual(placeAfter("0.1.1"), to("0.1", 2));
470  assert.deepEqual(placeAtStart("0.1"), to("0.1", 0));
471  assert.deepEqual(placeAtEnd(tree, "0.1"), to("0.1", 2));
472  assert.deepEqual(placeAtEnd(tree, "0.2"), to("0.2", 0));
473  assert.deepEqual(
474    moveMembers(tree, ["0.0"], placeAfter("0.1.0")).tree,
475    Stack(Switcher(b, a, c), Shelf()),
476  );
477  assert.deepEqual(
478    moveMembers(tree, ["0.1.0"], placeAtEnd(tree, "0.2")).tree,
479    Stack(a, Switcher(c), Shelf(b)),
480  );
481  // Beside the member itself is where it already is.
482  assert.equal(
483    moveObstacle(tree, ["0.0"], placeBefore("0.0")),
484    "already-there",
485  );
486  assert.equal(moveObstacle(tree, ["0.0"], placeAfter("0.0")), "already-there");
487  // The root has no neighbors, and text has no members.
488  assert.equal(moveObstacle(tree, ["0.0"], placeAfter("0")), "not-a-place");
489  assert.equal(
490    moveObstacle(tree, ["0.1"], placeAtEnd(tree, "0.0")),
491    "not-a-place",
492  );
493});
494
495test("a move is one step for Undo, and its selection survives saving", () => {
496  const model = Stack(heading, Switcher(a, b), Shelf(c));
497  const before: WorkingCopy = {
498    ...startWorkingCopy(model),
499    chosen: ["0.1.1", "0.1.0"],
500  };
501  const moves = movesFor(before.model, before.chosen)!;
502  const moved = moveMembers(before.model, moves.members, to("0.2", 1));
503  const after = commitEdit(before, moved.tree, moved.chosen);
504  assert.deepEqual(after.model, Stack(heading, Switcher(), Shelf(c, a, b)));
505  assert.deepEqual(after.chosen, ["0.2.1", "0.2.2"]);
506  assert.equal(after.undo.length, 1);
507  assert.deepEqual(restoreWorkingCopy(stored(after)), after, "reopened");
508
509  const undone = undoEdit(after)!;
510  assert.equal(undone.model, model, "the composition from before the move");
511  assert.deepEqual(undone.chosen, ["0.1.1", "0.1.0"], "and its selection");
512  assert.equal(undone.undo.length, 0);
513
514  // Nothing changed, so there is nothing for a caller to commit.
515  const unchanged = moveMembers(before.model, moves.members, to("0.1", 2));
516  assert.equal(unchanged.tree, before.model);
517});