Files
2026-11-16 17:26:44 -08:00

66 lines
2.8 KiB
TypeScript

import { test, expect, describe } from "bun:test";
import { rehypeCodeHighlight } from "../src/lib/codeHighlight";
/**
* 抽屉 markdown 的代码高亮换掉了 rehype-highlight(见 lib/codeHighlight.ts 头注释)。
* 这里钉住它和旧插件对齐的那几条:只动 `pre > code`、显式语言才高亮、没标语言的块
* 仍挂 `hljs` 类(样式不变)、不认识的语言和 no-highlight 保留原文。
*/
type N = { type: string; tagName?: string; value?: string; properties?: Record<string, unknown>; children?: N[] };
const text = (value: string): N => ({ type: "text", value });
const code = (cls: string[] | undefined, body: string): N => ({
type: "element", tagName: "code", properties: cls ? { className: cls } : {}, children: [text(body)],
});
const pre = (c: N): N => ({ type: "element", tagName: "pre", properties: {}, children: [c] });
const root = (...children: N[]): N => ({ type: "root", children });
const run = (tree: N) => { rehypeCodeHighlight()(tree); return tree; };
const classes = (n: N) => n.properties?.className as string[] | undefined;
const hasSpans = (n: N) => (n.children ?? []).some((c) => c.type === "element" && c.tagName === "span");
describe("rehypeCodeHighlight", () => {
test("显式语言的围栏代码块被高亮", () => {
const c = code(["language-kotlin"], "fun main() { val x = 1 }");
run(root(pre(c)));
expect(classes(c)?.[0]).toBe("hljs");
expect(hasSpans(c)).toBe(true);
});
test("语言别名(kt / sh / objc / yml)随语法注册生效", () => {
for (const alias of ["kt", "sh", "objc", "yml", "ts", "diff"]) {
const c = code([`language-${alias}`], "a: 1\n+ b\nlet x = 1");
run(root(pre(c)));
expect(classes(c)).toContain("hljs");
}
const c = code(["language-sh"], "echo $HOME");
run(root(pre(c)));
expect(hasSpans(c)).toBe(true);
});
test("没标语言:不做自动识别,但挂 hljs 类(外观与以前一致)", () => {
const c = code(undefined, "const x = { a: 1 };");
run(root(pre(c)));
expect(classes(c)).toEqual(["hljs"]);
expect(c.children).toEqual([text("const x = { a: 1 };")]);
});
test("不认识的语言保留原文,不抛", () => {
const c = code(["language-brainfuck"], "+++[>+<-]");
expect(() => run(root(pre(c)))).not.toThrow();
expect(c.children).toEqual([text("+++[>+<-]")]);
});
test("no-highlight 跳过,连 hljs 类都不加", () => {
const c = code(["language-js", "no-highlight"], "let a");
run(root(pre(c)));
expect(classes(c)).toEqual(["language-js", "no-highlight"]);
});
test("行内 code(不在 pre 里)不动", () => {
const c = code(["language-js"], "let a");
const p: N = { type: "element", tagName: "p", properties: {}, children: [c] };
run(root(p));
expect(classes(c)).toEqual(["language-js"]);
});
});