CustomElementRegistry.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/FunctionObject.h>
  7. #include <LibJS/Runtime/Iterator.h>
  8. #include <LibJS/Runtime/ValueInlines.h>
  9. #include <LibWeb/Bindings/CustomElementRegistryPrototype.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/ElementFactory.h>
  12. #include <LibWeb/DOM/ShadowRoot.h>
  13. #include <LibWeb/HTML/CustomElements/CustomElementName.h>
  14. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  15. #include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
  16. #include <LibWeb/HTML/Scripting/Environments.h>
  17. #include <LibWeb/HTML/Window.h>
  18. #include <LibWeb/Namespace.h>
  19. namespace Web::HTML {
  20. GC_DEFINE_ALLOCATOR(CustomElementRegistry);
  21. GC_DEFINE_ALLOCATOR(CustomElementDefinition);
  22. CustomElementRegistry::CustomElementRegistry(JS::Realm& realm)
  23. : Bindings::PlatformObject(realm)
  24. {
  25. }
  26. CustomElementRegistry::~CustomElementRegistry() = default;
  27. void CustomElementRegistry::initialize(JS::Realm& realm)
  28. {
  29. Base::initialize(realm);
  30. WEB_SET_PROTOTYPE_FOR_INTERFACE(CustomElementRegistry);
  31. }
  32. void CustomElementRegistry::visit_edges(Visitor& visitor)
  33. {
  34. Base::visit_edges(visitor);
  35. visitor.visit(m_custom_element_definitions);
  36. visitor.visit(m_when_defined_promise_map);
  37. }
  38. // https://webidl.spec.whatwg.org/#es-callback-function
  39. // https://github.com/whatwg/html/pull/9893
  40. static JS::ThrowCompletionOr<GC::Ref<WebIDL::CallbackType>> convert_value_to_callback_function(JS::VM& vm, JS::Value value)
  41. {
  42. // FIXME: De-duplicate this from the IDL generator.
  43. // 1. If the result of calling IsCallable(V) is false and the conversion to an IDL value is not being performed due to V being assigned to an attribute whose type is a nullable callback function that is annotated with [LegacyTreatNonObjectAsNull], then throw a TypeError.
  44. if (!value.is_function())
  45. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, value.to_string_without_side_effects());
  46. // 2. Return the IDL callback function type value that represents a reference to the same object that V represents, with the incumbent realm as the callback context.
  47. return vm.heap().allocate<WebIDL::CallbackType>(value.as_object(), HTML::incumbent_realm());
  48. }
  49. // https://webidl.spec.whatwg.org/#es-sequence
  50. static JS::ThrowCompletionOr<Vector<String>> convert_value_to_sequence_of_strings(JS::VM& vm, JS::Value value)
  51. {
  52. // FIXME: De-duplicate this from the IDL generator.
  53. // An ECMAScript value V is converted to an IDL sequence<T> value as follows:
  54. // 1. If V is not an Object, throw a TypeError.
  55. if (!value.is_object())
  56. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, value.to_string_without_side_effects());
  57. // 2. Let method be ? GetMethod(V, @@iterator).
  58. auto method = TRY(value.get_method(vm, vm.well_known_symbol_iterator()));
  59. // 3. If method is undefined, throw a TypeError.
  60. if (!method)
  61. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, value.to_string_without_side_effects());
  62. // 4. Return the result of creating a sequence from V and method.
  63. // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
  64. // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
  65. // 1. Let iter be ? GetIterator(iterable, sync, method).
  66. // FIXME: The WebIDL spec is out of date - it should be using GetIteratorFromMethod.
  67. auto iterator = TRY(JS::get_iterator_from_method(vm, value, *method));
  68. // 2. Initialize i to be 0.
  69. Vector<String> sequence_of_strings;
  70. // 3. Repeat
  71. for (;;) {
  72. // 1. Let next be ? IteratorStep(iter).
  73. auto next = TRY(JS::iterator_step(vm, iterator));
  74. // 2. If next is false, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
  75. if (!next)
  76. return sequence_of_strings;
  77. // 3. Let nextItem be ? IteratorValue(next).
  78. auto next_item = TRY(JS::iterator_value(vm, *next));
  79. // 4. Initialize Si to the result of converting nextItem to an IDL value of type T.
  80. // https://webidl.spec.whatwg.org/#es-DOMString
  81. // An ECMAScript value V is converted to an IDL DOMString value by running the following algorithm:
  82. // 1. If V is null and the conversion is to an IDL type associated with the [LegacyNullToEmptyString] extended attribute, then return the DOMString value that represents the empty string.
  83. // NOTE: This doesn't apply.
  84. // 2. Let x be ? ToString(V).
  85. // 3. Return the IDL DOMString value that represents the same sequence of code units as the one the ECMAScript String value x represents.
  86. auto string_value = TRY(next_item.to_string(vm));
  87. sequence_of_strings.append(move(string_value));
  88. // 5. Set i to i + 1.
  89. }
  90. }
  91. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-define
  92. JS::ThrowCompletionOr<void> CustomElementRegistry::define(String const& name, WebIDL::CallbackType* constructor, ElementDefinitionOptions options)
  93. {
  94. auto& realm = this->realm();
  95. auto& vm = this->vm();
  96. // 1. If IsConstructor(constructor) is false, then throw a TypeError.
  97. if (!JS::Value(constructor->callback).is_constructor())
  98. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, JS::Value(constructor->callback).to_string_without_side_effects());
  99. // 2. If name is not a valid custom element name, then throw a "SyntaxError" DOMException.
  100. if (!is_valid_custom_element_name(name))
  101. return JS::throw_completion(WebIDL::SyntaxError::create(realm, MUST(String::formatted("'{}' is not a valid custom element name"sv, name))));
  102. // 3. If this's custom element definition set contains an item with name name, then throw a "NotSupportedError" DOMException.
  103. auto existing_definition_with_name_iterator = m_custom_element_definitions.find_if([&name](auto const& definition) {
  104. return definition->name() == name;
  105. });
  106. if (existing_definition_with_name_iterator != m_custom_element_definitions.end())
  107. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, MUST(String::formatted("A custom element with name '{}' is already defined"sv, name))));
  108. // 4. If this's custom element definition set contains an item with constructor constructor, then throw a "NotSupportedError" DOMException.
  109. auto existing_definition_with_constructor_iterator = m_custom_element_definitions.find_if([&constructor](auto const& definition) {
  110. return definition->constructor().callback == constructor->callback;
  111. });
  112. if (existing_definition_with_constructor_iterator != m_custom_element_definitions.end())
  113. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, "The given constructor is already in use by another custom element"_string));
  114. // 5. Let localName be name.
  115. String local_name = name;
  116. // 6. Let extends be options["extends"] if it exists; otherwise null.
  117. auto& extends = options.extends;
  118. // 7. If extends is not null:
  119. if (extends.has_value()) {
  120. // 1. If extends is a valid custom element name, then throw a "NotSupportedError" DOMException.
  121. if (is_valid_custom_element_name(extends.value()))
  122. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, MUST(String::formatted("'{}' is a custom element name, only non-custom elements can be extended"sv, extends.value()))));
  123. // 2. If the element interface for extends and the HTML namespace is HTMLUnknownElement
  124. // (e.g., if extends does not indicate an element definition in this specification),
  125. // then throw a "NotSupportedError" DOMException.
  126. if (DOM::is_unknown_html_element(extends.value()))
  127. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, MUST(String::formatted("'{}' is an unknown HTML element"sv, extends.value()))));
  128. // 3. Set localName to extends.
  129. local_name = extends.value();
  130. }
  131. // 8. If this's element definition is running is true, then throw a "NotSupportedError" DOMException.
  132. if (m_element_definition_is_running)
  133. return JS::throw_completion(WebIDL::NotSupportedError::create(realm, "Cannot recursively define custom elements"_string));
  134. // 9. Set this's element definition is running to true.
  135. m_element_definition_is_running = true;
  136. // 10. Let formAssociated be false.
  137. bool form_associated = false;
  138. // 11. Let disableInternals be false.
  139. bool disable_internals = false;
  140. // 12. Let disableShadow be false.
  141. bool disable_shadow = false;
  142. // 13. Let observedAttributes be an empty sequence<DOMString>.
  143. Vector<String> observed_attributes;
  144. // NOTE: This is not in the spec, but is required because of how we catch the exception by using a lambda, meaning we need to define this
  145. // variable outside of it to use it later.
  146. CustomElementDefinition::LifecycleCallbacksStorage lifecycle_callbacks;
  147. // 14. Run the following steps while catching any exceptions:
  148. auto get_definition_attributes_from_constructor = [&]() -> JS::ThrowCompletionOr<void> {
  149. // 1. Let prototype be ? Get(constructor, "prototype").
  150. auto prototype_value = TRY(constructor->callback->get(vm.names.prototype));
  151. // 2. If prototype is not an Object, then throw a TypeError exception.
  152. if (!prototype_value.is_object())
  153. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, prototype_value.to_string_without_side_effects());
  154. auto& prototype = prototype_value.as_object();
  155. // 3. Let lifecycleCallbacks be the ordered map «[ "connectedCallback" → null, "disconnectedCallback" → null, "adoptedCallback" → null,
  156. // "attributeChangedCallback" → null ]».
  157. lifecycle_callbacks.set(CustomElementReactionNames::connectedCallback, {});
  158. lifecycle_callbacks.set(CustomElementReactionNames::disconnectedCallback, {});
  159. lifecycle_callbacks.set(CustomElementReactionNames::adoptedCallback, {});
  160. lifecycle_callbacks.set(CustomElementReactionNames::attributeChangedCallback, {});
  161. // 4. For each callbackName of the keys of lifecycleCallbacks:
  162. for (auto const& callback_name : { CustomElementReactionNames::connectedCallback, CustomElementReactionNames::disconnectedCallback, CustomElementReactionNames::adoptedCallback, CustomElementReactionNames::attributeChangedCallback }) {
  163. // 1. Let callbackValue be ? Get(prototype, callbackName).
  164. auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string()));
  165. // 2. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of
  166. // converting callbackValue to the Web IDL Function callback type.
  167. if (!callback_value.is_undefined()) {
  168. auto callback = TRY(convert_value_to_callback_function(vm, callback_value));
  169. lifecycle_callbacks.set(callback_name, callback);
  170. }
  171. }
  172. // 5. If lifecycleCallbacks["attributeChangedCallback"] is not null:
  173. auto attribute_changed_callback_iterator = lifecycle_callbacks.find(CustomElementReactionNames::attributeChangedCallback);
  174. VERIFY(attribute_changed_callback_iterator != lifecycle_callbacks.end());
  175. if (attribute_changed_callback_iterator->value) {
  176. // 1. Let observedAttributesIterable be ? Get(constructor, "observedAttributes").
  177. auto observed_attributes_iterable = TRY(constructor->callback->get(vm.names.observedAttributes));
  178. // 2. If observedAttributesIterable is not undefined, then set observedAttributes to the result of converting observedAttributesIterable
  179. // to a sequence<DOMString>. Rethrow any exceptions from the conversion.
  180. if (!observed_attributes_iterable.is_undefined())
  181. observed_attributes = TRY(convert_value_to_sequence_of_strings(vm, observed_attributes_iterable));
  182. }
  183. // 6. Let disabledFeatures be an empty sequence<DOMString>.
  184. Vector<String> disabled_features;
  185. // 7. Let disabledFeaturesIterable be ? Get(constructor, "disabledFeatures").
  186. auto disabled_features_iterable = TRY(constructor->callback->get(vm.names.disabledFeatures));
  187. // 8. If disabledFeaturesIterable is not undefined, then set disabledFeatures to the result of converting disabledFeaturesIterable to a
  188. // sequence<DOMString>. Rethrow any exceptions from the conversion.
  189. if (!disabled_features_iterable.is_undefined())
  190. disabled_features = TRY(convert_value_to_sequence_of_strings(vm, disabled_features_iterable));
  191. // 9. If disabledFeatures contains "internals", then set disableInternals to true.
  192. disable_internals = disabled_features.contains_slow("internals"sv);
  193. // 10. If disabledFeatures contains "shadow", then set disableShadow to true.
  194. disable_shadow = disabled_features.contains_slow("shadow"sv);
  195. // 11. Let formAssociatedValue be ? Get( constructor, "formAssociated").
  196. auto form_associated_value = TRY(constructor->callback->get(vm.names.formAssociated));
  197. // 12. Set formAssociated to the result of converting formAssociatedValue to a boolean.
  198. form_associated = form_associated_value.to_boolean();
  199. // 13. If formAssociated is true, then for each callbackName of « "formAssociatedCallback", "formResetCallback", "formDisabledCallback",
  200. // "formStateRestoreCallback" »:
  201. if (form_associated) {
  202. for (auto const& callback_name : { CustomElementReactionNames::formAssociatedCallback, CustomElementReactionNames::formResetCallback, CustomElementReactionNames::formDisabledCallback, CustomElementReactionNames::formStateRestoreCallback }) {
  203. // 1. Let callbackValue be ? Get(prototype, callbackName).
  204. auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string()));
  205. // 2. If callbackValue is not undefined, then set lifecycleCallbacks[callbackName] to the result of converting callbackValue
  206. // to the Web IDL Function callback type.
  207. if (!callback_value.is_undefined())
  208. lifecycle_callbacks.set(callback_name, TRY(convert_value_to_callback_function(vm, callback_value)));
  209. }
  210. }
  211. return {};
  212. };
  213. auto maybe_exception = get_definition_attributes_from_constructor();
  214. // Then, regardless of whether the above steps threw an exception or not: set this's element definition is running to false.
  215. m_element_definition_is_running = false;
  216. // Finally, if the steps threw an exception, rethrow that exception.
  217. if (maybe_exception.is_throw_completion())
  218. return maybe_exception.release_error();
  219. // 15. Let definition be a new custom element definition with name name, local name localName, constructor constructor,
  220. // observed attributes observedAttributes, lifecycle callbacks lifecycleCallbacks, form-associated formAssociated,
  221. // disable internals disableInternals, and disable shadow disableShadow.
  222. auto definition = CustomElementDefinition::create(realm, name, local_name, *constructor, move(observed_attributes), move(lifecycle_callbacks), form_associated, disable_internals, disable_shadow);
  223. // 16. Append definition to this's custom element definition set.
  224. m_custom_element_definitions.append(definition);
  225. // 17. Let document be this's relevant global object's associated Document.
  226. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  227. // 18. Let upgradeCandidates be all elements that are shadow-including descendants of document, whose namespace is the HTML namespace
  228. // and whose local name is localName, in shadow-including tree order.
  229. // Additionally, if extends is non-null, only include elements whose is value is equal to name.
  230. Vector<GC::Root<DOM::Element>> upgrade_candidates;
  231. document.for_each_shadow_including_descendant([&](DOM::Node& inclusive_descendant) {
  232. if (!is<DOM::Element>(inclusive_descendant))
  233. return TraversalDecision::Continue;
  234. auto& inclusive_descendant_element = static_cast<DOM::Element&>(inclusive_descendant);
  235. if (inclusive_descendant_element.namespace_uri() == Namespace::HTML && inclusive_descendant_element.local_name() == local_name && (!extends.has_value() || inclusive_descendant_element.is_value() == name))
  236. upgrade_candidates.append(GC::make_root(inclusive_descendant_element));
  237. return TraversalDecision::Continue;
  238. });
  239. // 19. For each element element of upgradeCandidates, enqueue a custom element upgrade reaction given element and definition.
  240. for (auto& element : upgrade_candidates)
  241. element->enqueue_a_custom_element_upgrade_reaction(definition);
  242. // 20. If this's when-defined promise map[name] exists:
  243. auto promise_when_defined_iterator = m_when_defined_promise_map.find(name);
  244. if (promise_when_defined_iterator != m_when_defined_promise_map.end()) {
  245. // 1. Resolve this's when-defined promise map[name] with constructor.
  246. WebIDL::resolve_promise(realm, promise_when_defined_iterator->value, constructor->callback);
  247. // 2. Remove this's when-defined promise map[name].
  248. m_when_defined_promise_map.remove(name);
  249. }
  250. return {};
  251. }
  252. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-get
  253. Variant<GC::Root<WebIDL::CallbackType>, JS::Value> CustomElementRegistry::get(String const& name) const
  254. {
  255. // 1. If this's custom element definition set contains an item with name name, then return that item's constructor.
  256. auto existing_definition_iterator = m_custom_element_definitions.find_if([&name](auto const& definition) {
  257. return definition->name() == name;
  258. });
  259. if (!existing_definition_iterator.is_end())
  260. return GC::make_root((*existing_definition_iterator)->constructor());
  261. // 2. Return undefined.
  262. return JS::js_undefined();
  263. }
  264. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-getname
  265. Optional<String> CustomElementRegistry::get_name(GC::Root<WebIDL::CallbackType> const& constructor) const
  266. {
  267. // 1. If this's custom element definition set contains an item with constructor constructor, then return that item's name.
  268. auto existing_definition_iterator = m_custom_element_definitions.find_if([&constructor](auto const& definition) {
  269. return definition->constructor().callback == constructor.cell()->callback;
  270. });
  271. if (!existing_definition_iterator.is_end())
  272. return (*existing_definition_iterator)->name();
  273. // 2. Return null.
  274. return {};
  275. }
  276. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-whendefined
  277. WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> CustomElementRegistry::when_defined(String const& name)
  278. {
  279. auto& realm = this->realm();
  280. // 1. If name is not a valid custom element name, then return a promise rejected with a "SyntaxError" DOMException.
  281. if (!is_valid_custom_element_name(name))
  282. return WebIDL::create_rejected_promise(realm, WebIDL::SyntaxError::create(realm, MUST(String::formatted("'{}' is not a valid custom element name"sv, name))));
  283. // 2. If this's custom element definition set contains an item with name name, then return a promise resolved with that item's constructor.
  284. auto existing_definition_iterator = m_custom_element_definitions.find_if([&name](GC::Root<CustomElementDefinition> const& definition) {
  285. return definition->name() == name;
  286. });
  287. if (existing_definition_iterator != m_custom_element_definitions.end())
  288. return WebIDL::create_resolved_promise(realm, (*existing_definition_iterator)->constructor().callback);
  289. // 3. If this's when-defined promise map[name] does not exist, then set this's when-defined promise map[name] to a new promise.
  290. auto existing_promise_iterator = m_when_defined_promise_map.find(name);
  291. GC::Ptr<WebIDL::Promise> promise;
  292. if (existing_promise_iterator == m_when_defined_promise_map.end()) {
  293. promise = WebIDL::create_promise(realm);
  294. m_when_defined_promise_map.set(name, *promise);
  295. } else {
  296. promise = existing_promise_iterator->value;
  297. }
  298. // 4. Return this's when-defined promise map[name].
  299. VERIFY(promise);
  300. return GC::Ref { *promise };
  301. }
  302. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-upgrade
  303. void CustomElementRegistry::upgrade(GC::Ref<DOM::Node> root) const
  304. {
  305. // 1. Let candidates be a list of all of root's shadow-including inclusive descendant elements, in shadow-including tree order.
  306. Vector<GC::Root<DOM::Element>> candidates;
  307. root->for_each_shadow_including_inclusive_descendant([&](DOM::Node& inclusive_descendant) {
  308. if (!is<DOM::Element>(inclusive_descendant))
  309. return TraversalDecision::Continue;
  310. auto& inclusive_descendant_element = static_cast<DOM::Element&>(inclusive_descendant);
  311. candidates.append(GC::make_root(inclusive_descendant_element));
  312. return TraversalDecision::Continue;
  313. });
  314. // 2. For each candidate of candidates, try to upgrade candidate.
  315. for (auto& candidate : candidates)
  316. candidate->try_to_upgrade();
  317. }
  318. GC::Ptr<CustomElementDefinition> CustomElementRegistry::get_definition_with_name_and_local_name(String const& name, String const& local_name) const
  319. {
  320. auto definition_iterator = m_custom_element_definitions.find_if([&](GC::Root<CustomElementDefinition> const& definition) {
  321. return definition->name() == name && definition->local_name() == local_name;
  322. });
  323. return definition_iterator.is_end() ? nullptr : definition_iterator->ptr();
  324. }
  325. GC::Ptr<CustomElementDefinition> CustomElementRegistry::get_definition_from_new_target(JS::FunctionObject const& new_target) const
  326. {
  327. auto definition_iterator = m_custom_element_definitions.find_if([&](GC::Root<CustomElementDefinition> const& definition) {
  328. return definition->constructor().callback.ptr() == &new_target;
  329. });
  330. return definition_iterator.is_end() ? nullptr : definition_iterator->ptr();
  331. }
  332. }