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