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