# Recipes

> Four complete workflows with Birch UI Document Editor - a contract review with locked tracking, mail merge on a server, a template with content controls, and an editor embedded with collaboration.

Each recipe below is a complete workflow rather than a single call. The same code runs as a test in `packages/document/test/docs-recipes.test.ts` (the server recipe also in `test/headless.test.ts`, in a Node environment without a DOM), so it is type-checked and executed with every change to the package.

## Contract review with locked tracking

You send a contract to a counterparty, they may only suggest changes, and you resolve their suggestions and file a redline against what you sent.

```ts
import { compareDocuments, createDocumentEditor, documentToDocx } from '@birchui/document';

// 1. The counterparty opens the file. Tracking is locked with a password they do not have.
const counterparty = createDocumentEditor(host, { author: 'Daniel Brandt' });
await counterparty.importDocx(sentBytes);
await counterparty.protectDocument('trackedChanges', 'Harbour-2026');
// Everything they type is now a tracked change; setTrackChanges(false) and acceptChanges() do nothing.
const returned = await counterparty.exportDocx();

// 2. You open what came back. The lock travelled inside the DOCX file.
const review = createDocumentEditor(host, { author: 'Priya Raman' });
await review.importDocx(returned);
review.getRevisions({ author: 'Daniel Brandt' }); // what they changed
await review.unprotectDocument('Harbour-2026'); // false with the wrong password

// 3. Resolve: one change by id, the rest by author, or by date and kind.
const [delivery] = review.getRevisions({ kinds: ['replace'] });
review.acceptChanges({ ids: [delivery.id] });
review.rejectChanges({ author: 'Daniel Brandt' });

// 4. File a redline of the agreed text against the text you sent.
const redline = compareDocuments(original.content, review.getJSON().content, { author: 'Priya Raman' });
const filed = await documentToDocx({ ...original, content: redline }, { trackRevisions: true });
```

In the editor the same steps are **Review → Restrict editing → Lock tracking with a password…**, the balloons and the Reviewing pane, and **Review → Compare**. See [Track changes](https://docs.birchui.com/document/track-changes.md) and [Compare and versions](https://docs.birchui.com/document/compare-and-versions.md).

## Mail merge on a server

One DOCX template, a list of records, one output per record. Nothing here needs a browser: `@birchui/document/headless` does not contain the editor.

```ts title="renewals.mjs"
import {
  documentToDocx,
  documentToHtml,
  documentToPdf,
  docxToDocument,
  mergeDocument,
} from '@birchui/document/headless';
import { readFile, writeFile } from 'node:fs/promises';

const template = await docxToDocument(await readFile('renewal-letter.docx'));

for (const customer of customers) {
  const merged = mergeDocument(template, customer, { locale: 'en-GB', currency: 'EUR' });
  await writeFile(`out/${customer.id}.docx`, await documentToDocx(merged));
  await writeFile(`out/${customer.id}.pdf`, await documentToPdf(merged));
  await writeFile(`out/${customer.id}.html`, documentToHtml(merged, { fullDocument: true }));
}
```

`documentToPdf` lays the document out without a browser, with its own line breaking from font metrics. It is meant for letters, contracts and reports made of paragraphs, lists, tables and pictures, and it does not reproduce the editor's layout line for line; its limits are listed under [PDF on a server](https://docs.birchui.com/document/pdf-and-print.md#pdf-on-a-server). When the PDF must match what people saw in the editor, export it in the browser with `editor.exportPdf()`.

The template uses `MERGEFIELD` fields or `{{tokens}}`, with `{{#if …}}` and `{{#each …}}` for conditions and repeating table rows; see [Mail merge](https://docs.birchui.com/document/mail-merge.md).

`node packages/document/scripts/headless-throughput.mjs` generates 1,000 seven-clause contracts with a fee table from one template on one thread. On the laptop this was written on it reported:

| Step | Time per contract |
| --- | --- |
| DOCX to model | 0.67 ms |
| Merge | 0.34 ms |
| Model to DOCX | 0.83 ms |
| Model to HTML | 0.13 ms |
| Model to PDF | 1.45 ms |
| All five | 3.43 ms, 292 contracts per second |

These are single runs on a machine that was doing other work; treat them as an order of magnitude. Reading the template once instead of per contract saves the first step.

## Template with content controls

A form that people fill in: controls with tags, validation before saving, and protection so that only the controls can be edited.

```ts
const editor = createDocumentEditor(host, { content: orderFormTemplate });

editor.exec('insertContentControl', { kind: 'plainText', tag: 'customer', title: 'Customer', required: true });
editor.exec('insertContentControl', {
  kind: 'dropdown',
  tag: 'delivery',
  title: 'Delivery',
  items: [
    { text: 'Standard (3 days)', value: 'standard' },
    { text: 'Next day', value: 'express' },
  ],
});

editor.validateForm(); // [{ tag: 'customer', title: 'Customer', message: 'Customer is required.' }]
editor.setFormData({ customer: 'Harper & Lowe LLP', delivery: 'express' }); // 2 controls changed
editor.getFormData(); // { customer: 'Harper & Lowe LLP', delivery: 'express' }

await editor.protectDocument('forms'); // only the controls accept input; add a password to keep it that way
const file = await editor.exportDocx(); // controls, tags, list items and the protection are in the DOCX file
```

See [Content controls and forms](https://docs.birchui.com/document/forms.md).

## Embed with collaboration

Two or more people in one document. The authority orders the edits; this example keeps it in the page, which is how a demo or a test runs. In production the authority is the relay in `packages/document/examples/collab-relay`, reached with `createSocketBackend`.

```ts
import {
  createAuthorityBackend,
  createCollabAuthority,
  createCollabProvider,
  createDocumentEditor,
} from '@birchui/document';

const authority = createCollabAuthority({ document: content });
const join = (host: HTMLElement, author: string) =>
  createDocumentEditor(host, { author, content, collab: createCollabProvider(createAuthorityBackend(authority)) });

const priya = join(leftHost, 'Priya Raman');
const daniel = join(rightHost, 'Daniel Brandt');

priya.on('presenceChange', ({ collaborators }) => showPeople(collaborators));
priya.on('collabConnection', ({ status }) => showConnection(status)); // 'connected' | 'reconnecting' | 'offline'

const version = await priya.saveCollabVersion('Sent to counterparty');
// … both keep editing and commenting …
const redline = version && (await priya.diffCollabVersions(version.id, null)); // tracked changes since that version
await priya.listCollabVersions();
```

Every editor starts from the same `content`, or receives the authority's snapshot. See [Collaboration](https://docs.birchui.com/document/collaboration.md) for the relay, offline edits, range locks and writing your own backend.
