-
Notifications
You must be signed in to change notification settings - Fork 30
/
mutation_observer.js
220 lines (190 loc) · 5.04 KB
/
mutation_observer.js
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
// @ts-check
/** @typedef { import('../types').ElementSpec } ElementSpec */
/** @typedef { import('../types').ElementEvents } ElementEvents */
/** @typedef { import('../types').ObserverList } ObserverList */
import each from '../each'
/**
* The name of this strategy.
* @type string
*/
export const name = 'MutationObserver'
/**
* List of observers tags.
* @type ObserverList
*/
export const observers = {}
export function isSupported() {
return 'MutationObserver' in window
}
/**
* Defines a custom element.
*
* @example
* defineElement(
* { component: MyComponent },
* 'my-div',
* {
* onMount: () => {},
* onUpdate: () => {},
* onUnmount: () => {},
* }
* )
*
* @private
* @param {ElementSpec} elSpec
* @param {string} elName
* @param {ElementEvents} events
*/
export function defineElement(elSpec, elName, events) {
elName = elName.toLowerCase()
// Maintain parity with what would happen in Custom Elements mode
if (!isValidName(elName)) {
if (elSpec.quiet) {
return
}
throw new Error(`Remount: "${elName}" is not a valid custom element elName`)
}
if (observers[elName]) {
if (elSpec.quiet) {
return
}
throw new Error(`Remount: "${elName}" is already registered`)
}
const observer = new MutationObserver(
/** @type MutationCallback */ mutations => {
each(mutations, (/** @type MutationRecord */ mutation) => {
each(mutation.addedNodes, (/** @type Node */ node) => {
if (isElement(node)) {
checkForMount(node, elName, events)
}
})
})
}
)
observer.observe(document.body, {
childList: true,
subtree: true
})
observers[name] = /* true */ observer
window.addEventListener('DOMContentLoaded', () => {
const nodes = document.getElementsByTagName(name)
each(nodes, (/** @type HTMLElement */ node) =>
checkForMount(node, name, events)
)
})
}
/**
* Checks if this new element should fire an `onUpdate` hook.
* Recurses down to its descendant nodes.
*
* @param {HTMLElement} node
* @param {string} elName
* @param {ElementEvents} events
*/
function checkForMount(node, elName, events) {
if (node.nodeName.toLowerCase() === elName) {
// It's a match!
events.onMount(node, node)
observeForUpdates(node, events)
observeForRemoval(node, events)
} else if (node.children && node.children.length) {
// Recurse down into the other additions
each(node.children, (/** @type HTMLElement */ subnode) => {
if (isElement(subnode)) {
checkForMount(subnode, elName, events)
}
})
}
}
/**
* Observes for any changes in attributes.
*
* @param {Element} node
* @param {ElementEvents} events
*/
function observeForUpdates(node, events) {
const { onUpdate } = events
const observer = new MutationObserver(
/** @type MutationCallback */ mutations => {
each(mutations, (/** @type MutationRecord */ mutation) => {
const targetNode = mutation.target
if (isElement(targetNode)) {
onUpdate(targetNode, targetNode)
}
})
}
)
observer.observe(node, { attributes: true })
}
/**
* Observes a node's parent to wait until the node is removed
* @param {HTMLElement} node
* @param {ElementEvents} events
*/
function observeForRemoval(node, events) {
const { onUnmount } = events
const parent = node.parentNode
// Not sure when this can happen, but let's add this for type safety
if (!parent) {
return
}
const observer = new MutationObserver(
/** @type MutationCallback */ mutations => {
each(mutations, (/** @type MutationRecord */ mutation) => {
each(mutation.removedNodes, (/** @type Node */ subnode) => {
if (node !== subnode) {
return
}
if (isElement(node)) {
// @ts-ignore TypeScript expects 0 arguments...?
observer.disconnect(parent)
onUnmount(node, node)
}
})
})
}
)
observer.observe(parent, { childList: true, subtree: true })
}
/**
* Validate a custom tag.
*
* Since Remount can work with either Custom Elements or MutationObserver API's,
* it'd be wise if we rejected element names that won't work in Custom Elements
* mode (even if we're using MutationObserver mode).
*
* @param {string} elName
* @returns {boolean}
*
* @example
* isValidName('div') // => false
* isValidName('my-div') // => true
* isValidName('123-456') // => false
* isValidName('my-123') // => true
*
* @private
*/
function isValidName(elName) {
return !!(elName.indexOf('-') !== -1 && elName.match(/^[a-z][a-z0-9-]*$/))
}
/**
* Shadow DOM is not supported with the Mutation Observer strategy.
*/
export function supportsShadow() {
return false
}
/**
* Checks if a given Node is an HTMLElement.
*
* It's possible that a mutation's `addedNodes` return something that isn't an
* HTMLElement.
*
* @param {any} node
* @returns {node is HTMLElement}
*/
function isElement(node) {
if (node) {
return true
}
return false
}