typstream

@typstream/react

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

@typstream/react renders Typst streamed from an LLM, live, in React. It is a thin layer over @typstream/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 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.

Install

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

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

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

Prop

Type

islands (beta) maps island names to React components (IslandComponents, each an IslandComponent): a render island 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 (it is always on), and engine options such as fonts or an adapter on the component. For those, create an engine with 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.

Prop

Type

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. See Exports.

TypstreamProvider

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.

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.

SettingHow it merges
plugins, stylesheetsLists add up, outer first. A plugin key given at two levels is applied once, as the innermost definition.
inputs, filesRecords merge; inner keys win.
onRendered, onFallback, onWatchdog, onDiagnosticsAll are called, outer ones first.
Everything elseThe 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.

TypstreamProviderProps

Prop

Type

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.

Prop

Type

TelemetryHooks

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.

useTypstream

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.

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

preloadTypstream

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.

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). 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

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.

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

PreloadTypstreamOptions

Prop

Type

plugins, targets and text are the engine's PreloadOptions.

TypstreamPreload

Prop

Type

Beta

preloadTypstream, usePreloadTypstream, PreloadTypstreamOptions, TypstreamPreload and PRELOAD_HOLD_MS are beta. See Preloading the engine.

TypstreamInfo

Prop

Type

status is "idle" until the document opens, then one of the engine's document statuses: 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: Engine, DocumentState, DocumentStatus, PreloadOptions.
  • From @typstream/dom: StandaloneHtmlOptions, TypstreamExportOptions and TypstreamHtmlExportOptions, what the exports take.
  • From @typstream/core: AppliedFix, CompiledEvent, CompileReport, DocumentEvent, FallbackEvent, FallbackLevel, RenderedEvent, WatchdogEvent.

See also

On this page