@folijs/view 0.5.0 → 1.0.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/README.md +1 -1
  3. package/dist/clipboard.d.ts +1 -49
  4. package/dist/clipboard.d.ts.map +1 -1
  5. package/dist/clipboard.js +65 -13
  6. package/dist/clipboard.js.map +1 -1
  7. package/dist/extension.d.ts +90 -0
  8. package/dist/extension.d.ts.map +1 -0
  9. package/dist/extension.js +152 -0
  10. package/dist/extension.js.map +1 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/layout/flow.d.ts +1 -109
  15. package/dist/layout/flow.d.ts.map +1 -1
  16. package/dist/layout/flow.js +808 -103
  17. package/dist/layout/flow.js.map +1 -1
  18. package/dist/print.d.ts +6 -0
  19. package/dist/print.d.ts.map +1 -0
  20. package/dist/print.js +35 -0
  21. package/dist/print.js.map +1 -0
  22. package/dist/render.d.ts +1 -24
  23. package/dist/render.d.ts.map +1 -1
  24. package/dist/render.js +4 -1
  25. package/dist/render.js.map +1 -1
  26. package/dist/view.d.ts +244 -64
  27. package/dist/view.d.ts.map +1 -1
  28. package/dist/view.js +1945 -215
  29. package/dist/view.js.map +1 -1
  30. package/dist/word/blocks.d.ts +0 -146
  31. package/dist/word/blocks.d.ts.map +1 -1
  32. package/dist/word/blocks.js +294 -59
  33. package/dist/word/blocks.js.map +1 -1
  34. package/dist/word/columns.d.ts +2 -0
  35. package/dist/word/columns.d.ts.map +1 -0
  36. package/dist/word/columns.js +63 -0
  37. package/dist/word/columns.js.map +1 -0
  38. package/dist/word/controls.d.ts +2 -0
  39. package/dist/word/controls.d.ts.map +1 -0
  40. package/dist/word/controls.js +416 -0
  41. package/dist/word/controls.js.map +1 -0
  42. package/dist/word/edit.d.ts +1 -71
  43. package/dist/word/edit.d.ts.map +1 -1
  44. package/dist/word/edit.js +338 -29
  45. package/dist/word/edit.js.map +1 -1
  46. package/dist/word/matches.d.ts +2 -0
  47. package/dist/word/matches.d.ts.map +1 -0
  48. package/dist/word/matches.js +102 -0
  49. package/dist/word/matches.js.map +1 -0
  50. package/dist/word/notes.d.ts +2 -0
  51. package/dist/word/notes.d.ts.map +1 -0
  52. package/dist/word/notes.js +403 -0
  53. package/dist/word/notes.js.map +1 -0
  54. package/dist/word/pages.d.ts +30 -20
  55. package/dist/word/pages.d.ts.map +1 -1
  56. package/dist/word/pages.js +421 -229
  57. package/dist/word/pages.js.map +1 -1
  58. package/dist/word/regions.d.ts +2 -0
  59. package/dist/word/regions.d.ts.map +1 -0
  60. package/dist/word/regions.js +388 -0
  61. package/dist/word/regions.js.map +1 -0
  62. package/dist/word/table.d.ts +1 -78
  63. package/dist/word/table.d.ts.map +1 -1
  64. package/dist/word/table.js +13 -3
  65. package/dist/word/table.js.map +1 -1
  66. package/package.json +6 -3
  67. package/src/clipboard.ts +93 -20
  68. package/src/extension.ts +267 -0
  69. package/src/index.ts +10 -0
  70. package/src/layout/flow.ts +997 -116
  71. package/src/print.ts +55 -0
  72. package/src/render.ts +6 -1
  73. package/src/view.ts +2178 -245
  74. package/src/word/blocks.ts +339 -62
  75. package/src/word/columns.ts +81 -0
  76. package/src/word/controls.ts +457 -0
  77. package/src/word/edit.ts +381 -31
  78. package/src/word/matches.ts +104 -0
  79. package/src/word/notes.ts +464 -0
  80. package/src/word/pages.ts +518 -221
  81. package/src/word/regions.ts +488 -0
  82. package/src/word/table.ts +33 -8
package/src/word/pages.ts CHANGED
@@ -4,20 +4,49 @@
4
4
  * Word's spacing, keep rules, widow and orphan control and explicit breaks. Editing moves to
5
5
  * v3 in 8.7.
6
6
  */
7
- import type { FoliDocument, SectionJSON } from "@folijs/core";
8
- import { type BlockBox, flow } from "../layout/flow.js";
7
+ import {
8
+ type FieldLayout,
9
+ type FoliDocument,
10
+ noteNumbers,
11
+ noteProperties,
12
+ noteTexts,
13
+ parseContent,
14
+ type ResourceJSON,
15
+ type ReviewView,
16
+ type SectionJSON,
17
+ } from "@folijs/core";
18
+ import { Resolver } from "@folijs/core/internal";
19
+ import {
20
+ type BlockBox,
21
+ type FlowNote,
22
+ type FlowSection,
23
+ type Fragment,
24
+ flowFrom,
25
+ notePieces,
26
+ pagesOf,
27
+ spaceAfterText,
28
+ } from "../layout/flow.js";
29
+ import { printStyles, SHEET_ATTR } from "../print.js";
9
30
  import {
10
31
  type BlockOptions,
32
+ NOTE_REF_ATTR,
33
+ PICTURE_ATTR,
11
34
  PX_PER_TWIP,
12
35
  renderBlocks,
36
+ WORD_COLUMN_BREAK_ATTR,
13
37
  WORD_PAGE_BREAK_ATTR,
14
38
  type WordBlock,
15
39
  } from "./blocks.js";
