documentation/components/source/movement.ts

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 puts
5 * it among the members of a group: the same group, which changes reading
6 * order, or another, which also changes membership. What moves is intact. A
7 * group arrives with its arrangement and everything in it; text keeps its
8 * kind and wording. Nothing else is rewritten: the group the members leave
9 * keeps its place and arrangement, even with no members left, and the group
10 * 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` makes
17 * the move.
18 */
19import type { Composition, Group } from "./composition.ts";
20import { selectionOf } from "./composition-editing.ts";
21import {
22  atPath,
23  neighboringMembers,
24  parentPath,
25  replaceAt,
26} from "./grouping.ts";
27import { fitsIn, type Edited, type Insertion } from "./working-copy.ts";
28
29const position = (path: string) =>
30  Number(path.slice(path.lastIndexOf(".") + 1));
31
32/** The place just before the member at `path`. */
33export function placeBefore(path: string): Insertion {
34  return { parent: parentPath(path), index: position(path) };
35}
36/** The place just after the member at `path`. */
37export function placeAfter(path: string): Insertion {
38  return { parent: parentPath(path), index: position(path) + 1 };
39}
40/** The place before every member of the group at `group`. */
41export function placeAtStart(group: string): Insertion {
42  return { parent: group, index: 0 };
43}
44/** The place after every member of the group at `group`. */
45export function placeAtEnd(tree: Composition, group: string): Insertion {
46  const node = atPath(tree, group);
47  return {
48    parent: group,
49    index: node && "children" in node ? node.children.length : 0,
50  };
51}
52
53/** Why some members cannot move to some place. */
54export type MoveObstacle =
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";
67
68/** Each obstacle in a sentence an author can act on. */
69export const moveObstacles: Record<MoveObstacle, string> = {
70  root: "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};
77
78/** The members that move together: neighbors in one group, in reading order. */
79interface Run {
80  /** The group they leave. */
81  readonly parent: string;
82  readonly group: Group;
83  /** The first member's position in that group. */
84  readonly start: number;
85  readonly paths: readonly string[];
86  readonly nodes: readonly Composition[];
87}
88
89function runOf(
90  tree: Composition,
91  members: readonly string[],
92): Run | "root" | "not-members" {
93  if (members.includes("0")) return "root";
94  if (!neighboringMembers(tree, members)) return "not-members";
95  const parent = parentPath(members[0]!);
96  const group = atPath(tree, parent);
97  if (!group || !("children" in group)) return "not-members";
98  const start = Math.min(...members.map(position));
99  const nodes = group.children.slice(start, start + members.length);
100  return {
101    parent,
102    group,
103    start,
104    paths: nodes.map((_, index) => `${parent}.${start + index}`),
105    nodes,
106  };
107}
108
109function obstacleAt(
110  tree: Composition,
111  run: Run,
112  to: Insertion,
113): MoveObstacle | undefined {
114  const group = atPath(tree, to.parent);
115  if (
116    !group ||
117    !("children" in group) ||
118    !Number.isInteger(to.index) ||
119    to.index < 0 ||
120    to.index > group.children.length
121  )
122    return "not-a-place";
123  if (
124    run.paths.some(
125      (path) => to.parent === path || to.parent.startsWith(`${path}.`),
126    )
127  )
128    return "inside-itself";
129  // Just before the run, just after it, and anywhere between its members.
130  if (
131    to.parent === run.parent &&
132    to.index >= run.start &&
133    to.index <= run.start + run.nodes.length
134  )
135    return "already-there";
136  return fitsIn(to.parent, run.nodes) ? undefined : "too-deep";
137}
138
139/**
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 in
143 * any order. `to` is a place in `tree` as it is now.
144 */
145export function moveObstacle(
146  tree: Composition,
147  members: readonly string[],
148  to: Insertion,
149): MoveObstacle | undefined {
150  const run = runOf(tree, members);
151  return typeof run === "string" ? run : obstacleAt(tree, run, to);
152}
153
154/** A place some members can move to, with the group that would receive them. */
155export interface Place extends Insertion {
156  readonly group: Group;
157}
158
159/** Where the current selection can move. */
160export interface Moves {
161  /** What would move: the selected member or run, in reading order. */
162  readonly members: readonly string[];
163  /**
164   * Every place it can go, in the order the places appear when the
165   * composition is read: a group's start, then each member with the places
166   * inside it, then the place after that member. It can be empty.
167   */
168  readonly places: readonly Place[];
169  /**
170   * How many of `places` come before where the members are now. The rest
171   * come after, so `places[earlier - 1]` and `places[earlier]` are the
172   * nearest moves in each direction.
173   */
174  readonly earlier: number;
175  /** True when the nesting limit alone withholds some place. */
176  readonly limited: boolean;
177}
178
179/**
180 * Reads a selection as something to move. A selection of nothing, or of the
181 * root, has nothing that can move.
182 */
183export function movesFor(
184  tree: Composition,
185  chosen: readonly string[],
186): Moves | undefined {
187  const selection = selectionOf(tree, chosen);
188  const run =
189    selection.selected === "nothing"
190      ? undefined
191      : runOf(
192          tree,
193          selection.selected === "members" ? selection.paths : [selection.path],
194        );
195  if (!run || typeof run === "string" || !("children" in tree))
196    return undefined;
197  const places: Place[] = [];
198  let earlier = 0;
199  let limited = false;
200  const visit = (group: Group, parent: string) => {
201    for (let index = 0; index <= group.children.length; index++) {
202      const obstacle = obstacleAt(tree, run, { parent, index });
203      if (!obstacle) places.push({ parent, index, group });
204      // No place lies between the places the run already occupies.
205      else if (obstacle === "already-there") earlier = places.length;
206      else if (obstacle === "too-deep") limited = true;
207      const member = group.children[index];
208      if (member && "children" in member) visit(member, `${parent}.${index}`);
209    }
210  };
211  visit(tree, "0");
212  return { members: run.paths, places, earlier, limited };
213}
214
215/** A move's result: the new tree, the moved members, and where they left. */
216export interface Moved extends Edited {
217  /**
218   * The group the members left, at its path in `tree`. That path differs
219   * 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   */
222  readonly from: string;
223}
224
225/**
226 * `path` once the members of `group` at `from` and beyond stand `by` places
227 * along. Only a path through one of those members changes.
228 */
229function along(path: string, group: string, from: number, by: number): string {
230  if (!path.startsWith(`${group}.`)) return path;
231  const [member, ...rest] = path.slice(group.length + 1).split(".");
232  return Number(member) < from
233    ? path
234    : [group, Number(member) + by, ...rest].join(".");
235}
236
237/**
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 their
241 * order and are the same objects as before, as is every group and text the
242 * move did not pass through. The group they leave stays, whatever is left
243 * in it.
244 *
245 * Moving members to where they already are returns `tree` itself, so a
246 * caller can tell that nothing changed. Any other obstacle throws.
247 */
248export function moveMembers(
249  tree: Composition,
250  members: readonly string[],
251  to: Insertion,
252): Moved {
253  const run = runOf(tree, members);
254  if (typeof run === "string") throw new Error(moveObstacles[run]);
255  const obstacle = obstacleAt(tree, run, to);
256  if (obstacle === "already-there")
257    return { tree, chosen: run.paths, from: run.parent };
258  if (obstacle) throw new Error(moveObstacles[obstacle]);
259
260  const count = run.nodes.length;
261  const without = replaceAt(tree, run.parent, {
262    kind: run.group.kind,
263    children: 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 their
268  // group have closed up by `count`, which moves the place itself when it is
269  // in that group, and its group's path when that runs through one of them.
270  const parent = along(to.parent, run.parent, run.start + count, -count);
271  const index =
272    to.parent === run.parent && to.index > run.start
273      ? to.index - count
274      : to.index;
275  const receiving = atPath(without, parent);
276  if (!receiving || !("children" in receiving))
277    throw new Error(moveObstacles["not-a-place"]);
278  const children = [...receiving.children];
279  children.splice(index, 0, ...run.nodes);
280  return {
281    tree: replaceAt(without, parent, { kind: receiving.kind, children }),
282    chosen: 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}