@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.
- package/dist/{build-CFL7nhz0.js → build-B0GJXy8I.js} +1 -1
- package/dist/{check-pEQh4jJE.js → check-CuDIWsPT.js} +3 -3
- package/dist/cli/bin.js +8 -12
- package/dist/{config-4nz5NnxW.js → config-CAZ7Z_va.js} +1 -1
- package/dist/{context-BH8C-dSW.js → context-PWAh9qbf.js} +1 -1
- package/dist/{dev-BCSUczXW.js → dev-CYqppXDI.js} +1 -1
- package/dist/{diagram-xlVDekYk.js → diagram-CCaUUnRe.js} +85 -12
- package/dist/{export-BQ-GvMsb.js → export-1JtO2OMC.js} +5 -8
- package/dist/{import-Daat3L2J.js → import-CsrdBOZ8.js} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -2
- package/dist/ops/index.d.ts +2 -3
- package/dist/ops/index.js +4 -4
- package/dist/{ops-DQfckiyp.js → ops-B2y9BMpk.js} +5 -4
- package/dist/{preview-CwCrw-i3.js → preview-DW3PM-JV.js} +1 -1
- package/dist/{sdk-C9nl30dW.d.ts → sdk-BqU6mwD_.d.ts} +8 -1
- package/dist/{sdk-DhcqZdAw.js → sdk-CqNZzbkz.js} +12 -1
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
- package/skills/doc-authoring/SKILL.md +6 -3
- package/src/app/components/footnote.tsx +6 -1
- package/src/app/components/numbering.tsx +1 -0
- package/src/app/lib/agent-bridge.ts +13 -0
- package/src/app/lib/docx/from-dom.ts +889 -0
- package/src/app/lib/docx/ooxml.test.ts +299 -0
- package/src/app/lib/docx/ooxml.ts +755 -0
- package/src/app/lib/export-docx.ts +225 -0
- package/src/app/lib/export-dom.ts +23 -3
- package/src/app/lib/export-image.ts +47 -2
- package/src/app/lib/export-pdf.ts +6 -0
- package/src/app/lib/flow-measure.ts +3 -0
- package/src/app/lib/sdk.ts +8 -0
- package/src/app/lib/svg-ids.ts +37 -0
- package/src/app/routes/doc.tsx +12 -1
- package/src/app/styles.css +20 -0
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The rendered pages, read back as a document Word can flow.
|
|
3
|
+
*
|
|
4
|
+
* This works on the offscreen print copy at true sheet size, the same tree the
|
|
5
|
+
* PDF and HTML exporters serialise, and reads *computed* styles rather than
|
|
6
|
+
* tags: documents here are styled inline, so a heading is bold because of a
|
|
7
|
+
* `fontWeight` in a style object, not because it is an `<h1>`. The tags still
|
|
8
|
+
* decide structure — headings, tables, lists — because that is what Word's
|
|
9
|
+
* navigation, table tools and numbering work from.
|
|
10
|
+
*
|
|
11
|
+
* What has no structure to give — a chart drawn with boxes, a compiled diagram
|
|
12
|
+
* — is drawn to a PNG and placed as a picture: it cannot be edited in Word,
|
|
13
|
+
* but it is there, and nothing around it has to be retyped.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { FLOW_BLOCK_ATTR } from '../../components/flow-page';
|
|
17
|
+
import { FOOTNOTE_ID_ATTR } from '../../components/footnote';
|
|
18
|
+
import { elementToPng } from '../export-image';
|
|
19
|
+
import { LABEL_ATTR, LABEL_ID_ATTR } from '../labels';
|
|
20
|
+
import type { DocModule } from '../sdk';
|
|
21
|
+
import {
|
|
22
|
+
type Block,
|
|
23
|
+
hexColor,
|
|
24
|
+
type ImagePart,
|
|
25
|
+
type Inline,
|
|
26
|
+
type Paragraph,
|
|
27
|
+
PX_TO_EMU,
|
|
28
|
+
PX_TO_HALF_POINTS,
|
|
29
|
+
PX_TO_TWIPS,
|
|
30
|
+
type Run,
|
|
31
|
+
type StyleId,
|
|
32
|
+
type Table,
|
|
33
|
+
type TableCell,
|
|
34
|
+
type TextRun,
|
|
35
|
+
} from './ooxml';
|
|
36
|
+
|
|
37
|
+
/** What each Word style already says, so a run only carries what differs. */
|
|
38
|
+
export type StyleBaseline = { halfPoints: number; color: string; bold: boolean; italic: boolean };
|
|
39
|
+
|
|
40
|
+
export type WalkOptions = {
|
|
41
|
+
doc: DocModule;
|
|
42
|
+
/** Width of the text block, px — images are scaled to fit it. */
|
|
43
|
+
textWidth: number;
|
|
44
|
+
baselines: Record<StyleId, StyleBaseline>;
|
|
45
|
+
/** Lower-cased family names that mean "set in the mono font". */
|
|
46
|
+
monoFamilies: string[];
|
|
47
|
+
/** The page margin Word's section uses, px. */
|
|
48
|
+
margin: number;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type PageInfo = {
|
|
52
|
+
/** A flow page after the first of its section continues it — no break before. */
|
|
53
|
+
continues: boolean;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type WalkResult = {
|
|
57
|
+
blocks: Block[];
|
|
58
|
+
footnotes: Array<{ id: number; paragraphs: Paragraph[] }>;
|
|
59
|
+
images: ImagePart[];
|
|
60
|
+
lists: Array<'bullet' | 'decimal'>;
|
|
61
|
+
finalFooter: boolean;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
type Ctx = WalkOptions & {
|
|
65
|
+
images: ImagePart[];
|
|
66
|
+
lists: Array<'bullet' | 'decimal'>;
|
|
67
|
+
/** Note id on the page → Word's numeric id, in order of first reference. */
|
|
68
|
+
notes: Map<string, number>;
|
|
69
|
+
container: HTMLElement;
|
|
70
|
+
page: { top: number; bottom: number; fixed: boolean; first: boolean };
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const BLOCK_TAGS = new Set([
|
|
74
|
+
'ADDRESS',
|
|
75
|
+
'ARTICLE',
|
|
76
|
+
'ASIDE',
|
|
77
|
+
'BLOCKQUOTE',
|
|
78
|
+
'DIV',
|
|
79
|
+
'DL',
|
|
80
|
+
'FIELDSET',
|
|
81
|
+
'FIGCAPTION',
|
|
82
|
+
'FIGURE',
|
|
83
|
+
'FOOTER',
|
|
84
|
+
'FORM',
|
|
85
|
+
'H1',
|
|
86
|
+
'H2',
|
|
87
|
+
'H3',
|
|
88
|
+
'H4',
|
|
89
|
+
'H5',
|
|
90
|
+
'H6',
|
|
91
|
+
'HEADER',
|
|
92
|
+
'HR',
|
|
93
|
+
'LI',
|
|
94
|
+
'MAIN',
|
|
95
|
+
'NAV',
|
|
96
|
+
'OL',
|
|
97
|
+
'P',
|
|
98
|
+
'PRE',
|
|
99
|
+
'SECTION',
|
|
100
|
+
'TABLE',
|
|
101
|
+
'UL',
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
const INLINE_DISPLAYS = new Set([
|
|
105
|
+
'inline',
|
|
106
|
+
'inline-block',
|
|
107
|
+
'inline-flex',
|
|
108
|
+
'inline-grid',
|
|
109
|
+
'contents',
|
|
110
|
+
]);
|
|
111
|
+
|
|
112
|
+
const STRUCTURE = 'p,h1,h2,h3,h4,h5,h6,table,ul,ol,pre,blockquote';
|
|
113
|
+
|
|
114
|
+
/** Where each block sat on its sheet, for fixed pages whose layout is by position. */
|
|
115
|
+
const placed = new WeakMap<Block, { top: number; bottom: number }>();
|
|
116
|
+
|
|
117
|
+
function place(block: Block, box: { top: number; bottom: number }) {
|
|
118
|
+
if (!placed.has(block)) placed.set(block, { top: box.top, bottom: box.bottom });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isHidden(el: Element): boolean {
|
|
122
|
+
if (el.getAttribute('aria-hidden') === 'true') return true;
|
|
123
|
+
const style = getComputedStyle(el);
|
|
124
|
+
return style.display === 'none' || style.visibility === 'hidden';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A fixed page draws its own running header and footer, as absolutely placed
|
|
129
|
+
* short lines at the sheet's top or bottom edge. Word has headers and footers
|
|
130
|
+
* of its own, so these would otherwise repeat as body text on every page.
|
|
131
|
+
*/
|
|
132
|
+
function isRunningLine(el: Element, ctx: Ctx): boolean {
|
|
133
|
+
if (!ctx.page.fixed) return false;
|
|
134
|
+
const position = getComputedStyle(el).position;
|
|
135
|
+
if (position !== 'absolute' && position !== 'fixed') return false;
|
|
136
|
+
// A running line is words. A logo placed at the top of a cover is the cover.
|
|
137
|
+
const text = (el.textContent ?? '').trim();
|
|
138
|
+
if (text === '' || text.length > 120) return false;
|
|
139
|
+
const rect = el.getBoundingClientRect();
|
|
140
|
+
const height = ctx.page.bottom - ctx.page.top;
|
|
141
|
+
return rect.bottom <= ctx.page.top + height * 0.12 || rect.top >= ctx.page.bottom - height * 0.12;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function skip(el: Element, ctx: Ctx): boolean {
|
|
145
|
+
return el.hasAttribute('data-od-footnotes') || isHidden(el) || isRunningLine(el, ctx);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function isBlock(el: Element): boolean {
|
|
149
|
+
if (el instanceof SVGElement) return false;
|
|
150
|
+
if (BLOCK_TAGS.has(el.tagName)) return !INLINE_DISPLAYS.has(getComputedStyle(el).display);
|
|
151
|
+
return !INLINE_DISPLAYS.has(getComputedStyle(el).display);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function hasBlockChild(el: Element, ctx: Ctx): boolean {
|
|
155
|
+
return Array.from(el.children).some((child) => !skip(child, ctx) && isBlock(child));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function align(el: Element): Paragraph['align'] {
|
|
159
|
+
const value = getComputedStyle(el).textAlign;
|
|
160
|
+
if (value === 'center') return 'center';
|
|
161
|
+
if (value === 'right' || value === 'end') return 'right';
|
|
162
|
+
if (value === 'justify') return 'both';
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function spacing(el: Element): Pick<Paragraph, 'spacingBefore' | 'spacingAfter'> {
|
|
167
|
+
const style = getComputedStyle(el);
|
|
168
|
+
return {
|
|
169
|
+
spacingBefore: (Number.parseFloat(style.marginTop) || 0) * PX_TO_TWIPS,
|
|
170
|
+
spacingAfter: (Number.parseFloat(style.marginBottom) || 0) * PX_TO_TWIPS,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// Inline content
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
function textRun(
|
|
179
|
+
text: string,
|
|
180
|
+
host: Element,
|
|
181
|
+
base: StyleBaseline,
|
|
182
|
+
ctx: Ctx,
|
|
183
|
+
linked: boolean,
|
|
184
|
+
): TextRun {
|
|
185
|
+
const style = getComputedStyle(host);
|
|
186
|
+
const run: TextRun = { type: 'text', text };
|
|
187
|
+
const weight = Number.parseInt(style.fontWeight, 10) || 400;
|
|
188
|
+
const bold = weight >= 600;
|
|
189
|
+
if (bold !== base.bold) run.bold = bold;
|
|
190
|
+
const italic = style.fontStyle === 'italic' || style.fontStyle.startsWith('oblique');
|
|
191
|
+
if (italic !== base.italic) run.italic = italic;
|
|
192
|
+
const decoration = style.textDecorationLine;
|
|
193
|
+
if (!linked && decoration.includes('underline')) run.underline = true;
|
|
194
|
+
if (decoration.includes('line-through')) run.strike = true;
|
|
195
|
+
if (style.textTransform === 'uppercase') run.caps = true;
|
|
196
|
+
const tracking = Number.parseFloat(style.letterSpacing);
|
|
197
|
+
if (tracking) run.tracking = tracking * PX_TO_TWIPS;
|
|
198
|
+
const family = style.fontFamily.toLowerCase();
|
|
199
|
+
if (family.includes('monospace') || ctx.monoFamilies.some((mono) => family.includes(mono))) {
|
|
200
|
+
run.mono = true;
|
|
201
|
+
}
|
|
202
|
+
const color = hexColor(style.color);
|
|
203
|
+
if (!linked && color && color !== base.color) run.color = color;
|
|
204
|
+
const halfPoints = Math.round((Number.parseFloat(style.fontSize) || 0) * PX_TO_HALF_POINTS);
|
|
205
|
+
if (halfPoints > 0 && Math.abs(halfPoints - base.halfPoints) >= 1) run.halfPoints = halfPoints;
|
|
206
|
+
const vertical = style.verticalAlign;
|
|
207
|
+
if (host.closest('sup') || vertical === 'super') run.vert = 'superscript';
|
|
208
|
+
else if (host.closest('sub') || vertical === 'sub') run.vert = 'subscript';
|
|
209
|
+
return run;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function imageFrom(el: Element, ctx: Ctx): Promise<string | null> {
|
|
213
|
+
const rect = el.getBoundingClientRect();
|
|
214
|
+
if (rect.width < 1 || rect.height < 1) return null;
|
|
215
|
+
let bytes: Uint8Array | null = null;
|
|
216
|
+
let ext: ImagePart['ext'] = 'png';
|
|
217
|
+
if (el instanceof HTMLImageElement) {
|
|
218
|
+
try {
|
|
219
|
+
const res = await fetch(el.currentSrc || el.src);
|
|
220
|
+
const type = res.headers.get('content-type') ?? '';
|
|
221
|
+
if (res.ok && /image\/(png|jpeg|gif)/.test(type)) {
|
|
222
|
+
bytes = new Uint8Array(await res.arrayBuffer());
|
|
223
|
+
ext = type.includes('jpeg') ? 'jpeg' : type.includes('gif') ? 'gif' : 'png';
|
|
224
|
+
}
|
|
225
|
+
} catch {
|
|
226
|
+
/* Falls through to drawing it, which embeds the source itself. */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (!bytes) {
|
|
230
|
+
try {
|
|
231
|
+
bytes = (await elementToPng(el, ctx.doc)).bytes;
|
|
232
|
+
ext = 'png';
|
|
233
|
+
} catch {
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const scale = Math.min(1, ctx.textWidth / rect.width);
|
|
238
|
+
const name = `image${ctx.images.length + 1}`;
|
|
239
|
+
ctx.images.push({
|
|
240
|
+
name,
|
|
241
|
+
ext,
|
|
242
|
+
bytes,
|
|
243
|
+
width: rect.width * scale * PX_TO_EMU,
|
|
244
|
+
height: rect.height * scale * PX_TO_EMU,
|
|
245
|
+
});
|
|
246
|
+
return name;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function collapse(text: string, host: Element): string {
|
|
250
|
+
const whiteSpace = getComputedStyle(host).whiteSpace;
|
|
251
|
+
return whiteSpace.startsWith('pre') || whiteSpace === 'break-spaces'
|
|
252
|
+
? text
|
|
253
|
+
: text.replace(/\s+/g, ' ');
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function inlinesOf(
|
|
257
|
+
nodes: Node[],
|
|
258
|
+
base: StyleBaseline,
|
|
259
|
+
ctx: Ctx,
|
|
260
|
+
linked = false,
|
|
261
|
+
): Promise<Inline[]> {
|
|
262
|
+
const out: Inline[] = [];
|
|
263
|
+
for (const node of nodes) {
|
|
264
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
265
|
+
const host = node.parentElement;
|
|
266
|
+
if (!host) continue;
|
|
267
|
+
const raw = collapse(node.nodeValue ?? '', host);
|
|
268
|
+
if (raw === '') continue;
|
|
269
|
+
// Newlines survive only where whitespace is kept, and there they break the line.
|
|
270
|
+
raw.split('\n').forEach((line, at) => {
|
|
271
|
+
if (at > 0) out.push({ type: 'break' });
|
|
272
|
+
// A tab inside a text run is not a tab to Word; it has an element of its own.
|
|
273
|
+
line.split('\t').forEach((piece, step) => {
|
|
274
|
+
if (step > 0) out.push({ type: 'tab' });
|
|
275
|
+
if (piece !== '') out.push(textRun(piece, host, base, ctx, linked));
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (!(node instanceof Element) || isHidden(node)) continue;
|
|
281
|
+
if (node.hasAttribute('data-od-ref')) {
|
|
282
|
+
// "Table 3" and not "Table 3 (p. 5)": Word repaginates, and the page
|
|
283
|
+
// would be wrong the moment it did.
|
|
284
|
+
out.push(...(await inlinesOf(Array.from(node.childNodes).slice(0, 2), base, ctx, linked)));
|
|
285
|
+
} else if (node.tagName === 'BR') {
|
|
286
|
+
out.push({ type: 'break' });
|
|
287
|
+
} else if (node.getAttribute(LABEL_ATTR) === 'footnote') {
|
|
288
|
+
const key = node.getAttribute(LABEL_ID_ATTR) ?? '';
|
|
289
|
+
if (!ctx.notes.has(key)) ctx.notes.set(key, ctx.notes.size + 1);
|
|
290
|
+
out.push({ type: 'footnote', id: ctx.notes.get(key) as number });
|
|
291
|
+
} else if (node instanceof HTMLImageElement || node instanceof SVGSVGElement) {
|
|
292
|
+
const image = await imageFrom(node, ctx);
|
|
293
|
+
if (image) out.push({ type: 'image', image });
|
|
294
|
+
} else if (node instanceof HTMLAnchorElement && node.getAttribute('href') && !linked) {
|
|
295
|
+
const runs = (await inlinesOf(Array.from(node.childNodes), base, ctx, true)).filter(
|
|
296
|
+
(inline): inline is Run => inline.type !== 'link',
|
|
297
|
+
);
|
|
298
|
+
out.push({ type: 'link', href: node.getAttribute('href') as string, runs });
|
|
299
|
+
} else {
|
|
300
|
+
out.push(...(await inlinesOf(Array.from(node.childNodes), base, ctx, linked)));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return out;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Trims the whitespace a browser would not draw: at either end, and doubled between runs. */
|
|
307
|
+
function tidy(inlines: Inline[]): Inline[] {
|
|
308
|
+
const texts: TextRun[] = [];
|
|
309
|
+
const visit = (list: Inline[]) => {
|
|
310
|
+
for (const inline of list) {
|
|
311
|
+
if (inline.type === 'text') texts.push(inline);
|
|
312
|
+
else if (inline.type === 'link') visit(inline.runs);
|
|
313
|
+
else if (inline.type === 'break') texts.push({ type: 'text', text: '\n' });
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
visit(inlines);
|
|
317
|
+
let previous = '\n';
|
|
318
|
+
for (const run of texts) {
|
|
319
|
+
if (run.text === '\n') {
|
|
320
|
+
previous = '\n';
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (previous.endsWith(' ') || previous === '\n') run.text = run.text.replace(/^ +/, '');
|
|
324
|
+
if (run.text !== '') previous = run.text;
|
|
325
|
+
}
|
|
326
|
+
for (let at = texts.length - 1; at >= 0; at--) {
|
|
327
|
+
const run = texts[at] as TextRun;
|
|
328
|
+
if (run.text === '\n') break;
|
|
329
|
+
run.text = run.text.replace(/ +$/, '');
|
|
330
|
+
if (run.text !== '') break;
|
|
331
|
+
}
|
|
332
|
+
const keep = (inline: Inline): boolean =>
|
|
333
|
+
inline.type === 'text'
|
|
334
|
+
? inline.text !== ''
|
|
335
|
+
: inline.type === 'link'
|
|
336
|
+
? inline.runs.some(keep)
|
|
337
|
+
: true;
|
|
338
|
+
return inlines
|
|
339
|
+
.filter(keep)
|
|
340
|
+
.map((inline) =>
|
|
341
|
+
inline.type === 'link' ? { ...inline, runs: inline.runs.filter(keep) as Run[] } : inline,
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function hasContent(inlines: Inline[]): boolean {
|
|
346
|
+
return inlines.some((inline) => inline.type !== 'break');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function paragraphOf(
|
|
350
|
+
nodes: Node[],
|
|
351
|
+
style: StyleId,
|
|
352
|
+
from: Element,
|
|
353
|
+
ctx: Ctx,
|
|
354
|
+
extra: Partial<Paragraph> = {},
|
|
355
|
+
): Promise<Paragraph | null> {
|
|
356
|
+
const raw = await inlinesOf(nodes, ctx.baselines[style], ctx);
|
|
357
|
+
// Code keeps its spaces: indentation is the content there.
|
|
358
|
+
const inlines =
|
|
359
|
+
style === 'Code'
|
|
360
|
+
? raw.filter((inline) => inline.type !== 'text' || inline.text !== '')
|
|
361
|
+
: tidy(raw);
|
|
362
|
+
if (!hasContent(inlines)) return null;
|
|
363
|
+
const paragraph: Paragraph = { type: 'paragraph', inlines, ...spacing(from), ...extra };
|
|
364
|
+
if (style !== 'Normal') paragraph.style = style;
|
|
365
|
+
const alignment = align(from);
|
|
366
|
+
if (alignment) paragraph.align = alignment;
|
|
367
|
+
return paragraph;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ---------------------------------------------------------------------------
|
|
371
|
+
// Blocks
|
|
372
|
+
// ---------------------------------------------------------------------------
|
|
373
|
+
|
|
374
|
+
async function blocksOf(el: Element, ctx: Ctx, out: Block[], style: StyleId = 'Normal') {
|
|
375
|
+
let buffer: Node[] = [];
|
|
376
|
+
const flush = async () => {
|
|
377
|
+
if (buffer.length === 0) return;
|
|
378
|
+
const paragraph = await paragraphOf(buffer, style, el, ctx);
|
|
379
|
+
if (paragraph) {
|
|
380
|
+
const range = document.createRange();
|
|
381
|
+
range.setStartBefore(buffer[0] as Node);
|
|
382
|
+
range.setEndAfter(buffer[buffer.length - 1] as Node);
|
|
383
|
+
place(paragraph, range.getBoundingClientRect());
|
|
384
|
+
out.push(paragraph);
|
|
385
|
+
}
|
|
386
|
+
buffer = [];
|
|
387
|
+
};
|
|
388
|
+
for (const child of Array.from(el.childNodes)) {
|
|
389
|
+
if (child instanceof Element) {
|
|
390
|
+
if (skip(child, ctx)) continue;
|
|
391
|
+
if (isBlock(child)) {
|
|
392
|
+
await flush();
|
|
393
|
+
await blockOf(child, ctx, out, style);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
buffer.push(child);
|
|
398
|
+
}
|
|
399
|
+
await flush();
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** A row of short pieces side by side — a running footer, a contents line — as one line with a tab. */
|
|
403
|
+
function isTabbedRow(el: Element, ctx: Ctx): boolean {
|
|
404
|
+
const style = getComputedStyle(el);
|
|
405
|
+
if (!style.display.includes('flex') || style.flexDirection.startsWith('column')) return false;
|
|
406
|
+
const children = Array.from(el.children).filter((child) => !skip(child, ctx));
|
|
407
|
+
return children.length > 1 && children.every((child) => !hasBlockChild(child, ctx));
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function blockOf(el: Element, ctx: Ctx, out: Block[], style: StyleId) {
|
|
411
|
+
const start = out.length;
|
|
412
|
+
await blockOfElement(el, ctx, out, style);
|
|
413
|
+
const box = el.getBoundingClientRect();
|
|
414
|
+
for (const block of out.slice(start)) place(block, box);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleId) {
|
|
418
|
+
const tag = el.tagName;
|
|
419
|
+
// A picture laid out as a block — placed absolutely, or set to display:
|
|
420
|
+
// block — has no children to make a paragraph from; it is the paragraph.
|
|
421
|
+
if (el instanceof HTMLImageElement || el instanceof SVGSVGElement) {
|
|
422
|
+
const image = await imageFrom(el, ctx);
|
|
423
|
+
if (image) out.push({ type: 'paragraph', inlines: [{ type: 'image', image }] });
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (el.hasAttribute('data-od-toc')) {
|
|
427
|
+
out.push(tocOf(el, ctx));
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
if (el.hasAttribute('data-od-list-of')) {
|
|
431
|
+
for (const row of Array.from(el.children)) {
|
|
432
|
+
const pieces = Array.from(row.children).filter((piece) => !isHidden(piece));
|
|
433
|
+
const inlines: Inline[] = [];
|
|
434
|
+
for (const [at, piece] of pieces.slice(0, 2).entries()) {
|
|
435
|
+
if (at > 0) inlines.push({ type: 'text', text: ' ' });
|
|
436
|
+
inlines.push(...(await inlinesOf([piece], ctx.baselines.Normal, ctx)));
|
|
437
|
+
}
|
|
438
|
+
const tidied = tidy(inlines);
|
|
439
|
+
if (!hasContent(tidied)) continue;
|
|
440
|
+
// The page is a PAGEREF to the caption's bookmark: Word works it out
|
|
441
|
+
// again as it paginates, and an app that does not update fields shows
|
|
442
|
+
// the page open-doc printed it on.
|
|
443
|
+
const entry = row.getAttribute('data-od-list-entry');
|
|
444
|
+
const page = pieces.length > 2 ? (pieces[pieces.length - 1]?.textContent ?? '').trim() : '';
|
|
445
|
+
const paragraph: Paragraph = { type: 'paragraph', inlines: tidied, ...spacing(row) };
|
|
446
|
+
if (entry && page) {
|
|
447
|
+
paragraph.inlines.push(
|
|
448
|
+
{ type: 'tab' },
|
|
449
|
+
{ type: 'field', instr: `PAGEREF ${bookmarkFor(entry)} \\h`, cached: page },
|
|
450
|
+
);
|
|
451
|
+
paragraph.rightTab = ctx.textWidth * PX_TO_TWIPS;
|
|
452
|
+
paragraph.leader = true;
|
|
453
|
+
}
|
|
454
|
+
out.push(paragraph);
|
|
455
|
+
}
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (/^H[1-6]$/.test(tag)) {
|
|
459
|
+
const level = Number(tag[1]);
|
|
460
|
+
// A heading the outline skips is either the cover's title or a heading the
|
|
461
|
+
// contents should not list — "Contents" itself. Word has a style for each.
|
|
462
|
+
const outlined = el.getAttribute('data-od-outline') !== 'skip';
|
|
463
|
+
const heading: StyleId = outlined
|
|
464
|
+
? (`Heading${level}` as StyleId)
|
|
465
|
+
: ctx.page.first && level === 1
|
|
466
|
+
? 'Title'
|
|
467
|
+
: 'TOCHeading';
|
|
468
|
+
const paragraph = await paragraphOf(Array.from(el.childNodes), heading, el, ctx, {
|
|
469
|
+
keepNext: true,
|
|
470
|
+
});
|
|
471
|
+
if (paragraph) out.push(paragraph);
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (tag === 'TABLE') {
|
|
475
|
+
out.push(await tableOf(el as HTMLTableElement, ctx));
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
if (tag === 'UL' || tag === 'OL') {
|
|
479
|
+
await listOf(el, ctx, out, 0);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
if (tag === 'PRE') {
|
|
483
|
+
const paragraph = await paragraphOf(Array.from(el.childNodes), 'Code', el, ctx);
|
|
484
|
+
if (paragraph) out.push(...boxed([paragraph], el));
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (tag === 'FIGURE') {
|
|
488
|
+
await figureOf(el, ctx, out);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (tag === 'FIGCAPTION') {
|
|
492
|
+
const paragraph = await paragraphOf(Array.from(el.childNodes), 'Caption', el, ctx);
|
|
493
|
+
if (paragraph) out.push(captioned(paragraph, el));
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (tag === 'HR') return;
|
|
497
|
+
if (tag === 'BLOCKQUOTE') {
|
|
498
|
+
const inner: Block[] = [];
|
|
499
|
+
await blocksOf(el, ctx, inner, 'Quote');
|
|
500
|
+
const paragraphs = inner.filter((block): block is Paragraph => block.type === 'paragraph');
|
|
501
|
+
out.push(...(paragraphs.length === inner.length ? boxed(paragraphs, el) : inner));
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (isTabbedRow(el, ctx)) {
|
|
505
|
+
const pieces = Array.from(el.children).filter((child) => !skip(child, ctx));
|
|
506
|
+
const inlines: Inline[] = [];
|
|
507
|
+
for (const [at, piece] of pieces.entries()) {
|
|
508
|
+
if (at > 0) inlines.push({ type: 'tab' });
|
|
509
|
+
inlines.push(...tidy(await inlinesOf([piece], ctx.baselines[style], ctx)));
|
|
510
|
+
}
|
|
511
|
+
if (inlines.some((inline) => inline.type !== 'tab')) {
|
|
512
|
+
out.push({
|
|
513
|
+
type: 'paragraph',
|
|
514
|
+
inlines,
|
|
515
|
+
rightTab: ctx.textWidth * PX_TO_TWIPS,
|
|
516
|
+
...spacing(el),
|
|
517
|
+
...(style !== 'Normal' ? { style } : {}),
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
if (!hasBlockChild(el, ctx)) {
|
|
523
|
+
const paragraph = await paragraphOf(Array.from(el.childNodes), style, el, ctx);
|
|
524
|
+
if (paragraph) out.push(paragraph);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
await blocksOf(el, ctx, out, style);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function tocOf(el: Element, ctx: Ctx): Block {
|
|
531
|
+
const entries = Array.from(el.querySelectorAll('[data-od-toc-entry]')).map((row) => {
|
|
532
|
+
const id = row.getAttribute('data-od-toc-entry') ?? '';
|
|
533
|
+
const heading = id ? ctx.container.querySelector(`#${CSS.escape(id)}`) : null;
|
|
534
|
+
const level = heading && /^H[1-6]$/.test(heading.tagName) ? Number(heading.tagName[1]) : 1;
|
|
535
|
+
const text = (heading?.textContent ?? row.textContent ?? '').replace(/\s+/g, ' ').trim();
|
|
536
|
+
return { text, level };
|
|
537
|
+
});
|
|
538
|
+
return { type: 'toc', entries };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function listOf(el: Element, ctx: Ctx, out: Block[], level: number) {
|
|
542
|
+
ctx.lists.push(el.tagName === 'OL' ? 'decimal' : 'bullet');
|
|
543
|
+
const numId = ctx.lists.length;
|
|
544
|
+
for (const item of Array.from(el.children)) {
|
|
545
|
+
if (item.tagName !== 'LI' || skip(item, ctx)) continue;
|
|
546
|
+
const nested = Array.from(item.children).filter(
|
|
547
|
+
(child) => child.tagName === 'UL' || child.tagName === 'OL',
|
|
548
|
+
);
|
|
549
|
+
const own = Array.from(item.childNodes).filter(
|
|
550
|
+
(child) => !(child instanceof Element && nested.includes(child)),
|
|
551
|
+
);
|
|
552
|
+
const paragraph = await paragraphOf(own, 'ListParagraph', item, ctx, {
|
|
553
|
+
list: { numId, level },
|
|
554
|
+
});
|
|
555
|
+
if (paragraph) out.push(paragraph);
|
|
556
|
+
for (const list of nested) await listOf(list, ctx, out, level + 1);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function border(style: CSSStyleDeclaration, side: 'Top' | 'Left' | 'Bottom' | 'Right') {
|
|
561
|
+
const width = Number.parseFloat(style.getPropertyValue(`border-${side.toLowerCase()}-width`));
|
|
562
|
+
const kind = style.getPropertyValue(`border-${side.toLowerCase()}-style`);
|
|
563
|
+
const color = hexColor(style.getPropertyValue(`border-${side.toLowerCase()}-color`));
|
|
564
|
+
if (!width || kind === 'none' || kind === 'hidden' || !color) return undefined;
|
|
565
|
+
// Eighths of a point; Word draws nothing thinner than a quarter point.
|
|
566
|
+
return { color, size: Math.max(2, Math.round(width * 0.75 * 8)) };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* A block that drew a panel or a rule round itself — a code block's tinted
|
|
571
|
+
* box, a quote's bar — as a one-cell table. A paragraph's own borders would
|
|
572
|
+
* do in Word, but Pages ignores their padding and draws them tight against
|
|
573
|
+
* the text; a cell's fill, borders and margins read the same in both.
|
|
574
|
+
*/
|
|
575
|
+
function boxed(paragraphs: Paragraph[], el: Element): Block[] {
|
|
576
|
+
const style = getComputedStyle(el);
|
|
577
|
+
const fill = hexColor(style.backgroundColor) ?? undefined;
|
|
578
|
+
const borders: NonNullable<TableCell['borders']> = {};
|
|
579
|
+
for (const side of ['Top', 'Left', 'Bottom', 'Right'] as const) {
|
|
580
|
+
const rule = border(style, side);
|
|
581
|
+
if (rule) borders[side.toLowerCase() as keyof typeof borders] = rule;
|
|
582
|
+
}
|
|
583
|
+
if (!fill && Object.keys(borders).length === 0) return paragraphs;
|
|
584
|
+
const pad = (side: string) =>
|
|
585
|
+
(Number.parseFloat(style.getPropertyValue(`padding-${side}`)) || 0) * PX_TO_TWIPS;
|
|
586
|
+
const cell: TableCell = {
|
|
587
|
+
blocks: paragraphs.map((paragraph, at) => ({
|
|
588
|
+
...paragraph,
|
|
589
|
+
spacingBefore: 0,
|
|
590
|
+
spacingAfter: at === paragraphs.length - 1 ? 0 : paragraph.spacingAfter,
|
|
591
|
+
// The cell's margin is the inset now; a quote's own indent would double it.
|
|
592
|
+
indent: 0,
|
|
593
|
+
})),
|
|
594
|
+
borders,
|
|
595
|
+
...(fill ? { fill } : {}),
|
|
596
|
+
padding: { top: pad('top'), left: pad('left'), bottom: pad('bottom'), right: pad('right') },
|
|
597
|
+
};
|
|
598
|
+
const width = el.getBoundingClientRect().width * PX_TO_TWIPS;
|
|
599
|
+
return [
|
|
600
|
+
{
|
|
601
|
+
type: 'table',
|
|
602
|
+
columns: [width],
|
|
603
|
+
rows: [{ header: false, cells: [cell] }],
|
|
604
|
+
cellMargin: { left: pad('left'), right: pad('right') },
|
|
605
|
+
},
|
|
606
|
+
];
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async function tableOf(table: HTMLTableElement, ctx: Ctx): Promise<Table> {
|
|
610
|
+
const rows = Array.from(table.rows);
|
|
611
|
+
const widest = rows.reduce(
|
|
612
|
+
(best, row) => (row.cells.length > (best?.cells.length ?? 0) ? row : best),
|
|
613
|
+
rows[0],
|
|
614
|
+
);
|
|
615
|
+
const widths = Array.from(widest?.cells ?? []).map((cell) => cell.getBoundingClientRect().width);
|
|
616
|
+
const total = widths.reduce((sum, width) => sum + width, 0) || 1;
|
|
617
|
+
const fit = Math.min(1, ctx.textWidth / total);
|
|
618
|
+
const columns = widths.map((width) => width * fit * PX_TO_TWIPS);
|
|
619
|
+
|
|
620
|
+
const out: Table = { type: 'table', columns, rows: [] };
|
|
621
|
+
for (const row of rows) {
|
|
622
|
+
const header =
|
|
623
|
+
row.parentElement?.tagName === 'THEAD' ||
|
|
624
|
+
(row.cells.length > 0 && Array.from(row.cells).every((cell) => cell.tagName === 'TH'));
|
|
625
|
+
const cells: TableCell[] = [];
|
|
626
|
+
for (const cell of Array.from(row.cells)) {
|
|
627
|
+
const blocks: Block[] = [];
|
|
628
|
+
await blocksOf(cell, ctx, blocks);
|
|
629
|
+
const paragraphs = blocks
|
|
630
|
+
.filter((block): block is Paragraph => block.type === 'paragraph')
|
|
631
|
+
.map((paragraph) => ({
|
|
632
|
+
...paragraph,
|
|
633
|
+
spacingBefore: 0,
|
|
634
|
+
spacingAfter: 0,
|
|
635
|
+
...(align(cell) ? { align: align(cell) } : {}),
|
|
636
|
+
}));
|
|
637
|
+
const style = getComputedStyle(cell);
|
|
638
|
+
const borders: TableCell['borders'] = {};
|
|
639
|
+
for (const side of ['Top', 'Left', 'Bottom', 'Right'] as const) {
|
|
640
|
+
const edge = border(style, side);
|
|
641
|
+
if (edge) borders[side.toLowerCase() as 'top'] = edge;
|
|
642
|
+
}
|
|
643
|
+
cells.push({
|
|
644
|
+
blocks: paragraphs,
|
|
645
|
+
...(cell.colSpan > 1 ? { span: cell.colSpan } : {}),
|
|
646
|
+
borders,
|
|
647
|
+
padding: {
|
|
648
|
+
top: (Number.parseFloat(style.paddingTop) || 0) * PX_TO_TWIPS,
|
|
649
|
+
left: (Number.parseFloat(style.paddingLeft) || 0) * PX_TO_TWIPS,
|
|
650
|
+
bottom: (Number.parseFloat(style.paddingBottom) || 0) * PX_TO_TWIPS,
|
|
651
|
+
right: (Number.parseFloat(style.paddingRight) || 0) * PX_TO_TWIPS,
|
|
652
|
+
},
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
out.rows.push({ header, cells });
|
|
656
|
+
}
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
async function figureOf(figure: Element, ctx: Ctx, out: Block[]) {
|
|
661
|
+
const start = out.length;
|
|
662
|
+
await figureParts(figure, ctx, out);
|
|
663
|
+
// The figure's own margins are what separate it from the text around it;
|
|
664
|
+
// its caption and picture carry none of their own.
|
|
665
|
+
const { spacingBefore = 0, spacingAfter = 0 } = spacing(figure);
|
|
666
|
+
const first = out[start];
|
|
667
|
+
const last = out[out.length - 1];
|
|
668
|
+
if (first?.type === 'paragraph') {
|
|
669
|
+
first.spacingBefore = Math.max(first.spacingBefore ?? 0, spacingBefore);
|
|
670
|
+
}
|
|
671
|
+
if (last?.type === 'paragraph' && out.length > start) {
|
|
672
|
+
last.spacingAfter = Math.max(last.spacingAfter ?? 0, spacingAfter);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** Word bookmark names are letters, digits and underscores, starting with a letter. */
|
|
677
|
+
function bookmarkFor(labelId: string): string {
|
|
678
|
+
return `od_${labelId.replace(/[^A-Za-z0-9_]/g, '_')}`.slice(0, 40);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** Marks a caption so the list of figures or tables can point at its page. */
|
|
682
|
+
function captioned(paragraph: Paragraph, caption: Element): Paragraph {
|
|
683
|
+
const id = caption.closest(`[${LABEL_ID_ATTR}]`)?.getAttribute(LABEL_ID_ATTR);
|
|
684
|
+
if (id) paragraph.bookmark = bookmarkFor(id);
|
|
685
|
+
return paragraph;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function figureParts(figure: Element, ctx: Ctx, out: Block[]) {
|
|
689
|
+
const children = Array.from(figure.children).filter((child) => !skip(child, ctx));
|
|
690
|
+
for (const [at, child] of children.entries()) {
|
|
691
|
+
const captionNext = children[at + 1]?.tagName === 'FIGCAPTION';
|
|
692
|
+
if (child.tagName === 'FIGCAPTION') {
|
|
693
|
+
const paragraph = await paragraphOf(Array.from(child.childNodes), 'Caption', child, ctx, {
|
|
694
|
+
keepNext: at === 0,
|
|
695
|
+
});
|
|
696
|
+
if (paragraph) out.push(captioned(paragraph, child));
|
|
697
|
+
} else if (child.tagName === 'TABLE' || child.querySelector(STRUCTURE)) {
|
|
698
|
+
await blockOf(child, ctx, out, 'Normal');
|
|
699
|
+
} else {
|
|
700
|
+
// A drawing: what it shows is not text Word could reflow.
|
|
701
|
+
const image = await imageFrom(child, ctx);
|
|
702
|
+
if (image) {
|
|
703
|
+
out.push({
|
|
704
|
+
type: 'paragraph',
|
|
705
|
+
align: 'center',
|
|
706
|
+
keepNext: captionNext,
|
|
707
|
+
inlines: [{ type: 'image', image }],
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// ---------------------------------------------------------------------------
|
|
715
|
+
// Pages
|
|
716
|
+
// ---------------------------------------------------------------------------
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* The document in reading order. A fixed page is its own sheet in Word too, so
|
|
720
|
+
* it starts on a new page; a flow section's later pages continue it, and Word
|
|
721
|
+
* decides where they break.
|
|
722
|
+
*/
|
|
723
|
+
export async function docxFromPages(
|
|
724
|
+
hosts: HTMLElement[],
|
|
725
|
+
pages: PageInfo[],
|
|
726
|
+
container: HTMLElement,
|
|
727
|
+
options: WalkOptions,
|
|
728
|
+
): Promise<WalkResult> {
|
|
729
|
+
const ctx: Ctx = {
|
|
730
|
+
...options,
|
|
731
|
+
images: [],
|
|
732
|
+
lists: [],
|
|
733
|
+
notes: new Map(),
|
|
734
|
+
container,
|
|
735
|
+
page: { top: 0, bottom: 0, fixed: true, first: true },
|
|
736
|
+
};
|
|
737
|
+
const blocks: Block[] = [];
|
|
738
|
+
let previousFooter = true;
|
|
739
|
+
|
|
740
|
+
for (const [index, host] of hosts.entries()) {
|
|
741
|
+
const info = pages[index] ?? { continues: false };
|
|
742
|
+
const rect = host.getBoundingClientRect();
|
|
743
|
+
ctx.page = {
|
|
744
|
+
top: rect.top,
|
|
745
|
+
bottom: rect.bottom,
|
|
746
|
+
fixed: !info.continues && !host.querySelector(`[${FLOW_BLOCK_ATTR}]`),
|
|
747
|
+
first: index === 0,
|
|
748
|
+
};
|
|
749
|
+
const own: Block[] = [];
|
|
750
|
+
const flowBlocks = Array.from(host.querySelectorAll(`[${FLOW_BLOCK_ATTR}]`));
|
|
751
|
+
if (flowBlocks.length > 0) {
|
|
752
|
+
for (const block of flowBlocks) await blockOf(block, ctx, own, 'Normal');
|
|
753
|
+
} else {
|
|
754
|
+
await blocksOf(host, ctx, own);
|
|
755
|
+
}
|
|
756
|
+
// A fixed page places its words where it wants them — a logo at the top,
|
|
757
|
+
// a cover's title low on the sheet, a closing line centred. Word flows
|
|
758
|
+
// from the top margin, so each gap as it was on the sheet becomes the
|
|
759
|
+
// space before the block below it. Word adds a paragraph's space after to
|
|
760
|
+
// the next one's space before instead of collapsing them as CSS does, so
|
|
761
|
+
// the space after goes to zero wherever the gap is set this way.
|
|
762
|
+
if (ctx.page.fixed) {
|
|
763
|
+
let bottom = rect.top + options.margin;
|
|
764
|
+
let previous: Paragraph | null = null;
|
|
765
|
+
for (const block of own) {
|
|
766
|
+
const box = placed.get(block);
|
|
767
|
+
if (!box) continue;
|
|
768
|
+
const gap = Math.max(0, box.top - bottom);
|
|
769
|
+
if (block.type === 'paragraph') {
|
|
770
|
+
block.spacingBefore = gap * PX_TO_TWIPS;
|
|
771
|
+
if (previous) previous.spacingAfter = 0;
|
|
772
|
+
previous = block;
|
|
773
|
+
} else {
|
|
774
|
+
previous = null;
|
|
775
|
+
}
|
|
776
|
+
bottom = Math.max(bottom, box.bottom);
|
|
777
|
+
}
|
|
778
|
+
// Word sets a heading's line from the font's own height, taller than the
|
|
779
|
+
// page's CSS line-height, so a sheet laid out to its last pixel — a
|
|
780
|
+
// cover's byline at the foot — would spill its last lines onto a page of
|
|
781
|
+
// their own. The gaps give back a little of the sheet to absorb that.
|
|
782
|
+
const gapped = own.filter(
|
|
783
|
+
(block): block is Paragraph => block.type === 'paragraph' && (block.spacingBefore ?? 0) > 0,
|
|
784
|
+
);
|
|
785
|
+
const total = gapped.reduce((sum, block) => sum + (block.spacingBefore ?? 0), 0);
|
|
786
|
+
const reserve = Math.min(
|
|
787
|
+
total * 0.3,
|
|
788
|
+
(rect.height - options.margin * 2) * 0.08 * PX_TO_TWIPS,
|
|
789
|
+
);
|
|
790
|
+
if (total > 0) {
|
|
791
|
+
for (const block of gapped) {
|
|
792
|
+
block.spacingBefore = ((block.spacingBefore ?? 0) * (total - reserve)) / total;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
// Flow pages carry the section footer; a fixed sheet prints its own
|
|
797
|
+
// running lines, so it sits in a section without one. The section break
|
|
798
|
+
// itself starts the next page.
|
|
799
|
+
const footer = !ctx.page.fixed;
|
|
800
|
+
const breaksSection = own.length > 0 && blocks.length > 0 && footer !== previousFooter;
|
|
801
|
+
if (breaksSection) {
|
|
802
|
+
const last = blocks[blocks.length - 1];
|
|
803
|
+
if (last?.type === 'paragraph' && !last.sectionEnd) {
|
|
804
|
+
last.sectionEnd = { footer: previousFooter };
|
|
805
|
+
} else {
|
|
806
|
+
blocks.push({
|
|
807
|
+
type: 'paragraph',
|
|
808
|
+
inlines: [],
|
|
809
|
+
spacingBefore: 0,
|
|
810
|
+
spacingAfter: 0,
|
|
811
|
+
lineExact: 20,
|
|
812
|
+
sectionEnd: { footer: previousFooter },
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
const first = own[0];
|
|
817
|
+
if (first) {
|
|
818
|
+
const newPage = index > 0 && !info.continues && !breaksSection;
|
|
819
|
+
// Word and Pages drop the space before the first paragraph on a page —
|
|
820
|
+
// at the top of the document and after a break alike — so a gap there,
|
|
821
|
+
// a cover's title low on its sheet or a closing line centred, is held
|
|
822
|
+
// open by a spacer's line height instead, which they keep.
|
|
823
|
+
const lead = ctx.page.fixed && first.type === 'paragraph' ? (first.spacingBefore ?? 0) : 0;
|
|
824
|
+
if (first.type === 'paragraph' && lead === 0) {
|
|
825
|
+
if (newPage) first.pageBreakBefore = true;
|
|
826
|
+
} else if (lead > 0 || newPage) {
|
|
827
|
+
if (first.type === 'paragraph') first.spacingBefore = 0;
|
|
828
|
+
own.unshift({
|
|
829
|
+
type: 'paragraph',
|
|
830
|
+
inlines: [],
|
|
831
|
+
...(newPage ? { pageBreakBefore: true } : {}),
|
|
832
|
+
spacingBefore: 0,
|
|
833
|
+
spacingAfter: 0,
|
|
834
|
+
lineExact: lead > 0 ? Math.round(lead) : 20,
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
if (own.length > 0) previousFooter = footer;
|
|
839
|
+
blocks.push(...own);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const footnotes: WalkResult['footnotes'] = [];
|
|
843
|
+
for (const [key, id] of ctx.notes) {
|
|
844
|
+
const row = container.querySelector(`[${FOOTNOTE_ID_ATTR}="${CSS.escape(key)}"]`);
|
|
845
|
+
const body = row?.lastElementChild;
|
|
846
|
+
const paragraph = body
|
|
847
|
+
? await paragraphOf(Array.from(body.childNodes), 'FootnoteText', body, ctx)
|
|
848
|
+
: null;
|
|
849
|
+
footnotes.push({
|
|
850
|
+
id,
|
|
851
|
+
paragraphs: [
|
|
852
|
+
paragraph
|
|
853
|
+
? { ...paragraph, spacingBefore: 0, spacingAfter: 0 }
|
|
854
|
+
: { type: 'paragraph', inlines: [] },
|
|
855
|
+
],
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
return { blocks, footnotes, images: ctx.images, lists: ctx.lists, finalFooter: previousFooter };
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** Runs for one element — the footer the orchestrator renders on its own. */
|
|
863
|
+
export async function lineOf(el: Element, options: WalkOptions): Promise<Paragraph | null> {
|
|
864
|
+
const ctx: Ctx = {
|
|
865
|
+
...options,
|
|
866
|
+
images: [],
|
|
867
|
+
lists: [],
|
|
868
|
+
notes: new Map(),
|
|
869
|
+
container: el as HTMLElement,
|
|
870
|
+
page: { top: 0, bottom: 0, fixed: false, first: false },
|
|
871
|
+
};
|
|
872
|
+
const out: Block[] = [];
|
|
873
|
+
await blockOf(el, ctx, out, 'Normal');
|
|
874
|
+
const paragraphs = out.filter((block): block is Paragraph => block.type === 'paragraph');
|
|
875
|
+
if (paragraphs.length === 0) return null;
|
|
876
|
+
// A footer is one line in Word; several blocks become one line split by tabs.
|
|
877
|
+
const inlines: Inline[] = [];
|
|
878
|
+
for (const [at, paragraph] of paragraphs.entries()) {
|
|
879
|
+
if (at > 0) inlines.push({ type: 'tab' });
|
|
880
|
+
inlines.push(...paragraph.inlines);
|
|
881
|
+
}
|
|
882
|
+
return {
|
|
883
|
+
type: 'paragraph',
|
|
884
|
+
inlines,
|
|
885
|
+
rightTab: paragraphs[0]?.rightTab ?? options.textWidth * PX_TO_TWIPS,
|
|
886
|
+
spacingBefore: 0,
|
|
887
|
+
spacingAfter: 0,
|
|
888
|
+
};
|
|
889
|
+
}
|