1/**2 * Editing a composition's grouping and arrangement together.3 *4 * The supplied content is fixed: the same leaves, in the same order. A reader5 * decides which neighbors form a group and how each group arranges its6 * members. Every state that can be reached that way is a nesting of Stack,7 * Shelf and Switcher groups over that one sequence, in which each group has8 * at least two members. `restoreComposition` accepts only those states.9 *10 * A selection is one node, or a run of neighboring members of one group.11 * `selectionOf` says what a selection permits, and `chooseMember` says how a12 * click changes it. The edits themselves are `groupMembers`, `ungroupMembers`13 * and `arrangeGroup`.14 */15importtype { Composition, Group } from"./composition.ts";16import { arrangementTarget, isArrangement } from"./arrangement.ts";17import {18atPath,19groupingReason,20neighboringMembers,21parentPath,22} from"./grouping.ts";2324typeContent=Exclude<Composition, Group>;2526// Regrouping n leaves yields at most 2n − 1 nodes and n − 1 levels of groups,27// so these bounds admit every state of an exercise with up to 13 leaves.28constmaximumNodes=100;29constmaximumAncestors=12;3031functioncontentOf(tree:Composition):Content[] {32return"children"intree?tree.children.flatMap(contentOf) : [tree];33}3435/**36 * Reads a saved regrouping and rearrangement of `initial`.37 *38 * The saved value supplies structure only: which runs of content are grouped,39 * and each group's arrangement. Its root is a group, every group has at least40 * two members, and its leaves match `initial`'s in kind, text, order and41 * number. The result holds `initial`'s own leaves, so saved data cannot42 * reorder, replace, drop, repeat or add content. A value with more than 10043 * nodes, or with a node more than 12 levels below the root, is rejected.44 */45exportfunctionrestoreComposition(46saved:unknown,47initial:Composition,48):Composition|undefined {49constsupplied=contentOf(initial);50letused=0;51letnodes=0;52functionrestore(value:unknown, ancestors:number):Composition|undefined {53if (54++nodes>maximumNodes||55ancestors>maximumAncestors||56!value||57typeofvalue!=="object"58 )59returnundefined;60constrecord=valueasRecord<string, unknown>;61if (!isArrangement(record.kind)) {62// Content is taken in reading order and from `initial`, never copied.63constleaf=supplied[used];64if (!leaf||record.kind!==leaf.kind||record.text!==leaf.text)65returnundefined;66used++;67returnleaf;68 }69if (!Array.isArray(record.children) ||record.children.length<2)70returnundefined;71constchildren:Composition[] = [];72for (constmemberofrecord.children) {73constchild=restore(member, ancestors+1);74if (!child) returnundefined;75children.push(child);76 }77return { kind: record.kind, children };78 }79consttree=restore(saved, 0);80returntree&&"children"intree&&used===supplied.length81?tree82:undefined;83}8485/** What the reader has selected, and so which edits apply. */86exporttypeEditingSelection=87| { readonlyselected:"nothing" }88/** One leaf. It has no members to arrange and never stands for its group. */89| { readonlyselected:"content"; readonlypath:string }90/** One group: the target of an arrangement. The root cannot be ungrouped. */91| {92readonlyselected:"group";93readonlypath:string;94readonlygroup:Group;95readonlycanUngroup:boolean;96 }97/**98 * Two or more neighboring members of `parent`, in reading order. They can99 * be grouped unless they are all of its members: every group keeps at100 * least two members, and a group around all of them would leave one.101 */102| {103readonlyselected:"members";104readonlypaths:readonlystring[];105readonlyparent:string;106readonlycanGroup:boolean;107 };108109/**110 * Reads a selection against the composition it was made in. Paths that no111 * longer name a node, repeat, skip a neighbor or span different groups112 * select nothing.113 */114exportfunctionselectionOf(115tree:Composition,116chosen:readonlystring[],117):EditingSelection {118const [path, ...others] =chosen;119if (path===undefined) return { selected: "nothing" };120if (!others.length) {121consttarget=arrangementTarget(tree, chosen);122if (target)123return { selected: "group", ...target, canUngroup: path!=="0" };124returnatPath(tree, path)125? { selected: "content", path }126: { selected: "nothing" };127 }128if (!neighboringMembers(tree, chosen)) return { selected: "nothing" };129constposition= (member:string) =>Number(member.split(".").at(-1));130return {131selected: "members",132paths: [...chosen].sort((a, b) =>position(a) -position(b)),133parent: parentPath(path),134canGroup: !groupingReason(tree, chosen),135 };136}137138/**139 * The selection after the reader chooses `path`.140 *141 * Choosing a neighbor of the selection extends it. Choosing a selected142 * member removes it. Choosing anything else, at any level, starts a new143 * selection there; the root has no neighbors, so it is always selected alone.144 * Removing a member from the middle of a run keeps the first member chosen.145 * The result lists members in the order they were chosen.146 */147exportfunctionchooseMember(148tree:Composition,149chosen:readonlystring[],150path:string,151):readonlystring[] {152if (!atPath(tree, path)) returnchosen;153if (chosen.includes(path)) {154constrest=chosen.filter((member) =>member!==path);155returnrest.length>1&&!neighboringMembers(tree, rest)156? [rest[0]!]157:rest;158 }159constextended= [...chosen, path];160returnchosen.length&&neighboringMembers(tree, extended)161?extended162: [path];163}164165/**166 * Reads a saved selection for `tree`. Anything that is not a selection the167 * reader could have made there restores as no selection.168 */169exportfunctionrestoreSelection(170saved:unknown,171tree:Composition,172):readonlystring[] {173if (174!Array.isArray(saved) ||175!saved.every((path):pathisstring=>typeofpath==="string")176 )177return [];178returnselectionOf(tree, saved).selected==="nothing"? [] :saved;179}