Open History to see the last commit
1import { codeToTokens } from "@pierre/highlights";
2import { pierreDark, pierreLight } from "@pierre/highlights/themes";
3import { describe, expect, it, vi } from "vite-plus/test";
4
5import { resolveHighlightLanguage } from "./highlightLanguage";
6import { highlightCode, tokenizeCode } from "./highlights";
7
8vi.mock("expo", async () => {
9 const { createWasmHighlightsModule } = await import("./highlights.testing");
10 const highlights = createWasmHighlightsModule();
11 return { requireOptionalNativeModule: () => highlights };
12});
13
14describe("highlightCode", () => {
15 it("produces @pierre/highlights' own tokens and colors", () => {
16 const code = [
17 "/** 🎉 docs\r",
18 " */",
19 "export const greet = (name: string) => <b title={`hi ${name}`}>é</b>;",
20 "const multi = `first",
21 "second`; // done",
22 "",
23 ].join("\n");
24
25 for (const [scheme, theme] of [
26 ["light", pierreLight],
27 ["dark", pierreDark],
28 ] as const) {
29 const expected = codeToTokens(code, { lang: "tsx", theme }).tokens.map((line) =>
30 line.map((token) => ({
31 content: token.content,
32 color: token.color ?? null,
33 fontStyle: token.fontStyle ?? null,
34 })),
35 );
36 expect(highlightCode(code, "tsx", scheme)).toEqual(expected);
37 }
38 });
39
40 it("keeps an over-long line as one plain token", () => {
41 const longLine = `const data = "${"x".repeat(1_000)}";`;
42 const [first, second] = highlightCode(`let a = 1;\n${longLine}`, "typescript", "dark");
43
44 expect(first?.length).toBeGreaterThan(1);
45 expect(second).toEqual([{ content: longLine, color: null, fontStyle: null }]);
46 });
47});
48
49it("normalizes only requested lines from full-source records, including CRLF and a long comment opener", () => {
50 const code = `const first = 1;\r\n${" ".repeat(1_001)}/*\r\ninside\r\n*/\r\nconst last = 2;`;
51 const source = tokenizeCode(code, "typescript");
52 expect(source.byteLength).toBeGreaterThan(0);
53 for (let line = 0; line < 5; line++) {
54 expect(source.highlightLine(line, "dark")).toEqual(
55 highlightCode(code, "typescript", "dark")[line],
56 );
57 }
58 expect(source.highlightLine(2, "dark")?.[0]?.color).toBe("#737373");
59 expect(source.highlightLine(100, "dark")).toBeUndefined();
60});
61
62it.each([
63 "asm",
64 "assembly",
65 "s",
66 ...["asm", "ASM", "s", "S", "nasm", "NASM"].map((ext) => `src/start.${ext}`),
67])("highlights assembly in %s", (hint) => {
68 const language = resolveHighlightLanguage(
69 hint.includes("/") ? { path: hint } : { language: hint },
70 );
71 const code = "mov eax, 42 ; answer\nret";
72 for (const scheme of ["light", "dark"] as const) {
73 const tokens = highlightCode(code, language, scheme);
74 expect(tokens.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(code);
75 expect(new Set(tokens.flat().map((token) => token.color)).size).toBeGreaterThan(1);
76 }
77});