tests/declaration.test.ts

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import { runInNewContext } from "node:vm";
4import {
5  declaration,
6  example,
7  Stack,
8  Shelf,
9  Switcher,
10  type Composition,
11} from "../documentation/components/source/composition.ts";
12
13function source(tree: Composition, width: number) {
14  return declaration(tree, "0", 0, width)
15    .map((line) => line.tokens.map((token) => token.text).join(""))
16    .join("\n");
17}
18
19test("the initial lesson breaks between members instead of inside a long flat group", () => {
20  assert.equal(
21    source(example("flat"), 80),
22    `Stack(
23  Text("Execution completed"),
24  Text("Run lasted 4m 1s"),
25  Text("Remediation Plan proposed"),
26  Text("Awaiting approval")
27)`,
28  );
29});
30
31test("short groups stay together and narrower panels expand them without losing selectable paths", () => {
32  const tree = example("nested");
33  assert.match(
34    source(tree, 80),
35    /  Stack\(Text\("Execution completed"\), Text\("Run lasted 4m 1s"\)\)/,
36  );
37  assert.match(
38    source(tree, 40),
39    /  Stack\(\n    Text\("Execution completed"\),/,
40  );
41  const names = (width: number) =>
42    declaration(tree, "0", 0, width).flatMap((line) =>
43      line.tokens
44        .filter((token) => token.kind)
45        .map((token) => [token.kind, token.path]),
46    );
47  assert.deepEqual(names(24), names(80));
48});
49
50test("formatting preserves the exact tree and string values across widths", () => {
51  const text: Composition = {
52    kind: "Text",
53    text: 'A long line with "quotes", a newline\nand "); throw new Error("not code"); // 🪴',
54  };
55  const tree = Stack(
56    example("article"),
57    Shelf(text, { kind: "Meta", text: "caption" }),
58  );
59  const constructors = {
60    Stack,
61    Shelf,
62    Switcher,
63    Text: (text: string): Composition => ({ kind: "Text", text }),
64    Heading: (text: string): Composition => ({ kind: "Heading", text }),
65    Meta: (text: string): Composition => ({ kind: "Meta", text }),
66  };
67  for (const width of [16, 35, 80, 200]) {
68    assert.deepEqual(runInNewContext(source(tree, width), constructors), tree);
69  }
70});