# @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.

Source: https://typstream.vercel.app/docs/reference/dom

`@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:

- **`mountTypstream`** shows 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**: `createHtmlRenderer` for the HTML target (sanitized, block-diffed Typst HTML with word fade-in
  and a caret) and `createPagedView` for the paged target (pages painted on canvases, or SVG, changed pages only,
  with a selectable text layer).
- **`standaloneHtml`** and **`standalonePages`**, 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`](/docs/reference/typstream) or [`@typstream/react`](/docs/reference/react),
which wrap `mountTypstream`. Use the renderers directly only when you drive an
[`EngineDocument`](/docs/reference/engine#enginedocument) yourself.

## Install

```npm
npm install @typstream/dom @typstream/engine
```

`mountTypstream` takes an engine from [`@typstream/engine`](/docs/reference/engine). For html-compat's layout support
in the HTML target, add [`@typstream/html-compat`](/docs/reference/html-compat) and pass its plugin.

## Example

```ts
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 caret
```

The [vanilla JS guide](/docs/getting-started/vanilla) 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 fresh `inputs` object doesn't reopen the
  document.
- **Source.** A `source` that extends the last one is pushed as a chunk; any other `source` replaces the text.
  `isStreaming` turning false finishes the document (strict heal, final compile); turning true again starts it over,
  as for a regenerated answer. `stream` (an `AsyncIterable<string>`) is the alternative to `source`: 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 to `reportError`. 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`, `inputs` and `files` change in place, and the latest `resolveImage` is
  the one called. A different `engine`, `plugins`, `preamble` or `template`, `heal` or `schedule` options, adding or
  removing `resolveImage`, 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: false` opens it right away.
- **Renderers follow the artifact's target**, so after `target` changes the old output stays until the first
  artifact of the new target.
- **Callbacks.** `onStatusChange` and `onDiagnostics` follow the document's state. `onRendered` fires for each
  artifact drawn, with its compile's report plus `renderMs` and `blocks` (HTML) or `pages` (paged). `onFallback` and
  `onWatchdog` pass on the document's [events](/docs/reference/core#telemetry-events).
- **`destroy()`** disposes the document and removes what was rendered. The engine is yours and stays.

## API

### `mountTypstream`

```ts
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`

### TypstreamOptions

Options of mountTypstream.

| Prop              | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine`          | `Engine`                                                                   | Compiles the document. Documents on one engine share its worker and compile one at a time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `source?`         | `string \| undefined`                                                      | The document so far: its whole text, growing while it streams.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `stream?`         | `AsyncIterable<string> \| null \| undefined`                               | Chunks to read instead of `source`. The document starts over when a new stream is given, and is complete when the stream ends. A stream is read once, however many mounts are given it: each shows all of its text, including what arrived before it mounted, so a mount replaced while the stream continues (React StrictMode mounts twice) loses nothing. The stream is closed (`return()`) when a chunk arrives after the last mount reading it was destroyed; a mount given it later shows what was read, as a finished document. To show an answer from the start again, pass a new stream. |
| `isStreaming?`    | `boolean \| undefined`                                                     | More `source` is coming. While false (default) the source is complete and compiles strictly (final mode); going back to true starts the document over.                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `streamingRange?` | `Range \| null \| undefined`                                               | While `isStreaming`: the part of `source` being written, in `source`'s offsets, such as a model rewriting one question of a finished document (PLAN §5.2). Only it heals as text being typed; the rest is settled and shows as it did. A finished document given a range streams again without starting over, and finishes when `isStreaming` turns false. Keep it block-aligned, as `EngineDocument.setStreamingRange` says. Ignored with `stream`.                                                                                                                                             |
| `target?`         | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                                                                                                                                                                   |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `preamble?`       | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `template?`       | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `inputs?`         | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `files?`          | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `resolveImage?`   | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                                                                                                                                                                       |
| `heal?`           | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too.                                                                                                                                            |
| `stylesheets?`    | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `animated?`       | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `caret?`          | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `fonts?`          | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `theme?`          | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `linkTarget?`     | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `textLayer?`      | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                                                                                                                                                                        |
| `islands?`        | `Readonly<Record<string, IslandRenderer>> \| undefined`                    | Island renderers by name (PLAN §8.4): markers whose name a plugin declares are mounted over their fallback drawing. Changing the object remounts every island, so keep it stable.                                                                                                                                                                                                                                                                                                                                                                                                                |
| `lazy?`           | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onStatusChange?` | `((status: DocumentStatus, state: DocumentState) => void) \| undefined`    | The document's status changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `onDiagnostics?`  | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `onRendered?`     | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                                                                                                                                                             |
| `onFallback?`     | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                                                                                                                                                            |
| `onWatchdog?`     | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |

#### `MountedTypstream`

### MountedTypstream

A document mounted by mountTypstream.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element`      | `HTMLElement`                                               | The element passed to `mountTypstream`.                                                                                                                                                                                                                                                                                                                                                                              |
| `document`     | `EngineDocument \| null`                                    | The engine document; `null` until the element first comes near the viewport (see `lazy`). A new one when the engine, preamble, heal or schedule options change.                                                                                                                                                                                                                                                      |
| `getState`     | `() => DocumentState \| null`                               | The document's state, `null` before it opens.                                                                                                                                                                                                                                                                                                                                                                        |
| `subscribe`    | `(listener: () => void) => () => void`                      | Calls `listener` whenever `getState()` changes; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                    |
| `update`       | `(options: TypstreamOptions) => void`                       | Applies new options. Anything left out goes back to its default.                                                                                                                                                                                                                                                                                                                                                     |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF (#18), from the engine that compiles the preview. Its inputs are the template's, `inputs` and `options.inputs`, without reflow's page size, so it prints at the document's own size. Opens a document that hasn't opened yet (see `lazy`). Rejects with the engine's `ExportError`.                                                                                                      |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, laid out as the pages (standalonePages; `pages: false` for standaloneHtml's reading layout), with the mount's plugins, `stylesheets`, `theme`, its Typst fonts and the fonts it uses from the engine's font catalogues; `options` add to or override them (a `mathFont`, a `title`). Otherwise as MountedTypstream.exportPdf, `options.inputs` included. |
| `exportDocx`   | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as an editable DOCX file that Word lays out as the PDF (#131): its paragraphs, lists and tables, Typst's fonts embedded. Equations, images and drawings hold their place as empty space for now. Otherwise as MountedTypstream.exportPdf.                                                                                                                                                       |
| `exportSource` | `() => string`                                              | The source the exports compile (the healed input); opens the document if needed.                                                                                                                                                                                                                                                                                                                                     |
| `destroy`      | `() => void`                                                | Disposes the document and removes what was rendered. The engine stays (it isn't ours).                                                                                                                                                                                                                                                                                                                               |

#### `TypstreamExportOptions`

What `exportPdf` and `exportDocx` take.

### TypstreamExportOptions

Options of a MountedTypstream's exports.

| Prop      | Type                                  | Description                                                                                                                                                          |
| --------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs?` | `Record<string, string> \| undefined` | `sys.inputs` for this export only, over the template's and the mount's `inputs`: a teacher's copy (`{ showAnswers: "true" }`) of a preview that shows the student's. |

#### `TypstreamHtmlExportOptions`

What `exportHtml` takes: `TypstreamExportOptions`, `StandaloneHtmlOptions`, and `pages`.

### TypstreamHtmlExportOptions

How MountedTypstream.exportHtml makes the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |
| `pages?`       | `boolean \| undefined`                                      | Laid out as the pages, as the HTML target shows them (standalonePages, the mount's Typst fonts embedded). Default true; `false` gives Typst's HTML in a reading layout (standaloneHtml).                                                           |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `inputs?`      | `Record<string, string> \| undefined`                       | `sys.inputs` for this export only, over the template's and the mount's `inputs`: a teacher's copy (`{ showAnswers: "true" }`) of a preview that shows the student's.                                                                               |

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`](/docs/reference/engine#exporterror). See [Exports](/docs/guides/exports).

```ts
const pdf = await view.exportPdf();
const key = await view.exportPdf({ inputs: { showAnswers: "true" } });
const file = await view.exportHtml({ title: "Fractions worksheet" });
```

### `createHtmlRenderer`

```ts
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.

```ts
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' `sanitize` facets 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, and `data-typstream-start` when 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; `onPages` hears the page
  count.
- **Sets the language and direction** on `root` from the document's `lang`, so right-to-left documents order lists
  and tables correctly.

#### `HtmlRendererOptions`

### HtmlRendererOptions

Options for createHtmlRenderer.

| Prop            | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| --------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `theme?`        | `"auto" \| "dark" \| "light" \| undefined`              | `auto` (default) follows the page's `color-scheme`; `light` and `dark` force one.                                                                                                                                                                                                                                                                                                                                                                                 |
| `animation?`    | `AnimateOptions \| undefined`                           | Word fade-in settings, used by updates with `animate`.                                                                                                                                                                                                                                                                                                                                                                                                            |
| `idPrefix?`     | `string \| undefined`                                   | Prefix for the document's ids (and the links to them), so documents on one page don't collide. Default: unique per renderer.                                                                                                                                                                                                                                                                                                                                      |
| `plugins?`      | `readonly TypstreamPlugin[] \| undefined`               | Plugins whose `sanitize` facet allows more tags and attributes, and whose `stylesheets` are injected before `stylesheets` (html-compat's, for one), in the order given (mountTypstream passes the engine's resolved list, dependencies first).                                                                                                                                                                                                                    |
| `linkTarget?`   | `string \| null \| undefined`                           | `target` of links to http(s) URLs; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                           |
| `stylesheets?`  | `readonly string[] \| undefined`                        | More CSS to inject next to the renderer's own and the plugins'. Injected once per document or shadow root, as constructable stylesheets where supported (no `style-src 'unsafe-inline'` needed).                                                                                                                                                                                                                                                                  |
| `injectStyles?` | `boolean \| undefined`                                  | Inject htmlRendererCss, the plugins' stylesheets and `stylesheets`. Default true; pass false to ship them yourself.                                                                                                                                                                                                                                                                                                                                               |
| `islands?`      | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each `typstream-island` marker whose name a plugin in `plugins` declares is mounted over its fallback.                                                                                                                                                                                                                                                                                                                      |
| `file?`         | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                                                                                                                                      |
| `layout?`       | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | How the document's pages are shown, as the paged view's layouts: `fixed` (default), its pages at their own size, scaled down to fit the element; `fit-width`, scaled to the element's width; `reflow`, pages as wide as the element (open the document with the paged view's `REFLOW_PREAMBLE` and `reflowInputs`, which html-compat reads). The document is laid out on sheets of its page size and margins and breaks across them where Typst breaks its pages. |
| `onPages?`      | `((count: number) => void) \| undefined`                | Called when the number of pages changes. A document whose headers or footers show the page count (`counter(page).final()`) reads it from the input `typstream-page-count` (html-compat): `mountTypstream` sets it and compiles again.                                                                                                                                                                                                                             |

#### `HtmlRenderer`

### HtmlRenderer

A rendered HTML document.

| Prop          | Type                                                              | Description                                                                                                                                                                                                                                                                                                                                                        |
| ------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `root`        | `HTMLElement`                                                     | The element the document is rendered into.                                                                                                                                                                                                                                                                                                                         |
| `update`      | `(html: string, options?: HtmlUpdateOptions) => HtmlUpdateResult` | Shows `html` (a Typst HTML export, untrusted), changing only what differs from the last update.                                                                                                                                                                                                                                                                    |
| `sourceRange` | `(node: Node) => { from: number; to: number \| null; } \| null`   | The source range of the top-level block containing `node`: from its anchor to the next one, `to` being `null` for the last. Offsets are in the compiled document (the healed source, without the preamble; map them to the raw stream with heal's `map.toInput`). `null` for nodes outside a block, or blocks without an anchor (before the first one, footnotes). |
| `blockAt`     | `(offset: number) => Element \| null`                             | The top-level block whose source range contains `offset`, if any.                                                                                                                                                                                                                                                                                                  |
| `clear`       | `() => void`                                                      | Removes the document. The renderer can be updated again.                                                                                                                                                                                                                                                                                                           |
| `dispose`     | `() => void`                                                      | Removes the document and everything the renderer added to `root`.                                                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="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`.
</Callout>

#### `HtmlUpdateOptions`

### HtmlUpdateOptions

Per-update options.

| Prop       | Type                          | Description                                                                                                                                                                                                                                                                                    |
| ---------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animate?` | `boolean \| undefined`        | Fade in new words (while streaming). Default false.                                                                                                                                                                                                                                            |
| `caret?`   | `boolean \| undefined`        | Show a caret after the last text (while streaming). Default false.                                                                                                                                                                                                                             |
| `stable?`  | `number \| null \| undefined` | While streaming, heal's stable offset (`stableOffset`): islands whose block starts at or after it are incomplete. Default: the document is complete. `null` says the stream has ended: the pages, laid out from the first block that changed while it streamed, are then laid out again whole. |

#### `HtmlUpdateResult`

### HtmlUpdateResult

What an update did.

| Prop      | Type     | Description                                |
| --------- | -------- | ------------------------------------------ |
| `blocks`  | `number` | Top-level blocks now shown.                |
| `created` | `number` | Blocks parsed and inserted by this update. |
| `removed` | `number` | Blocks removed by this update.             |
| `ms`      | `number` | Main-thread time of the update, ms.        |

#### 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](/docs/guides/islands).

### IslandInstance

A mounted island, as its renderer returns it.

| Prop      | Type                           | Description                                                                                     |
| --------- | ------------------------------ | ----------------------------------------------------------------------------------------------- |
| `update`  | `(props: IslandProps) => void` | New props: the marker's data changed, it stopped being incomplete, or the document's files did. |
| `destroy` | `() => void`                   | The marker is gone, or the renderer is disposed: unmount. The host is removed after.            |

#### `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.

### AnimateOptions

Word fade-in settings.

| Prop            | Type                                                              | Description                                                                                                                                                                                                 |
| --------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animation?`    | `"blurIn" \| "fadeIn" \| "slideUp" \| (string & {}) \| undefined` | Keyframes: `fadeIn` (default), `blurIn`, `slideUp`, or your own `@keyframes`, whose name must be `typstream-` followed by this value: `"pop"` plays `@keyframes typstream-pop` (add it with `stylesheets`). |
| `duration?`     | `number \| undefined`                                             | Per word, in ms. Default 150.                                                                                                                                                                               |
| `easing?`       | `string \| undefined`                                             | CSS easing. Default `ease`.                                                                                                                                                                                 |
| `stagger?`      | `number \| undefined`                                             | Delay between consecutive words, in ms. Default 40.                                                                                                                                                         |
| `sep?`          | `"char" \| "word" \| undefined`                                   | Animate by `word` (default; CJK characters count as words) or by `char`.                                                                                                                                    |
| `maxBacklogMs?` | `number \| undefined`                                             | How far ahead of wall-clock words may be scheduled, in ms; a fast stream compresses its stagger to fit, down to 4 ms per word. Default 320.                                                                 |

### `htmlRendererCss`

```ts
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`

```ts
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`

```ts
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.

### TypstFont

A font file to show the HTML target's text in.

| Prop      | Type                                | Description                                         |
| --------- | ----------------------------------- | --------------------------------------------------- |
| `url`     | `string \| URL`                     | Where the file is.                                  |
| `family`  | `string`                            | Its family, as Typst names it (`Libertinus Serif`). |
| `weight?` | `number \| undefined`               | Default 400.                                        |
| `style?`  | `"italic" \| "normal" \| undefined` | Default `normal`.                                   |

### `registerLoadedFont` (beta)

```ts
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`

```ts
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"`, which `mountPaged` and
  `mountTypstream` ask 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)` and `mailto` links keep their `href` (see `isSafeHref`); they open in `linkTarget`. On a
  canvas page they are `<a>` elements over their area (`.typstream-links`). Links within the document stay inert.
  Images load only from `data:` URLs.
- **Islands (beta).** With `islands` (and `plugins`, which declare the names, and `file`), each marker in the
  artifact's `islands` is mounted over its page in a box positioned in `cqw`, like the links, so redrawing a page
  leaves it alone. An island is incomplete while `PagedRenderOptions.stable` (`view.render(artifact, { stable })`) is
  at or before its source. `mountPaged` passes the document's plugins, files and stable offset. See
  [Writing an island](/docs/guides/islands#the-paged-target).
- **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`

### PagedViewOptions

Options of createPagedView.

| Prop          | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                          |
| ------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layout?`     | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | `fixed` (default): pages at their authored size, scaled down to fit the container. `fit-width`: the same pages scaled up or down to the container's width, as a PDF viewer's "fit width" shows them. `reflow`: pages fill the container's width with no space between them (use it with mountPaged's reflow layout, which compiles pages that wide). |
| `textLayer?`  | `boolean \| undefined`                                  | Build the selectable text layer. Default true.                                                                                                                                                                                                                                                                                                       |
| `linkTarget?` | `string \| null \| undefined`                           | Where safe links open (`target`); `null` leaves it to the browser. Default `"_blank"`.                                                                                                                                                                                                                                                               |
| `rootMargin?` | `string \| undefined`                                   | How far outside the viewport a page still counts as visible (IntersectionObserver `rootMargin`). Default `"50%"`.                                                                                                                                                                                                                                    |
| `onDraw?`     | `((info: DrawInfo) => void) \| undefined`               | Called after each batch of drawing (telemetry, tests).                                                                                                                                                                                                                                                                                               |
| `islands?`    | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each island marker in an artifact's `islands` whose name a plugin in `plugins` declares is mounted over its fallback drawing, in a layer over its page.                                                                                                                                                        |
| `plugins?`    | `readonly TypstreamPlugin[] \| undefined`               | The plugins whose `islands` declare which markers mount.                                                                                                                                                                                                                                                                                             |
| `file?`       | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                         |

#### `PagedView`

### PagedView

A mounted paged renderer.

| Prop      | Type                                                              | Description                                                                                                                                                                                                                                                         |
| --------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element` | `HTMLElement`                                                     | The element holding the pages (`.typstream-paged`), appended to the container.                                                                                                                                                                                      |
| `render`  | `(artifact: PagedArtifact, options?: PagedRenderOptions) => void` | Shows `artifact`. A complete artifact (`base: null`) or changed pages both work: pages are matched by index and redrawn only when their hash differs. Pages past `pageCount` are removed. The artifact's islands are mounted, moved or unmounted to match its list. |
| `pending` | `number`                                                          | Pages and text layers waiting for idle time or the next frame.                                                                                                                                                                                                      |
| `flush`   | `() => void`                                                      | Draws everything pending now (before printing, in tests).                                                                                                                                                                                                           |
| `destroy` | `() => void`                                                      | Removes the pages and stops all observers and callbacks.                                                                                                                                                                                                            |

#### `PagedRenderOptions`

### PagedRenderOptions

Options of one PagedView.render.

| Prop      | Type                          | Description                                                                                                                                           |
| --------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stable?` | `number \| null \| undefined` | While streaming, heal's stable offset (`stableOffset`): islands whose source starts at or after it are incomplete. Default: the document is complete. |

#### `DrawInfo` (beta)

<Callout type="warn" title="Beta">
`DrawInfo` and the `onDraw` option are beta: meant for telemetry and tests, and may change before the first stable
release.
</Callout>

### DrawInfo

One batch of drawing by a PagedView.

| Prop         | Type                           | Description                                                                               |
| ------------ | ------------------------------ | ----------------------------------------------------------------------------------------- |
| `pages`      | `number[]`                     | Zero-based indices of the pages drawn: their SVG put in, or their canvas painted.         |
| `textLayers` | `number[]`                     | Zero-based indices of the pages whose text layer was built.                               |
| `ms`         | `number`                       | Main-thread time of the batch, in ms (style, layout and paint follow later).              |
| `when`       | `"flush" \| "frame" \| "idle"` | `frame`: visible pages at the next frame; `idle`: in idle time; `flush`: PagedView.flush. |

### `mountPaged`

```ts
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`:

```ts
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`

### MountPagedOptions

Options of mountPaged.

| Prop              | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                          |
| ----------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                        | `canvas` (default): pages come as drawings and are painted on canvases, a millisecond or two per streamed update where SVG pages take 12–31 ms (#14); pages the engine can't draw (gradients, tilings, colour glyphs) still come as SVG. `svg`: every page as SVG in the DOM, vector at any zoom.                                                    |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                           | Page height in the reflow layout: `"a4"` (default) keeps A4's proportions at the container's width, so long documents still have pages and only the changed ones are sent; `"auto"` makes one page as tall as the content (every update then redraws the whole document: for short ones).                                                            |
| `inputs?`         | `Record<string, string> \| undefined`                   | The document's other `sys.inputs`; reflow adds its own to them.                                                                                                                                                                                                                                                                                      |
| `resizeDebounce?` | `number \| undefined`                                   | Reflow: wait this long after the container's width last changed before recompiling (ms). Default 150.                                                                                                                                                                                                                                                |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | `fixed` (default): pages at their authored size, scaled down to fit the container. `fit-width`: the same pages scaled up or down to the container's width, as a PDF viewer's "fit width" shows them. `reflow`: pages fill the container's width with no space between them (use it with mountPaged's reflow layout, which compiles pages that wide). |
| `textLayer?`      | `boolean \| undefined`                                  | Build the selectable text layer. Default true.                                                                                                                                                                                                                                                                                                       |
| `linkTarget?`     | `string \| null \| undefined`                           | Where safe links open (`target`); `null` leaves it to the browser. Default `"_blank"`.                                                                                                                                                                                                                                                               |
| `rootMargin?`     | `string \| undefined`                                   | How far outside the viewport a page still counts as visible (IntersectionObserver `rootMargin`). Default `"50%"`.                                                                                                                                                                                                                                    |
| `onDraw?`         | `((info: DrawInfo) => void) \| undefined`               | Called after each batch of drawing (telemetry, tests).                                                                                                                                                                                                                                                                                               |
| `islands?`        | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each island marker in an artifact's `islands` whose name a plugin in `plugins` declares is mounted over its fallback drawing, in a layer over its page.                                                                                                                                                        |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`               | The plugins whose `islands` declare which markers mount.                                                                                                                                                                                                                                                                                             |
| `file?`           | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                         |

#### `MountedPaged`

### MountedPaged

A paged view mounted on a document.

| Prop      | Type         | Description                                        |
| --------- | ------------ | -------------------------------------------------- |
| `view`    | `PagedView`  | The view the document renders into.                |
| `destroy` | `() => void` | Stops following the document and removes the view. |

### `REFLOW_PREAMBLE`

```ts
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"`.

```ts
const doc = engine.open({ target: "paged", preamble: REFLOW_PREAMBLE });
mountPaged(container, doc, { layout: "reflow" });
```

### `reflowInputs`

```ts
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`

```ts
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`

```ts
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 class `typstream` on `<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 and `data:` images and fonts (plus `mathFont`'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.

```ts
const file = standaloneHtml(await doc.exportHtml(), { plugins: [htmlCompat], title: "Worksheet" });
const url = URL.createObjectURL(new Blob([file], { type: "text/html" }));
```

#### `StandaloneHtmlOptions`

### StandaloneHtmlOptions

How standaloneHtml builds the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

### `standalonePages`

```ts
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`.

```ts
const file = await standalonePages(await doc.exportHtml({ anchors: true }), { plugins: [htmlCompat], typstFonts });
```

#### `StandalonePagesOptions`

### StandalonePagesOptions

How standalonePages builds the file: StandaloneHtmlOptions, and Typst's fonts.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `typstFonts?`  | `readonly TypstFont[] \| undefined`                         | Typst's fonts (`registerTypstFonts`; `typstream` passes the engine's): those the pages use are embedded in the file, so it shows them where they aren't installed.                                                                                 |
| `document?`    | `Document \| undefined`                                     | The document to lay the pages out in. Default `document`.                                                                                                                                                                                          |
| `onPages?`     | `((count: number) => void) \| undefined`                    | Called with the number of pages the export was laid out on: what `counter(page).final()` should be, through the input `typstream-page-count` (`MountedTypstream.exportHtml()` compiles again with it).                                             |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

## Class names and CSS variables

Use these to theme the output; [Theming](/docs/guides/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](/docs/getting-started/vanilla)
- [Render targets](/docs/concepts/render-targets)
- [Theming](/docs/guides/theming)
- [Exports](/docs/guides/exports)
- [Security](/docs/guides/security)
- [`@typstream/engine`](/docs/reference/engine), which compiles what these renderers show
