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

composerCodeBlockHighlight.test.ts

152 lines5.4 KB

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​
21/**
22 * Stands in for the Shiki highlighter so the offset arithmetic can be checked
23 * without loading a real grammar. Splits each line into whitespace-delimited
24 * tokens, which is enough shape for the flattening logic under test.
25 */
26function fakeHighlighter(colorFor: (content: string) => string | undefined) {
27 return {
28 codeToTokens(code: string) {
29 return {
30 tokens: code.split(/\r?\n/).map((line) =>
31 line
32 .split(/(\s+)/)
33 .filter((part) => part.length > 0)
34 .map((content) => ({ content, color: colorFor(content) })),
35 ),
36 };
37 },
38 } as unknown as Parameters<typeof tokenizeBlock>[0];
40​
41describe("composer code block highlighting", () => {
42 it("maps token offsets to positions within the block text", () => {
43 const highlighter = fakeHighlighter((content) => (content === "const" ? "#ff0000" : undefined));
44​
45 const decorations = tokenizeBlock(highlighter, "const answer = 42", "ts", THEME);
46​
47 expect(decorations).toEqual([{ from: 0, to: 5, color: "#ff0000" }]);
48 });
49​
50 it("accounts for the newline between lines", () => {
51 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
52​
53 const decorations = tokenizeBlock(highlighter, "one\ntwo", "ts", THEME);
54​
55 // "one" is 3 characters, then the newline, so "two" starts at 4.
56 expect(decorations).toEqual([{ from: 4, to: 7, color: "#00ff00" }]);
57 });
58​
59 it("accounts for both characters of a CRLF line break", () => {
60 const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));
61​
62 const decorations = tokenizeBlock(highlighter, "one\r\ntwo", "ts", THEME);
63​
64 expect(decorations).toEqual([{ from: 5, to: 8, color: "#00ff00" }]);
65 });
66​
67 it("skips whitespace-only tokens so indentation is not decorated", () => {
68 const highlighter = fakeHighlighter(() => "#0000ff");
69​
70 const decorations = tokenizeBlock(highlighter, " indented", "ts", THEME);
71​
72 expect(decorations).toEqual([{ from: 2, to: 10, color: "#0000ff" }]);
73 });
74​
75 it("falls back to plain text when the grammar throws", () => {
76 const throwing = {
77 codeToTokens() {
78 throw new Error("unsupported language");
79 },
80 } as unknown as Parameters<typeof tokenizeBlock>[0];
81​
82 expect(tokenizeBlock(throwing, "const answer = 42", "nope", THEME)).toEqual([]);
83 });
84});
85​
86describe("the highlighting size cap", () => {
87 // Each keystroke re-tokenizes the whole fence on the main thread; past a
88 // few hundred lines that stalls typing, so large fences stay plain.
89 it("highlights a fence up to the cap", () => {
90 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH))).toBe(true);
91 });
92​
93 it("leaves a fence past the cap plain", () => {
94 expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH + 1))).toBe(false);
95 });
96});
97​
98describe("a highlighter that fails to load", () => {
99 afterEach(() => {
100 vi.unstubAllGlobals();
101 });
102​
103 /**
104 * Shiki can fail to initialize at all. The blocks it could not reach stay
105 * plain, the ones it could are still painted, and nothing is left rejected.
106 */
107 it("still repaints the blocks whose highlighter loaded", async () => {
108 vi.mocked(getSyntaxHighlighterPromise).mockImplementation((language) =>
109 language === "ts"
110 ? Promise.resolve(fakeHighlighter(() => "#ff0000"))
111 : Promise.reject(new Error("Shiki failed to initialize")),
112 );
113 const editor = new Editor({
114 extensions: [
115 StarterKit.configure({ codeBlock: false, trailingNode: false }),
116 ComposerCodeBlockExtension,
117 composerCodeBlockHighlight({ resolveTheme: () => THEME }),
118 ],
119 content: {
120 type: "doc",
121 content: [
122 { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text: "a" }] },
123 { type: "codeBlock", attrs: { language: "py" }, content: [{ type: "text", text: "b" }] },
124 ],
125 },
126 });
127 // The plugin watches <html> for theme changes; the unit suite has no DOM.
128 vi.stubGlobal("document", { documentElement: {} });
129 vi.stubGlobal(
130 "MutationObserver",
131 class {
132 observe() {}
133 disconnect() {}
134 },
135 );
136 // ProseMirror names each plugin after its key, though it does not type it.
137 const plugin = editor.extensionManager.plugins.find((candidate) =>
138 (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),
139 );
140 const repainted = new Promise<void>((resolve) => {
141 const view = {
142 get state() {
143 return editor.state;
144 },
145 dispatch: () => resolve(),
146 } as unknown as EditorView;
147 plugin?.spec.view?.(view);
148 });
149​
150 await expect(repainted).resolves.toBeUndefined();
151 });
152});