Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import { embeddedScripts } from "../../lib/embeddedScripts";
4import { keyedLines, withEmbeddedScripts, wordsOf } from "./HighlightedTokens";
5
6function tokensOf(...contents: string[]) {
7 let offset = 0;
8 return contents.map((content) => {
9 const token = { content, offset };
10 offset += content.length;
11 return token;
12 });
13}
14
15function shape(parts: ReturnType<typeof wordsOf>) {
16 return parts.map((part) =>
17 typeof part === "string" ? part : part.pieces.map((piece) => piece.text).join(""),
18 );
19}
20
21describe("wordsOf", () => {
22 it.each([
23 [["echo", " ", '"', "$HOME", "/${", "PATH", "%%:*", '}"'], 'echo "$HOME/${PATH%%:*}"'],
24 [["rsync", " ", "-a", " ", "--exclude", " ", "build"], "rsync -a --exclude build"],
25 [["git", " && ", "echo", " ", '"two words"', "; "], 'git && echo "two words"; '],
26 [[" ", "indented"], " indented"],
27 [[], ""],
28 ])("wraps the same words as the plain-text fallback: %j", (contents, line) => {
29 expect(shape(wordsOf(tokensOf(...contents)))).toEqual(
30 line.split(/(\s+)/u).filter((part) => part !== ""),
31 );
32 });
33
34 it("keeps each piece's own token so colors survive regrouping", () => {
35 const [word] = wordsOf(tokensOf('"', "$HOME", '"'));
36 expect(
37 typeof word === "string" ? null : word?.pieces.map((piece) => piece.token.content),
38 ).toEqual(['"', "$HOME", '"']);
39 });
40});
41
42describe("keyedLines", () => {
43 it.each([
44 "git status\ngit diff",
45 "Get-ChildItem\r\nWrite-Output done\r\n",
46 "mixed\r\nendings\n\nlone \r stays",
47 ])("renders the same text as the source: %j", (code) => {
48 // Shiki splits lines on \r?\n and drops the ending from the tokens.
49 const lines = code.split(/\r?\n/u).map((line) => tokensOf(line));
50 const rendered = keyedLines(code, lines)
51 .map(({ tokens, ending }) => tokens.map((token) => token.content).join("") + ending)
52 .join("");
53 expect(rendered).toBe(code);
54 });
55
56 it("keys empty lines apart", () => {
57 const code = "a\r\n\r\n\r\nb";
58 const keys = keyedLines(
59 code,
60 code.split(/\r?\n/u).map((line) => tokensOf(line)),
61 ).map((line) => line.key);
62 expect(new Set(keys).size).toBe(keys.length);
63 });
64});
65
66describe("withEmbeddedScripts", () => {
67 function tokenize(text: string, language: string) {
68 if (language === "unknown") throw new Error("Language not found");
69 let lineStart = 0;
70 return text.split(/\r?\n/u).map((line) => {
71 const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
72 content: match[0],
73 offset: lineStart + match.index,
74 color: language,
75 }));
76 lineStart +=
77 line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
78 return tokens;
79 });
80 }
81
82 function colorsOf(code: string, scripts = embeddedScripts(code)) {
83 const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
84 expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
85 code.replaceAll("\r\n", "\n"),
86 );
87 return lines.flat().map((token) => [token.content, token.color]);
88 }
89
90 it("colors each nested script with its own grammar, keeping the text", () => {
91 expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
92 [`bash -lc "python3 -c '`, "shellscript"],
93 ["print(1)", "python"],
94 [`'"`, "shellscript"],
95 ]);
96 });
97
98 it("colors an escape sequence like the character it spells", () => {
99 expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
100 `print(\\"x\\")`,
101 "python",
102 ]);
103 });
104
105 it("keeps the surrounding colors where a grammar is missing", () => {
106 const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
107 const [script] = embeddedScripts(code);
108 const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
109 colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
110 expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
111 });
112});