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