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

# Build your own skin

A skin is your own chrome around the editor's pages: a toolbar, a menu bar, panels and dialogs that look like your product. Two demos are skins of this type. They use only the public `@reductoai/docx-editor` API:

| Demo | Looks like |
| - | - |
| `/word/` demo | Microsoft Word: ribbon, contextual tabs, galleries, Word's dialogs |
| `/gdocs/` demo | Google Docs: menu bar, one-row toolbar, selection bubble, outline rail |

This guide shows the pattern that both demos follow. The examples use Svelte 5, but each step is plain calls on `EditorModel`, so the same steps work in React, Vue or vanilla JS.

## Choose how much to replace

| Approach | You keep | You build |
| - | - | - |
| **Slots** on `mountDocxEditor` | Pages, caret, ruler, review margin, find, the built-in dialogs, the command palette | The regions you replace |
| **Headless** `EditorModel` | Pages, caret, input, commands | Everything else. See [Headless editor](https://docs.reducto.ai/office/docx/ui/headless-editor.md) |

If you only need to remove or add a few buttons, you do not need a skin: use [`toolbarItems`](https://docs.reducto.ai/office/docx/ui/editor#change-the-format-bar) on the built-in format bar.

Start with slots. Both demos do. The review margin, the ruler and the dialogs are a large amount of work, and a slot lets you keep them while you replace the parts that the user sees first.

## 1. Mount the editor with your slots

A slot is a function that gets a host element and the model, and returns a cleanup. The host element is `display: contents`, so your markup sits in the editor's grid where the built-in region was.

```ts theme={null}
import { mount, unmount, type Component } from "svelte";
import { PALETTE_ON_MOD_K, mountDocxEditor, type EditorModel, type EditorSlot } from "@reductoai/docx-editor";
import "@reductoai/docx-editor/style.css";

function slot<P extends Record<string, unknown>>(
  component: Component<P>,
  props: (model: EditorModel) => P,
): EditorSlot {
  return (host, model) => {
    const instance = mount(component, { target: host, props: props(model) });
    return () => void unmount(instance);
  };
}

const editor = mountDocxEditor(el, {
  worker: () => new Worker(new URL("@reductoai/docx-editor/worker", import.meta.url), { type: "module" }),
  verticalRuler: true,
  keybindings: { overrides: [PALETTE_ON_MOD_K, { key: "mod+o", command: "file.open" }] },
  slots: {
    toolbar: slot(Toolbar, (model) => ({ model })),
    contextMenu: slot(ContextMenu, (model) => ({ model })),
    selection: slot(SelectionBubble, (model) => ({ model })),
    nav: slot(Sidebar, (model) => ({ model })),
    navClosed: slot(NavRail, (model) => ({ model })),
    empty: slot(Empty, (model) => ({ model })),
  },
});
const model = editor.model;
```

For each slot: leave it out to keep the built-in, pass `null` to remove the region, or pass a function to put your markup there.

| Slot | Shown | /gdocs/ | /word/ |
| - | - | - | - |
| `toolbar` | always | one-row toolbar | `null`: the ribbon sits above the editor |
| `selection` | while the document is editable | comment and suggest bubble | `null` |
| `contextMenu` | `model.ui.contextMenu.open` | own menu | own menu |
| `nav` | `model.nav.open` | outline and find | built-in |
| `navClosed` | `model.nav` is closed | rail button that opens it | none |
| `empty` | no document open | sample picker | sample picker |
| `progress` | a document opens | built-in | built-in |
| `inspector` | `model.inspectorVisible` | built-in | built-in |

Find lives in the `nav` region: `model.find.show()` and Ctrl+F open the pane on its results tab. If you set `nav` to `null`, render your own find box while `model.find.open` is true, or find has no UI.

A region that is outside the editor (a title bar, a menu bar, a ribbon) is not a slot. Put it next to the mount element and give it `editor.model`.

In React, each slot is a prop that takes a node: `<DocxEditor toolbar={<MyToolbar model={model} />} selection={null} />`.

## 2. Bind your UI to the model

`EditorModel` is an `Observable`. `subscribe(fn)` calls `fn` on every change. `subscribe(fn, "format")` calls it when one field changes. Side models (`review`, `find`, `nav`, `spell`, `ui`) are adopted children, so a change in them also reaches a listener on the model.

Both demos use one small bridge, so that a template runs again when the model changes:

```ts theme={null}
// live.svelte.ts
import { createSubscriber } from "svelte/reactivity";
import type { EditorModel } from "@reductoai/docx-editor";

export function live(model: EditorModel): { readonly m: EditorModel } {
  const track = createSubscriber((update) => model.subscribe(update));
  return {
    get m() {
      track();
      return model;
    },
  };
}
```

```svelte theme={null}
<script lang="ts">
  let { model }: { model: EditorModel } = $props();
  const view = live(model);
  const f = $derived(view.m.format);
  const off = $derived(view.m.ir === null || !f);
</script>

<button class:on={f?.bold} disabled={off} onclick={() => model.toggleBold()}>B</button>
```

In React, use `useObservable(model, (m) => ({ bold: !!m?.format?.bold }))`. Always give a selector to a component that stays mounted, because the model changes on each caret move.

Fields that a skin reads most:

| Field | Use |
| - | - |
| `ir` | `null` when no document is open. Disable controls on it |
| `format` | [`FormatState`](https://docs.reducto.ai/office/docx/api/types-editor-text-and-formatting#formatstate) at the caret: run, paragraph, list, table, image, section |
| `canUndo`, `canRedo` | Undo and redo buttons |
| `readOnly`, `suggesting`, `suggestingPolicy` | The mode control (Editing, Suggesting, Viewing). Hide the choice unless `suggestingPolicy` is `"allow"` |
| `zoom`, `page`, `pageLabel` | Status bar and zoom box |
| `name` | The title. Set it to rename the file |
| `review.markupCount`, `review.open`, `review.canComment` | Comment buttons |
| `version` | Goes up on each change. Use it to build a menu again while it is open |

## 3. Run commands

There are three ways to run a command. Use the highest one that does the job:

1. **A keymap command**: `model.keys.run("format.bold")`. The keymap also gives the shortcut text (`keys.label(id)`), a tooltip (`keys.title(id, "Bold")`) and the enabled state (`keys.enabled(id)`). Your button, menu item and shortcut then always agree. See [Keyboard shortcuts](https://docs.reducto.ai/office/docx/ui/keyboard-shortcuts.md) for the ids.
2. **A method**: `toggleBold()`, `setAlignment("center")`, `toggleList("bullet")`, `applyRunFormat({ font: "Arial" })`, `undo()`, `startComment()`, `pickImage()`, `copyFormat()` and `pasteFormat()`.
3. **An `EditorCommand`**: `await model.run({ kind: "paragraphFormat", format: { styleId: "Heading1" } })`. Every edit is one of these. Read [`EditorCommand`](https://docs.reducto.ai/office/docx/api/types-editor-editor#editorcommand) for the full list.

```ts theme={null}
const tip = model.keys.title("format.italic", "Italic"); // "Italic (⌘I)"
model.keys.run("paragraph.indent");
await model.run({ kind: "list", format: "decimal" });
await model.run({ kind: "sectionFormat", format: { orientation: "landscape" } });
```

Some actions need more than one command, or a browser API. [Editor actions](https://docs.reducto.ai/office/docx/api/editor-actions.md) has them as functions: `runClipboard(model, "paste", "text")`, `openLinkDialog(model)`, `selectTablePart(model, "row")`, bookmarks, notes, headers and footers, and `insertTextFromFile`.

### Keep the caret

A click on a toolbar button must not take focus from the document. If it does, the selection goes away before the command runs.

* Call `event.preventDefault()` on `mousedown` in the toolbar. Do not do this on text inputs (the font size box).
* After a popup or dialog closes, call `model.focusInput()`.

```svelte theme={null}
<div role="toolbar" onmousedown={(e) => (e.target as HTMLElement).tagName !== "INPUT" && e.preventDefault()}>
```

## 4. Build menus from data

Both demos keep menus as data: a list of entries that a function builds when the menu opens. The function reads the model at that time, so checked and disabled states are always current.

```ts theme={null}
type Entry =
  | { kind: "sep" }
  | { kind: "item"; label: string; run?: () => void; keys?: string; checked?: boolean; disabled?: boolean; missing?: string }
  | { kind: "sub"; label: string; items: () => Entry[] };

const key = (model: EditorModel, id: string, label: string): Entry => ({
  kind: "item",
  label,
  run: () => model.keys.run(id),
  keys: model.keys.label(id) || undefined,
  disabled: !model.keys.enabled(id),
});

function editMenu(model: EditorModel): Entry[] {
  return [
    key(model, "edit.undo", "Undo"),
    key(model, "edit.redo", "Redo"),
    { kind: "sep" },
    { kind: "item", label: "Paste without formatting", run: () => void runClipboard(model, "paste", "text") },
  ];
}
```

To show a menu, call the builder inside the template and read `model.version` first, so that the menu updates while it is open: `{@const entries = (m.version, popup.build())}`.

If your menu has an entry that you cannot serve yet, give it a reason (`missing` above). Show the entry greyed out, with the reason as its tooltip. The user then knows the feature is planned, not lost.

### Put your menus in the command palette

The built-in palette (`model.ui.palette`) searches registered providers. Register one that walks your menus, and "search the menus" finds every leaf:

```ts theme={null}
model.ui.palette.register(() =>
  MENUBAR.flatMap((name) => leaves(menuFor(name, model)).map((e) => ({
    id: `skin:${name}:${e.label}`, group: "document", label: e.label, detail: name, run: e.run,
  }))),
);
```

## 5. Fill galleries and lists

[Fonts, colours and galleries](https://docs.reducto.ai/office/docx/api/editor-galleries.md) has the data that a font box or a Word gallery needs:

| Control | Data |
| - | - |
| Font box | `fontChoices(model.format?.font)`; preview each name with `faceCss(name)` |
| Size box | `FONT_SIZES` |
| Highlight grid | `HIGHLIGHTS` (Word's 16 named colours) |
| Style box | `model.host.paragraphStyles()`, named with `styleLabel(style.name)`, previewed with `lookCss`. `style.inUse` marks the styles the document uses (Word's "In current document"); `style.builtin` marks one Word adds on first use, applied by `style.name` |
| Theme colours and fonts | `WORD_THEME_COLORS`, `WORD_THEME_FONTS`; swatches from `THEME_GALLERY_SLOTS`, the picker row from `themeRow` |
| Line spacing | `PARAGRAPH_SPACING_PRESETS` |
| Multilevel list | `WORD_MULTILEVEL_LISTS` |
| Picture effects | `SHADOW_PRESETS`, `REFLECTION_PRESETS`, `GLOW_PRESETS`, `SOFT_EDGE_PRESETS`, `RECOLOR_TILES`; tile CSS from `effectLook` and `recolorLook` |
| Table styles | `model.host.tableStyles()`, previewed with `tableThumb(style.tableLook, table.look)` |
| Shapes | `SHAPE_GROUPS`, previewed with `shapePreview` |
| Chart Quick Layout | `quickLayoutThumb(n)` |
| Symbols | `SYMBOL_SUBSETS`, `subsetChars`, `SPECIAL_CHARACTERS` |
| Proofing language | `sortedLanguages()`, named with `languageName` |

Each gallery value is the payload of one `EditorCommand`, so a click is one `model.run(...)`.

```ts theme={null}
const fonts = fontChoices(model.format?.font).map((name) => ({
  label: name,
  css: faceCss(name),
  checked: model.format?.font === name,
  run: () => model.applyRunFormat({ font: name }),
}));
```

## 6. Context menu

The editor decides what a right click offers. It puts the rows in `model.ui.contextMenu` (`open`, `x`, `y`, `items`). Your `contextMenu` slot only draws them:

```ts theme={null}
function entries(items: MenuItem[]): Entry[] {
  return items.map((row) =>
    row.kind === "separator" ? { kind: "sep" }
    : row.kind === "submenu" ? { kind: "sub", label: row.label, items: () => entries(row.items) }
    : { kind: "item", label: row.label, keys: row.detail, disabled: row.disabled, checked: row.checked, run: row.run },
  );
}
```

When the user picks a row or clicks outside, call `model.ui.contextMenu.close()` and then `model.focusInput()`.

## 7. Floating UI over the pages

To place a bubble next to the selection, use `model.selectionBox()` (client coordinates) and `model.layerFor(pageIndex)` (the page element). Hide the bubble while `model.pointing` is true (a drag is in progress) or while `model.ui.contextMenu.open` is true. Listen for `scroll` (capture) and `resize` and place it again.

## 8. Panels: navigation, find, review, spelling

| Panel | Model | Calls |
| - | - | - |
| Outline | `model.nav` | `show("headings")`, `hide()`, `rows`, `tab` |
| Find and replace | `model.find` | `query`, `search()`, `step(1)`, `replace()`, `replaceAll()`, `hits`, `index` |
| Comments and changes | `model.review` | `toggle()`, `accept(scope)`, `reject(scope)`, `reply(id, text)` |
| Spelling | `model.spell` | `toggle()`, `suggest(word)`, `replace(miss, word)`, `add(word)`, `ignore(word)` |

Read [Review, find and navigation models](https://docs.reducto.ai/office/docx/api/editor-panels.md) for each member.

## 9. Your own commands and keys

Register host actions (open, print, a dialog) as keymap commands. Then a shortcut, a menu item and the palette all run the same thing, and the user can change the key:

```ts theme={null}
const off = model.keys.register({ id: "file.print", title: "Print", category: "File", run: () => print() });
// with { key: "mod+p", command: "file.print" } in keybindings.overrides
```

Each `register` returns a function that removes the command. Call it when the skin unmounts, before `editor.destroy()`.

## 10. Files

| Action | Call |
| - | - |
| Open | `editor.open(bytes, name)` |
| New | `model.openBlank()` |
| Drop a picture | `const file = imageFileFrom(event.dataTransfer); if (file) await model.insertImageFile(file)` |
| Download | `downloadDocx(model)`, `downloadPdf(model)` |
| Print | `const { bytes } = await model.toPdf()`, then print it in a hidden `iframe` |
| Compare | `model.compareWith(bytes, { name })` |
| Insert a file at the caret | `insertTextFromFile(model, file)` |
| Password-protected files | `model.passwordPrompt`, `model.unlock(password)` |
| Password to modify, read-only recommended | `model.modifyPrompt`, `model.answerModify(answer)` |

Show errors with `model.fail(message)`. The editor shows them in its own toast.

## 11. Dialogs

You can keep the built-in dialogs and call them from your chrome, for example `model.ui.openAuthorDialog(model.revisionAuthor)`. To draw a dialog of your own, read the current values from `model.format` (for page setup, `format.section`), then send one command when the user clicks OK:

```ts theme={null}
await model.run({ kind: "sectionFormat", format }).catch((error) => model.fail(String(error)));
model.focusInput();
```

## 12. Look and feel

* Override the CSS tokens of the editor (`--rd-accent`, `--rd-radius`, `--rd-font-sans`, and the others in `@reductoai/docx-editor/tokens.css`) so that the pages, rulers and built-in panels match your chrome. The tokens are in a cascade layer, so a plain `:root` rule wins whether your CSS loads before or after the package's.
* Give your own classes a prefix, so that they do not collide with the editor's classes.
* The editor's reset and base font apply only under the `reductoai` class. Your chrome outside the mount root keeps your page's styles. To give it the editor's base, add `class="reductoai"` to its root.
* Your slot markup is in the editor's grid. Style it as a grid item.

## Checklist

* Disable controls when `model.ir` is `null`.
* Prevent focus loss on `mousedown`, and call `model.focusInput()` after each popup.
* Prefer `model.keys.run(id)` for commands that have a shortcut.
* Build menus when they open. Do not cache them.
* Remove every `register` and `subscribe` when the skin unmounts.
* Keep `window.editor = model` in development builds. You can then try a command in the console before you add a button for it.
