# Review 250 changes in a Word agreement

Reveal pending changes in a finished-looking agreement. Reject the 10-day proposal, type your own wording, then accept the approved batch and download a verified copy.

## 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.35.0. Direct dependencies are pinned in package.json.

## Try it

The copy reports zero pending changes across the document, including headers, footers, and notes. Open it in Microsoft Word to inspect the result.

The included DOCX is a public synthetic example. It is not your uploaded document or the current edited demo state. Export a separate DOCX, then reopen it in Word or SuperDoc. Built-in and custom review examples use Suggesting mode. The application form fills text fields directly.

## Files

- package.json
- examples/proof-review/main.ts
- examples/proof-review/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-review.docx

## Continue

[Current documentation](https://docs.superdoc.dev/editor/track-changes/)
[Open the public example](https://www.superdoc.dev/examples/proof-review/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-review",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22"
  },
  "scripts": {
    "dev": "vite --open /examples/proof-review/",
    "build": "vite build",
    "check": "tsc --noEmit"
  },
  "dependencies": {
    "superdoc": "2.35.0",
    "fflate": "0.8.3"
  },
  "devDependencies": {
    "vite": "6.4.1",
    "typescript": "5.8.3"
  }
}
```

### examples/proof-review/main.ts

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

mountWordProof('review', '/testkit_docs/proof-review.docx');
```

