# Compare an editable DOCX with Markdown

The comparison opens a synthetic Word agreement in SuperDoc and generates a Markdown export automatically. Upload a DOCX to see what its Markdown export leaves out or simplifies. View Markdown source in the output pane and diagnostic codes in the report beneath both panes. After editing, click or tab out of the Word editor to refresh automatically. On phones, you can also scroll from the editor to the Markdown export. Download DOCX saves the editable Word file. Download Markdown uses the latest document. Files you open stay in the browser.

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

This export leaves out Word’s tracked-change markup and comments. Use the DOCX to continue the review. A new DOCX built from the Markdown alone can’t recover the details the export left out.

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-markdown/main.ts
- examples/proof-markdown/index.html
- examples/shared/browser.ts
- examples/shared/style.css
- examples/proof-markdown/style.css
- vite.config.ts
- tsconfig.json
- public/samples/markup/vendor-services-markup.docx

## Continue

[Current documentation](https://docs.superdoc.dev/document-api/output-projections/)
[Open the public example](https://www.superdoc.dev/examples/proof-markdown/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-markdown",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22"
  },
  "scripts": {
    "dev": "vite --open /examples/proof-markdown/",
    "build": "vite build",
    "check": "tsc --noEmit"
  },
  "dependencies": {
    "superdoc": "2.36.0",
    "marked": "17.0.6"
  },
  "devDependencies": {
    "vite": "6.4.1",
    "typescript": "5.8.3"
  }
}
```

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

```javascript
import { SuperDoc } from 'superdoc';
import { Marked } from 'marked';
import { element, report } from '../shared/browser';
import './style.css';

