import type { EditorState, Range } from "@codemirror/state"; import type { DecorationSet, ViewUpdate } from "@codemirror/view"; import type { FileId, SvgRangedFrame, TypstDiagnostic, TypstState } from "@typbase/engine"; import { setDiagnostics } from "@codemirror/lint"; import { StateEffect, StateField } from "@codemirror/state"; import { Decoration, EditorView, ViewPlugin } from "@codemirror/view"; import { LRUCache } from "lru-cache"; import type { ExternalLinkOpener } from "./frames"; import type { NotebookCell, NotebookOptions } from "./notebook"; import type { TextRef, TypstRequestHandler } from "./types"; import { mergeTypstDiagnostics, rememberDiagnostics } from "./diagnostics"; import { frameActiveDecorations, frameIsInactive, hydrateFrameSvgs, installSharedDefs, knownFrameHashes, TypstWidget, } from "./frames"; import { cellIndexAt, notebookRefreshEffect } from "./notebook"; import { decorateNotebook, notebookRailMenuOpen } from "./notebook-widgets"; /** * Compiled frames per cache key, where the key is `path:revision:appRevision`. */ export const compileCache = new LRUCache< string, { frames: SvgRangedFrame[]; tooltips: SvgRangedFrame[]; /** Caret the tooltips were compiled for, so a cache hit cannot hide a moved caret. */ focus: number | null; /** Every equation in the note, not only the one the caret was in. */ equationRanges: [number, number][]; diagnostics: TypstDiagnostic[]; } >({ max: 2 }); const updateFlagStore = new Set(); /** * Dispatch this to recompile even when the document did not change. Used when * app data changed (fonts installed, workspace data, query results). */ export const typstRecompileEffect = StateEffect.define({}); /** Compile cache keys include the wasm revision so new fonts re-render. */ function compileCacheKey( path: string, typstState: TypstState, revision?: () => string | number | undefined, ): string { return `${path}:${typstState.revision()}:${revision?.() ?? ""}`; } const SCROLLBAR_ALLOWANCE = 12; function editorRenderWidth(scrollDOM: HTMLElement, contentDOM: HTMLElement): number { const pane = scrollDOM.getBoundingClientRect(); const gutters = scrollDOM.querySelector(".cm-gutters"); const contentStyle = getComputedStyle(contentDOM); const scrollStyle = getComputedStyle(scrollDOM); return Math.max( 0, pane.width - (gutters?.getBoundingClientRect().width ?? 0) - parseFloat(contentStyle.paddingLeft) - parseFloat(contentStyle.paddingRight) - parseFloat(scrollStyle.paddingLeft) - parseFloat(scrollStyle.paddingRight) - SCROLLBAR_ALLOWANCE, ); } export interface EquationOverlays { /** Rendered overlays, at most one when the render was given a caret. */ tooltips: SvgRangedFrame[]; /** * Every equation range in the note, not only the one the caret was in. The * popup compares the cursor against these to know when it has entered math * whose overlay the last render skipped. */ ranges: [number, number][]; /** Caret the overlays were compiled for. Null when the compile had none. */ focus: number | null; } export const tooltipsStateEffect = StateEffect.define(); export const tooltipsStateField = StateField.define({ create() { return { tooltips: [], ranges: [], focus: null }; }, update(overlays, transaction) { const effect = transaction.effects.find((e) => e.is(tooltipsStateEffect)); return effect ? effect.value : overlays; }, }); interface BuildDecorationsArgs { state: EditorState; view: EditorView; frames: SvgRangedFrame[]; locked: boolean; fileId: FileId; typstState: TypstState; openExternal?: ExternalLinkOpener; /** * Measured source heights for the active blocks, keyed by line start. The * first pass runs while the blocks' widgets are still mounted, so the view * reports the render height for those lines. The remeasure pass fills this * from the source lines once they exist. */ lineHeights?: Map; } /** * Builds the decoration set for a compile result: rendered blocks become * replace widgets, the block the cursor is in shows its source and stretches * its last line to the render's height. Returns the frames that show source, * for the remeasure pass. */ function buildDecorations({ state, view, frames, locked, fileId, typstState, openExternal, lineHeights, }: BuildDecorationsArgs): { decorations: DecorationSet; active: SvgRangedFrame[]; } { const decorations: Range[] = []; const active: SvgRangedFrame[] = []; for (const frame of frames) { const { start, end } = frame.range; if (!frame.render) continue; if (frameIsInactive(view, state, start, end)) { const widget = new TypstWidget(view, frame, locked, fileId, typstState, openExternal); decorations.push(Decoration.replace({ widget, typstFrame: true }).range(start, end)); continue; } active.push(frame); decorations.push(...frameActiveDecorations(view, state, frame, lineHeights)); } return { decorations: Decoration.set(decorations, true), active }; } /** * Source line heights for the blocks whose widgets were just removed. Runs * inside the view's measure pass, after the source lines are in the DOM, so * the heights are the text's and not the widget's. */ function measureLineHeights(view: EditorView, frames: SvgRangedFrame[]): Map { const heights = new Map(); const { state } = view; for (const frame of frames) { const { number: startLine } = state.doc.lineAt(frame.range.start); const { number: endLine } = state.doc.lineAt(frame.range.end); for (let currentLine = startLine; currentLine <= endLine; currentLine++) { const line = state.doc.line(currentLine); if (!heights.has(line.from)) { heights.set(line.from, view.lineBlockAt(line.from).height); } } } return heights; } interface DecorateResult { decorations: DecorationSet; tooltips: SvgRangedFrame[]; equationRanges: [number, number][]; tooltipFocus: number | null; frames: SvgRangedFrame[]; active: SvgRangedFrame[]; } interface DecorateArgs { fileId: FileId; spaceId: string; path: string; prelude: string; locked: boolean; update: ViewUpdate; updateInWidget: boolean; widthChanged: boolean; forced: boolean; typstState: TypstState; revision?: () => string | number | undefined; onRequests?: TypstRequestHandler; onPanic?: (fileId: FileId) => void; onCompile?: () => void; /** Opens a link clicked inside a rendered frame. See ExternalLinkOpener. */ onExternalLink?: ExternalLinkOpener; notebook?: NotebookOptions; renderFrames?: boolean; } function decorate({ fileId, spaceId, path, prelude, locked, update, updateInWidget: _updateInWidget, widthChanged, forced, typstState, revision, onRequests, onPanic, onCompile, onExternalLink, notebook, renderFrames = true, }: DecorateArgs): DecorateResult { const text = update.state.doc.toString(); const isFlaggedForUpdate = updateFlagStore.has(path); const cacheKey = compileCacheKey(path, typstState, revision); let frames: SvgRangedFrame[]; let tooltips: SvgRangedFrame[]; let equationRanges: [number, number][]; let diagnostics: TypstDiagnostic[]; let tooltipFocus: number | null; const mustCompile = forced || update.docChanged || widthChanged || !compileCache.has(cacheKey); if (mustCompile) { if (isFlaggedForUpdate) updateFlagStore.delete(path); else updateFlagStore.add(path); const focus = update.state.selection.main.from; let compileResult: ReturnType; try { compileResult = typstState.compilePaged( fileId, text, prelude, focus, undefined, knownFrameHashes(), ); } catch (error) { // A wasm panic aborts the instance: the host recreates it and remounts // the editor through onPanic. Until then, render nothing rather than // letting the trap break CodeMirror's update loop. console.error("[typst] compile panicked:", error); onPanic?.(fileId); return { decorations: Decoration.none, tooltips: [], equationRanges: [], tooltipFocus: null, frames: [], active: [], }; } dispatchDiagnostics(compileResult.diagnostics, update.state, update.view); rememberDiagnostics(path, text, compileResult.diagnostics); onCompile?.(); if (compileResult.requests.length > 0 && onRequests) { void Promise.resolve(onRequests(compileResult.requests, spaceId)).then((wasUpdated) => { if (!wasUpdated) return; // The cached result was compiled before the request was resolved. // Force a recompile instead of trusting it. Dispatch the effect alone: // a no-op document change maps the selection into the replaced range // and drops the cursor at the start of the note. update.view.dispatch({ effects: typstRecompileEffect.of(null) }); }); } installSharedDefs(compileResult.defs); hydrateFrameSvgs(compileResult.frames); ({ frames, tooltips, equation_ranges: equationRanges } = compileResult); diagnostics = compileResult.diagnostics; tooltipFocus = focus; compileCache.set(cacheKey, { frames, tooltips, focus, equationRanges, diagnostics, }); } else { const cached = compileCache.get(cacheKey)!; ({ frames, tooltips, equationRanges, diagnostics, focus: tooltipFocus } = cached); } const { view, state } = update; if (notebook) { let cells: NotebookCell[]; try { cells = notebook.cells(text); } catch (error) { console.error("[typst] cell extraction panicked:", error); onPanic?.(fileId); return { decorations: Decoration.none, tooltips: [], equationRanges: [], tooltipFocus: null, frames: [], active: [], }; } notebook.onCells?.(cells); notebook.onCompile?.({ text, frames, diagnostics }); const activeIndex = cells.length ? cellIndexAt(cells, state.selection.main.head) : null; notebook.onActiveCell?.(activeIndex); return { decorations: Decoration.set( decorateNotebook({ view, state, cells, frames, diagnostics, fileId, typstState, locked, readOnly: notebook.readOnly?.() ?? false, renderFrames, activeIndex, onExternalLink, onCommand: (command, index) => notebook.onCommand?.(command, index), options: notebook, }), true, ), tooltips, equationRanges, tooltipFocus, frames, // Notebook cells do their own source-height handling, so there is no // around-the-widget remeasure to schedule. active: [], }; } const built = buildDecorations({ state, view, frames, locked, fileId, typstState, openExternal: onExternalLink, }); return { decorations: built.decorations, tooltips, equationRanges, tooltipFocus, frames, active: built.active, }; } /** A block whose source is replaced by a rendered frame. */ export interface ReplacedFrame { from: number; to: number; } /** * The frames currently shown as widgets, in document order. A replace * decoration only exists while the frame is inactive, so this is also the set * of ranges where the source text has no DOM to measure against. */ export function replacedFrames(state: EditorState): ReplacedFrame[] { const decorations = state.field(typstStateField, false); if (!decorations) return []; const frames: ReplacedFrame[] = []; decorations.between(0, state.doc.length, (from, to, value) => { if (value.spec?.typstFrame === true) frames.push({ from, to }); }); return frames; } /** The replaced frame containing `pos`, if any. */ export function replacedFrameAt(state: EditorState, pos: number): ReplacedFrame | null { const decorations = state.field(typstStateField, false); if (!decorations) return null; let found: ReplacedFrame | null = null; decorations.between(0, state.doc.length, (from, to, value) => { if (!found && value.spec?.typstFrame === true && pos >= from && pos <= to) { found = { from, to }; } }); return found; } const typstStateEffect = StateEffect.define<{ decorations: DecorationSet }>({}); export const typstStateField = StateField.define({ create() { return Decoration.none; }, update(decorations, transaction) { const effect = transaction.effects.find((e) => e.is(typstStateEffect)); if (effect) return effect.value.decorations; return decorations.map(transaction.changes); }, provide: (field) => [EditorView.decorations.from(field)], }); export interface TypstViewPluginOptions { onRequests?: TypstRequestHandler; /** Extra component of the compile cache key: app data revisions. */ revision?: () => string | number | undefined; /** See TypstPluginOptions#onPanic. */ onPanic?: (fileId: FileId) => void; /** * Called after a compile pass succeeds. The host resets its health and * heap watchdog on it. */ onCompile?: () => void; /** See TypstPluginOptions#onExternalLink. */ onExternalLink?: ExternalLinkOpener; /** Cell rendering, run effects, and cell commands for notebook mode. */ notebook?: NotebookOptions; renderFrames?: boolean; } export const typstViewPlugin = ( fileId: FileId, spaceId: string, path: string, text: TextRef, prelude: TextRef, locked: boolean, typstState: TypstState, options: TypstViewPluginOptions = {}, ) => ViewPlugin.define((_view) => { // A freshly created view's first update never has doc/selection/focus // changes, and resize() reports false when the pane width already matches // the stored one. That happens whenever the view is rebuilt for a mode // switch (write -> source -> write): without this flag the render never // runs until the user clicks or types. let firstUpdate = true; let resizeTimer: number | undefined; let resizePending = false; let pointerDown = false; const renderFrames = options.renderFrames ?? true; /** * Reflows once the pane width has settled. A drag keeps the compiled frame * sizes until the pointer is released, so the rendered blocks do not resize * under the pointer while a splitter is being dragged. */ const flushResize = () => { clearTimeout(resizeTimer); if (!resizePending) return; resizePending = false; // The last pointer move can land before the resize observer reports the // settled width, so measure once more before the compile. try { typstState.resize( fileId, editorRenderWidth(_view.scrollDOM, _view.contentDOM), locked ? _view.scrollDOM.clientHeight : undefined, ); } catch (error) { console.error("[typst] resize panicked:", error); options.onPanic?.(fileId); return; } _view.dispatch({ effects: typstRecompileEffect.of(null) }); }; const onPointerDown = () => { pointerDown = true; }; const onPointerUp = () => { pointerDown = false; flushResize(); }; if (typeof window !== "undefined") { window.addEventListener("pointerdown", onPointerDown, true); window.addEventListener("pointerup", onPointerUp, true); window.addEventListener("pointercancel", onPointerUp, true); window.addEventListener("blur", onPointerUp); } // Dedupes remeasure requests for this view. The latest one wins. const remeasureKey = {}; /** * A pass that shows a block's source runs while the block's widget is still * mounted, so the view reports the widget's height for those lines and the * min-height that should keep the render's height comes out as zero. Once * the source lines are in the DOM and measured, rebuild the active * decorations with the real text heights. The measure pass runs before * paint, so the rebuild is not visible. */ const remeasureActive = (update: ViewUpdate, result: DecorateResult) => { if (result.active.length === 0) return; const { view, state } = update; const focused = view.hasFocus; const stale = () => view.state.doc !== state.doc || !view.state.selection.eq(state.selection) || view.hasFocus !== focused; view.requestMeasure({ key: remeasureKey, read: (readView) => (stale() ? null : measureLineHeights(readView, result.active)), write: (heights) => { if (!heights) return; queueMicrotask(() => { // Another update changed the inputs. That pass schedules its own // remeasure. if (stale()) return; const rebuilt = buildDecorations({ state: view.state, view, frames: result.frames, locked, fileId, typstState, openExternal: options.onExternalLink, lineHeights: heights, }); view.dispatch({ effects: typstStateEffect.of({ decorations: rebuilt.decorations, }), }); }); }, }); }; return { update(update: ViewUpdate) { let widthChanged = false; const effects = update.transactions.flatMap((transaction) => transaction.effects); const refresh = effects.some((effect) => effect.is(notebookRefreshEffect)); const forced = firstUpdate || update.transactions.some((transaction) => transaction.effects.some((effect) => effect.is(typstRecompileEffect)), ); firstUpdate = false; if (update.geometryChanged) { const { scrollDOM, contentDOM } = update.view; try { widthChanged = typstState.resize( fileId, editorRenderWidth(scrollDOM, contentDOM), locked ? scrollDOM.clientHeight : undefined, ); } catch (error) { // A dead instance throws here before the host remounts the pane. // Report it like a compile trap and skip the rest of the pass. console.error("[typst] resize panicked:", error); options.onPanic?.(fileId); return; } } if (widthChanged) { // Reflow once the pane width settles instead of on every resize // tick: recompiling per pointermove swaps the widget size mid-drag // and blocks the main thread. Until the recompile lands, widgets // keep their compiled size (see TypstWidget), so the render stays // consistent while the pane moves. While a pointer is down there is // no timer at all: a pause in a drag must not reflow the page. resizePending = true; clearTimeout(resizeTimer); if (!pointerDown) { resizeTimer = window.setTimeout(flushResize, 150); } } const focusChanged = update.focusChanged && !(options.notebook && notebookRailMenuOpen()); if (update.docChanged || update.selectionSet || focusChanged || forced || refresh) { queueMicrotask(() => { let result: DecorateResult; try { result = decorate({ fileId, spaceId, path, prelude: prelude.value, locked, update, updateInWidget: false, widthChanged, forced, typstState, revision: options.revision, onRequests: options.onRequests, onPanic: options.onPanic, onCompile: options.onCompile, onExternalLink: options.onExternalLink, notebook: options.notebook, renderFrames, }); } catch (error) { console.error("[typst] decorate panicked:", error); options.onPanic?.(fileId); return; } if (result) { const stateEffects = [ typstStateEffect.of({ decorations: result.decorations }), tooltipsStateEffect.of({ tooltips: result.tooltips, ranges: result.equationRanges, focus: result.tooltipFocus, }), ]; update.view.dispatch({ effects: stateEffects }); remeasureActive(update, result); } }); if (update.docChanged) text.value = update.state.doc.toString(); } }, destroy() { clearTimeout(resizeTimer); if (typeof window !== "undefined") { window.removeEventListener("pointerdown", onPointerDown, true); window.removeEventListener("pointerup", onPointerUp, true); window.removeEventListener("pointercancel", onPointerUp, true); window.removeEventListener("blur", onPointerUp); } }, }; }); function dispatchDiagnostics( typstDiagnostics: TypstDiagnostic[], state: EditorState, view: EditorView, ) { view.dispatch(setDiagnostics(state, mergeTypstDiagnostics(state, typstDiagnostics))); }