### examples/proof-review/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 250 changes in a Word agreement | SuperDoc example</title>
<meta name="description" content="Reveal pending changes in a finished-looking agreement. Reject the 10-day proposal, type your own wording, then accept the approved batch and download a verified copy.">
<link rel="canonical" href="https://www.superdoc.dev/examples/proof-review/index.html">
<link rel="alternate" type="text/markdown" href="https://www.superdoc.dev/examples/proof-review.md">
</head>
<body data-proof="review">
<header>
<h1>Review 250 changes in a Word agreement</h1>
<p>Reveal pending changes in a finished-looking agreement. Reject the 10-day proposal, type your own wording, then accept the approved batch and download a verified copy.</p>
<div class="actions" id="proof-actions">
<button type="button" data-proof-action="show" disabled>Show pending changes</button>
<button type="button" data-proof-action="reject" disabled>Reject the 10-day proposal</button>
<button type="button" data-proof-action="accept" disabled>Accept the remaining changes</button>
<button id="export" type="button" disabled>Download Word file</button>
<button type="button" data-proof-action="reset" disabled>Reset example</button>
<output id="status" role="status">Opening document…</output>
</div>
<p><a href="https://docs.superdoc.dev/editor/track-changes/">Build this</a> · <a href="/examples/proof-review.md">Read the source</a> · <a href="/examples/proof-review.zip">Download this project</a> · <a href="/testkit_docs/proof-review.docx">Download the original sample</a></p>
</header>
<div id="toolbar"></div>
<main class="solo"><div id="editor"></div></main>
<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; } }
```

### 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 jumpTargets = new Map([
  ['findings', { paraId: '50500150', instruction: 'Find the findings table and edit a status cell.' }],
  ['table', { paraId: '50504501', instruction: 'Edit a cell and check the repeated headings in Word.' }],
  ['numbering', { paraId: '50504502', instruction: 'Edit a numbered clause and check the levels in Word.' }],
  ['revision', { paraId: '50504503', instruction: 'Review the tracked change and the comment beside it.' }],
]);
export function mountWordProof(mode: Proof, fixture: string) {
  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');
  let editor: SuperDoc;
  let prepared: Blob | undefined;
  let reviewState = mode !== 'review';
  let working = false;
  const observe = (action: string) => window.dispatchEvent(new CustomEvent('superdoc:word-proof', { detail: action }));

  function elementText(part: Document, 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' });
  }

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

  async function acceptBatch() {
    const before = await getReview();
    if (before.length < 1) throw new Error('There are no pending suggestions.');
    const result = await editor.activeEditor.doc.trackChanges.decide({
      decision: 'accept', target: { kind: 'all' }, commentRetention: 'point',
    });
    if (!result.success) throw new Error('The review decision did not complete. No reviewed copy was prepared.');
    const candidate = await exportCopy();
    const parts = await proofParts(candidate);
    const pending = parts.flatMap(part => Array.from(part.getElementsByTagNameNS(ns, '*')))
      .filter(node => revisionNames.has(node.localName)).length;
    if (pending) throw new Error(`The downloaded copy still has ${pending} pending changes. Reset and try again.`);
    const commentAnchors = parts.flatMap(part => Array.from(part.getElementsByTagNameNS(ns, 'commentReference')));
    if (!commentAnchors.length) throw new Error('The saved copy lost the sample comment anchor.');
    await reopen(candidate);
    prepared = candidate;
    observe('task_succeeded');
    report(`${before.length} changes accepted. Zero changes left to review in this copy.`);
  }

  async function showReview() {
    editor.setDocumentMode('suggesting');
    reviewState = true;
    const items = await getReview();
    report(`${items.length} pending changes. Review the agreement before applying the batch.`);
  }

  async function rejectFirst() {
    const change = (await getReview()).find(item => item.insertedText?.includes('Approval is due within 10 days.'));
    if (!change) throw new Error('The sample proposal has already been resolved.');
    const result = await editor.activeEditor.doc.trackChanges.decide({
      decision: 'reject', target: { kind: 'id', id: change.id },
    });
    if (!result.success) throw new Error('The sample proposal could not be rejected.');
    report('The 10-day proposal was rejected. You can type your own wording in the review clause.');
  }

  async function proposeNumber() {
    const doc = editor.activeEditor.doc;
    const response = await doc.find({ select: { type: 'text', pattern: '30 days', caseSensitive: true } });
    const hit = response.items.at(0);
    const target = hit && (Reflect.get(hit, 'target') ?? Reflect.get(hit, 'address'));
    const blockId: unknown = target?.nodeId;
    if (response.items.length !== 1 || typeof blockId !== 'string') {
      throw new Error('The original target was not found.');
    }
    const result = await doc.replace({
      target: {
        kind: 'selection',
        start: { kind: 'text', blockId, offset: 0 },
        end: { kind: 'text', blockId, offset: 7 },
      },
      text: '60 days', expectedText: '30 days', replacementGranularity: 'word',
    }, { changeMode: 'tracked' });
    if (!result.success) throw new Error('The proposal could not be applied.');
    const parts = await proofParts(await exportCopy());
    const inserted = parts.flatMap(part => elementText(part, 'ins')).join('');
    const removed = parts.flatMap(part => elementText(part, '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.');
    }
    observe('task_succeeded');
    report('Only the number is marked. Use the review toolbar to accept or reject the proposal.');
  }

  function setControls(enabled: boolean) {
    actionBar.querySelectorAll<HTMLButtonElement>('button[data-proof-action]').forEach(button => {
      const action = button.dataset.proofAction;
      button.disabled = !enabled || (mode === 'review' && !reviewState && action !== 'show')
        || (reviewState && action === 'show') || (Boolean(prepared) && action !== 'reset');
    });
    download.disabled = !(enabled && (mode !== 'review' || prepared));
  }

  function setTracking(tracks: boolean) {
    editor.setDocumentMode(tracks ? 'suggesting' : 'editing');
    actionBar.querySelector('[data-proof-action="tracking"]')?.setAttribute('aria-pressed', String(tracks));
  }

  async function perform(action: string) {
    if (action === 'show') return await showReview();
    if (action === 'reject') return await rejectFirst();
    if (action === 'accept') return await acceptBatch();
    if (action === 'propose') return await proposeNumber();
    if (action === 'tracking') {
      const button = actionBar.querySelector<HTMLButtonElement>('[data-proof-action="tracking"]')!;
      const tracks = button.getAttribute('aria-pressed') !== 'true';
      setTracking(tracks);
      report(tracks ? 'Track Changes is on.' : 'Track Changes is off.');
      return;
    }
    const target = jumpTargets.get(action);
    if (!target) return;
    if (action === 'revision') setTracking(true);
    const result = await editor.activeEditor.pageMetrics.revealBodyTarget({ paraId: target.paraId });
    report(result.status === 'revealed' ? target.instruction : 'This page is still preparing. Try again when pagination settles.');
  }

  actionBar.addEventListener('click', async event => {
    const button = (event.target as HTMLElement).closest<HTMLButtonElement>('button');
    if (!button || button.disabled || working) return;
    if (button.dataset.proofAction === 'reset') {
      window.location.reload();
      return;
    }
    working = true;
    setControls(false);
    try {
      if (button === download) {
        observe('export_requested');
        releaseDownload(prepared ?? await exportCopy(), `word-${mode}-sample.docx`);
        observe('export_completed');
        report('Word file downloaded. Open it in Microsoft Word to inspect the result.');
      } else if (button.dataset.proofAction) {
        await perform(button.dataset.proofAction);
      }
    } catch (error) {
      if (button === download) observe('export_failed');
      else if (['accept', 'propose'].includes(button.dataset.proofAction ?? '')) observe('task_failed');
      showError(error);
    }
    finally {
      working = false;
      setControls(true);
    }
  });

  const config = {
    telemetry: { enabled: false },
    selector: '#editor',
    zoom: { mode: 'fit-width' as const, fitWidth: { padding: 16 } },
    viewing: { trackedChanges: 'final' as const, comments: false },
    user: { name: 'Example reviewer', email: 'reviewer@example.com' },
    ui: { toolbar: { container: '#toolbar', responsiveTo: 'container' as const } },
  };

  async function reopen(candidate: Blob) {
    editor.destroy();
    const copy = new File([candidate], 'reviewed-agreement.docx', {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    });
    editor = await new Promise<SuperDoc>((resolve, reject) => {
      const timer = setTimeout(() => reject(new Error('The saved copy did not reopen. Reset to try again.')), 20_000);
      new SuperDoc({
        ...config, document: copy, documentMode: 'viewing',
        onReady: ({ superdoc }) => { clearTimeout(timer); resolve(superdoc); },
        onContentError: ({ error }) => { clearTimeout(timer); reject(error); },
        onException: ({ error }) => { clearTimeout(timer); reject(error); },
      });
    });
    if ((await getReview()).length) throw new Error('The reopened copy still has pending changes.');
  }

  observe('load_started');
  new SuperDoc({
    ...config,
    document: fixture,
    documentMode: mode === 'review' ? 'viewing' : mode === 'precise' ? 'suggesting' : 'editing',
    onReady: ({ superdoc }) => {
      editor = superdoc;
      report(mode === 'review' ? 'The agreement looks finished. Show the pending changes.' : 'Ready to edit.');
      setControls(true);
      observe('ready');
    },
    onContentError: ({ error }) => showError(error),
    onException: ({ error }) => showError(error),
  });
}
```

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

