1import { test } from"node:test";2importassertfrom"node:assert/strict";3import {4example,5Stack,6Shelf,7Switcher,8typeComposition,9} from"../documentation/components/source/composition.ts";10import {11chooseMember,12restoreComposition,13restoreSelection,14selectionOf,15} from"../documentation/components/source/composition-editing.ts";16import {17arrangeGroup,18restoreArrangement,19} from"../documentation/components/source/arrangement.ts";20import {21atPath,22groupMembers,23ungroupMembers,24restoreGrouping,25} from"../documentation/components/source/grouping.ts";2627conststored= (value:unknown):unknown=>JSON.parse(JSON.stringify(value));28consttext= (value:string):Composition=> ({ kind: "Text", text: value });29functionmembers(tree:Composition|undefined):readonlyComposition[] {30if (!tree||!("children"intree)) thrownewError("Expected a group");31returntree.children;32}33/** A saved group as storage holds it: no promise that it is a composition. */34constgroup= (kind:string, ...children:unknown[]) => ({ kind, children });35functionrun(tree:Composition, chosen:readonlystring[]) {36constselection=selectionOf(tree, chosen);37if (selection.selected!=="members") thrownewError("Expected members");38returnselection;39}40functioncontent(tree:Composition):Composition[] {41return"children"intree?tree.children.flatMap(content) : [tree];42}43functionpaths(tree:Composition, path="0"):string[] {44return"children"intree45? [46path,47...tree.children.flatMap((child, index) =>48paths(child, `${path}.${index}`),49 ),50 ]51: [path];52}5354// The investigation's facts: one flat group of six.55constinitial=example("investigation");56const [finding, completed, updated, plan, approval, destination] =members(57initial,58) as [59Composition,60Composition,61Composition,62Composition,63Composition,64Composition,65];66assert.equal(members(initial).length, 6);6768/** Switcher(Stack(finding, Switcher(completed, updated)), Shelf(plan, approval), destination),69 * reached with the editor's own edits. */70functionauthored():Composition {71lettree=groupMembers(initial, ["0.1", "0.2"]);72tree=arrangeGroup(tree, "0.1", "Switcher");73tree=groupMembers(tree, ["0.0", "0.1"]);74tree=groupMembers(tree, ["0.1", "0.2"]);75tree=arrangeGroup(tree, "0.1", "Shelf");76returnarrangeGroup(tree, "0", "Switcher");77}7879test("a saved regrouping with its arrangements restores onto the supplied content", () => {80consttree=authored();81assert.deepEqual(82tree,83Switcher(84Stack(finding, Switcher(completed, updated)),85Shelf(plan, approval),86destination,87 ),88 );89constrestored=restoreComposition(stored(tree), initial);90assert.deepEqual(restored, tree);91// The content is the starting composition's own, in its order.92content(restored!).forEach((leaf, index) =>93assert.equal(leaf, content(initial)[index]),94 );95assert.deepEqual(restoreComposition(stored(initial), initial), initial);9697// Only structure is read. Anything else a saved node carries is dropped,98// including members attached to a piece of content.99constdecorated=stored(tree) as { children:Record<string, unknown>[] };100Object.assign(decorated, { style: "position: fixed", path: "0.9" });101Object.assign(decorated.children[2]!, {102children: [stored(finding), stored(finding)],103href: "https://example.com",104 });105assert.deepEqual(restoreComposition(decorated, initial), tree);106});107108test("saved state cannot change, reorder, drop, repeat or add content", () => {109constfirst=Stack(finding, Switcher(completed, updated));110constsecond=Shelf(plan, approval);111consttampered: [string, unknown][] = [112 [113"changed text",114Stack(115finding,116text("Investigation failed"),117updated,118plan,119approval,120destination,121 ),122 ],123 [124"changed kind",125Stack(126text((findingas { text:string }).text),127completed,128updated,129plan,130approval,131destination,132 ),133 ],134 [135"swapped neighbors",136Stack(finding, updated, completed, plan, approval, destination),137 ],138 [139"swapped inside a group",140Stack(finding, Switcher(updated, completed), second, destination),141 ],142 ["swapped groups", Stack(second, first, destination)],143 [144"moved across a boundary",145Stack(146Stack(finding, completed),147Stack(plan, updated),148approval,149destination,150 ),151 ],152 ["dropped content", Stack(first, second)],153 [154"dropped the first",155Stack(completed, updated, plan, approval, destination),156 ],157 ["repeated content", Stack(first, second, destination, destination)],158 [159"repeated in place",160Stack(finding, completed, completed, plan, approval, destination),161 ],162 [163"added content",164Stack(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",170group("Stack", first, second, { kind: "Text", text: 7 }),171 ],172 [173"text held in a list",174group("Stack", first, second, {175kind: "Text",176text: ["Destination: investigation session"],177 }),178 ],179 ];180for (const [label, value] oftampered)181assert.equal(restoreComposition(stored(value), initial), undefined, label);182});183184test("saved state needs a group at its root and two members in every group", () => {185constsix= [finding, completed, updated, plan, approval, destination];186constinvalid: [string, unknown][] = [187 ["content at the root", finding],188 ["a root around one group", Stack(initial)],189 [190"a group of one",191Stack(Stack(finding), completed, updated, plan, approval, destination),192 ],193 [194"a nested group of one",195Stack(196finding,197Stack(Stack(completed, updated)),198plan,199approval,200destination,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",208group(209"Stack",210finding,211group("Row", completed, updated),212plan,213approval,214destination,215 ),216 ],217 [218"a content kind holding members",219group(220"Stack",221group("Text", finding, completed),222updated,223plan,224approval,225destination,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 ];239for (const [label, value] ofinvalid)240assert.equal(restoreComposition(stored(value), initial), undefined, label);241assert.equal(restoreComposition(undefined, initial), undefined);242// A single piece of content has no regrouping to restore.243assert.equal(restoreComposition(stored(finding), finding), undefined);244assert.equal(restoreComposition(stored(Stack(finding)), finding), undefined);245});246247test("saved state is bounded in depth and size", () => {248constfacts= (count:number) =>249Array.from({ length: count }, (_, index) =>text(`Fact ${index+1}`));250/** `groups` groups, each inside the one before; the last holds the rest. */251functionchain(leaves:Composition[], groups:number):Composition {252constinnermost=leaves.length-groups+1;253lettree=Stack(...leaves.slice(-innermost));254for (letindex=leaves.length-innermost-1; index>=0; index--)255tree=Stack(leaves[index]!, tree);256returntree;257 }258constfourteen=facts(14);259constdeepest=chain(fourteen, 12);260assert.deepEqual(261restoreComposition(stored(deepest), Stack(...fourteen)),262deepest,263"content twelve levels below the root",264 );265assert.equal(266restoreComposition(stored(chain(fourteen, 13)), Stack(...fourteen)),267undefined,268"content thirteen levels below the root",269 );270271constwidest=Stack(...facts(99));272assert.deepEqual(273restoreComposition(stored(widest), widest),274widest,275"one hundred nodes",276 );277constwider=Stack(...facts(100));278assert.equal(279restoreComposition(stored(wider), wider),280undefined,281"one hundred and one nodes",282 );283284// Reading stops at the bound, however much more the value holds.285constendless=stored(finding);286constchildren:unknown[] =Array.from({ length: 5000 }, () =>endless);287Object.defineProperty(children, 150, {288get() {289thrownewError("Read past the node bound");290 },291 });292assert.equal(293restoreComposition({ kind: "Stack", children }, initial),294undefined,295 );296letnested:unknown=stored(Stack(finding, completed));297for (letdepth=0; depth<5000; depth++)298nested= { kind: "Stack", children: [nested, endless] };299assert.equal(restoreComposition(nested, initial), undefined);300});301302test("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.304constflat=example("flat");305constregrouped=groupMembers(flat, ["0.1", "0.2"]);306assert.deepEqual(restoreGrouping(stored(regrouped), flat), regrouped);307assert.deepEqual(restoreComposition(stored(regrouped), flat), regrouped);308constgrouped=example("grouped");309constrearranged=arrangeGroup(grouped, "0.0", "Switcher");310assert.deepEqual(restoreArrangement(stored(rearranged), grouped), rearranged);311assert.deepEqual(restoreComposition(stored(rearranged), grouped), rearranged);312313// A state with both edits belongs to the combined exercise alone.314constboth=stored(authored());315assert.ok(restoreComposition(both, initial));316assert.equal(restoreGrouping(both, initial), undefined);317assert.equal(restoreArrangement(both, initial), undefined);318constarrangedFlat=stored(arrangeGroup(initial, "0", "Shelf"));319assert.equal(restoreGrouping(arrangedFlat, initial), undefined);320constregroupedOnly=stored(groupMembers(initial, ["0.3", "0.4"]));321assert.equal(restoreArrangement(regroupedOnly, initial), undefined);322});323324test("the root can be selected and arranged, alone, and never ungrouped", () => {325assert.deepEqual(selectionOf(initial, ["0"]), {326selected: "group",327path: "0",328group: initial,329canUngroup: false,330 });331assert.throws(() =>ungroupMembers(initial, "0"),/inner group/);332constshelf=arrangeGroup(initial, "0", "Shelf");333assert.equal(members(shelf), members(initial));334assert.deepEqual(restoreComposition(stored(shelf), initial), shelf);335336// The root has no neighbors: it replaces a selection and is replaced by one.337assert.deepEqual(chooseMember(initial, [], "0"), ["0"]);338assert.deepEqual(chooseMember(initial, ["0.2", "0.3"], "0"), ["0"]);339assert.deepEqual(chooseMember(initial, ["0"], "0.2"), ["0.2"]);340assert.deepEqual(chooseMember(initial, ["0"], "0"), []);341assert.deepEqual(selectionOf(initial, ["0", "0.0"]), { selected: "nothing" });342});343344test("all the members of a group can be selected, but only their group can be arranged", () => {345letchosen:readonlystring[] = [];346for (constpathof ["0.2", "0.3", "0.1", "0.4", "0.0", "0.5"])347chosen=chooseMember(initial, chosen, path);348assert.deepEqual(selectionOf(initial, chosen), {349selected: "members",350paths: ["0.0", "0.1", "0.2", "0.3", "0.4", "0.5"],351parent: "0",352canGroup: false,353 });354assert.throws(() =>groupMembers(initial, chosen),/all the members/);355// Leaving one neighbor outside makes a group a reader can see.356constfewer=chooseMember(initial, chosen, "0.5");357assert.ok(run(initial, fewer).canGroup);358359// The same holds for a pair inside a nested group.360consttree=authored();361assert.deepEqual(selectionOf(tree, ["0.1.1", "0.1.0"]), {362selected: "members",363paths: ["0.1.0", "0.1.1"],364parent: "0.1",365canGroup: false,366 });367constparent=selectionOf(tree, ["0.1"]);368assert.equal(parent.selected, "group");369assert.equal(parent.selected==="group"&&parent.group.kind, "Shelf");370});371372test("groups and content select, group and ungroup together as neighbors", () => {373// Stack(finding, Switcher(completed, updated), plan, approval, destination)374consttree=arrangeGroup(375groupMembers(initial, ["0.1", "0.2"]),376"0.1",377"Switcher",378 );379constinner=atPath(tree, "0.1");380381letchosen=chooseMember(tree, [], "0.1");382assert.equal(selectionOf(tree, chosen).selected, "group");383chosen=chooseMember(tree, chosen, "0.2");384assert.deepEqual(selectionOf(tree, chosen), {385selected: "members",386paths: ["0.1", "0.2"],387parent: "0",388canGroup: true,389 });390constthree=chooseMember(tree, chosen, "0.0");391assert.deepEqual(three, ["0.1", "0.2", "0.0"], "in the order chosen");392assert.deepEqual(393run(tree, three).paths,394 ["0.0", "0.1", "0.2"],395"read in reading order",396 );397398// Anything that is not a neighbor starts a new selection, at any level.399assert.deepEqual(chooseMember(tree, chosen, "0.4"), ["0.4"]);400assert.deepEqual(chooseMember(tree, chosen, "0.1.0"), ["0.1.0"]);401assert.deepEqual(chooseMember(tree, ["0.1.0"], "0.1"), ["0.1"]);402assert.deepEqual(selectionOf(tree, ["0.1.0"]), {403selected: "content",404path: "0.1.0",405 });406// Choosing a selected member leaves it out.407assert.deepEqual(chooseMember(tree, three, "0.0"), ["0.1", "0.2"]);408assert.deepEqual(chooseMember(tree, chosen, "0.1"), ["0.2"]);409assert.deepEqual(410chooseMember(tree, three, "0.1"),411 ["0.2"],412"from the middle",413 );414assert.equal(chooseMember(tree, chosen, "0.9"), chosen, "no such member");415416// The order of choosing does not matter to the group. The inner group417// keeps its arrangement and its members; the new group is a Stack.418constgrouped=groupMembers(tree, ["0.2", "0.1"]);419assert.equal(atPath(grouped, "0.1")?.kind, "Stack");420assert.equal(atPath(grouped, "0.1.0"), inner);421assert.equal(atPath(grouped, "0.1.1"), plan);422content(grouped).forEach((leaf, index) =>423assert.equal(leaf, content(initial)[index]),424 );425constreleased=ungroupMembers(grouped, "0.1");426assert.deepEqual(released, tree);427assert.equal(atPath(released, "0.1"), inner);428});429430test("any sequence of edits keeps the content, its order, and a restorable state", () => {431letseed=20261120;432constrandom= (below:number) => {433seed= (seed*1664525+1013904223) >>>0;434returnMath.floor((seed/2**32) *below);435 };436constsupplied=content(initial);437constmade= { Group: 0, Ungroup: 0, Arrange: 0 };438letdeepest=0;439lettree=initial;440letchosen:readonlystring[] = [];441for (letstep=0; step<4000; step++) {442constall=paths(tree);443chosen=chooseMember(tree, chosen, all[random(all.length)]!);444constselection=selectionOf(tree, chosen);445assert.ok(446chosen.length===0||selection.selected!=="nothing",447"choosing always leaves a selection the editor can read",448 );449if (selection.selected==="members"&&selection.canGroup&&random(4)) {450tree=groupMembers(tree, chosen);451made.Group++;452// The new group stands where its first member stood, and can be undone453// by hand.454chosen= [selection.paths[0]!];455constgroup=selectionOf(tree, chosen);456assert.ok(group.selected==="group"&&group.canUngroup);457assert.equal(group.group.kind, "Stack");458 } elseif (selection.selected==="group") {459if (selection.canUngroup&&random(4) ===0) {460constcount=selection.group.children.length;461constfirst=Number(selection.path.split(".").at(-1));462constparent=selection.path.slice(0, selection.path.lastIndexOf("."));463tree=ungroupMembers(tree, selection.path);464made.Ungroup++;465// The released members are a run that can be grouped again.466chosen=Array.from(467 { length: count },468 (_, index) =>`${parent}.${first+index}`,469 );470construn=selectionOf(tree, chosen);471assert.ok(run.selected==="members"&&run.canGroup);472 } else {473constkind= (["Stack", "Shelf", "Switcher"] asconst)[random(3)]!;474constnext=arrangeGroup(tree, selection.path, kind);475if (next!==tree) made.Arrange++;476tree=next;477assert.deepEqual(selectionOf(tree, chosen), {478...selection,479group: atPath(tree, selection.path),480 });481 }482 }483constnow=content(tree);484assert.equal(now.length, supplied.length);485now.forEach((leaf, index) =>assert.equal(leaf, supplied[index]));486for (constpathofpaths(tree)) {487constnode=atPath(tree, path)!;488if ("children"innode) assert.ok(node.children.length>=2, path);489deepest=Math.max(deepest, path.split(".").length-1);490 }491assert.deepEqual(restoreComposition(stored(tree), initial), tree);492 }493// The walk exercised every edit and reached the deepest nesting six facts allow.494assert.ok(made.Group>100&&made.Ungroup>100&&made.Arrange>100);495assert.equal(deepest, 5);496});497498test("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 an500// edit was made from.501consthistory: [Composition, string[]][] = [];502lettree=initial;503constedit= (chosen:string[], next:Composition) => {504history.push([tree, chosen]);505tree=next;506 };507edit(["0.2", "0.1"], groupMembers(tree, ["0.2", "0.1"]));508edit(["0.1"], arrangeGroup(tree, "0.1", "Switcher"));509edit(["0.1"], ungroupMembers(tree, "0.1"));510edit(["0"], arrangeGroup(tree, "0", "Shelf"));511512constrestored=history.reverse().map(([before, chosen]) => {513assert.deepEqual(restoreSelection(stored(chosen), before), chosen);514constselection=selectionOf(before, chosen);515returnselection.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 });521assert.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});528529test("a saved selection restores only if the reader could have made it there", () => {530consttree=authored();531for (constchosenof [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 ])540assert.deepEqual(restoreSelection(stored(chosen), tree), chosen);541542constinvalid: [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 ];559for (const [label, value] ofinvalid)560assert.deepEqual(restoreSelection(value, tree), [], label);561562// A selection belongs to one composition: valid in one, stale in another.563assert.deepEqual(restoreSelection(["0.0.1.0"], tree), ["0.0.1.0"]);564assert.deepEqual(restoreSelection(["0.0.1.0"], initial), []);565});