script/dom/
domimplementation.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 dom_struct::dom_struct;
6use html5ever::{QualName, local_name, ns};
7use js::context::JSContext;
8use script_bindings::error::Error;
9use script_traits::DocumentActivity;
10
11use crate::document_loader::DocumentLoader;
12use crate::dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementationMethods;
13use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
14    DocumentMethods, ElementCreationOptions,
15};
16use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
17use crate::dom::bindings::codegen::UnionTypes::StringOrElementCreationOptions;
18use crate::dom::bindings::domname::{is_valid_doctype_name, namespace_from_domstring};
19use crate::dom::bindings::error::Fallible;
20use crate::dom::bindings::inheritance::Castable;
21use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
22use crate::dom::bindings::root::{Dom, DomRoot};
23use crate::dom::bindings::str::DOMString;
24use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLDocument};
25use crate::dom::documenttype::DocumentType;
26use crate::dom::element::{CustomElementCreationMode, ElementCreator};
27use crate::dom::node::Node;
28use crate::dom::text::Text;
29use crate::dom::types::Element;
30use crate::dom::xmldocument::XMLDocument;
31use crate::script_runtime::CanGc;
32
33// https://dom.spec.whatwg.org/#domimplementation
34#[dom_struct]
35pub(crate) struct DOMImplementation {
36    reflector_: Reflector,
37    document: Dom<Document>,
38}
39
40impl DOMImplementation {
41    fn new_inherited(document: &Document) -> DOMImplementation {
42        DOMImplementation {
43            reflector_: Reflector::new(),
44            document: Dom::from_ref(document),
45        }
46    }
47
48    pub(crate) fn new(document: &Document, can_gc: CanGc) -> DomRoot<DOMImplementation> {
49        let window = document.window();
50        reflect_dom_object(
51            Box::new(DOMImplementation::new_inherited(document)),
52            window,
53            can_gc,
54        )
55    }
56}
57
58// https://dom.spec.whatwg.org/#domimplementation
59impl DOMImplementationMethods<crate::DomTypeHolder> for DOMImplementation {
60    /// <https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype>
61    fn CreateDocumentType(
62        &self,
63        qualified_name: DOMString,
64        pubid: DOMString,
65        sysid: DOMString,
66        can_gc: CanGc,
67    ) -> Fallible<DomRoot<DocumentType>> {
68        // Step 1. If name is not a valid doctype name, then throw an
69        //      "InvalidCharacterError" DOMException.
70        if !is_valid_doctype_name(&qualified_name) {
71            debug!("Not a valid doctype name");
72            return Err(Error::InvalidCharacter(None));
73        }
74
75        Ok(DocumentType::new(
76            qualified_name,
77            Some(pubid),
78            Some(sysid),
79            &self.document,
80            can_gc,
81        ))
82    }
83
84    /// <https://dom.spec.whatwg.org/#dom-domimplementation-createdocument>
85    fn CreateDocument(
86        &self,
87        cx: &mut JSContext,
88        maybe_namespace: Option<DOMString>,
89        qname: DOMString,
90        maybe_doctype: Option<&DocumentType>,
91    ) -> Fallible<DomRoot<XMLDocument>> {
92        let win = self.document.window();
93        let loader = DocumentLoader::new(&self.document.loader());
94        let namespace = namespace_from_domstring(maybe_namespace.to_owned());
95
96        let content_type = match namespace {
97            ns!(html) => "application/xhtml+xml",
98            ns!(svg) => "image/svg+xml",
99            _ => "application/xml",
100        }
101        .parse()
102        .unwrap();
103
104        // Step 1. Let document be a new XMLDocument.
105        let doc = XMLDocument::new(
106            win,
107            HasBrowsingContext::No,
108            None,
109            self.document.origin().clone(),
110            IsHTMLDocument::NonHTMLDocument,
111            Some(content_type),
112            None,
113            DocumentActivity::Inactive,
114            DocumentSource::NotFromParser,
115            loader,
116            Some(self.document.insecure_requests_policy()),
117            self.document.has_trustworthy_ancestor_or_current_origin(),
118            self.document.custom_element_reaction_stack(),
119            CanGc::from_cx(cx),
120        );
121
122        // Step 2. Let element be null.
123        // Step 3. If qualifiedName is not the empty string, then set element to the result of running
124        // the internal createElementNS steps, given document, namespace, qualifiedName, and an empty dictionary.
125        let maybe_elem = if qname.is_empty() {
126            None
127        } else {
128            let options =
129                StringOrElementCreationOptions::ElementCreationOptions(ElementCreationOptions {
130                    is: None,
131                });
132            match doc
133                .upcast::<Document>()
134                .CreateElementNS(cx, maybe_namespace, qname, options)
135            {
136                Err(error) => return Err(error),
137                Ok(elem) => Some(elem),
138            }
139        };
140
141        {
142            let doc_node = doc.upcast::<Node>();
143
144            // Step 4.
145            if let Some(doc_type) = maybe_doctype {
146                doc_node.AppendChild(cx, doc_type.upcast()).unwrap();
147            }
148
149            // Step 5.
150            if let Some(ref elem) = maybe_elem {
151                doc_node.AppendChild(cx, elem.upcast()).unwrap();
152            }
153        }
154
155        // Step 6.
156        // The origin is already set
157
158        // Step 7.
159        Ok(doc)
160    }
161
162    /// <https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument>
163    fn CreateHTMLDocument(
164        &self,
165        cx: &mut JSContext,
166        title: Option<DOMString>,
167    ) -> DomRoot<Document> {
168        let win = self.document.window();
169        let loader = DocumentLoader::new(&self.document.loader());
170
171        // Step 1. Let doc be a new document that is an HTML document.
172        // Step 2. Set doc’s content type to "text/html".
173        let doc = Document::new(
174            win,
175            HasBrowsingContext::No,
176            None,
177            None,
178            // Step 8. doc’s origin is this’s associated document’s origin.
179            self.document.origin().clone(),
180            IsHTMLDocument::HTMLDocument,
181            None,
182            None,
183            DocumentActivity::Inactive,
184            DocumentSource::NotFromParser,
185            loader,
186            None,
187            None,
188            Default::default(),
189            false,
190            self.document.allow_declarative_shadow_roots(),
191            Some(self.document.insecure_requests_policy()),
192            self.document.has_trustworthy_ancestor_or_current_origin(),
193            self.document.custom_element_reaction_stack(),
194            self.document.creation_sandboxing_flag_set(),
195            CanGc::from_cx(cx),
196        );
197
198        {
199            // Step 3. Append a new doctype, with "html" as its name and with its node document set to doc, to doc.
200            let doc_node = doc.upcast::<Node>();
201            let doc_type = DocumentType::new(
202                DOMString::from("html"),
203                None,
204                None,
205                &doc,
206                CanGc::from_cx(cx),
207            );
208            doc_node.AppendChild(cx, doc_type.upcast()).unwrap();
209        }
210
211        {
212            // Step 4. Append the result of creating an element given doc, "html",
213            // and the HTML namespace, to doc.
214            let doc_node = doc.upcast::<Node>();
215            let doc_html = DomRoot::upcast::<Node>(Element::create(
216                cx,
217                QualName::new(None, ns!(html), local_name!("html")),
218                None,
219                &doc,
220                ElementCreator::ScriptCreated,
221                CustomElementCreationMode::Asynchronous,
222                None,
223            ));
224            doc_node
225                .AppendChild(cx, &doc_html)
226                .expect("Appending failed");
227
228            {
229                // Step 5. Append the result of creating an element given doc, "head",
230                // and the HTML namespace, to the html element created earlier.
231                let doc_head = DomRoot::upcast::<Node>(Element::create(
232                    cx,
233                    QualName::new(None, ns!(html), local_name!("head")),
234                    None,
235                    &doc,
236                    ElementCreator::ScriptCreated,
237                    CustomElementCreationMode::Asynchronous,
238                    None,
239                ));
240                doc_html.AppendChild(cx, &doc_head).unwrap();
241
242                // Step 6. If title is given:
243                if let Some(title_str) = title {
244                    // Step 6.1. Append the result of creating an element given doc, "title",
245                    // and the HTML namespace, to the head element created earlier.
246                    let doc_title = DomRoot::upcast::<Node>(Element::create(
247                        cx,
248                        QualName::new(None, ns!(html), local_name!("title")),
249                        None,
250                        &doc,
251                        ElementCreator::ScriptCreated,
252                        CustomElementCreationMode::Asynchronous,
253                        None,
254                    ));
255                    doc_head.AppendChild(cx, &doc_title).unwrap();
256
257                    // Step 6.2. Append a new Text node, with its data set to title (which could be the empty string)
258                    // and its node document set to doc, to the title element created earlier.
259                    let title_text = Text::new(title_str, &doc, CanGc::from_cx(cx));
260                    doc_title.AppendChild(cx, title_text.upcast()).unwrap();
261                }
262            }
263
264            // Step 7. Append the result of creating an element given doc, "body",
265            // and the HTML namespace, to the html element created earlier.
266            let doc_body = Element::create(
267                cx,
268                QualName::new(None, ns!(html), local_name!("body")),
269                None,
270                &doc,
271                ElementCreator::ScriptCreated,
272                CustomElementCreationMode::Asynchronous,
273                None,
274            );
275            doc_html.AppendChild(cx, doc_body.upcast()).unwrap();
276        }
277
278        // Step 9. Return doc.
279        doc
280    }
281
282    /// <https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature>
283    fn HasFeature(&self) -> bool {
284        true
285    }
286}