1import { test } from"node:test";2importassertfrom"node:assert/strict";3import {4Stack,5Shelf,6Switcher,7typeComposition,8} from"../documentation/components/source/composition.ts";9import {10atPath,11parentPath,12} from"../documentation/components/source/grouping.ts";13import {14moveMembers,15moveObstacle,16movesFor,17placeAfter,18placeAtEnd,19placeAtStart,20placeBefore,21} from"../documentation/components/source/movement.ts";22import {23commitEdit,24removeMember,25restoreWorkingCopy,26restoreWorkingTree,27startWorkingCopy,28undoEdit,29workingCopyLimits,30typeInsertion,31typeWorkingCopy,32} from"../documentation/components/source/working-copy.ts";3334conststored= (value:unknown):unknown=>JSON.parse(JSON.stringify(value));35consttext= (value:string):Composition=> ({ kind: "Text", text: value });36constheading:Composition= { kind: "Heading", text: "Title" };37constmeta:Composition= { kind: "Meta", text: "aside" };38const [a, b, c, d] = ["a", "b", "c", "d"].map(text) as [39Composition,40Composition,41Composition,42Composition,43];44functionat(tree:Composition, path:string):Composition {45constnode=atPath(tree, path);46if (!node) thrownewError(`Nothing at ${path}`);47returnnode;48}49constto= (parent:string, index:number):Insertion=> ({ parent, index });50/** Every path below the root, in reading order. */51functionmemberPaths(tree:Composition, path="0"):string[] {52return"children"intree53?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. */60functioneveryPlace(tree:Composition, path="0"):Insertion[] {61return"children"intree62? [63...Array.from({ length: tree.children.length+1 }, (_, index) =>64to(path, index),65 ),66...tree.children.flatMap((child, index) =>67everyPlace(child, `${path}.${index}`),68 ),69 ]70: [];71}72/** The composition with a run of neighbors taken out. */73functionwithout(tree:Composition, run:readonlystring[]):Composition {74constposition= (path:string) =>Number(path.split(".").at(-1));75// Last first, so each removal leaves the earlier paths as they were.76return [...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. */81constchain= (ancestors:number, ...inner:Composition[]):Composition=>82ancestors===0?Stack(...inner) :Stack(chain(ancestors-1, ...inner));8384test("a member moves to another group, whichever of the two comes first", () => {85consttree=Stack(Switcher(a, b), Shelf(c));86constlater=moveMembers(tree, ["0.0.0"], to("0.1", 1));87assert.deepEqual(later.tree, Stack(Switcher(b), Shelf(c, a)));88assert.deepEqual(later.chosen, ["0.1.1"]);89assert.equal(later.from, "0.0");9091constearlier=moveMembers(tree, ["0.1.0"], to("0.0", 1));92assert.deepEqual(earlier.tree, Stack(Switcher(a, c, b), Shelf()));93assert.deepEqual(earlier.chosen, ["0.0.1"]);94assert.equal(earlier.from, "0.1");95assert.deepEqual(tree, Stack(Switcher(a, b), Shelf(c)), "the original stays");96});9798test("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 its100// own path closes up by one.101constsibling=Stack(a, Stack(b), Shelf(c));102constfirst=moveMembers(sibling, ["0.0"], to("0.2", 0));103assert.deepEqual(first.tree, Stack(Stack(b), Shelf(a, c)));104assert.deepEqual(first.chosen, ["0.1.0"]);105106// The same, with the receiving group nested inside that later sibling.107constnested=Stack(a, b, Switcher(Stack(c), Shelf(d)));108constsecond=moveMembers(nested, ["0.0", "0.1"], to("0.2.1", 1));109assert.deepEqual(second.tree, Stack(Switcher(Stack(c), Shelf(d, a, b))));110assert.deepEqual(second.chosen, ["0.0.1.1", "0.0.1.2"]);111112// A group before the member, or in another branch, keeps its path.113constbefore=Stack(Stack(b), a, Stack(Shelf(c)));114assert.deepEqual(moveMembers(before, ["0.1"], to("0.0", 0)).chosen, [115"0.0.0",116 ]);117constbranches=Stack(Stack(a, b), Stack(Shelf(c)));118constthird=moveMembers(branches, ["0.0.0"], to("0.1.0", 0));119assert.deepEqual(third.tree, Stack(Stack(b), Stack(Shelf(a, c))));120assert.deepEqual(third.chosen, ["0.1.0.0"]);121});122123test("a member moves out to an enclosing group, before or after the group it left", () => {124consttree=Stack(a, Switcher(b, c));125constafter=moveMembers(tree, ["0.1.1"], to("0", 2));126assert.deepEqual(after.tree, Stack(a, Switcher(b), c));127assert.deepEqual(after.chosen, ["0.2"]);128assert.equal(after.from, "0.1");129130// Arriving ahead of the group it left moves that group along.131constahead=moveMembers(tree, ["0.1.1"], to("0", 0));132assert.deepEqual(ahead.tree, Stack(c, a, Switcher(b)));133assert.deepEqual(ahead.chosen, ["0.0"]);134assert.equal(ahead.from, "0.2");135assert.deepEqual(at(ahead.tree, ahead.from), Switcher(b), "one member left");136137constemptied=moveMembers(Stack(Stack(Shelf(a))), ["0.0.0.0"], to("0", 0));138assert.deepEqual(emptied.tree, Stack(a, Stack(Shelf())));139assert.equal(emptied.from, "0.1.0");140assert.deepEqual(141at(emptied.tree, emptied.from),142Shelf(),143"the emptied group keeps its arrangement and its place",144 );145});146147test("a member moves into a more deeply nested group, even an empty one", () => {148consttree=Stack(a, Stack(Shelf(b), Switcher()));149constdeeper=moveMembers(tree, ["0.0"], to("0.1.0", 1));150assert.deepEqual(deeper.tree, Stack(Stack(Shelf(b, a), Switcher())));151assert.deepEqual(deeper.chosen, ["0.0.0.1"]);152constempty=moveMembers(tree, ["0.0"], to("0.1.1", 0));153assert.deepEqual(empty.tree, Stack(Stack(Shelf(b), Switcher(a))));154assert.deepEqual(empty.chosen, ["0.0.1.0"]);155});156157test("what moves is intact, and what it does not pass through is untouched", () => {158constinner=Shelf(meta, a);159constmoving=Switcher(heading, inner);160constbystander=Stack(b, Shelf(c));161consttree=Stack(Stack(moving, d), Stack(), bystander);162constmoved=moveMembers(tree, ["0.0.0"], to("0.1", 0));163assert.deepEqual(164moved.tree,165Stack(Stack(d), Stack(Switcher(heading, Shelf(meta, a))), bystander),166 );167// The same objects, not copies: arrangement, members, kinds and wording.168assert.equal(at(moved.tree, moved.chosen[0]!), moving);169assert.equal(at(moved.tree, "0.1.0.1"), inner);170assert.equal(at(moved.tree, "0.1.0.0"), heading);171assert.equal(at(moved.tree, "0.2"), bystander);172assert.equal(at(moved.tree, "0.0.0"), d);173// The groups it left and joined keep their own arrangements.174constkinds=Stack(Switcher(a, b), Shelf(c));175constjoined=moveMembers(kinds, ["0.0.1"], to("0.1", 0)).tree;176assert.equal(at(joined, "0.0").kind, "Switcher");177assert.equal(at(joined, "0.1").kind, "Shelf");178});179180test("a member changes its place among the same neighbors, in either direction", () => {181consttree=Switcher(a, b, c, d);182constlast=moveMembers(tree, ["0.1"], to("0", 4));183assert.deepEqual(last.tree, Switcher(a, c, d, b));184assert.deepEqual(last.chosen, ["0.3"]);185assert.equal(last.from, "0");186187constfirst=moveMembers(tree, ["0.2"], to("0", 0));188assert.deepEqual(first.tree, Switcher(c, a, b, d));189assert.deepEqual(first.chosen, ["0.0"]);190191// The place between c and d, stated before b leaves.192constbetween=moveMembers(tree, ["0.1"], to("0", 3));193assert.deepEqual(between.tree, Switcher(a, c, b, d));194assert.deepEqual(between.chosen, ["0.2"]);195});196197test("a run of neighbors moves as one, in reading order", () => {198consttree=Stack(a, b, c, Shelf(d));199// Chosen out of order, as a selection can be.200constwithin=moveMembers(tree, ["0.2", "0.1"], to("0", 0));201assert.deepEqual(within.tree, Stack(b, c, a, Shelf(d)));202assert.deepEqual(within.chosen, ["0.0", "0.1"]);203204constacross=moveMembers(tree, ["0.1", "0.0"], to("0.3", 0));205assert.deepEqual(across.tree, Stack(c, Shelf(a, b, d)));206assert.deepEqual(across.chosen, ["0.1.0", "0.1.1"]);207208constall=moveMembers(Stack(Switcher(a, b), Stack()), ["0.0.0", "0.0.1"], {209parent: "0.1",210index: 0,211 });212assert.deepEqual(all.tree, Stack(Switcher(), Stack(a, b)));213assert.equal(all.from, "0.0");214});215216test("moving members to where they already are changes nothing", () => {217consttree=Stack(a, b, c, d);218// Before the run, between its members, and after it.219for (constindexof [1, 2, 3]) {220assert.equal(221moveObstacle(tree, ["0.1", "0.2"], to("0", index)),222"already-there",223 );224constmoved=moveMembers(tree, ["0.2", "0.1"], to("0", index));225assert.equal(moved.tree, tree, "the same composition, not a copy");226assert.deepEqual(moved.chosen, ["0.1", "0.2"]);227assert.equal(moved.from, "0");228 }229for (constindexof [0, 4])230assert.equal(moveObstacle(tree, ["0.1", "0.2"], to("0", index)), undefined);231constonly=Stack(Switcher(a));232assert.equal(moveMembers(only, ["0.0.0"], to("0.0", 1)).tree, only);233});234235test("a move that cannot happen is refused with its reason", () => {236consttree=Stack(a, Switcher(b, Stack(c)), d);237constbefore=stored(tree);238for (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 ] asconst) {257assert.equal(moveObstacle(tree, members, place), reason);258assert.throws(() =>moveMembers(tree, members, place));259 }260assert.deepEqual(stored(tree), before, "a refused move leaves no trace");261});262263test("members move only where nothing would be nested past the limit", () => {264constdeepest=workingCopyLimits.ancestors;265// The innermost Stack has one group fewer above it than text may have.266consttree=Stack(chain(deepest-2), a, Stack(b));267constinnermost=`0.0${".0".repeat(deepest-2)}`;268assert.deepEqual(at(tree, innermost), Stack());269constabove=innermost.slice(0, -2);270271constmoved=moveMembers(tree, ["0.1"], to(innermost, 0));272assert.equal(at(moved.tree, moved.chosen[0]!), a);273assert.deepEqual(restoreWorkingTree(stored(moved.tree)), moved.tree);274275// A group brings its own levels with it.276assert.equal(moveObstacle(tree, ["0.2"], to(innermost, 0)), "too-deep");277assert.throws(() =>moveMembers(tree, ["0.2"], to(innermost, 0)));278assert.equal(279moveObstacle(tree, ["0.1", "0.2"], to(innermost, 0)),280"too-deep",281 );282consthigher=moveMembers(tree, ["0.2"], to(above, 0));283assert.deepEqual(restoreWorkingTree(stored(higher.tree)), higher.tree);284285assert.equal(movesFor(tree, ["0.2"])!.limited, true);286assert.ok(287movesFor(tree, ["0.2"])!.places.every(288 (place) =>place.parent!==innermost,289 ),290 );291assert.equal(movesFor(tree, ["0.1"])!.limited, false);292293// At the limit, reading order can still change.294constfull=Stack(chain(deepest-2, a, b));295constreordered=moveMembers(full, [`${innermost}.0`], to(innermost, 2));296assert.deepEqual(at(reordered.tree, innermost), Stack(b, a));297});298299test("a selection's places are listed in reading order, split around where it is", () => {300consttree=Stack(a, Switcher(b, c), Shelf(), d);301constlisted= (chosen:readonlystring[]) => {302constmoves=movesFor(tree, chosen)!;303return {304members: moves.members,305places: moves.places.map((place) => [place.parent, place.index]),306earlier: moves.earlier,307 };308 };309assert.deepEqual(listed(["0.0"]), {310members: ["0.0"],311places: [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 ],320earlier: 0,321 });322assert.deepEqual(323listed(["0.1"]),324 {325members: ["0.1"],326places: [327 ["0", 0],328 ["0.2", 0],329 ["0", 3],330 ["0", 4],331 ],332earlier: 1,333 },334"a group has no place inside itself",335 );336assert.deepEqual(listed(["0.1.1"]), {337members: ["0.1.1"],338places: [339 ["0", 0],340 ["0", 1],341 ["0.1", 0],342 ["0", 2],343 ["0.2", 0],344 ["0", 3],345 ["0", 4],346 ],347earlier: 3,348 });349assert.deepEqual(listed(["0.3", "0.2"]), {350members: ["0.2", "0.3"],351places: [352 ["0", 0],353 ["0", 1],354 ["0.1", 0],355 ["0.1", 1],356 ["0.1", 2],357 ],358earlier: 5,359 });360// Each place names the group that would receive the members.361constplaces=movesFor(tree, ["0.0"])!.places;362assert.equal(places[0]!.group, at(tree, "0.1"));363assert.equal(places[4]!.group, at(tree, "0.2"));364365assert.equal(movesFor(tree, []), undefined, "nothing selected");366assert.equal(movesFor(tree, ["0"]), undefined, "the root has nowhere to go");367assert.equal(movesFor(tree, ["0.0", "0.2"]), undefined, "not a selection");368assert.deepEqual(369movesFor(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});374375test("every listed place is a move that leaves everything else as it was", () => {376consttree=Stack(377heading,378Switcher(a, Shelf(b, meta), c),379Stack(),380Shelf(Stack(d)),381 );382constselections= [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 ];388letmoves=0;389for (constchosenofselections) {390const { members, places } =movesFor(tree, chosen)!;391constmoving=members.map((path) =>at(tree, path));392// The list and the single judgment agree about every place there is.393for (constplaceofeveryPlace(tree))394assert.equal(395moveObstacle(tree, members, place) ===undefined,396places.some(397 (listed) =>398listed.parent===place.parent&&listed.index===place.index,399 ),400`${members} to ${place.parent}:${place.index}`,401 );402for (constplaceofplaces) {403moves++;404constmoved=moveMembers(tree, members, place);405constlabel=`${members} to ${place.parent}:${place.index}`;406assert.notEqual(moved.tree, tree, label);407assert.deepEqual(408moved.chosen.map((path) =>at(moved.tree, path)),409moving,410label,411 );412moved.chosen.forEach((path, index) =>413assert.equal(at(moved.tree, path), moving[index], label),414 );415// Take the members out of both: nothing else differs.416assert.deepEqual(417without(moved.tree, moved.chosen),418without(tree, members),419label,420 );421assert.equal(422at(moved.tree, parentPath(moved.chosen[0]!)).kind,423place.group.kind,424label,425 );426assert.deepEqual(427restoreWorkingTree(stored(moved.tree)),428moved.tree,429label,430 );431// The moved selection is one the author could have made there.432assert.deepEqual(433movesFor(moved.tree, moved.chosen)!.members,434moved.chosen,435 );436 }437 }438assert.ok(moves>80, `${moves} moves checked`);439});440441test("stepping to the nearest place carries a member through the composition and back", () => {442conststart=Stack(a, Switcher(b, Stack(c)), Shelf(), d);443lettree=start;444letchosen:readonlystring[] = ["0.0"];445conststep= (direction:"later"|"earlier") => {446constmoves=movesFor(tree, chosen)!;447constplace=448moves.places[direction==="later"?moves.earlier:moves.earlier-1];449if (!place) returnfalse;450 ({ tree, chosen } =moveMembers(tree, moves.members, place));451assert.equal(at(tree, chosen[0]!), a);452returntrue;453 };454// Every step reaches a new place, so there are as many steps as places.455constplaces=movesFor(start, ["0.0"])!.places.length;456letforward=0;457while (forward<=places&&step("later")) forward++;458assert.equal(forward, places);459assert.deepEqual(tree, Stack(Switcher(b, Stack(c)), Shelf(), d, a));460letback=0;461while (back<=places&&step("earlier")) back++;462assert.equal(back, places);463assert.deepEqual(tree, start);464});465466test("a place can be named by a neighbor or by a group's start and end", () => {467consttree=Stack(a, Switcher(b, c), Shelf());468assert.deepEqual(placeBefore("0.1.1"), to("0.1", 1));469assert.deepEqual(placeAfter("0.1.1"), to("0.1", 2));470assert.deepEqual(placeAtStart("0.1"), to("0.1", 0));471assert.deepEqual(placeAtEnd(tree, "0.1"), to("0.1", 2));472assert.deepEqual(placeAtEnd(tree, "0.2"), to("0.2", 0));473assert.deepEqual(474moveMembers(tree, ["0.0"], placeAfter("0.1.0")).tree,475Stack(Switcher(b, a, c), Shelf()),476 );477assert.deepEqual(478moveMembers(tree, ["0.1.0"], placeAtEnd(tree, "0.2")).tree,479Stack(a, Switcher(c), Shelf(b)),480 );481// Beside the member itself is where it already is.482assert.equal(483moveObstacle(tree, ["0.0"], placeBefore("0.0")),484"already-there",485 );486assert.equal(moveObstacle(tree, ["0.0"], placeAfter("0.0")), "already-there");487// The root has no neighbors, and text has no members.488assert.equal(moveObstacle(tree, ["0.0"], placeAfter("0")), "not-a-place");489assert.equal(490moveObstacle(tree, ["0.1"], placeAtEnd(tree, "0.0")),491"not-a-place",492 );493});494495test("a move is one step for Undo, and its selection survives saving", () => {496constmodel=Stack(heading, Switcher(a, b), Shelf(c));497constbefore:WorkingCopy= {498...startWorkingCopy(model),499chosen: ["0.1.1", "0.1.0"],500 };501constmoves=movesFor(before.model, before.chosen)!;502constmoved=moveMembers(before.model, moves.members, to("0.2", 1));503constafter=commitEdit(before, moved.tree, moved.chosen);504assert.deepEqual(after.model, Stack(heading, Switcher(), Shelf(c, a, b)));505assert.deepEqual(after.chosen, ["0.2.1", "0.2.2"]);506assert.equal(after.undo.length, 1);507assert.deepEqual(restoreWorkingCopy(stored(after)), after, "reopened");508509constundone=undoEdit(after)!;510assert.equal(undone.model, model, "the composition from before the move");511assert.deepEqual(undone.chosen, ["0.1.1", "0.1.0"], "and its selection");512assert.equal(undone.undo.length, 0);513514// Nothing changed, so there is nothing for a caller to commit.515constunchanged=moveMembers(before.model, moves.members, to("0.1", 2));516assert.equal(unchanged.tree, before.model);517});