script/dom/
create.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 html5ever::{LocalName, Prefix, QualName, local_name, ns};
6use js::context::JSContext;
7use js::rust::HandleObject;
8
9use crate::dom::bindings::error::{report_pending_exception, throw_dom_exception};
10use crate::dom::bindings::inheritance::Castable;
11use crate::dom::bindings::reflector::DomGlobal;
12use crate::dom::bindings::root::DomRoot;
13use crate::dom::customelementregistry::{
14    CustomElementRegistry, CustomElementState, is_valid_custom_element_name, upgrade_element,
15};
16use crate::dom::document::Document;
17use crate::dom::element::{CustomElementCreationMode, Element, ElementCreator};
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
20use crate::dom::html::htmlareaelement::HTMLAreaElement;
21use crate::dom::html::htmlaudioelement::HTMLAudioElement;
22use crate::dom::html::htmlbaseelement::HTMLBaseElement;
23use crate::dom::html::htmlbodyelement::HTMLBodyElement;
24use crate::dom::html::htmlbrelement::HTMLBRElement;
25use crate::dom::html::htmlbuttonelement::HTMLButtonElement;
26use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
27use crate::dom::html::htmldataelement::HTMLDataElement;
28use crate::dom::html::htmldatalistelement::HTMLDataListElement;
29use crate::dom::html::htmldetailselement::HTMLDetailsElement;
30use crate::dom::html::htmldialogelement::HTMLDialogElement;
31use crate::dom::html::htmldirectoryelement::HTMLDirectoryElement;
32use crate::dom::html::htmldivelement::HTMLDivElement;
33use crate::dom::html::htmldlistelement::HTMLDListElement;
34use crate::dom::html::htmlelement::HTMLElement;
35use crate::dom::html::htmlembedelement::HTMLEmbedElement;
36use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
37use crate::dom::html::htmlfontelement::HTMLFontElement;
38use crate::dom::html::htmlformelement::HTMLFormElement;
39use crate::dom::html::htmlframeelement::HTMLFrameElement;
40use crate::dom::html::htmlframesetelement::HTMLFrameSetElement;
41use crate::dom::html::htmlheadelement::HTMLHeadElement;
42use crate::dom::html::htmlheadingelement::{HTMLHeadingElement, HeadingLevel};
43use crate::dom::html::htmlhrelement::HTMLHRElement;
44use crate::dom::html::htmlhtmlelement::HTMLHtmlElement;
45use crate::dom::html::htmliframeelement::HTMLIFrameElement;
46use crate::dom::html::htmlimageelement::HTMLImageElement;
47use crate::dom::html::htmlinputelement::HTMLInputElement;
48use crate::dom::html::htmllabelelement::HTMLLabelElement;
49use crate::dom::html::htmllegendelement::HTMLLegendElement;
50use crate::dom::html::htmllielement::HTMLLIElement;
51use crate::dom::html::htmllinkelement::HTMLLinkElement;
52use crate::dom::html::htmlmapelement::HTMLMapElement;
53use crate::dom::html::htmlmenuelement::HTMLMenuElement;
54use crate::dom::html::htmlmetaelement::HTMLMetaElement;
55use crate::dom::html::htmlmeterelement::HTMLMeterElement;
56use crate::dom::html::htmlmodelement::HTMLModElement;
57use crate::dom::html::htmlobjectelement::HTMLObjectElement;
58use crate::dom::html::htmlolistelement::HTMLOListElement;
59use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
60use crate::dom::html::htmloptionelement::HTMLOptionElement;
61use crate::dom::html::htmloutputelement::HTMLOutputElement;
62use crate::dom::html::htmlparagraphelement::HTMLParagraphElement;
63use crate::dom::html::htmlparamelement::HTMLParamElement;
64use crate::dom::html::htmlpictureelement::HTMLPictureElement;
65use crate::dom::html::htmlpreelement::HTMLPreElement;
66use crate::dom::html::htmlprogresselement::HTMLProgressElement;
67use crate::dom::html::htmlquoteelement::HTMLQuoteElement;
68use crate::dom::html::htmlscriptelement::HTMLScriptElement;
69use crate::dom::html::htmlselectelement::HTMLSelectElement;
70use crate::dom::html::htmlslotelement::HTMLSlotElement;
71use crate::dom::html::htmlsourceelement::HTMLSourceElement;
72use crate::dom::html::htmlspanelement::HTMLSpanElement;
73use crate::dom::html::htmlstyleelement::HTMLStyleElement;
74use crate::dom::html::htmltablecaptionelement::HTMLTableCaptionElement;
75use crate::dom::html::htmltablecellelement::HTMLTableCellElement;
76use crate::dom::html::htmltablecolelement::HTMLTableColElement;
77use crate::dom::html::htmltableelement::HTMLTableElement;
78use crate::dom::html::htmltablerowelement::HTMLTableRowElement;
79use crate::dom::html::htmltablesectionelement::HTMLTableSectionElement;
80use crate::dom::html::htmltemplateelement::HTMLTemplateElement;
81use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
82use crate::dom::html::htmltimeelement::HTMLTimeElement;
83use crate::dom::html::htmltitleelement::HTMLTitleElement;
84use crate::dom::html::htmltrackelement::HTMLTrackElement;
85use crate::dom::html::htmlulistelement::HTMLUListElement;
86use crate::dom::html::htmlunknownelement::HTMLUnknownElement;
87use crate::dom::html::htmlvideoelement::HTMLVideoElement;
88use crate::dom::svg::svgelement::SVGElement;
89use crate::dom::svg::svgimageelement::SVGImageElement;
90use crate::dom::svg::svgsvgelement::SVGSVGElement;
91use crate::realms::{InRealm, enter_auto_realm};
92use crate::script_runtime::CanGc;
93use crate::script_thread::ScriptThread;
94
95fn create_svg_element(
96    name: QualName,
97    prefix: Option<Prefix>,
98    document: &Document,
99    proto: Option<HandleObject>,
100) -> DomRoot<Element> {
101    assert_eq!(name.ns, ns!(svg));
102
103    macro_rules! make(
104        ($ctor:ident) => ({
105            let obj = $ctor::new(name.local, prefix, document, proto, CanGc::note());
106            DomRoot::upcast(obj)
107        });
108        ($ctor:ident, $($arg:expr),+) => ({
109            let obj = $ctor::new(name.local, prefix, document, proto, $($arg),+, CanGc::note());
110            DomRoot::upcast(obj)
111        })
112    );
113
114    match name.local {
115        local_name!("image") => make!(SVGImageElement),
116        local_name!("svg") => make!(SVGSVGElement),
117        _ => make!(SVGElement),
118    }
119}
120
121/// <https://dom.spec.whatwg.org/#concept-create-element>
122#[expect(clippy::too_many_arguments)]
123fn create_html_element(
124    cx: &mut JSContext,
125    name: QualName,
126    prefix: Option<Prefix>,
127    is: Option<LocalName>,
128    document: &Document,
129    creator: ElementCreator,
130    mode: CustomElementCreationMode,
131    proto: Option<HandleObject>,
132) -> DomRoot<Element> {
133    assert_eq!(name.ns, ns!(html));
134
135    // Step 2. If registry is "default", then set registry
136    // to the result of looking up a custom element registry given document.
137    // TODO: We don't pass in any other value than "default" atm
138    let registry = CustomElementRegistry::lookup_a_custom_element_registry(document.upcast());
139
140    // Step 3. Let definition be the result of looking up a custom element
141    // definition given document, namespace, localName, and is.
142    let definition = document.lookup_custom_element_definition(&name.ns, &name.local, is.as_ref());
143
144    // Step 4. If definition is non-null...
145    if let Some(definition) = definition {
146        // ...and definition’s name is not equal to its local name
147        // (i.e., definition represents a customized built-in element):
148        if !definition.is_autonomous() {
149            // Step 4.1. Let interface be the element interface for localName and the HTML namespace.
150            // Step 4.2. Set result to the result of creating an element internal given document,
151            // interface, localName, the HTML namespace, prefix, "undefined", is, and registry.
152            let element = create_native_html_element(name, prefix, document, creator, proto);
153            element.set_is(definition.name.clone());
154            element.set_custom_element_state(CustomElementState::Undefined);
155            element.set_custom_element_registry(registry);
156
157            match mode {
158                // Step 4.3. If synchronousCustomElements is true, then run this step while catching any exceptions:
159                CustomElementCreationMode::Synchronous => {
160                    // Step 4.3.1. Upgrade result using definition.
161                    upgrade_element(definition, &element, CanGc::from_cx(cx));
162                    // TODO: "If this step threw an exception exception:" steps.
163                },
164                // Step 4.4. Otherwise, enqueue a custom element upgrade reaction given result and definition.
165                CustomElementCreationMode::Asynchronous => {
166                    ScriptThread::enqueue_upgrade_reaction(&element, definition)
167                },
168            }
169            return element;
170        } else {
171            // Step 5. Otherwise, if definition is non-null:
172            match mode {
173                // Step 5.1. If synchronousCustomElements is true, then run these
174                // steps while catching any exceptions:
175                CustomElementCreationMode::Synchronous => {
176                    let local_name = name.local;
177                    // TODO(jdm) Pass proto to create_element?
178                    // Steps 4.1.1-4.1.11
179                    return match definition.create_element(
180                        document,
181                        prefix.clone(),
182                        registry.clone(),
183                        CanGc::from_cx(cx),
184                    ) {
185                        Ok(element) => {
186                            element.set_custom_element_definition(definition.clone());
187                            element
188                        },
189                        Err(error) => {
190                            // If any of these steps threw an exception exception:
191                            let global =
192                                GlobalScope::current().unwrap_or_else(|| document.global());
193
194                            let mut realm = enter_auto_realm(cx, &*global);
195                            let cx = &mut realm.current_realm();
196
197                            let in_realm_proof = cx.into();
198                            let in_realm = InRealm::Already(&in_realm_proof);
199
200                            // Substep 1. Report exception for definition’s constructor’s corresponding
201                            // JavaScript object’s associated realm’s global object.
202                            throw_dom_exception(cx.into(), &global, error, CanGc::from_cx(cx));
203                            report_pending_exception(cx.into(), in_realm, CanGc::from_cx(cx));
204
205                            // Substep 2. Set result to the result of creating an element internal given document,
206                            // HTMLUnknownElement, localName, the HTML namespace, prefix, "failed", null, and registry.
207                            let element = DomRoot::upcast::<Element>(HTMLUnknownElement::new(
208                                local_name,
209                                prefix,
210                                document,
211                                proto,
212                                CanGc::from_cx(cx),
213                            ));
214                            element.set_custom_element_state(CustomElementState::Failed);
215                            element.set_custom_element_registry(registry);
216                            element
217                        },
218                    };
219                },
220                // Step 4.2. Otherwise:
221                CustomElementCreationMode::Asynchronous => {
222                    // Step 4.2.1. Set result to a new element that implements the HTMLElement interface,
223                    // with no attributes, namespace set to the HTML namespace, namespace prefix set to
224                    // prefix, local name set to localName, custom element state set to "undefined",
225                    // custom element definition set to null, is value set to null, and node document
226                    // set to document.
227                    let result = DomRoot::upcast::<Element>(HTMLElement::new(
228                        name.local,
229                        prefix,
230                        document,
231                        proto,
232                        CanGc::from_cx(cx),
233                    ));
234                    result.set_custom_element_state(CustomElementState::Undefined);
235                    result.set_custom_element_registry(registry);
236                    // Step 4.2.2. Enqueue a custom element upgrade reaction given result and definition.
237                    ScriptThread::enqueue_upgrade_reaction(&result, definition);
238                    return result;
239                },
240            }
241        }
242    }
243
244    // Step 5. Otherwise:
245    // Step 5.1. Let interface be the element interface for localName and namespace.
246    // Step 5.2. Set result to a new element that implements interface, with no attributes,
247    // namespace set to namespace, namespace prefix set to prefix, local name set to localName,
248    // custom element state set to "uncustomized", custom element definition set to null,
249    // is value set to is, and node document set to document.
250    let result = create_native_html_element(name.clone(), prefix, document, creator, proto);
251    // Step 5.3. If namespace is the HTML namespace, and either localName is a valid custom element name or
252    // is is non-null, then set result’s custom element state to "undefined".
253    match is {
254        Some(is) => {
255            result.set_is(is);
256            result.set_custom_element_state(CustomElementState::Undefined);
257            result.set_custom_element_registry(registry);
258        },
259        None => {
260            if is_valid_custom_element_name(&name.local) {
261                result.set_custom_element_state(CustomElementState::Undefined);
262                result.set_custom_element_registry(registry);
263            } else {
264                // Note: This is a performance optimization. See the doc comment of the method for
265                // more information.
266                result.set_initial_custom_element_state_to_uncustomized();
267            }
268        },
269    };
270
271    // Step 6. Return result.
272    result
273}
274
275pub(crate) fn create_native_html_element(
276    name: QualName,
277    prefix: Option<Prefix>,
278    document: &Document,
279    creator: ElementCreator,
280    proto: Option<HandleObject>,
281) -> DomRoot<Element> {
282    assert_eq!(name.ns, ns!(html));
283
284    macro_rules! make(
285        ($ctor:ident) => ({
286            let obj = $ctor::new(name.local, prefix, document, proto, CanGc::note());
287            DomRoot::upcast(obj)
288        });
289        ($ctor:ident, $($arg:expr),+) => ({
290            let obj = $ctor::new(name.local, prefix, document, proto, $($arg),+, CanGc::note());
291            DomRoot::upcast(obj)
292        })
293    );
294
295    // This is a big match, and the IDs for inline-interned atoms are not very structured.
296    // Perhaps we should build a perfect hash from those IDs instead.
297    // https://html.spec.whatwg.org/multipage/#elements-in-the-dom
298    match name.local {
299        local_name!("a") => make!(HTMLAnchorElement),
300        local_name!("abbr") => make!(HTMLElement),
301        local_name!("acronym") => make!(HTMLElement),
302        local_name!("address") => make!(HTMLElement),
303        local_name!("area") => make!(HTMLAreaElement),
304        local_name!("article") => make!(HTMLElement),
305        local_name!("aside") => make!(HTMLElement),
306        local_name!("audio") => make!(HTMLAudioElement),
307        local_name!("b") => make!(HTMLElement),
308        local_name!("base") => make!(HTMLBaseElement),
309        local_name!("bdi") => make!(HTMLElement),
310        local_name!("bdo") => make!(HTMLElement),
311        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:bgsound
312        local_name!("bgsound") => make!(HTMLUnknownElement),
313        local_name!("big") => make!(HTMLElement),
314        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:blink
315        local_name!("blink") => make!(HTMLUnknownElement),
316        // https://html.spec.whatwg.org/multipage/#the-blockquote-element
317        local_name!("blockquote") => make!(HTMLQuoteElement),
318        local_name!("body") => make!(HTMLBodyElement),
319        local_name!("br") => make!(HTMLBRElement),
320        local_name!("button") => make!(HTMLButtonElement),
321        local_name!("canvas") => make!(HTMLCanvasElement),
322        local_name!("caption") => make!(HTMLTableCaptionElement),
323        local_name!("center") => make!(HTMLElement),
324        local_name!("cite") => make!(HTMLElement),
325        local_name!("code") => make!(HTMLElement),
326        local_name!("col") => make!(HTMLTableColElement),
327        local_name!("colgroup") => make!(HTMLTableColElement),
328        local_name!("data") => make!(HTMLDataElement),
329        local_name!("datalist") => make!(HTMLDataListElement),
330        local_name!("dd") => make!(HTMLElement),
331        local_name!("del") => make!(HTMLModElement),
332        local_name!("details") => make!(HTMLDetailsElement),
333        local_name!("dfn") => make!(HTMLElement),
334        local_name!("dialog") => make!(HTMLDialogElement),
335        local_name!("dir") => make!(HTMLDirectoryElement),
336        local_name!("div") => make!(HTMLDivElement),
337        local_name!("dl") => make!(HTMLDListElement),
338        local_name!("dt") => make!(HTMLElement),
339        local_name!("em") => make!(HTMLElement),
340        local_name!("embed") => make!(HTMLEmbedElement),
341        local_name!("fieldset") => make!(HTMLFieldSetElement),
342        local_name!("figcaption") => make!(HTMLElement),
343        local_name!("figure") => make!(HTMLElement),
344        local_name!("font") => make!(HTMLFontElement),
345        local_name!("footer") => make!(HTMLElement),
346        local_name!("form") => make!(HTMLFormElement),
347        local_name!("frame") => make!(HTMLFrameElement),
348        local_name!("frameset") => make!(HTMLFrameSetElement),
349        local_name!("h1") => make!(HTMLHeadingElement, HeadingLevel::Heading1),
350        local_name!("h2") => make!(HTMLHeadingElement, HeadingLevel::Heading2),
351        local_name!("h3") => make!(HTMLHeadingElement, HeadingLevel::Heading3),
352        local_name!("h4") => make!(HTMLHeadingElement, HeadingLevel::Heading4),
353        local_name!("h5") => make!(HTMLHeadingElement, HeadingLevel::Heading5),
354        local_name!("h6") => make!(HTMLHeadingElement, HeadingLevel::Heading6),
355        local_name!("head") => make!(HTMLHeadElement),
356        local_name!("header") => make!(HTMLElement),
357        local_name!("hgroup") => make!(HTMLElement),
358        local_name!("hr") => make!(HTMLHRElement),
359        local_name!("html") => make!(HTMLHtmlElement),
360        local_name!("i") => make!(HTMLElement),
361        local_name!("iframe") => make!(HTMLIFrameElement),
362        local_name!("img") => make!(HTMLImageElement, creator),
363        local_name!("input") => make!(HTMLInputElement),
364        local_name!("ins") => make!(HTMLModElement),
365        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:isindex-2
366        local_name!("isindex") => make!(HTMLUnknownElement),
367        local_name!("kbd") => make!(HTMLElement),
368        // https://html.spec.whatwg.org/multipage/#keygen
369        local_name!("keygen") => make!(HTMLUnknownElement),
370        local_name!("label") => make!(HTMLLabelElement),
371        local_name!("legend") => make!(HTMLLegendElement),
372        local_name!("li") => make!(HTMLLIElement),
373        local_name!("link") => make!(HTMLLinkElement, creator),
374        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:listing
375        local_name!("listing") => make!(HTMLPreElement),
376        local_name!("main") => make!(HTMLElement),
377        local_name!("map") => make!(HTMLMapElement),
378        local_name!("mark") => make!(HTMLElement),
379        local_name!("marquee") => make!(HTMLElement),
380        local_name!("menu") => make!(HTMLMenuElement),
381        local_name!("meta") => make!(HTMLMetaElement),
382        local_name!("meter") => make!(HTMLMeterElement),
383        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:multicol
384        local_name!("multicol") => make!(HTMLUnknownElement),
385        local_name!("nav") => make!(HTMLElement),
386        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:nextid
387        local_name!("nextid") => make!(HTMLUnknownElement),
388        local_name!("nobr") => make!(HTMLElement),
389        local_name!("noframes") => make!(HTMLElement),
390        local_name!("noscript") => make!(HTMLElement),
391        local_name!("object") => make!(HTMLObjectElement),
392        local_name!("ol") => make!(HTMLOListElement),
393        local_name!("optgroup") => make!(HTMLOptGroupElement),
394        local_name!("option") => make!(HTMLOptionElement),
395        local_name!("output") => make!(HTMLOutputElement),
396        local_name!("p") => make!(HTMLParagraphElement),
397        local_name!("param") => make!(HTMLParamElement),
398        local_name!("picture") => make!(HTMLPictureElement),
399        local_name!("plaintext") => make!(HTMLPreElement),
400        local_name!("pre") => make!(HTMLPreElement),
401        local_name!("progress") => make!(HTMLProgressElement),
402        local_name!("q") => make!(HTMLQuoteElement),
403        local_name!("rp") => make!(HTMLElement),
404        local_name!("rt") => make!(HTMLElement),
405        local_name!("ruby") => make!(HTMLElement),
406        local_name!("s") => make!(HTMLElement),
407        local_name!("samp") => make!(HTMLElement),
408        local_name!("script") => make!(HTMLScriptElement, creator),
409        local_name!("section") => make!(HTMLElement),
410        local_name!("select") => make!(HTMLSelectElement),
411        local_name!("slot") => make!(HTMLSlotElement),
412        local_name!("small") => make!(HTMLElement),
413        local_name!("source") => make!(HTMLSourceElement),
414        // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:spacer
415        local_name!("spacer") => make!(HTMLUnknownElement),
416        local_name!("span") => make!(HTMLSpanElement),
417        local_name!("strike") => make!(HTMLElement),
418        local_name!("strong") => make!(HTMLElement),
419        local_name!("style") => make!(HTMLStyleElement, creator),
420        local_name!("sub") => make!(HTMLElement),
421        local_name!("summary") => make!(HTMLElement),
422        local_name!("sup") => make!(HTMLElement),
423        local_name!("table") => make!(HTMLTableElement),
424        local_name!("tbody") => make!(HTMLTableSectionElement),
425        local_name!("td") => make!(HTMLTableCellElement),
426        local_name!("template") => make!(HTMLTemplateElement),
427        local_name!("textarea") => make!(HTMLTextAreaElement),
428        // https://html.spec.whatwg.org/multipage/#the-tfoot-element:concept-element-dom
429        local_name!("tfoot") => make!(HTMLTableSectionElement),
430        local_name!("th") => make!(HTMLTableCellElement),
431        // https://html.spec.whatwg.org/multipage/#the-thead-element:concept-element-dom
432        local_name!("thead") => make!(HTMLTableSectionElement),
433        local_name!("time") => make!(HTMLTimeElement),
434        local_name!("title") => make!(HTMLTitleElement),
435        local_name!("tr") => make!(HTMLTableRowElement),
436        local_name!("tt") => make!(HTMLElement),
437        local_name!("track") => make!(HTMLTrackElement),
438        local_name!("u") => make!(HTMLElement),
439        local_name!("ul") => make!(HTMLUListElement),
440        local_name!("var") => make!(HTMLElement),
441        local_name!("video") => make!(HTMLVideoElement),
442        local_name!("wbr") => make!(HTMLElement),
443        local_name!("xmp") => make!(HTMLPreElement),
444        _ if is_valid_custom_element_name(&name.local) => make!(HTMLElement),
445        _ => make!(HTMLUnknownElement),
446    }
447}
448
449pub(crate) fn create_element(
450    cx: &mut JSContext,
451    name: QualName,
452    is: Option<LocalName>,
453    document: &Document,
454    creator: ElementCreator,
455    mode: CustomElementCreationMode,
456    proto: Option<HandleObject>,
457) -> DomRoot<Element> {
458    let prefix = name.prefix.clone();
459    match name.ns {
460        ns!(html) => create_html_element(cx, name, prefix, is, document, creator, mode, proto),
461        ns!(svg) => create_svg_element(name, prefix, document, proto),
462        _ => Element::new(
463            name.local,
464            name.ns,
465            prefix,
466            document,
467            proto,
468            CanGc::from_cx(cx),
469        ),
470    }
471}