Open History to see the last commit
1import { Editor } from "@tiptap/core";
2import type { EditorView } from "@tiptap/pm/view";
3import StarterKit from "@tiptap/starter-kit";
4import { afterEach, describe, expect, it, vi } from "vite-plus/test";
5
6import { ComposerCodeBlockExtension } from "~/composer-rich-text-doc";
7import type { DiffThemeName } from "~/lib/diffRendering";
8import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
9
10import {
11 composerCodeBlockHighlight,
12 MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH,
13 shouldHighlightCodeBlock,
14 tokenizeBlock,
15} from "./composerCodeBlockHighlight";
16
17vi.mock("~/lib/syntaxHighlighting", () => ({ getSyntaxHighlighterPromise: vi.fn() }));
18
19const THEME = "github-dark" as DiffThemeName;
20
21function fakeHighlighter(colorFor: (content: string) => string | undefined) {
22 return {
23 codeToTokens(code: string) {
24 return {
25 tokens: code.split(/\r?\n/).map((line) =>
26 line
27 .split(/(\s+)/)
28 .filter((part) => part.length > 0)
29 .map((content) => ({ content, color: colorFor(content) })),
30 ),
31 };
32 },
33 } as unknown as Parameters<typeof tokenizeBlock>[0];
34}
35
36describe("composer code block highlighting", () => {
37 it("maps token offsets to positions within the block text", () => {
38 const highlighter = fakeHighlighter((content) => (content === "const" ? "#ff0000" : undefined));
39
40 const decorations = tokenizeBlock(highlighter, "const answer = 42", "ts", THEME);
41
42 expect(decorations).toEqual([{ from: 0, to: 5, color: "#ff0000" }]);
43 });
44
45 it("accounts for the newline between lines", () => {
46 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
47
48 const decorations = tokenizeBlock(highlighter, "one\ntwo", "ts", THEME);
49
50 expect(decorations).toEqual([{ from: 4, to: 7, color: "#00ff00" }]);
51 });
52
53 it("accounts for both characters of a CRLF line break", () => {
54 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
55
56 const decorations = tokenizeBlock(highlighter, "one\r\ntwo", "ts", THEME);
57
58 expect(decorations).toEqual([{ from: 5, to: 8, color: "#00ff00" }]);
59 });
60
61 it("skips whitespace-only tokens so indentation is not decorated", () => {
62 const highlighter = fakeHighlighter(() => "#0000ff");
63
64 const decorations = tokenizeBlock(highlighter, " indented", "ts", THEME);
65
66 expect(decorations).toEqual([{ from: 2, to: 10, color: "#0000ff" }]);
67 });
68
69 it("falls back to plain text when the grammar throws", () => {
70 const throwing = {
71 codeToTokens() {
72 throw new Error("unsupported language");
73 },
74 } as unknown as Parameters<typeof tokenizeBlock>[0];
75
76 expect(tokenizeBlock(throwing, "const answer = 42", "nope", THEME)).toEqual([]);
77 });
78});
79
80describe("the highlighting size cap", () => {
81 it("highlights a fence up to the cap", () => {
82 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH))).toBe(true);
83 });
84
85 it("leaves a fence past the cap plain", () => {
86 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH + 1))).toBe(false);
87 });
88});
89
90describe("a highlighter that fails to load", () => {
91 afterEach(() => {
92 vi.unstubAllGlobals();
93 });
94
95 it("still repaints the blocks whose highlighter loaded", async () => {
96 vi.mocked(getSyntaxHighlighterPromise).mockImplementation((language) =>
97 language === "ts"
98 ? Promise.resolve(fakeHighlighter(() => "#ff0000"))
99 : Promise.reject(new Error("Shiki failed to initialize")),
100 );
101 const editor = new Editor({
102 extensions: [
103 StarterKit.configure({ codeBlock: false, trailingNode: false }),
104 ComposerCodeBlockExtension,
105 composerCodeBlockHighlight({ resolveTheme: () => THEME }),
106 ],
107 content: {
108 type: "doc",
109 content: [
110 { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text: "a" }] },
111 { type: "codeBlock", attrs: { language: "py" }, content: [{ type: "text", text: "b" }] },
112 ],
113 },
114 });
115 // The plugin watches <html> for theme changes; the unit suite has no DOM.
116 vi.stubGlobal("document", { documentElement: {} });
117 vi.stubGlobal(
118 "MutationObserver",
119 class {
120 observe() {}
121 disconnect() {}
122 },
123 );
124 // ProseMirror names each plugin after its key, though it does not type it.
125 const plugin = editor.extensionManager.plugins.find((candidate) =>
126 (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),
127 );
128 const repainted = new Promise<void>((resolve) => {
129 const view = {
130 get state() {
131 return editor.state;
132 },
133 dispatch: () => resolve(),
134 } as unknown as EditorView;
135 plugin?.spec.view?.(view);
136 });
137
138 await expect(repainted).resolves.toBeUndefined();
139 });
140});