import type { EditorState, Range } from "@codemirror/state"; import type { FileId, SvgRangedFrame, TypstState } from "@typbase/engine"; import { Decoration } from "@codemirror/view"; import { EditorView, WidgetType } from "@codemirror/view"; import { LRUCache } from "lru-cache"; const containerCache = new LRUCache({ max: 128 }); /** * Frame markup by content hash. A compile sends these hashes to the engine, so * frames that did not change come back empty instead of repeating their SVG. */ const frameSvgCache = new LRUCache({ max: 512 }); const SVG_NS = "http://www.w3.org/2000/svg"; let sharedDefs: SVGDefsElement | undefined; let sharedDefsMarkup = ""; /** Hashes of frames the client can supply to a compile. */ export function knownFrameHashes(): number[] { return [...frameSvgCache.keys()]; } /** * Fills in frames the engine reused. A frame comes back with empty `svg` only * when its hash was passed to [`knownFrameHashes`], so every empty frame has an * entry here. */ export function hydrateFrameSvgs(frames: SvgRangedFrame[]): void { // Fill reused frames first. Caching a new frame can evict an entry the same // compile reused, so every lookup happens before any insert. for (const frame of frames) { if (!frame.render.svg) { frame.render.svg = frameSvgCache.get(frame.render.hash) ?? ""; } } for (const frame of frames) { if (frame.render.svg) frameSvgCache.set(frame.render.hash, frame.render.svg); } } /** * Places the glyph and gradient definitions a frame set references. */ export function installSharedDefs(defs: string | null | undefined): void { // A compile that needed no definitions leaves whatever is already there. Ids // are content hashes, so a stale block still answers a reference correctly. if (!defs) return; if (sharedDefs?.isConnected && defs === sharedDefsMarkup) return; if (!sharedDefs || !sharedDefs.isConnected) { // An `` wrapper sized to nothing, with a real `` inside, so the // installed markup is the same shape the exporter writes into a frame. const host = document.createElementNS(SVG_NS, "svg"); host.setAttribute("width", "0"); host.setAttribute("height", "0"); host.setAttribute("aria-hidden", "true"); host.style.position = "absolute"; sharedDefs = document.createElementNS(SVG_NS, "defs"); host.append(sharedDefs); document.body.append(host); } // The engine hands over the *contents* of its defs blocks, so the elements go // in directly. A `` never paints, so an unstyled host is enough and // nothing here can affect layout. sharedDefs.innerHTML = ""; sharedDefs.innerHTML = defs; sharedDefsMarkup = defs; } /** * Opens an external link for the host. Browsers get a new tab. The app passes * its `openExternal`, which hands the URL to the system browser in Tauri * (a webview has no tab strip, so `window.open` is dropped there). * * The opener owns any confirmation. Browsers have their own tab strip, but a * host that wants to ask first (the app's modal) does so before opening. */ export type ExternalLinkOpener = (url: string) => void; const openInNewTab: ExternalLinkOpener = (url) => { window.open(url, "_blank", "noopener,noreferrer"); }; /** * The compiled size of an SVG frame, from the markup's viewBox. The viewBox * is the page width the engine laid out at (pt), and the app renders one * Typst point per CSS pixel, so the numbers map to px directly. * * `frame.render.width` is the chunk's bounding-box width, which does not * change with the pane for fixed-size blocks (images, boxes). The viewBox * width is the correct resize key and the size to pin: a render laid out * for a wider pane must keep its size, not be stretched by CSS while a * resize is in flight. */ export function frameSize(frame: SvgRangedFrame): { width: number; height: number } { const match = frame.render.svg.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/); return { width: match ? Number(match[1]) : frame.render.width, height: match ? Number(match[2]) : frame.render.height, }; } /** * Pins a container's SVG to the compiled frame size (via CSS variables). The * container keeps max-width: 100% so it never exceeds the line. An explicit * container width would make CodeMirror's flex layout grow the content width * forever (resize -> wider widget -> wider content). The pinned SVG overflows * the clamped container while the pane is narrower than the compiled width. * The scroller clips it, so the render stays its size instead of scaling. */ export function syncFrameContainer(container: HTMLElement, frame: SvgRangedFrame): void { const size = frameSize(frame); const sizeKey = `${Math.round(size.width)}x${Math.round(size.height)}`; container.dataset.frameFrom = String(frame.range.start); container.dataset.frameTo = String(frame.range.end); if (container.dataset.renderSize === sizeKey) return; container.dataset.renderSize = sizeKey; container.style.setProperty("--render-w", size.width + "px"); container.style.setProperty("--render-h", size.height + "px"); container.style.height = size.height + "px"; container.setHTMLUnsafe(frame.render.svg); } /** Fresh frame container for widgets that manage their own DOM (notebook outputs). */ export function createFrameContainer(frame: SvgRangedFrame): HTMLElement { const container = document.createElement("div"); container.dataset.hash = frame.render.hash.toString(); container.classList.add("typst-render"); syncFrameContainer(container, frame); return container; } /** * Click handling shared by inline widgets and notebook outputs: typbase:// * links are left for the host's anchor router, external links go through * `openExternal` (which owns any confirmation), anything else maps back into * the compiled document and moves the cursor. Alt-click edits the link instead * of following it. */ export function attachFrameInteractions( container: HTMLElement, view: EditorView, frame: SvgRangedFrame, fileId: FileId, typstState: TypstState, openExternal: ExternalLinkOpener = openInNewTab, ): void { const handle = (event: MouseEvent) => { event.preventDefault(); const target = event.target as Element | null; const anchor = target?.closest?.("a[href]") as HTMLAnchorElement | null; if (anchor && !event.altKey) { if (event.type !== "click") return; const href = anchor.getAttribute("href") ?? ""; if (href.startsWith("typbase://")) return; openExternal(href); return; } const { top, left } = container.getBoundingClientRect(); // App pt == screen px, so the click lands in document points as is. const x = event.clientX - left; const y = event.clientY - top + frame.render.yOffset; const jump = (() => { try { return typstState.jumpPaged(fileId, x, y); } catch (error) { console.error("[typst] jump panicked:", error); return undefined; } })(); const position = jump ? jump.position : frame.range.end; view.focus(); view.dispatch({ selection: { anchor: position } }); }; container.addEventListener("click", handle); container.addEventListener("mousedown", handle); } /** * True when the selection does not touch `start..end`, so the frame can render * as a widget instead of showing source. Shared by the inline WYSIWYG pass and * the notebook markup cells. */ export function frameIsInactive( view: EditorView, state: EditorState, start: number, end: number, ): boolean { return ( !view.hasFocus || state.selection.ranges.every( (range) => (range.from < start || range.from > end) && (range.to < start || range.to > end) && (start < range.from || start > range.to) && (end < range.from || end > range.to), ) ); } /** * Line decorations that stand in for a frame while the cursor is inside it: * the source stays visible with the frame's height reserved, so the pane does * not jump between render and source. Matches the inline WYSIWYG behavior. * * `lineHeights` has measured source heights from the remeasure pass. When * it is absent the view still reports the widget's height for those lines. */ export function frameActiveDecorations( view: EditorView, state: EditorState, frame: SvgRangedFrame, lineHeights?: Map, ): Range[] { const decorations: Range[] = []; let lineHeight = 0; const textTop = Number.isFinite(frame.render.textTop) ? Math.max(0, frame.render.textTop) : 0; 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); let style = ""; if (currentLine == startLine) { style += "border-top-left-radius:0.25rem;border-top-right-radius:0.25rem;"; if (textTop > 0) style += `box-sizing:border-box;padding-top:${textTop}px;`; } if (currentLine == endLine) { style += `border-bottom-left-radius:0.25rem;border-bottom-right-radius:0.25rem;min-height:${Math.max(0, frame.render.height - lineHeight)}px`; } else { lineHeight += lineHeights?.get(line.from) ?? view.lineBlockAt(line.from).height; } decorations.push( Decoration.line({ class: "cm-activeLine", attributes: { style }, }).range(line.from), ); } return decorations; } export class TypstWidget extends WidgetType { private container: HTMLElement; private readonly size: { width: number; height: number }; public constructor( private readonly view: EditorView, private readonly frame: SvgRangedFrame, private readonly locked: boolean, private readonly fileId: FileId, private readonly typstState: TypstState, private readonly openExternal?: ExternalLinkOpener, ) { super(); this.size = frameSize(frame); const cached = containerCache.get(frame.render.hash); // The content hash does not include pane width, so a reused container may // contain a frame laid out for a wider pane. Refresh its markup when the // geometry differs, so resizing the editor reflows the inline preview. if (cached?.isConnected) { this.container = cached; syncFrameContainer(cached, frame); } else { const container = document.createElement("div"); container.dataset.hash = frame.render.hash.toString(); container.classList.add("typst-render"); if (!locked) attachFrameInteractions(container, view, frame, fileId, typstState, this.openExternal); containerCache.set(frame.render.hash, container); this.container = container; syncFrameContainer(container, frame); } } public override eq(other: TypstWidget) { return ( other.frame.render.hash === this.frame.render.hash && other.frame.range.start === this.frame.range.start && other.frame.range.end === this.frame.range.end && other.size.width === this.size.width && other.size.height === this.size.height ); } public toDOM() { return this.container; } public override get estimatedHeight() { return this.frame.render.height; } }