# Agents (/docs/agents)



`@betteroffice/agents` gives agents a bounded document workflow:
discover → grep → read → propose → render → verify → export.
DOCX supports body text, headers, footers, and table cell stories. XLSX adds
cell input and formula proposals and PPTX adds slide-text proposals, each with
its own direct-edit and PNG preview tools; tracked changes are DOCX-only.

## MCP [#mcp]

```sh
bun add @betteroffice/agents
codex mcp add betteroffice -- /absolute/path/to/node_modules/.bin/betteroffice-mcp --root /absolute/path/to/documents
```

Start a new Codex session. Ask it to find a section, propose a precise edit,
inspect the proposed page, and export a new file. The local server exposes
literal search, bounded reads, reviewable edits, PNG page previews, and
save/reopen checks. File paths are checked against the configured root and exports never
overwrite existing files. Use `--read-only` to expose inspection tools only.

## SDK [#sdk]

```ts
import { openDocx } from '@betteroffice/agents';
import { renderDocxPage } from '@betteroffice/agents/render';

const doc = await openDocx(bytes, { renderer: renderDocxPage });
try {
  const page = doc.grep({ query: 'Executive summary' });
  const paragraph = doc.read(page.matches[0].ref);
  const proposal = doc.propose({
    author: 'document-agent',
    edits: [{
      ref: paragraph.ref,
      revision: paragraph.revision,
      oldText: 'Executive summary',
      newText: 'Board summary',
    }],
  });
  const preview = await doc.render(1, proposal.id);
  const checks = await doc.verify(proposal.id);
  const revisedBytes = await doc.export(proposal.id);
} finally {
  doc.close();
}
```

Use `attachDocx(session)` with a directly owned `YrsSession`. The default React
editor keeps its session in a worker; use its async ref methods, including
`readParagraphs` and `proposeChanges`, for live editor integration. Proposals
check target text and formatting before acceptance; unrelated edits survive.
Acceptance is one undo step. Exporting a pending proposal leaves the live
document unchanged.

Follow search `nextCursor`, outline `nextOffset`, and read `nextStart` values
to retrieve more context. Paragraph refs belong to an open session. Text
offsets use UTF-16. Proposals replace text within one paragraph; paragraph
breaks, embeds, and existing tracked changes are protected from them. `edit`
batches (the MCP `docx_edit` tool) apply paragraph, table row, comment, and
section edits directly.

Save/reopen checks do not establish semantic or visual correctness. Inspect
the rendered pages and their warnings before delivery.