40
+ import { bandElement, type ColumnsPx, columnsPx } from "./columns.js";
41
+ import { lineBottoms, type NoteGroup, PageNotes } from "./notes.js";
42
+ import { PageRegions } from "./regions.js";
16
43
 
17
44
  export type { ReviewView } from "./blocks.js";
18
45
 
19
46
  /** The class of each page element. */
20
47
  export const WORD_PAGE_CLASS = "foli-word-page";
48
+ /** The breaks that keep a paragraph from being one line to the flow. */
49
+ const BREAKS = `br[${WORD_PAGE_BREAK_ATTR}],br[${WORD_COLUMN_BREAK_ATTR}]`;
21
50
 
22
51
  export interface DocumentPages {
23
52
  /** The page elements, in order. */
@@ -34,6 +63,18 @@ export interface DocumentPages {
34
63
  * a vertical merge covers, as Word lists none), with the page (0-based) it starts on.
35
64
  */
36
65
  cellParagraphs(): { page: number; text: string }[];
66
+ /**
67
+ * Where body positions are on these pages, for `updateFields` (`PAGE`, `NUMPAGES`, `PAGEREF`,
68
+ * a table of contents' page numbers).
69
+ * shortcut: a position's page is the one its top-level block starts on (a bookmark in a paragraph or table carried to the next page gets the page it starts on); use the lines when a document needs it.
70
+ */
71
+ readonly fieldLayout: FieldLayout;
72
+ /**
73
+ * Print rules for these pages, as the editor's: one sheet of its section's size per page (named
74
+ * pages where sections differ), no gaps. For a web page holding these pages only (`@page`
75
+ * applies to the whole web page).
76
+ */
77
+ printStyles(): string;
37
78
  /** Removes the pages. */
38
79
  destroy(): void;
39
80
  }
