Skip to main content

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