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

# Headless editor

`@reductoai/docx-editor/model` is the layer under the editor chrome. It has no Svelte and no markup of its own. You get `EditorModel`: it opens a document, paints the pages, holds the caret and selection, takes keyboard and mouse input, and runs commands. You build every button and panel.

## The smallest editor

```ts theme={null}
import {
  EditorModel,
  attachEditorInput,
  createDefaultHost,
  portableFonts,
} from "@reductoai/docx-editor/model";
import "@reductoai/docx-editor/style.css";

const fonts = portableFonts("/fonts");
const model = new EditorModel({
  fonts,
  transport: {
    fonts,
    createHost: (bytes, name, onProgress) => createDefaultHost(fonts, bytes, name, onProgress),
    spawnWorker: () => {
      const worker = new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" });
      worker.postMessage({ type: "configure", fontsUrl: "/fonts" });
      return worker;
    },
  },
});

// DOM: a stage that takes input, with the scrolling pages inside it
const stage = document.querySelector<HTMLElement>("#stage")!;
const pages = document.querySelector<HTMLElement>("#pages")!;
model.attach(pages);
const detach = attachEditorInput(stage, model);

await model.open(bytes, "report.docx");
```

```html theme={null}
<div id="stage" class="viewer">
  <div id="pages" class="pages paper-bg" tabindex="-1"></div>
</div>
```

`style.css` styles the `.viewer`, `.pages` and page classes. If you do not import it, copy the page and caret rules from `@reductoai/docx-editor/styles.css`. The base rules (reset, font, selection colour, scrollbars) apply only under the `reductoai` class. To use them in your chrome, add the class to its root.

When you are done, call `detach()` and `model.destroy()`.

## What each part does

| Part | Role |
| - | - |
| `transport.createHost` | Builds the document session: parse, layout, the command interpreter. Runs in the worker, or in the page if there is no worker |
| `transport.spawnWorker` | Starts the worker. Without it, or if the worker fails to load, the session runs in the page |
| `fonts` | Gives face bytes to the page so the canvases paint with the faces that the layout measured |
| `model.attach(pagesEl)` | Paints pages into the element, as cards that scroll |
| `attachEditorInput(stage, model)` | Adds a hidden input for typing, IME and clipboard, plus mouse and keyboard handlers |

## Bind your UI

`EditorModel` extends `Observable`:

```ts theme={null}
model.subscribe(() => render());            // any change
model.subscribe(() => renderToolbar(), "format"); // one field
```

Fields you will use:

