1/**2 * Moving members of a working copy to another place.3 *4 * A move takes one member, or a run of neighbors, out of its group and puts5 * it among the members of a group: the same group, which changes reading6 * order, or another, which also changes membership. What moves is intact. A7 * group arrives with its arrangement and everything in it; text keeps its8 * kind and wording. Nothing else is rewritten: the group the members leave9 * keeps its place and arrangement, even with no members left, and the group10 * that receives them keeps its own.11 *12 * A place is always stated in the composition as it is before the move.13 * `moveMembers` works out where that place is once the members have left.14 *15 * `moveObstacle` is the one statement of whether a move can happen.16 * `movesFor` lists every place a selection can go, and `moveMembers` makes17 * the move.18 */19importtype { Composition, Group } from"./composition.ts";20import { selectionOf } from"./composition-editing.ts";21import {22atPath,23neighboringMembers,24parentPath,25replaceAt,26} from"./grouping.ts";27import { fitsIn, typeEdited, typeInsertion } from"./working-copy.ts";2829constposition= (path:string) =>30Number(path.slice(path.lastIndexOf(".") +1));3132/** The place just before the member at `path`. */33exportfunctionplaceBefore(path:string):Insertion {34return { parent: parentPath(path), index: position(path) };35}36/** The place just after the member at `path`. */37exportfunctionplaceAfter(path:string):Insertion {38return { parent: parentPath(path), index: position(path) +1 };39}40/** The place before every member of the group at `group`. */41exportfunctionplaceAtStart(group:string):Insertion {42return { parent: group, index: 0 };43}44/** The place after every member of the group at `group`. */45exportfunctionplaceAtEnd(tree:Composition, group:string):Insertion {46constnode=atPath(tree, group);47return {48parent: group,49index: node&&"children"innode?node.children.length:0,50 };51}5253/** Why some members cannot move to some place. */54exporttypeMoveObstacle=55/** The whole composition was asked to move. */56|"root"57/** What was asked to move is not one member or a run of neighbors. */58|"not-members"59/** The place is not among the members of a group. */60|"not-a-place"61/** The place is inside a group that is moving. */62|"inside-itself"63/** The members would be nested more deeply than a working copy allows. */64|"too-deep"65/** The members are already there: the move would change nothing. */66|"already-there";6768/** Each obstacle in a sentence an author can act on. */69exportconstmoveObstacles:Record<MoveObstacle, string> = {70root: "The whole composition has no group to move within.",71"not-members": "Select one member, or neighboring members, to move them.",72"not-a-place": "Choose a place among the members of a group.",73"inside-itself": "A group cannot move inside itself.",74"too-deep": "That place is nested too deeply to hold this.",75"already-there": "That is where this already is.",76};7778/** The members that move together: neighbors in one group, in reading order. */79interfaceRun {80/** The group they leave. */81readonlyparent:string;82readonlygroup:Group;83/** The first member's position in that group. */84readonlystart:number;85readonlypaths:readonlystring[];86readonlynodes:readonlyComposition[];87}8889functionrunOf(90tree:Composition,91members:readonlystring[],92):Run|"root"|"not-members" {93if (members.includes("0")) return"root";94if (!neighboringMembers(tree, members)) return"not-members";95constparent=parentPath(members[0]!);96constgroup=atPath(tree, parent);97if (!group||!("children"ingroup)) return"not-members";98conststart=Math.min(...members.map(position));99constnodes=group.children.slice(start, start+members.length);100return {101parent,102group,103start,104paths: nodes.map((_, index) =>`${parent}.${start+index}`),105nodes,106 };107}108109functionobstacleAt(110tree:Composition,111run:Run,112to:Insertion,113):MoveObstacle|undefined {114constgroup=atPath(tree, to.parent);115if (116!group||117!("children"ingroup) ||118!Number.isInteger(to.index) ||119to.index<0||120to.index>group.children.length121 )122return"not-a-place";123if (124run.paths.some(125 (path) =>to.parent===path||to.parent.startsWith(`${path}.`),126 )127 )128return"inside-itself";129// Just before the run, just after it, and anywhere between its members.130if (131to.parent===run.parent&&132to.index>=run.start&&133to.index<=run.start+run.nodes.length134 )135return"already-there";136returnfitsIn(to.parent, run.nodes) ?undefined:"too-deep";137}138139/**140 * Why `members` cannot move to `to`, or `undefined` when they can.141 *142 * `members` is one member that is not the root, or a run of neighbors in143 * any order. `to` is a place in `tree` as it is now.144 */145exportfunctionmoveObstacle(146tree:Composition,147members:readonlystring[],148to:Insertion,149):MoveObstacle|undefined {150construn=runOf(tree, members);151returntypeofrun==="string"?run:obstacleAt(tree, run, to);152}153154/** A place some members can move to, with the group that would receive them. */155exportinterfacePlaceextendsInsertion {156readonlygroup:Group;157}158159/** Where the current selection can move. */160exportinterfaceMoves {161/** What would move: the selected member or run, in reading order. */162readonlymembers:readonlystring[];163/**164 * Every place it can go, in the order the places appear when the165 * composition is read: a group's start, then each member with the places166 * inside it, then the place after that member. It can be empty.167 */168readonlyplaces:readonlyPlace[];169/**170 * How many of `places` come before where the members are now. The rest171 * come after, so `places[earlier - 1]` and `places[earlier]` are the172 * nearest moves in each direction.173 */174readonlyearlier:number;175/** True when the nesting limit alone withholds some place. */176readonlylimited:boolean;177}178179/**180 * Reads a selection as something to move. A selection of nothing, or of the181 * root, has nothing that can move.182 */183exportfunctionmovesFor(184tree:Composition,185chosen:readonlystring[],186):Moves|undefined {187constselection=selectionOf(tree, chosen);188construn=189selection.selected==="nothing"190?undefined191:runOf(192tree,193selection.selected==="members"?selection.paths: [selection.path],194 );195if (!run||typeofrun==="string"||!("children"intree))196returnundefined;197constplaces:Place[] = [];198letearlier=0;199letlimited=false;200constvisit= (group:Group, parent:string) => {201for (letindex=0; index<=group.children.length; index++) {202constobstacle=obstacleAt(tree, run, { parent, index });203if (!obstacle) places.push({ parent, index, group });204// No place lies between the places the run already occupies.205elseif (obstacle==="already-there") earlier=places.length;206elseif (obstacle==="too-deep") limited=true;207constmember=group.children[index];208if (member&&"children"inmember) visit(member, `${parent}.${index}`);209 }210 };211visit(tree, "0");212return { members: run.paths, places, earlier, limited };213}214215/** A move's result: the new tree, the moved members, and where they left. */216exportinterfaceMovedextendsEdited {217/**218 * The group the members left, at its path in `tree`. That path differs219 * from before when the members arrived ahead of it in an enclosing group.220 * The group that received them is the parent of `chosen`.221 */222readonlyfrom:string;223}224225/**226 * `path` once the members of `group` at `from` and beyond stand `by` places227 * along. Only a path through one of those members changes.228 */229functionalong(path:string, group:string, from:number, by:number):string {230if (!path.startsWith(`${group}.`)) returnpath;231const [member, ...rest] =path.slice(group.length+1).split(".");232returnNumber(member) < from233?path234: [group, Number(member) +by, ...rest].join(".");235}236237/**238 * Moves `members` to `to` and selects them where they now are.239 *240 * `to` is a place in `tree`, before anything moves. The members keep their241 * order and are the same objects as before, as is every group and text the242 * move did not pass through. The group they leave stays, whatever is left243 * in it.244 *245 * Moving members to where they already are returns `tree` itself, so a246 * caller can tell that nothing changed. Any other obstacle throws.247 */248exportfunctionmoveMembers(249tree:Composition,250members:readonlystring[],251to:Insertion,252):Moved {253construn=runOf(tree, members);254if (typeofrun==="string") thrownewError(moveObstacles[run]);255constobstacle=obstacleAt(tree, run, to);256if (obstacle==="already-there")257return { tree, chosen: run.paths, from: run.parent };258if (obstacle) thrownewError(moveObstacles[obstacle]);259260constcount=run.nodes.length;261constwithout=replaceAt(tree, run.parent, {262kind: run.group.kind,263children: run.group.children.filter(264 (_, index) =>index<run.start||index>=run.start+count,265 ),266 });267// The place was stated before the members left. Later members of their268// group have closed up by `count`, which moves the place itself when it is269// in that group, and its group's path when that runs through one of them.270constparent=along(to.parent, run.parent, run.start+count, -count);271constindex=272to.parent===run.parent&&to.index>run.start273?to.index-count274:to.index;275constreceiving=atPath(without, parent);276if (!receiving||!("children"inreceiving))277thrownewError(moveObstacles["not-a-place"]);278constchildren= [...receiving.children];279children.splice(index, 0, ...run.nodes);280return {281tree: replaceAt(without, parent, { kind: receiving.kind, children }),282chosen: run.nodes.map((_, offset) =>`${parent}.${index+offset}`),283// Arriving ahead of the group they left moves that group along.284 from: along(run.parent, parent, index, count),285 };286}