@folijs/view 0.5.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 (61) hide show
  1. package/CHANGELOG.md +33 -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/layout/flow.d.ts +193 -20
  6. package/dist/layout/flow.d.ts.map +1 -1
  7. package/dist/layout/flow.js +789 -101
  8. package/dist/layout/flow.js.map +1 -1
  9. package/dist/print.d.ts +22 -0
  10. package/dist/print.d.ts.map +1 -0
  11. package/dist/print.js +31 -0
  12. package/dist/print.js.map +1 -0
  13. package/dist/view.d.ts +220 -7
  14. package/dist/view.d.ts.map +1 -1
  15. package/dist/view.js +1753 -208
  16. package/dist/view.js.map +1 -1
  17. package/dist/word/blocks.d.ts +30 -1
  18. package/dist/word/blocks.d.ts.map +1 -1
  19. package/dist/word/blocks.js +193 -40
  20. package/dist/word/blocks.js.map +1 -1
  21. package/dist/word/columns.d.ts +23 -0
  22. package/dist/word/columns.d.ts.map +1 -0
  23. package/dist/word/columns.js +51 -0
  24. package/dist/word/columns.js.map +1 -0
  25. package/dist/word/controls.d.ts +63 -0
  26. package/dist/word/controls.d.ts.map +1 -0
  27. package/dist/word/controls.js +411 -0
  28. package/dist/word/controls.js.map +1 -0
  29. package/dist/word/edit.d.ts +17 -5
  30. package/dist/word/edit.d.ts.map +1 -1
  31. package/dist/word/edit.js +157 -26
  32. package/dist/word/edit.js.map +1 -1
  33. package/dist/word/matches.d.ts +23 -0
  34. package/dist/word/matches.d.ts.map +1 -0
  35. package/dist/word/matches.js +97 -0
  36. package/dist/word/matches.js.map +1 -0
  37. package/dist/word/notes.d.ts +105 -0
  38. package/dist/word/notes.d.ts.map +1 -0
  39. package/dist/word/notes.js +392 -0
  40. package/dist/word/notes.js.map +1 -0
  41. package/dist/word/pages.d.ts +18 -13
  42. package/dist/word/pages.d.ts.map +1 -1
  43. package/dist/word/pages.js +420 -229
  44. package/dist/word/pages.js.map +1 -1
  45. package/dist/word/regions.d.ts +113 -0
  46. package/dist/word/regions.d.ts.map +1 -0
  47. package/dist/word/regions.js +374 -0
  48. package/dist/word/regions.js.map +1 -0
  49. package/package.json +2 -2
  50. package/src/clipboard.ts +3 -0
  51. package/src/layout/flow.ts +945 -110
  52. package/src/print.ts +48 -0
  53. package/src/view.ts +1957 -229
  54. package/src/word/blocks.ts +219 -36
  55. package/src/word/columns.ts +66 -0
  56. package/src/word/controls.ts +447 -0
  57. package/src/word/edit.ts +175 -23
  58. package/src/word/matches.ts +99 -0
  59. package/src/word/notes.ts +451 -0
  60. package/src/word/pages.ts +501 -220
  61. package/src/word/regions.ts +469 -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. */
@@ -34,6 +62,18 @@ export interface DocumentPages {
34
62
  * a vertical merge covers, as Word lists none), with the page (0-based) it starts on.
35
63
  */
36
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;
37
77
  /** Removes the pages. */
38
78
  destroy(): void;
39
79
  }
@@ -114,54 +154,6 @@ export function measureLineRatio(container: HTMLElement): (family: string) => nu
114
154
  };
115
155
  }
116
156
 
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
157
  /**
166
158
  * A table block's line ends without those inside a row that may not split (`cantSplit`), unless
167
159
  * the row is taller than a page.
@@ -190,20 +182,32 @@ function headerHeight(element: HTMLElement): number {
190
182
  return bottom ? bottom - element.getBoundingClientRect().top : 0;
191
183
  }
192
184
 
193
- /** The lines that end with an explicit page break, by the break's position. */
194
- 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[] {
195
187
  const top = element.getBoundingClientRect().top;
196
- return [...element.querySelectorAll(`br[${WORD_PAGE_BREAK_ATTR}]`)].map((br) => {
188
+ return [...element.querySelectorAll(`br[${attr}]`)].map((br) => {
197
189
  const y = br.getBoundingClientRect().top - top;
198
190
  const line = bottoms.findIndex((bottom) => y < bottom);
199
191
  return line < 0 ? bottoms.length - 1 : line;
200
192
  });
201
193
  }
202
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
+
203
207
  /**
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.
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.
207
211
  */
208
212
  export function renderDocument(
209
213
  document: FoliDocument,
@@ -211,193 +215,468 @@ export function renderDocument(
211
215
  options: Omit<BlockOptions, "lineRatio"> = {},
212
216
  ): DocumentPages {
213
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);
214
229
  const blocks = renderBlocks(document, doc, {
215
230
  ...options,
216
231
  lineRatio: measureLineRatio(container),
232
+ notes: { references: noteTextsNow },
217
233
  });
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[] }[] = [];
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>();
222
251
  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 });
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);
229
280
  current = [];
230
281
  };
231
282
  for (const block of blocks) {
232
283
  current.push(block);
233
284
  if (block.section) close(block.section);
234
285
  }
235
- 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
+ });
236
296
 
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[]>();
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;
252
313
  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
- }
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;
259
319
  return value;
260
320
  };
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
- );
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;
355
+
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;
274
476
  }
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();
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
+ };
315
526
 
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;
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);
387
579
  }
388
- cellPages.push({ page: pages.length + at, text: cell.text });
389
580
  }
390
- const first = placed[0];
391
- if (first) for (const index of block.nodes) firstPage.set(index, pages.length + first.page);
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,
593
+ });
392
594
  });
393
- for (const { page } of groupPages) {
394
- container.append(page);
395
- 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 });
396
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));
397
636
  }
637
+ const pages = created.map(({ page }) => {
638
+ container.append(page);
639
+ return page;
640
+ });
398
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`;
399
664
  return {
400
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
+ },
401
680
  pageOf: (index) => firstPage.get(index),
402
681
  lineOf: (index) => {
403
682
  if (!firstLine) {
@@ -409,8 +688,10 @@ export function renderDocument(
409
688
  page = placement.page;
410
689
  line = 1;
411
690
  }
412
- for (const node of placement.nodes ?? []) firstLine.set(node, line);
413
- 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();
414
695
  }
415
696
  }
416
697
  return firstLine.get(index);