> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Editor

`@reductoai/docx-editor` gives you a Word-like editor in one call: toolbar, ruler, pages, review margin, find, context menu, dialogs, icons and styles.

> [!NOTE]
>
> Before you mount the editor, add the [license proxy](https://docs.reducto.ai/office/licensing/setup.md#3-in-a-browser-add-the-license-proxy) to your backend. The examples below assume it is at `/reducto`. A browser editor without a proxy opens no document.

## Vanilla JS

```ts theme={null}
import { mountDocxEditor } from "@reductoai/docx-editor";
import "@reductoai/docx-editor/style.css";

const editor = mountDocxEditor(document.getElementById("app")!, {
  proxyUrl: "/reducto",
  worker: () =>
    new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" }),
});

const bytes = new Uint8Array(await (await fetch("/contract.docx")).arrayBuffer());
await editor.open(bytes, "contract.docx");
```

Give the element a height. The editor fills it.

```css theme={null}
#app {
  height: 100vh;
}
```

## React

```tsx theme={null}
"use client";
import { useState } from "react";
import { DocxEditor, useObservable } from "@reductoai/docx-editor/react";
import { downloadDocx, downloadPdf, type EditorModel } from "@reductoai/docx-editor";
import "@reductoai/docx-editor/style.css";

const worker = () =>
  new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" });

export function Editor({ doc }: { doc: { bytes: Uint8Array; name: string } }) {
  const [model, setModel] = useState<EditorModel | null>(null);
  const hasDoc = useObservable(model, (m) => !!m?.ir);

  return (
    <div style={{ height: "100vh", display: "grid", gridTemplateRows: "auto 1fr" }}>
      <header>
        <button disabled={!hasDoc} onClick={() => model && downloadDocx(model)}>Save .docx</button>
        <button disabled={!hasDoc} onClick={() => model && downloadPdf(model)}>PDF</button>
      </header>
      <DocxEditor proxyUrl="/reducto" worker={worker} document={doc} onReady={setModel} />
    </div>
  );
}
```

The editor paints on canvases, so it must run on the client. In Next.js, load it with `dynamic(() => import("./Editor"), { ssr: false })`.

`document` opens again when the object changes, so keep it stable between renders (state or `useMemo`).

`useObservable(model, pick)` re-renders only when a picked field changes. Always pass a selector for a component that stays mounted: the model changes on every caret move.

## Svelte 5

Use `mountDocxEditor` from a Svelte 5 component. The bundle has its own Svelte runtime, so it works with any Svelte version:

```svelte theme={null}
<script lang="ts">
  import { mountDocxEditor, type DocxEditorHandle } from "@reductoai/docx-editor";
  import "@reductoai/docx-editor/style.css";

  let { bytes, name }: { bytes: Uint8Array; name: string } = $props();
  let host: HTMLDivElement;
  let editor: DocxEditorHandle | undefined;

  $effect(() => {
    editor = mountDocxEditor(host, {
      proxyUrl: "/reducto",
      worker: () =>
        new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" }),
      document: { bytes, name },
    });
    return () => editor?.destroy();
  });
</script>

<div class="editor" bind:this={host}></div>
```

To build your own chrome, replace regions with slots, or drive the headless model. See [Build your own skin](https://docs.reducto.ai/office/docx/ui/custom-skin.md) and [Headless editor](https://docs.reducto.ai/office/docx/ui/headless-editor.md).

## Options

| Option | Default | Notes |
| - | - | - |
| `proxyUrl` | none | Required in a browser. The path of your [license proxy](https://docs.reducto.ai/office/licensing/setup.md#3-in-a-browser-add-the-license-proxy) route, such as `"/reducto"` |
| `worker` | none: layout runs on the page thread | Strongly recommended. Vite: `import W from "@reductoai/docx-editor/worker?worker"` |
| `wasmUrl` | the `engine.wasm` that `@reductoai/docx` ships | The layout engine. Set it only where your bundler does not copy the file. See [Layout engine](#layout-engine) |
| `fontsUrl` | the jsDelivr copy of `@reductoai/portable-fonts` | Your own `/fonts` folder. See [Fonts](https://docs.reducto.ai/office/docx/getting-started/fonts.md) |
| `transport` | built from `worker` and `fontsUrl` | Full control. See [Headless editor](https://docs.reducto.ai/office/docx/ui/headless-editor.md#your-own-worker) |
| `fonts` | the portable fonts at `fontsUrl` | The faces that pages and PDF export paint with. Pair it with `transport` |
| `rulerUnit` | `"in"` | or `"cm"` |
| `verticalRuler` | `false` | Word's vertical ruler beside the pages |
| `document` | none | `{ bytes, name, options }` to open on mount. `options` are the `open` options, such as `markup` |
| `keybindings` | Word's keys, user changes in `localStorage` | See [Keyboard shortcuts](https://docs.reducto.ai/office/docx/ui/keyboard-shortcuts.md) |
| `spellDictionary` | `localStorage` | Where "Add to dictionary" keeps the user's words |
| `links` | none | Callbacks on link clicks and link hover. See [Links](#links) |
| `toolbarItems` | the full format bar | Controls to leave off the built-in bar or add to it. See [Change the format bar](#change-the-format-bar) |
| `readOnly` | `false` | A reader's view. See [Read-only view](#read-only-view) |
| `suggesting` | `"allow"` | `"off"` or `"on"` sets the editing mode and stops the user from changing it. See [Lock the editing mode](#lock-the-editing-mode) |
| `slots` | all built in | See below |

## Layout engine

The editor lays out pages in `@reductoai/docx/engine.wasm`, a file in the `@reductoai/docx` package. Vite, webpack and Next.js copy it into your build with a hashed name, as they do for an image, so you set nothing.

Set `wasmUrl` only with another bundler (esbuild, for example), or when you serve the file from another place. Copy `node_modules/@reductoai/docx/wasm/engine.wasm` to your site and give its URL:

```ts theme={null}
mountDocxEditor(el, {
  worker,
  wasmUrl: "/engine.wasm",
});
```

* If the engine does not load, the editor shows `no layout engine` in place of the document, and `model.error` holds the text with the URL that failed.
* The browser downloads the engine (about 2 MB compressed) once. Serve it with `content-type: application/wasm`, so the browser compiles it while it downloads.
* Use it with `worker`. On the page thread it works too, but it starts more slowly.
* If the engine fails while it opens or lays out the document (a WebAssembly trap, which Safari 18.0 sometimes hits), the editor starts a fresh engine and lays out the current document again once, in the same Session.
* A worker that you write yourself over `serveEditorHost` finds the engine the same way. See [Your own worker](https://docs.reducto.ai/office/docx/ui/headless-editor.md#your-own-worker).
* A page with a Content-Security-Policy must allow WebAssembly: add `'wasm-unsafe-eval'` to `script-src`. Without it the engine does not start and the error names the directive.
* The engine and the package come from one release. Do not mix an `engine.wasm` from one version with the editor of another.

## Save and export

```ts theme={null}
const docx = await editor.model.toBytes();          // the edited .docx
const { bytes: pdf } = await editor.model.toPdf();  // fonts embedded
const pngs = await editor.model.toPng({ pages: [1], scale: 2 });
```

`downloadDocx(model)` and `downloadPdf(model)` wrap these in a file download.

## Replace regions

Eight regions take a slot. Leave a slot out to keep the built-in, pass `null` to remove the region, or pass a function to put your own markup there.

| Region | Shown | Built-in |
| - | - | - |
| `toolbar` | always | the format bar |
| `empty` | no document open | file picker |
| `progress` | while a document opens | phase list |
| `inspector` | `model.inspectorVisible` | format panel on the right |
| `nav` | `model.nav.open` | headings and find, on the left |
| `navClosed` | `model.nav` is closed | nothing; put a rail or button here that opens the pane |
| `contextMenu` | `model.ui.contextMenu.open` | right-click menu |
| `selection` | the document is editable | the strip that floats over a selection |

```ts theme={null}
mountDocxEditor(el, {
  worker,
  slots: {
    inspector: null,
    toolbar: (host, model) => {
      const bold = document.createElement("button");
      bold.textContent = "B";
      bold.onclick = () => model.toggleBold();
      host.append(bold);
      const off = model.subscribe(() => bold.classList.toggle("on", !!model.format?.bold), "format");
      return () => off();
    },
  },
});
```

In React, the regions are props that take a node: `toolbar={<MyToolbar model={model} />}`, `inspector={null}`.

To change a built-in region, replace it with your own. The format bar is the exception: `toolbarItems` changes it (see below). If you replace most regions, use the [headless model](https://docs.reducto.ai/office/docx/ui/headless-editor.md).

Everything a toolbar needs is on the model: `model.format`, `toggleBold()`, `toggleItalic()`, `setAlignment()`, `toggleList()`, `undo()`, `redo()`, `setSuggesting()`, `model.find`, `model.review`, and `formatCommands(model)` for the full command list. [Build your own skin](https://docs.reducto.ai/office/docx/ui/custom-skin.md) shows a complete toolbar, menu bar and context menu.

## Change the format bar

You can keep the built-in format bar and remove or add controls. `hide` takes section names and control names. `add` puts your own control at the end of a section. If you do not give a section, your control gets a section of its own after the built-in sections:

```ts theme={null}
import { mountDocxEditor } from "@reductoai/docx-editor";

mountDocxEditor(el, {
  worker,
  toolbarItems: {
    hide: ["chart", "mode", "fields"],
    add: [
      {
        section: "insert",
        slot: (host, model) => {
          const button = document.createElement("button");
          button.className = "btn-ghost";
          button.textContent = "Signature";
          button.onclick = () => void model.run({ kind: "insertText", text: "Signed: ________" });
          host.append(button);
        },
      },
    ],
  },
});
```

Live example

On the docs site, this example runs live. Change `hide`, and the bar under the code changes.

| Section | Controls |
| - | - |
| `history` | `undo`, `redo` |
| `marks` | `bold`, `italic`, `underline`, `moreText` |
| `style` | `paragraphStyle` |
| `font` | `fontFace`, `fontSize` |
| `colour` | `textColour`, `highlight` |
| `paragraph` | `align`, `lists`, `paragraphSettings` |
| `insert` | `table`, `link`, `shape`, `chart`, `picture`, `textBox` |
| `fields` | `contentControl`, `toc` |
| `selection` | `pictureFormat` |
| `view` | `pageLabel`, `palette`, `outline`, `find`, `formatPanel`, `shortcuts` |
| `review` | `comment`, `markup`, `mode` |

`TOOLBAR_SECTIONS` has the same list. When the bar is too narrow, your controls fold into the More tools menu with the built-in controls. A control of your own goes under its `label` there (default "More").

To change the bar after mount, assign a new object to `model.toolbarItems`. For example, hide the insert section for a reviewer.

A hidden control only goes off the bar. Its keys and its command palette row still work. To stop all edits, set `readOnly`.

In React, `toolbarItems` is a prop, and an addition takes a `node` in place of a `slot`:

```tsx theme={null}
import { useState } from "react";
import type { EditorModel } from "@reductoai/docx-editor";
import { DocxEditor, useObservable } from "@reductoai/docx-editor/react";

function SignatureButton({ model }: { model: EditorModel | null }) {
  const ready = useObservable(model, (m) => Boolean(m?.selection));
  return (
    <button
      className="btn-ghost"
      disabled={!ready}
      onClick={() => void model?.run({ kind: "insertText", text: "Signed: ________" })}
    >
      Signature
    </button>
  );
}

export function Editor({ reviewer }: { reviewer: boolean }) {
  const [model, setModel] = useState<EditorModel | null>(null);
  return (
    <DocxEditor
      worker={() => new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" })}
      onReady={setModel}
      toolbarItems={{
        hide: reviewer ? ["insert", "fields", "font", "mode"] : ["chart"],
        add: [{ section: "insert", node: <SignatureButton model={model} /> }],
      }}
    />
  );
}
```

You can write the object inline. The editor compares it by value, so a render with the same names changes nothing. A change of `reviewer` changes the bar at once. Read the model in an added node through `useObservable(model, select)`, so the node renders only when the field it reads changes. With `hide: ["insert"]`, the built-in insert controls go away, but your Signature button stays.

## Theme

Every colour, radius, shadow and font is a CSS custom property. Override them on `:root` or on the mount element:

```css theme={null}
:root {
  --rd-accent: oklch(55% 0.2 290);
  --rd-radius: 4px;
  --rd-font-sans: "Inter", system-ui, sans-serif;
}
```

`@reductoai/docx-editor/tokens.css` lists every token.

The stylesheet styles only the editor. Its reset, font, text selection colour and scrollbars apply under the `reductoai` class. The editor puts this class on its mount root and on the menus and dialogs it shows over the page. Your page keeps its own styles, also after the editor unmounts. On a page that shows only the editor, add the class to `<html>` and import `page.css` for the page margin and background:

```html theme={null}
<html class="reductoai">
```

```ts theme={null}
import "@reductoai/docx-editor/style.css";
import "@reductoai/docx-editor/page.css";
```

For dark mode, set `data-theme="dark"` on `<html>` and repaint the pages with Word's dark-page colours:

```ts theme={null}
document.documentElement.dataset.theme = "dark";
editor.model.setScheme("dark");
```

PDF and PNG exports always paint light.

## Track changes and comments

* `model.setSuggesting(true)` tracks the user's edits (Word's *Track Changes*).
* `model.review` drives the review margin: `accept(scope)`, `reject(scope)`, `reply(id, text)`, `resolve(id, true)`, `remove(id)`. A scope is `"all"`, `"selection"`, `{ id }` or `{ ids }`.

### Lock the editing mode

By default, the user picks Editing or Suggesting in the mode menu, with ⌘⇧E (Ctrl+Shift+E), or with the command palette. A document that has Word's *Track Changes* setting on opens in Suggesting mode. Set `suggesting` to take this choice away:

| `suggesting` | Mode | The user can change it |
| - | - | - |
| `"allow"` (default) | The document's setting, then the user's choice | Yes |
| `"off"` | Editing. Every edit goes into the document directly | No |
| `"on"` | Suggesting. Every edit is a tracked change | No |

```ts theme={null}
mountDocxEditor(el, { worker, suggesting: "off" });
// React: <DocxEditor worker={worker} suggesting="off" />
```

With `"off"` or `"on"`:

* The mode menu keeps Accept all, Reject all, Show resolved comments and Change user name. It does not show the Editing and Suggesting choice.
* ⌘⇧E does nothing, and the command palette does not show *Track changes*.
* Each document opens in the locked mode, whatever its own setting is.
* Tracked changes that are already in the document still show, and the user can accept or reject them.

To change the lock later, set `model.suggestingPolicy`. `model.setSuggesting()` cannot override the lock. To remove the mode menu too, add `toolbarItems: { hide: ["mode"] }`.

### Display for Review

Word's Display for Review sets how tracked changes show. Pick it when you open the document. The first layout then uses it:

```ts theme={null}
await editor.open(bytes, "draft.docx", { markup: "none" });
// React: document={{ bytes, name, options: { markup: "none" } }}
```

Change it later with `model.setMarkup(markup)`:

| `markup` | Shows | Edits |
| - | - | - |
| `"all"` (default) | Insertions underlined and deletions struck through in the text. Deletions go to balloons while the review margin is open (`model.review.open`) | Yes |
| `"simple"` | The document as if accepted, with a bar beside each changed line | Yes |
| `"none"` | The document as if accepted | Yes |
| `"original"` | The document as if every change were rejected | No. The editor is read-only until you pick another view |

The user can type, track changes, accept and reject in every view except Original. A reopen with `keepView` keeps the current view.

### Set the author

Each tracked change and comment carries an author name. The default is `"Reducto"`. Set the name of your signed-in user before or after a document opens:

```ts theme={null}
editor.model.setRevisionAuthor("Jordan Ruiz");
```

The name stays for every document that opens later in this editor. `model.revisionAuthor` reads the current name.

An editor connected to a [document server](https://docs.reducto.ai/office/document-server.md) uses the token's `name` (else the `name` in `server`) until you set one.

The user can also set the name: *Change user name…* in the editing mode menu or the command palette. The editor does not save this name. To keep it across visits, store it yourself:

```ts theme={null}
const saved = localStorage.getItem("author");
if (saved) editor.model.setRevisionAuthor(saved);

editor.model.subscribe(() => {
  localStorage.setItem("author", editor.model.revisionAuthor);
}, "revisionAuthor");
```

## Read-only view

Set `readOnly: true` when you mount the editor (in React, the `readOnly` prop), or set `model.readOnly = true` later, to make a reader's view:

* The caret moves, text selects, and Find and Copy work. Every edit is dropped.
* The toolbar, the inspector and the selection strip go away. The context menu has only Copy, Find and the navigation pane.
* A plain click on a link follows it, and the pointer shows a hand over links. A drag that starts on a link selects text.
* The pages get a transparent text layer, so a screen reader can read them.

`model.locked` is different. It drops commands while another writer (for example, an agent turn) owns the session. The chrome stays.

## Screen readers

The pages are canvas, so the editor speaks through a polite live region (`role="status"`) next to its input:

* When the caret lands on a new line, the screen reader reads the line. An empty line reads "blank".
* An arrow key, Home or End along the same line reads the characters the caret crosses. A typed key is not read again, because the screen reader echoes it.
* A selection reads its text (up to 200 characters) and "selected".
* A tracked deletion on the line reads as "deleted: … end deleted". In All Markup, an insertion reads as "inserted: … end inserted".

The read-only view also gets the text layer, so the screen reader can read the whole page in its own reading mode.

## Links

`links` hooks every hyperlink. An `href` is a URL, or `#name` for a bookmark.

```ts theme={null}
mountDocxEditor(el, {
  worker,
  links: {
    onClick: ({ href, follow, event }) => {
      if (!href.startsWith("https://cite.example/")) return false;
      if (follow) openSource(href);
      else previewSource(href);
      return true;
    },
    onHover: (hover) => (hover ? showCard(hover.href, hover.rect) : hideCard()),
  },
});
```

* `onClick` runs on every click on a link and on every *Open link* (from the link strip or the context menu).
* `follow` is `true` when the editor would open the link: Cmd+click (Ctrl+click on Windows), a click in a read-only view, or *Open link*. Return `true` and the editor does not open it.
* A plain click while editing puts the caret in the link. `onClick` then gets `follow: false`, so you can show a preview while the user edits.
* `onHover` gets the link under the pointer and the box of its text on that line, in client pixels. It gets `null` when the pointer leaves the link. The box is measured when the pointer moves. If the pages scroll under a still pointer, the box is out of date.

In React, pass the same object as the `links` prop. Change it at any time with `model.links = { ... }`.

## Drive it with OfficeJS

An agent can edit the open document with the facade: at once, as tracked changes while the user types, or as suggestion cards the user accepts one at a time. See [Agent edits](https://docs.reducto.ai/office/docx/ui/agent-edits.md).
