Blame view

lib/jsdom/living/custom-elements/CustomElementRegistry-impl.js 7.42 KB
858f2bdf5   Boyan Georgiev   fixes
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
  "use strict";
  
  const webIDLConversions = require("webidl-conversions");
  const DOMException = require("domexception/webidl2js-wrapper");
  
  const NODE_TYPE = require("../node-type");
  
  const { HTML_NS } = require("../helpers/namespaces");
  const { getHTMLElementInterface } = require("../helpers/create-element");
  const { shadowIncludingInclusiveDescendantsIterator } = require("../helpers/shadow-dom");
  const { isValidCustomElementName, tryUpgradeElement, enqueueCEUpgradeReaction } = require("../helpers/custom-elements");
  
  const idlUtils = require("../generated/utils");
  const HTMLUnknownElement = require("../generated/HTMLUnknownElement");
  
  const LIFECYCLE_CALLBACKS = [
    "connectedCallback",
    "disconnectedCallback",
    "adoptedCallback",
    "attributeChangedCallback"
  ];
  
  function convertToSequenceDOMString(obj) {
    if (!obj || !obj[Symbol.iterator]) {
      throw new TypeError("Invalid Sequence");
    }
  
    return Array.from(obj).map(webIDLConversions.DOMString);
  }
  
  // Returns true is the passed value is a valid constructor.
  // Borrowed from: https://stackoverflow.com/a/39336206/3832710
  function isConstructor(value) {
    if (typeof value !== "function") {
      return false;
    }
  
    try {
      const P = new Proxy(value, {
        construct() {
          return {};
        }
      });
  
      // eslint-disable-next-line no-new
      new P();
  
      return true;
    } catch (error) {
      return false;
    }
  }
  
  // https://html.spec.whatwg.org/#customelementregistry
  class CustomElementRegistryImpl {
    constructor(globalObject) {
      this._customElementDefinitions = [];
      this._elementDefinitionIsRunning = false;
      this._whenDefinedPromiseMap = Object.create(null);
  
      this._globalObject = globalObject;
    }
  
    // https://html.spec.whatwg.org/#dom-customelementregistry-define
    define(name, ctor, options) {
      const { _globalObject } = this;
  
      if (!isConstructor(ctor)) {
        throw new TypeError("Constructor argument is not a constructor.");
      }
  
      if (!isValidCustomElementName(name)) {
        throw DOMException.create(_globalObject, ["Name argument is not a valid custom element name.", "SyntaxError"]);
      }
  
      const nameAlreadyRegistered = this._customElementDefinitions.some(entry => entry.name === name);
      if (nameAlreadyRegistered) {
        throw DOMException.create(_globalObject, [
          "This name has already been registered in the registry.",
          "NotSupportedError"
        ]);
      }
  
      const ctorAlreadyRegistered = this._customElementDefinitions.some(entry => entry.ctor === ctor);
      if (ctorAlreadyRegistered) {
        throw DOMException.create(_globalObject, [
          "This constructor has already been registered in the registry.",
          "NotSupportedError"
        ]);
      }
  
      let localName = name;
  
      let extendsOption = null;
      if (options !== undefined && options.extends) {
        extendsOption = options.extends;
      }
  
      if (extendsOption !== null) {
        if (isValidCustomElementName(extendsOption)) {
          throw DOMException.create(_globalObject, [
            "Option extends value can't be a valid custom element name.",
            "NotSupportedError"
          ]);
        }
  
        const extendsInterface = getHTMLElementInterface(extendsOption);
        if (extendsInterface === HTMLUnknownElement) {
          throw DOMException.create(_globalObject, [
            `${extendsOption} is an HTMLUnknownElement.`,
            "NotSupportedError"
          ]);
        }
  
        localName = extendsOption;
      }
  
      if (this._elementDefinitionIsRunning) {
        throw DOMException.create(_globalObject, [
          "Invalid nested custom element definition.",
          "NotSupportedError"
        ]);
      }
  
      this._elementDefinitionIsRunning = true;
  
      let disableShadow = false;
      let observedAttributes = [];
      const lifecycleCallbacks = {
        connectedCallback: null,
        disconnectedCallback: null,
        adoptedCallback: null,
        attributeChangedCallback: null
      };
  
      let caughtError;
      try {
        const { prototype } = ctor;
  
        if (typeof prototype !== "object") {
          throw new TypeError("Invalid constructor prototype.");
        }
  
        for (const callbackName of LIFECYCLE_CALLBACKS) {
          const callbackValue = prototype[callbackName];
  
          if (callbackValue !== undefined) {
            lifecycleCallbacks[callbackName] = webIDLConversions.Function(callbackValue);
          }
        }
  
        if (lifecycleCallbacks.attributeChangedCallback !== null) {
          const observedAttributesIterable = ctor.observedAttributes;
  
          if (observedAttributesIterable !== undefined) {
            observedAttributes = convertToSequenceDOMString(observedAttributesIterable);
          }
        }
  
        let disabledFeatures = [];
        const disabledFeaturesIterable = ctor.disabledFeatures;
        if (disabledFeaturesIterable) {
          disabledFeatures = convertToSequenceDOMString(disabledFeaturesIterable);
        }
  
        disableShadow = disabledFeatures.includes("shadow");
      } catch (err) {
        caughtError = err;
      } finally {
        this._elementDefinitionIsRunning = false;
      }
  
      if (caughtError !== undefined) {
        throw caughtError;
      }
  
      const definition = {
        name,
        localName,
        ctor,
        observedAttributes,
        lifecycleCallbacks,
        disableShadow,
        constructionStack: []
      };
  
      this._customElementDefinitions.push(definition);
  
      const document = idlUtils.implForWrapper(this._globalObject._document);
  
      const upgradeCandidates = [];
      for (const candidate of shadowIncludingInclusiveDescendantsIterator(document)) {
        if (
          (candidate._namespaceURI === HTML_NS && candidate._localName === localName) &&
          (extendsOption === null || candidate._isValue === name)
        ) {
          upgradeCandidates.push(candidate);
        }
      }
  
      for (const upgradeCandidate of upgradeCandidates) {
        enqueueCEUpgradeReaction(upgradeCandidate, definition);
      }
  
      if (this._whenDefinedPromiseMap[name] !== undefined) {
        this._whenDefinedPromiseMap[name].resolve(undefined);
        delete this._whenDefinedPromiseMap[name];
      }
    }
  
    // https://html.spec.whatwg.org/#dom-customelementregistry-get
    get(name) {
      const definition = this._customElementDefinitions.find(entry => entry.name === name);
      return definition && definition.ctor;
    }
  
    // https://html.spec.whatwg.org/#dom-customelementregistry-whendefined
    whenDefined(name) {
      if (!isValidCustomElementName(name)) {
        return Promise.reject(DOMException.create(
          this._globalObject,
          ["Name argument is not a valid custom element name.", "SyntaxError"]
        ));
      }
  
      const alreadyRegistered = this._customElementDefinitions.some(entry => entry.name === name);
      if (alreadyRegistered) {
        return Promise.resolve();
      }
  
      if (this._whenDefinedPromiseMap[name] === undefined) {
        let resolve;
        const promise = new Promise(r => {
          resolve = r;
        });
  
        // Store the pending Promise along with the extracted resolve callback to actually resolve the returned Promise,
        // once the custom element is registered.
        this._whenDefinedPromiseMap[name] = {
          promise,
          resolve
        };
      }
  
      return this._whenDefinedPromiseMap[name].promise;
    }
  
    // https://html.spec.whatwg.org/#dom-customelementregistry-upgrade
    upgrade(root) {
      for (const candidate of shadowIncludingInclusiveDescendantsIterator(root)) {
        if (candidate.nodeType === NODE_TYPE.ELEMENT_NODE) {
          tryUpgradeElement(candidate);
        }
      }
    }
  }
  
  module.exports = {
    implementation: CustomElementRegistryImpl
  };