documentation/components/source/workbench-selection.ts

1/**
2 * Selecting in the workbench.
3 *
4 * A lesson teaches that each click builds on the selection, and
5 * `chooseMember` is that rule. The workbench is for an author who has not
6 * read the lesson: a click selects the one thing clicked, and building on
7 * the selection is something the author asks for.
8 *
9 * The workbench's inspector always describes something, so its selection is
10 * never empty. With nothing else selected, the whole composition is.
11 */
12import type { Composition } from "./composition.ts";
13import { chooseMember } from "./composition-editing.ts";
14import { atPath } from "./grouping.ts";
15
16/** The whole composition's path. */
17const whole = "0";
18
19/** A selection the inspector can describe: `chosen`, or the whole composition. */
20export function subjectOf(chosen: readonly string[]): readonly string[] {
21  return chosen.length ? chosen : [whole];
22}
23
24/**
25 * The selection after the author chooses `path`.
26 *
27 * Without `extend` it is that one node. With `extend` the choice builds on
28 * the selection as `chooseMember` does: a neighbor joins it, a selected
29 * member leaves it, and anything else starts again. A member that is the
30 * only one selected stays selected. A path that names nothing changes
31 * nothing.
32 */
33export function selectionAfter(
34  tree: Composition,
35  chosen: readonly string[],
36  path: string,
37  extend: boolean,
38): readonly string[] {
39  if (!atPath(tree, path)) return chosen;
40  if (!extend) return [path];
41  const next = chooseMember(tree, chosen, path);
42  return next.length ? next : [path];
43}