Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328import 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<number, HTMLElement>({ 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<number, string>({ 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 `<svg>` wrapper sized to nothing, with a real `<defs>` 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 `<symbol>` 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<number, number>,): Range<Decoration>[] { const decorations: Range<Decoration>[] = []; 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; }}