Skip to main content

atmos/os_lib/web_apis/builtins/
dom_doc.rs

1// 主文書以外の `Document`(2026-11-20 TODO S3、WPT `dom/` の `dom/common.js` が使う複数文書)。
2//
3// `new Document()`・`document.implementation.createHTMLDocument()`・`createDocument()`・`DOMParser` の文書は、DOM ブリッジの
4// アリーナの `#document` ノード(`DomBridge::create_document_node`)として持つ。ハンドルはふつうの DOM ノードと同じ
5// (`===` で同一・リスナ・`childNodes`・`appendChild`)で、`Document` のメンバーは `Interp::doc_node_get` が受け持つ。
6// 主文書(`HostRef(HOST_DOCUMENT)` の `document`)の動きは変えない。ノードの所有文書は `DomBridge::node_doc`
7// (主文書以外のものだけを記録)。主文書だけのページでは `DomBridge::extra_docs == 0` で、ここへは一切入らない。
8use super::dom_ns::{ns_arg, validate_and_extract, HTML_NS, SVG_NS};
9use super::*;
10use crate::os_lib::web_apis::dom_bridge::{DomBridge, DomNode};
11
12/// `this`(`#document` のハンドル、または `_doc` を持つ DOMImplementation)が指す主文書以外の文書。`None` は主文書。
13pub(crate) fn owner_of_this(it: &Interp, this: &Value) -> Option<usize> {
14    if it.dom().borrow().extra_docs == 0 {
15        return None;
16    }
17    let i = match this_dom_idx(this) {
18        Some(i) => Some(i),
19        None => match this {
20            Value::Object(o) => o.borrow().props.get("_doc").and_then(this_dom_idx),
21            _ => None,
22        },
23    };
24    i.filter(|&i| it.dom().borrow().is_doc_node(i))
25}
26
27/// 新しく作ったノードを `owner`(`None` は主文書)のものにする。
28#[inline]
29pub(crate) fn note_created(it: &Interp, owner: Option<usize>, idx: usize) {
30    if let Some(d) = owner {
31        it.dom().borrow_mut().set_owner_subtree(idx, Some(d));
32    }
33}
34
35/// `#document` ノードのクラス名(原型の決定用)。
36pub(crate) fn doc_class_name(n: &DomNode) -> &'static str {
37    if n.attrs.contains_key("_html") {
38        "HTMLDocument"
39    } else if n.attrs.contains_key("_xmldoc") {
40        "XMLDocument"
41    } else {
42        "Document"
43    }
44}
45
46/// 値が(主文書を含む)`Document` か。
47pub(crate) fn is_document_value(it: &Interp, v: &Value) -> bool {
48    match v {
49        Value::Object(o) => match &o.borrow().kind {
50            ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_DOCUMENT => true,
51            k => k.dom_node().is_some_and(|i| it.dom().borrow().is_doc_node(i)),
52        },
53        _ => false,
54    }
55}
56
57/// 値が ShadowRoot か。
58pub(crate) fn is_shadow_root_value(it: &Interp, v: &Value) -> bool {
59    this_dom_idx(v).is_some_and(|i| it.dom().borrow().shadow_tree.get_host_by_root(i).is_some())
60}
61
62fn first_element_child(dom: &DomBridge, parent: usize) -> Option<usize> {
63    dom.nodes
64        .get(parent)?
65        .children
66        .iter()
67        .copied()
68        .find(|&c| dom.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
69}
70
71fn doc_title_element(dom: &DomBridge, doc: usize) -> Option<usize> {
72    let root = first_element_child(dom, doc)?;
73    if dom.nodes.get(root).is_some_and(|n| n.tag == "svg") {
74        return dom.nodes.get(root)?.children.iter().copied().find(|&c| dom.nodes.get(c).is_some_and(|n| !n.is_text && n.tag == "title"));
75    }
76    dom.descendants_by_tag_name(root, "title").into_iter().next()
77}
78
79fn new_doc_with(it: &Interp, ctype: &str, html: bool, xmldoc: bool) -> usize {
80    let mut dom = it.dom().borrow_mut();
81    let d = dom.create_document_node(ctype, html);
82    if xmldoc {
83        if let Some(n) = dom.nodes.get_mut(d) {
84            n.attrs.insert(String::from("_xmldoc"), String::from("1"));
85        }
86    }
87    d
88}
89
90/// `new Document()`。
91pub(crate) fn document_ctor(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
92    let d = new_doc_with(it, "application/xml", false, false);
93    Ok(it.dom_val(d))
94}
95
96/// `DOMImplementation.createHTMLDocument(title)`。
97fn impl_create_html_document(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
98    let d = new_doc_with(it, "text/html", true, false);
99    {
100        let mut dom = it.dom().borrow_mut();
101        let dt = dom.create_doctype("html", "", "");
102        dom.append_child(d, dt);
103        let html = dom.create_element("html");
104        dom.append_child(d, html);
105        let head = dom.create_element("head");
106        dom.append_child(html, head);
107        if let Some(t) = a.first().filter(|v| !matches!(v, Value::Undefined)) {
108            let title = dom.create_element("title");
109            dom.append_child(head, title);
110            let txt = dom.create_text_node(&t.to_js_string());
111            dom.append_child(title, txt);
112        }
113        let body = dom.create_element("body");
114        dom.append_child(html, body);
115    }
116    Ok(it.dom_val(d))
117}
118
119/// `DOMImplementation.createDocument(namespace, qualifiedName, doctype)`。
120fn impl_create_document(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
121    if a.len() < 2 {
122        return Err(it.type_error(alloc::format!(
123            "Failed to execute 'createDocument' on 'DOMImplementation': 2 arguments required, but only {} present.",
124            a.len()
125        )));
126    }
127    let ns = ns_arg(&arg(a, 0));
128    let qname = match arg(a, 1) {
129        Value::Null => String::new(),
130        v => v.to_js_string(),
131    };
132    let doctype = arg(a, 2);
133    let dt_idx = match &doctype {
134        Value::Null | Value::Undefined => None,
135        v => match this_dom_idx(v).filter(|&i| it.dom().borrow().nodes.get(i).is_some_and(|n| n.tag == "#doctype")) {
136            Some(i) => Some(i),
137            None => return Err(it.type_error("Failed to execute 'createDocument' on 'DOMImplementation': parameter 3 is not of type 'DocumentType'.")),
138        },
139    };
140    let ctype = match ns.as_deref() {
141        Some(HTML_NS) => "application/xhtml+xml",
142        Some(SVG_NS) => "image/svg+xml",
143        _ => "application/xml",
144    };
145    let d = new_doc_with(it, ctype, false, true);
146    let el = if qname.is_empty() {
147        None
148    } else {
149        let (ns2, prefix, local) = validate_and_extract(it, ns.as_deref(), &qname)?;
150        Some(super::dom_ns::make_element_ns(it, Some(d), ns2, prefix, &local, &qname))
151    };
152    {
153        let mut dom = it.dom().borrow_mut();
154        if let Some(dt) = dt_idx {
155            dom.append_child(d, dt);
156        }
157        if let Some(e) = el {
158            dom.append_child(d, e);
159        }
160    }
161    Ok(it.dom_val(d))
162}
163
164/// `DOMImplementation.createDocumentType(name, publicId, systemId)`。
165fn impl_create_document_type(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
166    if a.len() < 3 {
167        return Err(it.type_error(alloc::format!(
168            "Failed to execute 'createDocumentType' on 'DOMImplementation': 3 arguments required, but only {} present.",
169            a.len()
170        )));
171    }
172    let name = arg(a, 0).to_js_string();
173    // 【2026-11-19】名前は ASCII 空白・NUL・`>` を含まないこと(先頭の文字の制限は無い。DOM Standard)。
174    if name.chars().any(|c| matches!(c, ' ' | '\t' | '\n' | '\x0c' | '\r' | '\0' | '>')) {
175        return Err(it.dom_exception("InvalidCharacterError", "The string contains invalid characters."));
176    }
177    let owner = owner_of_this(it, &t);
178    let idx = it.dom().borrow_mut().create_doctype(&name, &arg(a, 1).to_js_string(), &arg(a, 2).to_js_string());
179    note_created(it, owner, idx);
180    Ok(it.dom_val(idx))
181}
182
183/// `document.implementation`(`owner` は主文書以外の文書のハンドル。主文書は `None`)。
184pub(crate) fn make_implementation(proto: Option<ObjRef>, owner: Option<Value>) -> Value {
185    let o = Obj::plain();
186    {
187        let mut im = o.borrow_mut();
188        im.proto = proto;
189        im.props.insert("hasFeature".into(), nv("DOMImplementation.hasFeature", |_, _, _| Ok(Value::Bool(true))));
190        im.props.insert("createDocumentType".into(), nv("DOMImplementation.createDocumentType", impl_create_document_type));
191        im.props.insert("createHTMLDocument".into(), nv("DOMImplementation.createHTMLDocument", impl_create_html_document));
192        im.props.insert("createDocument".into(), nv("DOMImplementation.createDocument", impl_create_document));
193        if let Some(d) = owner {
194            im.props.insert("_doc".into(), d);
195            im.hide_props(&["_doc"]);
196        }
197    }
198    Value::Object(o)
199}
200
201/// 空白をたたんだ文字列(`document.title`)。
202fn strip_and_collapse(s: &str) -> String {
203    s.split([' ', '\t', '\n', '\x0c', '\r']).filter(|p| !p.is_empty()).collect::<Vec<_>>().join(" ")
204}
205
206/// `doc.createCDATASection(data)`(XML 文書だけ)。テキストノードに `_cdata` の印を付けたもの(`nodeType` 4)。
207pub(crate) fn doc_create_cdata_section(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
208    let owner = owner_of_this(it, &t);
209    if it.dom().borrow().doc_is_html(owner) {
210        return Err(it.dom_exception("NotSupportedError", "This operation is not supported for HTML documents."));
211    }
212    let data = arg(a, 0).to_js_string();
213    if data.contains("]]>") {
214        return Err(it.dom_exception("InvalidCharacterError", "String contains an invalid character"));
215    }
216    let idx = it.dom().borrow_mut().create_text_node(&data);
217    if let Some(n) = it.dom().borrow_mut().nodes.get_mut(idx) {
218        n.attrs.insert(String::from("_cdata"), String::from("1"));
219    }
220    note_created(it, owner, idx);
221    Ok(it.dom_val(idx))
222}
223
224fn doc_node_url(dom: &DomBridge, idx: usize) -> String {
225    dom.nodes
226        .get(idx)
227        .and_then(|n| n.attrs.get("_url"))
228        .filter(|s| !s.is_empty())
229        .cloned()
230        .unwrap_or_else(|| String::from("about:blank"))
231}
232
233fn is_html_base_in_doc(dom: &DomBridge, doc_idx: usize, elem_idx: usize) -> bool {
234    if let Some(ns) = dom.nodes.get(elem_idx).and_then(|n| n.attrs.get("_ns")) {
235        return ns == HTML_NS;
236    }
237    if dom.doc_is_html(Some(doc_idx)) {
238        return dom
239            .nodes
240            .get(elem_idx)
241            .and_then(super::dom_ns::node_namespace)
242            .as_deref()
243            == Some(HTML_NS);
244    }
245    let mut cur = Some(elem_idx);
246    while let Some(i) = cur {
247        let Some(n) = dom.nodes.get(i) else { break };
248        if let Some(xmlns) = n.attrs.get("xmlns") {
249            return xmlns == HTML_NS;
250        }
251        if i == doc_idx {
252            break;
253        }
254        cur = n.parent;
255    }
256    false
257}
258
259fn doc_node_base_uri(dom: &DomBridge, idx: usize) -> String {
260    let url = doc_node_url(dom, idx);
261    for b in dom.descendants_by_tag_name(idx, "base") {
262        if is_html_base_in_doc(dom, idx, b) {
263            if let Some(href) = dom.get_attr(b, "href") {
264                return match super::url_parser::parse(&href, Some(&url)) {
265                    Some(u) => super::url_parser::serialize(&u, false),
266                    None => super::resolve_url(&url, &href),
267                };
268            }
269        }
270    }
271    dom.nodes
272        .get(idx)
273        .and_then(|n| n.attrs.get("_base_url"))
274        .filter(|s| !s.is_empty())
275        .cloned()
276        .unwrap_or(url)
277}
278
279/// `doc.cloneNode(deep)`(`#document` ノード、および主文書の `document`)。
280pub(crate) fn doc_clone_node(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
281    let deep = arg(a, 0).truthy();
282    let (ctype, html, xmldoc, kids, url, base_url) = if let Some(src) = this_dom_idx(&this) {
283        let dom = it.dom().borrow();
284        let n = &dom.nodes[src];
285        (
286            n.attrs.get("_ctype").cloned().unwrap_or_default(),
287            n.attrs.contains_key("_html"),
288            n.attrs.contains_key("_xmldoc"),
289            n.children.clone(),
290            doc_node_url(&dom, src),
291            doc_node_base_uri(&dom, src),
292        )
293    } else if super::this_host_idx(&this, crate::os_lib::web_apis::dom_bridge::HOST_DOCUMENT).is_some() {
294        let dom = it.dom().borrow();
295        let mut kids = Vec::new();
296        if let Some(dt) = dom.main_doctype {
297            kids.push(dt);
298        }
299        if !dom.nodes.is_empty() {
300            kids.push(0);
301        }
302        let u = super::location_href(&it.global)
303            .filter(|s| !s.is_empty())
304            .unwrap_or_else(|| it.base_url.clone());
305        let u = if u.is_empty() { String::from("about:blank") } else { u };
306        let b = dom
307            .first_by_tag("base")
308            .and_then(|bi| dom.get_attr(bi, "href"))
309            .map(|h| super::resolve_url(&u, &h))
310            .unwrap_or_else(|| u.clone());
311        (String::from("text/html"), true, false, kids, u, b)
312    } else {
313        return Ok(Value::Null);
314    };
315    let d = new_doc_with(it, &ctype, html, xmldoc);
316    {
317        let mut dom = it.dom().borrow_mut();
318        if let Some(n) = dom.nodes.get_mut(d) {
319            n.attrs.insert(String::from("_url"), url);
320            n.attrs.insert(String::from("_base_url"), base_url);
321        }
322        if deep {
323            for k in kids {
324                let c = dom.clone_node(k, true);
325                dom.append_child(d, c);
326            }
327        }
328    }
329    Ok(it.dom_val(d))
330}
331
332impl Interp {
333    /// `#document` ノード `idx` の `Document` のメンバー。`#document` でなければ `None`(呼び出し側は通常の経路へ進む)。
334    pub(crate) fn doc_node_get(&mut self, idx: usize, key: &str) -> Option<Value> {
335        if !self.dom().borrow().is_doc_node(idx) {
336            return None;
337        }
338        let f = |it: &Interp, n: &'static str, f: NativeFn| it.builtin_fn_val(n, f);
339        Some(match key {
340            "nodeType" => Value::Number(9.0),
341            "nodeName" => Value::str("#document"),
342            "nodeValue" | "textContent" | "ownerDocument" | "location" | "activeElement" | "ontouchstart" => Value::Null,
343            "defaultView" => {
344                let iframe_idx = self.dom().borrow().iframe_doc_to_elem.get(&idx).copied();
345                match iframe_idx {
346                    Some(fi) => self.get_iframe_content_window(fi),
347                    None => Value::Null,
348                }
349            }
350            "isConnected" => Value::Bool(true),
351            "URL" | "documentURI" => Value::str(doc_node_url(&self.dom().borrow(), idx)),
352            "baseURI" => Value::str(doc_node_base_uri(&self.dom().borrow(), idx)),
353            "contentType" => Value::str(self.dom().borrow().nodes[idx].attrs.get("_ctype").cloned().unwrap_or_default()),
354            "characterSet" | "charset" | "inputEncoding" => Value::str("UTF-8"),
355            "compatMode" => Value::str("CSS1Compat"),
356            "readyState" => Value::str("complete"),
357            "referrer" | "cookie" | "lastModified" | "domain" => Value::str(""),
358            "hidden" => Value::Bool(false),
359            "visibilityState" => Value::str("visible"),
360            "documentElement" => {
361                let e = first_element_child(&self.dom().borrow(), idx);
362                crate::os_lib::web_apis::builtins::dom_handle(self, e)
363            }
364            "doctype" => {
365                let dt = {
366                    let dom = self.dom().borrow();
367                    dom.nodes[idx].children.iter().copied().find(|&c| dom.nodes.get(c).is_some_and(|n| n.tag == "#doctype"))
368                };
369                crate::os_lib::web_apis::builtins::dom_handle(self, dt)
370            }
371            "head" | "body" => {
372                let r = {
373                    let dom = self.dom().borrow();
374                    first_element_child(&dom, idx).filter(|&h| dom.nodes[h].tag == "html").and_then(|h| {
375                        dom.nodes[h].children.iter().copied().find(|&c| {
376                            dom.nodes.get(c).is_some_and(|n| {
377                                !n.is_text && (if key == "head" { n.tag == "head" } else { n.tag == "body" || n.tag == "frameset" })
378                            })
379                        })
380                    })
381                };
382                crate::os_lib::web_apis::builtins::dom_handle(self, r)
383            }
384            "title" => {
385                let dom = self.dom().borrow();
386                match doc_title_element(&dom, idx) {
387                    Some(t) => Value::str(strip_and_collapse(&dom.get_text_content(t))),
388                    None => Value::str(""),
389                }
390            }
391            "implementation" => {
392                let cached = self.dom().borrow().doc_impls.get(&idx).cloned();
393                match cached {
394                    Some(v) => v,
395                    None => {
396                        let proto = match self.global.borrow().vars.get("DOMImplementation") {
397                            Some(Value::Object(c)) => match c.borrow().props.get("prototype") {
398                                Some(Value::Object(p)) => Some(p.clone()),
399                                _ => None,
400                            },
401                            _ => None,
402                        };
403                        let v = make_implementation(proto, Some(self.dom_val(idx)));
404                        self.dom().borrow_mut().doc_impls.insert(idx, v.clone());
405                        v
406                    }
407                }
408            }
409            "createElement" => f(self, "createElement", super::dom::document_create_element),
410            "createElementNS" => f(self, "createElementNS", super::dom_ns::document_create_element_ns),
411            "createTextNode" => f(self, "createTextNode", super::dom::document_create_text_node),
412            "createComment" => f(self, "createComment", super::dom::document_create_comment),
413            "createProcessingInstruction" => f(self, "createProcessingInstruction", super::dom::document_create_processing_instruction),
414            "createDocumentFragment" => f(self, "createDocumentFragment", super::dom::document_create_document_fragment),
415            "createCDATASection" => f(self, "createCDATASection", doc_create_cdata_section),
416            "createAttribute" => f(self, "createAttribute", super::dom_attr::document_create_attribute),
417            "createAttributeNS" => f(self, "createAttributeNS", super::dom_attr::document_create_attribute_ns),
418            "createEvent" => f(self, "createEvent", super::events::document_create_event),
419            "importNode" => f(self, "importNode", super::dom_document::doc_import_node),
420            "adoptNode" => f(self, "adoptNode", super::dom_document::doc_adopt_node),
421            "createRange" => f(self, "createRange", super::range::document_create_range),
422            "createTreeWalker" => f(self, "createTreeWalker", super::window_api::document_create_tree_walker),
423            "createNodeIterator" => f(self, "createNodeIterator", super::window_api::document_create_node_iterator),
424            "normalize" => f(self, "normalize", super::dom::dom_normalize),
425            "getRootNode" => f(self, "getRootNode", super::dom::dom_get_root_node),
426            "cloneNode" => f(self, "cloneNode", doc_clone_node),
427            _ => return None,
428        })
429    }
430
431    /// `#document` ノードへの代入。扱ったら `true`。
432    pub(crate) fn doc_node_set(&mut self, idx: usize, key: &str, s: &str) -> bool {
433        if !self.dom().borrow().is_doc_node(idx) {
434            return false;
435        }
436        match key {
437            "textContent" | "nodeValue" => true,
438            "title" => {
439                let (root, title, head) = {
440                    let dom = self.dom().borrow();
441                    let root = first_element_child(&dom, idx);
442                    let head = root.and_then(|r| dom.nodes[r].children.iter().copied().find(|&c| dom.nodes.get(c).is_some_and(|n| n.tag == "head")));
443                    (root, doc_title_element(&dom, idx), head)
444                };
445                let is_html = root.is_some_and(|r| self.dom().borrow().nodes[r].tag == "html");
446                let mut dom = self.dom().borrow_mut();
447                match (title, head) {
448                    (Some(t), _) => dom.set_text_content(t, s),
449                    (None, Some(h)) if is_html => {
450                        let t = dom.create_element("title");
451                        dom.inherit_owner(t, h);
452                        dom.append_child(h, t);
453                        dom.set_text_content(t, s);
454                    }
455                    _ => {}
456                }
457                true
458            }
459            _ => false,
460        }
461    }
462}