Nacre/vendor/servo-script/dom/node/customelementregistry.rs
astar76 0ecfd0f573 S031: root due timers in vendored servo-script (R5-01 SIGSEGV), crash-adblock regression smoke
fire_timer moved due timers into an unrooted Vec; a GC inside one callback swept
the functions of the timers still waiting. Heavy-web reruns and cargo test still pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 20:38:47 -06:00

1777 lines
69 KiB
Rust

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::cell::Cell;
use std::collections::VecDeque;
use std::ffi::CStr;
use std::ptr::NonNull;
use std::rc::Rc;
use std::{mem, ptr};
use dom_struct::dom_struct;
use html5ever::{LocalName, Namespace, Prefix, ns};
use js::context::JSContext;
use js::conversions::{FromJSValConvertible, ToJSValConvertible};
use js::glue::UnwrapObjectStatic;
use js::jsapi::{HandleValueArray, Heap, IsCallable, IsConstructor, JSObject};
use js::jsval::{BooleanValue, JSVal, NullValue, ObjectValue, UndefinedValue};
use js::realm::{AutoRealm, CurrentRealm};
use js::rust::wrappers2::{Construct1, JS_GetProperty, SameValue};
use js::rust::{HandleObject, MutableHandleValue};
use rustc_hash::{FxBuildHasher, FxHashSet};
use script_bindings::callback::HasCallbackHolder;
use script_bindings::cell::DomRefCell;
use script_bindings::reflector::{DomObject, Reflector, reflect_dom_object_with_proto};
use script_bindings::settings_stack::{run_a_callback, run_a_script};
use style::attr::AttrValue;
use crate::DomTypeHolder;
use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::{
CustomElementConstructor, CustomElementRegistryMethods, ElementDefinitionOptions,
};
use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::conversions::{ConversionResult, StringificationBehavior, get_property};
use crate::dom::bindings::error::{
Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception,
};
use crate::dom::bindings::inheritance::{Castable, DocumentFragmentTypeId, NodeTypeId};
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{AsHandleValue, Dom, DomRoot, UnrootedDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::HashMapTracedValues;
use crate::dom::document::Document;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlelement::HTMLElement;
use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
use crate::dom::iterators::ShadowIncluding;
use crate::dom::node::{Node, NodeTraits};
use crate::dom::promise::Promise;
use crate::dom::shadowroot::ShadowRoot;
use crate::dom::window::Window;
use crate::dom::{RootedPromise, TracedPromise};
use crate::event_loop::script_thread::ScriptThread;
use crate::realms::enter_auto_realm;
use crate::runtime::job_queue::CustomElementReactionMicrotask;
/// <https://dom.spec.whatwg.org/#concept-element-custom-element-state>
#[derive(Clone, Copy, Default, Eq, JSTraceable, MallocSizeOf, PartialEq)]
pub(crate) enum CustomElementState {
Undefined,
Failed,
#[default]
Uncustomized,
Precustomized,
Custom,
}
/// <https://html.spec.whatwg.org/multipage/#customelementregistry>
#[dom_struct]
pub(crate) struct CustomElementRegistry {
reflector_: Reflector,
window: Dom<Window>,
/// It is safe to use FxBuildHasher here as `LocalName` is an `Atom` in the string_cache.
/// These get a u32 hashed instead of a string.
/// <https://html.spec.whatwg.org/multipage/#when-defined-promise-map>
when_defined: DomRefCell<HashMapTracedValues<LocalName, TracedPromise, FxBuildHasher>>,
/// <https://html.spec.whatwg.org/multipage/#element-definition-is-running>
element_definition_is_running: Cell<bool>,
/// <https://html.spec.whatwg.org/multipage/#is-scoped>
is_scoped: Cell<bool>,
/// <https://html.spec.whatwg.org/multipage/#scoped-document-set>
scoped_document_set: DomRefCell<FxHashSet<Dom<Document>>>,
#[conditional_malloc_size_of]
/// <https://html.spec.whatwg.org/multipage/#custom-element-definition-set>
definitions:
DomRefCell<HashMapTracedValues<LocalName, Rc<CustomElementDefinition>, FxBuildHasher>>,
}
impl CustomElementRegistry {
fn new_inherited(window: &Window) -> CustomElementRegistry {
CustomElementRegistry {
reflector_: Reflector::new(),
window: Dom::from_ref(window),
when_defined: DomRefCell::new(HashMapTracedValues::new_fx()),
element_definition_is_running: Cell::new(false),
is_scoped: Cell::new(false),
scoped_document_set: Default::default(),
definitions: DomRefCell::new(HashMapTracedValues::new_fx()),
}
}
pub(crate) fn new(cx: &mut JSContext, window: &Window) -> DomRoot<CustomElementRegistry> {
CustomElementRegistry::new_with_proto(cx, window, None)
}
fn new_with_proto(
cx: &mut JSContext,
window: &Window,
proto: Option<HandleObject>,
) -> DomRoot<CustomElementRegistry> {
reflect_dom_object_with_proto(
cx,
Box::new(CustomElementRegistry::new_inherited(window)),
window,
proto,
)
}
/// <https://html.spec.whatwg.org/multipage/#is-scoped>
pub(crate) fn is_scoped(&self) -> bool {
self.is_scoped.get()
}
/// Cleans up any active promises
/// <https://github.com/servo/servo/issues/15318>
pub(crate) fn teardown(&self) {
self.when_defined.borrow_mut().0.clear()
}
/// <https://html.spec.whatwg.org/multipage/#htmlconstructor>
/// Step 5. Let definition be the item in registry's custom element
/// definition set with constructor equal to NewTarget.
pub(crate) fn lookup_definition_by_constructor(
&self,
constructor: HandleObject,
) -> Option<Rc<CustomElementDefinition>> {
self.definitions
.borrow()
.0
.values()
.find(|definition| definition.constructor.callback() == constructor.get())
.cloned()
}
/// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-registry>
pub(crate) fn lookup_a_custom_element_registry(
node: &Node,
) -> Option<DomRoot<CustomElementRegistry>> {
match node.type_id() {
// Step 1. If node is an Element object, then return node's custom element registry.
NodeTypeId::Element(_) => node
.downcast::<Element>()
.expect("Nodes with element type must be an element")
.custom_element_registry(),
// Step 2. If node is a ShadowRoot object, then return node's custom element registry.
NodeTypeId::DocumentFragment(DocumentFragmentTypeId::ShadowRoot) => node
.downcast::<ShadowRoot>()
.expect("Nodes with ShadowRoot type must be a ShadowRoot")
.custom_element_registry(),
// Step 3. If node is a Document object, then return node's custom element registry.
NodeTypeId::Document(_) => node
.downcast::<Document>()
.expect("Nodes with document type must be a document")
.custom_element_registry(),
// Step 4. Return null.
_ => None,
}
}
/// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-definition>
pub(crate) fn lookup_custom_element_definition(
registry: Option<&CustomElementRegistry>,
namespace: &Namespace,
local_name: &LocalName,
is: Option<&LocalName>,
) -> Option<Rc<CustomElementDefinition>> {
// Step 1. If registry is null, then return null.
let registry = registry?;
// Step 2. If namespace is not the HTML namespace, then return null.
if *namespace != ns!(html) {
return None;
}
// Step 3. If registry's custom element definition set contains an item
// with name and local name both equal to localName, then return that
// item.
// Step 4. If registry's custom element definition set contains an item
// with name equal to is and local name equal to localName, then return
// that item.
// Step 5. Return null.
registry
.definitions
.borrow()
.0
.values()
.find(|definition| {
definition.local_name == *local_name &&
(definition.name == *local_name || Some(&definition.name) == is)
})
.cloned()
}
/// <https://dom.spec.whatwg.org/#is-a-global-custom-element-registry>
pub(crate) fn is_a_global_element_registry(registry: Option<&CustomElementRegistry>) -> bool {
// Null or a CustomElementRegistry object registry is a global custom element registry
// if registry is non-null and registry's is scoped is false.
registry.is_some_and(|r| !r.is_scoped())
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
/// Steps 10.1, 10.2
#[expect(unsafe_code)]
fn check_prototype(
&self,
cx: &mut JSContext,
constructor: HandleObject,
mut prototype: MutableHandleValue,
) -> ErrorResult {
unsafe {
// Step 10.1
if !JS_GetProperty(cx, constructor, c"prototype".as_ptr(), prototype.reborrow()) {
return Err(Error::JSFailed);
}
// Step 10.2
if !prototype.is_object() {
return Err(Error::Type(
c"constructor.prototype is not an object".to_owned(),
));
}
}
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
/// This function includes both steps 14.3 and 14.4 which add the callbacks to a map and
/// process them.
fn get_callbacks(
&self,
cx: &mut JSContext,
prototype: HandleObject,
) -> Fallible<RootedLifecycleCallbacks> {
// Step 4
Ok(RootedLifecycleCallbacks {
connected_callback: get_callback(cx, prototype, c"connectedCallback")?,
disconnected_callback: get_callback(cx, prototype, c"disconnectedCallback")?,
connected_move_callback: get_callback(cx, prototype, c"connectedMoveCallback")?,
adopted_callback: get_callback(cx, prototype, c"adoptedCallback")?,
attribute_changed_callback: get_callback(cx, prototype, c"attributeChangedCallback")?,
form_associated_callback: None,
form_disabled_callback: None,
form_reset_callback: None,
form_state_restore_callback: None,
})
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
/// Step 14.13: Add form associated callbacks to LifecycleCallbacks
#[expect(unsafe_code)]
unsafe fn add_form_associated_callbacks(
&self,
cx: &mut JSContext,
prototype: HandleObject,
callbacks: &mut RootedLifecycleCallbacks,
) -> ErrorResult {
callbacks.form_associated_callback =
get_callback(cx, prototype, c"formAssociatedCallback")?;
callbacks.form_reset_callback = get_callback(cx, prototype, c"formResetCallback")?;
callbacks.form_disabled_callback = get_callback(cx, prototype, c"formDisabledCallback")?;
callbacks.form_state_restore_callback =
get_callback(cx, prototype, c"formStateRestoreCallback")?;
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#upgrade-particular-elements-within-a-document>
fn upgrade_particular_elements_within_a_document(
&self,
cx: &JSContext,
document: &Document,
definition: &Rc<CustomElementDefinition>,
local_name: &LocalName,
name: &LocalName,
) {
// Step 1. Let upgradeCandidates be all elements that are shadow-including
// descendants of document, whose custom element registry is registry, whose
// namespace is the HTML namespace, and whose local name is localName,
// in shadow-including tree order. Additionally, if name is not localName,
// only include elements whose is value is equal to name.
for candidate in document
.upcast::<Node>()
.traverse_preorder_non_rooting(cx, ShadowIncluding::Yes)
.filter_map(UnrootedDom::downcast::<Element>)
{
// Note: If the registry is scoped, only include elements whose custom
// element registry is explicitly set to this registry. Otherwise,
// include elements with no explicit registry (they inherit the
// document's global registry) as well.
let registry_matches = if self.is_scoped.get() {
candidate
.custom_element_registry()
.is_some_and(|registry| *registry == *self)
} else {
candidate
.custom_element_registry()
.is_none_or(|registry| *registry == *self)
};
if *candidate.local_name() == *local_name &&
*candidate.namespace() == ns!(html) &&
registry_matches &&
(*name == *local_name || candidate.get_is().as_ref() == Some(name))
{
// Step 2. For each element element of upgradeCandidates: enqueue a
// custom element upgrade reaction given element and definition.
ScriptThread::enqueue_upgrade_reaction(cx, &candidate, definition.clone());
}
}
}
pub(crate) fn add_scoped_document(&self, document: &Document) {
self.scoped_document_set
.borrow_mut()
.insert(Dom::from_ref(document));
}
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
/// Step 14.4: Get `callbackValue` for all `callbackName` in `lifecycleCallbacks`.
#[expect(unsafe_code)]
fn get_callback(
cx: &mut JSContext,
prototype: HandleObject,
name: &CStr,
) -> Fallible<Option<RootedCallback<Function>>> {
rooted!(&in(cx) let mut callback = UndefinedValue());
unsafe {
// Step 10.4.1
if !JS_GetProperty(cx, prototype, name.as_ptr(), callback.handle_mut()) {
return Err(Error::JSFailed);
}
// Step 10.4.2
if !callback.is_undefined() {
if !callback.is_object() || !IsCallable(callback.to_object()) {
return Err(Error::Type(
c"Lifecycle callback is not callable".to_owned(),
));
}
Ok(Some(Function::new(cx, callback.to_object())))
} else {
Ok(None)
}
}
}
impl CustomElementRegistryMethods<crate::DomTypeHolder> for CustomElementRegistry {
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry>
fn Constructor(
cx: &mut JSContext,
window: &Window,
proto: Option<HandleObject>,
) -> DomRoot<CustomElementRegistry> {
let registry = CustomElementRegistry::new_with_proto(cx, window, proto);
// Step 1: Set this's is scoped to true.
registry.is_scoped.set(true);
registry
}
#[expect(unsafe_code)]
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
fn Define(
&self,
cx: &mut JSContext,
name: DOMString,
constructor_: RootedCallback<CustomElementConstructor>,
options: &ElementDefinitionOptions,
) -> ErrorResult {
rooted!(&in(cx) let constructor = constructor_.callback());
let name = LocalName::from(name);
// Step 1. If IsConstructor(constructor) is false, then throw a TypeError.
// We must unwrap the constructor as all wrappers are constructable if they are callable.
rooted!(&in(cx) let unwrapped_constructor = unsafe { UnwrapObjectStatic(constructor.get()) });
if unwrapped_constructor.is_null() {
// We do not have permission to access the unwrapped constructor.
return Err(Error::Security(None));
}
if unsafe { !IsConstructor(unwrapped_constructor.get()) } {
return Err(Error::Type(
c"Second argument of CustomElementRegistry.define is not a constructor".to_owned(),
));
}
// Step 2. If name is not a valid custom element name, then throw a "SyntaxError" DOMException.
if !is_valid_custom_element_name(&name) {
return Err(Error::Syntax(Some(format!(
"{} name is not a valid custom element name",
name
))));
}
// Step 3. If this's custom element definition set contains an item with name name,
// then throw a "NotSupportedError" DOMException.
if self.definitions.borrow().contains_key(&name) {
return Err(Error::NotSupported(Some(format!(
"{} has already been defined as a custom element",
name
))));
}
// Step 4. If this's custom element definition set contains an
// item with constructor constructor, then throw a "NotSupportedError" DOMException.
if self
.definitions
.borrow()
.iter()
.any(|(_, def)| def.constructor.callback() == constructor_.callback())
{
return Err(Error::NotSupported(None));
}
// Step 6. Let extends be options["extends"] if it exists; otherwise null.
let extends = &options.extends;
// Steps 5, 7
let local_name = if let Some(ref extended_name) = *extends {
// Step 7.1 If this's is scoped is true, then throw a "NotSupportedError" DOMException.
if self.is_scoped.get() {
return Err(Error::NotSupported(Some(
"Scoped custom element registries cannot define customized built-in elements"
.to_owned(),
)));
}
// Step 7.2 If extends is a valid custom element name, then throw a "NotSupportedError" DOMException.
if is_valid_custom_element_name(&extended_name.str()) {
return Err(Error::NotSupported(None));
}
// Step 7.3 If the element interface for extends and the HTML namespace is HTMLUnknownElement
// (e.g., if extends does not indicate an element definition in this specification)
// then throw a "NotSupportedError" DOMException.
if !is_extendable_element_interface(&extended_name.str()) {
return Err(Error::NotSupported(None));
}
// Step 7.4 Set localName to extends.
LocalName::from(extended_name)
} else {
// Step 5. Let localName be name.
name.clone()
};
// Step 8
if self.element_definition_is_running.get() {
return Err(Error::NotSupported(None));
}
// Step 9
self.element_definition_is_running.set(true);
// Steps 10-13: Initialize `formAssociated`, `disableInternals`, `disableShadow`, and
// `observedAttributes` with default values, but this is done later.
// Steps 14.1 - 14.2: Get the value of the prototype.
rooted!(&in(cx) let mut prototype = UndefinedValue());
{
let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
if let Err(error) =
self.check_prototype(&mut realm, constructor.handle(), prototype.handle_mut())
{
self.element_definition_is_running.set(false);
return Err(error);
}
};
// Steps 10.3 - 10.4
// It would be easier to get all the callbacks in one pass after
// we know whether this definition is going to be form-associated,
// but the order of operations is specified and it's observable
// if one of the callback getters throws an exception.
rooted!(&in(cx) let proto_object = prototype.to_object());
let mut callbacks = {
let mut realm = AutoRealm::new_from_handle(cx, proto_object.handle());
match self.get_callbacks(&mut realm, proto_object.handle()) {
Ok(callbacks) => callbacks,
Err(error) => {
self.element_definition_is_running.set(false);
return Err(error);
},
}
};
// Step 14.5: Handle the case where with `attributeChangedCallback` on `lifecycleCallbacks`
// is not null.
let observed_attributes: Vec<DOMString> = if callbacks.attribute_changed_callback.is_some()
{
let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
match get_property(
&mut realm,
constructor.handle(),
c"observedAttributes",
StringificationBehavior::Default,
) {
Ok(attributes) => attributes.unwrap_or_default(),
Err(error) => {
self.element_definition_is_running.set(false);
return Err(error);
},
}
} else {
Vec::new()
};
// Steps 14.6 - 14.10: Handle `disabledFeatures`.
let (disable_internals, disable_shadow) = {
let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
match get_property::<Vec<DOMString>>(
&mut realm,
constructor.handle(),
c"disabledFeatures",
StringificationBehavior::Default,
) {
Ok(sequence) => {
let sequence = sequence.unwrap_or_default();
(
sequence.iter().any(|s| *s == "internals"),
sequence.iter().any(|s| *s == "shadow"),
)
},
Err(error) => {
self.element_definition_is_running.set(false);
return Err(error);
},
}
};
// Step 14.11 - 14.12: Handle `formAssociated`.
let form_associated: bool = {
let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
match get_property(&mut realm, constructor.handle(), c"formAssociated", ()) {
Ok(flag) => flag.unwrap_or_default(),
Err(error) => {
self.element_definition_is_running.set(false);
return Err(error);
},
}
};
// Steps 14.13: Add the `formAssociated` callbacks.
if form_associated {
let mut realm = AutoRealm::new_from_handle(cx, proto_object.handle());
unsafe {
if let Err(error) = self.add_form_associated_callbacks(
&mut realm,
proto_object.handle(),
&mut callbacks,
) {
self.element_definition_is_running.set(false);
return Err(error);
}
}
}
self.element_definition_is_running.set(false);
// Step 15: Let definition be a new custom element definition with name name,
// local name localName, constructor constructor, observed attributes
// observedAttributes, lifecycle callbacks lifecycleCallbacks,
// form-associated formAssociated, disable internals disableInternals,
// and disable shadow disableShadow.
let definition = Rc::new(CustomElementDefinition::new(
name.clone(),
local_name.clone(),
constructor_,
observed_attributes,
callbacks,
form_associated,
disable_internals,
disable_shadow,
));
// Step 16: Append definition to this's custom element definition set.
self.definitions
.borrow_mut()
.insert(name.clone(), definition.clone());
// Step 17: If this's is scoped is true, then for each document of
// this's scoped document set: upgrade particular elements within a
// document given this, document, definition, and localName.
if self.is_scoped.get() {
for document in self.scoped_document_set.borrow().iter() {
self.upgrade_particular_elements_within_a_document(
cx,
document,
&definition,
&local_name,
&local_name,
);
}
} else {
// Step 18: Otherwise, upgrade particular elements within a document given
// this, this's relevant global object's associated Document, definition,
// localName, and name.
self.upgrade_particular_elements_within_a_document(
cx,
&self.window.Document(),
&definition,
&local_name,
&name,
);
}
// Step 19: If this's when-defined promise map[name] exists:
// Step 19.2: Remove this's when-defined promise map[name].
let promise = self
.when_defined
.borrow_mut()
.remove(&name)
.map(|promise| promise.root(cx));
if let Some(promise) = promise {
rooted!(&in(cx) let mut constructor = UndefinedValue());
definition
.constructor
.to_jsval(cx, constructor.handle_mut());
// Step 19.1: Resolve this's when-defined promise map[name] with constructor.
promise.resolve_native(cx, &constructor.get());
}
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get>
fn Get(&self, cx: &mut JSContext, name: DOMString, mut retval: MutableHandleValue) {
match self.definitions.borrow().get(&LocalName::from(name)) {
Some(definition) => definition.constructor.to_jsval(cx, retval),
None => retval.set(UndefinedValue()),
}
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-getname>
fn GetName(&self, constructor: RootedCallback<CustomElementConstructor>) -> Option<DOMString> {
self.definitions
.borrow()
.0
.values()
.find(|definition| definition.constructor.callback() == constructor.callback())
.map(|definition| DOMString::from(definition.name.to_string()))
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-whendefined>
fn WhenDefined(&self, realm: &mut CurrentRealm, name: DOMString) -> RootedPromise {
let name = LocalName::from(name);
// Step 1
if !is_valid_custom_element_name(&name) {
let promise = Promise::new_in_realm(realm);
let error = DOMException::new(
realm,
self.window.as_global_scope(),
DOMErrorName::SyntaxError,
);
promise.reject_native(realm, &error);
return promise;
}
// Step 2
if let Some(definition) = self.definitions.borrow().get(&LocalName::from(&*name)) {
rooted!(&in(*realm) let mut constructor = UndefinedValue());
definition
.constructor
.to_jsval(realm, constructor.handle_mut());
let promise = Promise::new_in_realm(realm);
promise.resolve_native(realm, &constructor.get());
return promise;
}
// Steps 3, 4, 5, 6
let existing_promise = self
.when_defined
.borrow()
.get(&name)
.map(|promise| promise.root(realm));
existing_promise.unwrap_or_else(|| {
let promise = Promise::new_in_realm(realm);
self.when_defined
.borrow_mut()
.insert(name, promise.to_traced());
promise
})
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-upgrade>
fn Upgrade(&self, cx: &JSContext, node: &Node) {
// Step 1. For each shadow-including inclusive descendant candidate of
// root, in shadow-including tree order:
for node in node.traverse_preorder_non_rooting(cx, ShadowIncluding::Yes) {
// Step 1.1. If candidate is not an Element node, then continue.
let Some(element) = node.downcast::<Element>() else {
continue;
};
// Step 1.2. If candidate's custom element registry is not this,
// then continue.
if element
.custom_element_registry()
.is_some_and(|registry| *registry != *self)
{
continue;
}
// Step 1.3. Try to upgrade candidate.
try_upgrade_element(cx, element);
}
}
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-initialize>
fn Initialize(&self, cx: &JSContext, root: &Node) -> ErrorResult {
// Step 1. If this's is scoped is false and either root is a Document node
// or root's node document's custom element registry is not this, then
// throw a "NotSupportedError" DOMException.
if !self.is_scoped.get() {
let is_document = root.is::<Document>();
let registry_mismatch = root
.owner_doc()
.custom_element_registry()
.is_some_and(|registry| *registry != *self);
if is_document || registry_mismatch {
return Err(Error::NotSupported(Some(
"Initialize is not allowed on a non-scoped registry for this root".to_owned(),
)));
}
}
// Step 2. If root is a Document node whose custom element registry is null,
// then set root's custom element registry to this.
if let Some(document) = root.downcast::<Document>() {
if document.custom_element_registry().is_none() {
document.set_custom_element_registry(self);
}
}
// Step 3. Otherwise, if root is a ShadowRoot node whose custom element registry
// is null, then set root's custom element registry to this.
else if let Some(shadow_root) = root.downcast::<ShadowRoot>() &&
shadow_root.custom_element_registry().is_none()
{
shadow_root.set_custom_element_registry(Some(self));
}
// Step 4. For each inclusive descendant inclusiveDescendant of root, in tree order:
for node in root.traverse_preorder(ShadowIncluding::No) {
// Step 4.1. If inclusiveDescendant is not an Element node, then continue.
let Some(element) = node.downcast::<Element>() else {
continue;
};
// Step 4.2. If inclusiveDescendant's custom element registry is null:
// Note: A global registry (set by Node::adopt) is treated the same as null.
// Both mean the element has no scoped registry, so it should get this one.
if element
.custom_element_registry()
.is_none_or(|registry| Self::is_a_global_element_registry(Some(&*registry)))
{
// Step 4.2.1. Set inclusiveDescendant's custom element registry to this.
element.set_custom_element_registry(Some(self), cx.no_gc());
// Step 4.2.2. If this's is scoped is true, then append
// inclusiveDescendant's node document to this's scoped document set.
if self.is_scoped.get() {
let document = element.upcast::<Node>().owner_doc();
self.scoped_document_set
.borrow_mut()
.insert(Dom::from_ref(&document));
}
// Step 4.3. If inclusiveDescendant's custom element registry is not this, then continue.
} else if element
.custom_element_registry()
.is_none_or(|registry| *registry != *self)
{
continue;
}
// Step 4.4. Try to upgrade inclusiveDescendant.
try_upgrade_element(cx, element);
}
Ok(())
}
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub(crate) struct LifecycleCallbacks {
connected_callback: Option<TracedCallback<Function>>,
connected_move_callback: Option<TracedCallback<Function>>,
disconnected_callback: Option<TracedCallback<Function>>,
adopted_callback: Option<TracedCallback<Function>>,
attribute_changed_callback: Option<TracedCallback<Function>>,
form_associated_callback: Option<TracedCallback<Function>>,
form_reset_callback: Option<TracedCallback<Function>>,
form_disabled_callback: Option<TracedCallback<Function>>,
form_state_restore_callback: Option<TracedCallback<Function>>,
}
struct RootedLifecycleCallbacks {
connected_callback: Option<RootedCallback<Function>>,
connected_move_callback: Option<RootedCallback<Function>>,
disconnected_callback: Option<RootedCallback<Function>>,
adopted_callback: Option<RootedCallback<Function>>,
attribute_changed_callback: Option<RootedCallback<Function>>,
form_associated_callback: Option<RootedCallback<Function>>,
form_reset_callback: Option<RootedCallback<Function>>,
form_disabled_callback: Option<RootedCallback<Function>>,
form_state_restore_callback: Option<RootedCallback<Function>>,
}
impl From<RootedLifecycleCallbacks> for LifecycleCallbacks {
fn from(callbacks: RootedLifecycleCallbacks) -> Self {
Self {
connected_callback: callbacks
.connected_callback
.map(|callback| callback.to_traced()),
connected_move_callback: callbacks
.connected_move_callback
.map(|callback| callback.to_traced()),
disconnected_callback: callbacks
.disconnected_callback
.map(|callback| callback.to_traced()),
adopted_callback: callbacks
.adopted_callback
.map(|callback| callback.to_traced()),
attribute_changed_callback: callbacks
.attribute_changed_callback
.map(|callback| callback.to_traced()),
form_associated_callback: callbacks
.form_associated_callback
.map(|callback| callback.to_traced()),
form_reset_callback: callbacks
.form_reset_callback
.map(|callback| callback.to_traced()),
form_disabled_callback: callbacks
.form_disabled_callback
.map(|callback| callback.to_traced()),
form_state_restore_callback: callbacks
.form_state_restore_callback
.map(|callback| callback.to_traced()),
}
}
}
#[derive(Clone, JSTraceable, MallocSizeOf)]
pub(crate) enum ConstructionStackEntry {
Element(DomRoot<Element>),
AlreadyConstructedMarker,
}
/// <https://html.spec.whatwg.org/multipage/#custom-element-definition>
/// # Safety
/// This can be shared inside an Rc because every Rc copy is reachable from a
/// CustomElementRegistry's definitions map, which the GC traces.
#[derive(Clone, JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
pub(crate) struct CustomElementDefinition {
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-name>
#[no_trace]
pub(crate) name: LocalName,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-local-name>
#[no_trace]
pub(crate) local_name: LocalName,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-constructor>
pub(crate) constructor: TracedCallback<CustomElementConstructor>,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-observed-attributes>
pub(crate) observed_attributes: Vec<DOMString>,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-lifecycle-callbacks>
pub(crate) callbacks: LifecycleCallbacks,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-construction-stack>
pub(crate) construction_stack: DomRefCell<Vec<ConstructionStackEntry>>,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-form-associated>
pub(crate) form_associated: bool,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-disable-internals>
pub(crate) disable_internals: bool,
/// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-disable-shadow>
pub(crate) disable_shadow: bool,
}
impl CustomElementDefinition {
#[expect(clippy::too_many_arguments)]
fn new(
name: LocalName,
local_name: LocalName,
constructor: RootedCallback<CustomElementConstructor>,
observed_attributes: Vec<DOMString>,
callbacks: RootedLifecycleCallbacks,
form_associated: bool,
disable_internals: bool,
disable_shadow: bool,
) -> CustomElementDefinition {
CustomElementDefinition {
name,
local_name,
constructor: constructor.to_traced(),
observed_attributes,
callbacks: callbacks.into(),
construction_stack: Default::default(),
form_associated,
disable_internals,
disable_shadow,
}
}
/// <https://html.spec.whatwg.org/multipage/#autonomous-custom-element>
pub(crate) fn is_autonomous(&self) -> bool {
self.name == self.local_name
}
/// <https://dom.spec.whatwg.org/#concept-create-element> Step 5.1
#[expect(unsafe_code)]
pub(crate) fn create_element(
&self,
cx: &mut JSContext,
document: &Document,
prefix: Option<Prefix>,
registry: Option<&CustomElementRegistry>,
) -> Fallible<DomRoot<Element>> {
let window = document.window();
// Step 5.1.1. Let C be definition’s constructor.
rooted!(&in(cx) let constructor = ObjectValue(self.constructor.callback()));
rooted!(&in(cx) let mut element = ptr::null_mut::<JSObject>());
{
// Go into the constructor's realm
let mut realm = AutoRealm::new(cx, NonNull::new(self.constructor.callback()).unwrap());
let cx = &mut realm;
// Step 5.3.1. Set result to the result of constructing C, with no arguments.
// https://webidl.spec.whatwg.org/#construct-a-callback-function
run_a_script::<DomTypeHolder, _, _>(cx, window.upcast(), |cx| {
run_a_callback::<DomTypeHolder, _>(window.upcast(), || {
let args = HandleValueArray::empty();
if unsafe { !Construct1(cx, constructor.handle(), &args, element.handle_mut()) }
{
Err(Error::JSFailed)
} else {
Ok(())
}
})
})?;
}
rooted!(&in(cx) let element_val = ObjectValue(element.get()));
let element: DomRoot<Element> =
match FromJSValConvertible::from_jsval(cx, element_val.handle(), ()) {
Ok(ConversionResult::Success(element)) => element,
Ok(ConversionResult::Failure(..)) => {
return Err(Error::Type(
c"Constructor did not return a DOM node".to_owned(),
));
},
_ => return Err(Error::JSFailed),
};
// Step 5.1.3.2 Assert: result’s custom element state and custom element definition are initialized.
// Step 5.1.3.3 Assert: result’s namespace is the HTML namespace.
// Note: IDL enforces that result is an HTMLElement object, which all use the HTML namespace.
// Note: the custom element definition is initialized by the caller if
// this method returns a success value.
assert!(element.is::<HTMLElement>());
// Step 5.1.3.4. If result’s attribute list is not empty, then throw a "NotSupportedError" DOMException.
// Step 5.1.3.5. If result has children, then throw a "NotSupportedError" DOMException.
// Step 5.1.3.6. If result’s parent is not null, then throw a "NotSupportedError" DOMException.
// Step 5.1.3.7. If result’s node document is not document, then throw a "NotSupportedError" DOMException.
// Step 5.1.3.8. If result’s local name is not equal to localName then throw a "NotSupportedError" DOMException.
if element.HasAttributes() ||
element.upcast::<Node>().children_count() > 0 ||
element.upcast::<Node>().has_parent() ||
&*element.upcast::<Node>().owner_doc() != document ||
*element.namespace() != ns!(html) ||
*element.local_name() != self.local_name
{
return Err(Error::NotSupported(None));
}
// Step 5.1.3.9. Set result’s namespace prefix to prefix.
element.set_prefix(prefix);
// Step 5.1.3.10. Set result’s is value to null.
// Element's `is` is None by default
// Step 5.1.3.11. Set result’s custom element registry to registry.
element.set_custom_element_registry(registry, cx.no_gc());
Ok(element)
}
pub(crate) fn has_attribute_changed_callback(&self) -> bool {
self.callbacks.attribute_changed_callback.is_some()
}
}
/// <https://html.spec.whatwg.org/multipage/#concept-upgrade-an-element>
pub(crate) fn upgrade_element(
cx: &mut JSContext,
definition: Rc<CustomElementDefinition>,
element: &Element,
) {
// Step 1. If element's custom element state is not "undefined" or "uncustomized", then return.
let state = element.get_custom_element_state();
if state != CustomElementState::Undefined && state != CustomElementState::Uncustomized {
return;
}
// Step 2. Set element's custom element definition to definition.
element.set_custom_element_definition(Rc::clone(&definition), cx.no_gc());
// Step 3. Set element's custom element state to "failed".
element.set_custom_element_state(CustomElementState::Failed, cx.no_gc());
// Step 4. For each attribute in element's attribute list, in order, enqueue a custom element callback reaction
// with element, callback name "attributeChangedCallback", and « attribute's local name, null, attribute's value,
// attribute's namespace ».
let custom_element_reaction_stack = ScriptThread::custom_element_reaction_stack();
for attr in element.attrs().borrow().iter() {
let local_name = attr.local_name().clone();
let namespace = attr.namespace().clone();
custom_element_reaction_stack.enqueue_callback_reaction(
cx,
element,
CallbackReaction::AttributeChanged(local_name, None, Some(&*attr.value()), namespace),
Some(definition.clone()),
);
}
// Step 5. If element is connected, then enqueue a custom element callback reaction with element,
// callback name "connectedCallback", and « ».
if element.is_connected() {
custom_element_reaction_stack.enqueue_callback_reaction(
cx,
element,
CallbackReaction::Connected,
Some(definition.clone()),
);
}
// Step 6. Add element to the end of definition's construction stack.
definition
.construction_stack
.borrow_mut()
.push(ConstructionStackEntry::Element(DomRoot::from_ref(element)));
// Steps 7-8, successful case
let result = run_upgrade_constructor(cx, &definition, element);
// "regardless of whether the above steps threw an exception" step
definition.construction_stack.borrow_mut().pop();
// Step 8 exception handling
if let Err(error) = result {
// Step 8.exception.1
element.clear_custom_element_definition(cx.no_gc());
// Step 8.exception.2
element.clear_reaction_queue();
// Step 8.exception.3
let global = GlobalScope::current().expect("No current global");
let mut realm = enter_auto_realm(cx, &*global);
let cx = &mut realm.current_realm();
throw_dom_exception(cx, &global, error);
report_pending_exception(cx);
return;
}
// Step 9: handle with form-associated custom element
if let Some(html_element) = element.downcast::<HTMLElement>() &&
html_element.is_form_associated_custom_element()
{
// We know this element is is form-associated, so we can use the implementation of
// `FormControl` for HTMLElement, which makes that assumption.
// Step 9.1: Reset the form owner of element
html_element.reset_form_owner(cx);
if let Some(form) = html_element.form_owner() {
// Even though the tree hasn't structurally mutated,
// HTMLCollections need to be invalidated.
form.upcast::<Node>().rev_version(cx.no_gc());
// The spec tells us specifically to enqueue a formAssociated reaction
// here, but it also says to do that for resetting form owner in general,
// and we don't need two reactions.
}
// Either enabled_state or disabled_state needs to be set,
// and the possibility of a disabled fieldset ancestor needs
// to be accounted for. (In the spec, being disabled is
// a fact that's true or false about a node at a given time,
// not a flag that belongs to the node and is updated,
// so it doesn't describe this check as an action.)
element.check_disabled_attribute();
element.check_ancestors_disabled_state_for_form_control(cx.no_gc());
element.update_read_write_state_from_readonly_attribute();
// Step 9.2: If element is disabled, then enqueue a custom element callback reaction
// with element.
if element.disabled_state() {
custom_element_reaction_stack.enqueue_callback_reaction(
cx,
element,
CallbackReaction::FormDisabled(true),
Some(definition),
)
}
}
// Step 10
element.set_custom_element_state(CustomElementState::Custom, cx.no_gc());
}
/// <https://html.spec.whatwg.org/multipage/#concept-upgrade-an-element>
/// Steps 9.1-9.4
#[expect(unsafe_code)]
fn run_upgrade_constructor(
cx: &mut JSContext,
definition: &CustomElementDefinition,
element: &Element,
) -> ErrorResult {
let constructor = &definition.constructor;
let window = element.owner_window();
rooted!(&in(cx) let constructor_val = ObjectValue(constructor.callback()));
rooted!(&in(cx) let mut element_val = UndefinedValue());
element.to_jsval(cx, element_val.handle_mut());
rooted!(&in(cx) let mut construct_result = ptr::null_mut::<JSObject>());
{
// Step 9.1. If definition's disable shadow is true and element's shadow root is non-null,
// then throw a "NotSupportedError" DOMException.
if definition.disable_shadow && element.is_shadow_host() {
return Err(Error::NotSupported(None));
}
// Go into the constructor's realm
let mut realm = AutoRealm::new(cx, NonNull::new(constructor.callback()).unwrap());
let cx = &mut *realm;
let args = HandleValueArray::empty();
// Step 8.2. Set element's custom element state to "precustomized".
element.set_custom_element_state(CustomElementState::Precustomized, cx.no_gc());
// Step 9.3. Let constructResult be the result of constructing C, with no arguments.
// https://webidl.spec.whatwg.org/#construct-a-callback-function
run_a_script::<DomTypeHolder, _, _>(cx, window.upcast(), |cx| {
run_a_callback::<DomTypeHolder, _>(window.upcast(), || {
if unsafe {
!Construct1(
cx,
constructor_val.handle(),
&args,
construct_result.handle_mut(),
)
} {
Err(Error::JSFailed)
} else {
Ok(())
}
})
})?;
let mut same = false;
rooted!(&in(cx) let construct_result_val = ObjectValue(construct_result.get()));
// Step 9.4. If SameValue(constructResult, element) is false, then throw a TypeError.
if unsafe {
!SameValue(
cx,
construct_result_val.handle(),
element_val.handle(),
&mut same,
)
} {
return Err(Error::JSFailed);
}
if !same {
return Err(Error::Type(
c"Returned element is not SameValue as the upgraded element".to_owned(),
));
}
}
Ok(())
}
/// <https://html.spec.whatwg.org/multipage/#concept-try-upgrade>
pub(crate) fn try_upgrade_element(cx: &JSContext, element: &Element) {
// Step 1. Let definition be the result of looking up a custom element
// definition given element's custom element registry, element's namespace,
// element's local name, and element's is value.
let lookup_registry = {
// TODO: Remove this fallback when Node::adopt is aligned according to specs.
// Currently elements carry stale global registry from another document.
let registry = element.custom_element_registry();
if registry
.as_ref()
.is_some_and(|registry| registry.is_scoped())
{
registry
} else {
element.owner_document().custom_element_registry()
}
};
if let Some(definition) = CustomElementRegistry::lookup_custom_element_definition(
lookup_registry.as_deref(),
element.namespace(),
element.local_name(),
element.get_is().as_ref(),
) {
// Step 2. If definition is not null, then enqueue a custom element
// upgrade reaction given element and definition.
ScriptThread::enqueue_upgrade_reaction(cx, element, definition);
}
}
#[derive(JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
pub(crate) enum CustomElementReaction {
Upgrade(#[conditional_malloc_size_of] Rc<CustomElementDefinition>),
Callback(
TracedCallback<Function>,
#[ignore_malloc_size_of = "mozjs"] Box<[Heap<JSVal>]>,
),
}
impl CustomElementReaction {
/// <https://html.spec.whatwg.org/multipage/#invoke-custom-element-reactions>
pub(crate) fn invoke(&self, cx: &mut JSContext, element: &Element) {
// Step 2.1
match *self {
CustomElementReaction::Upgrade(ref definition) => {
upgrade_element(cx, definition.clone(), element)
},
CustomElementReaction::Callback(ref callback, ref arguments) => {
// We're rooted, so it's safe to hand out a handle to objects in Heap
let arguments = arguments.iter().map(|arg| arg.as_handle_value()).collect();
rooted!(&in(cx) let mut value: JSVal);
let _ = callback.Call_(
cx,
element,
arguments,
value.handle_mut(),
ExceptionHandling::Report,
);
},
}
}
}
pub(crate) enum CallbackReaction<'a> {
Connected,
Disconnected,
Adopted(DomRoot<Document>, DomRoot<Document>),
AttributeChanged(
LocalName,
Option<&'a AttrValue>,
Option<&'a AttrValue>,
Namespace,
),
FormAssociated(Option<DomRoot<HTMLFormElement>>),
FormDisabled(bool),
FormReset,
ConnectedMove,
}
/// <https://html.spec.whatwg.org/multipage/#processing-the-backup-element-queue>
#[derive(Clone, Copy, Eq, JSTraceable, MallocSizeOf, PartialEq)]
enum BackupElementQueueFlag {
Processing,
NotProcessing,
}
/// <https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack>
/// # Safety
/// This can be shared inside an Rc because one of those Rc copies lives
/// inside ScriptThread, so the GC can always reach this structure.
#[derive(JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
pub(crate) struct CustomElementReactionStack {
stack: DomRefCell<Vec<ElementQueue>>,
backup_queue: ElementQueue,
processing_backup_element_queue: Cell<BackupElementQueueFlag>,
}
impl CustomElementReactionStack {
pub(crate) fn new() -> CustomElementReactionStack {
CustomElementReactionStack {
stack: DomRefCell::new(Vec::new()),
backup_queue: ElementQueue::new(),
processing_backup_element_queue: Cell::new(BackupElementQueueFlag::NotProcessing),
}
}
pub(crate) fn push_new_element_queue(&self) {
self.stack.borrow_mut().push(ElementQueue::new());
}
pub(crate) fn pop_current_element_queue(&self, cx: &mut JSContext) {
rooted_vec!(let mut stack);
mem::swap(&mut *stack, &mut *self.stack.borrow_mut());
if let Some(current_queue) = stack.last() {
current_queue.invoke_reactions(cx);
}
stack.pop();
mem::swap(&mut *self.stack.borrow_mut(), &mut *stack);
self.stack.borrow_mut().append(&mut *stack);
}
/// <https://html.spec.whatwg.org/multipage/#enqueue-an-element-on-the-appropriate-element-queue>
/// Step 4
pub(crate) fn invoke_backup_element_queue(&self, cx: &mut JSContext) {
// Step 4.1
self.backup_queue.invoke_reactions(cx);
// Step 4.2
self.processing_backup_element_queue
.set(BackupElementQueueFlag::NotProcessing);
}
/// <https://html.spec.whatwg.org/multipage/#enqueue-an-element-on-the-appropriate-element-queue>
pub(crate) fn enqueue_element(&self, cx: &JSContext, element: &Element) {
if let Some(current_queue) = self.stack.borrow().last() {
// Step 2
current_queue.append_element(element);
} else {
// Step 1.1
self.backup_queue.append_element(element);
// Step 1.2
if self.processing_backup_element_queue.get() == BackupElementQueueFlag::Processing {
return;
}
// Step 1.3
self.processing_backup_element_queue
.set(BackupElementQueueFlag::Processing);
// Step 4
ScriptThread::enqueue_microtask(cx, Box::new(CustomElementReactionMicrotask::new()));
}
}
/// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-callback-reaction>
#[cfg_attr(crown, expect(crown::unrooted_must_root))]
pub(crate) fn enqueue_callback_reaction(
&self,
cx: &mut JSContext,
element: &Element,
reaction: CallbackReaction,
definition: Option<Rc<CustomElementDefinition>>,
) {
// Step 1. Let definition be element's custom element definition.
let definition = match definition.or_else(|| element.get_custom_element_definition()) {
Some(definition) => definition,
None => return,
};
// Step 2. Let callback be the value of the entry in definition's lifecycle callbacks with
// key callbackName.
let (callback, args) = match reaction {
CallbackReaction::Connected => {
(definition.callbacks.connected_callback.clone(), Vec::new())
},
CallbackReaction::Disconnected => (
definition.callbacks.disconnected_callback.clone(),
Vec::new(),
),
CallbackReaction::Adopted(ref old_doc, ref new_doc) => {
let args = vec![Heap::default(), Heap::default()];
args[0].set(ObjectValue(old_doc.reflector().get_jsobject().get()));
args[1].set(ObjectValue(new_doc.reflector().get_jsobject().get()));
(definition.callbacks.adopted_callback.clone(), args)
},
CallbackReaction::AttributeChanged(local_name, old_val, val, namespace) => {
// Step 5.
if !definition
.observed_attributes
.iter()
.any(|attr| *attr == *local_name)
{
return;
}
// We might be here during HTML parsing, rather than
// during Javscript execution, and so we typically aren't
// already in a realm here.
let mut realm = enter_auto_realm(cx, &*element.global());
let cx = &mut realm;
let local_name = DOMString::from(&*local_name);
rooted!(&in(cx) let mut name_value = UndefinedValue());
local_name.to_jsval(cx, name_value.handle_mut());
rooted!(&in(cx) let mut old_value = NullValue());
if let Some(old_val) = old_val {
old_val.to_jsval(cx, old_value.handle_mut());
}
rooted!(&in(cx) let mut value = NullValue());
if let Some(val) = val {
val.to_jsval(cx, value.handle_mut());
}
rooted!(&in(cx) let mut namespace_value = NullValue());
if namespace != ns!() {
let namespace = DOMString::from(&*namespace);
namespace.to_jsval(cx, namespace_value.handle_mut());
}
let args = vec![
Heap::default(),
Heap::default(),
Heap::default(),
Heap::default(),
];
args[0].set(name_value.get());
args[1].set(old_value.get());
args[2].set(value.get());
args[3].set(namespace_value.get());
(
definition.callbacks.attribute_changed_callback.clone(),
args,
)
},
CallbackReaction::FormAssociated(form) => {
let args = vec![Heap::default()];
if let Some(form) = form {
args[0].set(ObjectValue(form.reflector().get_jsobject().get()));
} else {
args[0].set(NullValue());
}
(definition.callbacks.form_associated_callback.clone(), args)
},
CallbackReaction::FormDisabled(disabled) => {
rooted!(&in(cx) let disabled_value = BooleanValue(disabled));
let args = vec![Heap::default()];
args[0].set(disabled_value.get());
(definition.callbacks.form_disabled_callback.clone(), args)
},
CallbackReaction::FormReset => {
(definition.callbacks.form_reset_callback.clone(), Vec::new())
},
CallbackReaction::ConnectedMove => {
let callback = definition.callbacks.connected_move_callback.clone();
// Step 3. If callbackName is "connectedMoveCallback" and callback is null:
if callback.is_none() {
// Step 3.1. Let disconnectedCallback be the value of the entry in
// definition's lifecycle callbacks with key "disconnectedCallback".
let disconnected_callback = definition.callbacks.disconnected_callback.clone();
// Step 3.2. Let connectedCallback be the value of the entry in
// definition's lifecycle callbacks with key "connectedCallback".
let connected_callback = definition.callbacks.connected_callback.clone();
// Step 3.3. If connectedCallback and disconnectedCallback are null,
// then return.
if disconnected_callback.is_none() && connected_callback.is_none() {
return;
}
// Step 3.4. Set callback to the following steps:
// Step 3.4.1. If disconnectedCallback is not null, then call
// disconnectedCallback with no arguments.
if let Some(disconnected_callback) = disconnected_callback {
element.push_callback_reaction(
disconnected_callback.root(cx),
Box::new([]),
cx.no_gc(),
);
}
// Step 3.4.2. If connectedCallback is not null, then call
// connectedCallback with no arguments.
if let Some(connected_callback) = connected_callback {
element.push_callback_reaction(
connected_callback.root(cx),
Box::new([]),
cx.no_gc(),
);
}
self.enqueue_element(cx, element);
return;
}
(callback, Vec::new())
},
};
// Step 4. If callback is null, then return.
let callback = match callback {
Some(callback) => callback,
None => return,
};
// Step 6. Add a new callback reaction to element's custom element reaction queue, with
// callback function callback and arguments args.
element.push_callback_reaction(callback.root(cx), args.into_boxed_slice(), cx.no_gc());
// Step 7. Enqueue an element on the appropriate element queue given element.
self.enqueue_element(cx, element);
}
/// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-upgrade-reaction>
pub(crate) fn enqueue_upgrade_reaction(
&self,
cx: &JSContext,
element: &Element,
definition: Rc<CustomElementDefinition>,
) {
// Step 1. Add a new upgrade reaction to element's custom element reaction queue,
// with custom element definition definition.
element.push_upgrade_reaction(definition, cx.no_gc());
// Step 2. Enqueue an element on the appropriate element queue given element.
self.enqueue_element(cx, element);
}
}
/// <https://html.spec.whatwg.org/multipage/#element-queue>
#[derive(JSTraceable, MallocSizeOf)]
#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
struct ElementQueue {
queue: DomRefCell<VecDeque<Dom<Element>>>,
}
impl ElementQueue {
fn new() -> ElementQueue {
ElementQueue {
queue: Default::default(),
}
}
/// <https://html.spec.whatwg.org/multipage/#invoke-custom-element-reactions>
fn invoke_reactions(&self, cx: &mut JSContext) {
// Steps 1-2
while let Some(element) = self.next_element() {
element.invoke_reactions(cx)
}
self.queue.borrow_mut().clear();
}
fn next_element(&self) -> Option<DomRoot<Element>> {
self.queue
.borrow_mut()
.pop_front()
.as_deref()
.map(DomRoot::from_ref)
}
fn append_element(&self, element: &Element) {
self.queue.borrow_mut().push_back(Dom::from_ref(element));
}
}
/// <https://html.spec.whatwg.org/multipage/#valid-custom-element-name>
pub(crate) fn is_valid_custom_element_name(name: &str) -> bool {
// Custom elment names must match:
// PotentialCustomElementName ::= [a-z] (PCENChar)* '-' (PCENChar)*
let mut chars = name.chars();
if !chars.next().is_some_and(|c| c.is_ascii_lowercase()) {
return false;
}
let mut has_dash = false;
for c in chars {
if c == '-' {
has_dash = true;
continue;
}
if !is_potential_custom_element_char(c) {
return false;
}
}
if !has_dash {
return false;
}
if name == "annotation-xml" ||
name == "color-profile" ||
name == "font-face" ||
name == "font-face-src" ||
name == "font-face-uri" ||
name == "font-face-format" ||
name == "font-face-name" ||
name == "missing-glyph"
{
return false;
}
true
}
/// Check if this character is a PCENChar
/// <https://html.spec.whatwg.org/multipage/#prod-pcenchar>
fn is_potential_custom_element_char(c: char) -> bool {
c == '-' ||
c == '.' ||
c == '_' ||
c == '\u{B7}' ||
c.is_ascii_digit() ||
c.is_ascii_lowercase() ||
('\u{C0}'..='\u{D6}').contains(&c) ||
('\u{D8}'..='\u{F6}').contains(&c) ||
('\u{F8}'..='\u{37D}').contains(&c) ||
('\u{37F}'..='\u{1FFF}').contains(&c) ||
('\u{200C}'..='\u{200D}').contains(&c) ||
('\u{203F}'..='\u{2040}').contains(&c) ||
('\u{2070}'..='\u{218F}').contains(&c) ||
('\u{2C00}'..='\u{2FEF}').contains(&c) ||
('\u{3001}'..='\u{D7FF}').contains(&c) ||
('\u{F900}'..='\u{FDCF}').contains(&c) ||
('\u{FDF0}'..='\u{FFFD}').contains(&c) ||
('\u{10000}'..='\u{EFFFF}').contains(&c)
}
fn is_extendable_element_interface(element: &str) -> bool {
element == "a" ||
element == "abbr" ||
element == "acronym" ||
element == "address" ||
element == "area" ||
element == "article" ||
element == "aside" ||
element == "audio" ||
element == "b" ||
element == "base" ||
element == "bdi" ||
element == "bdo" ||
element == "big" ||
element == "blockquote" ||
element == "body" ||
element == "br" ||
element == "button" ||
element == "canvas" ||
element == "caption" ||
element == "center" ||
element == "cite" ||
element == "code" ||
element == "col" ||
element == "colgroup" ||
element == "data" ||
element == "datalist" ||
element == "dd" ||
element == "del" ||
element == "details" ||
element == "dfn" ||
element == "dialog" ||
element == "dir" ||
element == "div" ||
element == "dl" ||
element == "dt" ||
element == "em" ||
element == "embed" ||
element == "fieldset" ||
element == "figcaption" ||
element == "figure" ||
element == "font" ||
element == "footer" ||
element == "form" ||
element == "frame" ||
element == "frameset" ||
element == "h1" ||
element == "h2" ||
element == "h3" ||
element == "h4" ||
element == "h5" ||
element == "h6" ||
element == "head" ||
element == "header" ||
element == "hgroup" ||
element == "hr" ||
element == "html" ||
element == "i" ||
element == "iframe" ||
element == "img" ||
element == "input" ||
element == "ins" ||
element == "kbd" ||
element == "label" ||
element == "legend" ||
element == "li" ||
element == "link" ||
element == "listing" ||
element == "main" ||
element == "map" ||
element == "mark" ||
element == "marquee" ||
element == "menu" ||
element == "meta" ||
element == "meter" ||
element == "nav" ||
element == "nobr" ||
element == "noframes" ||
element == "noscript" ||
element == "object" ||
element == "ol" ||
element == "optgroup" ||
element == "option" ||
element == "output" ||
element == "p" ||
element == "param" ||
element == "picture" ||
element == "plaintext" ||
element == "pre" ||
element == "progress" ||
element == "q" ||
element == "rp" ||
element == "rt" ||
element == "ruby" ||
element == "s" ||
element == "samp" ||
element == "script" ||
element == "section" ||
element == "select" ||
element == "slot" ||
element == "small" ||
element == "source" ||
element == "span" ||
element == "strike" ||
element == "strong" ||
element == "style" ||
element == "sub" ||
element == "summary" ||
element == "sup" ||
element == "table" ||
element == "tbody" ||
element == "td" ||
element == "template" ||
element == "textarea" ||
element == "tfoot" ||
element == "th" ||
element == "thead" ||
element == "time" ||
element == "title" ||
element == "tr" ||
element == "tt" ||
element == "track" ||
element == "u" ||
element == "ul" ||
element == "var" ||
element == "video" ||
element == "wbr" ||
element == "xmp"
}