Skip to content

Truly independent web browser

LibWeb+Meta: Implement Highlight and its registry in Rust

Andreas Klingafd77354c3bf
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rs
index 16726932041..813b605ad69 100644
--- a/Libraries/LibJS/Rust/src/api.rs
+++ b/Libraries/LibJS/Rust/src/api.rs
@@ -68,6 +68,7 @@ pub use crate::runtime::iterator::{
iterator_complete, iterator_next, iterator_step_value, iterator_to_list, iterator_value,
};
pub use crate::runtime::map::Map;
+pub use crate::runtime::map_iterator::MapIterator;
pub use crate::runtime::module::Module;
pub use crate::runtime::module_environment::ModuleEnvironment;
pub use crate::runtime::module_request::ModuleRequest;
@@ -82,6 +83,7 @@ pub use crate::runtime::property_key::PropertyKey;
pub use crate::runtime::realm::Realm;
pub use crate::runtime::regexp_object::{RegExpObject, regexp_create};
pub use crate::runtime::set::Set;
+pub use crate::runtime::set_iterator::SetIterator;
pub use crate::runtime::string_object::StringObject;
pub use crate::runtime::typed_array::{
Kind as TypedArrayKind, TypedArrayBase, TypedArrayWithBufferWitness, create_typed_array_on_buffer,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index 93021a3ea32..953449d7cba 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -1275,6 +1275,16 @@ pub(crate) fn rooted_sequence_to_js<T: Trace + Clone + 'static>(
Ok(Value::from_object(array))
}
+/// The elements of a sequence of a dictionary in a MarkedVec, which keeps them alive while the dictionary is converted.
+pub(crate) fn mark_sequence<'vm, T: Trace + Clone + 'static>(
+ cx: &CallContext<'vm>,
+ sequence: &[T],
+) -> MarkedVec<'vm, T> {
+ let marked = MarkedVec::with_capacity(cx.vm(), sequence.len());
+ marked.extend_from_slice(sequence);
+ marked
+}
+
/// An IDL record converted to a JS value, https://webidl.spec.whatwg.org/#js-record, with the conversion of its
/// values. The entries of the record are in the order of the Vec.
pub(crate) fn record_to_js<K: Into<Utf16String>, V>(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/maplike.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/maplike.rs
new file mode 100644
index 00000000000..f67a9a711c5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/maplike.rs
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The maplike declarations of the interfaces implemented in Rust, https://webidl.spec.whatwg.org/#idl-maplike
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ Attribute, ErrorKind, ErrorType, Gc, Map, MapIterator, Object, PropertyAttributes, PropertyKey, PropertyKind,
+ RawNativeFunctionPointer, Realm, ThrowCompletionOr, Value, Vm, call,
+};
+
+use crate::bindings::CallContext;
+use crate::bindings::conversions::{ToJs, to_dom_string};
+use crate::bindings::interface::{Interface, Ref, define_attribute, define_operation, implementation_of, this_object};
+
+/// What the implementation of an interface with a maplike declaration, whose keys are strings, implements.
+pub(crate) trait Maplike: Interface {
+ // https://webidl.spec.whatwg.org/#dfn-map-entries
+ fn map_entries(&self, cx: &CallContext) -> Gc<Map>;
+}
+
+/// What the implementation of an interface with a read-write maplike declaration implements, for the operations that
+/// the interface does not declare itself.
+pub(crate) trait WritableMaplike: Maplike {
+ /// Sets the entry of the key to a value that the bindings converted to the value type.
+ fn map_set(&self, cx: &CallContext, key: Utf16String, value: Value);
+ fn map_remove(&self, cx: &CallContext, key: &Utf16String) -> bool;
+ fn map_clear(&self, cx: &CallContext);
+}
+
+/// What the generated bindings of a maplike declaration with operations of the bindings define.
+pub(crate) trait MaplikeDeclaration: Maplike {
+ /// Throws unless the JS value converts to the value type of the declaration.
+ fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()>;
+}
+
+/// Defines the properties that every maplike declaration has, https://webidl.spec.whatwg.org/#es-maplike
+#[expect(clippy::too_many_arguments, reason = "these are the functions of the declaration")]
+pub(crate) fn define_maplike_properties(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ size: RawNativeFunctionPointer,
+ entries: RawNativeFunctionPointer,
+ keys: RawNativeFunctionPointer,
+ values: RawNativeFunctionPointer,
+ for_each: RawNativeFunctionPointer,
+ get: RawNativeFunctionPointer,
+ has: RawNativeFunctionPointer,
+) {
+ define_attribute(vm, realm, prototype, "size", size, None);
+ define_operation(vm, realm, prototype, "entries", entries, 0);
+ prototype.define_direct_property(
+ vm,
+ &PropertyKey::from(vm.well_known_symbols().iterator),
+ prototype.get_without_side_effects(vm, &vm.names.entries),
+ PropertyAttributes::new(Attribute::CONFIGURABLE | Attribute::WRITABLE),
+ );
+ define_operation(vm, realm, prototype, "keys", keys, 0);
+ define_operation(vm, realm, prototype, "values", values, 0);
+ define_operation(vm, realm, prototype, "forEach", for_each, 1);
+ define_operation(vm, realm, prototype, "get", get, 1);
+ define_operation(vm, realm, prototype, "has", has, 1);
+}
+
+fn this_implementation<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<(Gc<Object>, Ref<T>, CallContext<'_>)> {
+ let (wrapper, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+ Ok((wrapper, implementation_of(wrapper), CallContext::new(vm, realm)))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-size
+pub(crate) fn map_size<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "size" and type "getter".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ let map = implementation.map_entries(&cx);
+
+ // 3. Return map's size, converted to a JavaScript value.
+ Ok(Value::from_f64(map.map_size() as f64))
+}
+
+fn create_map_iterator<T: Maplike>(vm: &Vm, kind: PropertyKind) -> ThrowCompletionOr<Value> {
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+ let map = implementation.map_entries(&cx);
+ Ok(Value::from_object(
+ MapIterator::create(vm, cx.realm(), map, kind).upcast::<Object>(),
+ ))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-entries
+pub(crate) fn map_iterator_entries<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "entries" and type "method".
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ // 3. Return the result of creating a map iterator from map with kind "key+value".
+ create_map_iterator::<T>(vm, PropertyKind::KeyAndValue)
+}
+
+// https://webidl.spec.whatwg.org/#js-map-keys
+pub(crate) fn map_iterator_keys<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "keys" and type "method".
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ // 3. Return the result of creating a map iterator from map with kind "key".
+ create_map_iterator::<T>(vm, PropertyKind::Key)
+}
+
+// https://webidl.spec.whatwg.org/#js-map-values
+pub(crate) fn map_iterator_values<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "values" and type "method".
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ // 3. Return the result of creating a map iterator from map with kind "value".
+ create_map_iterator::<T>(vm, PropertyKind::Value)
+}
+
+// https://webidl.spec.whatwg.org/#js-map-forEach
+pub(crate) fn map_for_each<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "forEach" and type "method".
+ let (wrapper, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ let map = implementation.map_entries(&cx);
+
+ // 3. Let callbackFn be the first argument passed to the function, or undefined if not supplied.
+ // 4. If IsCallable(callbackFn) is false, throw a TypeError.
+ let callback = vm.argument(0);
+ if !callback.is_function() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&callback]);
+ }
+
+ // 5. Let thisArg be the second argument passed to the function, or undefined if not supplied.
+ let this_arg = vm.argument(1);
+
+ // 6. For each key → value of map:
+ let iterator = map.begin();
+ while !iterator.is_end() {
+ // 1. Let jsKey be key converted to a JavaScript value.
+ // 2. Let jsValue be value converted to a JavaScript value.
+ let entry = iterator.current();
+
+ // 3. Perform ? Call(callbackFn, thisArg, « jsValue, jsKey, O »).
+ call(
+ vm,
+ callback,
+ this_arg,
+ &[entry.value, entry.key, Value::from_object(wrapper)],
+ )?;
+ iterator.advance();
+ }
+
+ // 7. Return undefined.
+ Ok(Value::UNDEFINED)
+}
+
+/// The map entries of the this value, and the key argument converted to the key type and back to a JS value.
+fn entries_and_key<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<(Gc<Map>, Value)> {
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+ let map = implementation.map_entries(&cx);
+ let key = to_dom_string(vm, vm.argument(0))?;
+ Ok((map, key.to_js(&cx)?))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-get
+pub(crate) fn map_get<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "get" and type "method".
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ // 3. Let keyType be the key type specified in the maplike declaration.
+ // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let key be keyArg converted to an IDL value of type keyType.
+ let (map, key) = entries_and_key::<T>(vm)?;
+
+ // 7. If map[key] exists, then return map[key], converted to a JavaScript value.
+ // 8. Return undefined.
+ Ok(map.map_get(key).unwrap_or(Value::UNDEFINED))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-has
+pub(crate) fn map_has<T: Maplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "has" and type "method".
+ // 2. Let map be the map entries of the IDL value that represents a reference to O.
+ // 3. Let keyType be the key type specified in the maplike declaration.
+ // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let key be keyArg converted to an IDL value of type keyType.
+ let (map, key) = entries_and_key::<T>(vm)?;
+
+ // 7. If map[key] exists, then return true, otherwise return false.
+ Ok(Value::from_bool(map.map_has(key)))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-set
+pub(crate) fn map_set<T: MaplikeDeclaration + WritableMaplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "set" and type "method".
+ let (wrapper, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Let keyType be the key type specified in the maplike declaration, and valueType be the value type.
+ // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let key be keyArg converted to an IDL value of type keyType.
+ let key = to_dom_string(vm, vm.argument(0))?;
+
+ // 7. Let valueArg be the second argument passed to this function, or undefined if not supplied.
+ // 8. Let value be valueArg converted to an IDL value of type valueType.
+ let value = vm.argument(1);
+ T::check_value(vm, value)?;
+
+ // 9. Set map[key] to value.
+ implementation.map_set(&cx, key, value);
+
+ // 10. Return O.
+ Ok(Value::from_object(wrapper))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-delete
+pub(crate) fn map_delete<T: WritableMaplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "delete" and type "method".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Let keyType be the key type specified in the maplike declaration.
+ // 4. Let keyArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let key be keyArg converted to an IDL value of type keyType.
+ let key = to_dom_string(vm, vm.argument(0))?;
+
+ // 7. Let retVal be true if map[key] exists, or else false.
+ // 8. Remove map[key].
+ // 9. Return retVal.
+ Ok(Value::from_bool(implementation.map_remove(&cx, &key)))
+}
+
+// https://webidl.spec.whatwg.org/#js-map-clear
+pub(crate) fn map_clear<T: WritableMaplike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "clear" and type "method".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Clear map.
+ // NOTE: The map is preserved because there may be existing iterators, currently suspended, iterating over it.
+ implementation.map_clear(&cx);
+
+ // 4. Return undefined.
+ Ok(Value::UNDEFINED)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
index 3ef529468a9..c870dbafa57 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs
@@ -28,9 +28,11 @@ pub(crate) mod generated;
pub(crate) mod global_object;
pub(crate) mod interface;
pub(crate) mod iterable;
+pub(crate) mod maplike;
pub(crate) mod promise;
pub(crate) mod realm_data;
pub(crate) mod services;
+pub(crate) mod setlike;
pub(crate) mod structured_data;
pub(crate) mod transport;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs
new file mode 100644
index 00000000000..4f075a06871
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The setlike declarations of the interfaces implemented in Rust, https://webidl.spec.whatwg.org/#idl-setlike
+
+use core::cell::RefCell;
+
+use libjs_rust::api::{
+ Attribute, ErrorKind, ErrorType, Gc, GcWeak, Object, PropertyAttributes, PropertyKey, PropertyKind,
+ RawNativeFunctionPointer, Realm, Set, SetIterator, ThrowCompletionOr, Trace, Value, Vm, call,
+};
+
+use crate::bindings::CallContext;
+use crate::bindings::interface::{Interface, Ref, define_attribute, define_operation, implementation_of, this_object};
+use crate::bindings::realm_data::{WrapperWorld, wrapper_world_of};
+
+/// The JS collection of an object in each wrapper world that asked for it, as the entries of a collection hold the
+/// wrappers of one world. Nothing keeps a collection alive here, so the next use creates it again if it is collected.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WorldEntries<T: 'static> {
+ #[gc(untraced)]
+ entries: RefCell<Vec<(WrapperWorld, GcWeak<T>)>>,
+}
+
+impl<T> Default for WorldEntries<T> {
+ fn default() -> Self {
+ Self {
+ entries: RefCell::new(Vec::new()),
+ }
+ }
+}
+
+impl<T> WorldEntries<T> {
+ /// The collection of the wrapper world of the call, which `create` makes if there is none.
+ pub(crate) fn get_or_create(&self, cx: &CallContext, create: impl FnOnce() -> Gc<T>) -> Gc<T> {
+ let wrapper_world = wrapper_world_of(cx.vm(), cx.realm());
+ self.entries.borrow_mut().retain(|(_, entries)| entries.get().is_some());
+ let existing = self
+ .entries
+ .borrow()
+ .iter()
+ .find(|(world, _)| *world == wrapper_world)
+ .and_then(|(_, entries)| entries.get());
+ if let Some(entries) = existing {
+ return entries;
+ }
+ let entries = create();
+ self.entries
+ .borrow_mut()
+ .push((wrapper_world, GcWeak::new(cx.vm().heap(), entries)));
+ entries
+ }
+
+ /// The live collections, which the caller updates when the object changes.
+ pub(crate) fn live(&self) -> Vec<Gc<T>> {
+ self.entries
+ .borrow()
+ .iter()
+ .filter_map(|(_, entries)| entries.get())
+ .collect()
+ }
+}
+
+/// What the implementation of an interface with a setlike declaration implements.
+pub(crate) trait Setlike: Interface {
+ // https://webidl.spec.whatwg.org/#dfn-set-entries
+ fn set_entries(&self, cx: &CallContext) -> Gc<Set>;
+}
+
+/// What the implementation of an interface with a read-write setlike declaration implements, for the operations that
+/// the interface does not declare itself. The value is one that the bindings converted to the value type.
+pub(crate) trait WritableSetlike: Setlike {
+ fn set_add(&self, cx: &CallContext, value: Value);
+ fn set_remove(&self, cx: &CallContext, value: Value) -> bool;
+ fn set_clear(&self, cx: &CallContext);
+}
+
+/// What the generated bindings of an interface with a setlike declaration define.
+pub(crate) trait SetlikeDeclaration: Setlike {
+ /// Throws unless the JS value converts to the value type of the declaration.
+ fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()>;
+}
+
+/// Defines the properties that every setlike declaration has, https://webidl.spec.whatwg.org/#es-setlike
+#[expect(clippy::too_many_arguments, reason = "these are the functions of the declaration")]
+pub(crate) fn define_setlike_properties(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ prototype: Gc<Object>,
+ size: RawNativeFunctionPointer,
+ entries: RawNativeFunctionPointer,
+ for_each: RawNativeFunctionPointer,
+ has: RawNativeFunctionPointer,
+ values: RawNativeFunctionPointer,
+) {
+ define_attribute(vm, realm, prototype, "size", size, None);
+ define_operation(vm, realm, prototype, "entries", entries, 0);
+ define_operation(vm, realm, prototype, "keys", values, 0);
+ define_operation(vm, realm, prototype, "values", values, 0);
+ prototype.define_direct_property(
+ vm,
+ &PropertyKey::from(vm.well_known_symbols().iterator),
+ prototype.get_without_side_effects(vm, &PropertyKey::from_utf8("values")),
+ PropertyAttributes::new(Attribute::CONFIGURABLE | Attribute::WRITABLE),
+ );
+ define_operation(vm, realm, prototype, "forEach", for_each, 1);
+ define_operation(vm, realm, prototype, "has", has, 1);
+}
+
+fn this_implementation<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<(Gc<Object>, Ref<T>, CallContext<'_>)> {
+ let (wrapper, realm) = this_object(vm, T::wrapper_class(), T::NAME)?;
+ Ok((wrapper, implementation_of(wrapper), CallContext::new(vm, realm)))
+}
+
+// https://webidl.spec.whatwg.org/#js-set-size
+pub(crate) fn set_size<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "size" and type "getter".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 2. Let set be the set entries of the IDL value that represents a reference to O.
+ let set = implementation.set_entries(&cx);
+
+ // 3. Return set's size, converted to a JavaScript value.
+ Ok(Value::from_f64(set.set_size() as f64))
+}
+
+fn create_set_iterator<T: Setlike>(vm: &Vm, kind: PropertyKind) -> ThrowCompletionOr<Value> {
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+ let set = implementation.set_entries(&cx);
+ Ok(Value::from_object(
+ SetIterator::create(vm, cx.realm(), set, kind).upcast::<Object>(),
+ ))
+}
+
+// https://webidl.spec.whatwg.org/#js-set-entries
+pub(crate) fn set_iterator_entries<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "entries" and type "method".
+ // 2. Let set be the set entries of the IDL value that represents a reference to O.
+ // 3. Return the result of creating a set iterator from set with kind "key+value".
+ create_set_iterator::<T>(vm, PropertyKind::KeyAndValue)
+}
+
+// https://webidl.spec.whatwg.org/#js-set-values
+pub(crate) fn set_iterator_values<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "values" and type "method".
+ // 2. Let set be the set entries of the IDL value that represents a reference to O.
+ // 3. Return the result of creating a set iterator from set with kind "value".
+ create_set_iterator::<T>(vm, PropertyKind::Value)
+}
+
+// https://webidl.spec.whatwg.org/#js-set-forEach
+pub(crate) fn set_for_each<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "forEach" and type "method".
+ let (wrapper, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 2. Let set be the set entries of the IDL value that represents a reference to O.
+ let set = implementation.set_entries(&cx);
+
+ // 3. Let callbackFn be the first argument passed to the function, or undefined if not supplied.
+ // 4. If IsCallable(callbackFn) is false, throw a TypeError.
+ let callback = vm.argument(0);
+ if !callback.is_function() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&callback]);
+ }
+
+ // 5. Let thisArg be the second argument passed to the function, or undefined if not supplied.
+ let this_arg = vm.argument(1);
+
+ // 6. For each value of set:
+ let iterator = set.begin();
+ while !iterator.is_end() {
+ // 1. Let jsValue be value converted to a JavaScript value.
+ let value = iterator.current();
+
+ // 2. Perform ? Call(callbackFn, thisArg, « jsValue, jsValue, O»).
+ call(vm, callback, this_arg, &[value, value, Value::from_object(wrapper)])?;
+ iterator.advance();
+ }
+
+ // 7. Return undefined.
+ Ok(Value::UNDEFINED)
+}
+
+// https://webidl.spec.whatwg.org/#js-set-has
+pub(crate) fn set_has<T: SetlikeDeclaration>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "has" and type "method".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 2. Let set be the set entries of the IDL value that represents a reference to O.
+ let set = implementation.set_entries(&cx);
+
+ // 3. Let valueType be the value type specified in the setlike declaration.
+ // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let value be valueArg converted to an IDL value of type valueType.
+ let value = vm.argument(0);
+ T::check_value(vm, value)?;
+
+ // 7. If set contains value, then return true, otherwise return false.
+ Ok(Value::from_bool(set.set_has(value)))
+}
+
+// https://webidl.spec.whatwg.org/#js-set-add
+pub(crate) fn set_add<T: SetlikeDeclaration + WritableSetlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "add" and type "method".
+ let (wrapper, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Let valueType be the value type specified in the setlike declaration.
+ // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let value be valueArg converted to an IDL value of type valueType.
+ let value = vm.argument(0);
+ T::check_value(vm, value)?;
+
+ // 7. If set does not contain value, then append value to set.
+ implementation.set_add(&cx, value);
+
+ // 8. Return O.
+ Ok(Value::from_object(wrapper))
+}
+
+// https://webidl.spec.whatwg.org/#js-set-delete
+pub(crate) fn set_delete<T: SetlikeDeclaration + WritableSetlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "delete" and type "method".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Let valueType be the value type specified in the setlike declaration.
+ // 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.
+ // 5. Let value be valueArg converted to an IDL value of type valueType.
+ let value = vm.argument(0);
+ T::check_value(vm, value)?;
+
+ // 7. Let retVal be true if set contains value, or else false.
+ // 8. Remove value from set.
+ // 9. Return retVal.
+ Ok(Value::from_bool(implementation.set_remove(&cx, value)))
+}
+
+// https://webidl.spec.whatwg.org/#js-set-clear
+pub(crate) fn set_clear<T: WritableSetlike>(vm: &Vm) -> ThrowCompletionOr<Value> {
+ // 1. Let O be the this value, implementation-checked against A with identifier "clear" and type "method".
+ let (_, implementation, cx) = this_implementation::<T>(vm)?;
+
+ // 3. Empty set.
+ implementation.set_clear(&cx);
+
+ // 4. Return undefined.
+ Ok(Value::UNDEFINED)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index 394f2e71de3..0ecf1265c7c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -57,6 +57,7 @@ use super::css_transform_value::CSSTransformValue;
use super::css_unit_value::CSSUnitValue;
use super::css_unparsed_value::CSSUnparsedValue;
use super::font_face_set_load_event::{FontFaceSetLoadEvent, FontFaceSetLoadEventInit};
+use super::highlight_registry::HighlightRegistry;
use super::media_list::MediaList;
use super::media_query_list::MediaQueryList;
use super::screen::Screen;
@@ -537,6 +538,18 @@ pub unsafe extern "C" fn web_font_face_set_load_event_create(
.as_ptr()
}
+/// A new HighlightRegistry of the document.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `document` a live Document.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_highlight_registry_create(vm: *mut c_void, document: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live Document.
+ let (vm, document) = unsafe { (vm_from_abi(vm), CppCell::from_raw(document)) };
+ cell_into_abi(HighlightRegistry::create(vm, document))
+}
+
/// A new StylePropertyMap of the declaration.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs b/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs
new file mode 100644
index 00000000000..34338cd897e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Highlight, https://drafts.csswg.org/css-highlight-api-1/#highlight
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+use std::collections::HashSet;
+
+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Object, Set, Trace, Value};
+
+use super::css_rule::wrap_cpp_cell;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::setlike::{Setlike, WorldEntries, WritableSetlike};
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_abstract_range_of_wrapper(wrapper: *mut c_void) -> *mut c_void;
+}
+
+/// The enumeration HighlightType of CSS/Highlight.idl.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum HighlightType {
+ Highlight,
+ SpellingError,
+ GrammarError,
+}
+
+/// The AbstractRange that a JS value of the value type of the setlike declaration wraps.
+fn range_of_value(value: Value) -> CppCell {
+ // SAFETY: The bindings checked that the value is a wrapper of an AbstractRange.
+ unsafe { CppCell::from_raw(web_css_abstract_range_of_wrapper(value.as_object().as_ptr().cast())) }
+}
+
+fn range_wrapper(cx: &CallContext, range: &CppCell) -> Value {
+ Value::from_object(wrap_cpp_cell(cx, range).wrapper())
+}
+
+/// The call context of the realm that a collection of a wrapper world lives in.
+fn context_of_set<'vm>(cx: &CallContext<'vm>, set: Gc<Set>) -> CallContext<'vm> {
+ CallContext::new(cx.vm(), set.upcast::<Object>().shape().realm())
+}
+
+// https://drafts.csswg.org/css-highlight-api-1/#highlight
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Highlight {
+ /// The set entries of this setlike object, in insertion order.
+ ranges: GcRefCell<Vec<CppCell>>,
+ /// The addresses of the ranges, to find one without a walk over all of them.
+ #[gc(untraced)]
+ range_addresses: RefCell<HashSet<usize>>,
+ #[gc(untraced)]
+ priority: Cell<i32>,
+ #[gc(untraced)]
+ highlight_type: Cell<HighlightType>,
+ set_entries: WorldEntries<Set>,
+}
+
+impl Wrappable for Highlight {}
+
+impl Highlight {
+ // https://drafts.csswg.org/css-highlight-api-1/#dom-highlight-highlight
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ initial_ranges: MarkedVec<'_, CppInterface>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // 1. Let highlight be the new Highlight object.
+ // 2. Set highlight’s priority to 0.
+ // 3. Set highlight’s type to highlight.
+ let highlight = allocate(cx.vm(), |_| Self {
+ ranges: GcRefCell::new(Vec::new()),
+ range_addresses: RefCell::new(HashSet::new()),
+ priority: Cell::new(0),
+ highlight_type: Cell::new(HighlightType::Highlight),
+ set_entries: WorldEntries::default(),
+ });
+
+ // 4. For each range of initialRanges, let rangeArg be the result of converting range to an ECMAScript value,
+ // then run the steps for a built-in setlike add function, with highlight as the this value, and rangeArg as
+ // the argument.
+ // NB: highlight has no wrapper yet, so there are no set entries in any world to update.
+ for range in initial_ranges.to_vec() {
+ highlight.add_range(cx, range_of_value(Value::from_object(range.wrapper())));
+ }
+
+ // 5. Return highlight.
+ Ok(highlight)
+ }
+
+ pub(crate) fn priority(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.priority.get())
+ }
+
+ pub(crate) fn set_priority(&self, _: &mut CallContext, priority: i32) -> WebIdlResult<()> {
+ self.priority.set(priority);
+ Ok(())
+ }
+
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<HighlightType> {
+ Ok(self.highlight_type.get())
+ }
+
+ pub(crate) fn set_type(&self, _: &mut CallContext, highlight_type: HighlightType) -> WebIdlResult<()> {
+ self.highlight_type.set(highlight_type);
+ Ok(())
+ }
+
+ /// The priority that sorts the results of highlightsFromPoint().
+ pub(crate) fn current_priority(&self) -> i32 {
+ self.priority.get()
+ }
+
+ /// The ranges of the highlight, in insertion order.
+ pub(crate) fn ranges(&self) -> Vec<CppCell> {
+ self.ranges.borrow().clone()
+ }
+
+ fn add_range(&self, cx: &CallContext, range: CppCell) -> bool {
+ if !self.range_addresses.borrow_mut().insert(range.as_ptr() as usize) {
+ return false;
+ }
+ self.ranges.borrow_mut(cx.vm()).push(range);
+ true
+ }
+}
+
+impl Setlike for Highlight {
+ fn set_entries(&self, cx: &CallContext) -> Gc<Set> {
+ self.set_entries.get_or_create(cx, || {
+ let set = Set::create(cx.vm(), cx.realm());
+ for range in self.ranges() {
+ set.set_add(cx.vm(), range_wrapper(cx, &range));
+ }
+ set
+ })
+ }
+}
+
+impl WritableSetlike for Highlight {
+ fn set_add(&self, cx: &CallContext, value: Value) {
+ let range = range_of_value(value);
+ if !self.add_range(cx, range.clone()) {
+ return;
+ }
+ for set in self.set_entries.live() {
+ set.set_add(cx.vm(), range_wrapper(&context_of_set(cx, set), &range));
+ }
+ // FIXME: https://drafts.csswg.org/css-highlight-api-1/#repaint
+ // The addition or removal of a range in a registered custom highlight must cause the user agent to
+ // reevaluate the rendering, and to repaint if appropriate. We do not paint custom highlights yet.
+ }
+
+ fn set_remove(&self, cx: &CallContext, value: Value) -> bool {
+ let range = range_of_value(value);
+ if !self.range_addresses.borrow_mut().remove(&(range.as_ptr() as usize)) {
+ return false;
+ }
+ self.ranges
+ .borrow_mut(cx.vm())
+ .retain(|existing| existing.as_ptr() != range.as_ptr());
+ for set in self.set_entries.live() {
+ set.set_remove(cx.vm(), range_wrapper(&context_of_set(cx, set), &range));
+ }
+ true
+ }
+
+ fn set_clear(&self, cx: &CallContext) {
+ self.range_addresses.borrow_mut().clear();
+ self.ranges.borrow_mut(cx.vm()).clear();
+ for set in self.set_entries.live() {
+ set.set_clear(cx.vm());
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs b/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs
new file mode 100644
index 00000000000..fb2068637b6
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! HighlightRegistry, https://drafts.csswg.org/css-highlight-api-1/#highlightregistry
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcRefCell, Map, MarkedVec, Object, Trace, Value, Vm};
+
+use super::css_rule::wrap_cpp_cell;
+use super::highlight::Highlight;
+use crate::bindings::conversions::{CppInterface, ToJs};
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, Wrappable, allocate, implementation_of, wrap};
+use crate::bindings::maplike::{Maplike, WritableMaplike};
+use crate::bindings::setlike::WorldEntries;
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_highlight_registry_point_is_in_viewport(document: *mut c_void, x: f32, y: f32) -> bool;
+ fn web_css_highlight_registry_shadow_root_at_point(document: *mut c_void, x: f32, y: f32) -> *mut c_void;
+ fn web_css_highlight_registry_range_is_hit(range: *mut c_void, x: f32, y: f32) -> bool;
+ fn web_css_shadow_root_of_wrapper(wrapper: *mut c_void) -> *mut c_void;
+}
+
+/// The dictionary HighlightsFromPointOptions of CSS/HighlightRegistry.idl.
+pub(crate) struct HighlightsFromPointOptions<'vm> {
+ pub(crate) shadow_roots: MarkedVec<'vm, CppInterface>,
+}
+
+/// The dictionary HighlightHitResult of CSS/HighlightRegistry.idl.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct HighlightHitResult {
+ pub(crate) highlight: Option<Ref<Highlight>>,
+ pub(crate) ranges: Option<Vec<CppInterface>>,
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+struct RegisteredHighlight {
+ #[gc(untraced)]
+ name: Utf16String,
+ highlight: Ref<Highlight>,
+}
+
+// https://drafts.csswg.org/css-highlight-api-1/#highlightregistry
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct HighlightRegistry {
+ document: CppCell,
+ /// The map entries of this maplike object, in registration order.
+ highlights: GcRefCell<Vec<RegisteredHighlight>>,
+ map_entries: WorldEntries<Map>,
+}
+
+impl Wrappable for HighlightRegistry {}
+
+/// The call context of the realm that a collection of a wrapper world lives in.
+fn context_of_map<'vm>(cx: &CallContext<'vm>, map: Gc<Map>) -> CallContext<'vm> {
+ CallContext::new(cx.vm(), map.upcast::<Object>().shape().realm())
+}
+
+fn set_map_entry(cx: &CallContext, map: Gc<Map>, name: &Utf16String, highlight: Ref<Highlight>) {
+ let key = name.clone().to_js(cx).expect("a string converts to a JS value");
+ map.map_set(cx.vm(), key, Value::from_object(wrap(cx, highlight)));
+}
+
+impl HighlightRegistry {
+ pub(crate) fn create(vm: &Vm, document: CppCell) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ document,
+ highlights: GcRefCell::new(Vec::new()),
+ map_entries: WorldEntries::default(),
+ })
+ }
+
+ // https://drafts.csswg.org/css-highlight-api-1/#dom-highlightregistry-highlightsfrompoint
+ pub(crate) fn highlights_from_point<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ x: f32,
+ y: f32,
+ options: HighlightsFromPointOptions<'_>,
+ ) -> WebIdlResult<MarkedVec<'vm, HighlightHitResult>> {
+ let vm = cx.vm();
+ let results = MarkedVec::new(vm);
+ let document = self.document.as_ptr();
+
+ // 1. If any of the following are true, return the empty sequence:
+ // * x is negative
+ // * y is negative
+ // * x is greater than the viewport width excluding the size of a rendered scroll bar (if any)
+ // * y is greater than the viewport height excluding the size of a rendered scroll bar (if any)
+ // SAFETY: The document is live.
+ if !unsafe { web_css_highlight_registry_point_is_in_viewport(document, x, y) } {
+ return Ok(results);
+ }
+
+ // * The topmost box in the viewport in paint order that would be a target for hit testing at coordinates x,y
+ // when applying the transforms that apply to the descendants of the viewport, has an element associated to
+ // it that's in a shadow tree whose shadow root is not contained by options.shadowRoots.
+ // SAFETY: The document is live.
+ let shadow_root = unsafe { web_css_highlight_registry_shadow_root_at_point(document, x, y) };
+ if !shadow_root.is_null() {
+ let is_contained = options.shadow_roots.to_vec().iter().any(|allowed_shadow_root| {
+ // SAFETY: The bindings checked that the wrapper is that of a ShadowRoot.
+ unsafe { web_css_shadow_root_of_wrapper(allowed_shadow_root.wrapper().as_ptr().cast()) == shadow_root }
+ });
+ if !is_contained {
+ return Ok(results);
+ }
+ }
+
+ // 2. Otherwise, let results be an empty sequence.
+ // NB: The results stay in registration order in a MarkedVec, as they hold new wrappers, with the sort keys next
+ // to them.
+ let unsorted_results = MarkedVec::new(vm);
+ let mut sort_keys: Vec<(i32, usize)> = Vec::new();
+
+ // 3. For each Highlight highlight in this HighlightRegistry:
+ for (registration_index, entry) in self.highlights.borrow().clone().into_iter().enumerate() {
+ let highlight = entry.highlight;
+
+ // 1. Let result be a new HighlightHitResult with highlight set to highlight.
+ let ranges = MarkedVec::new(vm);
+
+ // 2. For each AbstractRange abstractRange in highlight:
+ for abstract_range in highlight.ranges() {
+ // 1. If abstractRange is an invalid StaticRange, then continue.
+ // 2. Let range be a new Range whose start node and end node are set to abstractRange’s start node and
+ // end node respectively, and start offset and end offset are set to abstractRange’s start offset
+ // and end offset respectively.
+ // 3. If the coordinates x,y fall inside at least one of the DOMRects returned by calling
+ // getClientRects() on range, then append abstractRange to result.ranges.
+ // SAFETY: The range is live.
+ if unsafe { web_css_highlight_registry_range_is_hit(abstract_range.as_ptr(), x, y) } {
+ ranges.push(wrap_cpp_cell(cx, &abstract_range));
+ }
+ }
+
+ // 3. If result.ranges is not empty, append result to results.
+ if !ranges.is_empty() {
+ sort_keys.push((highlight.current_priority(), registration_index));
+ unsorted_results.push(HighlightHitResult {
+ highlight: Some(highlight),
+ ranges: Some(ranges.to_vec()),
+ });
+ }
+ }
+
+ // 4. Sort results by descending order of priority of its HighlightHitResults' highlight attributes.
+ // NB: When two or more custom highlights have the same numerical priority, the one most recently registered has
+ // the higher effective priority.
+ let mut order: Vec<usize> = (0..sort_keys.len()).collect();
+ order.sort_by_key(|index| {
+ let (priority, registration_index) = sort_keys[*index];
+ (core::cmp::Reverse(priority), core::cmp::Reverse(registration_index))
+ });
+
+ // 5. Return results.
+ for index in order {
+ results.push(unsorted_results.get(index).expect("the index is in the results"));
+ }
+ Ok(results)
+ }
+}
+
+impl Maplike for HighlightRegistry {
+ fn map_entries(&self, cx: &CallContext) -> Gc<Map> {
+ self.map_entries.get_or_create(cx, || {
+ let map = Map::create(cx.vm(), cx.realm());
+ for entry in self.highlights.borrow().clone() {
+ set_map_entry(cx, map, &entry.name, entry.highlight);
+ }
+ map
+ })
+ }
+}
+
+impl WritableMaplike for HighlightRegistry {
+ fn map_set(&self, cx: &CallContext, key: Utf16String, value: Value) {
+ // FIXME: https://drafts.csswg.org/css-highlight-api-1/#repaint
+ // The addition or removal of a custom highlight in the highlight registry must cause the user agent to
+ // reevaluate the rendering, and to repaint if appropriate. We do not paint custom highlights yet.
+ let highlight = implementation_of::<Highlight>(value.as_object());
+ {
+ let mut highlights = self.highlights.borrow_mut(cx.vm());
+ match highlights.iter_mut().find(|entry| entry.name == key) {
+ Some(entry) => entry.highlight = highlight,
+ None => highlights.push(RegisteredHighlight {
+ name: key.clone(),
+ highlight,
+ }),
+ }
+ }
+ for map in self.map_entries.live() {
+ set_map_entry(&context_of_map(cx, map), map, &key, highlight);
+ }
+ }
+
+ fn map_remove(&self, cx: &CallContext, key: &Utf16String) -> bool {
+ let position = self.highlights.borrow().iter().position(|entry| entry.name == *key);
+ let Some(position) = position else {
+ return false;
+ };
+ self.highlights.borrow_mut(cx.vm()).remove(position);
+ for map in self.map_entries.live() {
+ let key = key.clone().to_js(cx).expect("a string converts to a JS value");
+ map.map_remove(cx.vm(), key);
+ }
+ true
+ }
+
+ fn map_clear(&self, cx: &CallContext) {
+ self.highlights.borrow_mut(cx.vm()).clear();
+ for map in self.map_entries.live() {
+ map.map_clear(cx.vm());
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index e72fcfe75d4..120299647d2 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -65,6 +65,8 @@ pub(crate) mod css_unparsed_value;
pub(crate) mod css_variable_reference_value;
pub(crate) mod exports;
pub(crate) mod font_face_set_load_event;
+pub(crate) mod highlight;
+pub(crate) mod highlight_registry;
pub(crate) mod media_list;
pub(crate) mod media_query_list;
pub(crate) mod media_query_list_event;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index e4af3cbafbe..12c96e338c9 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -109,7 +109,6 @@ set(SOURCES
CSS/FontResolution.cpp
CSS/FontFaceSet.cpp
CSS/Frequency.cpp
- CSS/Highlight.cpp
CSS/HighlightRegistry.cpp
CSS/HypotheticalElement.cpp
CSS/Invalidation/AdoptedStyleSheetInvalidator.cpp
diff --git a/Libraries/LibWeb/CSS/BindingsGlue.h b/Libraries/LibWeb/CSS/BindingsGlue.h
index 5711782695a..3354233ab90 100644
--- a/Libraries/LibWeb/CSS/BindingsGlue.h
+++ b/Libraries/LibWeb/CSS/BindingsGlue.h
@@ -29,8 +29,6 @@ class CSSFontFeatureValuesMap;
class FontFace;
class FontFaceState;
class FontFaceSet;
-class Highlight;
-class HighlightRegistry;
}
@@ -57,18 +55,4 @@ WEB_API void did_add_font_face(CSS::FontFaceSet const&, NonnullRefPtr<CSS::FontF
WEB_API void did_remove_font_face(CSS::FontFaceSet const&, NonnullRefPtr<CSS::FontFaceState>);
WEB_API void did_reorder_font_faces(CSS::FontFaceSet const&, Vector<NonnullRefPtr<CSS::FontFaceState>> const&);
-WEB_API GC::Ref<JS::Set> setlike_entries(JS::Realm&, WrapperWorld const&, CSS::Highlight const&);
-WEB_API bool setlike_has(CSS::Highlight const&, JS::Value);
-WEB_API void setlike_add(CSS::Highlight&, JS::Value);
-WEB_API bool setlike_remove(CSS::Highlight&, JS::Value);
-WEB_API void setlike_clear(CSS::Highlight&);
-WEB_API void setlike_on_set_modified_from_js(CSS::Highlight&);
-
-WEB_API GC::Ref<JS::Map> map_entries(JS::Realm&, CSS::HighlightRegistry&);
-WEB_API Optional<JS::Value> map_get(JS::Realm&, CSS::HighlightRegistry&, Utf16View key);
-WEB_API bool map_has(CSS::HighlightRegistry&, Utf16View key);
-WEB_API bool map_remove(CSS::HighlightRegistry&, Utf16View key);
-WEB_API void map_clear(CSS::HighlightRegistry&);
-WEB_API WebIDL::ExceptionOr<void> set(JS::Realm&, CSS::HighlightRegistry&, Utf16String const& key, JS::Value);
-
}
diff --git a/Libraries/LibWeb/CSS/Highlight.cpp b/Libraries/LibWeb/CSS/Highlight.cpp
deleted file mode 100644
index 458fb8b8513..00000000000
--- a/Libraries/LibWeb/CSS/Highlight.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Set.h>
-#include <LibWeb/Bindings/Highlight.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/CSS/BindingsGlue.h>
-#include <LibWeb/CSS/Highlight.h>
-#include <LibWeb/DOM/AbstractRange.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(Highlight);
-
-// https://drafts.csswg.org/css-highlight-api-1/#dom-highlight-highlight
-GC::Ref<Highlight> Highlight::construct_impl(GC::RootVector<GC::Ref<DOM::AbstractRange>> const& initial_ranges)
-{
- // 1. Let highlight be the new Highlight object.
- auto highlight = GC::Heap::the().allocate<Highlight>();
-
- // 2. Set highlight’s priority to 0.
- highlight->m_priority = 0;
-
- // 3. Set highlight’s type to highlight.
- highlight->m_type = HighlightType::Highlight;
-
- // 4. For each range of initialRanges, let rangeArg be the result of converting range to an ECMAScript value,
- // then run the steps for a built-in setlike add function, with highlight as the this value, and rangeArg as
- // the argument.
- // NB: highlight has no wrapper yet, so there are no set entries in any world to update.
- for (auto range : initial_ranges)
- highlight->add_range(range);
-
- // 5. Return highlight.
- return highlight;
-}
-
-Highlight::Highlight() = default;
-
-void Highlight::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto range : m_ranges)
- visitor.visit(range);
-}
-
-bool Highlight::has_range(DOM::AbstractRange& range) const
-{
- return m_ranges.contains(GC::Ref { range });
-}
-
-void Highlight::add_range(GC::Ref<DOM::AbstractRange> range)
-{
- m_ranges.set(range, AK::HashSetExistingEntryBehavior::Keep);
-}
-
-bool Highlight::remove_range(DOM::AbstractRange& range)
-{
- return m_ranges.remove(GC::Ref { range });
-}
-
-void Highlight::clear_ranges()
-{
- m_ranges.clear();
-}
-
-}
-
-namespace Web::Bindings {
-
-static WrapperWorldWeakValueCacheMap<CSS::Highlight const, JS::Set>& highlight_set_caches()
-{
- static NeverDestroyed<WrapperWorldWeakValueCacheMap<CSS::Highlight const, JS::Set>> caches;
- return *caches;
-}
-
-static WrapperWorldWeakValueCache<JS::Set>& highlight_set_cache_for(CSS::Highlight const& highlight)
-{
- return highlight_set_caches().cache_for(highlight);
-}
-
-static DOM::AbstractRange& range_from_set_value(JS::Value value)
-{
- auto* range = Bindings::impl_from<DOM::AbstractRange>(&value.as_object());
- VERIFY(range);
- return *range;
-}
-
-static JS::Value wrap_range(JS::Realm& realm, DOM::AbstractRange& range)
-{
- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { range });
-}
-
-GC::Ref<JS::Set> setlike_entries(JS::Realm& realm, WrapperWorld const& wrapper_world, CSS::Highlight const& highlight)
-{
- auto& cache = highlight_set_cache_for(highlight);
- if (auto set_entries = cache.get(wrapper_world))
- return *set_entries;
-
- auto set_entries = GC::make_root(JS::Set::create(realm));
- for (auto range : highlight.ranges())
- set_entries->set_add(wrap_range(realm, *range));
- cache.set(wrapper_world, set_entries.ptr());
- return GC::Ref { *set_entries };
-}
-
-bool setlike_has(CSS::Highlight const& highlight, JS::Value value)
-{
- return highlight.has_range(range_from_set_value(value));
-}
-
-void setlike_add(CSS::Highlight& highlight, JS::Value value)
-{
- auto& range = range_from_set_value(value);
- highlight.add_range(range);
- highlight_set_cache_for(highlight).for_each([&](auto& set_entries) {
- set_entries.set_add(wrap_range(HTML::relevant_realm(set_entries), range));
- });
-}
-
-bool setlike_remove(CSS::Highlight& highlight, JS::Value value)
-{
- auto& range = range_from_set_value(value);
- auto removed = highlight.remove_range(range);
- if (removed) {
- highlight_set_cache_for(highlight).for_each([&](auto& set_entries) {
- set_entries.set_remove(wrap_range(HTML::relevant_realm(set_entries), range));
- });
- }
- return removed;
-}
-
-void setlike_clear(CSS::Highlight& highlight)
-{
- highlight.clear_ranges();
- highlight_set_cache_for(highlight).for_each([&](auto& set_entries) {
- set_entries.set_clear();
- });
-}
-
-void setlike_on_set_modified_from_js(CSS::Highlight&)
-{
- // FIXME: https://drafts.csswg.org/css-highlight-api-1/#repaint
- // The addition or removal of a range in a registered custom highlight must cause the user agent to
- // reevaluate the rendering, and to repaint if appropriate. We do not paint custom highlights yet.
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/Highlight.h b/Libraries/LibWeb/CSS/Highlight.h
deleted file mode 100644
index 830b24af7db..00000000000
--- a/Libraries/LibWeb/CSS/Highlight.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/HashTable.h>
-#include <LibGC/RootVector.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWebCommon/Bindings/Highlight.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::CSS {
-
-using HighlightType = Bindings::HighlightType;
-
-// https://drafts.csswg.org/css-highlight-api-1/#highlight
-class WEB_API Highlight final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Highlight, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Highlight);
-
-public:
- static GC::Ref<Highlight> construct_impl(GC::RootVector<GC::Ref<DOM::AbstractRange>> const& initial_ranges);
- virtual ~Highlight() override = default;
-
- WebIDL::Long priority() const { return m_priority; }
- void set_priority(WebIDL::Long priority) { m_priority = priority; }
-
- HighlightType type() const { return m_type; }
- void set_type(HighlightType type) { m_type = type; }
-
- // The set entries of this setlike object, in insertion order.
- OrderedHashTable<GC::Ref<DOM::AbstractRange>> const& ranges() const { return m_ranges; }
- bool has_range(DOM::AbstractRange&) const;
- void add_range(GC::Ref<DOM::AbstractRange>);
- bool remove_range(DOM::AbstractRange&);
- void clear_ranges();
-
-private:
- Highlight();
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- OrderedHashTable<GC::Ref<DOM::AbstractRange>> m_ranges;
- WebIDL::Long m_priority { 0 };
- HighlightType m_type { HighlightType::Highlight };
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/Highlight.idl b/Libraries/LibWeb/CSS/Highlight.idl
index bc6ddab0d9b..99177d90b59 100644
--- a/Libraries/LibWeb/CSS/Highlight.idl
+++ b/Libraries/LibWeb/CSS/Highlight.idl
@@ -6,7 +6,7 @@ enum HighlightType {
};
// https://drafts.csswg.org/css-highlight-api-1/#highlight
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface Highlight {
constructor(AbstractRange... initialRanges);
setlike<AbstractRange>;
diff --git a/Libraries/LibWeb/CSS/HighlightRegistry.cpp b/Libraries/LibWeb/CSS/HighlightRegistry.cpp
index bff5ed0c444..b1cfb6f9f73 100644
--- a/Libraries/LibWeb/CSS/HighlightRegistry.cpp
+++ b/Libraries/LibWeb/CSS/HighlightRegistry.cpp
@@ -4,280 +4,112 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Map.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibWeb/Bindings/Highlight.h>
-#include <LibWeb/Bindings/HighlightRegistry.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/CSS/BindingsGlue.h>
-#include <LibWeb/CSS/Highlight.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/CSS/HighlightRegistry.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/StaticRange.h>
#include <LibWeb/DOM/Utils.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/Layout/RenderDocument.h>
#include <LibWeb/Painting/HitTestResult.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(HighlightRegistry);
+extern "C" {
-GC::Ref<HighlightRegistry> HighlightRegistry::create(DOM::Document& document)
-{
- return GC::Heap::the().allocate<HighlightRegistry>(document);
-}
-
-HighlightRegistry::HighlightRegistry(DOM::Document& document)
- : m_document(document)
-{
-}
-
-void HighlightRegistry::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_document);
- for (auto& entry : m_highlights)
- visitor.visit(entry.value);
-}
+// Defined in Bindings/Rust/src/css/exports.rs.
+void* web_highlight_registry_create(JSVM*, void* document);
-GC::Ptr<Highlight> HighlightRegistry::get_highlight(Utf16View name) const
-{
- auto highlight = m_highlights.get(Utf16String::from_utf16(name));
- if (!highlight.has_value())
- return {};
- return *highlight;
+// Declared in Bindings/Rust/src/css/highlight.rs and Bindings/Rust/src/css/highlight_registry.rs.
+void* web_css_abstract_range_of_wrapper(void* wrapper);
+void* web_css_shadow_root_of_wrapper(void* wrapper);
+bool web_css_highlight_registry_point_is_in_viewport(void* document, float x, float y);
+void* web_css_highlight_registry_shadow_root_at_point(void* document, float x, float y);
+bool web_css_highlight_registry_range_is_hit(void* abstract_range, float x, float y);
}
-bool HighlightRegistry::has_highlight(Utf16View name) const
-{
- return m_highlights.contains(Utf16String::from_utf16(name));
-}
-
-void HighlightRegistry::set_highlight(Utf16String name, GC::Ref<Highlight> highlight)
+GC::Ref<HighlightRegistry> HighlightRegistry::create(DOM::Document& document)
{
- // FIXME: https://drafts.csswg.org/css-highlight-api-1/#repaint
- // The addition or removal of a custom highlight in the highlight registry must cause the user agent to
- // reevaluate the rendering, and to repaint if appropriate. We do not paint custom highlights yet.
- m_highlights.set(move(name), highlight);
+ auto* registry = web_highlight_registry_create(JS::HostABI::vm_to_abi(JS::VM::the()), static_cast<GC::Cell*>(&document));
+ return GC::Ref { *static_cast<HighlightRegistry*>(registry) };
}
-bool HighlightRegistry::remove_highlight(Utf16View name)
+static DOM::Document& document_from_abi(void* document)
{
- return m_highlights.remove(Utf16String::from_utf16(name));
+ return *static_cast<DOM::Document*>(static_cast<GC::Cell*>(document));
}
-void HighlightRegistry::clear_highlights()
+void* web_css_abstract_range_of_wrapper(void* wrapper)
{
- m_highlights.clear();
+ auto* range = Bindings::impl_from<DOM::AbstractRange>(static_cast<JS::Object*>(wrapper));
+ VERIFY(range);
+ return static_cast<GC::Cell*>(range);
}
-static bool shadow_root_is_contained_by_options(DOM::ShadowRoot const& shadow_root, Bindings::HighlightsFromPointOptions const& options)
+void* web_css_shadow_root_of_wrapper(void* wrapper)
{
- for (auto const& allowed_shadow_root : options.shadow_roots) {
- if (allowed_shadow_root.ptr() == &shadow_root)
- return true;
- }
- return false;
+ auto* shadow_root = Bindings::impl_from<DOM::ShadowRoot>(static_cast<JS::Object*>(wrapper));
+ VERIFY(shadow_root);
+ return static_cast<GC::Cell*>(shadow_root);
}
-// https://drafts.csswg.org/css-highlight-api-1/#dom-highlightregistry-highlightsfrompoint
-GC::ConservativeVector<Bindings::HighlightHitResult> HighlightRegistry::highlights_from_point(float x, float y, Bindings::HighlightsFromPointOptions const& options)
+bool web_css_highlight_registry_point_is_in_viewport(void* raw_document, float x, float y)
{
- auto& document = *m_document;
-
- // 1. If any of the following are true, return the empty sequence:
- // * x is negative
- // * y is negative
- // * x is greater than the viewport width excluding the size of a rendered scroll bar (if any)
- // * y is greater than the viewport height excluding the size of a rendered scroll bar (if any)
// FIXME: This should account for the size of the scroll bar.
- auto viewport_rect = document.viewport_rect();
+ auto viewport_rect = document_from_abi(raw_document).viewport_rect();
CSSPixelPoint position { x, y };
- if (x < 0 || y < 0 || position.x() > viewport_rect.width() || position.y() > viewport_rect.height())
- return {};
-
- // * The topmost box in the viewport in paint order that would be a target for hit testing at coordinates x,y
- // when applying the transforms that apply to the descendants of the viewport, has an element associated to
- // it that's in a shadow tree whose shadow root is not contained by options.shadowRoots.
- {
- document.update_layout(DOM::UpdateLayoutReason::HighlightRegistryHighlightsFromPoint);
- Layout::ForcedReadScope read { document };
- GC::Ptr<DOM::Element> hit_element;
- (void)document.hit_test_all(read, position, [&](Painting::HitTestResult result) {
- auto* node = result.dom_node();
- if (!node)
- return TraversalDecision::Continue;
- hit_element = is<DOM::Element>(*node) ? static_cast<DOM::Element*>(node) : node->parent_element();
- return TraversalDecision::Break;
- });
- if (hit_element) {
- // AD-HOC: If the element is inside a UA internal shadow root, retarget to the host, as elementFromPoint()
- // does. UA internal shadow roots can never be passed in options.shadowRoots.
- hit_element = DOM::retarget_from_ua_internal_shadow_root(*hit_element);
- if (auto* shadow_root = as_if<DOM::ShadowRoot>(hit_element->root()); shadow_root && !shadow_root_is_contained_by_options(*shadow_root, options))
- return {};
- }
- }
-
- // 2. Otherwise, let results be an empty sequence.
- struct ResultWithRegistrationIndex {
- Bindings::HighlightHitResult result;
- WebIDL::Long priority;
- size_t registration_index;
- };
- GC::ConservativeVector<ResultWithRegistrationIndex> results;
-
- // 3. For each Highlight highlight in this HighlightRegistry:
- size_t registration_index = 0;
- for (auto const& entry : m_highlights) {
- auto highlight = entry.value;
-
- // 1. Let result be a new HighlightHitResult with highlight set to highlight.
- Bindings::HighlightHitResult result;
- result.highlight = highlight;
- GC::RootVector<GC::Ref<DOM::AbstractRange>> ranges;
-
- // 2. For each AbstractRange abstractRange in highlight:
- for (auto abstract_range : highlight->ranges()) {
- // 1. If abstractRange is an invalid StaticRange, then continue.
- if (auto* static_range = as_if<DOM::StaticRange>(*abstract_range); static_range && !static_range->is_valid())
- continue;
-
- // 2. Let range be a new Range whose start node and end node are set to abstractRange’s start node and end
- // node respectively, and start offset and end offset are set to abstractRange’s start offset and end
- // offset respectively.
- // OPTIMIZATION: A live Range already has these boundary points, so we use it instead of creating a new live
- // Range that every DOM mutation would have to update until it is collected.
- GC::Ptr<DOM::Range> range = as_if<DOM::Range>(*abstract_range);
- if (!range)
- range = DOM::Range::create(abstract_range->start_container(), abstract_range->start_offset(), abstract_range->end_container(), abstract_range->end_offset());
-
- // 3. If the coordinates x,y fall inside at least one of the DOMRects returned by calling getClientRects()
- // on range, then append abstractRange to result.ranges.
- // NB: A rect is treated as half-open, so that the empty rect of a collapsed range is never hit.
- auto client_rects = range->client_rects();
- auto is_hit = any_of(client_rects, [&](Gfx::DoubleRect const& rect) {
- return x >= rect.left() && x < rect.right() && y >= rect.top() && y < rect.bottom();
- });
- if (is_hit)
- ranges.append(abstract_range);
- }
-
- // 3. If result.ranges is not empty, append result to results.
- if (!ranges.is_empty()) {
- result.ranges = move(ranges);
- results.append({ move(result), highlight->priority(), registration_index });
- }
- ++registration_index;
- }
-
- // 4. Sort results by descending order of priority of its HighlightHitResults' highlight attributes.
- // NB: When two or more custom highlights have the same numerical priority, the one most recently registered has
- // the higher effective priority.
- quick_sort(results, [](auto const& a, auto const& b) {
- if (a.priority != b.priority)
- return a.priority > b.priority;
- return a.registration_index > b.registration_index;
+ return !(x < 0 || y < 0 || position.x() > viewport_rect.width() || position.y() > viewport_rect.height());
+}
+
+// The shadow root of the tree of the element of the topmost box at the point, if it is in a shadow tree.
+void* web_css_highlight_registry_shadow_root_at_point(void* raw_document, float x, float y)
+{
+ auto& document = document_from_abi(raw_document);
+ document.update_layout(DOM::UpdateLayoutReason::HighlightRegistryHighlightsFromPoint);
+ Layout::ForcedReadScope read { document };
+ GC::Ptr<DOM::Element> hit_element;
+ (void)document.hit_test_all(read, CSSPixelPoint { x, y }, [&](Painting::HitTestResult result) {
+ auto* node = result.dom_node();
+ if (!node)
+ return TraversalDecision::Continue;
+ hit_element = is<DOM::Element>(*node) ? static_cast<DOM::Element*>(node) : node->parent_element();
+ return TraversalDecision::Break;
});
+ if (!hit_element)
+ return nullptr;
- // 5. Return results.
- GC::ConservativeVector<Bindings::HighlightHitResult> sorted_results;
- sorted_results.ensure_capacity(results.size());
- for (auto& result : results)
- sorted_results.unchecked_append(move(result.result));
- return sorted_results;
+ // AD-HOC: If the element is inside a UA internal shadow root, retarget to the host, as elementFromPoint()
+ // does. UA internal shadow roots can never be passed in options.shadowRoots.
+ hit_element = DOM::retarget_from_ua_internal_shadow_root(*hit_element);
+ return static_cast<GC::Cell*>(as_if<DOM::ShadowRoot>(hit_element->root()));
}
-}
-
-namespace Web::Bindings {
-
-static WrapperWorldWeakValueCacheMap<CSS::HighlightRegistry, JS::Map>& highlight_registry_caches()
+bool web_css_highlight_registry_range_is_hit(void* raw_abstract_range, float x, float y)
{
- static NeverDestroyed<WrapperWorldWeakValueCacheMap<CSS::HighlightRegistry, JS::Map>> caches;
- return *caches;
-}
-
-static WrapperWorldWeakValueCache<JS::Map>& entries_cache_for(CSS::HighlightRegistry& registry)
-{
- return highlight_registry_caches().cache_for(registry);
-}
-
-static void set_map_entry(JS::Map& map_entries, Utf16View name, CSS::Highlight& highlight)
-{
- auto& map_realm = HTML::relevant_realm(map_entries);
- auto key = GC::make_root(JS::PrimitiveString::create(map_realm.vm(), name));
- JS::Value value = Bindings::wrap(Bindings::host_defined_wrapper_world(map_realm), map_realm, GC::Ref { highlight });
- map_entries.map_set(JS::Value { key.ptr() }, value);
-}
-
-static void remove_map_entry(JS::Map& map_entries, Utf16View name)
-{
- auto& map_realm = HTML::relevant_realm(map_entries);
- auto key = GC::make_root(JS::PrimitiveString::create(map_realm.vm(), name));
- map_entries.map_remove(JS::Value { key.ptr() });
-}
-
-GC::Ref<JS::Map> map_entries(JS::Realm& realm, CSS::HighlightRegistry& registry)
-{
- auto& wrapper_world = host_defined_wrapper_world(realm);
- auto& cache = entries_cache_for(registry);
- if (auto map_entries = cache.get(wrapper_world))
- return *map_entries;
-
- auto map_entries = GC::make_root(JS::Map::create(realm));
- for (auto const& entry : registry.highlights())
- set_map_entry(*map_entries, entry.key, *entry.value);
- cache.set(wrapper_world, map_entries.ptr());
- return GC::Ref { *map_entries };
-}
+ auto& abstract_range = *static_cast<DOM::AbstractRange*>(static_cast<GC::Cell*>(raw_abstract_range));
-Optional<JS::Value> map_get(JS::Realm& realm, CSS::HighlightRegistry& registry, Utf16View key)
-{
- auto highlight = registry.get_highlight(key);
- if (!highlight)
- return {};
- return JS::Value { Bindings::wrap(host_defined_wrapper_world(realm), realm, GC::Ref { *highlight }) };
-}
+ // 1. If abstractRange is an invalid StaticRange, then continue.
+ if (auto* static_range = as_if<DOM::StaticRange>(abstract_range); static_range && !static_range->is_valid())
+ return false;
-bool map_has(CSS::HighlightRegistry& registry, Utf16View key)
-{
- return registry.has_highlight(key);
-}
+ // 2. Let range be a new Range whose start node and end node are set to abstractRange’s start node and end
+ // node respectively, and start offset and end offset are set to abstractRange’s start offset and end
+ // offset respectively.
+ // OPTIMIZATION: A live Range already has these boundary points, so we use it instead of creating a new live
+ // Range that every DOM mutation would have to update until it is collected.
+ GC::Ptr<DOM::Range> range = as_if<DOM::Range>(abstract_range);
+ if (!range)
+ range = DOM::Range::create(abstract_range.start_container(), abstract_range.start_offset(), abstract_range.end_container(), abstract_range.end_offset());
-bool map_remove(CSS::HighlightRegistry& registry, Utf16View key)
-{
- auto removed = registry.remove_highlight(key);
- if (removed) {
- entries_cache_for(registry).for_each([&](auto& map_entries) {
- remove_map_entry(map_entries, key);
- });
- }
- return removed;
-}
-
-void map_clear(CSS::HighlightRegistry& registry)
-{
- registry.clear_highlights();
- entries_cache_for(registry).for_each([&](auto& map_entries) {
- map_entries.map_clear();
- });
-}
-
-WebIDL::ExceptionOr<void> set(JS::Realm&, CSS::HighlightRegistry& registry, Utf16String const& key, JS::Value value)
-{
- auto* highlight = Bindings::impl_from<CSS::Highlight>(&value.as_object());
- VERIFY(highlight);
- registry.set_highlight(key, *highlight);
- entries_cache_for(registry).for_each([&](auto& map_entries) {
- set_map_entry(map_entries, key, *highlight);
+ // 3. If the coordinates x,y fall inside at least one of the DOMRects returned by calling getClientRects()
+ // on range, then append abstractRange to result.ranges.
+ // NB: A rect is treated as half-open, so that the empty rect of a collapsed range is never hit.
+ return any_of(range->client_rects(), [&](Gfx::DoubleRect const& rect) {
+ return x >= rect.left() && x < rect.right() && y >= rect.top() && y < rect.bottom();
});
- return {};
}
}
diff --git a/Libraries/LibWeb/CSS/HighlightRegistry.h b/Libraries/LibWeb/CSS/HighlightRegistry.h
index eb9d1be636e..ee1a143c14b 100644
--- a/Libraries/LibWeb/CSS/HighlightRegistry.h
+++ b/Libraries/LibWeb/CSS/HighlightRegistry.h
@@ -6,42 +6,20 @@
#pragma once
-#include <AK/HashMap.h>
-#include <AK/Utf16String.h>
-#include <LibGC/ConservativeVector.h>
+#include <LibGC/Ptr.h>
#include <LibWeb/Bindings/HighlightRegistry.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
namespace Web::CSS {
// https://drafts.csswg.org/css-highlight-api-1/#highlightregistry
-class WEB_API HighlightRegistry final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(HighlightRegistry, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(HighlightRegistry);
+class WEB_API HighlightRegistry final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(HighlightRegistry, highlight_registry)
public:
[[nodiscard]] static GC::Ref<HighlightRegistry> create(DOM::Document&);
- virtual ~HighlightRegistry() override = default;
-
- // The map entries of this maplike object, in insertion order.
- OrderedHashMap<Utf16String, GC::Ref<Highlight>> const& highlights() const { return m_highlights; }
- GC::Ptr<Highlight> get_highlight(Utf16View name) const;
- bool has_highlight(Utf16View name) const;
- void set_highlight(Utf16String name, GC::Ref<Highlight>);
- bool remove_highlight(Utf16View name);
- void clear_highlights();
-
- GC::ConservativeVector<Bindings::HighlightHitResult> highlights_from_point(float x, float y, Bindings::HighlightsFromPointOptions const&);
-
-private:
- explicit HighlightRegistry(DOM::Document&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<DOM::Document> m_document;
- OrderedHashMap<Utf16String, GC::Ref<Highlight>> m_highlights;
};
}
diff --git a/Libraries/LibWeb/CSS/HighlightRegistry.idl b/Libraries/LibWeb/CSS/HighlightRegistry.idl
index 1a9bb066f11..de2bedec404 100644
--- a/Libraries/LibWeb/CSS/HighlightRegistry.idl
+++ b/Libraries/LibWeb/CSS/HighlightRegistry.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-highlight-api-1/#highlightregistry
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface HighlightRegistry {
maplike<DOMString, Highlight>;
};
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index c049f3bf6a3..3201a8d0531 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -296,7 +296,6 @@ class Frequency;
class FrequencyPercentage;
class FrequencyStyleValue;
class FunctionStyleValue;
-class Highlight;
class HighlightRegistry;
class HueRotateFilterStyleValue;
class ImageSetStyleValue;
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 7b16c78157d..867204d8701 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -672,6 +672,14 @@ def implementation_method_signatures(
f"impl PairIterable with Key = {key_type} and Value = {value_type}: "
"fn value_pairs_to_iterate_over(target: &Self::Target) -> impl Deref<Target = [(Self::Key, Self::Value)]> + '_"
)
+ if members.setlike is not None:
+ signatures.append("impl Setlike: fn set_entries(&self, cx: &CallContext) -> Gc<Set>")
+ if members.setlike.writable_operations:
+ signatures.append("impl WritableSetlike: fn set_add, fn set_remove, fn set_clear")
+ if members.maplike is not None:
+ signatures.append("impl Maplike: fn map_entries(&self, cx: &CallContext) -> Gc<Map>")
+ if members.maplike.writable_operations:
+ signatures.append("impl WritableMaplike: fn map_set, fn map_remove, fn map_clear")
if members.async_iterator is not None:
what = f"the asynchronously iterable declaration of {interface.name}"
parameters = parameter_list(what, members.async_iterator.parameters)
@@ -721,6 +729,88 @@ def pair_iterator_types(
)
+def write_rust_collection_declaration(
+ out: TextIO, context: GenerationContext, interface: Interface, members: RustMembers
+) -> None:
+ """The value check of the operations that the bindings define for a setlike or maplike declaration."""
+ what = f"the value type of the declaration of {interface.name}"
+ if members.setlike is not None:
+ conversion = rust_to_idl_value(members.setlike.value_type, {}, "value", "value", context, what)
+ out.write(
+ f"""
+ impl crate::bindings::setlike::SetlikeDeclaration for Implementation {{
+ fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()> {{
+ {conversion}?;
+ Ok(())
+ }}
+ }}
+"""
+ )
+ if members.maplike is not None and "set" in members.maplike.writable_operations:
+ conversion = rust_to_idl_value(members.maplike.value_type, {}, "value", "value", context, what)
+ out.write(
+ f"""
+ impl crate::bindings::maplike::MaplikeDeclaration for Implementation {{
+ fn check_value(vm: &Vm, value: Value) -> ThrowCompletionOr<()> {{
+ {conversion}?;
+ Ok(())
+ }}
+ }}
+"""
+ )
+
+
+def write_rust_collection_properties(out: TextIO, members: RustMembers, defined_property_names: list[str]) -> None:
+ """Defines the properties of a setlike or maplike declaration on the interface prototype object."""
+
+ def define_writable_operations(module: str, prefix: str, operations: list[str], lengths: dict[str, int]) -> None:
+ for name in operations:
+ out.write(
+ f' define_operation(vm, realm, prototype, "{name}", '
+ f"raw_native!(crate::bindings::{module}::{prefix}_{name}::<Implementation>), {lengths[name]});\n"
+ )
+ defined_property_names.extend(operations)
+
+ if members.setlike is not None:
+ out.write(
+ """ crate::bindings::setlike::define_setlike_properties(
+ vm,
+ realm,
+ prototype,
+ raw_native!(crate::bindings::setlike::set_size::<Implementation>),
+ raw_native!(crate::bindings::setlike::set_iterator_entries::<Implementation>),
+ raw_native!(crate::bindings::setlike::set_for_each::<Implementation>),
+ raw_native!(crate::bindings::setlike::set_has::<Implementation>),
+ raw_native!(crate::bindings::setlike::set_iterator_values::<Implementation>),
+ );
+"""
+ )
+ defined_property_names.extend(members.setlike.function_names)
+ define_writable_operations(
+ "setlike", "set", members.setlike.writable_operations, {"add": 1, "delete": 1, "clear": 0}
+ )
+ if members.maplike is not None:
+ out.write(
+ """ crate::bindings::maplike::define_maplike_properties(
+ vm,
+ realm,
+ prototype,
+ raw_native!(crate::bindings::maplike::map_size::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_iterator_entries::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_iterator_keys::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_iterator_values::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_for_each::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_get::<Implementation>),
+ raw_native!(crate::bindings::maplike::map_has::<Implementation>),
+ );
+"""
+ )
+ defined_property_names.extend(members.maplike.function_names)
+ define_writable_operations(
+ "maplike", "map", members.maplike.writable_operations, {"set": 2, "delete": 1, "clear": 0}
+ )
+
+
def write_rust_pair_iterator(out: TextIO, interface: Interface) -> None:
"""The classes of the default iterator objects of the interface, and the steps of its iterator prototype object,
which the bindings runtime implements for every interface with a pair iterator,
@@ -1053,6 +1143,8 @@ def write_rust_interface(
if members.pair_iterator is not None:
write_rust_pair_iterator(out, interface)
+ write_rust_collection_declaration(out, context, interface, members)
+
if members.async_iterator is not None:
write_rust_async_iterator(out, context, interface)
@@ -1138,6 +1230,7 @@ def write_rust_interface(
"""
)
defined_property_names.extend(members.pair_iterator.function_names)
+ write_rust_collection_properties(out, members, defined_property_names)
if members.async_iterator is not None:
out.write(
f""" define_async_iterator_properties(
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index 3d56d938c78..1aa722d4d43 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -215,6 +215,29 @@ class RustPairIterator:
function_names = ["entries", "forEach", "keys", "values"]
+@dataclass
+class RustSetlike:
+ """The setlike declaration of an interface, https://webidl.spec.whatwg.org/#idl-setlike. The names say which
+ operations of a read-write declaration the bindings define, as the interface can declare them itself."""
+
+ value_type: IDLType
+ writable_operations: list[str]
+
+ function_names = ["size", "entries", "values", "keys", "forEach", "has"]
+
+
+@dataclass
+class RustMaplike:
+ """The maplike declaration of an interface, whose keys are strings, https://webidl.spec.whatwg.org/#idl-maplike.
+ The names say which operations of a read-write declaration the bindings define, as the interface can declare them
+ itself."""
+
+ value_type: IDLType
+ writable_operations: list[str]
+
+ function_names = ["size", "entries", "keys", "values", "forEach", "get", "has"]
+
+
@dataclass
class RustAsyncIterator:
"""The value asynchronously iterable declaration of an interface, https://webidl.spec.whatwg.org/#idl-async-iterable,
@@ -266,6 +289,8 @@ class RustMembers:
indexed_property_getter: Optional[RustIndexedPropertyGetter] = None
indexed_property_setter: Optional[RustIndexedPropertySetter] = None
pair_iterator: Optional[RustPairIterator] = None
+ setlike: Optional[RustSetlike] = None
+ maplike: Optional[RustMaplike] = None
async_iterator: Optional[RustAsyncIterator] = None
constructors: List[RustConstructor] = field(default_factory=list)
constants: List[RustConstant] = field(default_factory=list)
@@ -292,6 +317,10 @@ class RustMembers:
names.append(self.indexed_property_getter.operation.operation.name)
if self.pair_iterator is not None:
names.extend(self.pair_iterator.function_names)
+ if self.setlike is not None:
+ names.extend(self.setlike.function_names + self.setlike.writable_operations)
+ if self.maplike is not None:
+ names.extend(self.maplike.function_names + self.maplike.writable_operations)
if self.async_iterator is not None:
names.append("values")
names.extend(constant.name for constant in self.constants)
@@ -344,8 +373,6 @@ def rust_members(interface: Interface) -> RustMembers:
]
if any(special_operations):
fail("it has special operations other than an indexed property getter and setter")
- if interface.maplike or interface.setlike:
- fail("it is a maplike or setlike")
if interface.async_iterable is not None and interface.async_iterable.key_type is not None:
fail("it has a pair asynchronously iterable declaration")
has_value_iterator = interface.iterable is not None and interface.iterable.key_type is None
@@ -360,6 +387,24 @@ def rust_members(interface: Interface) -> RustMembers:
if interface.iterable is not None and interface.iterable.key_type is not None:
members.pair_iterator = RustPairIterator(interface.iterable.key_type, interface.iterable.value_type)
+ def writable_operations(declaration, names: list[str]) -> list[str]:
+ """The operations of a read-write declaration that the interface does not declare itself."""
+ if declaration.readonly:
+ return []
+ declared = set(operation_overload_sets(interface))
+ return [name for name in names if name not in declared]
+
+ if interface.setlike is not None:
+ members.setlike = RustSetlike(
+ interface.setlike.value_type, writable_operations(interface.setlike, ["add", "delete", "clear"])
+ )
+ if interface.maplike is not None:
+ if interface.maplike.key_type.name not in ("DOMString", "CSSOMString"):
+ fail("its maplike declaration has keys that are not strings")
+ members.maplike = RustMaplike(
+ interface.maplike.value_type, writable_operations(interface.maplike, ["set", "delete", "clear"])
+ )
+
getter = interface.indexed_property_getter
if has_value_iterator and getter is None:
fail("it declares a value iterator and supports no indexed properties")
diff --git a/Meta/Generators/libweb_bindings/rust_to_js_value.py b/Meta/Generators/libweb_bindings/rust_to_js_value.py
index 6317aaf9377..cce5f655952 100644
--- a/Meta/Generators/libweb_bindings/rust_to_js_value.py
+++ b/Meta/Generators/libweb_bindings/rust_to_js_value.py
@@ -14,6 +14,7 @@ from Generators.libweb_bindings.rust_names import rust_identifier
from Generators.libweb_bindings.rust_names import rust_local_name
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
from Generators.libweb_bindings.rust_types import holds_cells
+from Generators.libweb_bindings.rust_types import is_sequence_of_cells
from Generators.libweb_bindings.rust_types import member_other_than_undefined
from Generators.libweb_bindings.rust_types import rust_dictionary_path
from Generators.libweb_bindings.rust_types import rust_enumeration_path
@@ -136,18 +137,28 @@ def write_dictionary_to_js(out: TextIO, context: GenerationContext, dictionary:
fields = []
keys = []
conversions = []
+ marked_sequences = []
for member in dictionary.members:
what = f"{dictionary.name}.{member.name}"
member_type = rust_type(member.type, context, what)
- if has_sequence_of_cells(member.type, context):
- # NB: A sequence is kept alive from where its conversion starts, which is after the object of the
- # dictionary is created and the members before this one are converted.
- raise UnsupportedByRustBindings(
- f"{what} has the type {member.type}, with a sequence of values that are or can hold cells, which the "
- "Rust bindings do not convert from a member of a dictionary yet"
- )
field = rust_identifier(member.name)
local = rust_local_name(member.name)
+ if has_sequence_of_cells(member.type, context):
+ if not is_sequence_of_cells(member.type, context):
+ raise UnsupportedByRustBindings(
+ f"{what} has the type {member.type}, with a nested sequence of values that are or can hold cells, "
+ "which the Rust bindings do not convert from a member of a dictionary yet"
+ )
+ # NB: The struct holds the sequence in a Vec, which hides it from the collector. It moves to a MarkedVec
+ # before the object of the dictionary is created, which is the first allocation of the conversion.
+ if member.required or member.default_value is not None:
+ marked_sequences.append(
+ f" let {local} = crate::bindings::conversions::mark_sequence(cx, &{local});\n"
+ )
+ else:
+ marked_sequences.append(
+ f" let {local} = {local}.map(|value| crate::bindings::conversions::mark_sequence(cx, &value));\n"
+ )
key = f"{rust_identifier(member.name).removeprefix('r#').rstrip('_').upper()}_KEY"
keys.append(
f' static {key}: LazyLock<PropertyKey> = LazyLock::new(|| PropertyKey::from_utf8("{member.name}"));\n'
@@ -175,7 +186,7 @@ def write_dictionary_to_js(out: TextIO, context: GenerationContext, dictionary:
{"".join(fields)} impl ToJs for {path} {{
fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {{
{"".join(keys)} let {path} {{ {bindings} }} = self;
- let object = create_dictionary_object(cx);
+{"".join(marked_sequences)} let object = create_dictionary_object(cx);
{"".join(conversions)} Ok(Value::from_object(object))
}}
}}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index a52364d8dcf..55c939d6222 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -36,7 +36,7 @@ CHECKED_SUFFIXES = {
# the same change. If it goes up, justify the architecture change here.
ALLOWED_REALM_MENTIONS = {
"Animations": (5, 14, "animation callbacks/events and CSS value materialization still pass spec-selected realms"),
- "CSS": (9, 24, "CSS Typed OM, parser-facing reification, style-value JS materialization, and setlike/maplike glue"),
+ "CSS": (7, 19, "CSS Typed OM, parser-facing reification, style-value JS materialization, and setlike/maplike glue"),
"Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),
"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),
"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),