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

syntaxHighlighting.test.ts

69 lines2.7 KB

1import { getFiletypeFromFileName } from "@pierre/diffs";
2import { expect, it, vi } from "vite-plus/test";
3​
4import { subscribeToThemeSyntax } from "../themePalette";
5import { getSyntaxHighlighterPromise } from "./syntaxHighlighting";
6import { DIFF_THEME_NAMES, resolveDiffThemeName } from "./diffRendering";
7​
8vi.mock(import("../themePalette"), async (original) => ({
9 ...(await original()),
10 getAppliedThemeSyntax: (appearance) =>
11 appearance === "dark"
12 ? { keyword: { color: "#ff00ff" }, foreground: { color: "#aabbcc" } }
13 : undefined,
14}));
15​
16it("highlights with the applied theme's syntax colors once they load", async () => {
17 const highlighter = await getSyntaxHighlighterPromise("typescript");
18 const loaded = new Promise<void>((resolve) => {
19 const unsubscribe = subscribeToThemeSyntax(() => {
20 unsubscribe();
21 resolve();
22 });
23 });
24 expect(resolveDiffThemeName("dark")).toBe(DIFF_THEME_NAMES.dark);
25 await loaded;
26 const theme = resolveDiffThemeName("dark");
27 const { tokens } = highlighter.codeToTokens("if (x) {}", { lang: "typescript", theme });
28 expect(tokens[0]?.[0]).toMatchObject({ content: "if ", color: "#ff00ff" });
29 expect(tokens[0]?.find((token) => token.content.includes("x"))?.color).toBe("#aabbcc");
30 expect(resolveDiffThemeName("light")).toBe(DIFF_THEME_NAMES.light);
31});
32​
33const SAMPLES = [
34 {
35 name: "assembly",
36 code: "mov eax, 42 ; answer\nret",
37 hints: [
38 "asm",
39 "assembly",
40 "s",
41 ...["asm", "ASM", "s", "S", "nasm", "NASM"].map((ext) => `src/start.${ext}`),
42 ],
43 },
44 {
45 name: "verilog",
46 code: "module top(input wire clk);\n reg [7:0] q; // count\nendmodule",
47 hints: ["verilog", "src/top.v", "src/defs.vh"],
48 },
49 {
50 name: "systemverilog",
51 code: "module top(input logic clk);\n always_ff @(posedge clk) q <= 8'd1; // count\nendmodule",
52 hints: ["systemverilog", "system-verilog", "src/top.sv", "src/defs.svh"],
53 },
54 {
55 name: "vhdl",
56 code: "entity top is\n port (clk : in std_logic); -- clock\nend entity;",
57 hints: ["vhdl", "src/top.vhd", "src/top.vhdl"],
58 },
59].flatMap(({ name, code, hints }) => hints.map((hint) => ({ name, code, hint })));
60​
61it.each(SAMPLES)("highlights $name in $hint", async ({ code, hint }) => {
62 const language = hint.includes("/") ? getFiletypeFromFileName(hint) : hint;
63 const highlighter = await getSyntaxHighlighterPromise(language);
64 for (const theme of Object.values(DIFF_THEME_NAMES)) {
65 const { tokens } = highlighter.codeToTokens(code, { lang: language, theme });
66 expect(tokens.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(code);
67 expect(new Set(tokens.flat().map((token) => token.color)).size).toBeGreaterThan(1);
68 }
69});