/
domobserver.ts
425 lines (378 loc) · 15.3 KB
/
domobserver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import browser from "./browser"
import {ContentView, Dirty} from "./contentview"
import {EditorView} from "./editorview"
import {editable} from "./extension"
import {hasSelection, getSelection, DOMSelectionState, isEquivalentPosition,
deepActiveElement, dispatchKey, atElementStart} from "./dom"
const observeOptions = {
childList: true,
characterData: true,
subtree: true,
attributes: true,
characterDataOldValue: true
}
// IE11 has very broken mutation observers, so we also listen to
// DOMCharacterDataModified there
const useCharData = browser.ie && browser.ie_version <= 11
export class DOMObserver {
dom: HTMLElement
win: Window
observer: MutationObserver
active: boolean = false
// The known selection. Kept in our own object, as opposed to just
// directly accessing the selection because:
// - Safari doesn't report the right selection in shadow DOM
// - Reading from the selection forces a DOM layout
// - This way, we can ignore selectionchange events if we have
// already seen the 'new' selection
selectionRange: DOMSelectionState = new DOMSelectionState
// Set when a selection change is detected, cleared on flush
selectionChanged = false
delayedFlush = -1
resizeTimeout = -1
queue: MutationRecord[] = []
delayedAndroidKey: {key: string, keyCode: number} | null = null
onCharData: any
scrollTargets: HTMLElement[] = []
intersection: IntersectionObserver | null = null
resize: ResizeObserver | null = null
intersecting: boolean = false
gapIntersection: IntersectionObserver | null = null
gaps: readonly HTMLElement[] = []
// Timeout for scheduling check of the parents that need scroll handlers
parentCheck = -1
constructor(private view: EditorView,
private onChange: (from: number, to: number, typeOver: boolean) => boolean,
private onScrollChanged: (event: Event) => void) {
this.dom = view.contentDOM
this.observer = new MutationObserver(mutations => {
for (let mut of mutations) this.queue.push(mut)
// IE11 will sometimes (on typing over a selection or
// backspacing out a single character text node) call the
// observer callback before actually updating the DOM.
//
// Unrelatedly, iOS Safari will, when ending a composition,
// sometimes first clear it, deliver the mutations, and then
// reinsert the finished text. CodeMirror's handling of the
// deletion will prevent the reinsertion from happening,
// breaking composition.
if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&
mutations.some(m => m.type == "childList" && m.removedNodes.length ||
m.type == "characterData" && m.oldValue!.length > m.target.nodeValue!.length))
this.flushSoon()
else
this.flush()
})
if (useCharData)
this.onCharData = (event: MutationEvent) => {
this.queue.push({target: event.target,
type: "characterData",
oldValue: event.prevValue} as MutationRecord)
this.flushSoon()
}
this.onSelectionChange = this.onSelectionChange.bind(this)
this.onResize = this.onResize.bind(this)
this.onPrint = this.onPrint.bind(this)
this.onScroll = this.onScroll.bind(this)
if (typeof ResizeObserver == "function") {
this.resize = new ResizeObserver(() => {
if (this.view.docView.lastUpdate < Date.now() - 75) this.onResize()
})
this.resize.observe(view.scrollDOM)
}
this.win = view.dom.ownerDocument.defaultView
this.addWindowListeners(this.win)
this.start()
if (typeof IntersectionObserver == "function") {
this.intersection = new IntersectionObserver(entries => {
if (this.parentCheck < 0) this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000)
if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {
this.intersecting = !this.intersecting
if (this.intersecting != this.view.inView)
this.onScrollChanged(document.createEvent("Event"))
}
}, {})
this.intersection.observe(this.dom)
this.gapIntersection = new IntersectionObserver(entries => {
if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
this.onScrollChanged(document.createEvent("Event"));
}, {})
}
this.listenForScroll()
this.readSelectionRange()
}
onScroll(e: Event) {
if (this.intersecting) this.flush(false)
this.onScrollChanged(e)
}
onResize() {
if (this.resizeTimeout < 0) this.resizeTimeout = setTimeout(() => {
this.resizeTimeout = -1
this.view.requestMeasure()
}, 50)
}
onPrint() {
this.view.viewState.printing = true
this.view.measure()
setTimeout(() => {
this.view.viewState.printing = false
this.view.requestMeasure()
}, 500)
}
updateGaps(gaps: readonly HTMLElement[]) {
if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
this.gapIntersection.disconnect()
for (let gap of gaps) this.gapIntersection.observe(gap)
this.gaps = gaps
}
}
onSelectionChange(event: Event) {
if (!this.readSelectionRange() || this.delayedAndroidKey) return
let {view} = this, sel = this.selectionRange
if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))
return
let context = sel.anchorNode && view.docView.nearest(sel.anchorNode)
if (context && context.ignoreEvent(event)) return
// Deletions on IE11 fire their events in the wrong order, giving
// us a selection change event before the DOM changes are
// reported.
// Chrome Android has a similar issue when backspacing out a
// selection (#645).
if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&
// (Selection.isCollapsed isn't reliable on IE)
sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
this.flushSoon()
else
this.flush(false)
}
readSelectionRange() {
let {view} = this
// The Selection object is broken in shadow roots in Safari. See
// https://github.com/codemirror/dev/issues/414
let range = browser.safari && (view.root as any).nodeType == 11 && deepActiveElement() == this.dom &&
safariSelectionRangeHack(this.view) || getSelection(view.root)
if (!range || this.selectionRange.eq(range)) return false
let local = hasSelection(this.dom, range)
// Detect the situation where the browser has, on focus, moved the
// selection to the start of the content element. Reset it to the
// position from the editor state.
if (local && !this.selectionChanged &&
view.inputState.lastFocusTime > Date.now() - 200 &&
view.inputState.lastTouchTime < Date.now() - 300 &&
atElementStart(this.dom, range)) {
this.view.inputState.lastFocusTime = 0
view.docView.updateSelection()
return false
}
this.selectionRange.setRange(range)
if (local) this.selectionChanged = true
return true
}
setSelectionRange(anchor: {node: Node, offset: number}, head: {node: Node, offset: number}) {
this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset)
this.selectionChanged = false
}
clearSelectionRange() {
this.selectionRange.set(null, 0, null, 0)
}
listenForScroll() {
this.parentCheck = -1
let i = 0, changed: HTMLElement[] | null = null
for (let dom = this.dom as any; dom;) {
if (dom.nodeType == 1) {
if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom) i++
else if (!changed) changed = this.scrollTargets.slice(0, i)
if (changed) changed.push(dom)
dom = dom.assignedSlot || dom.parentNode
} else if (dom.nodeType == 11) { // Shadow root
dom = dom.host
} else {
break
}
}
if (i < this.scrollTargets.length && !changed) changed = this.scrollTargets.slice(0, i)
if (changed) {
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll)
for (let dom of this.scrollTargets = changed) dom.addEventListener("scroll", this.onScroll)
}
}
ignore<T>(f: () => T): T {
if (!this.active) return f()
try {
this.stop()
return f()
} finally {
this.start()
this.clear()
}
}
start() {
if (this.active) return
this.observer.observe(this.dom, observeOptions)
if (useCharData)
this.dom.addEventListener("DOMCharacterDataModified", this.onCharData)
this.active = true
}
stop() {
if (!this.active) return
this.active = false
this.observer.disconnect()
if (useCharData)
this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData)
}
// Throw away any pending changes
clear() {
this.processRecords()
this.queue.length = 0
this.selectionChanged = false
}
// Chrome Android, especially in combination with GBoard, not only
// doesn't reliably fire regular key events, but also often
// surrounds the effect of enter or backspace with a bunch of
// composition events that, when interrupted, cause text duplication
// or other kinds of corruption. This hack makes the editor back off
// from handling DOM changes for a moment when such a key is
// detected (via beforeinput or keydown), and then tries to flush
// them or, if that has no effect, dispatches the given key.
delayAndroidKey(key: string, keyCode: number) {
if (!this.delayedAndroidKey) requestAnimationFrame(() => {
let key = this.delayedAndroidKey!
this.delayedAndroidKey = null
this.delayedFlush = -1
if (!this.flush())
dispatchKey(this.dom, key.key, key.keyCode)
})
// Since backspace beforeinput is sometimes signalled spuriously,
// Enter always takes precedence.
if (!this.delayedAndroidKey || key == "Enter")
this.delayedAndroidKey = {key, keyCode}
}
flushSoon() {
if (this.delayedFlush < 0)
this.delayedFlush = window.setTimeout(() => { this.delayedFlush = -1; this.flush() }, 20)
}
forceFlush() {
if (this.delayedFlush >= 0) {
window.clearTimeout(this.delayedFlush)
this.delayedFlush = -1
}
this.flush()
}
processRecords() {
let records = this.queue
for (let mut of this.observer.takeRecords()) records.push(mut)
if (records.length) this.queue = []
let from = -1, to = -1, typeOver = false
for (let record of records) {
let range = this.readMutation(record)
if (!range) continue
if (range.typeOver) typeOver = true
if (from == -1) {
;({from, to} = range)
} else {
from = Math.min(range.from, from)
to = Math.max(range.to, to)
}
}
return {from, to, typeOver}
}
// Apply pending changes, if any
flush(readSelection = true) {
// Completely hold off flushing when pending keys are set—the code
// managing those will make sure processRecords is called and the
// view is resynchronized after
if (this.delayedFlush >= 0 || this.delayedAndroidKey) return
if (readSelection) this.readSelectionRange()
let {from, to, typeOver} = this.processRecords()
let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange)
if (from < 0 && !newSel) return
this.view.inputState.lastFocusTime = 0
this.selectionChanged = false
let startState = this.view.state
let handled = this.onChange(from, to, typeOver)
// The view wasn't updated
if (this.view.state == startState) this.view.update([])
return handled
}
readMutation(rec: MutationRecord): {from: number, to: number, typeOver: boolean} | null {
let cView = this.view.docView.nearest(rec.target)
if (!cView || cView.ignoreMutation(rec)) return null
cView.markDirty(rec.type == "attributes")
if (rec.type == "attributes") cView.dirty |= Dirty.Attrs
if (rec.type == "childList") {
let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1)
let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1)
return {from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false}
} else if (rec.type == "characterData") {
return {from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue}
} else {
return null
}
}
setWindow(win: Window) {
if (win != this.win) {
this.removeWindowListeners(this.win)
this.win = win
this.addWindowListeners(this.win)
}
}
addWindowListeners(win: Window) {
win.addEventListener("resize", this.onResize)
win.addEventListener("beforeprint", this.onPrint)
win.addEventListener("scroll", this.onScroll)
win.document.addEventListener("selectionchange", this.onSelectionChange)
}
removeWindowListeners(win: Window) {
win.removeEventListener("scroll", this.onScroll)
win.removeEventListener("resize", this.onResize)
win.removeEventListener("beforeprint", this.onPrint)
win.document.removeEventListener("selectionchange", this.onSelectionChange)
}
destroy() {
this.stop()
this.intersection?.disconnect()
this.gapIntersection?.disconnect()
this.resize?.disconnect()
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll)
this.removeWindowListeners(this.win)
clearTimeout(this.parentCheck)
clearTimeout(this.resizeTimeout)
}
}
function findChild(cView: ContentView, dom: Node | null, dir: number): ContentView | null {
while (dom) {
let curView = ContentView.get(dom)
if (curView && curView.parent == cView) return curView
let parent = dom.parentNode
dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling
}
return null
}
// Used to work around a Safari Selection/shadow DOM bug (#414)
function safariSelectionRangeHack(view: EditorView) {
let found = null as null | StaticRange
// Because Safari (at least in 2018-2021) doesn't provide regular
// access to the selection inside a shadowroot, we have to perform a
// ridiculous hack to get at it—using `execCommand` to trigger a
// `beforeInput` event so that we can read the target range from the
// event.
function read(event: InputEvent) {
event.preventDefault()
event.stopImmediatePropagation()
found = (event as any).getTargetRanges()[0]
}
view.contentDOM.addEventListener("beforeinput", read, true)
document.execCommand("indent")
view.contentDOM.removeEventListener("beforeinput", read, true)
if (!found) return null
let anchorNode = found!.startContainer, anchorOffset = found!.startOffset
let focusNode = found!.endContainer, focusOffset = found!.endOffset
let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor)
// Since such a range doesn't distinguish between anchor and head,
// use a heuristic that flips it around if its end matches the
// current anchor.
if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
[anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]
return {anchorNode, anchorOffset, focusNode, focusOffset}
}