refactor(webui): unify code and diff highlighting (#6412)
* refactor(webui): unify code and diff highlighting Replace Prism with shared Highlights tokens and Pierre read-only diffs, retaining rare grammars through lazy Shiki and preserving source, copy, preview and diff controls. Restore single-session Composer ownership inside the conversation column while retaining the shared multi-pane footer. Keep the measured large-diff scroll regression explicit during review. * fix(webui): contain highlighting errors and retain diff selections Refs NAN-343 * test(webui): align pane fixtures after main rebase * chore(webui): update highlighting dependencies Keep grammar fallback coverage on a language that still requires Shiki, and align reading-size assertions with main.
This commit is contained in:
1 parent
f5c359476b
commit
3a37269f3f
44 files changed
+2261
-1072
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { normalizeCodeLanguage } from "./code-language";
|
||||
import type { CodeLine } from "./code-tokens";
|
||||
|
||||
export interface CodeHighlight {
|
||||
read(): CodeLine[];
|
||||
}
|
||||
|
||||
const MAX_CACHED_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_CACHE_ENTRIES = 16;
|
||||
const cache = new Map<string, CodeHighlight>();
|
||||
let sourceBytes = 0;
|
||||
|
||||
function cacheKey(source: string, language: string): string {
|
||||
return `${normalizeCodeLanguage(language)}\0${source}`;
|
||||
}
|
||||
|
||||
export function cachedCodeHighlight(source: string, language: string): CodeHighlight | undefined {
|
||||
const key = cacheKey(source, language);
|
||||
const resource = cache.get(key);
|
||||
if (resource) {
|
||||
cache.delete(key);
|
||||
cache.set(key, resource);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
export function discardCodeHighlight(source: string, language: string): void {
|
||||
const key = cacheKey(source, language);
|
||||
if (cache.delete(key)) sourceBytes -= key.length * 2;
|
||||
}
|
||||
|
||||
export function cacheCodeHighlight(source: string, language: string, resource: CodeHighlight): void {
|
||||
const key = cacheKey(source, language);
|
||||
const bytes = key.length * 2;
|
||||
if (bytes > MAX_CACHED_SOURCE_BYTES) return;
|
||||
discardCodeHighlight(source, language);
|
||||
while (cache.size >= MAX_CACHE_ENTRIES || sourceBytes + bytes > MAX_CACHED_SOURCE_BYTES) {
|
||||
const oldest = cache.keys().next().value!;
|
||||
cache.delete(oldest);
|
||||
sourceBytes -= oldest.length * 2;
|
||||
}
|
||||
cache.set(key, resource);
|
||||
sourceBytes += bytes;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createHighlighterCore } from "shiki/core";
|
||||
import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
|
||||
import { bundledLanguages } from "shiki/langs";
|
||||
|
||||
import { CODE_TEXTMATE_THEME, CODE_THEME_NAME } from "./code-theme";
|
||||
import type { CodeToken } from "./code-tokens";
|
||||
|
||||
let loaded: Awaited<ReturnType<typeof createHighlighterCore>> | undefined;
|
||||
const highlighter = createHighlighterCore({
|
||||
engine: createJavaScriptRegexEngine(), langs: [],
|
||||
themes: [CODE_TEXTMATE_THEME],
|
||||
}).then(engine => { loaded = engine; return engine; });
|
||||
|
||||
export function highlightGrammar(source: string, language: string): CodeToken[][] | Promise<CodeToken[][]> {
|
||||
const loader = Object.hasOwn(bundledLanguages, language) ? bundledLanguages[language as keyof typeof bundledLanguages] : undefined;
|
||||
if (!loader) return source.split("\n").map(content => [{ content }]);
|
||||
if (loaded?.getLoadedLanguages().includes(language)) return loaded.codeToTokens(source, { lang: language, theme: CODE_THEME_NAME }).tokens;
|
||||
return highlighter.then(async engine => {
|
||||
await engine.loadLanguage(loader);
|
||||
return engine.codeToTokens(source, { lang: language, theme: CODE_THEME_NAME }).tokens;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { codeToTokens, isSupportedLanguage } from "@pierre/highlights";
|
||||
|
||||
import { cacheCodeHighlight, cachedCodeHighlight, type CodeHighlight } from "./code-highlight-cache";
|
||||
import { CODE_THEME, codeHighlighterLanguage } from "./code-theme";
|
||||
import { codeTokenLines, type CodeLine } from "./code-tokens";
|
||||
|
||||
type HighlightResult =
|
||||
| { state: "ready"; lines: CodeLine[] }
|
||||
| { state: "pending"; promise: Promise<void> }
|
||||
| { state: "failed"; error: unknown };
|
||||
let grammars: typeof import("./code-highlighter-grammars") | undefined;
|
||||
|
||||
function highlight(source: string, language: string): CodeHighlight {
|
||||
const code = source.replace(/\r\n/g, "\n").replace(/\r$/, "");
|
||||
let result: HighlightResult;
|
||||
if (isSupportedLanguage(language)) {
|
||||
result = { state: "ready", lines: codeTokenLines(source, codeToTokens(code, { lang: language, theme: CODE_THEME }).tokens) };
|
||||
} else {
|
||||
const tokens = grammars ? grammars.highlightGrammar(code, language) : import("./code-highlighter-grammars").then(module => {
|
||||
grammars = module;
|
||||
return module.highlightGrammar(code, language);
|
||||
});
|
||||
if (tokens instanceof Promise) {
|
||||
const promise = tokens.then(tokens => {
|
||||
result = { state: "ready", lines: codeTokenLines(source, tokens) };
|
||||
}, error => { result = { state: "failed", error }; });
|
||||
result = { state: "pending", promise };
|
||||
} else {
|
||||
result = { state: "ready", lines: codeTokenLines(source, tokens) };
|
||||
}
|
||||
}
|
||||
return { read() {
|
||||
if (result.state === "pending") throw result.promise;
|
||||
if (result.state === "failed") throw result.error;
|
||||
return result.lines;
|
||||
} };
|
||||
}
|
||||
|
||||
export function codeHighlight(source: string, language: string): CodeHighlight {
|
||||
const cached = cachedCodeHighlight(source, language);
|
||||
if (cached) return cached;
|
||||
const resource = highlight(source, codeHighlighterLanguage(language));
|
||||
cacheCodeHighlight(source, language, resource);
|
||||
return resource;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Theme } from "@pierre/highlights";
|
||||
import type { ThemeRegistration } from "shiki";
|
||||
|
||||
export const CODE_THEME_NAME = "nanobot-code";
|
||||
export const CODE_THEME: Theme = {
|
||||
name: CODE_THEME_NAME, appearance: "dark", cssVariables: { prefix: "--code-" },
|
||||
style: {
|
||||
"editor.foreground": "foreground", "editor.background": "background",
|
||||
syntax: {
|
||||
comment: { color: "comment", font_style: "italic" },
|
||||
string: "string", "text.literal": "string",
|
||||
keyword: "keyword", preproc: "keyword",
|
||||
operator: "function", function: "function", constructor: "function",
|
||||
type: "property", attribute: "property", tag: "property",
|
||||
property: "property", number: "property", boolean: "property", constant: "property",
|
||||
title: { color: "keyword", font_weight: 700 }, emphasis: { font_style: "italic" }, "emphasis.strong": { font_weight: 700 },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const CODE_TEXTMATE_THEME: ThemeRegistration = {
|
||||
name: CODE_THEME_NAME, type: "dark", fg: "var(--code-foreground)", bg: "var(--code-background)",
|
||||
tokenColors: [
|
||||
{ scope: "comment", settings: { foreground: "var(--code-comment)", fontStyle: "italic" } },
|
||||
{ scope: ["string", "markup.raw"], settings: { foreground: "var(--code-string)" } },
|
||||
{ scope: ["keyword", "storage"], settings: { foreground: "var(--code-keyword)" } },
|
||||
{ scope: ["entity.name.function", "support.function", "variable.function", "keyword.operator"], settings: { foreground: "var(--code-function)" } },
|
||||
{ scope: ["constant", "support.type", "entity.name.type", "entity.name.tag", "entity.other.attribute-name", "entity.name.section"], settings: { foreground: "var(--code-property)" } },
|
||||
{ scope: ["keyword.operator.new", "keyword.operator.expression"], settings: { foreground: "var(--code-keyword)" } },
|
||||
{ scope: "markup.heading", settings: { foreground: "var(--code-keyword)", fontStyle: "bold" } },
|
||||
{ scope: "markup.italic", settings: { fontStyle: "italic" } },
|
||||
{ scope: "markup.bold", settings: { fontStyle: "bold" } },
|
||||
],
|
||||
};
|
||||
|
||||
export function codeHighlighterLanguage(language: string): string {
|
||||
return language === "markup" ? "html" : language === "docker" ? "dockerfile" : language;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export interface CodeToken {
|
||||
content: string;
|
||||
color?: string;
|
||||
fontStyle?: number;
|
||||
}
|
||||
|
||||
export interface CodeLine {
|
||||
text: string;
|
||||
tokens: CodeToken[];
|
||||
}
|
||||
|
||||
export function codeTokenLines(source: string, tokens: CodeToken[][]): CodeLine[] {
|
||||
const lines = source.split("\n");
|
||||
return lines.map((text, index) => {
|
||||
const ending = index < lines.length - 1 ? "\n" : "";
|
||||
const cr = text.endsWith("\r") ? "\r" : "";
|
||||
return { text: text + ending, tokens: [...tokens[index] ?? [], ...(cr || ending ? [{ content: cr + ending }] : [])] };
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user