@folijs/view 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/view.ts CHANGED
@@ -2,35 +2,49 @@ import {
2
2
  AllSelection,
3
3
  arrowAcrossLeaf,
4
4
  autolinkHref,
5
+ CellSelection,
5
6
  type Command,
7
+ cellsAsTable,
6
8
  closeHistory,
7
9
  type DocumentSettings,
8
10
  deleteBackward,
9
11
  deleteForward,
10
12
  deleteSelection,
13
+ deleteSelectionKeepingTables,
11
14
  type Editor,
12
15
  type EditorState,
16
+ extendCellSelection,
13
17
  fitPaste,
14
18
  fitPastedV2,
19
+ goToCellVertically,
15
20
  insertHardBreak,
16
21
  insertLink,
22
+ insertPicture,
17
23
  insertText,
18
24
  isSafeHref,
25
+ keepTablesApart,
19
26
  type Node as ModelNode,
20
27
  marksAt,
21
28
  NodeSelection,
22
29
  parseContentV2,
30
+ pasteCells,
31
+ type ResourceJSON,
32
+ type ReviewView,
23
33
  redo,
24
34
  type SectionJSON,
25
35
  Selection,
26
36
  Slice,
27
37
  sectionSettings,
38
+ setColumnWidth,
39
+ setComments,
28
40
  setLink,
41
+ setPictureSize,
29
42
  splitBlock,
30
43
  TextSelection,
31
44
  type Transaction,
32
45
  TransformError,
33
46
  toggleMark,
47
+ trackState,
34
48
  typedMarks,
35
49
  undo,
36
50
  type WordContext,
@@ -49,14 +63,69 @@ import {
49
63
  type Reuse,
50
64
  } from "./layout/flow.js";
51
65
  import { type BlockDesc, PAGE_BREAK_ATTR } from "./render.js";
52
- import { spacing, type WordBlockDesc, WordRenderer } from "./word/edit.js";
66
+
67
+ import { EMU_PER_PX, imageSource, PICTURE_ATTR } from "./word/blocks.js";
68
+ import {
69
+ FLOAT_ANCHORS,
70
+ spacing,
71
+ type WordBlockDesc,
72
+ type WordInfo,
73
+ WordRenderer,
74
+ } from "./word/edit.js";
53
75
  import { measureLineRatio } from "./word/pages.js";
76
+ import {
77
+ collect,
78
+ type FlowItem,
79
+ FRAME_ATTR,
80
+ type Frame,
81
+ frameElement,
82
+ REPEATED_ATTR,
83
+ type Unit,
84
+ } from "./word/table.js";
85
+
86
+ /** What the flow needs of a table: no paragraph spacing or keep rules of its own. */
87
+ const TABLE_WORD: WordInfo = {
88
+ before: 0,
89
+ after: 0,
90
+ keepNext: false,
91
+ keepLines: false,
92
+ pageBreakBefore: false,
93
+ style: null,
94
+ contextual: false,
95
+ };
96
+
97
+ /** Where a table's fragment is: the rows it shows, the header rows drawn again above them. */
98
+ interface TablePart {
99
+ rows: number[];
100
+ headers: number[];
101
+ }
102
+
103
+ /** A table as last rendered: its wrappers (one per page it is on), their pages, how it was cut. */
104
+ interface FrameState {
105
+ wrappers: HTMLElement[];
106
+ pages: number[];
107
+ /** The parts and the units' fragments in each, as a string: equal means the same DOM. */
108
+ key: string;
109
+ }
110
+
111
+ /** A table's measurement, in layout px from the table's top (drawn whole). */
112
+ export interface TableMeasure {
113
+ rows: { top: number; bottom: number }[];
114
+ /** The top of each of its units (by index into the units), null for one not shown (covered). */
115
+ tops: Map<number, number | null>;
116
+ /** Where the table may break: inside rows that may split, and between rows (sorted). */
117
+ breaks?: number[];
118
+ }
54
119
 
55
120
  /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
56
121
  const WORD_RULES: FlowRules = { ...DEFAULT_RULES, spacing: "word" };
57
122
 
58
123
  /** Class of the element of a node-selected block (a rule). */
59
124
  const SELECTED_CLASS = "foli-selected-node";
125
+ /** Marks a cell of a cell selection. */
126
+ const CELL_CLASS = "foli-selected-cell";
127
+ /** On the host while cells are selected: the browser's own highlight (in DOM order) is hidden. */
128
+ const CELLS_ATTR = "data-foli-cells";
60
129
 
61
130
  interface DomPoint {
62
131
  node: Node;
@@ -68,12 +137,33 @@ export interface EditorViewOptions {
68
137
  editable?: boolean;
69
138
  /** Shown while the document is one empty block (default: none). */
70
139
  placeholder?: string;
140
+ /**
141
+ * The URL to show a picture's image from (`key` in the document's `resources`): an image in
142
+ * the .docx package it came from has none of its own (`packageImages` in `@folijs/docx` gives
143
+ * object URLs). Undefined for a key: the resource's own image `data:` URL or web URL (fetched
144
+ * as it is shown), else a box of the picture's size; `null` (or "") for a key: that box (an
145
+ * app that does not fetch web URLs found in documents says so here). `null` clears it.
146
+ */
147
+ resource?: ((key: string, resource: ResourceJSON) => string | null | undefined) | null;
148
+ /**
149
+ * Where pasted and dropped image files go (ADR-0006's upload hook): the URL the app stores the
150
+ * file at (or a `data:` URL, opting in), and the alt text if it has asked for it. Without it,
151
+ * image files are not pasted or dropped. A picture inserted without alt text is marked, as an
152
+ * imported one is.
153
+ */
154
+ upload?:
155
+ | ((file: File) => Promise<string | { src: string; alt?: string; decorative?: boolean }>)
156
+ | null;
71
157
  }
72
158
 
73
159
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
160
+ /** On the span of a selected picture (it holds the resize handle). */
161
+ const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
162
+ /** The smallest a picture gets by dragging its handle, in px. */
163
+ const MIN_PICTURE = 8;
74
164
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
75
165
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
76
- const STYLES = `[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
166
+ const STYLES = `.${CELL_CLASS}{box-shadow:inset 0 0 0 9999px rgba(0,120,215,.22)}[${CELLS_ATTR}] ::selection{background:transparent}[data-foli-no-alt]{outline:2px dashed #b45309;outline-offset:-2px}@media print{[data-foli-no-alt]{outline:none}}[${PICTURE_SELECTED_ATTR}]{position:relative;outline:2px solid Highlight}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{position:absolute;right:-5px;bottom:-5px;width:10px;height:10px;box-sizing:border-box;border:1px solid Canvas;background:Highlight;cursor:nwse-resize;forced-color-adjust:none}@media print{[${PICTURE_SELECTED_ATTR}]{outline:none}[${PICTURE_SELECTED_ATTR}] [data-foli-resize]{display:none}}[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
77
167
 
78
168
  /**
79
169
  * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
@@ -129,6 +219,13 @@ function printStyles(settings: DocumentSettings, sheets: readonly Sheet[], id: s
129
219
  );
130
220
  }
131
221
 
222
+ /** Whether `node` is inside an element of `stop` that is not displayed (hidden deleted text). */
223
+ function hiddenIn(node: Node, stop: Node): boolean {
224
+ for (let el = node.parentElement; el && el !== stop; el = el.parentElement)
225
+ if (el.style.display === "none") return true;
226
+ return false;
227
+ }
228
+
132
229
  /** The attribute naming a page's page setup (its index among the document's) for print. */
133
230
  const SHEET_ATTR = "data-foli-sheet";
134
231
 
@@ -142,6 +239,9 @@ interface Sheet {
142
239
  function sheetOf(settings: DocumentSettings, index: number): Sheet {
143
240
  const { pageSize, margins } = settings;
144
241
  const css =
242
+ // The containing block, stacking context and formatting context of floating pictures: one
243
+ // reaching past the page's text makes the page taller, never overlaps the next page.
244
+ "position: relative; isolation: isolate; display: flow-root; " +
145
245
  `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
146
246
  `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
147
247
  return { settings, css, index };
@@ -239,8 +339,19 @@ export class EditorView {
239
339
  private indexOf = new Map<BlockDesc, number>();
240
340
  /** The element that shows a node selection, if any. */
241
341
  private selectedDom: HTMLElement | null = null;
242
- /** The page of each fragment of each block. */
243
- private fragmentPages = new Map<BlockDesc, readonly number[]>();
342
+ /** The cells a cell selection marks, and the caret written in its head cell. */
343
+ private selectedCells: HTMLElement[] = [];
344
+ private cellCaret: number | null = null;
345
+ /** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
346
+ private itemPages = new Map<ModelNode, readonly number[]>();
347
+ /** Each table as last rendered, by node. */
348
+ private frames = new Map<ModelNode, FrameState>();
349
+ /** The table each wrapper element draws (part of). */
350
+ private frameOf = new Map<Node, Frame>();
351
+ /** Each table as last rendered, by its index among the top-level items. */
352
+ private frameAt: ({ node: ModelNode; state: FrameState } | undefined)[] = [];
353
+ /** Elements the view itself removed: the read-back does not take them for input. */
354
+ private viewRemoved = new WeakSet<Node>();
244
355
  /** The block each fragment element belongs to. */
245
356
  private owner = new Map<Node, BlockDesc>();
246
357
  /** The page elements, in order; the host's only children. */
@@ -305,6 +416,27 @@ export class EditorView {
305
416
  private readonly addedTabIndex: boolean;
306
417
  /** Renders the document's blocks; made by the first render. */
307
418
  private word: WordRenderer | null = null;
419
+ /** Where pasted and dropped image files go (`EditorViewOptions.upload`). */
420
+ private upload: EditorViewOptions["upload"];
421
+ /** The selected picture's span (with its resize handle). */
422
+ private selectedPicture: HTMLElement | null = null;
423
+ /** A picture being resized: its position, element, size at the press, scale, the press. */
424
+ private resize: {
425
+ pos: number;
426
+ img: HTMLElement;
427
+ width: number;
428
+ height: number;
429
+ scale: number;
430
+ /** The widest it may get (layout px). */
431
+ max: number;
432
+ x: number;
433
+ y: number;
434
+ style: string;
435
+ } | null = null;
436
+ /** The app's URLs for pictures' images (`EditorViewOptions.resource`). */
437
+ private resource: EditorViewOptions["resource"];
438
+ /** How tracked changes show. */
439
+ private review: ReviewView = "markup";
308
440
  /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
309
441
  private readonly ratios = new Map<string, number>();
310
442
  /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
@@ -325,10 +457,13 @@ export class EditorView {
325
457
  host.style.whiteSpace = "pre-wrap";
326
458
  host.style.overflowWrap = "break-word";
327
459
  host.replaceChildren();
460
+ this.review = trackState(this.state)?.view ?? "markup";
328
461
  this.resizeObserver =
329
462
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
330
463
  this.observer = new MutationObserver(this.onMutations);
331
464
  this.observer.observe(host, { childList: true, characterData: true, subtree: true });
465
+ // The picture resolver before the first render: no image drawn from a URL the app refuses.
466
+ this.resource = options.resource ?? undefined;
332
467
  this.render();
333
468
  this.setOptions(options);
334
469
 
@@ -340,9 +475,12 @@ export class EditorView {
340
475
  host.addEventListener("compositionend", this.onCompositionEnd);
341
476
  host.addEventListener("blur", this.onBlur);
342
477
  host.addEventListener("mousedown", this.onMouseDown);
478
+ host.addEventListener("mousemove", this.onMouseMove);
343
479
  host.addEventListener("copy", this.onCopy);
344
480
  host.addEventListener("cut", this.onCut);
345
481
  host.addEventListener("paste", this.onPaste);
482
+ host.addEventListener("dragover", this.onDragOver);
483
+ host.addEventListener("drop", this.onDrop);
346
484
  host.addEventListener("click", this.onClick);
347
485
  host.addEventListener("auxclick", this.onClick);
348
486
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
@@ -366,9 +504,14 @@ export class EditorView {
366
504
  host.removeEventListener("compositionend", this.onCompositionEnd);
367
505
  host.removeEventListener("blur", this.onBlur);
368
506
  host.removeEventListener("mousedown", this.onMouseDown);
507
+ host.removeEventListener("mousemove", this.onMouseMove);
508
+ this.endDrag();
369
509
  host.removeEventListener("copy", this.onCopy);
370
510
  host.removeEventListener("cut", this.onCut);
371
511
  host.removeEventListener("paste", this.onPaste);
512
+ host.removeEventListener("dragover", this.onDragOver);
513
+ host.removeEventListener("drop", this.onDrop);
514
+ this.endResize();
372
515
  host.removeEventListener("click", this.onClick);
373
516
  host.removeEventListener("auxclick", this.onClick);
374
517
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
@@ -404,8 +547,26 @@ export class EditorView {
404
547
  // Finish a running composition while its text can still go into the model.
405
548
  if (!options.editable && this.composing) this.onCompositionEnd();
406
549
  this.editable = options.editable;
550
+ // A selected picture's handle only while it can be resized.
551
+ this.endResize();
552
+ this.showSelectedPicture();
407
553
  }
408
554
  if (options.placeholder !== undefined) this.placeholder = options.placeholder;
555
+ if (options.upload !== undefined) this.upload = options.upload ?? undefined;
556
+ // null clears the resolver (stored as none): the same as none is no change.
557
+ const resource = options.resource ?? undefined;
558
+ if (options.resource !== undefined && resource !== this.resource) {
559
+ this.resource = resource;
560
+ // Every picture again, from the new URLs: after a running composition, keeping the
561
+ // selection.
562
+ if (this.word) {
563
+ if (this.composing) this.onCompositionEnd();
564
+ this.word = null;
565
+ this.render();
566
+ this.writeSelection(false);
567
+ }
568
+ }
569
+
409
570
  // Read-only: no caret and no browser editing; the text stays selectable and copyable.
410
571
  host.setAttribute("contenteditable", String(this.editable));
411
572
  if (this.editable) host.removeAttribute("aria-readonly");
@@ -436,7 +597,16 @@ export class EditorView {
436
597
  // ---------- rendering ----------
437
598
 
438
599
  private update(state: EditorState): void {
439
- const docChanged = state.doc !== this.state.doc;
600
+ // A resize is of the picture at its position when it started: the document changed, over.
601
+ if (state.doc !== this.state.doc) this.onResizeCancel();
602
+ const review = trackState(state)?.view ?? "markup";
603
+ // Another review view (`setReviewView`): every block drawn again, by a new renderer.
604
+ const reviewChanged = review !== this.review;
605
+ if (reviewChanged) {
606
+ this.review = review;
607
+ this.word = null;
608
+ }
609
+ const docChanged = state.doc !== this.state.doc || reviewChanged;
440
610
  const selectionChanged = !state.selection.eq(this.state.selection);
441
611
  this.state = state;
442
612
  if (docChanged) this.render();
@@ -493,10 +663,22 @@ export class EditorView {
493
663
  if (renewed) this.fontsChanged = false;
494
664
  let word = this.word as WordRenderer;
495
665
  if (renewed) {
496
- word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio);
666
+ // A document with pictures: the mark of one without alt text is the view's stylesheet's.
667
+ if (context.envelope.resources) injectStyles(this.host);
668
+ word = this.word = new WordRenderer(
669
+ context,
670
+ ownerDocument,
671
+ this.lineRatio,
672
+ false,
673
+ this.review,
674
+ imageSource(context.envelope.resources, this.resource ?? undefined),
675
+ );
497
676
  this.invalidateLayout();
498
677
  }
499
- word.prepare(doc);
678
+ // The blocks the view renders (paragraphs in table cells among them) and the page flow's
679
+ // items (top-level paragraphs and opaque blocks, and tables).
680
+ const { units, items } = collect(doc, context.resolver);
681
+ word.prepare(units.map((unit) => unit.node));
500
682
  const layout = sectionLayouts(doc, context.envelope.section);
501
683
  doc.forEach((node, _, i) => {
502
684
  const { sheet, breakAfter } = layout[i] as BlockLayout;
@@ -508,40 +690,127 @@ export class EditorView {
508
690
  const previous = new Map(
509
691
  this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]),
510
692
  );
511
- const previousPages = this.fragmentPages;
693
+ const previousPages = this.itemPages;
694
+ const previousFrames = this.frames;
512
695
  this.dirty.clear();
513
696
  const dropLines = this.linesStale && !this.composing;
514
697
  if (dropLines) {
515
698
  this.linesStale = false;
516
699
  this.flowed = null;
517
700
  }
701
+ // What can be reused: a block whose list number, comment shading or cell formatting changed
702
+ // (an edit before it) is redrawn.
703
+ const reusable = units.map((unit, i) => {
704
+ const found = renewed ? undefined : previous.get(unit.node);
705
+ if (found && found.key === word.key(i, unit.cell)) return found;
706
+ if (found) this.stale.add(unit.node);
707
+ return undefined;
708
+ });
709
+ this.staleAroundFloats(
710
+ doc,
711
+ previousPages,
712
+ new Set(units.filter((_, i) => !reusable[i]).map((unit) => unit.node)),
713
+ );
714
+ // A table is measured again (drawn whole first) when it changed, went stale, or one of its
715
+ // blocks is redrawn or stale; its blocks with it.
716
+ const remeasureUnit = units.map(() => false);
717
+ for (const item of items) {
718
+ const frame = item.frame;
719
+ if (!frame) continue;
720
+ let stale = dropLines || !this.measures.has(frame.node) || this.stale.has(frame.node);
721
+ for (let u = frame.first; !stale && u < frame.end; u++)
722
+ stale = !reusable[u] || this.stale.has((units[u] as Unit).node);
723
+ if (!stale) continue;
724
+ this.stale.add(frame.node);
725
+ for (let u = frame.first; u < frame.end; u++) remeasureUnit[u] = true;
726
+ }
518
727
  let blocks: WordBlockDesc[] = [];
519
- const starts: number[] = [];
520
- doc.forEach((node, pos) => {
521
- let reused = renewed ? undefined : previous.get(node);
522
- // A block whose list number or comment shading changed (an edit before it) is redrawn.
523
- if (reused && reused.key !== word.key(blocks.length)) {
524
- reused = undefined;
525
- this.stale.add(node);
526
- }
728
+ // Nodes still in the document: an old block or table at an index is only taken over (during
729
+ // a composition) when its node is gone, never when an insertion moved it along.
730
+ const present = new Set<ModelNode>(units.map((unit) => unit.node));
731
+ for (const item of items) if (item.frame) present.add(item.frame.node);
732
+ units.forEach((unit, i) => {
733
+ const { node } = unit;
734
+ let reused = reusable[i];
527
735
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
528
736
  // fragment's end breaks its line, so its lines would depend on where it was split before.
529
- const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
737
+ const remeasure =
738
+ remeasureUnit[i] || dropLines || !this.measures.has(node) || this.stale.has(node);
530
739
  if (reused && reused.fragments.length > 1 && remeasure && !this.composing) reused = undefined;
531
740
  if (reused) previous.delete(node);
532
- blocks.push(reused ?? word.render(node, blocks.length));
533
- starts.push(pos);
741
+ const desc = reused ?? word.render(node, i, [], unit.cell);
742
+ blocks.push(desc);
743
+ // Drawn again in a table cell: the new block takes the old one's place there, so a table
744
+ // kept as it is (during a composition, which moves nothing) still holds it. During a
745
+ // composition a block whose node changed takes the place of the block drawn at its index.
746
+ const atIndex = this.blocks[i];
747
+ const old = reused
748
+ ? undefined
749
+ : (previous.get(node) ??
750
+ (this.composing &&
751
+ atIndex &&
752
+ !present.has(atIndex.node) &&
753
+ previous.get(atIndex.node) === atIndex
754
+ ? atIndex
755
+ : undefined));
756
+ const first = old?.fragments[0];
757
+ if (old && first?.isConnected && first.parentElement?.closest(`[${FRAME_ATTR}]`)) {
758
+ first.replaceWith(...desc.fragments);
759
+ for (const fragment of old.fragments.slice(1)) fragment.remove();
760
+ for (const fragment of old.fragments) this.viewRemoved.add(fragment);
761
+ previous.delete(old.node);
762
+ }
534
763
  });
535
764
  for (const stale of previous.values())
536
- for (const fragment of stale.fragments) fragment.remove();
765
+ for (const fragment of stale.fragments) {
766
+ fragment.remove();
767
+ this.viewRemoved.add(fragment);
768
+ }
537
769
  this.applyPrintStyles(layout);
770
+ const doc_ = this.host.ownerDocument;
771
+ const frames = new Map<ModelNode, FrameState>();
772
+ /** A table drawn whole, on one page: what is measured. */
773
+ const whole = (frame: Frame): FrameState => {
774
+ const rows = frame.rows.map((_, r) => r);
775
+ const wrapper = frameElement(
776
+ frame,
777
+ rows,
778
+ [],
779
+ (r, c) => this.cellContent(frame, r, c, blocks, () => true),
780
+ doc_,
781
+ );
782
+ return { wrappers: [wrapper], pages: [0], key: "" };
783
+ };
784
+ // Before the flow, each item where it was (a new one joins the page of the item before it);
785
+ // a table that changed is drawn whole on that page.
538
786
  let last = 0;
539
- let pages = blocks.map((desc) => {
540
- const before = previousPages.get(desc);
787
+ let pages = items.map((item, i) => {
788
+ const node = doc.child(i);
789
+ const before = previousPages.get(node);
790
+ if (item.frame) {
791
+ let state = previousFrames.get(node);
792
+ // During a composition nothing moves: a table that changed keeps the wrappers drawn at
793
+ // its place (its redrawn blocks took their old ones' places above).
794
+ const at = this.frameAt[i];
795
+ if (!state && this.composing && at && !present.has(at.node)) state = at.state;
796
+ if (!state || (this.stale.has(node) && !this.composing)) state = whole(item.frame);
797
+ frames.set(node, state);
798
+ const pagesBefore = before ?? (state === at?.state ? state.pages : undefined);
799
+ return state.wrappers.map((_, f) => (last = Math.max(last, pagesBefore?.[f] ?? last)));
800
+ }
801
+ const desc = blocks[item.unit] as WordBlockDesc;
541
802
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
542
803
  });
543
804
  pages = separateSheets(pages, layout);
544
- this.place(blocks, pages, layout);
805
+ const elementsOf = (item: FlowItem, i: number): readonly HTMLElement[] =>
806
+ item.frame
807
+ ? (frames.get(doc.child(i)) as FrameState).wrappers
808
+ : (blocks[item.unit] as WordBlockDesc).fragments;
809
+ this.place(
810
+ items.map((item, i) => elementsOf(item, i)),
811
+ pages,
812
+ layout,
813
+ );
545
814
  if (!this.composing) {
546
815
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
547
816
  let scale: number | undefined;
@@ -554,7 +823,7 @@ export class EditorView {
554
823
  const measure = this.measures.get(desc.node);
555
824
  if (measure) delete measure.lines;
556
825
  }
557
- const nodes = blocks.map((desc) => desc.node);
826
+ const nodes = items.map((_, i) => doc.child(i));
558
827
  // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
559
828
  const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
560
829
  const measureOf = (desc: BlockDesc) => {
@@ -571,33 +840,141 @@ export class EditorView {
571
840
  found.lines ??= measureLines(desc, layoutPx());
572
841
  return found.lines;
573
842
  };
574
- const boxes = blocks.map((desc, i) =>
575
- wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i] as BlockLayout),
843
+ const tableOf = (frame: Frame, i: number) => {
844
+ let found = this.measures.get(frame.node);
845
+ if (!found?.table || this.stale.delete(frame.node)) {
846
+ const wrapper = (frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement;
847
+ // Its blocks are measured with it (their heights, for a resize later).
848
+ for (let u = frame.first; u < frame.end; u++) {
849
+ const desc = blocks[u] as WordBlockDesc;
850
+ this.stale.delete(desc.node);
851
+ this.measures.set(desc.node, measureBox(desc, layoutPx()));
852
+ }
853
+ found = measureTable(frame, wrapper, blocks, layoutPx());
854
+ this.measures.set(frame.node, found);
855
+ }
856
+ return found;
857
+ };
858
+ const words = items.map((item) =>
859
+ item.frame ? TABLE_WORD : (blocks[item.unit] as WordBlockDesc).word,
576
860
  );
861
+ const boxes = items.map((item, i) => {
862
+ const pageHeight = contentHeight((layout[i] as BlockLayout).sheet.settings);
863
+ if (item.frame) {
864
+ const frame = item.frame;
865
+ const measure = tableOf(frame, i);
866
+ // A section break after it, or a page break before the next paragraph, ends its page.
867
+ const breakAfter =
868
+ (layout[i] as BlockLayout).breakAfter || !!words[i + 1]?.pageBreakBefore;
869
+ return tableBox(frame, measure, pageHeight, breakAfter, () =>
870
+ breaksOf(frame, measure, blocks, pageHeight, lines),
871
+ );
872
+ }
873
+ const desc = blocks[item.unit] as WordBlockDesc;
874
+ return wordBox(
875
+ words,
876
+ i,
877
+ desc,
878
+ measureOf(desc),
879
+ () => lines(desc),
880
+ layout[i] as BlockLayout,
881
+ );
882
+ });
577
883
  const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
578
884
  this.flowed = { nodes, result };
579
885
  this.stale.clear();
580
886
  const flowed = result.fragments;
581
- blocks = blocks.map((desc, i) => {
887
+ // Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
888
+ // and their blocks split where a row is.
889
+ const splitsOf = new Map<number, number[]>();
890
+ const parts = new Map<number, { parts: TablePart[]; partOf: Map<number, number[]> }>();
891
+ items.forEach((item, i) => {
582
892
  const fragments = flowed[i] ?? [];
583
- const contentStart = (starts[i] as number) + 1;
584
- const splits = fragments.slice(1).map((fragment) => {
585
- const offset = lines(desc).starts[fragment.fromLine] as number;
586
- // Never split a grapheme cluster across pages.
587
- return clusterBoundary(doc, contentStart + offset, false) - contentStart;
588
- });
893
+ if (item.unit !== undefined) {
894
+ const desc = blocks[item.unit] as WordBlockDesc;
895
+ const contentStart = ((units[item.unit] as Unit).pos as number) + 1;
896
+ splitsOf.set(
897
+ item.unit,
898
+ fragments.slice(1).map((fragment) => {
899
+ const offset = lines(desc).starts[fragment.fromLine] as number;
900
+ // Never split a grapheme cluster across pages.
901
+ return clusterBoundary(doc, contentStart + offset, false) - contentStart;
902
+ }),
903
+ );
904
+ return;
905
+ }
906
+ const frame = item.frame;
907
+ const measure = this.measures.get(frame.node) as Measure;
908
+ const cut = cutTable(frame, measure, fragments, blocks, lines);
909
+ parts.set(i, cut);
910
+ for (const [u, at] of cut.splits) {
911
+ const contentStart = (units[u] as Unit).pos + 1;
912
+ splitsOf.set(
913
+ u,
914
+ at.map((offset) => clusterBoundary(doc, contentStart + offset, false) - contentStart),
915
+ );
916
+ }
917
+ });
918
+ blocks = blocks.map((desc, u) => {
919
+ const splits = splitsOf.get(u) ?? [];
589
920
  const same =
590
921
  splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
591
- return same ? desc : word.render(desc.node, i, splits);
922
+ return same ? desc : word.render(desc.node, u, splits, (units[u] as Unit).cell);
592
923
  });
593
- pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
594
- applyGaps(blocks, pages, boxes);
595
- this.place(blocks, pages, layout);
924
+ pages = items.map((item, i) => {
925
+ const fragments = flowed[i] ?? [];
926
+ if (!item.frame) return fragments.map((fragment) => fragment.page);
927
+ const node = doc.child(i);
928
+ const cut = parts.get(i) as { parts: TablePart[]; partOf: Map<number, number[]> };
929
+ const key = JSON.stringify([cut.parts, [...cut.partOf]]);
930
+ const kept = frames.get(node) as FrameState;
931
+ const pagesOf = fragments.map((fragment) => fragment.page);
932
+ // The same cut of the same table, its blocks' elements all in it: its wrappers stay.
933
+ if (kept.key === key && holdsAll(kept, item.frame, blocks)) {
934
+ frames.set(node, { ...kept, pages: pagesOf });
935
+ return pagesOf;
936
+ }
937
+ const wrappers = cut.parts.map((part, k) =>
938
+ frameElement(
939
+ item.frame,
940
+ part.rows,
941
+ part.headers,
942
+ (r, c) =>
943
+ this.cellContent(item.frame, r, c, blocks, (u, f) => cut.partOf.get(u)?.[f] === k),
944
+ doc_,
945
+ ),
946
+ );
947
+ frames.set(node, { wrappers, pages: pagesOf, key });
948
+ return pagesOf;
949
+ });
950
+ const firsts = items.map((item, i) =>
951
+ item.frame
952
+ ? ((frames.get(doc.child(i)) as FrameState).wrappers[0] as HTMLElement)
953
+ : (blocks[item.unit] as WordBlockDesc).dom,
954
+ );
955
+ applyGaps(firsts, pages, boxes);
956
+ this.place(
957
+ items.map((item, i) => elementsOf(item, i)),
958
+ pages,
959
+ layout,
960
+ );
596
961
  }
962
+ // (Wrappers no longer drawn are not in a page: `place` removed them.)
963
+ this.frames = frames;
964
+ this.frameAt = items.map((item, i) => {
965
+ const state = item.frame && frames.get(doc.child(i));
966
+ return state ? { node: doc.child(i), state } : undefined;
967
+ });
968
+ this.frameOf = new Map();
969
+ items.forEach((item, i) => {
970
+ if (!item.frame) return;
971
+ for (const wrapper of (frames.get(doc.child(i)) as FrameState).wrappers)
972
+ this.frameOf.set(wrapper, item.frame);
973
+ });
597
974
  this.blocks = blocks;
598
- this.starts = starts;
975
+ this.starts = units.map((unit) => unit.pos);
599
976
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
600
- this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
977
+ this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
601
978
  this.owner = new Map(
602
979
  blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc] as const)),
603
980
  );
@@ -611,6 +988,43 @@ export class EditorView {
611
988
  if (this.composing) this.pending.push(...records);
612
989
  }
613
990
 
991
+ /**
992
+ * A floating picture reaches into the blocks after its paragraph (their lines go around it):
993
+ * a block that changed (new, drawn again or stale) on a page holding one has the blocks after
994
+ * it on that page and the next measured again. A new block counts on the page of the block
995
+ * before it, where `place` first puts it, and the next (it may have been that page's first);
996
+ * only blocks that changed reach on, not the ones this marks, so an edit re-measures three
997
+ * pages at most.
998
+ */
999
+ private staleAroundFloats(
1000
+ doc: ModelNode,
1001
+ pagesOf: ReadonlyMap<ModelNode, readonly number[]>,
1002
+ redrawn: ReadonlySet<ModelNode>,
1003
+ ): void {
1004
+ const blocks: { node: ModelNode; pages: readonly number[]; changed: boolean }[] = [];
1005
+ let last = 0;
1006
+ doc.forEach((node) => {
1007
+ const known = pagesOf.get(node);
1008
+ const pages = known?.length ? known : [last, last + 1];
1009
+ last = known?.length ? (known[known.length - 1] as number) : last;
1010
+ blocks.push({ node, pages, changed: !known || redrawn.has(node) || this.stale.has(node) });
1011
+ });
1012
+ // The pages floats are on now, and were on before (a float deleted or made inline leaves
1013
+ // lines that went around it).
1014
+ const floatPages = new Set<number>();
1015
+ for (const { node, pages } of blocks)
1016
+ if (holdsFloat(node)) for (const p of pages) floatPages.add(p);
1017
+ for (const [node, pages] of pagesOf)
1018
+ if (holdsFloat(node)) for (const p of pages) floatPages.add(p);
1019
+ if (!floatPages.size) return;
1020
+ let reach = -1;
1021
+ for (const { node, pages, changed } of blocks) {
1022
+ if ((pages[0] as number) <= reach) this.stale.add(node);
1023
+ if (changed && pages.some((p) => floatPages.has(p)))
1024
+ reach = Math.max(reach, (pages[pages.length - 1] as number) + 1);
1025
+ }
1026
+ }
1027
+
614
1028
  /** A font's normal line height ratio, measured outside the host (no input to read back). */
615
1029
  private lineRatio = (family: string): number => {
616
1030
  let ratio = this.ratios.get(family);
@@ -629,13 +1043,13 @@ export class EditorView {
629
1043
  * or a page (stray DOM) is removed.
630
1044
  */
631
1045
  private place(
632
- blocks: readonly BlockDesc[],
1046
+ elements: readonly (readonly HTMLElement[])[],
633
1047
  pages: readonly (readonly number[])[],
634
1048
  layout: readonly BlockLayout[],
635
1049
  ): void {
636
1050
  const { host } = this;
637
- const items = blocks.flatMap((desc, i) =>
638
- desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })),
1051
+ const items = elements.flatMap((list, i) =>
1052
+ list.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })),
639
1053
  );
640
1054
  const count = (items[items.length - 1]?.page ?? 0) + 1;
641
1055
  const sheets: Sheet[] = [];
@@ -675,6 +1089,7 @@ export class EditorView {
675
1089
  while (at) {
676
1090
  const next: ChildNode | null = at.nextSibling;
677
1091
  at.remove();
1092
+ this.viewRemoved.add(at);
678
1093
  at = next;
679
1094
  }
680
1095
  }
@@ -688,6 +1103,40 @@ export class EditorView {
688
1103
  this.pages.length = count;
689
1104
  }
690
1105
 
1106
+ /**
1107
+ * What a table's cell shows in one of its fragments: its blocks' elements that `takes` puts
1108
+ * there, and nested tables whole (where their first block goes).
1109
+ */
1110
+ private cellContent(
1111
+ frame: Frame,
1112
+ r: number,
1113
+ c: number,
1114
+ blocks: readonly WordBlockDesc[],
1115
+ takes: (unit: number, fragment: number) => boolean,
1116
+ ): Node[] {
1117
+ const out: Node[] = [];
1118
+ for (const item of frame.rows[r]?.cells[c]?.items ?? []) {
1119
+ if ("frame" in item) {
1120
+ const nested = item.frame;
1121
+ if (!takes(nested.first, 0)) continue;
1122
+ out.push(
1123
+ frameElement(
1124
+ nested,
1125
+ nested.rows.map((_, i) => i),
1126
+ [],
1127
+ (rr, cc) => this.cellContent(nested, rr, cc, blocks, () => true),
1128
+ this.host.ownerDocument,
1129
+ ),
1130
+ );
1131
+ continue;
1132
+ }
1133
+ (blocks[item.unit] as WordBlockDesc).fragments.forEach((fragment, f) => {
1134
+ if (takes(item.unit, f)) out.push(fragment);
1135
+ });
1136
+ }
1137
+ return out;
1138
+ }
1139
+
691
1140
  private createPage(): HTMLElement {
692
1141
  const page = this.host.ownerDocument.createElement("section");
693
1142
  page.className = "foli-page";
@@ -809,9 +1258,18 @@ export class EditorView {
809
1258
  return null;
810
1259
  }
811
1260
 
812
- /** Whether `node` holds blocks rather than content: the host or a page. */
1261
+ /**
1262
+ * Whether `node` holds blocks rather than content: the host, a page, or a table's wrapper,
1263
+ * table, rows and cells.
1264
+ */
813
1265
  private holdsBlocks(node: Node): boolean {
814
- return node === this.host || this.pages.includes(node as HTMLElement);
1266
+ return (
1267
+ node === this.host ||
1268
+ this.pages.includes(node as HTMLElement) ||
1269
+ (node.nodeType === Node.ELEMENT_NODE &&
1270
+ (node as Element).hasAttribute(FRAME_ATTR) &&
1271
+ !(node as Element).closest(`[${REPEATED_ATTR}]`))
1272
+ );
815
1273
  }
816
1274
 
817
1275
  /** Index of the first block that starts at or after `pos` (the block count if none). */
@@ -829,17 +1287,36 @@ export class EditorView {
829
1287
  /** Model position of a DOM point inside the host, or null if it is outside. */
830
1288
  posFromDOM(node: Node, offset: number): number | null {
831
1289
  const { host } = this;
1290
+ // In a header row drawn again (not document content): the first position below it.
1291
+ const at = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
1292
+ const repeated = at?.closest(`[${REPEATED_ATTR}]`);
1293
+ if (repeated?.parentNode && host.contains(repeated)) {
1294
+ const parent = repeated.parentNode;
1295
+ return this.posFromDOM(parent, [...parent.childNodes].indexOf(repeated as ChildNode) + 1);
1296
+ }
832
1297
  if (this.holdsBlocks(node)) {
833
1298
  // Between fragments: the start of the first one after the point (a block start, or
834
1299
  // where a continuation starts), else the document end.
835
1300
  const range = host.ownerDocument.createRange();
836
1301
  range.setStart(node, offset);
1302
+ const posOf = (i: number, f: number) =>
1303
+ f === 0
1304
+ ? (this.starts[i] as number)
1305
+ : (this.starts[i] as number) +
1306
+ 1 +
1307
+ ((this.blocks[i] as BlockDesc).splits[f - 1] as number);
1308
+ // Without tables, blocks are in DOM order: the first one after the point. In a row split
1309
+ // across pages, a cell's continuation comes after the next cell: the earliest in the DOM.
1310
+ let best: { i: number; f: number; dom: HTMLElement } | null = null;
837
1311
  for (const [i, desc] of this.blocks.entries()) {
838
1312
  const f = desc.fragments.findIndex((fragment) => range.comparePoint(fragment, 0) >= 0);
839
- if (f === 0) return this.starts[i] as number;
840
- if (f > 0) return (this.starts[i] as number) + 1 + (desc.splits[f - 1] as number);
1313
+ if (f < 0) continue;
1314
+ const dom = desc.fragments[f] as HTMLElement;
1315
+ if (!this.frames.size) return posOf(i, f);
1316
+ if (!best || dom.compareDocumentPosition(best.dom) & Node.DOCUMENT_POSITION_FOLLOWING)
1317
+ best = { i, f, dom };
841
1318
  }
842
- return this.state.doc.content.size;
1319
+ return best ? posOf(best.i, best.f) : this.state.doc.content.size;
843
1320
  }
844
1321
  const element = this.blockElement(node);
845
1322
  const owner = element ? this.owner.get(element) : undefined;
@@ -885,7 +1362,9 @@ export class EditorView {
885
1362
  // browser shows it at the start of the next line at a soft wrap.
886
1363
  const split = desc.splits.indexOf(offset);
887
1364
  if (split >= 0) return fragmentStart(desc, split + 1);
888
- for (const leaf of desc.leaves) {
1365
+ // Deleted text hidden by the review view takes no caret: the shown text next to it does.
1366
+ const shown = desc.leaves.filter((leaf) => !hiddenIn(leaf.dom, desc.dom));
1367
+ for (const leaf of shown) {
889
1368
  if (
890
1369
  leaf.dom.nodeType === Node.TEXT_NODE &&
891
1370
  leaf.offset <= offset &&
@@ -893,10 +1372,15 @@ export class EditorView {
893
1372
  )
894
1373
  return { node: leaf.dom, offset: offset - leaf.offset };
895
1374
  }
896
- const next = desc.leaves.find((leaf) => leaf.offset >= offset);
897
- if (next) return before(next.dom);
898
- const last = desc.leaves[desc.leaves.length - 1];
1375
+ const next = shown.find((leaf) => leaf.offset >= offset);
1376
+ if (next) {
1377
+ if (next.dom.nodeType === Node.TEXT_NODE) return { node: next.dom, offset: 0 };
1378
+ return before(next.dom);
1379
+ }
1380
+ const last = shown[shown.length - 1];
899
1381
  if (last) {
1382
+ if (last.dom.nodeType === Node.TEXT_NODE)
1383
+ return { node: last.dom, offset: (last.dom as Text).length };
900
1384
  const point = before(last.dom);
901
1385
  return { node: point.node, offset: point.offset + 1 };
902
1386
  }
@@ -916,21 +1400,42 @@ export class EditorView {
916
1400
  // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
917
1401
  if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
918
1402
  const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
1403
+ // Around a table's (first) wrapper: the table selected whole.
1404
+ const table = child && this.frameOf.get(child);
1405
+ if (table) return NodeSelection.create(this.state.doc, table.pos);
919
1406
  const owner = child && this.owner.get(child);
920
1407
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
921
1408
  if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
922
1409
  return NodeSelection.create(this.state.doc, this.starts[index] as number);
923
1410
  }
924
- const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
925
- const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
1411
+ // Several ranges (Firefox selects table cells so, one range per cell): from the first cell
1412
+ // to the last (a range's start is in its cell; its end is after it).
1413
+ const many = sel.rangeCount > 1;
1414
+ const first = many ? sel.getRangeAt(0) : null;
1415
+ const lastRange = many ? sel.getRangeAt(sel.rangeCount - 1) : null;
1416
+ const anchor = first
1417
+ ? this.posFromDOM(first.startContainer, first.startOffset)
1418
+ : this.posFromDOM(sel.anchorNode, sel.anchorOffset);
1419
+ const head = lastRange
1420
+ ? this.posFromDOM(lastRange.startContainer, lastRange.startOffset)
1421
+ : this.posFromDOM(sel.focusNode, sel.focusOffset);
926
1422
  if (anchor === null || head === null) return null;
927
1423
  const { doc } = this.state;
1424
+ // The caret the view wrote for a cell selection (in its head cell): that selection.
1425
+ const current = this.state.selection;
1426
+ if (current instanceof CellSelection && anchor === head && anchor === this.cellCaret)
1427
+ return current;
1428
+ // Ends in two cells of one table: the cells between them.
1429
+ const a = cellAround(doc, anchor);
1430
+ const h = cellAround(doc, head);
1431
+ if (a && h && a.cell !== h.cell && a.table === h.table)
1432
+ return CellSelection.create(doc, a.cell, h.cell);
928
1433
  // Exactly around a selectable block leaf (a rule): the node selection that wrote it.
929
1434
  const from = Math.min(anchor, head);
930
1435
  const node = doc.nodeAt(from);
931
1436
  if (
932
1437
  node &&
933
- node.isBlock &&
1438
+ (node.isBlock || node.type.name === "picture") &&
934
1439
  node.isAtom &&
935
1440
  Math.max(anchor, head) === from + node.nodeSize &&
936
1441
  NodeSelection.isSelectable(node)
@@ -947,9 +1452,71 @@ export class EditorView {
947
1452
  return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
948
1453
  }
949
1454
 
1455
+ /** The span of the picture a node selection selects, if it selects one. */
1456
+ private pictureSpan(pos: number): HTMLElement | null {
1457
+ for (const img of this.host.querySelectorAll(`[${PICTURE_ATTR}]`)) {
1458
+ const span = img.parentElement;
1459
+ // A floating picture's place in the text is its anchor.
1460
+ if (span && this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0) === pos) return span;
1461
+ }
1462
+ return null;
1463
+ }
1464
+
1465
+ /** Marks the selected picture and gives it a resize handle (when the document is editable). */
1466
+ private showSelectedPicture(): void {
1467
+ const { selection } = this.state;
1468
+ const span =
1469
+ selection instanceof NodeSelection && selection.node.type.name === "picture"
1470
+ ? this.pictureSpan(selection.from)
1471
+ : null;
1472
+ const handled = !!span?.querySelector("[data-foli-resize]");
1473
+ if (span === this.selectedPicture && (!span || handled === this.editable)) return;
1474
+ this.selectedPicture?.removeAttribute(PICTURE_SELECTED_ATTR);
1475
+ this.selectedPicture?.querySelector("[data-foli-resize]")?.remove();
1476
+ this.selectedPicture = span;
1477
+ if (!span) return;
1478
+ injectStyles(this.host);
1479
+ span.setAttribute(PICTURE_SELECTED_ATTR, "");
1480
+ if (!this.editable) return;
1481
+ const handle = this.host.ownerDocument.createElement("span");
1482
+ handle.setAttribute("data-foli-resize", "");
1483
+ handle.setAttribute("aria-hidden", "true");
1484
+ span.append(handle);
1485
+ }
1486
+
1487
+ /** Marks the cells of a cell selection (their table cell elements, on every page). */
1488
+ private showSelectedCells(): void {
1489
+ const { selection } = this.state;
1490
+ const cells: HTMLElement[] = [];
1491
+ if (selection instanceof CellSelection) {
1492
+ for (const pos of selection.cells) {
1493
+ const caret = Selection.near(this.state.doc.resolve(pos + 1), 1).from;
1494
+ const { node } = this.domFromPos(caret);
1495
+ const element =
1496
+ node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement;
1497
+ const td = element?.closest("td");
1498
+ if (td instanceof HTMLElement) cells.push(td);
1499
+ }
1500
+ }
1501
+ for (const td of this.selectedCells) if (!cells.includes(td)) td.classList.remove(CELL_CLASS);
1502
+ for (const td of cells) td.classList.add(CELL_CLASS);
1503
+ this.selectedCells = cells;
1504
+ this.host.toggleAttribute(CELLS_ATTR, cells.length > 0);
1505
+ if (cells.length) injectStyles(this.host);
1506
+ }
1507
+
1508
+ /** The first wrapper of a node-selected table, if a table is selected. */
1509
+ private selectedTable(): HTMLElement | null {
1510
+ const { selection } = this.state;
1511
+ if (!(selection instanceof NodeSelection) || selection.node.type.name !== "table") return null;
1512
+ return this.frames.get(selection.node)?.wrappers[0] ?? null;
1513
+ }
1514
+
950
1515
  /** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
951
1516
  private showSelectedNode(): void {
952
- const dom = this.selectedBlock()?.dom ?? null;
1517
+ this.showSelectedCells();
1518
+ this.showSelectedPicture();
1519
+ const dom = this.selectedBlock()?.dom ?? this.selectedTable();
953
1520
  if (dom === this.selectedDom) return;
954
1521
  this.selectedDom?.classList.remove(SELECTED_CLASS);
955
1522
  dom?.classList.add(SELECTED_CLASS);
@@ -995,12 +1562,20 @@ export class EditorView {
995
1562
  const current = this.readSelection();
996
1563
  if (current && this.shows(current)) return;
997
1564
  }
998
- const selected = this.selectedBlock();
1565
+ const selected = this.selectedBlock()?.dom ?? this.selectedTable();
999
1566
  if (selected) {
1000
- const point = before(selected.dom);
1567
+ const point = before(selected);
1001
1568
  sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
1002
1569
  return;
1003
1570
  }
1571
+ // Cells: drawn by their class; the native caret stays in the head cell (ADR-0006).
1572
+ if (selection instanceof CellSelection) {
1573
+ const caret = Selection.near(doc.resolve(selection.head + 1), 1).from;
1574
+ this.cellCaret = caret;
1575
+ const point = this.domFromPos(caret);
1576
+ sel.collapse(point.node, point.offset);
1577
+ return;
1578
+ }
1004
1579
  // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
1005
1580
  // The model takes the snapped selection back on its next read of the DOM.
1006
1581
  const from = clusterBoundary(doc, selection.from, false);
@@ -1114,6 +1689,397 @@ export class EditorView {
1114
1689
  });
1115
1690
  }
1116
1691
 
1692
+ // ---------- column borders (10.7c) ----------
1693
+
1694
+ /** A column border being dragged: its table and column, the column's width, the press, the guide. */
1695
+ private drag: {
1696
+ table: ModelNode;
1697
+ column: number;
1698
+ width: number;
1699
+ startX: number;
1700
+ perTwip: number;
1701
+ guide: HTMLElement;
1702
+ } | null = null;
1703
+ /** Whether this view set the host's cursor (an embedder's own cursor is left alone). */
1704
+ private resizeCursor = false;
1705
+
1706
+ /**
1707
+ * The column border of a top-level table near the pointer (within 4 px): an edge of the cell
1708
+ * under it (a grid line through a merged cell is no border), or the table's right edge from
1709
+ * outside; as the grid column left of it, with the table's px per twip. None in read-only
1710
+ * mode, during a composition, or while tracking (column widths do not change then).
1711
+ */
1712
+ private columnBorder(
1713
+ event: MouseEvent,
1714
+ ): { table: ModelNode; column: number; perTwip: number; rect: DOMRect } | null {
1715
+ if (!this.editable || this.composing || trackState(this.state)?.on) return null;
1716
+ const target = event.target as Element | null;
1717
+ const wrapper = target?.closest?.(`[${FRAME_ATTR}="table"]`);
1718
+ const element = wrapper?.querySelector(`:scope > table[${FRAME_ATTR}]`);
1719
+ if (!wrapper || !element || !this.host.contains(wrapper)) return null;
1720
+ let table: ModelNode | undefined;
1721
+ for (const [node, frame] of this.frames)
1722
+ if (frame.wrappers.includes(wrapper as HTMLElement)) table = node;
1723
+ const grid = (table?.attrs.grid as number[] | undefined) ?? [];
1724
+ const total = grid.reduce((a, b) => a + b, 0);
1725
+ if (!table || !total) return null;
1726
+ const rect = element.getBoundingClientRect();
1727
+ const perTwip = rect.width / total;
1728
+ const edges: number[] = [];
1729
+ let x = rect.left;
1730
+ for (const width of grid) {
1731
+ x += width * perTwip;
1732
+ edges.push(x);
1733
+ }
1734
+ const near = (column: number) => Math.abs(event.clientX - (edges[column] as number)) <= 4;
1735
+ // The grid lines that are borders here: the cell's own edges, the table's right edge from
1736
+ // outside it, any line on the table's own border area (none in a row's empty places).
1737
+ const cell = target?.closest("td");
1738
+ let columns: number[];
1739
+ if (cell && element.contains(cell)) {
1740
+ const box = cell.getBoundingClientRect();
1741
+ const at = (line: number) => edges.findIndex((edge) => Math.abs(edge - line) <= 3);
1742
+ columns = [at(box.left), at(box.right)].filter((c) => c >= 0);
1743
+ } else if (target === element) columns = grid.map((_w, i) => i);
1744
+ else if (element.contains(target)) columns = [];
1745
+ else columns = [grid.length - 1];
1746
+ const column = columns.find(near);
1747
+ return column === undefined ? null : { table, column, perTwip, rect };
1748
+ }
1749
+
1750
+ /** The pointer over a column border shows that it can be dragged. */
1751
+ private onMouseMove = (event: MouseEvent): void => {
1752
+ if (this.drag) return;
1753
+ const near = event.buttons === 0 && this.columnBorder(event) !== null;
1754
+ if (near === this.resizeCursor) return;
1755
+ this.resizeCursor = near;
1756
+ this.host.style.cursor = near ? "col-resize" : "";
1757
+ };
1758
+
1759
+ /**
1760
+ * A press on a column border (no Shift: Shift-click extends the selection) starts dragging it:
1761
+ * a guide line follows the pointer and the release moves the border by as much as the pointer
1762
+ * moved (`setColumnWidth`); a press without a move changes nothing; Escape, the button let go
1763
+ * elsewhere or the window losing the focus cancel.
1764
+ */
1765
+ private startColumnDrag(event: MouseEvent): boolean {
1766
+ this.endDrag();
1767
+ if (event.shiftKey) return false;
1768
+ const border = this.columnBorder(event);
1769
+ if (!border) return false;
1770
+ // No caret or text selection from this press. Focus taken by it keeps the selection the
1771
+ // model has (the press places none).
1772
+ event.preventDefault();
1773
+ if (!this.hasFocus()) {
1774
+ this.host.focus({ preventScroll: true });
1775
+ this.writeSelection(true);
1776
+ }
1777
+ const doc = this.host.ownerDocument;
1778
+ const guide = doc.createElement("div");
1779
+ guide.setAttribute("aria-hidden", "true");
1780
+ Object.assign(guide.style, {
1781
+ position: "fixed",
1782
+ top: `${border.rect.top}px`,
1783
+ height: `${border.rect.height}px`,
1784
+ left: `${event.clientX}px`,
1785
+ width: "0",
1786
+ borderLeft: "1px dashed GrayText",
1787
+ pointerEvents: "none",
1788
+ zIndex: "2147483647",
1789
+ });
1790
+ doc.body.append(guide);
1791
+ const width = (border.table.attrs.grid as number[])[border.column] as number;
1792
+ this.drag = { ...border, width, startX: event.clientX, guide };
1793
+ doc.addEventListener("mousemove", this.onDragMove);
1794
+ doc.addEventListener("mouseup", this.onDragEnd);
1795
+ doc.addEventListener("keydown", this.onDragKey, true);
1796
+ doc.defaultView?.addEventListener("blur", this.onDragBlur);
1797
+ return true;
1798
+ }
1799
+
1800
+ private onDragMove = (event: MouseEvent): void => {
1801
+ if (!this.drag) return;
1802
+ // The button let go where no mouseup reached the page (another window, a menu): cancelled.
1803
+ if ((event.buttons & 1) === 0) this.endDrag();
1804
+ else this.drag.guide.style.left = `${event.clientX}px`;
1805
+ };
1806
+
1807
+ private onDragEnd = (event: MouseEvent): void => {
1808
+ const drag = this.endDrag();
1809
+ if (!drag) return;
1810
+ const moved = event.clientX - drag.startX;
1811
+ // A click on a border (no real move) is no resize.
1812
+ if (Math.abs(moved) < 2) return;
1813
+ // The table's position: a top-level block's.
1814
+ let pos = -1;
1815
+ this.state.doc.forEach((node, offset) => {
1816
+ if (node === drag.table) pos = offset;
1817
+ });
1818
+ if (pos >= 0) this.run(setColumnWidth(pos, drag.column, drag.width + moved / drag.perTwip));
1819
+ };
1820
+
1821
+ private onDragKey = (event: KeyboardEvent): void => {
1822
+ if (event.key !== "Escape") return;
1823
+ event.preventDefault();
1824
+ event.stopPropagation();
1825
+ this.endDrag();
1826
+ };
1827
+
1828
+ private onDragBlur = (): void => {
1829
+ this.endDrag();
1830
+ };
1831
+
1832
+ /** Ends a drag (its guide and listeners gone) and returns it. */
1833
+ private endDrag(): NonNullable<EditorView["drag"]> | null {
1834
+ const { drag } = this;
1835
+ if (!drag) return null;
1836
+ this.drag = null;
1837
+ drag.guide.remove();
1838
+ const doc = this.host.ownerDocument;
1839
+ doc.removeEventListener("mousemove", this.onDragMove);
1840
+ doc.removeEventListener("mouseup", this.onDragEnd);
1841
+ doc.removeEventListener("keydown", this.onDragKey, true);
1842
+ doc.defaultView?.removeEventListener("blur", this.onDragBlur);
1843
+ if (this.resizeCursor) {
1844
+ this.resizeCursor = false;
1845
+ this.host.style.cursor = "";
1846
+ }
1847
+ return drag;
1848
+ }
1849
+
1850
+ // ---------- pictures (10.8d) ----------
1851
+
1852
+ /**
1853
+ * A press on a picture selects it (a node selection); on the selected picture's handle it
1854
+ * starts a resize that keeps its aspect ratio (`setPictureSize` on release, Escape cancels).
1855
+ */
1856
+ private pictureMouseDown(event: MouseEvent): boolean {
1857
+ this.endResize();
1858
+ if (event.shiftKey || this.composing) return false;
1859
+ const target = event.target as Element | null;
1860
+ const span = target?.closest?.(`[${PICTURE_ATTR}], [data-foli-resize]`)?.parentElement ?? null;
1861
+ if (!span || !this.host.contains(span)) return false;
1862
+ const pos = this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0);
1863
+ if (pos === null) return false;
1864
+ event.preventDefault();
1865
+ if (!this.hasFocus()) this.host.focus({ preventScroll: true });
1866
+ if (!(this.state.selection instanceof NodeSelection && this.state.selection.from === pos))
1867
+ this.dispatch(this.state.tr.setSelection(NodeSelection.create(this.state.doc, pos)));
1868
+ // Already selected: written again (the focus may have put a caret in the host).
1869
+ else this.writeSelection(true);
1870
+ const img = span.querySelector(`[${PICTURE_ATTR}]`) as HTMLElement | null;
1871
+ if (!img || !target?.closest("[data-foli-resize]") || !this.editable) return true;
1872
+ const rect = img.getBoundingClientRect();
1873
+ const width = Number.parseFloat(img.style.width) || rect.width;
1874
+ const scale = rect.width / width || 1;
1875
+ this.resize = {
1876
+ pos,
1877
+ img,
1878
+ width: rect.width,
1879
+ height: rect.height,
1880
+ scale,
1881
+ // No wider than the page's text (layout px).
1882
+ max: Math.max(this.textWidthEmu() / EMU_PER_PX, MIN_PICTURE),
1883
+ x: event.clientX,
1884
+ y: event.clientY,
1885
+ style: img.getAttribute("style") ?? "",
1886
+ };
1887
+ const doc = this.host.ownerDocument;
1888
+ doc.addEventListener("mousemove", this.onResizeMove);
1889
+ doc.addEventListener("mouseup", this.onResizeEnd);
1890
+ doc.addEventListener("keydown", this.onResizeKey, true);
1891
+ doc.defaultView?.addEventListener("blur", this.onResizeCancel);
1892
+ return true;
1893
+ }
1894
+
1895
+ /** The size (layout px) a resize gives at the pointer: the larger move, the ratio kept. */
1896
+ private resizedTo(event: MouseEvent): { width: number; height: number } {
1897
+ const r = this.resize as NonNullable<EditorView["resize"]>;
1898
+ const ratio = r.height / r.width;
1899
+ const dx = event.clientX - r.x;
1900
+ const dy = (event.clientY - r.y) / ratio;
1901
+ const width = Math.min(
1902
+ Math.max((r.width + (Math.abs(dx) > Math.abs(dy) ? dx : dy)) / r.scale, MIN_PICTURE),
1903
+ r.max,
1904
+ );
1905
+ return { width, height: width * ratio };
1906
+ }
1907
+
1908
+ private onResizeMove = (event: MouseEvent): void => {
1909
+ if (!this.resize) return;
1910
+ if ((event.buttons & 1) === 0) {
1911
+ this.onResizeCancel();
1912
+ return;
1913
+ }
1914
+ const { width, height } = this.resizedTo(event);
1915
+ this.resize.img.style.width = `${width}px`;
1916
+ this.resize.img.style.height = `${height}px`;
1917
+ };
1918
+
1919
+ private onResizeEnd = (event: MouseEvent): void => {
1920
+ if (!this.resize) return;
1921
+ const { width, height } = this.resizedTo(event);
1922
+ const r = this.endResize();
1923
+ if (!r) return;
1924
+ // No real move: nothing changes (a jiggle drawn while moving goes back).
1925
+ const moved = Math.abs(event.clientX - r.x) >= 2 || Math.abs(event.clientY - r.y) >= 2;
1926
+ const applied =
1927
+ moved &&
1928
+ this.run(
1929
+ setPictureSize(r.pos, Math.round(width * EMU_PER_PX), Math.round(height * EMU_PER_PX)),
1930
+ );
1931
+ // Not applied (no move, tracking, the picture gone): as it was.
1932
+ if (!applied) r.img.setAttribute("style", r.style);
1933
+ };
1934
+
1935
+ private onResizeKey = (event: KeyboardEvent): void => {
1936
+ if (event.key !== "Escape") return;
1937
+ event.preventDefault();
1938
+ event.stopPropagation();
1939
+ this.onResizeCancel();
1940
+ };
1941
+
1942
+ private onResizeCancel = (): void => {
1943
+ const r = this.endResize();
1944
+ if (r) r.img.setAttribute("style", r.style);
1945
+ };
1946
+
1947
+ /** Ends a resize (its listeners gone) and returns it. */
1948
+ private endResize(): NonNullable<EditorView["resize"]> | null {
1949
+ const r = this.resize;
1950
+ if (!r) return null;
1951
+ this.resize = null;
1952
+ const doc = this.host.ownerDocument;
1953
+ doc.removeEventListener("mousemove", this.onResizeMove);
1954
+ doc.removeEventListener("mouseup", this.onResizeEnd);
1955
+ doc.removeEventListener("keydown", this.onResizeKey, true);
1956
+ doc.defaultView?.removeEventListener("blur", this.onResizeCancel);
1957
+ return r;
1958
+ }
1959
+
1960
+ private textWidthEmu(): number {
1961
+ return textWidthEmu(this.state);
1962
+ }
1963
+
1964
+ /** Image files in a transfer (paste or drop), when the app takes uploads. */
1965
+ private imageFiles(data: DataTransfer | null): File[] {
1966
+ if (!this.upload || !this.editable || !data) return [];
1967
+ // A clipboard object from code may have no files.
1968
+ return [...(data.files ?? [])].filter((file) => file.type.startsWith("image/"));
1969
+ }
1970
+
1971
+ /** Whether a drag carries files (from outside the page). */
1972
+ private static carriesFiles = (event: DragEvent) =>
1973
+ [...(event.dataTransfer?.types ?? [])].includes("Files");
1974
+
1975
+ private onDragOver = (event: DragEvent): void => {
1976
+ if (!EditorView.carriesFiles(event)) return;
1977
+ // Files dropped here never open in the page (unsaved work would be lost).
1978
+ event.preventDefault();
1979
+ const images = [...(event.dataTransfer?.items ?? [])].some((i) => i.type.startsWith("image/"));
1980
+ if (event.dataTransfer)
1981
+ event.dataTransfer.dropEffect = images && this.upload && this.editable ? "copy" : "none";
1982
+ };
1983
+
1984
+ private onDrop = (event: DragEvent): void => {
1985
+ if (!EditorView.carriesFiles(event)) return;
1986
+ event.preventDefault();
1987
+ const files = this.imageFiles(event.dataTransfer);
1988
+ if (!files.length || this.composing) return;
1989
+ // The place the files were dropped.
1990
+ const doc = this.host.ownerDocument as Document & {
1991
+ caretPositionFromPoint?: (
1992
+ x: number,
1993
+ y: number,
1994
+ ) => { offsetNode: Node; offset: number } | null;
1995
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
1996
+ };
1997
+ const point = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
1998
+ const range = point ? null : doc.caretRangeFromPoint?.(event.clientX, event.clientY);
1999
+ const node = point?.offsetNode ?? range?.startContainer;
2000
+ const offset = point?.offset ?? range?.startOffset ?? 0;
2001
+ const pos = node ? this.posFromDOM(node, offset) : null;
2002
+ if (pos !== null)
2003
+ this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
2004
+ void this.insertFiles(files);
2005
+ };
2006
+
2007
+ /**
2008
+ * Inserts image files where the selection is now, one picture each, in order: each measured
2009
+ * first (one the browser cannot show is skipped, not uploaded), then given to the `upload`
2010
+ * option, then inserted at its natural size (96 px per inch) no wider than the page's text,
2011
+ * where the selection was, however the document changed meanwhile (after a composition that
2012
+ * runs then). A file whose upload fails is skipped (reported on the console). Resolves to
2013
+ * the number inserted (none without `upload`); never rejects.
2014
+ */
2015
+ async insertFiles(files: readonly File[]): Promise<number> {
2016
+ const upload = this.upload;
2017
+ if (!upload || !this.editable) return 0;
2018
+ // The insertion point, mapped through every change until the pictures go in.
2019
+ let at = this.state.selection.from;
2020
+ const replace = !this.state.selection.empty;
2021
+ // Another document (`setDocument` notifies with no transaction): the files are not for it.
2022
+ let lost = false;
2023
+ let mapped = this.state.doc;
2024
+ // The user's own selection while a picture goes in, mapped, to give back after it.
2025
+ let user: Selection | null = null;
2026
+ const unsubscribe = this.editor.subscribe((state, transactions) => {
2027
+ for (const tr of transactions) {
2028
+ at = tr.mapping.map(at);
2029
+ if (user) user = user.map(tr.doc, tr.mapping);
2030
+ }
2031
+ if (!transactions.length && state.doc !== mapped) lost = true;
2032
+ mapped = state.doc;
2033
+ });
2034
+ let inserted = 0;
2035
+ try {
2036
+ for (const file of files) {
2037
+ if (!file.type.startsWith("image/")) continue;
2038
+ const size = await measureImageFile(file, this.host.ownerDocument);
2039
+ if (this.destroyed) return inserted;
2040
+ if (!size) continue;
2041
+ let answer: Awaited<ReturnType<NonNullable<EditorViewOptions["upload"]>>>;
2042
+ try {
2043
+ answer = await upload(file);
2044
+ } catch (error) {
2045
+ console.warn(`Foli: the upload of ${file.name} failed`, error);
2046
+ continue;
2047
+ }
2048
+ const { src, alt, decorative } =
2049
+ typeof answer === "string" ? { src: answer } : (answer ?? { src: "" });
2050
+ if (typeof src !== "string" || !src) continue;
2051
+ // The browser owns the DOM during a composition: the picture goes in after it.
2052
+ while (this.composing && !this.destroyed) await new Promise((r) => setTimeout(r, 50));
2053
+ if (this.destroyed || !this.editable || lost) return inserted;
2054
+ const scale = Math.min(1, this.textWidthEmu() / (size.width * EMU_PER_PX));
2055
+ // A `data:` URL says its own type (an app may have converted the file).
2056
+ const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
2057
+ const picture = {
2058
+ contentType: type,
2059
+ ...(src.startsWith("data:") ? { data: src } : { url: src }),
2060
+ width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
2061
+ height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
2062
+ ...(typeof alt === "string" && alt.trim() ? { alt } : {}),
2063
+ ...(decorative === true ? { decorative } : {}),
2064
+ };
2065
+ const { doc, selection } = this.state;
2066
+ const pos = Math.min(at, doc.content.size);
2067
+ // The first picture replaces what was selected at the paste (still selected there).
2068
+ const here = replace && inserted === 0 && selection.from === pos;
2069
+ // A caret the user moved elsewhere meanwhile stays there.
2070
+ const elsewhere = !here && !(selection.empty && selection.from === pos);
2071
+ user = elsewhere ? selection : null;
2072
+ if (!here) this.dispatch(this.state.tr.setSelection(TextSelection.near(doc.resolve(pos))));
2073
+ if (this.run(insertPicture(picture, { requireAlt: false }))) inserted++;
2074
+ if (user) this.dispatch(this.state.tr.setSelection(user));
2075
+ user = null;
2076
+ }
2077
+ return inserted;
2078
+ } finally {
2079
+ unsubscribe();
2080
+ }
2081
+ }
2082
+
1117
2083
  /**
1118
2084
  * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
1119
2085
  * selection to the start of the next block, so typing over it would merge the two blocks.
@@ -1124,6 +2090,22 @@ export class EditorView {
1124
2090
  // focuses nothing (prevented, middle button) must not skip the next keyboard focus.
1125
2091
  if (this.pointerFocus) setTimeout(() => (this.pointerFocus = false));
1126
2092
  if (event.button !== 0) return;
2093
+ if (this.startColumnDrag(event)) return;
2094
+ if (this.pictureMouseDown(event)) return;
2095
+ // A click puts a caret where it lands, even on the one a cell selection wrote.
2096
+ if (!event.shiftKey) this.cellCaret = null;
2097
+ // A header row drawn again is not document content: the caret goes below it.
2098
+ const repeated = (event.target as Element | null)?.closest?.(`[${REPEATED_ATTR}]`);
2099
+ if (repeated && this.host.contains(repeated) && !event.shiftKey) {
2100
+ const pos = this.posFromDOM(repeated, 0);
2101
+ if (pos !== null) {
2102
+ event.preventDefault();
2103
+ if (!this.hasFocus()) this.host.focus({ preventScroll: true });
2104
+ const $pos = this.state.doc.resolve(pos);
2105
+ this.dispatch(this.state.tr.setSelection(Selection.near($pos)));
2106
+ }
2107
+ return;
2108
+ }
1127
2109
  const element = this.blockElement(event.target as Node | null);
1128
2110
  const owner = element ? this.owner.get(element) : undefined;
1129
2111
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
@@ -1195,7 +2177,36 @@ export class EditorView {
1195
2177
  }
1196
2178
  // Up/Down on a textblock's first/last line next to a rule select it (only the view knows
1197
2179
  // lines; measured only when a rule is beside the block); else the browser moves the caret.
2180
+ // Shift+arrows in a table: cells selected grow by a cell; from text in a cell, Shift+Up or
2181
+ // Down starts a cell selection once the head is on the cell's first or last line.
2182
+ const shift: Record<string, ["row" | "column", -1 | 1]> = {
2183
+ "Shift-ArrowUp": ["row", -1],
2184
+ "Shift-ArrowDown": ["row", 1],
2185
+ "Shift-ArrowLeft": ["column", -1],
2186
+ "Shift-ArrowRight": ["column", 1],
2187
+ };
2188
+ const growing = Object.hasOwn(shift, name) ? shift[name] : undefined;
2189
+ if (growing) {
2190
+ const [axis, dir] = growing;
2191
+ const grow = extendCellSelection(axis, dir);
2192
+ const leaving =
2193
+ this.state.selection instanceof CellSelection ||
2194
+ (axis === "row" && this.caretOnEdgeLine(dir, true));
2195
+ if (leaving && grow(this.state) && this.run(grow)) {
2196
+ event.preventDefault();
2197
+ return;
2198
+ }
2199
+ }
1198
2200
  const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
2201
+ // In a table, from a cell's first or last line: the cell above or below, or out of the
2202
+ // table (browsers go to the next cell in the DOM, or across pages to the wrong row).
2203
+ const cells = vertical ? goToCellVertically(vertical as -1 | 1) : null;
2204
+ // (A selection of a cell's whole content, Tab's, moves as the cell: no line to measure.)
2205
+ const onEdge = () => !this.state.selection.empty || this.caretOnEdgeLine(vertical as -1 | 1);
2206
+ if (cells?.(this.state) && onEdge() && this.run(cells)) {
2207
+ event.preventDefault();
2208
+ return;
2209
+ }
1199
2210
  const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
1200
2211
  if (across?.(this.state) && this.caretOnEdgeLine(vertical as -1 | 1) && this.run(across)) {
1201
2212
  event.preventDefault();
@@ -1206,16 +2217,20 @@ export class EditorView {
1206
2217
  * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
1207
2218
  * block's first or last fragment (a block split across pages has several).
1208
2219
  */
1209
- private caretOnEdgeLine(dir: -1 | 1): boolean {
2220
+ private caretOnEdgeLine(dir: -1 | 1, focusOnly = false): boolean {
1210
2221
  const sel = this.host.ownerDocument.getSelection();
1211
- if (!sel?.rangeCount || !sel.isCollapsed || !sel.focusNode) return false;
2222
+ // `focusOnly`: a range's head (Shift+arrows), else only a caret.
2223
+ if (!sel?.rangeCount || (!focusOnly && !sel.isCollapsed) || !sel.focusNode) return false;
1212
2224
  const element = this.blockElement(sel.focusNode);
1213
2225
  const desc = element ? this.owner.get(element) : undefined;
1214
2226
  if (!desc?.node.isTextblock) return false;
1215
2227
  const fragment = desc.fragments[dir < 0 ? 0 : desc.fragments.length - 1];
1216
2228
  if (!fragment || element !== fragment) return false;
1217
2229
  if (!desc.node.content.size) return true;
1218
- const caret = sel.getRangeAt(0).getClientRects()[0];
2230
+ const at = this.host.ownerDocument.createRange();
2231
+ at.setStart(sel.focusNode, sel.focusOffset);
2232
+ at.collapse(true);
2233
+ const caret = at.getClientRects()[0];
1219
2234
  const lines = this.host.ownerDocument.createRange();
1220
2235
  lines.selectNodeContents(fragment);
1221
2236
  const rects = lines.getClientRects();
@@ -1348,13 +2363,13 @@ export class EditorView {
1348
2363
  };
1349
2364
 
1350
2365
  private onMutations = (records: MutationRecord[]): void => {
1351
- this.pending.push(...records);
1352
- if (!this.composing) this.flush();
2366
+ this.pending.push(...records.filter((r) => !handleOnly(r)));
2367
+ if (!this.composing && this.pending.length) this.flush();
1353
2368
  };
1354
2369
 
1355
2370
  /** Reads back every DOM change recorded so far. */
1356
2371
  private flush(): void {
1357
- const records = [...this.pending, ...this.observer.takeRecords()];
2372
+ const records = [...this.pending, ...this.observer.takeRecords().filter((r) => !handleOnly(r))];
1358
2373
  this.pending = [];
1359
2374
  if (records.length) this.readBack(records);
1360
2375
  }
@@ -1391,26 +2406,51 @@ export class EditorView {
1391
2406
  else if ((node as Element).getAttribute?.("contenteditable") === "false") return;
1392
2407
  else node.childNodes.forEach(walk);
1393
2408
  };
1394
- let first = true;
1395
- // Block-level nodes in order: inside pages and containers, and anything else in the host.
1396
- const blockLevel: Node[] = [];
2409
+ // Block-level nodes: inside pages and tables, and anything else in the host.
2410
+ let stray = false;
1397
2411
  const collect = (parent: Node) => {
1398
2412
  for (const child of parent.childNodes) {
2413
+ if (this.owner.has(child)) continue;
2414
+ // Drawn, not document content (a repeated header row): no text of the model.
2415
+ if ((child as Element).getAttribute?.("contenteditable") === "false") continue;
1399
2416
  if (this.holdsBlocks(child)) collect(child);
1400
- else blockLevel.push(child);
2417
+ // Text outside every block (an element the browser added): a block the model does not
2418
+ // have. An empty stray node (an extension's marker) holds none; the re-render removes it.
2419
+ else if (child.textContent) stray = true;
1401
2420
  }
1402
2421
  };
1403
2422
  collect(this.host);
1404
- let previousOwner: BlockDesc | undefined;
1405
- for (const child of blockLevel) {
1406
- const owner = this.owner.get(child);
1407
- // An empty stray node (an extension's marker) holds no text; the re-render removes it.
1408
- if (!owner && !child.textContent) continue;
1409
- // The fragments of one block are one text; anything else starts a new block.
1410
- if (!first && !(owner && owner === previousOwner)) domText += BLOCK_SEPARATOR;
2423
+ if (stray) {
2424
+ // shortcut: a change that adds blocks cannot be read back yet; it is dropped.
2425
+ console.warn("Foli: discarded a DOM change that adds blocks or line breaks");
2426
+ this.rerender();
2427
+ return;
2428
+ }
2429
+ // Each block's fragments are one text, blocks in document order (a row split across pages
2430
+ // has its cells' fragments on two pages).
2431
+ // A block whose elements the browser removed (merging it into another) has no text there.
2432
+ // One missing without a recorded removal was never placed (drawn during a composition):
2433
+ // its text counts as unchanged, never as deleted.
2434
+ const removed = new Set(
2435
+ records.flatMap((record) => [...record.removedNodes]).filter((n) => !this.viewRemoved.has(n)),
2436
+ );
2437
+ const removedByInput = (node: Node) => {
2438
+ for (let at: Node | null = node; at; at = at.parentNode) if (removed.has(at)) return true;
2439
+ return false;
2440
+ };
2441
+ let first = true;
2442
+ for (const desc of this.blocks) {
2443
+ const shown = desc.fragments.filter((fragment) => this.host.contains(fragment));
2444
+ if (!shown.length && !desc.fragments.some(removedByInput)) {
2445
+ if (!first) domText += BLOCK_SEPARATOR;
2446
+ first = false;
2447
+ domText += textOfBlock(desc.node);
2448
+ continue;
2449
+ }
2450
+ if (!shown.length) continue;
2451
+ if (!first) domText += BLOCK_SEPARATOR;
1411
2452
  first = false;
1412
- previousOwner = owner;
1413
- walk(child);
2453
+ for (const fragment of shown) walk(fragment);
1414
2454
  }
1415
2455
 
1416
2456
  const { doc } = this.state;
@@ -1419,14 +2459,7 @@ export class EditorView {
1419
2459
  this.blocks.forEach(({ node: block }, i) => {
1420
2460
  if (i > 0) modelText += BLOCK_SEPARATOR;
1421
2461
  lineStarts.push(modelText.length);
1422
- block.forEach((child) => {
1423
- // A tab is text in the DOM (a "\t" text node).
1424
- modelText += child.isText
1425
- ? (child.text ?? "")
1426
- : child.type.name === "tab"
1427
- ? "\t"
1428
- : HARD_BREAK;
1429
- });
2462
+ modelText += textOfBlock(block);
1430
2463
  });
1431
2464
  /** Model position of an offset in `modelText`. */
1432
2465
  const posAt = (offset: number): number => {
@@ -1503,14 +2536,17 @@ export class EditorView {
1503
2536
  if (selection.empty || !event.clipboardData) return;
1504
2537
  event.preventDefault();
1505
2538
  const context = wordContext(this.state) as WordContext;
2539
+ // Selected cells are copied as a table of their own (ADR-0006).
2540
+ const table = selection instanceof CellSelection ? cellsAsTable(selection) : null;
2541
+ const source = table ? doc.type.create(null, table) : doc;
1506
2542
  const { text, html, json } = serializeRange(
1507
- doc,
1508
- selection.from,
1509
- selection.to,
2543
+ source,
2544
+ table ? 0 : selection.from,
2545
+ table ? source.content.size : selection.to,
1510
2546
  this.host.ownerDocument,
1511
2547
  { context, ratio: this.lineRatio },
1512
2548
  );
1513
- event.clipboardData.setData("text/plain", text);
2549
+ event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
1514
2550
  event.clipboardData.setData("text/html", html);
1515
2551
  event.clipboardData.setData(FOLI_MIME, json);
1516
2552
  };
@@ -1531,6 +2567,12 @@ export class EditorView {
1531
2567
  if (this.composing) return;
1532
2568
  this.syncSelection();
1533
2569
  const data = event.clipboardData;
2570
+ // An image alone (a screenshot, an image copied from a page): a picture.
2571
+ const files = plain ? [] : this.imageFiles(data);
2572
+ if (files.length && !data.getData(FOLI_MIME) && !data.getData("text/plain").trim()) {
2573
+ void this.insertFiles(files);
2574
+ return;
2575
+ }
1534
2576
  this.paste(
1535
2577
  plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data,
1536
2578
  !plain,
@@ -1597,13 +2639,26 @@ export class EditorView {
1597
2639
  if (open) throw new TransformError("Open content is pasted as a slice");
1598
2640
  insertBlocks(tr, doc);
1599
2641
  };
1600
- const strategies = [asSlice, asBlocks];
2642
+ // Rows (a table alone) into a table fill its cells from the selected one (ADR-0006).
2643
+ const intoCells = (tr: Transaction) => {
2644
+ if (only?.type.name !== "table" || !pasteCells(tr, only))
2645
+ throw new TransformError("Only rows are pasted into cells");
2646
+ };
2647
+ const strategies = [intoCells, asSlice, asBlocks];
1601
2648
  for (const strategy of strategies) {
1602
2649
  const tr = state.tr;
1603
2650
  try {
1604
- tr.deleteSelection();
2651
+ // Other content over selected cells goes into the anchor cell; across a table's edge,
2652
+ // whole rows go (`deleteSelectionKeepingTables`).
2653
+ if (strategy !== intoCells && !tr.selection.empty) deleteSelectionKeepingTables(tr, true);
1605
2654
  strategy(tr);
1606
- if (envelope && envelope !== wordContext(state)?.envelope) withEnvelope(tr, envelope);
2655
+ // A pasted table never ends the body nor touches another table (Word's rules).
2656
+ keepTablesApart(tr);
2657
+ const current = wordContext(state)?.envelope;
2658
+ if (envelope && current && envelope !== current) {
2659
+ withEnvelope(tr, envelope);
2660
+ setComments(tr, current.comments, envelope.comments);
2661
+ }
1607
2662
  } catch (error) {
1608
2663
  if (error instanceof TransformError) continue;
1609
2664
  throw error;
@@ -1618,6 +2673,19 @@ export class EditorView {
1618
2673
  };
1619
2674
  }
1620
2675
 
2676
+ /** Copied cells as text, as spreadsheets read it: a tab between cells, a line per row. */
2677
+ function cellsText(table: ModelNode): string {
2678
+ const rows: string[] = [];
2679
+ table.forEach((row) => {
2680
+ const cells: string[] = [];
2681
+ row.forEach((cell) => {
2682
+ cells.push(cell.textBetween(0, cell.content.size, " "));
2683
+ });
2684
+ rows.push(cells.join("\t"));
2685
+ });
2686
+ return rows.join("\n");
2687
+ }
2688
+
1621
2689
  /**
1622
2690
  * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1623
2691
  * paragraph, else between its two halves (an empty one is replaced as a slice first).
@@ -1648,13 +2716,201 @@ function layoutScale(page: HTMLElement, settings: DocumentSettings): number {
1648
2716
  }
1649
2717
 
1650
2718
  /** A block's measurement: border-box height across its fragments (layout px), margins, lines. */
1651
- interface Measure {
2719
+ export interface Measure {
1652
2720
  height: number;
1653
2721
  marginTop: number;
1654
2722
  marginBottom: number;
1655
2723
  /** Vertical padding and border, which every fragment of a split block repeats. */
1656
2724
  box: number;
1657
2725
  lines?: Lines;
2726
+ /** A table's rows and blocks. */
2727
+ table?: TableMeasure;
2728
+ }
2729
+
2730
+ /** The innermost cell around pos (the position before it) and its table's, or null. */
2731
+ function cellAround(doc: ModelNode, pos: number): { cell: number; table: number } | null {
2732
+ const $pos = doc.resolve(pos);
2733
+ for (let d = $pos.depth; d > 2; d--)
2734
+ if ($pos.node(d).type.name === "tableCell")
2735
+ return { cell: $pos.before(d), table: $pos.before(d - 2) };
2736
+ return null;
2737
+ }
2738
+
2739
+ /** A block's text as the read-back compares it: a tab "\t", other inline leaves one character. */
2740
+ function textOfBlock(block: ModelNode): string {
2741
+ let text = "";
2742
+ block.forEach((child) => {
2743
+ // A tab is text in the DOM (a "\t" text node).
2744
+ text += child.isText ? (child.text ?? "") : child.type.name === "tab" ? "\t" : HARD_BREAK;
2745
+ });
2746
+ return text;
2747
+ }
2748
+
2749
+ /** Whether a table's wrappers hold every element of its blocks (none was drawn anew). */
2750
+ function holdsAll(state: FrameState, frame: Frame, blocks: readonly WordBlockDesc[]): boolean {
2751
+ for (let u = frame.first; u < frame.end; u++)
2752
+ for (const fragment of (blocks[u] as WordBlockDesc).fragments)
2753
+ if (!state.wrappers.some((wrapper) => wrapper.contains(fragment))) return false;
2754
+ return true;
2755
+ }
2756
+
2757
+ /** Measures a table drawn whole: its height, its rows and where its blocks start. */
2758
+ function measureTable(
2759
+ frame: Frame,
2760
+ wrapper: HTMLElement,
2761
+ blocks: readonly WordBlockDesc[],
2762
+ scale: number,
2763
+ ): Measure {
2764
+ const box = wrapper.getBoundingClientRect();
2765
+ const rows = [...wrapper.querySelectorAll(":scope > table > tbody > tr")].map((tr) => {
2766
+ const rect = tr.getBoundingClientRect();
2767
+ return { top: (rect.top - box.top) / scale, bottom: (rect.bottom - box.top) / scale };
2768
+ });
2769
+ const tops = new Map<number, number | null>();
2770
+ for (let u = frame.first; u < frame.end; u++) {
2771
+ const dom = (blocks[u] as WordBlockDesc).dom;
2772
+ // A block of a cell a merge covers is not shown: it goes with its row.
2773
+ const hidden = !!dom.closest(`[${FRAME_ATTR}="covered"]`);
2774
+ tops.set(u, hidden ? null : (dom.getBoundingClientRect().top - box.top) / scale);
2775
+ }
2776
+ return {
2777
+ height: box.height / scale,
2778
+ marginTop: 0,
2779
+ marginBottom: 0,
2780
+ box: 0,
2781
+ table: { rows, tops },
2782
+ };
2783
+ }
2784
+
2785
+ /**
2786
+ * Where a table may break across pages (from its top, sorted): after each row, and inside a row
2787
+ * at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
2788
+ * page), is part of a vertical merge or holds a nested table (shortcut: those split only
2789
+ * between rows; a nested table stays whole within its row).
2790
+ */
2791
+ export function breaksOf(
2792
+ frame: Frame,
2793
+ measure: Measure,
2794
+ blocks: readonly WordBlockDesc[],
2795
+ pageHeight: number,
2796
+ lines: (desc: BlockDesc) => Lines,
2797
+ ): number[] {
2798
+ const t = measure.table as TableMeasure;
2799
+ if (t.breaks) return t.breaks;
2800
+ const out: number[] = [];
2801
+ frame.rows.forEach((row, r) => {
2802
+ const { top, bottom } = t.rows[r] ?? { top: 0, bottom: 0 };
2803
+ const merged = row.cells.some((cell) => cell.vMerge !== null);
2804
+ const nested = row.cells.some((cell) => cell.items.some((item) => "frame" in item));
2805
+ const splits = (!row.cantSplit || bottom - top > pageHeight) && !merged && !nested;
2806
+ if (splits)
2807
+ for (const cell of row.cells)
2808
+ for (const item of cell.items) {
2809
+ if ("frame" in item) continue;
2810
+ const unitTop = t.tops.get(item.unit);
2811
+ if (unitTop === null || unitTop === undefined) continue;
2812
+ for (const b of lines(blocks[item.unit] as WordBlockDesc).bottoms) {
2813
+ const y = unitTop + b;
2814
+ if (y > top + 0.5 && y < bottom - 0.5) out.push(y);
2815
+ }
2816
+ }
2817
+ out.push(r === frame.rows.length - 1 ? Math.max(bottom, measure.height) : bottom);
2818
+ });
2819
+ out.sort((a, b) => a - b);
2820
+ t.breaks = out.filter((y, k) => k === 0 || y - (out[k - 1] as number) > 0.5);
2821
+ return t.breaks;
2822
+ }
2823
+
2824
+ /** What the flow needs of a table: its height, where it may break, its header rows' height. */
2825
+ function tableBox(
2826
+ frame: Frame,
2827
+ measure: Measure,
2828
+ pageHeight: number,
2829
+ breakAfter: boolean,
2830
+ breaks: () => number[],
2831
+ ): BlockBox {
2832
+ const t = measure.table as TableMeasure;
2833
+ const header = frame.headers ? (t.rows[frame.headers - 1]?.bottom ?? 0) : 0;
2834
+ return {
2835
+ height: measure.height,
2836
+ marginTop: 0,
2837
+ marginBottom: 0,
2838
+ pageHeight,
2839
+ repeat: header,
2840
+ // Word keeps no lines together across a table's rows (a cell's paragraph splits anywhere).
2841
+ anyLine: true,
2842
+ lines: breaks,
2843
+ breaksAfter: () => (breakAfter ? [breaks().length - 1] : []),
2844
+ };
2845
+ }
2846
+
2847
+ /**
2848
+ * A flowed table cut into its fragments: the rows each shows (a row split across pages in
2849
+ * both), the header rows drawn again above a continuation, the fragment of the table each
2850
+ * block's fragments go in, and where a block of a split row splits (content offsets).
2851
+ */
2852
+ export function cutTable(
2853
+ frame: Frame,
2854
+ measure: Measure,
2855
+ fragments: readonly { fromLine: number; toLine: number }[],
2856
+ blocks: readonly WordBlockDesc[],
2857
+ lines: (desc: BlockDesc) => Lines,
2858
+ ): { parts: TablePart[]; partOf: Map<number, number[]>; splits: Map<number, number[]> } {
2859
+ const t = measure.table as TableMeasure;
2860
+ const all = frame.rows.map((_, r) => r);
2861
+ const partOf = new Map<number, number[]>();
2862
+ const splits = new Map<number, number[]>();
2863
+ if (fragments.length <= 1 || !t.breaks) {
2864
+ for (let u = frame.first; u < frame.end; u++) partOf.set(u, [0]);
2865
+ return { parts: [{ rows: all, headers: [] }], partOf, splits };
2866
+ }
2867
+ const breaks = t.breaks;
2868
+ const bounds = fragments.map((f) => [
2869
+ f.fromLine ? (breaks[f.fromLine - 1] as number) : 0,
2870
+ f.toLine === Number.POSITIVE_INFINITY ? measure.height : (breaks[f.toLine - 1] as number),
2871
+ ]) as [number, number][];
2872
+ const parts = bounds.map(([y0, y1], k): TablePart => {
2873
+ const rows = all.filter((r) => {
2874
+ const row = t.rows[r] ?? { top: 0, bottom: 0 };
2875
+ return row.top < y1 - 0.5 && row.bottom > y0 + 0.5;
2876
+ });
2877
+ const repeat = k > 0 && frame.headers > 0 && (rows[0] ?? 0) >= frame.headers;
2878
+ return { rows, headers: repeat ? all.slice(0, frame.headers) : [] };
2879
+ });
2880
+ frame.rows.forEach((row, r) => {
2881
+ const ks = parts.flatMap((part, k) => (part.rows.includes(r) ? [k] : []));
2882
+ const firstPart = ks[0] ?? 0;
2883
+ for (const cell of row.cells)
2884
+ for (const item of cell.items) {
2885
+ if ("frame" in item) {
2886
+ for (let u = item.frame.first; u < item.frame.end; u++) partOf.set(u, [firstPart]);
2887
+ continue;
2888
+ }
2889
+ const u = item.unit;
2890
+ const top = t.tops.get(u);
2891
+ if (ks.length < 2 || top === null || top === undefined) {
2892
+ partOf.set(u, [firstPart]);
2893
+ continue;
2894
+ }
2895
+ // Each line on the page its bottom fits; consecutive lines on one page are a fragment.
2896
+ const { starts, bottoms } = lines(blocks[u] as WordBlockDesc);
2897
+ const runs: number[] = [];
2898
+ const at: number[] = [];
2899
+ bottoms.forEach((b, i) => {
2900
+ const y = top + b;
2901
+ const k =
2902
+ ks.find((part) => y <= (bounds[part] as [number, number])[1] + 0.5) ??
2903
+ (ks.at(-1) as number);
2904
+ if (runs.at(-1) !== k) {
2905
+ if (runs.length) at.push(starts[i] as number);
2906
+ runs.push(k);
2907
+ }
2908
+ });
2909
+ partOf.set(u, runs.length ? runs : [firstPart]);
2910
+ if (at.length) splits.set(u, at);
2911
+ }
2912
+ });
2913
+ return { parts, partOf, splits };
1658
2914
  }
1659
2915
 
1660
2916
  /** Reads a block's height (in layout px) and vertical margins from the DOM. */
@@ -1685,16 +2941,16 @@ function measureBox(desc: BlockDesc, scale: number): Measure {
1685
2941
  * and a page break before the next block ending this one's page.
1686
2942
  */
1687
2943
  function wordBox(
1688
- blocks: readonly WordBlockDesc[],
2944
+ words: readonly WordInfo[],
1689
2945
  i: number,
2946
+ desc: WordBlockDesc,
1690
2947
  measure: Measure,
1691
2948
  lines: () => Lines,
1692
2949
  layout: BlockLayout,
1693
2950
  ): BlockBox {
1694
2951
  const pageHeight = contentHeight(layout.sheet.settings);
1695
- const desc = blocks[i] as WordBlockDesc;
1696
- const next = blocks[i + 1];
1697
- const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
2952
+ const next = words[i + 1] ? { word: words[i + 1] as WordInfo } : undefined;
2953
+ const { before, after } = spacing(words[i - 1], desc.word, next?.word);
1698
2954
  const pageBreaks = desc.leaves.filter(
1699
2955
  (leaf) =>
1700
2956
  leaf.dom.nodeType !== Node.TEXT_NODE && (leaf.dom as Element).hasAttribute(PAGE_BREAK_ATTR),
@@ -1730,11 +2986,11 @@ function wordBox(
1730
2986
  * Written only when it changes.
1731
2987
  */
1732
2988
  function applyGaps(
1733
- blocks: readonly BlockDesc[],
2989
+ firsts: readonly HTMLElement[],
1734
2990
  pages: readonly (readonly number[])[],
1735
2991
  boxes: readonly BlockBox[],
1736
2992
  ): void {
1737
- blocks.forEach((desc, i) => {
2993
+ firsts.forEach((dom, i) => {
1738
2994
  const page = pages[i]?.[0] ?? 0;
1739
2995
  const above = pages[i - 1];
1740
2996
  const box = boxes[i] as BlockBox;
@@ -1748,9 +3004,9 @@ function applyGaps(
1748
3004
  page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1749
3005
  gap = forced ? box.marginTop : 0;
1750
3006
  }
1751
- if (gaps.get(desc.dom) === gap) return;
1752
- gaps.set(desc.dom, gap);
1753
- desc.dom.style.marginTop = `${gap}px`;
3007
+ if (gaps.get(dom) === gap) return;
3008
+ gaps.set(dom, gap);
3009
+ dom.style.marginTop = `${gap}px`;
1754
3010
  });
1755
3011
  }
1756
3012
 
@@ -1790,7 +3046,7 @@ function reuseOf(
1790
3046
  };
1791
3047
  }
1792
3048
 
1793
- interface Lines {
3049
+ export interface Lines {
1794
3050
  /** Content offset where each line starts. */
1795
3051
  starts: number[];
1796
3052
  /** Bottom of each line box, in layout px from the block's top, as if it were not split. */
@@ -1996,3 +3252,76 @@ export function keyName(event: KeyboardEvent): string {
1996
3252
  if (mod) name = `Mod-${name}`;
1997
3253
  return name;
1998
3254
  }
3255
+
3256
+ /**
3257
+ * The text width of a document's (last) section in EMU (635 per twip; Word's Letter page and
3258
+ * margins where it does not say): the widest a picture is inserted or resized.
3259
+ * shortcut: the last section's, not the caret's section or table cell; use the caret's when
3260
+ * documents mix page sizes.
3261
+ */
3262
+ export function textWidthEmu(state: EditorState): number {
3263
+ const section = wordContext(state)?.envelope.section;
3264
+ return (
3265
+ ((section?.pageSize?.width ?? 12_240) -
3266
+ (section?.margins?.left ?? 1440) -
3267
+ (section?.margins?.right ?? 1440)) *
3268
+ 635
3269
+ );
3270
+ }
3271
+
3272
+ /** A file's image's natural size (CSS px) from a local object URL, before any upload. */
3273
+ export async function measureImageFile(
3274
+ file: File,
3275
+ doc: Document,
3276
+ ): Promise<{ width: number; height: number } | null> {
3277
+ if (typeof URL.createObjectURL !== "function") return null;
3278
+ const url = URL.createObjectURL(file);
3279
+ try {
3280
+ return await naturalSize(url, doc);
3281
+ } finally {
3282
+ URL.revokeObjectURL(url);
3283
+ }
3284
+ }
3285
+
3286
+ /** An image's natural size (CSS px), or null when it does not load. */
3287
+ async function naturalSize(
3288
+ src: string,
3289
+ doc: Document,
3290
+ ): Promise<{ width: number; height: number } | null> {
3291
+ const img = doc.createElement("img");
3292
+ // Load events, not decode(): WebKit rejects decode() for an image outside the document.
3293
+ const loaded = new Promise<boolean>((resolve) => {
3294
+ img.onload = () => resolve(true);
3295
+ img.onerror = () => resolve(false);
3296
+ });
3297
+ img.src = src;
3298
+ if (!(await loaded)) return null;
3299
+ return img.naturalWidth && img.naturalHeight
3300
+ ? { width: img.naturalWidth, height: img.naturalHeight }
3301
+ : null;
3302
+ }
3303
+
3304
+ /** Whether a block holds a floating picture (cached per node: nodes do not change). */
3305
+ const floats = new WeakMap<ModelNode, boolean>();
3306
+ function holdsFloat(node: ModelNode): boolean {
3307
+ let found = floats.get(node);
3308
+ if (found === undefined) {
3309
+ found = false;
3310
+ node.descendants((child) => {
3311
+ if (child.type.name === "picture" && child.attrs.float) found = true;
3312
+ return !found;
3313
+ });
3314
+ floats.set(node, found);
3315
+ }
3316
+ return found;
3317
+ }
3318
+
3319
+ /** A change that only adds or removes a picture's resize handle (the view's own, not input). */
3320
+ function handleOnly(record: MutationRecord): boolean {
3321
+ const nodes = [...record.addedNodes, ...record.removedNodes];
3322
+ return (
3323
+ record.type === "childList" &&
3324
+ nodes.length > 0 &&
3325
+ nodes.every((n) => n.nodeType === 1 && (n as Element).hasAttribute("data-foli-resize"))
3326
+ );
3327
+ }