Files
backnotprop__plannotator/packages/ui/utils/codeHighlight.ts
Michael Ramos c08b188812 perf(ui): single Shiki highlighter, palette-matched code blocks, drop highlight.js (#1218)
* perf(build): stub out the dead Oniguruma WASM in every bundle

@pierre/diffs picks its Shiki engine with a runtime ternary:

    engine: preferredHighlighter === "shiki-wasm"
      ? createOnigurumaEngine(import("shiki/wasm"))
      : createJavaScriptRegexEngine()

Plannotator pins `preferredHighlighter: 'shiki-js'` (and Pierre's own
default is 'shiki-js'), so the Oniguruma branch never executes. Because
the choice is a runtime ternary, bundlers keep the `import("shiki/wasm")`
edge anyway and inline `@shikijs/engine-oniguruma/wasm-inlined`, a
~622 KB base64 blob, into the single-file HTML builds. The review app
paid for it twice: once on the main thread (via
`highlighter/shared_highlighter.js`) and once inside the `?worker&inline`
Pierre worker.

Alias `shiki/wasm` to a stub that throws if it is ever reached. Wired via
`resolve.alias` rather than a plugin because `resolve.alias` is shared
with Vite's worker build and `plugins` are not.

Highlighting output is unchanged: the JS regex engine was already the one
doing the work. Opting back into 'shiki-wasm' now fails loudly instead of
silently costing every user a megabyte of dead bytes.

    apps/review/dist/index.html  19,424,646 -> 18,180,545  (-1,244,101 raw / -463,348 gzip)
    apps/hook/dist/index.html    23,032,467 -> 22,410,416    (-622,051 raw / -233,485 gzip)

* perf(ui): consolidate code highlighting onto Shiki, drop highlight.js

The app shipped two highlighters. Shiki already tokenised the code-review
diff pane (via @pierre/diffs, JavaScript regex engine); highlight.js
separately coloured markdown fences and review suggestion snippets at
~982 KB minified for a full build of ~190 grammars. That second
highlighter is now gone.

Every call site moves onto `packages/ui/utils/codeHighlight.ts`, a thin
wrapper over Pierre's SHARED Shiki instance:

  CodeBlock, Viewer, PlanCleanDiffView   markdown fences
  InlineMarkdown                          code-file hover preview
  HighlightedCode                         review suggestion snippets

Reusing Pierre's instance rather than standing up a second fine-grained
one is deliberate. Pierre imports Shiki's full bundle, so every grammar
and theme is ALREADY inlined in the single-file builds: a separate
highlighter with a curated language list would have duplicated a subset
of bytes that are already there. Sharing costs nothing, gives every
language Shiki bundles instead of a shortlist, and — the point of the
change — guarantees fences resolve the exact same theme the diff pane
resolves.

Theming. `SHIKI_THEME_MAP` / `resolveSyntaxTheme` move from
`packages/review-editor/hooks/usePierreTheme.ts` to
`packages/ui/utils/syntaxTheme.ts`; usePierreTheme re-exports them, so
the review editor's imports are unchanged. `useFenceTheme()` feeds the
components and re-highlights on palette or mode change. Code blocks now
follow the active palette across all ~52 themes in both light and dark,
instead of always rendering github-dark and relying on hand-written
`.hljs-*` override stacks to stay legible. Those stacks are deleted:
`packages/editor/index.css`'s light-mode token palette, and
`colorblind.css`'s hand-tuned tokens which existed to APPROXIMATE
@pierre/theme's protanopia-deuteranopia themes that are now simply used.

Behaviour held fixed:

  - Language-less fences stay plain text (#1212). No auto-detection
    anywhere, including the hover preview, which previously called
    `hljs.highlightAuto`. `HighlightedCode` derives its language from
    the caller's file path; an unknown extension renders plain.
  - `applyHighlight(el, ...)` keeps the imperative `hljs.highlightElement`
    DOM contract the annotation layer reaches into, and writes plain text
    at final size first so async highlighting causes no layout shift.
    Already-attached grammars highlight synchronously — no flicker on
    cached highlights.
  - It also verifies the rendered text is byte-identical to the source
    and falls back to plain otherwise, because annotations address code
    blocks by text offset.
  - `@plannotator/ui`'s public API is unchanged: the highlighter is a
    module-level default like the package's other seams, no new props.

The `hljs` class on fenced `<code>` becomes `pn-code` (it is a
structural hook for blockTargeting, vim navigation and print.css, and it
named a library we no longer ship). `language-*` stays.

    apps/review/dist/index.html  18,180,545 -> 17,270,889  (-909,656 raw / -291,921 gzip)
    apps/hook/dist/index.html    22,410,416 -> 21,704,434  (-705,982 raw / -238,096 gzip)

Verified the diff pane is untouched: the rendered Pierre shadow-DOM
markup is byte-for-byte identical between an origin/main build and this
one (SHA-256 aa1ee88a…).

* fix(ui): strip stray NUL bytes from the code-highlight source

Two U+0000 bytes slipped into comments in the previous commit, which made
git treat the file as binary. Replaced with spaces; no behaviour change.

* fix(ui): keep code-block annotation marks across highlight swaps

Fenced code is annotated by hand: one `<mark data-bind-id>` inside the
`<code>` element, which `applyHighlight` also owns. Every highlight swap
(palette change, dark/light toggle, or the first async grammar attach
after load) replaces that element's children, so the mark was silently
wiped and nothing put it back. Annotation state, the sidebar panel and
exports were unaffected; the loss was purely visual, and deterministic.

`applyHighlight` now publishes every write through `onCodeHighlightSwap`,
synchronously, immediately after it. `Viewer` subscribes and re-paints the
fence's mark, so a swapped block ends up with BOTH the new theme's tokens
and its annotation. The shared painter (`paintCodeBlockMark`) moves the
token spans into the mark instead of flattening them to text, so creating
an annotation no longer costs a block its colours either.

Being driven by the swap also fixes the cousin race by ordering rather
than timing: share/draft restore runs on a timer after load, and on a slow
machine the first async swap could land after it and wipe the restored
marks per block. A restore that painted before the swap is now
re-established in the same task the swap ran in, and one that runs after
finds the mark already there.

Removal tombstones the id before re-highlighting, because the host drops
the annotation from state a tick later — without it the swap listener
would paint the just-removed annotation back in, and a fence carrying a
second annotation would end up bare.

Also closes the named gap in the WASM coverage: entry-assets only grepped
source, so a future @pierre/diffs bump could reintroduce the inlined blob
through a different import specifier unnoticed. It now greps the built
`apps/{review,hook}/dist/index.html` for the base64 WASM magic, skipping
on an unbuilt checkout and running for real in the CI job that builds the
bundles.
2026-08-05 21:54:40 -07:00

294 lines
9.9 KiB
TypeScript

/**
* Syntax highlighting for markdown fences and suggestion snippets.
*
* There is exactly ONE highlighter in the app: the Shiki instance
* `@pierre/diffs` already runs for the code-review diff pane
* (`getSharedHighlighter`, driven by Shiki's JavaScript regex engine). Reusing
* it rather than standing up a second one buys three things:
*
* - Fences render in the SAME resolved theme as the diff pane, so a code
* block and a diff hunk finally agree about what "Kanagawa Wave" looks
* like. See `./syntaxTheme.ts`.
* - Zero added bundle weight. Pierre imports Shiki's full bundle, so every
* grammar and theme is already inlined; a separate fine-grained highlighter
* would have duplicated a subset of what is already there.
* - Every language Shiki bundles, not a hand-curated shortlist.
*
* The API is deliberately imperative (`applyHighlight(el, ...)`) because that is
* exactly the shape the removed `hljs.highlightElement(el)` had. The annotation
* layer reaches into these `<code>` elements to wrap `<mark>`s and to restore
* plain text afterwards, so keeping the DOM contract identical keeps that code
* working untouched.
*
* Language-less fences are never highlighted and never guessed at — see #1212.
* There is no auto-detection anywhere in this module.
*/
type PierreModule = typeof import('@pierre/diffs');
/**
* Structural class on every fenced-code `<code>` element.
*
* `blockTargeting`, the vim navigation layer and the print stylesheet all
* address code blocks through `pre > code.pn-code`. It used to be `.hljs`,
* which named a library the app no longer ships; the hook itself is unchanged,
* only the name is. The `language-*` class alongside it is still how
* `blockTargeting` reads a block's language back out of the DOM.
*/
export const CODE_BLOCK_CLASS = 'pn-code';
export function codeBlockClassName(language?: string): string {
return `${CODE_BLOCK_CLASS} font-mono${language ? ` language-${language}` : ''}`;
}
/** Shiki's `FontStyle` bitmask. Inlined so this module needs no shiki types. */
const FONT_STYLE_ITALIC = 1;
const FONT_STYLE_BOLD = 2;
const FONT_STYLE_UNDERLINE = 4;
const FONT_STYLE_STRIKETHROUGH = 8;
let pierre: PierreModule | undefined;
let pierreLoad: Promise<PierreModule | undefined> | undefined;
/** `${lang} ${theme}` pairs attached to the shared highlighter. */
const ready = new Set<string>();
/** Pairs the highlighter refused (unknown grammar or theme). Never retried. */
const rejected = new Set<string>();
const inflight = new Map<string, Promise<boolean>>();
const pairKey = (lang: string, theme: string) => `${lang} ${theme}`;
function loadPierre(): Promise<PierreModule | undefined> {
pierreLoad ??= import('@pierre/diffs').then(
(mod) => {
pierre = mod;
return mod;
},
() => undefined,
);
return pierreLoad;
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
interface ThemedTokenish {
content: string;
color?: string;
bgColor?: string;
fontStyle?: number;
htmlStyle?: Record<string, string> | string;
}
function tokenStyle(token: ThemedTokenish): string {
if (typeof token.htmlStyle === 'string') return token.htmlStyle;
const parts: string[] = [];
if (token.htmlStyle) {
for (const [prop, value] of Object.entries(token.htmlStyle)) parts.push(`${prop}:${value}`);
}
if (token.color) parts.push(`color:${token.color}`);
if (token.bgColor) parts.push(`background-color:${token.bgColor}`);
const fontStyle = token.fontStyle ?? 0;
if (fontStyle > 0) {
if (fontStyle & FONT_STYLE_ITALIC) parts.push('font-style:italic');
if (fontStyle & FONT_STYLE_BOLD) parts.push('font-weight:bold');
const decorations: string[] = [];
if (fontStyle & FONT_STYLE_UNDERLINE) decorations.push('underline');
if (fontStyle & FONT_STYLE_STRIKETHROUGH) decorations.push('line-through');
if (decorations.length) parts.push(`text-decoration:${decorations.join(' ')}`);
}
return parts.join(';');
}
/**
* Highlighted markup for `code`, or `null` when it cannot be produced right now
* (highlighter not loaded yet, grammar/theme not attached yet, or the tokens do
* not reconstruct the input exactly).
*
* Synchronous by design: once a (lang, theme) pair is attached, every later
* block using it highlights during the same tick, so there is no flicker on
* cached highlights.
*/
export function highlightToHtml(code: string, lang: string, theme: string): string | null {
const mod = pierre;
if (!mod || !ready.has(pairKey(lang, theme))) return null;
const highlighter = mod.getHighlighterIfLoaded();
if (!highlighter) {
// The shared highlighter was disposed out from under us; everything we
// believed was attached is gone with it.
ready.clear();
return null;
}
let lines: ThemedTokenish[][];
try {
lines = highlighter.codeToTokens(code, { lang, theme }).tokens as ThemedTokenish[][];
} catch {
ready.delete(pairKey(lang, theme));
return null;
}
// Invariant: the rendered text must be byte-identical to the source. The
// annotation layer addresses these blocks by text offset, so a tokenizer that
// normalised line endings (or dropped a trailing newline) would silently
// misplace every highlight in the block. Bail to plain text instead.
let html = '';
let plain = '';
for (let i = 0; i < lines.length; i++) {
if (i > 0) {
html += '\n';
plain += '\n';
}
for (const token of lines[i]!) {
plain += token.content;
const style = tokenStyle(token);
html += style
? `<span style="${style}">${escapeHtml(token.content)}</span>`
: escapeHtml(token.content);
}
}
return plain === code ? html : null;
}
/**
* Attach `lang` + `theme` to the shared highlighter. Resolves `false` for
* grammars or themes Shiki does not know, which is a normal outcome for a fence
* tagged with something made up: that block simply stays plain.
*/
export function ensureHighlight(lang: string, theme: string): Promise<boolean> {
const key = pairKey(lang, theme);
if (ready.has(key)) return Promise.resolve(true);
if (rejected.has(key)) return Promise.resolve(false);
const existing = inflight.get(key);
if (existing) return existing;
const load = loadPierre()
.then(async (mod) => {
if (!mod) return false;
await mod.getSharedHighlighter({
themes: [theme],
langs: [lang],
preferredHighlighter: 'shiki-js',
});
ready.add(key);
return true;
})
.catch(() => {
rejected.add(key);
return false;
})
.then((ok) => {
inflight.delete(key);
return ok;
});
inflight.set(key, load);
return load;
}
/** Monotonic stamp per element so a slow async highlight from a previous
* content/theme never lands on top of a newer one. */
const renderSeq = new WeakMap<HTMLElement, number>();
let seqCounter = 0;
type HighlightSwapListener = (el: HTMLElement) => void;
const swapListeners = new Set<HighlightSwapListener>();
/**
* Observe every write `applyHighlight` makes to a `<code>` element.
*
* Each write REPLACES the element's children, which destroys anything the
* annotation layer wrapped inside it — a whole-fence `<mark data-bind-id>` is
* gone the moment the palette changes or the first async grammar attach lands.
* Listeners run SYNCHRONOUSLY, immediately after the write, so re-applying a
* mark from a listener is ordered by construction rather than by a timer: a
* restore that ran before the swap is re-established in the same task the swap
* happened in, and a restore that runs after it finds the mark already there.
*
* Returns an unsubscribe function.
*/
export function onCodeHighlightSwap(listener: HighlightSwapListener): () => void {
swapListeners.add(listener);
return () => {
swapListeners.delete(listener);
};
}
function notifyHighlightSwap(el: HTMLElement): void {
if (swapListeners.size === 0) return;
for (const listener of Array.from(swapListeners)) {
// A misbehaving observer must never take syntax highlighting down with it.
try {
listener(el);
} catch {}
}
}
/**
* Drop-in replacement for `hljs.highlightElement(el)`.
*
* Writes plain text immediately so the block has its final size and content on
* the very first paint (no layout shift, no empty flash), then swaps in
* highlighted markup when the grammar is attached. When the grammar is already
* attached the highlighted markup is written straight away with no intermediate
* plain state.
*/
export function applyHighlight(
el: HTMLElement,
code: string,
lang: string | undefined,
theme: string,
): void {
const seq = ++seqCounter;
renderSeq.set(el, seq);
// #1212: a fence with no language stays plain. Never guess.
if (!lang) {
el.textContent = code;
notifyHighlightSwap(el);
return;
}
const immediate = highlightToHtml(code, lang, theme);
if (immediate !== null) {
el.innerHTML = immediate;
notifyHighlightSwap(el);
return;
}
el.textContent = code;
notifyHighlightSwap(el);
void ensureHighlight(lang, theme).then((ok) => {
if (!ok || renderSeq.get(el) !== seq || !el.isConnected) return;
const html = highlightToHtml(code, lang, theme);
if (html === null) return;
el.innerHTML = html;
notifyHighlightSwap(el);
});
}
/** Test seam: forget every cached attachment and module handle. */
export function __resetCodeHighlightCacheForTests(): void {
ready.clear();
rejected.clear();
inflight.clear();
pierre = undefined;
pierreLoad = undefined;
}
/**
* Test seam: stand in for `@pierre/diffs` so a test can drive real swaps
* (including WHEN the async one lands) without loading Shiki's full bundle.
* Pass `undefined` to go back to the real dynamic import.
*/
export function __setCodeHighlightModuleForTests(mod: PierreModule | undefined): void {
ready.clear();
rejected.clear();
inflight.clear();
pierre = mod;
pierreLoad = mod ? Promise.resolve(mod) : undefined;
}