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