The best way to control Claude Code, Codex and more from any computer or phone

main
ts 63 lines 2 KB
Raw
1 import { createHighlighterCore, type HighlighterCore } from "shiki/core";
2 import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
3 import { vscode } from "../theme.ts";
4
5 /** One colour per character of the source (newlines included). */
6 export type Colors = string[];
7
8 const languages: Record<string, string> = {
9 ts: "typescript",
10 tsx: "tsx",
11 js: "javascript",
12 json: "json",
13 html: "html",
14 css: "css",
15 };
16
17 export const languageOf = (file: string): string | undefined =>
18 languages[file.split(".").pop() ?? ""];
19
20 export const languageLabel = (file: string): string =>
21 ({
22 typescript: "TypeScript",
23 tsx: "TypeScript JSX",
24 javascript: "JavaScript",
25 json: "JSON",
26 html: "HTML",
27 css: "CSS",
28 })[languageOf(file) ?? ""] ?? "Plain Text";
29
30 let highlighter: Promise<HighlighterCore> | undefined;
31 const getHighlighter = () =>
32 (highlighter ??= createHighlighterCore({
33 themes: [import("shiki/themes/dark-plus.mjs")],
34 langs: [
35 import("shiki/langs/typescript.mjs"),
36 import("shiki/langs/tsx.mjs"),
37 import("shiki/langs/javascript.mjs"),
38 import("shiki/langs/json.mjs"),
39 import("shiki/langs/html.mjs"),
40 import("shiki/langs/css.mjs"),
41 ],
42 engine: createJavaScriptRegexEngine(),
43 }));
44
45 /** Per-character colours of `code` in VS Code's Dark+ token colours. */
46 export const highlight = async (file: string, code: string): Promise<Colors> => {
47 const lang = languageOf(file);
48 if (!lang) return Array.from(code, () => vscode.fg);
49 const { tokens } = (await getHighlighter()).codeToTokens(code, {
50 lang,
51 theme: "dark-plus",
52 });
53 const colors: Colors = [];
54 tokens.forEach((line, index) => {
55 for (const token of line) {
56 for (let i = 0; i < token.content.length; i++) colors.push(token.color ?? vscode.fg);
57 }
58 if (index < tokens.length - 1) colors.push(vscode.fg);
59 });
60 // Shiki normalises line endings; pad defensively so indexes always resolve.
61 while (colors.length < code.length) colors.push(vscode.fg);
62 return colors;
63 };