Skip to main content

script/dom/node/
customelementregistry.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::collections::VecDeque;
7use std::ffi::CStr;
8use std::ptr::NonNull;
9use std::rc::Rc;
10use std::{mem, ptr};
11
12use dom_struct::dom_struct;
13use html5ever::{LocalName, Namespace, Prefix, ns};
14use js::context::JSContext;
15use js::conversions::{FromJSValConvertible, ToJSValConvertible};
16use js::glue::UnwrapObjectStatic;
17use js::jsapi::{HandleValueArray, Heap, IsCallable, IsConstructor, JSObject};
18use js::jsval::{BooleanValue, JSVal, NullValue, ObjectValue, UndefinedValue};
19use js::realm::{AutoRealm, CurrentRealm};
20use js::rust::wrappers2::{Construct1, SameValue};
21use js::rust::{HandleObject, MutableHandleValue};
22use rustc_hash::{FxBuildHasher, FxHashSet};
23use script_bindings::callback::HasCallbackHolder;
24use script_bindings::cell::DomRefCell;
25use script_bindings::domstring::TracedDOMString;
26use script_bindings::js::JS_GetProperty;
27use script_bindings::reflector::{DomObject, Reflector, reflect_dom_object_with_proto};
28use script_bindings::settings_stack::{run_a_callback, run_a_script};
29use style::attr::AttrValue;
30
31use crate::DomTypeHolder;
32use crate::dom::bindings::callback::{ExceptionHandling, RootedCallback, TracedCallback};
33use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::{
34    CustomElementConstructor, CustomElementRegistryMethods, ElementDefinitionOptions,
35};
36use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
37use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
38use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
39use crate::dom::bindings::conversions::{ConversionResult, StringificationBehavior, get_property};
40use crate::dom::bindings::error::{
41    Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception,
42};
43use crate::dom::bindings::inheritance::{Castable, DocumentFragmentTypeId, NodeTypeId};
44use crate::dom::bindings::reflector::DomGlobal;
45use crate::dom::bindings::root::{AsHandleValue, Dom, DomRoot, UnrootedDom};
46use crate::dom::bindings::str::DOMString;
47use crate::dom::bindings::trace::HashMapTracedValues;
48use crate::dom::document::Document;
49use crate::dom::domexception::{DOMErrorName, DOMException};
50use crate::dom::element::Element;
51use crate::dom::globalscope::GlobalScope;
52use crate::dom::html::htmlelement::HTMLElement;
53use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
54use crate::dom::iterators::ShadowIncluding;
55use crate::dom::node::{Node, NodeTraits};
56use crate::dom::promise::Promise;
57use crate::dom::shadowroot::shadowroot::ShadowRoot;
58use crate::dom::window::Window;
59use crate::dom::{RootedPromise, TracedPromise};
60use crate::event_loop::script_thread::ScriptThread;
61use crate::realms::enter_auto_realm;
62use crate::runtime::job_queue::CustomElementReactionMicrotask;
63
64/// <https://dom.spec.whatwg.org/#concept-element-custom-element-state>
65#[derive(Clone, Copy, Default, Eq, JSTraceable, MallocSizeOf, PartialEq)]
66pub(crate) enum CustomElementState {
67    Undefined,
68    Failed,
69    #[default]
70    Uncustomized,
71    Precustomized,
72    Custom,
73}
74
75/// <https://html.spec.whatwg.org/multipage/#customelementregistry>
76#[dom_struct]
77pub(crate) struct CustomElementRegistry {
78    reflector_: Reflector,
79
80    window: Dom<Window>,
81
82    /// It is safe to use FxBuildHasher here as `LocalName` is an `Atom` in the string_cache.
83    /// These get a u32 hashed instead of a string.
84    /// <https://html.spec.whatwg.org/multipage/#when-defined-promise-map>
85    when_defined: DomRefCell<HashMapTracedValues<LocalName, TracedPromise, FxBuildHasher>>,
86
87    /// <https://html.spec.whatwg.org/multipage/#element-definition-is-running>
88    element_definition_is_running: Cell<bool>,
89
90    /// <https://html.spec.whatwg.org/multipage/#is-scoped>
91    is_scoped: Cell<bool>,
92
93    /// <https://html.spec.whatwg.org/multipage/#scoped-document-set>
94    scoped_document_set: DomRefCell<FxHashSet<Dom<Document>>>,
95
96    #[conditional_malloc_size_of]
97    /// <https://html.spec.whatwg.org/multipage/#custom-element-definition-set>
98    definitions:
99        DomRefCell<HashMapTracedValues<LocalName, Rc<CustomElementDefinition>, FxBuildHasher>>,
100}
101
102impl CustomElementRegistry {
103    fn new_inherited(window: &Window) -> CustomElementRegistry {
104        CustomElementRegistry {
105            reflector_: Reflector::new(),
106            window: Dom::from_ref(window),
107            when_defined: DomRefCell::new(HashMapTracedValues::new_fx()),
108            element_definition_is_running: Cell::new(false),
109            is_scoped: Cell::new(false),
110            scoped_document_set: Default::default(),
111            definitions: DomRefCell::new(HashMapTracedValues::new_fx()),
112        }
113    }
114
115    pub(crate) fn new(cx: &mut JSContext, window: &Window) -> DomRoot<CustomElementRegistry> {
116        CustomElementRegistry::new_with_proto(cx, window, None)
117    }
118
119    fn new_with_proto(
120        cx: &mut JSContext,
121        window: &Window,
122        proto: Option<HandleObject>,
123    ) -> DomRoot<CustomElementRegistry> {
124        reflect_dom_object_with_proto(
125            cx,
126            Box::new(CustomElementRegistry::new_inherited(window)),
127            window,
128            proto,
129        )
130    }
131
132    /// <https://html.spec.whatwg.org/multipage/#is-scoped>
133    pub(crate) fn is_scoped(&self) -> bool {
134        self.is_scoped.get()
135    }
136
137    /// Cleans up any active promises
138    /// <https://github.com/servo/servo/issues/15318>
139    pub(crate) fn teardown(&self) {
140        self.when_defined.borrow_mut().0.clear()
141    }
142
143    /// <https://html.spec.whatwg.org/multipage/#htmlconstructor>
144    /// Step 5. Let definition be the item in registry's custom element
145    /// definition set with constructor equal to NewTarget.
146    pub(crate) fn lookup_definition_by_constructor(
147        &self,
148        constructor: HandleObject,
149    ) -> Option<Rc<CustomElementDefinition>> {
150        self.definitions
151            .borrow()
152            .0
153            .values()
154            .find(|definition| definition.constructor.callback() == constructor.get())
155            .cloned()
156    }
157
158    /// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-registry>
159    pub(crate) fn lookup_a_custom_element_registry(
160        node: &Node,
161    ) -> Option<DomRoot<CustomElementRegistry>> {
162        match node.type_id() {
163            // Step 1. If node is an Element object, then return node's custom element registry.
164            NodeTypeId::Element(_) => node
165                .downcast::<Element>()
166                .expect("Nodes with element type must be an element")
167                .custom_element_registry(),
168            // Step 2. If node is a ShadowRoot object, then return node's custom element registry.
169            NodeTypeId::DocumentFragment(DocumentFragmentTypeId::ShadowRoot) => node
170                .downcast::<ShadowRoot>()
171                .expect("Nodes with ShadowRoot type must be a ShadowRoot")
172                .custom_element_registry(),
173            // Step 3. If node is a Document object, then return node's custom element registry.
174            NodeTypeId::Document(_) => node
175                .downcast::<Document>()
176                .expect("Nodes with document type must be a document")
177                .custom_element_registry(),
178            // Step 4. Return null.
179            _ => None,
180        }
181    }
182
183    /// <https://html.spec.whatwg.org/multipage/#look-up-a-custom-element-definition>
184    pub(crate) fn lookup_custom_element_definition(
185        registry: Option<&CustomElementRegistry>,
186        namespace: &Namespace,
187        local_name: &LocalName,
188        is: Option<&LocalName>,
189    ) -> Option<Rc<CustomElementDefinition>> {
190        // Step 1. If registry is null, then return null.
191        let registry = registry?;
192
193        // Step 2. If namespace is not the HTML namespace, then return null.
194        if *namespace != ns!(html) {
195            return None;
196        }
197
198        // Step 3. If registry's custom element definition set contains an item
199        // with name and local name both equal to localName, then return that
200        // item.
201        // Step 4. If registry's custom element definition set contains an item
202        // with name equal to is and local name equal to localName, then return
203        // that item.
204        // Step 5. Return null.
205        registry
206            .definitions
207            .borrow()
208            .0
209            .values()
210            .find(|definition| {
211                definition.local_name == *local_name &&
212                    (definition.name == *local_name || Some(&definition.name) == is)
213            })
214            .cloned()
215    }
216
217    /// <https://dom.spec.whatwg.org/#is-a-global-custom-element-registry>
218    pub(crate) fn is_a_global_element_registry(registry: Option<&CustomElementRegistry>) -> bool {
219        // Null or a CustomElementRegistry object registry is a global custom element registry
220        // if registry is non-null and registry's is scoped is false.
221        registry.is_some_and(|r| !r.is_scoped())
222    }
223
224    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
225    /// Steps 10.1, 10.2
226    fn check_prototype(
227        &self,
228        cx: &mut JSContext,
229        constructor: HandleObject,
230        mut prototype: MutableHandleValue,
231    ) -> ErrorResult {
232        // Step 10.1
233        if !JS_GetProperty(cx, constructor, c"prototype", prototype.reborrow()) {
234            return Err(Error::JSFailed);
235        }
236
237        // Step 10.2
238        if !prototype.is_object() {
239            return Err(Error::Type(
240                c"constructor.prototype is not an object".to_owned(),
241            ));
242        }
243        Ok(())
244    }
245
246    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
247    /// This function includes both steps 14.3 and 14.4 which add the callbacks to a map and
248    /// process them.
249    fn get_callbacks(
250        &self,
251        cx: &mut JSContext,
252        prototype: HandleObject,
253    ) -> Fallible<RootedLifecycleCallbacks> {
254        // Step 4
255        Ok(RootedLifecycleCallbacks {
256            connected_callback: get_callback(cx, prototype, c"connectedCallback")?,
257            disconnected_callback: get_callback(cx, prototype, c"disconnectedCallback")?,
258            connected_move_callback: get_callback(cx, prototype, c"connectedMoveCallback")?,
259            adopted_callback: get_callback(cx, prototype, c"adoptedCallback")?,
260            attribute_changed_callback: get_callback(cx, prototype, c"attributeChangedCallback")?,
261
262            form_associated_callback: None,
263            form_disabled_callback: None,
264            form_reset_callback: None,
265            form_state_restore_callback: None,
266        })
267    }
268
269    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
270    /// Step 14.13: Add form associated callbacks to LifecycleCallbacks
271    fn add_form_associated_callbacks(
272        &self,
273        cx: &mut JSContext,
274        prototype: HandleObject,
275        callbacks: &mut RootedLifecycleCallbacks,
276    ) -> ErrorResult {
277        callbacks.form_associated_callback =
278            get_callback(cx, prototype, c"formAssociatedCallback")?;
279        callbacks.form_reset_callback = get_callback(cx, prototype, c"formResetCallback")?;
280        callbacks.form_disabled_callback = get_callback(cx, prototype, c"formDisabledCallback")?;
281        callbacks.form_state_restore_callback =
282            get_callback(cx, prototype, c"formStateRestoreCallback")?;
283
284        Ok(())
285    }
286
287    /// <https://html.spec.whatwg.org/multipage/#upgrade-particular-elements-within-a-document>
288    fn upgrade_particular_elements_within_a_document(
289        &self,
290        cx: &JSContext,
291        document: &Document,
292        definition: &Rc<CustomElementDefinition>,
293        local_name: &LocalName,
294        name: &LocalName,
295    ) {
296        // Step 1. Let upgradeCandidates be all elements that are shadow-including
297        // descendants of document, whose custom element registry is registry, whose
298        // namespace is the HTML namespace, and whose local name is localName,
299        // in shadow-including tree order. Additionally, if name is not localName,
300        // only include elements whose is value is equal to name.
301        for candidate in document
302            .upcast::<Node>()
303            .traverse_preorder_unrooted(cx, ShadowIncluding::Yes)
304            .filter_map(UnrootedDom::downcast::<Element>)
305        {
306            // Note: If the registry is scoped, only include elements whose custom
307            // element registry is explicitly set to this registry. Otherwise,
308            // include elements with no explicit registry (they inherit the
309            // document's global registry) as well.
310            let registry_matches = if self.is_scoped.get() {
311                candidate
312                    .custom_element_registry()
313                    .is_some_and(|registry| *registry == *self)
314            } else {
315                candidate
316                    .custom_element_registry()
317                    .is_none_or(|registry| *registry == *self)
318            };
319            if *candidate.local_name() == *local_name &&
320                *candidate.namespace() == ns!(html) &&
321                registry_matches &&
322                (*name == *local_name || candidate.get_is().as_ref() == Some(name))
323            {
324                // Step 2. For each element element of upgradeCandidates: enqueue a
325                // custom element upgrade reaction given element and definition.
326                ScriptThread::enqueue_upgrade_reaction(cx, &candidate, definition.clone());
327            }
328        }
329    }
330
331    pub(crate) fn add_scoped_document(&self, document: &Document) {
332        self.scoped_document_set
333            .borrow_mut()
334            .insert(Dom::from_ref(document));
335    }
336}
337
338/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
339/// Step 14.4: Get `callbackValue` for all `callbackName` in `lifecycleCallbacks`.
340#[expect(unsafe_code)]
341fn get_callback(
342    cx: &mut JSContext,
343    prototype: HandleObject,
344    name: &CStr,
345) -> Fallible<Option<RootedCallback<Function>>> {
346    rooted!(&in(cx) let mut callback = UndefinedValue());
347    unsafe {
348        // Step 10.4.1
349        if !JS_GetProperty(cx, prototype, name, callback.handle_mut()) {
350            return Err(Error::JSFailed);
351        }
352
353        // Step 10.4.2
354        if !callback.is_undefined() {
355            if !callback.is_object() || !IsCallable(callback.to_object()) {
356                return Err(Error::Type(
357                    c"Lifecycle callback is not callable".to_owned(),
358                ));
359            }
360            Ok(Some(Function::new(cx, callback.to_object())))
361        } else {
362            Ok(None)
363        }
364    }
365}
366
367impl CustomElementRegistryMethods<crate::DomTypeHolder> for CustomElementRegistry {
368    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry>
369    fn Constructor(
370        cx: &mut JSContext,
371        window: &Window,
372        proto: Option<HandleObject>,
373    ) -> DomRoot<CustomElementRegistry> {
374        let registry = CustomElementRegistry::new_with_proto(cx, window, proto);
375
376        // Step 1: Set this's is scoped to true.
377        registry.is_scoped.set(true);
378        registry
379    }
380
381    #[expect(unsafe_code)]
382    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-define>
383    fn Define(
384        &self,
385        cx: &mut JSContext,
386        name: DOMString,
387        constructor_: RootedCallback<CustomElementConstructor>,
388        options: &ElementDefinitionOptions,
389    ) -> ErrorResult {
390        rooted!(&in(cx) let constructor = constructor_.callback());
391        let name = LocalName::from(name);
392
393        // Step 1. If IsConstructor(constructor) is false, then throw a TypeError.
394        // We must unwrap the constructor as all wrappers are constructable if they are callable.
395        rooted!(&in(cx) let unwrapped_constructor = unsafe { UnwrapObjectStatic(constructor.get()) });
396
397        if unwrapped_constructor.is_null() {
398            // We do not have permission to access the unwrapped constructor.
399            return Err(Error::Security(None));
400        }
401
402        if unsafe { !IsConstructor(unwrapped_constructor.get()) } {
403            return Err(Error::Type(
404                c"Second argument of CustomElementRegistry.define is not a constructor".to_owned(),
405            ));
406        }
407
408        // Step 2. If name is not a valid custom element name, then throw a "SyntaxError" DOMException.
409        if !is_valid_custom_element_name(&name) {
410            return Err(Error::Syntax(Some(format!(
411                "{} name is not a valid custom element name",
412                name
413            ))));
414        }
415
416        // Step 3. If this's custom element definition set contains an item with name name,
417        // then throw a "NotSupportedError" DOMException.
418        if self.definitions.borrow().contains_key(&name) {
419            return Err(Error::NotSupported(Some(format!(
420                "{} has already been defined as a custom element",
421                name
422            ))));
423        }
424
425        // Step 4. If this's custom element definition set contains an
426        // item with constructor constructor, then throw a "NotSupportedError" DOMException.
427        if self
428            .definitions
429            .borrow()
430            .iter()
431            .any(|(_, def)| def.constructor.callback() == constructor_.callback())
432        {
433            return Err(Error::NotSupported(None));
434        }
435
436        // Step 6. Let extends be options["extends"] if it exists; otherwise null.
437        let extends = &options.extends;
438
439        // Steps 5, 7
440        let local_name = if let Some(ref extended_name) = *extends {
441            // Step 7.1 If this's is scoped is true, then throw a "NotSupportedError" DOMException.
442            if self.is_scoped.get() {
443                return Err(Error::NotSupported(Some(
444                    "Scoped custom element registries cannot define customized built-in elements"
445                        .to_owned(),
446                )));
447            }
448
449            // Step 7.2 If extends is a valid custom element name, then throw a "NotSupportedError" DOMException.
450            if is_valid_custom_element_name(&extended_name.str()) {
451                return Err(Error::NotSupported(None));
452            }
453
454            // Step 7.3 If the element interface for extends and the HTML namespace is HTMLUnknownElement
455            // (e.g., if extends does not indicate an element definition in this specification)
456            // then throw a "NotSupportedError" DOMException.
457            if !is_extendable_element_interface(&extended_name.str()) {
458                return Err(Error::NotSupported(None));
459            }
460
461            // Step 7.4 Set localName to extends.
462            LocalName::from(extended_name)
463        } else {
464            // Step 5. Let localName be name.
465            name.clone()
466        };
467
468        // Step 8
469        if self.element_definition_is_running.get() {
470            return Err(Error::NotSupported(None));
471        }
472
473        // Step 9
474        self.element_definition_is_running.set(true);
475
476        // Steps 10-13: Initialize `formAssociated`, `disableInternals`, `disableShadow`, and
477        // `observedAttributes` with default values, but this is done later.
478
479        // Steps 14.1 - 14.2: Get the value of the prototype.
480        rooted!(&in(cx) let mut prototype = UndefinedValue());
481        {
482            let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
483            if let Err(error) =
484                self.check_prototype(&mut realm, constructor.handle(), prototype.handle_mut())
485            {
486                self.element_definition_is_running.set(false);
487                return Err(error);
488            }
489        };
490
491        // Steps 10.3 - 10.4
492        // It would be easier to get all the callbacks in one pass after
493        // we know whether this definition is going to be form-associated,
494        // but the order of operations is specified and it's observable
495        // if one of the callback getters throws an exception.
496        rooted!(&in(cx) let proto_object = prototype.to_object());
497        let mut callbacks = {
498            let mut realm = AutoRealm::new_from_handle(cx, proto_object.handle());
499            match self.get_callbacks(&mut realm, proto_object.handle()) {
500                Ok(callbacks) => callbacks,
501                Err(error) => {
502                    self.element_definition_is_running.set(false);
503                    return Err(error);
504                },
505            }
506        };
507
508        // Step 14.5: Handle the case where with `attributeChangedCallback` on `lifecycleCallbacks`
509        // is not null.
510        let observed_attributes: Vec<DOMString> = if callbacks.attribute_changed_callback.is_some()
511        {
512            let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
513            match get_property(
514                &mut realm,
515                constructor.handle(),
516                c"observedAttributes",
517                StringificationBehavior::Default,
518            ) {
519                Ok(attributes) => attributes.unwrap_or_default(),
520                Err(error) => {
521                    self.element_definition_is_running.set(false);
522                    return Err(error);
523                },
524            }
525        } else {
526            Vec::new()
527        };
528
529        // Steps 14.6 - 14.10: Handle `disabledFeatures`.
530        let (disable_internals, disable_shadow) = {
531            let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
532            match get_property::<Vec<DOMString>>(
533                &mut realm,
534                constructor.handle(),
535                c"disabledFeatures",
536                StringificationBehavior::Default,
537            ) {
538                Ok(sequence) => {
539                    let sequence = sequence.unwrap_or_default();
540                    (
541                        sequence.iter().any(|s| *s == "internals"),
542                        sequence.iter().any(|s| *s == "shadow"),
543                    )
544                },
545                Err(error) => {
546                    self.element_definition_is_running.set(false);
547                    return Err(error);
548                },
549            }
550        };
551
552        // Step 14.11 - 14.12: Handle `formAssociated`.
553        let form_associated: bool = {
554            let mut realm = AutoRealm::new_from_handle(cx, constructor.handle());
555            match get_property(&mut realm, constructor.handle(), c"formAssociated", ()) {
556                Ok(flag) => flag.unwrap_or_default(),
557                Err(error) => {
558                    self.element_definition_is_running.set(false);
559                    return Err(error);
560                },
561            }
562        };
563
564        // Steps 14.13: Add the `formAssociated` callbacks.
565        if form_associated {
566            let mut realm = AutoRealm::new_from_handle(cx, proto_object.handle());
567            if let Err(error) = self.add_form_associated_callbacks(
568                &mut realm,
569                proto_object.handle(),
570                &mut callbacks,
571            ) {
572                self.element_definition_is_running.set(false);
573                return Err(error);
574            }
575        }
576
577        self.element_definition_is_running.set(false);
578
579        // Step 15: Let definition be a new custom element definition with name name,
580        // local name localName, constructor constructor, observed attributes
581        // observedAttributes, lifecycle callbacks lifecycleCallbacks,
582        // form-associated formAssociated, disable internals disableInternals,
583        // and disable shadow disableShadow.
584        let definition = Rc::new(CustomElementDefinition::new(
585            name.clone(),
586            local_name.clone(),
587            constructor_,
588            observed_attributes,
589            callbacks,
590            form_associated,
591            disable_internals,
592            disable_shadow,
593        ));
594
595        // Step 16: Append definition to this's custom element definition set.
596        self.definitions
597            .safe_borrow_mut(cx.no_gc())
598            .insert(name.clone(), definition.clone());
599
600        // Step 17: If this's is scoped is true, then for each document of
601        // this's scoped document set: upgrade particular elements within a
602        // document given this, document, definition, and localName.
603        if self.is_scoped.get() {
604            for document in self.scoped_document_set.borrow().iter() {
605                self.upgrade_particular_elements_within_a_document(
606                    cx,
607                    document,
608                    &definition,
609                    &local_name,
610                    &local_name,
611                );
612            }
613        } else {
614            // Step 18: Otherwise, upgrade particular elements within a document given
615            // this, this's relevant global object's associated Document, definition,
616            // localName, and name.
617            self.upgrade_particular_elements_within_a_document(
618                cx,
619                &self.window.Document(),
620                &definition,
621                &local_name,
622                &name,
623            );
624        }
625
626        // Step 19: If this's when-defined promise map[name] exists:
627        // Step 19.2: Remove this's when-defined promise map[name].
628        let promise = self
629            .when_defined
630            .safe_borrow_mut(cx.no_gc())
631            .remove(&name)
632            .map(|promise| promise.root(cx));
633        if let Some(promise) = promise {
634            rooted!(&in(cx) let mut constructor = UndefinedValue());
635            definition
636                .constructor
637                .to_jsval(cx, constructor.handle_mut());
638            // Step 19.1: Resolve this's when-defined promise map[name] with constructor.
639            promise.resolve_native(cx, &constructor.get());
640        }
641        Ok(())
642    }
643
644    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get>
645    fn Get(&self, cx: &mut JSContext, name: DOMString, mut retval: MutableHandleValue) {
646        match self.definitions.borrow().get(&LocalName::from(name)) {
647            Some(definition) => definition.constructor.to_jsval(cx, retval),
648            None => retval.set(UndefinedValue()),
649        }
650    }
651
652    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-getname>
653    fn GetName(&self, constructor: RootedCallback<CustomElementConstructor>) -> Option<DOMString> {
654        self.definitions
655            .borrow()
656            .0
657            .values()
658            .find(|definition| definition.constructor.callback() == constructor.callback())
659            .map(|definition| TracedDOMString::from(definition.name.clone()).root())
660    }
661
662    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-whendefined>
663    fn WhenDefined(&self, realm: &mut CurrentRealm, name: DOMString) -> RootedPromise {
664        let name = LocalName::from(name);
665
666        // Step 1
667        if !is_valid_custom_element_name(&name) {
668            let promise = Promise::new_in_realm(realm);
669            let error = DOMException::new(
670                realm,
671                self.window.as_global_scope(),
672                DOMErrorName::SyntaxError,
673            );
674            promise.reject_native(realm, &error);
675            return promise;
676        }
677
678        // Step 2
679        if let Some(definition) = self.definitions.borrow().get(&LocalName::from(&*name)) {
680            rooted!(&in(*realm) let mut constructor = UndefinedValue());
681            definition
682                .constructor
683                .to_jsval(realm, constructor.handle_mut());
684            let promise = Promise::new_in_realm(realm);
685            promise.resolve_native(realm, &constructor.get());
686            return promise;
687        }
688
689        // Steps 3, 4, 5, 6
690        let existing_promise = self
691            .when_defined
692            .borrow()
693            .get(&name)
694            .map(|promise| promise.root(realm));
695        existing_promise.unwrap_or_else(|| {
696            let promise = Promise::new_in_realm(realm);
697            self.when_defined
698                .safe_borrow_mut(realm.no_gc())
699                .insert(name, promise.to_traced());
700            promise
701        })
702    }
703
704    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-upgrade>
705    fn Upgrade(&self, cx: &JSContext, node: &Node) {
706        // Step 1. For each shadow-including inclusive descendant candidate of
707        // root, in shadow-including tree order:
708        for node in node.traverse_preorder_unrooted(cx, ShadowIncluding::Yes) {
709            // Step 1.1. If candidate is not an Element node, then continue.
710            let Some(element) = node.downcast::<Element>() else {
711                continue;
712            };
713            // Step 1.2. If candidate's custom element registry is not this,
714            // then continue.
715            if element
716                .custom_element_registry()
717                .is_some_and(|registry| *registry != *self)
718            {
719                continue;
720            }
721            // Step 1.3. Try to upgrade candidate.
722            try_upgrade_element(cx, element);
723        }
724    }
725
726    /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-initialize>
727    fn Initialize(&self, cx: &JSContext, root: &Node) -> ErrorResult {
728        // Step 1. If this's is scoped is false and either root is a Document node
729        // or root's node document's custom element registry is not this, then
730        // throw a "NotSupportedError" DOMException.
731        if !self.is_scoped.get() {
732            let is_document = root.is::<Document>();
733            let registry_mismatch = root
734                .owner_doc()
735                .custom_element_registry()
736                .is_some_and(|registry| *registry != *self);
737            if is_document || registry_mismatch {
738                return Err(Error::NotSupported(Some(
739                    "Initialize is not allowed on a non-scoped registry for this root".to_owned(),
740                )));
741            }
742        }
743
744        // Step 2. If root is a Document node whose custom element registry is null,
745        // then set root's custom element registry to this.
746        if let Some(document) = root.downcast::<Document>() {
747            if document.custom_element_registry().is_none() {
748                document.set_custom_element_registry(self);
749            }
750        }
751        // Step 3. Otherwise, if root is a ShadowRoot node whose custom element registry
752        // is null, then set root's custom element registry to this.
753        else if let Some(shadow_root) = root.downcast::<ShadowRoot>() &&
754            shadow_root.custom_element_registry().is_none()
755        {
756            shadow_root.set_custom_element_registry(Some(self));
757        }
758
759        // Step 4. For each inclusive descendant inclusiveDescendant of root, in tree order:
760        for node in root.traverse_preorder(ShadowIncluding::No) {
761            // Step 4.1. If inclusiveDescendant is not an Element node, then continue.
762            let Some(element) = node.downcast::<Element>() else {
763                continue;
764            };
765
766            // Step 4.2. If inclusiveDescendant's custom element registry is null:
767            // Note: A global registry (set by Node::adopt) is treated the same as null.
768            //       Both mean the element has no scoped registry, so it should get this one.
769            if element
770                .custom_element_registry()
771                .is_none_or(|registry| Self::is_a_global_element_registry(Some(&*registry)))
772            {
773                // Step 4.2.1. Set inclusiveDescendant's custom element registry to this.
774                element.set_custom_element_registry(Some(self), cx.no_gc());
775
776                // Step 4.2.2. If this's is scoped is true, then append
777                // inclusiveDescendant's node document to this's scoped document set.
778                if self.is_scoped.get() {
779                    let document = element.upcast::<Node>().owner_doc();
780                    self.scoped_document_set
781                        .safe_borrow_mut(cx.no_gc())
782                        .insert(Dom::from_ref(&document));
783                }
784            // Step 4.3. If inclusiveDescendant's custom element registry is not this, then continue.
785            } else if element
786                .custom_element_registry()
787                .is_none_or(|registry| *registry != *self)
788            {
789                continue;
790            }
791
792            // Step 4.4. Try to upgrade inclusiveDescendant.
793            try_upgrade_element(cx, element);
794        }
795        Ok(())
796    }
797}
798
799#[derive(Clone, JSTraceable, MallocSizeOf)]
800#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
801pub(crate) struct LifecycleCallbacks {
802    connected_callback: Option<TracedCallback<Function>>,
803    connected_move_callback: Option<TracedCallback<Function>>,
804    disconnected_callback: Option<TracedCallback<Function>>,
805    adopted_callback: Option<TracedCallback<Function>>,
806    attribute_changed_callback: Option<TracedCallback<Function>>,
807    form_associated_callback: Option<TracedCallback<Function>>,
808    form_reset_callback: Option<TracedCallback<Function>>,
809    form_disabled_callback: Option<TracedCallback<Function>>,
810    form_state_restore_callback: Option<TracedCallback<Function>>,
811}
812
813struct RootedLifecycleCallbacks {
814    connected_callback: Option<RootedCallback<Function>>,
815    connected_move_callback: Option<RootedCallback<Function>>,
816    disconnected_callback: Option<RootedCallback<Function>>,
817    adopted_callback: Option<RootedCallback<Function>>,
818    attribute_changed_callback: Option<RootedCallback<Function>>,
819    form_associated_callback: Option<RootedCallback<Function>>,
820    form_reset_callback: Option<RootedCallback<Function>>,
821    form_disabled_callback: Option<RootedCallback<Function>>,
822    form_state_restore_callback: Option<RootedCallback<Function>>,
823}
824
825impl From<RootedLifecycleCallbacks> for LifecycleCallbacks {
826    fn from(callbacks: RootedLifecycleCallbacks) -> Self {
827        Self {
828            connected_callback: callbacks
829                .connected_callback
830                .map(|callback| callback.to_traced()),
831            connected_move_callback: callbacks
832                .connected_move_callback
833                .map(|callback| callback.to_traced()),
834            disconnected_callback: callbacks
835                .disconnected_callback
836                .map(|callback| callback.to_traced()),
837            adopted_callback: callbacks
838                .adopted_callback
839                .map(|callback| callback.to_traced()),
840            attribute_changed_callback: callbacks
841                .attribute_changed_callback
842                .map(|callback| callback.to_traced()),
843            form_associated_callback: callbacks
844                .form_associated_callback
845                .map(|callback| callback.to_traced()),
846            form_reset_callback: callbacks
847                .form_reset_callback
848                .map(|callback| callback.to_traced()),
849            form_disabled_callback: callbacks
850                .form_disabled_callback
851                .map(|callback| callback.to_traced()),
852            form_state_restore_callback: callbacks
853                .form_state_restore_callback
854                .map(|callback| callback.to_traced()),
855        }
856    }
857}
858
859#[derive(Clone, JSTraceable, MallocSizeOf)]
860#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
861pub(crate) enum ConstructionStackEntry {
862    Element(Dom<Element>),
863    AlreadyConstructedMarker,
864}
865
866/// <https://html.spec.whatwg.org/multipage/#custom-element-definition>
867/// # Safety
868/// This can be shared inside an Rc because every Rc copy is reachable from a
869/// CustomElementRegistry's definitions map, which the GC traces.
870#[derive(Clone, JSTraceable, MallocSizeOf)]
871#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
872#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
873pub(crate) struct CustomElementDefinition {
874    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-name>
875    #[no_trace]
876    pub(crate) name: LocalName,
877
878    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-local-name>
879    #[no_trace]
880    pub(crate) local_name: LocalName,
881
882    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-constructor>
883    pub(crate) constructor: TracedCallback<CustomElementConstructor>,
884
885    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-observed-attributes>
886    pub(crate) observed_attributes: Vec<DOMString>,
887
888    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-lifecycle-callbacks>
889    pub(crate) callbacks: LifecycleCallbacks,
890
891    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-construction-stack>
892    pub(crate) construction_stack: DomRefCell<Vec<ConstructionStackEntry>>,
893
894    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-form-associated>
895    pub(crate) form_associated: bool,
896
897    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-disable-internals>
898    pub(crate) disable_internals: bool,
899
900    /// <https://html.spec.whatwg.org/multipage/#concept-custom-element-definition-disable-shadow>
901    pub(crate) disable_shadow: bool,
902}
903
904impl CustomElementDefinition {
905    #[expect(clippy::too_many_arguments)]
906    fn new(
907        name: LocalName,
908        local_name: LocalName,
909        constructor: RootedCallback<CustomElementConstructor>,
910        observed_attributes: Vec<DOMString>,
911        callbacks: RootedLifecycleCallbacks,
912        form_associated: bool,
913        disable_internals: bool,
914        disable_shadow: bool,
915    ) -> CustomElementDefinition {
916        CustomElementDefinition {
917            name,
918            local_name,
919            constructor: constructor.to_traced(),
920            observed_attributes,
921            callbacks: callbacks.into(),
922            construction_stack: Default::default(),
923            form_associated,
924            disable_internals,
925            disable_shadow,
926        }
927    }
928
929    /// <https://html.spec.whatwg.org/multipage/#autonomous-custom-element>
930    pub(crate) fn is_autonomous(&self) -> bool {
931        self.name == self.local_name
932    }
933
934    /// <https://dom.spec.whatwg.org/#concept-create-element> Step 5.1
935    #[expect(unsafe_code)]
936    pub(crate) fn create_element(
937        &self,
938        cx: &mut JSContext,
939        document: &Document,
940        prefix: Option<Prefix>,
941        registry: Option<&CustomElementRegistry>,
942    ) -> Fallible<DomRoot<Element>> {
943        let window = document.window();
944
945        // Step 5.1.1. Let C be definition’s constructor.
946        rooted!(&in(cx) let constructor = ObjectValue(self.constructor.callback()));
947        rooted!(&in(cx) let mut element = ptr::null_mut::<JSObject>());
948        {
949            // Go into the constructor's realm
950            let mut realm = AutoRealm::new(cx, NonNull::new(self.constructor.callback()).unwrap());
951            let cx = &mut realm;
952
953            // Step 5.3.1. Set result to the result of constructing C, with no arguments.
954            // https://webidl.spec.whatwg.org/#construct-a-callback-function
955            run_a_script::<DomTypeHolder, _, _>(cx, window.upcast(), |cx| {
956                run_a_callback::<DomTypeHolder, _>(window.upcast(), || {
957                    let args = HandleValueArray::empty();
958                    if unsafe { !Construct1(cx, constructor.handle(), &args, element.handle_mut()) }
959                    {
960                        Err(Error::JSFailed)
961                    } else {
962                        Ok(())
963                    }
964                })
965            })?;
966        }
967
968        rooted!(&in(cx) let element_val = ObjectValue(element.get()));
969        let element: DomRoot<Element> =
970            match FromJSValConvertible::from_jsval(cx, element_val.handle(), ()) {
971                Ok(ConversionResult::Success(element)) => element,
972                Ok(ConversionResult::Failure(..)) => {
973                    return Err(Error::Type(
974                        c"Constructor did not return a DOM node".to_owned(),
975                    ));
976                },
977                _ => return Err(Error::JSFailed),
978            };
979
980        // Step 5.1.3.2 Assert: result’s custom element state and custom element definition are initialized.
981        // Step 5.1.3.3 Assert: result’s namespace is the HTML namespace.
982        // Note: IDL enforces that result is an HTMLElement object, which all use the HTML namespace.
983        // Note: the custom element definition is initialized by the caller if
984        // this method returns a success value.
985        assert!(element.is::<HTMLElement>());
986
987        // Step 5.1.3.4. If result’s attribute list is not empty, then throw a "NotSupportedError" DOMException.
988        // Step 5.1.3.5. If result has children, then throw a "NotSupportedError" DOMException.
989        // Step 5.1.3.6. If result’s parent is not null, then throw a "NotSupportedError" DOMException.
990        // Step 5.1.3.7. If result’s node document is not document, then throw a "NotSupportedError" DOMException.
991        // Step 5.1.3.8. If result’s local name is not equal to localName then throw a "NotSupportedError" DOMException.
992        if element.HasAttributes() ||
993            element.upcast::<Node>().children_count() > 0 ||
994            element.upcast::<Node>().has_parent() ||
995            &*element.upcast::<Node>().owner_doc() != document ||
996            *element.namespace() != ns!(html) ||
997            *element.local_name() != self.local_name
998        {
999            return Err(Error::NotSupported(None));
1000        }
1001
1002        // Step 5.1.3.9. Set result’s namespace prefix to prefix.
1003        element.set_prefix(prefix);
1004
1005        // Step 5.1.3.10. Set result’s is value to null.
1006        // Element's `is` is None by default
1007
1008        // Step 5.1.3.11. Set result’s custom element registry to registry.
1009        element.set_custom_element_registry(registry, cx.no_gc());
1010
1011        Ok(element)
1012    }
1013
1014    pub(crate) fn has_attribute_changed_callback(&self) -> bool {
1015        self.callbacks.attribute_changed_callback.is_some()
1016    }
1017}
1018
1019/// <https://html.spec.whatwg.org/multipage/#concept-upgrade-an-element>
1020pub(crate) fn upgrade_element(
1021    cx: &mut JSContext,
1022    definition: Rc<CustomElementDefinition>,
1023    element: &Element,
1024) {
1025    // Step 1. If element's custom element state is not "undefined" or "uncustomized", then return.
1026    let state = element.get_custom_element_state();
1027    if state != CustomElementState::Undefined && state != CustomElementState::Uncustomized {
1028        return;
1029    }
1030
1031    // Step 2. Set element's custom element definition to definition.
1032    element.set_custom_element_definition(Rc::clone(&definition), cx.no_gc());
1033
1034    // Step 3. Set element's custom element state to "failed".
1035    element.set_custom_element_state(CustomElementState::Failed, cx.no_gc());
1036
1037    // Step 4. For each attribute in element's attribute list, in order, enqueue a custom element callback reaction
1038    // with element, callback name "attributeChangedCallback", and « attribute's local name, null, attribute's value,
1039    // attribute's namespace ».
1040    let custom_element_reaction_stack = ScriptThread::custom_element_reaction_stack();
1041    for attr in element.attrs().borrow().iter() {
1042        let local_name = attr.local_name().clone();
1043        let namespace = attr.namespace().clone();
1044        custom_element_reaction_stack.enqueue_callback_reaction(
1045            cx,
1046            element,
1047            CallbackReaction::AttributeChanged(local_name, None, Some(&*attr.value()), namespace),
1048            Some(definition.clone()),
1049        );
1050    }
1051
1052    // Step 5. If element is connected, then enqueue a custom element callback reaction with element,
1053    // callback name "connectedCallback", and « ».
1054    if element.is_connected() {
1055        custom_element_reaction_stack.enqueue_callback_reaction(
1056            cx,
1057            element,
1058            CallbackReaction::Connected,
1059            Some(definition.clone()),
1060        );
1061    }
1062
1063    // Step 6. Add element to the end of definition's construction stack.
1064    definition
1065        .construction_stack
1066        .safe_borrow_mut(cx.no_gc())
1067        .push(ConstructionStackEntry::Element(Dom::from_ref(element)));
1068
1069    // Steps 7-8, successful case
1070    let result = run_upgrade_constructor(cx, &definition, element);
1071
1072    // "regardless of whether the above steps threw an exception" step
1073    definition
1074        .construction_stack
1075        .safe_borrow_mut(cx.no_gc())
1076        .pop();
1077
1078    // Step 8 exception handling
1079    if let Err(error) = result {
1080        // Step 8.exception.1
1081        element.clear_custom_element_definition(cx.no_gc());
1082
1083        // Step 8.exception.2
1084        element.clear_reaction_queue();
1085
1086        // Step 8.exception.3
1087        let global = GlobalScope::current().expect("No current global");
1088
1089        let mut realm = enter_auto_realm(cx, &*global);
1090        let cx = &mut realm.current_realm();
1091
1092        throw_dom_exception(cx, &global, error);
1093        report_pending_exception(cx);
1094
1095        return;
1096    }
1097
1098    // Step 9: handle with form-associated custom element
1099    if let Some(html_element) = element.downcast::<HTMLElement>() &&
1100        html_element.is_form_associated_custom_element()
1101    {
1102        // We know this element is is form-associated, so we can use the implementation of
1103        // `FormControl` for HTMLElement, which makes that assumption.
1104        // Step 9.1: Reset the form owner of element
1105        html_element.reset_form_owner(cx);
1106        if let Some(form) = html_element.form_owner() {
1107            // Even though the tree hasn't structurally mutated,
1108            // HTMLCollections need to be invalidated.
1109            form.upcast::<Node>().rev_version(cx.no_gc());
1110            // The spec tells us specifically to enqueue a formAssociated reaction
1111            // here, but it also says to do that for resetting form owner in general,
1112            // and we don't need two reactions.
1113        }
1114
1115        // Either enabled_state or disabled_state needs to be set,
1116        // and the possibility of a disabled fieldset ancestor needs
1117        // to be accounted for. (In the spec, being disabled is
1118        // a fact that's true or false about a node at a given time,
1119        // not a flag that belongs to the node and is updated,
1120        // so it doesn't describe this check as an action.)
1121        element.check_disabled_attribute(cx.no_gc());
1122        element.check_ancestors_disabled_state_for_form_control(cx.no_gc());
1123        element.update_read_write_state_from_readonly_attribute(cx.no_gc());
1124
1125        // Step 9.2: If element is disabled, then enqueue a custom element callback reaction
1126        // with element.
1127        if element.disabled_state() {
1128            custom_element_reaction_stack.enqueue_callback_reaction(
1129                cx,
1130                element,
1131                CallbackReaction::FormDisabled(true),
1132                Some(definition),
1133            )
1134        }
1135    }
1136
1137    // Step 10
1138    element.set_custom_element_state(CustomElementState::Custom, cx.no_gc());
1139}
1140
1141/// <https://html.spec.whatwg.org/multipage/#concept-upgrade-an-element>
1142/// Steps 9.1-9.4
1143#[expect(unsafe_code)]
1144fn run_upgrade_constructor(
1145    cx: &mut JSContext,
1146    definition: &CustomElementDefinition,
1147    element: &Element,
1148) -> ErrorResult {
1149    let constructor = &definition.constructor;
1150    let window = element.owner_window();
1151    rooted!(&in(cx) let constructor_val = ObjectValue(constructor.callback()));
1152    rooted!(&in(cx) let mut element_val = UndefinedValue());
1153    element.to_jsval(cx, element_val.handle_mut());
1154    rooted!(&in(cx) let mut construct_result = ptr::null_mut::<JSObject>());
1155    {
1156        // Step 9.1. If definition's disable shadow is true and element's shadow root is non-null,
1157        // then throw a "NotSupportedError" DOMException.
1158        if definition.disable_shadow && element.is_shadow_host() {
1159            return Err(Error::NotSupported(None));
1160        }
1161
1162        // Go into the constructor's realm
1163        let mut realm = AutoRealm::new(cx, NonNull::new(constructor.callback()).unwrap());
1164        let cx = &mut *realm;
1165
1166        let args = HandleValueArray::empty();
1167        // Step 8.2. Set element's custom element state to "precustomized".
1168        element.set_custom_element_state(CustomElementState::Precustomized, cx.no_gc());
1169
1170        // Step 9.3. Let constructResult be the result of constructing C, with no arguments.
1171        // https://webidl.spec.whatwg.org/#construct-a-callback-function
1172        run_a_script::<DomTypeHolder, _, _>(cx, window.upcast(), |cx| {
1173            run_a_callback::<DomTypeHolder, _>(window.upcast(), || {
1174                if unsafe {
1175                    !Construct1(
1176                        cx,
1177                        constructor_val.handle(),
1178                        &args,
1179                        construct_result.handle_mut(),
1180                    )
1181                } {
1182                    Err(Error::JSFailed)
1183                } else {
1184                    Ok(())
1185                }
1186            })
1187        })?;
1188
1189        let mut same = false;
1190        rooted!(&in(cx) let construct_result_val = ObjectValue(construct_result.get()));
1191
1192        // Step 9.4. If SameValue(constructResult, element) is false, then throw a TypeError.
1193        if unsafe {
1194            !SameValue(
1195                cx,
1196                construct_result_val.handle(),
1197                element_val.handle(),
1198                &mut same,
1199            )
1200        } {
1201            return Err(Error::JSFailed);
1202        }
1203        if !same {
1204            return Err(Error::Type(
1205                c"Returned element is not SameValue as the upgraded element".to_owned(),
1206            ));
1207        }
1208    }
1209    Ok(())
1210}
1211
1212/// <https://html.spec.whatwg.org/multipage/#concept-try-upgrade>
1213pub(crate) fn try_upgrade_element(cx: &JSContext, element: &Element) {
1214    // Step 1. Let definition be the result of looking up a custom element
1215    // definition given element's custom element registry, element's namespace,
1216    // element's local name, and element's is value.
1217    let lookup_registry = {
1218        // TODO: Remove this fallback when Node::adopt is aligned according to specs.
1219        //       Currently elements carry stale global registry from another document.
1220        let registry = element.custom_element_registry();
1221        if registry
1222            .as_ref()
1223            .is_some_and(|registry| registry.is_scoped())
1224        {
1225            registry
1226        } else {
1227            element
1228                .owner_document_unrooted(cx.no_gc())
1229                .custom_element_registry()
1230        }
1231    };
1232    if let Some(definition) = CustomElementRegistry::lookup_custom_element_definition(
1233        lookup_registry.as_deref(),
1234        element.namespace(),
1235        element.local_name(),
1236        element.get_is().as_ref(),
1237    ) {
1238        // Step 2. If definition is not null, then enqueue a custom element
1239        // upgrade reaction given element and definition.
1240        ScriptThread::enqueue_upgrade_reaction(cx, element, definition);
1241    }
1242}
1243
1244#[derive(JSTraceable, MallocSizeOf)]
1245#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
1246pub(crate) enum CustomElementReaction {
1247    Upgrade(#[conditional_malloc_size_of] Rc<CustomElementDefinition>),
1248    Callback(
1249        TracedCallback<Function>,
1250        #[ignore_malloc_size_of = "mozjs"] Box<[Heap<JSVal>]>,
1251    ),
1252}
1253
1254impl CustomElementReaction {
1255    /// <https://html.spec.whatwg.org/multipage/#invoke-custom-element-reactions>
1256    pub(crate) fn invoke(&self, cx: &mut JSContext, element: &Element) {
1257        // Step 2.1
1258        match *self {
1259            CustomElementReaction::Upgrade(ref definition) => {
1260                upgrade_element(cx, definition.clone(), element)
1261            },
1262            CustomElementReaction::Callback(ref callback, ref arguments) => {
1263                // We're rooted, so it's safe to hand out a handle to objects in Heap
1264                let arguments = arguments.iter().map(|arg| arg.as_handle_value()).collect();
1265                rooted!(&in(cx) let mut value: JSVal);
1266                let _ = callback.Call_(
1267                    cx,
1268                    element,
1269                    arguments,
1270                    value.handle_mut(),
1271                    ExceptionHandling::Report,
1272                );
1273            },
1274        }
1275    }
1276}
1277
1278pub(crate) enum CallbackReaction<'a> {
1279    Connected,
1280    Disconnected,
1281    Adopted(DomRoot<Document>, DomRoot<Document>),
1282    AttributeChanged(
1283        LocalName,
1284        Option<&'a AttrValue>,
1285        Option<&'a AttrValue>,
1286        Namespace,
1287    ),
1288    FormAssociated(Option<DomRoot<HTMLFormElement>>),
1289    FormDisabled(bool),
1290    FormReset,
1291    ConnectedMove,
1292}
1293
1294/// <https://html.spec.whatwg.org/multipage/#processing-the-backup-element-queue>
1295#[derive(Clone, Copy, Eq, JSTraceable, MallocSizeOf, PartialEq)]
1296enum BackupElementQueueFlag {
1297    Processing,
1298    NotProcessing,
1299}
1300
1301/// <https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack>
1302/// # Safety
1303/// This can be shared inside an Rc because one of those Rc copies lives
1304/// inside ScriptThread, so the GC can always reach this structure.
1305#[derive(JSTraceable, MallocSizeOf)]
1306#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
1307#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
1308pub(crate) struct CustomElementReactionStack {
1309    stack: DomRefCell<Vec<ElementQueue>>,
1310    backup_queue: ElementQueue,
1311    processing_backup_element_queue: Cell<BackupElementQueueFlag>,
1312}
1313
1314impl CustomElementReactionStack {
1315    pub(crate) fn new() -> CustomElementReactionStack {
1316        CustomElementReactionStack {
1317            stack: DomRefCell::new(Vec::new()),
1318            backup_queue: ElementQueue::new(),
1319            processing_backup_element_queue: Cell::new(BackupElementQueueFlag::NotProcessing),
1320        }
1321    }
1322
1323    pub(crate) fn push_new_element_queue(&self) {
1324        self.stack.borrow_mut().push(ElementQueue::new());
1325    }
1326
1327    pub(crate) fn pop_current_element_queue(&self, cx: &mut JSContext) {
1328        rooted_vec!(let mut stack);
1329        mem::swap(&mut *stack, &mut *self.stack.safe_borrow_mut(cx.no_gc()));
1330
1331        if let Some(current_queue) = stack.last() {
1332            current_queue.invoke_reactions(cx);
1333        }
1334        stack.pop();
1335
1336        mem::swap(&mut *self.stack.safe_borrow_mut(cx.no_gc()), &mut *stack);
1337        self.stack.safe_borrow_mut(cx.no_gc()).append(&mut *stack);
1338    }
1339
1340    /// <https://html.spec.whatwg.org/multipage/#enqueue-an-element-on-the-appropriate-element-queue>
1341    /// Step 4
1342    pub(crate) fn invoke_backup_element_queue(&self, cx: &mut JSContext) {
1343        // Step 4.1
1344        self.backup_queue.invoke_reactions(cx);
1345
1346        // Step 4.2
1347        self.processing_backup_element_queue
1348            .set(BackupElementQueueFlag::NotProcessing);
1349    }
1350
1351    /// <https://html.spec.whatwg.org/multipage/#enqueue-an-element-on-the-appropriate-element-queue>
1352    pub(crate) fn enqueue_element(&self, cx: &JSContext, element: &Element) {
1353        if let Some(current_queue) = self.stack.borrow().last() {
1354            // Step 2
1355            current_queue.append_element(element);
1356        } else {
1357            // Step 1.1
1358            self.backup_queue.append_element(element);
1359
1360            // Step 1.2
1361            if self.processing_backup_element_queue.get() == BackupElementQueueFlag::Processing {
1362                return;
1363            }
1364
1365            // Step 1.3
1366            self.processing_backup_element_queue
1367                .set(BackupElementQueueFlag::Processing);
1368
1369            // Step 4
1370            ScriptThread::enqueue_microtask(cx, Box::new(CustomElementReactionMicrotask::new()));
1371        }
1372    }
1373
1374    /// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-callback-reaction>
1375    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
1376    pub(crate) fn enqueue_callback_reaction(
1377        &self,
1378        cx: &mut JSContext,
1379        element: &Element,
1380        reaction: CallbackReaction,
1381        definition: Option<Rc<CustomElementDefinition>>,
1382    ) {
1383        // Step 1. Let definition be element's custom element definition.
1384        let definition = match definition.or_else(|| element.get_custom_element_definition()) {
1385            Some(definition) => definition,
1386            None => return,
1387        };
1388
1389        // Step 2. Let callback be the value of the entry in definition's lifecycle callbacks with
1390        // key callbackName.
1391        let (callback, args) = match reaction {
1392            CallbackReaction::Connected => {
1393                (definition.callbacks.connected_callback.clone(), Vec::new())
1394            },
1395            CallbackReaction::Disconnected => (
1396                definition.callbacks.disconnected_callback.clone(),
1397                Vec::new(),
1398            ),
1399            CallbackReaction::Adopted(ref old_doc, ref new_doc) => {
1400                let args = vec![Heap::default(), Heap::default()];
1401                args[0].set(ObjectValue(old_doc.reflector().get_jsobject().get()));
1402                args[1].set(ObjectValue(new_doc.reflector().get_jsobject().get()));
1403                (definition.callbacks.adopted_callback.clone(), args)
1404            },
1405            CallbackReaction::AttributeChanged(local_name, old_val, val, namespace) => {
1406                // Step 5.
1407                if !definition
1408                    .observed_attributes
1409                    .iter()
1410                    .any(|attr| *attr == *local_name)
1411                {
1412                    return;
1413                }
1414
1415                // We might be here during HTML parsing, rather than
1416                // during Javscript execution, and so we typically aren't
1417                // already in a realm here.
1418                let mut realm = enter_auto_realm(cx, &*element.global());
1419                let cx = &mut realm;
1420
1421                let local_name = TracedDOMString::from(local_name).root();
1422                rooted!(&in(cx) let mut name_value = UndefinedValue());
1423                local_name.to_jsval(cx, name_value.handle_mut());
1424
1425                rooted!(&in(cx) let mut old_value = NullValue());
1426                if let Some(old_val) = old_val {
1427                    old_val.to_jsval(cx, old_value.handle_mut());
1428                }
1429
1430                rooted!(&in(cx) let mut value = NullValue());
1431                if let Some(val) = val {
1432                    val.to_jsval(cx, value.handle_mut());
1433                }
1434
1435                rooted!(&in(cx) let mut namespace_value = NullValue());
1436                if namespace != ns!() {
1437                    let namespace = TracedDOMString::from(namespace).root();
1438                    namespace.to_jsval(cx, namespace_value.handle_mut());
1439                }
1440
1441                let args = vec![
1442                    Heap::default(),
1443                    Heap::default(),
1444                    Heap::default(),
1445                    Heap::default(),
1446                ];
1447                args[0].set(name_value.get());
1448                args[1].set(old_value.get());
1449                args[2].set(value.get());
1450                args[3].set(namespace_value.get());
1451
1452                (
1453                    definition.callbacks.attribute_changed_callback.clone(),
1454                    args,
1455                )
1456            },
1457            CallbackReaction::FormAssociated(form) => {
1458                let args = vec![Heap::default()];
1459                if let Some(form) = form {
1460                    args[0].set(ObjectValue(form.reflector().get_jsobject().get()));
1461                } else {
1462                    args[0].set(NullValue());
1463                }
1464                (definition.callbacks.form_associated_callback.clone(), args)
1465            },
1466            CallbackReaction::FormDisabled(disabled) => {
1467                rooted!(&in(cx) let disabled_value = BooleanValue(disabled));
1468                let args = vec![Heap::default()];
1469                args[0].set(disabled_value.get());
1470                (definition.callbacks.form_disabled_callback.clone(), args)
1471            },
1472            CallbackReaction::FormReset => {
1473                (definition.callbacks.form_reset_callback.clone(), Vec::new())
1474            },
1475            CallbackReaction::ConnectedMove => {
1476                let callback = definition.callbacks.connected_move_callback.clone();
1477                // Step 3. If callbackName is "connectedMoveCallback" and callback is null:
1478                if callback.is_none() {
1479                    // Step 3.1. Let disconnectedCallback be the value of the entry in
1480                    // definition's lifecycle callbacks with key "disconnectedCallback".
1481                    let disconnected_callback = definition.callbacks.disconnected_callback.clone();
1482
1483                    // Step 3.2. Let connectedCallback be the value of the entry in
1484                    // definition's lifecycle callbacks with key "connectedCallback".
1485                    let connected_callback = definition.callbacks.connected_callback.clone();
1486
1487                    // Step 3.3. If connectedCallback and disconnectedCallback are null,
1488                    // then return.
1489                    if disconnected_callback.is_none() && connected_callback.is_none() {
1490                        return;
1491                    }
1492
1493                    // Step 3.4. Set callback to the following steps:
1494                    // Step 3.4.1. If disconnectedCallback is not null, then call
1495                    // disconnectedCallback with no arguments.
1496                    if let Some(disconnected_callback) = disconnected_callback {
1497                        element.push_callback_reaction(
1498                            disconnected_callback.root(cx),
1499                            Box::new([]),
1500                            cx.no_gc(),
1501                        );
1502                    }
1503                    // Step 3.4.2. If connectedCallback is not null, then call
1504                    // connectedCallback with no arguments.
1505                    if let Some(connected_callback) = connected_callback {
1506                        element.push_callback_reaction(
1507                            connected_callback.root(cx),
1508                            Box::new([]),
1509                            cx.no_gc(),
1510                        );
1511                    }
1512
1513                    self.enqueue_element(cx, element);
1514                    return;
1515                }
1516
1517                (callback, Vec::new())
1518            },
1519        };
1520
1521        // Step 4. If callback is null, then return.
1522        let callback = match callback {
1523            Some(callback) => callback,
1524            None => return,
1525        };
1526
1527        // Step 6. Add a new callback reaction to element's custom element reaction queue, with
1528        // callback function callback and arguments args.
1529        element.push_callback_reaction(callback.root(cx), args.into_boxed_slice(), cx.no_gc());
1530
1531        // Step 7. Enqueue an element on the appropriate element queue given element.
1532        self.enqueue_element(cx, element);
1533    }
1534
1535    /// <https://html.spec.whatwg.org/multipage/#enqueue-a-custom-element-upgrade-reaction>
1536    pub(crate) fn enqueue_upgrade_reaction(
1537        &self,
1538        cx: &JSContext,
1539        element: &Element,
1540        definition: Rc<CustomElementDefinition>,
1541    ) {
1542        // Step 1. Add a new upgrade reaction to element's custom element reaction queue,
1543        // with custom element definition definition.
1544        element.push_upgrade_reaction(definition, cx.no_gc());
1545
1546        // Step 2. Enqueue an element on the appropriate element queue given element.
1547        self.enqueue_element(cx, element);
1548    }
1549}
1550
1551/// <https://html.spec.whatwg.org/multipage/#element-queue>
1552#[derive(JSTraceable, MallocSizeOf)]
1553#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
1554struct ElementQueue {
1555    queue: DomRefCell<VecDeque<Dom<Element>>>,
1556}
1557
1558impl ElementQueue {
1559    fn new() -> ElementQueue {
1560        ElementQueue {
1561            queue: Default::default(),
1562        }
1563    }
1564
1565    /// <https://html.spec.whatwg.org/multipage/#invoke-custom-element-reactions>
1566    fn invoke_reactions(&self, cx: &mut JSContext) {
1567        // Steps 1-2
1568        while let Some(element) = self.next_element() {
1569            element.invoke_reactions(cx)
1570        }
1571        self.queue.safe_borrow_mut(cx.no_gc()).clear();
1572    }
1573
1574    fn next_element(&self) -> Option<DomRoot<Element>> {
1575        self.queue
1576            .borrow_mut()
1577            .pop_front()
1578            .as_deref()
1579            .map(DomRoot::from_ref)
1580    }
1581
1582    fn append_element(&self, element: &Element) {
1583        self.queue.borrow_mut().push_back(Dom::from_ref(element));
1584    }
1585}
1586
1587/// <https://html.spec.whatwg.org/multipage/#valid-custom-element-name>
1588pub(crate) fn is_valid_custom_element_name(name: &str) -> bool {
1589    // Custom elment names must match:
1590    // PotentialCustomElementName ::= [a-z] (PCENChar)* '-' (PCENChar)*
1591    let mut chars = name.chars();
1592    if !chars.next().is_some_and(|c| c.is_ascii_lowercase()) {
1593        return false;
1594    }
1595
1596    let mut has_dash = false;
1597
1598    for c in chars {
1599        if c == '-' {
1600            has_dash = true;
1601            continue;
1602        }
1603
1604        if !is_potential_custom_element_char(c) {
1605            return false;
1606        }
1607    }
1608
1609    if !has_dash {
1610        return false;
1611    }
1612
1613    if name == "annotation-xml" ||
1614        name == "color-profile" ||
1615        name == "font-face" ||
1616        name == "font-face-src" ||
1617        name == "font-face-uri" ||
1618        name == "font-face-format" ||
1619        name == "font-face-name" ||
1620        name == "missing-glyph"
1621    {
1622        return false;
1623    }
1624
1625    true
1626}
1627
1628/// Check if this character is a PCENChar
1629/// <https://html.spec.whatwg.org/multipage/#prod-pcenchar>
1630fn is_potential_custom_element_char(c: char) -> bool {
1631    c == '-' ||
1632        c == '.' ||
1633        c == '_' ||
1634        c == '\u{B7}' ||
1635        c.is_ascii_digit() ||
1636        c.is_ascii_lowercase() ||
1637        ('\u{C0}'..='\u{D6}').contains(&c) ||
1638        ('\u{D8}'..='\u{F6}').contains(&c) ||
1639        ('\u{F8}'..='\u{37D}').contains(&c) ||
1640        ('\u{37F}'..='\u{1FFF}').contains(&c) ||
1641        ('\u{200C}'..='\u{200D}').contains(&c) ||
1642        ('\u{203F}'..='\u{2040}').contains(&c) ||
1643        ('\u{2070}'..='\u{218F}').contains(&c) ||
1644        ('\u{2C00}'..='\u{2FEF}').contains(&c) ||
1645        ('\u{3001}'..='\u{D7FF}').contains(&c) ||
1646        ('\u{F900}'..='\u{FDCF}').contains(&c) ||
1647        ('\u{FDF0}'..='\u{FFFD}').contains(&c) ||
1648        ('\u{10000}'..='\u{EFFFF}').contains(&c)
1649}
1650
1651fn is_extendable_element_interface(element: &str) -> bool {
1652    element == "a" ||
1653        element == "abbr" ||
1654        element == "acronym" ||
1655        element == "address" ||
1656        element == "area" ||
1657        element == "article" ||
1658        element == "aside" ||
1659        element == "audio" ||
1660        element == "b" ||
1661        element == "base" ||
1662        element == "bdi" ||
1663        element == "bdo" ||
1664        element == "big" ||
1665        element == "blockquote" ||
1666        element == "body" ||
1667        element == "br" ||
1668        element == "button" ||
1669        element == "canvas" ||
1670        element == "caption" ||
1671        element == "center" ||
1672        element == "cite" ||
1673        element == "code" ||
1674        element == "col" ||
1675        element == "colgroup" ||
1676        element == "data" ||
1677        element == "datalist" ||
1678        element == "dd" ||
1679        element == "del" ||
1680        element == "details" ||
1681        element == "dfn" ||
1682        element == "dialog" ||
1683        element == "dir" ||
1684        element == "div" ||
1685        element == "dl" ||
1686        element == "dt" ||
1687        element == "em" ||
1688        element == "embed" ||
1689        element == "fieldset" ||
1690        element == "figcaption" ||
1691        element == "figure" ||
1692        element == "font" ||
1693        element == "footer" ||
1694        element == "form" ||
1695        element == "frame" ||
1696        element == "frameset" ||
1697        element == "h1" ||
1698        element == "h2" ||
1699        element == "h3" ||
1700        element == "h4" ||
1701        element == "h5" ||
1702        element == "h6" ||
1703        element == "head" ||
1704        element == "header" ||
1705        element == "hgroup" ||
1706        element == "hr" ||
1707        element == "html" ||
1708        element == "i" ||
1709        element == "iframe" ||
1710        element == "img" ||
1711        element == "input" ||
1712        element == "ins" ||
1713        element == "kbd" ||
1714        element == "label" ||
1715        element == "legend" ||
1716        element == "li" ||
1717        element == "link" ||
1718        element == "listing" ||
1719        element == "main" ||
1720        element == "map" ||
1721        element == "mark" ||
1722        element == "marquee" ||
1723        element == "menu" ||
1724        element == "meta" ||
1725        element == "meter" ||
1726        element == "nav" ||
1727        element == "nobr" ||
1728        element == "noframes" ||
1729        element == "noscript" ||
1730        element == "object" ||
1731        element == "ol" ||
1732        element == "optgroup" ||
1733        element == "option" ||
1734        element == "output" ||
1735        element == "p" ||
1736        element == "param" ||
1737        element == "picture" ||
1738        element == "plaintext" ||
1739        element == "pre" ||
1740        element == "progress" ||
1741        element == "q" ||
1742        element == "rp" ||
1743        element == "rt" ||
1744        element == "ruby" ||
1745        element == "s" ||
1746        element == "samp" ||
1747        element == "script" ||
1748        element == "section" ||
1749        element == "select" ||
1750        element == "slot" ||
1751        element == "small" ||
1752        element == "source" ||
1753        element == "span" ||
1754        element == "strike" ||
1755        element == "strong" ||
1756        element == "style" ||
1757        element == "sub" ||
1758        element == "summary" ||
1759        element == "sup" ||
1760        element == "table" ||
1761        element == "tbody" ||
1762        element == "td" ||
1763        element == "template" ||
1764        element == "textarea" ||
1765        element == "tfoot" ||
1766        element == "th" ||
1767        element == "thead" ||
1768        element == "time" ||
1769        element == "title" ||
1770        element == "tr" ||
1771        element == "tt" ||
1772        element == "track" ||
1773        element == "u" ||
1774        element == "ul" ||
1775        element == "var" ||
1776        element == "video" ||
1777        element == "wbr" ||
1778        element == "xmp"
1779}