@open-document/core 0.8.0 → 0.9.0

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.
@@ -0,0 +1,755 @@
1
+ /*
2
+ * A .docx is a zip of XML parts. This file writes those parts from a small
3
+ * document model — paragraphs, tables, a contents field, footnotes — and knows
4
+ * nothing about the DOM, so everything about the output can be tested in Node.
5
+ *
6
+ * The aim is a document Word flows itself, not a picture of the pages: Word
7
+ * repaginates the moment anyone edits, so the structure (styles, headings,
8
+ * real footnotes, a TOC field) is what survives review, and the page breaks
9
+ * are Word's to decide.
10
+ */
11
+
12
+ export type TextRun = {
13
+ type: 'text';
14
+ text: string;
15
+ /** `false` turns off what the paragraph style turns on — plain words in a heading. */
16
+ bold?: boolean;
17
+ italic?: boolean;
18
+ underline?: boolean;
19
+ strike?: boolean;
20
+ /** `text-transform: uppercase`, kept as a property so the words stay as typed. */
21
+ caps?: boolean;
22
+ /** Letter spacing in twips. */
23
+ tracking?: number;
24
+ mono?: boolean;
25
+ /** `rrggbb`, no hash. */
26
+ color?: string;
27
+ /** Font size in half-points, only when it differs from the paragraph style's. */
28
+ halfPoints?: number;
29
+ vert?: 'superscript' | 'subscript';
30
+ };
31
+
32
+ export type Run =
33
+ | TextRun
34
+ | { type: 'break' }
35
+ | { type: 'tab' }
36
+ /** A field Word computes itself — `PAGE`, `NUMPAGES`. */
37
+ | { type: 'field'; instr: string; cached: string }
38
+ | { type: 'footnote'; id: number }
39
+ /** The note's own number, at the start of its text in footnotes.xml. */
40
+ | { type: 'footnoteRef' }
41
+ | { type: 'image'; image: string };
42
+
43
+ export type Inline = Run | { type: 'link'; href: string; runs: Run[] };
44
+
45
+ export type StyleId =
46
+ | 'Normal'
47
+ | 'Title'
48
+ | 'Heading1'
49
+ | 'Heading2'
50
+ | 'Heading3'
51
+ | 'Heading4'
52
+ | 'Heading5'
53
+ | 'Heading6'
54
+ | 'Caption'
55
+ | 'Code'
56
+ | 'Quote'
57
+ | 'ListParagraph'
58
+ | 'FootnoteText'
59
+ /** A heading kept out of the contents — "Contents" itself, a list heading. */
60
+ | 'TOCHeading';
61
+
62
+ export type Paragraph = {
63
+ type: 'paragraph';
64
+ style?: StyleId;
65
+ align?: 'left' | 'center' | 'right' | 'both';
66
+ inlines: Inline[];
67
+ list?: { numId: number; level: number };
68
+ pageBreakBefore?: boolean;
69
+ keepNext?: boolean;
70
+ /** Twips. */
71
+ spacingBefore?: number;
72
+ spacingAfter?: number;
73
+ /** Left indent, twips, over the style's own. */
74
+ indent?: number;
75
+ /** An exact line height, twips — a spacer that holds open a gap. */
76
+ lineExact?: number;
77
+ /**
78
+ * Ends a section here — whether that section's pages carry the footer.
79
+ * Fixed sheets print their own running lines, so they sit in sections
80
+ * without one.
81
+ */
82
+ sectionEnd?: { footer: boolean };
83
+ /** Right-aligned tab stop, twips from the left margin — a footer's page number. */
84
+ rightTab?: number;
85
+ /** Dots leading to the right tab, as a contents entry has. */
86
+ leader?: boolean;
87
+ /** A bookmark round the paragraph, for a PAGEREF to find its page. */
88
+ bookmark?: string;
89
+ };
90
+
91
+ export type CellBorder = { color: string /** Eighths of a point. */; size: number };
92
+
93
+ export type TableCell = {
94
+ blocks: Paragraph[];
95
+ span?: number;
96
+ borders?: Partial<Record<'top' | 'left' | 'bottom' | 'right', CellBorder>>;
97
+ /** `rrggbb`. */
98
+ fill?: string;
99
+ /** Twips. */
100
+ padding?: { top: number; left: number; bottom: number; right: number };
101
+ };
102
+
103
+ export type Table = {
104
+ type: 'table';
105
+ /** Twips per column. */
106
+ columns: number[];
107
+ rows: Array<{ header: boolean; cells: TableCell[] }>;
108
+ /** Left and right cell margins for the whole table, twips. Pages reads these, not a cell's own. */
109
+ cellMargin?: { left: number; right: number };
110
+ };
111
+
112
+ /** A contents field Word fills in; the entries are what shows until it does. */
113
+ export type TocField = { type: 'toc'; entries: Array<{ text: string; level: number }> };
114
+
115
+ export type Block = Paragraph | Table | TocField;
116
+
117
+ export type ImagePart = {
118
+ name: string;
119
+ ext: 'png' | 'jpeg' | 'gif';
120
+ bytes: Uint8Array;
121
+ /** EMU. */
122
+ width: number;
123
+ height: number;
124
+ };
125
+
126
+ export type FontSpec = {
127
+ ascii: string;
128
+ eastAsia: string;
129
+ kind: 'sans' | 'serif' | 'mono';
130
+ };
131
+
132
+ export type DocxModel = {
133
+ title: string;
134
+ author?: string;
135
+ page: {
136
+ /** Twips. */
137
+ width: number;
138
+ height: number;
139
+ landscape: boolean;
140
+ margin: number;
141
+ };
142
+ fonts: { body: FontSpec; heading: FontSpec; mono: FontSpec };
143
+ /** Half-points. */
144
+ sizes: {
145
+ title: number;
146
+ h1: number;
147
+ h2: number;
148
+ h3: number;
149
+ body: number;
150
+ caption: number;
151
+ };
152
+ /** `rrggbb`. */
153
+ colors: { text: string; muted: string; accent: string };
154
+ /**
155
+ * Body line height in twips, as a minimum. CSS `line-height: 1.55` is 1.55 ×
156
+ * the font size; Word's "multiple" spacing is 1.55 × the font's own single
157
+ * line, which is already taller than its size — about 15% looser than the
158
+ * page. A minimum keeps the page's rhythm and still lets a line holding a
159
+ * picture grow.
160
+ */
161
+ line: number;
162
+ blocks: Block[];
163
+ footnotes: Array<{ id: number; paragraphs: Paragraph[] }>;
164
+ footer?: Paragraph;
165
+ /** Whether the last section carries the footer. Defaults to true. */
166
+ finalFooter?: boolean;
167
+ images: ImagePart[];
168
+ /** One entry per list; ordered lists restart at 1 each. */
169
+ lists: Array<'bullet' | 'decimal'>;
170
+ };
171
+
172
+ export const PX_TO_TWIPS = 15;
173
+ export const PX_TO_EMU = 9525;
174
+ export const PX_TO_HALF_POINTS = 1.5;
175
+
176
+ export function escapeXml(text: string): string {
177
+ return (
178
+ text
179
+ .replace(/&/g, '&amp;')
180
+ .replace(/</g, '&lt;')
181
+ .replace(/>/g, '&gt;')
182
+ .replace(/"/g, '&quot;')
183
+ // XML 1.0 has no way to write most control characters, even escaped.
184
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is being removed
185
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '')
186
+ );
187
+ }
188
+
189
+ const GENERIC = new Set([
190
+ '-apple-system',
191
+ 'blinkmacsystemfont',
192
+ 'system-ui',
193
+ 'ui-sans-serif',
194
+ 'ui-serif',
195
+ 'ui-monospace',
196
+ 'ui-rounded',
197
+ 'sans-serif',
198
+ 'serif',
199
+ 'monospace',
200
+ 'cursive',
201
+ 'fantasy',
202
+ 'inherit',
203
+ ]);
204
+
205
+ const CJK_FONT =
206
+ /noto (sans|serif) (tc|sc|jp|kr|hk|cjk)|pingfang|hiragino|jhenghei|yahei|正黑|明體|楷|source han|思源|yu gothic|yu mincho|meiryo|malgun|ms mincho|ms gothic|heiti|songti|kaiti|biaukai|dfkai|simsun|simhei|mingliu|gulim|batang|lxgw|霞鶩/i;
207
+
208
+ /**
209
+ * A CSS font stack as the two names Word needs. Word has no fallback stack, so
210
+ * the first family that names a real font wins; system aliases mean nothing
211
+ * to it. A CJK family anywhere in the stack becomes the East Asian font — the
212
+ * one Word uses for Han, kana and hangul — because leaving it to Word's
213
+ * default changes glyph widths, and with them every line break.
214
+ */
215
+ export function fontsFor(stack: string, fallback: 'sans' | 'serif' | 'mono'): FontSpec {
216
+ const families = stack
217
+ .split(',')
218
+ .map((family) => family.trim().replace(/^['"]|['"]$/g, ''))
219
+ .filter((family) => family !== '');
220
+ const real = families.filter((family) => !GENERIC.has(family.toLowerCase()));
221
+ const generic =
222
+ families.find((family) => ['serif', 'monospace', 'ui-monospace'].includes(family)) ?? '';
223
+ const kind = generic === 'serif' ? 'serif' : generic.includes('monospace') ? 'mono' : fallback;
224
+ const fallbackFont =
225
+ kind === 'serif' ? 'Times New Roman' : kind === 'mono' ? 'Courier New' : 'Arial';
226
+ const latin = real.find((family) => !CJK_FONT.test(family)) ?? fallbackFont;
227
+ const eastAsia = real.find((family) => CJK_FONT.test(family)) ?? latin;
228
+ return { ascii: latin, eastAsia, kind };
229
+ }
230
+
231
+ const FONT_CLASS = {
232
+ sans: { family: 'swiss', pitch: 'variable', alt: 'Arial' },
233
+ serif: { family: 'roman', pitch: 'variable', alt: 'Times New Roman' },
234
+ mono: { family: 'modern', pitch: 'fixed', alt: 'Courier New' },
235
+ } as const;
236
+
237
+ /**
238
+ * Word has no fallback stack, so a family the reader has not installed — a
239
+ * web font like JetBrains Mono — would otherwise come out in the app's default,
240
+ * which is a serif. The font table says what kind of face each one is and names
241
+ * a stand-in every machine has, so code stays monospaced wherever it opens.
242
+ */
243
+ function fontTableXml(fonts: DocxModel['fonts']): string {
244
+ const entries = new Map<string, FontSpec['kind']>();
245
+ for (const font of [fonts.body, fonts.heading, fonts.mono]) {
246
+ if (!entries.has(font.ascii)) entries.set(font.ascii, font.kind);
247
+ if (!entries.has(font.eastAsia)) entries.set(font.eastAsia, font.kind);
248
+ }
249
+ const body = Array.from(entries, ([name, kind]) => {
250
+ const { family, pitch, alt } = FONT_CLASS[kind];
251
+ const altName = name === alt ? '' : `<w:altName w:val="${alt}"/>`;
252
+ return `<w:font w:name="${escapeXml(name)}">${altName}<w:family w:val="${family}"/><w:pitch w:val="${pitch}"/></w:font>`;
253
+ }).join('');
254
+ return (
255
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
256
+ `<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:fonts>`
257
+ );
258
+ }
259
+
260
+ /** `rgb(22, 24, 29)` or `#16181d` as `16181d`; null for anything transparent. */
261
+ export function hexColor(css: string): string | null {
262
+ const hex = css.trim().match(/^#([0-9a-f]{6})$/i);
263
+ if (hex?.[1]) return hex[1].toLowerCase();
264
+ const short = css.trim().match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
265
+ if (short)
266
+ return `${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`.toLowerCase();
267
+ const rgb = css.match(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,/]+([\d.]+))?/i);
268
+ if (!rgb) return null;
269
+ if (rgb[4] !== undefined && Number(rgb[4]) === 0) return null;
270
+ return [rgb[1], rgb[2], rgb[3]]
271
+ .map((channel) => Number(channel).toString(16).padStart(2, '0'))
272
+ .join('');
273
+ }
274
+
275
+ function fontsXml(font: FontSpec): string {
276
+ return `<w:rFonts w:ascii="${escapeXml(font.ascii)}" w:hAnsi="${escapeXml(font.ascii)}" w:eastAsia="${escapeXml(font.eastAsia)}" w:cs="${escapeXml(font.ascii)}"/>`;
277
+ }
278
+
279
+ type WriteContext = {
280
+ model: DocxModel;
281
+ /** Relationship ids for this part — document and footer each have their own. */
282
+ rels: Array<{ id: string; type: string; target: string; external?: boolean }>;
283
+ imageIds: Map<string, string>;
284
+ drawingId: { value: number };
285
+ bookmarkId?: { value: number };
286
+ /** A section's properties, with or without the footer. */
287
+ section?: (footer: boolean) => string;
288
+ };
289
+
290
+ const REL_HYPERLINK =
291
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink';
292
+ const REL_IMAGE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image';
293
+
294
+ function relFor(ctx: WriteContext, type: string, target: string, external = false): string {
295
+ const existing = ctx.rels.find((rel) => rel.type === type && rel.target === target);
296
+ if (existing) return existing.id;
297
+ const id = `rId${ctx.rels.length + 1}`;
298
+ ctx.rels.push({ id, type, target, ...(external ? { external: true } : {}) });
299
+ return id;
300
+ }
301
+
302
+ function runPropsXml(run: TextRun, ctx: WriteContext): string {
303
+ const parts: string[] = [];
304
+ if (run.mono) parts.push(fontsXml(ctx.model.fonts.mono));
305
+ if (run.bold !== undefined) {
306
+ parts.push(run.bold ? '<w:b/><w:bCs/>' : '<w:b w:val="0"/><w:bCs w:val="0"/>');
307
+ }
308
+ if (run.italic !== undefined) {
309
+ parts.push(run.italic ? '<w:i/><w:iCs/>' : '<w:i w:val="0"/><w:iCs w:val="0"/>');
310
+ }
311
+ if (run.caps) parts.push('<w:caps/>');
312
+ if (run.strike) parts.push('<w:strike/>');
313
+ // Code is not prose; a spelling checker underlines every identifier in it.
314
+ if (run.mono) parts.push('<w:noProof/>');
315
+ if (run.color) parts.push(`<w:color w:val="${run.color}"/>`);
316
+ if (run.tracking) parts.push(`<w:spacing w:val="${Math.round(run.tracking)}"/>`);
317
+ if (run.halfPoints)
318
+ parts.push(`<w:sz w:val="${run.halfPoints}"/><w:szCs w:val="${run.halfPoints}"/>`);
319
+ if (run.underline) parts.push('<w:u w:val="single"/>');
320
+ if (run.vert) parts.push(`<w:vertAlign w:val="${run.vert}"/>`);
321
+ return parts.length > 0 ? `<w:rPr>${parts.join('')}</w:rPr>` : '';
322
+ }
323
+
324
+ function textXml(text: string): string {
325
+ return `<w:t xml:space="preserve">${escapeXml(text)}</w:t>`;
326
+ }
327
+
328
+ function imageXml(name: string, ctx: WriteContext): string {
329
+ const image = ctx.model.images.find((candidate) => candidate.name === name);
330
+ if (!image) return '';
331
+ let rel = ctx.imageIds.get(name);
332
+ if (!rel) {
333
+ rel = relFor(ctx, REL_IMAGE, `media/${image.name}.${image.ext}`);
334
+ ctx.imageIds.set(name, rel);
335
+ }
336
+ const id = ctx.drawingId.value++;
337
+ const extent = `cx="${Math.round(image.width)}" cy="${Math.round(image.height)}"`;
338
+ return (
339
+ '<w:r><w:drawing>' +
340
+ `<wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent ${extent}/>` +
341
+ `<wp:docPr id="${id}" name="Picture ${id}"/>` +
342
+ '<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>' +
343
+ '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
344
+ `<pic:pic><pic:nvPicPr><pic:cNvPr id="${id}" name="${escapeXml(image.name)}"/><pic:cNvPicPr/></pic:nvPicPr>` +
345
+ `<pic:blipFill><a:blip r:embed="${rel}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
346
+ `<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext ${extent}/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>` +
347
+ '</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>'
348
+ );
349
+ }
350
+
351
+ function runXml(run: Run, ctx: WriteContext, linked = false): string {
352
+ switch (run.type) {
353
+ case 'text': {
354
+ const props = runPropsXml(run, ctx);
355
+ const style = linked ? '<w:rStyle w:val="Hyperlink"/>' : '';
356
+ const rPr = style
357
+ ? props
358
+ ? props.replace('<w:rPr>', `<w:rPr>${style}`)
359
+ : `<w:rPr>${style}</w:rPr>`
360
+ : props;
361
+ return `<w:r>${rPr}${textXml(run.text)}</w:r>`;
362
+ }
363
+ case 'break':
364
+ return '<w:r><w:br/></w:r>';
365
+ case 'tab':
366
+ return '<w:r><w:tab/></w:r>';
367
+ case 'field':
368
+ return `<w:fldSimple w:instr=" ${escapeXml(run.instr)} "><w:r>${textXml(run.cached)}</w:r></w:fldSimple>`;
369
+ case 'footnote':
370
+ return `<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteReference w:id="${run.id}"/></w:r>`;
371
+ case 'footnoteRef':
372
+ return '<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteRef/></w:r>';
373
+ case 'image':
374
+ return imageXml(run.image, ctx);
375
+ }
376
+ }
377
+
378
+ function inlineXml(inline: Inline, ctx: WriteContext): string {
379
+ if (inline.type !== 'link') return runXml(inline, ctx);
380
+ const inner = inline.runs.map((run) => runXml(run, ctx, true)).join('');
381
+ // An in-document anchor has no bookmark to point at in Word; its words stay.
382
+ if (inline.href.startsWith('#')) return inner;
383
+ const rel = relFor(ctx, REL_HYPERLINK, inline.href, true);
384
+ return `<w:hyperlink r:id="${rel}">${inner}</w:hyperlink>`;
385
+ }
386
+
387
+ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
388
+ const props: string[] = [];
389
+ if (paragraph.style && paragraph.style !== 'Normal') {
390
+ props.push(`<w:pStyle w:val="${paragraph.style}"/>`);
391
+ }
392
+ if (paragraph.keepNext) props.push('<w:keepNext/>');
393
+ if (paragraph.pageBreakBefore) props.push('<w:pageBreakBefore/>');
394
+ if (paragraph.list) {
395
+ props.push(
396
+ `<w:numPr><w:ilvl w:val="${paragraph.list.level}"/><w:numId w:val="${paragraph.list.numId}"/></w:numPr>`,
397
+ );
398
+ }
399
+ if (paragraph.rightTab !== undefined) {
400
+ const leader = paragraph.leader ? ' w:leader="dot"' : '';
401
+ props.push(
402
+ `<w:tabs><w:tab w:val="right"${leader} w:pos="${Math.round(paragraph.rightTab)}"/></w:tabs>`,
403
+ );
404
+ }
405
+ if (
406
+ paragraph.spacingBefore !== undefined ||
407
+ paragraph.spacingAfter !== undefined ||
408
+ paragraph.lineExact !== undefined
409
+ ) {
410
+ const before =
411
+ paragraph.spacingBefore !== undefined
412
+ ? ` w:before="${Math.round(paragraph.spacingBefore)}"`
413
+ : '';
414
+ const after =
415
+ paragraph.spacingAfter !== undefined
416
+ ? ` w:after="${Math.round(paragraph.spacingAfter)}"`
417
+ : '';
418
+ const line =
419
+ paragraph.lineExact !== undefined
420
+ ? ` w:line="${Math.max(20, Math.round(paragraph.lineExact))}" w:lineRule="exact"`
421
+ : '';
422
+ props.push(`<w:spacing${before}${after}${line}/>`);
423
+ }
424
+ if (paragraph.indent !== undefined)
425
+ props.push(`<w:ind w:left="${Math.round(paragraph.indent)}"/>`);
426
+ if (paragraph.align && paragraph.align !== 'left')
427
+ props.push(`<w:jc w:val="${paragraph.align}"/>`);
428
+ if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd.footer));
429
+ const pPr = props.length > 0 ? `<w:pPr>${props.join('')}</w:pPr>` : '';
430
+ const runs = paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
431
+ if (!paragraph.bookmark) return `<w:p>${pPr}${runs}</w:p>`;
432
+ ctx.bookmarkId ??= { value: 0 };
433
+ const id = ctx.bookmarkId.value++;
434
+ return (
435
+ `<w:p>${pPr}<w:bookmarkStart w:id="${id}" w:name="${escapeXml(paragraph.bookmark)}"/>` +
436
+ `${runs}<w:bookmarkEnd w:id="${id}"/></w:p>`
437
+ );
438
+ }
439
+
440
+ function tableXml(table: Table, ctx: WriteContext): string {
441
+ const total = table.columns.reduce((sum, width) => sum + width, 0);
442
+ const grid = table.columns.map((width) => `<w:gridCol w:w="${Math.round(width)}"/>`).join('');
443
+ const rows = table.rows
444
+ .map((row) => {
445
+ const trPr = row.header
446
+ ? '<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>'
447
+ : '<w:trPr><w:cantSplit/></w:trPr>';
448
+ let column = 0;
449
+ const cells = row.cells
450
+ .map((cell) => {
451
+ const span = cell.span ?? 1;
452
+ const width = table.columns
453
+ .slice(column, column + span)
454
+ .reduce((sum, value) => sum + value, 0);
455
+ column += span;
456
+ const props: string[] = [`<w:tcW w:w="${Math.round(width)}" w:type="dxa"/>`];
457
+ if (span > 1) props.push(`<w:gridSpan w:val="${span}"/>`);
458
+ const sides = (['top', 'left', 'bottom', 'right'] as const)
459
+ .map((side) => {
460
+ const border = cell.borders?.[side];
461
+ return border
462
+ ? `<w:${side} w:val="single" w:sz="${border.size}" w:space="0" w:color="${border.color}"/>`
463
+ : `<w:${side} w:val="nil"/>`;
464
+ })
465
+ .join('');
466
+ props.push(`<w:tcBorders>${sides}</w:tcBorders>`);
467
+ if (cell.fill) props.push(`<w:shd w:val="clear" w:color="auto" w:fill="${cell.fill}"/>`);
468
+ if (cell.padding) {
469
+ const { top, left, bottom, right } = cell.padding;
470
+ props.push(
471
+ `<w:tcMar><w:top w:w="${Math.round(top)}" w:type="dxa"/><w:left w:w="${Math.round(left)}" w:type="dxa"/><w:bottom w:w="${Math.round(bottom)}" w:type="dxa"/><w:right w:w="${Math.round(right)}" w:type="dxa"/></w:tcMar>`,
472
+ );
473
+ }
474
+ // A cell must end in a paragraph, even an empty one.
475
+ const body =
476
+ cell.blocks.length > 0
477
+ ? cell.blocks.map((block) => paragraphXml(block, ctx)).join('')
478
+ : '<w:p/>';
479
+ return `<w:tc><w:tcPr>${props.join('')}</w:tcPr>${body}</w:tc>`;
480
+ })
481
+ .join('');
482
+ return `<w:tr>${trPr}${cells}</w:tr>`;
483
+ })
484
+ .join('');
485
+ return (
486
+ `<w:tbl><w:tblPr><w:tblW w:w="${Math.round(total)}" w:type="dxa"/><w:tblLayout w:type="fixed"/>` +
487
+ `<w:tblCellMar><w:left w:w="${Math.round(table.cellMargin?.left ?? 0)}" w:type="dxa"/><w:right w:w="${Math.round(table.cellMargin?.right ?? 0)}" w:type="dxa"/></w:tblCellMar></w:tblPr>` +
488
+ `<w:tblGrid>${grid}</w:tblGrid>${rows}</w:tbl>` +
489
+ // Word joins two tables that touch; a paragraph keeps them apart.
490
+ '<w:p><w:pPr><w:spacing w:before="0" w:after="0"/></w:pPr></w:p>'
491
+ );
492
+ }
493
+
494
+ function tocXml(toc: TocField): string {
495
+ const begin =
496
+ '<w:p><w:r><w:fldChar w:fldCharType="begin" w:dirty="true"/></w:r>' +
497
+ '<w:r><w:instrText xml:space="preserve"> TOC \\o "1-3" \\h \\z \\u </w:instrText></w:r>' +
498
+ '<w:r><w:fldChar w:fldCharType="separate"/></w:r></w:p>';
499
+ const entries = toc.entries
500
+ .map(
501
+ (entry) =>
502
+ `<w:p><w:pPr><w:pStyle w:val="TOC${Math.min(3, Math.max(1, entry.level))}"/></w:pPr><w:r>${textXml(entry.text)}</w:r></w:p>`,
503
+ )
504
+ .join('');
505
+ return `${begin}${entries}<w:p><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>`;
506
+ }
507
+
508
+ function blockXml(block: Block, ctx: WriteContext): string {
509
+ if (block.type === 'paragraph') return paragraphXml(block, ctx);
510
+ if (block.type === 'table') return tableXml(block, ctx);
511
+ return tocXml(block);
512
+ }
513
+
514
+ const NS =
515
+ 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
516
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
517
+ 'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
518
+ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
519
+ 'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"';
520
+
521
+ const XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
522
+
523
+ function relsXml(rels: WriteContext['rels']): string {
524
+ const body = rels
525
+ .map(
526
+ (rel) =>
527
+ `<Relationship Id="${rel.id}" Type="${rel.type}" Target="${escapeXml(rel.target)}"${rel.external ? ' TargetMode="External"' : ''}/>`,
528
+ )
529
+ .join('');
530
+ return `${XML_HEAD}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${body}</Relationships>`;
531
+ }
532
+
533
+ function stylesXml(model: DocxModel): string {
534
+ const { fonts, sizes, colors } = model;
535
+ const heading = (id: string, name: string, size: number, level: number, color = colors.text) =>
536
+ `<w:style w:type="paragraph" w:styleId="${id}"><w:name w:val="${name}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="9"/><w:qFormat/>` +
537
+ `<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before="240" w:after="120" w:line="240" w:lineRule="auto"/><w:outlineLvl w:val="${level}"/></w:pPr>` +
538
+ `<w:rPr>${fontsXml(fonts.heading)}<w:b/><w:bCs/><w:color w:val="${color}"/><w:sz w:val="${size}"/><w:szCs w:val="${size}"/></w:rPr></w:style>`;
539
+ const h4 = Math.max(sizes.body, Math.round((sizes.h3 + sizes.body) / 2));
540
+ // Page numbers sit on a right tab at the text block's edge, led by dots — the
541
+ // shape the contents has on the page, and Word's own.
542
+ const textWidth = Math.round(model.page.width - model.page.margin * 2);
543
+ const toc = (level: number) =>
544
+ `<w:style w:type="paragraph" w:styleId="TOC${level}"><w:name w:val="toc ${level}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="39"/><w:pPr><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="${textWidth}"/></w:tabs><w:spacing w:after="60"/><w:ind w:left="${(level - 1) * 240}"/></w:pPr></w:style>`;
545
+ return (
546
+ `${XML_HEAD}<w:styles ${NS}>` +
547
+ `<w:docDefaults><w:rPrDefault><w:rPr>${fontsXml(fonts.body)}<w:color w:val="${colors.text}"/><w:sz w:val="${sizes.body}"/><w:szCs w:val="${sizes.body}"/></w:rPr></w:rPrDefault>` +
548
+ `<w:pPrDefault><w:pPr><w:spacing w:after="160" w:line="${Math.round(model.line)}" w:lineRule="atLeast"/></w:pPr></w:pPrDefault></w:docDefaults>` +
549
+ '<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>' +
550
+ '<w:style w:type="character" w:default="1" w:styleId="DefaultParagraphFont"><w:name w:val="Default Paragraph Font"/><w:uiPriority w:val="1"/><w:semiHidden/></w:style>' +
551
+ `<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="240" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr>${fontsXml(fonts.heading)}<w:b/><w:sz w:val="${sizes.title}"/><w:szCs w:val="${sizes.title}"/></w:rPr></w:style>` +
552
+ heading('Heading1', 'heading 1', sizes.h1, 0) +
553
+ heading('Heading2', 'heading 2', sizes.h2, 1) +
554
+ heading('Heading3', 'heading 3', sizes.h3, 2) +
555
+ heading('Heading4', 'heading 4', h4, 3) +
556
+ heading('Heading5', 'heading 5', sizes.body, 4) +
557
+ heading('Heading6', 'heading 6', sizes.body, 5, colors.muted) +
558
+ `<w:style w:type="paragraph" w:styleId="Caption"><w:name w:val="caption"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:before="60" w:after="200"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
559
+ `<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr>${fontsXml(fonts.mono)}<w:noProof/><w:sz w:val="${Math.max(12, sizes.body - 2)}"/></w:rPr></w:style>` +
560
+ `<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:ind w:left="720"/></w:pPr><w:rPr><w:i/><w:color w:val="${colors.muted}"/></w:rPr></w:style>` +
561
+ '<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="80"/><w:ind w:left="720"/><w:contextualSpacing/></w:pPr></w:style>' +
562
+ `<w:style w:type="paragraph" w:styleId="FootnoteText"><w:name w:val="footnote text"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
563
+ '<w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style>' +
564
+ `<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="${colors.accent}"/><w:u w:val="single"/></w:rPr></w:style>` +
565
+ `<w:style w:type="paragraph" w:styleId="Footer"><w:name w:val="footer"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
566
+ `<w:style w:type="paragraph" w:styleId="TOCHeading"><w:name w:val="TOC Heading"/><w:basedOn w:val="Heading1"/><w:next w:val="Normal"/><w:pPr><w:outlineLvl w:val="9"/></w:pPr></w:style>` +
567
+ toc(1) +
568
+ toc(2) +
569
+ toc(3) +
570
+ '</w:styles>'
571
+ );
572
+ }
573
+
574
+ function numberingXml(model: DocxModel): string {
575
+ const levels = (kind: 'bullet' | 'decimal') =>
576
+ Array.from({ length: 9 }, (_, level) => {
577
+ const text = kind === 'bullet' ? ['•', '◦', '▪'][level % 3] : `%${level + 1}.`;
578
+ const format =
579
+ kind === 'bullet' ? 'bullet' : ['decimal', 'lowerLetter', 'lowerRoman'][level % 3];
580
+ return (
581
+ `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="${format}"/><w:lvlText w:val="${text}"/><w:lvlJc w:val="left"/>` +
582
+ `<w:pPr><w:ind w:left="${720 + level * 360}" w:hanging="360"/></w:pPr></w:lvl>`
583
+ );
584
+ }).join('');
585
+ const abstracts =
586
+ `<w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>${levels('bullet')}</w:abstractNum>` +
587
+ `<w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>${levels('decimal')}</w:abstractNum>`;
588
+ // One num per list, so each ordered list counts from 1 on its own.
589
+ const nums = model.lists
590
+ .map(
591
+ (kind, index) =>
592
+ `<w:num w:numId="${index + 1}"><w:abstractNumId w:val="${kind === 'bullet' ? 0 : 1}"/>` +
593
+ (kind === 'decimal'
594
+ ? '<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride>'
595
+ : '') +
596
+ '</w:num>',
597
+ )
598
+ .join('');
599
+ return `${XML_HEAD}<w:numbering ${NS}>${abstracts}${nums}</w:numbering>`;
600
+ }
601
+
602
+ /** Every part of the package, keyed by its path inside the zip. */
603
+ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8Array> {
604
+ const drawingId = { value: 1 };
605
+
606
+ const docCtx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
607
+ const fixedRels = [
608
+ ['http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', 'styles.xml'],
609
+ [
610
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings',
611
+ 'settings.xml',
612
+ ],
613
+ [
614
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes',
615
+ 'footnotes.xml',
616
+ ],
617
+ [
618
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering',
619
+ 'numbering.xml',
620
+ ],
621
+ [
622
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable',
623
+ 'fontTable.xml',
624
+ ],
625
+ ] as const;
626
+ for (const [type, target] of fixedRels) relFor(docCtx, type, target);
627
+ const REL_FOOTER = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer';
628
+ const footerRel = model.footer ? relFor(docCtx, REL_FOOTER, 'footer1.xml') : null;
629
+ // A section with no footer reference inherits the one before it, so a
630
+ // section meant to have none points at an empty footer instead.
631
+ const bareFooter =
632
+ footerRel &&
633
+ (model.finalFooter === false ||
634
+ model.blocks.some(
635
+ (block) => block.type === 'paragraph' && block.sectionEnd?.footer === false,
636
+ ));
637
+ const bareRel = bareFooter ? relFor(docCtx, REL_FOOTER, 'footer2.xml') : null;
638
+
639
+ const { page } = model;
640
+ const margin = Math.round(page.margin);
641
+ docCtx.section = (footer) => {
642
+ const rel = footer ? footerRel : bareRel;
643
+ return (
644
+ '<w:sectPr>' +
645
+ (rel ? `<w:footerReference w:type="default" r:id="${rel}"/>` : '') +
646
+ `<w:pgSz w:w="${Math.round(page.width)}" w:h="${Math.round(page.height)}"${page.landscape ? ' w:orient="landscape"' : ''}/>` +
647
+ `<w:pgMar w:top="${margin}" w:right="${margin}" w:bottom="${margin}" w:left="${margin}" w:header="${Math.round(margin / 2)}" w:footer="${Math.round(margin / 2)}" w:gutter="0"/>` +
648
+ '</w:sectPr>'
649
+ );
650
+ };
651
+ const body = model.blocks.map((block) => blockXml(block, docCtx)).join('');
652
+ const sectPr = docCtx.section(model.finalFooter !== false);
653
+ const documentXml = `${XML_HEAD}<w:document ${NS}><w:body>${body}${sectPr}</w:body></w:document>`;
654
+
655
+ // Footnotes and the footer are parts of their own, with their own rels.
656
+ const noteCtx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
657
+ const notes = model.footnotes
658
+ .map((note) => {
659
+ const paragraphs = note.paragraphs.map((paragraph, index) =>
660
+ paragraphXml(
661
+ {
662
+ ...paragraph,
663
+ style: 'FootnoteText',
664
+ inlines:
665
+ index === 0
666
+ ? [{ type: 'footnoteRef' }, { type: 'text', text: ' ' }, ...paragraph.inlines]
667
+ : paragraph.inlines,
668
+ },
669
+ noteCtx,
670
+ ),
671
+ );
672
+ return `<w:footnote w:id="${note.id}">${paragraphs.join('')}</w:footnote>`;
673
+ })
674
+ .join('');
675
+ const footnotesXml =
676
+ `${XML_HEAD}<w:footnotes ${NS}>` +
677
+ '<w:footnote w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:footnote>' +
678
+ '<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>' +
679
+ `${notes}</w:footnotes>`;
680
+
681
+ const footerCtx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
682
+ const footerXml = model.footer
683
+ ? `${XML_HEAD}<w:ftr ${NS}>${paragraphXml({ ...model.footer, style: model.footer.style ?? ('Footer' as StyleId) }, footerCtx)}</w:ftr>`
684
+ : null;
685
+
686
+ const settingsXml =
687
+ `${XML_HEAD}<w:settings ${NS}>` +
688
+ // Word reads settings in schema order and calls the file damaged when an
689
+ // element is out of place: updateFields belongs after the spacing control.
690
+ '<w:defaultTabStop w:val="720"/><w:characterSpacingControl w:val="compressPunctuation"/>' +
691
+ // The contents field is written with the entries it had on screen; Word
692
+ // brings the page numbers up to date as it opens the file.
693
+ '<w:updateFields w:val="true"/>' +
694
+ '<w:footnotePr><w:footnote w:id="-1"/><w:footnote w:id="0"/></w:footnotePr>' +
695
+ '<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat>' +
696
+ '</w:settings>';
697
+
698
+ const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
699
+ const coreXml =
700
+ `${XML_HEAD}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">` +
701
+ `<dc:title>${escapeXml(model.title)}</dc:title>` +
702
+ (model.author ? `<dc:creator>${escapeXml(model.author)}</dc:creator>` : '') +
703
+ `<dcterms:created xsi:type="dcterms:W3CDTF">${now}</dcterms:created>` +
704
+ `<dcterms:modified xsi:type="dcterms:W3CDTF">${now}</dcterms:modified>` +
705
+ '</cp:coreProperties>';
706
+
707
+ const imageTypes = [...new Set(model.images.map((image) => image.ext))]
708
+ .map((ext) => `<Default Extension="${ext}" ContentType="image/${ext}"/>`)
709
+ .join('');
710
+ const contentTypes =
711
+ `${XML_HEAD}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
712
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
713
+ `<Default Extension="xml" ContentType="application/xml"/>${imageTypes}` +
714
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
715
+ '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
716
+ '<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>' +
717
+ '<Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/>' +
718
+ '<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>' +
719
+ '<Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/>' +
720
+ (footerXml
721
+ ? '<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>'
722
+ : '') +
723
+ (bareRel
724
+ ? '<Override PartName="/word/footer2.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>'
725
+ : '') +
726
+ '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>' +
727
+ '</Types>';
728
+
729
+ const packageRels =
730
+ `${XML_HEAD}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
731
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
732
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>' +
733
+ '</Relationships>';
734
+
735
+ const parts: Record<string, string | Uint8Array> = {
736
+ '[Content_Types].xml': contentTypes,
737
+ '_rels/.rels': packageRels,
738
+ 'docProps/core.xml': coreXml,
739
+ 'word/document.xml': documentXml,
740
+ 'word/_rels/document.xml.rels': relsXml(docCtx.rels),
741
+ 'word/styles.xml': stylesXml(model),
742
+ 'word/settings.xml': settingsXml,
743
+ 'word/numbering.xml': numberingXml(model),
744
+ 'word/fontTable.xml': fontTableXml(model.fonts),
745
+ 'word/footnotes.xml': footnotesXml,
746
+ };
747
+ if (noteCtx.rels.length > 0) parts['word/_rels/footnotes.xml.rels'] = relsXml(noteCtx.rels);
748
+ if (footerXml) {
749
+ parts['word/footer1.xml'] = footerXml;
750
+ if (footerCtx.rels.length > 0) parts['word/_rels/footer1.xml.rels'] = relsXml(footerCtx.rels);
751
+ }
752
+ if (bareRel) parts['word/footer2.xml'] = `${XML_HEAD}<w:ftr ${NS}><w:p/></w:ftr>`;
753
+ for (const image of model.images) parts[`word/media/${image.name}.${image.ext}`] = image.bytes;
754
+ return parts;
755
+ }