@folijs/view 0.0.0-stage → 0.2.0

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