# @typstream/react

> React bindings for typstream, with the Typstream component, TypstreamProvider for app-wide settings and the useTypstream() hook.

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

`@typstream/react` renders Typst streamed from an LLM, live, in React. It is a thin layer over
[`@typstream/dom`](/docs/reference/dom)'s `mountTypstream`: the component owns a `<div>`, and everything inside it
belongs to the framework-free renderers, which React never touches. On top of that it adds app-wide settings
(`TypstreamProvider`), a hook to read a document's state (`useTypstream`), and one engine worker shared by the whole
page.

## When to use it

Most apps install [`typstream`](/docs/reference/typstream) instead, which is this package with html-compat, the math
font and the vendored Typst packages set up. Use `@typstream/react` directly when you want to pick every plugin
yourself. Without React, use [`@typstream/dom`](/docs/reference/dom).

## Install

```npm
npm install @typstream/react
```

React 19 is a peer dependency (`react@^19`). The bundle is marked `"use client"`, so it works in Next.js's App Router.

## Example

```tsx title="Answer.tsx"
"use client";
import { Typstream, useTypstream } from "@typstream/react";

export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  const t = useTypstream();
  return (
    <article>
      <Typstream ref={t.ref} source={text} isStreaming={streaming} animated caret />
      <footer>
        {t.status}
        {streaming && t.openFrames[0] ? ` · writing a ${t.openFrames[0].frame}…` : ""}
      </footer>
    </article>
  );
}
```

## Behaviour

- **One worker, many documents.** Instances without an `engine` share one engine for the page. It is created on first
  use and terminated one second after the last instance (or provider) unmounts, so it survives StrictMode's remount
  and answers replacing each other. Compiles run one at a time across all its documents.
- **Only visible or streaming documents compile.** A document opens when its element comes within one screen of the
  viewport, or as soon as it streams. Offscreen, finished documents apply prop changes when they scroll back.
  `lazy={false}` opens the document right away.
- **StrictMode-safe.** The mount follows the component's lifetime: StrictMode's second mount opens a fresh document
  and the first is disposed. Unmounting disposes the document.
- **Server rendering.** On the server the component renders an empty `<div>` and starts in the browser.
- **Props apply in place.** Every render passes the latest props to the mount, which acts only on what changed.
  Inline objects (`inputs={{ showAnswers: "true" }}`) are compared by value, so they don't reopen the document on
  every render. Changing the engine, `preamble`, `template`, `plugins`, `heal` or `schedule`, or switching to or from the
  reflow layout, opens a new document, and the
  old output stays until its first compile.
- **The host element** is a `<div class="typstream-host">`, plus your `className`.

## API

### `Typstream`

```ts
const Typstream: (props: TypstreamProps) => JSX.Element;
```

Renders a streaming Typst document. Heals each prefix, compiles it in the engine's worker and shows HTML (default) or
SVG pages, keeping the last good output while a prefix doesn't compile.

The document is either `source`, its whole text so far (as streamdown takes it), or `stream`, an
`AsyncIterable<string>` of chunks. Create a stream once (for example in `useMemo`): a new stream starts the document
over. A stream is read once, however many instances are given it, and each shows all of its text, so StrictMode's
remount loses nothing.

- `isStreaming` says more `source` is coming. When it turns false, the document is finished: compiled strictly (final
  mode), without the caret. Turning it true again starts over, as for a regenerated answer. With `stream` it is
  ignored; the document finishes when the stream ends.
- `target` switches between `"html"` and `"paged"` in place; the old output stays until the new target's first
  compile.
- `inputs` sets `sys.inputs`, for example `{ showAnswers: "true" }` to recompile with an answer key instead of asking
  the model again.

```tsx
<Typstream
  source={text}
  isStreaming={streaming}
  target="paged"
  layout="fit-width"
  inputs={{ showAnswers: String(showAnswers) }}
  onStatusChange={(status) => console.log(status)}
/>
```

