@folijs/view 0.2.0 → 0.3.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/src/view.ts CHANGED
@@ -10,22 +10,32 @@ import {
10
10
  deleteSelection,
11
11
  type Editor,
12
12
  type EditorState,
13
+ fitPaste,
14
+ fitPastedV2,
13
15
  insertHardBreak,
14
16
  insertLink,
15
17
  insertText,
18
+ isSafeHref,
16
19
  type Node as ModelNode,
17
20
  marksAt,
18
21
  NodeSelection,
22
+ parseContentV2,
19
23
  redo,
24
+ type SectionJSON,
20
25
  Selection,
21
26
  Slice,
27
+ sectionSettings,
22
28
  setLink,
23
29
  splitBlock,
24
30
  TextSelection,
25
31
  type Transaction,
26
32
  TransformError,
27
33
  toggleMark,
34
+ typedMarks,
28
35
  undo,
36
+ type WordContext,
37
+ withEnvelope,
38
+ wordContext,
29
39
  } from "@folijs/core";
30
40
  import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
31
41
  import {
@@ -33,29 +43,17 @@ import {
33
43
  contentHeight,
34
44
  DEFAULT_RULES,
35
45
  type FlowResult,
46
+ type FlowRules,
36
47
  flowFrom,
37
48
  PX_PER_MM,
38
49
  type Reuse,
39
50
  } from "./layout/flow.js";
40
- import {
41
- type BlockDesc,
42
- createWrapper,
43
- isWrapper,
44
- isWrapperFor,
45
- PAGE_BREAK_ATTR,
46
- renderBlock,
47
- } from "./render.js";
51
+ import { type BlockDesc, PAGE_BREAK_ATTR } from "./render.js";
52
+ import { spacing, type WordBlockDesc, WordRenderer } from "./word/edit.js";
53
+ import { measureLineRatio } from "./word/pages.js";
48
54
 
49
- /**
50
- * A container around blocks (a list, a list item) as rendered: its node, the position before it
51
- * (which identifies it within one render), its index in its parent and its first block's index.
52
- */
53
- interface Container {
54
- readonly node: ModelNode;
55
- readonly pos: number;
56
- readonly index: number;
57
- readonly firstBlock: number;
58
- }
55
+ /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
56
+ const WORD_RULES: FlowRules = { ...DEFAULT_RULES, spacing: "word" };
59
57
 
60
58
  /** Class of the element of a node-selected block (a rule). */
61
59
  const SELECTED_CLASS = "foli-selected-node";
@@ -101,19 +99,122 @@ let viewCount = 0;
101
99
 
102
100
  /**
103
101
  * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
104
- * the document's size per page, without margins (the page's padding holds them). A page is
105
- * exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
102
+ * its section's size per page (the last section's where named pages are not supported), without
103
+ * 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
106
104
  * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
107
105
  * page) is not cut: it prints over the next sheet.
108
106
  * 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.
109
107
  */
110
- function printStyles({ pageSize }: DocumentSettings, id: string): string {
111
- const { width, height } = pageSize;
108
+ function printStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: string): string {
109
+ const { width, height } = settings.pageSize;
110
+ const last = sheetOf(settings, 0).css;
112
111
  const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
112
+ // Sections with other page setups: a named page each (engines without named pages print
113
+ // every sheet at the last section's size).
114
+ const named = sheets.every((sheet) => sheet.css === last)
115
+ ? ""
116
+ : sheets
117
+ .map(({ settings: { pageSize: size }, index }) => {
118
+ const name = `foli-${id}-${index}`;
119
+ return (
120
+ `@page ${name}{size:${size.width}mm ${size.height}mm;margin:0}` +
121
+ `${pages}[${SHEET_ATTR}="${index}"]{page:${name};height:${size.height}mm!important}`
122
+ );
123
+ })
124
+ .join("");
113
125
  return (
114
126
  `@media print{@page{size:${width}mm ${height}mm;margin:0}` +
115
127
  `${pages}{height:${height}mm!important;margin-block:0!important;` +
116
- `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}}`
128
+ `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`
129
+ );
130
+ }
131
+
132
+ /** The attribute naming a page's page setup (its index among the document's) for print. */
133
+ const SHEET_ATTR = "data-foli-sheet";
134
+
135
+ /** A page setup: its settings (mm), the page style it gives, its index among the document's. */
136
+ interface Sheet {
137
+ readonly settings: DocumentSettings;
138
+ readonly css: string;
139
+ readonly index: number;
140
+ }
141
+
142
+ function sheetOf(settings: DocumentSettings, index: number): Sheet {
143
+ const { pageSize, margins } = settings;
144
+ const css =
145
+ `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
146
+ `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
147
+ return { settings, css, index };
148
+ }
149
+
150
+ /** The style each page element was last given (its `cssText` reads back normalized). */
151
+ const pageSheets = new WeakMap<HTMLElement, string>();
152
+
153
+ /** A block's section: its page setup, and whether the next block starts a new page. */
154
+ interface BlockLayout {
155
+ readonly sheet: Sheet;
156
+ readonly breakAfter: boolean;
157
+ }
158
+
159
+ /**
160
+ * The section of each top-level block (the section a paragraph's `section` ends; the
161
+ * envelope's for the blocks after the last such paragraph). A section starts a new page,
162
+ * unless it is continuous with the same page setup as the one before (shortcut: a continuous
163
+ * section with another page setup starts a new page; Word's even and odd page sections do not
164
+ * add a blank page), as `renderDocument` lays sections out.
165
+ */
166
+ function sectionLayouts(doc: ModelNode, last: SectionJSON): BlockLayout[] {
167
+ const sheets = new Map<string, Sheet>();
168
+ const bySection = new Map<SectionJSON, Sheet>();
169
+ const sheet = (section: SectionJSON) => {
170
+ let found = bySection.get(section);
171
+ if (!found) {
172
+ const settings = sectionSettings(section);
173
+ const css = sheetOf(settings, 0).css;
174
+ found = sheets.get(css) ?? sheetOf(settings, sheets.size);
175
+ sheets.set(css, found);
176
+ bySection.set(section, found);
177
+ }
178
+ return found;
179
+ };
180
+ const sections: SectionJSON[] = [];
181
+ let section = last;
182
+ for (let i = doc.childCount - 1; i >= 0; i--) {
183
+ const own = doc.child(i).attrs.section as SectionJSON | null | undefined;
184
+ if (own) section = own;
185
+ sections[i] = section;
186
+ }
187
+ // Indexes in document order: the first page setup is 0.
188
+ sections.forEach(sheet);
189
+ return sections.map((own, i) => {
190
+ const next = sections[i + 1];
191
+ // By position, as `renderDocument`: two paragraphs may end sections with one object.
192
+ const ends = !!next && !!doc.child(i).attrs.section;
193
+ const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
194
+ return { sheet: sheet(own), breakAfter };
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Initial pages (before a flow), moved where needed so that each page holds blocks of one
200
+ * page setup: a block is measured in a page of its own section's width.
201
+ */
202
+ function separateSheets(
203
+ pages: readonly (readonly number[])[],
204
+ layout: readonly BlockLayout[],
205
+ ): number[][] {
206
+ const css: string[] = [];
207
+ let floor = 0;
208
+ return pages.map((list, i) =>
209
+ list.map((p) => {
210
+ const want = (layout[i] as BlockLayout).sheet.css;
211
+ let page = Math.max(p, floor);
212
+ // Only the last page used so far has a setup: the next one is free.
213
+ if (css[page] !== undefined && css[page] !== want) page++;
214
+ css[page] ??= want;
215
+ floor = page;
216
+ return page;
217
+ }),
117
218
  );
118
219
  }
119
220
 
@@ -126,21 +227,16 @@ function printStyles({ pageSize }: DocumentSettings, id: string): string {
126
227
  * view cannot prevent (Android keyboards, extensions). A MutationObserver records those; the view
127
228
  * then reads the changed text back into a transaction (`readBack`) and re-renders.
128
229
  *
129
- * Blocks are the leaf blocks of the document at any depth (paragraphs, headings, rules); the
130
- * containers around them (lists, list items) are rebuilt on each page around the blocks it holds
131
- * (ADR-0004).
230
+ * Blocks are the document's paragraphs and opaque blocks (a schema v3 document has no
231
+ * containers: a list is numbered paragraphs).
132
232
  */
133
233
  export class EditorView {
134
234
  private state: EditorState;
135
- private blocks: BlockDesc[] = [];
235
+ private blocks: WordBlockDesc[] = [];
136
236
  /** Position before each block, parallel to `blocks`. */
137
237
  private starts: number[] = [];
138
- /** The containers around each block, outermost first, parallel to `blocks`. */
139
- private chains: (readonly Container[])[] = [];
140
238
  /** The index of each block in `blocks`. */
141
239
  private indexOf = new Map<BlockDesc, number>();
142
- /** The container types around each block at its last render (a change means re-measuring). */
143
- private chainKeys = new WeakMap<ModelNode, string>();
144
240
  /** The element that shows a node selection, if any. */
145
241
  private selectedDom: HTMLElement | null = null;
146
242
  /** The page of each fragment of each block. */
@@ -149,7 +245,16 @@ export class EditorView {
149
245
  private owner = new Map<Node, BlockDesc>();
150
246
  /** The page elements, in order; the host's only children. */
151
247
  private pages: HTMLElement[] = [];
152
- private pageStyle = "";
248
+ /** The page setup of each page (its section's), parallel to `pages`. */
249
+ private sheets: Sheet[] = [];
250
+ /** The page setups the print rules were written for. */
251
+ private printKey = "";
252
+ /**
253
+ * Each block's page setup and whether a section break follows it, as last rendered: a block
254
+ * whose layout changed (a section break inserted or removed around it) is measured and
255
+ * flowed again.
256
+ */
257
+ private layoutKeys = new WeakMap<ModelNode, string>();
153
258
  /** Marks the host for this view's print rules (`printStyles`). */
154
259
  private readonly id = String(++viewCount);
155
260
  /**
@@ -164,7 +269,7 @@ export class EditorView {
164
269
  * Measurements by model node: a node's rendered height, margins and lines only depend on
165
270
  * its content (unchanged node, same identity), the page width and the CSS. Cleared when the
166
271
  * page settings or the fonts change; single entries go stale when a block's size changes
167
- * without an edit (`ResizeObserver`: CSS, fonts, a container).
272
+ * without an edit (`ResizeObserver`: CSS, fonts).
168
273
  */
169
274
  private measures = new WeakMap<ModelNode, Measure>();
170
275
  private readonly stale = new Set<ModelNode>();
@@ -189,6 +294,8 @@ export class EditorView {
189
294
  private readonly observer: MutationObserver;
190
295
  private readonly unsubscribe: () => void;
191
296
  private editable = true;
297
+ /** Escape was the last key: Tab now leaves the editor. */
298
+ private tabLeaves = false;
192
299
  private placeholder = "";
193
300
  /** The block that shows the placeholder, if any. */
194
301
  private placeholderDom: HTMLElement | null = null;
@@ -196,6 +303,12 @@ export class EditorView {
196
303
  private pointerFocus = false;
197
304
  /** Whether the view added the host's tabindex (a read-only host must stay focusable). */
198
305
  private readonly addedTabIndex: boolean;
306
+ /** Renders the document's blocks; made by the first render. */
307
+ private word: WordRenderer | null = null;
308
+ /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
309
+ private readonly ratios = new Map<string, number>();
310
+ /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
311
+ private fontsChanged = false;
199
312
 
200
313
  constructor(
201
314
  readonly host: HTMLElement,
@@ -370,6 +483,28 @@ export class EditorView {
370
483
  private render(): void {
371
484
  const { doc } = this.state;
372
485
  const ownerDocument = this.host.ownerDocument;
486
+ // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
487
+ // editor's state always has one (`createEditor`).
488
+ const context = wordContext(this.state) as WordContext;
489
+ // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
490
+ // block it would redraw.
491
+ const renewed =
492
+ context !== (this.word?.context ?? null) || (this.fontsChanged && !this.composing);
493
+ if (renewed) this.fontsChanged = false;
494
+ let word = this.word as WordRenderer;
495
+ if (renewed) {
496
+ word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio);
497
+ this.invalidateLayout();
498
+ }
499
+ word.prepare(doc);
500
+ const layout = sectionLayouts(doc, context.envelope.section);
501
+ doc.forEach((node, _, i) => {
502
+ const { sheet, breakAfter } = layout[i] as BlockLayout;
503
+ const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
504
+ const before = this.layoutKeys.get(node);
505
+ if (before !== undefined && before !== key) this.stale.add(node);
506
+ this.layoutKeys.set(node, key);
507
+ });
373
508
  const previous = new Map(
374
509
  this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]),
375
510
  );
@@ -380,63 +515,38 @@ export class EditorView {
380
515
  this.linesStale = false;
381
516
  this.flowed = null;
382
517
  }
383
- let blocks: BlockDesc[] = [];
518
+ let blocks: WordBlockDesc[] = [];
384
519
  const starts: number[] = [];
385
- const chains: (readonly Container[])[] = [];
386
- // Leaf blocks at any depth, in document order, with the containers around each.
387
- const open: Container[] = [];
388
- // The chain of the open containers and its key, rebuilt only when they change (blocks in
389
- // the same container share one array).
390
- let chain: readonly Container[] = [];
391
- let chainKey = "";
392
- const changed = () => {
393
- chain = open.slice();
394
- chainKey = open.map((container) => container.node.type.name).join(">");
395
- };
396
- doc.descendants((node, pos, _parent, index) => {
397
- let popped = false;
398
- while (open.length) {
399
- const last = open[open.length - 1] as Container;
400
- if (pos < last.pos + last.node.nodeSize) break;
401
- open.pop();
402
- popped = true;
403
- }
404
- if (!node.isTextblock && !node.isLeaf) {
405
- open.push({ node, pos, index, firstBlock: blocks.length });
406
- changed();
407
- return true;
520
+ doc.forEach((node, pos) => {
521
+ let reused = renewed ? undefined : previous.get(node);
522
+ // A block whose list number or comment shading changed (an edit before it) is redrawn.
523
+ if (reused && reused.key !== word.key(blocks.length)) {
524
+ reused = undefined;
525
+ this.stale.add(node);
408
526
  }
409
- if (popped) changed();
410
- // A block moved into or out of a container (wrapped in a list, indented, lifted) keeps its
411
- // node but not its line width or margins: measure it again, and re-flow from it.
412
- const before = this.chainKeys.get(node);
413
- if (before !== undefined && before !== chainKey) this.stale.add(node);
414
- this.chainKeys.set(node, chainKey);
415
- let reused = previous.get(node);
416
527
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
417
528
  // fragment's end breaks its line, so its lines would depend on where it was split before.
418
529
  const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
419
530
  if (reused && reused.fragments.length > 1 && remeasure && !this.composing) reused = undefined;
420
531
  if (reused) previous.delete(node);
421
- blocks.push(reused ?? renderBlock(node, ownerDocument));
532
+ blocks.push(reused ?? word.render(node, blocks.length));
422
533
  starts.push(pos);
423
- chains.push(chain);
424
- return false;
425
534
  });
426
535
  for (const stale of previous.values())
427
536
  for (const fragment of stale.fragments) fragment.remove();
428
- this.applyGeometry();
537
+ this.applyPrintStyles(layout);
429
538
  let last = 0;
430
539
  let pages = blocks.map((desc) => {
431
540
  const before = previousPages.get(desc);
432
541
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
433
542
  });
434
- this.place(blocks, pages, chains);
543
+ pages = separateSheets(pages, layout);
544
+ this.place(blocks, pages, layout);
435
545
  if (!this.composing) {
436
546
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
437
547
  let scale: number | undefined;
438
548
  const layoutPx = () => {
439
- scale ??= layoutScale(this.pages[0] as HTMLElement, this.editor.settings);
549
+ scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
440
550
  return scale;
441
551
  };
442
552
  if (dropLines)
@@ -445,7 +555,8 @@ export class EditorView {
445
555
  if (measure) delete measure.lines;
446
556
  }
447
557
  const nodes = blocks.map((desc) => desc.node);
448
- const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale) : undefined;
558
+ // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
559
+ const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
449
560
  const measureOf = (desc: BlockDesc) => {
450
561
  let found = this.measures.get(desc.node);
451
562
  // A stale block is measured again once per render.
@@ -460,8 +571,10 @@ export class EditorView {
460
571
  found.lines ??= measureLines(desc, layoutPx());
461
572
  return found.lines;
462
573
  };
463
- const boxes = blocks.map((desc) => blockBox(desc, measureOf(desc), () => lines(desc)));
464
- const result = flowFrom(boxes, contentHeight(this.editor.settings), DEFAULT_RULES, reuse);
574
+ const boxes = blocks.map((desc, i) =>
575
+ wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i] as BlockLayout),
576
+ );
577
+ const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
465
578
  this.flowed = { nodes, result };
466
579
  this.stale.clear();
467
580
  const flowed = result.fragments;
@@ -475,14 +588,14 @@ export class EditorView {
475
588
  });
476
589
  const same =
477
590
  splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
478
- return same ? desc : renderBlock(desc.node, ownerDocument, splits);
591
+ return same ? desc : word.render(desc.node, i, splits);
479
592
  });
480
593
  pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
481
- this.place(blocks, pages, chains);
594
+ applyGaps(blocks, pages, boxes);
595
+ this.place(blocks, pages, layout);
482
596
  }
483
597
  this.blocks = blocks;
484
598
  this.starts = starts;
485
- this.chains = chains;
486
599
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
487
600
  this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
488
601
  this.owner = new Map(
@@ -498,111 +611,72 @@ export class EditorView {
498
611
  if (this.composing) this.pending.push(...records);
499
612
  }
500
613
 
614
+ /** A font's normal line height ratio, measured outside the host (no input to read back). */
615
+ private lineRatio = (family: string): number => {
616
+ let ratio = this.ratios.get(family);
617
+ if (ratio === undefined) {
618
+ const doc = this.host.ownerDocument;
619
+ ratio = measureLineRatio(doc.body ?? doc.documentElement)(family);
620
+ this.ratios.set(family, ratio);
621
+ }
622
+ return ratio;
623
+ };
624
+
501
625
  /**
502
626
  * Puts each fragment of each block into its page (pages are non-decreasing in document
503
- * order), inside the elements of the block's containers (lists, list items), creating and
504
- * removing pages as needed. A page reuses the container elements already at the same place
505
- * (same tag, in order), so an edit inside a list moves no DOM. Anything else in the host, a
506
- * page or a container (stray DOM) is removed.
627
+ * order), creating and removing pages as needed, and gives each page the page setup of its
628
+ * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
629
+ * or a page (stray DOM) is removed.
507
630
  */
508
631
  private place(
509
632
  blocks: readonly BlockDesc[],
510
633
  pages: readonly (readonly number[])[],
511
- chains: readonly (readonly Container[])[],
634
+ layout: readonly BlockLayout[],
512
635
  ): void {
513
636
  const { host } = this;
514
637
  const items = blocks.flatMap((desc, i) =>
515
- desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0, block: i, fragment: f })),
638
+ desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })),
516
639
  );
517
640
  const count = (items[items.length - 1]?.page ?? 0) + 1;
641
+ const sheets: Sheet[] = [];
642
+ pages.forEach((list, i) => {
643
+ for (const p of list) sheets[p] ??= (layout[i] as BlockLayout).sheet;
644
+ });
645
+ // A page no block starts on (none yet) takes the setup of the page before it.
646
+ for (let p = 0; p < count; p++)
647
+ sheets[p] ??=
648
+ sheets[p - 1] ?? (layout[0] as BlockLayout | undefined)?.sheet ?? this.lastSheet();
649
+ this.sheets = sheets.slice(0, count);
518
650
  while (this.pages.length < count) this.pages.push(this.createPage());
651
+ this.sheets.forEach((sheet, p) => {
652
+ const page = this.pages[p] as HTMLElement;
653
+ const key = `${sheet.index} ${sheet.css}`;
654
+ if (pageSheets.get(page) === key) return;
655
+ pageSheets.set(page, key);
656
+ page.style.cssText = sheet.css;
657
+ page.setAttribute(SHEET_ATTR, String(sheet.index));
658
+ });
519
659
  // Pages first, in order; anything else in the host ends up after them.
520
660
  let cursor = host.firstChild;
521
661
  for (const page of this.pages.slice(0, count)) {
522
662
  if (page === cursor) cursor = cursor.nextSibling;
523
663
  else host.insertBefore(page, cursor);
524
664
  }
525
- const ownerDocument = host.ownerDocument;
526
- /** Removes what is left after the last placed child (strays, and blocks of later pages). */
527
- const closeLevel = (level: { at: ChildNode | null }) => {
528
- let at = level.at;
529
- while (at) {
530
- const next: ChildNode | null = at.nextSibling;
531
- at.remove();
532
- at = next;
533
- }
534
- };
535
- // Block fragments not placed yet, and their blocks. A container element whose first block is
536
- // still to be placed, in another container at that level, belongs to that later container: a
537
- // block before it gets a new element instead of taking it (which would move every later block
538
- // into the next element along, e.g. when one list item moves to the next page).
539
- const pending = new Map<Node, number>(items.map((item) => [item.dom, item.block]));
540
- /** Container elements placed in this pass (never taken twice). */
541
- const claimed = new Set<Node>();
542
665
  let i = 0;
543
666
  for (let p = 0; p < count; p++) {
544
667
  const page = this.pages[p] as HTMLElement;
545
- const stack: { el: HTMLElement; at: ChildNode | null; pos: number }[] = [
546
- { el: page, at: page.firstChild, pos: -1 },
547
- ];
668
+ let at = page.firstChild;
548
669
  for (; i < items.length && items[i]?.page === p; i++) {
549
- const item = items[i] as (typeof items)[number];
550
- const chain = chains[item.block] ?? [];
551
- // Keep the open containers this block shares with the previous one on this page.
552
- let common = 0;
553
- while (
554
- common < chain.length &&
555
- common + 1 < stack.length &&
556
- stack[common + 1]?.pos === (chain[common] as Container).pos
557
- )
558
- common++;
559
- while (stack.length > common + 1) closeLevel(stack.pop() as (typeof stack)[number]);
560
- for (let k = common; k < chain.length; k++) {
561
- const container = chain[k] as Container;
562
- const parent = stack[stack.length - 1] as (typeof stack)[number];
563
- let element: HTMLElement;
564
- const candidate = parent.at;
565
- const later = isWrapperFor(candidate, container.node)
566
- ? pending.get(firstBlockIn(candidate) as Node)
567
- : undefined;
568
- // The element that holds this block now, at the innermost level: a list item whose
569
- // block moves to another page takes its element along (as a paragraph does), instead
570
- // of a new one replacing it on every page an edit shifts.
571
- const own = k === chain.length - 1 ? item.dom.parentNode : null;
572
- if (
573
- isWrapperFor(candidate, container.node) &&
574
- !claimed.has(candidate) &&
575
- (later === undefined || chains[later]?.[k]?.pos === container.pos)
576
- ) {
577
- element = candidate;
578
- parent.at = element.nextSibling;
579
- } else if (
580
- isWrapperFor(own, container.node) &&
581
- !claimed.has(own) &&
582
- !own.contains(parent.el)
583
- ) {
584
- element = own;
585
- for (const level of stack) if (level.at === element) level.at = element.nextSibling;
586
- parent.el.insertBefore(element, parent.at);
587
- } else {
588
- element = createWrapper(container.node, ownerDocument);
589
- parent.el.insertBefore(element, parent.at);
590
- }
591
- claimed.add(element);
592
- styleContainer(element, container, chain[k - 1], item);
593
- stack.push({ el: element, at: element.firstChild, pos: container.pos });
594
- }
595
- const top = stack[stack.length - 1] as (typeof stack)[number];
596
- if (item.dom === top.at) top.at = top.at.nextSibling;
597
- else {
598
- // A cursor of an outer level may point at this block (it moves into a new container):
599
- // step it past, or it would point into the container.
600
- for (const level of stack) if (level.at === item.dom) level.at = item.dom.nextSibling;
601
- top.el.insertBefore(item.dom, top.at);
602
- }
603
- pending.delete(item.dom);
670
+ const { dom } = items[i] as (typeof items)[number];
671
+ if (dom === at) at = at.nextSibling;
672
+ else page.insertBefore(dom, at);
673
+ }
674
+ // What is left after the last placed block: strays, and blocks of later pages.
675
+ while (at) {
676
+ const next: ChildNode | null = at.nextSibling;
677
+ at.remove();
678
+ at = next;
604
679
  }
605
- while (stack.length) closeLevel(stack.pop() as (typeof stack)[number]);
606
680
  }
607
681
  // Pages no longer needed and stray DOM in the host: all after the last page by now.
608
682
  let rest = (this.pages[count - 1] as HTMLElement).nextSibling;
@@ -617,19 +691,20 @@ export class EditorView {
617
691
  private createPage(): HTMLElement {
618
692
  const page = this.host.ownerDocument.createElement("section");
619
693
  page.className = "foli-page";
620
- page.style.cssText = this.pageStyle;
621
694
  return page;
622
695
  }
623
696
 
624
- /** Page size and margins from the document settings, applied to every page when they change. */
625
- private applyGeometry(): void {
626
- const { pageSize, margins } = this.editor.settings;
627
- const style =
628
- `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
629
- `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
630
- if (style === this.pageStyle) return;
631
- this.pageStyle = style;
632
- for (const page of this.pages) page.style.cssText = style;
697
+ /** The last section's page setup (the envelope's), for an empty document. */
698
+ private lastSheet(): Sheet {
699
+ return sheetOf(this.editor.settings, 0);
700
+ }
701
+
702
+ /** The print rules for the document's page setups, written when they change. */
703
+ private applyPrintStyles(layout: readonly BlockLayout[]): void {
704
+ const sheets = [...new Set(layout.map((block) => block.sheet))];
705
+ const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
706
+ if (key === this.printKey) return;
707
+ this.printKey = key;
633
708
  // shortcut: written when the page settings change; a host moved to another document or shadow root keeps them where they were until then.
634
709
  for (const style of this.printStyles) style.remove();
635
710
  const doc = this.host.ownerDocument;
@@ -639,11 +714,10 @@ export class EditorView {
639
714
  this.printStyles = parents.map((parent) => {
640
715
  const style = doc.createElement("style");
641
716
  style.setAttribute("data-foli-print", "");
642
- style.textContent = printStyles(this.editor.settings, this.id);
717
+ style.textContent = printStyles(this.editor.settings, sheets, this.id);
643
718
  parent.append(style);
644
719
  return style;
645
720
  });
646
- this.invalidateLayout();
647
721
  }
648
722
 
649
723
  /** Forgets every measurement: the next flow measures the whole document again. */
@@ -654,6 +728,9 @@ export class EditorView {
654
728
 
655
729
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
656
730
  private onFontsLoaded = (): void => {
731
+ // v3 line heights come from the fonts' measured ratios: render every block again.
732
+ this.ratios.clear();
733
+ this.fontsChanged = true;
657
734
  this.invalidateLayout();
658
735
  this.scheduleRelayout();
659
736
  };
@@ -685,7 +762,7 @@ export class EditorView {
685
762
  if (!desc || !measured || this.stale.has(desc.node)) continue;
686
763
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
687
764
  if (!entry.contentRect.width) continue;
688
- scale ??= layoutScale(this.pages[0] as HTMLElement, this.editor.settings);
765
+ scale ??= layoutScale(this.pages[0] as HTMLElement, (this.sheets[0] as Sheet).settings);
689
766
  let height = 0;
690
767
  for (const fragment of desc.fragments) height += fragment.getBoundingClientRect().height;
691
768
  // A block is measured whole; each fragment of a split one keeps its padding and border,
@@ -732,9 +809,9 @@ export class EditorView {
732
809
  return null;
733
810
  }
734
811
 
735
- /** Whether `node` holds blocks rather than content: the host, a page or a container. */
812
+ /** Whether `node` holds blocks rather than content: the host or a page. */
736
813
  private holdsBlocks(node: Node): boolean {
737
- return node === this.host || this.pages.includes(node as HTMLElement) || isWrapper(node);
814
+ return node === this.host || this.pages.includes(node as HTMLElement);
738
815
  }
739
816
 
740
817
  /** Index of the first block that starts at or after `pos` (the block count if none). */
@@ -823,7 +900,10 @@ export class EditorView {
823
900
  const point = before(last.dom);
824
901
  return { node: point.node, offset: point.offset + 1 };
825
902
  }
826
- return { node: desc.dom, offset: 0 };
903
+ // An empty block: before its <br> (after a list number shown in front of it).
904
+ const tail = desc.dom.lastChild;
905
+ const end = tail?.nodeName === "BR" ? desc.dom.childNodes.length - 1 : 0;
906
+ return { node: desc.dom, offset: end };
827
907
  }
828
908
 
829
909
  // ---------- selection ----------
@@ -1088,19 +1168,25 @@ export class EditorView {
1088
1168
  const $pos = this.state.doc.resolve(pos);
1089
1169
  const node = $pos.parent.maybeChild($pos.index());
1090
1170
  const href = node && type.isInSet(node.marks)?.attrs.href;
1091
- return typeof href === "string" ? href : null;
1171
+ return isSafeHref(href) ? href : null;
1092
1172
  }
1093
1173
 
1094
1174
  private onKeyDown = (event: KeyboardEvent): void => {
1095
1175
  if (event.isComposing || this.composing) return;
1096
1176
  this.syncSelection();
1097
- if (this.crossFragmentEdge(event)) {
1177
+ if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
1098
1178
  event.preventDefault();
1099
1179
  return;
1100
1180
  }
1101
1181
  const name = keyName(event);
1102
1182
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
1103
1183
  this.plainPaste = name === "Mod-Shift-v";
1184
+ // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
1185
+ // would type a tab (no keyboard trap).
1186
+ const tab = name === "Tab" || name === "Shift-Tab";
1187
+ const leave = tab && (this.tabLeaves || !this.editable);
1188
+ if (event.key !== "Shift") this.tabLeaves = name === "Escape";
1189
+ if (leave) return;
1104
1190
  // Like `editor.handleKey`, but through the view's dispatch, so read-only mode drops edits.
1105
1191
  // A key no command takes keeps its default (Tab outside a list moves the focus on).
1106
1192
  if (this.runKey(name)) {
@@ -1193,6 +1279,30 @@ export class EditorView {
1193
1279
  return true;
1194
1280
  }
1195
1281
 
1282
+ /**
1283
+ * A v3 list number is not text, but browsers stop the caret before it as well as after: Right
1284
+ * at the end of the paragraph before, or Left at a numbered paragraph's start, would seem to do
1285
+ * nothing. Moves over the paragraph boundary in one step (word moves are left to the browser).
1286
+ */
1287
+ private crossListNumber(event: KeyboardEvent): boolean {
1288
+ const forward = event.key === "ArrowRight";
1289
+ if (!this.word || (!forward && event.key !== "ArrowLeft")) return false;
1290
+ if (event.metaKey || event.ctrlKey || event.altKey) return false;
1291
+ const { selection, doc } = this.state;
1292
+ if (!(selection instanceof TextSelection) || (!event.shiftKey && !selection.empty))
1293
+ return false;
1294
+ const { $head } = selection;
1295
+ if ($head.depth !== 1 || $head.parentOffset !== (forward ? $head.parent.content.size : 0))
1296
+ return false;
1297
+ const numbered = $head.index(0) + (forward ? 1 : 0);
1298
+ const other = doc.maybeChild($head.index(0) + (forward ? 1 : -1));
1299
+ if (!other?.isTextblock || !this.word.hasMarker(numbered)) return false;
1300
+ const head = forward ? $head.after() + 1 : $head.before() - 1;
1301
+ const anchor = event.shiftKey ? selection.anchor : head;
1302
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, anchor, head)));
1303
+ return true;
1304
+ }
1305
+
1196
1306
  /** Safety net: a DOM change that was not prevented is read back into the model. */
1197
1307
  private onInput = (): void => {
1198
1308
  if (!this.composing) this.flush();
@@ -1277,6 +1387,8 @@ export class EditorView {
1277
1387
  if (node === sel?.focusNode) caret = domText.length + sel.focusOffset;
1278
1388
  domText += (node as Text).data;
1279
1389
  } else if (hardBreaks.has(node)) domText += HARD_BREAK;
1390
+ // Shown but not document text (a list number, opaque content): never read back.
1391
+ else if ((node as Element).getAttribute?.("contenteditable") === "false") return;
1280
1392
  else node.childNodes.forEach(walk);
1281
1393
  };
1282
1394
  let first = true;
@@ -1307,7 +1419,14 @@ export class EditorView {
1307
1419
  this.blocks.forEach(({ node: block }, i) => {
1308
1420
  if (i > 0) modelText += BLOCK_SEPARATOR;
1309
1421
  lineStarts.push(modelText.length);
1310
- modelText += block.textBetween(0, block.content.size, "", HARD_BREAK);
1422
+ block.forEach((child) => {
1423
+ // A tab is text in the DOM (a "\t" text node).
1424
+ modelText += child.isText
1425
+ ? (child.text ?? "")
1426
+ : child.type.name === "tab"
1427
+ ? "\t"
1428
+ : HARD_BREAK;
1429
+ });
1311
1430
  });
1312
1431
  /** Model position of an offset in `modelText`. */
1313
1432
  const posAt = (offset: number): number => {
@@ -1383,11 +1502,13 @@ export class EditorView {
1383
1502
  const { selection, doc } = this.state;
1384
1503
  if (selection.empty || !event.clipboardData) return;
1385
1504
  event.preventDefault();
1505
+ const context = wordContext(this.state) as WordContext;
1386
1506
  const { text, html, json } = serializeRange(
1387
1507
  doc,
1388
1508
  selection.from,
1389
1509
  selection.to,
1390
1510
  this.host.ownerDocument,
1511
+ { context, ratio: this.lineRatio },
1391
1512
  );
1392
1513
  event.clipboardData.setData("text/plain", text);
1393
1514
  event.clipboardData.setData("text/html", html);
@@ -1442,14 +1563,22 @@ export class EditorView {
1442
1563
  };
1443
1564
  if (command(state, dispatch)) return applied;
1444
1565
  }
1445
- const marks = (state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1446
- const pasted = docFromClipboard(data, marks);
1447
- // One empty textblock: nothing to paste (a lone rule is something).
1566
+ const marks = typedMarks(state.storedMarks ?? marksAt(state.selection.$from)).map((m) =>
1567
+ m.toJSON(),
1568
+ );
1569
+ // The document takes the styles, lists and comments the content needs (HTML is read as
1570
+ // schema v2 content, then migrated).
1571
+ const pasted = docFromClipboard(data, marks, (found) =>
1572
+ found.html
1573
+ ? fitPastedV2(state, parseContentV2(found.content))
1574
+ : fitPaste(state, found.content, found.word),
1575
+ );
1576
+ // One empty paragraph: nothing to paste (a lone opaque block is something).
1448
1577
  const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
1449
1578
  if (!pasted || (only?.isTextblock && !only.content.size)) return false;
1450
- const { doc, open } = pasted;
1451
- // As a slice (text joins the text around the caret); where the schema refuses that (a
1452
- // list in a paragraph), as whole blocks fitted at the caret.
1579
+ const { doc, open, envelope } = pasted;
1580
+ // As a slice (text joins the text around the caret); where that cannot be (an opaque block
1581
+ // at an end), as whole blocks at the caret.
1453
1582
  const asSlice = (tr: Transaction) => {
1454
1583
  const $pos = tr.selection.$from;
1455
1584
  if (!open && $pos.depth === 1 && $pos.parent.isTextblock && !$pos.parent.content.size) {
@@ -1457,9 +1586,9 @@ export class EditorView {
1457
1586
  tr.replace(from, $pos.after(), new Slice(doc.content, 0, 0));
1458
1587
  tr.setSelection(Selection.near(tr.doc.resolve(from + doc.content.size), -1));
1459
1588
  } else {
1460
- // A slice opens into its first and last blocks: a rule there has no inside.
1589
+ // A slice opens into its first and last blocks: an opaque block there has no inside.
1461
1590
  if (doc.firstChild?.isLeaf || doc.lastChild?.isLeaf) {
1462
- throw new TransformError("A rule at an end is pasted as a block");
1591
+ throw new TransformError("An opaque block at an end is pasted as a block");
1463
1592
  }
1464
1593
  tr.replaceSelection(doc.slice(1, doc.content.size - 1));
1465
1594
  }
@@ -1474,6 +1603,7 @@ export class EditorView {
1474
1603
  try {
1475
1604
  tr.deleteSelection();
1476
1605
  strategy(tr);
1606
+ if (envelope && envelope !== wordContext(state)?.envelope) withEnvelope(tr, envelope);
1477
1607
  } catch (error) {
1478
1608
  if (error instanceof TransformError) continue;
1479
1609
  throw error;
@@ -1489,96 +1619,25 @@ export class EditorView {
1489
1619
  }
1490
1620
 
1491
1621
  /**
1492
- * Pastes whole blocks at the caret (after deleting the selection), for content a slice cannot
1493
- * fit (lists): a single pasted list inside a list item joins that list (its items replace an
1494
- * empty item, go before or after the item, or between its two halves); other blocks go before
1495
- * or after the caret's textblock (replacing it when empty) where its parent takes them, else
1496
- * between its two halves. Throws TransformError where the schema does not allow it.
1622
+ * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1623
+ * paragraph, else between its two halves (an empty one is replaced as a slice first).
1497
1624
  */
1498
1625
  function insertBlocks(tr: Transaction, doc: ModelNode): void {
1499
1626
  const $pos = tr.selection.$from;
1500
1627
  if (!$pos.parent.isTextblock) throw new TransformError("No textblock at the caret");
1501
1628
  const atStart = $pos.parentOffset === 0;
1502
1629
  const atEnd = $pos.parentOffset === $pos.parent.content.size;
1503
- const only = doc.childCount === 1 ? doc.firstChild : null;
1504
- const itemType = tr.doc.type.schema.nodes.listItem;
1505
- const inItem = $pos.depth >= 2 && $pos.node(-1).type === itemType;
1506
1630
  let at: number;
1507
- let content = doc.content;
1508
- if (only && inItem && only.firstChild?.type === itemType) {
1509
- content = only.content;
1510
- const depth = $pos.depth - 1;
1511
- const item = $pos.node(depth);
1512
- if (atStart && atEnd && item.childCount === 1) {
1513
- at = $pos.before(depth);
1514
- tr.delete(at, $pos.after(depth));
1515
- } else if (atEnd) {
1516
- // After the item (and its nested list, if it has one): no item left without its text.
1517
- at = $pos.after(depth);
1518
- } else if (atStart && $pos.index(depth) === 0) at = $pos.before(depth);
1519
- else if (atStart) {
1520
- // At a later block's start: split the item between blocks, not inside the text.
1521
- const boundary = $pos.before();
1522
- tr.split(boundary, 1);
1523
- at = boundary + 1;
1524
- } else {
1525
- tr.split($pos.pos, 2);
1526
- at = $pos.pos + 2;
1527
- }
1528
- } else {
1529
- // Before, after, or in place of the textblock where its parent takes the blocks there (a
1530
- // list item's first paragraph must stay first); else between its two halves.
1531
- const parent = $pos.node(-1);
1532
- const index = $pos.index(-1);
1533
- if (atStart && atEnd && parent.canReplace(index, index + 1, content)) {
1534
- at = $pos.before();
1535
- tr.delete(at, $pos.after());
1536
- } else if (atStart && parent.canReplace(index, index, content)) at = $pos.before();
1537
- else if (atEnd && parent.canReplace(index + 1, index + 1, content)) at = $pos.after();
1538
- else {
1539
- tr.split($pos.pos);
1540
- at = $pos.pos + 1;
1541
- }
1631
+ if (atStart) at = $pos.before();
1632
+ else if (atEnd) at = $pos.after();
1633
+ else {
1634
+ tr.split($pos.pos);
1635
+ at = $pos.pos + 1;
1542
1636
  }
1543
- tr.insert(at, content);
1544
- tr.setSelection(Selection.near(tr.doc.resolve(at + content.size), -1));
1545
- }
1546
-
1547
- /** The first block element inside a container element (through nested containers), or null. */
1548
- function firstBlockIn(element: Element): Element | null {
1549
- let child = element.firstElementChild;
1550
- while (isWrapper(child)) child = child.firstElementChild;
1551
- return child;
1552
- }
1553
-
1554
- /**
1555
- * Sets what a container element shows on a page: an ordered list item's number (so numbering
1556
- * continues across pages), and no marker on an item continued from the previous page (its
1557
- * first block is on an earlier page, or this is a continued fragment of it).
1558
- */
1559
- function styleContainer(
1560
- element: HTMLElement,
1561
- container: Container,
1562
- parent: Container | undefined,
1563
- item: { block: number; fragment: number },
1564
- ): void {
1565
- if (element.localName !== "li") return;
1566
- const continued = item.block !== container.firstBlock || item.fragment > 0;
1567
- const start = parent?.node.type.name === "orderedList" ? parent.node.attrs.start : undefined;
1568
- const value = typeof start === "number" ? String(start + container.index) : null;
1569
- // Written only when they change (checked against what was written last, without reading the
1570
- // DOM): this runs for every list item on every render, and every write invalidates style.
1571
- const state = `${continued}|${value}`;
1572
- if (containerStates.get(element) === state) return;
1573
- containerStates.set(element, state);
1574
- element.style.listStyleType = continued ? "none" : "";
1575
- if (value === null) element.removeAttribute("value");
1576
- else element.setAttribute("value", value);
1637
+ tr.insert(at, doc.content);
1638
+ tr.setSelection(Selection.near(tr.doc.resolve(at + doc.content.size), -1));
1577
1639
  }
1578
1640
 
1579
- /** What `styleContainer` last wrote on each list item element. */
1580
- const containerStates = new WeakMap<HTMLElement, string>();
1581
-
1582
1641
  /**
1583
1642
  * Client rects are scaled by CSS `zoom` or a `transform` on an ancestor, while margins and the
1584
1643
  * page geometry are in layout px: the ratio between the two for a page. From the page's width
@@ -1620,34 +1679,84 @@ function measureBox(desc: BlockDesc, scale: number): Measure {
1620
1679
  }
1621
1680
 
1622
1681
  /**
1623
- * What the flow needs of a block: its measurement, its lines (on demand), and what the rules
1624
- * need: headings keep with the next block; page breaks end their line's page.
1682
+ * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
1683
+ * and after (next to its neighbours), keep with next, keep lines together (not for a block
1684
+ * taller than a page, or one with a page break in it), page breaks ending their line's page,
1685
+ * and a page break before the next block ending this one's page.
1625
1686
  */
1626
- function blockBox(desc: BlockDesc, measure: Measure, lines: () => Lines): BlockBox {
1687
+ function wordBox(
1688
+ blocks: readonly WordBlockDesc[],
1689
+ i: number,
1690
+ measure: Measure,
1691
+ lines: () => Lines,
1692
+ layout: BlockLayout,
1693
+ ): BlockBox {
1694
+ const pageHeight = contentHeight(layout.sheet.settings);
1695
+ const desc = blocks[i] as WordBlockDesc;
1696
+ const next = blocks[i + 1];
1697
+ const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
1698
+ const pageBreaks = desc.leaves.filter(
1699
+ (leaf) =>
1700
+ leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(PAGE_BREAK_ATTR),
1701
+ );
1702
+ const hasBreak = pageBreaks.length > 0;
1703
+ const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
1704
+ const bottoms = () => (kept ? [measure.height] : lines().bottoms);
1627
1705
  return {
1628
1706
  height: measure.height,
1629
- marginTop: measure.marginTop,
1630
- marginBottom: measure.marginBottom,
1631
- lines: () => lines().bottoms,
1632
- keepWithNext: desc.node.type.name === "heading",
1707
+ marginTop: before,
1708
+ marginBottom: after,
1709
+ keepWithNext: desc.word.keepNext,
1710
+ pageHeight,
1711
+ lines: bottoms,
1633
1712
  breaksAfter: () => {
1634
- const breaks = desc.leaves.filter(
1635
- (leaf) =>
1636
- leaf.dom.nodeType !== Node.TEXT_NODE &&
1637
- (leaf.dom as Element).hasAttribute(PAGE_BREAK_ATTR),
1638
- );
1639
- if (!breaks.length) return [];
1640
- const { starts } = lines();
1641
- // The line holding the break: the last one starting at or before it.
1642
- return breaks.map((leaf) => {
1713
+ // The line holding each break: the last one starting at or before it.
1714
+ const breaks = pageBreaks.map((leaf) => {
1715
+ const { starts } = lines();
1643
1716
  let line = starts.length - 1;
1644
1717
  while (line > 0 && (starts[line] as number) > leaf.offset) line--;
1645
1718
  return line;
1646
1719
  });
1720
+ if (next?.word.pageBreakBefore || layout.breakAfter) breaks.push(bottoms().length - 1);
1721
+ return breaks;
1647
1722
  },
1648
1723
  };
1649
1724
  }
1650
1725
 
1726
+ /**
1727
+ * Writes Word's space above each v3 block as its top margin: the space after the block above
1728
+ * and the space before this one, on the same page; at the top of a page only its space before,
1729
+ * and only on the first page or after an explicit break (a page the text flowed onto drops it).
1730
+ * Written only when it changes.
1731
+ */
1732
+ function applyGaps(
1733
+ blocks: readonly BlockDesc[],
1734
+ pages: readonly (readonly number[])[],
1735
+ boxes: readonly BlockBox[],
1736
+ ): void {
1737
+ blocks.forEach((desc, i) => {
1738
+ const page = pages[i]?.[0] ?? 0;
1739
+ const above = pages[i - 1];
1740
+ const box = boxes[i] as BlockBox;
1741
+ let gap: number;
1742
+ if (above && above[above.length - 1] === page)
1743
+ gap = (boxes[i - 1] as BlockBox).marginBottom + box.marginTop;
1744
+ else {
1745
+ const prior = boxes[i - 1];
1746
+ const breaks = prior?.breaksAfter?.() ?? [];
1747
+ const forced =
1748
+ page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1749
+ gap = forced ? box.marginTop : 0;
1750
+ }
1751
+ if (gaps.get(desc.dom) === gap) return;
1752
+ gaps.set(desc.dom, gap);
1753
+ desc.dom.style.marginTop = `${gap}px`;
1754
+ });
1755
+ }
1756
+
1757
+ /** The gap `applyGaps` last wrote on each block element (the style serializes it rounded). */
1758
+ const gaps = new WeakMap<HTMLElement, number>();
1759
+
1651
1760
  /**
1652
1761
  * What the next flow can reuse of the last one: the unchanged blocks before the first changed
1653
1762
  * (or stale) one, and the unchanged tail after the last.
@@ -1656,6 +1765,7 @@ function reuseOf(
1656
1765
  last: { nodes: readonly ModelNode[]; result: FlowResult },
1657
1766
  nodes: readonly ModelNode[],
1658
1767
  stale: ReadonlySet<ModelNode>,
1768
+ margin = 0,
1659
1769
  ): Reuse {
1660
1770
  const before = last.nodes;
1661
1771
  const same = (a: ModelNode | undefined, b: ModelNode | undefined) =>
@@ -1669,6 +1779,9 @@ function reuseOf(
1669
1779
  same(nodes[nodes.length - 1 - tail], before[before.length - 1 - tail])
1670
1780
  )
1671
1781
  tail++;
1782
+ // Blocks whose box depends on a changed neighbour are not reused either.
1783
+ from = Math.max(0, from - margin);
1784
+ tail = Math.max(0, tail - margin);
1672
1785
  const delta = nodes.length - before.length;
1673
1786
  return {
1674
1787
  previous: last.result,