documentation/components/source/working-copy.ts

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 or
5 * rearrange it. A working copy fixes nothing but its shape: the root is a
6 * group, and every node is a group with one of the three arrangements or
7 * content with one of the three roles. Content can be rewritten, given
8 * 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 arrangement
11 * however many members it has. Removing a group's last member leaves an
12 * empty group, and an author can add an empty group to fill later. Nothing
13 * 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 wording
16 * is for, and the stylesheet decides how each role looks. The model holds no
17 * size, rank or urgency, and a role is not an arrangement: changing it
18 * leaves the wording, its place and every group as they were.
19 *
20 * `editsFor` says what a selection permits. Each edit returns the new tree
21 * together with the path the author will want selected next. Selection
22 * itself follows `chooseMember` in `composition-editing.ts`. Moving members
23 * to another place is in `movement.ts`.
24 */
25import type { Composition, Group, LeafKind, Primitive } from "./composition.ts";
26import { isArrangement } from "./arrangement.ts";
27import {
28  atPath,
29  neighboringMembers,
30  parentPath,
31  replaceAt,
32  ungroupMembers,
33} from "./grouping.ts";
34import { restoreSelection, selectionOf } from "./composition-editing.ts";
35
36export type Content = Exclude<Composition, Group>;
37
38/** The roles content can have, in the order an author is offered them. */
39export const contentKinds: readonly LeafKind[] = ["Text", "Heading", "Meta"];
40
41export function isContentKind(value: unknown): value is LeafKind {
42  return contentKinds.some((kind) => kind === value);
43}
44
45/**
46 * How large a working copy and its history may grow. Saved state beyond
47 * these bounds is rejected, and `editsFor` withholds the edit that would
48 * 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 */
51export const workingCopyLimits = {
52  nodes: 200,
53  ancestors: 12,
54  history: 50,
55} as const;
56
57/** The text a new member starts with, ready to be replaced. */
58export const newText = "New text";
59
60const position = (path: string) =>
61  Number(path.slice(path.lastIndexOf(".") + 1));
62const ancestorsOf = (path: string) => path.split(".").length - 1;
63
64function countNodes(tree: Composition): number {
65  return "children" in tree
66    ? tree.children.reduce((sum, child) => sum + countNodes(child), 1)
67    : 1;
68}
69/** Whether one more node keeps `tree` within `workingCopyLimits.nodes`. */
70function hasRoom(tree: Composition): boolean {
71  return countNodes(tree) < workingCopyLimits.nodes;
72}
73/** Levels of nesting below `tree`: none for content or an empty group. */
74function levelsBelow(tree: Composition): number {
75  return "children" in tree
76    ? 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 nested
81 * more deeply than `workingCopyLimits.ancestors` allows. Adding, grouping
82 * and moving all ask this one question.
83 */
84export function fitsIn(
85  parent: string,
86  members: readonly Composition[],
87): boolean {
88  return (
89    ancestorsOf(parent) + 1 + Math.max(0, ...members.map(levelsBelow)) <=
90    workingCopyLimits.ancestors
91  );
92}
93function groupAt(tree: Composition, path: string): Group {
94  const node = atPath(tree, path);
95  if (!node || !("children" in node)) throw new Error("Expected a group");
96  return node;
97}
98
99/**
100 * Reads a composition of unknown origin as a working copy.
101 *
102 * The value supplies everything: text, the number and order of members, and
103 * each group's arrangement. Groups may have no members or one. The root is a
104 * group, kinds are the six known ones, text is a string, and the whole stays
105 * within `workingCopyLimits`. The result is built afresh, so nothing else
106 * the value carried survives.
107 */
108export function restoreWorkingTree(saved: unknown): Composition | undefined {
109  let nodes = 0;
110  function restore(value: unknown, ancestors: number): Composition | undefined {
111    if (
112      ++nodes > workingCopyLimits.nodes ||
113      ancestors > workingCopyLimits.ancestors ||
114      !value ||
115      typeof value !== "object"
116    )
117      return undefined;
118    const record = value as Record<string, unknown>;
119    if (isArrangement(record.kind)) {
120      if (!Array.isArray(record.children)) return undefined;
121      const children: Composition[] = [];
122      for (const member of record.children) {
123        const child = restore(member, ancestors + 1);
124        if (!child) return undefined;
125        children.push(child);
126      }
127      return { kind: record.kind, children };
128    }
129    return isContentKind(record.kind) && typeof record.text === "string"
130      ? { kind: record.kind, text: record.text }
131      : undefined;
132  }
133  const tree = restore(saved, 0);
134  return tree && "children" in tree ? tree : undefined;
135}
136
137/** A composition and the selection made in it. */
138export interface Snapshot {
139  readonly model: Composition;
140  readonly chosen: readonly string[];
141}
142
143/** The author's composition, selection, and the states Undo returns to. */
144export interface WorkingCopy extends Snapshot {
145  /** Earlier states, oldest first. */
146  readonly undo: readonly Snapshot[];
147}
148
149function restoreSnapshot(saved: unknown): Snapshot | undefined {
150  if (!saved || typeof saved !== "object") return undefined;
151  const record = saved as Record<string, unknown>;
152  const model = restoreWorkingTree(record.model);
153  return model && { model, chosen: restoreSelection(record.chosen, model) };
154}
155
156/**
157 * Reads a saved working copy. An unreadable composition means there is no
158 * working copy. A selection that does not fit its composition restores as no
159 * selection, and an unreadable history entry is dropped.
160 */
161export function restoreWorkingCopy(saved: unknown): WorkingCopy | undefined {
162  const current = restoreSnapshot(saved);
163  if (!current) return undefined;
164  const history = (saved as Record<string, unknown>).undo;
165  const undo = (Array.isArray(history) ? history : [])
166    .slice(-workingCopyLimits.history)
167    .flatMap((entry) => restoreSnapshot(entry) ?? []);
168  return { ...current, undo };
169}
170
171/** A fresh working copy of `model`, with nothing selected and no history. */
172export function startWorkingCopy(model: Composition): WorkingCopy {
173  return { model, chosen: [], undo: [] };
174}
175
176function remembering(copy: WorkingCopy, before: Snapshot): readonly Snapshot[] {
177  return [...copy.undo, before].slice(-workingCopyLimits.history);
178}
179
180/** The working copy after one edit: the state before it becomes undoable. */
181export function commitEdit(
182  copy: WorkingCopy,
183  model: Composition,
184  chosen: readonly string[],
185): WorkingCopy {
186  return {
187    model,
188    chosen,
189    undo: remembering(copy, { model: copy.model, chosen: copy.chosen }),
190  };
191}
192
193/** The working copy before its last edit, or `undefined` with none to undo. */
194export function undoEdit(copy: WorkingCopy): WorkingCopy | undefined {
195  const before = copy.undo.at(-1);
196  return before && { ...before, undo: copy.undo.slice(0, -1) };
197}
198
199/**
200 * A place among the members of the group at `parent`: before its member
201 * `index`, or after its last member when `index` is their number.
202 */
203export interface Insertion {
204  readonly parent: string;
205  readonly index: number;
206}
207
208/** What the current selection lets the author do. An absent edit is unavailable. */
209export interface WorkingEdits {
210  /** The one selected content, whose wording and role can change. */
211  readonly text:
212    { readonly path: string; readonly content: Content } | undefined;
213  /** The one selected group, whose arrangement can change. */
214  readonly arrange:
215    { readonly path: string; readonly group: Group } | undefined;
216  /**
217   * A new member as the last member of `group`: the selected group, or the
218   * whole composition when nothing is selected. New content and a new empty
219   * group fit in the same places, so this serves `addText` and `addGroup`.
220   */
221  readonly inside: (Insertion & { readonly group: Group }) | undefined;
222  /** A new member as the next sibling of the selected member or run. */
223  readonly after: Insertion | undefined;
224  /** The selected neighbors a new Stack can hold: one member, or several. */
225  readonly wrap: readonly string[] | undefined;
226  /** The selected inner group whose members can rejoin its parent. */
227  readonly release: string | undefined;
228  /** The selected member that can be removed. The root cannot. */
229  readonly remove: string | undefined;
230  /** True when only `workingCopyLimits` withholds adding or grouping. */
231  readonly full: boolean;
232}
233
234/**
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 group
238 * of one, or a group around all of its parent's members, is a decision the
239 * author may make.
240 */
241export function editsFor(
242  tree: Composition,
243  chosen: readonly string[],
244): WorkingEdits {
245  const selection = selectionOf(tree, chosen);
246  const room = hasRoom(tree);
247  let full = false;
248  const within = (allowed: boolean) => {
249    if (!allowed) full = true;
250    return allowed;
251  };
252
253  const single =
254    selection.selected === "group" || selection.selected === "content"
255      ? selection.path
256      : undefined;
257  const run =
258    selection.selected === "members"
259      ? selection.paths
260      : single !== undefined && single !== "0"
261        ? [single]
262        : undefined;
263  const target =
264    selection.selected === "group"
265      ? selection
266      : selection.selected === "nothing"
267        ? { path: "0", group: groupAt(tree, "0") }
268        : undefined;
269
270  const node = single === undefined ? undefined : atPath(tree, single);
271  const text =
272    single !== undefined && node && !("children" in node)
273      ? { path: single, content: node }
274      : undefined;
275  // A new member is content or an empty group: one node, nothing nested.
276  const inside =
277    target &&
278    within(room && fitsIn(target.path, [{ kind: "Text", text: newText }]))
279      ? {
280          parent: target.path,
281          index: target.group.children.length,
282          group: target.group,
283        }
284      : undefined;
285  const after =
286    run && 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.
290  const wrap =
291    run &&
292    within(
293      room &&
294        fitsIn(parentPath(run[0]!), [
295          { kind: "Stack", children: run.map((path) => atPath(tree, path)!) },
296        ]),
297    )
298      ? run
299      : undefined;
300  return {
301    text,
302    arrange:
303      selection.selected === "group"
304        ? { path: selection.path, group: selection.group }
305        : undefined,
306    inside,
307    after,
308    wrap,
309    release:
310      selection.selected === "group" && selection.canUngroup
311        ? selection.path
312        : undefined,
313    remove: single !== undefined && single !== "0" ? single : undefined,
314    full,
315  };
316}
317
318/** What follows an edit: the new tree and the selection that suits it. */
319export interface Edited {
320  readonly tree: Composition;
321  readonly chosen: readonly string[];
322}
323
324/**
325 * Rewrites the text at `path`, keeping its kind. The same text returns
326 * `tree` itself, so a caller can tell that nothing changed.
327 */
328export function editText(
329  tree: Composition,
330  path: string,
331  text: string,
332): Composition {
333  const content = atPath(tree, path);
334  if (!content || "children" in content)
335    throw new Error("Select one text to edit it.");
336  if (content.text === text) return tree;
337  return replaceAt(tree, path, { kind: content.kind, text });
338}
339
340/**
341 * Gives the content at `path` another role, keeping its wording and its
342 * place. Nodes outside the path being rebuilt keep their identity. The role
343 * 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 */
347export function editContentKind(
348  tree: Composition,
349  path: string,
350  kind: LeafKind,
351): Composition {
352  if (!isContentKind(kind)) throw new Error("Choose Text, Heading or Meta.");
353  const content = atPath(tree, path);
354  if (!content || "children" in content)
355    throw new Error("Select one text to change its role.");
356  if (content.kind === kind) return tree;
357  return replaceAt(tree, path, { kind, text: content.text });
358}
359
360/**
361 * Puts one new member at `at` and selects it. Later siblings move along by
362 * one. The place must exist, and the result must stay within
363 * `workingCopyLimits`; `editsFor` offers only places where it does.
364 */
365function insertMember(
366  tree: Composition,
367  at: Insertion,
368  member: Composition,
369): Edited {
370  const group = groupAt(tree, at.parent);
371  if (
372    !Number.isInteger(at.index) ||
373    at.index < 0 ||
374    at.index > group.children.length
375  )
376    throw new Error("A new member needs a position in its group.");
377  if (!hasRoom(tree))
378    throw new Error("This working copy has no room for another member.");
379  if (!fitsIn(at.parent, [member]))
380    throw new Error("That group is nested too deeply to hold a new member.");
381  const children = [...group.children];
382  children.splice(at.index, 0, member);
383  return {
384    tree: replaceAt(tree, at.parent, { kind: group.kind, children }),
385    chosen: [`${at.parent}.${at.index}`],
386  };
387}
388
389/** Adds a Text at `at` and selects it. */
390export function addText(
391  tree: Composition,
392  at: Insertion,
393  text: string = newText,
394): Edited {
395  return insertMember(tree, at, { kind: "Text", text });
396}
397
398/**
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 its
401 * place while it is empty, and `editsFor` then offers a place inside it.
402 */
403export function addGroup(
404  tree: Composition,
405  at: Insertion,
406  kind: Primitive,
407): Edited {
408  if (!isArrangement(kind)) throw new Error("Choose Stack, Shelf or Switcher.");
409  return insertMember(tree, at, { kind, children: [] });
410}
411
412/**
413 * Replaces the whole composition with an empty Stack and selects it, ready
414 * to be added to. A composition that is already an empty Stack returns
415 * `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 */
420export function blankComposition(tree: Composition): Edited {
421  const blank =
422    tree.kind === "Stack" && "children" in tree && !tree.children.length;
423  return {
424    tree: blank ? tree : { kind: "Stack", children: [] },
425    chosen: ["0"],
426  };
427}
428
429/**
430 * Removes the member at `path` with everything in it. Its group stays, with
431 * 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 one
433 * before it, else to the emptied group.
434 */
435export function removeMember(tree: Composition, path: string): Edited {
436  const parent = parentPath(path);
437  if (!parent || !atPath(tree, path))
438    throw new Error("Select a member to remove it.");
439  const group = groupAt(tree, parent);
440  const index = position(path);
441  const children = group.children.filter((_, at) => at !== index);
442  const next = Math.min(index, children.length - 1);
443  return {
444    tree: replaceAt(tree, parent, { kind: group.kind, children }),
445    chosen: [next < 0 ? parent : `${parent}.${next}`],
446  };
447}
448
449/**
450 * Puts one member, or a run of neighbors, into a new Stack where they stood
451 * and selects it. They may be all of their group's members.
452 */
453export function wrapMembers(
454  tree: Composition,
455  paths: readonly string[],
456): Edited {
457  if (!neighboringMembers(tree, paths))
458    throw new Error("Select neighboring members of one group.");
459  const parent = parentPath(paths[0]!);
460  const group = groupAt(tree, parent);
461  const start = Math.min(...paths.map(position));
462  const children = [...group.children];
463  children.splice(start, paths.length, {
464    kind: "Stack",
465    children: children.slice(start, start + paths.length),
466  });
467  return {
468    tree: replaceAt(tree, parent, { kind: group.kind, children }),
469    chosen: [`${parent}.${start}`],
470  };
471}
472
473/**
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 and
476 * its parent is selected.
477 */
478export function releaseGroup(tree: Composition, path: string): Edited {
479  const parent = parentPath(path);
480  if (!parent) throw new Error("Select an inner group to ungroup.");
481  const { children } = groupAt(tree, path);
482  const start = position(path);
483  return {
484    tree: ungroupMembers(tree, path),
485    chosen: children.length
486      ? children.map((_, index) => `${parent}.${start + index}`)
487      : [parent],
488  };
489}
490
491/**
492 * One uninterrupted rewording of one text. The composition changes as the
493 * author types, and the whole rewording is a single step for Undo.
494 */
495export interface TextEdit {
496  readonly path: string;
497  readonly before: Snapshot;
498}
499
500export function beginTextEdit(copy: WorkingCopy, path: string): TextEdit {
501  const content = atPath(copy.model, path);
502  if (!content || "children" in content)
503    throw new Error("Select one text to edit it.");
504  return { path, before: { model: copy.model, chosen: copy.chosen } };
505}
506
507/** The working copy while typing. History waits for the edit to finish. */
508export function typeText(
509  copy: WorkingCopy,
510  edit: TextEdit,
511  text: string,
512): WorkingCopy {
513  return { ...copy, model: editText(copy.model, edit.path, text) };
514}
515
516/** Ends the edit. It becomes one undoable step if the wording changed. */
517export function finishTextEdit(copy: WorkingCopy, edit: TextEdit): WorkingCopy {
518  const wording = (model: Composition) => {
519    const content = atPath(model, edit.path);
520    return content && !("children" in content) ? content.text : undefined;
521  };
522  return wording(copy.model) === wording(edit.before.model)
523    ? copy
524    : { ...copy, undo: remembering(copy, edit.before) };
525}
526
527/** Abandons the edit: the composition and selection from before it return. */
528export function cancelTextEdit(copy: WorkingCopy, edit: TextEdit): WorkingCopy {
529  return { ...edit.before, undo: copy.undo };
530}