@open-document/core 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{build-CFL7nhz0.js → build-B0GJXy8I.js} +1 -1
  2. package/dist/{check-pEQh4jJE.js → check-CuDIWsPT.js} +3 -3
  3. package/dist/cli/bin.js +8 -12
  4. package/dist/{config-4nz5NnxW.js → config-CAZ7Z_va.js} +1 -1
  5. package/dist/{context-BH8C-dSW.js → context-PWAh9qbf.js} +1 -1
  6. package/dist/{dev-BCSUczXW.js → dev-CYqppXDI.js} +1 -1
  7. package/dist/{diagram-xlVDekYk.js → diagram-CCaUUnRe.js} +85 -12
  8. package/dist/{export-BQ-GvMsb.js → export-1JtO2OMC.js} +5 -8
  9. package/dist/{import-Daat3L2J.js → import-CsrdBOZ8.js} +2 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +6 -2
  12. package/dist/ops/index.d.ts +2 -3
  13. package/dist/ops/index.js +4 -4
  14. package/dist/{ops-DQfckiyp.js → ops-B2y9BMpk.js} +5 -4
  15. package/dist/{preview-CwCrw-i3.js → preview-DW3PM-JV.js} +1 -1
  16. package/dist/{sdk-C9nl30dW.d.ts → sdk-BqU6mwD_.d.ts} +8 -1
  17. package/dist/{sdk-DhcqZdAw.js → sdk-CqNZzbkz.js} +12 -1
  18. package/dist/vite/index.js +1 -1
  19. package/package.json +1 -1
  20. package/skills/doc-authoring/SKILL.md +6 -3
  21. package/src/app/components/footnote.tsx +6 -1
  22. package/src/app/components/numbering.tsx +1 -0
  23. package/src/app/lib/agent-bridge.ts +13 -0
  24. package/src/app/lib/docx/from-dom.ts +889 -0
  25. package/src/app/lib/docx/ooxml.test.ts +299 -0
  26. package/src/app/lib/docx/ooxml.ts +755 -0
  27. package/src/app/lib/export-docx.ts +225 -0
  28. package/src/app/lib/export-dom.ts +23 -3
  29. package/src/app/lib/export-image.ts +47 -2
  30. package/src/app/lib/export-pdf.ts +6 -0
  31. package/src/app/lib/flow-measure.ts +3 -0
  32. package/src/app/lib/sdk.ts +8 -0
  33. package/src/app/lib/svg-ids.ts +37 -0
  34. package/src/app/routes/doc.tsx +12 -1
  35. package/src/app/styles.css +20 -0
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The document as a .docx — structure Word flows itself, for review that runs
3
+ * on Word: track changes, comments, pasting a section into someone else's
4
+ * template. Page-for-page fidelity is not the aim; Word repaginates the moment
5
+ * anyone types, so what has to survive is the structure.
6
+ *
7
+ * The browser downloads it; the headless exporter writes it to disk through
8
+ * the bridge. Both call `buildDocDocx`, so there is one way to make one.
9
+ */
10
+
11
+ import { createElement } from 'react';
12
+ import { createRoot } from 'react-dom/client';
13
+ import { type DesignSystem, defaultDesign, designToCssVars } from './design';
14
+ import { docxFromPages, lineOf, type PageInfo, type StyleBaseline } from './docx/from-dom';
15
+ import {
16
+ buildDocxParts,
17
+ type DocxModel,
18
+ fontsFor,
19
+ hexColor,
20
+ type Inline,
21
+ type Paragraph,
22
+ PX_TO_HALF_POINTS,
23
+ PX_TO_TWIPS,
24
+ type StyleId,
25
+ } from './docx/ooxml';
26
+ import { downloadBlob, withRenderedPages } from './export-dom';
27
+ import { type DocEntry, type FlowSection, isFlowSection } from './flow';
28
+ import { DocPageProvider } from './page-context';
29
+ import { nextFrame, waitForFonts } from './print-ready';
30
+ import { type DocModule, resolvePageGeometry } from './sdk';
31
+ import type { ExpandedPage } from './use-doc-pages';
32
+
33
+ export type DocxBundle = { filename: string; mimeType: string; bytes: Uint8Array };
34
+
35
+ export const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
36
+
37
+ // Page numbers no document prints, so the footer can be drawn once and every
38
+ // place a number landed found again and handed to Word as a field.
39
+ const PAGE_SENTINEL = 97_531;
40
+ const TOTAL_SENTINEL = 86_420;
41
+
42
+ /** A flow page after the first of its section continues it; everything else starts a sheet. */
43
+ function pageInfo(pages: ExpandedPage[]): PageInfo[] {
44
+ return pages.map((page, at) => {
45
+ const flow = /^f(\d+)-(\d+)$/.exec(page.key);
46
+ const previous = /^f(\d+)-/.exec(pages[at - 1]?.key ?? '');
47
+ return { continues: Boolean(flow && previous && previous[1] === flow[1]) };
48
+ });
49
+ }
50
+
51
+ function firstFamily(stack: string): string {
52
+ return (stack.split(',')[0] ?? '')
53
+ .trim()
54
+ .replace(/^['"]|['"]$/g, '')
55
+ .toLowerCase();
56
+ }
57
+
58
+ function baselines(design: DesignSystem): Record<StyleId, StyleBaseline> {
59
+ const text = hexColor(design.palette.text) ?? '000000';
60
+ const muted = hexColor(design.palette.muted) ?? text;
61
+ const size = (px: number) => Math.round(px * PX_TO_HALF_POINTS);
62
+ const plain = { color: text, bold: false, italic: false };
63
+ const heading = (px: number) => ({
64
+ halfPoints: size(px),
65
+ color: text,
66
+ bold: true,
67
+ italic: false,
68
+ });
69
+ const { typeScale } = design;
70
+ return {
71
+ Normal: { ...plain, halfPoints: size(typeScale.body) },
72
+ ListParagraph: { ...plain, halfPoints: size(typeScale.body) },
73
+ Title: heading(typeScale.title),
74
+ Heading1: heading(typeScale.h1),
75
+ Heading2: heading(typeScale.h2),
76
+ Heading3: heading(typeScale.h3),
77
+ Heading4: heading(Math.max(typeScale.body, (typeScale.h3 + typeScale.body) / 2)),
78
+ Heading5: heading(typeScale.body),
79
+ Heading6: { ...heading(typeScale.body), color: muted },
80
+ Caption: { ...plain, color: muted, halfPoints: size(typeScale.caption) },
81
+ Code: { ...plain, halfPoints: Math.max(12, size(typeScale.body) - 2) },
82
+ Quote: { ...plain, color: muted, italic: true, halfPoints: size(typeScale.body) },
83
+ FootnoteText: { ...plain, color: muted, halfPoints: size(typeScale.caption) },
84
+ TOCHeading: heading(typeScale.h1),
85
+ };
86
+ }
87
+
88
+ /**
89
+ * The first flow section's footer, as a Word footer. It is drawn once with
90
+ * sentinel page numbers, and wherever a sentinel landed the text becomes a
91
+ * PAGE or NUMPAGES field — so Word numbers the pages it lays out, not the ones
92
+ * open-doc did.
93
+ */
94
+ async function footerOf(
95
+ doc: DocModule,
96
+ design: DesignSystem,
97
+ width: number,
98
+ walk: Parameters<typeof lineOf>[1],
99
+ ): Promise<Paragraph | undefined> {
100
+ const section = ((doc.default ?? []) as DocEntry[]).find(
101
+ (entry): entry is FlowSection => isFlowSection(entry) && Boolean(entry.footer),
102
+ );
103
+ const Footer = section?.footer;
104
+ if (!Footer) return undefined;
105
+
106
+ const host = document.createElement('div');
107
+ host.setAttribute('aria-hidden', 'true');
108
+ Object.assign(host.style, { position: 'fixed', left: '-99999px', top: '0', width: `${width}px` });
109
+ for (const [name, value] of Object.entries(designToCssVars(design))) {
110
+ host.style.setProperty(name, value);
111
+ }
112
+ host.style.fontFamily = 'var(--od-font-body)';
113
+ host.style.color = 'var(--od-text)';
114
+ document.body.appendChild(host);
115
+ const root = createRoot(host);
116
+ try {
117
+ root.render(
118
+ createElement(
119
+ DocPageProvider,
120
+ { index: PAGE_SENTINEL - 1, total: TOTAL_SENTINEL },
121
+ createElement(Footer),
122
+ ),
123
+ );
124
+ await nextFrame();
125
+ await waitForFonts();
126
+ await nextFrame();
127
+ const target = host.firstElementChild;
128
+ const line = target ? await lineOf(target, walk) : null;
129
+ if (!line) return undefined;
130
+ const fields = (inlines: Inline[]): Inline[] =>
131
+ inlines.flatMap((inline): Inline[] => {
132
+ if (inline.type !== 'text') return [inline];
133
+ return inline.text
134
+ .split(new RegExp(`(${PAGE_SENTINEL}|${TOTAL_SENTINEL})`))
135
+ .filter((piece) => piece !== '')
136
+ .map(
137
+ (piece): Inline =>
138
+ piece === String(PAGE_SENTINEL)
139
+ ? { type: 'field', instr: 'PAGE', cached: '1' }
140
+ : piece === String(TOTAL_SENTINEL)
141
+ ? { type: 'field', instr: 'NUMPAGES', cached: '1' }
142
+ : { ...inline, text: piece },
143
+ );
144
+ });
145
+ return { ...line, inlines: fields(line.inlines) };
146
+ } finally {
147
+ root.unmount();
148
+ host.remove();
149
+ }
150
+ }
151
+
152
+ export async function buildDocDocx(
153
+ doc: DocModule,
154
+ docId: string,
155
+ pages: ExpandedPage[],
156
+ ): Promise<DocxBundle | null> {
157
+ if (pages.length === 0) return null;
158
+ const geometry = resolvePageGeometry(doc.meta);
159
+ const design = (doc.design as DesignSystem | undefined) ?? defaultDesign;
160
+ const textWidth = geometry.width - design.margin * 2;
161
+ const walk = {
162
+ doc,
163
+ textWidth,
164
+ baselines: baselines(design),
165
+ monoFamilies: [firstFamily(design.fonts.mono)].filter((family) => family !== ''),
166
+ margin: design.margin,
167
+ };
168
+
169
+ const content = await withRenderedPages(pages, geometry, doc, (hosts, container) =>
170
+ docxFromPages(hosts, pageInfo(pages), container, walk),
171
+ );
172
+ const footer = await footerOf(doc, design, textWidth, walk);
173
+
174
+ const size = (px: number) => Math.round(px * PX_TO_HALF_POINTS);
175
+ const text = hexColor(design.palette.text) ?? '000000';
176
+ const model: DocxModel = {
177
+ title: doc.meta?.title ?? docId,
178
+ ...(doc.meta?.author ? { author: doc.meta.author } : {}),
179
+ page: {
180
+ width: geometry.width * PX_TO_TWIPS,
181
+ height: geometry.height * PX_TO_TWIPS,
182
+ landscape: geometry.width > geometry.height,
183
+ margin: design.margin * PX_TO_TWIPS,
184
+ },
185
+ fonts: {
186
+ body: fontsFor(design.fonts.body, 'sans'),
187
+ heading: fontsFor(design.fonts.heading, 'sans'),
188
+ mono: fontsFor(design.fonts.mono, 'mono'),
189
+ },
190
+ sizes: {
191
+ title: size(design.typeScale.title),
192
+ h1: size(design.typeScale.h1),
193
+ h2: size(design.typeScale.h2),
194
+ h3: size(design.typeScale.h3),
195
+ body: size(design.typeScale.body),
196
+ caption: size(design.typeScale.caption),
197
+ },
198
+ colors: {
199
+ text,
200
+ muted: hexColor(design.palette.muted) ?? text,
201
+ accent: hexColor(design.palette.accent) ?? text,
202
+ },
203
+ line: design.leading * design.typeScale.body * PX_TO_TWIPS,
204
+ ...content,
205
+ ...(footer ? { footer } : {}),
206
+ };
207
+
208
+ const parts = buildDocxParts(model);
209
+ const { zipSync, strToU8 } = await import('fflate');
210
+ const tree: Record<string, Uint8Array> = {};
211
+ for (const [name, part] of Object.entries(parts)) {
212
+ tree[name] = typeof part === 'string' ? strToU8(part) : part;
213
+ }
214
+ return { filename: `${docId}.docx`, mimeType: DOCX_MIME, bytes: zipSync(tree) };
215
+ }
216
+
217
+ export async function exportDocAsDocx(
218
+ doc: DocModule,
219
+ docId: string,
220
+ pages: ExpandedPage[],
221
+ ): Promise<void> {
222
+ const bundle = await buildDocDocx(doc, docId, pages);
223
+ if (!bundle) return;
224
+ downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
225
+ }
@@ -12,16 +12,24 @@ import { DocPageProvider } from './page-context';
12
12
  import { nextFrame, waitForFonts, waitForImages } from './print-ready';
13
13
  import { captureScan, restoreScan, scanDocument } from './scan';
14
14
  import type { DocModule, PageGeometry } from './sdk';
15
+ import { scopeSvgIds } from './svg-ids';
15
16
  import type { ExpandedPage } from './use-doc-pages';
16
17
 
17
18
  export const ASSET_EXT_RE =
18
19
  /\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
19
20
 
20
- export async function renderPagesToHtml(
21
+ /**
22
+ * Draws the pages offscreen at true sheet size, waits until they are settled —
23
+ * fonts, images, the numbering scan — hands the page hosts to `visit` while
24
+ * they are still live, and tears everything down after. Exporters that need
25
+ * computed styles (DOCX reads them) visit the live tree; the others serialise.
26
+ */
27
+ export async function withRenderedPages<T>(
21
28
  pages: ExpandedPage[],
22
29
  geometry: PageGeometry,
23
30
  doc: DocModule,
24
- ): Promise<string[]> {
31
+ visit: (hosts: HTMLElement[], container: HTMLElement) => Promise<T> | T,
32
+ ): Promise<T> {
25
33
  const container = document.createElement('div');
26
34
  container.setAttribute('aria-hidden', 'true');
27
35
  Object.assign(container.style, {
@@ -62,14 +70,26 @@ export async function renderPagesToHtml(
62
70
  scanDocument(container, doc.meta);
63
71
  await nextFrame();
64
72
  await nextFrame();
73
+ hosts.forEach((host, i) => {
74
+ scopeSvgIds(host, `export-${i}`);
75
+ });
65
76
 
66
- return hosts.map((host) => host.innerHTML);
77
+ return await visit(hosts, container);
67
78
  } finally {
68
79
  for (const root of roots) root.unmount();
69
80
  container.remove();
70
81
  restoreScan(previousScan);
71
82
  }
72
83
  }
84
+
85
+ export async function renderPagesToHtml(
86
+ pages: ExpandedPage[],
87
+ geometry: PageGeometry,
88
+ doc: DocModule,
89
+ ): Promise<string[]> {
90
+ return withRenderedPages(pages, geometry, doc, (hosts) => hosts.map((host) => host.innerHTML));
91
+ }
92
+
73
93
  export function collectCss(): string {
74
94
  const chunks: string[] = [];
75
95
  for (const sheet of Array.from(document.styleSheets)) {
@@ -19,6 +19,7 @@ import {
19
19
  renderPagesToHtml,
20
20
  toAbsolute,
21
21
  } from './export-dom';
22
+ import { PAGE_ATTR } from './outline';
22
23
  import { type DocModule, type PageGeometry, resolvePageGeometry } from './sdk';
23
24
  import type { ExpandedPage } from './use-doc-pages';
24
25
 
@@ -146,7 +147,9 @@ function blobToDataUrl(blob: Blob): Promise<string> {
146
147
  * The design variables live on the page host, and renderPagesToHtml returns the
147
148
  * host's innerHTML, so they are not in the markup and have to be put back.
148
149
  */
149
- function buildSvg(pageHtml: string, css: string, geometry: PageGeometry, doc: DocModule): string {
150
+ type Box = Pick<PageGeometry, 'width' | 'height'>;
151
+
152
+ function buildSvg(pageHtml: string, css: string, geometry: Box, doc: DocModule): string {
150
153
  const SVG_NS = 'http://www.w3.org/2000/svg';
151
154
  const XHTML_NS = 'http://www.w3.org/1999/xhtml';
152
155
 
@@ -177,7 +180,12 @@ function buildSvg(pageHtml: string, css: string, geometry: PageGeometry, doc: Do
177
180
  style.appendChild(document.createTextNode(css));
178
181
  wrapper.appendChild(style);
179
182
 
183
+ // A page sized by `height: 100%` measures against this box; without a height
184
+ // of its own the page collapses to its content, and whatever it placed
185
+ // against its foot — a footer, a centred closing, a cover's title — moves up.
180
186
  const content = document.createElementNS(XHTML_NS, 'div');
187
+ content.setAttribute('style', 'width:100%;height:100%');
188
+ content.setAttribute(PAGE_ATTR, '');
181
189
  content.innerHTML = pageHtml;
182
190
  wrapper.appendChild(content);
183
191
 
@@ -195,7 +203,7 @@ function buildSvg(pageHtml: string, css: string, geometry: PageGeometry, doc: Do
195
203
  * Verified against Chrome 151 — a plain SVG is clean either way, so the taint
196
204
  * follows the foreignObject and the URL scheme together, not either alone.
197
205
  */
198
- async function rasterise(svg: string, geometry: PageGeometry): Promise<Blob> {
206
+ async function rasterise(svg: string, geometry: Box): Promise<Blob> {
199
207
  const source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
200
208
 
201
209
  const image = new Image();
@@ -224,3 +232,40 @@ async function rasterise(svg: string, geometry: PageGeometry): Promise<Blob> {
224
232
  );
225
233
  });
226
234
  }
235
+
236
+ /**
237
+ * One element as a PNG, through the same `foreignObject` path as a page — for
238
+ * what a DOCX cannot hold as structure: a chart built from boxes, a compiled
239
+ * diagram whose colours are the document's CSS variables. Pulled out of its
240
+ * page, the element would lose the type it inherits, so that goes round it.
241
+ */
242
+ export async function elementToPng(
243
+ el: Element,
244
+ doc: DocModule,
245
+ ): Promise<{ bytes: Uint8Array; width: number; height: number }> {
246
+ const rect = el.getBoundingClientRect();
247
+ const width = Math.max(1, Math.ceil(rect.width));
248
+ const height = Math.max(1, Math.ceil(rect.height));
249
+ const inherited = getComputedStyle(el);
250
+ // Drawn on its own canvas, the element must start at the canvas's corner.
251
+ // Whatever placed it on the page — absolute offsets, a transform, margins —
252
+ // would otherwise put it off the edge, and the picture comes out blank.
253
+ const clone = el.cloneNode(true) as HTMLElement | SVGElement;
254
+ for (const [name, value] of [
255
+ ['position', 'static'],
256
+ ['inset', 'auto'],
257
+ ['margin', '0'],
258
+ ['transform', 'none'],
259
+ ['width', `${width}px`],
260
+ ['height', `${height}px`],
261
+ ]) {
262
+ clone.style.setProperty(name as string, value as string);
263
+ }
264
+ const wrapped =
265
+ `<div style="font-family:${inherited.fontFamily.replace(/"/g, "'")};color:${inherited.color};` +
266
+ `font-size:${inherited.fontSize};line-height:${inherited.lineHeight};width:${width}px">${clone.outerHTML}</div>`;
267
+ const { css, html } = await embedAssets([wrapped], doc);
268
+ const svg = buildSvg(html[0] ?? '', css, { width, height }, doc);
269
+ const blob = await rasterise(svg, { width, height });
270
+ return { bytes: new Uint8Array(await blob.arrayBuffer()), width, height };
271
+ }
@@ -6,6 +6,7 @@ import { DocPageProvider } from './page-context';
6
6
  import { nextFrame, sleep, waitForDataWaitfor, waitForFonts, waitForImages } from './print-ready';
7
7
  import { captureScan, restoreScan, scanDocument } from './scan';
8
8
  import { type DocModule, resolvePageGeometry } from './sdk';
9
+ import { scopeSvgIds } from './svg-ids';
9
10
  import type { ExpandedPage } from './use-doc-pages';
10
11
 
11
12
  export const PRINT_ROOT_ID = 'od-print-root';
@@ -157,6 +158,11 @@ export async function mountPrintCopy(
157
158
  scanDocument(root, doc.meta);
158
159
  await nextFrame();
159
160
  await sleep(50);
161
+ // Last, once React has drawn every page: a page still rendering has no ids
162
+ // to rename yet.
163
+ Array.from(root.children).forEach((host, i) => {
164
+ scopeSvgIds(host, `print-${i}`);
165
+ });
160
166
  } catch (err) {
161
167
  dispose();
162
168
  throw err;
@@ -79,6 +79,9 @@ export async function measureFlowSections(
79
79
 
80
80
  const host = document.createElement('div');
81
81
  host.setAttribute('aria-hidden', 'true');
82
+ // The sheet's own element styles (styles.css) apply here too, so a block
83
+ // measures as it will print.
84
+ host.setAttribute('data-od-measure', '');
82
85
  Object.assign(host.style, {
83
86
  position: 'fixed',
84
87
  left: '-99999px',
@@ -64,6 +64,14 @@ export type FlowSection = {
64
64
  /** What a document's default export may contain: fixed pages, flow sections, or both. */
65
65
  export type DocEntry = DocPage | FlowSection;
66
66
 
67
+ /**
68
+ * Every format `open-doc export` can write. The CLI's `--format`, the MCP
69
+ * `export_document` schema and `ops/layout.ts` all read this tuple, so adding a
70
+ * format is one edit here and its branch in `exportDocument`.
71
+ */
72
+ export const EXPORT_FORMATS = ['pdf', 'html', 'png', 'docx'] as const;
73
+ export type ExportFormat = (typeof EXPORT_FORMATS)[number];
74
+
67
75
  export type DocMeta = {
68
76
  title?: string;
69
77
  subtitle?: string;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A page is drawn more than once — the thumbnail rail, the viewer, the print
3
+ * copy, an export's offscreen copy — and an inline SVG's `id` comes along each
4
+ * time. `url(#glow)` resolves to the *first* element in the document with that
5
+ * id, which is the thumbnail's. When printing hides the rail, the print copy's
6
+ * gradients, clip paths and markers point into a subtree that is not drawn,
7
+ * and they vanish from the PDF. Renaming the ids inside a copy, and every
8
+ * reference to them inside the same copy, keeps each copy pointing at itself.
9
+ */
10
+
11
+ const URL_REF = /url\(\s*(['"]?)#([^'")\s]+)\1\s*\)/g;
12
+
13
+ export function scopeSvgIds(root: Element, suffix: string): void {
14
+ const renamed = new Map<string, string>();
15
+ for (const el of Array.from(root.querySelectorAll('svg [id]'))) {
16
+ const next = `${el.id}--${suffix}`;
17
+ renamed.set(el.id, next);
18
+ el.id = next;
19
+ }
20
+ if (renamed.size === 0) return;
21
+
22
+ for (const el of Array.from(root.querySelectorAll('svg, svg *'))) {
23
+ for (const attr of Array.from(el.attributes)) {
24
+ let value = attr.value;
25
+ if ((attr.localName === 'href' || attr.name === 'xlink:href') && value.startsWith('#')) {
26
+ const target = renamed.get(value.slice(1));
27
+ if (target) value = `#${target}`;
28
+ } else if (value.includes('url(')) {
29
+ value = value.replace(URL_REF, (whole, quote: string, id: string) => {
30
+ const target = renamed.get(id);
31
+ return target ? `url(${quote}#${target}${quote})` : whole;
32
+ });
33
+ }
34
+ if (value !== attr.value) el.setAttributeNS(attr.namespaceURI, attr.name, value);
35
+ }
36
+ }
37
+ }
@@ -8,6 +8,7 @@ import {
8
8
  FileCode2,
9
9
  FileImage,
10
10
  FileText,
11
+ FileType2,
11
12
  Image,
12
13
  LayoutGrid,
13
14
  Loader2,
@@ -35,6 +36,7 @@ import { EditSaveCard } from '../components/panel/edit-save-card';
35
36
  import { ThemeToggle } from '../components/theme-toggle';
36
37
  import { Menu, MenuItem } from '../components/ui/menu';
37
38
  import { useAgentBridge } from '../lib/agent-bridge';
39
+ import { exportDocAsDocx } from '../lib/export-docx';
38
40
  import { exportDocAsHtml } from '../lib/export-html';
39
41
  import { exportDocAsImages } from '../lib/export-image';
40
42
  import { exportDocAsPdf } from '../lib/export-pdf';
@@ -54,13 +56,14 @@ import {
54
56
  writeViewMode,
55
57
  } from '../lib/view-mode';
56
58
 
57
- type DownloadFormat = 'pdf' | 'html' | 'png' | 'svg';
59
+ type DownloadFormat = 'pdf' | 'html' | 'png' | 'svg' | 'docx';
58
60
 
59
61
  const DOWNLOAD_LABEL: Record<DownloadFormat, string> = {
60
62
  pdf: 'PDF',
61
63
  html: 'HTML',
62
64
  png: 'PNG',
63
65
  svg: 'SVG',
66
+ docx: 'Word',
64
67
  };
65
68
 
66
69
  const DOWNLOAD_FORMATS = [
@@ -68,6 +71,12 @@ const DOWNLOAD_FORMATS = [
68
71
  { format: 'html' as const, label: 'HTML', hint: 'Self-contained, printable', icon: FileCode2 },
69
72
  { format: 'png' as const, label: 'PNG', hint: 'Pixels, 2x — for slides and chat', icon: Image },
70
73
  { format: 'svg' as const, label: 'SVG', hint: 'Vector, keeps text as text', icon: FileImage },
74
+ {
75
+ format: 'docx' as const,
76
+ label: 'Word (DOCX)',
77
+ hint: 'Editable — Word lays out the pages',
78
+ icon: FileType2,
79
+ },
71
80
  ];
72
81
 
73
82
  const GUTTER = 48;
@@ -325,6 +334,8 @@ export function Doc() {
325
334
  );
326
335
  } else if (format === 'html') {
327
336
  await exportDocAsHtml(doc, docId, chosen);
337
+ } else if (format === 'docx') {
338
+ await exportDocAsDocx(doc, docId, chosen);
328
339
  } else {
329
340
  await exportDocAsImages(doc, docId, chosen, format, (progress) =>
330
341
  setDownload({ format, percent: progress.percent }),
@@ -91,6 +91,26 @@
91
91
  background-color: rgb(59 130 246 / 0.3);
92
92
  color: inherit;
93
93
  }
94
+ /* Preflight strips every list of its markers and indent, which suits the
95
+ chrome and not the paper: a plain <ul> in a document should print as a
96
+ list. Given back on the sheet and in the measuring host alike — a list
97
+ measured without its indent wraps differently from the one printed — and
98
+ only just outranking preflight, so a document's own list style still wins. */
99
+ :is([data-od-page], [data-od-measure]) :where(ul, ol) {
100
+ padding-inline-start: 1.5em;
101
+ }
102
+ :is([data-od-page], [data-od-measure]) :where(ul) {
103
+ list-style: disc;
104
+ }
105
+ :is([data-od-page], [data-od-measure]) :where(ol) {
106
+ list-style: decimal;
107
+ }
108
+ :is([data-od-page], [data-od-measure]) :where(ul ul, ol ul) {
109
+ list-style: circle;
110
+ }
111
+ :is([data-od-page], [data-od-measure]) :where(ul ul ul, ol ul ul, ul ol ul) {
112
+ list-style: square;
113
+ }
94
114
  /* A heading's space-above is what separates it from the section before it —
95
115
  but at the top of a page that space is just a dent. Strip it there so the
96
116
  first block of every flow page starts flush with the margin. */