@folijs/view 0.2.0 → 0.4.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.
package/dist/view.js CHANGED
@@ -1,7 +1,11 @@
1
- import { AllSelection, arrowAcrossLeaf, autolinkHref, closeHistory, deleteBackward, deleteForward, deleteSelection, insertHardBreak, insertLink, insertText, marksAt, NodeSelection, redo, Selection, Slice, setLink, splitBlock, TextSelection, TransformError, toggleMark, undo, } from "@folijs/core";
1
+ import { AllSelection, arrowAcrossLeaf, autolinkHref, closeHistory, deleteBackward, deleteForward, deleteSelection, fitPaste, fitPastedV2, insertHardBreak, insertLink, insertText, isSafeHref, marksAt, NodeSelection, parseContentV2, redo, Selection, Slice, sectionSettings, setComments, setLink, splitBlock, TextSelection, TransformError, toggleMark, trackState, typedMarks, undo, withEnvelope, wordContext, } from "@folijs/core";
2
2
  import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
3
3
  import { contentHeight, DEFAULT_RULES, flowFrom, PX_PER_MM, } from "./layout/flow.js";
4
- import { createWrapper, isWrapper, isWrapperFor, PAGE_BREAK_ATTR, renderBlock, } from "./render.js";
4
+ import { PAGE_BREAK_ATTR } from "./render.js";
5
+ import { spacing, WordRenderer } from "./word/edit.js";
6
+ import { measureLineRatio } from "./word/pages.js";
7
+ /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
8
+ const WORD_RULES = { ...DEFAULT_RULES, spacing: "word" };
5
9
  /** Class of the element of a node-selected block (a rule). */
6
10
  const SELECTED_CLASS = "foli-selected-node";
7
11
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
@@ -30,18 +34,104 @@ const VIEW_ATTR = "data-foli-view";
30
34
  let viewCount = 0;
31
35
  /**
32
36
  * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
33
- * the document's size per page, without margins (the page's padding holds them). A page is
34
- * exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
37
+ * its section's size per page (the last section's where named pages are not supported), without
38
+ * margins (the page's padding holds them). A page is exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
35
39
  * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
36
40
  * page) is not cut: it prints over the next sheet.
37
41
  * shortcut: `@page` is per document: with several editors of different page sizes on one web page, the last one's sheet size wins (each keeps its own page rules); print one editor per document until that is needed.
38
42
  */
