1import { Stack } from"./composition.ts";2importtype { Composition } from"./composition.ts";34exportfunctionatPath(5tree:Composition,6path:string,7):Composition|undefined {8constparts=path.split(".");9if (parts.shift() !=="0") returnundefined;10letnode=tree;11for (constpartofparts) {12if (!/^(0|[1-9]\d*)$/.test(part) ||!("children"innode)) returnundefined;13constchild=node.children[Number(part)];14if (!child) returnundefined;15node=child;16 }17returnnode;18}19exportfunctionparentPath(path:string):string {20returnpath.slice(0, path.lastIndexOf("."));21}22/** A tree in which `value` stands at `path`. Every node off that path is shared. */23exportfunctionreplaceAt(24tree:Composition,25path:string,26value:Composition,27):Composition {28if (path==="0") returnvalue;29constparent=parentPath(path);30constnode=atPath(tree, parent);31if (!node||!("children"innode))32thrownewError("Missing composition parent");33constchildren= [...node.children];34children[Number(path.split(".").at(-1))] =value;35returnreplaceAt(tree, parent, { ...node, children });36}37// A selection can include every sibling even though this introductory editor38// cannot add a redundant group around that complete selection.39exportfunctionneighboringMembers(40tree:Composition,41paths:readonlystring[],42):boolean {43if (!paths.length||newSet(paths).size!==paths.length) returnfalse;44constparent=parentPath(paths[0]!);45if (46!parent||47paths.some((path) =>parentPath(path) !==parent||!atPath(tree, path))48 )49returnfalse;50constindices=paths51 .map((path) =>Number(path.split(".").at(-1)))52 .sort((a, b) =>a-b);53returnindices.every((index, i) =>i===0||index===indices[i-1]!+1);54}55exportfunctiongroupingReason(56tree:Composition,57paths:readonlystring[],58):string|undefined {59if (paths.length<2) return"Select two or more neighboring members.";60if (newSet(paths).size!==paths.length) return"Select each member once.";61constparent=parentPath(paths[0]!);62if (63!parent||64paths.some((path) =>parentPath(path) !==parent||!atPath(tree, path))65 )66return"Choose members of the same group.";67constnode=atPath(tree, parent);68if (!node||!("children"innode))69return"Choose members of the same group.";70constindices=paths71 .map((path) =>Number(path.split(".").at(-1)))72 .sort((a, b) =>a-b);73if (indices.some((index, i) =>i>0&&index!==indices[i-1]!+1))74return"Select neighboring members, with none skipped.";75if (indices.length===node.children.length)76return"These are already all the members of one group. Leave a neighbor outside the new group.";77returnundefined;78}79exportfunctiongroupMembers(80tree:Composition,81paths:readonlystring[],82):Composition {83constreason=groupingReason(tree, paths);84if (reason) thrownewError(reason);85constparent=parentPath(paths[0]!);86constnode=atPath(tree, parent)!;87if (!("children"innode)) thrownewError("Expected group");88conststart=Math.min(89...paths.map((path) =>Number(path.split(".").at(-1))),90 );91constchildren= [...node.children];92children.splice(93start,94paths.length,95Stack(...children.slice(start, start+paths.length)),96 );97returnreplaceAt(tree, parent, { ...node, children });98}99exportfunctionungroupMembers(tree:Composition, path:string):Composition {100constnode=atPath(tree, path);101constparent=parentPath(path);102constcontainer=atPath(tree, parent);103if (104!parent||105!node||106!("children"innode) ||107!container||108!("children"incontainer)109 )110thrownewError("Select an inner group to ungroup.");111constchildren= [...container.children];112children.splice(Number(path.split(".").at(-1)), 1, ...node.children);113returnreplaceAt(tree, parent, { ...container, children });114}115116// Saved exercises may regroup the supplied content, but cannot replace or reorder it.117exportfunctionrestoreGrouping(118saved:unknown,119initial:Composition,120):Composition|undefined {121letremaining=100;122functionparse(value:unknown, depth:number):Composition|undefined {123if (--remaining<0||depth>12||!value||typeofvalue!=="object")124returnundefined;125constrecord=valueasRecord<string, unknown>;126if (127record.kind==="Stack"&&128Array.isArray(record.children) &&129record.children.length>=2130 ) {131constchildren=record.children.map((child) =>parse(child, depth+1));132if (children.some((child) =>!child)) returnundefined;133returnStack(...(childrenasComposition[]));134 }135if (136 ["Text", "Heading", "Meta"].includes(String(record.kind)) &&137typeofrecord.text==="string"138 )139return {140kind: record.kindas"Text"|"Heading"|"Meta",141text: record.text,142 };143returnundefined;144 }145functionleaves(tree:Composition):string[] {146return"children"intree147?tree.children.flatMap(leaves)148: [JSON.stringify([tree.kind, tree.text])];149 }150consttree=parse(saved, 0);151returntree&&152tree.kind==="Stack"&&153JSON.stringify(leaves(tree)) ===JSON.stringify(leaves(initial))154?tree155:undefined;156}