This repository has been archived by the owner on Oct 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathCustomElementInternals.js
407 lines (357 loc) · 13.3 KB
/
CustomElementInternals.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
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
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import * as Utilities from './Utilities.js';
import CEState from './CustomElementState.js';
export default class CustomElementInternals {
/**
* @param {{
* shadyDomFastWalk: boolean,
* noDocumentConstructionObserver: boolean,
* }} options
*/
constructor(options) {
/** @type {!Map<string, !CustomElementDefinition>} */
this._localNameToDefinition = new Map();
/** @type {!Map<!Function, !CustomElementDefinition>} */
this._constructorToDefinition = new Map();
/** @type {!Array<!function(!Node)>} */
this._patchesNode = [];
/** @type {!Array<!function(!Element)>} */
this._patchesElement = [];
/** @type {boolean} */
this._hasPatches = false;
/** @const {boolean} */
this.shadyDomFastWalk = options.shadyDomFastWalk;
/** @const {boolean} */
this.useDocumentConstructionObserver = !options.noDocumentConstructionObserver;
}
/**
* @param {string} localName
* @param {!CustomElementDefinition} definition
*/
setDefinition(localName, definition) {
this._localNameToDefinition.set(localName, definition);
this._constructorToDefinition.set(definition.constructorFunction, definition);
}
/**
* @param {string} localName
* @return {!CustomElementDefinition|undefined}
*/
localNameToDefinition(localName) {
return this._localNameToDefinition.get(localName);
}
/**
* @param {!Function} constructor
* @return {!CustomElementDefinition|undefined}
*/
constructorToDefinition(constructor) {
return this._constructorToDefinition.get(constructor);
}
/**
* @param {!Node} node
* @param {!function(!Element)} callback
* @param {!Set<!Node>=} visitedImports
*/
forEachElement(node, callback, visitedImports) {
const sd = window['ShadyDOM'];
if (this.shadyDomFastWalk && sd && sd['inUse']) {
if (node.nodeType === Node.ELEMENT_NODE) {
const element = /** @type {!Element} */(node);
callback(element);
}
// most easily gets to document, element, documentFragment
if (node.querySelectorAll) {
const elements = sd['nativeMethods'].querySelectorAll.call(node, '*');
for (let i = 0; i < elements.length; i++) {
callback(elements[i]);
}
}
} else {
Utilities.walkDeepDescendantElements(node, callback, visitedImports);
}
}
/**
* @param {!function(!Node)} patch
*/
addNodePatch(patch) {
this._hasPatches = true;
this._patchesNode.push(patch);
}
/**
* @param {!function(!Element)} patch
*/
addElementPatch(patch) {
this._hasPatches = true;
this._patchesElement.push(patch);
}
/**
* @param {!Node} node
*/
patchTree(node) {
if (!this._hasPatches) return;
this.forEachElement(node, element => this.patchElement(element));
}
/**
* @param {!Node} node
*/
patchNode(node) {
if (!this._hasPatches) return;
if (node.__CE_patched) return;
node.__CE_patched = true;
for (let i = 0; i < this._patchesNode.length; i++) {
this._patchesNode[i](node);
}
}
/**
* @param {!Element} element
*/
patchElement(element) {
if (!this._hasPatches) return;
if (element.__CE_patched) return;
element.__CE_patched = true;
for (let i = 0; i < this._patchesNode.length; i++) {
this._patchesNode[i](element);
}
for (let i = 0; i < this._patchesElement.length; i++) {
this._patchesElement[i](element);
}
}
/**
* @param {!Node} root
*/
connectTree(root) {
const elements = [];
this.forEachElement(root, element => elements.push(element));
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
if (element.__CE_state === CEState.custom) {
this.connectedCallback(element);
} else {
this.upgradeElement(element);
}
}
}
/**
* @param {!Node} root
*/
disconnectTree(root) {
const elements = [];
this.forEachElement(root, element => elements.push(element));
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
if (element.__CE_state === CEState.custom) {
this.disconnectedCallback(element);
}
}
}
/**
* Upgrades all uncustomized custom elements at and below a root node for
* which there is a definition. When custom element reaction callbacks are
* assumed to be called synchronously (which, by the current DOM / HTML spec
* definitions, they are *not*), callbacks for both elements customized
* synchronously by the parser and elements being upgraded occur in the same
* relative order.
*
* NOTE: This function, when used to simulate the construction of a tree that
* is already created but not customized (i.e. by the parser), does *not*
* prevent the element from reading the 'final' (true) state of the tree. For
* example, the element, during truly synchronous parsing / construction would
* see that it contains no children as they have not yet been inserted.
* However, this function does not modify the tree, the element will
* (incorrectly) have children. Additionally, self-modification restrictions
* for custom element constructors imposed by the DOM spec are *not* enforced.
*
*
* The following nested list shows the steps extending down from the HTML
* spec's parsing section that cause elements to be synchronously created and
* upgraded:
*
* The "in body" insertion mode:
* https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
* - Switch on token:
* .. other cases ..
* -> Any other start tag
* - [Insert an HTML element](below) for the token.
*
* Insert an HTML element:
* https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
* - Insert a foreign element for the token in the HTML namespace:
* https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
* - Create an element for a token:
* https://html.spec.whatwg.org/multipage/syntax.html#create-an-element-for-the-token
* - Will execute script flag is true?
* - (Element queue pushed to the custom element reactions stack.)
* - Create an element:
* https://dom.spec.whatwg.org/#concept-create-element
* - Sync CE flag is true?
* - Constructor called.
* - Self-modification restrictions enforced.
* - Sync CE flag is false?
* - (Upgrade reaction enqueued.)
* - Attributes appended to element.
* (`attributeChangedCallback` reactions enqueued.)
* - Will execute script flag is true?
* - (Element queue popped from the custom element reactions stack.
* Reactions in the popped stack are invoked.)
* - (Element queue pushed to the custom element reactions stack.)
* - Insert the element:
* https://dom.spec.whatwg.org/#concept-node-insert
* - Shadow-including descendants are connected. During parsing
* construction, there are no shadow-*excluding* descendants.
* However, the constructor may have validly attached a shadow
* tree to itself and added descendants to that shadow tree.
* (`connectedCallback` reactions enqueued.)
* - (Element queue popped from the custom element reactions stack.
* Reactions in the popped stack are invoked.)
*
* @param {!Node} root
* @param {{
* visitedImports: (!Set<!Node>|undefined),
* upgrade: (!function(!Element)|undefined),
* }=} options
*/
patchAndUpgradeTree(root, options = {}) {
const visitedImports = options.visitedImports;
const upgrade = options.upgrade || (element => this.upgradeElement(element));
const elements = [];
const gatherElements = element => {
if (this._hasPatches) {
this.patchElement(element);
}
if (element.localName === 'link' &&
element.getAttribute('rel') === 'import') {
// The HTML Imports polyfill sets a descendant element of the link to
// the `import` property, specifically this is *not* a Document.
const importNode = /** @type {?Node} */ (element.import);
if (importNode instanceof Node) {
importNode.__CE_isImportDocument = true;
// Connected links are associated with the registry.
importNode.__CE_hasRegistry = true;
}
if (importNode && importNode.readyState === 'complete') {
importNode.__CE_documentLoadHandled = true;
} else {
// If this link's import root is not available, its contents can't be
// walked. Wait for 'load' and walk it when it's ready.
element.addEventListener('load', () => {
const importNode = /** @type {!Node} */ (element.import);
if (importNode.__CE_documentLoadHandled) return;
importNode.__CE_documentLoadHandled = true;
// Clone the `visitedImports` set that was populated sync during
// the `patchAndUpgradeTree` call that caused this 'load' handler to
// be added. Then, remove *this* link's import node so that we can
// walk that import again, even if it was partially walked later
// during the same `patchAndUpgradeTree` call.
const clonedVisitedImports = new Set(visitedImports);
clonedVisitedImports.delete(importNode);
this.patchAndUpgradeTree(importNode, {visitedImports: clonedVisitedImports, upgrade});
});
}
} else {
elements.push(element);
}
};
// `forEachElement` populates (and internally checks against)
// `visitedImports` when traversing a loaded import.
this.forEachElement(root, gatherElements, visitedImports);
for (let i = 0; i < elements.length; i++) {
upgrade(elements[i]);
}
}
/**
* @param {!HTMLElement} element
*/
upgradeElement(element) {
const currentState = element.__CE_state;
if (currentState !== undefined) return;
// Prevent elements created in documents without a browsing context from
// upgrading.
//
// https://html.spec.whatwg.org/multipage/custom-elements.html#look-up-a-custom-element-definition
// "If document does not have a browsing context, return null."
//
// https://html.spec.whatwg.org/multipage/window-object.html#dom-document-defaultview
// "The defaultView IDL attribute of the Document interface, on getting,
// must return this Document's browsing context's WindowProxy object, if
// this Document has an associated browsing context, or null otherwise."
const ownerDocument = element.ownerDocument;
if (
!ownerDocument.defaultView &&
!(ownerDocument.__CE_isImportDocument && ownerDocument.__CE_hasRegistry)
) return;
const definition = this._localNameToDefinition.get(element.localName);
if (!definition) return;
definition.constructionStack.push(element);
const constructor = definition.constructorFunction;
try {
try {
let result = new (constructor)();
if (result !== element) {
throw new Error('The custom element constructor did not produce the element being upgraded.');
}
} finally {
definition.constructionStack.pop();
}
} catch (e) {
element.__CE_state = CEState.failed;
throw e;
}
element.__CE_state = CEState.custom;
element.__CE_definition = definition;
// Check `hasAttributes` here to avoid iterating when it's not necessary.
if (definition.attributeChangedCallback && element.hasAttributes()) {
const observedAttributes = definition.observedAttributes;
for (let i = 0; i < observedAttributes.length; i++) {
const name = observedAttributes[i];
const value = element.getAttribute(name);
if (value !== null) {
this.attributeChangedCallback(element, name, null, value, null);
}
}
}
if (Utilities.isConnected(element)) {
this.connectedCallback(element);
}
}
/**
* @param {!Element} element
*/
connectedCallback(element) {
const definition = element.__CE_definition;
if (definition.connectedCallback) {
definition.connectedCallback.call(element);
}
}
/**
* @param {!Element} element
*/
disconnectedCallback(element) {
const definition = element.__CE_definition;
if (definition.disconnectedCallback) {
definition.disconnectedCallback.call(element);
}
}
/**
* @param {!Element} element
* @param {string} name
* @param {?string} oldValue
* @param {?string} newValue
* @param {?string} namespace
*/
attributeChangedCallback(element, name, oldValue, newValue, namespace) {
const definition = element.__CE_definition;
if (
definition.attributeChangedCallback &&
definition.observedAttributes.indexOf(name) > -1
) {
definition.attributeChangedCallback.call(element, name, oldValue, newValue, namespace);
}
}
}