@folijs/view 0.1.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/dist/view.js CHANGED
@@ -1,7 +1,13 @@
1
- import { AllSelection, closeHistory, deleteBackward, deleteForward, deleteSelection, insertHardBreak, insertText, marksAt, redo, Selection, Slice, 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, setLink, splitBlock, TextSelection, TransformError, toggleMark, 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 { 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" };
9
+ /** Class of the element of a node-selected block (a rule). */
10
+ const SELECTED_CLASS = "foli-selected-node";
5
11
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
6
12
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
7
13
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
@@ -28,18 +34,97 @@ const VIEW_ATTR = "data-foli-view";
28
34
  let viewCount = 0;
29
35
  /**
30
36
  * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
31
- * the document's size per page, without margins (the page's padding holds them). A page is
32
- * 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
33
39
  * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
34
40
  * page) is not cut: it prints over the next sheet.
35
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.
36
42
  */
37
- function printStyles({ pageSize }, id) {
38
- const { width, height } = pageSize;
43
+ function printStyles(settings, sheets, id) {
44
+ const { width, height } = settings.pageSize;
45
+ const last = sheetOf(settings, 0).css;
39
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("");
40
58
  return (`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
41
59
  `${pages}{height:${height}mm!important;margin-block:0!important;` +
42
- `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
+ /** The attribute naming a page's page setup (its index among the document's) for print. */
63
+ const SHEET_ATTR = "data-foli-sheet";
64
+ function sheetOf(settings, index) {
65
+ const { pageSize, margins } = settings;
66
+ const css = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
67
+ `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
68
+ return { settings, css, index };
69
+ }
70
+ /** The style each page element was last given (its `cssText` reads back normalized). */
71
+ const pageSheets = new WeakMap();
72
+ /**
73
+ * The section of each top-level block (the section a paragraph's `section` ends; the
74
+ * envelope's for the blocks after the last such paragraph). A section starts a new page,
75
+ * unless it is continuous with the same page setup as the one before (shortcut: a continuous
76
+ * section with another page setup starts a new page; Word's even and odd page sections do not
77
+ * add a blank page), as `renderDocument` lays sections out.
78
+ */
79
+ function sectionLayouts(doc, last) {
80
+ const sheets = new Map();
81
+ const bySection = new Map();
82
+ const sheet = (section) => {
83
+ let found = bySection.get(section);
84
+ if (!found) {
85
+ const settings = sectionSettings(section);
86
+ const css = sheetOf(settings, 0).css;
87
+ found = sheets.get(css) ?? sheetOf(settings, sheets.size);
88
+ sheets.set(css, found);
89
+ bySection.set(section, found);
90
+ }
91
+ return found;
92
+ };
93
+ const sections = [];
94
+ let section = last;
95
+ for (let i = doc.childCount - 1; i >= 0; i--) {
96
+ const own = doc.child(i).attrs.section;
97
+ if (own)
98
+ section = own;
99
+ sections[i] = section;
100
+ }
101
+ // Indexes in document order: the first page setup is 0.
102
+ sections.forEach(sheet);
103
+ return sections.map((own, i) => {
104
+ const next = sections[i + 1];
105
+ // By position, as `renderDocument`: two paragraphs may end sections with one object.
106
+ const ends = !!next && !!doc.child(i).attrs.section;
107
+ const breakAfter = ends && !(next.type === "continuous" && sheet(next).css === sheet(own).css);
108
+ return { sheet: sheet(own), breakAfter };
109
+ });
110
+ }
111
+ /**
112
+ * Initial pages (before a flow), moved where needed so that each page holds blocks of one
113
+ * page setup: a block is measured in a page of its own section's width.
114
+ */
115
+ function separateSheets(pages, layout) {
116
+ const css = [];
117
+ let floor = 0;
118
+ return pages.map((list, i) => list.map((p) => {
119
+ const want = layout[i].sheet.css;
120
+ let page = Math.max(p, floor);
121
+ // Only the last page used so far has a setup: the next one is free.
122
+ if (css[page] !== undefined && css[page] !== want)
123
+ page++;
124
+ css[page] ??= want;
125
+ floor = page;
126
+ return page;
127
+ }));
43
128
  }
44
129
  /**
45
130
  * The editable view of an `Editor` from `@folijs/core`: renders its state into one
@@ -50,7 +135,8 @@ function printStyles({ pageSize }, id) {
50
135
  * view cannot prevent (Android keyboards, extensions). A MutationObserver records those; the view
51
136
  * then reads the changed text back into a transaction (`readBack`) and re-renders.
52
137
  *
53
- * shortcut: assumes schema v1 (doc > textblocks > inline); nested blocks arrive with lists in Phase 7.
138
+ * Blocks are the document's paragraphs and opaque blocks (a schema v3 document has no
139
+ * containers: a list is numbered paragraphs).
54
140
  */
55
141
  export class EditorView {
56
142
  host;
@@ -59,13 +145,26 @@ export class EditorView {
59
145
  blocks = [];
60
146
  /** Position before each block, parallel to `blocks`. */
61
147
  starts = [];
148
+ /** The index of each block in `blocks`. */
149
+ indexOf = new Map();
150
+ /** The element that shows a node selection, if any. */
151
+ selectedDom = null;
62
152
  /** The page of each fragment of each block. */
63
153
  fragmentPages = new Map();
64
154
  /** The block each fragment element belongs to. */
65
155
  owner = new Map();
66
156
  /** The page elements, in order; the host's only children. */
67
157
  pages = [];
68
- pageStyle = "";
158
+ /** The page setup of each page (its section's), parallel to `pages`. */
159
+ sheets = [];
160
+ /** The page setups the print rules were written for. */
161
+ printKey = "";
162
+ /**
163
+ * Each block's page setup and whether a section break follows it, as last rendered: a block
164
+ * whose layout changed (a section break inserted or removed around it) is measured and
165
+ * flowed again.
166
+ */
167
+ layoutKeys = new WeakMap();
69
168
  /** Marks the host for this view's print rules (`printStyles`). */
70
169
  id = String(++viewCount);
71
170
  /**
@@ -80,7 +179,7 @@ export class EditorView {
80
179
  * Measurements by model node: a node's rendered height, margins and lines only depend on
81
180
  * its content (unchanged node, same identity), the page width and the CSS. Cleared when the
82
181
  * page settings or the fonts change; single entries go stale when a block's size changes
83
- * without an edit (`ResizeObserver`: CSS, fonts, a container).
182
+ * without an edit (`ResizeObserver`: CSS, fonts).
84
183
  */
85
184
  measures = new WeakMap();
86
185
  stale = new Set();
@@ -105,6 +204,8 @@ export class EditorView {
105
204
  observer;
106
205
  unsubscribe;
107
206
  editable = true;
207
+ /** Escape was the last key: Tab now leaves the editor. */
208
+ tabLeaves = false;
108
209
  placeholder = "";
109
210
  /** The block that shows the placeholder, if any. */
110
211
  placeholderDom = null;
@@ -112,6 +213,12 @@ export class EditorView {
112
213
  pointerFocus = false;
113
214
  /** Whether the view added the host's tabindex (a read-only host must stay focusable). */
114
215
  addedTabIndex;
216
+ /** Renders the document's blocks; made by the first render. */
217
+ word = null;
218
+ /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
219
+ ratios = new Map();
220
+ /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
221
+ fontsChanged = false;
115
222
  constructor(host, editor, options = {}) {
116
223
  this.host = host;
117
224
  this.editor = editor;
@@ -143,6 +250,8 @@ export class EditorView {
143
250
  host.addEventListener("copy", this.onCopy);
144
251
  host.addEventListener("cut", this.onCut);
145
252
  host.addEventListener("paste", this.onPaste);
253
+ host.addEventListener("click", this.onClick);
254
+ host.addEventListener("auxclick", this.onClick);
146
255
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
147
256
  host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
148
257
  this.unsubscribe = editor.subscribe((state) => this.update(state));
@@ -167,6 +276,8 @@ export class EditorView {
167
276
  host.removeEventListener("copy", this.onCopy);
168
277
  host.removeEventListener("cut", this.onCut);
169
278
  host.removeEventListener("paste", this.onPaste);
279
+ host.removeEventListener("click", this.onClick);
280
+ host.removeEventListener("auxclick", this.onClick);
170
281
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
171
282
  const owned = [
172
283
  "contenteditable",
@@ -240,6 +351,7 @@ export class EditorView {
240
351
  this.state = state;
241
352
  if (docChanged)
242
353
  this.render();
354
+ this.showSelectedNode();
243
355
  this.writeSelection(docChanged);
244
356
  // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
245
357
  if (docChanged || selectionChanged)
@@ -283,6 +395,29 @@ export class EditorView {
283
395
  render() {
284
396
  const { doc } = this.state;
285
397
  const ownerDocument = this.host.ownerDocument;
398
+ // A new document (envelope) gets its renderer; nothing rendered before is reused then. An
399
+ // editor's state always has one (`createEditor`).
400
+ const context = wordContext(this.state);
401
+ // Fonts loaded: a new renderer (new line heights), but not while a composition runs in a
402
+ // block it would redraw.
403
+ const renewed = context !== (this.word?.context ?? null) || (this.fontsChanged && !this.composing);
404
+ if (renewed)
405
+ this.fontsChanged = false;
406
+ let word = this.word;
407
+ if (renewed) {
408
+ word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio);
409
+ this.invalidateLayout();
410
+ }
411
+ word.prepare(doc);
412
+ const layout = sectionLayouts(doc, context.envelope.section);
413
+ doc.forEach((node, _, i) => {
414
+ const { sheet, breakAfter } = layout[i];
415
+ const key = `${sheet.css}${breakAfter ? "|break" : ""}`;
416
+ const before = this.layoutKeys.get(node);
417
+ if (before !== undefined && before !== key)
418
+ this.stale.add(node);
419
+ this.layoutKeys.set(node, key);
420
+ });
286
421
  const previous = new Map(this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]));
287
422
  const previousPages = this.fragmentPages;
288
423
  this.dirty.clear();
@@ -293,8 +428,13 @@ export class EditorView {
293
428
  }
294
429
  let blocks = [];
295
430
  const starts = [];
296
- doc.forEach((node, offset) => {
297
- let reused = previous.get(node);
431
+ doc.forEach((node, pos) => {
432
+ let reused = renewed ? undefined : previous.get(node);
433
+ // A block whose list number or comment shading changed (an edit before it) is redrawn.
434
+ if (reused && reused.key !== word.key(blocks.length)) {
435
+ reused = undefined;
436
+ this.stale.add(node);
437
+ }
298
438
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
299
439
  // fragment's end breaks its line, so its lines would depend on where it was split before.
300
440
  const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
@@ -302,24 +442,25 @@ export class EditorView {
302
442
  reused = undefined;
303
443
  if (reused)
304
444
  previous.delete(node);
305
- blocks.push(reused ?? renderBlock(node, ownerDocument));
306
- starts.push(offset);
445
+ blocks.push(reused ?? word.render(node, blocks.length));
446
+ starts.push(pos);
307
447
  });
308
448
  for (const stale of previous.values())
309
449
  for (const fragment of stale.fragments)
310
450
  fragment.remove();
311
- this.applyGeometry();
451
+ this.applyPrintStyles(layout);
312
452
  let last = 0;
313
453
  let pages = blocks.map((desc) => {
314
454
  const before = previousPages.get(desc);
315
455
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
316
456
  });
317
- this.place(blocks, pages);
457
+ pages = separateSheets(pages, layout);
458
+ this.place(blocks, pages, layout);
318
459
  if (!this.composing) {
319
460
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
320
461
  let scale;
321
462
  const layoutPx = () => {
322
- scale ??= layoutScale(this.pages[0], this.editor.settings);
463
+ scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
323
464
  return scale;
324
465
  };
325
466
  if (dropLines)
@@ -329,7 +470,8 @@ export class EditorView {
329
470
  delete measure.lines;
330
471
  }
331
472
  const nodes = blocks.map((desc) => desc.node);
332
- const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale) : undefined;
473
+ // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
474
+ const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
333
475
  const measureOf = (desc) => {
334
476
  let found = this.measures.get(desc.node);
335
477
  // A stale block is measured again once per render.
@@ -344,8 +486,8 @@ export class EditorView {
344
486
  found.lines ??= measureLines(desc, layoutPx());
345
487
  return found.lines;
346
488
  };
347
- const boxes = blocks.map((desc) => blockBox(desc, measureOf(desc), () => lines(desc)));
348
- const result = flowFrom(boxes, contentHeight(this.editor.settings), DEFAULT_RULES, reuse);
489
+ const boxes = blocks.map((desc, i) => wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i]));
490
+ const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
349
491
  this.flowed = { nodes, result };
350
492
  this.stale.clear();
351
493
  const flowed = result.fragments;
@@ -358,35 +500,68 @@ export class EditorView {
358
500
  return clusterBoundary(doc, contentStart + offset, false) - contentStart;
359
501
  });
360
502
  const same = splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
361
- return same ? desc : renderBlock(desc.node, ownerDocument, splits);
503
+ return same ? desc : word.render(desc.node, i, splits);
362
504
  });
363
505
  pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
364
- this.place(blocks, pages);
506
+ applyGaps(blocks, pages, boxes);
507
+ this.place(blocks, pages, layout);
365
508
  }
366
509
  this.blocks = blocks;
367
510
  this.starts = starts;
511
+ this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
368
512
  this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
369
513
  this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
370
514
  this.unflowed = this.composing;
371
515
  this.observeSizes();
372
516
  this.showPlaceholder();
517
+ this.showSelectedNode();
373
518
  // The view's own DOM changes are not input. During a composition, keep what the browser
374
519
  // changed before this render: the touched blocks are read back at compositionend.
375
520
  const records = this.observer.takeRecords();
376
521
  if (this.composing)
377
522
  this.pending.push(...records);
378
523
  }
524
+ /** A font's normal line height ratio, measured outside the host (no input to read back). */
525
+ lineRatio = (family) => {
526
+ let ratio = this.ratios.get(family);
527
+ if (ratio === undefined) {
528
+ const doc = this.host.ownerDocument;
529
+ ratio = measureLineRatio(doc.body ?? doc.documentElement)(family);
530
+ this.ratios.set(family, ratio);
531
+ }
532
+ return ratio;
533
+ };
379
534
  /**
380
535
  * Puts each fragment of each block into its page (pages are non-decreasing in document
381
- * order), creating and removing pages as needed. Anything else in the host or a page (stray
382
- * DOM) is removed.
536
+ * order), creating and removing pages as needed, and gives each page the page setup of its
537
+ * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
538
+ * or a page (stray DOM) is removed.
383
539
  */
384
- place(blocks, pages) {
540
+ place(blocks, pages, layout) {
385
541
  const { host } = this;
386
542
  const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
387
543
  const count = (items[items.length - 1]?.page ?? 0) + 1;
544
+ const sheets = [];
545
+ pages.forEach((list, i) => {
546
+ for (const p of list)
547
+ sheets[p] ??= layout[i].sheet;
548
+ });
549
+ // A page no block starts on (none yet) takes the setup of the page before it.
550
+ for (let p = 0; p < count; p++)
551
+ sheets[p] ??=
552
+ sheets[p - 1] ?? layout[0]?.sheet ?? this.lastSheet();
553
+ this.sheets = sheets.slice(0, count);
388
554
  while (this.pages.length < count)
389
555
  this.pages.push(this.createPage());
556
+ this.sheets.forEach((sheet, p) => {
557
+ const page = this.pages[p];
558
+ const key = `${sheet.index} ${sheet.css}`;
559
+ if (pageSheets.get(page) === key)
560
+ return;
561
+ pageSheets.set(page, key);
562
+ page.style.cssText = sheet.css;
563
+ page.setAttribute(SHEET_ATTR, String(sheet.index));
564
+ });
390
565
  // Pages first, in order; anything else in the host ends up after them.
391
566
  let cursor = host.firstChild;
392
567
  for (const page of this.pages.slice(0, count)) {
@@ -395,28 +570,25 @@ export class EditorView {
395
570
  else
396
571
  host.insertBefore(page, cursor);
397
572
  }
398
- const blockDoms = new Set(items.map((item) => item.dom));
399
573
  let i = 0;
400
574
  for (let p = 0; p < count; p++) {
401
575
  const page = this.pages[p];
402
576
  let at = page.firstChild;
403
577
  for (; i < items.length && items[i]?.page === p; i++) {
404
- const dom = items[i].dom;
578
+ const { dom } = items[i];
405
579
  if (dom === at)
406
580
  at = at.nextSibling;
407
581
  else
408
582
  page.insertBefore(dom, at);
409
583
  }
410
- // What is left: strays go; fragments of a later page are moved there next.
584
+ // What is left after the last placed block: strays, and blocks of later pages.
411
585
  while (at) {
412
586
  const next = at.nextSibling;
413
- if (!blockDoms.has(at))
414
- at.remove();
587
+ at.remove();
415
588
  at = next;
416
589
  }
417
590
  }
418
- // Pages no longer needed and stray DOM in the host: all after the last page by now. Taken
419
- // after the block loop, since a block found loose in the host has just moved into a page.
591
+ // Pages no longer needed and stray DOM in the host: all after the last page by now.
420
592
  let rest = this.pages[count - 1].nextSibling;
421
593
  while (rest) {
422
594
  const next = rest.nextSibling;
@@ -428,19 +600,19 @@ export class EditorView {
428
600
  createPage() {
429
601
  const page = this.host.ownerDocument.createElement("section");
430
602
  page.className = "foli-page";
431
- page.style.cssText = this.pageStyle;
432
603
  return page;
433
604
  }
434
- /** Page size and margins from the document settings, applied to every page when they change. */
435
- applyGeometry() {
436
- const { pageSize, margins } = this.editor.settings;
437
- const style = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
438
- `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
439
- if (style === this.pageStyle)
605
+ /** The last section's page setup (the envelope's), for an empty document. */
606
+ lastSheet() {
607
+ return sheetOf(this.editor.settings, 0);
608
+ }
609
+ /** The print rules for the document's page setups, written when they change. */
610
+ applyPrintStyles(layout) {
611
+ const sheets = [...new Set(layout.map((block) => block.sheet))];
612
+ const key = [this.lastSheet(), ...sheets].map((sheet) => sheet.css).join("\n");
613
+ if (key === this.printKey)
440
614
  return;
441
- this.pageStyle = style;
442
- for (const page of this.pages)
443
- page.style.cssText = style;
615
+ this.printKey = key;
444
616
  // shortcut: written when the page settings change; a host moved to another document or shadow root keeps them where they were until then.
445
617
  for (const style of this.printStyles)
446
618
  style.remove();
@@ -452,11 +624,10 @@ export class EditorView {
452
624
  this.printStyles = parents.map((parent) => {
453
625
  const style = doc.createElement("style");
454
626
  style.setAttribute("data-foli-print", "");
455
- style.textContent = printStyles(this.editor.settings, this.id);
627
+ style.textContent = printStyles(this.editor.settings, sheets, this.id);
456
628
  parent.append(style);
457
629
  return style;
458
630
  });
459
- this.invalidateLayout();
460
631
  }
461
632
  /** Forgets every measurement: the next flow measures the whole document again. */
462
633
  invalidateLayout() {
@@ -465,6 +636,9 @@ export class EditorView {
465
636
  }
466
637
  /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
467
638
  onFontsLoaded = () => {
639
+ // v3 line heights come from the fonts' measured ratios: render every block again.
640
+ this.ratios.clear();
641
+ this.fontsChanged = true;
468
642
  this.invalidateLayout();
469
643
  this.scheduleRelayout();
470
644
  };
@@ -499,7 +673,7 @@ export class EditorView {
499
673
  // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
500
674
  if (!entry.contentRect.width)
501
675
  continue;
502
- scale ??= layoutScale(this.pages[0], this.editor.settings);
676
+ scale ??= layoutScale(this.pages[0], this.sheets[0].settings);
503
677
  let height = 0;
504
678
  for (const fragment of desc.fragments)
505
679
  height += fragment.getBoundingClientRect().height;
@@ -538,20 +712,35 @@ export class EditorView {
538
712
  nextFrame(run);
539
713
  }
540
714
  // ---------- position mapping ----------
541
- /** The block element that contains `node` (the child of a page it sits in), or null. */
715
+ /** The block element (a fragment of a rendered block) that contains `node`, or null. */
542
716
  blockElement(node) {
543
- let element = node;
544
- while (element?.parentNode && !this.pages.includes(element.parentNode)) {
545
- if (element.parentNode === this.host)
546
- return null;
547
- element = element.parentNode;
717
+ for (let element = node; element && element !== this.host; element = element.parentNode) {
718
+ if (this.owner.has(element))
719
+ return element;
548
720
  }
549
- return element?.parentNode ? element : null;
721
+ return null;
722
+ }
723
+ /** Whether `node` holds blocks rather than content: the host or a page. */
724
+ holdsBlocks(node) {
725
+ return node === this.host || this.pages.includes(node);
726
+ }
727
+ /** Index of the first block that starts at or after `pos` (the block count if none). */
728
+ blockFrom(pos) {
729
+ let lo = 0;
730
+ let hi = this.starts.length;
731
+ while (lo < hi) {
732
+ const mid = (lo + hi) >> 1;
733
+ if (this.starts[mid] < pos)
734
+ lo = mid + 1;
735
+ else
736
+ hi = mid;
737
+ }
738
+ return lo;
550
739
  }
551
740
  /** Model position of a DOM point inside the host, or null if it is outside. */
552
741
  posFromDOM(node, offset) {
553
742
  const { host } = this;
554
- if (node === host || this.pages.includes(node)) {
743
+ if (this.holdsBlocks(node)) {
555
744
  // Between fragments: the start of the first one after the point (a block start, or
556
745
  // where a continuation starts), else the document end.
557
746
  const range = host.ownerDocument.createRange();
@@ -567,10 +756,15 @@ export class EditorView {
567
756
  }
568
757
  const element = this.blockElement(node);
569
758
  const owner = element ? this.owner.get(element) : undefined;
570
- const index = owner ? this.blocks.indexOf(owner) : -1;
759
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
571
760
  const desc = this.blocks[index];
572
761
  if (!desc)
573
762
  return null;
763
+ // A point in or at a block leaf (a rule): before it, or after it at its end.
764
+ if (!desc.node.isTextblock) {
765
+ const after = node === desc.dom && offset > 0;
766
+ return this.starts[index] + (after ? desc.node.nodeSize : 0);
767
+ }
574
768
  const contentStart = this.starts[index] + 1;
575
769
  const leaf = desc.leaves.find((l) => l.dom === node);
576
770
  if (leaf && node.nodeType === Node.TEXT_NODE)
@@ -587,11 +781,20 @@ export class EditorView {
587
781
  /** DOM point for a model position. At a mark boundary the caret stays in the text before it. */
588
782
  domFromPos(pos) {
589
783
  const { doc } = this.state;
590
- let $pos = doc.resolve(pos);
591
- // Between blocks: use the nearest block edge (schema v1 has only textblocks at depth 1).
592
- if ($pos.depth === 0)
593
- $pos = doc.resolve($pos.nodeAfter ? pos + 1 : pos - 1);
594
- const desc = this.blocks[$pos.index(0)];
784
+ const $pos = doc.resolve(pos);
785
+ if (!$pos.parent.isTextblock) {
786
+ // Between blocks: the start of the next block (before a rule), else the document end.
787
+ const next = this.blocks[this.blockFrom(pos)];
788
+ if (next)
789
+ return next.node.isTextblock ? fragmentStart(next, 0) : before(next.dom);
790
+ const last = this.blocks[this.blocks.length - 1];
791
+ if (!last.node.isTextblock) {
792
+ const point = before(last.dom);
793
+ return { node: point.node, offset: point.offset + 1 };
794
+ }
795
+ return fragmentEnd(last, last.fragments.length - 1);
796
+ }
797
+ const desc = this.blocks[this.blockFrom($pos.before())];
595
798
  const offset = $pos.parentOffset;
596
799
  // Where a fragment starts, show the caret at the start of the next page's fragment, as a
597
800
  // browser shows it at the start of the next line at a soft wrap.
@@ -612,7 +815,10 @@ export class EditorView {
612
815
  const point = before(last.dom);
613
816
  return { node: point.node, offset: point.offset + 1 };
614
817
  }
615
- return { node: desc.dom, offset: 0 };
818
+ // An empty block: before its <br> (after a list number shown in front of it).
819
+ const tail = desc.dom.lastChild;
820
+ const end = tail?.nodeName === "BR" ? desc.dom.childNodes.length - 1 : 0;
821
+ return { node: desc.dom, offset: end };
616
822
  }
617
823
  // ---------- selection ----------
618
824
  /** The live DOM selection as a model selection, or null if it is not inside the host. */
@@ -620,13 +826,48 @@ export class EditorView {
620
826
  const sel = this.host.ownerDocument.getSelection();
621
827
  if (!sel?.anchorNode || !sel.focusNode)
622
828
  return null;
829
+ // A range around exactly one block leaf element (a rule): the node selection that wrote it.
830
+ // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
831
+ if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
832
+ const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
833
+ const owner = child && this.owner.get(child);
834
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
835
+ if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
836
+ return NodeSelection.create(this.state.doc, this.starts[index]);
837
+ }
623
838
  const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
624
839
  const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
625
840
  if (anchor === null || head === null)
626
841
  return null;
627
842
  const { doc } = this.state;
843
+ // Exactly around a selectable block leaf (a rule): the node selection that wrote it.
844
+ const from = Math.min(anchor, head);
845
+ const node = doc.nodeAt(from);
846
+ if (node &&
847
+ node.isBlock &&
848
+ node.isAtom &&
849
+ Math.max(anchor, head) === from + node.nodeSize &&
850
+ NodeSelection.isSelectable(node))
851
+ return NodeSelection.create(doc, from);
628
852
  return TextSelection.between(doc.resolve(anchor), doc.resolve(head));
629
853
  }
854
+ /** The rendered block a node selection selects, if it selects one. */
855
+ selectedBlock() {
856
+ const { selection } = this.state;
857
+ if (!(selection instanceof NodeSelection))
858
+ return null;
859
+ const desc = this.blocks[this.blockFrom(selection.from)];
860
+ return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
861
+ }
862
+ /** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
863
+ showSelectedNode() {
864
+ const dom = this.selectedBlock()?.dom ?? null;
865
+ if (dom === this.selectedDom)
866
+ return;
867
+ this.selectedDom?.classList.remove(SELECTED_CLASS);
868
+ dom?.classList.add(SELECTED_CLASS);
869
+ this.selectedDom = dom;
870
+ }
630
871
  /**
631
872
  * Brings the model selection up to date with the DOM. `selectionchange` is asynchronous, so
632
873
  * every input handler calls this first instead of trusting the last event.
@@ -666,6 +907,12 @@ export class EditorView {
666
907
  if (current && this.shows(current))
667
908
  return;
668
909
  }
910
+ const selected = this.selectedBlock();
911
+ if (selected) {
912
+ const point = before(selected.dom);
913
+ sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
914
+ return;
915
+ }
669
916
  // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
670
917
  // The model takes the snapped selection back on its next read of the DOM.
671
918
  const from = clusterBoundary(doc, selection.from, false);
@@ -723,7 +970,9 @@ export class EditorView {
723
970
  this.run(insertText(text));
724
971
  return;
725
972
  case "insertParagraph":
726
- this.run(splitBlock);
973
+ // The same as Enter (a list item splits or ends), for keyboards that send no keydown.
974
+ if (!this.runKey("Enter"))
975
+ this.run(splitBlock);
727
976
  return;
728
977
  case "insertLineBreak":
729
978
  this.run(insertHardBreak);
@@ -766,8 +1015,19 @@ export class EditorView {
766
1015
  return;
767
1016
  }
768
1017
  const unit = type.startsWith("deleteWord") ? "word" : "char";
1018
+ // A one-character delete goes through the key bindings first (Backspace at a list item's
1019
+ // start lifts it), as the key itself would.
1020
+ if (unit === "char" && this.runKey(type.endsWith("Forward") ? "Delete" : "Backspace"))
1021
+ return;
769
1022
  this.run(type.endsWith("Forward") ? deleteForward(unit) : deleteBackward(unit));
770
1023
  };
1024
+ /** Runs the first command bound to `name` that applies, through the view's dispatch. */
1025
+ runKey(name) {
1026
+ return this.state.plugins.some((plugin) => {
1027
+ const command = plugin.spec.keymap?.[name];
1028
+ return command ? this.run(command) : false;
1029
+ });
1030
+ }
771
1031
  /**
772
1032
  * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
773
1033
  * selection to the start of the next block, so typing over it would merge the two blocks.
@@ -778,42 +1038,121 @@ export class EditorView {
778
1038
  // focuses nothing (prevented, middle button) must not skip the next keyboard focus.
779
1039
  if (this.pointerFocus)
780
1040
  setTimeout(() => (this.pointerFocus = false));
781
- if (event.detail !== 3 || event.button !== 0)
1041
+ if (event.button !== 0)
782
1042
  return;
783
1043
  const element = this.blockElement(event.target);
784
1044
  const owner = element ? this.owner.get(element) : undefined;
785
- const index = owner ? this.blocks.indexOf(owner) : -1;
1045
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
786
1046
  const desc = this.blocks[index];
787
1047
  if (!desc)
788
1048
  return;
789
- event.preventDefault();
790
- const from = this.starts[index] + 1;
791
1049
  const { doc } = this.state;
1050
+ const start = this.starts[index];
1051
+ let selection;
1052
+ if (!desc.node.isTextblock) {
1053
+ // A click on a rule selects it (the browser would put the caret beside it); Shift+click
1054
+ // extends the selection natively.
1055
+ if (event.shiftKey || !NodeSelection.isSelectable(desc.node))
1056
+ return;
1057
+ selection = NodeSelection.create(doc, start);
1058
+ }
1059
+ else if (event.detail === 3) {
1060
+ selection = TextSelection.create(doc, start + 1, start + 1 + desc.node.content.size);
1061
+ }
1062
+ else
1063
+ return;
1064
+ event.preventDefault();
792
1065
  this.host.focus();
793
- this.dispatch(this.state.tr
794
- .setSelection(TextSelection.create(doc, from, from + desc.node.content.size))
795
- .setStoredMarks(null));
1066
+ this.dispatch(this.state.tr.setSelection(selection).setStoredMarks(null));
796
1067
  this.writeSelection(true);
797
1068
  };
1069
+ /**
1070
+ * A click on a link in the document does not navigate (it places the caret, also in read-only
1071
+ * mode); Ctrl+click (Cmd+click on Apple platforms) opens it in a new tab, without `opener`.
1072
+ */
1073
+ onClick = (event) => {
1074
+ const target = event.target;
1075
+ const element = target instanceof Element ? target.closest("a") : null;
1076
+ if (!element || !this.host.contains(element))
1077
+ return;
1078
+ event.preventDefault();
1079
+ if (event.type !== "click" || !(IS_MAC ? event.metaKey : event.ctrlKey))
1080
+ return;
1081
+ const href = this.linkHref(element);
1082
+ if (href)
1083
+ this.host.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
1084
+ };
1085
+ /** The href of the link an `<a>` shows, read from the model (the DOM is never the truth). */
1086
+ linkHref(element) {
1087
+ const pos = this.posFromDOM(element, 0);
1088
+ const type = this.state.schema.marks.link;
1089
+ if (pos === null || !type)
1090
+ return null;
1091
+ const $pos = this.state.doc.resolve(pos);
1092
+ const node = $pos.parent.maybeChild($pos.index());
1093
+ const href = node && type.isInSet(node.marks)?.attrs.href;
1094
+ return isSafeHref(href) ? href : null;
1095
+ }
798
1096
  onKeyDown = (event) => {
799
1097
  if (event.isComposing || this.composing)
800
1098
  return;
801
1099
  this.syncSelection();
802
- if (this.crossFragmentEdge(event)) {
1100
+ if (this.crossFragmentEdge(event) || this.crossListNumber(event)) {
803
1101
  event.preventDefault();
804
1102
  return;
805
1103
  }
806
1104
  const name = keyName(event);
807
1105
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
808
1106
  this.plainPaste = name === "Mod-Shift-v";
1107
+ // Tab and Shift+Tab move the focus on in read-only mode, and right after Escape where Tab
1108
+ // would type a tab (no keyboard trap).
1109
+ const tab = name === "Tab" || name === "Shift-Tab";
1110
+ const leave = tab && (this.tabLeaves || !this.editable);
1111
+ if (event.key !== "Shift")
1112
+ this.tabLeaves = name === "Escape";
1113
+ if (leave)
1114
+ return;
809
1115
  // Like `editor.handleKey`, but through the view's dispatch, so read-only mode drops edits.
810
- const handled = this.state.plugins.some((plugin) => {
811
- const command = plugin.spec.keymap?.[name];
812
- return command ? this.run(command) : false;
813
- });
814
- if (handled)
1116
+ // A key no command takes keeps its default (Tab outside a list moves the focus on).
1117
+ if (this.runKey(name)) {
815
1118
  event.preventDefault();
1119
+ return;
1120
+ }
1121
+ // Up/Down on a textblock's first/last line next to a rule select it (only the view knows
1122
+ // lines; measured only when a rule is beside the block); else the browser moves the caret.
1123
+ const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
1124
+ const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
1125
+ if (across?.(this.state) && this.caretOnEdgeLine(vertical) && this.run(across)) {
1126
+ event.preventDefault();
1127
+ }
816
1128
  };
1129
+ /**
1130
+ * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
1131
+ * block's first or last fragment (a block split across pages has several).
1132
+ */
1133
+ caretOnEdgeLine(dir) {
1134
+ const sel = this.host.ownerDocument.getSelection();
1135
+ if (!sel?.rangeCount || !sel.isCollapsed || !sel.focusNode)
1136
+ return false;
1137
+ const element = this.blockElement(sel.focusNode);
1138
+ const desc = element ? this.owner.get(element) : undefined;
1139
+ if (!desc?.node.isTextblock)
1140
+ return false;
1141
+ const fragment = desc.fragments[dir < 0 ? 0 : desc.fragments.length - 1];
1142
+ if (!fragment || element !== fragment)
1143
+ return false;
1144
+ if (!desc.node.content.size)
1145
+ return true;
1146
+ const caret = sel.getRangeAt(0).getClientRects()[0];
1147
+ const lines = this.host.ownerDocument.createRange();
1148
+ lines.selectNodeContents(fragment);
1149
+ const rects = lines.getClientRects();
1150
+ const edge = rects[dir < 0 ? 0 : rects.length - 1];
1151
+ // No caret box (some positions next to a line break): leave the move to the browser.
1152
+ if (!caret || !edge)
1153
+ return false;
1154
+ return dir < 0 ? caret.top + 1 < edge.bottom : caret.bottom - 1 > edge.top;
1155
+ }
817
1156
  /**
818
1157
  * Caret affinity at a page break. The end of one fragment and the start of the next are two
819
1158
  * DOM caret stops for one model position, so a native Left/Right (or word move) there would
@@ -843,7 +1182,7 @@ export class EditorView {
843
1182
  const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
844
1183
  if (head === null)
845
1184
  return false;
846
- const offset = head - this.starts[this.blocks.indexOf(desc)] - 1;
1185
+ const offset = head - this.starts[this.indexOf.get(desc) ?? -1] - 1;
847
1186
  let target = null;
848
1187
  // Stepping back over an edge after a hard break lands before the <br>: the point after it
849
1188
  // is still the split, and browsers would show it before the <br> anyway. That step is
@@ -873,6 +1212,32 @@ export class EditorView {
873
1212
  this.syncSelection();
874
1213
  return true;
875
1214
  }
1215
+ /**
1216
+ * A v3 list number is not text, but browsers stop the caret before it as well as after: Right
1217
+ * at the end of the paragraph before, or Left at a numbered paragraph's start, would seem to do
1218
+ * nothing. Moves over the paragraph boundary in one step (word moves are left to the browser).
1219
+ */
1220
+ crossListNumber(event) {
1221
+ const forward = event.key === "ArrowRight";
1222
+ if (!this.word || (!forward && event.key !== "ArrowLeft"))
1223
+ return false;
1224
+ if (event.metaKey || event.ctrlKey || event.altKey)
1225
+ return false;
1226
+ const { selection, doc } = this.state;
1227
+ if (!(selection instanceof TextSelection) || (!event.shiftKey && !selection.empty))
1228
+ return false;
1229
+ const { $head } = selection;
1230
+ if ($head.depth !== 1 || $head.parentOffset !== (forward ? $head.parent.content.size : 0))
1231
+ return false;
1232
+ const numbered = $head.index(0) + (forward ? 1 : 0);
1233
+ const other = doc.maybeChild($head.index(0) + (forward ? 1 : -1));
1234
+ if (!other?.isTextblock || !this.word.hasMarker(numbered))
1235
+ return false;
1236
+ const head = forward ? $head.after() + 1 : $head.before() - 1;
1237
+ const anchor = event.shiftKey ? selection.anchor : head;
1238
+ this.dispatch(this.state.tr.setSelection(TextSelection.create(doc, anchor, head)));
1239
+ return true;
1240
+ }
876
1241
  /** Safety net: a DOM change that was not prevented is read back into the model. */
877
1242
  onInput = () => {
878
1243
  if (!this.composing)
@@ -960,12 +1325,24 @@ export class EditorView {
960
1325
  }
961
1326
  else if (hardBreaks.has(node))
962
1327
  domText += HARD_BREAK;
1328
+ // Shown but not document text (a list number, opaque content): never read back.
1329
+ else if (node.getAttribute?.("contenteditable") === "false")
1330
+ return;
963
1331
  else
964
1332
  node.childNodes.forEach(walk);
965
1333
  };
966
1334
  let first = true;
967
- // Block-level nodes in order: the children of each page, and anything else in the host.
968
- const blockLevel = [...this.host.childNodes].flatMap((child) => this.pages.includes(child) ? [...child.childNodes] : [child]);
1335
+ // Block-level nodes in order: inside pages and containers, and anything else in the host.
1336
+ const blockLevel = [];
1337
+ const collect = (parent) => {
1338
+ for (const child of parent.childNodes) {
1339
+ if (this.holdsBlocks(child))
1340
+ collect(child);
1341
+ else
1342
+ blockLevel.push(child);
1343
+ }
1344
+ };
1345
+ collect(this.host);
969
1346
  let previousOwner;
970
1347
  for (const child of blockLevel) {
971
1348
  const owner = this.owner.get(child);
@@ -982,11 +1359,18 @@ export class EditorView {
982
1359
  const { doc } = this.state;
983
1360
  const lineStarts = [];
984
1361
  let modelText = "";
985
- doc.forEach((block, _offset, i) => {
1362
+ this.blocks.forEach(({ node: block }, i) => {
986
1363
  if (i > 0)
987
1364
  modelText += BLOCK_SEPARATOR;
988
1365
  lineStarts.push(modelText.length);
989
- modelText += block.textBetween(0, block.content.size, "", HARD_BREAK);
1366
+ block.forEach((child) => {
1367
+ // A tab is text in the DOM (a "\t" text node).
1368
+ modelText += child.isText
1369
+ ? (child.text ?? "")
1370
+ : child.type.name === "tab"
1371
+ ? "\t"
1372
+ : HARD_BREAK;
1373
+ });
990
1374
  });
991
1375
  /** Model position of an offset in `modelText`. */
992
1376
  const posAt = (offset) => {
@@ -1061,7 +1445,8 @@ export class EditorView {
1061
1445
  if (selection.empty || !event.clipboardData)
1062
1446
  return;
1063
1447
  event.preventDefault();
1064
- const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument);
1448
+ const context = wordContext(this.state);
1449
+ const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
1065
1450
  event.clipboardData.setData("text/plain", text);
1066
1451
  event.clipboardData.setData("text/html", html);
1067
1452
  event.clipboardData.setData(FOLI_MIME, json);
@@ -1084,25 +1469,48 @@ export class EditorView {
1084
1469
  return;
1085
1470
  this.syncSelection();
1086
1471
  const data = event.clipboardData;
1087
- this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data);
1472
+ this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data, !plain);
1088
1473
  };
1089
1474
  /**
1090
1475
  * Replaces the selection with clipboard content (Foli JSON, else HTML, else plain text). The
1091
1476
  * paste starts a new undo step (typing right after it joins that step). Closed content (whole
1092
1477
  * blocks) goes into an empty textblock whole, so a pasted heading stays a heading; open
1093
1478
  * content, and anything pasted into a non-empty block, joins the text around the selection,
1094
- * so the target block keeps its type. Returns whether anything was inserted.
1479
+ * so the target block keeps its type. Plain text that is one URL becomes a link (`autolink`,
1480
+ * not for paste as plain text): over selected text inside one block, that text is linked;
1481
+ * otherwise the URL is inserted as linked text. Returns whether anything was inserted.
1095
1482
  */
1096
- paste(data) {
1483
+ paste(data, autolink = true) {
1097
1484
  const { state } = this;
1098
- const marks = (state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1099
- const pasted = docFromClipboard(data, marks);
1100
- // One empty block: nothing to paste.
1101
- if (!pasted || pasted.doc.content.size <= 2)
1485
+ const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
1486
+ const href = text ? autolinkHref(text) : null;
1487
+ if (href) {
1488
+ const { selection } = state;
1489
+ const inside = !selection.empty &&
1490
+ selection.$from.sameParent(selection.$to) &&
1491
+ selection.$from.parent.inlineContent;
1492
+ let applied = false;
1493
+ const command = inside ? setLink(href) : insertLink(href, text.trim());
1494
+ const dispatch = (tr) => {
1495
+ applied = this.dispatch(tr.setMeta(closeHistory, true));
1496
+ };
1497
+ if (command(state, dispatch))
1498
+ return applied;
1499
+ }
1500
+ const marks = typedMarks(state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1501
+ // The document takes the styles, lists and comments the content needs (HTML is read as
1502
+ // schema v2 content, then migrated).
1503
+ const pasted = docFromClipboard(data, marks, (found) => found.html
1504
+ ? fitPastedV2(state, parseContentV2(found.content))
1505
+ : fitPaste(state, found.content, found.word));
1506
+ // One empty paragraph: nothing to paste (a lone opaque block is something).
1507
+ const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
1508
+ if (!pasted || (only?.isTextblock && !only.content.size))
1102
1509
  return false;
1103
- const { doc, open } = pasted;
1104
- try {
1105
- const tr = state.tr.deleteSelection();
1510
+ const { doc, open, envelope } = pasted;
1511
+ // As a slice (text joins the text around the caret); where that cannot be (an opaque block
1512
+ // at an end), as whole blocks at the caret.
1513
+ const asSlice = (tr) => {
1106
1514
  const $pos = tr.selection.$from;
1107
1515
  if (!open && $pos.depth === 1 && $pos.parent.isTextblock && !$pos.parent.content.size) {
1108
1516
  const from = $pos.before();
@@ -1110,22 +1518,63 @@ export class EditorView {
1110
1518
  tr.setSelection(Selection.near(tr.doc.resolve(from + doc.content.size), -1));
1111
1519
  }
1112
1520
  else {
1521
+ // A slice opens into its first and last blocks: an opaque block there has no inside.
1522
+ if (doc.firstChild?.isLeaf || doc.lastChild?.isLeaf) {
1523
+ throw new TransformError("An opaque block at an end is pasted as a block");
1524
+ }
1113
1525
  tr.replaceSelection(doc.slice(1, doc.content.size - 1));
1114
1526
  }
1527
+ };
1528
+ const asBlocks = (tr) => {
1529
+ if (open)
1530
+ throw new TransformError("Open content is pasted as a slice");
1531
+ insertBlocks(tr, doc);
1532
+ };
1533
+ const strategies = [asSlice, asBlocks];
1534
+ for (const strategy of strategies) {
1535
+ const tr = state.tr;
1536
+ try {
1537
+ tr.deleteSelection();
1538
+ strategy(tr);
1539
+ if (envelope && envelope !== wordContext(state)?.envelope)
1540
+ withEnvelope(tr, envelope);
1541
+ }
1542
+ catch (error) {
1543
+ if (error instanceof TransformError)
1544
+ continue;
1545
+ throw error;
1546
+ }
1115
1547
  return this.dispatch(tr.setMeta(closeHistory, true));
1116
1548
  }
1117
- catch (error) {
1118
- // shortcut: content the schema cannot fit at the selection is not pasted; general fitting comes with nested blocks (Phase 7).
1119
- if (error instanceof TransformError)
1120
- return false;
1121
- throw error;
1122
- }
1549
+ return false;
1123
1550
  }
1124
1551
  onSelectionChange = () => {
1125
1552
  if (!this.composing && this.hasFocus())
1126
1553
  this.syncSelection();
1127
1554
  };
1128
1555
  }
1556
+ /**
1557
+ * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1558
+ * paragraph, else between its two halves (an empty one is replaced as a slice first).
1559
+ */
1560
+ function insertBlocks(tr, doc) {
1561
+ const $pos = tr.selection.$from;
1562
+ if (!$pos.parent.isTextblock)
1563
+ throw new TransformError("No textblock at the caret");
1564
+ const atStart = $pos.parentOffset === 0;
1565
+ const atEnd = $pos.parentOffset === $pos.parent.content.size;
1566
+ let at;
1567
+ if (atStart)
1568
+ at = $pos.before();
1569
+ else if (atEnd)
1570
+ at = $pos.after();
1571
+ else {
1572
+ tr.split($pos.pos);
1573
+ at = $pos.pos + 1;
1574
+ }
1575
+ tr.insert(at, doc.content);
1576
+ tr.setSelection(Selection.near(tr.doc.resolve(at + doc.content.size), -1));
1577
+ }
1129
1578
  /**
1130
1579
  * Client rects are scaled by CSS `zoom` or a `transform` on an ancestor, while margins and the
1131
1580
  * page geometry are in layout px: the ratio between the two for a page. From the page's width
@@ -1155,37 +1604,75 @@ function measureBox(desc, scale) {
1155
1604
  };
1156
1605
  }
1157
1606
  /**
1158
- * What the flow needs of a block: its measurement, its lines (on demand), and what the rules
1159
- * need: headings keep with the next block; page breaks end their line's page.
1607
+ * What the flow needs of a block: its measurement, its lines (on demand), Word's spacing before
1608
+ * and after (next to its neighbours), keep with next, keep lines together (not for a block
1609
+ * taller than a page, or one with a page break in it), page breaks ending their line's page,
1610
+ * and a page break before the next block ending this one's page.
1160
1611
  */
1161
- function blockBox(desc, measure, lines) {
1612
+ function wordBox(blocks, i, measure, lines, layout) {
1613
+ const pageHeight = contentHeight(layout.sheet.settings);
1614
+ const desc = blocks[i];
1615
+ const next = blocks[i + 1];
1616
+ const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
1617
+ const pageBreaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1618
+ const hasBreak = pageBreaks.length > 0;
1619
+ const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
1620
+ const bottoms = () => (kept ? [measure.height] : lines().bottoms);
1162
1621
  return {
1163
1622
  height: measure.height,
1164
- marginTop: measure.marginTop,
1165
- marginBottom: measure.marginBottom,
1166
- lines: () => lines().bottoms,
1167
- keepWithNext: desc.node.type.name === "heading",
1623
+ marginTop: before,
1624
+ marginBottom: after,
1625
+ keepWithNext: desc.word.keepNext,
1626
+ pageHeight,
1627
+ lines: bottoms,
1168
1628
  breaksAfter: () => {
1169
- const breaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE &&
1170
- leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1171
- if (!breaks.length)
1172
- return [];
1173
- const { starts } = lines();
1174
- // The line holding the break: the last one starting at or before it.
1175
- return breaks.map((leaf) => {
1629
+ // The line holding each break: the last one starting at or before it.
1630
+ const breaks = pageBreaks.map((leaf) => {
1631
+ const { starts } = lines();
1176
1632
  let line = starts.length - 1;
1177
1633
  while (line > 0 && starts[line] > leaf.offset)
1178
1634
  line--;
1179
1635
  return line;
1180
1636
  });
1637
+ if (next?.word.pageBreakBefore || layout.breakAfter)
1638
+ breaks.push(bottoms().length - 1);
1639
+ return breaks;
1181
1640
  },
1182
1641
  };
1183
1642
  }
1643
+ /**
1644
+ * Writes Word's space above each v3 block as its top margin: the space after the block above
1645
+ * and the space before this one, on the same page; at the top of a page only its space before,
1646
+ * and only on the first page or after an explicit break (a page the text flowed onto drops it).
1647
+ * Written only when it changes.
1648
+ */
1649
+ function applyGaps(blocks, pages, boxes) {
1650
+ blocks.forEach((desc, i) => {
1651
+ const page = pages[i]?.[0] ?? 0;
1652
+ const above = pages[i - 1];
1653
+ const box = boxes[i];
1654
+ let gap;
1655
+ if (above && above[above.length - 1] === page)
1656
+ gap = boxes[i - 1].marginBottom + box.marginTop;
1657
+ else {
1658
+ const prior = boxes[i - 1];
1659
+ const breaks = prior?.breaksAfter?.() ?? [];
1660
+ const forced = page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1661
+ gap = forced ? box.marginTop : 0;
1662
+ }
1663
+ if (gaps.get(desc.dom) === gap)
1664
+ return;
1665
+ gaps.set(desc.dom, gap);
1666
+ desc.dom.style.marginTop = `${gap}px`;
1667
+ });
1668
+ }
1669
+ /** The gap `applyGaps` last wrote on each block element (the style serializes it rounded). */
1670
+ const gaps = new WeakMap();
1184
1671
  /**
1185
1672
  * What the next flow can reuse of the last one: the unchanged blocks before the first changed
1186
1673
  * (or stale) one, and the unchanged tail after the last.
1187
1674
  */
1188
- function reuseOf(last, nodes, stale) {
1675
+ function reuseOf(last, nodes, stale, margin = 0) {
1189
1676
  const before = last.nodes;
1190
1677
  const same = (a, b) => a !== undefined && a === b && !stale.has(a);
1191
1678
  let from = 0;
@@ -1196,6 +1683,9 @@ function reuseOf(last, nodes, stale) {
1196
1683
  tail < before.length - from &&
1197
1684
  same(nodes[nodes.length - 1 - tail], before[before.length - 1 - tail]))
1198
1685
  tail++;
1686
+ // Blocks whose box depends on a changed neighbour are not reused either.
1687
+ from = Math.max(0, from - margin);
1688
+ tail = Math.max(0, tail - margin);
1199
1689
  const delta = nodes.length - before.length;
1200
1690
  return {
1201
1691
  previous: last.result,
@@ -1377,9 +1867,10 @@ const IS_MAC = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(nav
1377
1867
  export function keyName(event) {
1378
1868
  let key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
1379
1869
  const mod = IS_MAC ? event.metaKey : event.ctrlKey;
1380
- // Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z).
1381
- if (mod && !/^[a-z]$/.test(key) && /^Key[A-Z]$/.test(event.code))
1382
- key = event.code.slice(3).toLowerCase();
1870
+ // Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z);
1871
+ // with Shift, Ctrl+Shift+7 still means "7" (the character is "&" or "/" depending on layout).
1872
+ if (mod && !/^[a-z0-9]$/.test(key) && /^(Key[A-Z]|Digit[0-9])$/.test(event.code))
1873
+ key = event.code.slice(-1).toLowerCase();
1383
1874
  let name = key;
1384
1875
  if (event.shiftKey && key !== "Shift")
1385
1876
  name = `Shift-${name}`;