Open History to see the last commit
1import { getSharedHighlighter } from "@pierre/diffs";
2import { toHtml } from "hast-util-to-html";
3import { act } from "react";
4import { createRoot } from "react-dom/client";
5import { afterEach, expect, it, vi } from "vite-plus/test";
6
7import { createIncrementalHighlightedDocument } from "../../lib/incrementalHighlighting";
8import { HighlightedCodeLines } from "./HighlightedCodeLines";
9
10afterEach(() => {
11 vi.unstubAllGlobals();
12});
13
14// React writes inline styles through CSSOM, so normalize Shiki's style strings the same way.
15function normalizedHtml(html: string) {
16 const host = document.createElement("div");
17 host.innerHTML = html;
18 for (const element of host.querySelectorAll<HTMLElement>("*")) {
19 const style = element.style.cssText;
20 const attributes = [...element.attributes].toSorted((a, b) => a.name.localeCompare(b.name));
21 for (const { name } of attributes) element.removeAttribute(name);
22 for (const { name, value } of attributes) element.setAttribute(name, value);
23 if (style) element.style.cssText = style;
24 }
25 return host.innerHTML;
26}
27
28it("streams Shiki HTML into the DOM, keeping finished lines mounted", async () => {
29 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
30 const highlighter = await getSharedHighlighter({
31 langs: ["typescript"],
32 themes: ["pierre-dark", "pierre-light"],
33 preferredHighlighter: "shiki-wasm",
34 });
35 const code =
36 'const html = "<img src=x onerror=alert(1)>";\n\n/* multi\nline */\n\tconst x = 1;\n';
37 for (const theme of ["pierre-dark", "pierre-light"] as const) {
38 const highlight = createIncrementalHighlightedDocument(highlighter, "typescript", theme);
39 const container = document.createElement("div");
40 const root = createRoot(container);
41 let firstLine: Element | null = null;
42 for (let end = 0; end <= code.length; end++) {
43 const tree = highlight(code.slice(0, end));
44 await act(async () => root.render(<HighlightedCodeLines root={tree} />));
45 expect(normalizedHtml(container.innerHTML)).toBe(normalizedHtml(toHtml(tree)));
46 if (end > code.indexOf("\n")) {
47 firstLine ??= container.querySelector("code > .line");
48 expect(container.querySelector("code > .line")).toBe(firstLine);
49 }
50 }
51 expect(container.querySelector("img")).toBeNull();
52 await act(async () => root.unmount());
53 }
54});