# Review a returned Word agreement

The counterparty proposed extending the approval window from 15 to 30 days. Review that pending change and download the agreement.

## Run

Requires Node.js 22 or newer. `npm install` then `npm run dev`. Open the localhost URL Vite prints. To check and build the project, run `npm run check` and `npm run build`.

Browser editor: 2.36.0. Direct dependencies are pinned in package.json.

## Try it

Accepting keeps 30 days. Rejecting restores 15. The original comment stays anchored in either editable Word file.

The included DOCX is a public synthetic example. It is not your uploaded document or the current edited demo state. Export a separate DOCX and inspect the result in Microsoft Word.

## Files

- package.json
- examples/proof-legal-word-handoff/main.ts
- examples/proof-legal-word-handoff/index.html
- examples/shared/browser.ts
- examples/shared/style.css
- examples/shared/word-proof.ts
- examples/shared/word-proof.css
- vite.config.ts
- tsconfig.json
- public/testkit_docs/proof-legal-word-handoff.docx

- public/responsive/brand-2x.webp
- public/responsive/brand-3x.webp
- public/fonts/inter-7.woff2
- public/fonts/OFL-Inter.txt

## Continue

[Current documentation](https://docs.superdoc.dev/editor/custom-ui/tracked-changes/)
[Open the public example](https://www.superdoc.dev/examples/proof-legal-word-handoff/index.html)
[SuperDoc licensing](https://docs.superdoc.dev/editor/license/)

The shared browser.ts file contains the export button, status messages and CSS imports. Document setup and task logic are in main.ts.

## Complete source

### package.json

```json
{
  "name": "superdoc-proof-legal-word-handoff",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22"
  },
  "scripts": {
    "dev": "vite --open /examples/proof-legal-word-handoff/",
    "build": "vite build",
    "check": "tsc --noEmit"
  },
  "dependencies": {
    "superdoc": "2.36.0",
    "fflate": "0.8.3"
  },
  "devDependencies": {
    "vite": "6.4.1",
    "typescript": "5.8.3"
  }
}
```

### examples/proof-legal-word-handoff/main.ts

```javascript
import { mountWordProof } from '../shared/word-proof';

mountWordProof('review', '/testkit_docs/proof-legal-word-handoff.docx', {
  filename: 'reviewed-approval-window.docx',
  pairedReplacement: true,
  comment: 'Has the reviewer received the final deliverable?',
});
```

### examples/proof-legal-word-handoff/index.html

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Review a returned Word agreement | SuperDoc example</title>
<meta name="description" content="Review the counterparty’s proposed 21-day approval window and download the agreement with the original comment.">
<link rel="canonical" href="https://www.superdoc.dev/examples/proof-legal-word-handoff/index.html">
<link rel="alternate" type="text/markdown" href="https://www.superdoc.dev/examples/proof-legal-word-handoff.md">
</head>
<body data-proof="review" data-handoff-review>
<header class="review-heading">
  <div class="proof-heading-copy">
    <a class="proof-brand" href="https://www.superdoc.dev/">
      <img src="/responsive/brand-2x.webp" srcset="/responsive/brand-2x.webp 2x, /responsive/brand-3x.webp 3x" width="18" height="20" alt="">SuperDoc
    </a>
    <h1>Review a returned Word agreement</h1>
    <p>A counterparty changed the approval window from 15 to 30 days. Accept or reject that change, then open the download in Word to check the deadline and original comment.</p>
  </div>
  <a class="proof-build" href="https://docs.superdoc.dev/editor/custom-ui/tracked-changes/"><svg class="build-this-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m8 6-6 6 6 6m8-12 6 6-6 6m-2-14-4 16"/></svg>Build this</a>
</header>
<main class="solo review-workspace" aria-label="Review the sample proposal">
  <div class="review-chrome">
    <div id="proof-actions" class="actions review-actions" role="group" aria-label="Review actions">
      <div class="review-action-group" role="group" aria-label="Selected change">
        <button type="button" data-proof-action="accept" disabled>Accept</button>
        <button type="button" data-proof-action="reject" disabled>Reject</button>
      </div>
      <div class="review-action-group review-handoff">
        <span id="review-count">Loading…</span>
        <button id="export" class="example-file-action" type="button" disabled><svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v12m-4-4 4 4 4-4M4 16v4h16v-4"/></svg>Download Word file</button>
        <button id="proof-reset" type="button">Reset example</button>
      </div>
    <div class="proof-history" role="group" aria-label="Document history">
      <button type="button" data-proof-history="undo" aria-label="Undo" title="Undo" disabled><svg aria-hidden="true" viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 14-5-5 5-5M4 9h10a5 5 0 0 1 0 10h-2"/></svg></button>
      <button type="button" data-proof-history="redo" aria-label="Redo" title="Redo" disabled><svg aria-hidden="true" viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 14 5-5-5-5m5 5H10a5 5 0 0 0 0 10h2"/></svg></button>
    </div>
    </div>
    <p id="review-selection" aria-live="polite"></p>
    <output id="status" role="status">Opening sample…</output>
  </div>
  <div id="editor" aria-label="Word document"></div>
</main>
<footer class="review-resources">
  <details>
    <summary>Sample and source</summary>
    <div class="proof-resource-links">
      <a href="https://www.superdoc.dev/examples/proof-legal-word-handoff.md">Read the browser example</a>
      <a href="https://www.superdoc.dev/examples/proof-legal-word-handoff.zip">Download the browser project</a>
      <a href="/testkit_docs/proof-legal-word-handoff.docx" download>Download the original sample</a>
    </div>
  </details>
  <a href="https://meetings.hubspot.com/caio-pizzol">Talk through your integration</a>
</footer>
<script type="module" src="./main.ts"></script>
</body>
</html>
```

### examples/shared/browser.ts

```javascript
import type { SuperDoc } from 'superdoc';
import 'superdoc/style.css';
import './style.css';

export function element<T extends HTMLElement>(id: string): T {
  const node = document.getElementById(id);
  if (!node) throw new Error(`Missing element: ${id}`);
  return node as T;
}

const status = element<HTMLOutputElement>('status');
const exportButton = element<HTMLButtonElement>('export');
export function report(message: string) { status.value = message; }
export function showError(error: unknown) {
  report(error instanceof Error ? error.message : String(error));
}

export function enableExport(superdoc: SuperDoc) {
  report('Ready. Edit the document, then export a copy.');
  exportButton.disabled = false;
  exportButton.addEventListener('click', async () => {
    exportButton.disabled = true;
    try {
      await superdoc.export({ exportType: ['docx'], exportedName: 'edited-example', triggerDownload: true });
      report('DOCX exported. Open the saved file to check your changes.');
    } catch (error) { showError(error); }
    finally { exportButton.disabled = false; }
  });
}
```

### examples/shared/style.css

```css
:root { font-family: system-ui, sans-serif; color: #242424; background: #f5f5f5; }
#editor { --sd-caret-color: #242424; }
input, textarea, [contenteditable="true"] { caret-color: #242424; }
* { box-sizing: border-box; }
body { margin: 0; }
header { padding: 1rem; border-bottom: 1px solid #ddd; background: white; }
h1 { font-size: 1.2rem; margin: 0 0 .5rem; }
p { line-height: 1.5; }
button, input { font: inherit; padding: .5rem .7rem; min-height: 44px; }
button { cursor: pointer; }
button:disabled { cursor: wait; }
label { display: grid; gap: .3rem; margin-bottom: .7rem; }
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: .7rem; }
main { display: grid; grid-template-columns: minmax(0, 1fr) 300px; }
main.solo { display: block; }
#editor { height: 76vh; overflow: auto; min-width: 0; }
aside { padding: 1rem; background: white; overflow: auto; max-height: 76vh; }
ul { list-style: none; padding: 0; }
li { border-bottom: 1px solid #ddd; padding: .7rem 0; }
li button { margin: .2rem; }
input { width: 100%; }
@media (max-width: 760px) { main { grid-template-columns: minmax(0, 1fr); } aside { max-height: none; } }

/* Keep file actions consistent with the homepage editor. */
.example-file-action {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: .375rem;
  min-height: 44px;
  padding: .45rem .7rem;
  border: 1px solid var(--example-file-border, #b9c9e0);
  border-radius: .5rem;
  background: var(--example-file-surface, #fff);
  color: var(--example-file-color, #1747b7);
  font-size: .875rem;
  font-weight: 600;
}
.example-file-action:hover:enabled { background: var(--example-file-hover, #edf3ff); }
.example-file-action svg { width: 1.05rem; height: 1.05rem; flex: none; }
.example-file-primary { background: #1355ff; border-color: #1355ff; color: #fff; }
.example-file-primary:hover:enabled { background: #0f44cc; border-color: #0f44cc; }

[data-template-example] footer { padding: 1rem; background: white; }
[data-template-example] #apply { color: white; background: #1355ff; border: 1px solid #1355ff; border-radius: .5rem; margin-top: .5rem; }
[data-template-example] #apply:disabled { opacity: .5; }
@media(max-width:760px) {
  [data-template-example] main > aside { grid-row: 1; }
  [data-template-example] #editor { height: 55dvh; }
}

[data-template-example] .template-more { margin-top: .55rem; }
[data-template-example] .template-more summary { min-height: 44px; align-content: center; cursor: pointer; }
.template-build { display: inline-flex; align-items: center; gap: .4rem; }
```

### examples/shared/word-proof.ts

```javascript
import { SuperDoc } from 'superdoc';
import { unzipSync } from 'fflate';
import { element, report, showError } from './browser';
import './word-proof.css';

type Proof = 'review' | 'report' | 'formatting' | 'precise';
const reportFinding = '50500151';
const reportChangeAction = 'report-change';
const formattingFinding = 'Evidence 0003 supports the quarterly controls review.';
const formattingHeading = '50504501';
const renewalComment = 'Confirm this term with the account team.';
export function mountWordProof(mode: Proof, fixture: string, sampleReview?: { filename: string; comment?: string; pairedReplacement?: boolean }) {
  const ns = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
  const revisionNames = new Set([
    'ins', 'del', 'moveFrom', 'moveTo', 'rPrChange', 'pPrChange', 'sectPrChange',
    'tblPrChange', 'tblGridChange', 'trPrChange', 'tcPrChange', 'cellIns', 'cellDel',
    'cellMerge', 'numberingChange',
  ]);
  const actionBar = element('proof-actions');
  const download = element<HTMLButtonElement>('export');
  const historyButtons = Array.from(actionBar.querySelectorAll<HTMLButtonElement>('[data-proof-history]'));
  const surface = element('editor');
  const compact = window.matchMedia('(max-width: 1099px), (pointer: coarse)');
  const precise = mode === 'precise' ? {
    proposal: actionBar.querySelector<HTMLButtonElement>('[data-proof-action="propose"]')!,
    decisions: element('precise-decisions'),
  } : undefined;
  const review = mode === 'review' ? {
    count: element('review-count'),
    selection: element('review-selection'),
    buttons: Array.from(actionBar.querySelectorAll<HTMLButtonElement>('[data-proof-action]')),
  } : undefined;
  const proposal = 'Approval is due within 10 days.';
  type Caret = Parameters<SuperDoc['ui']['selection']['apply']>[0];
  let editor: SuperDoc;
  let prepared: Blob | undefined;
  type Change = Awaited<ReturnType<typeof getReview>>[number];
  const decisions = new Map<string, 'accept' | 'reject'>();
  let changes: Change[] = [];
  let selected = -1;
  let findingCaret: Caret | undefined;
  let reviewReady = false;
  let working = false;
  let reviewDecided = false;
  let preciseChanges: Change[] = [];
  let numberProposed = false;
  let reportChangeProposed = false;
  let numberProposalDepth = Infinity;
  let reportProposalDepth = Infinity;
  let numberProposalIds = new Set<string>();
  const reviewHistory = new Map<number, typeof decisions>([[0, new Map()]]);
  const observe = (action: string) => window.dispatchEvent(new CustomEvent('superdoc:word-proof', { detail: action }));

  try {
    document.documentElement.classList.toggle('dark', localStorage.getItem('superdoc-theme') === 'dark');
  } catch { /* Storage can be blocked in an embedded example. */ }

  function elementText(part: Document | Element, tag: string): string[] {
    return Array.from(part.getElementsByTagNameNS(ns, tag), node => node.textContent ?? '');
  }

  function releaseDownload(blob: Blob, label: string) {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = label;
    link.click();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }

  function proofParts(blob: Blob): Promise<Document[]> {
    return blob.arrayBuffer().then(bytes => {
      const parts = unzipSync(new Uint8Array(bytes), {
        filter: part => /^word\/(document|header\d+|footer\d+|footnotes|endnotes|comments)\.xml$/.test(part.name),
      });
      if (!parts['word/document.xml']) throw new Error('The saved package is missing its document.');
      const decoder = new TextDecoder();
      return Object.values(parts).map(bytes => {
        const parsed = new DOMParser().parseFromString(decoder.decode(bytes), 'application/xml');
        if (parsed.querySelector('parsererror')) throw new Error('The saved Word file contains an unreadable part.');
        return parsed;
      });
    });
  }

  async function exportCopy() {
    return await editor.export({ exportType: ['docx'], triggerDownload: false, commentsType: 'external' });
  }

  function requireDocument(superdoc = editor) {
    const doc = superdoc.activeEditor?.doc;
    if (!doc) throw new Error('The document is still opening. Please try again.');
    return doc;
  }

  function revealParagraph(paraId: string) {
    const metrics = editor.activeEditor?.pageMetrics;
    if (!metrics) throw new Error('The page is still preparing. Please try again.');
    return metrics.revealBodyTarget({ paraId });
  }

  async function getReview(superdoc = editor) {
    const list = await requireDocument(superdoc).trackChanges.list({ in: 'all', limit: 300 });
    return list.items;
  }

  function changeTarget(change: Change) {
    return { id: change.id, story: change.address?.story };
  }

  async function revealChange(index: number) {
    const change = changes[index];
    if (!change) {
      selected = -1;
      editor.ui.trackChanges.setActive(null);
      return;
    }
    const target = changeTarget(change);
    const result = await editor.ui.trackChanges.scrollTo(target);
    editor.ui.trackChanges.setActive(target);
    selected = index;
    if (!result.success) report('This change is selected. Its location could not be shown in the preview.');
  }

  async function initializeReview() {
    changes = await getReview();
    const proposalIndex = sampleReview && changes.length ? 0 : changes.findIndex(item => item.insertedText?.trim() === proposal);
    if (proposalIndex < 0) throw new Error('The sample proposal could not be found.');
    report(sampleReview
      ? 'Review the highlighted change, or download the document with the proposal still pending.'
      : 'Accept or reject the highlighted change, then download the Word file.');
    await revealChange(proposalIndex);
    reviewReady = true;
    if (sampleReview) observe('ready');
  }

  async function decide(decision: 'accept' | 'reject', all: boolean) {
    const change = changes[selected];
    if (!all && !change) return;
    const before = all ? changes : [change];
    // Keep the agreement read-only between decisions. The Document API requires
    // a writable mode while it applies the explicit review action.
    surface.inert = true;
    editor.setDocumentMode('suggesting');
    try {
      const result = await requireDocument().trackChanges.decide({
        decision,
        target: all || sampleReview?.pairedReplacement ? { kind: 'all', story: 'all' } : { kind: 'id', ...changeTarget(change) },
        commentRetention: 'point',
      });
      if (!result.success) throw new Error('The decision could not be applied. Please try again.');
    } finally {
      editor.setDocumentMode('viewing');
      surface.inert = false;
    }
    if (sampleReview) {
      changes = await getReview();
      reviewDecided = true;
    } else {
      for (const item of before) {
        if (item.insertedText?.trim()) decisions.set(item.insertedText.trim(), decision);
      }
      changes = all ? [] : changes.filter((_, index) => index !== selected);
      reviewHistory.set((await requireDocument().history.get()).undoDepth, new Map(decisions));
    }
    prepared = undefined;
    const next = Math.min(selected, changes.length - 1);
    const outcome = decision === 'accept' ? 'Accepted' : 'Rejected';
    report(all ? `${outcome} all remaining changes.` : `${outcome} the selected change.`);
    await revealChange(next);
  }

  function revisionSignatures(items: Change[]) {
    return JSON.stringify(items.map(({ type, author, insertedText, deletedText, address }) =>
      JSON.stringify([type, author, insertedText, deletedText, address?.story?.kind]),
    ).sort());
  }

  async function verifyReview() {
    report('Checking the saved Word file…');
    const candidate = await exportCopy();
    const parts = await proofParts(candidate);
    if (!sampleReview) {
      const contents = parts.map(part => elementText(part, 't').join(''));
      for (const [text, decision] of decisions) {
        if (contents.some(part => part.includes(text)) !== (decision === 'accept')) {
          throw new Error('The saved copy did not preserve a review decision. Retry the download.');
        }
      }
      const originalComment = parts.some(part => elementText(part, 'comment').includes('Retain this comment for the reviewer.'));
      const anchored = parts.some(part => ['commentRangeStart', 'commentRangeEnd', 'commentReference']
        .every(tag => part.getElementsByTagNameNS(ns, tag).length));
      if (!originalComment || !anchored) throw new Error('The saved copy lost the original comment. Retry the download.');
    }
    if (!changes.length && parts.some(part => Array.from(part.getElementsByTagNameNS(ns, '*'))
      .some(node => revisionNames.has(node.localName)))) {
      throw new Error('The saved copy still contains revisions. Retry the download.');
    }
    if (revisionSignatures(await reopen(candidate)) !== revisionSignatures(changes)) {
      throw new Error('The reopened copy did not preserve the pending changes. Retry the download.');
    }
    prepared = candidate;
    if (!sampleReview || reviewDecided) observe('task_succeeded');
    return candidate;
  }

  function keepTargetVisible(paraId: string) {
    const paragraph = surface.querySelector(`[data-para-id="${paraId}"]`);
    if (!paragraph) return;
    const target = paragraph.getBoundingClientRect();
    const view = surface.getBoundingClientRect();
    if (target.top < view.top || target.bottom > view.bottom) {
      surface.scrollTop += target.top - view.top - 20;
    }
  }

  async function initializeFormatting() {
    await revealParagraph(formattingHeading);
    const { items } = await requireDocument().find({
      select: { type: 'text', pattern: formattingFinding, caseSensitive: true },
    });
    const match = items[0];
    if (items.length === 1 && match && 'nodeId' in match.address) {
      const point = { kind: 'text' as const, blockId: match.address.nodeId, offset: formattingFinding.length };
      findingCaret = { kind: 'selection', start: point, end: point };
    }
    // The painted coordinates describe the fitted page on touch screens.
    keepTargetVisible(formattingHeading);
    report('Edit finding 0003. Try adding “Confirmed.”, then download the DOCX.');
  }

  async function editFinding() {
    if (findingCaret && editor.ui.selection.apply(findingCaret).ok) editor.focus();
    else {
      await revealParagraph(formattingHeading);
      keepTargetVisible(formattingHeading);
    }
    report('Update the wording in finding 0003.');
  }

  async function proposeNumber() {
    if (numberProposed) return;
    const doc = requireDocument();
    const row = await doc.query.match({ select: { type: 'text', pattern: 'Renewal notice', caseSensitive: true }, require: 'exactlyOne' });
    const table = await doc.query.match({ select: { type: 'node', nodeType: 'table' }, require: 'exactlyOne' });
    const tableAddress = table.items[0]?.address;
    const labelAddress = row.items[0]?.address;
    if (!tableAddress || !('nodeId' in tableAddress) || !labelAddress || !('nodeId' in labelAddress)) {
      throw new Error('The renewal notice table could not be found.');
    }
    const { cells } = await doc.tables.getCells({ nodeId: tableAddress.nodeId });
    const label = cells.find(cell => cell.firstParagraphNodeId === labelAddress.nodeId);
    const term = label && cells.find(cell => cell.rowIndex === label.rowIndex && cell.columnIndex === label.columnIndex + 1);
    if (!term) throw new Error('The renewal notice cell could not be found.');
    const match = await doc.query.match({ select: { type: 'text', pattern: '30 days', caseSensitive: true }, within: term.address, require: 'exactlyOne' });
    const hit = match.items[0];
    const target = hit && 'target' in hit ? hit.target : undefined;
    if (!target) throw new Error('The expected 30-day renewal notice could not be found.');
    const before = new Set((await getReview()).map(change => change.id));
    const result = await doc.replace({
      target,
      text: '60 days', expectedText: '30 days', replacementGranularity: 'word',
    }, { changeMode: 'tracked' });
    if (!result.success) throw new Error('The proposal could not be applied.');
    numberProposed = true;
    const proposed = (await getReview()).filter(change => !before.has(change.id));
    numberProposalDepth = (await doc.history.get()).undoDepth;
    numberProposalIds = new Set(proposed.map(change => change.id));
    const parts = await proofParts(await exportCopy());
    const body = parts.find(part => part.documentElement.localName === 'document');
    const exportedRow = body && Array.from(body.getElementsByTagNameNS(ns, 'tr')).find(
      row => row.getElementsByTagNameNS(ns, 'tc')[0]?.textContent === 'Renewal notice',
    );
    const exportedTerm = exportedRow?.getElementsByTagNameNS(ns, 'tc')[1];
    if (!exportedTerm) throw new Error('The saved copy is missing the renewal notice term.');
    const inserted = elementText(exportedTerm, 'ins').join('');
    const removed = elementText(exportedTerm, 'del').join('');
    if (!['6', '60'].includes(inserted.trim()) || !['3', '30'].includes(removed.trim())) {
      throw new Error('The saved redline changes more than the expected number.');
    }
    const invoice = body && Array.from(body.getElementsByTagNameNS(ns, 'tr')).find(
      row => row.getElementsByTagNameNS(ns, 'tc')[0]?.textContent === 'Invoice payment',
    );
    if (invoice?.getElementsByTagNameNS(ns, 'tc')[1]?.textContent !== '30 days') {
      throw new Error('The saved file changed the separate invoice payment term.');
    }
    const originalComment = parts.some(part => elementText(part, 'comment').includes(renewalComment));
    if (!originalComment || !parts.some(part => part.getElementsByTagNameNS(ns, 'commentReference').length)) {
      throw new Error('The saved copy lost the original comment.');
    }
    if (!proposed.length) throw new Error('The proposal is present in the saved copy. Use the editor to review it.');
    preciseChanges = proposed;
    observe('task_succeeded');
    const reviewTarget = changeTarget(proposed[0]);
    const revealed = await editor.ui.trackChanges.scrollTo(reviewTarget);
    editor.ui.trackChanges.setActive(reviewTarget);
    report(revealed.success
      ? 'The renewal notice has one pending edit. Invoice payment stays at 30 days and the original comment stays attached.'
      : 'Find Renewal notice in the table to review the pending edit. Invoice payment stays at 30 days and the original comment stays attached.');
  }

  async function decideNumber(decision: 'accept' | 'reject') {
    const pendingIds = new Set((await getReview()).map(change => change.id));
    preciseChanges = preciseChanges.filter(change => pendingIds.has(change.id));
    const [first] = preciseChanges;
    if (!first) {
      report('The sample proposal has already been resolved. Download the Word file or reset the example.');
      return;
    }
    const result = await requireDocument().trackChanges.decide({
      decision,
      target: preciseChanges.length === 1
        ? { kind: 'id', ...changeTarget(first) }
        : { kind: 'ids', ids: preciseChanges.map(change => change.id) },
      commentRetention: 'point',
    });
    if (!result.success) throw new Error('The decision could not be applied. Please try again.');
    preciseChanges = [];
    editor.ui.trackChanges.setActive(null);
    report(decision === 'accept' ? 'Accepted. The term is 60 days.' : 'Rejected. The original 30-day term remains.');
  }

  async function refreshHistoryControls() {
    const history = await editor.activeEditor?.doc?.history.get();
    if (!history || working) return;
    for (const button of historyButtons) {
      button.disabled = !(button.dataset.proofHistory === 'undo' ? history.canUndo : history.canRedo);
    }
  }

  function setControls(enabled: boolean) {
    if (historyButtons.length) {
      if (enabled) void refreshHistoryControls();
      else for (const button of historyButtons) button.disabled = true;
    }
    if (mode === 'report') element('report-handoff').hidden = !reportChangeProposed;
    if (precise) {
      precise.proposal.hidden = numberProposed;
      precise.decisions.hidden = preciseChanges.length === 0;
    }
    if (!review) {
      actionBar.querySelectorAll<HTMLButtonElement>('button[data-proof-action]').forEach(button => {
        button.disabled = !enabled || (button.dataset.proofAction === reportChangeAction && reportChangeProposed);
      });
      download.disabled = !enabled;
      return;
    }
    const active = changes[selected];
    const pending = sampleReview?.pairedReplacement ? Number(changes.length > 0) : changes.length;
    review.count.textContent = reviewReady ? `${pending} pending` : 'Loading…';
    review.selection.textContent = active && sampleReview?.pairedReplacement
      ? 'Approval deadline · 15 days to 30 days'
      : active
      ? `Change ${selected + 1} of ${changes.length} · ${active.insertedText?.trim() || active.deletedText?.trim() || active.type}`
      : reviewReady ? 'No pending changes' : '';
    for (const button of review.buttons) {
      const action = button.dataset.proofAction;
      const available = action === 'previous' ? selected > 0
        : action === 'next' ? selected >= 0 && selected < changes.length - 1
        : action?.endsWith('-all') ? changes.length > 0 : Boolean(active);
      button.disabled = !enabled || !reviewReady || !available;
    }
    download.disabled = !enabled || (sampleReview ? !reviewReady : decisions.size === 0);
  }

  async function applyHistory(action: 'undo' | 'redo') {
    const doc = requireDocument();
    if (review) editor.setDocumentMode('suggesting');
    try {
      const result = await doc.history[action]();
      if (result.noop) return;
    } finally {
      if (review) editor.setDocumentMode('viewing');
    }
    const depth = (await doc.history.get()).undoDepth;
    if (review) {
      changes = await getReview();
      prepared = undefined;
      reviewDecided = depth > 0;
      decisions.clear();
      for (const [text, decision] of reviewHistory.get(depth) ?? []) decisions.set(text, decision);
      await revealChange(Math.max(0, Math.min(selected, changes.length - 1)));
    }
    if (precise) {
      numberProposed = depth >= numberProposalDepth;
      preciseChanges = (await getReview()).filter(change => numberProposalIds.has(change.id));
    }
    if (mode === 'report') reportChangeProposed = depth >= reportProposalDepth;
    report(action === 'undo' ? 'Last document action undone.' : 'Last document action redone.');
  }

  async function proposeReportChange() {
    if (reportChangeProposed) return;
    report('Finding audit row AUD-1789…');
    const revealed = await revealParagraph(reportFinding);
    if (revealed.status !== 'revealed') throw new Error('The findings page is still preparing. Try again.');
    const doc = requireDocument();
    const match = await doc.query.match({
      select: { type: 'text', pattern: 'Pending', caseSensitive: true },
      within: { kind: 'block', nodeType: 'paragraph', nodeId: reportFinding },
      require: 'exactlyOne',
    });
    const hit = match.items[0];
    const target = hit && 'target' in hit ? hit.target : undefined;
    if (!target) throw new Error('The expected Pending status could not be found.');
    const before = new Set((await getReview()).map(change => change.id));
    const start = performance.now();
    const result = await doc.replace({ target, expectedText: 'Pending', text: 'Confirmed' }, { changeMode: 'tracked' });
    const elapsed = performance.now() - start;
    if (!result.success) throw new Error('The tracked status edit could not be applied. Try again.');
    reportChangeProposed = true;
    reportProposalDepth = (await doc.history.get()).undoDepth;
    const change = (await getReview()).find(item => !before.has(item.id));
    if (!change) throw new Error('The status changed, but the pending review marker could not be located. Reset the example to try again.');
    const address = changeTarget(change);
    await editor.ui.trackChanges.scrollTo(address);
    editor.ui.trackChanges.setActive(address);
    const timing = elapsed >= 1 && elapsed < 1000 ? ` Edit applied in ${Math.round(elapsed)} ms.` : '';
    report(`AUD-1789 now has a pending change from Pending to Confirmed.${timing} Download the Word file to review it.`);
    observe('task_succeeded');
  }

  async function perform(action: string) {
    if (action === 'undo' || action === 'redo') return await applyHistory(action);
    if (action === 'initialize') return await initializeReview();
    if (action === 'formatting') return await initializeFormatting();
    if (action === 'findings-edit') return editFinding();
    if (action === 'previous' || action === 'next') {
      report('Review the selected change.');
      return await revealChange(selected + (action === 'next' ? 1 : -1));
    }
    if (action === 'reject' || action === 'accept' || action === 'reject-all' || action === 'accept-all') {
      if (precise && (action === 'accept' || action === 'reject')) return await decideNumber(action);
      return await decide(action.startsWith('accept') ? 'accept' : 'reject', action.endsWith('-all'));
    }
    if (action === 'propose') return await proposeNumber();
    if (action === reportChangeAction) return await proposeReportChange();

  }

  async function act(action: string, trigger?: HTMLButtonElement) {
    if (working) return;
    if (action === 'reset') {
      window.location.reload();
      return;
    }
    working = true;
    setControls(false);
    try {
      if (action === 'download') {
        observe('export_requested');
        const candidate = prepared ?? await (review ? verifyReview() : exportCopy());
        if (sampleReview?.comment) {
          const parts = await proofParts(candidate);
          const body = parts.find(part => part.documentElement.localName === 'document');
          if (!body?.getElementsByTagNameNS(ns, 'commentReference').length ||
              !parts.some(part => elementText(part, 'comment').includes(sampleReview.comment!))) {
            throw new Error('The exported file lost the original review comment.');
          }
        }
        if (mode === 'formatting') {
          const parts = await proofParts(candidate);
          const documentPart = parts.find(part => part.documentElement.localName === 'document')!;
          const row = Array.from(documentPart.getElementsByTagNameNS(ns, 'tr')).find(row =>
            row.getElementsByTagNameNS(ns, 'tc')[0]?.textContent === 'AUD-0003',
          );
          const editedFinding = row?.getElementsByTagNameNS(ns, 'tc')[1]?.textContent;
          if (editedFinding && editedFinding !== formattingFinding) observe('task_succeeded');
        }
        releaseDownload(candidate, sampleReview?.filename ?? `word-${mode}-sample.docx`);
        observe('export_completed');
        report(sampleReview
          ? changes.length
            ? 'Word file downloaded with pending changes.'
            : 'Word file downloaded with your review decisions.'
          : review
          ? `Word file downloaded. ${changes.length} pending changes remain for review in Word.`
          : 'Word file downloaded. Open it in Microsoft Word to inspect the result.');
      } else {
        await perform(action);
      }
    } catch (error) {
      if (action === 'download') {
        observe('export_failed');
        if (review) observe('task_failed');
      }
      else if (action === 'initialize' && sampleReview) observe('load_failed');
      else if (/^(accept|reject|propose)/.test(action)) observe('task_failed');
      showError(error);
    }
    finally {
      working = false;
      setControls(true);
      if (precise && trigger && (document.activeElement === trigger || document.activeElement === document.body)) {
        if (!precise.decisions.hidden && action === 'propose') {
          precise.decisions.querySelector('button')?.focus({ preventScroll: true });
        } else if (precise.decisions.hidden && (action === 'accept' || action === 'reject')) {
          download.focus({ preventScroll: true });
        }
      }
    }
  }

  actionBar.addEventListener('click', event => {
    const button = (event.target as HTMLElement).closest<HTMLButtonElement>('button');
    if (!button || button.disabled) return;
    const action = button === download ? 'download' : button.dataset.proofAction ?? button.dataset.proofHistory;
    if (action) void act(action, button);
  });
  if (historyButtons.length) surface.closest('main')?.addEventListener('keydown', event => {
    if (!editor || working || !(event.metaKey || event.ctrlKey) || event.altKey) return;
    if ((event.target as HTMLElement).closest('input, textarea, select')) return;
    const key = event.key.toLowerCase();
    const action = key === 'z' ? event.shiftKey ? 'redo' : 'undo' : key === 'y' && !event.shiftKey ? 'redo' : undefined;
    if (!action || historyButtons.find(button => button.dataset.proofHistory === action)?.disabled) return;
    event.preventDefault();
    event.stopPropagation();
    void act(action);
  }, { capture: true });
  if (review) surface.addEventListener('click', event => {
    if (working || !reviewReady) return;
    const hit = editor.ui.trackChanges.getAt({ x: event.clientX, y: event.clientY });
    const index = hit ? changes.findIndex(change => change.id === hit.id) : -1;
    if (index < 0) return;
    editor.ui.trackChanges.setActive(hit!);
    selected = index;
    setControls(true);
  });
  document.getElementById('proof-reset')?.addEventListener('click', () => void act('reset'));
  if (!review) compact.addEventListener('change', () => editor?.setCommentsLayout(compact.matches ? 'inline' : 'sidebar'));
  const viewport = window.visualViewport;
  viewport?.addEventListener('resize', () => {
    document.body.style.setProperty('--proof-visible-height', `${viewport.height}px`);
  });
  window.addEventListener('pagehide', event => { if (!event.persisted) editor?.destroy(); });

  const config = {
    telemetry: { enabled: false },
    selector: '#editor',
    zoom: { mode: 'fit-width' as const, fitWidth: { padding: 16 } },
    viewing: { trackedChanges: review || mode === 'report' ? 'markup' as const : 'final' as const, comments: false },
    ...((review || precise) && { interaction: { trackedChanges: { allowDecisions: true } } }),
    user: { name: 'Example reviewer', email: 'reviewer@example.com' },
    ui: {
      ...(review ? {} : { toolbar: {
        container: '#toolbar', responsiveTo: 'container' as const,
        ...(historyButtons.length && { groups: {
          left: ['bold', 'italic', 'underline', 'strikethrough'], right: [],
        } }),
      } }),
      comments: review ? false as const : { layout: compact.matches ? 'inline' as const : 'sidebar' as const },
    },
  };

  async function reopen(candidate: Blob) {
    const host = document.createElement('div');
    host.id = 'review-verification';
    host.inert = true;
    host.setAttribute('aria-hidden', 'true');
    host.style.width = `${element('editor').clientWidth}px`;
    document.body.append(host);
    let verifier: SuperDoc | undefined;
    let timer: number | undefined;
    try {
      const copy = new File([candidate], 'reviewed-agreement.docx', {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      });
      const opened = await new Promise<SuperDoc>((resolve, reject) => {
        timer = window.setTimeout(() => reject(new Error('The saved copy did not reopen. Try verifying again.')), 20000);
        verifier = new SuperDoc({
          ...config, selector: '#review-verification', ui: {}, document: copy, documentMode: 'viewing',
          onReady: ({ superdoc }) => resolve(superdoc),
          onContentError: ({ error }) => reject(error),
          onException: ({ error }) => reject(error),
        });
      });
      return await getReview(opened);
    } finally {
      window.clearTimeout(timer);
      verifier?.destroy();
      host.remove();
    }
  }

  observe('load_started');
  new SuperDoc({
    ...config,
    document: fixture,
    documentMode: review ? 'viewing' : mode === 'precise' ? 'suggesting' : 'editing',
    onReady: ({ superdoc }) => {
      editor = superdoc;
      if (!sampleReview) observe('ready');
      if (review) void act('initialize');
      else if (mode === 'formatting') void act('formatting');
      else {
        report(precise ? 'Propose 60 days for Renewal notice. Invoice payment also starts at 30 days.' : 'Ready to suggest an edit in section 150.');
        setControls(true);
      }
    },
    onEditorUpdate: () => {
      if (!working && editor && historyButtons.length) setControls(true);
    },
    onContentError: ({ error }) => handleEditorError(error),
    onException: ({ error }) => handleEditorError(error),
  });

  function handleEditorError(error: unknown) {
    if (sampleReview && !reviewReady) observe('load_failed');
    showError(error);
  }
}
```

### examples/shared/word-proof.css

```css
@font-face {
  font-family: Inter;
  src: url('/fonts/inter-7.woff2') format('woff2');
  font-weight: 100 900;
  font-display: swap;
}

[data-proof] {
  --proof-bg: #f8fafc;
  --proof-surface: #fff;
  --proof-ink: #0f172a;
  --proof-secondary: #475569;
  --proof-border: #dbe2ea;
  --proof-link: #1747b7;
  --proof-hover: #edf3ff;
  --proof-disabled: #f1f5f9;
  --proof-accent: #1355ff;
  --proof-accent-hover: #0f44cc;
  --proof-mat: #edf0f5;
  min-height: 100dvh;
  background: var(--proof-bg);
  color: var(--proof-ink);
  font-family: Inter, system-ui, sans-serif;
}

.dark [data-proof] {
  --proof-bg: #0b0c10;
  --proof-surface: #161922;
  --proof-ink: #f1f5f9;
  --proof-secondary: #b6c2d3;
  --proof-border: #363e50;
  --proof-link: #a4bfff;
  --proof-hover: #202e4c;
  --proof-disabled: #252936;
  --proof-mat: #252936;
}

[data-proof] > :is(.review-heading, .review-workspace, .review-resources) {
  max-width: 90rem;
  margin-inline: auto;
}

[data-proof] > .review-heading {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  justify-content: space-between;
  gap: .5rem 1rem;
  padding: .65rem 1.25rem .85rem;
  border: 0;
  background: transparent;
}

.proof-heading-copy { flex: 1 1 34rem; }
[data-proof] h1 {
  margin: .15rem 0 .2rem;
  font-size: clamp(1.3rem, 2.7vw, 2rem);
  line-height: 1.17;
  letter-spacing: -.035em;
  font-weight: 700;
}

.review-heading p {
  max-width: 72ch;
  margin: 0;
  color: var(--proof-secondary);
  font-size: .875rem;
  line-height: 1.45;
}

.proof-brand, .proof-build {
  display: inline-flex;
  align-items: center;
  gap: .45rem;
  min-height: 44px;
  font-weight: 650;
}
.proof-brand {
  color: var(--proof-ink);
  text-decoration: none;
  font-size: .875rem;
  letter-spacing: -.02em;
}
.proof-brand img { border-radius: 4px; object-fit: contain; }
.proof-build {
  padding-inline: .85rem;
  border: 1px solid var(--proof-border);
  border-radius: .55rem;
  color: var(--proof-link);
  background: var(--proof-surface);
  text-decoration: none;
  font-size: .875rem;
}
.proof-build:hover { background: var(--proof-hover); }

.review-workspace {
  margin: 0 1rem;
  width: calc(100% - 2rem);
  border: 1px solid var(--proof-border);
  border-radius: .8rem;
  background: var(--proof-surface);
}

.review-chrome {
  position: sticky;
  top: 0;
  z-index: 5;
  border-radius: .8rem .8rem 0 0;
  border-bottom: 1px solid var(--proof-border);
  background: var(--proof-surface);
}

.review-actions {
  margin: 0;
  padding: .55rem .7rem 0;
  gap: .4rem;
}

.review-actions button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: .35rem;
  min-height: 44px;
  padding: .45rem .75rem;
  border: 1px solid var(--proof-border);
  border-radius: .5rem;
  background: var(--proof-surface);
  color: var(--proof-ink);
  font-size: .8125rem;
  font-weight: 650;
}
.review-actions button:hover:enabled { background: var(--proof-hover); }
.review-actions button:disabled {
  background: var(--proof-disabled);
  color: var(--proof-secondary);
  cursor: default;
}
.review-actions :is([data-proof-action="accept"], [data-proof-action="propose"], [data-proof-action="findings-edit"], [data-proof-action="report-change"], [aria-pressed="true"]):enabled {
  border-color: var(--proof-accent);
  background: var(--proof-accent);
  color: #fff;
}
.review-actions :is([data-proof-action="accept"], [data-proof-action="propose"], [data-proof-action="findings-edit"], [data-proof-action="report-change"], [aria-pressed="true"]):hover:enabled {
  background: var(--proof-accent-hover);
}
.review-actions #export:enabled { color: var(--proof-link); }
.review-actions [data-proof-action="reset"]:enabled { color: var(--proof-secondary); }
.review-actions [hidden] { display: none; }
.review-action-group { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; }
.review-action-group + .review-action-group { padding-inline-start: .45rem; border-inline-start: 1px solid var(--proof-border); }
.review-action-group.review-handoff { margin-inline-start: auto; }
#review-count { color: var(--proof-secondary); font-size: .8125rem; font-variant-numeric: tabular-nums; }
#review-selection {
  margin: .35rem .7rem 0;
  color: var(--proof-ink);
  font-size: .8125rem;
  font-weight: 650;
  overflow-wrap: anywhere;
}
[data-proof] #status {
  display: block;
  padding: .3rem .7rem .4rem;
  color: var(--proof-secondary);
  font-size: .8125rem;
}
[data-proof] #toolbar {
  background: #fff;
  color: #0f172a;
  color-scheme: light;
}

[data-proof] #editor {
  height: clamp(14rem, calc(var(--proof-visible-height, 100dvh) - 12rem), 52rem);
  background: var(--proof-mat);
  border-radius: 0 0 .8rem .8rem;
  color: #0f172a;
  color-scheme: light;
}
[data-proof="review"] #editor { height: clamp(14rem, calc(var(--proof-visible-height, 100dvh) - 13.5rem), 52rem); }
#review-verification { position: fixed; top: 0; left: 0; height: 22rem; visibility: hidden; overflow: hidden; pointer-events: none; }

.review-resources {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: .25rem 1.15rem;
  padding: .25rem 1.25rem .75rem;
  color: var(--proof-secondary);
  font-size: .875rem;
}

.review-resources summary { align-content: center; min-height: 44px; cursor: pointer; }
.review-resources a {
  display: inline-flex;
  align-items: center;
  min-height: 44px;
  color: var(--proof-link);
  text-underline-offset: .18em;
}
.proof-resource-links { display: flex; flex-wrap: wrap; gap: 0 1rem; }
[data-proof] :is(.review-heading, .review-chrome, .review-resources) :focus-visible {
  outline: 2px solid var(--proof-link);
  outline-offset: 2px;
}

@media (max-width: 1099px), (pointer: coarse) {
  [data-proof="formatting"] .review-chrome #toolbar { display: none; }
}

@media (max-width: 680px) {
  [data-proof] > .review-heading { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: .25rem .5rem; padding: 0 .8rem .65rem; }
  .proof-heading-copy { display: contents; }
  .proof-brand { grid-row: 1; grid-column: 1; justify-self: start; }
  .proof-build { grid-row: 1; grid-column: 2; background: transparent; border-color: transparent; padding-inline: .25rem; }
  .review-heading :is(h1, p) { grid-column: 1 / -1; }
  .review-workspace { width: 100%; border-inline: 0; border-radius: 0; }
  .review-chrome { border-radius: 0; }
  .review-actions { padding-inline: .6rem; }
  .review-actions button { padding-inline: .6rem; }
  .review-action-group + .review-action-group { padding-inline-start: 0; border-inline-start: 0; }
  .review-action-group.review-handoff { margin-inline-start: 0; }
  [data-proof] #editor {
    height: clamp(14rem, calc(var(--proof-visible-height, 100dvh) - 14.5rem), 42rem);
    border-radius: 0;
  }
  [data-proof="review"] #editor { height: clamp(14rem, calc(var(--proof-visible-height, 100dvh) - 18rem), 42rem); }
  .review-resources { padding-inline: .8rem; }
}

[data-proof="precise"] #editor, [data-proof="review"][data-handoff-review] #editor { height: clamp(16rem, 54dvh, 35rem); }

.proof-history { display: flex; align-items: center; gap: .3rem; }
.proof-history button { min-width: 44px; padding-inline: .45rem; }
```

### vite.config.ts

```javascript
import { defineConfig } from 'vite';
import { resolve } from 'node:path';
export default defineConfig({
  optimizeDeps: { exclude: ['@superdoc/docx-engine'], include: ['vue'] },
  resolve: { dedupe: ['vue'] },
  build: { rollupOptions: { input: resolve('examples/proof-legal-word-handoff/index.html') } },
});
```

### tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": [
      "ES2022",
      "DOM",
      "DOM.Iterable"
    ],
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": []
  },
  "include": [
    "examples/**/*.ts"
  ]
}
```

[Download the project](https://www.superdoc.dev/examples/proof-legal-word-handoff.zip)
[Download the public sample](https://www.superdoc.dev/testkit_docs/proof-legal-word-handoff.docx)
