documentation/components/source/composition-editing.ts

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 reader
5 * decides which neighbors form a group and how each group arranges its
6 * 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 has
8 * 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 a
12 * click changes it. The edits themselves are `groupMembers`, `ungroupMembers`
13 * and `arrangeGroup`.
14 */
15import type { Composition, Group } from "./composition.ts";
16import { arrangementTarget, isArrangement } from "./arrangement.ts";
17import {
18  atPath,
19  groupingReason,
20  neighboringMembers,
21  parentPath,
22} from "./grouping.ts";
23
24type Content = Exclude<Composition, Group>;
25
26// 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.
28const maximumNodes = 100;
29const maximumAncestors = 12;
30
31function contentOf(tree: Composition): Content[] {
32  return "children" in tree ? tree.children.flatMap(contentOf) : [tree];
33}
34
35/**
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 least
40 * two members, and its leaves match `initial`'s in kind, text, order and
41 * number. The result holds `initial`'s own leaves, so saved data cannot
42 * reorder, replace, drop, repeat or add content. A value with more than 100
43 * nodes, or with a node more than 12 levels below the root, is rejected.
44 */
45export function restoreComposition(
46  saved: unknown,
47  initial: Composition,
48): Composition | undefined {
49  const supplied = contentOf(initial);
50  let used = 0;
51  let nodes = 0;
52  function restore(value: unknown, ancestors: number): Composition | undefined {
53    if (
54      ++nodes > maximumNodes ||
55      ancestors > maximumAncestors ||
56      !value ||
57      typeof value !== "object"
58    )
59      return undefined;
60    const record = value as Record<string, unknown>;
61    if (!isArrangement(record.kind)) {
62      // Content is taken in reading order and from `initial`, never copied.
63      const leaf = supplied[used];
64      if (!leaf || record.kind !== leaf.kind || record.text !== leaf.text)
65        return undefined;
66      used++;
67      return leaf;
68    }
69    if (!Array.isArray(record.children) || record.children.length < 2)
70      return undefined;
71    const children: Composition[] = [];
72    for (const member of record.children) {
73      const child = restore(member, ancestors + 1);
74      if (!child) return undefined;
75      children.push(child);
76    }
77    return { kind: record.kind, children };
78  }
79  const tree = restore(saved, 0);
80  return tree && "children" in tree && used === supplied.length
81    ? tree
82    : undefined;
83}
84
85/** What the reader has selected, and so which edits apply. */
86export type EditingSelection =
87  | { readonly selected: "nothing" }
88  /** One leaf. It has no members to arrange and never stands for its group. */
89  | { readonly selected: "content"; readonly path: string }
90  /** One group: the target of an arrangement. The root cannot be ungrouped. */
91  | {
92      readonly selected: "group";
93      readonly path: string;
94      readonly group: Group;
95      readonly canUngroup: boolean;
96    }
97  /**
98   * Two or more neighboring members of `parent`, in reading order. They can
99   * be grouped unless they are all of its members: every group keeps at
100   * least two members, and a group around all of them would leave one.
101   */
102  | {
103      readonly selected: "members";
104      readonly paths: readonly string[];
105      readonly parent: string;
106      readonly canGroup: boolean;
107    };
108
109/**
110 * Reads a selection against the composition it was made in. Paths that no
111 * longer name a node, repeat, skip a neighbor or span different groups
112 * select nothing.
113 */
114export function selectionOf(
115  tree: Composition,
116  chosen: readonly string[],
117): EditingSelection {
118  const [path, ...others] = chosen;
119  if (path === undefined) return { selected: "nothing" };
120  if (!others.length) {
121    const target = arrangementTarget(tree, chosen);
122    if (target)
123      return { selected: "group", ...target, canUngroup: path !== "0" };
124    return atPath(tree, path)
125      ? { selected: "content", path }
126      : { selected: "nothing" };
127  }
128  if (!neighboringMembers(tree, chosen)) return { selected: "nothing" };
129  const position = (member: string) => Number(member.split(".").at(-1));
130  return {
131    selected: "members",
132    paths: [...chosen].sort((a, b) => position(a) - position(b)),
133    parent: parentPath(path),
134    canGroup: !groupingReason(tree, chosen),
135  };
136}
137
138/**
139 * The selection after the reader chooses `path`.
140 *
141 * Choosing a neighbor of the selection extends it. Choosing a selected
142 * member removes it. Choosing anything else, at any level, starts a new
143 * 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 */
147export function chooseMember(
148  tree: Composition,
149  chosen: readonly string[],
150  path: string,
151): readonly string[] {
152  if (!atPath(tree, path)) return chosen;
153  if (chosen.includes(path)) {
154    const rest = chosen.filter((member) => member !== path);
155    return rest.length > 1 && !neighboringMembers(tree, rest)
156      ? [rest[0]!]
157      : rest;
158  }
159  const extended = [...chosen, path];
160  return chosen.length && neighboringMembers(tree, extended)
161    ? extended
162    : [path];
163}
164
165/**
166 * Reads a saved selection for `tree`. Anything that is not a selection the
167 * reader could have made there restores as no selection.
168 */
169export function restoreSelection(
170  saved: unknown,
171  tree: Composition,
172): readonly string[] {
173  if (
174    !Array.isArray(saved) ||
175    !saved.every((path): path is string => typeof path === "string")
176  )
177    return [];
178  return selectionOf(tree, saved).selected === "nothing" ? [] : saved;
179}