Truly independent web browser
LibWeb: Implement DOMTokenList in Rust
Shannon Booth530d96e29b74
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 60056cdf410..5e80779578c 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -98,6 +98,8 @@ pub use crate::runtime::typed_array::{typed_array_byte_length, typed_array_length,};pub use crate::runtime::value::{number_to_string, same_value};-pub use crate::utf16::{Utf16Display, Utf16View, to_well_formed, utf16_formatted};+pub use crate::utf16::{+ Utf16Display, Utf16StringBuilder, Utf16View, to_well_formed, utf16_formatted, utf16_string_external_memory_size,+};/// Derives Trace for a type of the embedder, which marks the type `#[gc(crate = libjs_rust)]`.pub use libjs_runtime_macros::Trace;diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/dom_token_list.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/dom_token_list.rsnew file mode 100644index 00000000000..f525d440deb--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/dom_token_list.rs@@ -0,0 +1,503 @@+/*+ * Copyright (c) 2021, Tim Flynn <[email protected]>+ * Copyright (c) 2022, Andreas Kling <[email protected]>+ * Copyright (c) 2023, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://dom.spec.whatwg.org/#interface-domtokenlist++use core::cell::{Cell, RefCell};+use core::ffi::c_void;++use ak::{Utf16FlyString, Utf16String};+use libjs_rust::api::{Trace, Utf16StringBuilder, Utf16View, Vm, utf16_string_external_memory_size};+use libwebcommon_rust::infra::character_types::is_ascii_whitespace;++use crate::bindings::interface::{Wrappable, allocate, cell_from_abi, cell_into_abi};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::dom::element::CppElement;++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMTokenList {+ associated_element: CppElement,+ associated_attribute: Utf16FlyString,+ #[gc(untraced)]+ token_set: RefCell<Vec<Utf16String>>,+ is_running_update_steps: Cell<bool>,+}++impl Wrappable for DOMTokenList {+ const OWNS_EXTERNAL_MEMORY: bool = true;++ fn external_memory_size(&self) -> usize {+ let token_set = self.token_set.borrow();+ token_set+ .iter()+ .fold(token_set.capacity() * size_of::<Utf16String>(), |size, token| {+ size.saturating_add(utf16_string_external_memory_size(token))+ })+ }+}++impl DOMTokenList {+ // https://dom.spec.whatwg.org/#ref-for-domtokenlist%E2%91%A0%E2%91%A2+ fn new(associated_element: CppElement, associated_attribute: Utf16FlyString, value: Option<Utf16String>) -> Self {+ let list = Self {+ associated_element,+ associated_attribute,+ token_set: RefCell::new(Vec::new()),+ is_running_update_steps: Cell::new(false),+ };++ // When a DOMTokenList object set is created:+ // 1. Let element be set’s element.+ // 2. Let attributeName be set’s attribute name.+ // 3. Let value be the result of getting an attribute value given element and attributeName.+ // NB: The caller gets the attribute value.+ // 4. Run the attribute change steps for element, attributeName, value, value, and null.+ list.associated_attribute_changed(value);+ list+ }++ // https://dom.spec.whatwg.org/#ref-for-domtokenlist%E2%91%A0%E2%91%A1+ fn associated_attribute_changed(&self, value: Option<Utf16String>) {+ // 1. If localName is set’s attribute name, namespace is null, and value is null, then empty token set.+ // 2. Otherwise, if localName is set’s attribute name and namespace is null, then set set’s token set to value,+ // parsed.+ // AD-HOC: The caller is responsible for checking the name and namespace.+ // OPTIMIZATION: The update steps just wrote this value from the token set, so there is nothing new to parse.+ if self.is_running_update_steps.get() {+ return;+ }+ let mut token_set = self.token_set.borrow_mut();+ *token_set = Vec::new();+ let Some(value) = value else {+ return;+ };+ *token_set = parse_ordered_set(Utf16View::of_string(&value));+ }++ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(u32::try_from(self.token_set.borrow().len()).expect("a token list has fewer than 2^32 tokens"))+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-item+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Utf16String>> {+ let token_set = self.token_set.borrow();+ let index = index as usize;++ // 1. If index is equal to or greater than this’s token set’s size, then return null.+ if index >= token_set.len() {+ return Ok(None);+ }++ // 2. Return this’s token set[index].+ Ok(Some(token_set[index].clone()))+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-contains+ pub(crate) fn contains(&self, _: &mut CallContext, token: Utf16String) -> WebIdlResult<bool> {+ Ok(self.token_set.borrow().contains(&token))+ }++ pub(crate) fn add(&self, _: &mut CallContext, tokens: Vec<Utf16String>) -> WebIdlResult<()> {+ self.add_tokens(tokens)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-add+ fn add_tokens(&self, tokens: impl IntoIterator<Item = Utf16String>) -> WebIdlResult<()> {+ // 1. For each token of tokens:+ for token in tokens {+ // a. If token is the empty string, then throw a "SyntaxError" DOMException.+ // b. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.+ validate_token(&token)?;++ // 2. For each token of tokens: append token to this’s token set.+ append_to_ordered_set(&mut self.token_set.borrow_mut(), Utf16View::of_string(&token));+ }++ // 3. Run the update steps.+ self.run_update_steps();+ Ok(())+ }++ pub(crate) fn remove(&self, _: &mut CallContext, tokens: Vec<Utf16String>) -> WebIdlResult<()> {+ self.remove_tokens(tokens)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-remove+ fn remove_tokens(&self, tokens: impl IntoIterator<Item = Utf16String>) -> WebIdlResult<()> {+ // 1. For each token of tokens:+ for token in tokens {+ // a. If token is the empty string, then throw a "SyntaxError" DOMException.+ // b. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.+ validate_token(&token)?;++ // 2. For each token of tokens: remove token from this’s token set.+ remove_from_ordered_set(&mut self.token_set.borrow_mut(), Utf16View::of_string(&token));+ }++ // 3. Run the update steps.+ self.run_update_steps();+ Ok(())+ }++ pub(crate) fn toggle(&self, _: &mut CallContext, token: Utf16String, force: Option<bool>) -> WebIdlResult<bool> {+ self.toggle_token(token, force)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle+ fn toggle_token(&self, token: Utf16String, force: Option<bool>) -> WebIdlResult<bool> {+ // 1. If token is the empty string, then throw a "SyntaxError" DOMException.+ // 2. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.+ validate_token(&token)?;++ // 3. If this’s token set[token] exists:+ if self.token_set.borrow().contains(&token) {+ // a. If force is either not given or is false, then remove token from this’s token set, run the update steps and return false.+ if force != Some(true) {+ remove_from_ordered_set(&mut self.token_set.borrow_mut(), Utf16View::of_string(&token));+ self.run_update_steps();+ return Ok(false);+ }++ // b. Return true.+ return Ok(true);+ }++ // 4. Otherwise, if force not given or is true, append token to this’s token set, run the update steps, and return true.+ if force != Some(false) {+ append_to_ordered_set(&mut self.token_set.borrow_mut(), Utf16View::of_string(&token));+ self.run_update_steps();+ return Ok(true);+ }++ // 5. Return false.+ Ok(false)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-replace+ pub(crate) fn replace(+ &self,+ _: &mut CallContext,+ token: Utf16String,+ new_token: Utf16String,+ ) -> WebIdlResult<bool> {+ // 1. If either token or newToken is the empty string, then throw a "SyntaxError" DOMException.+ validate_token_not_empty(&token)?;+ validate_token_not_empty(&new_token)?;++ // 2. If either token or newToken contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.+ validate_token_not_whitespace(&token)?;+ validate_token_not_whitespace(&new_token)?;++ // 3. If this’s token set does not contain token, then return false.+ if !self.token_set.borrow().contains(&token) {+ return Ok(false);+ }++ // 4. Replace token in this’s token set with newToken.+ replace_in_ordered_set(+ &mut self.token_set.borrow_mut(),+ Utf16View::of_string(&token),+ Utf16View::of_string(&new_token),+ );++ // 5. Run the update steps.+ self.run_update_steps();++ // 6. Return true.+ Ok(true)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-supports+ pub(crate) fn supports(&self, _: &mut CallContext, token: Utf16String) -> WebIdlResult<bool> {+ // 1. Let result be the return value of validation steps called with token.+ // 2. Return result.+ self.run_validation_steps(Utf16View::of_string(&token))+ }++ // https://dom.spec.whatwg.org/#concept-domtokenlist-validation+ fn run_validation_steps(&self, token: Utf16View<'_>) -> WebIdlResult<bool> {+ let name = self.associated_element.local_name();+ let name = Utf16View::of_fly_string(&name);+ let attribute = Utf16View::of_fly_string(&self.associated_attribute);+ let supported_tokens: Option<&[&[u8]]> = match (name, attribute) {+ // https://html.spec.whatwg.org/multipage/links.html#linkTypes+ (name, attribute) if name == "link" && attribute == "rel" => Some(&[+ b"modulepreload",+ b"preload",+ b"preconnect",+ b"dns-prefetch",+ b"stylesheet",+ b"icon",+ b"alternate",+ b"prefetch",+ b"prerender",+ b"next",+ b"manifest",+ b"apple-touch-icon",+ b"apple-touch-icon-precomposed",+ b"canonical",+ ]),+ (name, attribute) if attribute == "rel" && (name == "a" || name == "area" || name == "form") => {+ Some(&[b"noreferrer", b"noopener", b"opener"])+ }++ // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#blocking-attribute+ (name, attribute) if attribute == "blocking" && (name == "link" || name == "script" || name == "style") => {+ Some(&[b"render"])+ }++ // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox+ (name, attribute) if name == "iframe" && attribute == "sandbox" => Some(&[+ b"allow-downloads",+ b"allow-forms",+ b"allow-modals",+ b"allow-orientation-lock",+ b"allow-pointer-lock",+ b"allow-popups",+ b"allow-popups-to-escape-sandbox",+ b"allow-presentation",+ b"allow-same-origin",+ b"allow-scripts",+ b"allow-top-navigation",+ b"allow-top-navigation-by-user-activation",+ b"allow-top-navigation-to-custom-protocols",+ ]),+ _ => None,+ };++ // 1. If set’s element and attribute name does not define supported tokens, then throw a TypeError.+ let Some(supported_tokens) = supported_tokens else {+ let mut message = Utf16StringBuilder::new();+ message.append_ascii("Attribute ");+ message.append(attribute);+ message.append_ascii(" does not define any supported tokens");+ return Err(Exception::TypeError(message.to_utf16_string()));+ };++ // 2. Let lowercaseToken be token, in ASCII lowercase.+ // 3. If lowercaseToken is present in the supported tokens of set’s element and attribute name, then return true.+ if supported_tokens+ .iter()+ .any(|supported| token.equals_ignoring_ascii_case(Utf16View::Ascii(supported)))+ {+ return Ok(true);+ }++ // 4. Return false.+ Ok(false)+ }++ // https://dom.spec.whatwg.org/#dom-domtokenlist-value+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self+ .associated_element+ .get_attribute_ns(None, &self.associated_attribute)+ .unwrap_or_default())+ }++ // https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-set-value%E2%91%A2+ pub(crate) fn set_value(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {+ self.associated_element+ .set_attribute_value(&self.associated_attribute, value);+ Ok(())+ }++ // https://dom.spec.whatwg.org/#concept-dtl-update+ fn run_update_steps(&self) {+ // 1. If get an attribute by namespace and local name given null, set’s attribute name, and set’s element returns null and set’s token set is empty, then return.+ let attribute = self+ .associated_element+ .get_attribute_ns(None, &self.associated_attribute);+ if attribute.is_none() && self.token_set.borrow().is_empty() {+ return;+ }++ // 2. Set an attribute value given set’s element, set’s attribute name, and the result of running the ordered set+ // serializer for set’s token set.+ let serialized = serialize_ordered_set(&self.token_set.borrow());+ let was_running_update_steps = self.is_running_update_steps.replace(true);+ self.associated_element+ .set_attribute_value(&self.associated_attribute, serialized);+ self.is_running_update_steps.set(was_running_update_steps);+ }+}++fn validate_token(token: &Utf16String) -> WebIdlResult<()> {+ validate_token_not_empty(token)?;+ validate_token_not_whitespace(token)+}++fn validate_token_not_empty(token: &Utf16String) -> WebIdlResult<()> {+ if token.is_empty() {+ return Err(Exception::syntax_error(Utf16String::from_utf8(+ "Non-empty DOM tokens are not allowed",+ )));+ }+ Ok(())+}++fn validate_token_not_whitespace(token: &Utf16String) -> WebIdlResult<()> {+ if Utf16View::of_string(token)+ .code_units()+ .any(|unit| is_ascii_whitespace(u32::from(unit)))+ {+ return Err(Exception::Dom(+ "InvalidCharacterError",+ Utf16String::from_utf8("DOM tokens containing ASCII whitespace are not allowed"),+ ));+ }+ Ok(())+}++// https://infra.spec.whatwg.org/#set-append+fn append_to_ordered_set(set: &mut Vec<Utf16String>, item: Utf16View<'_>) {+ if !set.iter().any(|value| Utf16View::of_string(value) == item) {+ set.push(item.to_utf16_string());+ }+}++// https://infra.spec.whatwg.org/#list-remove+fn remove_from_ordered_set(set: &mut Vec<Utf16String>, item: Utf16View<'_>) {+ if let Some(index) = set.iter().position(|value| Utf16View::of_string(value) == item) {+ set.remove(index);+ }+}++// https://infra.spec.whatwg.org/#set-replace+fn replace_in_ordered_set(set: &mut Vec<Utf16String>, item: Utf16View<'_>, replacement: Utf16View<'_>) {+ let item_index = set+ .iter()+ .position(|value| Utf16View::of_string(value) == item)+ .expect("the set contains the item");++ let Some(replacement_index) = set.iter().position(|value| Utf16View::of_string(value) == replacement) else {+ set[item_index] = replacement.to_utf16_string();+ return;+ };++ if item_index == replacement_index {+ return;+ }++ if replacement_index < item_index {+ set.remove(item_index);+ return;+ }++ set[item_index] = set.remove(replacement_index);+}++// https://dom.spec.whatwg.org/#concept-ordered-set-parser+fn parse_ordered_set(input: Utf16View<'_>) -> Vec<Utf16String> {+ // 1. Let inputTokens be the result of splitting input on ASCII whitespace.+ // 2. Let tokens be a new ordered set.+ let mut tokens = Vec::new();++ // 3. For each token of inputTokens: append token to tokens.+ let mut token_start = None;+ for (index, unit) in input.code_units().enumerate() {+ if is_ascii_whitespace(u32::from(unit)) {+ if let Some(start) = token_start.take() {+ append_to_ordered_set(&mut tokens, input.substring_view(start, index - start));+ }+ continue;+ }++ if token_start.is_none() {+ token_start = Some(index);+ }+ }+ if let Some(start) = token_start {+ append_to_ordered_set(+ &mut tokens,+ input.substring_view(start, input.length_in_code_units() - start),+ );+ }++ // 4. Return tokens.+ tokens+}++// https://dom.spec.whatwg.org/#concept-ordered-set-serializer+fn serialize_ordered_set(token_set: &[Utf16String]) -> Utf16String {+ // The ordered set serializer takes a set and returns the concatenation of set using U+0020 SPACE.+ let mut builder = Utf16StringBuilder::new();+ for token in token_set {+ if !builder.is_empty() {+ builder.append_ascii(" ");+ }+ builder.append(Utf16View::of_string(token));+ }+ builder.to_utf16_string()+}++/// # Safety+///+/// The caller passes a live VM and Element, lends the interned attribute name, and transfers ownership+/// of the initial attribute value if it is nonzero.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_token_list_create(+ vm: &Vm,+ element: *mut c_void,+ attribute: usize,+ value: usize,+) -> *mut c_void {+ // SAFETY: The caller passes a live Element and a live, borrowed attribute name.+ let (element, attribute) = unsafe {+ (+ CppElement::from_raw(element),+ Utf16FlyString::from_raw_borrowed(attribute),+ )+ };+ // SAFETY: A nonzero value transfers an ownership reference.+ let value = (value != 0).then(|| unsafe { Utf16String::from_raw_owned(value) });+ cell_into_abi(allocate(vm, |_| DOMTokenList::new(element, attribute, value)))+}++/// # Safety+///+/// The caller passes a live DOMTokenList and transfers ownership of the new attribute value if it is nonzero.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_token_list_attribute_changed(list: *mut c_void, value: usize) {+ // SAFETY: The caller passes a live DOMTokenList and transfers a reference for a nonzero value.+ let list = unsafe { cell_from_abi::<DOMTokenList>(list) };+ let value = (value != 0).then(|| unsafe { Utf16String::from_raw_owned(value) });+ list.associated_attribute_changed(value);+}++/// # Safety+///+/// The caller passes a live DOMTokenList and transfers ownership of a valid token.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_token_list_add(list: *mut c_void, token: usize) {+ // SAFETY: The caller passes a live DOMTokenList and transfers a reference to the token.+ let (list, token) = unsafe { (cell_from_abi::<DOMTokenList>(list), Utf16String::from_raw_owned(token)) };+ list.add_tokens([token]).must();+}++/// # Safety+///+/// The caller passes a live DOMTokenList and transfers ownership of a valid token.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_token_list_remove(list: *mut c_void, token: usize) {+ // SAFETY: The caller passes a live DOMTokenList and transfers a reference to the token.+ let (list, token) = unsafe { (cell_from_abi::<DOMTokenList>(list), Utf16String::from_raw_owned(token)) };+ list.remove_tokens([token]).must();+}++/// # Safety+///+/// The caller passes a live DOMTokenList and transfers ownership of a valid token.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_token_list_toggle(list: *mut c_void, token: usize, force: bool) {+ // SAFETY: The caller passes a live DOMTokenList and transfers a reference to the token.+ let (list, token) = unsafe { (cell_from_abi::<DOMTokenList>(list), Utf16String::from_raw_owned(token)) };+ list.toggle_token(token, Some(force)).must();+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rsindex ea85cc8b5ed..052449cbe3f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs@@ -8,7 +8,7 @@use core::ffi::c_void;-use ak::Utf16String;+use ak::{Utf16FlyString, Utf16String};use libjs_rust::api::{Gc, MarkedVec, Object, Trace};use crate::animations::animatable::{self, GetAnimationsOptions, UnrestrictedDoubleOrKeyframeAnimationOptions};@@ -19,6 +19,9 @@ use crate::bindings::{CallContext, WebIdlResult};unsafe extern "C" {fn web_dom_is_valid_attribute_local_name(name: usize) -> bool;+ fn web_dom_element_local_name(element: *mut c_void) -> usize;+ fn web_dom_element_get_attribute_ns(element: *mut c_void, namespace: usize, name: usize) -> usize;+ fn web_dom_element_set_attribute_value(element: *mut c_void, name: usize, value: usize);fn web_dom_element_attribute(element: *mut c_void,name: ak::Span<'_, u8>,@@ -46,6 +49,28 @@ impl CppElement {Self(unsafe { CppCell::from_raw(element) })}+ pub(crate) fn local_name(&self) -> Utf16FlyString {+ // SAFETY: The element is live and owns the returned local name.+ unsafe { Utf16FlyString::from_raw_borrowed(web_dom_element_local_name(self.0.as_ptr())) }+ }++ pub(crate) fn get_attribute_ns(+ &self,+ namespace: Option<&Utf16FlyString>,+ name: &Utf16FlyString,+ ) -> Option<Utf16String> {+ let namespace = namespace.map_or(0, |namespace| namespace.raw_identity());+ // SAFETY: The element is live and the names are lent for the call.+ let value = unsafe { web_dom_element_get_attribute_ns(self.0.as_ptr(), namespace, name.raw_identity()) };+ // SAFETY: A nonzero result transfers a reference to the value.+ (value != 0).then(|| unsafe { Utf16String::from_raw_owned(value) })+ }++ pub(crate) fn set_attribute_value(&self, name: &Utf16FlyString, value: Utf16String) {+ // SAFETY: The element is live, the name is lent for the call, and the value reference is transferred.+ unsafe { web_dom_element_set_attribute_value(self.0.as_ptr(), name.raw_identity(), value.into_raw()) };+ }+/// https://dom.spec.whatwg.org/#concept-element-attributes-get-valuepub(crate) fn attribute(&self, name: &str) -> Option<Utf16String> {let mut value = None;diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rsindex 578a96d199f..863f7bc6f6c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs@@ -13,6 +13,8 @@ pub(crate) mod abort_signal;#[cfg(not(test))]pub(crate) mod document;#[cfg(not(test))]+pub(crate) mod dom_token_list;+#[cfg(not(test))]pub(crate) mod element;pub(crate) mod event;#[cfg(not(test))]diff --git a/Libraries/LibWeb/DOM/DOMTokenList.cpp b/Libraries/LibWeb/DOM/DOMTokenList.cppindex b14023b15ba..fdad19157c2 100644--- a/Libraries/LibWeb/DOM/DOMTokenList.cpp+++ b/Libraries/LibWeb/DOM/DOMTokenList.cpp@@ -5,383 +5,49 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>-#include <AK/StringBuilder.h>-#include <AK/TemporaryChange.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/ExternalMemory.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/DOM/DOMTokenList.h>-#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>-#include <LibWeb/HTML/HTMLLinkElement.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWebCommon/Infra/CharacterTypes.h>--namespace {--// https://infra.spec.whatwg.org/#set-append-inline void append_to_ordered_set(Vector<Utf16String>& set, Utf16View item)-{- if (!set.contains_slow(item))- set.append(Utf16String::from_utf16(item));-}--// https://infra.spec.whatwg.org/#list-remove-inline void remove_from_ordered_set(Vector<Utf16String>& set, Utf16View item)-{- set.remove_first_matching([&](auto const& value) { return value == item; });-}--// https://infra.spec.whatwg.org/#set-replace-inline void replace_in_ordered_set(Vector<Utf16String>& set, Utf16View item, Utf16View replacement)-{- auto item_index = set.find_first_index_if([&](auto const& value) { return value == item; });- VERIFY(item_index.has_value());-- auto replacement_index = set.find_first_index_if([&](auto const& value) { return value == replacement; });- if (!replacement_index.has_value()) {- set[*item_index] = Utf16String::from_utf16(replacement);- return;- }-- if (*item_index == *replacement_index)- return;-- if (*replacement_index < *item_index) {- set.remove(*item_index);- return;- }-- set[*item_index] = move(set[*replacement_index]);- set.remove(*replacement_index);-}--}namespace Web::DOM {-GC_DEFINE_ALLOCATOR(DOMTokenList);--GC::Ref<DOMTokenList> DOMTokenList::create(Element& associated_element, Utf16FlyString associated_attribute)-{- return GC::Heap::the().allocate<DOMTokenList>(associated_element, move(associated_attribute));-}--// https://dom.spec.whatwg.org/#ref-for-domtokenlist%E2%91%A0%E2%91%A2-DOMTokenList::DOMTokenList(Element& associated_element, Utf16FlyString associated_attribute)- : m_associated_element(associated_element)- , m_associated_attribute(move(associated_attribute))-{- // When a DOMTokenList object set is created:- // 1. Let element be set’s element.- // 2. Let attributeName be set’s attribute name.- // 3. Let value be the result of getting an attribute value given element and attributeName.- auto value = m_associated_element->attribute(m_associated_attribute).value_or({});-- // 4. Run the attribute change steps for element, attributeName, value, value, and null.- associated_attribute_changed(value);-}--void DOMTokenList::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_associated_element);-}--size_t DOMTokenList::external_memory_size() const-{- auto size = Base::external_memory_size();- size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(m_token_set));- for (auto const& token : m_token_set)- size = JS::saturating_add_external_memory_size(size, JS::utf16_string_external_memory_size(token));- return size;-}--// https://dom.spec.whatwg.org/#ref-for-domtokenlist%E2%91%A0%E2%91%A1-void DOMTokenList::associated_attribute_changed(Utf16View value)-{- // 1. If localName is set’s attribute name, namespace is null, and value is null, then empty token set.- // 2. Otherwise, if localName is set’s attribute name and namespace is null, then set set’s token set to value,- // parsed.- // AD-HOC: The caller is responsible for checking the name and namespace.- // OPTIMIZATION: The update steps just wrote this value from the token set, so there is nothing new to parse.- if (m_is_running_update_steps)- return;- m_token_set.clear();- if (value.is_empty())- return;- m_token_set = parse_ordered_set(value);-}--// https://dom.spec.whatwg.org/#dom-domtokenlist-item-Optional<Utf16String> DOMTokenList::item(size_t index) const-{- // 1. If index is equal to or greater than this’s token set’s size, then return null.- if (index >= m_token_set.size())- return {};-- // 2. Return this’s token set[index].- return m_token_set[index];-}+extern "C" {-// https://dom.spec.whatwg.org/#dom-domtokenlist-contains-bool DOMTokenList::contains(Utf16View token)-{- return m_token_set.contains_slow(token);-}--WebIDL::ExceptionOr<void> DOMTokenList::add(Utf16View token)-{- TRY(validate_token(token));- append_to_ordered_set(m_token_set, token);- run_update_steps();- return {};+// Defined in Bindings/Rust/src/dom/dom_token_list.rs.+void* web_dom_token_list_create(JSVM*, Element*, FlatPtr attribute_name, FlatPtr initial_value);+void web_dom_token_list_attribute_changed(DOMTokenList*, FlatPtr value);+void web_dom_token_list_add(DOMTokenList*, FlatPtr token);+void web_dom_token_list_remove(DOMTokenList*, FlatPtr token);+void web_dom_token_list_toggle(DOMTokenList*, FlatPtr token, bool force);}-// https://dom.spec.whatwg.org/#dom-domtokenlist-add-WebIDL::ExceptionOr<void> DOMTokenList::add(Vector<Utf16String> const& tokens)+GC::Ref<DOMTokenList> DOMTokenList::create(Element& element, Utf16FlyString const& associated_attribute){- // 1. For each token of tokens:- for (auto const& token : tokens) {- // a. If token is the empty string, then throw a "SyntaxError" DOMException.- // b. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.- TRY(validate_token(token));-- // 2. For each token of tokens, append token to this’s token set.- append_to_ordered_set(m_token_set, token);- }-- // 3. Run the update steps.- run_update_steps();- return {};+ auto value = element.attribute(associated_attribute);+ return GC::Ref { *static_cast<DOMTokenList*>(web_dom_token_list_create(+ JS::HostABI::vm_to_abi(JS::VM::the()), &element, associated_attribute.raw_identity(),+ value.has_value() ? value.release_value().into_raw() : 0)) };}-WebIDL::ExceptionOr<void> DOMTokenList::remove(Utf16View token)+void DOMTokenList::associated_attribute_changed(Optional<Utf16String> const& value){- TRY(validate_token(token));- remove_from_ordered_set(m_token_set, token);- run_update_steps();- return {};+ web_dom_token_list_attribute_changed(this, value.has_value() ? value->to_raw_leaked() : 0);}-// https://dom.spec.whatwg.org/#dom-domtokenlist-remove-WebIDL::ExceptionOr<void> DOMTokenList::remove(Vector<Utf16String> const& tokens)+void DOMTokenList::add(Utf16View token){- // 1. For each token of tokens:- for (auto const& token : tokens) {- // a. If token is the empty string, then throw a "SyntaxError" DOMException.- // b. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.- TRY(validate_token(token));-- // 2. For each token of tokens, remove token from this’s token set.- remove_from_ordered_set(m_token_set, token);- }-- // 3. Run the update steps.- run_update_steps();- return {};+ web_dom_token_list_add(this, Utf16String::from_utf16(token).into_raw());}-// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle-WebIDL::ExceptionOr<bool> DOMTokenList::toggle(Utf16View token, Optional<bool> force)+void DOMTokenList::remove(Utf16View token){- // 1. If token is the empty string, then throw a "SyntaxError" DOMException.- // 2. If token contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.- TRY(validate_token(token));-- // 3. If this’s token set[token] exists, then:- if (contains(token)) {- // a. If force is either not given or is false, then remove token from this’s token set, run the update steps and return false.- if (!force.has_value() || !force.value()) {- remove_from_ordered_set(m_token_set, token);- run_update_steps();- return false;- }-- // b. Return true.- return true;- }-- // 4. Otherwise, if force not given or is true, append token to this’s token set, run the update steps, and return true.- if (!force.has_value() || force.value()) {- append_to_ordered_set(m_token_set, token);- run_update_steps();- return true;- }-- // 5. Return false.- return false;+ web_dom_token_list_remove(this, Utf16String::from_utf16(token).into_raw());}-// https://dom.spec.whatwg.org/#dom-domtokenlist-replace-WebIDL::ExceptionOr<bool> DOMTokenList::replace(Utf16View token, Utf16View new_token)+void DOMTokenList::toggle(Utf16View token, bool force){- // 1. If either token or newToken is the empty string, then throw a "SyntaxError" DOMException.- TRY(validate_token_not_empty(token));- TRY(validate_token_not_empty(new_token));-- // 2. If either token or newToken contains any ASCII whitespace, then throw an "InvalidCharacterError" DOMException.- TRY(validate_token_not_whitespace(token));- TRY(validate_token_not_whitespace(new_token));-- // 3. If this’s token set does not contain token, then return false.- if (!contains(token))- return false;-- // 4. Replace token in this’s token set with newToken.- replace_in_ordered_set(m_token_set, token, new_token);-- // 5. Run the update steps.- run_update_steps();-- // 6. Return true.- return true;-}--// https://dom.spec.whatwg.org/#dom-domtokenlist-supports-WebIDL::ExceptionOr<bool> DOMTokenList::supports(Utf16View token)-{- // 1. Let result be the return value of validation steps called with token.- auto result = run_validation_steps(token);-- // 2. Return result.- return result;-}--// https://dom.spec.whatwg.org/#concept-domtokenlist-validation-WebIDL::ExceptionOr<bool> DOMTokenList::run_validation_steps(Utf16View token)-{- static NeverDestroyed<HashMap<SupportedTokenKey, Vector<Utf16View>>> supported_tokens_map { HashMap<SupportedTokenKey, Vector<Utf16View>> {- // https://html.spec.whatwg.org/multipage/links.html#linkTypes- { { HTML::TagNames::link, HTML::AttributeNames::rel },- { u"modulepreload"sv, u"preload"sv, u"preconnect"sv, u"dns-prefetch"sv, u"stylesheet"sv, u"icon"sv, u"alternate"sv, u"prefetch"sv, u"prerender"sv, u"next"sv, u"manifest"sv, u"apple-touch-icon"sv, u"apple-touch-icon-precomposed"sv, u"canonical"sv } },- { { HTML::TagNames::a, HTML::AttributeNames::rel },- { u"noreferrer"sv, u"noopener"sv, u"opener"sv } },- { { HTML::TagNames::area, HTML::AttributeNames::rel },- { u"noreferrer"sv, u"noopener"sv, u"opener"sv } },- { { HTML::TagNames::form, HTML::AttributeNames::rel },- { u"noreferrer"sv, u"noopener"sv, u"opener"sv } },-- // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#blocking-attribute- { { HTML::TagNames::link, HTML::AttributeNames::blocking }, { u"render"sv } },- { { HTML::TagNames::script, HTML::AttributeNames::blocking }, { u"render"sv } },- { { HTML::TagNames::style, HTML::AttributeNames::blocking }, { u"render"sv } },-- // https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox- { { HTML::TagNames::iframe, HTML::AttributeNames::sandbox },- { u"allow-downloads"sv, u"allow-forms"sv, u"allow-modals"sv, u"allow-orientation-lock"sv, u"allow-pointer-lock"sv, u"allow-popups"sv, u"allow-popups-to-escape-sandbox"sv, u"allow-presentation"sv, u"allow-same-origin"sv, u"allow-scripts"sv, u"allow-top-navigation"sv, u"allow-top-navigation-by-user-activation"sv, u"allow-top-navigation-to-custom-protocols"sv } },- } };-- // 1. If set’s element and attribute name does not define supported tokens, then throw a TypeError.- auto supported_tokens = supported_tokens_map->get({ m_associated_element->local_name(), m_associated_attribute });- if (!supported_tokens.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Attribute {} does not define any supported tokens", m_associated_attribute) };-- // 2. Let lowercaseToken be token, in ASCII lowercase.- // 3. If lowercaseToken is present in the supported tokens of set’s element and attribute name, then return true.- for (auto supported_token : *supported_tokens) {- if (token.equals_ignoring_ascii_case(supported_token))- return true;- }-- // 4. Return false.- return false;-}--// https://dom.spec.whatwg.org/#concept-ordered-set-parser-Vector<Utf16String> DOMTokenList::parse_ordered_set(Utf16View input) const-{- // 1. Let inputTokens be the result of splitting input on ASCII whitespace.- // 2. Let tokens be a new ordered set.- Vector<Utf16String> tokens;-- // 3. For each token of inputTokens: append token to tokens.- Optional<size_t> token_start;- for (size_t i = 0; i < input.length_in_code_units(); ++i) {- if (Infra::is_ascii_whitespace(input.code_unit_at(i))) {- if (token_start.has_value()) {- append_to_ordered_set(tokens, input.substring_view(*token_start, i - *token_start));- token_start.clear();- }- continue;- }-- if (!token_start.has_value())- token_start = i;- }- if (token_start.has_value())- append_to_ordered_set(tokens, input.substring_view(*token_start));-- // 4. Return tokens.- return tokens;-}--// https://dom.spec.whatwg.org/#concept-ordered-set-serializer-Utf16String DOMTokenList::serialize_ordered_set() const-{- // The ordered set serializer takes a set and returns the concatenation of set using U+0020 SPACE.- Utf16StringBuilder builder;- for (auto const& token : m_token_set) {- if (!builder.is_empty())- builder.append_code_unit(' ');- builder.append(token);- }- return builder.to_string();-}--// https://dom.spec.whatwg.org/#dom-domtokenlist-value-Utf16String DOMTokenList::value() const-{- return m_associated_element->get_attribute_value(m_associated_attribute);-}--// https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-set-value%E2%91%A2-void DOMTokenList::set_value(Utf16View value)-{- GC::Ptr<DOM::Element> associated_element = m_associated_element.ptr();- if (!associated_element)- return;-- associated_element->set_attribute_value(m_associated_attribute, value);-}--WebIDL::ExceptionOr<void> DOMTokenList::validate_token(Utf16View token) const-{- TRY(validate_token_not_empty(token));- TRY(validate_token_not_whitespace(token));- return {};-}--WebIDL::ExceptionOr<void> DOMTokenList::validate_token_not_empty(Utf16View token) const-{- if (token.is_empty())- return WebIDL::SyntaxError::create("Non-empty DOM tokens are not allowed"_utf16);- return {};-}--WebIDL::ExceptionOr<void> DOMTokenList::validate_token_not_whitespace(Utf16View token) const-{- if (any_of(token, Infra::is_ascii_whitespace))- return WebIDL::InvalidCharacterError::create("DOM tokens containing ASCII whitespace are not allowed"_utf16);- return {};-}--// https://dom.spec.whatwg.org/#concept-dtl-update-void DOMTokenList::run_update_steps()-{- GC::Ptr<DOM::Element> associated_element = m_associated_element.ptr();- if (!associated_element)- return;-- // 1. If get an attribute by namespace and local name given null, set’s attribute name, and set’s element returns null and set’s token set is empty, then return.- auto attribute = associated_element->get_attribute_ns(Optional<Utf16FlyString> {}, m_associated_attribute);- if (!attribute.has_value() && m_token_set.is_empty())- return;-- // 2. Set an attribute value given set’s element, set’s attribute name, and the result of running the ordered set- // serializer for set’s token set.- TemporaryChange running_update_steps { m_is_running_update_steps, true };- associated_element->set_attribute_value(m_associated_attribute, serialize_ordered_set());+ web_dom_token_list_toggle(this, Utf16String::from_utf16(token).into_raw(), force);}}diff --git a/Libraries/LibWeb/DOM/DOMTokenList.h b/Libraries/LibWeb/DOM/DOMTokenList.hindex adad054e660..51a5c1742c6 100644--- a/Libraries/LibWeb/DOM/DOMTokenList.h+++ b/Libraries/LibWeb/DOM/DOMTokenList.h@@ -10,77 +10,23 @@#include <AK/Optional.h>#include <AK/Utf16FlyString.h>-#include <AK/Utf16String.h>-#include <AK/Utf16View.h>-#include <AK/Vector.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibGC/Ptr.h>+#include <LibWeb/Bindings/DOMTokenList.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::DOM {-// https://dom.spec.whatwg.org/#domtokenlist-class DOMTokenList final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(DOMTokenList, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMTokenList);+class DOMTokenList : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMTokenList, dom_token_list)public:- [[nodiscard]] static GC::Ref<DOMTokenList> create(Element& associated_element, Utf16FlyString associated_attribute);- ~DOMTokenList() = default;+ [[nodiscard]] static GC::Ref<DOMTokenList> create(Element&, Utf16FlyString const& associated_attribute);- void associated_attribute_changed(Utf16View value);-- size_t length() const { return m_token_set.size(); }- Optional<Utf16String> item(size_t index) const;- bool contains(Utf16View token);- WebIDL::ExceptionOr<void> add(Utf16View token);- WebIDL::ExceptionOr<void> add(Vector<Utf16String> const& tokens);- WebIDL::ExceptionOr<void> remove(Utf16View token);- WebIDL::ExceptionOr<void> remove(Vector<Utf16String> const& tokens);- WebIDL::ExceptionOr<bool> toggle(Utf16View token, Optional<bool> force);- WebIDL::ExceptionOr<bool> replace(Utf16View token, Utf16View new_token);- WebIDL::ExceptionOr<bool> supports(Utf16View token);- Utf16String value() const;- void set_value(Utf16View value);--private:- DOMTokenList(Element& associated_element, Utf16FlyString associated_attribute);-- virtual void visit_edges(GC::Cell::Visitor&) override;- virtual size_t external_memory_size() const override;-- WebIDL::ExceptionOr<void> validate_token(Utf16View token) const;- WebIDL::ExceptionOr<void> validate_token_not_empty(Utf16View token) const;- WebIDL::ExceptionOr<void> validate_token_not_whitespace(Utf16View token) const;- WebIDL::ExceptionOr<bool> run_validation_steps(Utf16View token);- void run_update_steps();-- Vector<Utf16String> parse_ordered_set(Utf16View) const;- Utf16String serialize_ordered_set() const;-- GC::NonnullMember<Element> m_associated_element;- Utf16FlyString m_associated_attribute;- Vector<Utf16String> m_token_set;- bool m_is_running_update_steps { false };-};--}--struct SupportedTokenKey {- Utf16FlyString element_name;- Utf16FlyString attribute_name;-- constexpr bool operator==(SupportedTokenKey const& other) const = default;-};--namespace AK {--template<>-struct Traits<SupportedTokenKey> : public DefaultTraits<SupportedTokenKey> {- static unsigned hash(SupportedTokenKey const& key)- {- return pair_int_hash(key.element_name.hash(), key.attribute_name.hash());- }+ void associated_attribute_changed(Optional<Utf16String> const&);+ void add(Utf16View);+ void remove(Utf16View);+ void toggle(Utf16View, bool force);};}diff --git a/Libraries/LibWeb/DOM/DOMTokenList.idl b/Libraries/LibWeb/DOM/DOMTokenList.idlindex 9f397afff06..4b91ada10ba 100644--- a/Libraries/LibWeb/DOM/DOMTokenList.idl+++ b/Libraries/LibWeb/DOM/DOMTokenList.idl@@ -1,5 +1,5 @@// https://dom.spec.whatwg.org/#interface-domtokenlist-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface DOMTokenList {readonly attribute unsigned long length;getter DOMString? item(unsigned long index);diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 68aaebc9676..00d711b71b3 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -177,6 +177,9 @@ namespace Web::DOM {extern "C" {// Called by Bindings/Rust/src/dom/element.rs.+FlatPtr web_dom_element_local_name(Element const*);+FlatPtr web_dom_element_get_attribute_ns(Element const*, FlatPtr namespace_, FlatPtr name);+void web_dom_element_set_attribute_value(Element*, FlatPtr name, FlatPtr value);void web_dom_element_attribute(Element*, ReadonlyBytes name, void* value, void (*on_value)(void*, FlatPtr));}@@ -6396,7 +6399,7 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16});}if (auto* rare_data = element_rare_data(); rare_data && rare_data->class_list)- rare_data->class_list->associated_attribute_changed(value_or_empty);+ rare_data->class_list->associated_attribute_changed(value);if (old_style_engine_classes.has_value())CSS::record_element_class_list_changed(*this, *old_style_engine_classes, m_classes);@@ -6494,7 +6497,7 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16}}if (auto* rare_data = element_rare_data(); rare_data && rare_data->part_list)- rare_data->part_list->associated_attribute_changed(value_or_empty);+ rare_data->part_list->associated_attribute_changed(value);CSS::record_element_parts_changed(*this);} else if (local_name == HTML::AttributeNames::exportparts) {CSS::Invalidation::invalidate_style_after_exportparts_attribute_change(*this);@@ -7151,6 +7154,25 @@ bool Element::is_potentially_render_blocking()return false;}+FlatPtr web_dom_element_local_name(Element const* element)+{+ return element->local_name().raw_identity();+}++FlatPtr web_dom_element_get_attribute_ns(Element const* element, FlatPtr namespace_, FlatPtr name)+{+ Optional<Utf16FlyString> namespace_name;+ if (namespace_ != 0)+ namespace_name = Utf16FlyString::from_raw(namespace_);+ auto attribute = element->get_attribute_ns(namespace_name, Utf16FlyString::from_raw(name));+ return attribute.has_value() ? attribute.release_value().into_raw() : 0;+}++void web_dom_element_set_attribute_value(Element* element, FlatPtr name, FlatPtr value)+{+ element->set_attribute_value(Utf16FlyString::from_raw(name), Utf16String::adopt_raw(value));+}+void web_dom_element_attribute(Element* element, ReadonlyBytes name, void* value, void (*on_value)(void*, FlatPtr)){auto attribute = element->attribute(Utf16FlyString::from_utf8(StringView { name }));diff --git a/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp b/Libraries/LibWeb/HTML/HTMLAnchorElement.cppindex 630d20120ae..a130fcb6e5f 100644--- a/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLAnchorElement.cpp@@ -38,7 +38,7 @@ void HTMLAnchorElement::attribute_changed(Utf16FlyString const& name, Optional<Uhref_content_attribute_changed();} else if (name == HTML::AttributeNames::rel) {if (m_rel_list)- m_rel_list->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_rel_list->associated_attribute_changed(value);}}diff --git a/Libraries/LibWeb/HTML/HTMLAreaElement.cpp b/Libraries/LibWeb/HTML/HTMLAreaElement.cppindex 31b62621226..65734201bea 100644--- a/Libraries/LibWeb/HTML/HTMLAreaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLAreaElement.cpp@@ -38,7 +38,7 @@ void HTMLAreaElement::attribute_changed(Utf16FlyString const& name, Optional<Utfhref_content_attribute_changed();} else if (name == HTML::AttributeNames::rel) {if (m_rel_list)- m_rel_list->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_rel_list->associated_attribute_changed(value);}if (name.is_one_of(HTML::AttributeNames::coords, HTML::AttributeNames::shape)) {diff --git a/Libraries/LibWeb/HTML/HTMLFormElement.cpp b/Libraries/LibWeb/HTML/HTMLFormElement.cppindex 0f7a59ad7b0..8dc3bad305f 100644--- a/Libraries/LibWeb/HTML/HTMLFormElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLFormElement.cpp@@ -793,7 +793,7 @@ void HTMLFormElement::attribute_changed(Utf16FlyString const& name, Optional<Utfif (name == HTML::AttributeNames::rel) {if (m_rel_list)- m_rel_list->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_rel_list->associated_attribute_changed(value);}}diff --git a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp b/Libraries/LibWeb/HTML/HTMLIFrameElement.cppindex 3ee0204b7c0..6f8d17644ae 100644--- a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp@@ -57,7 +57,7 @@ void HTMLIFrameElement::attribute_changed(Utf16FlyString const& name, Optional<Uif (name == HTML::AttributeNames::sandbox) {if (m_sandbox)- m_sandbox->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_sandbox->associated_attribute_changed(value);}// https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-iframe-element:process-the-iframe-attributes-2diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cppindex b6b1662f5cc..2b08c6b157f 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp@@ -243,7 +243,7 @@ void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf{Base::attribute_changed(name, old_value, value, namespace_);if (!namespace_.has_value() && name == AttributeNames::blocking && m_blocking)- m_blocking->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_blocking->associated_attribute_changed(value);// 4.6.7 Link types - https://html.spec.whatwg.org/multipage/links.html#linkTypesauto old_relationship = m_relationship;@@ -282,7 +282,7 @@ void HTMLLinkElement::attribute_changed(Utf16FlyString const& name, Optional<Utf}if (m_rel_list)- m_rel_list->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_rel_list->associated_attribute_changed(value);// NB: A link that no longer represents a stylesheet will not run stylesheet completion steps.if ((old_relationship & Relationship::Stylesheet) && !(m_relationship & Relationship::Stylesheet))diff --git a/Libraries/LibWeb/HTML/HTMLOutputElement.cpp b/Libraries/LibWeb/HTML/HTMLOutputElement.cppindex c967a7fcf1d..2531ceb817f 100644--- a/Libraries/LibWeb/HTML/HTMLOutputElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLOutputElement.cpp@@ -28,7 +28,7 @@ void HTMLOutputElement::form_associated_element_attribute_changed(Utf16FlyString{if (name == HTML::AttributeNames::for_) {if (m_html_for)- m_html_for->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_html_for->associated_attribute_changed(value);}}diff --git a/Libraries/LibWeb/HTML/HTMLScriptElement.cpp b/Libraries/LibWeb/HTML/HTMLScriptElement.cppindex adb6c707db7..c5d7af6a096 100644--- a/Libraries/LibWeb/HTML/HTMLScriptElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLScriptElement.cpp@@ -48,7 +48,7 @@ void HTMLScriptElement::attribute_changed(Utf16FlyString const& name, Optional<U{Base::attribute_changed(name, old_value, value, namespace_);if (!namespace_.has_value() && name == AttributeNames::blocking && m_blocking)- m_blocking->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_blocking->associated_attribute_changed(value);if (!namespace_.has_value() && name == HTML::AttributeNames::crossorigin) {m_crossorigin = cors_setting_attribute_from_keyword(value.map([](auto const& value) { return value.utf16_view(); }));diff --git a/Libraries/LibWeb/HTML/HTMLStyleElement.cpp b/Libraries/LibWeb/HTML/HTMLStyleElement.cppindex bf3c61950c6..a773122a84a 100644--- a/Libraries/LibWeb/HTML/HTMLStyleElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLStyleElement.cpp@@ -72,7 +72,7 @@ void HTMLStyleElement::attribute_changed(Utf16FlyString const& name, Optional<Ut{Base::attribute_changed(name, old_value, value, namespace_);if (!namespace_.has_value() && name == AttributeNames::blocking && m_blocking)- m_blocking->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_blocking->associated_attribute_changed(value);style_element_attribute_changed(name, value);}diff --git a/Libraries/LibWeb/HTML/MediaControls.cpp b/Libraries/LibWeb/HTML/MediaControls.cppindex c997308d448..9eab858da15 100644--- a/Libraries/LibWeb/HTML/MediaControls.cpp+++ b/Libraries/LibWeb/HTML/MediaControls.cpp@@ -59,8 +59,8 @@ void MediaControls::update_visibility(){auto& host = *m_host;- MUST(m_dom->container->class_list()->toggle("controls-hidden"_utf16, !host.should_expose_user_interface()));- MUST(m_dom->container->class_list()->toggle("picture-in-picture"_utf16, host.is_picture_in_picture_element()));+ m_dom->container->class_list()->toggle("controls-hidden"_utf16, !host.should_expose_user_interface());+ m_dom->container->class_list()->toggle("picture-in-picture"_utf16, host.is_picture_in_picture_element());update_placeholder_visibility();update_timeline();@@ -90,11 +90,11 @@ void MediaControls::create_shadow_tree()m_dom = MediaControlsDOM(document, *shadow_root, options);if (is_video)- MUST(m_dom->container->class_list()->add("video"_utf16));+ m_dom->container->class_list()->add("video"_utf16);else- MUST(m_dom->container->class_list()->add("audio"_utf16));+ m_dom->container->class_list()->add("audio"_utf16);if (is_picture_in_picture_player())- MUST(m_dom->container->class_list()->add("picture-in-picture-player"_utf16));+ m_dom->container->class_list()->add("picture-in-picture-player"_utf16);// Initialize stateupdate_play_pause_icon();@@ -592,7 +592,7 @@ void MediaControls::update_play_pause_icon()return m_media_element->paused();}();- MUST(m_dom->play_pause_icon->class_list()->toggle("playing"_utf16, !paused));+ m_dom->play_pause_icon->class_list()->toggle("playing"_utf16, !paused);}static Utf16String format_percent(double value)@@ -646,7 +646,7 @@ void MediaControls::update_timeline()while (m_buffered_ranges.size() < range_count) {auto element = MUST(DOM::create_element(m_host->document(), HTML::TagNames::div, Namespace::HTML));- MUST(element->class_list()->toggle("timeline-buffered"_utf16, true));+ element->class_list()->toggle("timeline-buffered"_utf16, true);MUST(element->style()->set_property(CSS::PropertyID::Display, "block"_utf16));m_dom->timeline_track->insert_before(element, nullptr);m_buffered_ranges.empend(*element);@@ -805,19 +805,19 @@ void MediaControls::update_volume_and_mute_indicator()if (new_volume_icon_state != m_mute_icon_state) {if (auto previous_class = icon_class(m_mute_icon_state); !previous_class.is_empty())- MUST(m_dom->mute_button->class_list()->remove(previous_class));+ m_dom->mute_button->class_list()->remove(previous_class);if (auto next_class = icon_class(new_volume_icon_state); !next_class.is_empty())- MUST(m_dom->mute_button->class_list()->add(next_class));+ m_dom->mute_button->class_list()->add(next_class);m_mute_icon_state = new_volume_icon_state;}if (muted != m_was_muted) {- MUST(m_dom->mute_button->class_list()->toggle("muted"_utf16, muted));+ m_dom->mute_button->class_list()->toggle("muted"_utf16, muted);m_was_muted = muted;}if (has_audio != m_had_audio) {- MUST(m_dom->volume_area->class_list()->toggle("hidden"_utf16, !has_audio));+ m_dom->volume_area->class_list()->toggle("hidden"_utf16, !has_audio);m_had_audio = has_audio;}}@@ -830,7 +830,7 @@ void MediaControls::update_fullscreen_icon()VERIFY(m_host);auto is_fullscreen_element = m_host->document().fullscreen_element() == m_host;- MUST(m_dom->fullscreen_icon->class_list()->toggle("fullscreen"_utf16, is_fullscreen_element));+ m_dom->fullscreen_icon->class_list()->toggle("fullscreen"_utf16, is_fullscreen_element);}void MediaControls::update_placeholder_visibility()@@ -866,7 +866,7 @@ void MediaControls::show_controls()VERIFY(m_media_element);VERIFY(m_dom->control_bar);- MUST(m_dom->control_bar->class_list()->add(visible_class()));+ m_dom->control_bar->class_list()->add(visible_class());if (!exchange(m_control_bar_is_shown, true)) {update_timeline();@@ -896,7 +896,7 @@ void MediaControls::hide_controls()if (m_dom->placeholder_circle && should_show_placeholder())return;- MUST(m_dom->control_bar->class_list()->remove(visible_class()));+ m_dom->control_bar->class_list()->remove(visible_class());m_hover_timer.clear();m_control_bar_is_shown = false;control_bar_visibility_did_change();diff --git a/Libraries/LibWeb/SVG/SVGAElement.cpp b/Libraries/LibWeb/SVG/SVGAElement.cppindex b73dfe6ccf7..1f6047baa7a 100644--- a/Libraries/LibWeb/SVG/SVGAElement.cpp+++ b/Libraries/LibWeb/SVG/SVGAElement.cpp@@ -44,7 +44,7 @@ void SVGAElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16Sthref_content_attribute_changed();if (name == HTML::AttributeNames::rel) {if (m_rel_list)- m_rel_list->associated_attribute_changed(value.has_value() ? value->utf16_view() : u""sv);+ m_rel_list->associated_attribute_changed(value);}}diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.pyindex 57c94972100..08f294ac5b3 100644--- a/Meta/Generators/libweb_bindings/rust_members.py+++ b/Meta/Generators/libweb_bindings/rust_members.py@@ -523,9 +523,11 @@ def rust_members(interface: Interface) -> RustMembers:if interface.stringifier is not None:stringifier = interface.stringifier- check_extended_attributes(- "its stringifier", stringifier.extended_attributes, SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES- )+ supported_attributes = SUPPORTED_STRINGIFIER_EXTENDED_ATTRIBUTES+ if stringifier.attribute is not None:+ # The attribute setter handles [CEReactions], including for a stringifier attribute.+ supported_attributes = supported_attributes | {"CEReactions"}+ check_extended_attributes("its stringifier", stringifier.extended_attributes, supported_attributes)check_exposure("its stringifier", stringifier.extended_attributes)attribute_getter_method = Noneif stringifier.attribute is not None:diff --git a/Tests/LibWeb/Text/expected/DOM/DOMTokenList-custom-element-reactions.txt b/Tests/LibWeb/Text/expected/DOM/DOMTokenList-custom-element-reactions.txtnew file mode 100644index 00000000000..8391ff34c09--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/DOMTokenList-custom-element-reactions.txt@@ -0,0 +1,6 @@+null -> seed seed: ["seed"]+seed seed -> seed appended: ["seed","appended"]+seed appended -> reentrant reentrant: ["reentrant"]+after add: true, 1, reentrant, reentrant reentrant+reentrant reentrant -> null: []+after removal: 0, undefineddiff --git a/Tests/LibWeb/Text/input/DOM/DOMTokenList-custom-element-reactions.html b/Tests/LibWeb/Text/input/DOM/DOMTokenList-custom-element-reactions.htmlnew file mode 100644index 00000000000..3ba3627a933--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/DOMTokenList-custom-element-reactions.html@@ -0,0 +1,25 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ class ClassListElement extends HTMLElement {+ static observedAttributes = ["class"];++ attributeChangedCallback(name, oldValue, newValue) {+ println(`${oldValue} -> ${newValue}: ${JSON.stringify([...this.classList])}`);+ if (newValue === "seed appended")+ this.className = "reentrant reentrant";+ }+ }+ customElements.define("class-list-element", ClassListElement);++ const element = document.createElement("class-list-element");+ const list = element.classList;+ list.value = "seed seed";+ list.add("appended");+ println(`after add: ${list === element.classList}, ${list.length}, ${list[0]}, ${list}`);++ element.removeAttribute("class");+ println(`after removal: ${list.length}, ${list[0]}`);+ });+</script>