The [package guide](https://github.com/openooxml/betteroffice/tree/main/packages/agents)
contains the complete tool catalog, limits, host integration, and testing setup.

## Spreadsheets and presentations [#spreadsheets-and-presentations]

`openXlsx(bytes)` and `openPptx(bytes)` expose the same review, accept/reject,
proposed export, and save/reopen workflow in their own sessions; `attachXlsx`
and `attachPptx` wrap a live editor's handle.

For XLSX, use `office_outline` to find sheet IDs, `office_cells` to read an A1
range, and `office_propose_cells` with `{cell, input}`. Inputs replace entire
cells; prefix formulas with `=`. Search is case-sensitive over displayed values.
For PPTX, use `office_grep` and `office_propose` with `{match, newText}` to replace
one occurrence inside a slide paragraph.

The MCP server adds direct edits: `xlsx_write_range`, `xlsx_format`, `xlsx_sort`,
and tools for rows, columns, sheets, defined names, filters, charts, and
conditional formats, with `xlsx_preview` rendering a range as PNG; `pptx_edit`
changes text, slides, layout mapping, shapes, images, notes, comments, and table
structure, with `pptx_preview` rendering a slide.

Follow pagination, and narrow searches that report the 10,000-match cap.
Any committed change invalidates outstanding XLSX/PPTX proposals. Accepting a
proposal as tracked changes is DOCX-only. See the package guide for the complete
tool catalog and formula calculation limits.


# Collaboration (/docs/collaboration)



BetterOffice editors synchronize through a Yrs CRDT. Each editor exposes its
replica to a collaboration provider, which exchanges updates over a transport
you supply. A relay routes those updates between peers in the same room.

`DocxEditor` reads asynchronously by default; deprecated `legacySyncApi` keeps the synchronous API and is removed in 0.6.0. Passing `collaboration` keeps the default editor.

## How updates flow [#how-updates-flow]

1. The editor publishes its replica through `collaboration.onReplica`.
2. The format provider converts replica updates to Yjs sync-v1 frames.
3. Your transport moves those frames between peers in the same document room.

Use a distinct room ID for every document and format. Updates from different
documents or formats are not interoperable.

## Deploy the Cloudflare relay [#deploy-the-cloudflare-relay]

The [reference relay](https://github.com/openooxml/betteroffice/tree/main/apps/relay)
uses one Durable Object per room. It accepts WebSockets at `/room/:roomId`,
replays retained frames to new peers, and broadcasts new binary frames. Its
[`wrangler.jsonc`](https://github.com/openooxml/betteroffice/blob/main/apps/relay/wrangler.jsonc)
contains the required `ROOMS` binding and SQLite migration.

From a BetterOffice checkout:

```bash
bun install
bun run --filter @betteroffice/collaboration-relay dev
bun run --filter @betteroffice/collaboration-relay deploy
```

Point your browser transport at the deployed Worker origin. The complete demo
adapter is [`createRoomTransport`](https://github.com/openooxml/betteroffice/blob/main/apps/demo/app/collab/createRoomTransport.ts);
it handles WebSocket reconnects, binary ownership, and backpressure. If you write
your own adapter, implement the `CollaborationTransport` exported by the format
package. A `false` return from `send` means the adapter must emit `drain` when it
can accept another frame.

## Connect an editor [#connect-an-editor]

Import `CollaborationProvider` from the package for your format:

| Format             | Provider import                    |
| ------------------ | ---------------------------------- |
| DOCX               | `@betteroffice/docx/collaboration` |
| XLSX               | `@betteroffice/xlsx/collaboration` |
| PPTX               | `@betteroffice/pptx/collaboration` |
| VSDX (from source) | `@betteroffice/vsdx`               |

[VSDX packages](./vsdx) are available from source.

Create the provider when the editor publishes its replica:

```ts
const onReplica = (replica) => {
  provider?.destroy();
  transport?.disconnect();
  if (!replica) return;

  transport = createRoomTransport(relayOrigin, roomId);
  provider = new CollaborationProvider(replica, transport);
  provider.connect();
};
```

Pass the collaboration options to your editor:

```tsx
const collaboration = { clientId, initialUpdate, onReplica };

<DocxEditor documentBuffer={docxBytes} collaboration={collaboration} />;
<XlsxEditor file={xlsxBytes} collaboration={collaboration} />;
<PptxEditor file={pptxBytes} fonts={fonts} collaboration={collaboration} />;
<VsdxEditor file={vsdxBytes} fonts={fonts} collaboration={collaboration} />;
```

`clientId` must be unique per open peer. `initialUpdate` must represent the
shared starting state for that document. The demo generates these states with
[`build-collaboration-seeds.ts`](https://github.com/openooxml/betteroffice/blob/main/apps/demo/scripts/build-collaboration-seeds.ts).

Call `provider.destroy()` and disconnect the transport when the editor unmounts
or changes rooms.

## Relay checkpoints and rehydration [#relay-checkpoints-and-rehydration]

The reference relay checkpoints its retained updates automatically after 512
frames, when the retained byte budget would be exceeded, or when a frame is
larger than 64 KiB. A checkpoint merges the binary Yjs v1 updates without
changing their CRDT identities. New updates form a short tail after it.

The checkpoint and deletion of covered updates commit in one storage
transaction. Checkpoint bytes are split into 64 KiB storage chunks. When a room
restarts, it loads the checkpoint and newer tail before accepting clients.
Joining clients receive both, then exchange state vectors with the relay to
supply a missing initial seed or offline changes. No online peer is required to
recover state already persisted in the room. Hosts with a Durable Object binding
can also call `await room.checkpoint()` to compact immediately.

Checkpoints preserve updates with missing dependencies, so updates arriving out
of order are still mergeable when their dependencies arrive. They deduplicate
and compact the update log; they do not garbage-collect deleted CRDT content,
reset client clocks, or provide a version-history archive. State already evicted
by an older relay cannot be recovered from its remaining log alone: a client
with the complete state must reconnect.

The checkpoint must fit in the 16 MiB collaboration frame budget. If merging
cannot fit a new update, the relay refuses it and preserves the previously
committed state. Storage failures close connections instead of broadcasting
uncommitted updates. The next request reloads committed state, so clients can
reconnect once storage recovers. The relay accepts one state-vector query per
frame to bound diff computation and caches merged state between updates.
Malformed legacy update entries are removed during repair; a peer with complete
state can supply missing history on reconnect. Malformed checkpoint storage
prevents the room from serving partial state.

The reference room still expires after 24 hours without connected clients.
Persist your source document and long-term backups separately; a checkpoint is
not a permanent saved Office file.

## Production setup [#production-setup]

Before deploying, add authentication and room authorization, set connection and
storage quotas, and choose a retention policy for long-lived documents. The
reference relay checkpoints automatically within its 16 MiB frame budget and
keeps the existing 24-hour idle expiration.
It caps total awareness payloads at 32 KiB per frame and allows a burst of 30
awareness frames per connection, replenishing 30 frames per second. These limits
apply by default, including to frames that also carry document updates.


# Getting started (/docs)



BetterOffice lets you open, edit, render, and save documents, spreadsheets, and
slides. Embed a React editor in your app, build on the JavaScript cores, or use
the Rust and Python APIs for server-side processing.

[Try the demo](https://demo.betteroffice.dev) or choose a guide to get started.

## Guides [#guides]

* [Packages](./packages): choose packages for your language and file format.
* [JavaScript](./javascript): install a React editor or use the framework-free core.
* [Migrating to 0.5](./migrating-to-0-5): move React editor hosts to the async editor API.
* [Rust](./rust): open, edit, render, and save files with native APIs.
* [Python](./python): work with DOCX, XLSX, and PPTX files from Python.
* [Agents](./agents): search, read, edit and preview Office files from an agent.
* [Collaboration](./collaboration): connect editors and deploy a relay.

## Releases and fidelity [#releases-and-fidelity]

* [Release notes](https://github.com/openooxml/betteroffice/releases): changes in each version.
* [Visual fidelity results](https://github.com/openooxml/betteroffice#benchmarks): published releases and source builds compared with Microsoft Office.


# JavaScript (/docs/javascript)



DOCX, XLSX, and PPTX each provide a framework-free core, a React editor, and
locale strings under the `@betteroffice` scope.

```bash
npm install @betteroffice/docx-react @betteroffice/docx react react-dom
```

`react` and `react-dom` (18 or 19) are peer dependencies of every `-react`
package.

## Add a React editor [#add-a-react-editor]

```tsx
import { DocxEditor } from "@betteroffice/docx-react";
import "@betteroffice/docx-react/styles.css";

<DocxEditor documentBuffer={bytes} onSave={(saved) => upload(saved)} />;
```

`documentBuffer` accepts an `ArrayBuffer`, `Uint8Array`, `Blob`, or `File`.
`file` and `fileName` are aliases of `documentBuffer` and `documentName`; when
both names are set, `documentBuffer` and `documentName` win.
`DocxEditor` reads asynchronously by default; deprecated `legacySyncApi` keeps the synchronous API and is removed in 0.6.0. `collaboration` runs on the default editor too. See [Migrating to 0.5](./migrating-to-0-5).
Without `onSave`, File > Save downloads the edited bytes. Configure
[fonts](./packages#fonts) before mounting the DOCX editor for consistent text
measurement and pagination.

The spreadsheet and presentation editors take a `Uint8Array` or an `ArrayBuffer`:

```tsx
import { XlsxEditor } from "@betteroffice/xlsx-react";
import { PptxEditor } from "@betteroffice/pptx-react";

<XlsxEditor file={bytes} fileName="report.xlsx" />;
<PptxEditor file={bytes} fonts={[{ family: "Inter", bytes: fontBytes }]} />;
```

`PptxEditor` requires at least one font face in `fonts` before it can lay out text.
`onDocumentChange({ version })` fires
alongside `onChange` after a committed edit; `downloadOnSave` (default: true
only without `onSave`), `initialZoom`, `loadingIndicator` and `style` match
`DocxEditor`, and a `collaboration.clientId` is generated when omitted.
Both default to the worker-owned async editor, whose `onReady` API answers reads
and exports with promises; deprecated `legacySyncApi` keeps the synchronous API
and is removed in 0.6.0. See [Migrating to 0.5](./migrating-to-0-5).

## Compose the DOCX toolbar [#compose-the-docx-toolbar]

The DOCX editor's built-in controls share one command store, `ref.commands`.
Pass `toolbar` to replace the default chrome with public parts in your own order,
next to your own actions:

```tsx
import {
  DocxEditor,
  EditorToolbar,
  ToolbarButton,
  ToolbarCommandButton,
  ToolbarCommandSelect,
  ToolbarGroup,
} from "@betteroffice/docx-react";

<DocxEditor
  documentBuffer={bytes}
  toolbar={
    <EditorToolbar>
      <EditorToolbar.Toolbar>
        <ToolbarGroup label="Formatting">
          <ToolbarCommandSelect id="paragraphStyle" />
          <ToolbarCommandButton id="bold" />
        </ToolbarGroup>
        <ToolbarCommandButton id="undo" />
        <ToolbarCommandSelect id="editingMode" />
        <ToolbarButton title="Share" onClick={share}>Share</ToolbarButton>
      </EditorToolbar.Toolbar>
    </EditorToolbar>
  }
/>;
```

Omit `toolbar` for the default chrome, pass `null` for none, or render the same
parts outside the editor inside `<DocxCommandProvider commands={commands}>`, with
`commands` captured from the ref (it may be `null` until the editor mounts).
Controls keep their active and `'mixed'` states, shortcuts, and read-only,
viewing and suggesting restrictions. `EditorToolbar.Review` also includes comments
and tracked-change controls.
A disabled command always states why
(`disabledReason.code` and a localized `message`), and `execute(id, args)` checks
availability again after preceding input, resolving to `{ ok: true, status }`
or `{ ok: false, failure }`. Queued work that cannot run is refused with the
exported `DocxCommandAdmissionError`, whose `code` (`DocxCommandAdmissionCode`)
is `input-failed`, `document-replaced`, `target-changed` or `editor-unavailable`;
`execute` reports it as `failure.code`. Dialogs a command opens apply to the
document and selection they opened with. At narrow widths, groups move into an
accessible More menu that keeps every built-in choice; wrap other host content
in `ToolbarOverflow` to give it an entry there.

## Host DOCX editor plugins [#host-docx-editor-plugins]

Host-owned tools install through the `plugins` prop. A plugin created with
`defineDocxPlugin` can contribute a docked panel, an overlay, sidebar cards and
commands; it reads and edits through restricted clients, never the session. The
plugin API can change in minor releases; changes are listed in the changelog:

```tsx
import { DocxEditor, defineDocxPlugin } from "@betteroffice/docx-react";

const review = defineDocxPlugin<{ count: number }>({
  id: "acme.review",
  createState: () => ({ count: 0 }),
  async onEvent(context, event) {
    if (event.type !== "load" && event.type !== "document-change") return;
    const read = await context.read.readParagraphs({ view: "accepted" });
    if (read.ok) context.setState({ count: read.paragraphs.length }, read.version);
  },
  panel: {
    title: "Review",
    placement: "right",
    render: ({ context }) => <p>{context.state.count} paragraphs</p>,
  },
  commands: [
    {
      id: "mark",
      label: "Mark reviewed",
      mutatesDocument: true,
      async execute(context) {
        if (!context.edits) return { ok: false, failure: { code: "not-granted", message: "Needs write access" } };
        const read = await context.read.readParagraphs({ view: "accepted" });
        if (!read.ok) return read;
        const first = read.paragraphs[0];
        const result = await context.edits.applyEdits({
          expectVersion: read.version,
          steps: [{ op: "insertText", target: { kind: "paragraph", story: "body", paraId: first.paraId }, at: "end", text: " ✓" }],
        });
        return result.ok ? { ok: true, status: "executed" } : result;
      },
    },
  ],
  toolbar: ["mark"],
});

<DocxEditor
  documentBuffer={bytes}
  plugins={[review]}
  pluginGrants={{ "acme.review": { document: "write", editBatches: true } }}
  onPluginError={(error) => console.error(error.pluginId, error.phase, error.error)}
/>;
```

**Lifecycle.** When a document is ready each plugin gets fresh state, runs
`initialize`, receives one `load` event (`loaded`, `replaced` or `attached`), and
then its contributions appear; a document change the hook did not make itself
aborts it and delivers `load` again, and after ten such runs the plugin is
stopped and reported. `document-change` carries only the committed version, for
typing, remote edits, undo, commands and batches (a plugin's own included), and
never for a refusal or no-op; `selection-change`, `mode-change` (with the
effective `readOnly`), `layout-change`, `proposal-change` (host proposals or
their preview decisions changed, with `previewVersion`) and `grants-change`
follow. Notifications
describe current state, so several changes can arrive as one, and a newer one
aborts the hook still handling the last (`context.signal`), unless that hook's
own edit batch made it. Replacing the document,
removing the plugin, changing its `revision`, unmounting or a failure ends the
activation: signals abort, clients refuse, and each `onCleanup` disposer runs
once with the reason. Plugins are matched by `id` and `revision`, so new array
identities and reordering keep their state; React StrictMode's double setup
creates two distinct activations.

**Stale results.** `setState(next, atVersion)` returns `false` for a superseded
or ended context or when the document is no longer at `atVersion`, which
defaults to the version the context was created at. Use `context.run(action)` in
event handlers: it supplies a fresh context and isolates failures.

**Grants.** Without a grant a plugin can read, validate and navigate only.
Built-in commands need their id in `commands`, and mutating ones also
`document: "write"`; `applyEdits` needs `document: "write"` and `editBatches`,
and `history: "none"` also needs `untrackedHistory`. Grants, the editor mode and
document policy are checked again immediately before each change, so revoking a
grant, switching to viewing mode, `readOnly`, or replacing the document refuses
through clients obtained earlier too. Mutating built-in commands refuse plugins
with `unsupported-policy` until they have an authoritative lock policy; edit
batches refuse locked content in Rust. In suggesting mode each batch step needs
`suggest`.

**Commands and toolbar.** Contributed commands register as
`plugin:<pluginId>/<id>` on `ref.commands` and always run with their own
plugin's clients, whether the default toolbar, a shortcut or the host invokes
them. A command's failure uses the plugin's own code, and a refused edit batch
returned as-is reaches the caller unchanged. Plugin shortcuts must use Mod or
Alt, or a function key; built-in and clipboard shortcuts take precedence, and a
clashing plugin shortcut is reported and not bound. Keys
pressed in plugin chrome are the user's: built-in shortcuts act on the editor
there, and a plugin's text fields keep their own editing keys. Replacement chrome
shows toolbar contributions with
`<DocxPluginToolbar />`, and `ToolbarCommandButton`, `ToolbarCommand`,
`useDocxCommand` and `useDocxCommandState` accept contributed ids.

**Story reads.** `read.listStories()` lists every story in id order with its
kind (`body`, `tableCell`, `contentControl`, `header`, `footer`, `footnote`,
`endnote` or `other`; comment bodies are not session stories), its `root`, the
story a cell or block control sits in, and a header's or footer's `part` and
`uses`: the sections whose properties reference the part, inheritance applied,
whether or not a page shows it. Each use's `shown` says whether the part is painted
in that section. It is absent before a complete layout of the current version,
and after an edit until the next layout; listen for `layout-change` and read again.
`read.readStories({ stories, byRoot, view })`
reads `'all'` stories, or listed kinds and story ids in their order without
repeats, in one call. An entry naming a kind is a kind, matching each story's
own kind unless `byRoot` matches its root's, so `['body']` with `byRoot` selects
everything under the body. The default editor and read-only `legacySyncApi`
editors without `collaboration` answer each with one worker read. A story that cannot be read
reports its own failure, the read limits stop the read with `truncated`, a story
larger than the limits on its own reports `limit-exceeded` (page it with
`readParagraphs` and `paraIds`), and
`expectVersion` refuses a changed document with `stale-version`.
`readParagraphs` and `readStories` include style-resolved `outlineLevel` and `list`
facts for accepted and original views, with rendered markers and counters from
the start of the root story, including for cell and `paraIds` reads.
Reads project pending paragraph-mark revisions as if accepted in the accepted
view or rejected in the original view. Joined paragraphs keep the following
paragraph's id. Edits still refuse pending paragraph-mark revisions.

An atom whose embed is a drawing carries `drawing`: the drawing's own `wp:docPr`
properties (`docPrId`, `name`, `title` and `descr`, each null when the attribute
is absent or empty, plus `hidden` and `decorative`), its `placement` (`inline`
or `anchor`) and its `type` (`picture`, `shape`, `textBox`, `group`, `chart`,
`diagram` or `other`). Content-control atoms carry `drawings` when nonempty,
listing the same properties in document order, including nested controls and
hyperlinks, projected to the requested revision view;
drawings inside field results are not listed, except drawings in a tracked
change inside a complex field's result, which reads treat as content beside the
field, inside or outside a control.
Structured export image and unsupported inlines carry
the same object as `drawing`, null when the drawing has none, and an image
inline's `altText` is its `descr`, falling back to its `title`. Sessions seeded
before these fields existed read them as absent until the document is reseeded.

**Coordinates.** `context.geometry` exists only while a rendered layout shows
the current version. An overlay may render during a pending layout with that and
`context.snapshot.layout` null, its `geometry` prop then being the previous
layout's. `geometry.dom` (a `RenderedDomContext`) answers in
pages-container units divided by zoom, and `geometry.toOverlayRect(rect)`
converts such a rectangle into pixels of the unscaled overlay layer, or returns
`null` once that layout is no longer rendered. `geometry.getPositionAtPoint`
hit-tests client coordinates like the caret and returns the layout's `version` and
`layoutId` with a collapsed accepted-view `target` for edit batch steps, or `null`
likewise, while input is pending, and until the pages show that layout.
`geometry.getAnchorGeometry(target)` resolves a proposal, revision, paragraph,
search match or text range to overlay-layer pixels: every visible fragment with
its zero-based `pageIndex`, an `anchor` collapsed at the end of the last one (at
the boundary of a target the preview hides, else at its paragraph) and the
anchor's `pageRect`. It refuses with a typed failure rather than answer from a
stale or unpainted layout, and `layout-change` repeats once the pages have painted
a layout that arrived before its pixels; `layout.previewVersion` is the proposal
preview the pixels show.
A target in a header or footer has fragments on every built page that paints it
and its anchor on the first; one that no laid-out page paints, built or not, is
`missing-target` once the layout is complete.
A `{ kind: 'drawing', paragraph, offset }` target answers with the drawn frame
box of the drawing atom at `offset` in that paragraph, the UTF-16 atom offset a
story read reports, on every page that paints it, with the first frame as its
`anchor`. Add `index` to address the zero-based entry of `drawings` from an
accepted-view read on a content-control atom at that offset: `{ kind: 'drawing', paragraph, offset, index: 0 }`.
An index outside that list or on another atom is `missing-target`.
An offset that is not on a drawing atom is `missing-target`, and so
is a drawing no page paints once the layout is complete; while a page that may
hold it is not laid out yet it is `layout-unavailable`. A picture's `title`,
`descr` and `placement` follow edits to its alt text and wrapping. Find a tagged picture
from a story read, then ask for its frame (`anchorFor` stands for however the
plugin builds the paragraph anchor it passes to `paragraph` and `search` targets):

```ts
const stories = await context.read.readStories({ view: 'accepted' });
for (const story of stories.ok ? stories.stories : []) {
  if (!story.ok) continue;
  for (const paragraph of story.paragraphs) {
    for (const atom of paragraph.atoms) {
      const drawing = atom.drawing;
      if (!drawing || ![drawing.name, drawing.title, drawing.descr].some((value) => value?.includes('template-marker'))) continue;
      const frame = context.geometry?.getAnchorGeometry({
        kind: 'drawing',
        paragraph: anchorFor(story.story, paragraph.paraId),
        offset: atom.offset,
      });
      if (frame?.ok) console.log(drawing.name, frame.anchor);
    }
  }
}
```

A plugin's `reservations(context)` returns `{ version, items }`: inline boxes,
blocks beside a paragraph and hidden ranges, in pixels at zoom 1, which the editor
lays out without painting and saves and paged exports leave out;
`{ kind: 'reservation', id }` answers a box once `layout.reservationsVersion` is
the set's `version`.
`geometry.readAnchorGeometries(targets)` answers every target in order and never
rejects or answers `pending`. Only the default editor awaits reads: targets
asked in one tick share one worker read, and `getAnchorGeometry` answers
`pending` while a target's read is in flight. The `legacySyncApi` editor, removed in
0.6.0, answers right away, and still `layout-unavailable` while its own reads
are in flight. A read the worker fails answers `read-failed` on both methods and
renders overlays again once; only `readAnchorGeometries` reads that target
again, so retry it with backoff. Answers come from the layout current when the
reads land, so results can carry a newer `layoutId` or `stale-version`, or
`layout-unavailable` while the latest edit, zoom or preview is not painted yet
or once the document is replaced; ask again on `layout-change`. A comment
sidebar, say, places all of its cards from one read:

```ts
const answers = await geometry.readAnchorGeometries(cards.map((card) => card.target));
const tops = answers.map((answer) => (answer.ok ? answer.anchor.y : null));
```

An answer that reaches pages not built yet lists them in `unbuiltPages` and is
provisional. `geometry.getPageRect(pageIndex)` returns a page box in
overlay-layer pixels with `built`, and `geometry.isPageBuilt(pageIndex)` says
whether a page is laid out without measuring the DOM; once their layout is no
longer shown they answer `null` and `false`.
`geometry.dom` can be replaced by a data-only facade in a minor release. Overlays
ignore the pointer unless an element sets `pointer-events: auto`. Sidebar cards
anchor to `{ version, story, paraId }` and appear only while that version is
current and the body paragraph is unique; a card's `render` receives its `item`,
so one component can draw every card and keep its state while that `id` stays.
`navigation.scrollToParagraph`
flushes input, waits briefly for a matching layout, keeps focus unless asked, and
reports `layout-unavailable` or `unsupported` instead of success when it cannot
scroll. In a narrow editor, side docks show tabs that open panels as drawers.

**Failures.** Each contribution renders behind its own error boundary and with
a command context restricted to its plugin. A throwing hook, renderer, sidebar
or command-state function, command or action stops only that plugin, runs its
cleanups and reaches `onPluginError`; other plugins and the editor continue.
Plugins share the page's JavaScript realm, so grants govern the supported API
rather than sandboxing code.

**Migrating.** `pluginOverlays`, `pluginSidebarItems` and
`pluginRenderedDomContext` remain as deprecated, unmanaged inputs;
`onRenderedDomContextReady` receives the editor's own context. The
snapshot-based `EditorPluginCore` contract in `@betteroffice/docx/plugin-api`
is deprecated; its geometry types remain.

## Compose the PPTX toolbar [#compose-the-pptx-toolbar]

The PPTX editor's controls share one command store, `api.commands`, handed to
`onReady`. Pass `toolbar` to replace the default controls with public parts in
your own order, next to your own actions:

```tsx
import {
  EditorToolbar,
  PptxEditor,
  ToolbarButton,
  ToolbarCommandButton,
  ToolbarCommandSelect,
  ToolbarGroup,
} from "@betteroffice/pptx-react";

<PptxEditor
  file={bytes}
  fonts={fonts}
  toolbar={
    <EditorToolbar mode="commands">
      <EditorToolbar.Toolbar>
        <ToolbarGroup label="Text">
          <ToolbarCommandSelect id="fontFamily" />
          <ToolbarCommandButton id="bold" />
        </ToolbarGroup>
        <ToolbarCommandButton id="undo" />
        <ToolbarCommandButton id="slideshow" />
        <ToolbarButton title="Share" onClick={share}>Share</ToolbarButton>
      </EditorToolbar.Toolbar>
    </EditorToolbar>
  }
/>;
```

Omit `toolbar` for the default controls or pass `null` for none;
`showToolbar={false}` hides the whole region. Supplied chrome also renders while
`readOnly`. Outside the editor, render the same parts inside
`<PptxCommandProvider commands={commands}>`, with `commands` captured from
`onReady` (it may be `null` until then). A disabled command always states why
(`disabledReason.code` and a localized `message`); mixed selections report
`'mixed'`. `execute(id, args)` runs after input accepted before it, such as a
picture still decoding, checks availability again, and resolves to
`{ ok: true, status }` or `{ ok: false, failure }`. Work that cannot run against
its input or target rejects with the exported `PptxCommandAdmissionError`, whose
`code` is a `PptxCommandAdmissionCode`. Commands and `api.handleAsync()` enforce
read-only mode; with `legacySyncApi`, `api.handle` stays direct host access. The prop-based
`EditorToolbar` and `Toolbar` remain supported but deprecated: without `mode`
they bind to their props, and `useEditorToolbar()` inside a command-mode toolbar
returns a view whose callbacks run the commands. At narrow widths, groups move
into an accessible More menu; wrap other host content in `ToolbarOverflow` to
give it an entry there. Keystrokes typed while earlier work is pending keep
their place through `handle.anchorCaret()` and `handle.resolveCaretAnchor()`,
caret anchors that later edits, undo and remote updates move along; with
`legacySyncApi`, hosts can use them too.

## Host PPTX editor plugins [#host-pptx-editor-plugins]

`PptxEditor` installs host-owned tools through the same `plugins`,
`pluginGrants` and `onPluginError` props as the DOCX editor, on the default
editor and with `legacySyncApi`. A plugin created with `definePptxPlugin`
contributes a docked panel, an overlay on the slide and
commands, and works through restricted clients. The plugin API can change in
minor releases; changes are listed in the changelog:

```tsx
import { PptxEditor, definePptxPlugin } from "@betteroffice/pptx-react";

const review = definePptxPlugin<{ slides: number }>({
  id: "acme.review",
  createState: () => ({ slides: 0 }),
  async onEvent(context, event) {
    if (event.type !== "load" && event.type !== "document-change") return;
    const read = await context.read.readContent();
    if (read.ok) context.setState({ slides: read.slides.length }, read.version);
  },
  panel: {
    title: "Review",
    placement: "right",
    render: ({ context }) => <p>{context.state.slides} slides</p>,
  },
  commands: [
    {
      id: "mark",
      label: "Mark reviewed",
      mutatesDocument: true,
      async execute(context) {
        if (!context.edits) return { ok: false, failure: { code: "not-granted", message: "Needs write access" } };
        const read = await context.read.readContent();
        if (!read.ok) return read;
        const slideId = context.snapshot.selection?.slideId;
        if (!slideId) return { ok: true, status: "noop" };
        const result = await context.edits.applyEdits({
          expectVersion: read.version,
          steps: [{ op: "setSlideNotes", target: { slideId }, text: "Reviewed" }],
        });
        return result.ok ? { ok: true, status: "executed" } : result;
      },
    },
  ],
  toolbar: ["mark"],
});

<PptxEditor
  file={bytes}
  fonts={fonts}
  plugins={[review]}
  pluginGrants={{ "acme.review": { document: "write", editBatches: true } }}
  onPluginError={(error) => console.error(error.pluginId, error.phase, error.error)}
/>;
```

**Lifecycle and grants** follow the DOCX editor: fresh state, `initialize` and
one `load` event per presentation (repeated when a change the hook did not make
arrives first, and stopped after ten runs), then coalesced `document-change`,
`selection-change`, `mode-change` (with `readOnly`), `layout-change` and
`grants-change` events. `document-change` comes from the presentation's
committed versions, so typing, commands, batches (a plugin's own included), undo,
redo and remote updates each produce one, and refusals or no-ops none. Replacing the presentation,
removing the plugin, changing its `revision`, unmounting or a failure ends the
activation and runs its cleanups once. Without a grant a plugin reads
(`read.version`, `readContent`, `findText`, `validateEdits`) and navigates;
built-in commands need an allowlisted id, mutating ones refuse with
`unsupported-policy`, and `applyEdits` needs `document: "write"` and
`editBatches`. Grants and `readOnly` are checked again right before each change.
Each client call waits for pending input in order with it; plugin handlers run
outside that queue. A contributed command's failure uses the plugin's own code,
and a refused edit batch returned as-is reaches the caller unchanged.

`readContent` includes effective `list` facts on story paragraphs, including inherited
bullets and numbered markers. Slides include `title`, `hidden` and `layout` (name and
type); unavailable facts are `null`. These fields are optional for older engines.
Slides also include `headerFooter` with visible slide footer, slide number and date
placeholder text; `layout.headerFooter` reports stored layout or master settings, which do not gate those placeholders.

**Selection and navigation.** `snapshot.selection` names the current slide
(session `slideId` and one-based `slide`) and a slide, shape or text target;
text keeps its `anchor`/`focus` direction. `navigation.goToSlide`,
`selectShape` and `selectText` take the version the target was read at, keep
keyboard focus unless `focus: true`, and refuse with `stale-version`,
`missing-target`, `layout-unavailable` or `unsupported` rather than retarget a
changed deck. Slide, shape and story ids are session-scoped.

**Coordinates.** `context.geometry` exists only while the canvas shows a
painted frame of the current version, and not during proposal review.
`layout.width`/`height` are the unzoomed slide in display-list pixels and
`layout.zoom` the resolved scale. `geometry.toOverlayRect({ space, rect })`
converts `slide-emu` (9,525 EMU per pixel) or `slide-px` rectangles into pixels
of the unscaled overlay layer on the slide, `getShapeRect(shapeId)` returns a
shape's rendered bounds including group descendants, and `getPositionAtPoint`
hit-tests client coordinates with `version` and `layoutId`. The layer
sits below selection handles and proposal controls and ignores the pointer
unless an element sets `pointer-events: auto`. Panels dock left, right or bottom
of the slide beside the thumbnail rail, and become drawers in a narrow editor.
Place `<PptxPluginToolbar />` in replacement chrome to keep contributed toolbar
commands. Plugin shortcuts must use Mod or Alt, or a function key; built-in and
clipboard shortcuts take precedence, and a clashing plugin shortcut is reported
and not bound. Keys pressed in plugin chrome are the user's: built-in shortcuts act
on the editor there, and a plugin's text fields keep their own editing keys.
Plugins share the page's JavaScript realm, so grants govern the
supported API rather than sandboxing code.

## Compose the XLSX toolbar [#compose-the-xlsx-toolbar]

The spreadsheet editor's built-in controls share one command store,
`api.commands`, handed to `onReady`. Pass `toolbar` to replace the default
chrome with parts bound to it; `EditorToolbar.FormulaBar` keeps the name box and
formula input:

```tsx
import {
  EditorToolbar,
  ToolbarButton,
  ToolbarCommandButton,
  ToolbarCommandSelect,
  ToolbarGroup,
  XlsxEditor,
} from "@betteroffice/xlsx-react";

<XlsxEditor
  file={bytes}
  toolbar={
    <EditorToolbar mode="commands">
      <EditorToolbar.Toolbar>
        <ToolbarGroup label="Formatting">
          <ToolbarCommandSelect id="numberFormat" />
          <ToolbarCommandButton id="bold" />
        </ToolbarGroup>
        <ToolbarCommandButton id="undo" />
        <ToolbarButton title="Share" onClick={share}>Share</ToolbarButton>
      </EditorToolbar.Toolbar>
      <EditorToolbar.FormulaBar />
    </EditorToolbar>
  }
/>;
```

Omit `toolbar` for the default chrome (hidden when `readOnly`), pass `null` for
none, or set `showToolbar={false}`. Outside the editor, render the same parts
inside `<XlsxCommandProvider commands={commands}>`, with `commands` captured from
`onReady` (`null` until then). `execute(id, args)` runs in order with pastes
and cell entries accepted before it, writes the cell or formula text typed so
far, checks availability again, and resolves to `{ ok: true, status }` or
`{ ok: false, failure }`; a disabled command
states why in `disabledReason`. With `legacySyncApi`, the synchronous `api.save()` throws
`XlsxSaveRefusedError` (`input-pending` or `input-failed`) instead of returning
bytes without accepted input; `execute("save", null)` waits for it and saves.
The editor API's `version`, `readCells`, `findText`, `validateEdits` and
`applyEdits` wait for that input too, and reject with the exported
`XlsxCommandAdmissionError` when they cannot run: its `code` is `input-failed`
while a refused entry waits for correction, `gesture-active` during a chart drag
and `document-replaced` when the workbook is replaced meanwhile.
With `legacySyncApi`, `selectCells` and `clearSelection` queue an open entry behind input that is
still waiting, so it may not have landed when they return. An open entry the
workbook refuses stays open and they change nothing; one it refused earlier
reopens at its own cell once they land on its sheet.
With `legacySyncApi`, the store gates the editor's own UI, not direct
`api.handle` calls. Existing prop-based `EditorToolbar` and `Toolbar` usage keeps
working in the default legacy mode; `mode="commands"` rejects those props. Narrow
rails move groups into an accessible More menu; wrap other host content in
`ToolbarOverflow` to give it an entry there.

## Host XLSX editor plugins [#host-xlsx-editor-plugins]

`readCells` sheet entries expose `headerFooter` with printable left, center and right sections using Excel dialog field tokens. Inactive even and first variants are null; `headerFooter` is null when absent or empty and omitted when source facts are unknown.

`XlsxEditor` installs host-owned tools through the same `plugins`,
`pluginGrants` and `onPluginError` props as the DOCX editor. A plugin
created with `defineXlsxPlugin` contributes a docked panel, an overlay on the
grid and commands, and works through restricted clients. The plugin API
can change in minor releases; changes are listed in the changelog:

```tsx
import { XlsxEditor, defineXlsxPlugin } from "@betteroffice/xlsx-react";

const review = defineXlsxPlugin<{ sheets: number }>({
  id: "acme.review",
  createState: () => ({ sheets: 0 }),
  async onEvent(context, event) {
    if (event.type !== "load" && event.type !== "document-change") return;
    const read = await context.read.readCells({ ranges: [] });
    if (read.ok) context.setState({ sheets: read.sheets.length }, read.version);
  },
  panel: {
    title: "Review",
    placement: "right",
    render: ({ context }) => <p>{context.state.sheets} sheets</p>,
  },
  commands: [
    {
      id: "mark",
      label: "Mark reviewed",
      mutatesDocument: true,
      async execute(context) {
        if (!context.edits) return { ok: false, failure: { code: "not-granted", message: "Needs write access" } };
        const selection = context.snapshot.selection;
        const version = await context.read.version();
        if (!version.ok) return version;
        if (!selection?.cells) return { ok: true, status: "noop" };
        const { anchor, focus } = selection.cells;
        const start = { row: Math.min(anchor.row, focus.row), col: Math.min(anchor.col, focus.col) };
        const end = { row: Math.max(anchor.row, focus.row), col: Math.max(anchor.col, focus.col) };
        const result = await context.edits.applyEdits({
          expectVersion: version.version,
          steps: [
            {
              op: "patchStyle",
              target: { sheetId: selection.sheetId, range: { kind: "rowCol", start, end } },
              patch: { fillColor: "#d9ead3" },
            },
          ],
        });
        return result.ok ? { ok: true, status: "executed" } : result;
      },
    },
  ],
  toolbar: ["mark"],
});

<XlsxEditor
  file={bytes}
  plugins={[review]}
  pluginGrants={{ "acme.review": { document: "write", editBatches: true } }}
  onPluginError={(error) => console.error(error.pluginId, error.phase, error.error)}
/>;
```

**Lifecycle and grants** follow the DOCX editor: fresh state,
`initialize` and one `load` event per workbook (repeated when a change the hook
did not make arrives first, and stopped after ten runs), then coalesced
`document-change`, `selection-change`, `mode-change` (with `readOnly`),
`layout-change` and `grants-change` events. `document-change` comes from the
workbook's committed versions after recalculation, so typing, commands, batches
(a plugin's own included), undo, redo and remote updates each produce one, and
refusals or no-ops none. Replacing the workbook, removing the plugin, changing its `revision`,
unmounting or a failure ends the activation and runs its cleanups once. Without
a grant a plugin reads (`read.version`, `readCells`, `findText`,
`validateEdits`) and navigates; built-in commands need an allowlisted id,
mutating ones refuse with `unsupported-policy`, and `applyEdits` needs
`document: "write"` and `editBatches`. Grants and `readOnly` are checked again
right before each change. Each client call waits for pending input in order
with it; plugin handlers run outside that queue. A contributed command's failure
uses the plugin's own code, and a refused edit batch returned as-is reaches the
caller unchanged.
`readCells` returns `sheets[].visibility`, which is `unknown` when source sheet metadata is unavailable and the sheet was not added in this session.

**Selection and navigation.** `snapshot.selection` names the active sheet
(session `sheetId` and zero-based `sheetIndex`), the selected cells with their
`anchor`/`focus` direction and a selected chart's id.
`navigation.selectCells({ sheetId, selection }, { expectVersion })` activates
the sheet, selects the cells and reveals the focus cell;
`navigation.scrollToCell({ sheetId, row, col }, { expectVersion, align })`
reveals a cell (`nearest`, `start` or `center`) and keeps the selection, which
is cleared when the cell is on another sheet. Both keep keyboard focus unless
`selectCells` gets `focus: true`, and refuse with `stale-version` or
`missing-target` rather than retarget a changed workbook. Sheet ids and versions
are session-scoped.

**Coordinates.** `context.geometry` exists only while the canvas shows a
painted frame of the current version. `layout` names its `sheetId`, `zoom` and
painted `viewport` in unzoomed sheet pixels, and changes with every scroll,
zoom and sheet switch. `geometry.getCellRect({ sheetId, row, col })` and
`getRangeRect({ sheetId, range })` return pixels of the overlay layer, zoomed
and clipped to the visible grid, frozen panes included; a cell scrolled out of
view returns null, and merged areas are addressed as ranges.
`getPositionAtPoint` is null until the editor exposes pointer queries. The
overlay layer sits on the grid below the editor's selection and cell editor and
ignores the pointer unless an element sets `pointer-events: auto`. Panels dock
left, right or bottom of the grid, above the sheet tabs, and become drawers in a
narrow editor. Place `<XlsxPluginToolbar />` in replacement chrome to keep
contributed toolbar commands. Plugin shortcuts must use Mod or Alt, or a
function key; built-in shortcuts win and a clashing plugin shortcut is reported. Keys pressed in plugin chrome are the user's:
built-in shortcuts act on the editor there, a plugin's text fields keep their
own editing keys, and no key or click in a contribution reaches the grid.
Plugins share the page's JavaScript realm, so grants govern the supported API
rather than sandboxing code, and they are not spreadsheet protection.

## Use the JavaScript core [#use-the-javascript-core]

```ts
import { initWasm, openWorkbook, paintDisplayList } from "@betteroffice/xlsx";

await initWasm();
const workbook = openWorkbook(new Uint8Array(await file.arrayBuffer()));

const frame = workbook.displayList({ x: 0, y: 0, width: 800, height: 600 });
paintDisplayList(canvas.getContext("2d")!, frame, devicePixelRatio);

workbook.editCell(0, 9, 2, "=SUM(C1:C9)");
const saved = workbook.save();
```

`initWasm()` fetches the packaged wasm asset once in browsers; pass wasm bytes or
a precompiled `WebAssembly.Module` in runtimes that cannot fetch that URL. The
core also provides hit-testing, viewport calculations, accessibility data, and
TSV clipboard helpers.

## Edit DOCX in version-checked batches [#edit-docx-in-version-checked-batches]

A DOCX session reads paragraphs with the version they were read at, then applies
a batch against that version: every step commits in one transaction and one undo
step, or the batch returns a typed refusal and nothing changes.

```ts
import { repackDocx } from "@betteroffice/docx/docx";
import { createYrsSession, yrsToDocument } from "@betteroffice/docx/yrs";

const session = await createYrsSession();
session.openDocx(bytes, true);
const read = session.readParagraphs({ view: "accepted" });
if (!read.ok) throw new Error(read.failure.message);
const first = read.paragraphs[0];

const result = session.applyEdits({
  expectVersion: read.version,
  steps: [
    { op: "insertText", target: { kind: "paragraph", story: "body", paraId: first.paraId }, at: "end", text: " (revised)" },
    { op: "insertParagraphs", target: { story: "body", paraId: first.paraId }, at: "end", paragraphs: [{ text: "New clause" }] },
  ],
});
if (!result.ok) console.warn(result.failure.code);

const saved = await repackDocx(yrsToDocument(session, session.materializeDocx()!));
```

Offsets are UTF-16 positions in the paragraph text, where each inline atom (hard
break, image, content control, note reference, field) is one U+FFFC. Steps insert,
replace and delete text within one paragraph, insert or delete complete
paragraphs, and apply paragraph styles; text steps can be recorded as tracked
changes. Versions belong to one session and change with every committed edit.
The React editor exposes the same `readParagraphs`, `findText`, `validateEdits`
and `applyEdits` on its ref, flushing pending input first. Paragraph and style
steps need a session opened from DOCX bytes, inline atoms cannot be replaced, and
list numbering is not supported: numbered paragraphs and styles that define or
inherit numbering refuse with `unsupported`. Steps also refuse content-locked
controls, existing tracked changes they would touch (tracked run formatting
included) and pending paragraph-mark revisions; paragraph and style steps
cannot be suggested, and an inserted
paragraph takes only its style's defaults, so it is never numbered. Deleting a
span that holds tables, controls, section breaks, opaque XML, fields' cached
results, or comments and bookmarks crossing it refuses, as does a step after
which saving would move an opaque XML block; a batch holds at most 128 steps,
1,048,576 inserted UTF-16 units and 1,024 new paragraphs.

## Edit PPTX in version-checked batches [#edit-pptx-in-version-checked-batches]

A presentation handle reads slides and story text with the version they were
read at, then applies a batch against that version: every step commits in one
transaction and one undo step, or the batch returns a typed refusal and nothing
changes.

```ts
import { initWasm, openPresentation } from "@betteroffice/pptx";

await initWasm();
const deck = openPresentation(bytes);
const read = deck.readContent();
if (!read.ok) throw new Error(read.failure.message);
const story = read.stories[0];
const within = { slideId: story.slideId, shapeId: story.shapeId, storyId: story.storyId };

const result = deck.applyEdits({
  expectVersion: read.version,
  steps: [
    { op: "replaceText", target: { kind: "search", within, text: "Q3" }, text: "Q4" },
    { op: "setSlideNotes", target: { slideId: story.slideId }, text: "Updated for Q4" },
  ],
});
if (!result.ok) console.warn(result.failure.code);

const saved = deck.save();
```

A story reads as its paragraphs joined by `\n`, with story-local UTF-16 offsets;
the read reports each paragraph's span, soft line breaks and field results.
Each shape at every depth also reports its alternative text: `title` and
`description` from its non-visual properties when non-empty, and
`decorative: true` when it carries the decorative extension.
Steps insert, replace and delete text within one paragraph, format and align
text, replace speaker notes, and set a top-level shape's rectangle, fill or
outline. Fields and soft line breaks are never replaced or deleted. Ids and
versions belong to one open session. `PptxEditor` exposes the same
`readContent`, `findText`, `validateEdits` and `applyEdits` on its editor API,
flushing pending input first. The Rust `Presentation` and the Python binding
take the same requests. A batch refuses when saving could turn a field into
plain text, which it rules out only while every field is non-empty and sits in
its paragraph's unchanged leading or trailing text; a paragraph's alignment and
text cannot change in one batch, and slides, shapes and paragraphs are neither
created nor removed. A batch holds at most 128 steps and 1,048,576 inserted
UTF-16 units, requests at most 16 MiB of JSON, and reads and searches return at
most 64 MiB, searches marking the cut with `truncated`.

### PPTX structured export [#pptx-structured-export]

`exportStructured()` returns the committed deck as JSON with the version it was
read at, and `exportMarkdown()` renders that same read as Markdown; neither
flushes input or changes anything. The `PptxEditor` editor API has both too, run after pending input.
`exportPptxStructured(bytes)`,
`exportPptxMarkdown(bytes)` and `renderPptxMarkdown(content)` do the same
headless, anchored to the returned snapshot.

```ts
import { exportPptxMarkdown } from "@betteroffice/pptx";

const read = deck.exportStructured({ includeNotes: true, includeComments: true });
if (!read.ok) throw new Error(read.failure.message);
const titles = read.content.slides.map((slide) => slide.shapes[0]?.name);

const { markdown, anchors } = await exportPptxMarkdown(bytes);
```

Slides follow deck order and shapes the current shape tree, depth first; this
is the authored order, not one inferred from geometry. Paragraphs carry levels,
resolved list markers, runs with marks, links, line breaks and cached field
results; tables keep spans and merges; pictures, media, charts, SmartArt and
embedded objects become placeholders with their alternative text. Every record
carries an anchor (`range` anchors are batch text targets in `readContent()`
offsets) and, when read from the file, its source part, SHA-256 and element
path. Hidden slides and shapes, notes and comments are explicit options, layout
and master content is not exported, and every omission is a diagnostic.
`maxBlocks` and `maxBytes` stop the export at a whole record and set
`truncated`. Markdown marks each
block with `<!-- pptx-export:N -->`, mapped back to its source in `anchors`.

## Edit XLSX in version-checked batches [#edit-xlsx-in-version-checked-batches]

A workbook reads cells with the version they were read at, then applies a batch
against that version: every step commits as one recalculated change and one undo
step, or the batch returns a typed refusal and nothing changes.

```ts
const read = workbook.readCells({
  ranges: [{ sheetId: "sheet:0", range: { kind: "a1", a1: "B3:D3" } }],
});
if (!read.ok) throw new Error(read.failure.message);

const now = new Date();
const result = workbook.applyEdits({
  expectVersion: read.version,
  calculation: { nowSerial: (now.getTime() - now.getTimezoneOffset() * 60_000) / 86_400_000 + 25_569 },
  steps: [
    {
      op: "setCellInputs",
      target: { sheetId: "sheet:0", range: { kind: "a1", a1: "B3" } },
      inputs: [["120"]],
      expect: { cells: [[{ displayText: read.ranges[0].cells[0][0].displayText }]] },
    },
    { op: "setFormulas", target: { sheetId: "sheet:0", range: { kind: "a1", a1: "E3" } }, formulas: [["D3*1.2"]] },
    { op: "patchStyle", target: { sheetId: "sheet:0", range: { kind: "a1", a1: "B3:E3" } }, patch: { bold: true } },
  ],
});
if (!result.ok) console.warn(result.failure.code);
```

Steps set cell inputs (parsed like typing, against each cell's current number
format), set formulas (stored as formulas whatever the format), set number
formats and patch styles. Targets name a sheet id from the current catalog and an
A1 range or zero-based corners; value matrices and guards match the target
exactly. Guards compare a cell's value, formula or display text before the
batch, and steps may combine content with formatting on the same cells but not
write one property twice. `findText` searches display text exactly and
case-sensitively. Volatile functions see only `calculation.nowSerial`. Versions
and sheet ids belong to one session. Batches do not insert or delete rows,
columns or sheets, merge cells or move charts, and refuse writes to merged-cell
followers, array-formula cells and locked cells of protected sheets. Formats on
a protected sheet need its protection to allow formatting cells. The React editor's
`onReady` API exposes the same operations, plus `save()`, which returns the bytes
and calls `onSave` without downloading. They commit pending drafts, nudges and
pastes first, and reject with `XlsxCommandAdmissionError` when that input
cannot be written or the workbook is replaced meanwhile.

## Export DOCX as structured content [#export-docx-as-structured-content]

`exportDocxStructured` reads a DOCX into read-only JSON: ordered stories of
headings, paragraphs, list items, tables and content controls, with the location
of every block and inline and a diagnostic for everything omitted or not
represented. `exportDocxMarkdown` renders the same content as Markdown with a
marker per block.

```ts
import { exportDocxMarkdown, exportDocxStructured } from "@betteroffice/docx";

const content = await exportDocxStructured(bytes, { revisionView: "accepted" });
const { markdown, anchors } = await exportDocxMarkdown(bytes, {
  revisionView: "markup",
  stories: ["body", "footnotes", "comments"],
});
```

`revisionView` is required: `accepted` and `original` project pending revisions,
`markup` keeps both with attribution. Only the body is exported unless `stories`
selects headers, footers, footnotes, endnotes or comments; omitted stories,
formatting and revision content are listed in `diagnostics`. Ranges use the edit
batch offsets (UTF-16, one U+FFFC per inline atom) in the view they name.
A list number its format cannot write, such as a Roman numeral past 3,999, is
drawn and exported without a marker, with an `unsupported-numbering` diagnostic.
Fields export their cached result and are never evaluated; images export alt
text and relationship metadata, not image data. On a live session,
`session.exportStructured(options)` and `session.exportMarkdown(options)` return
the content with the version its anchors belong to, without committing or
publishing anything, and `session.headings(story)` lists a story's headings
classified the same way. Exports stop at whole blocks when they reach `maxBlocks` or
`maxBytes` and report `truncated`. Markdown does not preserve Word pagination or
layout.

### Page fragments [#page-fragments]

A paged export attaches a page map to the same structured content: which physical
page, section and displayed page label shows each block and inline, and which
header, footer or note occurrence it sits in. Ordinary exports never lay anything
out; a paged export reads a layout and refuses one it cannot trust.

```ts
import { exportDocxStructuredWithPages, renderDocxMarkdownWithPages } from "@betteroffice/docx";

const paged = await exportDocxStructuredWithPages(
  bytes,
  { revisionView: "markup", stories: ["body", "headers", "footnotes"] },
  { fonts: [{ key: "sans", data: fontBase64 }], defaultChain: ["sans"] },
);
const { markdown } = await renderDocxMarkdownWithPages(paged, { pageMarkers: true });
```

The bytes export lays the document out in a private session with exactly the
fonts it is given, as base64 data, in a font store of its own (no system fonts are
looked up and no editor's fonts change) and returns a deterministic snapshot map.
Its layout options are plain JSON: `measurementDefaults`, `renderEnvironment`
(`showHiddenText`, `defaultTabStopTwips`) and `compatibility`; a font requirement
left with no font, including the default family text naming none falls back to, or
any text measured with stand-in metrics is refused as `layout-unavailable`. On a live session,
`session.exportStructuredWithPages(options)` reads the region layout the session
retains and never lays out, flushes or loads fonts. On the default React editor,
the ref's `exportStructuredWithPages` flushes pending input and exports the
worker's layout, waiting for layout and fonts when needed. With `legacySyncApi`,
the ref flushes pending input and exports the editor's layout, computing it
again or waiting for fonts when needed. Read-only `legacySyncApi`
viewers wait for their worker's layout. Page references describe that layout at
the returned version; a later edit may supersede it before it is painted.

* `pageIndex` counts physical pages from zero, blank parity pages included;
  `displayedNumber` and `displayedLabel` follow the section's PAGE numbering,
  which can restart, repeat or use Roman and letter formats. A format that cannot
  be written falls back to decimal with `numberingStatus: "fallback"`.
* A header or footer part is exported once as a story and has an occurrence on
  every page that shows it; notes have occurrences on the pages their note areas
  are on, independent of the page of their reference mark.
* Fragments name the export node (`nodeId`) and its block. Text slices are ranges
  in the export's own offsets; an atom such as a field, control or note mark is
  sliced whole, and marked `partial` with an `anchor-only` diagnostic when only
  part of its content is on the page. Tables list their row window with
  continuation and repeated-header flags, and every cell paragraph has fragments
  of its own for the lines its cell shows; a line the cell cuts through is listed
  with a `clipped-content` diagnostic.
* Pages are laid out with revision markup. `accepted` and `original` are refused
  with `unsupported-revision-layout` while any laid-out story, exported or not,
  holds pending revisions.
* A layout older than the document is refused with `stale-document`; section,
  settings or note metadata that no longer describes the document, changed fonts,
  measurement options or a mismatched `expectLayoutVersion` with `stale-layout`;
  no retained layout, or one missing a font the document needs, with
  `layout-unavailable`; notes that did not settle with `layout-not-converged`; a
  footnote the layout places away from its reference in a split table row with
  `unsupported`. A note too tall for its page's note area is diagnosed
  `unsupported-note-layout` instead of placed.
* `includeGeometry` adds rectangles in unzoomed CSS pixels (96 per inch) from the
  physical page's top-left corner. `maxFragments` and `maxLayoutBytes` bound the
  map separately from the content and mark it `truncated`; mapping stops a page
  past the limit, so a truncated map leaves out the diagnostics of later pages and
  of paragraphs no page shows.
* `renderDocxMarkdownWithPages` checks the map belongs to the content; with
  `pageMarkers`, each block marker is followed by
  `<!-- docx-pages: 0=i 1=ii -->` and no page break is written into the text.
* The map carries its own `schemaVersion` (1): additive fields keep it, and a
  change existing readers would misread bumps it.

Rust `EngineSession` also exports page maps; Python exports do not.

## Export XLSX content with anchors [#export-xlsx-content-with-anchors]

XLSX exports bounded sparse worksheet content and Markdown with positional
anchors, formulas, stored values, formatted text, explicit hidden-content
options, and omission diagnostics. Export does not recalculate formulas.

```ts
import { exportXlsxMarkdown } from "@betteroffice/xlsx";

const result = workbook.exportStructured({
  scope: [{ sheet: 0, range: "A1:H40" }],
  includeHiddenRows: false,
  maxCells: 20_000,
});
if (result.ok) {
  const { version, content } = result;
  const totals = content.sheets[0].cells.filter((cell) => cell.formula !== null);
}

const { markdown, anchors } = await exportXlsxMarkdown(bytes, {}, { maxRows: 100 });
```

A live export returns `{ ok, version, content }` read from the committed
workbook without flushing, recalculating or publishing anything; a refused scope
or option returns `{ ok: false, version, failure }` with `target` naming the
sheet or `null`. `exportXlsxStructured`, `exportXlsxMarkdown` and
`renderXlsxMarkdown` need no session: bytes are read as stored, with no clock.
Cells carry a typed value, the formula without `=`, the engine's display text,
the number format and merge membership; formula results are stored values
marked `unverified`, `missing` (the file stored none and nothing has calculated
since), `uncertain`, `cycle` or `limited`. Sheets also list merges,
tables, hyperlinks, hidden row and column spans, and drawing objects as
placeholders; defined names are listed read-only. Comments, rich-text formatting
runs (the text is exported), sheet features such as conditional formatting, data
validation and pivot tables, and unreadable charts, which stay placeholders, are
diagnosed rather than exported. Anchors are sheet index, sheet
name and A1 in that version or snapshot, not identities that survive structural
edits. `maxCells` and `maxBytes` stop at a complete record with `truncated`.
Markdown renders one labelled grid per sheet (200 rows, 50 columns and 10,000
positions by default), escaped HTML tables for merges, and
`<!-- xlsx-export:N -->` markers whose anchors are returned beside it.

## Fill DOCX content controls [#fill-docx-content-controls]

`listContentControls` lists a session's content controls in document order with
their tag, alias, type, lock, placement, anchor and current text, and the version
they were read at. A `setContentControlText` step in an edit batch fills a plain-
or rich-text control by its `controlId`, or by a tag or `ooxmlId` (the authored
`w:id`) only one control carries.

```ts
const read = session.listContentControls();
if (!read.ok) throw new Error(read.failure.message);
const byTag = (tag: string) => read.content.controls.find((control) => control.tag === tag)!;

const result = session.applyEdits({
  expectVersion: read.version,
  steps: [
    { op: "setContentControlText", target: { kind: "id", controlId: byTag("customer.name").controlId }, text: "Ada Lovelace" },
    { op: "setContentControlText", target: { kind: "tag", tag: "customer.address" }, text: "12 Example Street\nLondon" },
  ],
});
if (!result.ok) console.warn(result.failure.code, result.failure.reason);
```

The text replaces the control's content and clears its placeholder: CRLF becomes
LF, LF is a line break (a new paragraph in a rich-text block control), and a
plain-text control accepts it only with `w:multiLine`. The new text takes the
formatting of the control's first text run, or the control's own run properties
while it shows its placeholder. Every step commits or none does;
missing or duplicate tags and `ooxmlId`s, locked, data-bound and nested controls,
and content other than text, tabs and line breaks are refused as data with a
`reason`. `findContentControls(query)` returns every exact match of an id, tag,
`ooxmlId` or alias, and `listDocxContentControls(bytes)` and
`findDocxContentControls` read bytes without a session. Control ids belong to the
version they were read at and do not survive save and reopen; `ooxmlId` does, and
tags are the template author's names. Checkbox, dropdown and date controls keep
`setContentControlValue`; passing a string to it fills a text control the same
way. The React editor exposes `listContentControls` and `findContentControls` on
its ref. Filling needs a session opened from DOCX bytes; rich-text run input is
not supported. Controls the session does not hold as controls, such as those
in text boxes, are left out as a coverage gap (`complete: false`), and while one
exists, tag and `ooxmlId` fills refuse with `provenance-unavailable`.

## Compare DOCX files into tracked changes [#compare-docx-files-into-tracked-changes]

`compareDocx` compares the body paragraph text of an original and a revised DOCX
and returns the original with the differences as tracked insertions and
deletions, attributed to the author and date you pass. Everything else in the
package keeps the original's bytes.

```ts
import { compareDocx } from "@betteroffice/docx";

const result = await compareDocx(original, revised, {
  author: "Contract review",
  date: "2024-05-06T09:30:00+02:00",
});
if (result.ok) {
  await save(result.docx);
  for (const change of result.changes) console.log(change.kind, change.original.text, change.revised.text);
} else {
  for (const diagnostic of result.diagnostics) console.warn(diagnostic.code, diagnostic.message);
}
```

Only text inside body paragraphs whose structure is unchanged is compared.
Whole-paragraph additions, removals and moves, table and content-control
changes, formatting or style changes, field, hyperlink and object changes,
edits in paragraphs holding such content, existing tracked changes, and
differences outside the body return `{ ok: false, diagnostics }` and never a
partial redline; `unsupported: "report"` collects every diagnostic instead of
stopping at the first. `granularity` reports differences by Unicode word
(the default) or grapheme cluster, and `limits` can tighten the documented v1
bounds. The result is reopened and checked against both inputs before it is
returned: accepting every change gives the revised text and formatting,
rejecting every change gives the original. Review in BetterOffice is tested;
Word validation is reported separately. Native Rust and Python comparison is
not available.

## Operation profiles [#operation-profiles]

XLSX provides `editCellProfiled`, `applyOpsProfiled`, and `displayListProfiled`.
The edit results include stage timings in `profile`; display profiling returns
`{ displayList, profile }`. PPTX provides `layoutSlideProfiled` and profiled
mutation/history methods such as `insertTextProfiled` and `undoProfiled`, returning
`{ layout, profile }` or `{ receipt, profile }` respectively. Durations are in
milliseconds and describe engine stages; measure the surrounding browser
interaction separately when investigating input-to-paint latency.

## DOCX paragraph anchors [#docx-paragraph-anchors]

A DOCX `YrsSession` addresses paragraphs by session keys, which are never saved as Word
paragraph IDs (`w14:paraId`); a session anchor resolves on every replica of one
collaborative session, and seeding opens without a `generation` start a new
session. `saveYrsDocx(session)` from `@betteroffice/docx/yrs` returns the
saved bytes and a persisted anchor for each saved paragraph that has a Word paragraph ID,
qualified by its package part. Resolve it after reopening:

```ts
import { createYrsSession, saveYrsDocx } from "@betteroffice/docx/yrs";

const saved = await saveYrsDocx(session);
const reopened = await createYrsSession();
reopened.openDocx(saved.bytes, true);
const result = reopened.resolveParagraphAnchor(saved.paragraphs[0].persisted);
```

Paragraphs authored in the session always receive an ID. Source paragraphs without one
keep none until the host calls `session.persistParagraphIds()`, which covers every story
part, comments and note separators included, and refuses rather than guess at an
ambiguous comment reference. Results are `found`, `missing`, `ambiguous`, or
`unsupported`; table, cell, and content-control identities are not persisted.
The React editor's ref offers `getParagraphIdentities()` and
`resolveParagraphAnchors(anchors)`, which returns the results in input order with
the version they were resolved at.

## Package reference [#package-reference]

| Package                    | What it is                                                                                                                                                                                                                                                                                                                                                            |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@betteroffice/docx`       | Framework-free DOCX core: OOXML parse and serialize, CRDT editing, version-checked atomic text, paragraph and content-control batches, content-control discovery, structured JSON and Markdown export with source anchors, text shaping, pagination, canvas rendering. Saving preserves untouched package parts.                                                      |
| `@betteroffice/docx-react` | The DOCX editor and viewer as a React component: toolbar, paginated canvas, comments, tracked changes, a command store with composable toolbar parts, flushed version-checked edit batches and content-control discovery on its ref, and host-owned plugins with panels, overlays, sidebar items, lifecycle events, and explicitly granted commands and edit batches. |
| `@betteroffice/docx-i18n`  | UI locale strings and types for the DOCX React editor.                                                                                                                                                                                                                                                                                                                |
| `@betteroffice/xlsx`       | Framework-free XLSX core: SpreadsheetML parse and serialize, formula recalculation, version-checked atomic cell batches, anchored JSON and Markdown export, grid display lists, hit-testing, PNG export, and reviewable agent proposals.                                                                                                                              |
| `@betteroffice/xlsx-react` | The spreadsheet editor and viewer as a React component, with a command store and composable toolbar parts, flushed reads, version-checked edit batches and `save()` on its `onReady` API, and host-owned plugins with panels, overlays, lifecycle events, and explicitly granted commands and edit batches.                                                           |
| `@betteroffice/xlsx-i18n`  | UI locale strings and types for the XLSX React editor.                                                                                                                                                                                                                                                                                                                |
| `@betteroffice/pptx`       | Framework-free PPTX core: parsing, editing, version-checked atomic edit batches, structured JSON and Markdown export with anchors, masters and layouts, rendering, comments, collaboration, and saving. Untouched slides retain their source bytes.                                                                                                                   |
| `@betteroffice/pptx-react` | The slides editor and viewer as a React component, with a command store, composable toolbar parts, flushed version-checked edit batches and structured and Markdown export on its editor API, and host-owned plugins with panels, overlays, lifecycle events, and explicitly granted commands and edit batches.                                                       |
| `@betteroffice/pptx-i18n`  | UI locale strings and types for the PPTX React editor.                                                                                                                                                                                                                                                                                                                |

See [Collaboration](./collaboration) to connect editors through a shared relay.


# Migrating to 0.5 (/docs/migrating-to-0-5)



In 0.5 the default editor in `@betteroffice/docx-react`,
`@betteroffice/xlsx-react` and `@betteroffice/pptx-react` runs its document engine
in a worker, and reads, edits and saves through the editor API are async.

You are affected if your app:

* calls synchronous members of the DOCX editor ref, or passes `onChange`;
* reads the DOCX editor ref on mount or before a document has opened;
* uses the `onReady` API of the XLSX or PPTX editor;
* extends or narrows `DocxEditorProps`, `XlsxEditorProps` or `PptxEditorProps`;
* serves the editors from a bundler, CSP or browser that cannot run module workers.

No export was removed from any npm package: the breaks are changed types and
behaviour. An app that only mounts an editor and uses `onSave` needs no code
change, but check [hosting](#hosting).

## Keep the previous behaviour [#keep-the-previous-behaviour]

Two deprecated props opt out until 0.6.0, when they are removed. They do not
mean the same thing in every package:

| Package      | `legacySyncApi`                                                         | `experimentalWorkerOpen={false}`                             |
| ------------ | ----------------------------------------------------------------------- | ------------------------------------------------------------ |
| `docx-react` | Worker engine with a main-thread copy of the document. Synchronous ref. | In-thread engine, the 0.4 default. Synchronous ref.          |
| `xlsx-react` | In-thread engine. `onReady` gets the synchronous `XlsxEditorApi`.       | In-thread engine. `onReady` still gets `XlsxAsyncEditorApi`. |
| `pptx-react` | In-thread engine. `onReady` gets the synchronous `PptxEditorApi`.       | In-thread engine. `onReady` still gets `PptxAsyncEditorApi`. |

For DOCX, `legacySyncApi` is not the 0.4 default engine; pass
`experimentalWorkerOpen={false}` for that. For XLSX and PPTX, only
`legacySyncApi` restores the synchronous API. Each opt-out logs a deprecation
warning once.

## DOCX: replace synchronous ref members [#docx-replace-synchronous-ref-members]

On the default editor, these ref members throw `DocxSyncApiError` when
called. The member still exists, so `typeof ref.getDocument === "function"` does
not detect it. The error has `code: "sync-api-unavailable"`, the same code as
`XlsxAsyncApiSyncAccessError`, and `member` names the member called.

| Throws               | Use instead                                                                                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getDocument`        | `readParagraphs` or `exportStructuredWithPages`                                                                                                               |
| `getPageContent`     | `exportStructuredWithPages`                                                                                                                                   |
| `findInDocument`     | `findParagraphs`                                                                                                                                              |
| `getSelectionInfo`   | `readSelectionInfo`                                                                                                                                           |
| `getPositionAtPoint` | `readPositionAtPoint`                                                                                                                                         |
| `highlightRange`     | `readPositionAtPoint`                                                                                                                                         |
| `scrollToParaId`     | `scrollToParagraph`                                                                                                                                           |
| `scrollToPosition`   | `scrollToParagraph`                                                                                                                                           |
| `scrollToCommentId`  | `scrollToComment`                                                                                                                                             |
| `scrollToChangeId`   | `scrollToChange`                                                                                                                                              |
| `addComment`         | `insertComment`                                                                                                                                               |
| `replyToComment`     | `insertCommentReply`                                                                                                                                          |
| `proposeChange`      | `proposeChanges`                                                                                                                                              |
| `setParagraphStyle`  | `applyEdits`                                                                                                                                                  |
| `onContentChange`    | `onDocumentChange`                                                                                                                                            |
| `applyFormatting`    | `commands`                                                                                                                                                    |
| `insertBreak`        | `commands`                                                                                                                                                    |
| `getEditorRef`       | `getParagraphIdentities`, `resolveParagraphAnchors`, `readParagraphs`, `readSelectionInfo`, `findParagraphs`, `exportStructuredWithPages` or `proposeChanges` |

Read-only and viewing sessions differ for some members: for example,
`getSelectionInfo` returns `null`, and `getDocument`, `getPageContent` and
`findInDocument` throw `DocxAsyncOnlyError`. Passing `onChange` to the default editor renders an
error and reports `DocxSyncApiError` through `onError`; use
`onDocumentChange` with the async reads.

```tsx
import { DocxSyncApiError, type DocxEditorRef } from "@betteroffice/docx-react";

async function selectedText(editor: DocxEditorRef) {
  try {
    return editor.getSelectionInfo()?.selectedText ?? "";
  } catch (error) {
    if (!(error instanceof DocxSyncApiError)) throw error;
    return (await editor.readSelectionInfo())?.selectedText ?? "";
  }
}
```

The default editor loads as a separate chunk. Until it loads, `DocxEditor`
shows `loadingIndicator` and the forwarded ref is `null`, so do not read the ref
in a mount effect. Before a document has finished opening, ref reads such as
`readParagraphs`, `findText` and `readSelectionInfo` reject with the exported
`DocxEditorNotReadyError` (`code: "editor-not-ready"`), and so do `applyEdits` and
`save`; in 0.4, `save` resolved `null` when no document was open.
`getProposals` and `exportStructuredWithPages` wait for an opening document
instead.

When a queued command cannot run after pending input, `commands.execute`
resolves to `{ ok: false, failure }` whose `failure.code` is a
`DocxCommandAdmissionCode`: `input-failed`, `document-replaced`,
`target-changed` or `editor-unavailable`. Command admission raises these as the
exported `DocxCommandAdmissionError`.

`DocxEditor` also accepts `file` and `fileName`, the prop names of the XLSX and
PPTX editors, as aliases of `documentBuffer` and `documentName`. The older names
keep working; when both are set, `documentBuffer` and `documentName` win and a
development warning names the conflict.

## XLSX: use the async editor API [#xlsx-use-the-async-editor-api]

`onReady` receives `XlsxAsyncEditorApi`. Reading a removed member throws
`XlsxAsyncApiSyncAccessError` (`code: "sync-api-unavailable"`) naming its
replacement, so destructuring (`const { saveAsync } = api`) throws too.

| Throws                                                                | Use instead                                                        |
| --------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `saveAsync`                                                           | `save()`                                                           |
| `flush`, `flushPendingInput`                                          | `commands.execute("save", null)`                                   |
| `undo`, `redo`                                                        | `commands.execute("undo", null)`, `commands.execute("redo", null)` |
| `refreshProposals`                                                    | `commands.execute("proposalsPanel", { open: true })`               |
| `handle`                                                              | `commands`                                                         |
| `cell`, `cellAsync`, `rangeCells`, `rangeCellsAsync`, `readCellsSync` | `readCells(request)`                                               |
| `editCell`, `editCellAsync`                                           | `applyEdits(request)`                                              |
| `selectCells`, `selectCellsAsync`, `clearSelection`                   | plugin `navigation.selectCells`                                    |
| `getPositionAtPoint`                                                  | plugin `geometry.getPositionAtPoint`                               |

`version()`, `readCells`, `findText`, `validateEdits`, `applyEdits` and `save()`
are on the API and return promises. Each one commits pending input first and
rejects with `XlsxCommandAdmissionError` when that input cannot be written or
the workbook is replaced. Plugin members are on the context of a plugin created
with `defineXlsxPlugin`; see
[Host XLSX editor plugins](./javascript#host-xlsx-editor-plugins).

`await api.save()` returns the bytes and calls `onSave` without downloading.
The save command passes the bytes to `onSave` and downloads the workbook when
`downloadOnSave` is set, which defaults to `true` without `onSave` and `false`
with it. The command does not return bytes:

```tsx
import { XlsxEditor, type XlsxAsyncEditorApi } from "@betteroffice/xlsx-react";

const api = useRef<XlsxAsyncEditorApi | null>(null);

<XlsxEditor
  file={bytes}
  onSave={(saved) => upload(saved)}
  onReady={(ready) => { api.current = ready; }}
/>;

const result = await api.current?.commands.execute("save", null);
if (result && !result.ok) console.warn(result.failure);
```

## PPTX: await the editor API [#pptx-await-the-editor-api]

`onReady` receives `PptxAsyncEditorApi`. Use `handleAsync()` instead of
`handle`, which throws `PptxWorkerUnsupportedError` (exported from
`@betteroffice/pptx/worker`) with `code: "sync-api-unavailable"`, the same code
as DOCX and XLSX. Use `save()`, which now returns a promise; `saveAsync()` is a
deprecated alias. Await
`goToSlide`, `selectText`, `clearSelection`, `getPositionAtPoint`, `refresh` and
`refreshProposals`, which now return promises. `exportStructured()` and
`exportMarkdown()` are also on the API directly.

## Collaboration replicas [#collaboration-replicas]

`collaboration.onReplica` replicas are async in all three editors. For DOCX,
call `encodeStateVector`, `encodeStateAsUpdate` and `encodeStateAsUpdateChunks`
through `replica.async`. For XLSX, call `api.collaboration.encodeStateVector()`
and `api.collaboration.encodeStateAsUpdate()` on the `onReady` API. For PPTX, the
replica is an `AsyncCollaborationReplica` whose methods return promises; it may
also expose `encodeStateAsUpdateChunks` and `applyUpdateChunks`. On the default
PPTX editor, `collaboration.clientId` may be omitted and is generated for each
opened session.

## Props types are unions [#props-types-are-unions]

`DocxEditorProps`, `XlsxEditorProps` and `PptxEditorProps` are now unions of
the default and deprecated variants. An interface cannot extend a union, and
`Omit` and `Pick` over it keep only the props every variant shares. Extend the
default variant instead:

```tsx
import type { DocxAsyncEditorProps } from "@betteroffice/docx-react";

interface MyEditorProps extends DocxAsyncEditorProps {
  title: string;
}
```

The XLSX and PPTX equivalents are `XlsxAsyncEditorProps` and
`PptxAsyncEditorProps`.

## Hosting [#hosting]

The packages start their workers with
`new Worker(new URL("./….mjs", import.meta.url), { type: "module" })` and load
the worker editor as a separate chunk with `import()`. Your app needs:

* a bundler that emits those worker files and chunks at URLs the page can load;
* a Content Security Policy that allows same-origin workers (`worker-src 'self'`)
  and the chunks;
* `Worker` and `OffscreenCanvas` in the browser, and for DOCX also
  `HTMLCanvasElement.prototype.transferControlToOffscreen` and
  `createImageBitmap`.

When one of those browser features is missing, the editor falls back to the
deprecated in-thread engine and logs a warning. The fallback does not cover a
worker or chunk that fails to load: a chunk that fails to load reports
`DocxWorkerEditorChunkLoadError`, `XlsxWorkerEditorChunkLoadError` or
`PptxWorkerEditorChunkLoadError` through `onError`; remount to retry. The
editors do not use `SharedArrayBuffer`, so no cross-origin isolation headers
are needed.

## Types you implement [#types-you-implement]

These only affect code that builds its own objects of the package types:

* `docx-react`: `DocxCommandArgs` and `DocxCommandValues` add `tableGridlines`.
  Hand-written `DocxPluginGeometry` objects need `readAnchorGeometries`,
  `readPositionAtPoint`, `getPageRect` and `isPageBuilt`; `DocxPluginReadClient`
  objects need `listStories` and `readStories`.
* `docx`: `YrsSession` from `@betteroffice/docx/yrs` has new members, and its
  `insertText` and `deleteRange` return `YrsReplaceReceipt`.
* `xlsx`: `WorkbookHandle` has new members such as `moveRange`, `setHyperlink`
  and `listDefinedNames`.
* `docx-i18n` and `pptx-i18n`: a complete `LocaleStrings` object needs the new
  keys, including the PPTX `worker` group. `Translations` and
  `PartialLocaleStrings` are unaffected.

## Rust crates [#rust-crates]

The crates move from 0.3 on crates.io to 0.5. In `betteroffice-xlsx`,
`CalculationResult` adds the public field `budget_exhausted`, so struct
literals must set it, and `EditOperation` adds `SetCellValues` (it is
`#[non_exhaustive]`, so matches need no change). The engine crates add public
struct fields and enum variants, and a few engine functions change their
signatures. This includes types that `betteroffice-docx` and
`betteroffice-pptx` re-export, such as `DisplayPage` and `SlideSnapshot`.
Update struct literals and exhaustive matches over these types.


# Packages (/docs/packages)



BetterOffice provides DOCX, XLSX, and PPTX packages for JavaScript, Rust, and
Python. Choose a runtime below, then select the packages for your file format.

| Runtime                 | Install                                | Guide                      |
| ----------------------- | -------------------------------------- | -------------------------- |
| Browser, React, or Node | `npm install @betteroffice/docx-react` | [JavaScript](./javascript) |
| Native Rust             | `cargo add betteroffice-docx`          | [Rust](./rust)             |
| Python                  | `pip install betteroffice-docx`        | [Python](./python)         |

## Packages by format [#packages-by-format]

| Format | npm                                              | crates.io           | PyPI                |
| ------ | ------------------------------------------------ | ------------------- | ------------------- |
| DOCX   | `@betteroffice/docx`, `@betteroffice/docx-react` | `betteroffice-docx` | `betteroffice-docx` |
| XLSX   | `@betteroffice/xlsx`, `@betteroffice/xlsx-react` | `betteroffice-xlsx` | `betteroffice-xlsx` |
| PPTX   | `@betteroffice/pptx`, `@betteroffice/pptx-react` | `betteroffice-pptx` | `betteroffice-pptx` |

All three registries carry DOCX, XLSX, and PPTX. On npm, the core, React, and
locale packages of all three formats are released together under one version.
The font packages, the agent tools, the Rust crates, and the Python packages
have their own versions; use the registry links for current releases.

[VSDX](./vsdx) is available from source with a browser demo. Its npm packages and
Rust crates are not published.

## Fonts [#fonts]

The font packages provide open, metric-compatible alternatives to common
Microsoft fonts, plus Hebrew, Arabic, CJK, and international script coverage.

| Package                     | Contents                                                                                                                                                                                        |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@betteroffice/fonts`       | Carlito, Caladea, Liberation Sans/Serif/Mono, Gelasio, Comic Relief, Inter, Roboto, Source Sans 3, DM Sans, DM Serif Display, Open Sans, Montserrat, Poppins, Oswald, Heebo, Noto Hebrew/Arabic |
| `@betteroffice/fonts-cjk`   | Noto Sans SC/TC/JP/KR, Noto Serif SC                                                                                                                                                            |
| `@betteroffice/fonts-intl`  | Noto coverage for South and Southeast Asian, Armenian, Georgian, Ethiopic, Tibetan, Mongolian, Syriac, Thaana, Cherokee, and Tifinagh scripts                                                   |
| `@betteroffice/fonts-latin` | Latin and Noto RTL font pack, installed with the manager                                                                                                                                        |

For the DOCX editor, install `@betteroffice/fonts` and configure it before
mounting the editor:

```ts
import { configureDefaultFonts } from "@betteroffice/docx/layout";
import * as fonts from "@betteroffice/fonts";

configureDefaultFonts({ fonts });
```

To host the font files on your own CDN, pass `baseUrl` alongside `fonts`. The
module provides the font manifest and is required with either asset location.
Install `@betteroffice/fonts-cjk` when you need Chinese, Japanese, or Korean text.
Install `@betteroffice/fonts-intl` for additional international script coverage.
`@betteroffice/fonts-latin` is installed automatically with `@betteroffice/fonts`.
All font packages are optional and must be installed explicitly.

For headless PPTX (`openPresentation`), pass the faces in `fonts` and
`fallbackFonts`; `loadBundledFontBytes` from `@betteroffice/fonts` returns a
bundled face's bytes.

Missing font bytes can cause fallback measurements and different pagination.
See the language guides for font setup in other formats and runtimes.

## Choose an API [#choose-an-api]

* **React editor:** use a `-react` package for the toolbar, canvas, selection,
  and keyboard controls. The DOCX worker editor displays comment threads; host
  proposal review in its sidebar is opt-in.
* **Custom JavaScript UI:** use a framework-free core for editing, display lists,
  and hit-testing.
* **Native Rust:** use a `betteroffice-docx`, `betteroffice-xlsx`, or
  `betteroffice-pptx` crate.
* **Python scripts and services:** use the corresponding package on PyPI.
* **Individual engine components:** use the parsing, editing, or rendering crates
  listed in the [Rust guide](./rust#the-layers).

[Release notes](https://github.com/openooxml/betteroffice/releases) and each
package's changelog record shipped changes.

[Visual fidelity results](https://github.com/openooxml/betteroffice#benchmarks)
compare published packages and source builds with Microsoft Office on selected
corpus files. The [comparison harness](https://github.com/openooxml/betteroffice/tree/main/scripts/office-quality)
describes the measurement method.


# Python (/docs/python)



```bash
pip install betteroffice-docx
pip install betteroffice-xlsx
pip install betteroffice-pptx
```

Each package includes its Rust engine and runs independently of Microsoft Office.
Wheels support CPython 3.9 and later on Linux (x86\_64, aarch64), macOS (arm64,
x86\_64), and Windows (x86\_64).

Each package also installs the bundled fonts as three data wheels,
`betteroffice-fonts-latin` (4.7 MB), `betteroffice-fonts-intl` (2.2 MB) and
`betteroffice-fonts-cjk` (26.7 MB), shared by all three packages. Layout and
rendering read them from disk; nothing is downloaded at run time.
`register_font` adds a family or replaces a bundled one.

[`betteroffice-xlsx`](https://pypi.org/project/betteroffice-xlsx/) is the
spreadsheet package. Start with the workbook example below, or jump to
[DOCX](#docx) or [PPTX](#pptx).

## Edit a workbook [#edit-a-workbook]

```python
from betteroffice_xlsx import Workbook

wb = Workbook.open_path("budget.xlsx")
sheet = wb["Sheet1"]

sheet["B1"] = 10
sheet["B2"] = 32
sheet["B3"] = "=SUM(B1:B2)"

print(sheet["B3"])
print(sheet.formula("B3"))

wb.save_path("budget-out.xlsx")
```

This prints `42.0` and `SUM(B1:B2)`. Editing a cell recalculates its dependents;
other cells retain their cached results. Use `Workbook.open_recalculated` or
`recalculate()` to evaluate the whole workbook.

Cell values are returned as `None`, `float`, `str`, `bool`, or `CellError`. Errors
remain distinct from text values such as the string `"#DIV/0!"`.

## Render a sheet [#render-a-sheet]

```python
png = wb.render_png("Sheet1", scale=2.0, range="A1:H40")
png.write("preview.png")
```

Spreadsheet rendering uses the bundled fonts. Opening, recalculating,
rendering, and saving release the GIL, allowing these operations to run across
Python threads.

## Saving [#saving]

`save()` returns bytes; `save_path()` writes a file. Both preserve untouched
package parts, including charts, pivot tables, comments, macros, and custom XML.
Changed worksheets are patched to retain unmodified row, column, and cell markup.
Worksheets with missing or out-of-order row or cell addresses, and worksheets
reconstructed from collaboration updates, are serialized from the model instead.

## Collaboration and agent proposals [#collaboration-and-agent-proposals]

`Workbook.open_collaborative` creates a Yrs replica. Use `state_vector`,
`state_as_update`, `diff`, and `apply_update` to exchange updates over your
transport.

`propose` stages agent edits with before-and-after text for review.
`accept_proposal` applies the edits as a single undo step.

## Version-checked edit batches [#version-checked-edit-batches]

`read_cells` and `find_text` return cells with the workbook version they were
read at; `apply_edits` applies a batch against that version as one recalculated
undo step, or returns a refusal dictionary with nothing changed. Requests and
results are the same camelCase dictionaries JavaScript uses:

```python
read = wb.read_cells({"ranges": [{"sheetId": "sheet:0", "range": {"kind": "a1", "a1": "B3"}}]})
result = wb.apply_edits({
    "expectVersion": read["version"],
    "steps": [{
        "op": "setCellInputs",
        "target": {"sheetId": "sheet:0", "range": {"kind": "a1", "a1": "B3"}},
        "inputs": [["120"]],
    }],
})
if not result["ok"]:
    print(result["failure"]["code"])   # e.g. "stale-version"
```

Batches do not insert or delete rows, columns or sheets, and refuse writes to
merged-cell followers, array-formula cells and locked cells of protected sheets.
Formats on a protected sheet need its protection to allow formatting cells.

## Structured export [#structured-export]

`export_structured` and `export_markdown` return a workbook's sparse cells,
sheet metadata and diagnostics, or bounded Markdown with anchor markers, with the
version they were read at. Formula results are the stored values; nothing is
recalculated. Hidden sheets, rows, columns and names are opt-in:

```python
from betteroffice_xlsx import export_xlsx_markdown

result = wb.export_structured(scope=[{"sheet": 0, "range": "A1:H40"}], max_cells=20_000)
if result["ok"]:
    cells = result["content"]["sheets"][0]["cells"]

print(export_xlsx_markdown(wb.save(), markdown_options={"maxRows": 100})["markdown"])
```

See the [package README](https://pypi.org/project/betteroffice-xlsx/) for the full
API, error types, and an openpyxl comparison.

## DOCX [#docx]

[`betteroffice-docx`](https://pypi.org/project/betteroffice-docx/) reads
paragraphs, tables, and sections, edits plain single-run paragraphs, and saves
DOCX files while preserving unsupported package content.

`layout` paginates an input containing measured blocks and layout options.
`render_png` renders a page from that layout with the bundled fonts and any
registered with `register_font`.

`export_structured` returns anchored content in the shared camelCase schema;
`export_markdown` renders Markdown:

```python
from betteroffice_docx import Document

document = Document.open_path("contract.docx")
content = document.export_structured(revision_view="accepted", stories=["body", "footnotes"])
markdown = document.export_markdown(revision_view="markup")["markdown"]
```

Omitted and unsupported content is listed in `diagnostics`; unusable limits raise
`ExportError`. Python exports do not generate page maps; the JavaScript
packages attach them from a layout of the current document.

`list_content_controls` lists the document's content controls as a dict in the
same camelCase schema, and `find_content_controls` returns every exact match of a
tag, alias, `ooxmlId` (the authored `w:id`) or control id:

```python
controls = document.list_content_controls()["controls"]
named = document.find_content_controls({"kind": "tag", "tag": "customer.name"})
```

Each control carries its tag, alias, type, lock, placement, anchor and current
`value`. Filling controls needs a JavaScript editing session and is not available
from Python.

Comparing two DOCX files into tracked changes is not available from Python;
the JavaScript package's `compareDocx` offers it.

## PPTX [#pptx]

[`betteroffice-pptx`](https://pypi.org/project/betteroffice-pptx/) reads decks,
edits shapes and text, and saves `.pptx` files. `render_slide` returns a display
list; `render_png` produces PNG bytes and reads embedded images from the file.
Rendering uses the bundled fonts; `register_font` adds or replaces a family.

A `Presentation` must be used and released on the thread that opened it.

`read_content` returns slides and story text with the session version, and
`apply_edits` applies a batch of text, speaker-notes and shape steps against
that version as one undo step, or returns `{"ok": False, "failure": ...}` with
nothing changed. Requests are the typed dictionaries `PptxEditRequest` and
friends, shared with the JavaScript core.

`export_structured` and `export_markdown` return the committed deck as
structured content or Markdown with the version it was read at, and
`export_pptx_structured(data)` reads bytes as a snapshot. Records carry anchors
and source provenance, hidden slides and shapes, notes and comments are keyword
options, and every omission is listed in `diagnostics`.

`comments()` returns the deck's comments, and `comment_flavor` identifies the
legacy or modern format. Modern comments support replies and resolved status in
PowerPoint 365. Set the format with `set_comment_flavor` before adding comments.
`reply_to_comment` and `set_comment_status` raise an error on legacy decks.

```python
from betteroffice_pptx import Presentation

deck = Presentation.open_path("deck.pptx")
deck.add_comment(
    0,
    "Tighten this claim.",
    author="Ada Lovelace",
    initials="AL",
    created="2026-09-01T10:00:00.000",
    x=1_828_800,
    y=914_400,
)
deck.save_path("reviewed.pptx")
```

Positions use EMUs. Supply the creation timestamp through `created`.


# Rust (/docs/rust)



The Rust crates provide native APIs for the engines used by the browser editors.
Start with `betteroffice-docx`, `betteroffice-xlsx`, or `betteroffice-pptx`.
Individual parsing, editing, and rendering crates are also available.

```bash
cargo add betteroffice-xlsx
```

## Open, edit, render, save [#open-edit-render-save]

```rust
use betteroffice_xlsx::{CalculationOptions, CellRef, RenderOptions, SheetId, Workbook};

let mut workbook = Workbook::open_recalculated(&xlsx_bytes, CalculationOptions::default())?;

workbook.edit_cell(
    SheetId(0),
    CellRef::parse_a1("A1").unwrap(),
    "42",
    CalculationOptions::default(),
)?;

let png = workbook.render_sheet(SheetId(0), &RenderOptions::default())?;
let saved = workbook.save()?;
```

XLSX saves preserve untouched package parts, including charts, pivot tables,
comments, macros, and custom XML. Changed worksheets are patched to retain
unmodified row, column, and cell markup. Worksheets with missing or out-of-order
row or cell addresses, and worksheets reconstructed from collaboration updates,
are serialized from the model instead.

`Workbook::read_cells`, `find_text`, `validate_edits` and `apply_edits` take the
same serializable requests as JavaScript and Python. A batch commits every step
as one recalculated change, or returns an `EditRefusal` with the workbook
untouched:

```rust
use betteroffice_xlsx::{EditRequest, Workbook};

let request: EditRequest = serde_json::from_value(serde_json::json!({
    "expectVersion": workbook.version(),
    "steps": [{
        "op": "setCellInputs",
        "target": { "sheetId": "sheet:0", "range": { "kind": "a1", "a1": "B3" } },
        "inputs": [["120"]],
    }],
}))?;
match workbook.apply_edits(&request)? {
    Ok(applied) => println!("now at {}", applied.version),
    Err(refused) => println!("refused: {:?}", refused.failure.code),
}
```

Batches do not insert or delete rows, columns or sheets, and refuse writes to
merged-cell followers, array-formula cells and locked cells of protected sheets.
Formats on a protected sheet need its protection to allow formatting cells.

`Workbook::export_structured` and `export_markdown` read the committed workbook
with its version as sparse cells, sheet metadata and diagnostics, or as bounded
Markdown with anchor markers; `export_xlsx_structured`, `export_xlsx_markdown`
and `render_xlsx_markdown` work from bytes or content. None recalculates:
formula results are the stored values.

```rust
use betteroffice_xlsx::{XlsxExportOptions, XlsxMarkdownOptions, export_xlsx_markdown};

if let Ok(export) = workbook.export_structured(&XlsxExportOptions::default())? {
    for cell in &export.content.sheets[0].cells {
        println!("{:?} {:?} {}", cell.anchor, cell.formula, cell.display_text);
    }
}
let markdown = export_xlsx_markdown(&xlsx_bytes, &XlsxExportOptions::default(), &XlsxMarkdownOptions::default())?;
```

`Workbook::edit_cell_profiled` and `apply_ops_profiled` return the usual edit
outcome with an `EditProfile`. Supply a monotonic clock reporting milliseconds
to collect validate, apply, recalculation, and result-building durations. Normal
edit methods do not read a profiling clock.

Formula evaluation in `betteroffice-xlsx-calc` computes the date functions in the
1900 date system; only `TEXT` formats dates in a workbook's 1904 system. `RAND` is
not implemented, and the `RANDBETWEEN` seed is set on `EvalContext::rand_seed`, not
through `CalculationOptions`. `ROW()` and `COLUMN()` without a reference return
`#VALUE!` in a context built by `EvalContext::new`, which has no calling cell. A
defined name under `ROW`, `COLUMN`, `ROWS` or `COLUMNS` counts as a direct
reference, so a name bound to a computed reference keeps no dependency edge to
the cells that reference reads, and an `OFFSET` with a computed target
re-evaluates on every recalculation but may read a same-pass write to that target
one recalculation late. `SEARCH` and exact-mode `VLOOKUP`, `HLOOKUP` and `MATCH`
match `*` and `?` literally.

Open and save DOCX and PPTX files through their format APIs:

```rust
use betteroffice_docx::Document;

let mut document = Document::open(&docx_bytes)?;
let paragraph_id = document.paragraphs()[0].para_id.clone().unwrap();

document.replace_paragraph_text(&paragraph_id, "Updated in Rust")?;
let saved = document.save()?;
```

```rust
use betteroffice_pptx::Presentation;

let mut presentation = Presentation::open(&pptx_bytes)?;
let deck = presentation.snapshot()?;

presentation.register_font("Inter", false, false, &font_bytes)?;
let rendered = presentation.render_slide(0)?;
let saved = presentation.save()?;
```

`open_with_limits` on DOCX and PPTX accepts custom parser resource limits. Files
that exceed those limits are rejected.

`Document::export_structured` exports the current DOCX model as read-only
structured content, and `export_markdown` renders it as Markdown with source
anchors:

```rust
use betteroffice_docx::{Document, ExportOptions, RevisionView, StorySelection};

let document = Document::open(&docx_bytes)?;
let content = document.export_structured(&ExportOptions {
    stories: Some(vec![StorySelection::Body, StorySelection::Headers]),
    ..ExportOptions::new(RevisionView::Accepted)
})?;
let markdown = document.export_markdown(&ExportOptions::new(RevisionView::Markup))?;
```

The export reads edits made through the model, lists omitted and unsupported
content in `diagnostics`, and returns `Error::Export` for unusable limits. The
same content comes from `docx_edit::structured` for a live `EditingDoc` or raw
bytes. `Document` exports do not generate page maps: `Document::layout`
paginates measurements you supply, which prove nothing about the current model.
An `EngineSession` in `betteroffice-docx-edit` that lays a document out itself
attaches one with `export_structured_with_pages`, refusing a stale or incomplete
layout as the JavaScript API does.

`Document::list_content_controls` lists the content controls of the current model
in document order, with the structured export's control metadata plus placement,
anchor, parent control, current text and effective lock; `find_content_controls`
keeps the exact matches of an id, tag, authored `w:id` or alias:

```rust
use betteroffice_docx::{ContentControlQuery, ContentControlsOptions, Document};

let document = Document::open(&docx_bytes)?;
let controls = document.list_content_controls(&ContentControlsOptions::default())?;
let query = ContentControlQuery::Tag { tag: "customer.name".to_owned() };
let named = document.find_content_controls(&query, &ContentControlsOptions::default())?;
```

Ids and anchors address the returned snapshot. A live `EditingDoc` lists the same
controls with its version and fills plain- and rich-text ones through
`setContentControlText` steps of `apply_edits`; the `Document` facade has no
fill.

Comparing two DOCX files into tracked changes is available from the
JavaScript package's `compareDocx`. The native Rust and Python APIs do not
offer it; it is planned for when edited sessions save natively.

PPTX edits can also run as version-checked batches. `Presentation::read_content`
and `find_text` return story text with the session version, and `apply_edits`
applies every step against that version as one transaction and one undo step.
Policy refusals, such as a stale version or an ambiguous search, come back as the
inner `Err(EditRefusal)` with the deck unchanged:

```rust
use betteroffice_pptx::{EditRequest, ReadRequest};

let read = presentation.read_content(&ReadRequest::default())?.expect("readable deck");
let request: EditRequest = serde_json::from_value(serde_json::json!({
    "expectVersion": read.version,
    "steps": [{"op": "setSlideNotes", "target": {"slideId": read.slides[0].id}, "text": "Updated"}],
}))?;
match presentation.apply_edits(&request)? {
    Ok(applied) => assert!(applied.applied),
    Err(refusal) => eprintln!("{:?}: {}", refusal.failure.code, refusal.failure.message),
}
```

The request types are the JSON contract the JavaScript core and Python binding
use; `validate_edits` runs the same checks without changing anything.

`export_structured` and `export_markdown` read the committed deck as structured
content or Markdown with the version it was read at, and
`betteroffice_pptx::export_pptx_structured` reads bytes as a snapshot. Records
carry session or snapshot anchors and source provenance, and every omission is
a diagnostic:

```rust
use betteroffice_pptx::PptxExportOptions;

let options = PptxExportOptions {
    include_notes: Some(true),
    ..PptxExportOptions::default()
};
let read = presentation.export_structured(&options)?.expect("usable options");
for slide in &read.content.slides {
    println!("slide {}: {} shapes", slide.index, slide.shapes.len());
}
let markdown = betteroffice_pptx::export_pptx_markdown(&pptx_bytes, &options)?;
```

## PowerPoint comments [#powerpoint-comments]

`comment_flavor` reports whether a deck uses legacy or modern comments. Modern
comments support replies and resolved status in PowerPoint 365. Choose the format
with `set_comment_flavor` before adding the first comment. On legacy decks,
`reply_to_comment` and `set_comment_status` return `EditError::InvalidComment`.

```rust
use betteroffice_pptx::EditCtx;

let context = EditCtx::local("reviewer");
presentation.add_comment(
    &context,
    &deck.slides[0].id,
    "Ada Lovelace",
    "AL",
    "Tighten this claim.",
    "2026-09-01T10:00:00.000",
    1_828_800,
    914_400,
)?;
```

Supply a creation timestamp when adding a comment. Coordinates use EMUs.

## Fonts [#fonts]

The DOCX, PPTX, XLSX and VSDX crates resolve each face from the fonts embedded in
the document, then the faces you register with `register_font` or pass in
`OpenOptions::fonts`, then the bundled packs, then a last resort. The packs are
embedded through default features: `fonts-latin` (4.6 MB), `fonts-intl` (2.2 MB)
and `fonts-cjk` (26.7 MB). Turn off default features to leave them out:

```toml
betteroffice-docx = { version = "0.5", default-features = false, features = ["fonts-latin"] }
```

`open_with_options` reads the packs from a local directory or a provider you
implement instead; nothing is fetched:

```rust
use betteroffice_docx::fonts::{BundledFontOptions, FontPack, FontSource};
use betteroffice_docx::{Document, OpenOptions};

let options = OpenOptions {
    font_source: FontSource::Bundled(BundledFontOptions {
        packs: vec![FontPack::Latin],
        base_url: Some("/srv/betteroffice-fonts".into()),
    }),
    ..OpenOptions::default()
};
let document = Document::open_with_options(&docx_bytes, &options)?;
```

## Rendering [#rendering]

XLSX includes PNG rendering by default. `render_sheet` measures and draws cell
text with the face resolved for each font family, with Carlito as the last
resort. Enable the `raster` feature for native DOCX and PPTX PNG rendering:

```bash
cargo add betteroffice-docx --features raster
cargo add betteroffice-pptx --features raster
```

`render_slide` returns a display list and hit-test metadata. With the `raster` feature enabled, `render_png`
produces PNG bytes and reads embedded images from the presentation. SVG pictures
draw their paths, basic shapes, gradients, clip paths, symbols, `use` references
and hyperlinked content, and leave out their text and embedded raster images. A
picture that uses markers, filters, masks, patterns, scripts or animation is
skipped and counted in `skipped_images`.

PPTX saves preserve untouched parts and patch edited slides to retain unsupported
XML. The ZIP container is rebuilt, so the complete file may differ byte for byte.

## Format APIs [#format-apis]

| Crate               | What it is                                                                                                                                                                                    |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `betteroffice-docx` | Typed native API for opening, editing, laying out, and saving DOCX documents.                                                                                                                 |
| `betteroffice-xlsx` | Typed native API for opening, editing, collaborating, calculating, rendering, and saving XLSX workbooks, including version-checked atomic cell batches and anchored JSON and Markdown export. |
| `betteroffice-pptx` | Typed native API for opening, editing, collaborating on, and rendering PPTX presentations.                                                                                                    |

## The layers [#the-layers]

| Crate                      | What it is                                                                                                                                                                                                                                   |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `betteroffice-opc`         | The OPC container reader and writer, with ZIP expansion limits and path validation.                                                                                                                                                          |
| `betteroffice-fonts`       | Font pack decoding shared by every engine; also available as `fonts::decode_font_face` through each Rust facade. The `manager` feature adds family resolution and local bundled packs.                                                       |
| `betteroffice-fonts-latin` | Embedded Latin pack: metric-compatible Office families, presentation families, Hebrew and Arabic. Enabled by the `fonts-latin` feature.                                                                                                      |
| `betteroffice-fonts-intl`  | Embedded pack for 24 more scripts. Enabled by the `fonts-intl` feature.                                                                                                                                                                      |
| `betteroffice-fonts-cjk`   | Embedded CJK faces through `betteroffice-fonts-cjk-sc`, `betteroffice-fonts-cjk-tc`, `betteroffice-fonts-cjk-jp`, `betteroffice-fonts-cjk-kr` and `betteroffice-fonts-cjk-serif-sc`, one crate per face. Enabled by the `fonts-cjk` feature. |
| `betteroffice-ooxml-text`  | Shared text shaping, measurement, line breaking, and bidirectional text.                                                                                                                                                                     |
| `betteroffice-ooxml-diff`  | The bounded token LCS diff behind PPTX proposal previews and DOCX comparison.                                                                                                                                                                |
| `betteroffice-drawingml`   | The DrawingML colors, themes, shape models, and preset geometry shared by all three formats.                                                                                                                                                 |
| `betteroffice-metafile`    | Bounded EMF, EMF+ and WMF replay into vector drawings and SVG.                                                                                                                                                                               |
| `betteroffice-docx-parse`  | WordprocessingML parsing, typed relationship models, and the typed document model.                                                                                                                                                           |
| `betteroffice-docx-layout` | DOCX pagination, line flow, tables, floats, notes, and display lists.                                                                                                                                                                        |
| `betteroffice-docx-edit`   | CRDT editing and history for DOCX.                                                                                                                                                                                                           |
| `betteroffice-docx-raster` | The tiny-skia backend that paints a DOCX display list to PNG. For native builds.                                                                                                                                                             |
| `betteroffice-xlsx-model`  | Workbook, worksheet, cell, address, value, and style types.                                                                                                                                                                                  |
| `betteroffice-xlsx-parse`  | Streaming SpreadsheetML parse and serialize.                                                                                                                                                                                                 |
| `betteroffice-xlsx-calc`   | Formula parsing, dependency tracking, and evaluation.                                                                                                                                                                                        |
| `betteroffice-xlsx-ops`    | Operations for undo, redo, address remapping, and agent proposals.                                                                                                                                                                           |
| `betteroffice-xlsx-render` | Grid geometry and the target-agnostic display list.                                                                                                                                                                                          |
| `betteroffice-xlsx-raster` | The tiny-skia backend that paints an XLSX display list to PNG. For native builds.                                                                                                                                                            |
| `betteroffice-pptx-parse`  | Bounded PresentationML parsing and part-preserving package writes.                                                                                                                                                                           |
| `betteroffice-pptx-edit`   | The Yrs deck model for PPTX.                                                                                                                                                                                                                 |
| `betteroffice-pptx-render` | Slide layout and the PPTX display-list compiler.                                                                                                                                                                                             |
| `betteroffice-pptx-raster` | The tiny-skia backend that paints a PPTX display list to PNG. For native builds.                                                                                                                                                             |

The published Rust crates share a version. `betteroffice-docx`, `betteroffice-xlsx`
and `betteroffice-pptx` are the supported API. The crates above follow the engines:
their public types gain fields and variants, and their functions change, in any
release.


# Visio VSDX (/docs/vsdx)



VSDX support is available from source. [Try the diagram editor](https://demo.betteroffice.dev/vsdx)
or build the packages from the repository. The packages are not published on
npm, crates.io, or PyPI.

## Rust packages [#rust-packages]

See the [crate READMEs](https://github.com/openooxml/betteroffice/tree/main/crates/betteroffice-vsdx)
for API details and supported operations.

| Crate                       | Purpose                                 |
| --------------------------- | --------------------------------------- |
| `betteroffice-vsdx`         | Native facade                           |
| `betteroffice-vsdx-parse`   | Package parsing and lossless XML        |
| `betteroffice-vsdx-resolve` | ShapeSheet inheritance                  |
| `betteroffice-vsdx-eval`    | Formula evaluation                      |
| `betteroffice-vsdx-render`  | Display lists                           |
| `betteroffice-vsdx-edit`    | Transactional editing and collaboration |
| `betteroffice-vsdx-formula` | Bounded formula parsing                 |

`betteroffice-vsdx-validate` skips the overlapping-shape and connector-crossing
rules on pages where more than `MAX_PAIRWISE_SHAPES` (2,000) shapes have scene
bounds.

## JavaScript and React [#javascript-and-react]

`@betteroffice/vsdx` provides the Wasm engine and Canvas display-list painter. Initialize the Wasm module before opening a diagram.

`decodeFontFace(bytes, { codec, dict?, maxOutput? })` from `@betteroffice/vsdx` asynchronously decodes a packed font with the engine into `{ font, payload? }` ArrayBuffers; it rejects on invalid options or decode errors without retrying another decoder.

`@betteroffice/vsdx-react` provides the React editor. Its strings are supplied by `@betteroffice/vsdx-i18n`. Pass font bytes to the editor so layout and painting use the same faces.

## Rendering [#rendering]

Linear fill gradients render; non-linear `FillGradientDir` values, an
unresolvable stop and gradients with fewer than two stops fall back to the solid
fill with a fidelity diagnostic, and a stop with `GradientStopColorTrans` is
painted opaque and reported. Connectors route without Visio's obstacle
avoidance. Line jumps draw in the arc and gap styles; other jump styles and
last-routed (3) crossings stay unbridged, and a page past the crossing-detection
budget renders with no line jumps at all. The native PNG backend,
`betteroffice-vsdx-raster`, sets each run in the face registered for its family,
else a registered Arial or `sans-serif` face, else Carlito Regular, without
small caps, superscripts or subscripts,
and draws images other than JPEG and PNG as dashed placeholders counted in
`skipped_images`.

## Python [#python]

The Python binding reads pages, shapes, cells, and connections. Build it from a
repository checkout:

```bash
python -m pip install ./bindings/python-vsdx
```

VSDX files are not supported by the redaction CLI.


# WOPI app (/docs/wopi)



The WOPI app exposes BetterOffice as a WOPI client. A WOPI host (your file
platform) opens documents in BetterOffice, and BetterOffice reads and writes
the files back through the host. The app is a single Bun server shipped as a
container image. It serves discovery at `GET /hosting/discovery`, capabilities
at `GET /hosting/capabilities`, a health check at `GET /healthz`, and the
editor page the host embeds in an iframe.

Supported formats are DOCX, XLSX and PPTX. Supported actions are `view`,
`edit` and `editnew`, where `editnew` opens a 0-byte file as a blank document
and writes real bytes on first save.

## Co-editing model [#co-editing-model]

All editors of one file share one file session in one app process:

* One session per host and file id. The server opens the host bytes once and
  holds the document model (the server replica) in memory.
* Browsers join the server replica and exchange updates with it. The server
  applies each update first and broadcasts it only if the engine accepts it.
* Saves are server-side only. Browsers never upload file bytes. The server
  saves the replica back to the host, debounced, on save requests and on
  autosave.
* The app holds the WOPI lock for the session. A save leader (the earliest
  connected editor whose token can write and stays valid) signs host calls
  such as lock refresh and save. Leadership hands over when the leader leaves
  or their token nears expiry.
* When the last editor leaves, the app flushes pending edits before it
  unlocks. A crash loses at most the edits since the last autosave, unless
  the optional journal is on (see Security).

## What it does not do [#what-it-does-not-do]

* No legacy binary formats: no `.doc`, `.xls` or `.ppt`, and no OpenDocument
  formats. Only DOCX, XLSX and PPTX.
* No SharePoint or Microsoft 365 hosting. Hosting there requires Microsoft
  partner onboarding for the host side, which is out of scope.
* No cross-instance synchronisation. Two app instances never share a file
  session (see routing below).
* No disk cache of documents. File bytes live in memory for the session,
  except for the opt-in journal.

## Running it [#running-it]

Build the image from the repo root (the build context is the repo root):

```bash
docker build -f apps/wopi/Dockerfile -t betteroffice-wopi .
```

Run it behind a TLS reverse proxy. `WOPI_PUBLIC_URL` is the public HTTPS
origin browsers and the host use to reach the app:

```bash
docker run -d --name betteroffice-wopi \
  -p 3000:3000 \
  -v wopi-data:/data \
  -e WOPI_PUBLIC_URL=https://office.example.com \
  -e 'WOPI_HOSTS=[{"id":"opencloud","wopiSrcOrigins":["https://cloud.example.com"],"frameOrigins":["https://cloud.example.com"]}]' \
  betteroffice-wopi
```

To keep the variables in a file instead, pass them with the Docker
`--env-file` flag; the app only reads the environment.

Then point the reverse proxy for `https://office.example.com` at port 3000
and check `https://office.example.com/healthz` returns `{"status":"ok"}`.
The proxy terminates TLS for the app, so configure TLS there and have the
proxy send an HSTS header (`Strict-Transport-Security`) on its responses;
the app itself speaks plain HTTP on its port and builds every URL from
`WOPI_PUBLIC_URL`, so it needs no forwarded-header handling.

Notes:

* TLS is required. The app refuses an `http` public URL unless
  `WOPI_ALLOW_HTTP` is `1` (for local smoke tests only).
* Persist `/data`. The proof key lives there by default (see Security). If
  `/data` is lost, the app generates a new proof key and hosts must pick up
  the new discovery values.
* Run one instance per deployment. File sessions and session handles live
  in one process, with no cross-instance sync. A shared affinity cookie
  cannot keep two tabs for different files sticky to different instances.
  Multiple instances require the proxy to route `/wopi/edit` and
  `/wopi/view` by WOPISrc so all opens of one file reach the same instance,
  then map each returned page's `sessionHandle` to that instance. Route
  `/api/session/*`, including the SSE stream at `/api/session/events`, by
  the handle in `Authorization: Bearer`; route `/collab` by the same
  handle in the second `Sec-WebSocket-Protocol` value. Hashing the handle
  alone does not identify the instance that created it. The app provides
  no proxy mapping; without it, multiple instances are not supported.

## Configuration reference [#configuration-reference]

Every variable the server reads. Required variables have no default: the
server exits with an error naming the variable when one is missing or
invalid.

| Variable                    | Default                                                     | Rules                                                                                                                                                                                                                                                                                                                                                            |
| --------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WOPI_PUBLIC_URL`           | required                                                    | Public origin of the app, for example `https://office.example.com`. Must use `https` unless `WOPI_ALLOW_HTTP` is `1`. No query, fragment, username or password. Serve the app at the root of its origin, using a dedicated host name. Path prefixes are not supported. Trailing slashes are stripped.                                                            |
| `WOPI_HOSTS`                | required                                                    | JSON array with at least one entry. Each entry has a non-empty unique `id`, a non-empty `wopiSrcOrigins` array, and a `frameOrigins` array (may be empty). Origins are bare origins only: scheme, host and optional port, no path, query or wildcard. `https` is required unless `WOPI_ALLOW_HTTP` is `1`. One WOPISrc origin may not appear under two host ids. |
| `WOPI_ALLOW_HTTP`           | unset                                                       | Only the exact value `1` allows `http` for `WOPI_PUBLIC_URL` and for host origins. Any other value, including `true`, keeps `https` required.                                                                                                                                                                                                                    |
| `WOPI_PROOF_KEY_FILE`       | `data/proof-key.pem` (the image sets `/data/proof-key.pem`) | Path of the RSA proof key file. Created on first start if missing. Keep it on the persisted volume.                                                                                                                                                                                                                                                              |
| `WOPI_PROOF_OLD_KEY_FILE`   | unset                                                       | Path of the previous proof key file during rotation (see Security).                                                                                                                                                                                                                                                                                              |
| `WOPI_MAX_FILE_BYTES`       | `536870912` (512 MiB)                                       | Positive integer, in bytes. Files larger than this are refused. Sent to hosts as the expected maximum size.                                                                                                                                                                                                                                                      |
| `WOPI_MAX_EDITORS_PER_FILE` | `50`                                                        | Positive integer. Maximum simultaneous editors in one file session.                                                                                                                                                                                                                                                                                              |
| `WOPI_JOURNAL_DIR`          | unset (off)                                                 | Directory for the opt-in crash journal (see Security). Unset means no journal and nothing is written to disk.                                                                                                                                                                                                                                                    |
| `WOPI_INSTANCE_ID`          | random per start                                            | Stable id for this instance. Used in lock ids. Set it when you want recognisable lock owners in host logs.                                                                                                                                                                                                                                                       |
| `WOPI_RECONNECT_GRACE_MS`   | `30000`                                                     | Positive integer, in milliseconds. How long a user whose connection dropped keeps their session and lock before the app saves and releases it. A reconnect within this time resumes without a save and unlock cycle.                                                                                                                                             |
| `PORT`                      | `3000`                                                      | Integer from 1 to 65535. Port the server listens on. The image exposes 3000.                                                                                                                                                                                                                                                                                     |

Example `WOPI_HOSTS` with two hosts:

```json
[
  {"id":"opencloud","wopiSrcOrigins":["https://cloud.example.com"],"frameOrigins":["https://cloud.example.com"]},
  {"id":"nextcloud","wopiSrcOrigins":["https://files.example.com"],"frameOrigins":["https://files.example.com"]}
]
```

* `wopiSrcOrigins`: origins the app accepts in WOPISrc URLs. A WOPISrc from
  any other origin is refused before any fetch. List the origin the host
  puts in WOPISrc, which can differ per host (for OpenCloud it is the
  collaboration service origin, see below).
* `frameOrigins`: origins allowed to embed the editor page (sent as
  `frame-ancestors`). List the origin users open in the browser. It may be
  empty, which forbids framing.

## Memory sizing [#memory-sizing]

For every open file, the source bytes and the full document model of that
file live in memory, plus the shared edit history while the session is open.
Closing the last editor and flushing drops them.

Rule of thumb: budget roughly 5 times the file size per open file, then
measure with your files. A 10 MiB file is then roughly 50 MiB, and a file at
the 512 MiB cap can need a few GiB for one session. Concurrent sessions add
up, so size the container for the sum of the largest files you expect open
at once, and watch resident memory under real load before raising the cap.

The default cap is 512 MiB per file (`WOPI_MAX_FILE_BYTES` is `536870912`).
To allow 1 GiB files, set `WOPI_MAX_FILE_BYTES` to `1073741824` and give the
container memory for several times that per open large file.

## Security [#security]

Proof keys: the app signs WOPI calls to the host with an RSA key and
advertises the public key in discovery. The private key file is created with
restrictive permissions and is never served. Persist `/data` so the key (at
`/data/proof-key.pem` in the image) survives restarts. To rotate: generate
or place the new key at `WOPI_PROOF_KEY_FILE`, move the old key file aside
and set `WOPI_PROOF_OLD_KEY_FILE` to it, then restart. Discovery then
advertises the new key as current and the old key as old, so hosts that
cached the old key keep verifying during the changeover. Remove
`WOPI_PROOF_OLD_KEY_FILE` after hosts have picked up the new key (hosts
cache proof keys, for OpenCloud the default cache duration is 12 hours).

WOPISrc allowlist and frame origins: `WOPI_HOSTS` is the SSRF guard. The app
only fetches WOPISrc URLs whose origin is listed, follows no redirects on
WOPI calls, and only allows framing from the listed `frameOrigins`. Keep
both lists as short as your deployment allows.

Tokens: a host access token reaches the app only in the form POST body that
opens the editor. It is held in server memory for the session and sent to
the host as the `access_token` query parameter on WOPI calls. It is never
put in app URLs or page HTML, never written to disk, and log output redacts
it from URLs. Do not add proxies that log request bodies between the host
and the app.

Journal: `WOPI_JOURNAL_DIR` is off by default because it keeps document
data at rest on the app server. When set, the journal for a file stores
the original source the session opened, every accepted and local update,
and the item versions the app itself wrote as saves land. On reopen
after a restart, recovery runs after the app acquires its lock. If the
host version matches the original version or one the app wrote, it
rebuilds the session from the journal and resumes normal saving. If the
host version is unknown or missing, it rebuilds the journal separately
and uploads the recovered bytes through `PutRelativeFile`, suggesting
`<name> (conflict YYYY-MM-DD HH.mm).<ext>` with the current UTC time.
The host may choose a different name. Only after the upload succeeds
does the app delete the journal and make the session view only with
reason `externalChange`, displaying the host's current file. The original
file is not overwritten. If recovery or the upload fails, opening fails
and the journal stays on disk for a later retry. A normally recovered
journal is deleted on clean session close once no unsaved edits remain;
a broken journal is kept. Only enable it if you accept document data on
that volume, protect the volume like the documents themselves, and delete
journal data with the same retention rules as the files.

## OpenCloud [#opencloud]

Confirmed against the OpenCloud collaboration service configuration
reference. The collaboration service is the WOPI host; this app is the WOPI
client it talks to.

1. Run this app with a public HTTPS URL (above). In `WOPI_HOSTS`, add one
   entry for OpenCloud: `wopiSrcOrigins` and `frameOrigins` both list the
   public OpenCloud origin users open, for example
   `https://cloud.example.com`. If the collaboration service builds WOPISrc
   URLs from a different origin than the browser origin, list that origin
   in `wopiSrcOrigins` instead (it is the origin of the WOPISrc URLs the
   app receives).
2. Configure the collaboration service and restart it:
   * `COLLABORATION_APP_NAME`: a single word with no spaces or special
     characters, for example `BetterOffice`. This is the display name.
   * `COLLABORATION_APP_PRODUCT`: use `Collabora`. The product value
     switches the WOPI dialect the service expects. This app advertises
     both the Collabora-style (mime-named) and Microsoft-style discovery
     entries, and `Collabora` selects the mime-named entries plus the
     capabilities endpoint it already serves, which is the combination
     exercised first. `MicrosoftOfficeOnline` selects the Microsoft-style
     entries instead (unverified end to end with this app).
   * `COLLABORATION_APP_ADDR`: the public URL of this app, for example
     `https://office.example.com`. The service fetches
     `/hosting/discovery` from it.
   * `COLLABORATION_WOPI_SRC`: the base URL (scheme, host, port) where the
     collaboration service is reachable for this app, for example
     `https://cloud.example.com`. WOPISrc URLs are built from it, so its
     origin must be in `wopiSrcOrigins` above.
   * Proof settings: leave proof verification on. Only set
     `COLLABORATION_APP_PROOF_DISABLE` to `true` for debugging, never in
     production. `COLLABORATION_APP_PROOF_DURATION` controls how long the
     service caches proof keys (default `12h`); plan key rotation around
     it (see Security).
   * Also set the shared secret and gateway settings your OpenCloud
     deployment already requires for the collaboration service; they are
     unchanged by adding this app.
3. Open a DOCX, XLSX or PPTX file in OpenCloud and check it opens in
   BetterOffice, edits save back, and two users in the same file see each
   other.

The compose file in `apps/wopi/deploy/opencloud.compose.yml` wires exactly
this for a throwaway smoke test.

## Nextcloud [#nextcloud]

Uses the Nextcloud Office app (`richdocuments`), which is built for a
Collabora server. Confirmed against the Nextcloud admin manual and the
richdocuments settings; items marked unverified have not been confirmed
end to end with this app.

1. Run this app with a public HTTPS URL (above). In `WOPI_HOSTS`, add one
   entry for Nextcloud with `wopiSrcOrigins` and `frameOrigins` both set
   to your Nextcloud origin, for example `https://files.example.com`.
2. Install and enable the Nextcloud Office app (`richdocuments`).
3. In Settings, Administration, Nextcloud Office, set the WOPI (Collabora
   Online) server URL to the public URL of this app, for example
   `https://office.example.com`. If Nextcloud reaches the app at a
   different internal URL than browsers do, set the public WOPI URL
   separately (the app settings expose both; the config keys are
   `wopi_url` and `public_wopi_url`).
4. In the same settings, under the allow list for WOPI requests
   (`wopi_allowlist`), add the egress IP address (or CIDR range) of this
   app: the address Nextcloud sees on the server-to-server WOPI calls from
   the app. Without it, Nextcloud refuses the app's file requests. For a
   container, this is the egress address of the container host or proxy,
   not the container-internal address, unless Nextcloud runs on the same
   private network and sees that address.
5. If the app URL resolves to a local or private address from
   Nextcloud's point of view (as in the smoke compose stack), allow local
   remote servers or Nextcloud refuses the connection:
   `occ config:system:set allow_local_remote_servers --value=true --type=boolean`.
   Leave it off when the app is reachable at a public address.
6. Open a DOCX, XLSX or PPTX file and check viewing, editing, save and a
   second user joining.

Known limitations versus a Collabora server:

* `richdocuments` is built and tested against Collabora, and Nextcloud
  states other WOPI editors are not its tested target. Core view, edit and
  co-editing are expected to work; treat anything Collabora-specific as
  unverified until you have exercised it.
* Collabora-only extras are absent: for example document previews through
  convert-to and the Collabora admin console have no equivalent here
  (unverified, based on the design notes for this integration).
* New-file and template flows go through the host's own flow and then open
  with `editnew`; check your templates after setup (unverified).

The compose file in `apps/wopi/deploy/nextcloud.compose.yml` wires a
throwaway Nextcloud plus this app for a smoke test. It does not automate
the richdocuments settings above; apply them in the admin UI after first
start.

The editor needs a secure browser context: serve it over HTTPS. The smoke
stacks use plain HTTP on `*.localhost` host names, which browsers treat as
secure; other plain HTTP host names fail to open documents.

## Seafile [#seafile]

Confirmed against the Seafile admin manual (Collabora Online integration);
the settings below are Seafile's own. End-to-end behaviour with this app is
unverified unless your smoke test has covered it.

1. Run this app with a public HTTPS URL (above). In `WOPI_HOSTS`, add one
   entry for Seafile with `wopiSrcOrigins` and `frameOrigins` both set to
   your Seafile origin, for example `https://seafile.example.com`.
2. In `seahub_settings.py` (in the Seafile `conf` directory), set:

```python
OFFICE_SERVER_TYPE = 'CollaboraOffice'
ENABLE_OFFICE_WEB_APP = True
OFFICE_WEB_APP_BASE_URL = 'https://office.example.com/hosting/discovery'
ENABLE_OFFICE_WEB_APP_EDIT = True
OFFICE_WEB_APP_FILE_EXTENSION = ('docx', 'xlsx', 'pptx')
OFFICE_WEB_APP_EDIT_FILE_EXTENSION = ('docx', 'xlsx', 'pptx')
WOPI_ACCESS_TOKEN_EXPIRATION = 30 * 60  # seconds
```

* `OFFICE_WEB_APP_BASE_URL` is the discovery URL of this app (note the
  `/hosting/discovery` suffix, unlike the base URLs other hosts take).
* The extension lists in the Seafile manual include legacy and
  OpenDocument formats. Restrict them to `docx`, `xlsx` and `pptx`:
  those are the only formats this app opens, and listing more offers
  users files that then fail to open.
* `WOPI_ACCESS_TOKEN_EXPIRATION` is in seconds; the manual's example is
  30 minutes. Keep it at or above that while users edit: when a token
  expires the app hands save leadership to another editor with a valid
  token, and a lone editor whose token expired cannot save until they
  reopen the file.

3. Restart Seafile (restart the Seahub service or container) and open a
   DOCX, XLSX or PPTX file to check view and edit.