| Field | Meaning |
| - | - |
| `model.ir` | The layout of the open document, or `null` |
| `model.format` | Format at the caret: bold, italic, font, size, style, alignment … |
| `model.selection` | Anchor and focus positions |
| `model.canUndo`, `model.canRedo` | For undo and redo buttons |
| `model.page`, `model.pageLabel` | The page most in view |
| `model.progress` | Phases while a document opens |
| `model.error` | The last error |
| `model.suggesting` | Track-changes mode |
| `model.suggestingPolicy` | `"allow"`, or `"off"`/`"on"` to lock the mode. See [Lock the editing mode](https://docs.reducto.ai/office/docx/ui/editor.md#lock-the-editing-mode) |
| `model.markup` | Display for Review: `"all"`, `"simple"`, `"none"` or `"original"` |
| `model.readOnly` | A reader's view. See [Read-only view](https://docs.reducto.ai/office/docx/ui/editor.md#read-only-view) |
| `model.revisionAuthor` | The author of new tracked changes and comments |

Commands:

```ts theme={null}
model.toggleBold();
model.setAlignment("center");
model.toggleList("decimal");
model.undo();
model.setSuggesting(true);
model.setRevisionAuthor("Jordan Ruiz");
await model.run({ kind: "runFormat", format: { sizePt: 14, color: "C00000" } });
```

`await model.run(command)` and helpers such as `addBookmark(model, name)` resolve when the edit is applied locally, after the edits queued before it. Host reads such as `model.host.bookmarks()` then see the edit in solo and live mode. Before a server exec read or download, also await `editor.live.synced()`: see [When an edit is done](https://docs.reducto.ai/office/document-server.md).

`model.undo()` takes back typing in Word's steps. Text typed without a pause in the edits is one step, across its spaces and full stops. The step ends when the caret moves (even back to the same place), at Backspace or at a format change. Word's AutoCorrect capital at the start of a sentence is a step of its own.

`formatCommands(model)` returns every command as a list (`{ id, group, label, run }`), which is a good start for a command palette.

Side models for the panels: `model.review` (comments and changes), `model.find`, `model.nav` (headings), `model.spell` (spelling), `model.controls` (content controls), `model.ui` (context menu, palette and dialogs). `model.keys` is the keymap: `run(id)`, `label(id)`, `enabled(id)` and `register(command)`.

## Selection, hit-test and links

The model gives the selection and the pages in client pixels, so your chrome does not have to read the layout:

| Call | Returns |
| - | - |
| `model.select({ anchor, focus })` | Selects a range. A position is `{ target, offset }`. A target is `{ kind: "paragraph", bodyIndex }` or a table cell |
| `model.scrollCaretIntoView()` | Scrolls the caret into view |
| `model.selectionText()` | The selection as plain text, as Copy puts it on the clipboard |
| `model.selectionRects()` | One `DOMRect` for each selected line. Empty for a caret |
| `model.selectionBox()` | One `DOMRect` around the selection on the caret's page, or the caret |
| `model.hitTest(clientX, clientY)` | `{ page, x, y, position, link }` for a point on a page, or `null` |
| `model.links` | `{ onClick, onHover }`. See [Links](https://docs.reducto.ai/office/docx/ui/editor.md#links) |

`page` from `hitTest` is the page number that the other page calls take. `x` and `y` are in hundredths of a millimetre from the page's top-left corner. `position` is the text position under the point, and `link` is the link's `href`.

## Page overlays

`model.overlays` pins your own nodes to a page. The box is in points from the page's top-left corner:

```ts theme={null}
const tab = document.createElement("button");
tab.textContent = "Sign here";
tab.style.pointerEvents = "auto";
tab.addEventListener("pointerdown", (event) => event.stopPropagation());

const pin = model.overlays.mount(1, tab, { x: 72, y: 690, w: 120, h: 24 });
pin.move({ x: 72, y: 700, w: 120, h: 24 }); // or move(box, page)
pin.remove();
```

* The nodes stay in place when the user scrolls, zooms or edits.
* When a page goes away, its nodes leave the DOM. They come back when the page comes back.
* `model.overlays.list()` returns every pinned node.
* The layer is over the page and under the caret and selection. It takes no pointer events. A node that takes clicks sets `pointer-events: auto` and stops the event. If it does not, the press also places the caret.

## Example: a selection bar and a citation preview

The editor below has its own selection bar with an *Ask* button and a citation card on hover. It uses only the model:

```ts theme={null}
const bar = document.querySelector<HTMLElement>("#bar")!;
const card = document.querySelector<HTMLElement>("#card")!;

model.subscribe(() => {
  const rects = model.selectionRects();
  const last = rects.at(-1);
  bar.hidden = !last || model.readOnly;
  if (last) bar.style.translate = `${last.right}px ${last.bottom + 4}px`;
}, "selection");

document.querySelector("#ask")!.addEventListener("click", () => {
  askAssistant(model.selectionText(), model.selection);
});

model.links = {
  onHover: (hover) => {
    card.hidden = !hover?.href.startsWith("https://cite.example/");
    if (hover && !card.hidden) {
      card.textContent = citationTitle(hover.href);
      card.style.translate = `${hover.rect.left}px ${hover.rect.bottom + 4}px`;
    }
  },
  onClick: ({ href, follow }) => {
    if (!href.startsWith("https://cite.example/")) return false;
    if (follow) openSource(href);
    return true;
  },
};
```

```html theme={null}
<div id="stage" class="viewer">
  <div id="pages" class="pages paper-bg" tabindex="-1"></div>
</div>
<div id="bar" hidden style="position: fixed; left: 0; top: 0"><button id="ask">Ask</button></div>
<div id="card" hidden style="position: fixed; left: 0; top: 0"></div>
```

`selectionRects` and `hover.rect` are in client pixels, so the bar and the card use `position: fixed`. The bar moves only when the selection changes. To follow a scroll as well, subscribe to `"page"` or listen to the scroll of `#pages`.

For a full skin (toolbar, menus, galleries, context menu) built this way, read [Build your own skin](https://docs.reducto.ai/office/docx/ui/custom-skin.md). [Editor actions](https://docs.reducto.ai/office/docx/api/editor-actions.md) and [Fonts, colours and galleries](https://docs.reducto.ai/office/docx/api/editor-galleries.md) list the helpers that a skin calls.

## Your own worker

The default worker uses the portable fonts. To use other fonts or other layout options, write your own worker. It is three lines:

```ts theme={null}
// editor.worker.ts
import { createBrowserEditorHost, tableFaceProvider } from "@reductoai/docx/browser";
import { serveEditorHost } from "@reductoai/docx-editor/model";

const fonts = tableFaceProvider(() => fetch("/fonts/font-table.json").then((r) => r.json()), (file) => `/fonts/${file}`);

serveEditorHost({
  fonts,
  createHost: (bytes, name, onProgress) =>
    createBrowserEditorHost(bytes, { fonts, name, onProgress, trackedChanges: "inline", markupGutter: false }),
});
```

Then point the page at it:

```ts theme={null}
const model = new EditorModel({
  fonts,
  transport: {
    fonts,
    createHost: /* the same function, for the in-page fallback */,
    spawnWorker: () => new Worker(new URL("./editor.worker.ts", import.meta.url), { type: "module" }),
  },
});
```

Use the same fonts in the page and in the worker. The worker sends face bytes to the page with each layout, and the page skips the faces it already has.

`trackedChanges: "inline"` with `markupGutter: false` is what the built-in editor uses. The model then switches the view for Display for Review and the review margin (`model.setMarkup`, `open(..., { markup })`), so keep these values in your own worker.
