@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
@@ -8,19 +8,32 @@ export function contentHeight({ pageSize, margins }) {
8
8
  // Half a pixel of slack: measured heights are fractional and rounding must not add a page.
9
9
  const SLACK = 0.5;
10
10
  /**
11
- * Page flow: the fragments of each block, in order. Blocks fill a page in order; a block that
12
- * does not fit is split at a line boundary, the lines that fit staying on the page, the rest
13
- * continuing at the top of the next one (as many pages as it takes). A page with room for no
14
- * line of the next block ends; an empty page always takes at least one line.
11
+ * Page flow: the fragments of each block, in order. Blocks fill a page's columns in order; a
12
+ * block that does not fit is split at a line boundary, the lines that fit staying in the column,
13
+ * the rest continuing at the top of the next column or page (as many as it takes). A column with
14
+ * room for no line of the next block ends; an empty one always takes at least one line.
15
15
  *
16
16
  * Rules:
17
- * - Explicit page breaks: the line holding one ends its page.
17
+ * - Explicit breaks: the line holding a page break ends its page, a column break its column.
18
18
  * - Widows and orphans: a split leaves at least `orphans` lines at the bottom of a page and
19
19
  * carries at least `widows` lines to the next; a block too short for both moves whole. Not
20
20
  * applied where only an empty page could hold the lines, nor across an explicit break.
21
- * - Keep with next: a `keepWithNext` block (and a chain of them) moves to the next page when
22
- * the block after it would start there, unless it already starts its page or the move would
23
- * not bring them together (then the flow stays as it was).
21
+ * - Keep with next: a `keepWithNext` block (and a chain of them) moves to the next column or page
22
+ * when the block after it would start there, unless it already starts its column or the move
23
+ * would not bring them together (then the flow stays as it was).
24
+ * - Sections (`BlockBox.section`): a new one starts as its `start` says, an even or odd page
25
+ * section after a blank page when the page's number asks for one. A continuous one with the
26
+ * same page opens a band below the last; each band has its section's columns. A band of a
27
+ * `balanced` section ends with its columns level: its last page's columns take the shortest
28
+ * height that holds them.
29
+ *
30
+ * - Footnotes (ADR-0007, on Word's PDFs): a line with a reference goes on a page only if it, the
31
+ * separator and the note's first line fit. The note then takes the room down to the text, up to
32
+ * all of it, so a long one fills the page; the rest is carried to the foot of the next page,
33
+ * 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
34
+ * section with columns the notes are set in those columns across the foot of the band, whichever
35
+ * column refers to them, and every column's text ends above them.
36
+ * - Endnotes (`BlockBox.endnotes`) follow their block in the text, over as many pages as they need.
24
37
  *
25
38
  * Spacing follows CSS inside a padded page: the first block keeps its top margin, adjacent
26
39
  * margins collapse to the larger, and the last block's bottom margin stays inside the page
@@ -33,68 +46,498 @@ const SLACK = 0.5;
33
46
  export function flow(boxes, pageHeight, rules = DEFAULT_RULES) {
34
47
  return flowFrom(boxes, pageHeight, rules).fragments;
35
48
  }
49
+ /** A fragment's place in reading order: its page, band and column. */
50
+ const slot = (f) => f ? f.page * 1_000_000 + (f.band ?? 0) * 1000 + (f.column ?? 0) : 0;
36
51
  /**
37
52
  * `flow`, reusing a previous one: it starts at `reuse.from` (backed up over a chain of
38
- * keep-with-next blocks, whose placement depends on what follows) with the previous state
39
- * there, and once the state before an unchanged block equals the previous state before it, the
40
- * rest is the previous flow's. The result is the same as a full flow.
53
+ * keep-with-next blocks, whose placement depends on what follows, and to the start of a balanced
54
+ * section, whose columns depend on all of it) with the previous state there, and once the state
55
+ * before an unchanged block equals the previous state before it, the rest is the previous flow's.
56
+ * The result is the same as a full flow.
41
57
  */
42
58
  export function flowFrom(boxes, flowHeight, rules = DEFAULT_RULES, reuse) {
43
59
  let start = reuse ? Math.min(reuse.from, boxes.length, reuse.previous.fragments.length) : 0;
44
- while (start > 0 && boxes[start - 1]?.keepWithNext)
45
- start--;
60
+ const balancedAt = (i) => boxes[i]?.section?.balanced === true;
61
+ const sameSection = (i) => boxes[i]?.section === boxes[i - 1]?.section;
62
+ for (;;) {
63
+ if (start > 0 && boxes[start - 1]?.keepWithNext)
64
+ start--;
65
+ else if (start > 0 && start < boxes.length && balancedAt(start) && sameSection(start))
66
+ start--;
67
+ else
68
+ break;
69
+ }
46
70
  const result = reuse ? reuse.previous.fragments.slice(0, start) : [];
47
71
  const snapshots = reuse ? reuse.previous.states.slice(0, start) : [];
48
- let state = (reuse && reuse.previous.states[start]
72
+ const gaps = reuse ? reuse.previous.gaps.slice(0, start) : [];
73
+ let state = (reuse?.previous.states[start]
49
74
  ? { ...reuse.previous.states[start] }
50
- : { page: 0, used: 0, previousMargin: 0, onPage: 0, breakPending: false, forcedPage: true });
51
- /** Blocks that start a page because the keep-with-next rule moved them. */
75
+ : {
76
+ page: 0,
77
+ number: boxes[0]?.section?.pageStart ?? 1,
78
+ sectionPage: 0,
79
+ band: 0,
80
+ bandTop: 0,
81
+ lead: 0,
82
+ column: 0,
83
+ used: 0,
84
+ bandBottom: 0,
85
+ previousMargin: 0,
86
+ onPage: 0,
87
+ breakPending: false,
88
+ columnPending: false,
89
+ forcedPage: true,
90
+ owner: null,
91
+ notes: 0,
92
+ noteParts: [],
93
+ pageNotes: 0,
94
+ carry: [],
95
+ reserves: {},
96
+ });
97
+ /** Blocks that start a column because the keep-with-next rule moved them. */
52
98
  const breakBefore = new Set();
53
99
  const word = rules.spacing === "word";
100
+ /** While a section is balanced: the page whose columns are limited, and to what height. */
101
+ let balancing = null;
102
+ /** Note pieces placed and not yet held by a fragment. */
103
+ let pending = [];
104
+ /** Asked for by a later column: the band is flowed again with this kept at its foot. */
105
+ let retry = null;
106
+ const bandKey = () => `${state.page}|${state.band}`;
107
+ const reserved = () => state.reserves[bandKey()] ?? 0;
54
108
  const newPage = (forced = false) => {
55
109
  state.page++;
110
+ state.number++;
111
+ state.band = 0;
112
+ state.bandTop = 0;
113
+ state.lead = 0;
114
+ state.column = 0;
56
115
  state.used = 0;
116
+ state.bandBottom = 0;
57
117
  state.onPage = 0;
58
118
  state.forcedPage = forced;
119
+ state.owner = null;
120
+ state.notes = 0;
121
+ state.noteParts = [];
122
+ state.pageNotes = 0;
123
+ // What was kept on earlier pages is done with.
124
+ if (Object.keys(state.reserves).length)
125
+ state.reserves = Object.fromEntries(Object.entries(state.reserves).filter(([key]) => Number.parseInt(key, 10) >= state.page));
126
+ };
127
+ /** The next column of the band, or the next page after its last. */
128
+ const nextColumn = (box, forced = false) => {
129
+ if (state.column + 1 >= (box.section?.columns ?? 1)) {
130
+ newPage(forced);
131
+ return;
132
+ }
133
+ state.bandBottom = Math.max(state.bandBottom, state.used);
134
+ state.column++;
135
+ state.used = 0;
136
+ state.lead = 0;
137
+ state.onPage = 0;
138
+ state.forcedPage = forced;
139
+ };
140
+ /** The height a block may reach in the column, from the band's top. */
141
+ const room = (box) => pageRoom(box) - Math.max(state.notes, reserved());
142
+ /** The height a block may reach in the column, whatever notes take. */
143
+ const pageRoom = (box) => {
144
+ const section = state.owner?.section ?? box.section;
145
+ const page = (section
146
+ ? section.box({
147
+ index: state.page,
148
+ number: state.number,
149
+ first: state.owner?.first ?? state.page === state.sectionPage,
150
+ }).height
151
+ : (box.pageHeight ?? flowHeight)) -
152
+ state.bandTop -
153
+ state.pageNotes;
154
+ return balancing?.page === state.page ? Math.min(page, balancing.height) : page;
155
+ };
156
+ const piece = (note, fromLine, toLine) => ({
157
+ id: note.id,
158
+ page: state.page,
159
+ ...(state.band ? { band: state.band } : {}),
160
+ ...(state.column ? { column: state.column } : {}),
161
+ fromLine,
162
+ toLine,
163
+ });
164
+ /** A piece of the notes at a band's foot: they are the band's, not one column's. */
165
+ const footPiece = (note, fromLine, toLine) => ({
166
+ id: note.id,
167
+ page: state.page,
168
+ ...(state.band ? { band: state.band } : {}),
169
+ fromLine,
170
+ toLine,
171
+ });
172
+ /** How much of an endnote, from line `from`, fits in `free`. */
173
+ const linesIn = (note, from, free) => {
174
+ const lines = note.lines(state.column);
175
+ const top = from ? lines[from - 1] : 0;
176
+ let to = from;
177
+ while (to < lines.length && lines[to] - top <= free + SLACK)
178
+ to++;
179
+ return { to, height: to > from ? lines[to - 1] - top : 0, all: lines.length };
180
+ };
181
+ /** How much of a footnote fits in `free` beside the notes `parts` of the band's foot. */
182
+ const fitNote = (note, from, free, parts, columns) => {
183
+ const lines = note.lines(0);
184
+ const top = from ? lines[from - 1] : 0;
185
+ const beside = columns > 1 ? 0 : notesHeight(parts, 1);
186
+ const height = (to) => lines[to] - top;
187
+ let to = from;
188
+ while (to < lines.length &&
189
+ (columns > 1 ? notesHeight([...parts, height(to)], columns) : beside + height(to)) <=
190
+ free + SLACK)
191
+ to++;
192
+ return { to, height: to > from ? height(to - 1) : 0, all: lines.length };
193
+ };
194
+ const noteHeight = (note) => note.lines(0).at(-1) ?? 0;
195
+ const separatorPiece = (note) => footPiece(note, 0, note.lines(0).length);
196
+ /**
197
+ * On a page or band with no notes yet: what is carried over goes to its foot first, as much as
198
+ * fits, before any text (Word's PDFs: a long note takes whole pages). `force`: a page with
199
+ * nothing else on it takes at least a line.
200
+ */
201
+ const placeCarried = (box, force = false) => {
202
+ if (!state.carry.length || state.notes || state.onPage || !rules.notes)
203
+ return;
204
+ const { continuation } = rules.notes;
205
+ const columns = box.section?.columns ?? 1;
206
+ const above = noteHeight(continuation);
207
+ const free = pageRoom(box) - state.used - above;
208
+ const placed = [];
209
+ const left = [];
210
+ let parts = [];
211
+ for (const item of state.carry) {
212
+ if (left.length) {
213
+ left.push(item);
214
+ continue;
215
+ }
216
+ let fit = fitNote(item.note, item.from, free, parts, columns);
217
+ if (fit.to === item.from && force && !placed.length)
218
+ fit = fitNote(item.note, item.from, lineHeightOf(item), parts, 1);
219
+ if (fit.to > item.from) {
220
+ placed.push(footPiece(item.note, item.from, fit.to));
221
+ parts = [...parts, fit.height];
222
+ }
223
+ if (fit.to < fit.all)
224
+ left.push({ note: item.note, from: fit.to });
225
+ }
226
+ if (!placed.length)
227
+ return;
228
+ pending.push(separatorPiece(continuation), ...placed);
229
+ state.notes = above + notesHeight(parts, columns);
230
+ state.noteParts = parts;
231
+ state.carry = left;
232
+ };
233
+ /** The height of the next line of a carried note. */
234
+ const lineHeightOf = ({ note, from }) => {
235
+ const lines = note.lines(0);
236
+ return lines[from] - (from ? lines[from - 1] : 0);
237
+ };
238
+ /** Whether what does not fit here can go elsewhere: not from an empty last column at the top. */
239
+ const canMove = (box) => state.onPage > 0 ||
240
+ state.notes > 0 ||
241
+ state.bandTop > 0 ||
242
+ state.column + 1 < (box.section?.columns ?? 1);
243
+ /** Moves to where `section` starts; the space above a new band when it opens one. */
244
+ const enterSection = (section, previous) => {
245
+ const pageBroken = state.breakPending;
246
+ state.breakPending = false;
247
+ state.columnPending = false;
248
+ // Word's PDFs: notes on the page and a continuous break into other columns start a page.
249
+ const notesAbove = (state.notes > 0 || state.pageNotes > 0) && section.columns !== previous?.columns;
250
+ const samePage = !previous || (section.samePage(previous) && !notesAbove);
251
+ if (!pageBroken && samePage && section.start === "continuous") {
252
+ state.owner ??= {
253
+ section: previous ?? section,
254
+ first: state.page === state.sectionPage,
255
+ };
256
+ const lead = state.previousMargin;
257
+ state.bandTop += Math.max(state.bandBottom, state.used) + lead;
258
+ state.lead = lead;
259
+ state.band++;
260
+ state.column = 0;
261
+ state.used = 0;
262
+ state.bandBottom = 0;
263
+ state.onPage = 0;
264
+ state.forcedPage = true;
265
+ state.sectionPage = state.page;
266
+ state.pageNotes += state.notes;
267
+ state.notes = 0;
268
+ state.noteParts = [];
269
+ return lead;
270
+ }
271
+ if (!pageBroken &&
272
+ samePage &&
273
+ section.start === "nextColumn" &&
274
+ section.columns === previous?.columns &&
275
+ state.column + 1 < section.columns) {
276
+ nextColumn({ section }, true);
277
+ return undefined;
278
+ }
279
+ if (state.onPage || state.used || state.column || state.band)
280
+ newPage(true);
281
+ else
282
+ state.forcedPage = true;
283
+ const wrongKind = (number) => (section.start === "oddPage" && number % 2 === 0) ||
284
+ (section.start === "evenPage" && number % 2 === 1);
285
+ // Word's even and odd page sections (its PDFs, every kind, start and page before): a blank
286
+ // page when the number the pages have reached is the wrong kind, unless the section restarts
287
+ // its numbers in a document without even and odd headers. A restart then takes its start, or
288
+ // the next number when that is the wrong kind.
289
+ if (wrongKind(state.number) && (section.pageStart === undefined || rules.evenAndOddHeaders))
290
+ newPage(true);
291
+ if (section.pageStart !== undefined)
292
+ state.number = section.pageStart + (wrongKind(section.pageStart) ? 1 : 0);
293
+ state.sectionPage = state.page;
294
+ return undefined;
59
295
  };
60
296
  const place = (box, index) => {
61
- const pageHeight = box.pageHeight ?? flowHeight;
62
- if ((state.breakPending || breakBefore.has(index)) && state.onPage)
63
- newPage(state.breakPending);
297
+ const fragments = placeBlock(box, index);
298
+ if (box.endnotes?.length)
299
+ placeEndnotes(box, fragments);
300
+ return fragments;
301
+ };
302
+ /** A block's endnotes, after it in the text; lines that do not fit go on to the next column. */
303
+ const placeEndnotes = (box, fragments) => {
304
+ let lead = state.onPage ? state.previousMargin : 0;
305
+ for (const note of box.endnotes ?? []) {
306
+ let from = 0;
307
+ for (;;) {
308
+ const lines = note.lines(state.column);
309
+ if (from >= lines.length)
310
+ break;
311
+ const top = from ? lines[from - 1] : 0;
312
+ placeCarried(box);
313
+ const gap = state.onPage ? (lead ?? 0) : 0;
314
+ let fit = linesIn(note, from, room(box) - state.used - gap);
315
+ if (fit.to === from) {
316
+ if (canMove(box)) {
317
+ nextColumn(box);
318
+ continue;
319
+ }
320
+ fit = { ...fit, to: from + 1, height: lines[from] - top };
321
+ }
322
+ const part = piece(note, from, fit.to);
323
+ part.end = true;
324
+ if (gap)
325
+ part.lead = gap;
326
+ pending.push(part);
327
+ lead = undefined;
328
+ state.used += gap + fit.height;
329
+ state.onPage++;
330
+ from = fit.to;
331
+ if (from < lines.length)
332
+ nextColumn(box);
333
+ }
334
+ }
335
+ state.previousMargin = 0;
336
+ const last = fragments[fragments.length - 1];
337
+ if (last && pending.length)
338
+ last.notes = [...(last.notes ?? []), ...pending];
339
+ if (last)
340
+ pending = [];
341
+ };
342
+ const placeBlock = (box, index) => {
343
+ const previous = boxes[index - 1];
344
+ let lead;
345
+ if (index > 0 && box.section && previous?.section !== box.section)
346
+ lead = enterSection(box.section, previous?.section);
347
+ else if (state.breakPending && state.onPage)
348
+ newPage(true);
349
+ else if (state.columnPending)
350
+ nextColumn(box, true);
351
+ else if (breakBefore.has(index) && state.onPage)
352
+ nextColumn(box);
64
353
  state.breakPending = false;
354
+ state.columnPending = false;
355
+ const leadPage = state.page;
356
+ const at = (fromLine, toLine) => {
357
+ const fragment = { page: state.page, fromLine, toLine };
358
+ if (state.band)
359
+ fragment.band = state.band;
360
+ if (state.column)
361
+ fragment.column = state.column;
362
+ // Moved on to the next page, the block opens no band below anything.
363
+ if (lead !== undefined && state.page === leadPage)
364
+ fragment.lead = lead;
365
+ lead = undefined;
366
+ if (pending.length) {
367
+ fragment.notes = pending;
368
+ pending = [];
369
+ }
370
+ return fragment;
371
+ };
372
+ if (box.sectionMark && state.onPage) {
373
+ gaps[index] = 0;
374
+ return [{ ...at(0, Infinity), mark: true }];
375
+ }
65
376
  const above = state.previousMargin;
66
377
  state.previousMargin = box.marginBottom;
378
+ const adding = word && rules.addSpacing === true;
67
379
  const gap = () => {
68
- if (!state.onPage)
69
- return word && !state.forcedPage ? 0 : box.marginTop;
70
- return word ? above + box.marginTop : Math.max(above, box.marginTop);
380
+ if (!state.onPage) {
381
+ if (word && !state.forcedPage)
382
+ return 0;
383
+ return adding ? box.marginTop : Math.max(0, box.marginTop - state.lead);
384
+ }
385
+ return adding ? above + box.marginTop : Math.max(above, box.marginTop);
71
386
  };
72
387
  // The bottom margin that must fit on the page (Word lets the space after hang).
73
388
  const below = word ? 0 : box.marginBottom;
74
- const forced = box.breaksAfter?.() ?? [];
75
- if (!forced.length && state.used + gap() + box.height + below <= pageHeight + SLACK) {
76
- state.used += gap() + box.height;
389
+ const pageBreaks = box.breaksAfter?.(state.column) ?? [];
390
+ const columnBreaks = box.columnBreaksAfter?.(state.column) ?? [];
391
+ const forced = pageBreaks.length + columnBreaks.length > 0;
392
+ let measured = box.inColumn?.(state.column) ?? box;
393
+ /** The notes referred to on each line, in the column it is in now. */
394
+ const referred = () => {
395
+ const byLine = new Map();
396
+ for (const { line, note } of box.notes?.(state.column) ?? [])
397
+ byLine.set(line, [...(byLine.get(line) ?? []), note]);
398
+ return byLine;
399
+ };
400
+ let notesOf = referred();
401
+ if (state.carry.length && !state.onPage)
402
+ placeCarried(box);
403
+ if (!forced &&
404
+ !notesOf.size &&
405
+ state.used + gap() + measured.height + below <= room(box) + SLACK) {
406
+ const space = gap();
407
+ gaps[index] = space;
408
+ state.used += space + measured.height;
77
409
  state.onPage++;
78
- return [{ page: state.page, fromLine: 0, toLine: Infinity }];
410
+ return [at(0, Infinity)];
79
411
  }
80
- const lines = box.lines();
81
- const count = lines.length;
82
- const breaks = new Set(forced.filter((line) => line >= 0 && line < count));
412
+ let lines = measured.lines();
413
+ let count = lines.length;
414
+ const inRange = (list) => new Set(list.filter((at) => at >= 0 && at < count));
415
+ let pageAfter = inRange(pageBreaks);
416
+ let columnAfter = inRange(columnBreaks);
83
417
  const fragments = [];
84
418
  let line = 0;
419
+ /** The explicit breaks passed so far. */
420
+ let passed = 0;
421
+ /** After a move: `measured` is the new column's, and `line` where the text has got to. */
422
+ const remeasure = (broken = false) => {
423
+ if (!box.inColumn)
424
+ return;
425
+ const next = box.inColumn(state.column);
426
+ if (next === measured)
427
+ return;
428
+ const nextLines = next.lines();
429
+ // shortcut: the same share of the text is taken to start the same line in another
430
+ // width (a line either way); a word-exact tail needs the text in the flow's terms.
431
+ const share = line ? lines[line - 1] / (measured.height || 1) : 0;
432
+ measured = next;
433
+ lines = nextLines;
434
+ count = lines.length;
435
+ // Breaks are lines of this width.
436
+ pageAfter = inRange(box.breaksAfter?.(state.column) ?? []);
437
+ columnAfter = inRange(box.columnBreaksAfter?.(state.column) ?? []);
438
+ if (line > 0) {
439
+ // After an explicit break the text goes on right after the same break.
440
+ const after = [...pageAfter, ...columnAfter].sort((a, b) => a - b)[passed - 1];
441
+ let mapped = lines.findIndex((bottom) => bottom / (next.height || 1) > share + 1e-6);
442
+ if (mapped < 0)
443
+ mapped = count - 1;
444
+ line = broken && after !== undefined ? after + 1 : Math.max(mapped, 1);
445
+ }
446
+ // Nothing left in this width (all of it fits one wider line): the last fragment ends it.
447
+ if (line >= count) {
448
+ const last = fragments.at(-1);
449
+ if (last)
450
+ last.toLine = Infinity;
451
+ }
452
+ };
85
453
  while (line < count) {
86
454
  // The lines up to the next explicit break (or the end) can be split freely.
87
455
  let segmentEnd = line;
88
- while (segmentEnd < count && !breaks.has(segmentEnd))
456
+ while (segmentEnd < count && !pageAfter.has(segmentEnd) && !columnAfter.has(segmentEnd))
89
457
  segmentEnd++;
90
458
  segmentEnd = Math.min(segmentEnd + 1, count);
91
459
  const top = line ? lines[line - 1] : 0;
92
460
  // Only the block's first fragment has the gap above it; the others repeat its header.
93
461
  const spacing = line === 0 ? gap() : (box.repeat ?? 0);
462
+ notesOf = referred();
463
+ placeCarried(box);
464
+ const limit = pageRoom(box);
465
+ /**
466
+ * The footnotes of lines `line` to `to - 1` at the band's foot, each taking the room down
467
+ * to the text after its line; null when one's first line does not fit (`force`: it goes in).
468
+ * With columns the notes share the foot of them all: above them goes the tallest column.
469
+ */
470
+ // A block kept whole is one line to the flow already.
471
+ const keepAll = count === 1;
472
+ const planNotes = (to, force = false) => {
473
+ const plan = {
474
+ notes: state.notes,
475
+ parts: state.noteParts,
476
+ carry: state.carry,
477
+ pieces: [],
478
+ };
479
+ if (!notesOf.size || !rules.notes)
480
+ return plan;
481
+ const columns = box.section?.columns ?? 1;
482
+ for (let at = line; at < to; at++)
483
+ for (const note of notesOf.get(at) ?? []) {
484
+ // Behind a note already cut, it waits its turn.
485
+ if (plan.carry.length) {
486
+ plan.carry = [...plan.carry, { note, from: 0 }];
487
+ continue;
488
+ }
489
+ const { separator } = rules.notes;
490
+ const first = !plan.notes;
491
+ const above = first
492
+ ? noteHeight(separator)
493
+ : plan.notes - notesHeight(plan.parts, columns);
494
+ // Word's PDFs: the lines that the widow and orphan rules keep with this one stay above
495
+ // the note, and the paragraph's space after stays between its last line and the notes.
496
+ let kept = at + 1;
497
+ if (!box.anyLine && !keepAll) {
498
+ kept = Math.max(kept, line + rules.orphans);
499
+ if (count - kept < rules.widows)
500
+ kept = count;
501
+ kept = Math.min(kept, segmentEnd);
502
+ }
503
+ const after = kept === count ? box.marginBottom : 0;
504
+ const own = state.used + spacing + lines[kept - 1] - top + after;
505
+ const text = Math.max(own, columns > 1 && state.column ? state.bandBottom : 0);
506
+ let fit = fitNote(note, 0, limit - text - above, plan.parts, columns);
507
+ if (columns > 1 &&
508
+ state.column &&
509
+ !force &&
510
+ (!fit.to || (fit.to < fit.all && text > own))) {
511
+ // A later column's note, cut short by what the earlier columns hold: in Word they
512
+ // end above it. They are flowed again with its room kept, whole if the page can.
513
+ const lines = note.lines(0);
514
+ const whole = above + notesHeight([...plan.parts, lines.at(-1)], columns);
515
+ const one = above + notesHeight([...plan.parts, lines[0]], columns);
516
+ const height = whole < limit / 2 ? whole : one;
517
+ if (height > reserved() + SLACK && height < limit)
518
+ retry = { key: bandKey(), height };
519
+ }
520
+ if (!fit.to) {
521
+ if (!force)
522
+ return null;
523
+ fit = fitNote(note, 0, lineHeightOf({ note, from: 0 }), [], 1);
524
+ }
525
+ if (first)
526
+ plan.pieces.push(separatorPiece(separator));
527
+ plan.pieces.push(footPiece(note, 0, fit.to));
528
+ plan.parts = [...plan.parts, fit.height];
529
+ plan.notes = above + notesHeight(plan.parts, columns);
530
+ if (fit.to < fit.all)
531
+ plan.carry = [{ note, from: fit.to }];
532
+ }
533
+ return plan;
534
+ };
94
535
  let end = line;
95
536
  while (end < segmentEnd) {
96
537
  const bottom = lines[end] - top + (end + 1 === count ? below : 0);
97
- if (state.used + spacing + bottom > pageHeight + SLACK)
538
+ const plan = planNotes(end + 1);
539
+ if (!plan ||
540
+ state.used + spacing + bottom + Math.max(plan.notes, reserved()) > limit + SLACK)
98
541
  break;
99
542
  end++;
100
543
  }
@@ -103,107 +546,352 @@ export function flowFrom(boxes, flowHeight, rules = DEFAULT_RULES, reuse) {
103
546
  const kept = Math.min(end, segmentEnd - rules.widows);
104
547
  if (kept - line >= rules.orphans)
105
548
  end = kept;
106
- else if (state.onPage)
549
+ else if (canMove(box))
107
550
  end = line;
108
551
  }
109
552
  if (end === line) {
110
- if (state.onPage) {
111
- newPage();
553
+ if (canMove(box)) {
554
+ nextColumn(box);
555
+ remeasure();
112
556
  continue;
113
557
  }
114
558
  end = line + 1; // a line taller than a page is placed anyway
115
559
  }
116
- fragments.push({ page: state.page, fromLine: line, toLine: end });
560
+ // What the lines kept refer to: lines taken back take their notes with them.
561
+ const kept = planNotes(end, true);
562
+ if (kept) {
563
+ state.notes = kept.notes;
564
+ state.noteParts = kept.parts;
565
+ state.carry = kept.carry;
566
+ pending.push(...kept.pieces);
567
+ }
568
+ if (line === 0)
569
+ gaps[index] = spacing;
570
+ fragments.push(at(line, end));
117
571
  state.used += spacing + lines[end - 1] - top;
118
572
  state.onPage++;
119
573
  line = end;
120
- const broken = breaks.has(end - 1);
121
- if (line < count)
122
- newPage();
123
- else if (broken)
574
+ const pageBroken = pageAfter.has(end - 1);
575
+ const columnBroken = columnAfter.has(end - 1);
576
+ if (line < count) {
577
+ if (pageBroken || columnBroken)
578
+ passed++;
579
+ if (pageBroken)
580
+ newPage();
581
+ else
582
+ nextColumn(box, columnBroken);
583
+ remeasure(pageBroken || columnBroken);
584
+ }
585
+ else if (pageBroken)
124
586
  state.breakPending = true;
587
+ else if (columnBroken)
588
+ state.columnPending = true;
125
589
  }
126
590
  // Moved whole to a later page: not split.
127
591
  const [only] = fragments;
128
- if (fragments.length === 1 && only && !forced.length)
592
+ if (fragments.length === 1 && only && !forced)
129
593
  only.toLine = Infinity;
130
594
  return fragments;
131
595
  };
132
596
  /** The flow as it was before a keep-with-next move, by the block that triggered it. */
133
597
  const attempts = new Map();
134
- let index = start;
135
- while (index < boxes.length) {
136
- // Realigned with the previous flow: the rest is unchanged (no keep-with-next decision
137
- // about this block, made with the block before it, is pending). The block before it must
138
- // be unchanged too: had it been keep-with-next before the edit, the previous flow from
139
- // here holds a decision about a chain that no longer exists.
140
- const was = reuse && index > start && !attempts.size && reuse.previousIndex(index - 1) >= 0
141
- ? reuse.previousIndex(index)
142
- : -1;
143
- const before = was >= 0 ? reuse?.previous.states[was] : undefined;
144
- if (before && !boxes[index - 1]?.keepWithNext && sameState(before, state)) {
145
- const previous = reuse;
146
- result.length = index;
147
- snapshots.length = index;
148
- result.push(...previous.previous.fragments.slice(was));
149
- snapshots.push(...previous.previous.states.slice(was, -1));
150
- return {
151
- fragments: result,
152
- states: [...snapshots, { ...previous.previous.states.at(-1) }],
153
- };
154
- }
155
- snapshots[index] = { ...state };
156
- const fragments = place(boxes[index], index);
157
- result[index] = fragments;
158
- const previous = result[index - 1];
159
- const startsLater = previous !== undefined &&
160
- (fragments[0]?.page ?? 0) > (previous[previous.length - 1]?.page ?? 0);
161
- const attempt = attempts.get(index);
162
- if (attempt) {
163
- attempts.delete(index);
164
- // The move did not bring them together (the block does not fit after the heading on a
165
- // page of its own either): keep the flow as it was.
166
- if (startsLater) {
167
- result.splice(attempt.first, result.length - attempt.first, ...attempt.result);
168
- snapshots.splice(attempt.first, snapshots.length - attempt.first, ...attempt.snapshots);
169
- state = attempt.state;
170
- index++;
171
- continue;
598
+ /** Flows blocks `from` to `to`; a result when the rest could be taken from `reuse`. */
599
+ const run = (from, to) => {
600
+ let index = from;
601
+ while (index < to) {
602
+ // Realigned with the previous flow: the rest is unchanged (no keep-with-next decision
603
+ // about this block, made with the block before it, is pending). The block before it must
604
+ // be unchanged too: had it been keep-with-next before the edit, the previous flow from
605
+ // here holds a decision about a chain that no longer exists. Inside a balanced section the
606
+ // columns depend on the whole section: only its start realigns.
607
+ const was = reuse &&
608
+ !balancing &&
609
+ index > start &&
610
+ !attempts.size &&
611
+ reuse.previousIndex(index - 1) >= 0
612
+ ? reuse.previousIndex(index)
613
+ : -1;
614
+ const before = was >= 0 ? reuse?.previous.states[was] : undefined;
615
+ if (before &&
616
+ !boxes[index - 1]?.keepWithNext &&
617
+ !(balancedAt(index) && sameSection(index)) &&
618
+ sameState(before, state)) {
619
+ const previous = reuse.previous;
620
+ result.length = index;
621
+ snapshots.length = index;
622
+ gaps.length = index;
623
+ result.push(...previous.fragments.slice(was));
624
+ snapshots.push(...previous.states.slice(was, -1));
625
+ gaps.push(...previous.gaps.slice(was));
626
+ return {
627
+ fragments: result,
628
+ states: [...snapshots, { ...previous.states.at(-1) }],
629
+ gaps,
630
+ };
172
631
  }
173
- }
174
- if (startsLater && boxes[index - 1]?.keepWithNext) {
175
- // The chain of keep-with-next blocks before this one, each whole on one page.
176
- let first = index - 1;
177
- while (first > 0 &&
178
- boxes[first - 1]?.keepWithNext &&
179
- result[first - 1]?.length === 1 &&
180
- result[first - 1]?.[0]?.page === result[first]?.[0]?.page)
181
- first--;
182
- const beforeFirst = snapshots[first];
183
- if (!breakBefore.has(first) && beforeFirst.onPage > 0 && result[first]?.length === 1) {
184
- attempts.set(index, {
185
- first,
186
- result: result.slice(first),
187
- snapshots: snapshots.slice(first),
188
- state: { ...state },
189
- });
190
- breakBefore.add(first);
191
- state = { ...beforeFirst };
632
+ snapshots[index] = { ...state };
633
+ const fragments = place(boxes[index], index);
634
+ if (retry) {
635
+ const { key, height } = retry;
636
+ retry = null;
637
+ const [page, band] = key.split("|").map(Number);
638
+ // Back to the first block on that band: it may have started on an earlier page.
639
+ let first = index;
640
+ while (first > from &&
641
+ result[first - 1]?.some((f) => f.page === page && (f.band ?? 0) === band))
642
+ first--;
643
+ const before = snapshots[first];
644
+ state = { ...before, reserves: { ...before.reserves, [key]: height } };
192
645
  result.length = first;
646
+ snapshots.length = first;
647
+ gaps.length = first;
648
+ attempts.clear();
649
+ for (const moved of breakBefore)
650
+ if (moved >= first)
651
+ breakBefore.delete(moved);
652
+ pending = [];
193
653
  index = first;
194
654
  continue;
195
655
  }
656
+ result[index] = fragments;
657
+ const previous = result[index - 1];
658
+ const startsLater = previous !== undefined && slot(fragments[0]) > slot(previous[previous.length - 1]);
659
+ const attempt = attempts.get(index);
660
+ if (attempt) {
661
+ attempts.delete(index);
662
+ // The move did not bring them together (the block does not fit after the heading on a
663
+ // page of its own either): keep the flow as it was.
664
+ if (startsLater) {
665
+ result.splice(attempt.first, result.length - attempt.first, ...attempt.result);
666
+ snapshots.splice(attempt.first, snapshots.length - attempt.first, ...attempt.snapshots);
667
+ gaps.splice(attempt.first, gaps.length - attempt.first, ...attempt.gaps);
668
+ state = attempt.state;
669
+ index++;
670
+ continue;
671
+ }
672
+ }
673
+ if (startsLater && boxes[index - 1]?.keepWithNext && sameSection(index)) {
674
+ // The chain of keep-with-next blocks before this one, each whole in one column (keeping
675
+ // reaches no further back than the section: it starts where its `start` says).
676
+ let first = index - 1;
677
+ while (first > 0 &&
678
+ sameSection(first) &&
679
+ boxes[first - 1]?.keepWithNext &&
680
+ result[first - 1]?.length === 1 &&
681
+ slot(result[first - 1]?.[0]) === slot(result[first]?.[0]))
682
+ first--;
683
+ const beforeFirst = snapshots[first];
684
+ if (!breakBefore.has(first) && beforeFirst.onPage > 0 && result[first]?.length === 1) {
685
+ attempts.set(index, {
686
+ first,
687
+ result: result.slice(first),
688
+ snapshots: snapshots.slice(first),
689
+ gaps: gaps.slice(first),
690
+ state: { ...state },
691
+ });
692
+ breakBefore.add(first);
693
+ state = { ...beforeFirst };
694
+ result.length = first;
695
+ index = first;
696
+ continue;
697
+ }
698
+ }
699
+ index++;
700
+ const section = boxes[index - 1]?.section;
701
+ if (!balancing &&
702
+ section?.balanced &&
703
+ section.columns > 1 &&
704
+ boxes[index]?.section !== section)
705
+ balance(index);
706
+ }
707
+ return null;
708
+ };
709
+ /**
710
+ * Levels the columns of the balanced section ending before block `end`: flows it again with
711
+ * its last page's columns limited, looking for the shortest height that keeps it on that page.
712
+ */
713
+ const balance = (end) => {
714
+ const section = boxes[end - 1]?.section;
715
+ let first = end - 1;
716
+ while (first > 0 && boxes[first - 1]?.section === section)
717
+ first--;
718
+ const from = snapshots[first];
719
+ const { page } = state;
720
+ let high = Math.max(state.bandBottom, state.used);
721
+ let low = high / section.columns - 1;
722
+ /** The section flowed with its last page's columns `height` tall: does it stay there? */
723
+ const attempt = (height) => {
724
+ balancing = { page, height };
725
+ state = { ...from };
726
+ result.length = first;
727
+ snapshots.length = first;
728
+ attempts.clear();
729
+ for (const moved of breakBefore)
730
+ if (moved >= first)
731
+ breakBefore.delete(moved);
732
+ run(first, end);
733
+ // The last column takes what it is given: a column over the limit is a failure too.
734
+ return state.page === page && Math.max(state.used, state.bandBottom) <= height + SLACK;
735
+ };
736
+ while (high - low > 0.5) {
737
+ const middle = (low + high) / 2;
738
+ if (attempt(middle))
739
+ high = middle;
740
+ else
741
+ low = middle;
742
+ }
743
+ if (!attempt(high))
744
+ attempt(Number.POSITIVE_INFINITY);
745
+ balancing = null;
746
+ };
747
+ /** What is still carried after the last block goes on pages of its own. */
748
+ const finishNotes = () => {
749
+ const held = result[result.length - 1];
750
+ const last = held?.[held.length - 1];
751
+ const box = boxes[boxes.length - 1];
752
+ if (!held || !last || !box || (!state.carry.length && !last.notes?.some((p) => p.tail)))
753
+ return;
754
+ const end = state;
755
+ state = { ...state };
756
+ while (state.carry.length) {
757
+ newPage();
758
+ placeCarried(box, true);
759
+ }
760
+ const notes = [
761
+ ...(last.notes ?? []).filter((p) => !p.tail),
762
+ ...pending.map((p) => ({ ...p, tail: true })),
763
+ ];
764
+ pending = [];
765
+ state = end;
766
+ result[result.length - 1] = [...held.slice(0, -1), { ...last, notes }];
767
+ };
768
+ const reused = run(start, boxes.length);
769
+ if (reused)
770
+ return reused;
771
+ finishNotes();
772
+ return {
773
+ fragments: result,
774
+ states: [...snapshots.slice(0, boxes.length), { ...state }],
775
+ gaps: gaps.slice(0, boxes.length),
776
+ };
777
+ }
778
+ /**
779
+ * Each page of a flow: its number, its first section and whether that section starts on it. A page
780
+ * nothing is on (the blank page before an even or odd page section) has the next page's section.
781
+ */
782
+ export function pagesOf(boxes, result) {
783
+ const pages = [];
784
+ const owners = [];
785
+ const seen = new Set();
786
+ const onPages = new Map();
787
+ result.fragments.forEach((fragments, i) => {
788
+ const section = boxes[i]?.section;
789
+ const after = result.states[i + 1];
790
+ const own = onPages.get(section) ?? new Set();
791
+ onPages.set(section, own);
792
+ const places = [...fragments, ...fragments.flatMap((fragment) => fragment.notes ?? [])];
793
+ for (const { page } of places) {
794
+ own.add(page);
795
+ if (!pages[page]) {
796
+ owners[page] = section;
797
+ pages[page] = {
798
+ index: page,
799
+ // Pages count on from a block's first to its last: the number where it ended tells.
800
+ number: after.number - (after.page - page),
801
+ first: !seen.has(section),
802
+ section: section.index ?? 0,
803
+ sectionPages: 0,
804
+ };
805
+ }
806
+ seen.add(section);
196
807
  }
197
- index++;
808
+ });
809
+ pages.forEach((page, p) => {
810
+ if (page)
811
+ page.sectionPages = onPages.get(owners[p])?.size ?? 0;
812
+ });
813
+ for (let p = pages.length - 1; p >= 0; p--) {
814
+ const next = pages[p + 1];
815
+ pages[p] ??= { ...next, index: p, number: next.number - 1, first: false, sectionPages: 0 };
198
816
  }
199
- return { fragments: result, states: [...snapshots.slice(0, boxes.length), { ...state }] };
817
+ return pages;
818
+ }
819
+ /**
820
+ * Notes of heights `parts` set in `columns` columns, as Word sets those of a section with columns
821
+ * (its PDFs): whole, in order, each column as full as the height the set needs. That height and
822
+ * the column of each. One column: their sum.
823
+ */
824
+ export function arrangeNotes(parts, columns) {
825
+ const total = parts.reduce((sum, part) => sum + part, 0);
826
+ if (columns <= 1 || parts.length <= 1)
827
+ return { height: total, columnOf: parts.map(() => 0) };
828
+ const pack = (height) => {
829
+ const columnOf = [];
830
+ let column = 0;
831
+ let used = 0;
832
+ let tallest = 0;
833
+ for (const part of parts) {
834
+ if (used && used + part > height + 0.01) {
835
+ column++;
836
+ used = 0;
837
+ }
838
+ used += part;
839
+ tallest = Math.max(tallest, used);
840
+ columnOf.push(column);
841
+ }
842
+ return column < columns ? { height: tallest, columnOf } : null;
843
+ };
844
+ let low = Math.max(...parts, total / columns);
845
+ let best = pack(low);
846
+ if (best)
847
+ return best;
848
+ let high = total;
849
+ best = pack(high);
850
+ while (high - low > 0.25) {
851
+ const middle = (low + high) / 2;
852
+ const tried = pack(middle);
853
+ if (tried) {
854
+ best = tried;
855
+ high = middle;
856
+ }
857
+ else
858
+ low = middle;
859
+ }
860
+ return best;
861
+ }
862
+ const notesHeight = (parts, columns) => arrangeNotes(parts, columns).height;
863
+ /** The space after the last block of a column of a page, as flowed (what ends its text). */
864
+ export function spaceAfterText(boxes, result, page, band, column) {
865
+ for (let i = result.fragments.length - 1; i >= 0; i--)
866
+ for (const f of result.fragments[i] ?? [])
867
+ if (f.page === page && (f.band ?? 0) === band && (f.column ?? 0) === column)
868
+ return boxes[i]?.marginBottom ?? 0;
869
+ return 0;
200
870
  }
871
+ /** Every note piece of a flow, in order. */
872
+ export const notePieces = (result) => result.fragments.flatMap((fragments) => fragments.flatMap((f) => f.notes ?? []));
201
873
  function sameState(a, b) {
202
- return (a.page === b.page &&
874
+ return (a.notes === b.notes &&
875
+ JSON.stringify(a.reserves) === JSON.stringify(b.reserves) &&
876
+ a.noteParts.length === b.noteParts.length &&
877
+ a.noteParts.every((part, i) => part === b.noteParts[i]) &&
878
+ a.pageNotes === b.pageNotes &&
879
+ a.carry.length === b.carry.length &&
880
+ a.carry.every((item, i) => item.note.id === b.carry[i]?.note.id && item.from === b.carry[i]?.from) &&
881
+ a.page === b.page &&
882
+ a.number === b.number &&
883
+ a.sectionPage === b.sectionPage &&
884
+ a.band === b.band &&
885
+ a.bandTop === b.bandTop &&
886
+ a.lead === b.lead &&
887
+ a.column === b.column &&
203
888
  a.used === b.used &&
889
+ a.bandBottom === b.bandBottom &&
204
890
  a.previousMargin === b.previousMargin &&
205
891
  a.onPage === b.onPage &&
206
892
  a.breakPending === b.breakPending &&
207
- a.forcedPage === b.forcedPage);
893
+ a.columnPending === b.columnPending &&
894
+ a.forcedPage === b.forcedPage &&
895
+ a.owner === b.owner);
208
896
  }
209
897
  //# sourceMappingURL=flow.js.map