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

# Custom components

> [!WARNING]
>
> Custom components are an alpha feature. The API can change in a future release.

A custom component is your own UI inside a document: a signature box, a sortable table, an approval stamp. The editor shows your live view. The file keeps plain Word content, so Word and the PDF show it too.

A component has two parts:

* **Fallback.** Word content made from the component's state: a picture, a table, or free content. Word, the layout and the PDF show it.
* **Live view (optional).** DOM mounted over the fallback's box. It edits the document only through `commit(state)`.

The fallback keeps the component's type, id and JSON state:

| Fallback | Data is kept in | Use it for |
| - | - | - |
| Picture | The picture's properties (`wp:docPr` name and an extension) | Boxes with a fixed size: signatures, stamps, QR codes, charts |
| Table | The table's title and description (alt text) | Data that a Word user can also read and edit |
| Content | The code of an `ADDIN` field whose result is the content | Text, lists and tables that flow with the page: quotes, clauses, summaries |

Word keeps this data through edits, moves, resizes, copies and sorts. If the user deletes the content, the component is gone. If the data is lost, the content stays as a plain picture, table or text.

## Define a component

```ts theme={null}
import { defineComponent, type ComponentFallback } from "@reductoai/docx/components";

type Stamp = { status: "draft" | "approved" };

// Your own code: the PNG of a stamp.
declare function pngFor(status: Stamp["status"]): Uint8Array;

const stamp = defineComponent<Stamp>({
  type: "acme.stamp",
  fallback: (state): ComponentFallback => ({
    kind: "picture",
    bytes: pngFor(state.status),
    mime: "image/png",
    widthPt: 120,
    heightPt: 40,
    alt: state.status === "approved" ? "Approved" : "Draft",
  }),
});
```

* `type`: the component kind. Letters, digits, `.`, `_` and `-`, with your own prefix.
* `fallback(state)`: returns the Word content. Keep it pure. It runs on each state change, not at save.
* `read(rows, stored)`: table components only. Turns the cells back into state, because a Word user can edit them.

Fallback kinds:

