@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
@@ -1,9 +1,15 @@
1
1
  import type { DocumentSettings } from "@folijs/core";
2
2
 
3
- /** CSS pixels per millimetre (CSS fixes 1in = 96px = 25.4mm). */
3
+ /**
4
+ * CSS pixels per millimetre (CSS fixes 1in = 96px = 25.4mm).
5
+ * @internal
6
+ */
4
7
  export const PX_PER_MM = 96 / 25.4;
5
8
 
6
- /** A rendered block's border-box height and vertical margins, in CSS px. */
9
+ /**
10
+ * A rendered block's border-box height and vertical margins, in CSS px.
11
+ * @internal
12
+ */
7
13
  export interface BlockBox {
8
14
  height: number;
9
15
  marginTop: number;
@@ -17,26 +23,135 @@ export interface BlockBox {
17
23
  /** Keep on the same page as the start of the next block (headings). */
18
24
  keepWithNext?: boolean;
19
25
  /** The lines that end with an explicit page break (indices into `lines()`), if any. */
20
- breaksAfter?(): readonly number[];
26
+ breaksAfter?(column?: number): readonly number[];
21
27
  /** Height shown again at the top of each fragment after the first (a table's header rows). */
22
28
  repeat?: number;
23
29
  /** Splits at any of its line ends, without widow and orphan control (a table's rows). */
24
30
  anyLine?: boolean;
25
31
  /**
26
- * Content height of the pages this block goes on, when not the flow's (a section's page). A
27
- * block with another page height than the one before it must start a page (an explicit
28
- * break before it): a page has one height.
32
+ * The lines that end with an explicit column break, if any: indices into the lines of column
33
+ * `column` (`inColumn`), as for `breaksAfter`.
34
+ */
35
+ columnBreaksAfter?(column?: number): readonly number[];
36
+ /**
37
+ * Content height of the pages this block goes on, when not the flow's. A block with another
38
+ * page height than the one before it must start a page (an explicit break before it).
39
+ * `section`, when given, says it instead.
29
40
  */
30
41
  pageHeight?: number;
42
+ /** The section it is in: its blocks are consecutive and share this object. */
43
+ section?: FlowSection;
44
+ /**
45
+ * An empty paragraph that only holds a section's break: Word gives it no room after text
46
+ * (not its line, not its spacing). Alone at the top of a column it is an ordinary line.
47
+ */
48
+ sectionMark?: boolean;
49
+ /** Its height and lines in column `column` of its section, when the columns' widths differ. */
50
+ inColumn?: ((column: number) => Pick<BlockBox, "height" | "lines">) | undefined;
51
+ /** The footnotes referred to, with the line (of `column`'s lines) holding each reference. */
52
+ notes?: ((column: number) => readonly { line: number; note: FlowNote }[]) | undefined;
53
+ /** What follows this block in the text: the endnotes ending its section or the document. */
54
+ endnotes?: readonly FlowNote[] | undefined;
55
+ }
56
+
57
+ /**
58
+ * A note, or a separator, as the flow sees it: lines, split between pages like a block's.
59
+ * @internal
60
+ */
61
+ export interface FlowNote {
62
+ /** Its story. */
63
+ id: string;
64
+ /** The bottom of each of its lines from its top, in column `column`'s width. */
65
+ lines(column: number): readonly number[];
31
66
  }
32
67
 
33
- /** The lines `[fromLine, toLine)` of a block, placed on one page (`toLine` Infinity: to the end). */
68
+ /**
69
+ * Lines `[fromLine, toLine)` of a note on a page, at the foot or (`end`) after the text.
70
+ * @internal
71
+ */
72
+ export interface NotePiece {
73
+ id: string;
74
+ page: number;
75
+ band?: number;
76
+ column?: number;
77
+ fromLine: number;
78
+ toLine: number;
79
+ /** An endnote, in the text's flow: the space above it when it starts there. */
80
+ end?: boolean;
81
+ lead?: number;
82
+ /** On a page after the last block's, for what was still to come. */
83
+ tail?: boolean;
84
+ }
85
+
86
+ /**
87
+ * What a page's layout depends on: first page, odd or even, by displayed number.
88
+ * @internal
89
+ */
90
+ export interface FlowPage {
91
+ /** The page's place in the document, from 0. */
92
+ index: number;
93
+ /** Its displayed number (`w:pgNumType` restarts count). */
94
+ number: number;
95
+ /** Whether its section starts on it. */
96
+ first: boolean;
97
+ }
98
+
99
+ /**
100
+ * A page as flowed: what decides its header and footer (its first section's).
101
+ * @internal
102
+ */
103
+ export interface PageFacts extends FlowPage {
104
+ /** The first section on it, by its `index` (a page nothing is on: the next page's). */
105
+ section: number;
106
+ /** How many pages that section has text on; 0 for a page nothing is on. */
107
+ sectionPages: number;
108
+ }
109
+
110
+ /**
111
+ * A section as the flow sees it.
112
+ * @internal
113
+ */
114
+ export interface FlowSection {
115
+ /** Its place among the document's sections, from 0. */
116
+ index?: number;
117
+ /** How it starts (Word's `w:type`). */
118
+ start: "nextPage" | "continuous" | "evenPage" | "oddPage" | "nextColumn";
119
+ columns: number;
120
+ /** A continuous section follows: its columns end level on its last page. */
121
+ balanced?: boolean;
122
+ /** The displayed number of its first page, when it restarts them. */
123
+ pageStart?: number | undefined;
124
+ /**
125
+ * The content box of a page that starts with this section. A section continuing on another's
126
+ * page has that page's box, less what is above its band.
127
+ */
128
+ box(page: FlowPage): { height: number };
129
+ /** Whether a page of this section is a page of `other` (a continuous one can share it). */
130
+ samePage(other: FlowSection): boolean;
131
+ }
132
+
133
+ /**
134
+ * The lines `[fromLine, toLine)` of a block, placed on one page (`toLine` Infinity: to the end).
135
+ * Line numbers are those of the column it is in, when columns' widths differ.
136
+ * @internal
137
+ */
34
138
  export interface Fragment {
35
139
  page: number;
36
140
  fromLine: number;
37
141
  toLine: number;
142
+ /** Its band on the page (one per section on it), when not the first. */
143
+ band?: number;
144
+ /** Its column in the band, when not the first. */
145
+ column?: number;
146
+ /** The first fragment of a band after the first: the space between the two bands. */
147
+ lead?: number;
148
+ /** A `sectionMark` block given no room. */
149
+ mark?: boolean;
150
+ /** The notes this fragment brought onto their pages: those it refers to, what was carried. */
151
+ notes?: NotePiece[];
38
152
  }
39
153
 
154
+ /** @internal */
40
155
  export interface FlowRules {
41
156
  /** Fewest lines of a split block left at the bottom of a page. */
42
157
  orphans: number;
@@ -44,16 +159,30 @@ export interface FlowRules {
44
159
  widows: number;
45
160
  /**
46
161
  * How margins (paragraph spacing) combine. `css` (the default): as CSS in a padded page.
47
- * `word`: as Word spaces paragraphs. The space after one and the space before the next add up.
48
- * A page that a block flowed onto (not one an explicit break started, nor the first) drops
49
- * the space before its first block. The space after the last block on a page need not fit.
162
+ * `word`: as Word spaces paragraphs: the larger of the space after one and the space before
163
+ * the next (Word's PDFs of the corpus). A page or column that a block flowed onto (not one an
164
+ * explicit break started, nor the first) drops the space before its first block. The space
165
+ * after the last block on a page need not fit.
50
166
  */
51
167
  spacing?: "css" | "word";
168
+ /**
169
+ * With `word` spacing: the two spaces add up instead (a document with Word's
170
+ * `w:doNotUseHTMLParagraphAutoSpacing`, in every compatibility mode).
171
+ */
172
+ addSpacing?: boolean;
173
+ /** The document has even and odd headers: a section restarting its numbers still keeps sides. */
174
+ evenAndOddHeaders?: boolean;
175
+ /** What goes above footnotes: on a page they start on, and on one they continue on. */
176
+ notes?: { separator: FlowNote; continuation: FlowNote } | undefined;
52
177
  }
53
178
 
179
+ /** @internal */
54
180
  export const DEFAULT_RULES: FlowRules = { orphans: 2, widows: 2 };
55
181
 
56
- /** Height of a page's content box (page height minus top and bottom margins), in CSS px. */
182
+ /**
183
+ * Height of a page's content box (page height minus top and bottom margins), in CSS px.
184
+ * @internal
185
+ */
57
186
  export function contentHeight({ pageSize, margins }: DocumentSettings): number {
58
187
  return (pageSize.height - margins.top - margins.bottom) * PX_PER_MM;
59
188
  }
@@ -61,32 +190,76 @@ export function contentHeight({ pageSize, margins }: DocumentSettings): number {
61
190
  // Half a pixel of slack: measured heights are fractional and rounding must not add a page.
62
191
  const SLACK = 0.5;
63
192
 
64
- /** Where the flow stands before a block: shared by a full and an incremental flow. */
193
+ /**
194
+ * Where the flow stands before a block: shared by a full and an incremental flow.
195
+ * @internal
196
+ */
65
197
  export interface FlowState {
66
198
  page: number;
199
+ /** The page's displayed number. */
200
+ number: number;
201
+ /** The page the current section started on. */
202
+ sectionPage: number;
203
+ band: number;
204
+ /** Where the band starts on its page, the space above it included. */
205
+ bandTop: number;
206
+ /** The space above the band: its first block's space before counts from there. */
207
+ lead: number;
208
+ column: number;
209
+ /** The height used in the column, from the band's top. */
67
210
  used: number;
211
+ /** The tallest of the band's earlier columns. */
212
+ bandBottom: number;
68
213
  previousMargin: number;
214
+ /** Blocks in the column. */
69
215
  onPage: number;
70
216
  /** An explicit page break ended the previous block: the next one starts a new page. */
71
217
  breakPending: boolean;
72
- /** The page is the first or an explicit break started it (Word keeps its first space before). */
218
+ /** An explicit column break ended it: the next one starts a new column. */
219
+ columnPending: boolean;
220
+ /** The column is the first or an explicit break started it (Word keeps its first space before). */
73
221
  forcedPage: boolean;
222
+ /** On a page shared by sections: the first of them, which gives the page its box. */
223
+ owner: { section: FlowSection; first: boolean } | null;
224
+ /** The height footnotes take at the foot of the band, their separator included. */
225
+ notes: number;
226
+ /** The height of each of those notes. */
227
+ noteParts: readonly number[];
228
+ /** What the notes of the page's earlier bands take. */
229
+ pageNotes: number;
230
+ /** Footnotes still to be placed, from the line each has got to. */
231
+ carry: readonly { note: FlowNote; from: number }[];
232
+ /** Room kept at the foot of a band (by page and band) for notes its later columns refer to. */
233
+ reserves: Readonly<Record<string, number>>;
74
234
  }
75
235
 
76
236
  /**
77
- * Page flow: the fragments of each block, in order. Blocks fill a page in order; a block that
78
- * does not fit is split at a line boundary, the lines that fit staying on the page, the rest
79
- * continuing at the top of the next one (as many pages as it takes). A page with room for no
80
- * line of the next block ends; an empty page always takes at least one line.
237
+ * Page flow: the fragments of each block, in order. Blocks fill a page's columns in order; a
238
+ * block that does not fit is split at a line boundary, the lines that fit staying in the column,
239
+ * the rest continuing at the top of the next column or page (as many as it takes). A column with
240
+ * room for no line of the next block ends; an empty one always takes at least one line.
81
241
  *
82
242
  * Rules:
83
- * - Explicit page breaks: the line holding one ends its page.
243
+ * - Explicit breaks: the line holding a page break ends its page, a column break its column.
84
244
  * - Widows and orphans: a split leaves at least `orphans` lines at the bottom of a page and
85
245
  * carries at least `widows` lines to the next; a block too short for both moves whole. Not
86
246
  * applied where only an empty page could hold the lines, nor across an explicit break.
87
- * - Keep with next: a `keepWithNext` block (and a chain of them) moves to the next page when
88
- * the block after it would start there, unless it already starts its page or the move would
89
- * not bring them together (then the flow stays as it was).
247
+ * - Keep with next: a `keepWithNext` block (and a chain of them) moves to the next column or page
248
+ * when the block after it would start there, unless it already starts its column or the move
249
+ * would not bring them together (then the flow stays as it was).
250
+ * - Sections (`BlockBox.section`): a new one starts as its `start` says, an even or odd page
251
+ * section after a blank page when the page's number asks for one. A continuous one with the
252
+ * same page opens a band below the last; each band has its section's columns. A band of a
253
+ * `balanced` section ends with its columns level: its last page's columns take the shortest
254
+ * height that holds them.
255
+ *
256
+ * - Footnotes (ADR-0007, on Word's PDFs): a line with a reference goes on a page only if it, the
257
+ * separator and the note's first line fit. The note then takes the room down to the text, up to
258
+ * all of it, so a long one fills the page; the rest is carried to the foot of the next page,
259
+ * under the continuation separator, before any text is placed there, as much as fits. Lines a widow, orphan or keep rule takes back take their notes with them. In a
260
+ * section with columns the notes are set in those columns across the foot of the band, whichever
261
+ * column refers to them, and every column's text ends above them.
262
+ * - Endnotes (`BlockBox.endnotes`) follow their block in the text, over as many pages as they need.
90
263
  *
91
264
  * Spacing follows CSS inside a padded page: the first block keeps its top margin, adjacent
92
265
  * margins collapse to the larger, and the last block's bottom margin stays inside the page
@@ -95,6 +268,7 @@ export interface FlowState {
95
268
  * no top margin.
96
269
  *
97
270
  * shortcut: positive margins only (negative margins collapse differently).
271
+ * @internal
98
272
  */
99
273
  export function flow(
100
274
  boxes: readonly BlockBox[],
@@ -104,13 +278,21 @@ export function flow(
104
278
  return flowFrom(boxes, pageHeight, rules).fragments;
105
279
  }
106
280
 
107
- /** A flow with the state before each block (and after the last), for the next incremental one. */
281
+ /**
282
+ * A flow with the state before each block (and after the last), for the next incremental one.
283
+ * @internal
284
+ */
108
285
  export interface FlowResult {
109
286
  fragments: Fragment[][];
110
287
  states: FlowState[];
288
+ /** The space above each block's first fragment (what the renderers write as its margin). */
289
+ gaps: number[];
111
290
  }
112
291
 
113
- /** What an incremental flow may reuse from the previous one. */
292
+ /**
293
+ * What an incremental flow may reuse from the previous one.
294
+ * @internal
295
+ */
114
296
  export interface Reuse {
115
297
  previous: FlowResult;
116
298
  /** Blocks before this index are the previous flow's first blocks, with the same boxes. */
@@ -122,11 +304,17 @@ export interface Reuse {
122
304
  previousIndex(i: number): number;
123
305
  }
124
306
 
307
+ /** A fragment's place in reading order: its page, band and column. */
308
+ const slot = (f: Fragment | undefined) =>
309
+ f ? f.page * 1_000_000 + (f.band ?? 0) * 1000 + (f.column ?? 0) : 0;
310
+
125
311
  /**
126
312
  * `flow`, reusing a previous one: it starts at `reuse.from` (backed up over a chain of
127
- * keep-with-next blocks, whose placement depends on what follows) with the previous state
128
- * there, and once the state before an unchanged block equals the previous state before it, the
129
- * rest is the previous flow's. The result is the same as a full flow.
313
+ * keep-with-next blocks, whose placement depends on what follows, and to the start of a balanced
314
+ * section, whose columns depend on all of it) with the previous state there, and once the state
315
+ * before an unchanged block equals the previous state before it, the rest is the previous flow's.
316
+ * The result is the same as a full flow.
317
+ * @internal
130
318
  */
131
319
  export function flowFrom(
132
320
  boxes: readonly BlockBox[],
@@ -135,172 +323,865 @@ export function flowFrom(
135
323
  reuse?: Reuse,
136
324
  ): FlowResult {
137
325
  let start = reuse ? Math.min(reuse.from, boxes.length, reuse.previous.fragments.length) : 0;
138
- while (start > 0 && boxes[start - 1]?.keepWithNext) start--;
326
+ const balancedAt = (i: number) => boxes[i]?.section?.balanced === true;
327
+ const sameSection = (i: number) => boxes[i]?.section === boxes[i - 1]?.section;
328
+ for (;;) {
329
+ if (start > 0 && boxes[start - 1]?.keepWithNext) start--;
330
+ else if (start > 0 && start < boxes.length && balancedAt(start) && sameSection(start)) start--;
331
+ else break;
332
+ }
139
333
  const result: Fragment[][] = reuse ? reuse.previous.fragments.slice(0, start) : [];
140
334
  const snapshots: FlowState[] = reuse ? reuse.previous.states.slice(0, start) : [];
335
+ const gaps: number[] = reuse ? reuse.previous.gaps.slice(0, start) : [];
141
336
  let state: FlowState = (
142
- reuse && reuse.previous.states[start]
337
+ reuse?.previous.states[start]
143
338
  ? { ...reuse.previous.states[start] }
144
- : { page: 0, used: 0, previousMargin: 0, onPage: 0, breakPending: false, forcedPage: true }
339
+ : {
340
+ page: 0,
341
+ number: boxes[0]?.section?.pageStart ?? 1,
342
+ sectionPage: 0,
343
+ band: 0,
344
+ bandTop: 0,
345
+ lead: 0,
346
+ column: 0,
347
+ used: 0,
348
+ bandBottom: 0,
349
+ previousMargin: 0,
350
+ onPage: 0,
351
+ breakPending: false,
352
+ columnPending: false,
353
+ forcedPage: true,
354
+ owner: null,
355
+ notes: 0,
356
+ noteParts: [],
357
+ pageNotes: 0,
358
+ carry: [],
359
+ reserves: {},
360
+ }
145
361
  ) as FlowState;
146
- /** Blocks that start a page because the keep-with-next rule moved them. */
362
+ /** Blocks that start a column because the keep-with-next rule moved them. */
147
363
  const breakBefore = new Set<number>();
148
364
  const word = rules.spacing === "word";
365
+ /** While a section is balanced: the page whose columns are limited, and to what height. */
366
+ let balancing: { page: number; height: number } | null = null;
367
+ /** Note pieces placed and not yet held by a fragment. */
368
+ let pending: NotePiece[] = [];
369
+ /** Asked for by a later column: the band is flowed again with this kept at its foot. */
370
+ let retry: { key: string; height: number } | null = null;
371
+ const bandKey = () => `${state.page}|${state.band}`;
372
+ const reserved = () => state.reserves[bandKey()] ?? 0;
373
+
149
374
  const newPage = (forced = false) => {
150
375
  state.page++;
376
+ state.number++;
377
+ state.band = 0;
378
+ state.bandTop = 0;
379
+ state.lead = 0;
380
+ state.column = 0;
151
381
  state.used = 0;
382
+ state.bandBottom = 0;
152
383
  state.onPage = 0;
153
384
  state.forcedPage = forced;
385
+ state.owner = null;
386
+ state.notes = 0;
387
+ state.noteParts = [];
388
+ state.pageNotes = 0;
389
+ // What was kept on earlier pages is done with.
390
+ if (Object.keys(state.reserves).length)
391
+ state.reserves = Object.fromEntries(
392
+ Object.entries(state.reserves).filter(([key]) => Number.parseInt(key, 10) >= state.page),
393
+ );
394
+ };
395
+ /** The next column of the band, or the next page after its last. */
396
+ const nextColumn = (box: BlockBox, forced = false) => {
397
+ if (state.column + 1 >= (box.section?.columns ?? 1)) {
398
+ newPage(forced);
399
+ return;
400
+ }
401
+ state.bandBottom = Math.max(state.bandBottom, state.used);
402
+ state.column++;
403
+ state.used = 0;
404
+ state.lead = 0;
405
+ state.onPage = 0;
406
+ state.forcedPage = forced;
407
+ };
408
+ /** The height a block may reach in the column, from the band's top. */
409
+ const room = (box: BlockBox) => pageRoom(box) - Math.max(state.notes, reserved());
410
+ /** The height a block may reach in the column, whatever notes take. */
411
+ const pageRoom = (box: BlockBox) => {
412
+ const section = state.owner?.section ?? box.section;
413
+ const page =
414
+ (section
415
+ ? section.box({
416
+ index: state.page,
417
+ number: state.number,
418
+ first: state.owner?.first ?? state.page === state.sectionPage,
419
+ }).height
420
+ : (box.pageHeight ?? flowHeight)) -
421
+ state.bandTop -
422
+ state.pageNotes;
423
+ return balancing?.page === state.page ? Math.min(page, balancing.height) : page;
424
+ };
425
+ const piece = (note: FlowNote, fromLine: number, toLine: number): NotePiece => ({
426
+ id: note.id,
427
+ page: state.page,
428
+ ...(state.band ? { band: state.band } : {}),
429
+ ...(state.column ? { column: state.column } : {}),
430
+ fromLine,
431
+ toLine,
432
+ });
433
+ /** A piece of the notes at a band's foot: they are the band's, not one column's. */
434
+ const footPiece = (note: FlowNote, fromLine: number, toLine: number): NotePiece => ({
435
+ id: note.id,
436
+ page: state.page,
437
+ ...(state.band ? { band: state.band } : {}),
438
+ fromLine,
439
+ toLine,
440
+ });
441
+ /** How much of an endnote, from line `from`, fits in `free`. */
442
+ const linesIn = (note: FlowNote, from: number, free: number) => {
443
+ const lines = note.lines(state.column);
444
+ const top = from ? (lines[from - 1] as number) : 0;
445
+ let to = from;
446
+ while (to < lines.length && (lines[to] as number) - top <= free + SLACK) to++;
447
+ return { to, height: to > from ? (lines[to - 1] as number) - top : 0, all: lines.length };
448
+ };
449
+ /** How much of a footnote fits in `free` beside the notes `parts` of the band's foot. */
450
+ const fitNote = (
451
+ note: FlowNote,
452
+ from: number,
453
+ free: number,
454
+ parts: readonly number[],
455
+ columns: number,
456
+ ) => {
457
+ const lines = note.lines(0);
458
+ const top = from ? (lines[from - 1] as number) : 0;
459
+ const beside = columns > 1 ? 0 : notesHeight(parts, 1);
460
+ const height = (to: number) => (lines[to] as number) - top;
461
+ let to = from;
462
+ while (
463
+ to < lines.length &&
464
+ (columns > 1 ? notesHeight([...parts, height(to)], columns) : beside + height(to)) <=
465
+ free + SLACK
466
+ )
467
+ to++;
468
+ return { to, height: to > from ? height(to - 1) : 0, all: lines.length };
469
+ };
470
+ const noteHeight = (note: FlowNote) => note.lines(0).at(-1) ?? 0;
471
+ const separatorPiece = (note: FlowNote) => footPiece(note, 0, note.lines(0).length);
472
+ /**
473
+ * On a page or band with no notes yet: what is carried over goes to its foot first, as much as
474
+ * fits, before any text (Word's PDFs: a long note takes whole pages). `force`: a page with
475
+ * nothing else on it takes at least a line.
476
+ */
477
+ const placeCarried = (box: BlockBox, force = false) => {
478
+ if (!state.carry.length || state.notes || state.onPage || !rules.notes) return;
479
+ const { continuation } = rules.notes;
480
+ const columns = box.section?.columns ?? 1;
481
+ const above = noteHeight(continuation);
482
+ const free = pageRoom(box) - state.used - above;
483
+ const placed: NotePiece[] = [];
484
+ const left: FlowState["carry"][number][] = [];
485
+ let parts: readonly number[] = [];
486
+ for (const item of state.carry) {
487
+ if (left.length) {
488
+ left.push(item);
489
+ continue;
490
+ }
491
+ let fit = fitNote(item.note, item.from, free, parts, columns);
492
+ if (fit.to === item.from && force && !placed.length)
493
+ fit = fitNote(item.note, item.from, lineHeightOf(item), parts, 1);
494
+ if (fit.to > item.from) {
495
+ placed.push(footPiece(item.note, item.from, fit.to));
496
+ parts = [...parts, fit.height];
497
+ }
498
+ if (fit.to < fit.all) left.push({ note: item.note, from: fit.to });
499
+ }
500
+ if (!placed.length) return;
501
+ pending.push(separatorPiece(continuation), ...placed);
502
+ state.notes = above + notesHeight(parts, columns);
503
+ state.noteParts = parts;
504
+ state.carry = left;
505
+ };
506
+ /** The height of the next line of a carried note. */
507
+ const lineHeightOf = ({ note, from }: FlowState["carry"][number]) => {
508
+ const lines = note.lines(0);
509
+ return (lines[from] as number) - (from ? (lines[from - 1] as number) : 0);
510
+ };
511
+ /** Whether what does not fit here can go elsewhere: not from an empty last column at the top. */
512
+ const canMove = (box: BlockBox) =>
513
+ state.onPage > 0 ||
514
+ state.notes > 0 ||
515
+ state.bandTop > 0 ||
516
+ state.column + 1 < (box.section?.columns ?? 1);
517
+
518
+ /** Moves to where `section` starts; the space above a new band when it opens one. */
519
+ const enterSection = (section: FlowSection, previous: FlowSection | undefined) => {
520
+ const pageBroken = state.breakPending;
521
+ state.breakPending = false;
522
+ state.columnPending = false;
523
+ // Word's PDFs: notes on the page and a continuous break into other columns start a page.
524
+ const notesAbove =
525
+ (state.notes > 0 || state.pageNotes > 0) && section.columns !== previous?.columns;
526
+ const samePage = !previous || (section.samePage(previous) && !notesAbove);
527
+ if (!pageBroken && samePage && section.start === "continuous") {
528
+ state.owner ??= {
529
+ section: previous ?? section,
530
+ first: state.page === state.sectionPage,
531
+ };
532
+ const lead = state.previousMargin;
533
+ state.bandTop += Math.max(state.bandBottom, state.used) + lead;
534
+ state.lead = lead;
535
+ state.band++;
536
+ state.column = 0;
537
+ state.used = 0;
538
+ state.bandBottom = 0;
539
+ state.onPage = 0;
540
+ state.forcedPage = true;
541
+ state.sectionPage = state.page;
542
+ state.pageNotes += state.notes;
543
+ state.notes = 0;
544
+ state.noteParts = [];
545
+ return lead;
546
+ }
547
+ if (
548
+ !pageBroken &&
549
+ samePage &&
550
+ section.start === "nextColumn" &&
551
+ section.columns === previous?.columns &&
552
+ state.column + 1 < section.columns
553
+ ) {
554
+ nextColumn({ section } as BlockBox, true);
555
+ return undefined;
556
+ }
557
+ if (state.onPage || state.used || state.column || state.band) newPage(true);
558
+ else state.forcedPage = true;
559
+ const wrongKind = (number: number) =>
560
+ (section.start === "oddPage" && number % 2 === 0) ||
561
+ (section.start === "evenPage" && number % 2 === 1);
562
+ // Word's even and odd page sections (its PDFs, every kind, start and page before): a blank
563
+ // page when the number the pages have reached is the wrong kind, unless the section restarts
564
+ // its numbers in a document without even and odd headers. A restart then takes its start, or
565
+ // the next number when that is the wrong kind.
566
+ if (wrongKind(state.number) && (section.pageStart === undefined || rules.evenAndOddHeaders))
567
+ newPage(true);
568
+ if (section.pageStart !== undefined)
569
+ state.number = section.pageStart + (wrongKind(section.pageStart) ? 1 : 0);
570
+ state.sectionPage = state.page;
571
+ return undefined;
154
572
  };
155
573
 
156
574
  const place = (box: BlockBox, index: number): Fragment[] => {
157
- const pageHeight = box.pageHeight ?? flowHeight;
158
- if ((state.breakPending || breakBefore.has(index)) && state.onPage) newPage(state.breakPending);
575
+ const fragments = placeBlock(box, index);
576
+ if (box.endnotes?.length) placeEndnotes(box, fragments);
577
+ return fragments;
578
+ };
579
+
580
+ /** A block's endnotes, after it in the text; lines that do not fit go on to the next column. */
581
+ const placeEndnotes = (box: BlockBox, fragments: Fragment[]) => {
582
+ let lead: number | undefined = state.onPage ? state.previousMargin : 0;
583
+ for (const note of box.endnotes ?? []) {
584
+ let from = 0;
585
+ for (;;) {
586
+ const lines = note.lines(state.column);
587
+ if (from >= lines.length) break;
588
+ const top = from ? (lines[from - 1] as number) : 0;
589
+ placeCarried(box);
590
+ const gap = state.onPage ? (lead ?? 0) : 0;
591
+ let fit = linesIn(note, from, room(box) - state.used - gap);
592
+ if (fit.to === from) {
593
+ if (canMove(box)) {
594
+ nextColumn(box);
595
+ continue;
596
+ }
597
+ fit = { ...fit, to: from + 1, height: (lines[from] as number) - top };
598
+ }
599
+ const part = piece(note, from, fit.to);
600
+ part.end = true;
601
+ if (gap) part.lead = gap;
602
+ pending.push(part);
603
+ lead = undefined;
604
+ state.used += gap + fit.height;
605
+ state.onPage++;
606
+ from = fit.to;
607
+ if (from < lines.length) nextColumn(box);
608
+ }
609
+ }
610
+ state.previousMargin = 0;
611
+ const last = fragments[fragments.length - 1];
612
+ if (last && pending.length) last.notes = [...(last.notes ?? []), ...pending];
613
+ if (last) pending = [];
614
+ };
615
+
616
+ const placeBlock = (box: BlockBox, index: number): Fragment[] => {
617
+ const previous = boxes[index - 1];
618
+ let lead: number | undefined;
619
+ if (index > 0 && box.section && previous?.section !== box.section)
620
+ lead = enterSection(box.section, previous?.section);
621
+ else if (state.breakPending && state.onPage) newPage(true);
622
+ else if (state.columnPending) nextColumn(box, true);
623
+ else if (breakBefore.has(index) && state.onPage) nextColumn(box);
159
624
  state.breakPending = false;
625
+ state.columnPending = false;
626
+ const leadPage = state.page;
627
+ const at = (fromLine: number, toLine: number): Fragment => {
628
+ const fragment: Fragment = { page: state.page, fromLine, toLine };
629
+ if (state.band) fragment.band = state.band;
630
+ if (state.column) fragment.column = state.column;
631
+ // Moved on to the next page, the block opens no band below anything.
632
+ if (lead !== undefined && state.page === leadPage) fragment.lead = lead;
633
+ lead = undefined;
634
+ if (pending.length) {
635
+ fragment.notes = pending;
636
+ pending = [];
637
+ }
638
+ return fragment;
639
+ };
640
+ if (box.sectionMark && state.onPage) {
641
+ gaps[index] = 0;
642
+ return [{ ...at(0, Infinity), mark: true }];
643
+ }
160
644
  const above = state.previousMargin;
161
645
  state.previousMargin = box.marginBottom;
646
+ const adding = word && rules.addSpacing === true;
162
647
  const gap = () => {
163
- if (!state.onPage) return word && !state.forcedPage ? 0 : box.marginTop;
164
- return word ? above + box.marginTop : Math.max(above, box.marginTop);
648
+ if (!state.onPage) {
649
+ if (word && !state.forcedPage) return 0;
650
+ return adding ? box.marginTop : Math.max(0, box.marginTop - state.lead);
651
+ }
652
+ return adding ? above + box.marginTop : Math.max(above, box.marginTop);
165
653
  };
166
654
  // The bottom margin that must fit on the page (Word lets the space after hang).
167
655
  const below = word ? 0 : box.marginBottom;
168
- const forced = box.breaksAfter?.() ?? [];
169
- if (!forced.length && state.used + gap() + box.height + below <= pageHeight + SLACK) {
170
- state.used += gap() + box.height;
656
+ const pageBreaks = box.breaksAfter?.(state.column) ?? [];
657
+ const columnBreaks = box.columnBreaksAfter?.(state.column) ?? [];
658
+ const forced = pageBreaks.length + columnBreaks.length > 0;
659
+ let measured: Pick<BlockBox, "height" | "lines"> = box.inColumn?.(state.column) ?? box;
660
+ /** The notes referred to on each line, in the column it is in now. */
661
+ const referred = () => {
662
+ const byLine = new Map<number, FlowNote[]>();
663
+ for (const { line, note } of box.notes?.(state.column) ?? [])
664
+ byLine.set(line, [...(byLine.get(line) ?? []), note]);
665
+ return byLine;
666
+ };
667
+ let notesOf = referred();
668
+ if (state.carry.length && !state.onPage) placeCarried(box);
669
+ if (
670
+ !forced &&
671
+ !notesOf.size &&
672
+ state.used + gap() + measured.height + below <= room(box) + SLACK
673
+ ) {
674
+ const space = gap();
675
+ gaps[index] = space;
676
+ state.used += space + measured.height;
171
677
  state.onPage++;
172
- return [{ page: state.page, fromLine: 0, toLine: Infinity }];
678
+ return [at(0, Infinity)];
173
679
  }
174
- const lines = box.lines();
175
- const count = lines.length;
176
- const breaks = new Set(forced.filter((line) => line >= 0 && line < count));
680
+ let lines = measured.lines();
681
+ let count = lines.length;
682
+ const inRange = (list: readonly number[]) =>
683
+ new Set(list.filter((at) => at >= 0 && at < count));
684
+ let pageAfter = inRange(pageBreaks);
685
+ let columnAfter = inRange(columnBreaks);
177
686
  const fragments: Fragment[] = [];
178
687
  let line = 0;
688
+ /** The explicit breaks passed so far. */
689
+ let passed = 0;
690
+ /** After a move: `measured` is the new column's, and `line` where the text has got to. */
691
+ const remeasure = (broken = false) => {
692
+ if (!box.inColumn) return;
693
+ const next = box.inColumn(state.column);
694
+ if (next === measured) return;
695
+ const nextLines = next.lines();
696
+ // shortcut: the same share of the text is taken to start the same line in another
697
+ // width (a line either way); a word-exact tail needs the text in the flow's terms.
698
+ const share = line ? (lines[line - 1] as number) / (measured.height || 1) : 0;
699
+ measured = next;
700
+ lines = nextLines;
701
+ count = lines.length;
702
+ // Breaks are lines of this width.
703
+ pageAfter = inRange(box.breaksAfter?.(state.column) ?? []);
704
+ columnAfter = inRange(box.columnBreaksAfter?.(state.column) ?? []);
705
+ if (line > 0) {
706
+ // After an explicit break the text goes on right after the same break.
707
+ const after = [...pageAfter, ...columnAfter].sort((a, b) => a - b)[passed - 1];
708
+ let mapped = lines.findIndex((bottom) => bottom / (next.height || 1) > share + 1e-6);
709
+ if (mapped < 0) mapped = count - 1;
710
+ line = broken && after !== undefined ? after + 1 : Math.max(mapped, 1);
711
+ }
712
+ // Nothing left in this width (all of it fits one wider line): the last fragment ends it.
713
+ if (line >= count) {
714
+ const last = fragments.at(-1);
715
+ if (last) last.toLine = Infinity;
716
+ }
717
+ };
179
718
  while (line < count) {
180
719
  // The lines up to the next explicit break (or the end) can be split freely.
181
720
  let segmentEnd = line;
182
- while (segmentEnd < count && !breaks.has(segmentEnd)) segmentEnd++;
721
+ while (segmentEnd < count && !pageAfter.has(segmentEnd) && !columnAfter.has(segmentEnd))
722
+ segmentEnd++;
183
723
  segmentEnd = Math.min(segmentEnd + 1, count);
184
724
  const top = line ? (lines[line - 1] as number) : 0;
185
725
  // Only the block's first fragment has the gap above it; the others repeat its header.
186
726
  const spacing = line === 0 ? gap() : (box.repeat ?? 0);
727
+ notesOf = referred();
728
+ placeCarried(box);
729
+ const limit = pageRoom(box);
730
+ /**
731
+ * The footnotes of lines `line` to `to - 1` at the band's foot, each taking the room down
732
+ * to the text after its line; null when one's first line does not fit (`force`: it goes in).
733
+ * With columns the notes share the foot of them all: above them goes the tallest column.
734
+ */
735
+ // A block kept whole is one line to the flow already.
736
+ const keepAll = count === 1;
737
+ const planNotes = (to: number, force = false) => {
738
+ const plan = {
739
+ notes: state.notes,
740
+ parts: state.noteParts,
741
+ carry: state.carry,
742
+ pieces: [] as NotePiece[],
743
+ };
744
+ if (!notesOf.size || !rules.notes) return plan;
745
+ const columns = box.section?.columns ?? 1;
746
+ for (let at = line; at < to; at++)
747
+ for (const note of notesOf.get(at) ?? []) {
748
+ // Behind a note already cut, it waits its turn.
749
+ if (plan.carry.length) {
750
+ plan.carry = [...plan.carry, { note, from: 0 }];
751
+ continue;
752
+ }
753
+ const { separator } = rules.notes;
754
+ const first = !plan.notes;
755
+ const above = first
756
+ ? noteHeight(separator)
757
+ : plan.notes - notesHeight(plan.parts, columns);
758
+ // Word's PDFs: the lines that the widow and orphan rules keep with this one stay above
759
+ // the note, and the paragraph's space after stays between its last line and the notes.
760
+ let kept = at + 1;
761
+ if (!box.anyLine && !keepAll) {
762
+ kept = Math.max(kept, line + rules.orphans);
763
+ if (count - kept < rules.widows) kept = count;
764
+ kept = Math.min(kept, segmentEnd);
765
+ }
766
+ const after = kept === count ? box.marginBottom : 0;
767
+ const own = state.used + spacing + (lines[kept - 1] as number) - top + after;
768
+ const text = Math.max(own, columns > 1 && state.column ? state.bandBottom : 0);
769
+ let fit = fitNote(note, 0, limit - text - above, plan.parts, columns);
770
+ if (
771
+ columns > 1 &&
772
+ state.column &&
773
+ !force &&
774
+ (!fit.to || (fit.to < fit.all && text > own))
775
+ ) {
776
+ // A later column's note, cut short by what the earlier columns hold: in Word they
777
+ // end above it. They are flowed again with its room kept, whole if the page can.
778
+ const lines = note.lines(0);
779
+ const whole = above + notesHeight([...plan.parts, lines.at(-1) as number], columns);
780
+ const one = above + notesHeight([...plan.parts, lines[0] as number], columns);
781
+ const height = whole < limit / 2 ? whole : one;
782
+ if (height > reserved() + SLACK && height < limit) retry = { key: bandKey(), height };
783
+ }
784
+ if (!fit.to) {
785
+ if (!force) return null;
786
+ fit = fitNote(note, 0, lineHeightOf({ note, from: 0 }), [], 1);
787
+ }
788
+ if (first) plan.pieces.push(separatorPiece(separator));
789
+ plan.pieces.push(footPiece(note, 0, fit.to));
790
+ plan.parts = [...plan.parts, fit.height];
791
+ plan.notes = above + notesHeight(plan.parts, columns);
792
+ if (fit.to < fit.all) plan.carry = [{ note, from: fit.to }];
793
+ }
794
+ return plan;
795
+ };
187
796
  let end = line;
188
797
  while (end < segmentEnd) {
189
798
  const bottom = (lines[end] as number) - top + (end + 1 === count ? below : 0);
190
- if (state.used + spacing + bottom > pageHeight + SLACK) break;
799
+ const plan = planNotes(end + 1);
800
+ if (
801
+ !plan ||
802
+ state.used + spacing + bottom + Math.max(plan.notes, reserved()) > limit + SLACK
803
+ )
804
+ break;
191
805
  end++;
192
806
  }
193
807
  if (end < segmentEnd && end > line && !box.anyLine) {
194
808
  // A natural split: keep `widows` lines for the next page and `orphans` on this one.
195
809
  const kept = Math.min(end, segmentEnd - rules.widows);
196
810
  if (kept - line >= rules.orphans) end = kept;
197
- else if (state.onPage) end = line;
811
+ else if (canMove(box)) end = line;
198
812
  }
199
813
  if (end === line) {
200
- if (state.onPage) {
201
- newPage();
814
+ if (canMove(box)) {
815
+ nextColumn(box);
816
+ remeasure();
202
817
  continue;
203
818
  }
204
819
  end = line + 1; // a line taller than a page is placed anyway
205
820
  }
206
- fragments.push({ page: state.page, fromLine: line, toLine: end });
821
+ // What the lines kept refer to: lines taken back take their notes with them.
822
+ const kept = planNotes(end, true);
823
+ if (kept) {
824
+ state.notes = kept.notes;
825
+ state.noteParts = kept.parts;
826
+ state.carry = kept.carry;
827
+ pending.push(...kept.pieces);
828
+ }
829
+ if (line === 0) gaps[index] = spacing;
830
+ fragments.push(at(line, end));
207
831
  state.used += spacing + (lines[end - 1] as number) - top;
208
832
  state.onPage++;
209
833
  line = end;
210
- const broken = breaks.has(end - 1);
211
- if (line < count) newPage();
212
- else if (broken) state.breakPending = true;
834
+ const pageBroken = pageAfter.has(end - 1);
835
+ const columnBroken = columnAfter.has(end - 1);
836
+ if (line < count) {
837
+ if (pageBroken || columnBroken) passed++;
838
+ if (pageBroken) newPage();
839
+ else nextColumn(box, columnBroken);
840
+ remeasure(pageBroken || columnBroken);
841
+ } else if (pageBroken) state.breakPending = true;
842
+ else if (columnBroken) state.columnPending = true;
213
843
  }
214
844
  // Moved whole to a later page: not split.
215
845
  const [only] = fragments;
216
- if (fragments.length === 1 && only && !forced.length) only.toLine = Infinity;
846
+ if (fragments.length === 1 && only && !forced) only.toLine = Infinity;
217
847
  return fragments;
218
848
  };
219
849
 
220
850
  /** The flow as it was before a keep-with-next move, by the block that triggered it. */
221
851
  const attempts = new Map<
222
852
  number,
223
- { first: number; result: Fragment[][]; snapshots: FlowState[]; state: FlowState }
224
- >();
225
- let index = start;
226
- while (index < boxes.length) {
227
- // Realigned with the previous flow: the rest is unchanged (no keep-with-next decision
228
- // about this block, made with the block before it, is pending). The block before it must
229
- // be unchanged too: had it been keep-with-next before the edit, the previous flow from
230
- // here holds a decision about a chain that no longer exists.
231
- const was =
232
- reuse && index > start && !attempts.size && reuse.previousIndex(index - 1) >= 0
233
- ? reuse.previousIndex(index)
234
- : -1;
235
- const before = was >= 0 ? reuse?.previous.states[was] : undefined;
236
- if (before && !boxes[index - 1]?.keepWithNext && sameState(before, state)) {
237
- const previous = reuse as Reuse;
238
- result.length = index;
239
- snapshots.length = index;
240
- result.push(...previous.previous.fragments.slice(was));
241
- snapshots.push(...previous.previous.states.slice(was, -1));
242
- return {
243
- fragments: result,
244
- states: [...snapshots, { ...(previous.previous.states.at(-1) as FlowState) }],
245
- };
853
+ {
854
+ first: number;
855
+ result: Fragment[][];
856
+ snapshots: FlowState[];
857
+ gaps: number[];
858
+ state: FlowState;
246
859
  }
247
- snapshots[index] = { ...state };
248
- const fragments = place(boxes[index] as BlockBox, index);
249
- result[index] = fragments;
250
- const previous = result[index - 1];
251
- const startsLater =
252
- previous !== undefined &&
253
- (fragments[0]?.page ?? 0) > (previous[previous.length - 1]?.page ?? 0);
254
- const attempt = attempts.get(index);
255
- if (attempt) {
256
- attempts.delete(index);
257
- // The move did not bring them together (the block does not fit after the heading on a
258
- // page of its own either): keep the flow as it was.
259
- if (startsLater) {
260
- result.splice(attempt.first, result.length - attempt.first, ...attempt.result);
261
- snapshots.splice(attempt.first, snapshots.length - attempt.first, ...attempt.snapshots);
262
- state = attempt.state;
263
- index++;
264
- continue;
860
+ >();
861
+
862
+ /** Flows blocks `from` to `to`; a result when the rest could be taken from `reuse`. */
863
+ const run = (from: number, to: number): FlowResult | null => {
864
+ let index = from;
865
+ while (index < to) {
866
+ // Realigned with the previous flow: the rest is unchanged (no keep-with-next decision
867
+ // about this block, made with the block before it, is pending). The block before it must
868
+ // be unchanged too: had it been keep-with-next before the edit, the previous flow from
869
+ // here holds a decision about a chain that no longer exists. Inside a balanced section the
870
+ // columns depend on the whole section: only its start realigns.
871
+ const was =
872
+ reuse &&
873
+ !balancing &&
874
+ index > start &&
875
+ !attempts.size &&
876
+ reuse.previousIndex(index - 1) >= 0
877
+ ? reuse.previousIndex(index)
878
+ : -1;
879
+ const before = was >= 0 ? reuse?.previous.states[was] : undefined;
880
+ if (
881
+ before &&
882
+ !boxes[index - 1]?.keepWithNext &&
883
+ !(balancedAt(index) && sameSection(index)) &&
884
+ sameState(before, state)
885
+ ) {
886
+ const previous = (reuse as Reuse).previous;
887
+ result.length = index;
888
+ snapshots.length = index;
889
+ gaps.length = index;
890
+ result.push(...previous.fragments.slice(was));
891
+ snapshots.push(...previous.states.slice(was, -1));
892
+ gaps.push(...previous.gaps.slice(was));
893
+ return {
894
+ fragments: result,
895
+ states: [...snapshots, { ...(previous.states.at(-1) as FlowState) }],
896
+ gaps,
897
+ };
265
898
  }
266
- }
267
- if (startsLater && boxes[index - 1]?.keepWithNext) {
268
- // The chain of keep-with-next blocks before this one, each whole on one page.
269
- let first = index - 1;
270
- while (
271
- first > 0 &&
272
- boxes[first - 1]?.keepWithNext &&
273
- result[first - 1]?.length === 1 &&
274
- result[first - 1]?.[0]?.page === result[first]?.[0]?.page
275
- )
276
- first--;
277
- const beforeFirst = snapshots[first] as FlowState;
278
- if (!breakBefore.has(first) && beforeFirst.onPage > 0 && result[first]?.length === 1) {
279
- attempts.set(index, {
280
- first,
281
- result: result.slice(first),
282
- snapshots: snapshots.slice(first),
283
- state: { ...state },
284
- });
285
- breakBefore.add(first);
286
- state = { ...beforeFirst };
899
+ snapshots[index] = { ...state };
900
+ const fragments = place(boxes[index] as BlockBox, index);
901
+ if (retry) {
902
+ const { key, height } = retry;
903
+ retry = null;
904
+ const [page, band] = key.split("|").map(Number) as [number, number];
905
+ // Back to the first block on that band: it may have started on an earlier page.
906
+ let first = index;
907
+ while (
908
+ first > from &&
909
+ result[first - 1]?.some((f) => f.page === page && (f.band ?? 0) === band)
910
+ )
911
+ first--;
912
+ const before = snapshots[first] as FlowState;
913
+ state = { ...before, reserves: { ...before.reserves, [key]: height } };
287
914
  result.length = first;
915
+ snapshots.length = first;
916
+ gaps.length = first;
917
+ attempts.clear();
918
+ for (const moved of breakBefore) if (moved >= first) breakBefore.delete(moved);
919
+ pending = [];
288
920
  index = first;
289
921
  continue;
290
922
  }
923
+ result[index] = fragments;
924
+ const previous = result[index - 1];
925
+ const startsLater =
926
+ previous !== undefined && slot(fragments[0]) > slot(previous[previous.length - 1]);
927
+ const attempt = attempts.get(index);
928
+ if (attempt) {
929
+ attempts.delete(index);
930
+ // The move did not bring them together (the block does not fit after the heading on a
931
+ // page of its own either): keep the flow as it was.
932
+ if (startsLater) {
933
+ result.splice(attempt.first, result.length - attempt.first, ...attempt.result);
934
+ snapshots.splice(attempt.first, snapshots.length - attempt.first, ...attempt.snapshots);
935
+ gaps.splice(attempt.first, gaps.length - attempt.first, ...attempt.gaps);
936
+ state = attempt.state;
937
+ index++;
938
+ continue;
939
+ }
940
+ }
941
+ if (startsLater && boxes[index - 1]?.keepWithNext && sameSection(index)) {
942
+ // The chain of keep-with-next blocks before this one, each whole in one column (keeping
943
+ // reaches no further back than the section: it starts where its `start` says).
944
+ let first = index - 1;
945
+ while (
946
+ first > 0 &&
947
+ sameSection(first) &&
948
+ boxes[first - 1]?.keepWithNext &&
949
+ result[first - 1]?.length === 1 &&
950
+ slot(result[first - 1]?.[0]) === slot(result[first]?.[0])
951
+ )
952
+ first--;
953
+ const beforeFirst = snapshots[first] as FlowState;
954
+ if (!breakBefore.has(first) && beforeFirst.onPage > 0 && result[first]?.length === 1) {
955
+ attempts.set(index, {
956
+ first,
957
+ result: result.slice(first),
958
+ snapshots: snapshots.slice(first),
959
+ gaps: gaps.slice(first),
960
+ state: { ...state },
961
+ });
962
+ breakBefore.add(first);
963
+ state = { ...beforeFirst };
964
+ result.length = first;
965
+ index = first;
966
+ continue;
967
+ }
968
+ }
969
+ index++;
970
+ const section = boxes[index - 1]?.section;
971
+ if (
972
+ !balancing &&
973
+ section?.balanced &&
974
+ section.columns > 1 &&
975
+ boxes[index]?.section !== section
976
+ )
977
+ balance(index);
291
978
  }
292
- index++;
979
+ return null;
980
+ };
981
+
982
+ /**
983
+ * Levels the columns of the balanced section ending before block `end`: flows it again with
984
+ * its last page's columns limited, looking for the shortest height that keeps it on that page.
985
+ */
986
+ const balance = (end: number) => {
987
+ const section = boxes[end - 1]?.section as FlowSection;
988
+ let first = end - 1;
989
+ while (first > 0 && boxes[first - 1]?.section === section) first--;
990
+ const from = snapshots[first] as FlowState;
991
+ const { page } = state;
992
+ let high = Math.max(state.bandBottom, state.used);
993
+ let low = high / section.columns - 1;
994
+ /** The section flowed with its last page's columns `height` tall: does it stay there? */
995
+ const attempt = (height: number) => {
996
+ balancing = { page, height };
997
+ state = { ...from };
998
+ result.length = first;
999
+ snapshots.length = first;
1000
+ attempts.clear();
1001
+ for (const moved of breakBefore) if (moved >= first) breakBefore.delete(moved);
1002
+ run(first, end);
1003
+ // The last column takes what it is given: a column over the limit is a failure too.
1004
+ return state.page === page && Math.max(state.used, state.bandBottom) <= height + SLACK;
1005
+ };
1006
+ while (high - low > 0.5) {
1007
+ const middle = (low + high) / 2;
1008
+ if (attempt(middle)) high = middle;
1009
+ else low = middle;
1010
+ }
1011
+ if (!attempt(high)) attempt(Number.POSITIVE_INFINITY);
1012
+ balancing = null;
1013
+ };
1014
+
1015
+ /** What is still carried after the last block goes on pages of its own. */
1016
+ const finishNotes = () => {
1017
+ const held = result[result.length - 1];
1018
+ const last = held?.[held.length - 1];
1019
+ const box = boxes[boxes.length - 1];
1020
+ if (!held || !last || !box || (!state.carry.length && !last.notes?.some((p) => p.tail))) return;
1021
+ const end = state;
1022
+ state = { ...state };
1023
+ while (state.carry.length) {
1024
+ newPage();
1025
+ placeCarried(box, true);
1026
+ }
1027
+ const notes = [
1028
+ ...(last.notes ?? []).filter((p) => !p.tail),
1029
+ ...pending.map((p) => ({ ...p, tail: true })),
1030
+ ];
1031
+ pending = [];
1032
+ state = end;
1033
+ result[result.length - 1] = [...held.slice(0, -1), { ...last, notes }];
1034
+ };
1035
+
1036
+ const reused = run(start, boxes.length);
1037
+ if (reused) return reused;
1038
+ finishNotes();
1039
+ return {
1040
+ fragments: result,
1041
+ states: [...snapshots.slice(0, boxes.length), { ...state }],
1042
+ gaps: gaps.slice(0, boxes.length),
1043
+ };
1044
+ }
1045
+
1046
+ /**
1047
+ * Each page of a flow: its number, its first section and whether that section starts on it. A page
1048
+ * nothing is on (the blank page before an even or odd page section) has the next page's section.
1049
+ * @internal
1050
+ */
1051
+ export function pagesOf(boxes: readonly BlockBox[], result: FlowResult): PageFacts[] {
1052
+ const pages: (PageFacts | undefined)[] = [];
1053
+ const owners: FlowSection[] = [];
1054
+ const seen = new Set<FlowSection>();
1055
+ const onPages = new Map<FlowSection, Set<number>>();
1056
+ result.fragments.forEach((fragments, i) => {
1057
+ const section = boxes[i]?.section as FlowSection;
1058
+ const after = result.states[i + 1] as FlowState;
1059
+ const own = onPages.get(section) ?? new Set<number>();
1060
+ onPages.set(section, own);
1061
+ const places = [...fragments, ...fragments.flatMap((fragment) => fragment.notes ?? [])];
1062
+ for (const { page } of places) {
1063
+ own.add(page);
1064
+ if (!pages[page]) {
1065
+ owners[page] = section;
1066
+ pages[page] = {
1067
+ index: page,
1068
+ // Pages count on from a block's first to its last: the number where it ended tells.
1069
+ number: after.number - (after.page - page),
1070
+ first: !seen.has(section),
1071
+ section: section.index ?? 0,
1072
+ sectionPages: 0,
1073
+ };
1074
+ }
1075
+ seen.add(section);
1076
+ }
1077
+ });
1078
+ pages.forEach((page, p) => {
1079
+ if (page) page.sectionPages = onPages.get(owners[p] as FlowSection)?.size ?? 0;
1080
+ });
1081
+ for (let p = pages.length - 1; p >= 0; p--) {
1082
+ const next = pages[p + 1] as PageFacts;
1083
+ pages[p] ??= { ...next, index: p, number: next.number - 1, first: false, sectionPages: 0 };
293
1084
  }
294
- return { fragments: result, states: [...snapshots.slice(0, boxes.length), { ...state }] };
1085
+ return pages as PageFacts[];
295
1086
  }
296
1087
 
1088
+ /**
1089
+ * Notes of heights `parts` set in `columns` columns, as Word sets those of a section with columns
1090
+ * (its PDFs): whole, in order, each column as full as the height the set needs. That height and
1091
+ * the column of each. One column: their sum.
1092
+ * @internal
1093
+ */
1094
+ export function arrangeNotes(
1095
+ parts: readonly number[],
1096
+ columns: number,
1097
+ ): { height: number; columnOf: number[] } {
1098
+ const total = parts.reduce((sum, part) => sum + part, 0);
1099
+ if (columns <= 1 || parts.length <= 1) return { height: total, columnOf: parts.map(() => 0) };
1100
+ const pack = (height: number) => {
1101
+ const columnOf: number[] = [];
1102
+ let column = 0;
1103
+ let used = 0;
1104
+ let tallest = 0;
1105
+ for (const part of parts) {
1106
+ if (used && used + part > height + 0.01) {
1107
+ column++;
1108
+ used = 0;
1109
+ }
1110
+ used += part;
1111
+ tallest = Math.max(tallest, used);
1112
+ columnOf.push(column);
1113
+ }
1114
+ return column < columns ? { height: tallest, columnOf } : null;
1115
+ };
1116
+ let low = Math.max(...parts, total / columns);
1117
+ let best = pack(low);
1118
+ if (best) return best;
1119
+ let high = total;
1120
+ best = pack(high) as NonNullable<ReturnType<typeof pack>>;
1121
+ while (high - low > 0.25) {
1122
+ const middle = (low + high) / 2;
1123
+ const tried = pack(middle);
1124
+ if (tried) {
1125
+ best = tried;
1126
+ high = middle;
1127
+ } else low = middle;
1128
+ }
1129
+ return best;
1130
+ }
1131
+
1132
+ const notesHeight = (parts: readonly number[], columns: number) =>
1133
+ arrangeNotes(parts, columns).height;
1134
+
1135
+ /**
1136
+ * The space after the last block of a column of a page, as flowed (what ends its text).
1137
+ * @internal
1138
+ */
1139
+ export function spaceAfterText(
1140
+ boxes: readonly BlockBox[],
1141
+ result: Pick<FlowResult, "fragments">,
1142
+ page: number,
1143
+ band: number,
1144
+ column: number,
1145
+ ): number {
1146
+ for (let i = result.fragments.length - 1; i >= 0; i--)
1147
+ for (const f of result.fragments[i] ?? [])
1148
+ if (f.page === page && (f.band ?? 0) === band && (f.column ?? 0) === column)
1149
+ return boxes[i]?.marginBottom ?? 0;
1150
+ return 0;
1151
+ }
1152
+
1153
+ /**
1154
+ * Every note piece of a flow, in order.
1155
+ * @internal
1156
+ */
1157
+ export const notePieces = (result: Pick<FlowResult, "fragments">): NotePiece[] =>
1158
+ result.fragments.flatMap((fragments) => fragments.flatMap((f) => f.notes ?? []));
1159
+
297
1160
  function sameState(a: FlowState, b: FlowState): boolean {
298
1161
  return (
1162
+ a.notes === b.notes &&
1163
+ JSON.stringify(a.reserves) === JSON.stringify(b.reserves) &&
1164
+ a.noteParts.length === b.noteParts.length &&
1165
+ a.noteParts.every((part, i) => part === b.noteParts[i]) &&
1166
+ a.pageNotes === b.pageNotes &&
1167
+ a.carry.length === b.carry.length &&
1168
+ a.carry.every(
1169
+ (item, i) => item.note.id === b.carry[i]?.note.id && item.from === b.carry[i]?.from,
1170
+ ) &&
299
1171
  a.page === b.page &&
1172
+ a.number === b.number &&
1173
+ a.sectionPage === b.sectionPage &&
1174
+ a.band === b.band &&
1175
+ a.bandTop === b.bandTop &&
1176
+ a.lead === b.lead &&
1177
+ a.column === b.column &&
300
1178
  a.used === b.used &&
1179
+ a.bandBottom === b.bandBottom &&
301
1180
  a.previousMargin === b.previousMargin &&
302
1181
  a.onPage === b.onPage &&
303
1182
  a.breakPending === b.breakPending &&
304
- a.forcedPage === b.forcedPage
1183
+ a.columnPending === b.columnPending &&
1184
+ a.forcedPage === b.forcedPage &&
1185
+ a.owner === b.owner
305
1186
  );
306
1187
  }