const sample = '/samples/markup/vendor-services-markup.docx';
const maxFileSize = 50 * 1024 * 1024;
const projectedHtmlTags = new Set(['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'p', 'br', 'strong', 'em', 'u', 's', 'sub', 'sup']);

function renderProjectedHtml(html: string) {
  // GFM uses inline HTML for some Word tables. Parse it without loading any
  // resources and keep only the elements and table spans the preview needs.
  const template = document.createElement('template');
  template.innerHTML = html;
  for (const node of template.content.querySelectorAll('*')) {
    if (node.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !projectedHtmlTags.has(node.localName)) {
      node.remove();
      continue;
    }
    for (const attribute of [...node.attributes]) {
      const cellSpan = (node.localName === 'td' || node.localName === 'th') &&
        ['colspan', 'rowspan'].includes(attribute.name) && /^[1-9]\d{0,2}$/.test(attribute.value);
      if (!cellSpan) node.removeAttributeNode(attribute);
    }
  }
  return template.innerHTML;
}

const renderer = new Marked({
  renderer: {
    html: ({ text }) => renderProjectedHtml(text),
    image: () => '[Image omitted from preview]',
    link(token) { return this.parser.parseInline(token.tokens); },
  },
});
const workspace = element('docx-workspace');
const openButton = element<HTMLButtonElement>('open-file');
const fileInput = element<HTMLInputElement>('docx-file');
const resetButton = element<HTMLButtonElement>('reset-file');
const exportButton = element<HTMLButtonElement>('export');
const projectionStatus = element<HTMLOutputElement>('projection-status');
const retryMarkdown = element<HTMLButtonElement>('retry-markdown');
const projection = element('projection');
const source = element<HTMLTextAreaElement>('markdown-source');
const preview = element('markdown-preview');
const reportFooter = element('comparison-findings');
const findings = element<HTMLUListElement>('projection-loss');
const noFindings = element('projection-loss-empty');
const diagnostics = element<HTMLDetailsElement>('projection-diagnostics');
const diagnosticCodes = element<HTMLUListElement>('projection-diagnostic-codes');
const markdownButton = element<HTMLButtonElement>('download-markdown');

type DocumentApi = NonNullable<NonNullable<SuperDoc['activeEditor']>['doc']>;
type MarkdownResult = Awaited<ReturnType<DocumentApi['projectMarkdown']>>;
type Diagnostic = MarkdownResult['diagnostics'][number];
type Finding = { title: string; detail: string };

const featureNames: Partial<Record<Diagnostic['construct'], string>> = {
  text: 'Text formatting',
  paragraph: 'Paragraph formatting',
  heading: 'Headings',
  underline: 'Underlining',
  list: 'Lists',
  listLabel: 'List numbering',
  columnBreak: 'Column breaks',
  sectionBreak: 'Section breaks',
  pageBreak: 'Page breaks',
  image: 'Images',
  drawing: 'Drawings',
  embeddedObject: 'Embedded objects',
  field: 'Word fields',
  contentControl: 'Content controls',
  math: 'Equations',
  table: 'Tables',
  tableHeader: 'Table headers',
  colSpan: 'Merged table cells',
  rowSpan: 'Merged table cells',
};

const sampleFindings = {
  trackedChange: {
    title: 'Tracked changes left out of the Markdown export',
    detail: 'The DOCX shows both proposed edits. Delivery changes from 15 to 21 business days, and the review window changes from 2 to 5. The Markdown export shows 21 and 5 as plain text. The DOCX keeps the original and proposed wording, who proposed each edit, and the ability to accept or reject it.',
  },
  comment: {
    title: 'Anchored comment left out',
    detail: 'Markdown keeps the clause text. The comment and its anchor stay in the DOCX.',
  },
  styles: {
    title: 'Named Word styles left out',
    detail: 'The export keeps the heading levels and table contents. The DOCX keeps the named styles and Word formatting settings.',
  },
  layout: {
    title: 'Two-column layout left out',
    detail: 'Markdown reads in one column. The Markdown source marks where the column break was.',
  },
};

type Projection = { revision: number; result: MarkdownResult };

type DocumentSession = {
  editor?: SuperDoc;
  host: HTMLElement;
  sample: boolean;
  revision: number;
  editing: boolean;
  composing: boolean;
  edited?: boolean;
  snapshot?: Projection;
  renderedRevision?: number;
  inFlight?: { revision: number; promise: Promise<Projection | undefined> };
  downloadingMarkdown?: boolean;
};
let active: DocumentSession | undefined;
let opening: DocumentSession | undefined;
let busy = false;
let nextHostId = 0;
let projectionTimer: number | undefined;

function measure(session: DocumentSession, action: string) {
  if (session.sample) window.dispatchEvent(new CustomEvent('superdoc:word-proof', { detail: action }));
}

function updateControls() {
  openButton.disabled = busy;
  resetButton.disabled = busy || Boolean(active?.sample && !active.edited);
  exportButton.disabled = markdownButton.disabled = busy || !active;
  retryMarkdown.disabled = busy || !active;
}

function clearProjection() {
  projection.hidden = true;
  reportFooter.hidden = true;
  retryMarkdown.hidden = true;
  source.value = '';
  preview.replaceChildren();
  findings.replaceChildren();
  diagnosticCodes.replaceChildren();
  diagnostics.open = false;
}

function destroy(session: DocumentSession | undefined) {
  session?.editor?.destroy();
  session?.host.remove();
}

async function load(file?: File) {
  if (busy) return;
  busy = true;
  window.clearTimeout(projectionTimer);
  const host = document.createElement('div');
  host.className = 'comparison-document staging';
  host.inert = true;
  host.setAttribute('aria-hidden', 'true');
  const id = `comparison-document-${++nextHostId}`;
  host.innerHTML = `<div id="${id}-toolbar" class="comparison-toolstrip"></div><div id="${id}" class="comparison-editor" aria-label="Editable Word document"></div>`;
  workspace.append(host);
  const session: DocumentSession = { host, sample: !file, revision: 0, editing: false, composing: false };
  opening = session;
  if (active) active.host.inert = true;
  updateControls();
  report(file ? 'Opening your DOCX…' : 'Opening the sample agreement…');
  measure(session, 'load_started');
  let timer: number | undefined;
  let loaded = false;
  try {
    await new Promise<void>((ready, fail) => {
      timer = window.setTimeout(() => fail(new Error('Opening the document timed out.')), 30000);
      session.editor = new SuperDoc({
        selector: `#${id}`,
        document: file ?? sample,
        documentMode: 'editing',
        telemetry: { enabled: false },
        zoom: { mode: 'fit-width', fitWidth: { padding: 16 } },
        user: { name: 'Example editor', email: 'editor@example.com' },
        ui: {
          toolbar: {
            container: `#${id}-toolbar`,
            responsiveTo: 'container',
            groups: { left: ['undo', 'redo', 'bold', 'italic', 'underline'], right: [] },
          },
          comments: { layout: 'inline' },
        },
        onReady: () => ready(),
        onContentError: ({ error }) => fail(error),
        onException: ({ error }) => fail(error),
        onEditorUpdate: () => {
          session.revision += 1;
          if (active !== session) return;
          if (!session.edited) {
            session.edited = true;
            measure(session, 'edit_observed');
          }
          if (projectionStatus.value !== 'Changes pending') {
            projectionStatus.value = 'Changes pending';
            retryMarkdown.hidden = true;
            updateControls();
          }
          if (!session.editing) queuePreview(session);
        },
      });
    });
    if (opening !== session) return;
    destroy(active);
    active = session;
    loaded = true;
    clearProjection();
    projectionStatus.value = 'Generating Markdown export…';
    host.classList.remove('staging');
    host.inert = false;
    host.removeAttribute('aria-hidden');
    report('DOCX ready.');
    measure(session, 'ready');
  } catch {
    destroy(session);
    if (active) {
      active.host.inert = false;
    } else {
      projectionStatus.value = 'Open a DOCX to see its Markdown.';
    }
    const kept = active ? ' Your previous document is still in place.' : '';
    report((file ? 'Could not open this DOCX.' : 'Could not open the sample. Try Reset to sample.') + kept);
    measure(session, 'load_failed');
  } finally {
    clearTimeout(timer);
    if (opening === session) opening = undefined;
    busy = false;
    updateControls();
    if (loaded) void refreshPreview(session, session.revision);
    else if (active) queuePreview(active);
  }
}

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

function isCurrent(session: DocumentSession, revision: number) {
  return session === active && !opening && revision === session.revision;
}

function enterEditor(session: DocumentSession) {
  if (session.editing) return;
  session.editing = true;
  window.clearTimeout(projectionTimer);
}

function leaveEditor(session: DocumentSession) {
  if (!session.editing) return;
  session.editing = false;
  queuePreview(session);
}

function queuePreview(session: DocumentSession) {
  if (busy || session !== active || session.composing || session.editing ||
      session.renderedRevision === session.revision) return;
  window.clearTimeout(projectionTimer);
  // Let focus and the editor's final input settle before projecting the document.
  projectionTimer = window.setTimeout(() => void refreshPreview(session), 120);
}

async function getProjection(session: DocumentSession, revision: number): Promise<Projection | undefined> {
  if (!isCurrent(session, revision) || !session.editor) return;
  if (session.snapshot?.revision === revision) return session.snapshot;
  if (session.inFlight?.revision === revision) return session.inFlight.promise;
  if (session.inFlight) {
    await session.inFlight.promise;
    if (session.editing || session.composing) return;
    return getProjection(session, revision);
  }
  const editor = session.editor;
  const promise = (async () => {
    try {
      const result = await editor.activeEditor?.doc?.projectMarkdown({ reviewMode: 'final' });
      if (!result || result.status === 'failed') throw new Error('Projection failed');
      if (isCurrent(session, revision)) return session.snapshot = { revision, result };
    } catch {
      if (isCurrent(session, revision)) {
        showProjectionFailure(session, 'Could not generate Markdown.');
      }
    }
  })();
  session.inFlight = { revision, promise };
  try {
    return await promise;
  } finally {
    if (session.inFlight.promise === promise) session.inFlight = undefined;
  }
}

function reportFindings(result: MarkdownResult, untouchedSample: boolean): Finding[] {
  const reported: Finding[] = [];
  const reviewKinds = new Set(result.annotations.map(annotation => annotation.kind));
  const changes = new Map<string, Set<Diagnostic['disposition']>>();

  // Annotations describe source review data separately from the Markdown string.
  // A rendered annotation can identify retained text without making it a redline.
  for (const diagnostic of result.diagnostics) {
    if (!diagnostic.lossy) continue;
    const { construct, disposition } = diagnostic;
    if (construct === 'trackedChange' || construct === 'comment') {
      reviewKinds.add(construct);
      continue;
    }
    if (untouchedSample && (construct === 'text' || construct === 'columnBreak')) continue;
    const feature = featureNames[construct] ?? 'Other document features';
    const dispositions = changes.get(feature) ?? new Set();
    dispositions.add(disposition);
    changes.set(feature, dispositions);
  }

  if (untouchedSample) {
    reported.push(sampleFindings.trackedChange, sampleFindings.comment, sampleFindings.styles, sampleFindings.layout);
  } else {
    if (reviewKinds.has('trackedChange')) reported.push({
      title: 'Tracked changes left out of the Markdown export',
      detail: 'The DOCX still carries the pending edits and who proposed them. Use the DOCX to accept or reject those edits.',
    });
    if (reviewKinds.has('comment')) reported.push({
      title: 'Word comments left out of the Markdown export',
      detail: 'Use the DOCX to read the comment threads and see which text they refer to.',
    });
  }

  for (const [title, dispositions] of changes) {
    const effects = [];
    if (dispositions.has('omitted') || dispositions.has('rejected')) effects.push('omitted');
    if (dispositions.has('downgraded') || dispositions.has('normalized')) effects.push('simplified');
    if (dispositions.has('placeholder')) effects.push('shown as markers in the Markdown source');
    reported.push({
      title,
      detail: effects.length
        ? `The export reports some of this content was ${effects.join(', or ')}.`
        : 'The export reports a change here. See the diagnostic codes.',
    });
  }
  return reported;
}

function renderFindings(result: MarkdownResult, untouchedSample: boolean) {
  const rows = reportFindings(result, untouchedSample).map(({ title, detail }) => {
    const item = document.createElement('li');
    const label = document.createElement('strong');
    label.textContent = title + '.';
    item.append(label, ' ' + detail);
    return item;
  });
  findings.replaceChildren(...rows);
  findings.hidden = !rows.length;
  noFindings.hidden = Boolean(rows.length);

  const codes = new Set(result.diagnostics.map(({ code, construct, disposition }) => `${code} · ${construct} · ${disposition}`));
  diagnosticCodes.replaceChildren(...[...codes].map(value => {
    const item = document.createElement('li');
    const code = document.createElement('code');
    code.textContent = value;
    item.append(code);
    return item;
  }));
  diagnostics.hidden = !codes.size;
}

function showProjectionFailure(session: DocumentSession, message: string) {
  projectionStatus.value = message;
  retryMarkdown.hidden = false;
  measure(session, 'projection_failed');
}

function containWideMarkdown() {
  for (const table of preview.querySelectorAll('table')) {
    const scroller = document.createElement('div');
    scroller.className = 'markdown-table-scroll';
    scroller.setAttribute('role', 'region');
    scroller.setAttribute('aria-label', 'Markdown table');
    scroller.tabIndex = 0;
    table.replaceWith(scroller);
    scroller.append(table);
  }
  for (const block of preview.querySelectorAll('pre')) block.tabIndex = 0;
}

function renderPreview(session: DocumentSession, snapshot: Projection) {
  const { result, revision } = snapshot;
  if (!isCurrent(session, revision) || session.renderedRevision === revision) return;
  let html: string;
  try {
    html = renderer.parse(result.content, { async: false });
  } catch {
    showProjectionFailure(session, 'Could not render the Markdown preview.');
    return;
  }
  source.value = result.content;
  preview.innerHTML = html;
  containWideMarkdown();
  renderFindings(result, session.sample && !session.edited);
  projection.hidden = false;
  reportFooter.hidden = false;
  retryMarkdown.hidden = true;
  session.renderedRevision = revision;
  projectionStatus.value = 'Preview up to date';
  updateControls();
  measure(session, 'projection_succeeded');
}

async function refreshPreview(session: DocumentSession, initialRevision?: number) {
  const revision = session.revision;
  const initial = revision === initialRevision;
  if (busy || !isCurrent(session, revision) || session.composing || (session.editing && !initial) ||
      session.renderedRevision === revision) return;
  retryMarkdown.hidden = true;
  projectionStatus.value = initial ? 'Generating Markdown export…' : 'Updating Markdown…';
  const snapshot = await getProjection(session, revision);
  if (snapshot && !session.composing && (!session.editing || initial)) renderPreview(session, snapshot);
}

async function exportMarkdown() {
  const session = active;
  if (!session || busy || session.composing || session.downloadingMarkdown) return;
  const revision = session.revision;
  session.downloadingMarkdown = true;
  window.clearTimeout(projectionTimer);
  if (session.renderedRevision !== revision) {
    retryMarkdown.hidden = true;
    projectionStatus.value = 'Updating Markdown…';
  }
  try {
    const snapshot = await getProjection(session, revision);
    if (!snapshot || !isCurrent(session, revision)) return;
    if (!session.editing && !session.composing) renderPreview(session, snapshot);
    download(new Blob([snapshot.result.content], { type: 'text/markdown' }), 'document.md');
    measure(session, 'markdown_downloaded');
  } finally {
    session.downloadingMarkdown = false;
  }
}

async function exportDocx() {
  const session = active;
  if (!session?.editor || busy) return;
  busy = true;
  session.host.inert = true;
  updateControls();
  measure(session, 'export_requested');
  try {
    const output = await session.editor.export({ exportType: ['docx'], triggerDownload: false, commentsType: 'external' });
    if (!(output instanceof Blob) || !output.size) throw new Error('Empty export');
    download(output, 'edited-document.docx');
    report('Edited DOCX downloaded. Open it in Word to check your changes.');
    measure(session, 'export_completed');
  } catch {
    report('Could not download this DOCX. Try again.');
    measure(session, 'export_failed');
  } finally {
    busy = false;
    session.host.inert = false;
    updateControls();
    queuePreview(session);
  }
}

document.addEventListener('focusin', event => {
  if (!active) return;
  if (active.host.contains(event.target as Node)) enterEditor(active);
  else leaveEditor(active);
});
document.addEventListener('focusout', event => {
  const session = active;
  if (!session?.host.contains(event.target as Node) || session.host.contains(event.relatedTarget as Node)) return;
  queueMicrotask(() => {
    if (session === active && !session.host.contains(document.activeElement)) leaveEditor(session);
  });
});
document.addEventListener('pointerdown', event => {
  if (!active) return;
  if (active.host.contains(event.target as Node)) enterEditor(active);
  else leaveEditor(active);
}, { capture: true });
document.addEventListener('keydown', event => {
  const session = active;
  if (!session?.host.contains(event.target as Node)) return;
  enterEditor(session);
  if (event.key === 'Tab' && event.target instanceof Element && event.target.closest('.comparison-toolstrip')) {
    // The SDK toolbar handles Tab internally. In this one-group toolbar the
    // arrow keys still move between tools, and Tab leaves the toolbar.
    event.preventDefault();
    event.stopPropagation();
    if (event.shiftKey) exportButton.focus();
    else session.editor?.focus();
  }
}, { capture: true });
document.addEventListener('compositionstart', event => {
  if (active?.host.contains(event.target as Node)) active.composing = true;
});
document.addEventListener('compositionend', event => {
  if (!active?.host.contains(event.target as Node)) return;
  active.composing = false;
  queuePreview(active);
});
window.addEventListener('blur', () => { if (active) leaveEditor(active); });
window.addEventListener('focus', () => {
  if (active?.host.contains(document.activeElement)) enterEditor(active);
});

openButton.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', () => {
  const file = fileInput.files?.[0];
  fileInput.value = '';
  if (!file) return;
  if (!file.name.toLowerCase().endsWith('.docx') || !file.size || file.size > maxFileSize) {
    report('Choose a DOCX file under 50 MB.');
    return;
  }
  void load(file);
});
resetButton.addEventListener('click', () => void load());
exportButton.addEventListener('click', () => void exportDocx());
retryMarkdown.addEventListener('click', () => {
  if (!active) return;
  projectionStatus.focus({ preventScroll: true });
  leaveEditor(active);
  window.clearTimeout(projectionTimer);
  void refreshPreview(active);
});
markdownButton.addEventListener('click', () => {
  if (!active) return;
  leaveEditor(active);
  void exportMarkdown();
});
// The implicit root includes clipping by the landing page when this demo is
// framed. A phone visitor can leave the Word pane by scrolling without blur.
const stackedPanes = window.matchMedia('(max-width: 660px)');
let wordVisible = true;
let markdownVisible = false;
const paneVisibility = new IntersectionObserver(entries => {
  for (const entry of entries) {
    if (entry.target === workspace) wordVisible = entry.isIntersecting;
    else markdownVisible = entry.isIntersecting;
  }
  if (stackedPanes.matches && active?.editing && active.renderedRevision !== active.revision &&
      !wordVisible && markdownVisible) leaveEditor(active);
});
paneVisibility.observe(workspace);
paneVisibility.observe(preview);