* `picture`: PNG, JPEG, GIF, BMP, TIFF, EMF or WMF `bytes`, with an optional `svg` for sharp output. See [A QR code](#a-qr-code).
* `table`: `rows` of strings (the first row is the header) and an optional `style`.
* `content`: `ooxml`. See [Free content](#free-content).

## Add a live view in the editor

Pass components to `mountDocxEditor` as `components`. `mount(el, ctx)` gets a node over the fallback's box. The node moves and scales with the page, so size your view in `%` or `cqw`/`cqh`. The node ignores the pointer: set `pointer-events: auto` on the parts a user clicks. When a user turns or mirrors a picture, the node turns with it; `ctx.rotDeg` and `ctx.flip` give the angle and the mirror.

`drawPicture(widthPt, heightPt, draw)` makes a PNG fallback from a canvas. `insertComponent(model, def, state)` inserts a component at the caret.

```ts theme={null}
import { insertComponent } from "@reductoai/docx/components";
import { WordDocument } from "@reductoai/docx/officejs";
import { drawPicture, mountDocxEditor } from "@reductoai/docx-editor";

const W = 200;
const H = 64;

// Strokes are lists of [x, y] points, in points inside the box.
function ink(ctx, strokes) {
  ctx.strokeStyle = "#111";
  ctx.lineWidth = 1.5;
  ctx.lineCap = ctx.lineJoin = "round";
  for (const stroke of strokes) {
    ctx.beginPath();
    stroke.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
    ctx.stroke();
  }
}

function envelopeHash(strokes) {
  let h = 2166136261;
  for (const [x, y] of strokes.flat()) h = Math.imul(h ^ (x * 31 + y), 16777619);
  return (h >>> 0).toString(16).toUpperCase().padStart(8, "0") + "C67BF1455...";
}

function signHere(ctx, label) {
  ctx.fillStyle = "#fff8d6";
  ctx.fillRect(0, 0, W, H);
  ctx.strokeStyle = "#f2b700";
  ctx.setLineDash([4, 3]);
  ctx.strokeRect(0.5, 0.5, W - 1, H - 1);
  ctx.setLineDash([]);
  ctx.fillStyle = "#ffcd1c";
  ctx.beginPath();
  ctx.moveTo(6, 8);
  ctx.lineTo(48, 8);
  ctx.lineTo(58, 20);
  ctx.lineTo(48, 32);
  ctx.lineTo(6, 32);
  ctx.fill();
  ctx.fillStyle = "#1d1d1d";
  ctx.font = "bold 11px Arial";
  ctx.fillText("SIGN", 14, 24);
  ctx.fillStyle = "#8a7a3c";
  ctx.font = "10px Arial";
  ctx.fillText(label + " signature", 8, H - 10);
}

// DocuSign's stamp: a rounded bracket, the label on its top arm, the hash on its bottom arm.
function stamp(ctx, state) {
  const r = 9;
  const top = 8;
  const bottom = H - 8;
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, W, H);
  ctx.strokeStyle = "#1f4e8c";
  ctx.lineWidth = 1.8;
  ctx.beginPath();
  ctx.moveTo(18, top);
  ctx.arcTo(2, top, 2, bottom, r);
  ctx.arcTo(2, bottom, 18, bottom, r);
  ctx.lineTo(18, bottom);
  ctx.stroke();
  ctx.fillStyle = "#111";
  ctx.font = "bold 8.5px Arial";
  ctx.fillText("DocuSigned by:", 21, top + 3);
  ctx.font = "8px Arial";
  ctx.fillText(envelopeHash(state.strokes), 21, bottom + 3);
  ink(ctx, state.strokes);
}

const signature = {
  type: "acme.signature",
  fallback: (state) =>
    drawPicture(
      W,
      H,
      (ctx) => (state.strokes.length ? stamp(ctx, state) : signHere(ctx, state.label)),
      { alt: state.signedAt ? state.label + " signed " + state.signedAt : "Sign here: " + state.label },
    ),
  mount(el, { state, commit, readOnly }) {
    if (state.strokes.length || readOnly) return;
    const pad = document.createElement("canvas");
    pad.style.cssText =
      "pointer-events:auto;position:absolute;inset:0;width:100%;height:100%;cursor:crosshair;touch-action:none";
    const bar = document.createElement("div");
    bar.style.cssText =
      "pointer-events:auto;position:absolute;right:3%;top:10%;display:flex;gap:2cqw;font:600 4cqw Arial";
    const button = (text, css, onclick) => {
      const b = document.createElement("button");
      b.textContent = text;
      b.style.cssText = "border:0;border-radius:3px;padding:0.4em 0.8em;cursor:pointer;" + css;
      b.onclick = onclick;
      bar.append(b);
      return b;
    };
    let strokes = [];
    const paint = () => {
      const { width, height } = pad.getBoundingClientRect();
      pad.width = width * devicePixelRatio;
      pad.height = height * devicePixelRatio;
      const ctx = pad.getContext("2d");
      ctx.scale(pad.width / W, pad.height / H);
      ink(ctx, strokes);
      adopt.disabled = !strokes.length;
      adopt.style.opacity = strokes.length ? "1" : "0.4";
    };
    const at = (e) => {
      const r = pad.getBoundingClientRect();
      return [
        Math.round(((e.clientX - r.left) / r.width) * W * 10) / 10,
        Math.round(((e.clientY - r.top) / r.height) * H * 10) / 10,
      ];
    };
    pad.onpointerdown = (e) => {
      pad.setPointerCapture(e.pointerId);
      strokes.push([at(e)]);
    };
    pad.onpointermove = (e) => {
      if (!pad.hasPointerCapture(e.pointerId)) return;
      strokes.at(-1).push(at(e));
      paint();
    };
    button("Clear", "background:#fff;color:#333;box-shadow:inset 0 0 0 1px #bbb", () => {
      strokes = [];
      paint();
    });
    const adopt = button("Adopt and Sign", "background:#ffcd1c;color:#1d1d1d", () =>
      commit({ ...state, strokes, signedAt: new Date().toLocaleDateString("en-US") }),
    );
    el.append(pad, bar);
    paint();
  },
};

const TERMS = [
  ["Term", "The lease starts on 1 April 2026 and ends on 31 March 2027. After that, it continues from month to month until either party gives 30 days of written notice."],
  ["Rent", "The Tenant pays GBP 1,850 per month, in advance, on the first day of each month, by bank transfer to the account the Landlord names in writing. Rent that is more than 14 days late carries interest at 3% above the Bank of England base rate."],
  ["Deposit", "The Tenant pays a deposit of GBP 2,775 before the start date. The Landlord keeps it in a government-approved scheme and returns it within 10 days of the end of the lease, less any agreed deductions."],
  ["Use", "The Tenant uses the property only as a private home for no more than two persons. The Tenant does not sublet the property or assign this Agreement without the written consent of the Landlord."],
  ["Repairs", "The Landlord keeps the structure, the heating and the water supply in repair. The Tenant tells the Landlord about a defect as soon as possible and keeps the interior clean and in good condition."],
  ["Utilities", "The Tenant pays for gas, electricity, water, broadband and council tax from the start date until the end of the lease."],
  ["Access", "The Landlord may enter the property to inspect it or to do repairs at reasonable times, after at least 24 hours of written notice, except in an emergency."],
  ["Notices", "A notice under this Agreement is in writing and goes to the address of the other party shown above, or to an email address that the other party gives for this purpose."],
  ["Governing law", "The law of England and Wales governs this Agreement, and its courts have jurisdiction over any dispute."],
  ["Entire agreement", "This document is the full agreement between the parties. A change is valid only when both parties sign it."],
];
const SIGNERS = [
  ["Tenant", "Ada Lovelace"],
  ["Landlord", "Charles Babbage"],
];

// One page of a DocuSign envelope, written with the Office.js API.
async function lease() {
  const doc = await WordDocument.create();
  const { body } = doc;
  doc.setDefaultFont("Times New Roman");
  doc.getStyles().getByNameOrNullObject("Normal").font.size = 11.5;
  const section = doc.sections.getFirst();
  section.pageSetup.set({ topMargin: 54, bottomMargin: 54, leftMargin: 64, rightMargin: 64, headerDistance: 28 });
  section
    .getHeader("Primary")
    .insertParagraph("Docusign Envelope ID: 7C2A91E4-3B5F-4D08-9E61-A4F0C38B2D57", "Start")
    .font.set({ name: "Arial", size: 7.5, color: "#444444" });

  const title = body.paragraphs.getFirst();
  title.insertText("RESIDENTIAL LEASE AGREEMENT", "Start").font.set({ bold: true, size: 16 });
  title.set({ alignment: "Centered", spaceAfter: 2 });
  const address = body.insertParagraph("Unit 4B, 18 Analytical Row, London NW1 6XE", "End");
  address.set({ alignment: "Centered", spaceAfter: 16 });
  address.font.set({ bold: false, italic: true, size: 11.5 });
  const clause = (text) => {
    const p = body.insertParagraph(text, "End");
    if (p.isListItem) p.detachFromList();
    p.set({ alignment: "Justified", spaceAfter: 7 });
    p.font.set({ bold: false, italic: false });
    return p;
  };
  clause("This Lease Agreement (the Agreement) is made on 1 March 2026 between Charles Babbage (the Landlord) and Ada Lovelace (the Tenant), who agree to the terms below.");
  // The terms are one numbered list: a bold number, a tab, and a hanging indent.
  // A paragraph inserted after a list item joins the list, as in Word.
  for (const [head, text] of TERMS) {
    const p = body.insertParagraph("", "End");
    p.insertText(head + ". ", "End").font.bold = true;
    p.insertText(text, "End").font.bold = false;
    if (!p.isListItem) {
      const list = p.startNewList("decimal");
      list.setLevelNumbering(0, "Arabic", [0, "."]);
      list.setLevelFont(0, { bold: true });
      list.setLevelIndents(0, 27, -27);
    }
    p.set({ alignment: "Justified", spaceAfter: 7, noSpaceBetweenParagraphsOfSameStyle: false });
  }
  clause("IN WITNESS WHEREOF, the parties sign this Agreement on the dates shown below.").set({
    spaceBefore: 10,
    spaceAfter: 18,
  });

  // The signature blocks: one row, two cells, no borders.
  // A cell is built from its last paragraph up: Word types an End insert into that last paragraph.
  const table = body.insertTable(1, 2, "End", [SIGNERS.map(() => "Date: ____________________")]);
  for (const side of ["Top", "Bottom", "Left", "Right", "InsideHorizontal", "InsideVertical"]) {
    table.getBorder(side).type = "None";
  }
  for (const [col, [role, name]] of SIGNERS.entries()) {
    const date = table.getCell(0, col).body.paragraphs.getFirst();
    date.set({ spaceBefore: 14, spaceAfter: 0, rightIndent: 36 });
    const line = date.insertParagraph(name, "Before");
    line.font.bold = true;
    line.insertText(", " + role, "End").font.bold = false;
    line.borders.items[0].set({ isVisible: true, lineStyle: "Single", lineWidth: 0.75, color: "#000000" });
    line.set({ spaceBefore: 6, spaceAfter: 0 });
    const pad = line.insertParagraph("", "Before");
    pad.insertParagraph(role.toUpperCase(), "Before").set({ spaceBefore: 0, spaceAfter: 8 });
  }
  // Word keeps a paragraph after every table; this one stays small so the page holds.
  const tail = body.paragraphs.getLast();
  tail.set({ spaceBefore: 0, spaceAfter: 0, lineSpacing: 1 });
  tail.font.size = 1;

  for (const [col, [role]] of SIGNERS.entries()) {
    // A paragraph inserted Before copies its neighbour's border, as in Word.
    const [heading, pad] = table.getCell(0, col).body.paragraphs.items;
    heading.font.bold = true;
    heading.borders.items[0].isVisible = false;
    pad.borders.items[0].isVisible = false;
    pad.set({ spaceBefore: 0, spaceAfter: 0 });
    await insertComponent(doc, signature, { label: role, strokes: [] }, { paragraph: pad });
  }
  return doc.toBytes();
}

const editor = mountDocxEditor(el, { worker, components: [signature] });
lease().then((bytes) => editor.open(bytes, "Lease.docx"));
```

Live example

Scroll to the end of the lease. Draw a signature in a yellow box, then click **Adopt and Sign**. The strokes go into the state and the fallback becomes a DocuSign-style stamp. Undo restores the empty box in one step. Word shows the same stamp.

`WordDocument` writes the lease with Office.js, and the headless `insertComponent` puts a signature box in each table cell. The pad keeps the strokes until Adopt and Sign, so signing is one edit, not one per stroke.

### Check the round trip

Each live editor has **.docx**, **PDF** and **Open** buttons. To check that the file keeps the component:

1. Sign, then click **.docx**.
2. Open the file in Word, edit the text around the fallback, and save.
3. Click **Open** and select the saved file. The live view comes back with its state.

The PDF shows what a reader without the editor sees.

## A sortable table

A table component keeps its data in the cells. A Word user can edit cells, add rows or sort, and `read` gets the change. The state keeps only view settings, here the sort column.

The view adds a row of sort buttons above the table. The canvas still paints the real table, so it can split over pages. A split table gets one view per page; `ctx.part` and `ctx.parts` tell them apart.

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

const BLUE = "#2563eb";

const stars = {
  type: "acme.stars",
  fallback: (state) => ({ kind: "table", rows: state.rows, style: "Grid Table 4 - Accent 1" }),
  read: (rows, stored) => ({ ...stored, rows }),
  mount(el, { state, commit, part, readOnly }) {
    if (part > 0 || readOnly) return;
    const [header, ...body] = state.rows;
    const bar = document.createElement("div");
    bar.style.cssText =
      "position:absolute;bottom:100%;left:0;display:flex;align-items:center;gap:1cqw;padding-bottom:1.2cqw;" +
      "font:600 2.2cqw system-ui,sans-serif;color:#475569";
    bar.append("Sort by");
    header.forEach((name, column) => {
      const on = state.sort === column;
      const button = document.createElement("button");
      button.textContent = on ? name + (state.descending ? " ↓" : " ↑") : name;
      button.style.cssText =
        "pointer-events:auto;cursor:pointer;border-radius:999px;padding:0.3em 0.9em;font:inherit;" +
        "border:1px solid " + BLUE + ";" + (on ? "background:" + BLUE + ";color:#fff" : "background:#fff;color:" + BLUE);
      button.onclick = () => {
        const descending = on && !state.descending;
        const sorted = [...body].sort((a, b) => {
          const x = Number(a[column]);
          const y = Number(b[column]);
          const order = Number.isNaN(x - y) ? a[column].localeCompare(b[column]) : x - y;
          return descending ? -order : order;
        });
        void commit({ rows: [header, ...sorted], sort: column, descending });
      };
      bar.append(button);
    });
    el.append(bar);
  },
};

const editor = mountDocxEditor(el, { worker, components: [stars] });
insertComponent(editor.model, stars, {
  rows: [
    ["Star", "Magnitude", "Light years"],
    ["Vega", "0.03", "25"],
    ["Sirius", "-1.46", "8.6"],
    ["Rigel", "0.13", "860"],
    ["Betelgeuse", "0.50", "548"],
  ],
});
```

Live example

Edit a cell, then sort: the sort uses your edit. A sort is a real edit, so Undo reverts it.

Rules:

* **The table is the data.** Read the cells with `read`. Do not copy them into the state.
* **The view must fit the table's box.** It cannot change pagination. Put controls on or next to the table, not a second table over it.

## A picture that plays

The view can show what Word cannot. Here the file keeps a pixelated first frame of a GIF, and the editor plays the GIF on click. `fallback` can be `async`.

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

const GIF = "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif";

const surprise = {
  type: "acme.surprise",
  async fallback() {
    const frame = await createImageBitmap(await (await fetch(GIF)).blob());
    return drawPicture(
      200,
      170,
      (ctx) => {
        // Pixelate the first frame: draw it tiny, then scale it up without smoothing.
        const tiny = new OffscreenCanvas(8, 7);
        tiny.getContext("2d").drawImage(frame, 0, 0, 8, 7);
        ctx.imageSmoothingEnabled = false;
        ctx.drawImage(tiny, 0, 0, 200, 170);
        ctx.fillStyle = "rgba(0, 0, 0, 0.45)";
        ctx.fillRect(0, 0, 200, 170);
        ctx.fillStyle = "#fff";
        ctx.textAlign = "center";
        ctx.font = "bold 64px Arial";
        ctx.fillText("?", 100, 100);
        ctx.font = "bold 13px Arial";
        ctx.fillText("Click here for a surprise ▶", 100, 152);
      },
      { alt: "Click here for a surprise" },
    );
  },
  mount(el) {
    const gif = document.createElement("img");
    gif.alt = "Never gonna give you up";
    gif.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:none";
    el.append(gif);
    // The view takes no pointer, so the editor still selects and drags the picture.
    // A press and release in the box with no move between them is a click: it plays or stops the GIF.
    let down = null;
    const inside = (e) => {
      const r = el.getBoundingClientRect();
      return e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
    };
    const press = (e) => (down = inside(e) ? [e.clientX, e.clientY] : null);
    const release = (e) => {
      if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return;
      const play = gif.style.display === "none";
      if (play) gif.src = GIF;
      gif.style.display = play ? "block" : "none";
    };
    addEventListener("pointerdown", press, true);
    addEventListener("pointerup", release, true);
    return () => {
      removeEventListener("pointerdown", press, true);
      removeEventListener("pointerup", release, true);
    };
  },
};

const LOREM = [
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
  "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
  "Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida.",
  "Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue.",
];

const editor = mountDocxEditor(el, { worker, components: [surprise] });
insertComponent(editor.model, surprise, {}, {
  float: { wrap: "through", relativeFromH: "margin", alignH: "right", relativeFromV: "paragraph", topPt: 0 },
}).then(async () => {
  for (const [i, text] of LOREM.entries()) {
    if (i > 0) await editor.model.run({ kind: "splitParagraph" });
    await editor.model.run({ kind: "insertText", text });
  }
});
```

Live example

The view takes no pointer events. It listens on the window and treats a press and release with no move as a click. A click plays the GIF; a drag moves the picture like any float. The click changes no state, so it is not an edit. Word and the PDF show the pixelated frame.

## A QR code

A picture fallback can carry an SVG next to its PNG. Word shows the SVG, which stays sharp at any size and in print. A reader that cannot show an SVG uses the PNG. Here [uqr](https://github.com/unjs/uqr) makes the QR code, and the view is a bubble that shows when you point at the code.

On this page, other packages load from [esm.sh](https://esm.sh). In your app, run `npm install uqr`.

```ts theme={null}
import { encode, renderSVG } from "uqr";
import { drawPicture, insertComponent, mountDocxEditor } from "@reductoai/docx-editor";

const SIZE = 96;
const QR = { ecc: "M", border: 2 };

const qr = {
  type: "acme.qr",
  async fallback({ url }) {
    const { data, size } = encode(url, QR);
    const picture = await drawPicture(
      SIZE,
      SIZE,
      (ctx) => {
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, SIZE, SIZE);
        ctx.fillStyle = "#000";
        ctx.scale(SIZE / size, SIZE / size);
        data.forEach((row, y) => row.forEach((dark, x) => dark && ctx.fillRect(x, y, 1, 1)));
      },
      // Eight pixels for each module, so the edges of the modules stay sharp.
      { scale: (8 * size) / SIZE, alt: "QR code for " + url },
    );
    return { ...picture, svg: new TextEncoder().encode(renderSVG(url, QR)) };
  },
  mount(el, { state, commit, readOnly }) {
    if (readOnly) return;
    const bubble = document.createElement("label");
    bubble.textContent = "Link";
    bubble.style.cssText =
      "pointer-events:auto;position:absolute;left:0;top:100%;display:none;align-items:center;gap:0.7em;" +
      "padding:0.6em 0.8em;border-radius:0.7em;background:#1f2937;color:#fff;" +
      "font:600 10cqw system-ui,sans-serif;box-shadow:0 0.4em 1.4em rgb(0 0 0 / 0.35)";
    const input = document.createElement("input");
    input.value = state.url;
    input.maxLength = 300;
    input.spellcheck = false;
    input.style.cssText =
      "width:22em;padding:0.4em 0.6em;font:inherit;font-weight:400;color:#111;background:#fff;border:0;border-radius:0.4em";
    // Enter or a click outside the box applies the link.
    input.onchange = () => {
      const url = input.value.trim();
      if (url) void commit({ url });
    };
    bubble.append(input);
    el.append(bubble);
    // The view takes no pointer on the code, so the editor still selects and drags the picture.
    // The bubble shows only while the pointer is on the code or the bubble is in use.
    const point = (e) => {
      const r = el.getBoundingClientRect();
      const on = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
      bubble.style.display = on || bubble.matches(":hover, :focus-within") ? "flex" : "none";
    };
    addEventListener("pointermove", point, true);
    return () => removeEventListener("pointermove", point, true);
  },
};

const editor = mountDocxEditor(el, { worker, components: [qr] });
insertComponent(editor.model, qr, { url: "https://reducto.ai" }).then(async () => {
  await editor.model.run({ kind: "splitParagraph" });
  await editor.model.run({ kind: "insertText", text: "Scan the code with a phone camera to open the link." });
});
```

Live example

Point at the code, type a link in the bubble and press Enter: the code is drawn again as one undo step. The bubble is editor UI. It is not in the file, so Word and the PDF show only the code.

## A chart from a library

A view can use any drawing library. Here [Chart.js](https://www.chartjs.org) draws the chart twice: still, as the fallback, and live, as the view, with tooltips and a chart type toggle. In your app, run `npm install chart.js`.

```ts theme={null}
import { Chart } from "chart.js/auto";
import { drawPicture, insertComponent, mountDocxEditor } from "@reductoai/docx-editor";

const W = 420;
const H = 240;
const BLUE = "#2563eb";

function chartConfig(state, live) {
  return {
    type: state.kind,
    data: {
      labels: state.labels,
      datasets: [{ data: state.values, backgroundColor: BLUE, borderColor: BLUE, tension: 0.3 }],
    },
    options: {
      animation: live ? undefined : false,
      responsive: false,
      devicePixelRatio: 3,
      plugins: {
        legend: { display: false },
        title: { display: true, text: state.title, align: "start", font: { size: 14 } },
        tooltip: { callbacks: { label: (item) => " $" + item.formattedValue + "k" } },
      },
    },
  };
}

// Chart.js needs a canvas with a size: this one is W by H points, at three pixels per point.
function chartCanvas(state, live) {
  const canvas = document.createElement("canvas");
  canvas.width = W;
  canvas.height = H;
  return [canvas, new Chart(canvas, chartConfig(state, live))];
}

const revenue = {
  type: "acme.chart",
  async fallback(state) {
    const [canvas, still] = chartCanvas(state, false);
    const picture = await drawPicture(W, H, (ctx) => ctx.drawImage(canvas, 0, 0, W, H), {
      alt: state.title + ": " + state.labels.map((label, i) => label + " $" + state.values[i] + "k").join(", "),
    });
    still.destroy();
    return picture;
  },
  mount(el, { state, commit, readOnly }) {
    // The live chart keeps the fallback's size in points and scales with the page.
    const stage = document.createElement("div");
    stage.style.cssText =
      "pointer-events:auto;position:absolute;left:0;top:0;transform-origin:0 0;background:#fff";
    const [canvas, live] = chartCanvas(state, true);
    stage.append(canvas);
    const fit = () => (stage.style.transform = "scale(" + el.clientWidth / W + ")");
    const resize = new ResizeObserver(fit);
    resize.observe(el);
    fit();
    el.append(stage);
    if (!readOnly) {
      const bar = document.createElement("div");
      bar.style.cssText = "pointer-events:auto;position:absolute;right:2%;top:2%;display:flex;gap:1cqw";
      for (const kind of ["bar", "line"]) {
        const on = kind === state.kind;
        const button = document.createElement("button");
        button.textContent = kind === "bar" ? "Bars" : "Line";
        button.style.cssText =
          "cursor:pointer;border-radius:999px;padding:0.3em 0.9em;font:600 2.6cqw system-ui,sans-serif;" +
          "border:1px solid " + BLUE + ";" + (on ? "background:" + BLUE + ";color:#fff" : "background:#fff;color:" + BLUE);
        button.onclick = () => on || commit({ ...state, kind });
        bar.append(button);
      }
      el.append(bar);
    }
    return () => {
      resize.disconnect();
      live.destroy();
    };
  },
};

const editor = mountDocxEditor(el, { worker, components: [revenue] });
insertComponent(editor.model, revenue, {
  title: "Revenue by quarter, 2025 ($k)",
  kind: "bar",
  labels: ["Q1", "Q2", "Q3", "Q4"],
  values: [420, 515, 580, 710],
}).then(async () => {
  await editor.model.run({ kind: "splitParagraph" });
  await editor.model.run({ kind: "insertText", text: "Revenue grew in every quarter of 2025. Point at a bar to see its figure." });
});
```

Live example

Word and the PDF show the still chart. A type change draws the fallback again as one undo step. Draw the fallback with `animation: false`, so it shows the final chart, not the first frame.

## Free content

A content fallback is any Word content: paragraphs, lists, tables and pictures, with styles. `contentFallback(build)` gives `build` the body of a blank document to write with the usual API. Or pass `{ kind: "content", ooxml }` with a Flat OPC package or a body fragment.

The content fills whole paragraphs. `insertComponent` puts it after the caret's paragraph. In the file it is the result of an `ADDIN` field whose code keeps the type, id and state. Word never updates an `ADDIN` result, so F9 and printing do not change it.

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

const money = (n) => (n < 0 ? "-$" : "$") + Math.abs(n).toLocaleString("en-US");
const GREEN = "#15803d";
const AMBER = "#b45309";
const RED = "#b91c1c";
// Volume tiers on seats: from `min` seats, `off` comes off the seat price.
const TIERS = [
  { min: 25, off: 0.2, shade: "#86efac" },
  { min: 15, off: 0.1, shade: "#dcfce7" },
];
const APPROVAL = 8000;

function priced(state) {
  const seats = state.lines.find((line) => line.item === "Seats");
  const tier = TIERS.find((t) => seats.qty >= t.min);
  const next = TIERS.findLast((t) => seats.qty < t.min);
  const subtotal = state.lines.reduce((sum, line) => sum + line.qty * line.price, 0);
  const discount = tier ? -Math.round(seats.qty * seats.price * tier.off) : 0;
  return { seats, tier, next, subtotal, discount, total: subtotal + discount };
}

const quote = {
  type: "acme.quote",
  fallback: (state) =>
    contentFallback((body) => {
      const { seats, tier, next, discount, total } = priced(state);
      const title = body.insertParagraph("Quote for " + state.customer, "End");
      title.styleBuiltIn = "Heading2";
      body.insertParagraph("Valid for 30 days. Prices exclude tax.", "End");

      // The formatting is Word's own, so Word and the PDF show it too.
      const status = body.insertParagraph(
        next
          ? "Add " + (next.min - seats.qty) + " more seats for " + next.off * 100 + "% off every seat."
          : "Best price: the " + tier.off * 100 + "% volume discount applies.",
        "End",
      );
      status.font.set({ bold: true, color: next ? AMBER : GREEN });

      const rows = state.lines.map((line) => [line.item, String(line.qty), money(line.price), money(line.qty * line.price)]);
      if (tier) rows.push([tier.off * 100 + "% volume discount", "", "", money(discount)]);
      const table = body.insertTable(rows.length + 2, 4, "End", [
        ["Item", "Qty", "Unit price", "Amount"],
        ...rows,
        ["Total", "", "", money(total)],
      ]);
      const last = rows.length + 1;
      for (let r = 0; r <= last; r++) {
        for (const c of [1, 2, 3]) table.getCell(r, c).horizontalAlignment = "Right";
      }
      for (let c = 0; c < 4; c++) {
        table.getCell(0, c).shadingColor = "#1e40af";
        table.getCell(0, c).body.font.set({ bold: true, color: "#ffffff" });
        table.getCell(last, c).shadingColor = "#e2e8f0";
        table.getCell(last, c).body.font.bold = true;
      }
      if (tier) {
        table.getCell(1, 1).shadingColor = tier.shade;
        for (let c = 0; c < 4; c++) table.getCell(rows.length, c).body.font.color = GREEN;
      }
      if (total > APPROVAL) {
        table.getCell(last, 3).body.font.color = RED;
        body.insertParagraph("Over " + money(APPROVAL) + ": Finance must approve this quote.", "End").font.set({
          italic: true,
          color: RED,
        });
      }
    }),
  mount(el, { state, commit, readOnly }) {
    if (readOnly) return;
    const bar = document.createElement("div");
    bar.style.cssText = "pointer-events:auto;position:absolute;right:0;top:0;display:flex;gap:0.8cqw";
    const seats = (delta) => {
      const lines = state.lines.map((line) =>
        line.item === "Seats" ? { ...line, qty: Math.max(1, line.qty + delta) } : line,
      );
      void commit({ ...state, lines });
    };
    for (const [text, delta, filled] of [["− Remove a seat", -1, false], ["+ Add a seat", 1, true]]) {
      const button = document.createElement("button");
      button.textContent = text;
      button.style.cssText =
        "cursor:pointer;border-radius:999px;padding:0.45em 1em;font:600 1.6cqw system-ui,sans-serif;" +
        "border:1px solid #2563eb;box-shadow:0 1px 3px rgb(0 0 0 / 0.25);" +
        (filled ? "color:#fff;background:#2563eb" : "color:#2563eb;background:#fff");
      button.onclick = () => seats(delta);
      bar.append(button);
    }
    el.append(bar);
  },
};

const editor = mountDocxEditor(el, { worker, components: [quote] });
insertComponent(editor.model, quote, {
  customer: "Contoso",
  lines: [
    { item: "Seats", qty: 12, price: 300 },
    { item: "Onboarding", qty: 1, price: 2500 },
  ],
});
```

Live example

Click **+ Add a seat**: the content is written again from the new state, as one undo step. At 15 and 25 seats a green discount row appears, and a total over \$8,000 turns red with a note for Finance. This is plain Word formatting, so Word and the PDF match. The view covers the content on each page; content that spans pages gets one view per page.

Rules:

* **The state is the data.** The next `commit` writes the content again from the state and drops edits inside it. Text typed outside the field, in its first or last paragraph, stays.
* **Unlinking the field (Ctrl+Shift+F9)** keeps the content as plain text and removes the component.
* **Alt+F9 shows the field code and the state.** Do not put secrets in the state.

## Work with components

`mountDocxEditor` returns `components` for use from your own toolbar:

| Member | What it does |
| - | - |
| `components.list()` | Every component in the body, in document order: `key`, `id`, `type`, `carrier`, `state`, the table's `rows`, and the first body block and `blockCount` of content |
| `components.commit(key, state)` | Draws the fallback again and sets the state, as one undo step |
| `insertComponent(model, def, state, { float })` | Adds a component at the caret. `float` positions a picture component on the page |

A copied component keeps the same id. `list()` gives the copy its own `key` (`id-copy2`), which becomes its id on the first `commit`.

To remove a component, delete its content as a user would. `ctx.select()` puts the caret on it.

## Without the editor

`@reductoai/docx/components` works on a `WordDocument` in Node or the browser, for example to fill in components on a server or read them back after signing. This example uses the `stamp` component from [Define a component](#define-a-component):

```ts theme={null}
import { WordDocument } from "@reductoai/docx/node";
import { componentState, insertComponent, listComponents, updateComponent } from "@reductoai/docx/components";

const doc = await WordDocument.open("order.docx");
await insertComponent(doc, stamp, { status: "draft" });
await doc.save("order-draft.docx");

// Later, when the order is approved
const saved = await WordDocument.open("order-draft.docx");
for (const component of listComponents(saved)) {
  if (component.type !== stamp.type) continue;
  const { status } = componentState(stamp, component);
  if (status === "draft") await updateComponent(saved, stamp, component.key, { status: "approved" });
}
await saved.save("order-approved.docx");
```

`insertComponent` adds the component in a new paragraph at the end of the body, or at the end of the `paragraph` you give it. In Node, `fallback` runs with no DOM: `drawPicture` needs a canvas, so it works only in the browser.

`componentBoxes(layout, component)` returns a component's boxes on the laid-out pages, for your own overlays or a PDF signature field.

## Use cases

| Component | Fallback | Live view |
| - | - | - |
| E-signature, initials | Picture of the signature | Sign button, signature pad |
| Approval stamp | Picture: "Draft", "Approved" | A menu that changes the status |
| QR code or barcode | Picture (SVG with a PNG fallback) made from a URL or an id | An input for the value |
| Chart from data | Picture (SVG with a PNG fallback) | A chart library, a data editor |
| Sortable or filtered table | Word table | Sort and filter buttons |
| Price table, order lines | Word table with totals | Quantity inputs that recalculate the rows |
| Data from your system (CRM, ERP) | Word table or picture | A Refresh button that loads new data |
| Quote, clause or summary | Content: headings, text, lists and tables | Inputs that write the content again |

## Limits

* **A .docx is not proof.** Anyone with the file can change it, state included. For a legal signature, keep the audit data on your server and treat the signed PDF or a file hash as the record.
* **Validate state you read back.** Treat `state` as user input: Word users can edit alt text and tables.
* **A float placed on the page does not move with the text** and can end up over it. Put a component inline when it belongs to a paragraph.
* **Picture tools change the fallback, not the state.** To keep a fixed size, draw the fallback again on the next `commit`.
* **Only body components are read.** In headers, footers and notes they stay as their fallback.
