@typstream/dom
Framework-free renderers for typstream's output (HTML and SVG pages), mountTypstream to show an engine document in an element, and standalone HTML exports.
@typstream/dom turns the engine's output into DOM, with no framework. It has three layers, and you can use any of
them on its own:
mountTypstreamshows a streaming document in an element: it opens the document on an engine, feeds it, and draws each artifact with the renderer for its target. This is what the framework bindings wrap.- The renderers:
createHtmlRendererfor the HTML target (sanitized, block-diffed Typst HTML with word fade-in and a caret) andcreatePagedViewfor the paged target (pages painted on canvases, or SVG, changed pages only, with a selectable text layer). standaloneHtmlandstandalonePages, which make an HTML export a file that opens on its own: Typst's HTML in a reading layout, or laid out as the pages.
When to use it
Use @typstream/dom in apps without React (vanilla JS, Vue, Svelte, Solid, Angular), or to build bindings for another
framework. In React, use typstream or @typstream/react,
which wrap mountTypstream. Use the renderers directly only when you drive an
EngineDocument yourself.
Install
npm install @typstream/dom @typstream/enginemountTypstream takes an engine from @typstream/engine. For html-compat's layout support
in the HTML target, add @typstream/html-compat and pass its plugin.
Example
import { mountTypstream } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
import { htmlCompat } from "@typstream/html-compat";
const engine = createEngine({ spawn: engineWorker() });
const options = { engine, plugins: [htmlCompat], isStreaming: true, animated: true, caret: true };
const view = mountTypstream(document.querySelector("#answer")!, { ...options, source: "" });
let text = "";
for await (const chunk of llmStream) view.update({ ...options, source: (text += chunk) });
view.update({ ...options, source: text, isStreaming: false }); // finish: strict compile, no caretThe vanilla JS guide walks through it step by step.
How mountTypstream behaves
update(options)takes all options each time and acts only on what changed. Anything left out goes back to its default. Plain objects and arrays are compared by value, so passing a freshinputsobject doesn't reopen the document.- Source. A
sourcethat extends the last one is pushed as a chunk; any othersourcereplaces the text.isStreamingturning false finishes the document (strict heal, final compile); turning true again starts it over, as for a regenerated answer.stream(anAsyncIterable<string>) is the alternative tosource: a new stream starts the document over, and the document finishes when the stream ends. If the stream throws, what arrived is finished and the error goes toreportError. Mounts given the same stream share one reader: each shows all of its text, including what arrived before it mounted, so a mount replaced while the stream continues loses nothing. The stream is closed when a chunk arrives after the last mount reading it is destroyed. - In place or a new document.
target,inputsandfileschange in place, and the latestresolveImageis the one called. A differentengine,plugins,preambleortemplate,healorscheduleoptions, adding or removingresolveImage, or switching to or from the reflow layout opens a new document; the old output stays until its first compile. - Lazy. The document opens when the element comes within one screen of the viewport, or as soon as it streams.
Offscreen, finished documents apply changes when they scroll back.
lazy: falseopens it right away. - Renderers follow the artifact's target, so after
targetchanges the old output stays until the first artifact of the new target. - Callbacks.
onStatusChangeandonDiagnosticsfollow the document's state.onRenderedfires for each artifact drawn, with its compile's report plusrenderMsandblocks(HTML) orpages(paged).onFallbackandonWatchdogpass on the document's events. destroy()disposes the document and removes what was rendered. The engine is yours and stays.
API
mountTypstream
const mountTypstream: (element: HTMLElement, initial: TypstreamOptions) => MountedTypstream;Renders a streaming Typst document into element and keeps it up to date. The renderers are added inside element
(the HTML renderer in a child <div>, the pages in a .typstream-paged child).
TypstreamOptions
Prop
Type
MountedTypstream
Prop
Type
TypstreamExportOptions
What exportPdf and exportDocx take.
Prop
Type
TypstreamHtmlExportOptions
What exportHtml takes: TypstreamExportOptions, StandaloneHtmlOptions, and pages.
Prop
Type
The exports compile the document in final mode with the template's inputs, your inputs and the export's own
(exportPdf({ inputs }), for that export only), without the reflow page size, so they come out at the document's
own size. They reject with the engine's
ExportError. See Exports.
const pdf = await view.exportPdf();
const key = await view.exportPdf({ inputs: { showAnswers: "true" } });
const file = await view.exportHtml({ title: "Fractions worksheet" });createHtmlRenderer
const createHtmlRenderer: (root: HTMLElement, options?: HtmlRendererOptions) => HtmlRenderer;Renders Typst HTML artifacts into root, keeping the DOM of unchanged blocks across updates. Each update splits the
HTML into top-level blocks as strings, keeps every block whose string is unchanged (its DOM nodes are never
re-created), and parses, sanitizes and inserts only the rest. A stream usually changes only the last block.
const renderer = createHtmlRenderer(element, { plugins: [htmlCompat] });
doc.subscribe((s) => {
if (s.artifact?.target === "html") renderer.update(s.artifact.html, { animate: !s.final, caret: !s.final });
});What the renderer does with the HTML:
- Sanitizes it. The document's HTML is untrusted. It is parsed into an inert
<template>and cleaned by an allowlist of the HTML, MathML and SVG Typst writes; plugins'sanitizefacets allow more. The cleaned nodes are moved into the page, never serialized and parsed again. Inline styles are applied through the CSSOM, so a strict CSP needs no'unsafe-inline'for styles. - Scopes ids. Ids and the links to them get a prefix (
idPrefix), so documents on one page don't collide. - Opens external links in a new tab (
linkTarget, default_blank). - Marks source anchors. Each top-level block's first element gets
data-typstream-src, its offset in the compiled source, anddata-typstream-startwhen the block starts in the source (after a blank line, or a heading). - Lays it out on pages. The document goes on sheets of its page size and margins (html-compat writes them),
scaled as the paged view scales its pages (
layout), and breaks across them where Typst breaks its pages: lines with Typst's orphans and widows, table rows, blocks that don't break, headings kept with what follows, forced and weak page breaks. Headers and footers go on every sheet with its number, and footnotes at the foot of the page their reference is on (Typst's endnotes stay at the end for screen readers, out of sight). Columns fill as Typst's do, fractional spacing takes what its page or line leaves, and aligned blocks sit in the room their page leaves. With the engine's fonts registered (registerTypstFonts) and html-compat, a document looks as it does on the paged view's pages. It is laid out again when the root's width changes and when fonts finish loading;onPageshears the page count. - Sets the language and direction on
rootfrom the document'slang, so right-to-left documents order lists and tables correctly.
HtmlRendererOptions
Prop
Type
HtmlRenderer
Prop
Type
Beta
sourceRange() and blockAt() are beta: they may change before the first stable release. Their offsets are in the
compiled (healed) source, without the preamble; map them to the raw stream with heal's map.toInput.
HtmlUpdateOptions
Prop
Type
HtmlUpdateResult
Prop
Type
Islands (beta)
With islands (and file, what islands get as IslandProps.file), the renderer mounts a render island over each
typstream-island marker whose name a plugin declares: an IslandRenderer mounts into a host element positioned over
the marker's fallback and returns an IslandInstance (update, destroy). IslandRenderers maps names to them;
mountTypstream takes the same option. A marker keeps one island while its block is re-created as it streams; one
whose block starts at or after HtmlUpdateOptions.stable is incomplete. See Writing an island.
Prop
Type
AnimateOptions
Word fade-in settings: animated in TypstreamOptions, animation in HtmlRendererOptions. Only blocks whose HTML
changed are touched, and only their new text fades in. Words still fading in when their block changes continue where
they were instead of popping in. Under prefers-reduced-motion: reduce nothing animates.
Prop
Type
htmlRendererCss
const htmlRendererCss: string;The HTML renderer's CSS: theme variables, word fade-in, the caret, and Typst's MathML rules. The renderer injects it
(once per document or shadow root, as a constructed stylesheet where supported) unless you pass
injectStyles: false to ship it yourself.
registerMathFont
const registerMathFont: (url: string | URL, doc?: Document) => Promise<void>;Registers New Computer Modern Math as a web font in doc (default document), for MathML. Without a math font,
browsers can't stretch delimiters. Pass the URL of the engine's copy (from @typstream/engine-wasm/fonts) or your
own. It uses the FontFace API, so no font-src exception for inline CSS is needed, and it does nothing if the family
is already registered. The typstream package does this for you.
registerTypstFonts
const registerTypstFonts: (fonts: readonly TypstFont[], doc?: Document) => void;Registers Typst's fonts (the engine's, from @typstream/engine-wasm/fonts) as web fonts in doc (default
document), under the names html-compat's CSS asks for, with the layout profile's line box as their ascent and
descent: the HTML target's lines are then as tall as the paged view's, their baselines where Typst puts them. Pass
them as fonts to mountTypstream, which registers them when it shows an HTML document; the typstream package
does this for you. Registering a family twice does nothing.
Prop
Type
registerLoadedFont (beta)
const registerLoadedFont: (font: LoadedFontFamily, root: Node) => Promise<void>;Shows a family the engine loaded from a font catalogue (an entry of Engine.fonts, or a font event) in the HTML
target under root: it registers the family's files as web fonts in the root's document and adds the rule that gives
the text the engine marked with that family its font, in the root's document or shadow root. mountTypstream calls
it for HTML documents; call it yourself when you render with createHtmlRenderer. The files come from the HTTP
cache, where the worker's download put them. Like registerMathFont it uses the FontFace API, so a strict
Content-Security-Policy needs connect-src for the files but no font-src.
createPagedView
const createPagedView: (container: HTMLElement, options?: PagedViewOptions) => PagedView;The paged renderer without a document: it appends a .typstream-paged element to container; call
view.render(artifact) with any paged artifact, complete or changed pages only.
- Canvas or SVG, per page. A page that comes as a drawing (
pageFormat: "drawing", whichmountPagedandmountTypstreamask for) is painted on a<canvas>: about a millisecond for a dense page in Chromium and Safari, 10–15 ms in Firefox, against 12–31 ms for the same page as SVG. A page that comes as SVG goes in a shadow root. - Only changed pages are redrawn. Pages are matched by index and redrawn when their hash changes, so a streamed update usually touches the last page. Pages past the new page count are removed.
- Visible pages first. Changed pages on screen are drawn at the next frame. Offscreen ones, and every text layer,
wait for idle time (
requestIdleCallback, a timer in WebKit), or are drawn as soon as they scroll into view.view.flush()draws everything now. - Canvas pixels. Canvases are painted at
devicePixelRatio, again when it changes and after a pinch zoom settles, and every page is painted before the browser prints. Only pages near the viewport keep their pixels (8–14 MB per A4 page at a ratio of 2): a page that scrolls away gives them up a second later, and is painted again when it comes back. Offscreen canvas pages need no idle time: they are painted when they come into view. - SVG pages: one shadow root each. Typst's SVG gives glyph definitions ids that repeat on every page. A shadow
root per page scopes them (in one document, Chromium would re-resolve every glyph on every page whenever one
changed), and keeps your CSS off the SVG. Their hosts have
content-visibility: auto. - Text layer. Pages draw glyphs as shapes, so invisible HTML text is laid over each page from the engine's text
runs. Selection, copy (with line breaks), find-in-page and screen readers use it, and the canvas or SVG is
aria-hidden. Headings, lists and tables in it carry ARIA roles. - Links. Only
http(s)andmailtolinks keep theirhref(seeisSafeHref); they open inlinkTarget. On a canvas page they are<a>elements over their area (.typstream-links). Links within the document stay inert. Images load only fromdata:URLs. - Islands (beta). With
islands(andplugins, which declare the names, andfile), each marker in the artifact'sislandsis mounted over its page in a box positioned incqw, like the links, so redrawing a page leaves it alone. An island is incomplete whilePagedRenderOptions.stable(view.render(artifact, { stable })) is at or before its source.mountPagedpasses the document's plugins, files and stable offset. See Writing an island. - Strict CSP. Styles are added once per document as a constructed stylesheet, and the text layer is positioned
through the CSSOM, so no
'unsafe-inline'is needed.
PagedViewOptions
Prop
Type
PagedView
Prop
Type
PagedRenderOptions
Prop
Type
DrawInfo (beta)
Beta
DrawInfo and the onDraw option are beta: meant for telemetry and tests, and may change before the first stable
release.
Prop
Type
mountPaged
const mountPaged: (container: HTMLElement, doc: EngineDocument, options?: MountPagedOptions) => MountedPaged;Renders an engine document as pages in container and keeps them up to date. It switches the document to the paged
target, and asks for pages as drawings for canvases (renderer: "svg" asks for SVG). Use it when you drive the document yourself rather than through mountTypstream:
import { mountPaged } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "paged" });
const { destroy } = mountPaged(document.querySelector("#preview")!, doc);
for await (const chunk of llmStream) doc.push(chunk);
doc.finish();With layout: "fit-width", the document's pages are scaled to the container's width. With layout: "reflow", it
compiles pages as wide as the container through sys.inputs, and recompiles after a resize once resizing pauses
(resizeDebounce); meanwhile the old pages scale. Open the document with REFLOW_PREAMBLE in its preamble for that
to work.
MountPagedOptions
Prop
Type
MountedPaged
Prop
Type
REFLOW_PREAMBLE
const REFLOW_PREAMBLE: string;Typst for a document's preamble that sets the page size from sys.inputs in the reflow layout, and does nothing
without those inputs. A document's own #set page(width: …) or paper comes later and wins: Typst has no rule that
applies after the document, so reflow only sets the default page. mountTypstream adds it for you when
layout is "reflow".
const doc = engine.open({ target: "paged", preamble: REFLOW_PREAMBLE });
mountPaged(container, doc, { layout: "reflow" });reflowInputs
const reflowInputs: (
widthPx: number,
pageHeight?: "a4" | "auto",
inputs?: Record<string, string>,
) => Record<string, string>;The sys.inputs that make REFLOW_PREAMBLE lay pages out widthPx CSS pixels wide, added to inputs. With
pageHeight "a4" (default) pages keep A4's proportions at that width, so long documents still update page by page;
"auto" makes one page as tall as the content, for short documents. Widths are rounded to half a point, so subpixel
resizes don't recompile.
isSafeHref
const isSafeHref: (href: string) => boolean;Whether a link URL from a document may be followed: http:, https: and mailto: only. Relative URLs are refused
too, since a page has no base the document controls. Control characters and whitespace are ignored the way browsers
ignore them, so java\tscript: is refused. The paged renderer uses it on every page link.
standaloneHtml
const standaloneHtml: (html: string, options?: StandaloneHtmlOptions) => string;Makes an HTML export (EngineDocument.exportHtml()) a file that opens on its own. It adds:
- the renderer's theme, the plugins' stylesheets and
stylesheets, inline, and the classtypstreamon<body>; - an optional math font (embedded bytes or a URL);
- a Content-Security-Policy, first in
<head>, that keeps the document from running scripts or loading anything except inline styles anddata:images and fonts (plusmathFont's origin when it is a URL); dir="rtl"on<html>for a right-to-left language (Typst writes the language but no direction).
It also removes <meta http-equiv="refresh">. It is a string transform, so it runs anywhere, including Node.
MountedTypstream.exportHtml({ pages: false }) calls it with the mount's plugins, stylesheets and theme.
const file = standaloneHtml(await doc.exportHtml(), { plugins: [htmlCompat], title: "Worksheet" });
const url = URL.createObjectURL(new Blob([file], { type: "text/html" }));StandaloneHtmlOptions
Prop
Type
standalonePages
const standalonePages: (html: string, options?: StandalonePagesOptions) => Promise<string>;Makes an HTML export a file laid out as the pages, as the HTML renderer shows them. It lays the export out in
document, out of sight and at the pages' size, and writes the result in standaloneHtml's file (its policy, the
plugins' stylesheets, the title) with the renderer's CSS and the Typst fonts the pages use, embedded from
typstFonts. The file runs no script: it shows the pages one under the other and prints a page per sheet. It needs a
browser. MountedTypstream.exportHtml() calls it unless pages: false.
const file = await standalonePages(await doc.exportHtml({ anchors: true }), { plugins: [htmlCompat], typstFonts });StandalonePagesOptions
Prop
Type
Class names and CSS variables
Use these to theme the output; Theming has the details.
| Selector | What it is |
|---|---|
.typstream | The HTML renderer's root. data-typstream-theme="light" or "dark" when the theme is forced. |
.typstream-caret | The caret after the last text while streaming (aria-hidden). |
[data-typstream-src] | A top-level block's first element; the value is its offset in the compiled source. |
[data-typstream-start] | A top-level block that starts in the source (after a blank line, or a heading). |
.typstream-pages | The HTML renderer's root: its sheets (.typstream-paged > .typstream-page), the document over them (.typstream-flow), and headers and footers (.typstream-marginals). |
.typstream-break | Room the HTML renderer puts where a page ends (aria-hidden). |
[data-typstream-animate] | A word fading in. |
.typstream-paged | The paged view, with data-layout="fixed", "fit-width" or "reflow". |
.typstream-page | One page, with data-page (1-based). |
.typstream-text-layer | A page's invisible, selectable text. |
The HTML renderer's theme reads --typstream-foreground, --typstream-muted, --typstream-link,
--typstream-highlight and --typstream-caret-color, set with light-dark() so the auto theme follows the page's
color-scheme. --typstream-caret replaces the caret character. The renderer sets --typstream-animation,
--typstream-duration and --typstream-easing on its root from AnimateOptions.
See also
- Vanilla JS
- Render targets
- Theming
- Exports
- Security
@typstream/engine, which compiles what these renderers show
@typstream/ai
typstream with the Vercel AI SDK. An assistant message is a Typst document (textOf, isStreaming, textStream), and an answer that edits one applies its edits as they stream (createEditSession, editPrompt).
@typstream/engine
Compiles streamed Typst in a Web Worker, with a main-thread client that heals, schedules and supervises compiles, and the worker-side server you can host yourself.