Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useHighlightedCode.test.tsx

189 lines6.6 KB

1import { act, useLayoutEffect } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4​
5import type { MarkdownCodeHighlighter } from "./SelectableMarkdownText.types";
6import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
7​
8type Deferred = {
9 readonly code: string;
10 readonly resolve: (tokens: HighlightedCode) => void;
11};
12​
13/** One colored line per newline-separated line, so a line's color proves where it came from. */
14function tokensFor(code: string, color: string): HighlightedCode {
15 return code.split("\n").map((content) => [{ content, color, fontStyle: 0 }]);
17​
18function lineText(tokens: HighlightedCode | null): string | null {
19 return tokens?.map((line) => line.map((token) => token.content).join("")).join("\n") ?? null;
21​
22function lineColors(tokens: HighlightedCode | null): ReadonlyArray<string | null> {
23 return tokens?.map((line) => line[0]?.color ?? null) ?? [];
25​
26const deferred: Deferred[] = [];
27const readResults = new Map<string, HighlightedCode>();
28let renders = 0;
29let result: HighlightedCode | null = null;
30let root: Root;
31​
32const highlightCode: MarkdownCodeHighlighter = Object.assign(
33 vi.fn(
34 (input: { code: string }) =>
35 new Promise<HighlightedCode>((resolve) => {
36 deferred.push({ code: input.code, resolve });
37 }),
38 ),
39 {
40 read: vi.fn((input: { code: string }) => readResults.get(input.code)),
41 },
42);
43​
44function Probe(props: {
45 readonly code: string;
46 readonly language?: string;
47 readonly theme?: "light" | "dark";
48}) {
49 const tokens = useHighlightedCode(
50 props.code,
51 props.language ?? "ts",
52 props.theme ?? "dark",
53 highlightCode,
54 );
55 useLayoutEffect(() => {
56 renders += 1;
57 result = tokens;
58 });
59 return null;
61​
62async function render(props: Parameters<typeof Probe>[0]) {
63 await act(() => root.render(<Probe {...props} />));
65​
66async function resolveAsync(index: number, color: string) {
67 const pending = deferred[index];
68 if (!pending) throw new Error(`no pending highlight at ${index}`);
69 await act(async () => {
70 pending.resolve(tokensFor(pending.code, color));
71 });
73​
74beforeEach(async () => {
75 // The probe has no DOM output, but ReactDOM needs an event target.
76 const document = {
77 nodeType: 9,
78 addEventListener() {},
79 removeEventListener() {},
80 };
81 const container = {
82 nodeType: 1,
83 tagName: "DIV",
84 namespaceURI: "http://www.w3.org/1999/xhtml",
85 ownerDocument: document,
86 addEventListener() {},
87 removeEventListener() {},
88 };
89 vi.stubGlobal("document", document);
90 vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
91 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
92 deferred.length = 0;
93 readResults.clear();
94 renders = 0;
95 result = null;
96 vi.mocked(highlightCode).mockClear();
97 vi.mocked(highlightCode.read!).mockClear();
98 root = createRoot(container as unknown as HTMLElement);
99});
100​
101afterEach(async () => {
102 await act(() => root.unmount());
103 vi.unstubAllGlobals();
104});
105​
106// Every test uses a distinct language so the module-level token cache from an
107// earlier test can never satisfy a later one.
108describe("useHighlightedCode", () => {
109 it("keeps colors from the latest synchronous read when a later read misses", async () => {
110 const language = "sync-baseline";
111 await render({ code: "a", language });
112 expect(result).toBeNull();
113 await resolveAsync(0, "async");
114 expect(lineColors(result)).toEqual(["async"]);
115​
116 readResults.set("a\nb", tokensFor("a\nb", "sync-1"));
117 readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync-2"));
118 const rendersBeforeAppends = renders;
119 await render({ code: "a\nb", language });
120 await render({ code: "a\nb\nc", language });
121 expect(lineColors(result)).toEqual(["sync-2", "sync-2", "sync-2"]);
122 // A synchronous hit is one render per append: no state update, no highlighter call.
123 expect(renders - rendersBeforeAppends).toBe(2);
124 expect(highlightCode).toHaveBeenCalledTimes(1);
125​
126 await render({ code: "a\nb\nc\nd", language });
127 expect(highlightCode).toHaveBeenCalledTimes(2);
128 expect(lineText(result)).toBe("a\nb\nc\nd");
129 // Lines before the previous code's final newline are the completed ones.
130 expect(lineColors(result)).toEqual(["sync-2", "sync-2", null, null]);
131​
132 await resolveAsync(1, "async-2");
133 expect(lineColors(result)).toEqual(["async-2", "async-2", "async-2", "async-2"]);
134 });
135​
136 it("does not show obsolete text after a non-append edit", async () => {
137 const language = "non-append";
138 await render({ code: "a\nb", language });
139 await resolveAsync(0, "async");
140 readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
141 await render({ code: "a\nb\nc", language });
142 expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
143​
144 await render({ code: "x\nb\nc", language });
145 expect(result).toBeNull();
146 await resolveAsync(1, "async-2");
147 expect(lineText(result)).toBe("x\nb\nc");
148 });
149​
150 it("never reuses colors across a language or theme change", async () => {
151 const language = "theme-change";
152 await render({ code: "a\nb", language });
153 await resolveAsync(0, "async");
154 readResults.set("a\nb\nc", tokensFor("a\nb\nc", "sync"));
155 await render({ code: "a\nb\nc", language });
156 expect(lineColors(result)).toEqual(["sync", "sync", "sync"]);
157​
158 await render({ code: "a\nb\nc\nd", language, theme: "light" });
159 expect(result).toBeNull();
160 await render({ code: "a\nb\nc\nd", language: `${language}-other` });
161 expect(result).toBeNull();
162 });
163​
164 it("ignores an asynchronous completion that is older than the current code", async () => {
165 const language = "stale-async";
166 await render({ code: "a\nb", language });
167 await resolveAsync(0, "async");
168​
169 await render({ code: "a\nb\nc", language });
170 expect(deferred).toHaveLength(2);
171 expect(lineColors(result)).toEqual(["async", null, null]);
172​
173 readResults.set("a\nb\nc\nd", tokensFor("a\nb\nc\nd", "sync"));
174 await render({ code: "a\nb\nc\nd", language });
175 expect(lineColors(result)).toEqual(["sync", "sync", "sync", "sync"]);
176​
177 await render({ code: "a\nb\nc\nd\ne", language });
178 expect(deferred).toHaveLength(3);
179 expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
180​
181 // The older request finishes after newer synchronous results exist.
182 await resolveAsync(1, "stale");
183 expect(lineText(result)).toBe("a\nb\nc\nd\ne");
184 expect(lineColors(result)).toEqual(["sync", "sync", "sync", null, null]);
185​
186 await resolveAsync(2, "async-3");
187 expect(lineColors(result)).toEqual(["async-3", "async-3", "async-3", "async-3", "async-3"]);
188 });
189});