@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/dist/view.js CHANGED
@@ -1,17 +1,37 @@
1
- import { AllSelection, arrowAcrossLeaf, autolinkHref, closeHistory, deleteBackward, deleteForward, deleteSelection, fitPaste, fitPastedV2, insertHardBreak, insertLink, insertText, isSafeHref, marksAt, NodeSelection, parseContentV2, redo, Selection, Slice, sectionSettings, setLink, splitBlock, TextSelection, TransformError, toggleMark, typedMarks, undo, withEnvelope, wordContext, } from "@folijs/core";
1
+ import { AllSelection, arrowAcrossLeaf, autolinkHref, CellSelection, cellsAsTable, closeHistory, deleteBackward, deleteForward, deleteSelection, deleteSelectionKeepingTables, extendCellSelection, fitPaste, fitPastedV2, goToCellVertically, insertHardBreak, insertLink, insertPicture, insertText, isSafeHref, keepTablesApart, marksAt, NodeSelection, parseContentV2, pasteCells, redo, Selection, Slice, sectionSettings, setColumnWidth, setComments, setLink, setPictureSize, splitBlock, TextSelection, TransformError, toggleMark, trackState, typedMarks, undo, withEnvelope, wordContext, } from "@folijs/core";
2
2
  import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
3
3
  import { contentHeight, DEFAULT_RULES, flowFrom, PX_PER_MM, } from "./layout/flow.js";
4
4
  import { PAGE_BREAK_ATTR } from "./render.js";
5
- import { spacing, WordRenderer } from "./word/edit.js";
5
+ import { EMU_PER_PX, imageSource, PICTURE_ATTR } from "./word/blocks.js";
6
+ import { FLOAT_ANCHORS, spacing, WordRenderer, } from "./word/edit.js";
6
7
  import { measureLineRatio } from "./word/pages.js";
8
+ import { collect, FRAME_ATTR, frameElement, REPEATED_ATTR, } from "./word/table.js";
9
+ /** What the flow needs of a table: no paragraph spacing or keep rules of its own. */
10
+ const TABLE_WORD = {
11
+ before: 0,
12
+ after: 0,
13
+ keepNext: false,
14
+ keepLines: false,
15
+ pageBreakBefore: false,
16
+ style: null,
17
+ contextual: false,
18
+ };
7
19
  /** Word's paragraph spacing for a schema v3 document (`flow`'s `word` spacing). */
8
20
  const WORD_RULES = { ...DEFAULT_RULES, spacing: "word" };
9
21
  /** Class of the element of a node-selected block (a rule). */
10
22
  const SELECTED_CLASS = "foli-selected-node";
23
+ /** Marks a cell of a cell selection. */
24
+ const CELL_CLASS = "foli-selected-cell";
25
+ /** On the host while cells are selected: the browser's own highlight (in DOM order) is hidden. */
26
+ const CELLS_ATTR = "data-foli-cells";
11
27
  const PLACEHOLDER_ATTR = "data-foli-placeholder";
28
+ /** On the span of a selected picture (it holds the resize handle). */
29
+ const PICTURE_SELECTED_ATTR = "data-foli-picture-selected";
30
+ /** The smallest a picture gets by dragging its handle, in px. */
31
+ const MIN_PICTURE = 8;
12
32
  // Generated content is not document text: no caret stops inside it, a zero-height float keeps
13
33
  // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
14
- const STYLES = `[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
34
+ 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}`;
15
35
  /**
16
36
  * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
17
37
  * (by then the host is usually mounted where it will stay).
@@ -59,11 +79,22 @@ function printStyles(settings, sheets, id) {
59
79
  `${pages}{height:${height}mm!important;margin-block:0!important;` +
60
80
  `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}${named}}`);
61
81
  }
82
+ /** Whether `node` is inside an element of `stop` that is not displayed (hidden deleted text). */
83
+ function hiddenIn(node, stop) {
84
+ for (let el = node.parentElement; el && el !== stop; el = el.parentElement)
85
+ if (el.style.display === "none")
86
+ return true;
87
+ return false;
88
+ }
62
89
  /** The attribute naming a page's page setup (its index among the document's) for print. */
63
90
  const SHEET_ATTR = "data-foli-sheet";
64
91
  function sheetOf(settings, index) {
65
92
  const { pageSize, margins } = settings;
66
- const css = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
93
+ const css =
94
+ // The containing block, stacking context and formatting context of floating pictures: one
95
+ // reaching past the page's text makes the page taller, never overlaps the next page.
96
+ "position: relative; isolation: isolate; display: flow-root; " +
97
+ `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
67
98
  `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
68
99
  return { settings, css, index };
69
100
  }
