documentation/components/source/grouping.ts

1import { Stack } from "./composition.ts";
2import type { Composition } from "./composition.ts";
3
4export function atPath(
5  tree: Composition,
6  path: string,
7): Composition | undefined {
8  const parts = path.split(".");
9  if (parts.shift() !== "0") return undefined;
10  let node = tree;
11  for (const part of parts) {
12    if (!/^(0|[1-9]\d*)$/.test(part) || !("children" in node)) return undefined;
13    const child = node.children[Number(part)];
14    if (!child) return undefined;
15    node = child;
16  }
17  return node;
18}
19export function parentPath(path: string): string {
20  return path.slice(0, path.lastIndexOf("."));
21}
22/** A tree in which `value` stands at `path`. Every node off that path is shared. */
23export function replaceAt(
24  tree: Composition,
25  path: string,
26  value: Composition,
27): Composition {
28  if (path === "0") return value;
29  const parent = parentPath(path);
30  const node = atPath(tree, parent);
31  if (!node || !("children" in node))
32    throw new Error("Missing composition parent");
33  const children = [...node.children];
34  children[Number(path.split(".").at(-1))] = value;
35  return replaceAt(tree, parent, { ...node, children });
36}
37// A selection can include every sibling even though this introductory editor
38// cannot add a redundant group around that complete selection.
39export function neighboringMembers(
40  tree: Composition,
41  paths: readonly string[],
42): boolean {
43  if (!paths.length || new Set(paths).size !== paths.length) return false;
44  const parent = parentPath(paths[0]!);
45  if (
46    !parent ||
47    paths.some((path) => parentPath(path) !== parent || !atPath(tree, path))
48  )
49    return false;
50  const indices = paths
51    .map((path) => Number(path.split(".").at(-1)))
52    .sort((a, b) => a - b);
53  return indices.every((index, i) => i === 0 || index === indices[i - 1]! + 1);
54}
55export function groupingReason(
56  tree: Composition,
57  paths: readonly string[],
58): string | undefined {
59  if (paths.length < 2) return "Select two or more neighboring members.";
60  if (new Set(paths).size !== paths.length) return "Select each member once.";
61  const parent = parentPath(paths[0]!);
62  if (
63    !parent ||
64    paths.some((path) => parentPath(path) !== parent || !atPath(tree, path))
65  )
66    return "Choose members of the same group.";
67  const node = atPath(tree, parent);
68  if (!node || !("children" in node))
69    return "Choose members of the same group.";
70  const indices = paths
71    .map((path) => Number(path.split(".").at(-1)))
72    .sort((a, b) => a - b);
73  if (indices.some((index, i) => i > 0 && index !== indices[i - 1]! + 1))
74    return "Select neighboring members, with none skipped.";
75  if (indices.length === node.children.length)
76    return "These are already all the members of one group. Leave a neighbor outside the new group.";
77  return undefined;
78}
79export function groupMembers(
80  tree: Composition,
81  paths: readonly string[],
82): Composition {
83  const reason = groupingReason(tree, paths);
84  if (reason) throw new Error(reason);
85  const parent = parentPath(paths[0]!);
86  const node = atPath(tree, parent)!;
87  if (!("children" in node)) throw new Error("Expected group");
88  const start = Math.min(
89    ...paths.map((path) => Number(path.split(".").at(-1))),
90  );
91  const children = [...node.children];
92  children.splice(
93    start,
94    paths.length,
95    Stack(...children.slice(start, start + paths.length)),
96  );
97  return replaceAt(tree, parent, { ...node, children });
98}
99export function ungroupMembers(tree: Composition, path: string): Composition {
100  const node = atPath(tree, path);
101  const parent = parentPath(path);
102  const container = atPath(tree, parent);
103  if (
104    !parent ||
105    !node ||
106    !("children" in node) ||
107    !container ||
108    !("children" in container)
109  )
110    throw new Error("Select an inner group to ungroup.");
111  const children = [...container.children];
112  children.splice(Number(path.split(".").at(-1)), 1, ...node.children);
113  return replaceAt(tree, parent, { ...container, children });
114}
115
116// Saved exercises may regroup the supplied content, but cannot replace or reorder it.
117export function restoreGrouping(
118  saved: unknown,
119  initial: Composition,
120): Composition | undefined {
121  let remaining = 100;
122  function parse(value: unknown, depth: number): Composition | undefined {
123    if (--remaining < 0 || depth > 12 || !value || typeof value !== "object")
124      return undefined;
125    const record = value as Record<string, unknown>;
126    if (
127      record.kind === "Stack" &&
128      Array.isArray(record.children) &&
129      record.children.length >= 2
130    ) {
131      const children = record.children.map((child) => parse(child, depth + 1));
132      if (children.some((child) => !child)) return undefined;
133      return Stack(...(children as Composition[]));
134    }
135    if (
136      ["Text", "Heading", "Meta"].includes(String(record.kind)) &&
137      typeof record.text === "string"
138    )
139      return {
140        kind: record.kind as "Text" | "Heading" | "Meta",
141        text: record.text,
142      };
143    return undefined;
144  }
145  function leaves(tree: Composition): string[] {
146    return "children" in tree
147      ? tree.children.flatMap(leaves)
148      : [JSON.stringify([tree.kind, tree.text])];
149  }
150  const tree = parse(saved, 0);
151  return tree &&
152    tree.kind === "Stack" &&
153    JSON.stringify(leaves(tree)) === JSON.stringify(leaves(initial))
154    ? tree
155    : undefined;
156}