diff options
Diffstat (limited to 'Userland/Libraries/LibWeb/HTML')
17 files changed, 756 insertions, 24 deletions
diff --git a/Userland/Libraries/LibWeb/HTML/AttributeNames.h b/Userland/Libraries/LibWeb/HTML/AttributeNames.h index 9d602b6c0e..08838deee0 100644 --- a/Userland/Libraries/LibWeb/HTML/AttributeNames.h +++ b/Userland/Libraries/LibWeb/HTML/AttributeNames.h @@ -83,6 +83,7 @@ namespace AttributeNames { __ENUMERATE_HTML_ATTRIBUTE(imagesrcset) \ __ENUMERATE_HTML_ATTRIBUTE(inert) \ __ENUMERATE_HTML_ATTRIBUTE(integrity) \ + __ENUMERATE_HTML_ATTRIBUTE(is) \ __ENUMERATE_HTML_ATTRIBUTE(ismap) \ __ENUMERATE_HTML_ATTRIBUTE(itemscope) \ __ENUMERATE_HTML_ATTRIBUTE(label) \ diff --git a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp index 7649bcf37d..53b3aa1f4a 100644 --- a/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp +++ b/Userland/Libraries/LibWeb/HTML/BrowsingContext.cpp @@ -6,6 +6,7 @@ #include <LibWeb/Bindings/MainThreadVM.h> #include <LibWeb/DOM/Document.h> +#include <LibWeb/DOM/ElementFactory.h> #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/HTMLCollection.h> #include <LibWeb/DOM/Range.h> @@ -27,6 +28,7 @@ #include <LibWeb/Layout/BreakNode.h> #include <LibWeb/Layout/TextNode.h> #include <LibWeb/Layout/Viewport.h> +#include <LibWeb/Namespace.h> #include <LibWeb/Page/Page.h> #include <LibWeb/URL/URL.h> @@ -191,9 +193,9 @@ JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context document->set_is_initial_about_blank(true); // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element. - auto html_node = document->create_element(HTML::TagNames::html).release_value(); - MUST(html_node->append_child(document->create_element(HTML::TagNames::head).release_value())); - MUST(html_node->append_child(document->create_element(HTML::TagNames::body).release_value())); + auto html_node = DOM::create_element(document, HTML::TagNames::html, Namespace::HTML).release_value_but_fixme_should_propagate_errors(); + MUST(html_node->append_child(DOM::create_element(document, HTML::TagNames::head, Namespace::HTML).release_value_but_fixme_should_propagate_errors())); + MUST(html_node->append_child(DOM::create_element(document, HTML::TagNames::body, Namespace::HTML).release_value_but_fixme_should_propagate_errors())); MUST(document->append_child(html_node)); // 19. Set the active document of browsingContext to document. diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementDefinition.h b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementDefinition.h new file mode 100644 index 0000000000..ddfd9e7a98 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementDefinition.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/String.h> +#include <LibWeb/HTML/HTMLElement.h> +#include <LibWeb/WebIDL/CallbackType.h> + +namespace Web::HTML { + +struct AlreadyConstructedCustomElementMarker { +}; + +// https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-definition +class CustomElementDefinition : public JS::Cell { + JS_CELL(CustomElementDefinition, JS::Cell); + + using LifecycleCallbacksStorage = OrderedHashMap<FlyString, JS::Handle<WebIDL::CallbackType>>; + using ConstructionStackStorage = Vector<Variant<JS::Handle<DOM::Element>, AlreadyConstructedCustomElementMarker>>; + + static JS::NonnullGCPtr<CustomElementDefinition> create(JS::Realm& realm, String const& name, String const& local_name, WebIDL::CallbackType& constructor, Vector<String>&& observed_attributes, LifecycleCallbacksStorage&& lifecycle_callbacks, bool form_associated, bool disable_internals, bool disable_shadow) + { + return realm.heap().allocate<CustomElementDefinition>(realm, name, local_name, constructor, move(observed_attributes), move(lifecycle_callbacks), form_associated, disable_internals, disable_shadow).release_allocated_value_but_fixme_should_propagate_errors(); + } + + ~CustomElementDefinition() = default; + + String const& name() const { return m_name; } + String const& local_name() const { return m_local_name; } + + WebIDL::CallbackType& constructor() { return *m_constructor; } + WebIDL::CallbackType const& constructor() const { return *m_constructor; } + + Vector<String> const& observed_attributes() const { return m_observed_attributes; } + + LifecycleCallbacksStorage const& lifecycle_callbacks() const { return m_lifecycle_callbacks; } + + ConstructionStackStorage& construction_stack() { return m_construction_stack; } + ConstructionStackStorage const& construction_stack() const { return m_construction_stack; } + + bool form_associated() const { return m_form_associated; } + bool disable_internals() const { return m_disable_internals; } + bool disable_shadow() const { return m_disable_shadow; } + +private: + CustomElementDefinition(String const& name, String const& local_name, WebIDL::CallbackType& constructor, Vector<String>&& observed_attributes, LifecycleCallbacksStorage&& lifecycle_callbacks, bool form_associated, bool disable_internals, bool disable_shadow) + : m_name(name) + , m_local_name(local_name) + , m_constructor(JS::make_handle(constructor)) + , m_observed_attributes(move(observed_attributes)) + , m_lifecycle_callbacks(move(lifecycle_callbacks)) + , m_form_associated(form_associated) + , m_disable_internals(disable_internals) + , m_disable_shadow(disable_shadow) + { + } + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-name + // A name + // A valid custom element name + String m_name; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-local-name + // A local name + // A local name + String m_local_name; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-constructor + // A Web IDL CustomElementConstructor callback function type value wrapping the custom element constructor + JS::Handle<WebIDL::CallbackType> m_constructor; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-observed-attributes + // A list of observed attributes + // A sequence<DOMString> + Vector<String> m_observed_attributes; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks + // A collection of lifecycle callbacks + // A map, whose keys are the strings "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback", + // "formAssociatedCallback", "formDisabledCallback", "formResetCallback", and "formStateRestoreCallback". + // The corresponding values are either a Web IDL Function callback function type value, or null. + // By default the value of each entry is null. + LifecycleCallbacksStorage m_lifecycle_callbacks; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-construction-stack + // A construction stack + // A list, initially empty, that is manipulated by the upgrade an element algorithm and the HTML element constructors. + // Each entry in the list will be either an element or an already constructed marker. + ConstructionStackStorage m_construction_stack; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-form-associated + // A form-associated boolean + // If this is true, user agent treats elements associated to this custom element definition as form-associated custom elements. + bool m_form_associated { false }; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-disable-internals + // A disable internals boolean + // Controls attachInternals(). + bool m_disable_internals { false }; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-disable-shadow + // A disable shadow boolean + // Controls attachShadow(). + bool m_disable_shadow { false }; +}; + +} diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.cpp b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.cpp new file mode 100644 index 0000000000..cab0d2b681 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h> + +namespace Web::HTML::CustomElementReactionNames { + +#define __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(name) FlyString name; +ENUMERATE_CUSTOM_ELEMENT_REACTION_NAMES +#undef __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME + +ErrorOr<void> initialize_strings() +{ + static bool s_initialized = false; + VERIFY(!s_initialized); + +#define __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(name) \ + name = TRY(#name##_fly_string); + ENUMERATE_CUSTOM_ELEMENT_REACTION_NAMES +#undef __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME + + s_initialized = true; + return {}; +} + +} diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.h b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.h new file mode 100644 index 0000000000..ed54dfcc33 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementReactionNames.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/FlyString.h> + +namespace Web::HTML::CustomElementReactionNames { + +// https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks +#define ENUMERATE_CUSTOM_ELEMENT_REACTION_NAMES \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(connectedCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(disconnectedCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(adoptedCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(attributeChangedCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(formAssociatedCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(formDisabledCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(formResetCallback) \ + __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(formStateRestoreCallback) + +#define __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME(name) extern FlyString name; +ENUMERATE_CUSTOM_ELEMENT_REACTION_NAMES +#undef __ENUMERATE_CUSTOM_ELEMENT_REACTION_NAME + +ErrorOr<void> initialize_strings(); + +} diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.cpp b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.cpp new file mode 100644 index 0000000000..6f23225b9b --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.cpp @@ -0,0 +1,411 @@ +/* + * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include <LibJS/Runtime/FunctionObject.h> +#include <LibJS/Runtime/IteratorOperations.h> +#include <LibWeb/DOM/Document.h> +#include <LibWeb/DOM/ElementFactory.h> +#include <LibWeb/DOM/ShadowRoot.h> +#include <LibWeb/HTML/CustomElements/CustomElementName.h> +#include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h> +#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h> +#include <LibWeb/HTML/Scripting/Environments.h> +#include <LibWeb/HTML/Window.h> +#include <LibWeb/Namespace.h> + +namespace Web::HTML { + +CustomElementRegistry::CustomElementRegistry(JS::Realm& realm) + : Bindings::PlatformObject(realm) +{ +} + +CustomElementRegistry::~CustomElementRegistry() = default; + +JS::ThrowCompletionOr<void> CustomElementRegistry::initialize(JS::Realm& realm) +{ + MUST_OR_THROW_OOM(Base::initialize(realm)); + set_prototype(&Bindings::ensure_web_prototype<Bindings::CustomElementRegistryPrototype>(realm, "CustomElementRegistry")); + + return {}; +} + +// https://webidl.spec.whatwg.org/#es-callback-function +static JS::ThrowCompletionOr<JS::NonnullGCPtr<WebIDL::CallbackType>> convert_value_to_callback_function(JS::VM& vm, JS::Value value) +{ + // FIXME: De-duplicate this from the IDL generator. + // 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. + if (!value.is_function()) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, TRY_OR_THROW_OOM(vm, value.to_string_without_side_effects())); + + // 2. Return the IDL callback function type value that represents a reference to the same object that V represents, with the incumbent settings object as the callback context. + return vm.heap().allocate_without_realm<WebIDL::CallbackType>(value.as_object(), HTML::incumbent_settings_object()); +} + +// https://webidl.spec.whatwg.org/#es-sequence +static JS::ThrowCompletionOr<Vector<String>> convert_value_to_sequence_of_strings(JS::VM& vm, JS::Value value) +{ + // FIXME: De-duplicate this from the IDL generator. + // An ECMAScript value V is converted to an IDL sequence<T> value as follows: + // 1. If Type(V) is not Object, throw a TypeError. + if (!value.is_object()) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, value.to_string_without_side_effects())); + + // 2. Let method be ? GetMethod(V, @@iterator). + auto* method = TRY(value.get_method(vm, *vm.well_known_symbol_iterator())); + + // 3. If method is undefined, throw a TypeError. + if (!method) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, value.to_string_without_side_effects())); + + // 4. Return the result of creating a sequence from V and method. + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps: + // 1. Let iter be ? GetIterator(iterable, sync, method). + auto iterator = TRY(JS::get_iterator(vm, value, JS::IteratorHint::Sync, method)); + + // 2. Initialize i to be 0. + Vector<String> sequence_of_strings; + + // 3. Repeat + for (;;) { + // 1. Let next be ? IteratorStep(iter). + auto* next = TRY(JS::iterator_step(vm, iterator)); + + // 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. + if (!next) + return sequence_of_strings; + + // 3. Let nextItem be ? IteratorValue(next). + auto next_item = TRY(JS::iterator_value(vm, *next)); + + // 4. Initialize Si to the result of converting nextItem to an IDL value of type T. + + // https://webidl.spec.whatwg.org/#es-DOMString + // An ECMAScript value V is converted to an IDL DOMString value by running the following algorithm: + // 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. + // NOTE: This doesn't apply. + + // 2. Let x be ? ToString(V). + // 3. Return the IDL DOMString value that represents the same sequence of code units as the one the ECMAScript String value x represents. + auto string_value = TRY(next_item.to_string(vm)); + + sequence_of_strings.append(move(string_value)); + + // 5. Set i to i + 1. + } +} + +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-define +JS::ThrowCompletionOr<void> CustomElementRegistry::define(String const& name, WebIDL::CallbackType* constructor, ElementDefinitionOptions options) +{ + auto& realm = this->realm(); + auto& vm = this->vm(); + + // 1. If IsConstructor(constructor) is false, then throw a TypeError. + if (!JS::Value(constructor->callback).is_constructor()) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, TRY_OR_THROW_OOM(vm, JS::Value(constructor->callback).to_string_without_side_effects())); + + // 2. If name is not a valid custom element name, then throw a "SyntaxError" DOMException. + if (!is_valid_custom_element_name(name)) + return JS::throw_completion(WebIDL::SyntaxError::create(realm, DeprecatedString::formatted("'{}' is not a valid custom element name"sv, name))); + + // 3. If this CustomElementRegistry contains an entry with name name, then throw a "NotSupportedError" DOMException. + auto existing_definition_with_name_iterator = m_custom_element_definitions.find_if([&name](JS::Handle<CustomElementDefinition> const& definition) { + return definition->name() == name; + }); + + if (existing_definition_with_name_iterator != m_custom_element_definitions.end()) + return JS::throw_completion(WebIDL::NotSupportedError::create(realm, DeprecatedString::formatted("A custom element with name '{}' is already defined"sv, name))); + + // 4. If this CustomElementRegistry contains an entry with constructor constructor, then throw a "NotSupportedError" DOMException. + auto existing_definition_with_constructor_iterator = m_custom_element_definitions.find_if([&constructor](JS::Handle<CustomElementDefinition> const& definition) { + return definition->constructor().callback == constructor->callback; + }); + + if (existing_definition_with_constructor_iterator != m_custom_element_definitions.end()) + return JS::throw_completion(WebIDL::NotSupportedError::create(realm, "The given constructor is already in use by another custom element"sv)); + + // 5. Let localName be name. + String local_name = name; + + // 6. Let extends be the value of the extends member of options, or null if no such member exists. + auto& extends = options.extends; + + // 7. If extends is not null, then: + if (extends.has_value()) { + // 1. If extends is a valid custom element name, then throw a "NotSupportedError" DOMException. + if (is_valid_custom_element_name(extends.value())) + return JS::throw_completion(WebIDL::NotSupportedError::create(realm, DeprecatedString::formatted("'{}' is a custom element name, only non-custom elements can be extended"sv, extends.value()))); + + // 2. If the element interface for extends and the HTML namespace is HTMLUnknownElement (e.g., if extends does not indicate an element definition in this specification), then throw a "NotSupportedError" DOMException. + if (DOM::is_unknown_html_element(extends.value().to_deprecated_string())) + return JS::throw_completion(WebIDL::NotSupportedError::create(realm, DeprecatedString::formatted("'{}' is an unknown HTML element"sv, extends.value()))); + + // 3. Set localName to extends. + local_name = extends.value(); + } + + // 8. If this CustomElementRegistry's element definition is running flag is set, then throw a "NotSupportedError" DOMException. + if (m_element_definition_is_running) + return JS::throw_completion(WebIDL::NotSupportedError::create(realm, "Cannot recursively define custom elements"sv)); + + // 9. Set this CustomElementRegistry's element definition is running flag. + m_element_definition_is_running = true; + + // 10. Let formAssociated be false. + bool form_associated = false; + + // 11. Let disableInternals be false. + bool disable_internals = false; + + // 12. Let disableShadow be false. + bool disable_shadow = false; + + // 13. Let observedAttributes be an empty sequence<DOMString>. + Vector<String> observed_attributes; + + // 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 variable outside of it to use it later. + CustomElementDefinition::LifecycleCallbacksStorage lifecycle_callbacks; + + // 14. Run the following substeps while catching any exceptions: + auto get_definition_attributes_from_constructor = [&]() -> JS::ThrowCompletionOr<void> { + // 1. Let prototype be ? Get(constructor, "prototype"). + auto prototype_value = TRY(constructor->callback->get(vm.names.prototype)); + + // 2. If Type(prototype) is not Object, then throw a TypeError exception. + if (!prototype_value.is_object()) + return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, prototype_value.to_string_without_side_effects())); + + auto& prototype = prototype_value.as_object(); + + // 3. Let lifecycleCallbacks be a map with the keys "connectedCallback", "disconnectedCallback", "adoptedCallback", and "attributeChangedCallback", each of which belongs to an entry whose value is null. + lifecycle_callbacks.set(CustomElementReactionNames::connectedCallback, {}); + lifecycle_callbacks.set(CustomElementReactionNames::disconnectedCallback, {}); + lifecycle_callbacks.set(CustomElementReactionNames::adoptedCallback, {}); + lifecycle_callbacks.set(CustomElementReactionNames::attributeChangedCallback, {}); + + // 4. For each of the keys callbackName in lifecycleCallbacks, in the order listed in the previous step: + for (auto const& callback_name : { CustomElementReactionNames::connectedCallback, CustomElementReactionNames::disconnectedCallback, CustomElementReactionNames::adoptedCallback, CustomElementReactionNames::attributeChangedCallback }) { + // 1. Let callbackValue be ? Get(prototype, callbackName). + auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string())); + + // 2. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL Function callback type. Rethrow any exceptions from the conversion. + if (!callback_value.is_undefined()) { + auto callback = TRY(convert_value_to_callback_function(vm, callback_value)); + lifecycle_callbacks.set(callback_name, JS::make_handle(callback)); + } + } + + // 5. If the value of the entry in lifecycleCallbacks with key "attributeChangedCallback" is not null, then: + auto attribute_changed_callback_iterator = lifecycle_callbacks.find(CustomElementReactionNames::attributeChangedCallback); + VERIFY(attribute_changed_callback_iterator != lifecycle_callbacks.end()); + if (!attribute_changed_callback_iterator->value.is_null()) { + // 1. Let observedAttributesIterable be ? Get(constructor, "observedAttributes"). + auto observed_attributes_iterable = TRY(constructor->callback->get(JS::PropertyKey { "observedAttributes" })); + + // 2. If observedAttributesIterable is not undefined, then set observedAttributes to the result of converting observedAttributesIterable to a sequence<DOMString>. Rethrow any exceptions from the conversion. + if (!observed_attributes_iterable.is_undefined()) + observed_attributes = TRY(convert_value_to_sequence_of_strings(vm, observed_attributes_iterable)); + } + + // 6. Let disabledFeatures be an empty sequence<DOMString>. + Vector<String> disabled_features; + + // 7. Let disabledFeaturesIterable be ? Get(constructor, "disabledFeatures"). + auto disabled_features_iterable = TRY(constructor->callback->get(JS::PropertyKey { "disabledFeatures" })); + + // 8. If disabledFeaturesIterable is not undefined, then set disabledFeatures to the result of converting disabledFeaturesIterable to a sequence<DOMString>. Rethrow any exceptions from the conversion. + if (!disabled_features_iterable.is_undefined()) + disabled_features = TRY(convert_value_to_sequence_of_strings(vm, disabled_features_iterable)); + + // 9. Set disableInternals to true if disabledFeatures contains "internals". + disable_internals = disabled_features.contains_slow(TRY_OR_THROW_OOM(vm, "internals"_string)); + + // 10. Set disableShadow to true if disabledFeatures contains "shadow". + disable_shadow = disabled_features.contains_slow(TRY_OR_THROW_OOM(vm, "shadow"_string)); + + // 11. Let formAssociatedValue be ? Get( constructor, "formAssociated"). + auto form_associated_value = TRY(constructor->callback->get(JS::PropertyKey { "formAssociated" })); + + // 12. Set formAssociated to the result of converting formAssociatedValue to a boolean. Rethrow any exceptions from the conversion. + // NOTE: Converting to a boolean cannot throw with ECMAScript. + + // https://webidl.spec.whatwg.org/#es-boolean + // An ECMAScript value V is converted to an IDL boolean value by running the following algorithm: + // 1. Let x be the result of computing ToBoolean(V). + // 2. Return the IDL boolean value that is the one that represents the same truth value as the ECMAScript Boolean value x. + form_associated = form_associated_value.to_boolean(); + + // 13. If formAssociated is true, for each of "formAssociatedCallback", "formResetCallback", "formDisabledCallback", and "formStateRestoreCallback" callbackName: + if (form_associated) { + for (auto const& callback_name : { CustomElementReactionNames::formAssociatedCallback, CustomElementReactionNames::formResetCallback, CustomElementReactionNames::formDisabledCallback, CustomElementReactionNames::formStateRestoreCallback }) { + // 1. Let callbackValue be ? Get(prototype, callbackName). + auto callback_value = TRY(prototype.get(callback_name.to_deprecated_fly_string())); + + // 2. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL Function callback type. Rethrow any exceptions from the conversion. + if (!callback_value.is_undefined()) + lifecycle_callbacks.set(callback_name, JS::make_handle(TRY(convert_value_to_callback_function(vm, callback_value)))); + } + } + + return {}; + }; + + auto maybe_exception = get_definition_attributes_from_constructor(); + + // Then, perform the following substep, regardless of whether the above steps threw an exception or not: + // 1. Unset this CustomElementRegistry's element definition is running flag. + m_element_definition_is_running = false; + + // Finally, if the first set of substeps threw an exception, then rethrow that exception (thus terminating this algorithm). Otherwise, continue onward. + if (maybe_exception.is_throw_completion()) + return maybe_exception.release_error(); + + // 15. Let definition be a new custom element definition with name name, local name localName, constructor constructor, observed attributes observedAttributes, lifecycle callbacks lifecycleCallbacks, form-associated formAssociated, disable internals disableInternals, and disable shadow disableShadow. + auto definition = CustomElementDefinition::create(realm, name, local_name, *constructor, move(observed_attributes), move(lifecycle_callbacks), form_associated, disable_internals, disable_shadow); + + // 16. Add definition to this CustomElementRegistry. + m_custom_element_definitions.append(JS::make_handle(*definition)); + + // 17. Let document be this CustomElementRegistry's relevant global object's associated Document. + auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document(); + + // 18. Let upgrade candidates be all elements that are shadow-including descendants of document, whose namespace is the HTML namespace and whose local name is localName, in shadow-including tree order. + // Additionally, if extends is non-null, only include elements whose is value is equal to name. + Vector<JS::Handle<DOM::Element>> upgrade_candidates; + + document.for_each_shadow_including_descendant([&](DOM::Node& inclusive_descendant) { + if (!is<DOM::Element>(inclusive_descendant)) + return IterationDecision::Continue; + + auto& inclusive_descendant_element = static_cast<DOM::Element&>(inclusive_descendant); + + if (inclusive_descendant_element.namespace_() == Namespace::HTML && inclusive_descendant_element.local_name() == local_name.to_deprecated_string() && (!extends.has_value() || inclusive_descendant_element.is_value() == name)) + upgrade_candidates.append(JS::make_handle(inclusive_descendant_element)); + + return IterationDecision::Continue; + }); + + // 19. For each element element in upgrade candidates, enqueue a custom element upgrade reaction given element and definition. + for (auto& element : upgrade_candidates) + element->enqueue_a_custom_element_upgrade_reaction(definition); + + // 20. If this CustomElementRegistry's when-defined promise map contains an entry with key name: + auto promise_when_defined_iterator = m_when_defined_promise_map.find(name); + if (promise_when_defined_iterator != m_when_defined_promise_map.end()) { + // 1. Let promise be the value of that entry. + auto* promise = promise_when_defined_iterator->value.cell(); + + // 2. Resolve promise with constructor. + promise->fulfill(constructor->callback); + + // 3. Delete the entry with key name from this CustomElementRegistry's when-defined promise map. + m_when_defined_promise_map.remove(name); + } + + return {}; +} + +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-get +Variant<JS::Handle<WebIDL::CallbackType>, JS::Value> CustomElementRegistry::get(String const& name) const +{ + // 1. If this CustomElementRegistry contains an entry with name name, then return that entry's constructor. + auto existing_definition_iterator = m_custom_element_definitions.find_if([&name](JS::Handle<CustomElementDefinition> const& definition) { + return definition->name() == name; + }); + + if (!existing_definition_iterator.is_end()) + return JS::make_handle(existing_definition_iterator->cell()->constructor()); + + // 2. Otherwise, return undefined. + return JS::js_undefined(); +} + +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-whendefined +WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> CustomElementRegistry::when_defined(String const& name) +{ + auto& realm = this->realm(); + + // 1. If name is not a valid custom element name, then return a new promise rejected with a "SyntaxError" DOMException. + if (!is_valid_custom_element_name(name)) { + auto promise = JS::Promise::create(realm); + promise->reject(WebIDL::SyntaxError::create(realm, DeprecatedString::formatted("'{}' is not a valid custom element name"sv, name))); + return promise; + } + + // 2. If this CustomElementRegistry contains an entry with name name, then return a new promise resolved with that entry's constructor. + auto existing_definition_iterator = m_custom_element_definitions.find_if([&name](JS::Handle<CustomElementDefinition> const& definition) { + return definition->name() == name; + }); + + if (existing_definition_iterator != m_custom_element_definitions.end()) { + auto promise = JS::Promise::create(realm); + promise->fulfill(existing_definition_iterator->cell()->constructor().callback); + return promise; + } + + // 3. Let map be this CustomElementRegistry's when-defined promise map. + // NOTE: Not necessary. + + // 4. If map does not contain an entry with key name, create an entry in map with key name and whose value is a new promise. + // 5. Let promise be the value of the entry in map with key name. + JS::GCPtr<JS::Promise> promise; + + auto existing_promise_iterator = m_when_defined_promise_map.find(name); + if (existing_promise_iterator != m_when_defined_promise_map.end()) { + promise = existing_promise_iterator->value.cell(); + } else { + promise = JS::Promise::create(realm); + m_when_defined_promise_map.set(name, JS::make_handle(promise)); + } + + // 5. Return promise. + VERIFY(promise); + return JS::NonnullGCPtr { *promise }; +} + +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-upgrade +void CustomElementRegistry::upgrade(JS::NonnullGCPtr<DOM::Node> root) const +{ + // 1. Let candidates be a list of all of root's shadow-including inclusive descendant elements, in shadow-including tree order. + Vector<JS::Handle<DOM::Element>> candidates; + + root->for_each_shadow_including_inclusive_descendant([&](DOM::Node& inclusive_descendant) { + if (!is<DOM::Element>(inclusive_descendant)) + return IterationDecision::Continue; + + auto& inclusive_descendant_element = static_cast<DOM::Element&>(inclusive_descendant); + candidates.append(JS::make_handle(inclusive_descendant_element)); + + return IterationDecision::Continue; + }); + + // 2. For each candidate of candidates, try to upgrade candidate. + for (auto& candidate : candidates) + candidate->try_to_upgrade(); +} + +JS::GCPtr<CustomElementDefinition> CustomElementRegistry::get_definition_with_name_and_local_name(String const& name, String const& local_name) const +{ + auto definition_iterator = m_custom_element_definitions.find_if([&](JS::Handle<CustomElementDefinition> const& definition) { + return definition->name() == name && definition->local_name() == local_name; + }); + + return definition_iterator.is_end() ? nullptr : definition_iterator->ptr(); +} + +JS::GCPtr<CustomElementDefinition> CustomElementRegistry::get_definition_from_new_target(JS::FunctionObject const& new_target) const +{ + auto definition_iterator = m_custom_element_definitions.find_if([&](JS::Handle<CustomElementDefinition> const& definition) { + return definition->constructor().callback.ptr() == &new_target; + }); + + return definition_iterator.is_end() ? nullptr : definition_iterator->ptr(); +} + +} diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.h b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.h new file mode 100644 index 0000000000..9fb9c1d621 --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/RefCounted.h> +#include <LibWeb/Bindings/PlatformObject.h> +#include <LibWeb/HTML/CustomElements/CustomElementDefinition.h> + +namespace Web::HTML { + +struct ElementDefinitionOptions { + Optional<String> extends; +}; + +// https://html.spec.whatwg.org/multipage/custom-elements.html#customelementregistry +class CustomElementRegistry : public Bindings::PlatformObject { + WEB_PLATFORM_OBJECT(CustomElementRegistry, Bindings::PlatformObject); + +public: + virtual ~CustomElementRegistry() override; + + JS::ThrowCompletionOr<void> define(String const& name, WebIDL::CallbackType* constructor, ElementDefinitionOptions options); + Variant<JS::Handle<WebIDL::CallbackType>, JS::Value> get(String const& name) const; + WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> when_defined(String const& name); + void upgrade(JS::NonnullGCPtr<DOM::Node> root) const; + + JS::GCPtr<CustomElementDefinition> get_definition_with_name_and_local_name(String const& name, String const& local_name) const; + JS::GCPtr<CustomElementDefinition> get_definition_from_new_target(JS::FunctionObject const& new_target) const; + +private: + CustomElementRegistry(JS::Realm&); + + virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override; + + // Every CustomElementRegistry has a set of custom element definitions, initially empty. In general, algorithms in this specification look up elements in the registry by any of name, local name, or constructor. + Vector<JS::Handle<CustomElementDefinition>> m_custom_element_definitions; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#element-definition-is-running + // Every CustomElementRegistry also has an element definition is running flag which is used to prevent reentrant invocations of element definition. It is initially unset. + bool m_element_definition_is_running { false }; + + // https://html.spec.whatwg.org/multipage/custom-elements.html#when-defined-promise-map + // Every CustomElementRegistry also has a when-defined promise map, mapping valid custom element names to promises. It is used to implement the whenDefined() method. + OrderedHashMap<String, JS::Handle<JS::Promise>> m_when_defined_promise_map; +}; + +} diff --git a/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl new file mode 100644 index 0000000000..d4e8ade4ce --- /dev/null +++ b/Userland/Libraries/LibWeb/HTML/CustomElements/CustomElementRegistry.idl @@ -0,0 +1,15 @@ +#import <DOM/Node.idl> + +[Exposed=Window, UseNewAKString] +interface CustomElementRegistry { + [CEReactions] undefined define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options = {}); + (CustomElementConstructor or undefined) get(DOMString name); + Promise<CustomElementConstructor> whenDefined(DOMString name); + [CEReactions] undefined upgrade(Node root); +}; + +callback CustomElementConstructor = HTMLElement (); + +dictionary ElementDefinitionOptions { + DOMString extends; +}; diff --git a/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp index 00ff9cb2bb..2da21fb220 100644 --- a/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp +++ b/Userland/Libraries/LibWeb/HTML/HTMLInputElement.cpp @@ -8,6 +8,7 @@ #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h> #include <LibWeb/DOM/Document.h> +#include <LibWeb/DOM/ElementFactory.h> #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/ShadowRoot.h> #include <LibWeb/DOM/Text.h> @@ -21,6 +22,7 @@ #include <LibWeb/Layout/ButtonBox.h> #include <LibWeb/Layout/CheckBox.h> #include <LibWeb/Layout/RadioButton.h> +#include <LibWeb/Namespace.h> #include <LibWeb/WebIDL/DOMException.h> #include <LibWeb/WebIDL/ExceptionOr.h> @@ -408,7 +410,7 @@ void HTMLInputElement::create_shadow_tree_if_needed() auto initial_value = m_value; if (initial_value.is_null()) initial_value = DeprecatedString::empty(); - auto element = document().create_element(HTML::TagNames::div).release_value(); + auto element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors(); MUST(element->set_attribute(HTML::AttributeNames::style, "white-space: pre; padding-top: 1px; padding-bottom: 1px; padding-left: 2px; padding-right: 2px; height: 1lh;")); m_text_node = heap().allocate<DOM::Text>(realm(), document(), initial_value).release_allocated_value_but_fixme_should_propagate_errors(); m_text_node->set_always_editable(m_type != TypeAttributeState::FileUpload); diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp index ae94d43a08..fccbd1f256 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp @@ -19,6 +19,7 @@ #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/ProcessingInstruction.h> #include <LibWeb/DOM/Text.h> +#include <LibWeb/HTML/CustomElements/CustomElementDefinition.h> #include <LibWeb/HTML/EventLoop/EventLoop.h> #include <LibWeb/HTML/EventNames.h> #include <LibWeb/HTML/HTMLFormElement.h> @@ -629,18 +630,36 @@ JS::NonnullGCPtr<DOM::Element> HTMLParser::create_element_for(HTMLToken const& t // 4. Let local name be the tag name of the token. auto local_name = token.tag_name(); - // FIXME: 5. Let is be the value of the "is" attribute in the given token, if such an attribute exists, or null otherwise. - // FIXME: 6. Let definition be the result of looking up a custom element definition given document, given namespace, local name, and is. - // FIXME: 7. If definition is non-null and the parser was not created as part of the HTML fragment parsing algorithm, then let will execute script be true. Otherwise, let it be false. - // FIXME: 8. If will execute script is true, then: - // FIXME: 1. Increment document's throw-on-dynamic-markup-insertion counter. - // FIXME: 2. If the JavaScript execution context stack is empty, then perform a microtask checkpoint. - // FIXME: 3. Push a new element queue onto document's relevant agent's custom element reactions stack. + // 5. Let is be the value of the "is" attribute in the given token, if such an attribute exists, or null otherwise. + auto is_value_deprecated_string = token.attribute(AttributeNames::is); + Optional<String> is_value; + if (!is_value_deprecated_string.is_null()) + is_value = String::from_utf8(is_value_deprecated_string).release_value_but_fixme_should_propagate_errors(); + + // 6. Let definition be the result of looking up a custom element definition given document, given namespace, local name, and is. + auto definition = document->lookup_custom_element_definition(namespace_, local_name, is_value); + + // 7. If definition is non-null and the parser was not created as part of the HTML fragment parsing algorithm, then let will execute script be true. Otherwise, let it be false. + bool will_execute_script = definition && !m_parsing_fragment; + + // 8. If will execute script is true, then: + if (will_execute_script) { + // 1. Increment document's throw-on-dynamic-markup-insertion counter. + document->increment_throw_on_dynamic_markup_insertion_counter({}); + + // 2. If the JavaScript execution context stack is empty, then perform a microtask checkpoint. + auto& vm = main_thread_event_loop().vm(); + if (vm.execution_context_stack().is_empty()) + perform_a_microtask_checkpoint(); + + // 3. Push a new element queue onto document's relevant agent's custom element reactions stack. + auto& custom_data = verify_cast<Bindings::WebEngineCustomData>(*vm.custom_data()); + custom_data.custom_element_reactions_stack.element_queue_stack.append({}); + } // 9. Let element be the result of creating an element given document, localName, given namespace, null, and is. - // FIXME: If will execute script is true, set the synchronous custom elements flag; otherwise, leave it unset. - // FIXME: Pass in `null` and `is`. - auto element = create_element(*document, local_name, namespace_).release_value_but_fixme_should_propagate_errors(); + // If will execute script is true, set the synchronous custom elements flag; otherwise, leave it unset. + auto element = create_element(*document, local_name, namespace_, {}, is_value, will_execute_script).release_value_but_fixme_should_propagate_errors(); // 10. Append each attribute in the given token to element. // FIXME: This isn't the exact `append` the spec is talking about. @@ -649,10 +668,19 @@ JS::NonnullGCPtr<DOM::Element> HTMLParser::create_element_for(HTMLToken const& t return IterationDecision::Continue; }); - // FIXME: 11. If will execute script is true, then: - // FIXME: 1. Let queue be the result of popping from document's relevant agent's custom element reactions stack. (This will be the same element queue as was pushed above.) - // FIXME: 2. Invoke custom element reactions in queue. - // FIXME: 3. Decrement document's throw-on-dynamic-markup-insertion counter. + // 11. If will execute script is true, then: + if (will_execute_script) { + // 1. Let queue be the result of popping from document's relevant agent's custom element reactions stack. (This will be the same element queue as was pushed above.) + auto& vm = main_thread_event_loop().vm(); + auto& custom_data = verify_cast<Bindings::WebEngineCustomData>(*vm.custom_data()); + auto queue = custom_data.custom_element_reactions_stack.element_queue_stack.take_last(); + + // 2. Invoke custom element reactions in queue. + Bindings::invoke_custom_element_reactions(queue); + + // 3. Decrement document's throw-on-dynamic-markup-insertion counter. + document->decrement_throw_on_dynamic_markup_insertion_counter({}); + } // FIXME: 12. If element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element's namespace, that is a parse error. // Similarly, if element has an xmlns:xlink attribute in the XMLNS namespace whose value is not the XLink Namespace, that is a parse error. @@ -694,14 +722,22 @@ JS::NonnullGCPtr<DOM::Element> HTMLParser::insert_foreign_element(HTMLToken cons // NOTE: If it's not possible to insert the element at the adjusted insertion location, the element is simply dropped. if (!pre_insertion_validity.is_exception()) { + // 1. If the parser was not created as part of the HTML fragment parsing algorithm, then push a new element queue onto element's relevant agent's custom element reactions stack. if (!m_parsing_fragment) { - // FIXME: push a new element queue onto element's relevant agent's custom element reactions stack. + auto& vm = main_thread_event_loop().vm(); + auto& custom_data = verify_cast<Bindings::WebEngineCustomData>(*vm.custom_data()); + custom_data.custom_element_reactions_stack.element_queue_stack.append({}); } + // 2. Insert element at the adjusted insertion location. adjusted_insertion_location.parent->insert_before(*element, adjusted_insertion_location.insert_before_sibling); + // 3. If the parser was not created as part of the HTML fragment parsing algorithm, then pop the element queue from element's relevant agent's custom element reactions stack, and invoke custom element reactions in that queue. if (!m_parsing_fragment) { - // FIXME: pop the element queue from element's relevant agent's custom element reactions stack, and invoke custom element reactions in that queue. + auto& vm = main_thread_event_loop().vm(); + auto& custom_data = verify_cast<Bindings::WebEngineCustomData>(*vm.custom_data()); + auto queue = custom_data.custom_element_reactions_stack.element_queue_stack.take_last(); + Bindings::invoke_custom_element_reactions(queue); } } @@ -2269,6 +2305,12 @@ void HTMLParser::handle_text(HTMLToken& token) // Non-standard: Make sure the <script> element has up-to-date text content before preparing the script. flush_character_insertions(); + // If the active speculative HTML parser is null and the JavaScript execution context stack is empty, then perform a microtask checkpoint. + // FIXME: If the active speculative HTML parser is null + auto& vm = main_thread_event_loop().vm(); + if (vm.execution_context_stack().is_empty()) + perform_a_microtask_checkpoint(); + // Let script be the current node (which will be a script element). JS::NonnullGCPtr<HTMLScriptElement> script = verify_cast<HTMLScriptElement>(current_node()); @@ -3634,9 +3676,14 @@ DeprecatedString HTMLParser::serialize_html_fragment(DOM::Node const& node) builder.append('<'); builder.append(tag_name); - // FIXME: 3. If current node's is value is not null, and the element does not have an is attribute in its attribute list, - // then append the string " is="", followed by current node's is value escaped as described below in attribute mode, - // followed by a U+0022 QUOTATION MARK character ("). + // 3. If current node's is value is not null, and the element does not have an is attribute in its attribute list, + // then append the string " is="", followed by current node's is value escaped as described below in attribute mode, + // followed by a U+0022 QUOTATION MARK character ("). + if (element.is_value().has_value() && !element.has_attribute(AttributeNames::is)) { + builder.append(" is=\""sv); + builder.append(escape_string(element.is_value().value(), AttributeMode::Yes)); + builder.append('"'); + } // 4. For each attribute that the element has, append a U+0020 SPACE character, the attribute's serialized name as described below, a U+003D EQUALS SIGN character (=), // a U+0022 QUOTATION MARK character ("), the attribute's value, escaped as described below in attribute mode, and a second U+0022 QUOTATION MARK character ("). diff --git a/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h b/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h index c49d98ab65..bfc32c8c4a 100644 --- a/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h +++ b/Userland/Libraries/LibWeb/HTML/Parser/HTMLToken.h @@ -247,7 +247,7 @@ public: } } - StringView attribute(DeprecatedFlyString const& attribute_name) + StringView attribute(DeprecatedFlyString const& attribute_name) const { VERIFY(is_start_tag() || is_end_tag()); diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp index 605ffb8f27..a5a3d41bf6 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp +++ b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp @@ -435,6 +435,13 @@ JS::Object& entry_global_object() return entry_realm().global_object(); } +JS::VM& relevant_agent(JS::Object const& object) +{ + // The relevant agent for a platform object platformObject is platformObject's relevant Realm's agent. + // Spec Note: This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357. + return relevant_realm(object).vm(); +} + // https://html.spec.whatwg.org/multipage/webappapis.html#secure-context bool is_secure_context(Environment const& environment) { diff --git a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h index 3bccf5ef08..d2a7bec305 100644 --- a/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h +++ b/Userland/Libraries/LibWeb/HTML/Scripting/Environments.h @@ -148,6 +148,7 @@ JS::Object& relevant_global_object(JS::Object const&); JS::Realm& entry_realm(); EnvironmentSettingsObject& entry_settings_object(); JS::Object& entry_global_object(); +JS::VM& relevant_agent(JS::Object const&); [[nodiscard]] bool is_secure_context(Environment const&); [[nodiscard]] bool is_non_secure_context(Environment const&); diff --git a/Userland/Libraries/LibWeb/HTML/TagNames.h b/Userland/Libraries/LibWeb/HTML/TagNames.h index eb0efb7604..82726734b0 100644 --- a/Userland/Libraries/LibWeb/HTML/TagNames.h +++ b/Userland/Libraries/LibWeb/HTML/TagNames.h @@ -78,6 +78,7 @@ namespace Web::HTML::TagNames { __ENUMERATE_HTML_TAG(img) \ __ENUMERATE_HTML_TAG(input) \ __ENUMERATE_HTML_TAG(ins) \ + __ENUMERATE_HTML_TAG(isindex) \ __ENUMERATE_HTML_TAG(kbd) \ __ENUMERATE_HTML_TAG(keygen) \ __ENUMERATE_HTML_TAG(label) \ @@ -94,7 +95,9 @@ namespace Web::HTML::TagNames { __ENUMERATE_HTML_TAG(menuitem) \ __ENUMERATE_HTML_TAG(meta) \ __ENUMERATE_HTML_TAG(meter) \ + __ENUMERATE_HTML_TAG(multicol) \ __ENUMERATE_HTML_TAG(nav) \ + __ENUMERATE_HTML_TAG(nextid) \ __ENUMERATE_HTML_TAG(nobr) \ __ENUMERATE_HTML_TAG(noembed) \ __ENUMERATE_HTML_TAG(noframes) \ @@ -126,6 +129,7 @@ namespace Web::HTML::TagNames { __ENUMERATE_HTML_TAG(small) \ __ENUMERATE_HTML_TAG(source) \ __ENUMERATE_HTML_TAG(span) \ + __ENUMERATE_HTML_TAG(spacer) \ __ENUMERATE_HTML_TAG(strike) \ __ENUMERATE_HTML_TAG(strong) \ __ENUMERATE_HTML_TAG(style) \ diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp index fe7a8041a9..e3f821056e 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.cpp +++ b/Userland/Libraries/LibWeb/HTML/Window.cpp @@ -32,6 +32,7 @@ #include <LibWeb/DOM/EventDispatcher.h> #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h> #include <LibWeb/HTML/BrowsingContext.h> +#include <LibWeb/HTML/CustomElements/CustomElementRegistry.h> #include <LibWeb/HTML/EventHandler.h> #include <LibWeb/HTML/EventLoop/EventLoop.h> #include <LibWeb/HTML/Focus.h> @@ -104,6 +105,7 @@ void Window::visit_edges(JS::Cell::Visitor& visitor) visitor.visit(m_location); visitor.visit(m_crypto); visitor.visit(m_navigator); + visitor.visit(m_custom_element_registry); for (auto& plugin_object : m_pdf_viewer_plugin_objects) visitor.visit(plugin_object); for (auto& mime_type_object : m_pdf_viewer_mime_type_objects) @@ -1325,6 +1327,17 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<Crypto::Crypto>> Window::crypto() return JS::NonnullGCPtr { *m_crypto }; } +// https://html.spec.whatwg.org/multipage/custom-elements.html#dom-window-customelements +WebIDL::ExceptionOr<JS::NonnullGCPtr<CustomElementRegistry>> Window::custom_elements() +{ + auto& realm = this->realm(); + + // The customElements attribute of the Window interface must return the CustomElementRegistry object for that Window object. + if (!m_custom_element_registry) + m_custom_element_registry = MUST_OR_THROW_OOM(heap().allocate<CustomElementRegistry>(realm, realm)); + return JS::NonnullGCPtr { *m_custom_element_registry }; +} + // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts size_t Window::document_tree_child_browsing_context_count() const { diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h index 96f6599826..25195868d5 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.h +++ b/Userland/Libraries/LibWeb/HTML/Window.h @@ -186,6 +186,8 @@ public: WebIDL::ExceptionOr<JS::NonnullGCPtr<Crypto::Crypto>> crypto(); + WebIDL::ExceptionOr<JS::NonnullGCPtr<CustomElementRegistry>> custom_elements(); + private: explicit Window(JS::Realm&); @@ -216,6 +218,10 @@ private: JS::GCPtr<Navigator> m_navigator; JS::GCPtr<Location> m_location; + // https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-api + // Each Window object is associated with a unique instance of a CustomElementRegistry object, allocated when the Window object is created. + JS::GCPtr<CustomElementRegistry> m_custom_element_registry; + AnimationFrameCallbackDriver m_animation_frame_callback_driver; // https://w3c.github.io/requestidlecallback/#dfn-list-of-idle-request-callbacks diff --git a/Userland/Libraries/LibWeb/HTML/Window.idl b/Userland/Libraries/LibWeb/HTML/Window.idl index c605544a9e..5537e5b6ef 100644 --- a/Userland/Libraries/LibWeb/HTML/Window.idl +++ b/Userland/Libraries/LibWeb/HTML/Window.idl @@ -6,6 +6,7 @@ #import <DOM/EventTarget.idl> #import <HighResolutionTime/Performance.idl> #import <HTML/AnimationFrameProvider.idl> +#import <HTML/CustomElements/CustomElementRegistry.idl> #import <HTML/Navigator.idl> #import <HTML/WindowLocalStorage.idl> #import <HTML/WindowOrWorkerGlobalScope.idl> @@ -22,6 +23,7 @@ interface Window : EventTarget { attribute DOMString name; [PutForwards=href, LegacyUnforgeable] readonly attribute Location location; readonly attribute History history; + readonly attribute CustomElementRegistry customElements; undefined focus(); // other browsing contexts |