@@ -149,8 +180,19 @@ export class EditorView {
149
180
  indexOf = new Map();
150
181
  /** The element that shows a node selection, if any. */
151
182
  selectedDom = null;
152
- /** The page of each fragment of each block. */
153
- fragmentPages = new Map();
183
+ /** The cells a cell selection marks, and the caret written in its head cell. */
184
+ selectedCells = [];
185
+ cellCaret = null;
186
+ /** The pages of each top-level item (a paragraph's fragments, a table's wrappers), by node. */
187
+ itemPages = new Map();
188
+ /** Each table as last rendered, by node. */
189
+ frames = new Map();
190
+ /** The table each wrapper element draws (part of). */
191
+ frameOf = new Map();
192
+ /** Each table as last rendered, by its index among the top-level items. */
193
+ frameAt = [];
194
+ /** Elements the view itself removed: the read-back does not take them for input. */
195
+ viewRemoved = new WeakSet();
154
196
  /** The block each fragment element belongs to. */
155
197
  owner = new Map();
156
198
  /** The page elements, in order; the host's only children. */
@@ -215,6 +257,16 @@ export class EditorView {
215
257
  addedTabIndex;
216
258
  /** Renders the document's blocks; made by the first render. */
217
259
  word = null;
260
+ /** Where pasted and dropped image files go (`EditorViewOptions.upload`). */
261
+ upload;
262
+ /** The selected picture's span (with its resize handle). */
263
+ selectedPicture = null;
264
+ /** A picture being resized: its position, element, size at the press, scale, the press. */
265
+ resize = null;
266
+ /** The app's URLs for pictures' images (`EditorViewOptions.resource`). */
267
+ resource;
268
+ /** How tracked changes show. */
269
+ review = "markup";
218
270
  /** Fonts' normal line height ratios, measured once per family (Word's single spacing). */
219
271
  ratios = new Map();
220
272
  /** Web fonts loaded since the v3 blocks were drawn: the next render draws them again. */
@@ -233,10 +285,13 @@ export class EditorView {
233
285
  host.style.whiteSpace = "pre-wrap";
234
286
  host.style.overflowWrap = "break-word";
235
287
  host.replaceChildren();
288
+ this.review = trackState(this.state)?.view ?? "markup";
236
289
  this.resizeObserver =
237
290
  typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
238
291
  this.observer = new MutationObserver(this.onMutations);
239
292
  this.observer.observe(host, { childList: true, characterData: true, subtree: true });
293
+ // The picture resolver before the first render: no image drawn from a URL the app refuses.
294
+ this.resource = options.resource ?? undefined;
240
295
  this.render();
241
296
  this.setOptions(options);
242
297
  host.addEventListener("beforeinput", this.onBeforeInput);
@@ -247,9 +302,12 @@ export class EditorView {
247
302
  host.addEventListener("compositionend", this.onCompositionEnd);
248
303
  host.addEventListener("blur", this.onBlur);
249
304
  host.addEventListener("mousedown", this.onMouseDown);
305
+ host.addEventListener("mousemove", this.onMouseMove);
250
306
  host.addEventListener("copy", this.onCopy);
251
307
  host.addEventListener("cut", this.onCut);
252
308
  host.addEventListener("paste", this.onPaste);
309
+ host.addEventListener("dragover", this.onDragOver);
310
+ host.addEventListener("drop", this.onDrop);
253
311
  host.addEventListener("click", this.onClick);
254
312
  host.addEventListener("auxclick", this.onClick);
255
313
  host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
@@ -273,9 +331,14 @@ export class EditorView {
273
331
  host.removeEventListener("compositionend", this.onCompositionEnd);
274
332
  host.removeEventListener("blur", this.onBlur);
275
333
  host.removeEventListener("mousedown", this.onMouseDown);
334
+ host.removeEventListener("mousemove", this.onMouseMove);
335
+ this.endDrag();
276
336
  host.removeEventListener("copy", this.onCopy);
277
337
  host.removeEventListener("cut", this.onCut);
278
338
  host.removeEventListener("paste", this.onPaste);
339
+ host.removeEventListener("dragover", this.onDragOver);
340
+ host.removeEventListener("drop", this.onDrop);
341
+ this.endResize();
279
342
  host.removeEventListener("click", this.onClick);
280
343
  host.removeEventListener("auxclick", this.onClick);
281
344
  host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
@@ -313,9 +376,28 @@ export class EditorView {
313
376
  if (!options.editable && this.composing)
314
377
  this.onCompositionEnd();
315
378
  this.editable = options.editable;
379
+ // A selected picture's handle only while it can be resized.
380
+ this.endResize();
381
+ this.showSelectedPicture();
316
382
  }
317
383
  if (options.placeholder !== undefined)
318
384
  this.placeholder = options.placeholder;
385
+ if (options.upload !== undefined)
386
+ this.upload = options.upload ?? undefined;
387
+ // null clears the resolver (stored as none): the same as none is no change.
388
+ const resource = options.resource ?? undefined;
389
+ if (options.resource !== undefined && resource !== this.resource) {
390
+ this.resource = resource;
391
+ // Every picture again, from the new URLs: after a running composition, keeping the
392
+ // selection.
393
+ if (this.word) {
394
+ if (this.composing)
395
+ this.onCompositionEnd();
396
+ this.word = null;
397
+ this.render();
398
+ this.writeSelection(false);
399
+ }
400
+ }
319
401
  // Read-only: no caret and no browser editing; the text stays selectable and copyable.
320
402
  host.setAttribute("contenteditable", String(this.editable));
321
403
  if (this.editable)
@@ -346,7 +428,17 @@ export class EditorView {
346
428
  }
347
429
  // ---------- rendering ----------
348
430
  update(state) {
349
- const docChanged = state.doc !== this.state.doc;
431
+ // A resize is of the picture at its position when it started: the document changed, over.
432
+ if (state.doc !== this.state.doc)
433
+ this.onResizeCancel();
434
+ const review = trackState(state)?.view ?? "markup";
435
+ // Another review view (`setReviewView`): every block drawn again, by a new renderer.
436
+ const reviewChanged = review !== this.review;
437
+ if (reviewChanged) {
438
+ this.review = review;
439
+ this.word = null;
440
+ }
441
+ const docChanged = state.doc !== this.state.doc || reviewChanged;
350
442
  const selectionChanged = !state.selection.eq(this.state.selection);
351
443
  this.state = state;
352
444
  if (docChanged)
@@ -405,10 +497,16 @@ export class EditorView {
405
497
  this.fontsChanged = false;
406
498
  let word = this.word;
407
499
  if (renewed) {
408
- word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio);
500
+ // A document with pictures: the mark of one without alt text is the view's stylesheet's.
501
+ if (context.envelope.resources)
502
+ injectStyles(this.host);
503
+ word = this.word = new WordRenderer(context, ownerDocument, this.lineRatio, false, this.review, imageSource(context.envelope.resources, this.resource ?? undefined));
409
504
  this.invalidateLayout();
410
505
  }
411
- word.prepare(doc);
506
+ // The blocks the view renders (paragraphs in table cells among them) and the page flow's
507
+ // items (top-level paragraphs and opaque blocks, and tables).
508
+ const { units, items } = collect(doc, context.resolver);
509
+ word.prepare(units.map((unit) => unit.node));
412
510
  const layout = sectionLayouts(doc, context.envelope.section);
413
511
  doc.forEach((node, _, i) => {
414
512
  const { sheet, breakAfter } = layout[i];
@@ -419,43 +517,124 @@ export class EditorView {
419
517
  this.layoutKeys.set(node, key);
420
518
  });
421
519
  const previous = new Map(this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]));
422
- const previousPages = this.fragmentPages;
520
+ const previousPages = this.itemPages;
521
+ const previousFrames = this.frames;
423
522
  this.dirty.clear();
424
523
  const dropLines = this.linesStale && !this.composing;
425
524
  if (dropLines) {
426
525
  this.linesStale = false;
427
526
  this.flowed = null;
428
527
  }
528
+ // What can be reused: a block whose list number, comment shading or cell formatting changed
529
+ // (an edit before it) is redrawn.
530
+ const reusable = units.map((unit, i) => {
531
+ const found = renewed ? undefined : previous.get(unit.node);
532
+ if (found && found.key === word.key(i, unit.cell))
533
+ return found;
534
+ if (found)
535
+ this.stale.add(unit.node);
536
+ return undefined;
537
+ });
538
+ this.staleAroundFloats(doc, previousPages, new Set(units.filter((_, i) => !reusable[i]).map((unit) => unit.node)));
539
+ // A table is measured again (drawn whole first) when it changed, went stale, or one of its
540
+ // blocks is redrawn or stale; its blocks with it.
541
+ const remeasureUnit = units.map(() => false);
542
+ for (const item of items) {
543
+ const frame = item.frame;
544
+ if (!frame)
545
+ continue;
546
+ let stale = dropLines || !this.measures.has(frame.node) || this.stale.has(frame.node);
547
+ for (let u = frame.first; !stale && u < frame.end; u++)
548
+ stale = !reusable[u] || this.stale.has(units[u].node);
549
+ if (!stale)
550
+ continue;
551
+ this.stale.add(frame.node);
552
+ for (let u = frame.first; u < frame.end; u++)
553
+ remeasureUnit[u] = true;
554
+ }
429
555
  let blocks = [];
430
- const starts = [];
431
- doc.forEach((node, pos) => {
432
- let reused = renewed ? undefined : previous.get(node);
433
- // A block whose list number or comment shading changed (an edit before it) is redrawn.
434
- if (reused && reused.key !== word.key(blocks.length)) {
435
- reused = undefined;
436
- this.stale.add(node);
437
- }
556
+ // Nodes still in the document: an old block or table at an index is only taken over (during
557
+ // a composition) when its node is gone, never when an insertion moved it along.
558
+ const present = new Set(units.map((unit) => unit.node));
559
+ for (const item of items)
560
+ if (item.frame)
561
+ present.add(item.frame.node);
562
+ units.forEach((unit, i) => {
563
+ const { node } = unit;
564
+ let reused = reusable[i];
438
565
  // A split block about to be measured again (fonts, CSS) is rendered whole first: each
439
566
  // fragment's end breaks its line, so its lines would depend on where it was split before.
440
- const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
567
+ const remeasure = remeasureUnit[i] || dropLines || !this.measures.has(node) || this.stale.has(node);
441
568
  if (reused && reused.fragments.length > 1 && remeasure && !this.composing)
442
569
  reused = undefined;
443
570
  if (reused)
444
571
  previous.delete(node);
445
- blocks.push(reused ?? word.render(node, blocks.length));
446
- starts.push(pos);
572
+ const desc = reused ?? word.render(node, i, [], unit.cell);
573
+ blocks.push(desc);
574
+ // Drawn again in a table cell: the new block takes the old one's place there, so a table
575
+ // kept as it is (during a composition, which moves nothing) still holds it. During a
576
+ // composition a block whose node changed takes the place of the block drawn at its index.
577
+ const atIndex = this.blocks[i];
578
+ const old = reused
579
+ ? undefined
580
+ : (previous.get(node) ??
581
+ (this.composing &&
582
+ atIndex &&
583
+ !present.has(atIndex.node) &&
584
+ previous.get(atIndex.node) === atIndex
585
+ ? atIndex
586
+ : undefined));
587
+ const first = old?.fragments[0];
588
+ if (old && first?.isConnected && first.parentElement?.closest(`[${FRAME_ATTR}]`)) {
589
+ first.replaceWith(...desc.fragments);
590
+ for (const fragment of old.fragments.slice(1))
591
+ fragment.remove();
592
+ for (const fragment of old.fragments)
593
+ this.viewRemoved.add(fragment);
594
+ previous.delete(old.node);
595
+ }
447
596
  });
448
597
  for (const stale of previous.values())
449
- for (const fragment of stale.fragments)
598
+ for (const fragment of stale.fragments) {
450
599
  fragment.remove();
600
+ this.viewRemoved.add(fragment);
601
+ }
451
602
  this.applyPrintStyles(layout);
603
+ const doc_ = this.host.ownerDocument;
604
+ const frames = new Map();
605
+ /** A table drawn whole, on one page: what is measured. */
606
+ const whole = (frame) => {
607
+ const rows = frame.rows.map((_, r) => r);
608
+ const wrapper = frameElement(frame, rows, [], (r, c) => this.cellContent(frame, r, c, blocks, () => true), doc_);
609
+ return { wrappers: [wrapper], pages: [0], key: "" };
610
+ };
611
+ // Before the flow, each item where it was (a new one joins the page of the item before it);
612
+ // a table that changed is drawn whole on that page.
452
613
  let last = 0;
453
- let pages = blocks.map((desc) => {
454
- const before = previousPages.get(desc);
614
+ let pages = items.map((item, i) => {
615
+ const node = doc.child(i);
616
+ const before = previousPages.get(node);
617
+ if (item.frame) {
618
+ let state = previousFrames.get(node);
619
+ // During a composition nothing moves: a table that changed keeps the wrappers drawn at
620
+ // its place (its redrawn blocks took their old ones' places above).
621
+ const at = this.frameAt[i];
622
+ if (!state && this.composing && at && !present.has(at.node))
623
+ state = at.state;
624
+ if (!state || (this.stale.has(node) && !this.composing))
625
+ state = whole(item.frame);
626
+ frames.set(node, state);
627
+ const pagesBefore = before ?? (state === at?.state ? state.pages : undefined);
628
+ return state.wrappers.map((_, f) => (last = Math.max(last, pagesBefore?.[f] ?? last)));
629
+ }
630
+ const desc = blocks[item.unit];
455
631
  return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
456
632
  });
457
633
  pages = separateSheets(pages, layout);
458
- this.place(blocks, pages, layout);
634
+ const elementsOf = (item, i) => item.frame
635
+ ? frames.get(doc.child(i)).wrappers
636
+ : blocks[item.unit].fragments;
637
+ this.place(items.map((item, i) => elementsOf(item, i)), pages, layout);
459
638
  if (!this.composing) {
460
639
  // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
461
640
  let scale;
@@ -469,7 +648,7 @@ export class EditorView {
469
648
  if (measure)
470
649
  delete measure.lines;
471
650
  }
472
- const nodes = blocks.map((desc) => desc.node);
651
+ const nodes = items.map((_, i) => doc.child(i));
473
652
  // A block's spacing depends on its neighbours' styles: reuse stops a block earlier.
474
653
  const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale, 1) : undefined;
475
654
  const measureOf = (desc) => {
@@ -486,30 +665,109 @@ export class EditorView {
486
665
  found.lines ??= measureLines(desc, layoutPx());
487
666
  return found.lines;
488
667
  };
489
- const boxes = blocks.map((desc, i) => wordBox(blocks, i, measureOf(desc), () => lines(desc), layout[i]));
668
+ const tableOf = (frame, i) => {
669
+ let found = this.measures.get(frame.node);
670
+ if (!found?.table || this.stale.delete(frame.node)) {
671
+ const wrapper = frames.get(doc.child(i)).wrappers[0];
672
+ // Its blocks are measured with it (their heights, for a resize later).
673
+ for (let u = frame.first; u < frame.end; u++) {
674
+ const desc = blocks[u];
675
+ this.stale.delete(desc.node);
676
+ this.measures.set(desc.node, measureBox(desc, layoutPx()));
677
+ }
678
+ found = measureTable(frame, wrapper, blocks, layoutPx());
679
+ this.measures.set(frame.node, found);
680
+ }
681
+ return found;
682
+ };
683
+ const words = items.map((item) => item.frame ? TABLE_WORD : blocks[item.unit].word);
684
+ const boxes = items.map((item, i) => {
685
+ const pageHeight = contentHeight(layout[i].sheet.settings);
686
+ if (item.frame) {
687
+ const frame = item.frame;
688
+ const measure = tableOf(frame, i);
689
+ // A section break after it, or a page break before the next paragraph, ends its page.
690
+ const breakAfter = layout[i].breakAfter || !!words[i + 1]?.pageBreakBefore;
691
+ return tableBox(frame, measure, pageHeight, breakAfter, () => breaksOf(frame, measure, blocks, pageHeight, lines));
692
+ }
693
+ const desc = blocks[item.unit];
694
+ return wordBox(words, i, desc, measureOf(desc), () => lines(desc), layout[i]);
695
+ });
490
696
  const result = flowFrom(boxes, contentHeight(this.editor.settings), WORD_RULES, reuse);
491
697
  this.flowed = { nodes, result };
492
698
  this.stale.clear();
493
699
  const flowed = result.fragments;
494
- blocks = blocks.map((desc, i) => {
700
+ // Paragraphs: split where their fragments start. Tables: the rows each fragment shows,
701
+ // and their blocks split where a row is.
702
+ const splitsOf = new Map();
703
+ const parts = new Map();
704
+ items.forEach((item, i) => {
495
705
  const fragments = flowed[i] ?? [];
496
- const contentStart = starts[i] + 1;
497
- const splits = fragments.slice(1).map((fragment) => {
498
- const offset = lines(desc).starts[fragment.fromLine];
499
- // Never split a grapheme cluster across pages.
500
- return clusterBoundary(doc, contentStart + offset, false) - contentStart;
501
- });
706
+ if (item.unit !== undefined) {
707
+ const desc = blocks[item.unit];
708
+ const contentStart = units[item.unit].pos + 1;
709
+ splitsOf.set(item.unit, fragments.slice(1).map((fragment) => {
710
+ const offset = lines(desc).starts[fragment.fromLine];
711
+ // Never split a grapheme cluster across pages.
712
+ return clusterBoundary(doc, contentStart + offset, false) - contentStart;
713
+ }));
714
+ return;
715
+ }
716
+ const frame = item.frame;
717
+ const measure = this.measures.get(frame.node);
718
+ const cut = cutTable(frame, measure, fragments, blocks, lines);
719
+ parts.set(i, cut);
720
+ for (const [u, at] of cut.splits) {
721
+ const contentStart = units[u].pos + 1;
722
+ splitsOf.set(u, at.map((offset) => clusterBoundary(doc, contentStart + offset, false) - contentStart));
723
+ }
724
+ });
725
+ blocks = blocks.map((desc, u) => {
726
+ const splits = splitsOf.get(u) ?? [];
502
727
  const same = splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
503
- return same ? desc : word.render(desc.node, i, splits);
728
+ return same ? desc : word.render(desc.node, u, splits, units[u].cell);
504
729
  });
505
- pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
506
- applyGaps(blocks, pages, boxes);
507
- this.place(blocks, pages, layout);
730
+ pages = items.map((item, i) => {
731
+ const fragments = flowed[i] ?? [];
732
+ if (!item.frame)
733
+ return fragments.map((fragment) => fragment.page);
734
+ const node = doc.child(i);
735
+ const cut = parts.get(i);
736
+ const key = JSON.stringify([cut.parts, [...cut.partOf]]);
737
+ const kept = frames.get(node);
738
+ const pagesOf = fragments.map((fragment) => fragment.page);
739
+ // The same cut of the same table, its blocks' elements all in it: its wrappers stay.
740
+ if (kept.key === key && holdsAll(kept, item.frame, blocks)) {
741
+ frames.set(node, { ...kept, pages: pagesOf });
742
+ return pagesOf;
743
+ }
744
+ const wrappers = cut.parts.map((part, k) => frameElement(item.frame, part.rows, part.headers, (r, c) => this.cellContent(item.frame, r, c, blocks, (u, f) => cut.partOf.get(u)?.[f] === k), doc_));
745
+ frames.set(node, { wrappers, pages: pagesOf, key });
746
+ return pagesOf;
747
+ });
748
+ const firsts = items.map((item, i) => item.frame
749
+ ? frames.get(doc.child(i)).wrappers[0]
750
+ : blocks[item.unit].dom);
751
+ applyGaps(firsts, pages, boxes);
752
+ this.place(items.map((item, i) => elementsOf(item, i)), pages, layout);
508
753
  }
754
+ // (Wrappers no longer drawn are not in a page: `place` removed them.)
755
+ this.frames = frames;
756
+ this.frameAt = items.map((item, i) => {
757
+ const state = item.frame && frames.get(doc.child(i));
758
+ return state ? { node: doc.child(i), state } : undefined;
759
+ });
760
+ this.frameOf = new Map();
761
+ items.forEach((item, i) => {
762
+ if (!item.frame)
763
+ return;
764
+ for (const wrapper of frames.get(doc.child(i)).wrappers)
765
+ this.frameOf.set(wrapper, item.frame);
766
+ });
509
767
  this.blocks = blocks;
510
- this.starts = starts;
768
+ this.starts = units.map((unit) => unit.pos);
511
769
  this.indexOf = new Map(blocks.map((desc, i) => [desc, i]));
512
- this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
770
+ this.itemPages = new Map(items.map((_, i) => [doc.child(i), pages[i] ?? []]));
513
771
  this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
514
772
  this.unflowed = this.composing;
515
773
  this.observeSizes();
@@ -521,6 +779,44 @@ export class EditorView {
521
779
  if (this.composing)
522
780
  this.pending.push(...records);
523
781
  }
782
+ /**
783
+ * A floating picture reaches into the blocks after its paragraph (their lines go around it):
784
+ * a block that changed (new, drawn again or stale) on a page holding one has the blocks after
785
+ * it on that page and the next measured again. A new block counts on the page of the block
786
+ * before it, where `place` first puts it, and the next (it may have been that page's first);
787
+ * only blocks that changed reach on, not the ones this marks, so an edit re-measures three
788
+ * pages at most.
789
+ */
790
+ staleAroundFloats(doc, pagesOf, redrawn) {
791
+ const blocks = [];
792
+ let last = 0;
793
+ doc.forEach((node) => {
794
+ const known = pagesOf.get(node);
795
+ const pages = known?.length ? known : [last, last + 1];
796
+ last = known?.length ? known[known.length - 1] : last;
797
+ blocks.push({ node, pages, changed: !known || redrawn.has(node) || this.stale.has(node) });
798
+ });
799
+ // The pages floats are on now, and were on before (a float deleted or made inline leaves
800
+ // lines that went around it).
801
+ const floatPages = new Set();
802
+ for (const { node, pages } of blocks)
803
+ if (holdsFloat(node))
804
+ for (const p of pages)
805
+ floatPages.add(p);
806
+ for (const [node, pages] of pagesOf)
807
+ if (holdsFloat(node))
808
+ for (const p of pages)
809
+ floatPages.add(p);
810
+ if (!floatPages.size)
811
+ return;
812
+ let reach = -1;
813
+ for (const { node, pages, changed } of blocks) {
814
+ if (pages[0] <= reach)
815
+ this.stale.add(node);
816
+ if (changed && pages.some((p) => floatPages.has(p)))
817
+ reach = Math.max(reach, pages[pages.length - 1] + 1);
818
+ }
819
+ }
524
820
  /** A font's normal line height ratio, measured outside the host (no input to read back). */
525
821
  lineRatio = (family) => {
526
822
  let ratio = this.ratios.get(family);
@@ -537,9 +833,9 @@ export class EditorView {
537
833
  * blocks' section (one per page: `separateSheets`, section breaks). Anything else in the host
538
834
  * or a page (stray DOM) is removed.
539
835
  */
540
- place(blocks, pages, layout) {
836
+ place(elements, pages, layout) {
541
837
  const { host } = this;
542
- const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
838
+ const items = elements.flatMap((list, i) => list.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
543
839
  const count = (items[items.length - 1]?.page ?? 0) + 1;
544
840
  const sheets = [];
545
841
  pages.forEach((list, i) => {
@@ -585,6 +881,7 @@ export class EditorView {
585
881
  while (at) {
586
882
  const next = at.nextSibling;
587
883
  at.remove();
884
+ this.viewRemoved.add(at);
588
885
  at = next;
589
886
  }
590
887
  }
@@ -597,6 +894,27 @@ export class EditorView {
597
894
  }
598
895
  this.pages.length = count;
599
896
  }
897
+ /**
898
+ * What a table's cell shows in one of its fragments: its blocks' elements that `takes` puts
899
+ * there, and nested tables whole (where their first block goes).
900
+ */
901
+ cellContent(frame, r, c, blocks, takes) {
902
+ const out = [];
903
+ for (const item of frame.rows[r]?.cells[c]?.items ?? []) {
904
+ if ("frame" in item) {
905
+ const nested = item.frame;
906
+ if (!takes(nested.first, 0))
907
+ continue;
908
+ out.push(frameElement(nested, nested.rows.map((_, i) => i), [], (rr, cc) => this.cellContent(nested, rr, cc, blocks, () => true), this.host.ownerDocument));
909
+ continue;
910
+ }
911
+ blocks[item.unit].fragments.forEach((fragment, f) => {
912
+ if (takes(item.unit, f))
913
+ out.push(fragment);
914
+ });
915
+ }
916
+ return out;
917
+ }
600
918
  createPage() {
601
919
  const page = this.host.ownerDocument.createElement("section");
602
920
  page.className = "foli-page";
@@ -720,9 +1038,16 @@ export class EditorView {
720
1038
  }
721
1039
  return null;
722
1040
  }
723
- /** Whether `node` holds blocks rather than content: the host or a page. */
1041
+ /**
1042
+ * Whether `node` holds blocks rather than content: the host, a page, or a table's wrapper,
1043
+ * table, rows and cells.
1044
+ */
724
1045
  holdsBlocks(node) {
725
- return node === this.host || this.pages.includes(node);
1046
+ return (node === this.host ||
1047
+ this.pages.includes(node) ||
1048
+ (node.nodeType === Node.ELEMENT_NODE &&
1049
+ node.hasAttribute(FRAME_ATTR) &&
1050
+ !node.closest(`[${REPEATED_ATTR}]`)));
726
1051
  }
727
1052
  /** Index of the first block that starts at or after `pos` (the block count if none). */
728
1053
  blockFrom(pos) {
@@ -740,19 +1065,37 @@ export class EditorView {
740
1065
  /** Model position of a DOM point inside the host, or null if it is outside. */
741
1066
  posFromDOM(node, offset) {
742
1067
  const { host } = this;
1068
+ // In a header row drawn again (not document content): the first position below it.
1069
+ const at = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1070
+ const repeated = at?.closest(`[${REPEATED_ATTR}]`);
1071
+ if (repeated?.parentNode && host.contains(repeated)) {
1072
+ const parent = repeated.parentNode;
1073
+ return this.posFromDOM(parent, [...parent.childNodes].indexOf(repeated) + 1);
1074
+ }
743
1075
  if (this.holdsBlocks(node)) {
744
1076
  // Between fragments: the start of the first one after the point (a block start, or
745
1077
  // where a continuation starts), else the document end.
746
1078
  const range = host.ownerDocument.createRange();
747
1079
  range.setStart(node, offset);
1080
+ const posOf = (i, f) => f === 0
1081
+ ? this.starts[i]
1082
+ : this.starts[i] +
1083
+ 1 +
1084
+ this.blocks[i].splits[f - 1];
1085
+ // Without tables, blocks are in DOM order: the first one after the point. In a row split
1086
+ // across pages, a cell's continuation comes after the next cell: the earliest in the DOM.
1087
+ let best = null;
748
1088
  for (const [i, desc] of this.blocks.entries()) {
749
1089
  const f = desc.fragments.findIndex((fragment) => range.comparePoint(fragment, 0) >= 0);
750
- if (f === 0)
751
- return this.starts[i];
752
- if (f > 0)
753
- return this.starts[i] + 1 + desc.splits[f - 1];
1090
+ if (f < 0)
1091
+ continue;
1092
+ const dom = desc.fragments[f];
1093
+ if (!this.frames.size)
1094
+ return posOf(i, f);
1095
+ if (!best || dom.compareDocumentPosition(best.dom) & Node.DOCUMENT_POSITION_FOLLOWING)
1096
+ best = { i, f, dom };
754
1097
  }
755
- return this.state.doc.content.size;
1098
+ return best ? posOf(best.i, best.f) : this.state.doc.content.size;
756
1099
  }
757
1100
  const element = this.blockElement(node);
758
1101
  const owner = element ? this.owner.get(element) : undefined;
@@ -801,17 +1144,24 @@ export class EditorView {
801
1144
  const split = desc.splits.indexOf(offset);
802
1145
  if (split >= 0)
803
1146
  return fragmentStart(desc, split + 1);
804
- for (const leaf of desc.leaves) {
1147
+ // Deleted text hidden by the review view takes no caret: the shown text next to it does.
1148
+ const shown = desc.leaves.filter((leaf) => !hiddenIn(leaf.dom, desc.dom));
1149
+ for (const leaf of shown) {
805
1150
  if (leaf.dom.nodeType === Node.TEXT_NODE &&
806
1151
  leaf.offset <= offset &&
807
1152
  offset <= leaf.offset + leaf.size)
808
1153
  return { node: leaf.dom, offset: offset - leaf.offset };
809
1154
  }
810
- const next = desc.leaves.find((leaf) => leaf.offset >= offset);
811
- if (next)
1155
+ const next = shown.find((leaf) => leaf.offset >= offset);
1156
+ if (next) {
1157
+ if (next.dom.nodeType === Node.TEXT_NODE)
1158
+ return { node: next.dom, offset: 0 };
812
1159
  return before(next.dom);
813
- const last = desc.leaves[desc.leaves.length - 1];
1160
+ }
1161
+ const last = shown[shown.length - 1];
814
1162
  if (last) {
1163
+ if (last.dom.nodeType === Node.TEXT_NODE)
1164
+ return { node: last.dom, offset: last.dom.length };
815
1165
  const point = before(last.dom);
816
1166
  return { node: point.node, offset: point.offset + 1 };
817
1167
  }
@@ -830,21 +1180,43 @@ export class EditorView {
830
1180
  // (Its end, mapped alone, would be the start of the next block, not the end of the rule.)
831
1181
  if (sel.anchorNode === sel.focusNode && Math.abs(sel.anchorOffset - sel.focusOffset) === 1) {
832
1182
  const child = sel.anchorNode.childNodes[Math.min(sel.anchorOffset, sel.focusOffset)];
1183
+ // Around a table's (first) wrapper: the table selected whole.
1184
+ const table = child && this.frameOf.get(child);
1185
+ if (table)
1186
+ return NodeSelection.create(this.state.doc, table.pos);
833
1187
  const owner = child && this.owner.get(child);
834
1188
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
835
1189
  if (owner && !owner.node.isTextblock && NodeSelection.isSelectable(owner.node))
836
1190
  return NodeSelection.create(this.state.doc, this.starts[index]);
837
1191
  }
838
- const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
839
- const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
1192
+ // Several ranges (Firefox selects table cells so, one range per cell): from the first cell
1193
+ // to the last (a range's start is in its cell; its end is after it).
1194
+ const many = sel.rangeCount > 1;
1195
+ const first = many ? sel.getRangeAt(0) : null;
1196
+ const lastRange = many ? sel.getRangeAt(sel.rangeCount - 1) : null;
1197
+ const anchor = first
1198
+ ? this.posFromDOM(first.startContainer, first.startOffset)
1199
+ : this.posFromDOM(sel.anchorNode, sel.anchorOffset);
1200
+ const head = lastRange
1201
+ ? this.posFromDOM(lastRange.startContainer, lastRange.startOffset)
1202
+ : this.posFromDOM(sel.focusNode, sel.focusOffset);
840
1203
  if (anchor === null || head === null)
841
1204
  return null;
842
1205
  const { doc } = this.state;
1206
+ // The caret the view wrote for a cell selection (in its head cell): that selection.
1207
+ const current = this.state.selection;
1208
+ if (current instanceof CellSelection && anchor === head && anchor === this.cellCaret)
1209
+ return current;
1210
+ // Ends in two cells of one table: the cells between them.
1211
+ const a = cellAround(doc, anchor);
1212
+ const h = cellAround(doc, head);
1213
+ if (a && h && a.cell !== h.cell && a.table === h.table)
1214
+ return CellSelection.create(doc, a.cell, h.cell);
843
1215
  // Exactly around a selectable block leaf (a rule): the node selection that wrote it.
844
1216
  const from = Math.min(anchor, head);
845
1217
  const node = doc.nodeAt(from);
846
1218
  if (node &&
847
- node.isBlock &&
1219
+ (node.isBlock || node.type.name === "picture") &&
848
1220
  node.isAtom &&
849
1221
  Math.max(anchor, head) === from + node.nodeSize &&
850
1222
  NodeSelection.isSelectable(node))
@@ -859,9 +1231,75 @@ export class EditorView {
859
1231
  const desc = this.blocks[this.blockFrom(selection.from)];
860
1232
  return desc && this.starts[this.indexOf.get(desc) ?? -1] === selection.from ? desc : null;
861
1233
  }
1234
+ /** The span of the picture a node selection selects, if it selects one. */
1235
+ pictureSpan(pos) {
1236
+ for (const img of this.host.querySelectorAll(`[${PICTURE_ATTR}]`)) {
1237
+ const span = img.parentElement;
1238
+ // A floating picture's place in the text is its anchor.
1239
+ if (span && this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0) === pos)
1240
+ return span;
1241
+ }
1242
+ return null;
1243
+ }
1244
+ /** Marks the selected picture and gives it a resize handle (when the document is editable). */
1245
+ showSelectedPicture() {
1246
+ const { selection } = this.state;
1247
+ const span = selection instanceof NodeSelection && selection.node.type.name === "picture"
1248
+ ? this.pictureSpan(selection.from)
1249
+ : null;
1250
+ const handled = !!span?.querySelector("[data-foli-resize]");
1251
+ if (span === this.selectedPicture && (!span || handled === this.editable))
1252
+ return;
1253
+ this.selectedPicture?.removeAttribute(PICTURE_SELECTED_ATTR);
1254
+ this.selectedPicture?.querySelector("[data-foli-resize]")?.remove();
1255
+ this.selectedPicture = span;
1256
+ if (!span)
1257
+ return;
1258
+ injectStyles(this.host);
1259
+ span.setAttribute(PICTURE_SELECTED_ATTR, "");
1260
+ if (!this.editable)
1261
+ return;
1262
+ const handle = this.host.ownerDocument.createElement("span");
1263
+ handle.setAttribute("data-foli-resize", "");
1264
+ handle.setAttribute("aria-hidden", "true");
1265
+ span.append(handle);
1266
+ }
1267
+ /** Marks the cells of a cell selection (their table cell elements, on every page). */
1268
+ showSelectedCells() {
1269
+ const { selection } = this.state;
1270
+ const cells = [];
1271
+ if (selection instanceof CellSelection) {
1272
+ for (const pos of selection.cells) {
1273
+ const caret = Selection.near(this.state.doc.resolve(pos + 1), 1).from;
1274
+ const { node } = this.domFromPos(caret);
1275
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1276
+ const td = element?.closest("td");
1277
+ if (td instanceof HTMLElement)
1278
+ cells.push(td);
1279
+ }
1280
+ }
1281
+ for (const td of this.selectedCells)
1282
+ if (!cells.includes(td))
1283
+ td.classList.remove(CELL_CLASS);
1284
+ for (const td of cells)
1285
+ td.classList.add(CELL_CLASS);
1286
+ this.selectedCells = cells;
1287
+ this.host.toggleAttribute(CELLS_ATTR, cells.length > 0);
1288
+ if (cells.length)
1289
+ injectStyles(this.host);
1290
+ }
1291
+ /** The first wrapper of a node-selected table, if a table is selected. */
1292
+ selectedTable() {
1293
+ const { selection } = this.state;
1294
+ if (!(selection instanceof NodeSelection) || selection.node.type.name !== "table")
1295
+ return null;
1296
+ return this.frames.get(selection.node)?.wrappers[0] ?? null;
1297
+ }
862
1298
  /** Marks the element of a node-selected block, for styling (the DOM selection is around it). */
863
1299
  showSelectedNode() {
864
- const dom = this.selectedBlock()?.dom ?? null;
1300
+ this.showSelectedCells();
1301
+ this.showSelectedPicture();
1302
+ const dom = this.selectedBlock()?.dom ?? this.selectedTable();
865
1303
  if (dom === this.selectedDom)
866
1304
  return;
867
1305
  this.selectedDom?.classList.remove(SELECTED_CLASS);
@@ -907,12 +1345,20 @@ export class EditorView {
907
1345
  if (current && this.shows(current))
908
1346
  return;
909
1347
  }
910
- const selected = this.selectedBlock();
1348
+ const selected = this.selectedBlock()?.dom ?? this.selectedTable();
911
1349
  if (selected) {
912
- const point = before(selected.dom);
1350
+ const point = before(selected);
913
1351
  sel.setBaseAndExtent(point.node, point.offset, point.node, point.offset + 1);
914
1352
  return;
915
1353
  }
1354
+ // Cells: drawn by their class; the native caret stays in the head cell (ADR-0006).
1355
+ if (selection instanceof CellSelection) {
1356
+ const caret = Selection.near(doc.resolve(selection.head + 1), 1).from;
1357
+ this.cellCaret = caret;
1358
+ const point = this.domFromPos(caret);
1359
+ sel.collapse(point.node, point.offset);
1360
+ return;
1361
+ }
916
1362
  // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
917
1363
  // The model takes the snapped selection back on its next read of the DOM.
918
1364
  const from = clusterBoundary(doc, selection.from, false);
@@ -1028,6 +1474,402 @@ export class EditorView {
1028
1474
  return command ? this.run(command) : false;
1029
1475
  });
1030
1476
  }
1477
+ // ---------- column borders (10.7c) ----------
1478
+ /** A column border being dragged: its table and column, the column's width, the press, the guide. */
1479
+ drag = null;
1480
+ /** Whether this view set the host's cursor (an embedder's own cursor is left alone). */
1481
+ resizeCursor = false;
1482
+ /**
1483
+ * The column border of a top-level table near the pointer (within 4 px): an edge of the cell
1484
+ * under it (a grid line through a merged cell is no border), or the table's right edge from
1485
+ * outside; as the grid column left of it, with the table's px per twip. None in read-only
1486
+ * mode, during a composition, or while tracking (column widths do not change then).
1487
+ */
1488
+ columnBorder(event) {
1489
+ if (!this.editable || this.composing || trackState(this.state)?.on)
1490
+ return null;
1491
+ const target = event.target;
1492
+ const wrapper = target?.closest?.(`[${FRAME_ATTR}="table"]`);
1493
+ const element = wrapper?.querySelector(`:scope > table[${FRAME_ATTR}]`);
1494
+ if (!wrapper || !element || !this.host.contains(wrapper))
1495
+ return null;
1496
+ let table;
1497
+ for (const [node, frame] of this.frames)
1498
+ if (frame.wrappers.includes(wrapper))
1499
+ table = node;
1500
+ const grid = table?.attrs.grid ?? [];
1501
+ const total = grid.reduce((a, b) => a + b, 0);
1502
+ if (!table || !total)
1503
+ return null;
1504
+ const rect = element.getBoundingClientRect();
1505
+ const perTwip = rect.width / total;
1506
+ const edges = [];
1507
+ let x = rect.left;
1508
+ for (const width of grid) {
1509
+ x += width * perTwip;
1510
+ edges.push(x);
1511
+ }
1512
+ const near = (column) => Math.abs(event.clientX - edges[column]) <= 4;
1513
+ // The grid lines that are borders here: the cell's own edges, the table's right edge from
1514
+ // outside it, any line on the table's own border area (none in a row's empty places).
1515
+ const cell = target?.closest("td");
1516
+ let columns;
1517
+ if (cell && element.contains(cell)) {
1518
+ const box = cell.getBoundingClientRect();
1519
+ const at = (line) => edges.findIndex((edge) => Math.abs(edge - line) <= 3);
1520
+ columns = [at(box.left), at(box.right)].filter((c) => c >= 0);
1521
+ }
1522
+ else if (target === element)
1523
+ columns = grid.map((_w, i) => i);
1524
+ else if (element.contains(target))
1525
+ columns = [];
1526
+ else
1527
+ columns = [grid.length - 1];
1528
+ const column = columns.find(near);
1529
+ return column === undefined ? null : { table, column, perTwip, rect };
1530
+ }
1531
+ /** The pointer over a column border shows that it can be dragged. */
1532
+ onMouseMove = (event) => {
1533
+ if (this.drag)
1534
+ return;
1535
+ const near = event.buttons === 0 && this.columnBorder(event) !== null;
1536
+ if (near === this.resizeCursor)
1537
+ return;
1538
+ this.resizeCursor = near;
1539
+ this.host.style.cursor = near ? "col-resize" : "";
1540
+ };
1541
+ /**
1542
+ * A press on a column border (no Shift: Shift-click extends the selection) starts dragging it:
1543
+ * a guide line follows the pointer and the release moves the border by as much as the pointer
1544
+ * moved (`setColumnWidth`); a press without a move changes nothing; Escape, the button let go
1545
+ * elsewhere or the window losing the focus cancel.
1546
+ */
1547
+ startColumnDrag(event) {
1548
+ this.endDrag();
1549
+ if (event.shiftKey)
1550
+ return false;
1551
+ const border = this.columnBorder(event);
1552
+ if (!border)
1553
+ return false;
1554
+ // No caret or text selection from this press. Focus taken by it keeps the selection the
1555
+ // model has (the press places none).
1556
+ event.preventDefault();
1557
+ if (!this.hasFocus()) {
1558
+ this.host.focus({ preventScroll: true });
1559
+ this.writeSelection(true);
1560
+ }
1561
+ const doc = this.host.ownerDocument;
1562
+ const guide = doc.createElement("div");
1563
+ guide.setAttribute("aria-hidden", "true");
1564
+ Object.assign(guide.style, {
1565
+ position: "fixed",
1566
+ top: `${border.rect.top}px`,
1567
+ height: `${border.rect.height}px`,
1568
+ left: `${event.clientX}px`,
1569
+ width: "0",
1570
+ borderLeft: "1px dashed GrayText",
1571
+ pointerEvents: "none",
1572
+ zIndex: "2147483647",
1573
+ });
1574
+ doc.body.append(guide);
1575
+ const width = border.table.attrs.grid[border.column];
1576
+ this.drag = { ...border, width, startX: event.clientX, guide };
1577
+ doc.addEventListener("mousemove", this.onDragMove);
1578
+ doc.addEventListener("mouseup", this.onDragEnd);
1579
+ doc.addEventListener("keydown", this.onDragKey, true);
1580
+ doc.defaultView?.addEventListener("blur", this.onDragBlur);
1581
+ return true;
1582
+ }
1583
+ onDragMove = (event) => {
1584
+ if (!this.drag)
1585
+ return;
1586
+ // The button let go where no mouseup reached the page (another window, a menu): cancelled.
1587
+ if ((event.buttons & 1) === 0)
1588
+ this.endDrag();
1589
+ else
1590
+ this.drag.guide.style.left = `${event.clientX}px`;
1591
+ };
1592
+ onDragEnd = (event) => {
1593
+ const drag = this.endDrag();
1594
+ if (!drag)
1595
+ return;
1596
+ const moved = event.clientX - drag.startX;
1597
+ // A click on a border (no real move) is no resize.
1598
+ if (Math.abs(moved) < 2)
1599
+ return;
1600
+ // The table's position: a top-level block's.
1601
+ let pos = -1;
1602
+ this.state.doc.forEach((node, offset) => {
1603
+ if (node === drag.table)
1604
+ pos = offset;
1605
+ });
1606
+ if (pos >= 0)
1607
+ this.run(setColumnWidth(pos, drag.column, drag.width + moved / drag.perTwip));
1608
+ };
1609
+ onDragKey = (event) => {
1610
+ if (event.key !== "Escape")
1611
+ return;
1612
+ event.preventDefault();
1613
+ event.stopPropagation();
1614
+ this.endDrag();
1615
+ };
1616
+ onDragBlur = () => {
1617
+ this.endDrag();
1618
+ };
1619
+ /** Ends a drag (its guide and listeners gone) and returns it. */
1620
+ endDrag() {
1621
+ const { drag } = this;
1622
+ if (!drag)
1623
+ return null;
1624
+ this.drag = null;
1625
+ drag.guide.remove();
1626
+ const doc = this.host.ownerDocument;
1627
+ doc.removeEventListener("mousemove", this.onDragMove);
1628
+ doc.removeEventListener("mouseup", this.onDragEnd);
1629
+ doc.removeEventListener("keydown", this.onDragKey, true);
1630
+ doc.defaultView?.removeEventListener("blur", this.onDragBlur);
1631
+ if (this.resizeCursor) {
1632
+ this.resizeCursor = false;
1633
+ this.host.style.cursor = "";
1634
+ }
1635
+ return drag;
1636
+ }
1637
+ // ---------- pictures (10.8d) ----------
1638
+ /**
1639
+ * A press on a picture selects it (a node selection); on the selected picture's handle it
1640
+ * starts a resize that keeps its aspect ratio (`setPictureSize` on release, Escape cancels).
1641
+ */
1642
+ pictureMouseDown(event) {
1643
+ this.endResize();
1644
+ if (event.shiftKey || this.composing)
1645
+ return false;
1646
+ const target = event.target;
1647
+ const span = target?.closest?.(`[${PICTURE_ATTR}], [data-foli-resize]`)?.parentElement ?? null;
1648
+ if (!span || !this.host.contains(span))
1649
+ return false;
1650
+ const pos = this.posFromDOM(FLOAT_ANCHORS.get(span) ?? span, 0);
1651
+ if (pos === null)
1652
+ return false;
1653
+ event.preventDefault();
1654
+ if (!this.hasFocus())
1655
+ this.host.focus({ preventScroll: true });
1656
+ if (!(this.state.selection instanceof NodeSelection && this.state.selection.from === pos))
1657
+ this.dispatch(this.state.tr.setSelection(NodeSelection.create(this.state.doc, pos)));
1658
+ // Already selected: written again (the focus may have put a caret in the host).
1659
+ else
1660
+ this.writeSelection(true);
1661
+ const img = span.querySelector(`[${PICTURE_ATTR}]`);
1662
+ if (!img || !target?.closest("[data-foli-resize]") || !this.editable)
1663
+ return true;
1664
+ const rect = img.getBoundingClientRect();
1665
+ const width = Number.parseFloat(img.style.width) || rect.width;
1666
+ const scale = rect.width / width || 1;
1667
+ this.resize = {
1668
+ pos,
1669
+ img,
1670
+ width: rect.width,
1671
+ height: rect.height,
1672
+ scale,
1673
+ // No wider than the page's text (layout px).
1674
+ max: Math.max(this.textWidthEmu() / EMU_PER_PX, MIN_PICTURE),
1675
+ x: event.clientX,
1676
+ y: event.clientY,
1677
+ style: img.getAttribute("style") ?? "",
1678
+ };
1679
+ const doc = this.host.ownerDocument;
1680
+ doc.addEventListener("mousemove", this.onResizeMove);
1681
+ doc.addEventListener("mouseup", this.onResizeEnd);
1682
+ doc.addEventListener("keydown", this.onResizeKey, true);
1683
+ doc.defaultView?.addEventListener("blur", this.onResizeCancel);
1684
+ return true;
1685
+ }
1686
+ /** The size (layout px) a resize gives at the pointer: the larger move, the ratio kept. */
1687
+ resizedTo(event) {
1688
+ const r = this.resize;
1689
+ const ratio = r.height / r.width;
1690
+ const dx = event.clientX - r.x;
1691
+ const dy = (event.clientY - r.y) / ratio;
1692
+ const width = Math.min(Math.max((r.width + (Math.abs(dx) > Math.abs(dy) ? dx : dy)) / r.scale, MIN_PICTURE), r.max);
1693
+ return { width, height: width * ratio };
1694
+ }
1695
+ onResizeMove = (event) => {
1696
+ if (!this.resize)
1697
+ return;
1698
+ if ((event.buttons & 1) === 0) {
1699
+ this.onResizeCancel();
1700
+ return;
1701
+ }
1702
+ const { width, height } = this.resizedTo(event);
1703
+ this.resize.img.style.width = `${width}px`;
1704
+ this.resize.img.style.height = `${height}px`;
1705
+ };
1706
+ onResizeEnd = (event) => {
1707
+ if (!this.resize)
1708
+ return;
1709
+ const { width, height } = this.resizedTo(event);
1710
+ const r = this.endResize();
1711
+ if (!r)
1712
+ return;
1713
+ // No real move: nothing changes (a jiggle drawn while moving goes back).
1714
+ const moved = Math.abs(event.clientX - r.x) >= 2 || Math.abs(event.clientY - r.y) >= 2;
1715
+ const applied = moved &&
1716
+ this.run(setPictureSize(r.pos, Math.round(width * EMU_PER_PX), Math.round(height * EMU_PER_PX)));
1717
+ // Not applied (no move, tracking, the picture gone): as it was.
1718
+ if (!applied)
1719
+ r.img.setAttribute("style", r.style);
1720
+ };
1721
+ onResizeKey = (event) => {
1722
+ if (event.key !== "Escape")
1723
+ return;
1724
+ event.preventDefault();
1725
+ event.stopPropagation();
1726
+ this.onResizeCancel();
1727
+ };
1728
+ onResizeCancel = () => {
1729
+ const r = this.endResize();
1730
+ if (r)
1731
+ r.img.setAttribute("style", r.style);
1732
+ };
1733
+ /** Ends a resize (its listeners gone) and returns it. */
1734
+ endResize() {
1735
+ const r = this.resize;
1736
+ if (!r)
1737
+ return null;
1738
+ this.resize = null;
1739
+ const doc = this.host.ownerDocument;
1740
+ doc.removeEventListener("mousemove", this.onResizeMove);
1741
+ doc.removeEventListener("mouseup", this.onResizeEnd);
1742
+ doc.removeEventListener("keydown", this.onResizeKey, true);
1743
+ doc.defaultView?.removeEventListener("blur", this.onResizeCancel);
1744
+ return r;
1745
+ }
1746
+ textWidthEmu() {
1747
+ return textWidthEmu(this.state);
1748
+ }
1749
+ /** Image files in a transfer (paste or drop), when the app takes uploads. */
1750
+ imageFiles(data) {
1751
+ if (!this.upload || !this.editable || !data)
1752
+ return [];
1753
+ // A clipboard object from code may have no files.
1754
+ return [...(data.files ?? [])].filter((file) => file.type.startsWith("image/"));
1755
+ }
1756
+ /** Whether a drag carries files (from outside the page). */
1757
+ static carriesFiles = (event) => [...(event.dataTransfer?.types ?? [])].includes("Files");
1758
+ onDragOver = (event) => {
1759
+ if (!EditorView.carriesFiles(event))
1760
+ return;
1761
+ // Files dropped here never open in the page (unsaved work would be lost).
1762
+ event.preventDefault();
1763
+ const images = [...(event.dataTransfer?.items ?? [])].some((i) => i.type.startsWith("image/"));
1764
+ if (event.dataTransfer)
1765
+ event.dataTransfer.dropEffect = images && this.upload && this.editable ? "copy" : "none";
1766
+ };
1767
+ onDrop = (event) => {
1768
+ if (!EditorView.carriesFiles(event))
1769
+ return;
1770
+ event.preventDefault();
1771
+ const files = this.imageFiles(event.dataTransfer);
1772
+ if (!files.length || this.composing)
1773
+ return;
1774
+ // The place the files were dropped.
1775
+ const doc = this.host.ownerDocument;
1776
+ const point = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
1777
+ const range = point ? null : doc.caretRangeFromPoint?.(event.clientX, event.clientY);
1778
+ const node = point?.offsetNode ?? range?.startContainer;
1779
+ const offset = point?.offset ?? range?.startOffset ?? 0;
1780
+ const pos = node ? this.posFromDOM(node, offset) : null;
1781
+ if (pos !== null)
1782
+ this.dispatch(this.state.tr.setSelection(TextSelection.near(this.state.doc.resolve(pos))));
1783
+ void this.insertFiles(files);
1784
+ };
1785
+ /**
1786
+ * Inserts image files where the selection is now, one picture each, in order: each measured
1787
+ * first (one the browser cannot show is skipped, not uploaded), then given to the `upload`
1788
+ * option, then inserted at its natural size (96 px per inch) no wider than the page's text,
1789
+ * where the selection was, however the document changed meanwhile (after a composition that
1790
+ * runs then). A file whose upload fails is skipped (reported on the console). Resolves to
1791
+ * the number inserted (none without `upload`); never rejects.
1792
+ */
1793
+ async insertFiles(files) {
1794
+ const upload = this.upload;
1795
+ if (!upload || !this.editable)
1796
+ return 0;
1797
+ // The insertion point, mapped through every change until the pictures go in.
1798
+ let at = this.state.selection.from;
1799
+ const replace = !this.state.selection.empty;
1800
+ // Another document (`setDocument` notifies with no transaction): the files are not for it.
1801
+ let lost = false;
1802
+ let mapped = this.state.doc;
1803
+ // The user's own selection while a picture goes in, mapped, to give back after it.
1804
+ let user = null;
1805
+ const unsubscribe = this.editor.subscribe((state, transactions) => {
1806
+ for (const tr of transactions) {
1807
+ at = tr.mapping.map(at);
1808
+ if (user)
1809
+ user = user.map(tr.doc, tr.mapping);
1810
+ }
1811
+ if (!transactions.length && state.doc !== mapped)
1812
+ lost = true;
1813
+ mapped = state.doc;
1814
+ });
1815
+ let inserted = 0;
1816
+ try {
1817
+ for (const file of files) {
1818
+ if (!file.type.startsWith("image/"))
1819
+ continue;
1820
+ const size = await measureImageFile(file, this.host.ownerDocument);
1821
+ if (this.destroyed)
1822
+ return inserted;
1823
+ if (!size)
1824
+ continue;
1825
+ let answer;
1826
+ try {
1827
+ answer = await upload(file);
1828
+ }
1829
+ catch (error) {
1830
+ console.warn(`Foli: the upload of ${file.name} failed`, error);
1831
+ continue;
1832
+ }
1833
+ const { src, alt, decorative } = typeof answer === "string" ? { src: answer } : (answer ?? { src: "" });
1834
+ if (typeof src !== "string" || !src)
1835
+ continue;
1836
+ // The browser owns the DOM during a composition: the picture goes in after it.
1837
+ while (this.composing && !this.destroyed)
1838
+ await new Promise((r) => setTimeout(r, 50));
1839
+ if (this.destroyed || !this.editable || lost)
1840
+ return inserted;
1841
+ const scale = Math.min(1, this.textWidthEmu() / (size.width * EMU_PER_PX));
1842
+ // A `data:` URL says its own type (an app may have converted the file).
1843
+ const type = /^data:([^;,]+)/i.exec(src)?.[1]?.toLowerCase() ?? file.type;
1844
+ const picture = {
1845
+ contentType: type,
1846
+ ...(src.startsWith("data:") ? { data: src } : { url: src }),
1847
+ width: Math.max(1, Math.round(size.width * EMU_PER_PX * scale)),
1848
+ height: Math.max(1, Math.round(size.height * EMU_PER_PX * scale)),
1849
+ ...(typeof alt === "string" && alt.trim() ? { alt } : {}),
1850
+ ...(decorative === true ? { decorative } : {}),
1851
+ };
1852
+ const { doc, selection } = this.state;
1853
+ const pos = Math.min(at, doc.content.size);
1854
+ // The first picture replaces what was selected at the paste (still selected there).
1855
+ const here = replace && inserted === 0 && selection.from === pos;
1856
+ // A caret the user moved elsewhere meanwhile stays there.
1857
+ const elsewhere = !here && !(selection.empty && selection.from === pos);
1858
+ user = elsewhere ? selection : null;
1859
+ if (!here)
1860
+ this.dispatch(this.state.tr.setSelection(TextSelection.near(doc.resolve(pos))));
1861
+ if (this.run(insertPicture(picture, { requireAlt: false })))
1862
+ inserted++;
1863
+ if (user)
1864
+ this.dispatch(this.state.tr.setSelection(user));
1865
+ user = null;
1866
+ }
1867
+ return inserted;
1868
+ }
1869
+ finally {
1870
+ unsubscribe();
1871
+ }
1872
+ }
1031
1873
  /**
1032
1874
  * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
1033
1875
  * selection to the start of the next block, so typing over it would merge the two blocks.
@@ -1040,6 +1882,26 @@ export class EditorView {
1040
1882
  setTimeout(() => (this.pointerFocus = false));
1041
1883
  if (event.button !== 0)
1042
1884
  return;
1885
+ if (this.startColumnDrag(event))
1886
+ return;
1887
+ if (this.pictureMouseDown(event))
1888
+ return;
1889
+ // A click puts a caret where it lands, even on the one a cell selection wrote.
1890
+ if (!event.shiftKey)
1891
+ this.cellCaret = null;
1892
+ // A header row drawn again is not document content: the caret goes below it.
1893
+ const repeated = event.target?.closest?.(`[${REPEATED_ATTR}]`);
1894
+ if (repeated && this.host.contains(repeated) && !event.shiftKey) {
1895
+ const pos = this.posFromDOM(repeated, 0);
1896
+ if (pos !== null) {
1897
+ event.preventDefault();
1898
+ if (!this.hasFocus())
1899
+ this.host.focus({ preventScroll: true });
1900
+ const $pos = this.state.doc.resolve(pos);
1901
+ this.dispatch(this.state.tr.setSelection(Selection.near($pos)));
1902
+ }
1903
+ return;
1904
+ }
1043
1905
  const element = this.blockElement(event.target);
1044
1906
  const owner = element ? this.owner.get(element) : undefined;
1045
1907
  const index = owner ? (this.indexOf.get(owner) ?? -1) : -1;
@@ -1120,7 +1982,35 @@ export class EditorView {
1120
1982
  }
1121
1983
  // Up/Down on a textblock's first/last line next to a rule select it (only the view knows
1122
1984
  // lines; measured only when a rule is beside the block); else the browser moves the caret.
1985
+ // Shift+arrows in a table: cells selected grow by a cell; from text in a cell, Shift+Up or
1986
+ // Down starts a cell selection once the head is on the cell's first or last line.
1987
+ const shift = {
1988
+ "Shift-ArrowUp": ["row", -1],
1989
+ "Shift-ArrowDown": ["row", 1],
1990
+ "Shift-ArrowLeft": ["column", -1],
1991
+ "Shift-ArrowRight": ["column", 1],
1992
+ };
1993
+ const growing = Object.hasOwn(shift, name) ? shift[name] : undefined;
1994
+ if (growing) {
1995
+ const [axis, dir] = growing;
1996
+ const grow = extendCellSelection(axis, dir);
1997
+ const leaving = this.state.selection instanceof CellSelection ||
1998
+ (axis === "row" && this.caretOnEdgeLine(dir, true));
1999
+ if (leaving && grow(this.state) && this.run(grow)) {
2000
+ event.preventDefault();
2001
+ return;
2002
+ }
2003
+ }
1123
2004
  const vertical = name === "ArrowUp" ? -1 : name === "ArrowDown" ? 1 : 0;
2005
+ // In a table, from a cell's first or last line: the cell above or below, or out of the
2006
+ // table (browsers go to the next cell in the DOM, or across pages to the wrong row).
2007
+ const cells = vertical ? goToCellVertically(vertical) : null;
2008
+ // (A selection of a cell's whole content, Tab's, moves as the cell: no line to measure.)
2009
+ const onEdge = () => !this.state.selection.empty || this.caretOnEdgeLine(vertical);
2010
+ if (cells?.(this.state) && onEdge() && this.run(cells)) {
2011
+ event.preventDefault();
2012
+ return;
2013
+ }
1124
2014
  const across = vertical ? arrowAcrossLeaf(vertical, "line") : null;
1125
2015
  if (across?.(this.state) && this.caretOnEdgeLine(vertical) && this.run(across)) {
1126
2016
  event.preventDefault();
@@ -1130,9 +2020,10 @@ export class EditorView {
1130
2020
  * Whether the caret is on the first (`dir` -1) or last (1) line of its textblock, in the
1131
2021
  * block's first or last fragment (a block split across pages has several).
1132
2022
  */
1133
- caretOnEdgeLine(dir) {
2023
+ caretOnEdgeLine(dir, focusOnly = false) {
1134
2024
  const sel = this.host.ownerDocument.getSelection();
1135
- if (!sel?.rangeCount || !sel.isCollapsed || !sel.focusNode)
2025
+ // `focusOnly`: a range's head (Shift+arrows), else only a caret.
2026
+ if (!sel?.rangeCount || (!focusOnly && !sel.isCollapsed) || !sel.focusNode)
1136
2027
  return false;
1137
2028
  const element = this.blockElement(sel.focusNode);
1138
2029
  const desc = element ? this.owner.get(element) : undefined;
@@ -1143,7 +2034,10 @@ export class EditorView {
1143
2034
  return false;
1144
2035
  if (!desc.node.content.size)
1145
2036
  return true;
1146
- const caret = sel.getRangeAt(0).getClientRects()[0];
2037
+ const at = this.host.ownerDocument.createRange();
2038
+ at.setStart(sel.focusNode, sel.focusOffset);
2039
+ at.collapse(true);
2040
+ const caret = at.getClientRects()[0];
1147
2041
  const lines = this.host.ownerDocument.createRange();
1148
2042
  lines.selectNodeContents(fragment);
1149
2043
  const rects = lines.getClientRects();
@@ -1282,13 +2176,13 @@ export class EditorView {
1282
2176
  this.onCompositionEnd();
1283
2177
  };
1284
2178
  onMutations = (records) => {
1285
- this.pending.push(...records);
1286
- if (!this.composing)
2179
+ this.pending.push(...records.filter((r) => !handleOnly(r)));
2180
+ if (!this.composing && this.pending.length)
1287
2181
  this.flush();
1288
2182
  };
1289
2183
  /** Reads back every DOM change recorded so far. */
1290
2184
  flush() {
1291
- const records = [...this.pending, ...this.observer.takeRecords()];
2185
+ const records = [...this.pending, ...this.observer.takeRecords().filter((r) => !handleOnly(r))];
1292
2186
  this.pending = [];
1293
2187
  if (records.length)
1294
2188
  this.readBack(records);
@@ -1331,30 +2225,59 @@ export class EditorView {
1331
2225
  else
1332
2226
  node.childNodes.forEach(walk);
1333
2227
  };
1334
- let first = true;
1335
- // Block-level nodes in order: inside pages and containers, and anything else in the host.
1336
- const blockLevel = [];
2228
+ // Block-level nodes: inside pages and tables, and anything else in the host.
2229
+ let stray = false;
1337
2230
  const collect = (parent) => {
1338
2231
  for (const child of parent.childNodes) {
2232
+ if (this.owner.has(child))
2233
+ continue;
2234
+ // Drawn, not document content (a repeated header row): no text of the model.
2235
+ if (child.getAttribute?.("contenteditable") === "false")
2236
+ continue;
1339
2237
  if (this.holdsBlocks(child))
1340
2238
  collect(child);
1341
- else
1342
- blockLevel.push(child);
2239
+ // Text outside every block (an element the browser added): a block the model does not
2240
+ // have. An empty stray node (an extension's marker) holds none; the re-render removes it.
2241
+ else if (child.textContent)
2242
+ stray = true;
1343
2243
  }
1344
2244
  };
1345
2245
  collect(this.host);
1346
- let previousOwner;
1347
- for (const child of blockLevel) {
1348
- const owner = this.owner.get(child);
1349
- // An empty stray node (an extension's marker) holds no text; the re-render removes it.
1350
- if (!owner && !child.textContent)
2246
+ if (stray) {
2247
+ // shortcut: a change that adds blocks cannot be read back yet; it is dropped.
2248
+ console.warn("Foli: discarded a DOM change that adds blocks or line breaks");
2249
+ this.rerender();
2250
+ return;
2251
+ }
2252
+ // Each block's fragments are one text, blocks in document order (a row split across pages
2253
+ // has its cells' fragments on two pages).
2254
+ // A block whose elements the browser removed (merging it into another) has no text there.
2255
+ // One missing without a recorded removal was never placed (drawn during a composition):
2256
+ // its text counts as unchanged, never as deleted.
2257
+ const removed = new Set(records.flatMap((record) => [...record.removedNodes]).filter((n) => !this.viewRemoved.has(n)));
2258
+ const removedByInput = (node) => {
2259
+ for (let at = node; at; at = at.parentNode)
2260
+ if (removed.has(at))
2261
+ return true;
2262
+ return false;
2263
+ };
2264
+ let first = true;
2265
+ for (const desc of this.blocks) {
2266
+ const shown = desc.fragments.filter((fragment) => this.host.contains(fragment));
2267
+ if (!shown.length && !desc.fragments.some(removedByInput)) {
2268
+ if (!first)
2269
+ domText += BLOCK_SEPARATOR;
2270
+ first = false;
2271
+ domText += textOfBlock(desc.node);
2272
+ continue;
2273
+ }
2274
+ if (!shown.length)
1351
2275
  continue;
1352
- // The fragments of one block are one text; anything else starts a new block.
1353
- if (!first && !(owner && owner === previousOwner))
2276
+ if (!first)
1354
2277
  domText += BLOCK_SEPARATOR;
1355
2278
  first = false;
1356
- previousOwner = owner;
1357
- walk(child);
2279
+ for (const fragment of shown)
2280
+ walk(fragment);
1358
2281
  }
1359
2282
  const { doc } = this.state;
1360
2283
  const lineStarts = [];
@@ -1363,14 +2286,7 @@ export class EditorView {
1363
2286
  if (i > 0)
1364
2287
  modelText += BLOCK_SEPARATOR;
1365
2288
  lineStarts.push(modelText.length);
1366
- block.forEach((child) => {
1367
- // A tab is text in the DOM (a "\t" text node).
1368
- modelText += child.isText
1369
- ? (child.text ?? "")
1370
- : child.type.name === "tab"
1371
- ? "\t"
1372
- : HARD_BREAK;
1373
- });
2289
+ modelText += textOfBlock(block);
1374
2290
  });
1375
2291
  /** Model position of an offset in `modelText`. */
1376
2292
  const posAt = (offset) => {
@@ -1446,8 +2362,11 @@ export class EditorView {
1446
2362
  return;
1447
2363
  event.preventDefault();
1448
2364
  const context = wordContext(this.state);
1449
- const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
1450
- event.clipboardData.setData("text/plain", text);
2365
+ // Selected cells are copied as a table of their own (ADR-0006).
2366
+ const table = selection instanceof CellSelection ? cellsAsTable(selection) : null;
2367
+ const source = table ? doc.type.create(null, table) : doc;
2368
+ const { text, html, json } = serializeRange(source, table ? 0 : selection.from, table ? source.content.size : selection.to, this.host.ownerDocument, { context, ratio: this.lineRatio });
2369
+ event.clipboardData.setData("text/plain", table ? cellsText(table) : text);
1451
2370
  event.clipboardData.setData("text/html", html);
1452
2371
  event.clipboardData.setData(FOLI_MIME, json);
1453
2372
  };
@@ -1469,6 +2388,12 @@ export class EditorView {
1469
2388
  return;
1470
2389
  this.syncSelection();
1471
2390
  const data = event.clipboardData;
2391
+ // An image alone (a screenshot, an image copied from a page): a picture.
2392
+ const files = plain ? [] : this.imageFiles(data);
2393
+ if (files.length && !data.getData(FOLI_MIME) && !data.getData("text/plain").trim()) {
2394
+ void this.insertFiles(files);
2395
+ return;
2396
+ }
1472
2397
  this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data, !plain);
1473
2398
  };
1474
2399
  /**
@@ -1530,14 +2455,27 @@ export class EditorView {
1530
2455
  throw new TransformError("Open content is pasted as a slice");
1531
2456
  insertBlocks(tr, doc);
1532
2457
  };
1533
- const strategies = [asSlice, asBlocks];
2458
+ // Rows (a table alone) into a table fill its cells from the selected one (ADR-0006).
2459
+ const intoCells = (tr) => {
2460
+ if (only?.type.name !== "table" || !pasteCells(tr, only))
2461
+ throw new TransformError("Only rows are pasted into cells");
2462
+ };
2463
+ const strategies = [intoCells, asSlice, asBlocks];
1534
2464
  for (const strategy of strategies) {
1535
2465
  const tr = state.tr;
1536
2466
  try {
1537
- tr.deleteSelection();
2467
+ // Other content over selected cells goes into the anchor cell; across a table's edge,
2468
+ // whole rows go (`deleteSelectionKeepingTables`).
2469
+ if (strategy !== intoCells && !tr.selection.empty)
2470
+ deleteSelectionKeepingTables(tr, true);
1538
2471
  strategy(tr);
1539
- if (envelope && envelope !== wordContext(state)?.envelope)
2472
+ // A pasted table never ends the body nor touches another table (Word's rules).
2473
+ keepTablesApart(tr);
2474
+ const current = wordContext(state)?.envelope;
2475
+ if (envelope && current && envelope !== current) {
1540
2476
  withEnvelope(tr, envelope);
2477
+ setComments(tr, current.comments, envelope.comments);
2478
+ }
1541
2479
  }
1542
2480
  catch (error) {
1543
2481
  if (error instanceof TransformError)
@@ -1553,6 +2491,18 @@ export class EditorView {
1553
2491
  this.syncSelection();
1554
2492
  };
1555
2493
  }
2494
+ /** Copied cells as text, as spreadsheets read it: a tab between cells, a line per row. */
2495
+ function cellsText(table) {
2496
+ const rows = [];
2497
+ table.forEach((row) => {
2498
+ const cells = [];
2499
+ row.forEach((cell) => {
2500
+ cells.push(cell.textBetween(0, cell.content.size, " "));
2501
+ });
2502
+ rows.push(cells.join("\t"));
2503
+ });
2504
+ return rows.join("\n");
2505
+ }
1556
2506
  /**
1557
2507
  * Pastes whole blocks at the caret (after deleting the selection): before or after the caret's
1558
2508
  * paragraph, else between its two halves (an empty one is replaced as a slice first).
@@ -1583,6 +2533,170 @@ function insertBlocks(tr, doc) {
1583
2533
  function layoutScale(page, settings) {
1584
2534
  return page.getBoundingClientRect().width / (settings.pageSize.width * PX_PER_MM) || 1;
1585
2535
  }
2536
+ /** The innermost cell around pos (the position before it) and its table's, or null. */
2537
+ function cellAround(doc, pos) {
2538
+ const $pos = doc.resolve(pos);
2539
+ for (let d = $pos.depth; d > 2; d--)
2540
+ if ($pos.node(d).type.name === "tableCell")
2541
+ return { cell: $pos.before(d), table: $pos.before(d - 2) };
2542
+ return null;
2543
+ }
2544
+ /** A block's text as the read-back compares it: a tab "\t", other inline leaves one character. */
2545
+ function textOfBlock(block) {
2546
+ let text = "";
2547
+ block.forEach((child) => {
2548
+ // A tab is text in the DOM (a "\t" text node).
2549
+ text += child.isText ? (child.text ?? "") : child.type.name === "tab" ? "\t" : HARD_BREAK;
2550
+ });
2551
+ return text;
2552
+ }
2553
+ /** Whether a table's wrappers hold every element of its blocks (none was drawn anew). */
2554
+ function holdsAll(state, frame, blocks) {
2555
+ for (let u = frame.first; u < frame.end; u++)
2556
+ for (const fragment of blocks[u].fragments)
2557
+ if (!state.wrappers.some((wrapper) => wrapper.contains(fragment)))
2558
+ return false;
2559
+ return true;
2560
+ }
2561
+ /** Measures a table drawn whole: its height, its rows and where its blocks start. */
2562
+ function measureTable(frame, wrapper, blocks, scale) {
2563
+ const box = wrapper.getBoundingClientRect();
2564
+ const rows = [...wrapper.querySelectorAll(":scope > table > tbody > tr")].map((tr) => {
2565
+ const rect = tr.getBoundingClientRect();
2566
+ return { top: (rect.top - box.top) / scale, bottom: (rect.bottom - box.top) / scale };
2567
+ });
2568
+ const tops = new Map();
2569
+ for (let u = frame.first; u < frame.end; u++) {
2570
+ const dom = blocks[u].dom;
2571
+ // A block of a cell a merge covers is not shown: it goes with its row.
2572
+ const hidden = !!dom.closest(`[${FRAME_ATTR}="covered"]`);
2573
+ tops.set(u, hidden ? null : (dom.getBoundingClientRect().top - box.top) / scale);
2574
+ }
2575
+ return {
2576
+ height: box.height / scale,
2577
+ marginTop: 0,
2578
+ marginBottom: 0,
2579
+ box: 0,
2580
+ table: { rows, tops },
2581
+ };
2582
+ }
2583
+ /**
2584
+ * Where a table may break across pages (from its top, sorted): after each row, and inside a row
2585
+ * at its cells' line ends, unless the row may not split (`cantSplit`, unless taller than a
2586
+ * page), is part of a vertical merge or holds a nested table (shortcut: those split only
2587
+ * between rows; a nested table stays whole within its row).
2588
+ */
2589
+ export function breaksOf(frame, measure, blocks, pageHeight, lines) {
2590
+ const t = measure.table;
2591
+ if (t.breaks)
2592
+ return t.breaks;
2593
+ const out = [];
2594
+ frame.rows.forEach((row, r) => {
2595
+ const { top, bottom } = t.rows[r] ?? { top: 0, bottom: 0 };
2596
+ const merged = row.cells.some((cell) => cell.vMerge !== null);
2597
+ const nested = row.cells.some((cell) => cell.items.some((item) => "frame" in item));
2598
+ const splits = (!row.cantSplit || bottom - top > pageHeight) && !merged && !nested;
2599
+ if (splits)
2600
+ for (const cell of row.cells)
2601
+ for (const item of cell.items) {
2602
+ if ("frame" in item)
2603
+ continue;
2604
+ const unitTop = t.tops.get(item.unit);
2605
+ if (unitTop === null || unitTop === undefined)
2606
+ continue;
2607
+ for (const b of lines(blocks[item.unit]).bottoms) {
2608
+ const y = unitTop + b;
2609
+ if (y > top + 0.5 && y < bottom - 0.5)
2610
+ out.push(y);
2611
+ }
2612
+ }
2613
+ out.push(r === frame.rows.length - 1 ? Math.max(bottom, measure.height) : bottom);
2614
+ });
2615
+ out.sort((a, b) => a - b);
2616
+ t.breaks = out.filter((y, k) => k === 0 || y - out[k - 1] > 0.5);
2617
+ return t.breaks;
2618
+ }
2619
+ /** What the flow needs of a table: its height, where it may break, its header rows' height. */
2620
+ function tableBox(frame, measure, pageHeight, breakAfter, breaks) {
2621
+ const t = measure.table;
2622
+ const header = frame.headers ? (t.rows[frame.headers - 1]?.bottom ?? 0) : 0;
2623
+ return {
2624
+ height: measure.height,
2625
+ marginTop: 0,
2626
+ marginBottom: 0,
2627
+ pageHeight,
2628
+ repeat: header,
2629
+ // Word keeps no lines together across a table's rows (a cell's paragraph splits anywhere).
2630
+ anyLine: true,
2631
+ lines: breaks,
2632
+ breaksAfter: () => (breakAfter ? [breaks().length - 1] : []),
2633
+ };
2634
+ }
2635
+ /**
2636
+ * A flowed table cut into its fragments: the rows each shows (a row split across pages in
2637
+ * both), the header rows drawn again above a continuation, the fragment of the table each
2638
+ * block's fragments go in, and where a block of a split row splits (content offsets).
2639
+ */
2640
+ export function cutTable(frame, measure, fragments, blocks, lines) {
2641
+ const t = measure.table;
2642
+ const all = frame.rows.map((_, r) => r);
2643
+ const partOf = new Map();
2644
+ const splits = new Map();
2645
+ if (fragments.length <= 1 || !t.breaks) {
2646
+ for (let u = frame.first; u < frame.end; u++)
2647
+ partOf.set(u, [0]);
2648
+ return { parts: [{ rows: all, headers: [] }], partOf, splits };
2649
+ }
2650
+ const breaks = t.breaks;
2651
+ const bounds = fragments.map((f) => [
2652
+ f.fromLine ? breaks[f.fromLine - 1] : 0,
2653
+ f.toLine === Number.POSITIVE_INFINITY ? measure.height : breaks[f.toLine - 1],
2654
+ ]);
2655
+ const parts = bounds.map(([y0, y1], k) => {
2656
+ const rows = all.filter((r) => {
2657
+ const row = t.rows[r] ?? { top: 0, bottom: 0 };
2658
+ return row.top < y1 - 0.5 && row.bottom > y0 + 0.5;
2659
+ });
2660
+ const repeat = k > 0 && frame.headers > 0 && (rows[0] ?? 0) >= frame.headers;
2661
+ return { rows, headers: repeat ? all.slice(0, frame.headers) : [] };
2662
+ });
2663
+ frame.rows.forEach((row, r) => {
2664
+ const ks = parts.flatMap((part, k) => (part.rows.includes(r) ? [k] : []));
2665
+ const firstPart = ks[0] ?? 0;
2666
+ for (const cell of row.cells)
2667
+ for (const item of cell.items) {
2668
+ if ("frame" in item) {
2669
+ for (let u = item.frame.first; u < item.frame.end; u++)
2670
+ partOf.set(u, [firstPart]);
2671
+ continue;
2672
+ }
2673
+ const u = item.unit;
2674
+ const top = t.tops.get(u);
2675
+ if (ks.length < 2 || top === null || top === undefined) {
2676
+ partOf.set(u, [firstPart]);
2677
+ continue;
2678
+ }
2679
+ // Each line on the page its bottom fits; consecutive lines on one page are a fragment.
2680
+ const { starts, bottoms } = lines(blocks[u]);
2681
+ const runs = [];
2682
+ const at = [];
2683
+ bottoms.forEach((b, i) => {
2684
+ const y = top + b;
2685
+ const k = ks.find((part) => y <= bounds[part][1] + 0.5) ??
2686
+ ks.at(-1);
2687
+ if (runs.at(-1) !== k) {
2688
+ if (runs.length)
2689
+ at.push(starts[i]);
2690
+ runs.push(k);
2691
+ }
2692
+ });
2693
+ partOf.set(u, runs.length ? runs : [firstPart]);
2694
+ if (at.length)
2695
+ splits.set(u, at);
2696
+ }
2697
+ });
2698
+ return { parts, partOf, splits };
2699
+ }
1586
2700
  /** Reads a block's height (in layout px) and vertical margins from the DOM. */
1587
2701
  function measureBox(desc, scale) {
1588
2702
  let height = 0;
@@ -1609,11 +2723,10 @@ function measureBox(desc, scale) {
1609
2723
  * taller than a page, or one with a page break in it), page breaks ending their line's page,
1610
2724
  * and a page break before the next block ending this one's page.
1611
2725
  */
1612
- function wordBox(blocks, i, measure, lines, layout) {
2726
+ function wordBox(words, i, desc, measure, lines, layout) {
1613
2727
  const pageHeight = contentHeight(layout.sheet.settings);
1614
- const desc = blocks[i];
1615
- const next = blocks[i + 1];
1616
- const { before, after } = spacing(blocks[i - 1]?.word, desc.word, next?.word);
2728
+ const next = words[i + 1] ? { word: words[i + 1] } : undefined;
2729
+ const { before, after } = spacing(words[i - 1], desc.word, next?.word);
1617
2730
  const pageBreaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE && leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1618
2731
  const hasBreak = pageBreaks.length > 0;
1619
2732
  const kept = desc.word.keepLines && !hasBreak && measure.height <= pageHeight;
@@ -1646,8 +2759,8 @@ function wordBox(blocks, i, measure, lines, layout) {
1646
2759
  * and only on the first page or after an explicit break (a page the text flowed onto drops it).
1647
2760
  * Written only when it changes.
1648
2761
  */
1649
- function applyGaps(blocks, pages, boxes) {
1650
- blocks.forEach((desc, i) => {
2762
+ function applyGaps(firsts, pages, boxes) {
2763
+ firsts.forEach((dom, i) => {
1651
2764
  const page = pages[i]?.[0] ?? 0;
1652
2765
  const above = pages[i - 1];
1653
2766
  const box = boxes[i];
@@ -1660,10 +2773,10 @@ function applyGaps(blocks, pages, boxes) {
1660
2773
  const forced = page === 0 || (!!prior && breaks.length > 0 && breaks.includes(prior.lines().length - 1));
1661
2774
  gap = forced ? box.marginTop : 0;
1662
2775
  }
1663
- if (gaps.get(desc.dom) === gap)
2776
+ if (gaps.get(dom) === gap)
1664
2777
  return;
1665
- gaps.set(desc.dom, gap);
1666
- desc.dom.style.marginTop = `${gap}px`;
2778
+ gaps.set(dom, gap);
2779
+ dom.style.marginTop = `${gap}px`;
1667
2780
  });
1668
2781
  }
1669
2782
  /** The gap `applyGaps` last wrote on each block element (the style serializes it rounded). */
@@ -1882,4 +2995,66 @@ export function keyName(event) {
1882
2995
  name = `Mod-${name}`;
1883
2996
  return name;
1884
2997
  }
2998
+ /**
2999
+ * The text width of a document's (last) section in EMU (635 per twip; Word's Letter page and
3000
+ * margins where it does not say): the widest a picture is inserted or resized.
3001
+ * shortcut: the last section's, not the caret's section or table cell; use the caret's when
3002
+ * documents mix page sizes.
3003
+ */
3004
+ export function textWidthEmu(state) {
3005
+ const section = wordContext(state)?.envelope.section;
3006
+ return (((section?.pageSize?.width ?? 12_240) -
3007
+ (section?.margins?.left ?? 1440) -
3008
+ (section?.margins?.right ?? 1440)) *
3009
+ 635);
3010
+ }
3011
+ /** A file's image's natural size (CSS px) from a local object URL, before any upload. */
3012
+ export async function measureImageFile(file, doc) {
3013
+ if (typeof URL.createObjectURL !== "function")
3014
+ return null;
3015
+ const url = URL.createObjectURL(file);
3016
+ try {
3017
+ return await naturalSize(url, doc);
3018
+ }
3019
+ finally {
3020
+ URL.revokeObjectURL(url);
3021
+ }
3022
+ }
3023
+ /** An image's natural size (CSS px), or null when it does not load. */
3024
+ async function naturalSize(src, doc) {
3025
+ const img = doc.createElement("img");
3026
+ // Load events, not decode(): WebKit rejects decode() for an image outside the document.
3027
+ const loaded = new Promise((resolve) => {
3028
+ img.onload = () => resolve(true);
3029
+ img.onerror = () => resolve(false);
3030
+ });
3031
+ img.src = src;
3032
+ if (!(await loaded))
3033
+ return null;
3034
+ return img.naturalWidth && img.naturalHeight
3035
+ ? { width: img.naturalWidth, height: img.naturalHeight }
3036
+ : null;
3037
+ }
3038
+ /** Whether a block holds a floating picture (cached per node: nodes do not change). */
3039
+ const floats = new WeakMap();
3040
+ function holdsFloat(node) {
3041
+ let found = floats.get(node);
3042
+ if (found === undefined) {
3043
+ found = false;
3044
+ node.descendants((child) => {
3045
+ if (child.type.name === "picture" && child.attrs.float)
3046
+ found = true;
3047
+ return !found;
3048
+ });
3049
+ floats.set(node, found);
3050
+ }
3051
+ return found;
3052
+ }
3053
+ /** A change that only adds or removes a picture's resize handle (the view's own, not input). */
3054
+ function handleOnly(record) {
3055
+ const nodes = [...record.addedNodes, ...record.removedNodes];
3056
+ return (record.type === "childList" &&
3057
+ nodes.length > 0 &&
3058
+ nodes.every((n) => n.nodeType === 1 && n.hasAttribute("data-foli-resize")));
3059
+ }
1885
3060
  //# sourceMappingURL=view.js.map