~james/core

core/web/src/lib/markup/collapse.test.ts -rw-r--r-- 2.4 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { describe, expect, it } from "vitest";
import { COLLAPSED_LINES, collapseCodeblocks } from "#lib/markup/collapse.ts";
import { renderMarkup } from "#lib/markup/render.ts";
import type { MarkupContext } from "#lib/markup/paths.ts";

const ctx: MarkupContext = { repo: "ada.test/infra", ref: "main", collapseCode: true };

const fence = (lines: number): string =>
	["```ts", ...Array.from({ length: lines }, (_, i) => `const x${i} = ${i};`), "```"].join("\n");

describe("collapseCodeblocks", () => {
	it("leaves short blocks alone", () => {
		const html = `<pre><code>${"a\n".repeat(COLLAPSED_LINES - 1)}</code></pre>`;
		expect(collapseCodeblocks(html)).toBe(html);
	});

	it("wraps tall blocks with their line count and a toolbar slot", () => {
		const html = `<p>x</p><pre data-line="2"><code>${"a\n".repeat(COLLAPSED_LINES)}</code></pre>`;
		expect(collapseCodeblocks(html)).toBe(
			`<p>x</p><div data-codeblock="${COLLAPSED_LINES}"><div data-codeblock-toolbar></div><pre data-line="2"><code>${"a\n".repeat(COLLAPSED_LINES)}</code></pre></div>`
		);
	});

	it("counts a last line without a trailing newline", () => {
		const html = `<pre>${"a\n".repeat(COLLAPSED_LINES - 1)}a</pre>`;
		expect(collapseCodeblocks(html)).toContain(`data-codeblock="${COLLAPSED_LINES}"`);
	});

	it("wraps only the innermost of nested pre elements", () => {
		const inner = `<pre>${"a\n".repeat(COLLAPSED_LINES)}</pre>`;
		const out = collapseCodeblocks(`<pre>x${inner}</pre>`);
		expect(out.match(/data-codeblock=/g)).toHaveLength(1);
		expect(out.startsWith("<pre>x<div data-codeblock=")).toBe(true);
	});
});

describe("render", () => {
	it("collapses tall code in bodies", async () => {
		expect(await renderMarkup(fence(40), ctx)).toContain('data-codeblock="40"');
	});

	it("keeps tall code in documents expanded", async () => {
		expect(await renderMarkup(fence(40), { ...ctx, collapseCode: false })).not.toContain(
			"data-codeblock"
		);
	});

	it("keeps tall mermaid blocks whole", async () => {
		const diagram = [
			"```mermaid",
			"flowchart TB",
			...Array.from({ length: 40 }, (_, i) => `  n${i} --> n${i + 1}`),
			"```"
		].join("\n");
		const html = await renderMarkup(diagram, ctx);
		expect(html).toContain("<svg ");
		expect(html).not.toContain("data-codeblock");
	});

	it("drops a data-codeblock written in the source", async () => {
		expect(await renderMarkup('<div data-codeblock="99">x</div>', ctx)).not.toContain(
			"data-codeblock"
		);
	});
});