```css
[data-proof] > header {
  padding: clamp(1rem, 2.6vw, 2rem) clamp(1rem, 5vw, 4rem) 1rem;
  color: #17213a;
  border-bottom-color: #d4d9e5;
}

[data-proof] h1 {
  font-size: clamp(1.45rem, 3vw, 2.4rem);
  line-height: 1.14;
  letter-spacing: -.024em;
}

[data-proof] > header p {
  max-width: 72ch;
  margin: .7rem 0;
  color: #425171;
}

[data-proof] .actions {
  gap: .45rem;
  margin-top: .9rem;
}

[data-proof] .actions button {
  padding: .5rem .8rem;
  border: 1px solid #c2cadc;
  border-radius: .5rem;
  background: white;
  color: #17213a;
  font-size: .875rem;
  font-weight: 600;
}

[data-proof] .actions :is(#export, [data-proof-action="show"], [data-proof-action="propose"], [aria-pressed="true"]):enabled {
  border-color: #203e73;
  background: #203e73;
  color: white;
}

[data-proof] .actions button:disabled {
  background: #f2f4f8;
  color: #5f6d89;
  cursor: default;
}

[data-proof] .actions output {
  flex: 1 0 100%;
  margin-top: .25rem;
  font-size: .9rem;
}

[data-proof] > header a {
  color: #234779;
  text-underline-offset: .18em;
}

[data-proof] > header :focus-visible {
  outline: 2px solid #234779;
  outline-offset: 3px;
}
```

### 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-review/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-review.zip)
[Download the public sample](https://www.superdoc.dev/testkit_docs/proof-review.docx)