39
- function printStyles({ pageSize }, id) {
40
- const { width, height } = pageSize;
43
+ function printStyles(settings, sheets, id) {
44
+ const { width, height } = settings.pageSize;
45
+ const last = sheetOf(settings, 0).css;
41
46
  const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
47
+ // Sections with other page setups: a named page each (engines without named pages print
48
+ // every sheet at the last section's size).
49
+ const named = sheets.every((sheet) => sheet.css === last)
50
+ ? ""
51
+ : sheets
52
+ .map(({ settings: { pageSize: size }, index }) => {
53
+ const name = `foli-${id}-${index}`;
54
+ return (`@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
55
+ `${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`);
56
+ })
57
+ .join("");
42
58
  return (`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
43
59
  `${pages}{height:${height}mm!important;margin-block:0!important;` +
44
- `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}}`);
60
+ `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`);
61
+ }
62
+ /** Whether `node` is inside an element of `stop` that is not displayed (hidden deleted text). */
63
+ function hiddenIn(node, stop) {
64
+ for (let el = node.parentElement; el && el !== stop; el = el.parentElement)
65
+ if (el.style.display === "none")
66
+ return true;
67
+ return false;
68
+ }
69
+ /** The attribute naming a page's page setup (its index among the document's) for print. */
70
+ const SHEET_ATTR = "data-foli-sheet";
71
+ function sheetOf(settings, index) {
72
+ const { pageSize, margins } = settings;
73
+ const css = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
74
+ `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
75
+ return { settings, css, index };
76
+ }
77
+ /** The style each page element was last given (its `cssText` reads back normalized). */
78
+ const pageSheets = new WeakMap();
79
+ /**
80
+ * The section of each top-level block (the section a paragraph's `section` ends; the
81
+ * envelope's for the blocks after the last such paragraph). A section starts a new page,
82
+ * unless it is continuous with the same page setup as the one before (shortcut: a continuous
83
+ * section with another page setup starts a new page; Word's even and odd page sections do not
84
+ * add a blank page), as `renderDocument` lays sections out.
85
+ */
86
+ function sectionLayouts(doc, last) {
87
+ const sheets = new Map();
88
+ const bySection = new Map();
89
+ const sheet = (section) => {
90
+ let found = bySection.get(section);
91
+ if (!found) {
92
+ const settings = sectionSettings(section);
93
+ const css = sheetOf(settings, 0).css;
94
+ found = sheets.get(css) ?? sheetOf(settings, sheets.size);
95
+ sheets.set(css, found);
96
+ bySection.set(section, found);
97
+ }
98
+ return found;
99
+ };
100
+ const sections = [];
101
+ let section = last;
102
+ for (let i = doc.childCount - 1; i >= 0; i--) {
103
+ const own = doc.child(i).attrs.section;
104
+ if (own)
105
+ section = own;
106
+ sections[i] = section;
107
+ }
108
+ // Indexes in document order: the first page setup is 0.
109
+ sections.forEach(sheet);
110
+ return sections.map((own, i) => {
111
+ const next = sections[i + 1];
112
+ // By position, as `renderDocument`: two paragraphs may end sections with one object.
113
+ const ends = !!next && !!doc.child(i).attrs.section;
114
+ const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
115
+ return { sheet: sheet(own), breakAfter };
116
+ });
117
+ }
118
+ /**
119
+ * Initial pages (before a flow), moved where needed so that each page holds blocks of one
120
+ * page setup: a block is measured in a page of its own section's width.
121
+ */
122
+ function separateSheets(pages, layout) {
123
+ const css = [];
124
+ let floor = 0;
125
+ return pages.map((list, i) => list.map((p) => {
126
+ const want = layout[i].sheet.css;
127
+ let page = Math.max(p, floor);
128
+ // Only the last page used so far has a setup: the next one is free.
129
+ if (css[page] !== undefined && css[page] !== want)
130
+ page++;
131
+ css[page] ??= want;
132
+ floor = page;
133
+ return page;
134
+ }));
45
135
  }
46
136
  /**
47
137
  * The editable view of an `Editor` from `@folijs/core`: renders its state into one
@@ -52,9 +142,8 @@ function printStyles({ pageSize }, id) {
52
142
  * view cannot prevent (Android keyboards, extensions). A MutationObserver records those; the view
53
143
  * then reads the changed text back into a transaction (`readBack`) and re-renders.
54
144
  *
55
- * Blocks are the leaf blocks of the document at any depth (paragraphs, headings, rules); the
56
- * containers around them (lists, list items) are rebuilt on each page around the blocks it holds
57
- * (ADR-0004).
145
+ * Blocks are the document's paragraphs and opaque blocks (a schema v3 document has no
146
+ * containers: a list is numbered paragraphs).
58
147
  */
59
148
  export class EditorView {
60
149
  host;
@@ -63,12 +152,8 @@ export class EditorView {
63
152
  blocks = [];
64
153
  /** Position before each block, parallel to `blocks`. */
65
154
  starts = [];
66
- /** The containers around each block, outermost first, parallel to `blocks`. */
67
- chains = [];
68
155
  /** The index of each block in `blocks`. */
69
156
  indexOf = new Map();
70
- /** The container types around each block at its last render (a change means re-measuring). */
71
- chainKeys = new WeakMap();
72
157
  /** The element that shows a node selection, if any. */
73
158
  selectedDom = null;
74
159
  /** The page of each fragment of each block. */
@@ -77,7 +162,16 @@ export class EditorView {
77
162
  owner = new Map();
78
163
  /** The page elements, in order; the host's only children. */
79
164
  pages = [];
80
- pageStyle = "";
165
+ /** The page setup of each page (its section's), parallel to `pages`. */
166
+ sheets = [];
167
+ /** The page setups the print rules were written for. */
168
+ printKey = "";
169
+ /**
170
+ * Each block's page setup and whether a section break follows it, as last rendered: a block
171
+ * whose layout changed (a section break inserted or removed around it) is measured and
172
+ * flowed again.
173
+ */
174
+ layoutKeys = new WeakMap();
81
175
  /** Marks the host for this view's print rules (`printStyles`). */
82
176
  id = String(++viewCount);
83
177
  /**
@@ -92,7 +186,7 @@ export class EditorView {
92
186
  * Measurements by model node: a node's rendered height, margins and lines only depend on
93
187
  * its content (unchanged node, same identity), the page width and the CSS. Cleared when the
94
188
  * page settings or the fonts change; single entries go stale when a block's size changes
95
- * without an edit (`ResizeObserver`: CSS, fonts, a container).
189
+ * without an edit (`ResizeObserver`: CSS, fonts).
96
190
  */
97
191
  measures = new WeakMap();
98
192
  stale = new Set();
@@ -117,6 +211,8 @@ export class EditorView {
117
211
  observer;
118
212
  unsubscribe;
119
213
  editable = true;
214
+ /** Escape was the last key: Tab now leaves the editor. */
215
+ tabLeaves = false;
120
216
  placeholder = "";
121
217
  /** The block that shows the placeholder, if any. */
122
218
  placeholderDom = null;
@@ -124,6 +220,14 @@ export class EditorView {
124
220
  pointerFocus = false;
125
221
  /** Whether the view added the host's tabindex (a read-only host must stay focusable). */
126
222
  addedTabIndex;
223
+ /** Renders the document's blocks; made by the first render. */
224
+ word = null;
225
+ /** How tracked changes show. */
226
+ review = "markup";
227
+ /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
228
+ ratios = new Map();
229
+ /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
230
+ fontsChanged = false;
127
231
  constructor(host, editor, options = {}) {
128
232
  this.host = host;
129
233
  this.editor = editor;
@@ -138,6 +242,7 @@ export class EditorView {
138
242
  host.style.whiteSpace = "pre-wrap";
139
243
  host.style.overflowWrap = "break-word";
140
244
  host.replaceChildren();
245
+ this.review = trackState(this.state)?.view ?? "markup";
141
246
  this.resizeObserver =
142
247
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
143
248
  this.observer = new MutationObserver(this.onMutations);
@@ -251,7 +356,14 @@ export class EditorView {
251
356
  }
252
357
  // ---------- rendering ----------
253
358
  update(state) {
254
- const docChanged = state.doc !== this.state.doc;
359
+ const review = trackState(state)?.view ?? "markup";
360
+ // Another review view (`setReviewView`): every block drawn again, by a new renderer.
361
+ const reviewChanged = review !== this.review;
362
+ if (reviewChanged) {
363
+ this.review = review;
364
+ this.word = null;
365
+ }
366
+ const docChanged = state.doc !== this.state.doc || reviewChanged;
255
367
  const selectionChanged = !state.selection.eq(this.state.selection);
256
368
  this.state = state;
257
369
  if (docChanged)
@@ -300,6 +412,29 @@ export class EditorView {
300
412
  render() {
301
413
  const { doc } = this.state;
302
414
  const ownerDocument = this.host.ownerDocument;
415
+ // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
416
+ // editor's state always has one (`createEditor`).
417
+ const context = wordContext(this.state);
418
+ // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
419
+ // block it would redraw.
420
+ const renewed = context !== (this.word?.context ?? null) || (this.fontsChanged && !this.composing);
421
+ if (renewed)
422
+ this.fontsChanged = false;
423
+ let word = this.word;
424
+ if (renewed) {
425
+ word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio, false, this.review);
426
+ this.invalidateLayout();
427
+ }
428
+ word.prepare(doc);
429
+ const layout = sectionLayouts(doc, context.envelope.section);
430
+ doc.forEach((node, _, i) => {
431
+ const { sheet, breakAfter } = layout[i];
432
+ const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
433
+ const before = this.layoutKeys.get(node);
434
+ if (before !== undefined && before !== key)
435
+ this.stale.add(node);
436
+ this.layoutKeys.set(node, key);
437
+ });
303
438
  const previous = new Map(this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]));
304
439
  const previousPages = this.fragmentPages;
305
440
  this.dirty.clear();
@@ -310,40 +445,13 @@ export class EditorView {
310
445
  }
311
446
  let blocks = [];
312
447
  const starts = [];
313
- const chains = [];
314
- // Leaf blocks at any depth, in document order, with the containers around each.
315
- const open = [];
316
- // The chain of the open containers and its key, rebuilt only when they change (blocks in
317
- // the same container share one array).
318
- let chain = [];
319
- let chainKey = "";
320
- const changed = () => {
321
- chain = open.slice();
322
- chainKey = open.map((container) => container.node.type.name).join(">");
323
- };
324
- doc.descendants((node, pos, _parent, index) => {
325
- let popped = false;
326
- while (open.length) {
327
- const last = open[open.length - 1];
328
- if (pos < last.pos + last.node.nodeSize)
329
- break;
330
- open.pop();
331
- popped = true;
332
- }
333
- if (!node.isTextblock && !node.isLeaf) {
334
- open.push({ node, pos, index, firstBlock: blocks.length });
335
- changed();
336
- return true;
337
- }
338
- if (popped)
339
- changed();
340
- // A block moved into or out of a container (wrapped in a list, indented, lifted) keeps its
341
- // node but not its line width or margins: measure it again, and re-flow from it.
342
- const before = this.chainKeys.get(node);
343
- if (before !== undefined && before !== chainKey)
448
+ doc.forEach((node, pos) => {
449
+ let reused = renewed ? undefined : previous.get(node);
450
+ // A block whose list number or comment shading changed (an edit before it) is redrawn.
451
+ if (reused && reused.key !== word.key(blocks.length)) {
452
+ reused = undefined;
344
453
  this.stale.add(node);
345
- this.chainKeys.set(node, chainKey);
346
- let reused = previous.get(node);
454
+ }
347
455
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
348
456
  // fragment's end breaks its line, so its lines would depend on where it was split before.
349
457
  const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
@@ -351,26 +459,25 @@ export class EditorView {
351
459
  reused = undefined;
352
460
  if (reused)
353
461
  previous.delete(node);
354
- blocks.push(reused ?? renderBlock(node, ownerDocument));
462
+ blocks.push(reused ?? word.render(node, blocks.length));
355
463
  starts.push(pos);
356
- chains.push(chain);
357
- return false;
358
464
  });
359
465
  for (const stale of previous.values())
360
466
  for (const fragment of stale.fragments)
361
467
  fragment.remove();
362
- this.applyGeometry();
468
+ this.applyPrintStyles(layout);
363
469
  let last = 0;
364
470
  let pages = blocks.map((desc) => {
365
471
  const before = previousPages.get(desc);
366
472
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
367
473
  });
368
- this.place(blocks, pages, chains);
474
+ pages = separateSheets(pages, layout);
475
+ this.place(blocks, pages, layout);
369
476
  if (!this.composing) {
370
477
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
371
478
  let scale;
372
479
  const layoutPx = () => {
373
- scale ??= layoutScale(this.pages[0], this.editor.settings);
480
+ scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
374
481
  return scale;
375
482
  };
376
483
  if (dropLines)
@@ -380,7 +487,8 @@ export class EditorView {
380
487
  delete measure.lines;
381
488
  }
382
489
  const nodes = blocks.map((desc) => desc.node);
383
- const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale) : undefined;
490
+ // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
491
+ const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
384
492
  const measureOf = (desc) => {
385
493
  let found = this.measures.get(desc.node);
386
494
  // A stale block is measured again once per render.
@@ -395,8 +503,8 @@ export class EditorView {
395
503
  found.lines ??= measureLines(desc, layoutPx());
396
504
  return found.lines;
397
505
  };
398
- const boxes = blocks.map((desc) => blockBox(desc, measureOf(desc), () => lines(desc)));
399
- const result = flowFrom(boxes, contentHeight(this.editor.settings), DEFAULT_RULES, reuse);
506
+ const boxes = blocks.map((desc, i) => wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i]));
507
+ const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
400
508
  this.flowed = { nodes, result };
401
509
  this.stale.clear();
402
510
  const flowed = result.fragments;
@@ -409,14 +517,14 @@ export class EditorView {
409
517
  return clusterBoundary(doc, contentStart + offset, false) - contentStart;
410
518
  });
411
519
  const same = splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
412
- return same ? desc : renderBlock(desc.node, ownerDocument, splits);
520
+ return same ? desc : word.render(desc.node, i, splits);
413
521
  });
414
522
  pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
415
- this.place(blocks, pages, chains);
523
+ applyGaps(blocks, pages, boxes);
524
+ this.place(blocks, pages, layout);
416
525
  }
417
526
  this.blocks = blocks;
418
527
  this.starts = starts;
419
- this.chains = chains;
420
528
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
421
529
  this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
422
530
  this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
@@ -430,19 +538,47 @@ export class EditorView {
430
538
  if (this.composing)
431
539
  this.pending.push(...records);
432
540
  }
541
+ /** A font's normal line height ratio, measured outside the host (no input to read back). */
542
+ lineRatio = (family) => {
543
+ let ratio = this.ratios.get(family);
544
+ if (ratio === undefined) {
545
+ const doc = this.host.ownerDocument;
546
+ ratio = measureLineRatio(doc.body ?? doc.documentElement)(family);
547
+ this.ratios.set(family, ratio);
548
+ }
549
+ return ratio;
550
+ };
433
551
  /**
434
552
  * Puts each fragment of each block into its page (pages are non-decreasing in document
435
- * order), inside the elements of the block's containers (lists, list items), creating and
436
- * removing pages as needed. A page reuses the container elements already at the same place
437
- * (same tag, in order), so an edit inside a list moves no DOM. Anything else in the host, a
438
- * page or a container (stray DOM) is removed.
553
+ * order), creating and removing pages as needed, and gives each page the page setup of its
554
+ * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
555
+ * or a page (stray DOM) is removed.
439
556
  */
440
- place(blocks, pages, chains) {
557
+ place(blocks, pages, layout) {
441
558
  const { host } = this;
442
- const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0, block: i, fragment: f })));
559
+ const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
443
560
  const count = (items[items.length - 1]?.page ?? 0) + 1;
561
+ const sheets = [];
562
+ pages.forEach((list, i) => {
563
+ for (const p of list)
564
+ sheets[p] ??= layout[i].sheet;
565
+ });
566
+ // A page no block starts on (none yet) takes the setup of the page before it.
567
+ for (let p = 0; p < count; p++)
568
+ sheets[p] ??=
569
+ sheets[p - 1] ?? layout[0]?.sheet ?? this.lastSheet();
570
+ this.sheets = sheets.slice(0, count);
444
571
  while (this.pages.length < count)
445
572
  this.pages.push(this.createPage());
573
+ this.sheets.forEach((sheet, p) => {
574
+ const page = this.pages[p];
575
+ const key = `${sheet.index} ${sheet.css}`;
576
+ if (pageSheets.get(page) === key)
577
+ return;
578
+ pageSheets.set(page, key);
579
+ page.style.cssText = sheet.css;
580
+ page.setAttribute(SHEET_ATTR, String(sheet.index));
581
+ });
446
582
  // Pages first, in order; anything else in the host ends up after them.
447
583
  let cursor = host.firstChild;
448
584
  for (const page of this.pages.slice(0, count)) {
@@ -451,90 +587,23 @@ export class EditorView {
451
587
  else
452
588
  host.insertBefore(page, cursor);
453
589
  }
454
- const ownerDocument = host.ownerDocument;
455
- /** Removes what is left after the last placed child (strays, and blocks of later pages). */
456
- const closeLevel = (level) => {
457
- let at = level.at;
458
- while (at) {
459
- const next = at.nextSibling;
460
- at.remove();
461
- at = next;
462
- }
463
- };
464
- // Block fragments not placed yet, and their blocks. A container element whose first block is
465
- // still to be placed, in another container at that level, belongs to that later container: a
466
- // block before it gets a new element instead of taking it (which would move every later block
467
- // into the next element along, e.g. when one list item moves to the next page).
468
- const pending = new Map(items.map((item) => [item.dom, item.block]));
469
- /** Container elements placed in this pass (never taken twice). */
470
- const claimed = new Set();
471
590
  let i = 0;
472
591
  for (let p = 0; p < count; p++) {
473
592
  const page = this.pages[p];
474
- const stack = [
475
- { el: page, at: page.firstChild, pos: -1 },
476
- ];
593
+ let at = page.firstChild;
477
594
  for (; i < items.length && items[i]?.page === p; i++) {
478
- const item = items[i];
479
- const chain = chains[item.block] ?? [];
480
- // Keep the open containers this block shares with the previous one on this page.
481
- let common = 0;
482
- while (common < chain.length &&
483
- common + 1 < stack.length &&
484
- stack[common + 1]?.pos === chain[common].pos)
485
- common++;
486
- while (stack.length > common + 1)
487
- closeLevel(stack.pop());
488
- for (let k = common; k < chain.length; k++) {
489
- const container = chain[k];
490
- const parent = stack[stack.length - 1];
491
- let element;
492
- const candidate = parent.at;
493
- const later = isWrapperFor(candidate, container.node)
494
- ? pending.get(firstBlockIn(candidate))
495
- : undefined;
496
- // The element that holds this block now, at the innermost level: a list item whose
497
- // block moves to another page takes its element along (as a paragraph does), instead
498
- // of a new one replacing it on every page an edit shifts.
499
- const own = k === chain.length - 1 ? item.dom.parentNode : null;
500
- if (isWrapperFor(candidate, container.node) &&
501
- !claimed.has(candidate) &&
502
- (later === undefined || chains[later]?.[k]?.pos === container.pos)) {
503
- element = candidate;
504
- parent.at = element.nextSibling;
505
- }
506
- else if (isWrapperFor(own, container.node) &&
507
- !claimed.has(own) &&
508
- !own.contains(parent.el)) {
509
- element = own;
510
- for (const level of stack)
511
- if (level.at === element)
512
- level.at = element.nextSibling;
513
- parent.el.insertBefore(element, parent.at);
514
- }
515
- else {
516
- element = createWrapper(container.node, ownerDocument);
517
- parent.el.insertBefore(element, parent.at);
518
- }
519
- claimed.add(element);
520
- styleContainer(element, container, chain[k - 1], item);
521
- stack.push({ el: element, at: element.firstChild, pos: container.pos });
522
- }
523
- const top = stack[stack.length - 1];
524
- if (item.dom === top.at)
525
- top.at = top.at.nextSibling;
526
- else {
527
- // A cursor of an outer level may point at this block (it moves into a new container):
528
- // step it past, or it would point into the container.
529
- for (const level of stack)
530
- if (level.at === item.dom)
531
- level.at = item.dom.nextSibling;
532
- top.el.insertBefore(item.dom, top.at);
533
- }
534
- pending.delete(item.dom);
595
+ const { dom } = items[i];
596
+ if (dom === at)
597
+ at = at.nextSibling;
598
+ else
599
+ page.insertBefore(dom, at);
600
+ }
601
+ // What is left after the last placed block: strays, and blocks of later pages.
602
+ while (at) {
603
+ const next = at.nextSibling;
604
+ at.remove();
605
+ at = next;
535
606
  }
536
- while (stack.length)
537
- closeLevel(stack.pop());
538
607
  }
539
608
  // Pages no longer needed and stray DOM in the host: all after the last page by now.
540
609
  let rest = this.pages[count - 1].nextSibling;
@@ -548,19 +617,19 @@ export class EditorView {
548
617
  createPage() {
549
618
  const page = this.host.ownerDocument.createElement("section");
550
619
  page.className = "foli-page";
551
- page.style.cssText = this.pageStyle;
552
620
  return page;
553
621
  }
554
- /** Page size and margins from the document settings, applied to every page when they change. */
555
- applyGeometry() {
556
- const { pageSize, margins } = this.editor.settings;
557
- const style = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
558
- `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
559
- if (style === this.pageStyle)
622
+ /** The last section's page setup (the envelope's), for an empty document. */
623
+ lastSheet() {
624
+ return sheetOf(this.editor.settings, 0);
625
+ }
626
+ /** The print rules for the document's page setups, written when they change. */
627
+ applyPrintStyles(layout) {
628
+ const sheets = [...new Set(layout.map((block) => block.sheet))];
629
+ const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
630
+ if (key === this.printKey)
560
631
  return;
561
- this.pageStyle = style;
562
- for (const page of this.pages)
563
- page.style.cssText = style;
632
+ this.printKey = key;
564
633
  // shortcut: written when the page settings change; a host moved to another document or shadow root keeps them where they were until then.
565
634
  for (const style of this.printStyles)
566
635
  style.remove();
@@ -572,11 +641,10 @@ export class EditorView {
572
641
  this.printStyles = parents.map((parent) => {
573
642
  const style = doc.createElement("style");
574
643
  style.setAttribute("data-foli-print", "");
575
- style.textContent = printStyles(this.editor.settings, this.id);
644
+ style.textContent = printStyles(this.editor.settings, sheets, this.id);
576
645
  parent.append(style);
577
646
  return style;
578
647
  });
579
- this.invalidateLayout();
580
648
  }
581
649
  /** Forgets every measurement: the next flow measures the whole document again. */
582
650
  invalidateLayout() {
@@ -585,6 +653,9 @@ export class EditorView {
585
653
  }
586
654
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
587
655
  onFontsLoaded = () => {
656
+ // v3 line heights come from the fonts' measured ratios: render every block again.
657
+ this.ratios.clear();
658
+ this.fontsChanged = true;
588
659
  this.invalidateLayout();
589
660
  this.scheduleRelayout();
590
661
  };
@@ -619,7 +690,7 @@ export class EditorView {
619
690
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
620
691
  if (!entry.contentRect.width)
621
692
  continue;
622
- scale ??= layoutScale(this.pages[0], this.editor.settings);
693
+ scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
623
694
  let height = 0;
624
695
  for (const fragment of desc.fragments)
625
696
  height += fragment.getBoundingClientRect().height;
@@ -666,9 +737,9 @@ export class EditorView {
666
737
  }
667
738
  return null;
668
739
  }
669
- /** Whether `node` holds blocks rather than content: the host, a page or a container. */
740
+ /** Whether `node` holds blocks rather than content: the host or a page. */
670
741
  holdsBlocks(node) {
671
- return node === this.host || this.pages.includes(node) || isWrapper(node);
742
+ return node === this.host || this.pages.includes(node);
672
743
  }
673
744
  /** Index of the first block that starts at or after `pos` (the block count if none). */
674
745
  blockFrom(pos) {
@@ -747,21 +818,31 @@ export class EditorView {
747
818
  const split = desc.splits.indexOf(offset);
748
819
  if (split >= 0)
749
820
  return fragmentStart(desc, split + 1);
750
- for (const leaf of desc.leaves) {
821
+ // Deleted text hidden by the review view takes no caret: the shown text next to it does.
822
+ const shown = desc.leaves.filter((leaf) => !hiddenIn(leaf.dom, desc.dom));
823
+ for (const leaf of shown) {
751
824
  if (leaf.dom.nodeType === Node.TEXT_NODE &&
752
825
  leaf.offset <= offset &&
753
826
  offset <= leaf.offset + leaf.size)
754
827
  return { node: leaf.dom, offset: offset - leaf.offset };
755
828
  }
756
- const next = desc.leaves.find((leaf) => leaf.offset >= offset);
757
- if (next)
829
+ const next = shown.find((leaf) => leaf.offset >= offset);
830
+ if (next) {
831
+ if (next.dom.nodeType === Node.TEXT_NODE)
832
+ return { node: next.dom, offset: 0 };
758
833
  return before(next.dom);
759
- const last = desc.leaves[desc.leaves.length - 1];
834
+ }
835
+ const last = shown[shown.length - 1];
760
836
  if (last) {
837
+ if (last.dom.nodeType === Node.TEXT_NODE)
838
+ return { node: last.dom, offset: last.dom.length };
761
839
  const point = before(last.dom);
762
840
  return { node: point.node, offset: point.offset + 1 };
763
841
  }
764
- return { node: desc.dom, offset: 0 };
842
+ // An empty block: before its <br> (after a list number shown in front of it).
843
+ const tail = desc.dom.lastChild;
844
+ const end = tail?.nodeName === "BR" ? desc.dom.childNodes.length - 1 : 0;
845
+ return { node: desc.dom, offset: end };
765
846
  }
766
847
  // ---------- selection ----------
767
848
  /** The live DOM selection as a model selection, or null if it is not inside the host. */
@@ -1034,19 +1115,27 @@ export class EditorView {
1034
1115
  const $pos = this.state.doc.resolve(pos);
1035
1116
  const node = $pos.parent.maybeChild($pos.index());
1036
1117
  const href = node && type.isInSet(node.marks)?.attrs.href;
1037
- return typeof href === "string" ? href : null;
1118
+ return isSafeHref(href) ? href : null;
1038
1119
  }
1039
1120
  onKeyDown = (event) => {
1040
1121
  if (event.isComposing || this.composing)
1041
1122
  return;
1042
1123
  this.syncSelection();
1043
- if (this.crossFragmentEdge(event)) {
1124
+ if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
1044
1125
  event.preventDefault();
1045
1126
  return;
1046
1127
  }
1047
1128
  const name = keyName(event);
1048
1129
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
1049
1130
  this.plainPaste = name === "Mod-Shift-v";
1131
+ // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
1132
+ // would type a tab (no keyboard trap).
1133
+ const tab = name === "Tab" || name === "Shift-Tab";
1134
+ const leave = tab && (this.tabLeaves || !this.editable);
1135
+ if (event.key !== "Shift")
1136
+ this.tabLeaves = name === "Escape";
1137
+ if (leave)
1138
+ return;
1050
1139
  // Like `editor.handleKey`, but through the view's dispatch, so read-only mode drops edits.
1051
1140
  // A key no command takes keeps its default (Tab outside a list moves the focus on).
1052
1141
  if (this.runKey(name)) {
@@ -1147,6 +1236,32 @@ export class EditorView {
1147
1236
  this.syncSelection();
1148
1237
  return true;
1149
1238
  }
1239
+ /**
1240
+ * A v3 list number is not text, but browsers stop the caret before it as well as after: Right
1241
+ * at the end of the paragraph before, or Left at a numbered paragraph's start, would seem to do
1242
+ * nothing. Moves over the paragraph boundary in one step (word moves are left to the browser).
1243
+ */
1244
+ crossListNumber(event) {
1245
+ const forward = event.key === "ArrowRight";
1246
+ if (!this.word || (!forward && event.key !== "ArrowLeft"))
1247
+ return false;
1248
+ if (event.metaKey || event.ctrlKey || event.altKey)
1249
+ return false;
1250
+ const { selection, doc } = this.state;
1251
+ if (!(selection instanceof TextSelection) || (!event.shiftKey && !selection.empty))
1252
+ return false;
1253
+ const { $head } = selection;
1254
+ if ($head.depth !== 1 || $head.parentOffset !== (forward ? $head.parent.content.size : 0))
1255
+ return false;
1256
+ const numbered = $head.index(0) + (forward ? 1 : 0);
1257
+ const other = doc.maybeChild($head.index(0) + (forward ? 1 : -1));
1258
+ if (!other?.isTextblock || !this.word.hasMarker(numbered))
1259
+ return false;
1260
+ const head = forward ? $head.after() + 1 : $head.before() - 1;
1261
+ const anchor = event.shiftKey ? selection.anchor : head;
1262
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, anchor, head)));
1263
+ return true;
1264
+ }
1150
1265
  /** Safety net: a DOM change that was not prevented is read back into the model. */
1151
1266
  onInput = () => {
1152
1267
  if (!this.composing)
@@ -1234,6 +1349,9 @@ export class EditorView {
1234
1349
  }
1235
1350
  else if (hardBreaks.has(node))
1236
1351
  domText += HARD_BREAK;
1352
+ // Shown but not document text (a list number, opaque content): never read back.
1353
+ else if (node.getAttribute?.("contenteditable") === "false")
1354
+ return;
1237
1355
  else
1238
1356
  node.childNodes.forEach(walk);
1239
1357
  };
@@ -1269,7 +1387,14 @@ export class EditorView {
1269
1387
  if (i > 0)
1270
1388
  modelText += BLOCK_SEPARATOR;
1271
1389
  lineStarts.push(modelText.length);
1272
- modelText += block.textBetween(0, block.content.size, "", HARD_BREAK);
1390
+ block.forEach((child) => {
1391
+ // A tab is text in the DOM (a "\t" text node).
1392
+ modelText += child.isText
1393
+ ? (child.text ?? "")
1394
+ : child.type.name === "tab"
1395
+ ? "\t"
1396
+ : HARD_BREAK;
1397
+ });
1273
1398
  });
1274
1399
  /** Model position of an offset in `modelText`. */
1275
1400
  const posAt = (offset) => {
@@ -1344,7 +1469,8 @@ export class EditorView {
1344
1469
  if (selection.empty || !event.clipboardData)
1345
1470
  return;
1346
1471
  event.preventDefault();
1347
- const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument);
1472
+ const context = wordContext(this.state);
1473
+ const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
1348
1474
  event.clipboardData.setData("text/plain", text);
1349
1475
  event.clipboardData.setData("text/html", html);
1350
1476
  event.clipboardData.setData(FOLI_MIME, json);
@@ -1395,15 +1521,19 @@ export class EditorView {
1395
1521
  if (command(state, dispatch))
1396
1522
  return applied;
1397
1523
  }
1398
- const marks = (state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1399
- const pasted = docFromClipboard(data, marks);
1400
- // One empty textblock: nothing to paste (a lone rule is something).
1524
+ const marks = typedMarks(state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1525
+ // The document takes the styles, lists and comments the content needs (HTML is read as
1526
+ // schema v2 content, then migrated).
1527
+ const pasted = docFromClipboard(data, marks, (found) => found.html
1528
+ ? fitPastedV2(state, parseContentV2(found.content))
1529
+ : fitPaste(state, found.content, found.word));
1530
+ // One empty paragraph: nothing to paste (a lone opaque block is something).
1401
1531
  const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
1402
1532
  if (!pasted || (only?.isTextblock && !only.content.size))
1403
1533
  return false;
1404
- const { doc, open } = pasted;
1405
- // As a slice (text joins the text around the caret); where the schema refuses that (a
1406
- // list in a paragraph), as whole blocks fitted at the caret.
1534
+ const { doc, open, envelope } = pasted;
1535
+ // As a slice (text joins the text around the caret); where that cannot be (an opaque block
1536
+ // at an end), as whole blocks at the caret.
1407
1537
  const asSlice = (tr) => {
1408
1538
  const $pos = tr.selection.$from;
1409
1539
  if (!open && $pos.depth === 1 && $pos.parent.isTextblock && !$pos.parent.content.size) {
@@ -1412,9 +1542,9 @@ export class EditorView {
1412
1542
  tr.setSelection(Selection.near(tr.doc.resolve(from + doc.content.size), -1));
1413
1543
  }
1414
1544
  else {
1415
- // A slice opens into its first and last blocks: a rule there has no inside.
1545
+ // A slice opens into its first and last blocks: an opaque block there has no inside.
1416
1546
  if (doc.firstChild?.isLeaf || doc.lastChild?.isLeaf) {
1417
- throw new TransformError("A rule at an end is pasted as a block");
1547
+ throw new TransformError("An opaque block at an end is pasted as a block");
1418
1548
  }
1419
1549
  tr.replaceSelection(doc.slice(1, doc.content.size - 1));
1420
1550
  }
@@ -1430,6 +1560,11 @@ export class EditorView {
1430
1560
  try {
1431
1561
  tr.deleteSelection();
1432
1562
  strategy(tr);
1563
+ const current = wordContext(state)?.envelope;
1564
+ if (envelope && current && envelope !== current) {
1565
+ withEnvelope(tr, envelope);
1566
+ setComments(tr, current.comments, envelope.comments);
1567
+ }
1433
1568
  }
1434
1569
  catch (error) {
1435
1570
  if (error instanceof TransformError)
@@ -1446,11 +1581,8 @@ export class EditorView {
1446
1581
  };
1447
1582
  }
1448
1583
  /**
1449
- * Pastes whole blocks at the caret (after deleting the selection), for content a slice cannot
1450
- * fit (lists): a single pasted list inside a list item joins that list (its items replace an
1451
- * empty item, go before or after the item, or between its two halves); other blocks go before
1452
- * or after the caret's textblock (replacing it when empty) where its parent takes them, else
1453
- * between its two halves. Throws TransformError where the schema does not allow it.
1584
+ * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1585
+ * paragraph, else between its two halves (an empty one is replaced as a slice first).
1454
1586
  */
1455
1587
  function insertBlocks(tr, doc) {
1456
1588
  const $pos = tr.selection.$from;
@@ -1458,89 +1590,18 @@ function insertBlocks(tr, doc) {
1458
1590
  throw new TransformError("No textblock at the caret");
1459
1591
  const atStart = $pos.parentOffset === 0;
1460
1592
  const atEnd = $pos.parentOffset === $pos.parent.content.size;
1461
- const only = doc.childCount === 1 ? doc.firstChild : null;
1462
- const itemType = tr.doc.type.schema.nodes.listItem;
1463
- const inItem = $pos.depth >= 2 && $pos.node(-1).type === itemType;
1464
1593
  let at;
1465
- let content = doc.content;
1466
- if (only && inItem && only.firstChild?.type === itemType) {
1467
- content = only.content;
1468
- const depth = $pos.depth - 1;
1469
- const item = $pos.node(depth);
1470
- if (atStart && atEnd && item.childCount === 1) {
1471
- at = $pos.before(depth);
1472
- tr.delete(at, $pos.after(depth));
1473
- }
1474
- else if (atEnd) {
1475
- // After the item (and its nested list, if it has one): no item left without its text.
1476
- at = $pos.after(depth);
1477
- }
1478
- else if (atStart && $pos.index(depth) === 0)
1479
- at = $pos.before(depth);
1480
- else if (atStart) {
1481
- // At a later block's start: split the item between blocks, not inside the text.
1482
- const boundary = $pos.before();
1483
- tr.split(boundary, 1);
1484
- at = boundary + 1;
1485
- }
1486
- else {
1487
- tr.split($pos.pos, 2);
1488
- at = $pos.pos + 2;
1489
- }
1490
- }
1594
+ if (atStart)
1595
+ at = $pos.before();
1596
+ else if (atEnd)
1597
+ at = $pos.after();
1491
1598
  else {
1492
- // Before, after, or in place of the textblock where its parent takes the blocks there (a
1493
- // list item's first paragraph must stay first); else between its two halves.
1494
- const parent = $pos.node(-1);
1495
- const index = $pos.index(-1);
1496
- if (atStart && atEnd && parent.canReplace(index, index + 1, content)) {
1497
- at = $pos.before();
1498
- tr.delete(at, $pos.after());
1499
- }
1500
- else if (atStart && parent.canReplace(index, index, content))
1501
- at = $pos.before();
1502
- else if (atEnd && parent.canReplace(index + 1, index + 1, content))
1503
- at = $pos.after();
1504
- else {
1505
- tr.split($pos.pos);
1506
- at = $pos.pos + 1;
1507
- }
1599
+ tr.split($pos.pos);
1600
+ at = $pos.pos + 1;
1508
1601
  }
1509
- tr.insert(at, content);
1510
- tr.setSelection(Selection.near(tr.doc.resolve(at + content.size), -1));
1511
- }
1512
- /** The first block element inside a container element (through nested containers), or null. */
1513
- function firstBlockIn(element) {
1514
- let child = element.firstElementChild;
1515
- while (isWrapper(child))
1516
- child = child.firstElementChild;
1517
- return child;
1602
+ tr.insert(at, doc.content);
1603
+ tr.setSelection(Selection.near(tr.doc.resolve(at + doc.content.size), -1));
1518
1604
  }
1519
- /**
1520
- * Sets what a container element shows on a page: an ordered list item's number (so numbering
1521
- * continues across pages), and no marker on an item continued from the previous page (its
1522
- * first block is on an earlier page, or this is a continued fragment of it).
1523
- */
1524
- function styleContainer(element, container, parent, item) {
1525
- if (element.localName !== "li")
1526
- return;
1527
- const continued = item.block !== container.firstBlock || item.fragment > 0;
1528
- const start = parent?.node.type.name === "orderedList" ? parent.node.attrs.start : undefined;
1529
- const value = typeof start === "number" ? String(start + container.index) : null;
1530
- // Written only when they change (checked against what was written last, without reading the
1531
- // DOM): this runs for every list item on every render, and every write invalidates style.
1532
- const state = `${continued}|${value}`;
1533
- if (containerStates.get(element) === state)
1534
- return;
1535
- containerStates.set(element, state);
1536
- element.style.listStyleType = continued ? "none" : "";
1537
- if (value === null)
1538
- element.removeAttribute("value");
1539
- else
1540
- element.setAttribute("value", value);
1541
- }
1542
- /** What `styleContainer` last wrote on each list item element. */
1543
- const containerStates = new WeakMap();
1544
1605
  /**
1545
1606
  * Client rects are scaled by CSS `zoom` or a `transform` on an ancestor, while margins and the
1546
1607
  * page geometry are in layout px: the ratio between the two for a page. From the page's width
@@ -1570,37 +1631,75 @@ function measureBox(desc, scale) {
1570
1631
  };
1571
1632
  }
1572
1633
  /**
1573
- * What the flow needs of a block: its measurement, its lines (on demand), and what the rules
1574
- * need: headings keep with the next block; page breaks end their line's page.
1634
+ * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
1635
+ * and after (next to its neighbours), keep with next, keep lines together (not for a block
1636
+ * taller than a page, or one with a page break in it), page breaks ending their line's page,
1637
+ * and a page break before the next block ending this one's page.
1575
1638
  */
1576
- function blockBox(desc, measure, lines) {
1639
+ function wordBox(blocks, i, measure, lines, layout) {
1640
+ const pageHeight = contentHeight(layout.sheet.settings);
1641
+ const desc = blocks[i];
1642
+ const next = blocks[i + 1];
1643
+ const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
1644
+ const pageBreaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1645
+ const hasBreak = pageBreaks.length > 0;
1646
+ const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
1647
+ const bottoms = () => (kept ? [measure.height] : lines().bottoms);
1577
1648
  return {
1578
1649
  height: measure.height,
1579
- marginTop: measure.marginTop,
1580
- marginBottom: measure.marginBottom,
1581
- lines: () => lines().bottoms,
1582
- keepWithNext: desc.node.type.name === "heading",
1650
+ marginTop: before,
1651
+ marginBottom: after,
1652
+ keepWithNext: desc.word.keepNext,
1653
+ pageHeight,
1654
+ lines: bottoms,
1583
1655
  breaksAfter: () => {
1584
- const breaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE &&
1585
- leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1586
- if (!breaks.length)
1587
- return [];
1588
- const { starts } = lines();
1589
- // The line holding the break: the last one starting at or before it.
1590
- return breaks.map((leaf) => {
1656
+ // The line holding each break: the last one starting at or before it.
1657
+ const breaks = pageBreaks.map((leaf) => {
1658
+ const { starts } = lines();
1591
1659
  let line = starts.length - 1;
1592
1660
  while (line > 0 && starts[line] > leaf.offset)
1593
1661
  line--;
1594
1662
  return line;
1595
1663
  });
1664
+ if (next?.word.pageBreakBefore || layout.breakAfter)
1665
+ breaks.push(bottoms().length - 1);
1666
+ return breaks;
1596
1667
  },
1597
1668
  };
1598
1669
  }
1670
+ /**
1671
+ * Writes Word's space above each v3 block as its top margin: the space after the block above
1672
+ * and the space before this one, on the same page; at the top of a page only its space before,
1673
+ * and only on the first page or after an explicit break (a page the text flowed onto drops it).
1674
+ * Written only when it changes.
1675
+ */
1676
+ function applyGaps(blocks, pages, boxes) {
1677
+ blocks.forEach((desc, i) => {
1678
+ const page = pages[i]?.[0] ?? 0;
1679
+ const above = pages[i - 1];
1680
+ const box = boxes[i];
1681
+ let gap;
1682
+ if (above && above[above.length - 1] === page)
1683
+ gap = boxes[i - 1].marginBottom + box.marginTop;
1684
+ else {
1685
+ const prior = boxes[i - 1];
1686
+ const breaks = prior?.breaksAfter?.() ?? [];
1687
+ const forced = page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1688
+ gap = forced ? box.marginTop : 0;
1689
+ }
1690
+ if (gaps.get(desc.dom) === gap)
1691
+ return;
1692
+ gaps.set(desc.dom, gap);
1693
+ desc.dom.style.marginTop = `${gap}px`;
1694
+ });
1695
+ }
1696
+ /** The gap `applyGaps` last wrote on each block element (the style serializes it rounded). */
1697
+ const gaps = new WeakMap();
1599
1698
  /**
1600
1699
  * What the next flow can reuse of the last one: the unchanged blocks before the first changed
1601
1700
  * (or stale) one, and the unchanged tail after the last.
1602
1701
  */
1603
- function reuseOf(last, nodes, stale) {
1702
+ function reuseOf(last, nodes, stale, margin = 0) {
1604
1703
  const before = last.nodes;
1605
1704
  const same = (a, b) => a !== undefined && a === b && !stale.has(a);
1606
1705
  let from = 0;
@@ -1611,6 +1710,9 @@ function reuseOf(last, nodes, stale) {
1611
1710
  tail < before.length - from &&
1612
1711
  same(nodes[nodes.length - 1 - tail], before[before.length - 1 - tail]))
1613
1712
  tail++;
1713
+ // Blocks whose box depends on a changed neighbour are not reused either.
1714
+ from = Math.max(0, from - margin);
1715
+ tail = Math.max(0, tail - margin);
1614
1716
  const delta = nodes.length - before.length;
1615
1717
  return {
1616
1718
  previous: last.result,