@@ -95,6 +136,7 @@ function createPage(doc: Document, g: Geometry): { page: HTMLElement; body: HTML
95
136
  /**
96
137
  * The ratio of a font's normal line height to its size, measured: a line of 100 px text with
97
138
  * `line-height: normal` (the font's own ascent, descent and gap, as Word's single spacing).
139
+ * @internal
98
140
  */
99
141
  export function measureLineRatio(container: HTMLElement): (family: string) => number {
100
142
  return (family) => {
@@ -114,54 +156,6 @@ export function measureLineRatio(container: HTMLElement): (family: string) => nu
114
156
  };
115
157
  }
116
158
 
117
- /**
118
- * The bottom of each line of a rendered block, from its top. Lines are the vertical clusters of
119
- * its contents' client rects; a boundary is halfway between one line's content and the next's,
120
- * the last line ends at the block's bottom.
121
- *
122
- * shortcut: line boxes are inferred from content rects (exact for even line heights); a
123
- * superscript or a much larger run on a line moves that line's boundaries slightly.
124
- */
125
- export function lineBottoms(element: HTMLElement): number[] {
126
- const box = element.getBoundingClientRect();
127
- const doc = element.ownerDocument;
128
- const range = doc.createRange();
129
- const rects: { rect: DOMRect; text: boolean }[] = [];
130
- // Text and line breaks only: a range over the whole block also has the boxes of the
131
- // elements inside it (a table's), which span many lines.
132
- const walker = doc.createTreeWalker(element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
133
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
134
- if (node.nodeType === Node.TEXT_NODE) {
135
- range.selectNodeContents(node);
136
- for (const rect of range.getClientRects()) rects.push({ rect, text: true });
137
- } else if (node.nodeName === "BR")
138
- rects.push({ rect: (node as Element).getBoundingClientRect(), text: false });
139
- }
140
- rects.sort((a, b) => a.rect.top - b.rect.top);
141
- type Line = { top: number; bottom: number; text: boolean };
142
- const lines: Line[] = [];
143
- for (const { rect, text } of rects) {
144
- if (rect.height <= 0) continue;
145
- const last = lines[lines.length - 1];
146
- // Same line: it starts above the middle of the line so far.
147
- if (last && rect.top < (last.top + last.bottom) / 2) {
148
- // A line's text says where it is; a <br> only for a line without text (engines size
149
- // its box differently).
150
- if (text && !last.text) Object.assign(last, { top: rect.top, bottom: rect.bottom, text });
151
- else if (text === last.text) {
152
- last.top = Math.min(last.top, rect.top);
153
- last.bottom = Math.max(last.bottom, rect.bottom);
154
- }
155
- } else lines.push({ top: rect.top, bottom: rect.bottom, text });
156
- }
157
- const bottoms = lines.slice(1).map((line, i) => {
158
- const above = lines[i] as { bottom: number };
159
- return (above.bottom + line.top) / 2 - box.top;
160
- });
161
- bottoms.push(box.height);
162
- return bottoms;
163
- }
164
-
165
159
  /**
166
160
  * A table block's line ends without those inside a row that may not split (`cantSplit`), unless
167
161
  * the row is taller than a page.
@@ -190,214 +184,515 @@ function headerHeight(element: HTMLElement): number {
190
184
  return bottom ? bottom - element.getBoundingClientRect().top : 0;
191
185
  }
192
186
 
193
- /** The lines that end with an explicit page break, by the break's position. */
194
- function breakLines(element: HTMLElement, bottoms: readonly number[]): number[] {
187
+ /** The lines that end with one of the explicit breaks `attr` marks, by the break's position. */
188
+ function breakLines(element: HTMLElement, bottoms: readonly number[], attr: string): number[] {
195
189
  const top = element.getBoundingClientRect().top;
196
- return [...element.querySelectorAll(`br[${WORD_PAGE_BREAK_ATTR}]`)].map((br) => {
190
+ return [...element.querySelectorAll(`br[${attr}]`)].map((br) => {
197
191
  const y = br.getBoundingClientRect().top - top;
198
192
  const line = bottoms.findIndex((bottom) => y < bottom);
199
193
  return line < 0 ? bottoms.length - 1 : line;
200
194
  });
201
195
  }
202
196
 
197
+ /** A section on pages: its setup, its blocks and where they are measured. */
198
+ interface Section {
199
+ setup: SectionJSON;
200
+ geometry: Geometry;
201
+ columns: ColumnsPx;
202
+ blocks: WordBlock[];
203
+ flow: FlowSection;
204
+ /** A hidden page of the section's, and in it a column holding its blocks. */
205
+ measuring: HTMLElement;
206
+ column: HTMLElement;
207
+ }
208
+
209
+ /** `renderDocument`'s options. */
210
+ export interface RenderDocumentOptions {
211
+ /** `markup` (the default): insertions underlined, deletions struck through; `simple`, `final`: as if accepted. */
212
+ review?: ReviewView;
213
+ /** Fields show their codes instead of their results (Word's Alt+F9). */
214
+ fieldCodes?: boolean;
215
+ /**
216
+ * The URL to show a picture's image from (`key` in `resources`): the app's (a package part's
217
+ * object URL…); `null` (or "") shows the picture's box. Left out, or undefined for a key: the
218
+ * resource's own image `data:` URL or web URL (fetched as it is shown).
219
+ */
220
+ resource?: (key: string, resource: ResourceJSON) => string | null | undefined;
221
+ }
222
+
203
223
  /**
204
- * Lays a v3 document out on pages inside `container`. Headers, footers, footnotes and floating
205
- * content are not laid out yet (Phase 11); tables are shown from their verbatim XML until
206
- * Phase 10.
224
+ * Lays a v3 document out on pages inside `container`: every section's page setup, its columns
225
+ * (a band per section on a page), continuous sections, Word's blank pages, headers and footers
226
+ * with their page fields, footnotes at their columns' feet and endnotes after the text.
207
227
  */
208
228
  export function renderDocument(
209
229
  document: FoliDocument,
210
230
  container: HTMLElement,
211
- options: Omit<BlockOptions, "lineRatio"> = {},
231
+ options: RenderDocumentOptions = {},
212
232
  ): DocumentPages {
213
233
  const doc = container.ownerDocument;
234
+ // What notes show: numbers depend on the pages only where they restart on each.
235
+ const model = document.stories ? parseContent(document.content) : null;
236
+ const hideDeleted = (options.review ?? "markup") !== "markup";
237
+ const numbersOf = (pageOf?: (pos: number, story: string) => number | undefined) =>
238
+ model
239
+ ? noteNumbers(model, document, { hideDeleted, ...(pageOf ? { pageOf } : {}) }).filter(
240
+ (n) => !hideDeleted || !n.deleted,
241
+ )
242
+ : [];
243
+ let references = numbersOf();
244
+ const noteTextsNow = noteTexts(references);
214
245
  const blocks = renderBlocks(document, doc, {
215
246
  ...options,
216
247
  lineRatio: measureLineRatio(container),
248
+ notes: { references: noteTextsNow },
217
249
  });
218
- // Sections: consecutive blocks with one page setup. A section starts a new page unless it is
219
- // continuous with the same geometry (shortcut: a continuous section with another geometry
220
- // starts a new page).
221
- const groups: { geometry: Geometry; blocks: WordBlock[] }[] = [];
250
+ const sections: Section[] = [];
251
+ const setups: SectionJSON[] = [];
252
+ const lineRatio = measureLineRatio(container);
253
+ const regions = new PageRegions(
254
+ doc,
255
+ { ...options, lineRatio, measureIn: () => container },
256
+ new WeakMap(),
257
+ );
258
+ const resolver = new Resolver(document);
259
+ regions.setDocument(document, setups, resolver);
260
+ const notes = new PageNotes(
261
+ doc,
262
+ { ...options, lineRatio, measureIn: () => container },
263
+ new WeakMap(),
264
+ );
265
+ const geometryOf = new Map<FlowSection, Geometry>();
266
+ const sectionOf = new Map<WordBlock, Section>();
222
267
  let current: WordBlock[] = [];
223
- const close = (section: SectionJSON) => {
224
- const g = geometry(section);
225
- const previous = groups[groups.length - 1];
226
- if (section.type === "continuous" && previous && sameGeometry(previous.geometry, g))
227
- previous.blocks.push(...current);
228
- else groups.push({ geometry: g, blocks: current });
268
+ const close = (setup: SectionJSON) => {
269
+ const g = geometry(setup);
270
+ const columns = columnsPx(setup);
271
+ const index = setups.length;
272
+ setups.push(setup);
273
+ const flow: FlowSection = {
274
+ index,
275
+ start: setup.type ?? "nextPage",
276
+ columns: columns.widths.length,
277
+ pageStart: setup.pageNumbers?.start,
278
+ box: (page) => ({ height: regions.boxHeight(index, page) }),
279
+ samePage: (other) => sameGeometry(g, geometryOf.get(other) as Geometry),
280
+ };
281
+ geometryOf.set(flow, g);
282
+ // Measured in a page of the section's width, out of view, in its first column's width.
283
+ const { page, body } = createPage(doc, g);
284
+ page.style.position = "absolute";
285
+ page.style.visibility = "hidden";
286
+ page.style.height = "auto";
287
+ const column = doc.createElement("div");
288
+ column.style.display = "flow-root";
289
+ column.style.width = `${columns.widths[0]}px`;
290
+ body.append(column);
291
+ container.append(page);
292
+ column.append(...current.map((block) => block.element));
293
+ const section = { setup, geometry: g, columns, blocks: current, flow, measuring: page, column };
294
+ for (const block of current) sectionOf.set(block, section);
295
+ sections.push(section);
229
296
  current = [];
230
297
  };
231
298
  for (const block of blocks) {
232
299
  current.push(block);
233
300
  if (block.section) close(block.section);
234
301
  }
235
- if (current.length || !groups.length) close(document.section);
302
+ if (current.length || !sections.length) close(document.section);
303
+ notes.setDocument(document, setups, resolver, references);
304
+ sections.forEach((section, i) => {
305
+ const next = sections[i + 1];
306
+ section.flow.balanced =
307
+ !!next &&
308
+ section.flow.columns > 1 &&
309
+ next.setup.type === "continuous" &&
310
+ sameGeometry(section.geometry, next.geometry);
311
+ });
236
312
 
237
- const pages: HTMLElement[] = [];
238
- const firstPage = new Map<number, number>();
239
- /** Every fragment placed, in order: its page and how many lines it shows (measured lazily). */
240
- const placements: { page: number; nodes: number[] | null; lines: () => number }[] = [];
241
- const cellPages: { page: number; text: string }[] = [];
242
- for (const group of groups) {
243
- const g = group.geometry;
244
- // Measure in a page of the section's width, out of view.
245
- const measuring = createPage(doc, g);
246
- measuring.page.style.position = "absolute";
247
- measuring.page.style.visibility = "hidden";
248
- measuring.page.style.height = "auto";
249
- container.append(measuring.page);
250
- for (const block of group.blocks) measuring.body.append(block.element);
251
- const lines = new Map<WordBlock, number[]>();
313
+ /** A block's height and lines at each column width it was asked for. */
314
+ type Measured = Pick<BlockBox, "height" | "lines"> & {
315
+ shown(): number[];
316
+ /** The lines, at this width, that end with a break `attr` marks. */
317
+ breaks(attr: string): number[];
318
+ /** The footnotes referred to in the block, each with the line holding its reference. */
319
+ references(): { story: string; line: number }[];
320
+ };
321
+ const measured = new Map<WordBlock, Map<number, Measured>>();
322
+ const inWidth = (block: WordBlock, width: number) => {
323
+ const section = sectionOf.get(block) as Section;
324
+ const widths: Map<number, Measured> = measured.get(block) ?? new Map();
325
+ measured.set(block, widths);
326
+ const known = widths.get(width);
327
+ if (known) return known;
328
+ const { column, geometry: g } = section;
252
329
  const pageHeight = g.height - g.top - g.bottom;
253
- const linesOf = (block: WordBlock) => {
254
- let value = lines.get(block);
255
- if (!value) {
256
- value = keepRows(block.element, lineBottoms(block.element), pageHeight);
257
- lines.set(block, value);
258
- }
330
+ const atWidth = <T>(read: () => T): T => {
331
+ const before = column.style.width;
332
+ column.style.width = `${width}px`;
333
+ const value = read();
334
+ column.style.width = before;
259
335
  return value;
260
336
  };
261
- // Each cell paragraph's top in its block, measured while the blocks are laid out whole.
262
- const cellTops = new Map<WordBlock, { top: number; text: string }[]>();
263
- for (const block of group.blocks) {
264
- const cells = block.element.querySelectorAll("[data-foli-cell]");
265
- if (!cells.length) continue;
266
- const top = block.element.getBoundingClientRect().top;
267
- cellTops.set(
268
- block,
269
- [...cells].map((cell) => ({
270
- top: cell.getBoundingClientRect().top - top,
271
- text: cell.textContent ?? "",
272
- })),
273
- );
337
+ const height = atWidth(() => block.element.getBoundingClientRect().height);
338
+ const hasBreak = !!block.element.querySelector(BREAKS);
339
+ // A paragraph kept together is one line to the flow, unless it cannot be: taller than a
340
+ // page, or broken by a page break.
341
+ const kept = block.keepLines && !hasBreak && height <= pageHeight;
342
+ let lines: number[] | undefined;
343
+ const shown = () => {
344
+ lines ??= atWidth(() => keepRows(block.element, lineBottoms(block.element), pageHeight));
345
+ return lines;
346
+ };
347
+ const entry: Measured = {
348
+ height,
349
+ shown,
350
+ lines: () => (kept ? [height] : shown()),
351
+ breaks: (attr) => atWidth(() => breakLines(block.element, entry.lines(), attr)),
352
+ references: () =>
353
+ atWidth(() => {
354
+ const top = block.element.getBoundingClientRect().top;
355
+ const bottoms = entry.lines();
356
+ return [...block.element.querySelectorAll(`[${NOTE_REF_ATTR}]`)].map((element) => {
357
+ const y = element.getBoundingClientRect().bottom - top;
358
+ const line = bottoms.findIndex((bottom) => y <= bottom + 1);
359
+ return {
360
+ story: element.getAttribute(NOTE_REF_ATTR) as string,
361
+ line: line < 0 ? bottoms.length - 1 : line,
362
+ };
363
+ });
364
+ }),
365
+ };
366
+ widths.set(width, entry);
367
+ return entry;
368
+ };
369
+ const widthIn = (section: Section, fragment: Fragment) =>
370
+ section.columns.widths[fragment.column ?? 0] as number;
371
+
372
+ // Each cell paragraph's top in its block, measured while the blocks are laid out whole.
373
+ const cellTops = new Map<WordBlock, { top: number; text: string }[]>();
374
+ for (const block of blocks) {
375
+ const cells = block.element.querySelectorAll("[data-foli-cell]");
376
+ if (!cells.length) continue;
377
+ const top = block.element.getBoundingClientRect().top;
378
+ cellTops.set(
379
+ block,
380
+ [...cells].map((cell) => ({
381
+ top: cell.getBoundingClientRect().top - top,
382
+ text: cell.textContent ?? "",
383
+ })),
384
+ );
385
+ }
386
+ const headers = new Map<WordBlock, number>();
387
+ const endnotes = notes.endnotes();
388
+ const lastOfSection = (block: WordBlock, i: number) =>
389
+ !blocks[i + 1] || sectionOf.get(blocks[i + 1] as WordBlock) !== sectionOf.get(block);
390
+ const boxes: BlockBox[] = blocks.map((block, i) => {
391
+ const section = sectionOf.get(block) as Section;
392
+ const { widths } = section.columns;
393
+ const whole = inWidth(block, widths[0] as number);
394
+ const repeat = block.element.querySelector("tr") ? headerHeight(block.element) : 0;
395
+ if (repeat) headers.set(block, repeat);
396
+ const next = blocks[i + 1];
397
+ const has = (attr: string) => !!block.element.querySelector(`br[${attr}]`);
398
+ const hasPageBreak = has(WORD_PAGE_BREAK_ATTR);
399
+ const hasColumnBreak = has(WORD_COLUMN_BREAK_ATTR);
400
+ const index = section.flow.index ?? 0;
401
+ const refers = !!block.element.querySelector(`[${NOTE_REF_ATTR}]`);
402
+ return {
403
+ notes: refers
404
+ ? (column: number) =>
405
+ inWidth(block, widths[column] as number)
406
+ .references()
407
+ .flatMap(({ story, line }) => {
408
+ const note: FlowNote | null = notes.footnote(story, index);
409
+ return note ? [{ line, note }] : [];
410
+ })
411
+ : undefined,
412
+ endnotes: lastOfSection(block, i) ? endnotes.get(index) : undefined,
413
+ height: whole.height,
414
+ marginTop: block.before,
415
+ marginBottom: block.after,
416
+ repeat,
417
+ // A table splits at any line: no widow and orphan control across its rows.
418
+ anyLine: !!block.element.querySelector(":scope > table"),
419
+ keepWithNext: block.keepNext,
420
+ section: section.flow,
421
+ sectionMark:
422
+ !!block.section &&
423
+ !block.element.textContent &&
424
+ !block.element.querySelector(`[${PICTURE_ATTR}]`),
425
+ lines: whole.lines,
426
+ inColumn: widths.every((width) => width === widths[0])
427
+ ? undefined
428
+ : (column) => inWidth(block, widths[column] as number),
429
+ breaksAfter: (column = 0) => {
430
+ const measure = inWidth(block, widths[column] as number);
431
+ const breaks = hasPageBreak ? measure.breaks(WORD_PAGE_BREAK_ATTR) : [];
432
+ // The next block starts a page: this one's last line ends it.
433
+ if (next?.pageBreakBefore) breaks.push(measure.lines().length - 1);
434
+ return breaks;
435
+ },
436
+ columnBreaksAfter: (column = 0) =>
437
+ hasColumnBreak
438
+ ? inWidth(block, widths[column] as number).breaks(WORD_COLUMN_BREAK_ATTR)
439
+ : [],
440
+ };
441
+ });
442
+ // shortcut: widow and orphan control is on for every paragraph (Word's Normal has it; a
443
+ // paragraph turning it off is still kept to two lines).
444
+ const rules = {
445
+ orphans: 2,
446
+ widows: 2,
447
+ spacing: "word",
448
+ addSpacing: document.settings?.doNotUseHTMLParagraphAutoSpacing === true,
449
+ evenAndOddHeaders: document.settings?.evenAndOddHeaders === true,
450
+ notes: notes.flowRules(),
451
+ } as const;
452
+ let flowed = flowFrom(boxes, 0, rules);
453
+ let facts = pagesOf(boxes, flowed);
454
+ // The page count is known once flowed; a header holding it can change what fits.
455
+ for (let pass = 0; pass < 2 && regions.settle(facts); pass++) {
456
+ flowed = flowFrom(boxes, 0, rules);
457
+ facts = pagesOf(boxes, flowed);
458
+ }
459
+ // Numbers restarting on each page: known once flowed; a wider one is left as it is measured.
460
+ if (setups.some((setup) => noteProperties(document, "footnote", setup).restart === "eachPage")) {
461
+ const pages = new Map<string, number>();
462
+ for (const piece of notePieces(flowed))
463
+ if (!piece.fromLine && !pages.has(piece.id)) pages.set(piece.id, piece.page);
464
+ references = numbersOf((_pos, story) => pages.get(story));
465
+ const texts = noteTexts(references);
466
+ notes.setDocument(document, setups, resolver, references);
467
+ for (const block of blocks)
468
+ for (const element of block.element.querySelectorAll(`[${NOTE_REF_ATTR}]`))
469
+ element.textContent = texts.get(element.getAttribute(NOTE_REF_ATTR) as string) ?? "";
470
+ flowed = flowFrom(boxes, 0, rules);
471
+ facts = pagesOf(boxes, flowed);
472
+ }
473
+ const { fragments, gaps } = flowed;
474
+ const pieces = notePieces(flowed);
475
+ // What placing needs of the layout, read while the blocks are still laid out: split blocks' lines.
476
+ blocks.forEach((block, b) => {
477
+ const placed = fragments[b] ?? [];
478
+ if (placed.length < 2) return;
479
+ const section = sectionOf.get(block) as Section;
480
+ for (const fragment of placed) inWidth(block, widthIn(section, fragment)).lines();
481
+ });
482
+ for (const section of sections) section.measuring.remove();
483
+
484
+ // Each page's bands, from what is on it; a page with nothing (Word's blank page before an even
485
+ // or odd page section) has the setup of the page after it.
486
+ const bandsOf: Section[][] = [];
487
+ blocks.forEach((block, b) => {
488
+ for (const fragment of fragments[b] ?? []) {
489
+ const bands = bandsOf[fragment.page] ?? [];
490
+ bandsOf[fragment.page] = bands;
491
+ bands[fragment.band ?? 0] ??= sectionOf.get(block) as Section;
274
492
  }
275
- const headers = new Map<WordBlock, number>();
276
- const boxes: BlockBox[] = group.blocks.map((block, i) => {
277
- const height = block.element.getBoundingClientRect().height;
278
- const repeat = block.element.querySelector("tr") ? headerHeight(block.element) : 0;
279
- if (repeat) headers.set(block, repeat);
280
- const next = group.blocks[i + 1];
281
- const hasBreak = !!block.element.querySelector(`br[${WORD_PAGE_BREAK_ATTR}]`);
282
- // A paragraph kept together is one line to the flow, unless it cannot be: taller than a
283
- // page, or broken by a page break.
284
- const kept = block.keepLines && !hasBreak && height <= pageHeight;
285
- return {
286
- height,
287
- marginTop: block.before,
288
- marginBottom: block.after,
289
- repeat,
290
- // A table splits at any line: no widow and orphan control across its rows.
291
- anyLine: !!block.element.querySelector(":scope > table"),
292
- keepWithNext: block.keepNext,
293
- lines: () => (kept ? [height] : linesOf(block)),
294
- breaksAfter: () => {
295
- const breaks = hasBreak ? breakLines(block.element, linesOf(block)) : [];
296
- // The next block starts a page: this one's last line ends it.
297
- if (next?.pageBreakBefore) breaks.push((kept ? 1 : linesOf(block).length) - 1);
298
- return breaks;
299
- },
300
- };
301
- });
302
- // shortcut: widow and orphan control is on for every paragraph (Word's Normal has it; a
303
- // paragraph turning it off is still kept to two lines).
304
- const fragments = flow(boxes, pageHeight, { orphans: 2, widows: 2, spacing: "word" });
305
- // What placing needs of the layout, read while the blocks are still laid out: the lines of
306
- // split blocks, and which blocks end with an explicit page break.
307
- const endsWithBreak = new Set<WordBlock>();
308
- group.blocks.forEach((block, b) => {
309
- if ((fragments[b]?.length ?? 0) > 1) linesOf(block);
310
- if (!block.element.querySelector(`br[${WORD_PAGE_BREAK_ATTR}]`)) return;
311
- const bottoms = linesOf(block);
312
- if (breakLines(block.element, bottoms).includes(bottoms.length - 1)) endsWithBreak.add(block);
313
- });
314
- measuring.page.remove();
493
+ });
494
+ // A note can reach pages no text is on.
495
+ const count = Math.max(1, bandsOf.length, ...pieces.map((piece) => piece.page + 1));
496
+ const pageSetups: Section[] = [];
497
+ for (let p = count - 1; p >= 0; p--)
498
+ pageSetups[p] = bandsOf[p]?.[0] ?? pageSetups[p + 1] ?? (sections.at(-1) as Section);
499
+ const created = pageSetups.map((section, p) => {
500
+ const made = createPage(doc, section.geometry);
501
+ made.page.setAttribute(SHEET_ATTR, String(section.flow.index ?? 0));
502
+ const page = facts[p];
503
+ // Word's blank page before an even or odd page section has no header or footer (its PDF).
504
+ if (!page?.sectionPages) return made;
505
+ const { top, bottom } = regions.margins(page.section, page);
506
+ made.page.style.paddingTop = `${top}px`;
507
+ made.page.style.paddingBottom = `${bottom}px`;
508
+ for (const side of ["header", "footer"] as const) {
509
+ const drawing = regions.drawing(page.section, side, page);
510
+ if (!drawing) continue;
511
+ const region = regions.element(page.section, side);
512
+ region.append(drawing.content.content.cloneNode(true));
513
+ made.page.append(region);
514
+ }
515
+ return made;
516
+ });
517
+ const bandElements = new Map<string, { band: HTMLElement; columns: HTMLElement[] }>();
518
+ /** Where a fragment goes: the page's body, or its column when the page has bands. */
519
+ const holder = (
520
+ fragment: Pick<Fragment, "page" | "band" | "column" | "lead">,
521
+ section: Section,
522
+ ) => {
523
+ const { body } = created[fragment.page] as { body: HTMLElement };
524
+ const bands = bandsOf[fragment.page] ?? [section];
525
+ if (bands.length === 1 && section.flow.columns === 1) return body;
526
+ const band = fragment.band ?? 0;
527
+ // Bands in order: one that nothing starts in yet still comes before the later ones.
528
+ for (let b = 0; b <= band; b++) {
529
+ const key = `${fragment.page} ${b}`;
530
+ if (bandElements.has(key)) continue;
531
+ const made = bandElement(doc, (bands[b] as Section).columns);
532
+ bandElements.set(key, made);
533
+ body.append(made.band);
534
+ }
535
+ const made = bandElements.get(`${fragment.page} ${band}`) as {
536
+ band: HTMLElement;
537
+ columns: HTMLElement[];
538
+ };
539
+ if (fragment.lead) made.band.style.marginTop = `${fragment.lead}px`;
540
+ return made.columns[fragment.column ?? 0] as HTMLElement;
541
+ };
315
542
 
316
- const count = Math.max(1, ...fragments.flat().map((f) => f.page + 1));
317
- const groupPages = Array.from({ length: count }, () => createPage(doc, g));
318
- let previousOnPage: { page: number; block: number } | null = null;
319
- group.blocks.forEach((block, b) => {
320
- const placed = fragments[b] ?? [];
321
- const bottoms = placed.length > 1 ? linesOf(block) : [];
322
- placed.forEach((fragment, f) => {
323
- const target = groupPages[fragment.page] as { body: HTMLElement };
324
- let gap = 0;
325
- if (fragment.fromLine === 0) {
326
- if (previousOnPage?.page === fragment.page)
327
- gap = (group.blocks[previousOnPage.block] as WordBlock).after + block.before;
328
- else {
329
- // The first block on a page: Word keeps its space before on the section's first
330
- // page and after an explicit break only.
331
- const prior = group.blocks[b - 1];
332
- const forced =
333
- fragment.page === 0 ||
334
- block.pageBreakBefore ||
335
- (prior !== undefined && endsWithBreak.has(prior));
336
- gap = forced ? block.before : 0;
337
- }
338
- }
339
- let element: HTMLElement = block.element;
340
- if (placed.length > 1) {
341
- // A split block: each fragment shows its lines of the whole block, clipped.
342
- const top = fragment.fromLine ? (bottoms[fragment.fromLine - 1] ?? 0) : 0;
343
- const end =
344
- fragment.toLine === Number.POSITIVE_INFINITY
345
- ? (bottoms[bottoms.length - 1] ?? 0)
346
- : (bottoms[fragment.toLine - 1] ?? 0);
347
- const clip = doc.createElement("div");
348
- clip.style.overflow = "hidden";
349
- clip.style.height = `${end - top}px`;
350
- const inner = f === 0 ? block.element : (block.element.cloneNode(true) as HTMLElement);
351
- if (f > 0) inner.setAttribute("aria-hidden", "true");
352
- inner.style.marginTop = `${-top}px`;
353
- clip.append(inner);
354
- element = clip;
355
- const repeat = f > 0 ? (headers.get(block) ?? 0) : 0;
356
- if (repeat) {
357
- // The header rows again above the continuation.
358
- const header = doc.createElement("div");
359
- header.style.overflow = "hidden";
360
- header.style.height = `${repeat}px`;
361
- const copy = block.element.cloneNode(true) as HTMLElement;
362
- copy.setAttribute("aria-hidden", "true");
363
- copy.style.marginTop = "0";
364
- header.append(copy);
365
- element = doc.createElement("div");
366
- element.append(header, clip);
367
- }
368
- }
369
- element.style.marginTop = `${gap}px`;
370
- target.body.append(element);
371
- previousOnPage = { page: fragment.page, block: b };
372
- placements.push({
373
- page: pages.length + fragment.page,
374
- nodes: f === 0 ? block.nodes : null,
375
- lines: () =>
376
- (fragment.toLine === Number.POSITIVE_INFINITY
377
- ? linesOf(block).length
378
- : fragment.toLine) - fragment.fromLine,
379
- });
380
- });
381
- // Its cell paragraphs: on the page of the fragment their top is in.
382
- for (const cell of cellTops.get(block) ?? []) {
383
- let at = placed[0]?.page ?? 0;
384
- for (const fragment of placed) {
385
- const start = fragment.fromLine ? (bottoms[fragment.fromLine - 1] ?? 0) : 0;
386
- if (cell.top + 0.5 >= start) at = fragment.page;
543
+ /** The section a page's band is in: the one of the page's blocks, or of the page. */
544
+ const sectionAt = (page: number, band: number) =>
545
+ (bandsOf[page]?.[band] ?? pageSetups[page])?.flow.index ?? 0;
546
+ const groupsOf = (list: Parameters<typeof notes.groups>[0]): NoteGroup[] =>
547
+ notes.groups(list, sectionAt);
548
+ const footGroups = groupsOf(pieces).filter((group) => !group.inFlow);
549
+
550
+ const firstPage = new Map<number, number>();
551
+ /** Every fragment placed, in order: its page and how many lines it shows (measured lazily). */
552
+ const placements: {
553
+ page: number;
554
+ nodes: number[] | null;
555
+ mark: boolean;
556
+ lines: () => number;
557
+ }[] = [];
558
+ const cellPages: { page: number; text: string }[] = [];
559
+ blocks.forEach((block, b) => {
560
+ const section = sectionOf.get(block) as Section;
561
+ const placed = fragments[b] ?? [];
562
+ const bottomsOf = (fragment: Fragment) =>
563
+ inWidth(block, widthIn(section, fragment)).lines() as number[];
564
+ placed.forEach((fragment, f) => {
565
+ const target = holder(fragment, section);
566
+ let element: HTMLElement = block.element;
567
+ if (placed.length > 1) {
568
+ // A split block: each fragment shows its lines of the whole block, clipped.
569
+ const bottoms = bottomsOf(fragment);
570
+ const top = fragment.fromLine ? (bottoms[fragment.fromLine - 1] ?? 0) : 0;
571
+ const end =
572
+ fragment.toLine === Number.POSITIVE_INFINITY
573
+ ? (bottoms[bottoms.length - 1] ?? 0)
574
+ : (bottoms[fragment.toLine - 1] ?? 0);
575
+ const clip = doc.createElement("div");
576
+ clip.style.overflow = "hidden";
577
+ clip.style.height = `${end - top}px`;
578
+ const inner = f === 0 ? block.element : (block.element.cloneNode(true) as HTMLElement);
579
+ if (f > 0) inner.setAttribute("aria-hidden", "true");
580
+ inner.style.marginTop = `${-top}px`;
581
+ clip.append(inner);
582
+ element = clip;
583
+ const repeat = f > 0 ? (headers.get(block) ?? 0) : 0;
584
+ if (repeat) {
585
+ // The header rows again above the continuation.
586
+ const header = doc.createElement("div");
587
+ header.style.overflow = "hidden";
588
+ header.style.height = `${repeat}px`;
589
+ const copy = block.element.cloneNode(true) as HTMLElement;
590
+ copy.setAttribute("aria-hidden", "true");
591
+ copy.style.marginTop = "0";
592
+ header.append(copy);
593
+ element = doc.createElement("div");
594
+ element.append(header, clip);
387
595
  }
388
- cellPages.push({ page: pages.length + at, text: cell.text });
389
596
  }
390
- const first = placed[0];
391
- if (first) for (const index of block.nodes) firstPage.set(index, pages.length + first.page);
597
+ // A section's empty last paragraph takes no room.
598
+ if (fragment.mark) element.style.position = "absolute";
599
+ element.style.marginTop = `${fragment.fromLine === 0 ? (gaps[b] ?? 0) : 0}px`;
600
+ target.append(element);
601
+ placements.push({
602
+ page: fragment.page,
603
+ nodes: f === 0 ? block.nodes : null,
604
+ mark: !!fragment.mark,
605
+ lines: () =>
606
+ (fragment.toLine === Number.POSITIVE_INFINITY
607
+ ? inWidth(block, widthIn(section, fragment)).shown().length
608
+ : fragment.toLine) - fragment.fromLine,
609
+ });
392
610
  });
393
- for (const { page } of groupPages) {
394
- container.append(page);
395
- pages.push(page);
611
+ // Its cell paragraphs: on the page of the fragment their top is in.
612
+ for (const cell of cellTops.get(block) ?? []) {
613
+ let at = placed[0]?.page ?? 0;
614
+ for (const fragment of placed) {
615
+ const start = fragment.fromLine ? (bottomsOf(fragment)[fragment.fromLine - 1] ?? 0) : 0;
616
+ if (cell.top + 0.5 >= start) at = fragment.page;
617
+ }
618
+ cellPages.push({ page: at, text: cell.text });
396
619
  }
620
+ const first = placed[0];
621
+ if (first) for (const index of block.nodes) firstPage.set(index, first.page);
622
+ });
623
+ // Endnotes and footnotes set beneath the text come after the last block of their column.
624
+ for (const group of groupsOf(pieces))
625
+ if (group.inFlow)
626
+ holder(
627
+ { page: group.page, band: group.band, column: group.column },
628
+ sections[group.section] as Section,
629
+ ).append(
630
+ notes.groupElement(
631
+ group,
632
+ null,
633
+ undefined,
634
+ group.pieces[0]?.end
635
+ ? 0
636
+ : spaceAfterText(boxes, flowed, group.page, group.band, group.column),
637
+ ),
638
+ );
639
+ for (const group of groupsOf(pieces)) {
640
+ if (group.inFlow) continue;
641
+ const { page } = created[group.page] as { page: HTMLElement };
642
+ const section = sections[group.section] as Section;
643
+ const fact = facts[group.page];
644
+ const margin = fact?.sectionPages
645
+ ? regions.margins(fact.section, fact).bottom
646
+ : section.geometry.bottom;
647
+ const place = notes.footPlace(
648
+ { left: section.geometry.left, bottom: margin },
649
+ notes.stacked(group, footGroups),
650
+ );
651
+ page.append(notes.groupElement(group, place));
397
652
  }
653
+ const pages = created.map(({ page }) => {
654
+ container.append(page);
655
+ return page;
656
+ });
398
657
  let firstLine: Map<number, number> | null = null;
658
+ let starts: number[] | null = null;
659
+ const fieldLayout: FieldLayout = {
660
+ pages: facts.length,
661
+ pageAt: (pos) => {
662
+ if (!starts) {
663
+ const list: number[] = [];
664
+ (model ?? parseContent(document.content)).forEach((_node, offset) => {
665
+ list.push(offset);
666
+ });
667
+ starts = list;
668
+ }
669
+ // The top-level node holding `pos`, or the nearest one before it that is shown.
670
+ let index = starts.length - 1;
671
+ while (index > 0 && (starts[index] as number) > pos) index--;
672
+ while (index > 0 && !firstPage.has(index)) index--;
673
+ const fact = facts[firstPage.get(index) ?? -1];
674
+ if (!fact) return null;
675
+ const format = setups[fact.section]?.pageNumbers?.format;
676
+ return { number: fact.number, sectionPages: fact.sectionPages, format };
677
+ },
678
+ };
679
+ const px = (n: number) => `${n}px`;
399
680
  return {
400
681
  pages,
682
+ fieldLayout,
683
+ printStyles: () => {
684
+ const last = (sections.at(-1) as Section).geometry;
685
+ return printStyles(
686
+ `.${WORD_PAGE_CLASS}`,
687
+ { width: px(last.width), height: px(last.height) },
688
+ sections.map(({ geometry: g, flow }) => ({
689
+ width: px(g.width),
690
+ height: px(g.height),
691
+ index: flow.index ?? 0,
692
+ })),
693
+ "word",
694
+ );
695
+ },
401
696
  pageOf: (index) => firstPage.get(index),
402
697
  lineOf: (index) => {
403
698
  if (!firstLine) {
@@ -409,8 +704,10 @@ export function renderDocument(
409
704
  page = placement.page;
410
705
  line = 1;
411
706
  }
412
- for (const node of placement.nodes ?? []) firstLine.set(node, line);
413
- line += placement.lines();
707
+ // A section's mark is on the line before it, as Word numbers it.
708
+ for (const node of placement.nodes ?? [])
709
+ firstLine.set(node, placement.mark ? Math.max(line - 1, 1) : line);
710
+ if (!placement.mark) line += placement.lines();
414
711
  }
415
712
  }
416
713
  return firstLine.get(index);