window.addEventListener('pagehide', event => {
  if (!event.persisted) {
    paneVisibility.disconnect();
    window.clearTimeout(projectionTimer);
    destroy(opening);
    destroy(active);
    opening = active = undefined;
  }
});
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)');
function setTheme(dark: boolean) {
  document.documentElement.dataset.comparisonTheme = dark ? 'dark' : 'light';
}
setTheme(systemTheme.matches);
if (window.parent !== window) {
  const sameOrigin = window.location.origin;
  window.addEventListener('message', event => {
    if (event.origin === sameOrigin && event.source === window.parent &&
        event.data?.type === 'superdoc:comparison-theme' && typeof event.data.dark === 'boolean') {
      setTheme(event.data.dark);
    }
  });
  window.parent.postMessage({ type: 'superdoc:comparison-ready' }, sameOrigin);
  const main = document.querySelector('main')!;
  new ResizeObserver(() => {
    window.parent.postMessage({
      type: 'superdoc:comparison-height',
      height: Math.ceil(main.getBoundingClientRect().height) + 2,
    }, sameOrigin);
  }).observe(main);
} else {
  systemTheme.addEventListener('change', event => setTheme(event.matches));
}
void load();
```

### examples/proof-markdown/index.html

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src data: blob:; font-src 'self' data: blob:; connect-src 'self' ws://localhost:* ws://127.0.0.1:*; worker-src 'self' blob:; frame-src https://superdoc.dev; object-src 'none'; base-uri 'none'; form-action 'none'">
<title>Compare an editable DOCX with Markdown | SuperDoc example</title>
<meta name="description" content="Compare a Word agreement with its Markdown export. See what the export leaves out, then download either format.">
<link rel="canonical" href="https://www.superdoc.dev/examples/proof-markdown/index.html">
<link rel="alternate" type="text/markdown" href="https://www.superdoc.dev/examples/proof-markdown.md">
</head>
<body class="comparison-demo"><h1 class="comparison-heading">Compare an editable DOCX with Markdown</h1>
<main aria-label="DOCX and Markdown comparison">
  <div class="comparison-workbench">
    <div class="comparison-grid">
      <section class="comparison-pane" aria-labelledby="docx-heading">
        <header class="comparison-pane-header">
          <h2 id="docx-heading">Editable DOCX</h2>
          <div class="comparison-actions" role="group" aria-label="DOCX file actions">
            <button id="open-file" class="example-file-action example-file-primary" type="button" aria-controls="docx-workspace"><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 16V4m-4 4 4-4 4 4M4 16v4h16v-4"/></svg>Upload DOCX</button>
            <input id="docx-file" type="file" accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document" hidden>
            <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 DOCX</button>
          </div>
        </header>
        <p class="comparison-local">Files you open here stay in this browser.</p>
        <output id="status" role="status">Opening the sample agreement…</output>
        <div id="docx-workspace"></div>
        <button id="reset-file" class="comparison-text-action" type="button" disabled>Reset to sample</button>
      </section>
      <section class="comparison-pane" aria-labelledby="markdown-heading">
        <header class="comparison-pane-header">
          <h2 id="markdown-heading">Markdown export</h2>
          <button id="download-markdown" 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 Markdown</button>
        </header>
        <p class="comparison-local">This export leaves out Word’s tracked-change markup and comments. Use the DOCX to continue the review.</p>
        <div class="comparison-preview-state">
          <output id="projection-status" role="status" tabindex="-1">Waiting for the DOCX to open…</output>
          <button id="retry-markdown" class="comparison-text-action" type="button" aria-controls="markdown-preview" hidden>Retry Markdown</button>
        </div>
        <div id="projection" hidden>
          <div id="markdown-preview" role="region" aria-label="Rendered Markdown" tabindex="0"></div>
          <details>
            <summary>View Markdown source</summary>
            <textarea id="markdown-source" aria-label="Markdown source" readonly spellcheck="false"></textarea>
          </details>
        </div>
      </section>
    </div>
    <section id="comparison-findings" class="comparison-findings" aria-labelledby="findings-heading" hidden>
      <h2 id="findings-heading">What changed in Markdown</h2>
      <ul id="projection-loss" hidden></ul>
      <p id="projection-loss-empty" hidden>No changes reported for this preview.</p>
      <details id="projection-diagnostics" hidden>
        <summary>View diagnostic codes</summary>
        <p>SuperDoc reports these codes for the Markdown export. Review annotations are reported separately.</p>
        <ul id="projection-diagnostic-codes" tabindex="0" aria-label="Projection diagnostic codes"></ul>
      </details>
    </section>
  </div>
  <footer><a href="https://www.superdoc.dev/examples/proof-markdown.md" target="_blank" rel="noopener">Read the example source</a></footer>
</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; } }

/* 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; }
```

