Files
pipelines/web/src/highlight.js
T
alan ebf02c3bed web: gated access, anchored viewers, mobile tabs and chat colour
- serve.mjs requires a signed session cookie for every page, artifact and the
  WebSocket, with a password file, 30-day sessions, login throttling and public
  brand assets for the sign-in page.
- The diff viewer is a fixed-height top-anchored panel whose toolbar (modes,
  copy, previous, next, close as icons) is its first row; the artifact viewer is
  likewise a fixed frame so its navigation never moves.
- The audit's selected tab uses the app's normal selected surface and bottom
  accent. Sessions that were not recorded say so plainly.
- Chat code blocks are syntax-coloured; graph pinch-zoom works with two fingers
  while a single pointer still pans and clicks nodes.
- Phones always keep the destination bar (pane collapse is wide-only), with the
  destinations spread evenly and Search on the right; the list default width is
  narrower; the theme colour matches the app.
- Code-format and layout tests, plus the full browser suite, pass.
2026-10-20 02:21:51 +01:00

76 lines
5.2 KiB
JavaScript

// A small, dependency-free syntax colourer for fenced code in chat. It returns
// tokens, never HTML: the renderer appends spans with text nodes, so no model
// output can inject markup. Unknown languages still get strings, comments and
// numbers highlighted with the generic keyword set.
const KEYWORDS = {
go: "break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var true false nil iota",
javascript:
"async await break case catch class const continue debugger default delete do else export extends finally for from function get if import in instanceof let new of return set static super switch this throw try typeof var void while with yield true false null undefined",
typescript:
"abstract any as asserts async await boolean break case catch class const constructor continue declare default delete do else enum export extends false finally for from function get if implements import in infer instanceof interface is keyof let module namespace never new null number object of package private protected public readonly require return set static string super switch symbol this throw true try type typeof undefined unique unknown var void while with yield",
kotlin:
"as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while by catch constructor delegate dynamic field file finally get import init param property receiver set setparam where actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg",
java: "abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null",
shell:
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
bash:
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
python:
"and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield match case",
rust:
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
sql: "select from where insert into values update set delete create table alter drop index join left right inner outer group by order having limit offset as and or not null true false distinct union all",
json: "true false null",
};
const HASH_COMMENT = new Set(["shell", "bash", "python", "ruby", "yaml", "toml"]);
function languageKey(language) {
const key = String(language ?? "").trim().toLowerCase().split(/[\s:]/)[0];
if (key === "js" || key === "jsx") return "javascript";
if (key === "ts" || key === "tsx") return "typescript";
if (key === "sh" || key === "zsh") return "shell";
if (key === "py") return "python";
if (key === "kt") return "kotlin";
if (key === "rs") return "rust";
return key;
}
/**
* Tokenize one code block into `{text, kind}` with kind plain|comment|string|
* number|keyword|literal. Total and deterministic.
*/
export function highlight(code, language = "") {
const key = languageKey(language);
const keywords = new Set((KEYWORDS[key] ?? KEYWORDS.javascript).split(/\s+/).filter(Boolean));
const commentPattern = HASH_COMMENT.has(key) ? "#[^\\n]*" : key === "sql" ? "--[^\\n]*" : "\\/\\/[^\\n]*";
const pattern = new RegExp(
`(\\/\\*[\\s\\S]*?\\*\\/|${commentPattern}|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\b\\d+(?:\\.\\d+)?\\b|[A-Za-z_$][\\w$]*)`,
"g",
);
const text = String(code ?? "");
const tokens = [];
let last = 0;
for (const match of text.matchAll(pattern)) {
if (match.index > last) tokens.push({ text: text.slice(last, match.index), kind: "plain" });
const value = match[0];
let kind = "plain";
if (value.startsWith("//") || value.startsWith("#") || value.startsWith("--") || value.startsWith("/*")) {
kind = "comment";
} else if (/^["'`]/.test(value)) {
kind = "string";
} else if (/^\d/.test(value)) {
kind = "number";
} else if (keywords.has(value)) {
kind = value === "true" || value === "false" || value === "null" || value === "None" ||
value === "nil" || value === "True" || value === "False"
? "literal"
: "keyword";
}
tokens.push({ text: value, kind });
last = match.index + value.length;
}
if (last < text.length) tokens.push({ text: text.slice(last), kind: "plain" });
return tokens;
}