Open History to see the last commit
1import { Editor } from "@tiptap/core";
2import { EditorState, type Plugin, type Transaction } from "@tiptap/pm/state";
3import type { DecorationSet, EditorView } from "@tiptap/pm/view";
4import StarterKit from "@tiptap/starter-kit";
5import { afterEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test";
6
7import { ComposerCodeBlockExtension } from "~/composer-rich-text-doc";
8import type { DiffThemeName } from "~/lib/diffRendering";
9import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
10
11import {
12 composerCodeBlockHighlight,
13 MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH,
14 shouldHighlightCodeBlock,
15 tokenizeBlock,
16} from "./composerCodeBlockHighlight";
17
18vi.mock("~/lib/syntaxHighlighting", () => ({ getSyntaxHighlighterPromise: vi.fn() }));
19
20const THEME = "pierre-dark" as DiffThemeName;
21
22function fakeHighlighter(colorFor: (content: string) => string | undefined) {
23 return {
24 codeToTokens(code: string) {
25 return {
26 tokens: code.split(/\r?\n/).map((line) =>
27 line
28 .split(/(\s+)/)
29 .filter((part) => part.length > 0)
30 .map((content) => ({ content, color: colorFor(content) })),
31 ),
32 };
33 },
34 } as unknown as Parameters<typeof tokenizeBlock>[0];
35}
36
37describe("composer code block highlighting", () => {
38 it("maps token offsets to positions within the block text", () => {
39 const highlighter = fakeHighlighter((content) => (content === "const" ? "#ff0000" : undefined));
40
41 const decorations = tokenizeBlock(highlighter, "const answer = 42", "ts", THEME);
42
43 expect(decorations).toEqual([{ from: 0, to: 5, color: "#ff0000" }]);
44 });
45
46 it("accounts for the newline between lines", () => {
47 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
48
49 const decorations = tokenizeBlock(highlighter, "one\ntwo", "ts", THEME);
50
51 expect(decorations).toEqual([{ from: 4, to: 7, color: "#00ff00" }]);
52 });
53
54 it("accounts for both characters of a CRLF line break", () => {
55 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
56
57 const decorations = tokenizeBlock(highlighter, "one\r\ntwo", "ts", THEME);
58
59 expect(decorations).toEqual([{ from: 5, to: 8, color: "#00ff00" }]);
60 });
61
62 it("skips whitespace-only tokens so indentation is not decorated", () => {
63 const highlighter = fakeHighlighter(() => "#0000ff");
64
65 const decorations = tokenizeBlock(highlighter, " indented", "ts", THEME);
66
67 expect(decorations).toEqual([{ from: 2, to: 10, color: "#0000ff" }]);
68 });
69
70 it("falls back to plain text when the grammar throws", () => {
71 const throwing = {
72 codeToTokens() {
73 throw new Error("unsupported language");
74 },
75 } as unknown as Parameters<typeof tokenizeBlock>[0];
76
77 expect(tokenizeBlock(throwing, "const answer = 42", "nope", THEME)).toEqual([]);
78 });
79});
80
81describe("the highlighting size cap", () => {
82 it("highlights a fence up to the cap", () => {
83 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH))).toBe(true);
84 });
85
86 it("leaves a fence past the cap plain", () => {
87 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH + 1))).toBe(false);
88 });
89});
90
91describe("a highlighter that fails to load", () => {
92 afterEach(() => {
93 vi.unstubAllGlobals();
94 });
95
96 it("still repaints the blocks whose highlighter loaded", async () => {
97 vi.mocked(getSyntaxHighlighterPromise).mockImplementation((language) =>
98 language === "ts"
99 ? Promise.resolve(fakeHighlighter(() => "#ff0000"))
100 : Promise.reject(new Error("Shiki failed to initialize")),
101 );
102 const editor = new Editor({
103 extensions: [
104 StarterKit.configure({ codeBlock: false, trailingNode: false }),
105 ComposerCodeBlockExtension,
106 composerCodeBlockHighlight({ resolveTheme: () => THEME }),
107 ],
108 content: {
109 type: "doc",
110 content: [
111 { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text: "a" }] },
112 { type: "codeBlock", attrs: { language: "py" }, content: [{ type: "text", text: "b" }] },
113 ],
114 },
115 });
116 // The plugin watches <html> for theme changes; the unit suite has no DOM.
117 vi.stubGlobal("document", { documentElement: {} });
118 vi.stubGlobal(
119 "MutationObserver",
120 class {
121 observe() {}
122 disconnect() {}
123 },
124 );
125 // ProseMirror names each plugin after its key, though it does not type it.
126 const plugin = editor.extensionManager.plugins.find((candidate) =>
127 (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),
128 );
129 const repainted = new Promise<void>((resolve) => {
130 const view = {
131 get state() {
132 return editor.state;
133 },
134 dispatch: () => resolve(),
135 } as unknown as EditorView;
136 plugin?.spec.view?.(view);
137 });
138
139 await expect(repainted).resolves.toBeUndefined();
140 });
141});
142
143describe("highlighting edited fences", () => {
144 afterEach(() => {
145 vi.useRealTimers();
146 vi.unstubAllGlobals();
147 });
148
149 async function mountFence(text: string, resolveTheme = () => THEME) {
150 vi.useFakeTimers();
151 const highlighter = fakeHighlighter((content) =>
152 content.startsWith("x") ? "#ff0000" : undefined,
153 );
154 const tokenize = vi.spyOn(highlighter, "codeToTokens");
155 vi.mocked(getSyntaxHighlighterPromise).mockResolvedValue(highlighter);
156 const editor = new Editor({
157 extensions: [
158 StarterKit.configure({ codeBlock: false, trailingNode: false }),
159 ComposerCodeBlockExtension,
160 composerCodeBlockHighlight({ resolveTheme }),
161 ],
162 content: {
163 type: "doc",
164 content: [
165 { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text }] },
166 ],
167 },
168 });
169 vi.stubGlobal("document", { documentElement: {} });
170 vi.stubGlobal(
171 "MutationObserver",
172 class {
173 observe() {}
174 disconnect() {}
175 },
176 );
177 const plugin = editor.extensionManager.plugins.find((candidate) =>
178 (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),
179 ) as Plugin<DecorationSet>;
180 // A headless editor holds no plugins in its state, so give this one its own.
181 let state = EditorState.create({ doc: editor.state.doc, plugins: [plugin] });
182 // Like a real view, every dispatch updates the plugin's view.
183 let pluginView: ReturnType<NonNullable<typeof plugin.spec.view>> | undefined;
184 const view = {
185 get state() {
186 return state;
187 },
188 dispatch: (transaction: Transaction) => {
189 const previous = state;
190 state = state.apply(transaction);
191 pluginView?.update?.(view, previous);
192 },
193 } as unknown as EditorView;
194 pluginView = plugin.spec.view!(view);
195 onTestFinished(() => {
196 pluginView?.destroy?.();
197 editor.destroy();
198 });
199 await vi.advanceTimersByTimeAsync(0);
200 return {
201 tokenize,
202 ranges: () =>
203 plugin
204 .getState(state)!
205 .find()
206 .map(({ from, to }) => [from, to]),
207 edit: async (change: (transaction: Transaction) => Transaction) => {
208 view.dispatch(change(state.tr));
209 await vi.advanceTimersByTimeAsync(0);
210 },
211 colored: () =>
212 plugin
213 .getState(state)!
214 .find()
215 .map((decoration) => state.doc.textBetween(decoration.from, decoration.to)),
216 };
217 }
218
219 it("maps colors while typing above 2,000 characters and refreshes 300 ms after the last edit", async () => {
220 const fence = await mountFence(`x ${"y".repeat(1_999)}`);
221 expect(fence.tokenize).toHaveBeenCalledTimes(1);
222
223 await fence.edit((tr) => tr.insertText("x ", 1));
224 await vi.advanceTimersByTimeAsync(250);
225 await fence.edit((tr) => tr.insertText("y ", 1));
226 await vi.advanceTimersByTimeAsync(299);
227
228 expect(fence.tokenize).toHaveBeenCalledTimes(1);
229 expect(fence.colored()).toEqual(["x"]);
230 expect(fence.ranges()).toEqual([[5, 6]]);
231
232 await vi.advanceTimersByTimeAsync(1);
233
234 expect(fence.tokenize).toHaveBeenCalledTimes(2);
235 expect(fence.colored()).toEqual(["x", "x"]);
236 });
237
238 it("ignores a pending highlight when its text is edited away and restored", async () => {
239 const fence = await mountFence(`x ${"y".repeat(1_999)}`);
240 const staleHighlighter = fakeHighlighter(() => "#00ff00");
241 const staleTokenize = vi.spyOn(staleHighlighter, "codeToTokens");
242 let finishLoading!: () => void;
243 vi.mocked(getSyntaxHighlighterPromise).mockImplementationOnce(
244 () =>
245 new Promise((resolve) => {
246 finishLoading = () => resolve(staleHighlighter);
247 }),
248 );
249
250 await fence.edit((tr) => tr.insertText("x ", 1));
251 await vi.advanceTimersByTimeAsync(300);
252 await fence.edit((tr) => tr.insertText("y ", 1));
253 await fence.edit((tr) => tr.delete(1, 3));
254 finishLoading();
255 await vi.advanceTimersByTimeAsync(0);
256
257 expect(staleTokenize).not.toHaveBeenCalled();
258 expect(fence.colored()).toEqual(["x"]);
259 await vi.advanceTimersByTimeAsync(300);
260 expect(fence.tokenize).toHaveBeenCalledTimes(2);
261 expect(fence.colored()).toEqual(["x", "x"]);
262 });
263
264 it("refreshes a long fence immediately when the theme changes during a pending edit", async () => {
265 let theme = THEME;
266 const fence = await mountFence(`x ${"y".repeat(1_999)}`, () => theme);
267 await fence.edit((tr) => tr.insertText("x ", 1));
268
269 theme = "pierre-light";
270 await fence.edit((tr) => tr.setMeta("theme", true));
271
272 expect(fence.tokenize).toHaveBeenCalledTimes(2);
273 expect(fence.tokenize).toHaveBeenLastCalledWith(expect.any(String), { lang: "ts", theme });
274 expect(fence.colored()).toEqual(["x", "x"]);
275 await vi.advanceTimersByTimeAsync(300);
276 expect(fence.tokenize).toHaveBeenCalledTimes(2);
277 });
278
279 it("refreshes immediately when an edit leaves the fence at 2,000 characters", async () => {
280 const fence = await mountFence(`x ${"y".repeat(1_996)}`);
281
282 await fence.edit((tr) => tr.insertText("x ", 1));
283
284 expect(fence.tokenize).toHaveBeenCalledTimes(2);
285 expect(fence.colored()).toEqual(["x", "x"]);
286 });
287
288 it("clips a split token to its fences without coloring the paragraph between them", async () => {
289 const fence = await mountFence("x".repeat(6_000));
290
291 await fence.edit((tr) =>
292 tr
293 .split(3_001)
294 .insert(
295 3_002,
296 tr.doc.type.schema.node("paragraph", null, [tr.doc.type.schema.text("plain")]),
297 ),
298 );
299
300 expect(fence.tokenize).toHaveBeenCalledTimes(1);
301 expect(fence.ranges()).toEqual([
302 [1, 3_001],
303 [3_010, 6_010],
304 ]);
305 expect(fence.colored()).toEqual(["x".repeat(3_000), "x".repeat(3_000)]);
306 });
307
308 it("clears retained colors when the new language highlighter fails to load", async () => {
309 const fence = await mountFence(`x ${"y".repeat(1_999)}`);
310 vi.mocked(getSyntaxHighlighterPromise).mockRejectedValue(new Error("Shiki failed to load"));
311
312 await fence.edit((tr) => tr.setNodeMarkup(0, undefined, { language: "py" }));
313 expect(fence.colored()).toEqual(["x"]);
314
315 await vi.advanceTimersByTimeAsync(300);
316
317 expect(fence.colored()).toEqual([]);
318 });
319});