### examples/proof-markdown/style.css

```css
.comparison-demo {
  --comparison-bg: #f6f9fd;
  --comparison-surface: #fff;
  --comparison-text: #17213a;
  --comparison-muted: #425171;
  --comparison-line: #c9d7e9;
  --comparison-cta: #1849ba;
  --comparison-report: #eaf2ff;
  --comparison-report-accent: #587fbf;
  background: var(--comparison-bg);
  color: var(--comparison-text);
  color-scheme: light;
}
[data-comparison-theme="dark"] .comparison-demo {
  color-scheme: dark;
  --comparison-bg: #122339;
  --comparison-surface: #1b3049;
  --comparison-text: #f1f6fc;
  --comparison-muted: #c1d3e8;
  --comparison-line: #466486;
  --comparison-cta: #b3d0ff;
  --comparison-report: #213959;
  --comparison-report-accent: #8baff5;
  --example-file-surface: #1b3049;
  --example-file-color: #c7dbff;
  --example-file-border: #6485aa;
  --example-file-hover: #274665;
}
.comparison-demo main { display: block; max-width: 90rem; margin: auto; padding: .65rem; }
.comparison-demo footer { margin: 0; padding: .6rem 0 0; border: 0; }
.comparison-demo h2 { margin: 0; color: inherit; font-size: 1.1rem; }
.comparison-demo :is(footer a, summary) { color: var(--comparison-text); text-underline-offset: .2em; }
.comparison-demo :focus-visible { outline: 2px solid var(--comparison-cta); outline-offset: 2px; }
.comparison-pane-header,
.comparison-preview-state {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: .25rem .6rem;
}
.comparison-pane-header {
  padding: 0 0 .5rem;
  border: 0;
  border-bottom: 1px solid var(--comparison-line);
  background: transparent;
}
.comparison-actions { display: flex; flex-wrap: wrap; gap: .375rem; }
.comparison-text-action {
  min-height: 44px;
  padding: .35rem .1rem;
  border: 0;
  background: transparent;
  color: var(--comparison-cta);
  text-decoration: underline;
  text-underline-offset: .2em;
  font-size: .875rem;
  font-weight: 600;
}
.comparison-demo button:disabled { opacity: .6; cursor: default; }
.comparison-local, .comparison-demo #status, #projection-status { color: var(--comparison-muted); font-size: .875rem; }
.comparison-local { margin: .45rem 0 .15rem; }
.comparison-demo #status { display: block; margin-bottom: .45rem; }
.comparison-preview-state output { padding-block: .25rem; }
.comparison-workbench { border: 1px solid var(--comparison-line); border-radius: .75rem; }
.comparison-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.comparison-pane { min-width: 0; padding: .75rem; }
.comparison-pane + .comparison-pane { border-inline-start: 1px solid var(--comparison-line); }
.comparison-demo #docx-workspace { position: relative; min-height: 21rem; }
.comparison-document.staging { position: absolute; inset: 0; visibility: hidden; }
.comparison-document.staging:only-child { position: relative; }
.comparison-toolstrip, .comparison-editor { color-scheme: light; background: #fff; color: #242424; }
.comparison-toolstrip { min-height: 44px; }
.comparison-editor { height: 24rem; overflow: auto; }
#markdown-preview, #markdown-source {
  width: 100%;
  max-height: 22rem;
  overflow: auto;
  overflow-wrap: anywhere;
  box-sizing: border-box;
  padding: .65rem;
  border: 1px solid var(--comparison-line);
  border-radius: .35rem;
  background: var(--comparison-surface);
  color: var(--comparison-text);
}
#markdown-preview {
  overflow-x: hidden;
  overflow-y: auto;
  font-size: 1rem;
  line-height: 1.55;
}
#markdown-preview :is(h1, h2, h3, h4, h5, h6) { margin: .85em 0 .35em; line-height: 1.25; }
#markdown-preview h1 { font-size: 1.35rem; }
#markdown-preview h2 { font-size: 1.16rem; }
#markdown-preview h3 { font-size: 1.03rem; }
#markdown-preview > :first-child { margin-top: 0; }
#markdown-preview :is(p, li) { margin: .45rem 0; }
#markdown-preview :is(ul, ol) { padding-inline-start: 1.3rem; }
#markdown-preview ul { list-style: disc; }
#markdown-preview li { padding: 0; border: 0; }
#markdown-preview .markdown-table-scroll,
#markdown-preview pre { max-inline-size: 100%; overflow-x: auto; margin-block: .65rem; }
#markdown-preview table { border-collapse: collapse; }
#markdown-preview :is(td, th) { padding: .25rem .5rem; border: 1px solid var(--comparison-line); vertical-align: top; }
#markdown-preview pre { padding: .55rem; border: 1px solid var(--comparison-line); border-radius: .35rem; white-space: pre; }
.comparison-findings {
  padding: .85rem .9rem .65rem;
  border-block-start: 1px solid var(--comparison-line);
  border-inline-start: .25rem solid var(--comparison-report-accent);
  border-radius: 0 0 .7rem .7rem;
  background: var(--comparison-report);
  color: var(--comparison-text);
  font-size: .9rem;
}
.comparison-findings h2 { margin-block-end: .5rem; }
.comparison-findings > :is(ul, p, details) { max-inline-size: 75ch; }
.comparison-findings p { margin: 0; }
.comparison-findings ul { margin: 0; padding-inline-start: 1.15rem; list-style: disc; }
.comparison-findings li { padding: 0; border: 0; line-height: 1.45; }
.comparison-findings li + li { margin-top: .38rem; }
.comparison-findings strong { color: var(--comparison-text); }
#projection-diagnostics { font-size: .875rem; color: var(--comparison-muted); }
#projection-diagnostics p { margin: 0 0 .35rem; }
#projection-diagnostic-codes { max-block-size: 12rem; overflow: auto; margin: 0; padding-inline-start: 1.15rem; list-style: disc; }
#projection-diagnostic-codes li { border: 0; padding: .2rem 0; overflow-wrap: anywhere; }
.comparison-demo :is(#projection, #comparison-findings) details summary { min-height: 44px; align-content: center; }
#markdown-source { display: block; min-height: 9rem; resize: vertical; }
.comparison-demo summary { cursor: pointer; padding-block: .65rem; }
@media (max-width: 660px) {
  .comparison-grid { grid-template-columns: minmax(0, 1fr); }
  .comparison-pane + .comparison-pane { border-inline-start: 0; border-block-start: 1px solid var(--comparison-line); }
  .comparison-editor { height: 19rem; }
  #markdown-preview { max-height: 20rem; padding: .75rem; }
  #markdown-preview :is(td, th) { min-inline-size: 7rem; }
}

.comparison-heading { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.comparison-editor .superdoc { --superdoc-caret-color: #242424; }
```

### 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-markdown/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-markdown.zip)
[Download the public sample](https://www.superdoc.dev/samples/markup/vendor-services-markup.docx)
