@folijs/view 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,1394 @@
1
+ import { AllSelection, closeHistory, deleteBackward, deleteForward, deleteSelection, insertHardBreak, insertText, marksAt, redo, Selection, Slice, splitBlock, TextSelection, TransformError, toggleMark, undo, } from "@folijs/core";
2
+ import { docFromClipboard, FOLI_MIME, serializeRange } from "./clipboard.js";
3
+ import { contentHeight, DEFAULT_RULES, flowFrom, PX_PER_MM, } from "./layout/flow.js";
4
+ import { PAGE_BREAK_ATTR, renderBlock } from "./render.js";
5
+ const PLACEHOLDER_ATTR = "data-foli-placeholder";
6
+ // Generated content is not document text: no caret stops inside it, a zero-height float keeps
7
+ // the caret at the line start, and the empty alt text keeps screen readers on aria-placeholder.
8
+ const STYLES = `[${PLACEHOLDER_ATTR}]::before{content:attr(${PLACEHOLDER_ATTR});content:attr(${PLACEHOLDER_ATTR}) / "";float:inline-start;height:0;pointer-events:none;color:GrayText}`;
9
+ /**
10
+ * Adds the view's stylesheet once per document or shadow root, when a placeholder is first shown
11
+ * (by then the host is usually mounted where it will stay).
12
+ * shortcut: a CSP without 'unsafe-inline' for styles blocks it (placeholder not shown); ship a CSS file with the Phase 6 package if users need that.
13
+ */
14
+ function injectStyles(host) {
15
+ const doc = host.ownerDocument;
16
+ const root = host.getRootNode();
17
+ const parent = root.nodeType === Node.DOCUMENT_FRAGMENT_NODE
18
+ ? root
19
+ : (doc.head ?? doc.documentElement);
20
+ if (parent.querySelector("style[data-foli]"))
21
+ return;
22
+ const style = host.ownerDocument.createElement("style");
23
+ style.setAttribute("data-foli", "");
24
+ style.textContent = STYLES;
25
+ parent.append(style);
26
+ }
27
+ const VIEW_ATTR = "data-foli-view";
28
+ let viewCount = 0;
29
+ /**
30
+ * Print rules for the page settings of the view whose host has `VIEW_ATTR` = `id`: one sheet of
31
+ * the document's size per page, without margins (the page's padding holds them). A page is
32
+ * exactly as tall as a sheet (the flow keeps content inside it; the exact height absorbs its
33
+ * half-pixel slack), with no gap after it. Content taller than a page (a line taller than a
34
+ * page) is not cut: it prints over the next sheet.
35
+ * shortcut: `@page` is per document: with several editors of different page sizes on one web page, the last one's sheet size wins (each keeps its own page rules); print one editor per document until that is needed.
36
+ */
37
+ function printStyles({ pageSize }, id) {
38
+ const { width, height } = pageSize;
39
+ const pages = `[${VIEW_ATTR}="${id}"]>.foli-page`;
40
+ return (`@media print{@page{size:${width}mm ${height}mm;margin:0}` +
41
+ `${pages}{height:${height}mm!important;margin-block:0!important;` +
42
+ `break-after:page;break-inside:avoid}${pages}:last-child{break-after:auto}}`);
43
+ }
44
+ /**
45
+ * The editable view of an `Editor` from `@folijs/core`: renders its state into one
46
+ * `contenteditable` host and turns DOM input into core commands. The model is the source of
47
+ * truth; the DOM is rebuilt from it (unchanged blocks are reused by node identity).
48
+ *
49
+ * The browser edits the DOM itself only during composition (IME, dead keys) and for changes the
50
+ * view cannot prevent (Android keyboards, extensions). A MutationObserver records those; the view
51
+ * then reads the changed text back into a transaction (`readBack`) and re-renders.
52
+ *
53
+ * shortcut: assumes schema v1 (doc > textblocks > inline); nested blocks arrive with lists in Phase 7.
54
+ */
55
+ export class EditorView {
56
+ host;
57
+ editor;
58
+ state;
59
+ blocks = [];
60
+ /** Position before each block, parallel to `blocks`. */
61
+ starts = [];
62
+ /** The page of each fragment of each block. */
63
+ fragmentPages = new Map();
64
+ /** The block each fragment element belongs to. */
65
+ owner = new Map();
66
+ /** The page elements, in order; the host's only children. */
67
+ pages = [];
68
+ pageStyle = "";
69
+ /** Marks the host for this view's print rules (`printStyles`). */
70
+ id = String(++viewCount);
71
+ /**
72
+ * This view's print rules: in the document's head (`@page` only applies there) and, for a host
73
+ * in a shadow root, there too (page rules do not cross into it).
74
+ */
75
+ printStyles = [];
76
+ destroyed = false;
77
+ /** Set by a render during a composition, which places blocks but does not flow them. */
78
+ unflowed = false;
79
+ /**
80
+ * Measurements by model node: a node's rendered height, margins and lines only depend on
81
+ * its content (unchanged node, same identity), the page width and the CSS. Cleared when the
82
+ * page settings or the fonts change; single entries go stale when a block's size changes
83
+ * without an edit (`ResizeObserver`: CSS, fonts, a container).
84
+ */
85
+ measures = new WeakMap();
86
+ stale = new Set();
87
+ /**
88
+ * Set when a block resized without an edit: the CSS or a font changed, and may have rewrapped
89
+ * other blocks without changing their height. The next render drops every cached line list
90
+ * (heights stay; lines are measured again only for blocks that cross a page end).
91
+ */
92
+ linesStale = false;
93
+ /** The last flow and the nodes it was made for, for the next incremental one. */
94
+ flowed = null;
95
+ resizeObserver;
96
+ observed = new Set();
97
+ relayoutPending = false;
98
+ composing = false;
99
+ /** Set by Ctrl/Cmd+Shift+V for the paste event it triggers. */
100
+ plainPaste = false;
101
+ /** Blocks whose DOM the browser changed: the next render rebuilds them. */
102
+ dirty = new Set();
103
+ /** DOM mutations not yet read back (kept while a composition is running). */
104
+ pending = [];
105
+ observer;
106
+ unsubscribe;
107
+ editable = true;
108
+ placeholder = "";
109
+ /** The block that shows the placeholder, if any. */
110
+ placeholderDom = null;
111
+ /** Set by a mousedown that focuses the host: the click places the caret, not the view. */
112
+ pointerFocus = false;
113
+ /** Whether the view added the host's tabindex (a read-only host must stay focusable). */
114
+ addedTabIndex;
115
+ constructor(host, editor, options = {}) {
116
+ this.host = host;
117
+ this.editor = editor;
118
+ this.state = editor.state;
119
+ host.setAttribute("role", "textbox");
120
+ host.setAttribute("aria-multiline", "true");
121
+ host.setAttribute(VIEW_ATTR, this.id);
122
+ this.addedTabIndex = !host.hasAttribute("tabindex");
123
+ if (this.addedTabIndex)
124
+ host.tabIndex = 0;
125
+ // Spaces typed into the model must stay visible and caret-addressable.
126
+ host.style.whiteSpace = "pre-wrap";
127
+ host.style.overflowWrap = "break-word";
128
+ host.replaceChildren();
129
+ this.resizeObserver =
130
+ typeof ResizeObserver === "undefined" ? null : new ResizeObserver(this.onResize);
131
+ this.observer = new MutationObserver(this.onMutations);
132
+ this.observer.observe(host, { childList: true, characterData: true, subtree: true });
133
+ this.render();
134
+ this.setOptions(options);
135
+ host.addEventListener("beforeinput", this.onBeforeInput);
136
+ host.addEventListener("focus", this.onFocus);
137
+ host.addEventListener("keydown", this.onKeyDown);
138
+ host.addEventListener("input", this.onInput);
139
+ host.addEventListener("compositionstart", this.onCompositionStart);
140
+ host.addEventListener("compositionend", this.onCompositionEnd);
141
+ host.addEventListener("blur", this.onBlur);
142
+ host.addEventListener("mousedown", this.onMouseDown);
143
+ host.addEventListener("copy", this.onCopy);
144
+ host.addEventListener("cut", this.onCut);
145
+ host.addEventListener("paste", this.onPaste);
146
+ host.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
147
+ host.ownerDocument.fonts?.addEventListener("loadingdone", this.onFontsLoaded);
148
+ this.unsubscribe = editor.subscribe((state) => this.update(state));
149
+ }
150
+ destroy() {
151
+ this.destroyed = true;
152
+ this.unsubscribe();
153
+ this.host.ownerDocument.fonts?.removeEventListener("loadingdone", this.onFontsLoaded);
154
+ this.observer.disconnect();
155
+ this.resizeObserver?.disconnect();
156
+ for (const style of this.printStyles)
157
+ style.remove();
158
+ const { host } = this;
159
+ host.removeEventListener("beforeinput", this.onBeforeInput);
160
+ host.removeEventListener("focus", this.onFocus);
161
+ host.removeEventListener("keydown", this.onKeyDown);
162
+ host.removeEventListener("input", this.onInput);
163
+ host.removeEventListener("compositionstart", this.onCompositionStart);
164
+ host.removeEventListener("compositionend", this.onCompositionEnd);
165
+ host.removeEventListener("blur", this.onBlur);
166
+ host.removeEventListener("mousedown", this.onMouseDown);
167
+ host.removeEventListener("copy", this.onCopy);
168
+ host.removeEventListener("cut", this.onCut);
169
+ host.removeEventListener("paste", this.onPaste);
170
+ host.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
171
+ const owned = [
172
+ "contenteditable",
173
+ "role",
174
+ "aria-multiline",
175
+ "aria-readonly",
176
+ "aria-placeholder",
177
+ VIEW_ATTR,
178
+ ];
179
+ if (this.addedTabIndex)
180
+ owned.push("tabindex");
181
+ for (const name of owned)
182
+ host.removeAttribute(name);
183
+ host.style.removeProperty("white-space");
184
+ host.style.removeProperty("overflow-wrap");
185
+ if (!host.getAttribute("style"))
186
+ host.removeAttribute("style");
187
+ host.replaceChildren();
188
+ }
189
+ /** Focuses the host, shows the model selection in it and scrolls it into view. */
190
+ focus() {
191
+ this.host.focus();
192
+ this.writeSelection(true);
193
+ // The focus handler scrolls only when it writes the selection itself, and a DOM selection
194
+ // that already shows the model's (Firefox keeps one in an unfocused host) skips that.
195
+ this.scrollToSelection();
196
+ }
197
+ /** Changes the given options; the others keep their value. */
198
+ setOptions(options) {
199
+ const { host } = this;
200
+ if (options.editable !== undefined) {
201
+ // Finish a running composition while its text can still go into the model.
202
+ if (!options.editable && this.composing)
203
+ this.onCompositionEnd();
204
+ this.editable = options.editable;
205
+ }
206
+ if (options.placeholder !== undefined)
207
+ this.placeholder = options.placeholder;
208
+ // Read-only: no caret and no browser editing; the text stays selectable and copyable.
209
+ host.setAttribute("contenteditable", String(this.editable));
210
+ if (this.editable)
211
+ host.removeAttribute("aria-readonly");
212
+ else
213
+ host.setAttribute("aria-readonly", "true");
214
+ if (this.placeholder)
215
+ host.setAttribute("aria-placeholder", this.placeholder);
216
+ else
217
+ host.removeAttribute("aria-placeholder");
218
+ this.showPlaceholder();
219
+ }
220
+ /**
221
+ * Marks the only block while the document is one empty textblock; CSS shows the text. Hidden
222
+ * during a composition, whose text the model does not have yet.
223
+ */
224
+ showPlaceholder() {
225
+ const { doc } = this.state;
226
+ const empty = doc.childCount === 1 && doc.firstChild?.isTextblock && !doc.firstChild.content.size;
227
+ const target = this.placeholder && empty && !this.composing ? (this.blocks[0]?.dom ?? null) : null;
228
+ if (this.placeholderDom !== target)
229
+ this.placeholderDom?.removeAttribute(PLACEHOLDER_ATTR);
230
+ if (target) {
231
+ injectStyles(this.host);
232
+ target.setAttribute(PLACEHOLDER_ATTR, this.placeholder);
233
+ }
234
+ this.placeholderDom = target;
235
+ }
236
+ // ---------- rendering ----------
237
+ update(state) {
238
+ const docChanged = state.doc !== this.state.doc;
239
+ const selectionChanged = !state.selection.eq(this.state.selection);
240
+ this.state = state;
241
+ if (docChanged)
242
+ this.render();
243
+ this.writeSelection(docChanged);
244
+ // shortcut: scrolls for every change while focused; once remote or plugin changes exist, scroll only for local input (a transaction flag).
245
+ if (docChanged || selectionChanged)
246
+ this.scrollToSelection();
247
+ }
248
+ /**
249
+ * Scrolls the selection head into view. Browsers do it for their own edits and caret moves,
250
+ * not when the view changes the DOM and sets the selection (typing, Enter, undo, paste).
251
+ */
252
+ scrollToSelection() {
253
+ if (this.composing || !this.hasFocus())
254
+ return;
255
+ const doc = this.host.ownerDocument;
256
+ const sel = doc.getSelection();
257
+ const node = sel?.focusNode;
258
+ if (!sel || !node || !this.host.contains(node))
259
+ return;
260
+ const range = doc.createRange();
261
+ range.setStart(node, sel.focusOffset);
262
+ // An element point (next to a <br>, in an empty block) has no box of its own: measure the
263
+ // <br> after it, else the one before, else the element (never a whole tall block).
264
+ const near = node.childNodes[sel.focusOffset] ?? node.childNodes[sel.focusOffset - 1];
265
+ const element = near instanceof Element
266
+ ? near
267
+ : node.nodeType === Node.ELEMENT_NODE
268
+ ? node
269
+ : node.parentElement;
270
+ const rect = range.getClientRects?.()[0] ?? element?.getBoundingClientRect();
271
+ if (rect)
272
+ scrollRectIntoView(this.host, rect);
273
+ }
274
+ /**
275
+ * Renders the document into pages, reusing the DOM of blocks whose model node is unchanged.
276
+ * Blocks are first placed where they were (a new block joins the page of the block before
277
+ * it), then measured and flowed: a block that does not fit is split at a line boundary into
278
+ * fragments on consecutive pages. During a composition nothing moves, since moving or
279
+ * re-splitting the DOM the browser is composing in would break the IME.
280
+ *
281
+ * Measurements are cached by node and the flow restarts at the first changed block (5.4).
282
+ */
283
+ render() {
284
+ const { doc } = this.state;
285
+ const ownerDocument = this.host.ownerDocument;
286
+ const previous = new Map(this.blocks.filter((desc) => !this.dirty.has(desc)).map((desc) => [desc.node, desc]));
287
+ const previousPages = this.fragmentPages;
288
+ this.dirty.clear();
289
+ const dropLines = this.linesStale && !this.composing;
290
+ if (dropLines) {
291
+ this.linesStale = false;
292
+ this.flowed = null;
293
+ }
294
+ let blocks = [];
295
+ const starts = [];
296
+ doc.forEach((node, offset) => {
297
+ let reused = previous.get(node);
298
+ // A split block about to be measured again (fonts, CSS) is rendered whole first: each
299
+ // fragment's end breaks its line, so its lines would depend on where it was split before.
300
+ const remeasure = dropLines || !this.measures.has(node) || this.stale.has(node);
301
+ if (reused && reused.fragments.length > 1 && remeasure && !this.composing)
302
+ reused = undefined;
303
+ if (reused)
304
+ previous.delete(node);
305
+ blocks.push(reused ?? renderBlock(node, ownerDocument));
306
+ starts.push(offset);
307
+ });
308
+ for (const stale of previous.values())
309
+ for (const fragment of stale.fragments)
310
+ fragment.remove();
311
+ this.applyGeometry();
312
+ let last = 0;
313
+ let pages = blocks.map((desc) => {
314
+ const before = previousPages.get(desc);
315
+ return desc.fragments.map((_, f) => (last = Math.max(last, before?.[f] ?? last)));
316
+ });
317
+ this.place(blocks, pages);
318
+ if (!this.composing) {
319
+ // DOM reads only for blocks without a valid measurement (new, changed or stale ones).
320
+ let scale;
321
+ const layoutPx = () => {
322
+ scale ??= layoutScale(this.pages[0], this.editor.settings);
323
+ return scale;
324
+ };
325
+ if (dropLines)
326
+ for (const desc of blocks) {
327
+ const measure = this.measures.get(desc.node);
328
+ if (measure)
329
+ delete measure.lines;
330
+ }
331
+ const nodes = blocks.map((desc) => desc.node);
332
+ const reuse = this.flowed ? reuseOf(this.flowed, nodes, this.stale) : undefined;
333
+ const measureOf = (desc) => {
334
+ let found = this.measures.get(desc.node);
335
+ // A stale block is measured again once per render.
336
+ if (!found || this.stale.delete(desc.node)) {
337
+ found = measureBox(desc, layoutPx());
338
+ this.measures.set(desc.node, found);
339
+ }
340
+ return found;
341
+ };
342
+ const lines = (desc) => {
343
+ const found = measureOf(desc);
344
+ found.lines ??= measureLines(desc, layoutPx());
345
+ return found.lines;
346
+ };
347
+ const boxes = blocks.map((desc) => blockBox(desc, measureOf(desc), () => lines(desc)));
348
+ const result = flowFrom(boxes, contentHeight(this.editor.settings), DEFAULT_RULES, reuse);
349
+ this.flowed = { nodes, result };
350
+ this.stale.clear();
351
+ const flowed = result.fragments;
352
+ blocks = blocks.map((desc, i) => {
353
+ const fragments = flowed[i] ?? [];
354
+ const contentStart = starts[i] + 1;
355
+ const splits = fragments.slice(1).map((fragment) => {
356
+ const offset = lines(desc).starts[fragment.fromLine];
357
+ // Never split a grapheme cluster across pages.
358
+ return clusterBoundary(doc, contentStart + offset, false) - contentStart;
359
+ });
360
+ const same = splits.length === desc.splits.length && splits.every((at, k) => at === desc.splits[k]);
361
+ return same ? desc : renderBlock(desc.node, ownerDocument, splits);
362
+ });
363
+ pages = flowed.map((fragments) => fragments.map((fragment) => fragment.page));
364
+ this.place(blocks, pages);
365
+ }
366
+ this.blocks = blocks;
367
+ this.starts = starts;
368
+ this.fragmentPages = new Map(blocks.map((desc, i) => [desc, pages[i] ?? []]));
369
+ this.owner = new Map(blocks.flatMap((desc) => desc.fragments.map((fragment) => [fragment, desc])));
370
+ this.unflowed = this.composing;
371
+ this.observeSizes();
372
+ this.showPlaceholder();
373
+ // The view's own DOM changes are not input. During a composition, keep what the browser
374
+ // changed before this render: the touched blocks are read back at compositionend.
375
+ const records = this.observer.takeRecords();
376
+ if (this.composing)
377
+ this.pending.push(...records);
378
+ }
379
+ /**
380
+ * Puts each fragment of each block into its page (pages are non-decreasing in document
381
+ * order), creating and removing pages as needed. Anything else in the host or a page (stray
382
+ * DOM) is removed.
383
+ */
384
+ place(blocks, pages) {
385
+ const { host } = this;
386
+ const items = blocks.flatMap((desc, i) => desc.fragments.map((dom, f) => ({ dom, page: pages[i]?.[f] ?? 0 })));
387
+ const count = (items[items.length - 1]?.page ?? 0) + 1;
388
+ while (this.pages.length < count)
389
+ this.pages.push(this.createPage());
390
+ // Pages first, in order; anything else in the host ends up after them.
391
+ let cursor = host.firstChild;
392
+ for (const page of this.pages.slice(0, count)) {
393
+ if (page === cursor)
394
+ cursor = cursor.nextSibling;
395
+ else
396
+ host.insertBefore(page, cursor);
397
+ }
398
+ const blockDoms = new Set(items.map((item) => item.dom));
399
+ let i = 0;
400
+ for (let p = 0; p < count; p++) {
401
+ const page = this.pages[p];
402
+ let at = page.firstChild;
403
+ for (; i < items.length && items[i]?.page === p; i++) {
404
+ const dom = items[i].dom;
405
+ if (dom === at)
406
+ at = at.nextSibling;
407
+ else
408
+ page.insertBefore(dom, at);
409
+ }
410
+ // What is left: strays go; fragments of a later page are moved there next.
411
+ while (at) {
412
+ const next = at.nextSibling;
413
+ if (!blockDoms.has(at))
414
+ at.remove();
415
+ at = next;
416
+ }
417
+ }
418
+ // Pages no longer needed and stray DOM in the host: all after the last page by now. Taken
419
+ // after the block loop, since a block found loose in the host has just moved into a page.
420
+ let rest = this.pages[count - 1].nextSibling;
421
+ while (rest) {
422
+ const next = rest.nextSibling;
423
+ rest.remove();
424
+ rest = next;
425
+ }
426
+ this.pages.length = count;
427
+ }
428
+ createPage() {
429
+ const page = this.host.ownerDocument.createElement("section");
430
+ page.className = "foli-page";
431
+ page.style.cssText = this.pageStyle;
432
+ return page;
433
+ }
434
+ /** Page size and margins from the document settings, applied to every page when they change. */
435
+ applyGeometry() {
436
+ const { pageSize, margins } = this.editor.settings;
437
+ const style = `box-sizing: border-box; width: ${pageSize.width}mm; min-height: ${pageSize.height}mm; ` +
438
+ `padding: ${margins.top}mm ${margins.right}mm ${margins.bottom}mm ${margins.left}mm;`;
439
+ if (style === this.pageStyle)
440
+ return;
441
+ this.pageStyle = style;
442
+ for (const page of this.pages)
443
+ page.style.cssText = style;
444
+ // shortcut: written when the page settings change; a host moved to another document or shadow root keeps them where they were until then.
445
+ for (const style of this.printStyles)
446
+ style.remove();
447
+ const doc = this.host.ownerDocument;
448
+ const root = this.host.getRootNode();
449
+ const parents = [doc.head ?? doc.documentElement];
450
+ if (root.nodeType === Node.DOCUMENT_FRAGMENT_NODE)
451
+ parents.push(root);
452
+ this.printStyles = parents.map((parent) => {
453
+ const style = doc.createElement("style");
454
+ style.setAttribute("data-foli-print", "");
455
+ style.textContent = printStyles(this.editor.settings, this.id);
456
+ parent.append(style);
457
+ return style;
458
+ });
459
+ this.invalidateLayout();
460
+ }
461
+ /** Forgets every measurement: the next flow measures the whole document again. */
462
+ invalidateLayout() {
463
+ this.measures = new WeakMap();
464
+ this.flowed = null;
465
+ }
466
+ /** Re-flows the pages once web fonts have loaded: line heights and wrapping change. */
467
+ onFontsLoaded = () => {
468
+ this.invalidateLayout();
469
+ this.scheduleRelayout();
470
+ };
471
+ /** Observes the size of every rendered block element (and only those). */
472
+ observeSizes() {
473
+ if (!this.resizeObserver)
474
+ return;
475
+ for (const element of this.observed) {
476
+ if (this.owner.has(element))
477
+ continue;
478
+ this.resizeObserver.unobserve(element);
479
+ this.observed.delete(element);
480
+ }
481
+ for (const element of this.owner.keys()) {
482
+ if (!(element instanceof Element) || this.observed.has(element))
483
+ continue;
484
+ this.resizeObserver.observe(element);
485
+ this.observed.add(element);
486
+ }
487
+ }
488
+ /**
489
+ * A block whose height no longer matches its measurement changed without an edit (CSS, a web
490
+ * font, the content width): measure it again and re-flow, once per frame.
491
+ */
492
+ onResize = (entries) => {
493
+ let scale;
494
+ for (const entry of entries) {
495
+ const desc = this.owner.get(entry.target);
496
+ const measured = desc && this.measures.get(desc.node);
497
+ if (!desc || !measured || this.stale.has(desc.node))
498
+ continue;
499
+ // A hidden host (display: none) reports every block as 0x0: nothing to re-flow.
500
+ if (!entry.contentRect.width)
501
+ continue;
502
+ scale ??= layoutScale(this.pages[0], this.editor.settings);
503
+ let height = 0;
504
+ for (const fragment of desc.fragments)
505
+ height += fragment.getBoundingClientRect().height;
506
+ // A block is measured whole; each fragment of a split one keeps its padding and border,
507
+ // and each split may round by up to a pixel. Compared with the whole height alone, its
508
+ // fragments would re-flow it every frame.
509
+ const splits = desc.fragments.length - 1;
510
+ const expected = measured.height + splits * measured.box;
511
+ if (Math.abs(height / scale - expected) > 0.5 + splits) {
512
+ this.stale.add(desc.node);
513
+ this.linesStale = true;
514
+ }
515
+ }
516
+ if (this.stale.size)
517
+ this.scheduleRelayout();
518
+ };
519
+ /** Re-flows in the next animation frame (several requests in one frame make one pass). */
520
+ scheduleRelayout() {
521
+ if (this.relayoutPending)
522
+ return;
523
+ this.relayoutPending = true;
524
+ const win = this.host.ownerDocument.defaultView;
525
+ const nextFrame = (callback) => win?.requestAnimationFrame ? win.requestAnimationFrame(callback) : setTimeout(callback);
526
+ const run = () => {
527
+ this.relayoutPending = false;
528
+ if (this.destroyed)
529
+ return;
530
+ // compositionend flows what a composition kept from moving.
531
+ if (this.composing) {
532
+ this.unflowed = true;
533
+ return;
534
+ }
535
+ this.render();
536
+ this.writeSelection(false);
537
+ };
538
+ nextFrame(run);
539
+ }
540
+ // ---------- position mapping ----------
541
+ /** The block element that contains `node` (the child of a page it sits in), or null. */
542
+ blockElement(node) {
543
+ let element = node;
544
+ while (element?.parentNode && !this.pages.includes(element.parentNode)) {
545
+ if (element.parentNode === this.host)
546
+ return null;
547
+ element = element.parentNode;
548
+ }
549
+ return element?.parentNode ? element : null;
550
+ }
551
+ /** Model position of a DOM point inside the host, or null if it is outside. */
552
+ posFromDOM(node, offset) {
553
+ const { host } = this;
554
+ if (node === host || this.pages.includes(node)) {
555
+ // Between fragments: the start of the first one after the point (a block start, or
556
+ // where a continuation starts), else the document end.
557
+ const range = host.ownerDocument.createRange();
558
+ range.setStart(node, offset);
559
+ for (const [i, desc] of this.blocks.entries()) {
560
+ const f = desc.fragments.findIndex((fragment) => range.comparePoint(fragment, 0) >= 0);
561
+ if (f === 0)
562
+ return this.starts[i];
563
+ if (f > 0)
564
+ return this.starts[i] + 1 + desc.splits[f - 1];
565
+ }
566
+ return this.state.doc.content.size;
567
+ }
568
+ const element = this.blockElement(node);
569
+ const owner = element ? this.owner.get(element) : undefined;
570
+ const index = owner ? this.blocks.indexOf(owner) : -1;
571
+ const desc = this.blocks[index];
572
+ if (!desc)
573
+ return null;
574
+ const contentStart = this.starts[index] + 1;
575
+ const leaf = desc.leaves.find((l) => l.dom === node);
576
+ if (leaf && node.nodeType === Node.TEXT_NODE)
577
+ return contentStart + leaf.offset + Math.min(offset, leaf.size);
578
+ // An element point: the start of the first leaf at or after it, else the end of the block.
579
+ const range = host.ownerDocument.createRange();
580
+ range.setStart(node, offset);
581
+ for (const l of desc.leaves) {
582
+ if (range.comparePoint(l.dom, 0) >= 0)
583
+ return contentStart + l.offset;
584
+ }
585
+ return contentStart + desc.node.content.size;
586
+ }
587
+ /** DOM point for a model position. At a mark boundary the caret stays in the text before it. */
588
+ domFromPos(pos) {
589
+ const { doc } = this.state;
590
+ let $pos = doc.resolve(pos);
591
+ // Between blocks: use the nearest block edge (schema v1 has only textblocks at depth 1).
592
+ if ($pos.depth === 0)
593
+ $pos = doc.resolve($pos.nodeAfter ? pos + 1 : pos - 1);
594
+ const desc = this.blocks[$pos.index(0)];
595
+ const offset = $pos.parentOffset;
596
+ // Where a fragment starts, show the caret at the start of the next page's fragment, as a
597
+ // browser shows it at the start of the next line at a soft wrap.
598
+ const split = desc.splits.indexOf(offset);
599
+ if (split >= 0)
600
+ return fragmentStart(desc, split + 1);
601
+ for (const leaf of desc.leaves) {
602
+ if (leaf.dom.nodeType === Node.TEXT_NODE &&
603
+ leaf.offset <= offset &&
604
+ offset <= leaf.offset + leaf.size)
605
+ return { node: leaf.dom, offset: offset - leaf.offset };
606
+ }
607
+ const next = desc.leaves.find((leaf) => leaf.offset >= offset);
608
+ if (next)
609
+ return before(next.dom);
610
+ const last = desc.leaves[desc.leaves.length - 1];
611
+ if (last) {
612
+ const point = before(last.dom);
613
+ return { node: point.node, offset: point.offset + 1 };
614
+ }
615
+ return { node: desc.dom, offset: 0 };
616
+ }
617
+ // ---------- selection ----------
618
+ /** The live DOM selection as a model selection, or null if it is not inside the host. */
619
+ readSelection() {
620
+ const sel = this.host.ownerDocument.getSelection();
621
+ if (!sel?.anchorNode || !sel.focusNode)
622
+ return null;
623
+ const anchor = this.posFromDOM(sel.anchorNode, sel.anchorOffset);
624
+ const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
625
+ if (anchor === null || head === null)
626
+ return null;
627
+ const { doc } = this.state;
628
+ return TextSelection.between(doc.resolve(anchor), doc.resolve(head));
629
+ }
630
+ /**
631
+ * Brings the model selection up to date with the DOM. `selectionchange` is asynchronous, so
632
+ * every input handler calls this first instead of trusting the last event.
633
+ */
634
+ syncSelection() {
635
+ const selection = this.readSelection();
636
+ if (!selection || this.shows(selection))
637
+ return;
638
+ // A caret moved by the user drops marks toggled at the old position.
639
+ this.dispatch(this.state.tr.setSelection(selection).setStoredMarks(null));
640
+ }
641
+ /**
642
+ * Whether a selection read from the DOM already shows the model selection. An AllSelection is
643
+ * shown as the text range between its snapped ends, so reading it back must not replace it.
644
+ */
645
+ shows(dom) {
646
+ const { selection } = this.state;
647
+ const shown = selection instanceof AllSelection
648
+ ? TextSelection.between(selection.$anchor, selection.$head)
649
+ : selection;
650
+ return dom.anchor === shown.anchor && dom.head === shown.head;
651
+ }
652
+ hasFocus() {
653
+ const active = this.host.ownerDocument.activeElement;
654
+ return active === this.host || this.host.contains(active);
655
+ }
656
+ /** Writes the model selection to the DOM unless the DOM already shows it (keeps native affinity). */
657
+ writeSelection(force) {
658
+ if (this.composing || !this.hasFocus())
659
+ return;
660
+ const sel = this.host.ownerDocument.getSelection();
661
+ if (!sel)
662
+ return;
663
+ const { selection, doc } = this.state;
664
+ if (!force) {
665
+ const current = this.readSelection();
666
+ if (current && this.shows(current))
667
+ return;
668
+ }
669
+ // Never show a caret inside a grapheme cluster (the core snaps only out of surrogate pairs).
670
+ // The model takes the snapped selection back on its next read of the DOM.
671
+ const from = clusterBoundary(doc, selection.from, false);
672
+ const to = selection.empty ? from : clusterBoundary(doc, selection.to, true);
673
+ const forward = selection.anchor <= selection.head;
674
+ const anchor = this.domFromPos(forward ? from : to);
675
+ const head = this.domFromPos(forward ? to : from);
676
+ sel.setBaseAndExtent(anchor.node, anchor.offset, head.node, head.offset);
677
+ }
678
+ // ---------- input ----------
679
+ run(command) {
680
+ return command(this.state, (tr) => this.dispatch(tr));
681
+ }
682
+ /**
683
+ * Every change from user input goes through here. Read-only mode drops document changes and
684
+ * newly stored marks (Mod+B on a caret); selection changes, and clearing stored marks, still
685
+ * apply. Code can always change the document through the editor.
686
+ */
687
+ dispatch(tr) {
688
+ const marksAdded = tr.storedMarks !== null && tr.storedMarks !== this.state.storedMarks;
689
+ if (!this.editable && (tr.docChanged || marksAdded))
690
+ return false;
691
+ this.editor.dispatch(tr);
692
+ return true;
693
+ }
694
+ /** Selects the event's target range when the browser gives a non-empty one (spellcheck, deletes). */
695
+ selectTargetRange(event) {
696
+ const range = event.getTargetRanges?.()[0];
697
+ if (!range || range.collapsed)
698
+ return;
699
+ const from = this.posFromDOM(range.startContainer, range.startOffset);
700
+ const to = this.posFromDOM(range.endContainer, range.endOffset);
701
+ if (from === null || to === null)
702
+ return;
703
+ const { doc } = this.state;
704
+ const selection = TextSelection.between(doc.resolve(from), doc.resolve(to));
705
+ if (!selection.eq(this.state.selection))
706
+ this.dispatch(this.state.tr.setSelection(selection));
707
+ }
708
+ onBeforeInput = (event) => {
709
+ // During composition the browser owns the DOM; it is reconciled at compositionend. A
710
+ // composition event that arrives after it must not fall through to a delete or insert.
711
+ if (event.isComposing || this.composing || COMPOSITION_INPUT.has(event.inputType))
712
+ return;
713
+ event.preventDefault();
714
+ this.syncSelection();
715
+ const type = event.inputType;
716
+ const text = event.data ?? event.dataTransfer?.getData("text/plain") ?? "";
717
+ switch (type) {
718
+ case "insertText":
719
+ this.run(insertText(text));
720
+ return;
721
+ case "insertReplacementText":
722
+ this.selectTargetRange(event);
723
+ this.run(insertText(text));
724
+ return;
725
+ case "insertParagraph":
726
+ this.run(splitBlock);
727
+ return;
728
+ case "insertLineBreak":
729
+ this.run(insertHardBreak);
730
+ return;
731
+ case "historyUndo":
732
+ this.run(undo);
733
+ return;
734
+ case "historyRedo":
735
+ this.run(redo);
736
+ return;
737
+ case "formatBold":
738
+ case "formatItalic":
739
+ case "formatUnderline":
740
+ case "formatStrikeThrough": {
741
+ const mark = type === "formatStrikeThrough" ? "strike" : type.slice(6).toLowerCase();
742
+ this.run(toggleMark(mark));
743
+ return;
744
+ }
745
+ }
746
+ if (!type.startsWith("delete") || type === "deleteByDrag")
747
+ return;
748
+ this.selectTargetRange(event);
749
+ if (this.state.selection.empty && type.includes("Line")) {
750
+ // No target range: let the browser find the line edge, never delete a character instead.
751
+ // shortcut: hard-line deletes also stop at the visual line edge here; Chromium, Firefox and WebKit all give a range.
752
+ const sel = this.host.ownerDocument.getSelection();
753
+ if (type === "deleteEntireSoftLine") {
754
+ sel?.modify?.("move", "backward", "lineboundary");
755
+ sel?.modify?.("extend", "forward", "lineboundary");
756
+ }
757
+ else {
758
+ sel?.modify?.("extend", type.endsWith("Forward") ? "forward" : "backward", "lineboundary");
759
+ }
760
+ this.syncSelection();
761
+ this.run(deleteSelection);
762
+ return;
763
+ }
764
+ if (!this.state.selection.empty || type === "deleteByCut" || type === "deleteContent") {
765
+ this.run(deleteSelection);
766
+ return;
767
+ }
768
+ const unit = type.startsWith("deleteWord") ? "word" : "char";
769
+ this.run(type.endsWith("Forward") ? deleteForward(unit) : deleteBackward(unit));
770
+ };
771
+ /**
772
+ * Triple-click selects the clicked block's content. Chromium and WebKit natively extend the
773
+ * selection to the start of the next block, so typing over it would merge the two blocks.
774
+ */
775
+ onMouseDown = (event) => {
776
+ this.pointerFocus = !this.hasFocus();
777
+ // Focus from a mousedown happens in its default action, before this timer. A mousedown that
778
+ // focuses nothing (prevented, middle button) must not skip the next keyboard focus.
779
+ if (this.pointerFocus)
780
+ setTimeout(() => (this.pointerFocus = false));
781
+ if (event.detail !== 3 || event.button !== 0)
782
+ return;
783
+ const element = this.blockElement(event.target);
784
+ const owner = element ? this.owner.get(element) : undefined;
785
+ const index = owner ? this.blocks.indexOf(owner) : -1;
786
+ const desc = this.blocks[index];
787
+ if (!desc)
788
+ return;
789
+ event.preventDefault();
790
+ const from = this.starts[index] + 1;
791
+ const { doc } = this.state;
792
+ this.host.focus();
793
+ this.dispatch(this.state.tr
794
+ .setSelection(TextSelection.create(doc, from, from + desc.node.content.size))
795
+ .setStoredMarks(null));
796
+ this.writeSelection(true);
797
+ };
798
+ onKeyDown = (event) => {
799
+ if (event.isComposing || this.composing)
800
+ return;
801
+ this.syncSelection();
802
+ if (this.crossFragmentEdge(event)) {
803
+ event.preventDefault();
804
+ return;
805
+ }
806
+ const name = keyName(event);
807
+ // Ctrl/Cmd+Shift+V: the paste event that follows uses only the plain text.
808
+ this.plainPaste = name === "Mod-Shift-v";
809
+ // Like `editor.handleKey`, but through the view's dispatch, so read-only mode drops edits.
810
+ const handled = this.state.plugins.some((plugin) => {
811
+ const command = plugin.spec.keymap?.[name];
812
+ return command ? this.run(command) : false;
813
+ });
814
+ if (handled)
815
+ event.preventDefault();
816
+ };
817
+ /**
818
+ * Caret affinity at a page break. The end of one fragment and the start of the next are two
819
+ * DOM caret stops for one model position, so a native Left/Right (or word move) there would
820
+ * seem to do nothing. Step over the edge first, then let the browser make the move.
821
+ *
822
+ * shortcut: left-to-right only (ArrowRight is forward); bidi text needs visual order here and in the line measurement.
823
+ */
824
+ crossFragmentEdge(event) {
825
+ const forward = event.key === "ArrowRight";
826
+ if (!forward && event.key !== "ArrowLeft")
827
+ return false;
828
+ // Word moves are Alt on Apple platforms and Ctrl elsewhere; other modifiers are not moves
829
+ // this view knows (Cmd+arrows go to the line edge, Alt+arrows navigate history on Windows).
830
+ const word = IS_MAC ? event.altKey : event.ctrlKey;
831
+ if (event.metaKey || (IS_MAC ? event.ctrlKey : event.altKey))
832
+ return false;
833
+ const sel = this.host.ownerDocument.getSelection();
834
+ if (!sel?.focusNode || !sel.anchorNode || !sel.modify)
835
+ return false;
836
+ if (!event.shiftKey && !sel.isCollapsed)
837
+ return false;
838
+ const element = this.blockElement(sel.focusNode);
839
+ const desc = element ? this.owner.get(element) : undefined;
840
+ if (!desc || desc.fragments.length < 2)
841
+ return false;
842
+ const f = desc.fragments.indexOf(element);
843
+ const head = this.posFromDOM(sel.focusNode, sel.focusOffset);
844
+ if (head === null)
845
+ return false;
846
+ const offset = head - this.starts[this.blocks.indexOf(desc)] - 1;
847
+ let target = null;
848
+ // Stepping back over an edge after a hard break lands before the <br>: the point after it
849
+ // is still the split, and browsers would show it before the <br> anyway. That step is
850
+ // already the one-character move.
851
+ let moved = false;
852
+ if (forward && f < desc.fragments.length - 1 && offset === desc.splits[f])
853
+ target = fragmentStart(desc, f + 1);
854
+ else if (!forward && f > 0 && offset === desc.splits[f - 1]) {
855
+ const fragment = desc.fragments[f - 1];
856
+ const inside = desc.leaves.filter((l) => fragment.contains(l.dom));
857
+ const last = inside[inside.length - 1];
858
+ if (last && last.dom.nodeType !== Node.TEXT_NODE && last.offset + last.size === offset) {
859
+ target = before(last.dom);
860
+ moved = !word;
861
+ }
862
+ else
863
+ target = fragmentEnd(desc, f - 1);
864
+ }
865
+ if (!target)
866
+ return false;
867
+ if (event.shiftKey)
868
+ sel.setBaseAndExtent(sel.anchorNode, sel.anchorOffset, target.node, target.offset);
869
+ else
870
+ sel.collapse(target.node, target.offset);
871
+ if (!moved)
872
+ sel.modify(event.shiftKey ? "extend" : "move", forward ? "forward" : "backward", word ? "word" : "character");
873
+ this.syncSelection();
874
+ return true;
875
+ }
876
+ /** Safety net: a DOM change that was not prevented is read back into the model. */
877
+ onInput = () => {
878
+ if (!this.composing)
879
+ this.flush();
880
+ };
881
+ onCompositionStart = () => {
882
+ this.syncSelection();
883
+ this.composing = true;
884
+ this.showPlaceholder();
885
+ };
886
+ onCompositionEnd = () => {
887
+ this.composing = false;
888
+ this.flush();
889
+ // A render during the composition did not flow; if the read-back rendered nothing, flow now.
890
+ if (this.unflowed) {
891
+ this.render();
892
+ this.writeSelection(false);
893
+ }
894
+ this.showPlaceholder();
895
+ };
896
+ /**
897
+ * Focus from the keyboard or from code shows the model selection: once the page selection has
898
+ * moved elsewhere, browsers put the caret at the start of the host instead. A DOM selection
899
+ * that already shows the model selection (the window or tab regaining focus) is left alone,
900
+ * and so is the scroll position.
901
+ */
902
+ onFocus = () => {
903
+ const pointer = this.pointerFocus;
904
+ this.pointerFocus = false;
905
+ if (pointer)
906
+ return;
907
+ const current = this.readSelection();
908
+ if (current && this.shows(current))
909
+ return;
910
+ this.writeSelection(true);
911
+ this.scrollToSelection();
912
+ };
913
+ /** Some browsers drop compositionend when focus leaves mid-composition; never stay stuck in it. */
914
+ onBlur = () => {
915
+ this.pointerFocus = false;
916
+ if (this.composing)
917
+ this.onCompositionEnd();
918
+ };
919
+ onMutations = (records) => {
920
+ this.pending.push(...records);
921
+ if (!this.composing)
922
+ this.flush();
923
+ };
924
+ /** Reads back every DOM change recorded so far. */
925
+ flush() {
926
+ const records = [...this.pending, ...this.observer.takeRecords()];
927
+ this.pending = [];
928
+ if (records.length)
929
+ this.readBack(records);
930
+ }
931
+ /**
932
+ * Turns DOM changes into a transaction: diffs the DOM text with the model text (blocks joined
933
+ * by a separator, hard breaks as one character) and replaces the minimal changed range. The
934
+ * DOM caret only breaks ties, so typing "a" after "a" lands where the browser put it. Blocks
935
+ * whose DOM was touched are re-rendered even if their text is unchanged.
936
+ *
937
+ * shortcut: diffs the whole document text (O(document) per composition); limit it to the
938
+ * touched blocks if it shows in profiles.
939
+ */
940
+ readBack(records) {
941
+ for (const record of records) {
942
+ const node = this.blockElement(record.target);
943
+ const desc = node && this.owner.get(node);
944
+ if (desc)
945
+ this.dirty.add(desc);
946
+ }
947
+ const hardBreaks = new Set();
948
+ for (const desc of this.blocks)
949
+ for (const leaf of desc.leaves)
950
+ if (leaf.dom.nodeType !== Node.TEXT_NODE)
951
+ hardBreaks.add(leaf.dom);
952
+ const sel = this.host.ownerDocument.getSelection();
953
+ let caret = -1;
954
+ let domText = "";
955
+ const walk = (node) => {
956
+ if (node.nodeType === Node.TEXT_NODE) {
957
+ if (node === sel?.focusNode)
958
+ caret = domText.length + sel.focusOffset;
959
+ domText += node.data;
960
+ }
961
+ else if (hardBreaks.has(node))
962
+ domText += HARD_BREAK;
963
+ else
964
+ node.childNodes.forEach(walk);
965
+ };
966
+ let first = true;
967
+ // Block-level nodes in order: the children of each page, and anything else in the host.
968
+ const blockLevel = [...this.host.childNodes].flatMap((child) => this.pages.includes(child) ? [...child.childNodes] : [child]);
969
+ let previousOwner;
970
+ for (const child of blockLevel) {
971
+ const owner = this.owner.get(child);
972
+ // An empty stray node (an extension's marker) holds no text; the re-render removes it.
973
+ if (!owner && !child.textContent)
974
+ continue;
975
+ // The fragments of one block are one text; anything else starts a new block.
976
+ if (!first && !(owner && owner === previousOwner))
977
+ domText += BLOCK_SEPARATOR;
978
+ first = false;
979
+ previousOwner = owner;
980
+ walk(child);
981
+ }
982
+ const { doc } = this.state;
983
+ const lineStarts = [];
984
+ let modelText = "";
985
+ doc.forEach((block, _offset, i) => {
986
+ if (i > 0)
987
+ modelText += BLOCK_SEPARATOR;
988
+ lineStarts.push(modelText.length);
989
+ modelText += block.textBetween(0, block.content.size, "", HARD_BREAK);
990
+ });
991
+ /** Model position of an offset in `modelText`. */
992
+ const posAt = (offset) => {
993
+ let i = lineStarts.length - 1;
994
+ while (i > 0 && lineStarts[i] > offset)
995
+ i--;
996
+ return this.starts[i] + 1 + offset - lineStarts[i];
997
+ };
998
+ if (domText === modelText) {
999
+ this.rerender();
1000
+ return;
1001
+ }
1002
+ // The minimal change: common prefix, then common suffix (never overlapping the prefix).
1003
+ let start = 0;
1004
+ const shorter = Math.min(modelText.length, domText.length);
1005
+ while (start < shorter && modelText[start] === domText[start])
1006
+ start++;
1007
+ let end = modelText.length;
1008
+ let domEnd = domText.length;
1009
+ while (end > start && domEnd > start && modelText[end - 1] === domText[domEnd - 1]) {
1010
+ end--;
1011
+ domEnd--;
1012
+ }
1013
+ // A pure insertion or deletion inside repeated text ("aa" → "aaa") could sit at several
1014
+ // offsets; slide it back to where the DOM caret says it happened.
1015
+ const insertion = end === start;
1016
+ if (caret >= 0 && insertion !== (domEnd === start)) {
1017
+ while (start > 0 &&
1018
+ (insertion ? domEnd > caret : start > caret) &&
1019
+ modelText[start - 1] === (insertion ? domText[domEnd - 1] : modelText[end - 1])) {
1020
+ start--;
1021
+ end--;
1022
+ domEnd--;
1023
+ }
1024
+ }
1025
+ // Never split a surrogate pair.
1026
+ if (start > 0 && isHighSurrogate(modelText.charCodeAt(start - 1)))
1027
+ start--;
1028
+ if (end < modelText.length && isHighSurrogate(modelText.charCodeAt(end - 1))) {
1029
+ end++;
1030
+ domEnd++;
1031
+ }
1032
+ const inserted = domText.slice(start, domEnd);
1033
+ if (inserted.includes(BLOCK_SEPARATOR) || inserted.includes(HARD_BREAK)) {
1034
+ // shortcut: a change that adds blocks or line breaks cannot be read back yet; it is dropped.
1035
+ console.warn("Foli: discarded a DOM change that adds blocks or line breaks");
1036
+ this.rerender();
1037
+ return;
1038
+ }
1039
+ // One transaction: the command runs on a state with the changed range selected.
1040
+ const range = TextSelection.create(doc, posAt(start), posAt(end));
1041
+ const selected = this.state.apply(this.state.tr.setSelection(range));
1042
+ const command = inserted ? insertText(inserted) : deleteSelection;
1043
+ // A filtered or read-only transaction renders nothing: still drop the browser's DOM.
1044
+ let applied = false;
1045
+ command(selected, (tr) => {
1046
+ applied = this.dispatch(tr);
1047
+ });
1048
+ if (!applied || this.dirty.size)
1049
+ this.rerender();
1050
+ }
1051
+ /** Rebuilds every block that is not reused and puts the selection back. */
1052
+ rerender() {
1053
+ this.render();
1054
+ this.writeSelection(true);
1055
+ }
1056
+ // ---------- clipboard ----------
1057
+ /** Copy writes the model's content (plain text, HTML, Foli JSON), never the browser's DOM. */
1058
+ onCopy = (event) => {
1059
+ this.syncSelection();
1060
+ const { selection, doc } = this.state;
1061
+ if (selection.empty || !event.clipboardData)
1062
+ return;
1063
+ event.preventDefault();
1064
+ const { text, html, json } = serializeRange(doc, selection.from, selection.to, this.host.ownerDocument);
1065
+ event.clipboardData.setData("text/plain", text);
1066
+ event.clipboardData.setData("text/html", html);
1067
+ event.clipboardData.setData(FOLI_MIME, json);
1068
+ };
1069
+ onCut = (event) => {
1070
+ this.onCopy(event);
1071
+ if (!event.defaultPrevented)
1072
+ return;
1073
+ // Its own undo step, not merged with the typing before it.
1074
+ deleteSelection(this.state, (tr) => this.dispatch(tr.setMeta(closeHistory, true)));
1075
+ };
1076
+ onPaste = (event) => {
1077
+ if (!event.clipboardData)
1078
+ return;
1079
+ event.preventDefault();
1080
+ const plain = this.plainPaste;
1081
+ this.plainPaste = false;
1082
+ // The browser owns the DOM during a composition; a model change now would be overwritten.
1083
+ if (this.composing)
1084
+ return;
1085
+ this.syncSelection();
1086
+ const data = event.clipboardData;
1087
+ this.paste(plain ? { getData: (type) => (type === "text/plain" ? data.getData(type) : "") } : data);
1088
+ };
1089
+ /**
1090
+ * Replaces the selection with clipboard content (Foli JSON, else HTML, else plain text). The
1091
+ * paste starts a new undo step (typing right after it joins that step). Closed content (whole
1092
+ * blocks) goes into an empty textblock whole, so a pasted heading stays a heading; open
1093
+ * content, and anything pasted into a non-empty block, joins the text around the selection,
1094
+ * so the target block keeps its type. Returns whether anything was inserted.
1095
+ */
1096
+ paste(data) {
1097
+ const { state } = this;
1098
+ const marks = (state.storedMarks ?? marksAt(state.selection.$from)).map((m) => m.toJSON());
1099
+ const pasted = docFromClipboard(data, marks);
1100
+ // One empty block: nothing to paste.
1101
+ if (!pasted || pasted.doc.content.size <= 2)
1102
+ return false;
1103
+ const { doc, open } = pasted;
1104
+ try {
1105
+ const tr = state.tr.deleteSelection();
1106
+ const $pos = tr.selection.$from;
1107
+ if (!open && $pos.depth === 1 && $pos.parent.isTextblock && !$pos.parent.content.size) {
1108
+ const from = $pos.before();
1109
+ tr.replace(from, $pos.after(), new Slice(doc.content, 0, 0));
1110
+ tr.setSelection(Selection.near(tr.doc.resolve(from + doc.content.size), -1));
1111
+ }
1112
+ else {
1113
+ tr.replaceSelection(doc.slice(1, doc.content.size - 1));
1114
+ }
1115
+ return this.dispatch(tr.setMeta(closeHistory, true));
1116
+ }
1117
+ catch (error) {
1118
+ // shortcut: content the schema cannot fit at the selection is not pasted; general fitting comes with nested blocks (Phase 7).
1119
+ if (error instanceof TransformError)
1120
+ return false;
1121
+ throw error;
1122
+ }
1123
+ }
1124
+ onSelectionChange = () => {
1125
+ if (!this.composing && this.hasFocus())
1126
+ this.syncSelection();
1127
+ };
1128
+ }
1129
+ /**
1130
+ * Client rects are scaled by CSS `zoom` or a `transform` on an ancestor, while margins and the
1131
+ * page geometry are in layout px: the ratio between the two for a page. From the page's width
1132
+ * as set in mm (`offsetWidth` is rounded to a pixel: off by up to 0.1%, a pixel per page).
1133
+ */
1134
+ function layoutScale(page, settings) {
1135
+ return page.getBoundingClientRect().width / (settings.pageSize.width * PX_PER_MM) || 1;
1136
+ }
1137
+ /** Reads a block's height (in layout px) and vertical margins from the DOM. */
1138
+ function measureBox(desc, scale) {
1139
+ let height = 0;
1140
+ for (const fragment of desc.fragments)
1141
+ height += fragment.getBoundingClientRect().height;
1142
+ // A split block's first fragment has no bottom margin and its last no top margin (inline).
1143
+ const first = getComputedStyle(desc.dom);
1144
+ const last = getComputedStyle(desc.fragments[desc.fragments.length - 1]);
1145
+ // jsdom and detached nodes report no margins.
1146
+ const px = (value) => Number.parseFloat(value) || 0;
1147
+ return {
1148
+ height: height / scale,
1149
+ marginTop: px(first.marginTop),
1150
+ marginBottom: px(last.marginBottom),
1151
+ box: px(first.paddingTop) +
1152
+ px(first.paddingBottom) +
1153
+ px(first.borderTopWidth) +
1154
+ px(first.borderBottomWidth),
1155
+ };
1156
+ }
1157
+ /**
1158
+ * What the flow needs of a block: its measurement, its lines (on demand), and what the rules
1159
+ * need: headings keep with the next block; page breaks end their line's page.
1160
+ */
1161
+ function blockBox(desc, measure, lines) {
1162
+ return {
1163
+ height: measure.height,
1164
+ marginTop: measure.marginTop,
1165
+ marginBottom: measure.marginBottom,
1166
+ lines: () => lines().bottoms,
1167
+ keepWithNext: desc.node.type.name === "heading",
1168
+ breaksAfter: () => {
1169
+ const breaks = desc.leaves.filter((leaf) => leaf.dom.nodeType !== Node.TEXT_NODE &&
1170
+ leaf.dom.hasAttribute(PAGE_BREAK_ATTR));
1171
+ if (!breaks.length)
1172
+ return [];
1173
+ const { starts } = lines();
1174
+ // The line holding the break: the last one starting at or before it.
1175
+ return breaks.map((leaf) => {
1176
+ let line = starts.length - 1;
1177
+ while (line > 0 && starts[line] > leaf.offset)
1178
+ line--;
1179
+ return line;
1180
+ });
1181
+ },
1182
+ };
1183
+ }
1184
+ /**
1185
+ * What the next flow can reuse of the last one: the unchanged blocks before the first changed
1186
+ * (or stale) one, and the unchanged tail after the last.
1187
+ */
1188
+ function reuseOf(last, nodes, stale) {
1189
+ const before = last.nodes;
1190
+ const same = (a, b) => a !== undefined && a === b && !stale.has(a);
1191
+ let from = 0;
1192
+ while (from < nodes.length && from < before.length && same(nodes[from], before[from]))
1193
+ from++;
1194
+ let tail = 0;
1195
+ while (tail < nodes.length - from &&
1196
+ tail < before.length - from &&
1197
+ same(nodes[nodes.length - 1 - tail], before[before.length - 1 - tail]))
1198
+ tail++;
1199
+ const delta = nodes.length - before.length;
1200
+ return {
1201
+ previous: last.result,
1202
+ from,
1203
+ previousIndex: (i) => (i >= nodes.length - tail ? i - delta : -1),
1204
+ };
1205
+ }
1206
+ const NO_RECT = { top: 0, bottom: 0, height: 0 };
1207
+ /**
1208
+ * The lines of a rendered block, across its fragments. A line ends where the next character
1209
+ * (or <br>) starts below the vertical middle of the line's first one; a binary search finds each line's
1210
+ * first item. Between two lines the boundary is halfway between the first line's first item
1211
+ * bottom and the next line's first item top, which is exact for equal line heights (equal
1212
+ * half-leading above and below).
1213
+ *
1214
+ * shortcut: assumes left-to-right lines without vertical-align offsets (schema v1 has neither); bidi and superscripts need line boxes from the layout instead.
1215
+ */
1216
+ function measureLines(desc, scale) {
1217
+ const starts = [];
1218
+ const bottoms = [];
1219
+ const range = desc.dom.ownerDocument.createRange();
1220
+ let base = 0;
1221
+ for (const [f, fragment] of desc.fragments.entries()) {
1222
+ const box = fragment.getBoundingClientRect();
1223
+ const items = [];
1224
+ for (const leaf of desc.leaves) {
1225
+ if (!fragment.contains(leaf.dom))
1226
+ continue;
1227
+ if (leaf.dom.nodeType !== Node.TEXT_NODE) {
1228
+ const br = leaf.dom;
1229
+ items.push({ offset: leaf.offset, rect: () => br.getBoundingClientRect() });
1230
+ continue;
1231
+ }
1232
+ for (let k = 0; k < leaf.size; k++) {
1233
+ items.push({
1234
+ offset: leaf.offset + k,
1235
+ rect: () => {
1236
+ range.setStart(leaf.dom, k);
1237
+ range.setEnd(leaf.dom, k + 1);
1238
+ // jsdom has no range rects: every block is then one line.
1239
+ return range.getBoundingClientRect?.() ?? NO_RECT;
1240
+ },
1241
+ });
1242
+ }
1243
+ }
1244
+ // The extra <br> that shows an empty last line (no leaf of its own).
1245
+ const tail = fragment.lastChild;
1246
+ if (tail instanceof Element &&
1247
+ tail.tagName === "BR" &&
1248
+ !desc.leaves.some((l) => l.dom === tail))
1249
+ items.push({ offset: desc.node.content.size, rect: () => tail.getBoundingClientRect() });
1250
+ const from = f ? desc.splits[f - 1] : 0;
1251
+ if (!items.length) {
1252
+ starts.push(from);
1253
+ bottoms.push((base + box.height) / scale);
1254
+ base += box.height;
1255
+ continue;
1256
+ }
1257
+ const firsts = [];
1258
+ let i = 0;
1259
+ while (i < items.length) {
1260
+ // The line's reference: its first item with a box (zero-width characters have none).
1261
+ let reference = items[i].rect();
1262
+ for (let k = i + 1; !reference.height && k < items.length; k++)
1263
+ reference = items[k].rect();
1264
+ starts.push(items[i].offset);
1265
+ firsts.push(reference);
1266
+ const middle = (reference.top + reference.bottom) / 2;
1267
+ const below = (j) => {
1268
+ const rect = items[j].rect();
1269
+ // Below the middle of the line's first item: holds when glyph boxes of consecutive
1270
+ // lines overlap (line-height smaller than the font's content area) and for items of
1271
+ // different heights on one line.
1272
+ return rect.height > 0 && rect.top >= middle;
1273
+ };
1274
+ let lo = i + 1;
1275
+ let hi = items.length;
1276
+ while (lo < hi) {
1277
+ const mid = (lo + hi) >> 1;
1278
+ if (below(mid))
1279
+ hi = mid;
1280
+ else
1281
+ lo = mid + 1;
1282
+ }
1283
+ i = lo;
1284
+ }
1285
+ for (let line = 0; line < firsts.length; line++) {
1286
+ const next = firsts[line + 1];
1287
+ const y = next ? (firsts[line].bottom + next.top) / 2 : box.bottom;
1288
+ bottoms.push((base + y - box.top) / scale);
1289
+ }
1290
+ base += box.height;
1291
+ }
1292
+ return { starts, bottoms };
1293
+ }
1294
+ /** The DOM point at the start of a block's fragment `f`. */
1295
+ function fragmentStart(desc, f) {
1296
+ const fragment = desc.fragments[f];
1297
+ const offset = f ? desc.splits[f - 1] : 0;
1298
+ const leaf = desc.leaves.find((l) => l.offset === offset && fragment.contains(l.dom));
1299
+ if (!leaf)
1300
+ return { node: fragment, offset: 0 };
1301
+ return leaf.dom.nodeType === Node.TEXT_NODE ? { node: leaf.dom, offset: 0 } : before(leaf.dom);
1302
+ }
1303
+ /** The DOM point at the end of a block's fragment `f`. */
1304
+ function fragmentEnd(desc, f) {
1305
+ const fragment = desc.fragments[f];
1306
+ const inside = desc.leaves.filter((l) => fragment.contains(l.dom));
1307
+ const last = inside[inside.length - 1];
1308
+ if (!last)
1309
+ return { node: fragment, offset: fragment.childNodes.length };
1310
+ if (last.dom.nodeType === Node.TEXT_NODE)
1311
+ return { node: last.dom, offset: last.size };
1312
+ const point = before(last.dom);
1313
+ return { node: point.node, offset: point.offset + 1 };
1314
+ }
1315
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
1316
+ /** `pos`, or the start (`forward`: the end) of the grapheme cluster it falls inside. */
1317
+ function clusterBoundary(doc, pos, forward) {
1318
+ const { parent, parentOffset } = doc.resolve(pos);
1319
+ if (!parent.inlineContent || parentOffset === 0 || parentOffset === parent.content.size)
1320
+ return pos;
1321
+ // Leaves count as one character, a line feed (it never joins a cluster), as in the core.
1322
+ const text = parent.textBetween(0, parent.content.size, "", "\n");
1323
+ const cluster = graphemes.segment(text).containing(parentOffset);
1324
+ if (!cluster || cluster.index === parentOffset)
1325
+ return pos;
1326
+ return pos - parentOffset + cluster.index + (forward ? cluster.segment.length : 0);
1327
+ }
1328
+ /**
1329
+ * Scrolls every scrollable ancestor of `from`, then the window, so that `rect` is inside its
1330
+ * visible area (minus `scroll-padding`, e.g. for a sticky toolbar). Vertical only: text wraps.
1331
+ */
1332
+ function scrollRectIntoView(from, rect) {
1333
+ const doc = from.ownerDocument;
1334
+ const win = doc.defaultView;
1335
+ if (!win)
1336
+ return;
1337
+ let { top, bottom } = rect;
1338
+ const delta = (low, high) => top < low ? top - low : bottom > high ? Math.min(bottom - high, top - low) : 0;
1339
+ const last = new Set([doc.body, doc.documentElement]); // they scroll as the window
1340
+ for (let el = from; el && !last.has(el); el = el.parentElement) {
1341
+ const style = win.getComputedStyle(el);
1342
+ if (!/auto|scroll|overlay/.test(style.overflowY) || el.scrollHeight <= el.clientHeight)
1343
+ continue;
1344
+ const edge = el.getBoundingClientRect().top + el.clientTop;
1345
+ const low = edge + (Number.parseFloat(style.scrollPaddingTop) || 0);
1346
+ const high = edge + el.clientHeight - (Number.parseFloat(style.scrollPaddingBottom) || 0);
1347
+ const before = el.scrollTop;
1348
+ el.scrollTop += delta(low, high);
1349
+ top -= el.scrollTop - before;
1350
+ bottom -= el.scrollTop - before;
1351
+ }
1352
+ const root = win.getComputedStyle(doc.documentElement);
1353
+ const move = delta(Number.parseFloat(root.scrollPaddingTop) || 0, win.innerHeight - (Number.parseFloat(root.scrollPaddingBottom) || 0));
1354
+ if (move)
1355
+ win.scrollBy(0, move);
1356
+ }
1357
+ function before(node) {
1358
+ const parent = node.parentNode;
1359
+ return { node: parent, offset: Array.prototype.indexOf.call(parent.childNodes, node) };
1360
+ }
1361
+ /** Stand-ins used when diffing DOM text with model text. */
1362
+ const BLOCK_SEPARATOR = "\n";
1363
+ const HARD_BREAK = "\uFFFC";
1364
+ function isHighSurrogate(code) {
1365
+ return code >= 0xd800 && code <= 0xdbff;
1366
+ }
1367
+ const COMPOSITION_INPUT = new Set([
1368
+ "insertCompositionText",
1369
+ "deleteCompositionText",
1370
+ "insertFromComposition",
1371
+ ]);
1372
+ const IS_MAC = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
1373
+ /**
1374
+ * Normalizes a key event to a keymap name: modifiers in the order `Mod-Ctrl-Meta-Alt-Shift-`,
1375
+ * then the key (single characters lower-cased). `Mod` is Cmd on Apple platforms, Ctrl elsewhere.
1376
+ */
1377
+ export function keyName(event) {
1378
+ let key = event.key.length === 1 ? event.key.toLowerCase() : event.key;
1379
+ const mod = IS_MAC ? event.metaKey : event.ctrlKey;
1380
+ // Non-Latin layouts: Ctrl+B still means "b" (use the physical key when the character is not a-z).
1381
+ if (mod && !/^[a-z]$/.test(key) && /^Key[A-Z]$/.test(event.code))
1382
+ key = event.code.slice(3).toLowerCase();
1383
+ let name = key;
1384
+ if (event.shiftKey && key !== "Shift")
1385
+ name = `Shift-${name}`;
1386
+ if (event.altKey)
1387
+ name = `Alt-${name}`;
1388
+ if (IS_MAC ? event.ctrlKey : event.metaKey)
1389
+ name = `${IS_MAC ? "Ctrl" : "Meta"}-${name}`;
1390
+ if (mod)
1391
+ name = `Mod-${name}`;
1392
+ return name;
1393
+ }
1394
+ //# sourceMappingURL=view.js.map