1/**2 * A working copy: a composition its author may change freely.3 *4 * The guided exercises fix their content and let a reader regroup or5 * rearrange it. A working copy fixes nothing but its shape: the root is a6 * group, and every node is a group with one of the three arrangements or7 * content with one of the three roles. Content can be rewritten, given8 * another role, added and removed, and the whole can be made blank.9 *10 * A group is an authored decision, so it keeps its place and its arrangement11 * however many members it has. Removing a group's last member leaves an12 * empty group, and an author can add an empty group to fill later. Nothing13 * here dissolves a group on the author's behalf.14 *15 * Content has a role: a Heading, Text or Meta. A role says what the wording16 * is for, and the stylesheet decides how each role looks. The model holds no17 * size, rank or urgency, and a role is not an arrangement: changing it18 * leaves the wording, its place and every group as they were.19 *20 * `editsFor` says what a selection permits. Each edit returns the new tree21 * together with the path the author will want selected next. Selection22 * itself follows `chooseMember` in `composition-editing.ts`. Moving members23 * to another place is in `movement.ts`.24 */25importtype { Composition, Group, LeafKind, Primitive } from"./composition.ts";26import { isArrangement } from"./arrangement.ts";27import {28atPath,29neighboringMembers,30parentPath,31replaceAt,32ungroupMembers,33} from"./grouping.ts";34import { restoreSelection, selectionOf } from"./composition-editing.ts";3536exporttypeContent=Exclude<Composition, Group>;3738/** The roles content can have, in the order an author is offered them. */39exportconstcontentKinds:readonlyLeafKind[] = ["Text", "Heading", "Meta"];4041exportfunctionisContentKind(value:unknown):valueisLeafKind {42returncontentKinds.some((kind) =>kind===value);43}4445/**46 * How large a working copy and its history may grow. Saved state beyond47 * these bounds is rejected, and `editsFor` withholds the edit that would48 * pass them, so every state an author reaches can be saved and reopened.49 * `ancestors` counts the groups above the most deeply nested node.50 */51exportconstworkingCopyLimits= {52nodes: 200,53ancestors: 12,54history: 50,55} asconst;5657/** The text a new member starts with, ready to be replaced. */58exportconstnewText="New text";5960constposition= (path:string) =>61Number(path.slice(path.lastIndexOf(".") +1));62constancestorsOf= (path:string) =>path.split(".").length-1;6364functioncountNodes(tree:Composition):number {65return"children"intree66?tree.children.reduce((sum, child) =>sum+countNodes(child), 1)67:1;68}69/** Whether one more node keeps `tree` within `workingCopyLimits.nodes`. */70functionhasRoom(tree:Composition):boolean {71returncountNodes(tree) <workingCopyLimits.nodes;72}73/** Levels of nesting below `tree`: none for content or an empty group. */74functionlevelsBelow(tree:Composition):number {75return"children"intree76?Math.max(0, ...tree.children.map((child) =>levelsBelow(child) +1))77:0;78}79/**80 * Whether `members` could join the group at `parent` with nothing nested81 * more deeply than `workingCopyLimits.ancestors` allows. Adding, grouping82 * and moving all ask this one question.83 */84exportfunctionfitsIn(85parent:string,86members:readonlyComposition[],87):boolean {88return (89ancestorsOf(parent) +1+Math.max(0, ...members.map(levelsBelow)) <=90workingCopyLimits.ancestors91 );92}93functiongroupAt(tree:Composition, path:string):Group {94constnode=atPath(tree, path);95if (!node||!("children"innode)) thrownewError("Expected a group");96returnnode;97}9899/**100 * Reads a composition of unknown origin as a working copy.101 *102 * The value supplies everything: text, the number and order of members, and103 * each group's arrangement. Groups may have no members or one. The root is a104 * group, kinds are the six known ones, text is a string, and the whole stays105 * within `workingCopyLimits`. The result is built afresh, so nothing else106 * the value carried survives.107 */108exportfunctionrestoreWorkingTree(saved:unknown):Composition|undefined {109letnodes=0;110functionrestore(value:unknown, ancestors:number):Composition|undefined {111if (112++nodes>workingCopyLimits.nodes||113ancestors>workingCopyLimits.ancestors||114!value||115typeofvalue!=="object"116 )117returnundefined;118constrecord=valueasRecord<string, unknown>;119if (isArrangement(record.kind)) {120if (!Array.isArray(record.children)) returnundefined;121constchildren:Composition[] = [];122for (constmemberofrecord.children) {123constchild=restore(member, ancestors+1);124if (!child) returnundefined;125children.push(child);126 }127return { kind: record.kind, children };128 }129returnisContentKind(record.kind) &&typeofrecord.text==="string"130? { kind: record.kind, text: record.text }131:undefined;132 }133consttree=restore(saved, 0);134returntree&&"children"intree?tree:undefined;135}136137/** A composition and the selection made in it. */138exportinterfaceSnapshot {139readonlymodel:Composition;140readonlychosen:readonlystring[];141}142143/** The author's composition, selection, and the states Undo returns to. */144exportinterfaceWorkingCopyextendsSnapshot {145/** Earlier states, oldest first. */146readonlyundo:readonlySnapshot[];147}148149functionrestoreSnapshot(saved:unknown):Snapshot|undefined {150if (!saved||typeofsaved!=="object") returnundefined;151constrecord=savedasRecord<string, unknown>;152constmodel=restoreWorkingTree(record.model);153returnmodel&& { model, chosen: restoreSelection(record.chosen, model) };154}155156/**157 * Reads a saved working copy. An unreadable composition means there is no158 * working copy. A selection that does not fit its composition restores as no159 * selection, and an unreadable history entry is dropped.160 */161exportfunctionrestoreWorkingCopy(saved:unknown):WorkingCopy|undefined {162constcurrent=restoreSnapshot(saved);163if (!current) returnundefined;164consthistory= (savedasRecord<string, unknown>).undo;165constundo= (Array.isArray(history) ?history: [])166 .slice(-workingCopyLimits.history)167 .flatMap((entry) =>restoreSnapshot(entry) ?? []);168return { ...current, undo };169}170171/** A fresh working copy of `model`, with nothing selected and no history. */172exportfunctionstartWorkingCopy(model:Composition):WorkingCopy {173return { model, chosen: [], undo: [] };174}175176functionremembering(copy:WorkingCopy, before:Snapshot):readonlySnapshot[] {177return [...copy.undo, before].slice(-workingCopyLimits.history);178}179180/** The working copy after one edit: the state before it becomes undoable. */181exportfunctioncommitEdit(182copy:WorkingCopy,183model:Composition,184chosen:readonlystring[],185):WorkingCopy {186return {187model,188chosen,189undo: remembering(copy, { model: copy.model, chosen: copy.chosen }),190 };191}192193/** The working copy before its last edit, or `undefined` with none to undo. */194exportfunctionundoEdit(copy:WorkingCopy):WorkingCopy|undefined {195constbefore=copy.undo.at(-1);196returnbefore&& { ...before, undo: copy.undo.slice(0, -1) };197}198199/**200 * A place among the members of the group at `parent`: before its member201 * `index`, or after its last member when `index` is their number.202 */203exportinterfaceInsertion {204readonlyparent:string;205readonlyindex:number;206}207208/** What the current selection lets the author do. An absent edit is unavailable. */209exportinterfaceWorkingEdits {210/** The one selected content, whose wording and role can change. */211readonlytext:212 { readonlypath:string; readonlycontent:Content } |undefined;213/** The one selected group, whose arrangement can change. */214readonlyarrange:215 { readonlypath:string; readonlygroup:Group } |undefined;216/**217 * A new member as the last member of `group`: the selected group, or the218 * whole composition when nothing is selected. New content and a new empty219 * group fit in the same places, so this serves `addText` and `addGroup`.220 */221readonlyinside: (Insertion& { readonlygroup:Group }) |undefined;222/** A new member as the next sibling of the selected member or run. */223readonlyafter:Insertion|undefined;224/** The selected neighbors a new Stack can hold: one member, or several. */225readonlywrap:readonlystring[] |undefined;226/** The selected inner group whose members can rejoin its parent. */227readonlyrelease:string|undefined;228/** The selected member that can be removed. The root cannot. */229readonlyremove:string|undefined;230/** True when only `workingCopyLimits` withholds adding or grouping. */231readonlyfull:boolean;232}233234/**235 * Reads a selection against the working copy it was made in.236 *237 * Grouping needs no neighbor left outside and no second member: here a group238 * of one, or a group around all of its parent's members, is a decision the239 * author may make.240 */241exportfunctioneditsFor(242tree:Composition,243chosen:readonlystring[],244):WorkingEdits {245constselection=selectionOf(tree, chosen);246constroom=hasRoom(tree);247letfull=false;248constwithin= (allowed:boolean) => {249if (!allowed) full=true;250returnallowed;251 };252253constsingle=254selection.selected==="group"||selection.selected==="content"255?selection.path256:undefined;257construn=258selection.selected==="members"259?selection.paths260:single!==undefined&&single!=="0"261? [single]262:undefined;263consttarget=264selection.selected==="group"265?selection266:selection.selected==="nothing"267? { path: "0", group: groupAt(tree, "0") }268:undefined;269270constnode=single===undefined?undefined:atPath(tree, single);271consttext=272single!==undefined&&node&&!("children"innode)273? { path: single, content: node }274:undefined;275// A new member is content or an empty group: one node, nothing nested.276constinside=277target&&278within(room&&fitsIn(target.path, [{ kind: "Text", text: newText }]))279? {280parent: target.path,281index: target.group.children.length,282group: target.group,283 }284:undefined;285constafter=286run&&within(room)287? { parent: parentPath(run[0]!), index: position(run.at(-1)!) +1 }288:undefined;289// Grouping adds a level: the new Stack must fit where its members stand.290constwrap=291run&&292within(293room&&294fitsIn(parentPath(run[0]!), [295 { kind: "Stack", children: run.map((path) =>atPath(tree, path)!) },296 ]),297 )298?run299:undefined;300return {301text,302arrange:303selection.selected==="group"304? { path: selection.path, group: selection.group }305:undefined,306inside,307after,308wrap,309release:310selection.selected==="group"&&selection.canUngroup311?selection.path312:undefined,313remove: single!==undefined&&single!=="0"?single:undefined,314full,315 };316}317318/** What follows an edit: the new tree and the selection that suits it. */319exportinterfaceEdited {320readonlytree:Composition;321readonlychosen:readonlystring[];322}323324/**325 * Rewrites the text at `path`, keeping its kind. The same text returns326 * `tree` itself, so a caller can tell that nothing changed.327 */328exportfunctioneditText(329tree:Composition,330path:string,331text:string,332):Composition {333constcontent=atPath(tree, path);334if (!content||"children"incontent)335thrownewError("Select one text to edit it.");336if (content.text===text) returntree;337returnreplaceAt(tree, path, { kind: content.kind, text });338}339340/**341 * Gives the content at `path` another role, keeping its wording and its342 * place. Nodes outside the path being rebuilt keep their identity. The role343 * it already has returns `tree` itself, so a caller can tell that nothing changed.344 *345 * A group has an arrangement, not a role: `arrangeGroup` changes that.346 */347exportfunctioneditContentKind(348tree:Composition,349path:string,350kind:LeafKind,351):Composition {352if (!isContentKind(kind)) thrownewError("Choose Text, Heading or Meta.");353constcontent=atPath(tree, path);354if (!content||"children"incontent)355thrownewError("Select one text to change its role.");356if (content.kind===kind) returntree;357returnreplaceAt(tree, path, { kind, text: content.text });358}359360/**361 * Puts one new member at `at` and selects it. Later siblings move along by362 * one. The place must exist, and the result must stay within363 * `workingCopyLimits`; `editsFor` offers only places where it does.364 */365functioninsertMember(366tree:Composition,367at:Insertion,368member:Composition,369):Edited {370constgroup=groupAt(tree, at.parent);371if (372!Number.isInteger(at.index) ||373at.index<0||374at.index>group.children.length375 )376thrownewError("A new member needs a position in its group.");377if (!hasRoom(tree))378thrownewError("This working copy has no room for another member.");379if (!fitsIn(at.parent, [member]))380thrownewError("That group is nested too deeply to hold a new member.");381constchildren= [...group.children];382children.splice(at.index, 0, member);383return {384tree: replaceAt(tree, at.parent, { kind: group.kind, children }),385chosen: [`${at.parent}.${at.index}`],386 };387}388389/** Adds a Text at `at` and selects it. */390exportfunctionaddText(391tree:Composition,392at:Insertion,393text:string=newText,394):Edited {395returninsertMember(tree, at, { kind: "Text", text });396}397398/**399 * Adds a group with no members at `at`, arranged as `kind`, and selects it.400 * It is an authored group from the start: it keeps its arrangement and its401 * place while it is empty, and `editsFor` then offers a place inside it.402 */403exportfunctionaddGroup(404tree:Composition,405at:Insertion,406kind:Primitive,407):Edited {408if (!isArrangement(kind)) thrownewError("Choose Stack, Shelf or Switcher.");409returninsertMember(tree, at, { kind, children: [] });410}411412/**413 * Replaces the whole composition with an empty Stack and selects it, ready414 * to be added to. A composition that is already an empty Stack returns415 * `tree` itself, so a caller can tell that nothing changed.416 *417 * This is an edit like any other: a caller commits it with `commitEdit`,418 * and Undo then restores the composition and selection it replaced.419 */420exportfunctionblankComposition(tree:Composition):Edited {421constblank=422tree.kind==="Stack"&&"children"intree&&!tree.children.length;423return {424tree: blank?tree: { kind: "Stack", children: [] },425chosen: ["0"],426 };427}428429/**430 * Removes the member at `path` with everything in it. Its group stays, with431 * the same arrangement, even when that leaves it with one member or none.432 * The selection moves to the member now in that place, else to the one433 * before it, else to the emptied group.434 */435exportfunctionremoveMember(tree:Composition, path:string):Edited {436constparent=parentPath(path);437if (!parent||!atPath(tree, path))438thrownewError("Select a member to remove it.");439constgroup=groupAt(tree, parent);440constindex=position(path);441constchildren=group.children.filter((_, at) =>at!==index);442constnext=Math.min(index, children.length-1);443return {444tree: replaceAt(tree, parent, { kind: group.kind, children }),445chosen: [next<0?parent:`${parent}.${next}`],446 };447}448449/**450 * Puts one member, or a run of neighbors, into a new Stack where they stood451 * and selects it. They may be all of their group's members.452 */453exportfunctionwrapMembers(454tree:Composition,455paths:readonlystring[],456):Edited {457if (!neighboringMembers(tree, paths))458thrownewError("Select neighboring members of one group.");459constparent=parentPath(paths[0]!);460constgroup=groupAt(tree, parent);461conststart=Math.min(...paths.map(position));462constchildren= [...group.children];463children.splice(start, paths.length, {464kind: "Stack",465children: children.slice(start, start+paths.length),466 });467return {468tree: replaceAt(tree, parent, { kind: group.kind, children }),469chosen: [`${parent}.${start}`],470 };471}472473/**474 * Returns the members of the inner group at `path` to its parent, in place,475 * and selects them. An empty group has none to return: it disappears and476 * its parent is selected.477 */478exportfunctionreleaseGroup(tree:Composition, path:string):Edited {479constparent=parentPath(path);480if (!parent) thrownewError("Select an inner group to ungroup.");481const { children } =groupAt(tree, path);482conststart=position(path);483return {484tree: ungroupMembers(tree, path),485chosen: children.length486?children.map((_, index) =>`${parent}.${start+index}`)487: [parent],488 };489}490491/**492 * One uninterrupted rewording of one text. The composition changes as the493 * author types, and the whole rewording is a single step for Undo.494 */495exportinterfaceTextEdit {496readonlypath:string;497readonlybefore:Snapshot;498}499500exportfunctionbeginTextEdit(copy:WorkingCopy, path:string):TextEdit {501constcontent=atPath(copy.model, path);502if (!content||"children"incontent)503thrownewError("Select one text to edit it.");504return { path, before: { model: copy.model, chosen: copy.chosen } };505}506507/** The working copy while typing. History waits for the edit to finish. */508exportfunctiontypeText(509copy:WorkingCopy,510edit:TextEdit,511text:string,512):WorkingCopy {513return { ...copy, model: editText(copy.model, edit.path, text) };514}515516/** Ends the edit. It becomes one undoable step if the wording changed. */517exportfunctionfinishTextEdit(copy:WorkingCopy, edit:TextEdit):WorkingCopy {518constwording= (model:Composition) => {519constcontent=atPath(model, edit.path);520returncontent&&!("children"incontent) ?content.text:undefined;521 };522returnwording(copy.model) ===wording(edit.before.model)523?copy524: { ...copy, undo: remembering(copy, edit.before) };525}526527/** Abandons the edit: the composition and selection from before it return. */528exportfunctioncancelTextEdit(copy:WorkingCopy, edit:TextEdit):WorkingCopy {529return { ...edit.before, undo: copy.undo };530}