### `TypstreamProps`

Unset settings come from the nearest `TypstreamProvider`, then the defaults.

### TypstreamProps

Props of Typstream: the document (`source` or `stream`), how to
compile and show it, and callbacks. Unset settings come from the nearest
TypstreamProvider, then the defaults.

| Prop              | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine?`         | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `mathFont?`       | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                                                                                                                                                                          |
| `ref?`            | `Ref<TypstreamHandle> \| undefined`                                        | Receives the instance's TypstreamHandle, e.g. `useTypstream().ref`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `className?`      | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `style?`          | `CSSProperties \| undefined`                                               | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `id?`             | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `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.                                                                                                                                                                                                                                                                                                                                        |
| `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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `islands?`        | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                                                                                                                                                              |

`islands` (beta) maps island names to React components (`IslandComponents`, each an `IslandComponent`): a
[render island](/docs/guides/islands) mounts where a plugin's marker is, through a portal, so your context and
StrictMode reach it. `@typstream/mindmap/react`'s `mindmapIslands` is one.

Not available yet: a prop to turn off the engine's [fallback](/docs/concepts/fallback) (it is always on), and engine
options such as fonts or an adapter on the component. For those, create an engine with
[`createEngine`](/docs/reference/engine#createengine) and pass it as `engine`.

### `TypstreamHandle`

What a `<Typstream>`'s `ref` receives: the same object for the component's lifetime, for reading and exporting its
document from outside. `useTypstream()` wraps it and has the same exports; use the handle directly when you hold a
`ref` yourself, or need the raw `EngineDocument`.

### TypstreamHandle

A `<Typstream>` instance, for reading its document from outside (see
useTypstream). The same object for the component's lifetime.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element`      | `HTMLElement \| null`                                       | The element the document renders into, while mounted.                                                                                                                                                                                                                                                                                                                                                                                              |
| `document`     | `EngineDocument \| null`                                    | The engine document, once it has opened (documents open lazily, near the viewport).                                                                                                                                                                                                                                                                                                                                                                |
| `getState`     | `() => DocumentState \| null`                               | The document's state; `null` before it opens.                                                                                                                                                                                                                                                                                                                                                                                                      |
| `subscribe`    | `(listener: () => void) => () => void`                      | Calls `listener` whenever `getState()` or `document` changes.                                                                                                                                                                                                                                                                                                                                                                                      |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF (#18), compiled by the engine that renders the preview. It compiles with the template's inputs, the `inputs` prop and `options.inputs` (a teacher's copy: `{ showAnswers: "true" }`), but not a `layout="reflow"` preview's page size, so it prints at the document's own size. Opens a lazy document that hasn't opened yet. Rejects with the engine's `ExportError`, or an `Error` when the component isn't mounted. |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, laid out as the pages (see `standalonePages` in `@typstream/dom`; `pages: false` for `standaloneHtml`'s reading layout), with the component's plugins, `stylesheets`, `theme` and Typst fonts. `options` add to or override them (a `mathFont`, a `title`). Otherwise as TypstreamHandle.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). Otherwise as TypstreamHandle.exportPdf, `options.inputs` included.                                                                                                                                                                                                                                                                                             |
| `exportSource` | `() => string`                                              | The source the exports compile: the healed input, as a `.typ` file would hold it. Opens a lazy document that hasn't opened yet. Throws when the component isn't mounted.                                                                                                                                                                                                                                                                           |

```tsx
const ref = useRef<TypstreamHandle>(null);
// …
const pdf = await ref.current?.exportPdf();
const teacher = await ref.current?.exportPdf({ inputs: { showAnswers: "true" } });
```

The exports compile in final mode with the template's inputs, the `inputs` prop and the export's own `inputs`, but
not the reflow layout's page size, so a PDF comes out at the document's own size. An export opens a document that
hasn't opened yet (documents open lazily, near the viewport; `document` is `null` until then). Before the component
mounts and after it unmounts, the exports reject (`exportSource()` throws) with "`<Typstream>` isn't mounted". Export
errors reject with the engine's [`ExportError`](/docs/reference/engine#exporterror). See
[Exports](/docs/guides/exports).

### `TypstreamProvider`

```ts
const TypstreamProvider: (props: TypstreamProviderProps) => JSX.Element;
```

App-wide settings for every `<Typstream>` below it: the same props as the component, except the document (`source`,
`stream`, `isStreaming`) and `onStatusChange`.

```tsx
import { edu } from "@typstream/edu";
import { TypstreamProvider } from "@typstream/react";

<TypstreamProvider plugins={[edu]} theme="dark" heal={{ lint: { "currency-dollar": "warn" } }}>
  <App />
</TypstreamProvider>;
```

Settings merge from the outside in: library defaults, then each provider, then the component's own props.

| Setting | How it merges |
| --- | --- |
| `plugins`, `stylesheets` | Lists add up, outer first. A plugin key given at two levels is applied once, as the innermost definition. |
| `inputs`, `files` | Records merge; inner keys win. |
| `onRendered`, `onFallback`, `onWatchdog`, `onDiagnostics` | All are called, outer ones first. |
| Everything else | The innermost value that is set wins. |

Without an `engine`, the provider keeps the page's shared engine alive while it is mounted, so the worker survives
documents coming and going (a chat switching conversations). A provider is also the place to wire every document to
a log or analytics sink once; see [Telemetry](/docs/guides/telemetry).

### `TypstreamProviderProps`

### TypstreamProviderProps

Props of TypstreamProvider.

| Prop             | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children?`      | `ReactNode`                                                                | The app, or the part of it these settings apply to.                                                                                                                                                                                                                                                                                                                                                                                                   |
| `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.                                                                                                                                                                                             |
| `lazy?`          | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                 |
| `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.                                                                                                                                                                                                                                                                                                                                                                                       |
| `engine?`        | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                     |
| `mathFont?`      | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                               |
| `islands?`       | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                   |

### `TypstreamDefaults`

The settings a provider holds, and that `TypstreamProps` extends. Everything except `engine`, `resolveImage`, `islands`
and plugins' functions is serializable, so it can be stored per organization or per user.

### TypstreamDefaults

Settings that make sense for every document of an app. Everything except
`engine`, `resolveImage`, `islands` and plugins' functions is serializable, so it can
be stored per organization or per user.

| Prop             | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `engine?`        | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                     |
| `mathFont?`      | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                               |
| `islands?`       | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                   |
| `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.                                                                                                                                                                                             |
| `lazy?`          | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                 |
| `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.                                                                                                                                                                                                                                                                                                                                                                                       |

### `TelemetryHooks`

```ts
type TelemetryHooks = Pick<TypstreamOptions, "onRendered" | "onFallback" | "onWatchdog" | "onDiagnostics">;
```

The callbacks for logging and telemetry, on the component and on the provider. The library sends nothing itself;
the app decides what to collect. The event shapes are [`@typstream/core`'s](/docs/reference/core#telemetry-events).

### `useTypstream`

```ts
const useTypstream: () => TypstreamInfo;
```

Reads a `<Typstream>`'s document: status, diagnostics, healed source, open frames. Pass `t.ref` to the component.
React refs don't announce when they're set, so the hook hands out its own callback ref rather than reading yours.

```tsx
const t = useTypstream();
return (
  <>
    <Typstream ref={t.ref} source={text} isStreaming />
    {t.status === "stale" ? <p>Showing the last good render…</p> : null}
  </>
);
```

### `preloadTypstream`

```ts
const preloadTypstream: (options?: PreloadTypstreamOptions) => TypstreamPreload;
```

Gets the engine ready before the first `<Typstream>` mounts, so that document renders at once instead of waiting for
the wasm (about 6 MB) and fonts. Call it when a document is likely soon: the user opens the "Generate" dialog, sends
the prompt, or reaches the step before the page view.

```tsx
import { preloadTypstream } from "@typstream/react";

<button onClick={() => { preloadTypstream({ plugins: [edu] }); generate(); }}>Generate</button>
```

- **`level: "engine"`** (default) starts the page's shared engine, the one every `<Typstream>` without an `engine`
  uses. Then it runs `engine.preload()` with `plugins`, `targets` and `text`: warm-up compiles that load the
  plugins' packages, modules and fonts. It keeps the engine for `holdMs` (`PRELOAD_HOLD_MS`, a minute) and then lets
  it go. A `<Typstream>` that mounts in the meantime keeps it for as long as it needs it. `release()` lets go
  earlier; `holdMs: Infinity` keeps it until then.
- **`level: "fetch"`** only downloads the wasm and base fonts into the browser's caches (`prefetchEngine` from
  [`@typstream/engine/prefetch`](/docs/reference/engine#typstreamengineprefetch)). It starts no worker and holds no
  memory, for a document that may never come.
- **`ready`** resolves once the engine is warm (or the files are cached). It rejects if the engine can't start or a
  download fails. Ignoring it is safe: nothing is reported as unhandled.
- On a server (no `Worker`) it does nothing, so it's safe to call during rendering in Next.js.

An engine you pass as the `engine` prop isn't the shared one: warm that with `engine.preload()` instead.

### `usePreloadTypstream`

```ts
const usePreloadTypstream: (when?: boolean, options?: PreloadTypstreamOptions) => void;
```

`preloadTypstream` for a component. While the component is mounted and `when` is true, it keeps the shared engine
warm for the `<Typstream>`s to come, for the whole time rather than `holdMs`. Afterwards it lets the engine go, a
moment later. Put it in the screen that leads to a document: a chat's composer, or the dialog that starts a
generation (`usePreloadTypstream(open)`). `options` are read when `when` turns true.

```tsx
function GenerateDialog({ open }: { open: boolean }) {
  usePreloadTypstream(open, { plugins: [edu] });
  // …
}
```

### `PreloadTypstreamOptions`

### PreloadTypstreamOptions

Options of preloadTypstream and usePreloadTypstream: what
to warm (the engine's `PreloadOptions`), and how far to go.

| Prop       | Type                                      | Description                                                                                                                                                                                                                                                                                                                   |
| ---------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?` | `readonly TypstreamPlugin[] \| undefined` | Plugins the coming documents use. Their packages, fixer and generator modules and catalogue fonts load now, and the first of each plugin's prompt examples compiles, so what it draws (a generator's diagrams, a package's imports) is warm too.                                                                              |
| `level?`   | `"engine" \| "fetch" \| undefined`        | `engine` (default): start the default engine's worker, compile the wasm, load the fonts and compile warm-up documents with `plugins`, so the first document renders at once. `fetch`: only download the wasm and base fonts into the browser's caches, with no worker and no memory held, for a document that may never come. |
| `holdMs?`  | `number \| undefined`                     | `engine` level: how long, in ms, to keep the engine for documents to come when none mounts, before letting it go (a `<Typstream>` mounted meanwhile keeps it for as long as it needs it). Default PRELOAD_HOLD_MS; `Infinity` keeps it until `release()`.                                                                     |
| `targets?` | `readonly CompileTarget[] \| undefined`   | The targets the coming documents compile to, each compiled once. Default both: `["html", "paged"]`. The plugins' examples compile in the first only.                                                                                                                                                                          |
| `text?`    | `string \| undefined`                     | Typst to compile instead of the built-in sample and the plugins' examples, e.g. a document like the ones the app makes.                                                                                                                                                                                                       |

`plugins`, `targets` and `text` are the engine's [`PreloadOptions`](/docs/reference/engine#preloadoptions).

### `TypstreamPreload`

### TypstreamPreload

A preload under way: preloadTypstream's answer.

| Prop      | Type            | Description                                                                                                                                                                          |
| --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ready`   | `Promise<void>` | Resolves when the engine is warm (`fetch`: when the files are cached). Rejects if the engine can't start or a download fails; ignoring it is safe, nothing is reported as unhandled. |
| `release` | `() => void`    | Lets go of the engine now rather than after `holdMs`. Later calls do nothing.                                                                                                        |

<Callout type="warn" title="Beta">
`preloadTypstream`, `usePreloadTypstream`, `PreloadTypstreamOptions`, `TypstreamPreload` and `PRELOAD_HOLD_MS` are
beta. See [Preloading the engine](/docs/guides/preloading).
</Callout>

### `TypstreamInfo`

### TypstreamInfo

What useTypstream returns.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                      |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ref`          | `(handle: TypstreamHandle \| null) => void`                 | Pass to `<Typstream ref>`. Stable.                                                                                                                                                                                                                                                                                               |
| `handle`       | `TypstreamHandle \| null`                                   | The instance, once mounted.                                                                                                                                                                                                                                                                                                      |
| `state`        | `DocumentState \| null`                                     | The document's whole state; `null` until it opens.                                                                                                                                                                                                                                                                               |
| `status`       | `DocumentStatus`                                            | `idle` until the document opens.                                                                                                                                                                                                                                                                                                 |
| `diagnostics`  | `readonly Diagnostic[]`                                     | Diagnostics of the latest compile, in `source` coordinates.                                                                                                                                                                                                                                                                      |
| `healedSource` | `string`                                                    | The healed source the engine compiles (empty until the document opens).                                                                                                                                                                                                                                                          |
| `openFrames`   | `OpenFrame[]`                                               | Constructs still open at the end of the input, innermost first.                                                                                                                                                                                                                                                                  |
| `document`     | `EngineDocument \| null`                                    | The engine document. For exports, prefer `exportPdf()` and friends: the document's own exports use its inputs, which include a reflow preview's page size.                                                                                                                                                                       |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF, at its own page size (a reflow preview's width left out), with the template's inputs, the `inputs` prop and `options.inputs`. Opens a lazy document that hasn't opened yet. Rejects with the engine's `ExportError`, or an `Error` when no `<Typstream>` is mounted. See TypstreamHandle.exportPdf. |
| `exportDocx`   | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as an editable DOCX file. See TypstreamHandle.exportDocx.                                                                                                                                                                                                                                                   |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, with the component's plugins, `stylesheets` and `theme`; `options` add to or override them. See TypstreamHandle.exportHtml.                                                                                                                                          |
| `exportSource` | `() => string`                                              | The healed source the exports compile. Throws when no `<Typstream>` is mounted.                                                                                                                                                                                                                                                  |

`status` is `"idle"` until the document opens, then one of the engine's
[document statuses](/docs/reference/engine#documentstatus): `idle`, `compiling`, `stale`, `error` or `done`.

### Re-exported types

For convenience the package re-exports types from the packages it builds on:

- From [`@typstream/engine`](/docs/reference/engine): `Engine`, `DocumentState`, `DocumentStatus`, `PreloadOptions`.
- From [`@typstream/dom`](/docs/reference/dom): `StandaloneHtmlOptions`, `TypstreamExportOptions` and
  `TypstreamHtmlExportOptions`, what the exports take.
- From [`@typstream/core`](/docs/reference/core#telemetry-events): `AppliedFix`, `CompiledEvent`, `CompileReport`,
  `DocumentEvent`, `FallbackEvent`, `FallbackLevel`, `RenderedEvent`, `WatchdogEvent`.

## See also

- [Rendering in React](/docs/getting-started/react)
- [Next.js and the AI SDK](/docs/getting-started/nextjs-ai-sdk)
- [Streaming](/docs/concepts/streaming)
- [Render targets](/docs/concepts/render-targets)
- [Telemetry](/docs/guides/telemetry)
- [`@typstream/dom`](/docs/reference/dom), which this package wraps
