@folijs/view 0.1.0 → 0.2.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,9 @@
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, insertHardBreak, insertLink, insertText, marksAt, NodeSelection, redo, Selection, Slice, setLink, splitBlock, TextSelection, TransformError, toggleMark, undo, } 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 { createWrapper, isWrapper, isWrapperFor, PAGE_BREAK_ATTR, renderBlock, } from "./render.js";
5
+ /** Class of the element of a node-selected block (a rule). */
6
+ const SELECTED_CLASS = "foli-selected-node";
5
7
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
6
8
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
7
9
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
@@ -50,7 +52,9 @@ function printStyles({ pageSize }, id) {
50
52
  * view cannot prevent (Android keyboards, extensions). A MutationObserver records those; the view
51
53
  * then reads the changed text back into a transaction (`readBack`) and re-renders.
52
54
  *
53
- * shortcut: assumes schema v1 (doc > textblocks > inline); nested blocks arrive with lists in Phase 7.
55
+ * Blocks are the leaf blocks of the document at any depth (paragraphs, headings, rules); the
56
+ * containers around them (lists, list items) are rebuilt on each page around the blocks it holds
57
+ * (ADR-0004).
54
58
  */
55
59
  export class EditorView {
56
60
  host;
@@ -59,6 +63,14 @@ export class EditorView {
59
63
  blocks = [];
60
64
  /** Position before each block, parallel to `blocks`. */
61
65
  starts = [];
66
+ /** The containers around each block, outermost first, parallel to `blocks`. */
67
+ chains = [];
68
+ /** The index of each block in `blocks`. */
69
+ indexOf = new Map();
70
+ /** The container types around each block at its last render (a change means re-measuring). */
71
+ chainKeys = new WeakMap();
72
+ /** The element that shows a node selection, if any. */
73
+ selectedDom = null;
62
74
  /** The page of each fragment of each block. */
63
75
  fragmentPages = new Map();
64
76
  /** The block each fragment element belongs to. */
@@ -143,6 +155,8 @@ export class EditorView {
143
155
  host.addEventListener("copy", this.onCopy);
144
156
  host.addEventListener("cut", this.onCut);
145
157
  host.addEventListener("paste", this.onPaste);
158
+ host.addEventListener("click", this.onClick);
159
+ host.addEventListener("auxclick", this.onClick);
146
160
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
147
161
  host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
148
162
  this.unsubscribe = editor.subscribe((state) => this.update(state));
@@ -167,6 +181,8 @@ export class EditorView {
167
181
  host.removeEventListener("copy", this.onCopy);
168
182
  host.removeEventListener("cut", this.onCut);
169
183
  host.removeEventListener("paste", this.onPaste);
184
+ host.removeEventListener("click", this.onClick);
185
+ host.removeEventListener("auxclick", this.onClick);
170
186
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
171
187
  const owned = [
172
188
  "contenteditable",
@@ -240,6 +256,7 @@ export class EditorView {
240
256
  this.state = state;
241
257
  if (docChanged)
242
258
  this.render();
259
+ this.showSelectedNode();
243
260
  this.writeSelection(docChanged);
244
261
  // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
245
262
  if (docChanged || selectionChanged)
@@ -293,7 +310,39 @@ export class EditorView {
293
310
  }
294
311
  let blocks = [];
295
312
  const starts = [];
296
- doc.forEach((node, offset) => {
313
+ const chains = [];
314
+ // Leaf blocks at any depth, in document order, with the containers around each.
315
+ const open = [];
316
+ // The chain of the open containers and its key, rebuilt only when they change (blocks in
317
+ // the same container share one array).
318
+ let chain = [];
319
+ let chainKey = "";
320
+ const changed = () => {
321
+ chain = open.slice();
322
+ chainKey = open.map((container) => container.node.type.name).join(">");
323
+ };
324
+ doc.descendants((node, pos, _parent, index) => {
325
+ let popped = false;
326
+ while (open.length) {
327
+ const last = open[open.length - 1];
328
+ if (pos < last.pos + last.node.nodeSize)
329
+ break;
330
+ open.pop();
331
+ popped = true;
332
+ }
333
+ if (!node.isTextblock && !node.isLeaf) {
334
+ open.push({ node, pos, index, firstBlock: blocks.length });
335
+ changed();
336
+ return true;
337
+ }
338
+ if (popped)
339
+ changed();
340
+ // A block moved into or out of a container (wrapped in a list, indented, lifted) keeps its
341
+ // node but not its line width or margins: measure it again, and re-flow from it.
342
+ const before = this.chainKeys.get(node);
343
+ if (before !== undefined && before !== chainKey)
344
+ this.stale.add(node);
345
+ this.chainKeys.set(node, chainKey);
297
346
  let reused = previous.get(node);
298
347
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
299
348
  // fragment's end breaks its line, so its lines would depend on where it was split before.
@@ -303,7 +352,9 @@ export class EditorView {
303
352
  if (reused)
304
353
  previous.delete(node);
305
354
  blocks.push(reused ?? renderBlock(node, ownerDocument));
306
- starts.push(offset);
355
+ starts.push(pos);
356
+ chains.push(chain);
357
+ return false;
307
358
  });
308
359
  for (const stale of previous.values())
309
360
  for (const fragment of stale.fragments)
@@ -314,7 +365,7 @@ export class EditorView {
314
365
  const before = previousPages.get(desc);
315
366
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
316
367
  });
317
- this.place(blocks, pages);
368
+ this.place(blocks, pages, chains);
318
369
  if (!this.composing) {
319
370
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
320
371
  let scale;
@@ -361,15 +412,18 @@ export class EditorView {
361
412
  return same ? desc : renderBlock(desc.node, ownerDocument, splits);
362
413
  });
363
414
  pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
364
- this.place(blocks, pages);
415
+ this.place(blocks, pages, chains);
365
416
  }
366
417
  this.blocks = blocks;
367
418
  this.starts = starts;
419
+ this.chains = chains;
420
+ this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
368
421
  this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
369
422
  this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
370
423
  this.unflowed = this.composing;
371
424
  this.observeSizes();
372
425
  this.showPlaceholder();
426
+ this.showSelectedNode();
373
427
  // The view's own DOM changes are not input. During a composition, keep what the browser
374
428
  // changed before this render: the touched blocks are read back at compositionend.
375
429
  const records = this.observer.takeRecords();
@@ -378,12 +432,14 @@ export class EditorView {
378
432
  }
379
433
  /**
380
434
  * 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.
435
+ * order), inside the elements of the block's containers (lists, list items), creating and
436
+ * removing pages as needed. A page reuses the container elements already at the same place
437
+ * (same tag, in order), so an edit inside a list moves no DOM. Anything else in the host, a
438
+ * page or a container (stray DOM) is removed.
383
439
  */
384
- place(blocks, pages) {
440
+ place(blocks, pages, chains) {
385
441
  const { host } = this;
386
- const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
442
+ const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0, block: i, fragment: f })));
387
443
  const count = (items[items.length - 1]?.page ?? 0) + 1;
388
444
  while (this.pages.length < count)
389
445
  this.pages.push(this.createPage());
@@ -395,28 +451,92 @@ export class EditorView {
395
451
  else
396
452
  host.insertBefore(page, cursor);
397
453
  }
398
- const blockDoms = new Set(items.map((item) => item.dom));
454
+ const ownerDocument = host.ownerDocument;
455
+ /** Removes what is left after the last placed child (strays, and blocks of later pages). */
456
+ const closeLevel = (level) => {
457
+ let at = level.at;
458
+ while (at) {
459
+ const next = at.nextSibling;
460
+ at.remove();
461
+ at = next;
462
+ }
463
+ };
464
+ // Block fragments not placed yet, and their blocks. A container element whose first block is
465
+ // still to be placed, in another container at that level, belongs to that later container: a
466
+ // block before it gets a new element instead of taking it (which would move every later block
467
+ // into the next element along, e.g. when one list item moves to the next page).
468
+ const pending = new Map(items.map((item) => [item.dom, item.block]));
469
+ /** Container elements placed in this pass (never taken twice). */
470
+ const claimed = new Set();
399
471
  let i = 0;
400
472
  for (let p = 0; p < count; p++) {
401
473
  const page = this.pages[p];
402
- let at = page.firstChild;
474
+ const stack = [
475
+ { el: page, at: page.firstChild, pos: -1 },
476
+ ];
403
477
  for (; i < items.length && items[i]?.page === p; i++) {
404
- const dom = items[i].dom;
405
- if (dom === at)
406
- at = at.nextSibling;
407
- else
408
- page.insertBefore(dom, at);
409
- }
410
- // What is left: strays go; fragments of a later page are moved there next.
411
- while (at) {
412
- const next = at.nextSibling;
413
- if (!blockDoms.has(at))
414
- at.remove();
415
- at = next;
478
+ const item = items[i];
479
+ const chain = chains[item.block] ?? [];
480
+ // Keep the open containers this block shares with the previous one on this page.
481
+ let common = 0;
482
+ while (common < chain.length &&
483
+ common + 1 < stack.length &&
484
+ stack[common + 1]?.pos === chain[common].pos)
485
+ common++;
486
+ while (stack.length > common + 1)
487
+ closeLevel(stack.pop());
488
+ for (let k = common; k < chain.length; k++) {
489
+ const container = chain[k];
490
+ const parent = stack[stack.length - 1];
491
+ let element;
492
+ const candidate = parent.at;
493
+ const later = isWrapperFor(candidate, container.node)
494
+ ? pending.get(firstBlockIn(candidate))
495
+ : undefined;
496
+ // The element that holds this block now, at the innermost level: a list item whose
497
+ // block moves to another page takes its element along (as a paragraph does), instead
498
+ // of a new one replacing it on every page an edit shifts.
499
+ const own = k === chain.length - 1 ? item.dom.parentNode : null;
500
+ if (isWrapperFor(candidate, container.node) &&
501
+ !claimed.has(candidate) &&
502
+ (later === undefined || chains[later]?.[k]?.pos === container.pos)) {
503
+ element = candidate;
504
+ parent.at = element.nextSibling;
505
+ }
506
+ else if (isWrapperFor(own, container.node) &&
507
+ !claimed.has(own) &&
508
+ !own.contains(parent.el)) {
509
+ element = own;
510
+ for (const level of stack)
511
+ if (level.at === element)
512
+ level.at = element.nextSibling;
513
+ parent.el.insertBefore(element, parent.at);
514
+ }
515
+ else {
516
+ element = createWrapper(container.node, ownerDocument);
517
+ parent.el.insertBefore(element, parent.at);
518
+ }
519
+ claimed.add(element);
520
+ styleContainer(element, container, chain[k - 1], item);
521
+ stack.push({ el: element, at: element.firstChild, pos: container.pos });
522
+ }
523
+ const top = stack[stack.length - 1];
524
+ if (item.dom === top.at)
525
+ top.at = top.at.nextSibling;
526
+ else {
527
+ // A cursor of an outer level may point at this block (it moves into a new container):
528
+ // step it past, or it would point into the container.
529
+ for (const level of stack)
530
+ if (level.at === item.dom)
531
+ level.at = item.dom.nextSibling;
532
+ top.el.insertBefore(item.dom, top.at);
533
+ }
534
+ pending.delete(item.dom);
416
535
  }
536
+ while (stack.length)
537
+ closeLevel(stack.pop());
417
538
  }
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.
539
+ // Pages no longer needed and stray DOM in the host: all after the last page by now.
420
540
  let rest = this.pages[count - 1].nextSibling;
421
541
  while (rest) {
422
542
  const next = rest.nextSibling;
@@ -538,20 +658,35 @@ export class EditorView {
538
658
  nextFrame(run);
539
659
  }
540
660
  // ---------- position mapping ----------
541
- /** The block element that contains `node` (the child of a page it sits in), or null. */
661
+ /** The block element (a fragment of a rendered block) that contains `node`, or null. */
542
662
  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;
663
+ for (let element = node; element && element !== this.host; element = element.parentNode) {
664
+ if (this.owner.has(element))
665
+ return element;
666
+ }
667
+ return null;
668
+ }
669
+ /** Whether `node` holds blocks rather than content: the host, a page or a container. */
670
+ holdsBlocks(node) {
671
+ return node === this.host || this.pages.includes(node) || isWrapper(node);
672
+ }
673
+ /** Index of the first block that starts at or after `pos` (the block count if none). */
674
+ blockFrom(pos) {
675
+ let lo = 0;
676
+ let hi = this.starts.length;
677
+ while (lo < hi) {
678
+ const mid = (lo + hi) >> 1;
679
+ if (this.starts[mid] < pos)
680
+ lo = mid + 1;
681
+ else
682
+ hi = mid;
548
683
  }
549
- return element?.parentNode ? element : null;
684
+ return lo;
550
685
  }
551
686
  /** Model position of a DOM point inside the host, or null if it is outside. */
552
687
  posFromDOM(node, offset) {
553
688
  const { host } = this;
554
- if (node === host || this.pages.includes(node)) {
689
+ if (this.holdsBlocks(node)) {
555
690
  // Between fragments: the start of the first one after the point (a block start, or
556
691
  // where a continuation starts), else the document end.
557
692
  const range = host.ownerDocument.createRange();
@@ -567,10 +702,15 @@ export class EditorView {
567
702
  }
568
703
  const element = this.blockElement(node);
569
704
  const owner = element ? this.owner.get(element) : undefined;
570
- const index = owner ? this.blocks.indexOf(owner) : -1;
705
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
571
706
  const desc = this.blocks[index];
572
707
  if (!desc)
573
708
  return null;
709
+ // A point in or at a block leaf (a rule): before it, or after it at its end.
710
+ if (!desc.node.isTextblock) {
711
+ const after = node === desc.dom && offset > 0;
712
+ return this.starts[index] + (after ? desc.node.nodeSize : 0);
713
+ }
574
714
  const contentStart = this.starts[index] + 1;
575
715
  const leaf = desc.leaves.find((l) => l.dom === node);
576
716
  if (leaf && node.nodeType === Node.TEXT_NODE)
@@ -587,11 +727,20 @@ export class EditorView {
587
727
  /** DOM point for a model position. At a mark boundary the caret stays in the text before it. */
588
728
  domFromPos(pos) {
589
729
  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)];
730
+ const $pos = doc.resolve(pos);
731
+ if (!$pos.parent.isTextblock) {
732
+ // Between blocks: the start of the next block (before a rule), else the document end.
733
+ const next = this.blocks[this.blockFrom(pos)];
734
+ if (next)
735
+ return next.node.isTextblock ? fragmentStart(next, 0) : before(next.dom);
736
+ const last = this.blocks[this.blocks.length - 1];
737
+ if (!last.node.isTextblock) {
738
+ const point = before(last.dom);
739
+ return { node: point.node, offset: point.offset + 1 };
740
+ }
741
+ return fragmentEnd(last, last.fragments.length - 1);
742
+ }
743
+ const desc = this.blocks[this.blockFrom($pos.before())];
595
744
  const offset = $pos.parentOffset;
596
745
  // Where a fragment starts, show the caret at the start of the next page's fragment, as a
597
746
  // browser shows it at the start of the next line at a soft wrap.
@@ -620,13 +769,48 @@ export class EditorView {
620
769
  const sel = this.host.ownerDocument.getSelection();
621
770
  if (!sel?.anchorNode || !sel.focusNode)
622
771
  return null;
772
+ // A range around exactly one block leaf element (a rule): the node selection that wrote it.
773
+ // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
774
+ if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
775
+ const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
776
+ const owner = child && this.owner.get(child);
777
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
778
+ if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
779
+ return NodeSelection.create(this.state.doc, this.starts[index]);
780
+ }
623
781
  const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
624
782
  const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
625
783
  if (anchor === null || head === null)
626
784
  return null;
627
785
  const { doc } = this.state;
786
+ // Exactly around a selectable block leaf (a rule): the node selection that wrote it.
787
+ const from = Math.min(anchor, head);
788
+ const node = doc.nodeAt(from);
789
+ if (node &&
790
+ node.isBlock &&
791
+ node.isAtom &&
792
+ Math.max(anchor, head) === from + node.nodeSize &&
793
+ NodeSelection.isSelectable(node))
794
+ return NodeSelection.create(doc, from);
628
795
  return TextSelection.between(doc.resolve(anchor), doc.resolve(head));
629
796
  }
797
+ /** The rendered block a node selection selects, if it selects one. */
798
+ selectedBlock() {
799
+ const { selection } = this.state;
800
+ if (!(selection instanceof NodeSelection))
801
+ return null;
802
+ const desc = this.blocks[this.blockFrom(selection.from)];
803
+ return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
804
+ }
805
+ /** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
806
+ showSelectedNode() {
807
+ const dom = this.selectedBlock()?.dom ?? null;
808
+ if (dom === this.selectedDom)
809
+ return;
810
+ this.selectedDom?.classList.remove(SELECTED_CLASS);
811
+ dom?.classList.add(SELECTED_CLASS);
812
+ this.selectedDom = dom;
813
+ }
630
814
  /**
631
815
  * Brings the model selection up to date with the DOM. `selectionchange` is asynchronous, so
632
816
  * every input handler calls this first instead of trusting the last event.
@@ -666,6 +850,12 @@ export class EditorView {
666
850
  if (current && this.shows(current))
667
851
  return;
668
852
  }
853
+ const selected = this.selectedBlock();
854
+ if (selected) {
855
+ const point = before(selected.dom);
856
+ sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
857
+ return;
858
+ }
669
859
  // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
670
860
  // The model takes the snapped selection back on its next read of the DOM.
671
861
  const from = clusterBoundary(doc, selection.from, false);
@@ -723,7 +913,9 @@ export class EditorView {
723
913
  this.run(insertText(text));
724
914
  return;
725
915
  case "insertParagraph":
726
- this.run(splitBlock);
916
+ // The same as Enter (a list item splits or ends), for keyboards that send no keydown.
917
+ if (!this.runKey("Enter"))
918
+ this.run(splitBlock);
727
919
  return;
728
920
  case "insertLineBreak":
729
921
  this.run(insertHardBreak);
@@ -766,8 +958,19 @@ export class EditorView {
766
958
  return;
767
959
  }
768
960
  const unit = type.startsWith("deleteWord") ? "word" : "char";
961
+ // A one-character delete goes through the key bindings first (Backspace at a list item's
962
+ // start lifts it), as the key itself would.
963
+ if (unit === "char" && this.runKey(type.endsWith("Forward") ? "Delete" : "Backspace"))
964
+ return;
769
965
  this.run(type.endsWith("Forward") ? deleteForward(unit) : deleteBackward(unit));
770
966
  };
967
+ /** Runs the first command bound to `name` that applies, through the view's dispatch. */
968
+ runKey(name) {
969
+ return this.state.plugins.some((plugin) => {
970
+ const command = plugin.spec.keymap?.[name];
971
+ return command ? this.run(command) : false;
972
+ });
973
+ }
771
974
  /**
772
975
  * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
773
976
  * selection to the start of the next block, so typing over it would merge the two blocks.
@@ -778,23 +981,61 @@ export class EditorView {
778
981
  // focuses nothing (prevented, middle button) must not skip the next keyboard focus.
779
982
  if (this.pointerFocus)
780
983
  setTimeout(() => (this.pointerFocus = false));
781
- if (event.detail !== 3 || event.button !== 0)
984
+ if (event.button !== 0)
782
985
  return;
783
986
  const element = this.blockElement(event.target);
784
987
  const owner = element ? this.owner.get(element) : undefined;
785
- const index = owner ? this.blocks.indexOf(owner) : -1;
988
+ const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
786
989
  const desc = this.blocks[index];
787
990
  if (!desc)
788
991
  return;
789
- event.preventDefault();
790
- const from = this.starts[index] + 1;
791
992
  const { doc } = this.state;
993
+ const start = this.starts[index];
994
+ let selection;
995
+ if (!desc.node.isTextblock) {
996
+ // A click on a rule selects it (the browser would put the caret beside it); Shift+click
997
+ // extends the selection natively.
998
+ if (event.shiftKey || !NodeSelection.isSelectable(desc.node))
999
+ return;
1000
+ selection = NodeSelection.create(doc, start);
1001
+ }
1002
+ else if (event.detail === 3) {
1003
+ selection = TextSelection.create(doc, start + 1, start + 1 + desc.node.content.size);
1004
+ }
1005
+ else
1006
+ return;
1007
+ event.preventDefault();
792
1008
  this.host.focus();
793
- this.dispatch(this.state.tr
794
- .setSelection(TextSelection.create(doc, from, from + desc.node.content.size))
795
- .setStoredMarks(null));
1009
+ this.dispatch(this.state.tr.setSelection(selection).setStoredMarks(null));
796
1010
  this.writeSelection(true);
797
1011
  };
1012
+ /**
1013
+ * A click on a link in the document does not navigate (it places the caret, also in read-only
1014
+ * mode); Ctrl+click (Cmd+click on Apple platforms) opens it in a new tab, without `opener`.
1015
+ */
1016
+ onClick = (event) => {
1017
+ const target = event.target;
1018
+ const element = target instanceof Element ? target.closest("a") : null;
1019
+ if (!element || !this.host.contains(element))
1020
+ return;
1021
+ event.preventDefault();
1022
+ if (event.type !== "click" || !(IS_MAC ? event.metaKey : event.ctrlKey))
1023
+ return;
1024
+ const href = this.linkHref(element);
1025
+ if (href)
1026
+ this.host.ownerDocument.defaultView?.open(href, "_blank", "noopener,noreferrer");
1027
+ };
1028
+ /** The href of the link an `<a>` shows, read from the model (the DOM is never the truth). */
1029
+ linkHref(element) {
1030
+ const pos = this.posFromDOM(element, 0);
1031
+ const type = this.state.schema.marks.link;
1032
+ if (pos === null || !type)
1033
+ return null;
1034
+ const $pos = this.state.doc.resolve(pos);
1035
+ const node = $pos.parent.maybeChild($pos.index());
1036
+ const href = node && type.isInSet(node.marks)?.attrs.href;
1037
+ return typeof href === "string" ? href : null;
1038
+ }
798
1039
  onKeyDown = (event) => {
799
1040
  if (event.isComposing || this.composing)
800
1041
  return;
@@ -807,13 +1048,46 @@ export class EditorView {
807
1048
  // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
808
1049
  this.plainPaste = name === "Mod-Shift-v";
809
1050
  // 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)
1051
+ // A key no command takes keeps its default (Tab outside a list moves the focus on).
1052
+ if (this.runKey(name)) {
815
1053
  event.preventDefault();
1054
+ return;
1055
+ }
1056
+ // Up/Down on a textblock's first/last line next to a rule select it (only the view knows
1057
+ // lines; measured only when a rule is beside the block); else the browser moves the caret.
1058
+ const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
1059
+ const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
1060
+ if (across?.(this.state) && this.caretOnEdgeLine(vertical) && this.run(across)) {
1061
+ event.preventDefault();
1062
+ }
816
1063
  };
1064
+ /**
1065
+ * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
1066
+ * block's first or last fragment (a block split across pages has several).
1067
+ */
1068
+ caretOnEdgeLine(dir) {
1069
+ const sel = this.host.ownerDocument.getSelection();
1070
+ if (!sel?.rangeCount || !sel.isCollapsed || !sel.focusNode)
1071
+ return false;
1072
+ const element = this.blockElement(sel.focusNode);
1073
+ const desc = element ? this.owner.get(element) : undefined;
1074
+ if (!desc?.node.isTextblock)
1075
+ return false;
1076
+ const fragment = desc.fragments[dir < 0 ? 0 : desc.fragments.length - 1];
1077
+ if (!fragment || element !== fragment)
1078
+ return false;
1079
+ if (!desc.node.content.size)
1080
+ return true;
1081
+ const caret = sel.getRangeAt(0).getClientRects()[0];
1082
+ const lines = this.host.ownerDocument.createRange();
1083
+ lines.selectNodeContents(fragment);
1084
+ const rects = lines.getClientRects();
1085
+ const edge = rects[dir < 0 ? 0 : rects.length - 1];
1086
+ // No caret box (some positions next to a line break): leave the move to the browser.
1087
+ if (!caret || !edge)
1088
+ return false;
1089
+ return dir < 0 ? caret.top + 1 < edge.bottom : caret.bottom - 1 > edge.top;
1090
+ }
817
1091
  /**
818
1092
  * Caret affinity at a page break. The end of one fragment and the start of the next are two
819
1093
  * DOM caret stops for one model position, so a native Left/Right (or word move) there would
@@ -843,7 +1117,7 @@ export class EditorView {
843
1117
  const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
844
1118
  if (head === null)
845
1119
  return false;
846
- const offset = head - this.starts[this.blocks.indexOf(desc)] - 1;
1120
+ const offset = head - this.starts[this.indexOf.get(desc) ?? -1] - 1;
847
1121
  let target = null;
848
1122
  // Stepping back over an edge after a hard break lands before the <br>: the point after it
849
1123
  // is still the split, and browsers would show it before the <br> anyway. That step is
@@ -964,8 +1238,17 @@ export class EditorView {
964
1238
  node.childNodes.forEach(walk);
965
1239
  };
966
1240
  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]);
1241
+ // Block-level nodes in order: inside pages and containers, and anything else in the host.
1242
+ const blockLevel = [];
1243
+ const collect = (parent) => {
1244
+ for (const child of parent.childNodes) {
1245
+ if (this.holdsBlocks(child))
1246
+ collect(child);
1247
+ else
1248
+ blockLevel.push(child);
1249
+ }
1250
+ };
1251
+ collect(this.host);
969
1252
  let previousOwner;
970
1253
  for (const child of blockLevel) {
971
1254
  const owner = this.owner.get(child);
@@ -982,7 +1265,7 @@ export class EditorView {
982
1265
  const { doc } = this.state;
983
1266
  const lineStarts = [];
984
1267
  let modelText = "";
985
- doc.forEach((block, _offset, i) => {
1268
+ this.blocks.forEach(({ node: block }, i) => {
986
1269
  if (i > 0)
987
1270
  modelText += BLOCK_SEPARATOR;
988
1271
  lineStarts.push(modelText.length);
@@ -1084,25 +1367,44 @@ export class EditorView {
1084
1367
  return;
1085
1368
  this.syncSelection();
1086
1369
  const data = event.clipboardData;
1087
- this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data);
1370
+ this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data, !plain);
1088
1371
  };
1089
1372
  /**
1090
1373
  * Replaces the selection with clipboard content (Foli JSON, else HTML, else plain text). The
1091
1374
  * paste starts a new undo step (typing right after it joins that step). Closed content (whole
1092
1375
  * blocks) goes into an empty textblock whole, so a pasted heading stays a heading; open
1093
1376
  * 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.
1377
+ * so the target block keeps its type. Plain text that is one URL becomes a link (`autolink`,
1378
+ * not for paste as plain text): over selected text inside one block, that text is linked;
1379
+ * otherwise the URL is inserted as linked text. Returns whether anything was inserted.
1095
1380
  */
1096
- paste(data) {
1381
+ paste(data, autolink = true) {
1097
1382
  const { state } = this;
1383
+ const text = autolink && !data.getData(FOLI_MIME) ? data.getData("text/plain") : "";
1384
+ const href = text ? autolinkHref(text) : null;
1385
+ if (href) {
1386
+ const { selection } = state;
1387
+ const inside = !selection.empty &&
1388
+ selection.$from.sameParent(selection.$to) &&
1389
+ selection.$from.parent.inlineContent;
1390
+ let applied = false;
1391
+ const command = inside ? setLink(href) : insertLink(href, text.trim());
1392
+ const dispatch = (tr) => {
1393
+ applied = this.dispatch(tr.setMeta(closeHistory, true));
1394
+ };
1395
+ if (command(state, dispatch))
1396
+ return applied;
1397
+ }
1098
1398
  const marks = (state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1099
1399
  const pasted = docFromClipboard(data, marks);
1100
- // One empty block: nothing to paste.
1101
- if (!pasted || pasted.doc.content.size <= 2)
1400
+ // One empty textblock: nothing to paste (a lone rule is something).
1401
+ const only = pasted?.doc.childCount === 1 ? pasted.doc.firstChild : null;
1402
+ if (!pasted || (only?.isTextblock && !only.content.size))
1102
1403
  return false;
1103
1404
  const { doc, open } = pasted;
1104
- try {
1105
- const tr = state.tr.deleteSelection();
1405
+ // As a slice (text joins the text around the caret); where the schema refuses that (a
1406
+ // list in a paragraph), as whole blocks fitted at the caret.
1407
+ const asSlice = (tr) => {
1106
1408
  const $pos = tr.selection.$from;
1107
1409
  if (!open && $pos.depth === 1 && $pos.parent.isTextblock && !$pos.parent.content.size) {
1108
1410
  const from = $pos.before();
@@ -1110,22 +1412,135 @@ export class EditorView {
1110
1412
  tr.setSelection(Selection.near(tr.doc.resolve(from + doc.content.size), -1));
1111
1413
  }
1112
1414
  else {
1415
+ // A slice opens into its first and last blocks: a rule there has no inside.
1416
+ if (doc.firstChild?.isLeaf || doc.lastChild?.isLeaf) {
1417
+ throw new TransformError("A rule at an end is pasted as a block");
1418
+ }
1113
1419
  tr.replaceSelection(doc.slice(1, doc.content.size - 1));
1114
1420
  }
1421
+ };
1422
+ const asBlocks = (tr) => {
1423
+ if (open)
1424
+ throw new TransformError("Open content is pasted as a slice");
1425
+ insertBlocks(tr, doc);
1426
+ };
1427
+ const strategies = [asSlice, asBlocks];
1428
+ for (const strategy of strategies) {
1429
+ const tr = state.tr;
1430
+ try {
1431
+ tr.deleteSelection();
1432
+ strategy(tr);
1433
+ }
1434
+ catch (error) {
1435
+ if (error instanceof TransformError)
1436
+ continue;
1437
+ throw error;
1438
+ }
1115
1439
  return this.dispatch(tr.setMeta(closeHistory, true));
1116
1440
  }
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
- }
1441
+ return false;
1123
1442
  }
1124
1443
  onSelectionChange = () => {
1125
1444
  if (!this.composing && this.hasFocus())
1126
1445
  this.syncSelection();
1127
1446
  };
1128
1447
  }
1448
+ /**
1449
+ * Pastes whole blocks at the caret (after deleting the selection), for content a slice cannot
1450
+ * fit (lists): a single pasted list inside a list item joins that list (its items replace an
1451
+ * empty item, go before or after the item, or between its two halves); other blocks go before
1452
+ * or after the caret's textblock (replacing it when empty) where its parent takes them, else
1453
+ * between its two halves. Throws TransformError where the schema does not allow it.
1454
+ */
1455
+ function insertBlocks(tr, doc) {
1456
+ const $pos = tr.selection.$from;
1457
+ if (!$pos.parent.isTextblock)
1458
+ throw new TransformError("No textblock at the caret");
1459
+ const atStart = $pos.parentOffset === 0;
1460
+ const atEnd = $pos.parentOffset === $pos.parent.content.size;
1461
+ const only = doc.childCount === 1 ? doc.firstChild : null;
1462
+ const itemType = tr.doc.type.schema.nodes.listItem;
1463
+ const inItem = $pos.depth >= 2 && $pos.node(-1).type === itemType;
1464
+ let at;
1465
+ let content = doc.content;
1466
+ if (only && inItem && only.firstChild?.type === itemType) {
1467
+ content = only.content;
1468
+ const depth = $pos.depth - 1;
1469
+ const item = $pos.node(depth);
1470
+ if (atStart && atEnd && item.childCount === 1) {
1471
+ at = $pos.before(depth);
1472
+ tr.delete(at, $pos.after(depth));
1473
+ }
1474
+ else if (atEnd) {
1475
+ // After the item (and its nested list, if it has one): no item left without its text.
1476
+ at = $pos.after(depth);
1477
+ }
1478
+ else if (atStart && $pos.index(depth) === 0)
1479
+ at = $pos.before(depth);
1480
+ else if (atStart) {
1481
+ // At a later block's start: split the item between blocks, not inside the text.
1482
+ const boundary = $pos.before();
1483
+ tr.split(boundary, 1);
1484
+ at = boundary + 1;
1485
+ }
1486
+ else {
1487
+ tr.split($pos.pos, 2);
1488
+ at = $pos.pos + 2;
1489
+ }
1490
+ }
1491
+ else {
1492
+ // Before, after, or in place of the textblock where its parent takes the blocks there (a
1493
+ // list item's first paragraph must stay first); else between its two halves.
1494
+ const parent = $pos.node(-1);
1495
+ const index = $pos.index(-1);
1496
+ if (atStart && atEnd && parent.canReplace(index, index + 1, content)) {
1497
+ at = $pos.before();
1498
+ tr.delete(at, $pos.after());
1499
+ }
1500
+ else if (atStart && parent.canReplace(index, index, content))
1501
+ at = $pos.before();
1502
+ else if (atEnd && parent.canReplace(index + 1, index + 1, content))
1503
+ at = $pos.after();
1504
+ else {
1505
+ tr.split($pos.pos);
1506
+ at = $pos.pos + 1;
1507
+ }
1508
+ }
1509
+ tr.insert(at, content);
1510
+ tr.setSelection(Selection.near(tr.doc.resolve(at + content.size), -1));
1511
+ }
1512
+ /** The first block element inside a container element (through nested containers), or null. */
1513
+ function firstBlockIn(element) {
1514
+ let child = element.firstElementChild;
1515
+ while (isWrapper(child))
1516
+ child = child.firstElementChild;
1517
+ return child;
1518
+ }
1519
+ /**
1520
+ * Sets what a container element shows on a page: an ordered list item's number (so numbering
1521
+ * continues across pages), and no marker on an item continued from the previous page (its
1522
+ * first block is on an earlier page, or this is a continued fragment of it).
1523
+ */
1524
+ function styleContainer(element, container, parent, item) {
1525
+ if (element.localName !== "li")
1526
+ return;
1527
+ const continued = item.block !== container.firstBlock || item.fragment > 0;
1528
+ const start = parent?.node.type.name === "orderedList" ? parent.node.attrs.start : undefined;
1529
+ const value = typeof start === "number" ? String(start + container.index) : null;
1530
+ // Written only when they change (checked against what was written last, without reading the
1531
+ // DOM): this runs for every list item on every render, and every write invalidates style.
1532
+ const state = `${continued}|${value}`;
1533
+ if (containerStates.get(element) === state)
1534
+ return;
1535
+ containerStates.set(element, state);
1536
+ element.style.listStyleType = continued ? "none" : "";
1537
+ if (value === null)
1538
+ element.removeAttribute("value");
1539
+ else
1540
+ element.setAttribute("value", value);
1541
+ }
1542
+ /** What `styleContainer` last wrote on each list item element. */
1543
+ const containerStates = new WeakMap();
1129
1544
  /**
1130
1545
  * Client rects are scaled by CSS `zoom` or a `transform` on an ancestor, while margins and the
1131
1546
  * page geometry are in layout px: the ratio between the two for a page. From the page's width
@@ -1377,9 +1792,10 @@ const IS_MAC = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(nav
1377
1792
  export function keyName(event) {
1378
1793
  let key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
1379
1794
  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();
1795
+ // Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z);
1796
+ // with Shift, Ctrl+Shift+7 still means "7" (the character is "&" or "/" depending on layout).
1797
+ if (mod && !/^[a-z0-9]$/.test(key) && /^(Key[A-Z]|Digit[0-9])$/.test(event.code))
1798
+ key = event.code.slice(-1).toLowerCase();
1383
1799
  let name = key;
1384
1800
  if (event.shiftKey && key !== "Shift")
1385
1801
  name = `Shift-${name}`;