1import { test } from"node:test";2importassertfrom"node:assert/strict";3import {4declaration,5Stack,6Shelf,7Switcher,8typeComposition,9typeLeafKind,10typePrimitive,11} from"../documentation/components/source/composition.ts";12import {13arrangeGroup,14arrangements,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 {20addGroup,21addText,22blankComposition,23commitEdit,24contentKinds,25editContentKind,26editsFor,27editText,28isContentKind,29restoreWorkingCopy,30restoreWorkingTree,31startWorkingCopy,32undoEdit,33workingCopyLimits,34typeContent,35typeEdited,36typeInsertion,37typeWorkingCopy,38} from"../documentation/components/source/working-copy.ts";3940conststored= (value:unknown):unknown=>JSON.parse(JSON.stringify(value));41constcontent= (kind:LeafKind, text:string):Content=> ({ kind, text });42consttext= (value:string) =>content("Text", value);43const [a, b, c] = ["a", "b", "c"].map(text) as [44Composition,45Composition,46Composition,47];48constto= (parent:string, index:number):Insertion=> ({ parent, index });49functionat(tree:Composition, path:string):Composition {50constnode=atPath(tree, path);51if (!node) thrownewError(`Nothing at ${path}`);52returnnode;53}54constprinted= (tree:Composition) =>55declaration(tree)56 .map((line) =>line.tokens.map((token) =>token.text).join(""))57 .join("\n");58/** A chain of `levels` Stacks, the innermost empty. */59constnested= (levels:number):Composition=>60levels===1?Stack() :Stack(nested(levels-1));61/** A value the type system would refuse, as a control's value arrives. */62constuntyped= <T>(value:string) =>valueasunknownasT;6364test("content has one of three roles, and nothing else is one", () => {65assert.deepEqual(contentKinds, ["Text", "Heading", "Meta"]);66for (constkindofcontentKinds) assert.equal(isContentKind(kind), true);67for (constotherof [68...arrangements,69"text",70"Title",71"",727,73null,74undefined,75 ])76assert.equal(isContentKind(other), false, String(other));77});7879test("changing a role keeps the wording, the place and everything around it", () => {80constupdate=content("Text", "Updated Nov 18, 10:34 AM");81constinner=Shelf(update, b);82consttitle=content("Heading", "Request-log queries");83consttree=Stack(title, Switcher(a, inner), c);84constbefore=stored(tree);8586constedited=editContentKind(tree, "0.1.1.0", "Meta");87assert.deepEqual(88edited,89Stack(90title,91Switcher(a, Shelf(content("Meta", "Updated Nov 18, 10:34 AM"), b)),92c,93 ),94 );95// Nodes the edit did not pass through are the same objects as before.96assert.equal(at(edited, "0.0"), title);97assert.equal(at(edited, "0.1.0"), a);98assert.equal(at(edited, "0.1.1.1"), b);99assert.equal(at(edited, "0.2"), c);100assert.deepEqual(tree, before, "the original is not rewritten");101102assert.equal(103editContentKind(tree, "0.0", "Heading"),104tree,105"nothing changed",106 );107// Through every role and back: the wording never depended on the role.108letcycled=tree;109for (constkindof ["Heading", "Meta", "Text"] asconst) {110cycled=editContentKind(cycled, "0.1.1.0", kind);111assert.deepEqual(at(cycled, "0.1.1.0"), content(kind, update.text));112 }113assert.deepEqual(cycled, tree);114assert.deepEqual(115at(editContentKind(Stack(text("")), "0.0", "Heading"), "0.0"),116content("Heading", ""),117"wording may be empty",118 );119});120121test("a role belongs to content and an arrangement to a group", () => {122consttree=Stack(a, Switcher(b, c));123// A group has no role, and an arrangement is not one.124assert.throws(() =>editContentKind(tree, "0.1", "Heading"));125assert.throws(() =>editContentKind(tree, "0", "Text"));126assert.throws(() =>editContentKind(tree, "0.7", "Meta"), "nothing there");127assert.throws(() =>editContentKind(tree, "0.0", untyped("Stack")));128assert.throws(() =>editContentKind(tree, "0.0", untyped("Title")));129// Content has no arrangement.130assert.throws(() =>arrangeGroup(tree, "0.0", "Shelf"));131132// Every role sits in every arrangement, and each changes without the other.133for (constarrangementofarrangements) {134for (constroleofcontentKinds) {135constgroup=Stack({ kind: arrangement, children: [a, b] });136constasRole=editContentKind(group, "0.0.0", role);137assert.equal(at(asRole, "0.0").kind, arrangement);138assert.equal(at(asRole, "0.0.1"), b, "its neighbor is untouched");139for (constnextofarrangements) {140constarranged=arrangeGroup(asRole, "0.0", next);141assert.deepEqual(at(arranged, "0.0.0"), content(role, "a"));142assert.equal(at(arranged, "0.0.0"), at(asRole, "0.0.0"));143 }144 }145 }146});147148test("a role changes nothing about grouping: spacing, selection and moves stay the same", () => {149consttree=Stack(Stack(a, Switcher(b, c)), Shelf(a), b);150constselections= [["0.0.0"], ["0.0.1.0"], ["0.1.0"], ["0.2"]];151for (constroleofcontentKinds) {152letroled=tree;153for (const [path] ofselections)154roled=editContentKind(roled, path!, role);155// Structural spacing is computed from nesting alone.156assert.deepEqual(spacingLevels(roled), spacingLevels(tree), role);157for (constchosenofselections) {158const { text: was, ...before } =editsFor(tree, chosen);159const { text: is, ...after } =editsFor(roled, chosen);160assert.deepEqual(after, before, `${role} at ${chosen}`);161assert.equal(is?.path, was?.path);162assert.equal(is?.content.kind, role);163assert.deepEqual(164movesFor(roled, chosen)!.places.map((place) => [165place.parent,166place.index,167 ]),168movesFor(tree, chosen)!.places.map((place) => [169place.parent,170place.index,171 ]),172 );173 }174 }175// The declaration names the role and keeps the wording.176assert.equal(177printed(editContentKind(Stack(a, b), "0.1", "Meta")),178'Stack(Text("a"), Meta("b"))',179 );180});181182test("an empty group is added in place, with its arrangement, and is selected", () => {183consttree=Stack(a, Switcher(b), Shelf());184for (constkindofarrangements) {185constempty:Composition= { kind, children: [] };186constinside=addGroup(tree, to("0.2", 0), kind);187assert.deepEqual(inside.tree, Stack(a, Switcher(b), Shelf(empty)));188assert.deepEqual(inside.chosen, ["0.2.0"]);189190constbetween=addGroup(tree, to("0", 1), kind);191assert.deepEqual(between.tree, Stack(a, empty, Switcher(b), Shelf()));192assert.deepEqual(between.chosen, ["0.1"]);193assert.equal(at(between.tree, "0.0"), a);194assert.equal(195at(between.tree, "0.2"),196at(tree, "0.1"),197"moved along, intact",198 );199200constfirst=addGroup(tree, to("0.1", 0), kind);201assert.deepEqual(first.tree, Stack(a, Switcher(empty, b), Shelf()));202assert.equal(203at(first.tree, "0.1").kind,204"Switcher",205"its parent is unchanged",206 );207208assert.deepEqual(addGroup(Stack(), to("0", 0), kind).tree, Stack(empty));209assert.deepEqual(restoreWorkingTree(stored(inside.tree)), inside.tree);210 }211assert.deepEqual(tree, Stack(a, Switcher(b), Shelf()), "the original stays");212});213214test("a new empty group is an authored group: it can be filled, arranged, removed or left empty", () => {215constadded=addGroup(Stack(a), to("0", 1), "Switcher");216constedits=editsFor(added.tree, added.chosen);217assert.deepEqual(edits.arrange, { path: "0.1", group: Switcher() });218assert.deepEqual(edits.inside&& [edits.inside.parent, edits.inside.index], [219"0.1",2200,221 ]);222assert.equal(edits.remove, "0.1");223assert.equal(edits.text, undefined, "a group has no wording or role");224225constfilled=addText(added.tree, edits.inside!, "first");226assert.deepEqual(filled.tree, Stack(a, Switcher(text("first"))));227assert.deepEqual(filled.chosen, ["0.1.0"]);228// A group can hold a group before either holds any content.229constnestedGroup=addGroup(added.tree, edits.inside!, "Shelf");230assert.deepEqual(nestedGroup.tree, Stack(a, Switcher(Shelf())));231assert.deepEqual(232arrangeGroup(added.tree, "0.1", "Stack"),233Stack(a, Stack()),234"arranged while empty",235 );236// Left alone, it is saved and reopened as it is.237assert.deepEqual(restoreWorkingTree(stored(added.tree)), added.tree);238});239240test("a new member is refused where there is no such place or arrangement", () => {241consttree=Stack(a, Switcher(b));242constbefore=stored(tree);243for (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 ] asconst) {252assert.throws(() =>addGroup(tree, place, "Stack"), why);253assert.throws(() =>addText(tree, place), why);254 }255assert.throws(() =>addGroup(tree, to("0", 0), untyped<Primitive>("Grid")));256assert.throws(257 () =>addGroup(tree, to("0", 0), untyped<Primitive>("Text")),258"a role is not an arrangement",259 );260assert.deepEqual(stored(tree), before, "a refused edit leaves no trace");261});262263test("a new member is offered and accepted only within the size and nesting limits", () => {264const { nodes, ancestors } =workingCopyLimits;265constoffered= (tree:Composition, chosen:readonlystring[]) => {266constedits=editsFor(tree, chosen);267return [edits.inside, edits.after].filter((place) =>place!==undefined);268 };269/** Wherever a place is offered, content and an empty group both fit. */270constaccepts= (tree:Composition, chosen:readonlystring[]) => {271for (constplaceofoffered(tree, chosen)) {272for (consteditedof [273addText(tree, place),274addGroup(tree, place, "Switcher"),275 ])276assert.deepEqual(restoreWorkingTree(stored(edited.tree)), edited.tree);277 }278returnoffered(tree, chosen).length;279 };280281// One node of room left, then none.282constroomy=Stack(...Array.from({ length: nodes-2 }, () =>a));283assert.equal(accepts(roomy, ["0"]), 1);284assert.equal(accepts(roomy, ["0.0"]), 1);285constfull=addGroup(roomy, to("0", 0), "Shelf").tree;286assert.equal(editsFor(full, ["0"]).full, true);287assert.deepEqual(offered(full, ["0"]), []);288assert.deepEqual(289offered(full, ["0.0"]),290 [],291"not inside or after the new group",292 );293assert.throws(() =>addGroup(full, to("0", 0), "Stack"));294assert.throws(() =>addText(full, to("0.0", 0)));295296// The innermost group has one level left below it, then none.297constdeep=nested(ancestors);298constinnermost=`0${".0".repeat(ancestors-1)}`;299assert.deepEqual(at(deep, innermost), Stack());300assert.equal(accepts(deep, [innermost]), 2, "inside it and after it");301constdeepest=addGroup(deep, to(innermost, 0), "Switcher");302assert.deepEqual(at(deepest.tree, deepest.chosen[0]!), Switcher());303constedits=editsFor(deepest.tree, deepest.chosen);304assert.equal(305edits.inside,306undefined,307"nothing fits inside the deepest group",308 );309assert.equal(edits.full, true);310assert.throws(() =>311addGroup(deepest.tree, to(deepest.chosen[0]!, 0), "Stack"),312 );313assert.throws(() =>addText(deepest.tree, to(deepest.chosen[0]!, 0)));314// Beside it adds no level.315assert.equal(accepts(deepest.tree, deepest.chosen), 1);316});317318test("a blank start is an empty Stack with the whole composition selected", () => {319consttree=Stack(content("Heading", "Title"), Switcher(a, b));320constblank=blankComposition(tree);321assert.deepEqual(blank, { tree: Stack(), chosen: ["0"] });322assert.deepEqual(tree, Stack(content("Heading", "Title"), Switcher(a, b)));323// Another arrangement's empty root is still replaced by a Stack.324assert.deepEqual(blankComposition(Switcher()).tree, Stack());325// Already blank: the same composition, so there is nothing to commit.326constempty=Stack();327assert.equal(blankComposition(empty).tree, empty);328assert.deepEqual(blankComposition(empty).chosen, ["0"]);329330constedits=editsFor(blank.tree, blank.chosen);331assert.deepEqual(332edits.inside&& [edits.inside.parent, edits.inside.index],333 ["0", 0],334"ready to be added to",335 );336assert.deepEqual(edits.arrange, { path: "0", group: Stack() });337for (consteditof ["text", "after", "wrap", "release", "remove"] asconst)338assert.equal(edits[edit], undefined, edit);339assert.equal(movesFor(blank.tree, blank.chosen), undefined);340});341342test("starting over is one step for Undo, which restores the composition and its selection", () => {343constmodel=Stack(content("Heading", "Title"), Switcher(a, b), c);344constearlier=Stack(a);345constbefore:WorkingCopy= {346model,347chosen: ["0.1.1", "0.1.0"],348undo: [{ model: earlier, chosen: ["0.0"] }],349 };350constblank=blankComposition(before.model);351constafter=commitEdit(before, blank.tree, blank.chosen);352assert.deepEqual(after.model, Stack());353assert.deepEqual(after.chosen, ["0"]);354assert.equal(after.undo.length, 2);355assert.deepEqual(356restoreWorkingCopy(stored(after)),357after,358"saved and reopened",359 );360361constundone=undoEdit(after)!;362assert.equal(undone.model, model, "the composition that was replaced");363assert.deepEqual(undone.chosen, ["0.1.1", "0.1.0"], "and its selection");364assert.deepEqual(undone.undo, before.undo, "earlier history is intact");365// Reopened from storage, Undo still restores it.366constreopened=undoEdit(restoreWorkingCopy(stored(after))!)!;367assert.deepEqual(reopened.model, model);368assert.deepEqual(reopened.chosen, ["0.1.1", "0.1.0"]);369370// The first blank start has nothing before it.371constfirst:WorkingCopy= { ...startWorkingCopy(Stack()), chosen: ["0"] };372assert.deepEqual(restoreWorkingCopy(stored(first)), first);373assert.equal(undoEdit(first), undefined);374});375376test("an edit that changes nothing returns the same composition, so a caller commits nothing", () => {377constmodel=Stack(content("Meta", "aside"));378constcopy:WorkingCopy= { ...startWorkingCopy(model), chosen: ["0.0"] };379/** How a caller applies an edit: only a changed composition is history. */380constapply= (from:WorkingCopy, edited:Edited) =>381edited.tree=== from.model382? from383:commitEdit(from, edited.tree, edited.chosen);384385constsameRole=editContentKind(copy.model, "0.0", "Meta");386assert.equal(apply(copy, { tree: sameRole, chosen: ["0.0"] }), copy);387constblank=apply(copy, blankComposition(copy.model));388assert.equal(blank.undo.length, 1);389assert.equal(apply(blank, blankComposition(blank.model)), blank);390assert.equal(blank.undo.length, 1, "blank again is not a second step");391});392393test("a composition can be built from nothing, and every step can be saved and undone", () => {394letcopy:WorkingCopy= { ...startWorkingCopy(Stack()), chosen: ["0"] };395letsteps=0;396conststep= (397edit: (tree:Composition, edits:ReturnType<typeofeditsFor>) =>Edited,398 ) => {399constedited=edit(copy.model, editsFor(copy.model, copy.chosen));400assert.notEqual(edited.tree, copy.model);401copy=commitEdit(copy, edited.tree, edited.chosen);402steps++;403assert.deepEqual(404restoreWorkingCopy(stored(copy)),405copy,406printed(copy.model),407 );408 };409constreword= (wording:string) =>410step((tree) => ({411tree: editText(tree, copy.chosen[0]!, wording),412chosen: copy.chosen,413 }));414constrole= (kind:LeafKind) =>415step((tree) => ({416tree: editContentKind(tree, copy.chosen[0]!, kind),417chosen: copy.chosen,418 }));419420step((tree, edits) =>addText(tree, edits.inside!));421reword("Order shipped");422role("Heading");423step((tree, edits) =>addGroup(tree, edits.after!, "Switcher"));424step((tree, edits) =>addText(tree, edits.inside!));425reword("Arrives Thursday");426step((tree, edits) =>addText(tree, edits.after!));427reword("Updated 9:14 am");428role("Meta");429copy= { ...copy, chosen: ["0"] };430step((tree, edits) =>addGroup(tree, edits.inside!, "Shelf"));431432assert.deepEqual(433copy.model,434Stack(435content("Heading", "Order shipped"),436Switcher(text("Arrives Thursday"), content("Meta", "Updated 9:14 am")),437Shelf(),438 ),439 );440assert.deepEqual(copy.chosen, ["0.2"], "the group just added");441for (letundone=0; undone<steps; undone++) copy=undoEdit(copy)!;442assert.deepEqual(copy.model, Stack());443assert.deepEqual(copy.chosen, ["0"]);444assert.equal(undoEdit(copy), undefined);445});