// @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from "vitest"; import { CODE_SNAPSHOT_CSS, materializeSnapshotCloneLineNumbers, renderCodeSnapshotHtml, savePngDataUrlToFile, snapshotElementToPng } from "@/lib/codeSnapshot/codeSnapshot"; import { LEGACY_WEBVIEW_CLASS } from "@/lib/ui/legacyWebView"; const { createCodeHighlighter, highlightCode, toPng, isTauriRuntime, save, writeFile } = vi.hoisted(() => { const highlightCode = vi.fn((content: string, _lang: string) => `${content}`); return { createCodeHighlighter: vi.fn(async () => highlightCode), highlightCode, toPng: vi.fn(), isTauriRuntime: vi.fn(), save: vi.fn(), writeFile: vi.fn(), }; }); vi.mock("@/lib/ai/aiCodeHighlighter", () => ({ createAiShikiBlockCodeHighlighter: createCodeHighlighter, })); vi.mock("dom-to-image-more", () => ({ default: { toPng }, })); vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime, })); vi.mock("@tauri-apps/plugin-dialog", () => ({ save })); vi.mock("@tauri-apps/plugin-fs", () => ({ writeFile })); beforeEach(() => { createCodeHighlighter.mockResolvedValue(highlightCode); highlightCode.mockClear(); highlightCode.mockImplementation((content: string) => `${content}`); }); describe("renderCodeSnapshotHtml", () => { it("falls back to safe text when the code highlighter cannot initialize", async () => { createCodeHighlighter.mockRejectedValueOnce(new SyntaxError("Invalid regular expression: invalid group specifier name")); const html = await renderCodeSnapshotHtml({ code: "SELECT <初始化失败>", lang: "sql" }, { appearance: "light" }); expect(html).toContain('SELECT <初始化失败>'); }); it("falls back to safe line-preserving text when legacy WebKit cannot compile highlighting regexes", async () => { highlightCode.mockImplementationOnce(() => { throw new SyntaxError("Invalid regular expression: invalid group specifier name"); }); const html = await renderCodeSnapshotHtml({ code: `SELECT '<用户>&" 😀'\r\n-- 第二行\n`, lang: "sql" }, { appearance: "light" }); expect(html).toContain('SELECT '<用户>&" 😀'-- 第二行'); expect(html).not.toContain("<用户>"); expect(html.match(/class="line"/g)).toHaveLength(3); }); it("renders large fallback selections with one highlighter attempt", async () => { const code = Array.from({ length: 5_000 }, (_, index) => `SELECT ${index}`).join("\n"); highlightCode.mockImplementationOnce(() => { throw new SyntaxError("Invalid regular expression: invalid group specifier name"); }); const html = await renderCodeSnapshotHtml({ code, lang: "sql" }, { appearance: "dark" }); expect(highlightCode).toHaveBeenCalledOnce(); expect(html.match(/class="line"/g)).toHaveLength(5_000); }); it("renders a self-contained snapshot with embedded styles", async () => { const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "dark" }); expect(html).toContain("