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 106
/
CustomElementRegistry.js
278 lines (238 loc) · 9.05 KB
/
CustomElementRegistry.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
/**
* @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 CustomElementInternals from './CustomElementInternals.js';
import DocumentConstructionObserver from './DocumentConstructionObserver.js';
import Deferred from './Deferred.js';
import * as Utilities from './Utilities.js';
/**
* @unrestricted
*/
export default class CustomElementRegistry {
/**
* @param {!CustomElementInternals} internals
*/
constructor(internals) {
/**
* @private
* @type {boolean}
*/
this._elementDefinitionIsRunning = false;
/**
* @private
* @type {!CustomElementInternals}
*/
this._internals = internals;
/**
* @private
* @type {!Map<string, !Deferred<undefined>>}
*/
this._whenDefinedDeferred = new Map();
/**
* The default flush callback triggers the document walk synchronously.
* @private
* @type {!Function}
*/
this._flushCallback = fn => fn();
/**
* @private
* @type {boolean}
*/
this._flushPending = false;
/**
* @private
* @type {!Array<!CustomElementDefinition>}
*/
this._pendingDefinitions = [];
/**
* @private
* @const {!DocumentConstructionObserver|undefined}
*/
this._documentConstructionObserver = internals.useDocumentConstructionObserver ?
new DocumentConstructionObserver(internals, document) : undefined;
}
/**
* @param {string} localName
* @param {!Function} constructor
*/
define(localName, constructor) {
if (!(constructor instanceof Function)) {
throw new TypeError('Custom element constructors must be functions.');
}
if (!Utilities.isValidCustomElementName(localName)) {
throw new SyntaxError(`The element name '${localName}' is not valid.`);
}
if (this._internals.localNameToDefinition(localName)) {
throw new Error(`A custom element with name '${localName}' has already been defined.`);
}
if (this._elementDefinitionIsRunning) {
throw new Error('A custom element is already being defined.');
}
this._elementDefinitionIsRunning = true;
let connectedCallback;
let disconnectedCallback;
let adoptedCallback;
let attributeChangedCallback;
let observedAttributes;
try {
/** @type {!Object} */
const prototype = constructor.prototype;
if (!(prototype instanceof Object)) {
throw new TypeError('The custom element constructor\'s prototype is not an object.');
}
function getCallback(name) {
const callbackValue = prototype[name];
if (callbackValue !== undefined && !(callbackValue instanceof Function)) {
throw new Error(`The '${name}' callback must be a function.`);
}
return callbackValue;
}
connectedCallback = getCallback('connectedCallback');
disconnectedCallback = getCallback('disconnectedCallback');
adoptedCallback = getCallback('adoptedCallback');
attributeChangedCallback = getCallback('attributeChangedCallback');
// `observedAttributes` should not be read unless an
// `attributesChangedCallback` exists
observedAttributes = (attributeChangedCallback &&
constructor['observedAttributes']) || [];
} catch (e) {
throw e;
} finally {
this._elementDefinitionIsRunning = false;
}
const definition = {
localName,
constructorFunction: constructor,
connectedCallback,
disconnectedCallback,
adoptedCallback,
attributeChangedCallback,
observedAttributes,
constructionStack: [],
};
this._internals.setDefinition(localName, definition);
this._pendingDefinitions.push(definition);
// If we've already called the flush callback and it hasn't called back yet,
// don't call it again.
if (!this._flushPending) {
this._flushPending = true;
this._flushCallback(() => this._flush());
}
}
upgrade(element) {
this._internals.patchAndUpgradeTree(element);
}
_flush() {
// If no new definitions were defined, don't attempt to flush. This could
// happen if a flush callback keeps the function it is given and calls it
// multiple times.
if (this._flushPending === false) return;
this._flushPending = false;
const pendingDefinitions = this._pendingDefinitions;
/**
* Unupgraded elements with definitions that were defined *before* the last
* flush, in document order.
* @type {!Array<!HTMLElement>}
*/
const elementsWithStableDefinitions = [];
/**
* A map from `localName`s of definitions that were defined *after* the last
* flush to unupgraded elements matching that definition, in document order.
* @type {!Map<string, !Array<!HTMLElement>>}
*/
const elementsWithPendingDefinitions = new Map();
for (let i = 0; i < pendingDefinitions.length; i++) {
elementsWithPendingDefinitions.set(pendingDefinitions[i].localName, []);
}
this._internals.patchAndUpgradeTree(document, {
upgrade: element => {
// Ignore the element if it has already upgraded or failed to upgrade.
if (element.__CE_state !== undefined) return;
const localName = element.localName;
// If there is an applicable pending definition for the element, add the
// element to the list of elements to be upgraded with that definition.
const pendingElements = elementsWithPendingDefinitions.get(localName);
if (pendingElements) {
pendingElements.push(element);
// If there is *any other* applicable definition for the element, add it
// to the list of elements with stable definitions that need to be upgraded.
} else if (this._internals.localNameToDefinition(localName)) {
elementsWithStableDefinitions.push(element);
}
},
});
// Upgrade elements with 'stable' definitions first.
for (let i = 0; i < elementsWithStableDefinitions.length; i++) {
this._internals.upgradeElement(elementsWithStableDefinitions[i]);
}
// Upgrade elements with 'pending' definitions in the order they were defined.
while (pendingDefinitions.length > 0) {
const definition = pendingDefinitions.shift();
const localName = definition.localName;
// Attempt to upgrade all applicable elements.
const pendingUpgradableElements = elementsWithPendingDefinitions.get(definition.localName);
for (let i = 0; i < pendingUpgradableElements.length; i++) {
this._internals.upgradeElement(pendingUpgradableElements[i]);
}
// Resolve any promises created by `whenDefined` for the definition.
const deferred = this._whenDefinedDeferred.get(localName);
if (deferred) {
deferred.resolve(undefined);
}
}
}
/**
* @param {string} localName
* @return {Function|undefined}
*/
get(localName) {
const definition = this._internals.localNameToDefinition(localName);
if (definition) {
return definition.constructorFunction;
}
return undefined;
}
/**
* @param {string} localName
* @return {!Promise<undefined>}
*/
whenDefined(localName) {
if (!Utilities.isValidCustomElementName(localName)) {
return Promise.reject(new SyntaxError(`'${localName}' is not a valid custom element name.`));
}
const prior = this._whenDefinedDeferred.get(localName);
if (prior) {
return prior.toPromise();
}
const deferred = new Deferred();
this._whenDefinedDeferred.set(localName, deferred);
const definition = this._internals.localNameToDefinition(localName);
// Resolve immediately only if the given local name has a definition *and*
// the full document walk to upgrade elements with that local name has
// already happened.
if (definition && !this._pendingDefinitions.some(d => d.localName === localName)) {
deferred.resolve(undefined);
}
return deferred.toPromise();
}
polyfillWrapFlushCallback(outer) {
if (this._documentConstructionObserver) {
this._documentConstructionObserver.disconnect();
}
const inner = this._flushCallback;
this._flushCallback = flush => outer(() => inner(flush));
}
}
// Closure compiler exports.
window['CustomElementRegistry'] = CustomElementRegistry;
CustomElementRegistry.prototype['define'] = CustomElementRegistry.prototype.define;
CustomElementRegistry.prototype['upgrade'] = CustomElementRegistry.prototype.upgrade;
CustomElementRegistry.prototype['get'] = CustomElementRegistry.prototype.get;
CustomElementRegistry.prototype['whenDefined'] = CustomElementRegistry.prototype.whenDefined;
CustomElementRegistry.prototype['polyfillWrapFlushCallback'] = CustomElementRegistry.prototype.polyfillWrapFlushCallback;