Skip to main content

atmos/os_lib/web_apis/builtins/
dom.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4
5// ============ DOM ネイティブ ============
6
7/// 無害な no-op(未対応 API 用)。
8pub fn dom_noop(_: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
9    Ok(Value::Undefined)
10}
11
12/// `new XMLSerializer()`(丸ごと未対応だった。`.serializeToString(node)`
13/// という定番パターン)。
14pub(crate) fn xml_serializer_ctor(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
15    let o = Obj::plain();
16    o.borrow_mut().props.insert(
17        "serializeToString".into(),
18        nv("serializeToString", xml_serializer_serialize_to_string),
19    );
20    Ok(Value::Object(o))
21}
22/// `serializer.serializeToString(node)`。既存の `element.outerHTML` ゲッター
23/// (`interp.rs`)と同じ `DomBridge::get_outer_html` を再利用する(DOM 要素
24/// ハンドルでない値/未接続ノードは仕様の詳細な例外分岐を省略し空文字列を返す
25/// 簡略実装)。
26pub(crate) fn xml_serializer_serialize_to_string(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
27    let node = arg(a, 0);
28    match this_dom_idx(&node) {
29        Some(idx) => Ok(Value::str(it.dom().borrow().get_outer_html(idx))),
30        None => Ok(Value::str("")),
31    }
32}
33
34/// `this`(DOM 要素ハンドル)からノード index を取り出す。
35pub(crate) fn this_dom_idx(this: &Value) -> Option<usize> {
36    if let Value::Object(o) = this {
37        if let Some(i) = o.borrow().kind.dom_node() {
38            return Some(i);
39        }
40    }
41    None
42}
43
44/// `this`(Host("classList:N") など)から prefix を剥がして index を取り出す。
45/// `element.style.setProperty(name, value)`/`getPropertyValue(name)`/`removeProperty(name)`
46/// が丸ごと欠落していた(直接のプロパティ代入 `el.style.color = 'red'` と、
47/// `getComputedStyle().getPropertyValue()` はあったが、インラインスタイルの
48/// メソッド経由の読み書きが無かった)。特に CSS カスタムプロパティ(`--foo`)は
49/// camelCase のプロパティアクセサ経由では設定できないため、`setProperty` の欠落は
50/// カスタムプロパティを使う実用コードで特に影響が大きかった。
51pub fn dom_style_set_property(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
52    if let Some(idx) = this_host_idx(&this, HOST_STYLE) {
53        let name = arg(a, 0).to_js_string();
54        let value = arg(a, 1).to_js_string();
55        // `setProperty(name, value, priority)` の第3引数(丸ごと無視されて
56        // いた。2026-07-16 発見)。生の値文字列末尾に `!important` を
57        // 付加して保存すれば、`serialize_inline_style` 経由で再構築される
58        // `style` 属性文字列を通じて既存のカスケード側 `!important` パーサ
59        // (`css.rs`)にもそのまま伝わる。
60        let priority = arg(a, 2).to_js_string();
61        let stored = if !value.is_empty() && priority.eq_ignore_ascii_case("important") {
62            alloc::format!("{} !important", value)
63        } else {
64            value
65        };
66        it.dom().borrow_mut().set_style(idx, &name, &stored);
67    }
68    Ok(Value::Undefined)
69}
70pub fn dom_style_get_property_priority(
71    it: &mut Interp,
72    this: Value,
73    a: &[Value],
74) -> Result<Value, Value> {
75    if let Some(idx) = this_host_idx(&this, HOST_STYLE) {
76        let name = arg(a, 0).to_js_string();
77        return Ok(Value::str(it.dom().borrow().get_style_priority(idx, &name)));
78    }
79    Ok(Value::str(""))
80}
81pub fn dom_style_get_property_value(
82    it: &mut Interp,
83    this: Value,
84    a: &[Value],
85) -> Result<Value, Value> {
86    if let Some(idx) = this_host_idx(&this, HOST_STYLE) {
87        let name = arg(a, 0).to_js_string();
88        return Ok(Value::str(it.dom().borrow().get_style(idx, &name)));
89    }
90    Ok(Value::str(""))
91}
92pub fn dom_style_remove_property(
93    it: &mut Interp,
94    this: Value,
95    a: &[Value],
96) -> Result<Value, Value> {
97    if let Some(idx) = this_host_idx(&this, HOST_STYLE) {
98        let name = arg(a, 0).to_js_string();
99        let prev = it.dom().borrow().get_style(idx, &name);
100        it.dom().borrow_mut().set_style(idx, &name, "");
101        return Ok(Value::str(prev));
102    }
103    Ok(Value::str(""))
104}
105/// `style.item(index)`(丸ごと未対応だった。`style.length`と対)。
106/// `get_css_text`の直列化文字列を`;`で分割し直す簡略実装(`dom_props.rs`
107/// の`length`ゲッターと同じロジック)。
108pub fn dom_style_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
109    if let Some(idx) = this_host_idx(&this, HOST_STYLE) {
110        let names: alloc::vec::Vec<String> = it
111            .dom()
112            .borrow()
113            .get_css_text(idx)
114            .split(';')
115            .filter_map(|d| d.split_once(':').map(|(k, _)| k.trim().to_string()))
116            .filter(|k| !k.is_empty())
117            .collect();
118        let i = arg(a, 0).to_number();
119        if i.is_finite() && i >= 0.0 {
120            if let Some(name) = names.get(i as usize) {
121                return Ok(Value::str(name.clone()));
122            }
123        }
124    }
125    Ok(Value::str(""))
126}
127/// `this` が種類 `class`(`HOST_STYLE` など)のホスト物なら、その `id`(ノード index)。
128pub(crate) fn this_host_idx(this: &Value, class: u8) -> Option<usize> {
129    if let Value::Object(o) = this {
130        if let ObjKind::HostRef(h) = &o.borrow().kind {
131            if h.class == class {
132                return Some(h.id);
133            }
134        }
135    }
136    None
137}
138
139/// 要素ハンドルを Value にして返す。idx が無ければ null。
140pub(crate) fn dom_handle(it: &Interp, idx: Option<usize>) -> Value {
141    match idx {
142        Some(i) => it.dom_val(i),
143        None => Value::Null,
144    }
145}
146
147pub(crate) fn document_get_element_by_id(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
148    let id = arg(a, 0).to_js_string();
149    let idx = it.dom().borrow().get_element_by_id(&id);
150    Ok(dom_handle(it, idx))
151}
152
153/// `document.contains(node)`(2026-11-19。無くて ShadyDOM の `__shady_native_contains` が
154/// `contains is not a function` で落ちた)。document 自身か、document に接続された要素なら true。
155pub(crate) fn document_contains(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
156    let other = arg(a, 0);
157    if let (Value::Object(x), Value::Object(y)) = (&this, &other) {
158        if alloc::rc::Rc::ptr_eq(x, y) {
159            return Ok(Value::Bool(true));
160        }
161    }
162    if let Some(i) = this_dom_idx(&other) {
163        return Ok(Value::Bool(it.dom().borrow().is_attached(i)));
164    }
165    Ok(Value::Bool(false))
166}
167
168fn check_selector_syntax(it: &Interp, sel: &str) -> Result<(), Value> {
169    if crate::os_lib::dom_selector::selector_syntax_error(sel) {
170        return Err(it.dom_exception(
171            "SyntaxError",
172            "Failed to execute selector query: invalid selector syntax.",
173        ));
174    }
175    let mut quote: Option<char> = None;
176    let mut bracket = 0usize;
177    let mut escape = false;
178    let mut prev_slash = false;
179    for c in sel.chars() {
180        if escape {
181            escape = false;
182            prev_slash = false;
183            continue;
184        }
185        if c == '\\' {
186            escape = true;
187            prev_slash = false;
188            continue;
189        }
190        if let Some(q) = quote {
191            if c == q {
192                quote = None;
193            }
194            prev_slash = false;
195            continue;
196        }
197        match c {
198            '"' | '\'' => {
199                quote = Some(c);
200                prev_slash = false;
201            }
202            '[' => {
203                bracket += 1;
204                prev_slash = false;
205            }
206            ']' => {
207                bracket = bracket.saturating_sub(1);
208                prev_slash = false;
209            }
210            '/' if bracket == 0 => {
211                if prev_slash {
212                    return Err(it.dom_exception(
213                        "SyntaxError",
214                        "Failed to execute querySelector: '//' is not a valid selector.",
215                    ));
216                }
217                prev_slash = true;
218            }
219            _ => prev_slash = false,
220        }
221    }
222    Ok(())
223}
224
225pub(crate) fn document_query_selector(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
226    let sel = it.to_string_value(arg(a, 0))?;
227    check_selector_syntax(it, &sel)?;
228    let idx = it.dom().borrow().query(&sel);
229    Ok(dom_handle(it, idx))
230}
231
232pub(crate) fn document_query_selector_all(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
233    let sel = it.to_string_value(arg(a, 0))?;
234    check_selector_syntax(it, &sel)?;
235    let indices = it.dom().borrow().query_all(&sel);
236    Ok(make_static_node_list(it, indices))
237}
238/// 座標 `(x, y)` を含む矩形を持つ要素を、面積が小さい(=最も深くネストした)
239/// 順に列挙する共通ヘルパー。`elementFromPoint`/`elementsFromPoint` で共有。
240pub(crate) fn dom_hit_test(it: &Interp, x: f64, y: f64) -> alloc::vec::Vec<(usize, i64)> {
241    let dom = it.dom().borrow();
242    let mut matches: alloc::vec::Vec<(usize, i64)> = alloc::vec::Vec::new();
243    for (&idx, &(l, t, w, h)) in dom.rects.iter() {
244        let (lf, tf, wf, hf) = (l as f64, t as f64, w as f64, h as f64);
245        if x >= lf && x < lf + wf && y >= tf && y < tf + hf {
246            matches.push((idx, (w as i64) * (h as i64)));
247        }
248    }
249    matches.sort_by_key(|&(_, area)| area);
250    matches
251}
252pub(crate) fn document_element_from_point(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
253    let x = arg(a, 0).to_number();
254    let y = arg(a, 1).to_number();
255    let matches = dom_hit_test(it, x, y);
256    Ok(match matches.first() {
257        Some(&(idx, _)) => it.dom_val(idx),
258        None => Value::Null,
259    })
260}
261pub(crate) fn document_elements_from_point(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
262    let x = arg(a, 0).to_number();
263    let y = arg(a, 1).to_number();
264    let items: alloc::vec::Vec<Value> = dom_hit_test(it, x, y)
265        .into_iter()
266        .map(|(idx, _)| it.dom_val(idx))
267        .collect();
268    Ok(Value::Object(Obj::array(items)))
269}
270
271pub fn dom_add_event_listener(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
272    let event = arg(a, 0).to_js_string();
273    let func = arg(a, 1);
274    let default_passive = super::events::is_passive_by_default(it, &this, &event);
275    let (capture, once, passive, signal) =
276        super::events::parse_listener_opts_interp(it, &arg(a, 2), true, default_passive)?;
277    if let Some(idx) = this_dom_idx(&this) {
278        if matches!(func, Value::Object(_)) {
279            it.dom()
280                .borrow_mut()
281                .add_listener_full(idx, &event, func, capture, once, passive, signal);
282        }
283    }
284    Ok(Value::Undefined)
285}
286
287/// addEventListener / removeEventListener の第3引数を解釈する。
288/// boolean なら capture フラグ、オブジェクトなら {capture, once} を読む。
289pub(crate) fn parse_listener_opts(opt: &Value) -> (bool, bool) {
290    match opt {
291        Value::Bool(b) => (*b, false),
292        Value::Object(o) => {
293            let b = o.borrow();
294            let capture = b.props.get("capture").map(|v| v.truthy()).unwrap_or(false);
295            let once = b.props.get("once").map(|v| v.truthy()).unwrap_or(false);
296            (capture, once)
297        }
298        _ => (false, false),
299    }
300}
301/// `addEventListener(type, fn, {signal})` の `signal` オプションを取り出す。
302pub(crate) fn parse_listener_signal(opt: &Value) -> Option<Value> {
303    if let Value::Object(o) = opt {
304        let s = o.borrow().props.get("signal").cloned();
305        if let Some(sig) = &s {
306            if super::events::is_abort_signal(sig) {
307                return Some(sig.clone());
308            }
309        }
310    }
311    None
312}
313
314/// element.removeEventListener(type, fn, opts): 一致するリスナを削除する。
315pub fn dom_remove_event_listener(
316    it: &mut Interp,
317    this: Value,
318    a: &[Value],
319) -> Result<Value, Value> {
320    let event = arg(a, 0).to_js_string();
321    let func = arg(a, 1);
322    let (capture, _, _, _) = super::events::parse_listener_opts_interp(it, &arg(a, 2), false, false)?;
323    if let Some(idx) = this_dom_idx(&this) {
324        if matches!(func, Value::Object(_)) {
325            it.dom()
326                .borrow_mut()
327                .remove_listener(idx, &event, &func, capture);
328        }
329    }
330    Ok(Value::Undefined)
331}
332
333/// element.dispatchEvent(ev): ev.type のイベントを当該要素から発火する。
334/// 戻り値は !defaultPrevented(DOM 仕様)。
335pub fn dom_dispatch_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
336    let idx = match this_dom_idx(&this) {
337        Some(i) => i,
338        None => return Ok(Value::Bool(true)),
339    };
340    let ev = arg(a, 0);
341    super::events::validate_dispatch_event(it, &ev)?;
342    // ev.type を取得。bubbles など追加プロパティはそのまま渡す。
343    let (etype, extra) = if let Value::Object(o) = &ev {
344        let b = o.borrow();
345        let t = b
346            .props
347            .get("type")
348            .map(|v| v.to_js_string())
349            .unwrap_or_default();
350        let mut extra: Vec<(String, Value)> = Vec::new();
351        for (k, v) in b.props.iter() {
352            if matches!(
353                k.as_str(),
354                "type"
355                    | "target"
356                    | "currentTarget"
357                    | "eventPhase"
358                    | "defaultPrevented"
359                    | "preventDefault"
360                    | "stopPropagation"
361                    | "stopImmediatePropagation"
362                    | "composedPath"
363                    | "_composedPath"
364                    | "_stop"
365                    | "_stopImmediate"
366            ) {
367                continue;
368            }
369            extra.push((k.clone().into(), v.clone()));
370        }
371        (t, extra)
372    } else {
373        (ev.to_js_string(), Vec::new())
374    };
375    let user_ev = match &ev {
376        Value::Object(o) => Some(o.clone()),
377        _ => None,
378    };
379    let (_fired, prevented) = it.dispatch_event_object(idx, &etype, &extra, user_ev);
380    Ok(Value::Bool(!prevented))
381}
382
383/// `node.hasChildNodes()`(丸ごと未対応だった。`node.childNodes.length > 0`
384/// の定番の手間を省くメソッド)。
385pub fn dom_has_child_nodes(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
386    if let Some(idx) = this_dom_idx(&this) {
387        let has_kids = it
388            .dom()
389            .borrow()
390            .nodes
391            .get(idx)
392            .map(|n| !n.children.is_empty())
393            .unwrap_or(false);
394        return Ok(Value::Bool(has_kids));
395    }
396    Ok(Value::Bool(false))
397}
398pub fn dom_get_attribute(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
399    if let Some(r) = super::dom_pi::pi_attr(it, &this, "getAttribute", a) {
400        return r;
401    }
402    if let Some(idx) = this_dom_idx(&this) {
403        let name = super::dom_attr::fix_name(it, idx, &arg(a, 0).to_js_string());
404        let dom = it.dom().borrow();
405        let val = if name.starts_with('_') {
406            dom.get_attr(idx, &name)
407        } else {
408            dom.attr_entries(idx).into_iter().find_map(|(ns, qn)| {
409                if qn != name {
410                    return None;
411                }
412                match ns {
413                    None => dom.get_attr(idx, &qn),
414                    Some(u) => {
415                        let local = qn.split_once(':').map(|(_, l)| l).unwrap_or(&qn);
416                        dom.get_attr_ns(idx, Some(&u), local)
417                    }
418                }
419            })
420        };
421        return Ok(match val {
422            Some(v) => Value::str(v),
423            None => Value::Null,
424        });
425    }
426    Ok(Value::Null)
427}
428
429pub fn dom_has_attribute(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
430    if let Some(r) = super::dom_pi::pi_attr(it, &this, "hasAttribute", a) {
431        return r;
432    }
433    if let Some(idx) = this_dom_idx(&this) {
434        let name = super::dom_attr::fix_name(it, idx, &arg(a, 0).to_js_string());
435        let dom = it.dom().borrow();
436        let has = dom.has_attr(idx, &name)
437            || (!name.starts_with('_')
438                && dom
439                    .ns_attrs
440                    .get(&idx)
441                    .is_some_and(|list| list.iter().any(|(_, qn, _)| *qn == name)));
442        return Ok(Value::Bool(has));
443    }
444    Ok(Value::Bool(false))
445}
446
447/// `element.attributes`(`NamedNodeMap`。`{name,value}` の簡略表現)と同じ
448/// 形で `Attr` ノード相当のオブジェクトを作る。`ownerElement` も含める。
449pub fn dom_remove_attribute(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
450    if let Some(r) = super::dom_pi::pi_attr(it, &this, "removeAttribute", a) {
451        return r;
452    }
453    if let Some(idx) = this_dom_idx(&this) {
454        let name = super::dom_attr::fix_name(it, idx, &arg(a, 0).to_js_string());
455        let removed_ns = {
456            let mut dom = it.dom().borrow_mut();
457            if name.starts_with("on") && !dom.on_handlers.is_empty() {
458                dom.on_handlers.remove(&(idx, name.clone()));
459            }
460            if name.starts_with('_') {
461                dom.remove_attr(idx, &name);
462                false
463            } else {
464                let target = dom.attr_entries(idx).into_iter().find(|(_, qn)| *qn == name);
465                match target {
466                    Some((None, qn)) => {
467                        dom.remove_attr(idx, &qn);
468                        false
469                    }
470                    Some((Some(ns), qn)) => {
471                        let local = qn.split_once(':').map(|(_, l)| l).unwrap_or(&qn).to_string();
472                        dom.remove_attr_ns(idx, Some(&ns), &local);
473                        true
474                    }
475                    None => false,
476                }
477            }
478        };
479        if !removed_ns {
480            super::dom_handlers::attr_changed(it, idx, &name, None);
481        }
482    }
483    Ok(Value::Undefined)
484}
485
486// `getAttributeNS` ほかの名前空間つきの属性・`Attr` ノードは `dom_attr.rs`。
487pub fn dom_get_attribute_names(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
488    if let Some(r) = super::dom_pi::pi_attr(it, &this, "getAttributeNames", &[]) {
489        return r;
490    }
491    if let Some(idx) = this_dom_idx(&this) {
492        let names: Vec<Value> = it
493            .dom()
494            .borrow()
495            .attr_names(idx)
496            .into_iter()
497            .map(Value::str)
498            .collect();
499        return Ok(Value::Object(Obj::array(names)));
500    }
501    Ok(Value::Object(Obj::array(Vec::new())))
502}
503/// `element.hasAttributes()`(丸ごと未対応だった。単一属性の有無を見る `hasAttribute(name)`
504/// は既に実装済みだったが、「1つでも属性を持つか」を見るこちらが漏れていた)。
505pub fn dom_has_attributes(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
506    if let Some(r) = super::dom_pi::pi_attr(it, &this, "hasAttributes", &[]) {
507        return r;
508    }
509    if let Some(idx) = this_dom_idx(&this) {
510        return Ok(Value::Bool(!it.dom().borrow().attr_names(idx).is_empty()));
511    }
512    Ok(Value::Bool(false))
513}
514/// `node.normalize()`(丸ごと未対応だった。連続する隣接テキストノードを1つに連結し、
515/// 空のテキストノードを取り除く DOM 標準メソッド)。
516pub fn dom_normalize(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
517    if let Some(idx) = this_dom_idx(&this) {
518        it.dom().borrow_mut().normalize_node(idx);
519    }
520    Ok(Value::Undefined)
521}
522/// `CharacterData.appendData`/`.deleteData`/`.insertData`/`.replaceData`/`.substringData`。
523/// テキスト・コメントのみに意味を持つ(呼び出し元の `dom_props.rs` 側でガード済み)。
524/// 文字データを UTF-16 コード単位の列で得る(DOM の `length`・オフセットは UTF-16 コード単位。2026-11-19、
525/// WPT `dom/nodes/CharacterData-*.html`)。孤立サロゲートは文字列に入らない(この処理系の文字列は UTF-8)。
526fn char_data_units(it: &Interp, idx: usize) -> alloc::vec::Vec<u16> {
527    it.dom().borrow().get_text_content(idx).encode_utf16().collect()
528}
529fn units_to_string(u: &[u16]) -> String {
530    String::from_utf16_lossy(u)
531}
532/// WebIDL の `unsigned long`(ToUint32)。
533fn to_uint32(v: &Value) -> u32 {
534    let n = v.to_number();
535    if !n.is_finite() {
536        return 0;
537    }
538    (libm::trunc(n) as i64).rem_euclid(1i64 << 32) as u32
539}
540/// 引数の個数の検査(足りなければ TypeError)。
541fn need_args(it: &Interp, a: &[Value], n: usize, method: &str) -> Result<(), Value> {
542    if a.len() < n {
543        return Err(it.type_error(alloc::format!(
544            "Failed to execute '{}' on 'CharacterData': {} arguments required, but only {} present.",
545            method,
546            n,
547            a.len()
548        )));
549    }
550    Ok(())
551}
552pub fn dom_char_data_append(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
553    need_args(it, a, 1, "appendData")?;
554    if let Some(idx) = this_dom_idx(&this) {
555        let mut s = it.dom().borrow().get_text_content(idx);
556        let old_len = s.encode_utf16().count();
557        let add = arg(a, 0).to_js_string();
558        let add_len = add.encode_utf16().count();
559        s.push_str(&add);
560        it.dom().borrow_mut().replace_data(idx, old_len, 0, add_len, &s);
561    }
562    Ok(Value::Undefined)
563}
564/// `CharacterData`編集メソッド群(`deleteData`/`insertData`/`replaceData`/
565/// `substringData`)は仕様上、`offset`が`length`を超える場合`IndexSizeError`を
566/// 投げる(`count`側は超過分を自動的にクランプするだけで例外にはならない)。
567/// `offset`・`count` は `unsigned long`(負の値は 2^32 を足した大きな数になって範囲外)。
568fn char_data_check_offset(it: &Interp, offset_arg: Value, len: usize) -> Result<usize, Value> {
569    let offset = to_uint32(&offset_arg) as usize;
570    if offset > len {
571        return Err(it.dom_exception(
572            "IndexSizeError",
573            "The offset is greater than the length of the data",
574        ));
575    }
576    Ok(offset)
577}
578pub fn dom_char_data_delete(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
579    need_args(it, a, 2, "deleteData")?;
580    if let Some(idx) = this_dom_idx(&this) {
581        let u = char_data_units(it, idx);
582        let len = u.len();
583        let offset = char_data_check_offset(it, arg(a, 0), len)?;
584        let count = (to_uint32(&arg(a, 1)) as usize).min(len - offset);
585        let mut out = u[..offset].to_vec();
586        out.extend_from_slice(&u[offset + count..]);
587        it.dom().borrow_mut().replace_data(idx, offset, count, 0, &units_to_string(&out));
588    }
589    Ok(Value::Undefined)
590}
591pub fn dom_char_data_insert(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
592    need_args(it, a, 2, "insertData")?;
593    if let Some(idx) = this_dom_idx(&this) {
594        let u = char_data_units(it, idx);
595        let len = u.len();
596        let offset = char_data_check_offset(it, arg(a, 0), len)?;
597        let insert: alloc::vec::Vec<u16> = arg(a, 1).to_js_string().encode_utf16().collect();
598        let mut out = u[..offset].to_vec();
599        out.extend_from_slice(&insert);
600        out.extend_from_slice(&u[offset..]);
601        it.dom().borrow_mut().replace_data(idx, offset, 0, insert.len(), &units_to_string(&out));
602    }
603    Ok(Value::Undefined)
604}
605pub fn dom_char_data_replace(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
606    need_args(it, a, 3, "replaceData")?;
607    if let Some(idx) = this_dom_idx(&this) {
608        let u = char_data_units(it, idx);
609        let len = u.len();
610        let offset = char_data_check_offset(it, arg(a, 0), len)?;
611        let count = (to_uint32(&arg(a, 1)) as usize).min(len - offset);
612        let replacement: alloc::vec::Vec<u16> = arg(a, 2).to_js_string().encode_utf16().collect();
613        let mut out = u[..offset].to_vec();
614        out.extend_from_slice(&replacement);
615        out.extend_from_slice(&u[offset + count..]);
616        it.dom().borrow_mut().replace_data(idx, offset, count, replacement.len(), &units_to_string(&out));
617    }
618    Ok(Value::Undefined)
619}
620pub fn dom_char_data_substring(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
621    need_args(it, a, 2, "substringData")?;
622    if let Some(idx) = this_dom_idx(&this) {
623        let u = char_data_units(it, idx);
624        let len = u.len();
625        let offset = char_data_check_offset(it, arg(a, 0), len)?;
626        let count = (to_uint32(&arg(a, 1)) as usize).min(len - offset);
627        return Ok(Value::str(units_to_string(&u[offset..offset + count])));
628    }
629    Ok(Value::str(""))
630}
631/// `Text.splitText(offset)`。テキストノードを`offset`(UTF-16 コード単位)位置で
632/// 2つに分割し、後半を新しいテキストノードとして直後の兄弟に挿入して返す。
633pub fn dom_split_text(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
634    need_args(it, a, 1, "splitText")?;
635    let Some(idx) = this_dom_idx(&this) else {
636        return Ok(Value::Undefined);
637    };
638    let u = char_data_units(it, idx);
639    let len = u.len();
640    let offset = char_data_check_offset(it, arg(a, 0), len)?;
641    let before: String = units_to_string(&u[..offset]);
642    let after: String = units_to_string(&u[offset..]);
643    let new_idx = it.dom().borrow_mut().create_text_node(&after);
644    {
645        let mut dom = it.dom().borrow_mut();
646        dom.inherit_owner(new_idx, idx);
647        // CDATASection の分割は CDATASection(`_cdata` の印を引き継ぐ)。
648        if dom.nodes[idx].attrs.contains_key("_cdata") {
649            dom.nodes[new_idx].attrs.insert(String::from("_cdata"), String::from("1"));
650        }
651    }
652    let (parent, next_sibling) = {
653        let dom = it.dom().borrow();
654        match dom.nodes.get(idx).and_then(|n| n.parent) {
655            Some(p) => {
656                let pos = dom.nodes[p].children.iter().position(|&c| c == idx);
657                let next = pos.and_then(|i| dom.nodes[p].children.get(i + 1)).copied();
658                (Some(p), next)
659            }
660            None => (None, None),
661        }
662    };
663    if let Some(p) = parent {
664        it.dom().borrow_mut().insert_before(p, new_idx, next_sibling);
665    }
666    it.dom().borrow_mut().ranges_split(idx, new_idx, parent, offset);
667    it.dom().borrow_mut().replace_data(idx, offset, len - offset, 0, &before);
668    Ok(it.dom_val(new_idx))
669}
670
671/// HTML5 Table DOM(`table.insertRow`/`.deleteRow`/`.rows`、`tr.insertCell`/
672/// `.deleteCell`/`.cells`)が丸ごと未対応だった(2026-07-17 発見。`select.
673/// options.add`/`.remove` と同じ「動的に構築する」定番イディオム)。`thead`/
674/// `tbody`/`tfoot` を明示的にモデル化せず、常に文書順の `descendants_by_tags`
675/// で `tr`/`td`/`th` を集約する簡略実装(新規行は「参照行の親」=既存の
676/// `tbody`があればその中、無ければ`table`直下へ挿入する)。
677pub fn dom_table_insert_row(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
678    let Some(table_idx) = this_dom_idx(&this) else {
679        return Ok(Value::Undefined);
680    };
681    let rows = it.dom().borrow().descendants_by_tags(table_idx, &["tr"]);
682    let len = rows.len();
683    let pos = arg(a, 0).to_number();
684    let pos = if pos.is_nan() { -1 } else { pos as i64 };
685    // 仕様上 `insertRow(index)` の有効範囲は `-1 <= index <= rows.length`
686    // (`-1`/`length`は末尾への追加を意味する)で、範囲外は`IndexSizeError`を
687    // 投げるべきだが、以前は範囲外の値をすべて「末尾へ追加」として黙って
688    // 受け入れてしまっていた(`table.insertRow(9999)`が例外にならず末尾追加
689    // として成功していた)。`insertCell`/`deleteRow`/`deleteCell`にも同じ
690    // パターンのバグがあり、まとめて修正した。
691    if pos < -1 || pos > len as i64 {
692        return Err(it.dom_exception(
693            "IndexSizeError",
694            "The index provided is outside the range of rows represented by this table",
695        ));
696    }
697    let (parent, ref_child) = if pos >= 0 && (pos as usize) < len {
698        let r = rows[pos as usize];
699        (it.dom().borrow().nodes.get(r).and_then(|n| n.parent).unwrap_or(table_idx), Some(r))
700    } else if let Some(&last) = rows.last() {
701        (it.dom().borrow().nodes.get(last).and_then(|n| n.parent).unwrap_or(table_idx), None)
702    } else {
703        (table_idx, None)
704    };
705    let new_row = it.dom().borrow_mut().create_element("tr");
706    it.dom().borrow_mut().insert_before(parent, new_row, ref_child);
707    Ok(it.dom_val(new_row))
708}
709pub fn dom_table_delete_row(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
710    let Some(table_idx) = this_dom_idx(&this) else {
711        return Ok(Value::Undefined);
712    };
713    let rows = it.dom().borrow().descendants_by_tags(table_idx, &["tr"]);
714    let pos = arg(a, 0).to_number();
715    let pos = if pos.is_nan() { -1 } else { pos as i64 };
716    // 仕様上 `deleteRow(index)` の有効範囲は `-1 <= index < rows.length`
717    // (`-1`は末尾行の削除を意味する)で、範囲外は`IndexSizeError`を投げる
718    // べきだが、以前は範囲外の値をすべて「末尾行を削除」として黙って受け
719    // 入れてしまっていた(詳細は`insertRow`側の同種コメント参照)。
720    if pos < -1 || pos >= rows.len() as i64 {
721        return Err(it.dom_exception(
722            "IndexSizeError",
723            "The index provided is outside the range of rows represented by this table",
724        ));
725    }
726    let target = if pos >= 0 {
727        Some(rows[pos as usize])
728    } else {
729        rows.last().copied()
730    };
731    if let Some(r) = target {
732        it.dom().borrow_mut().remove_node(r);
733    }
734    Ok(Value::Undefined)
735}
736pub fn dom_table_insert_cell(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
737    let Some(row_idx) = this_dom_idx(&this) else {
738        return Ok(Value::Undefined);
739    };
740    let cells = it.dom().borrow().descendants_by_tags(row_idx, &["td", "th"]);
741    let len = cells.len();
742    let pos = arg(a, 0).to_number();
743    let pos = if pos.is_nan() { -1 } else { pos as i64 };
744    // `insertRow`と同じ仕様上の有効範囲チェック(`-1 <= index <= cells.length`)。
745    // 詳細はそちらの同種コメント参照。
746    if pos < -1 || pos > len as i64 {
747        return Err(it.dom_exception(
748            "IndexSizeError",
749            "The index provided is outside the range of cells represented by this row",
750        ));
751    }
752    let ref_child = if pos >= 0 && (pos as usize) < len { Some(cells[pos as usize]) } else { None };
753    let new_cell = it.dom().borrow_mut().create_element("td");
754    it.dom().borrow_mut().insert_before(row_idx, new_cell, ref_child);
755    Ok(it.dom_val(new_cell))
756}
757pub fn dom_table_delete_cell(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
758    let Some(row_idx) = this_dom_idx(&this) else {
759        return Ok(Value::Undefined);
760    };
761    let cells = it.dom().borrow().descendants_by_tags(row_idx, &["td", "th"]);
762    let pos = arg(a, 0).to_number();
763    let pos = if pos.is_nan() { -1 } else { pos as i64 };
764    // `deleteRow`と同じ仕様上の有効範囲チェック(`-1 <= index < cells.length`)。
765    // 詳細はそちらの同種コメント参照。
766    if pos < -1 || pos >= cells.len() as i64 {
767        return Err(it.dom_exception(
768            "IndexSizeError",
769            "The index provided is outside the range of cells represented by this row",
770        ));
771    }
772    let target = if pos >= 0 {
773        Some(cells[pos as usize])
774    } else {
775        cells.last().copied()
776    };
777    if let Some(c) = target {
778        it.dom().borrow_mut().remove_node(c);
779    }
780    Ok(Value::Undefined)
781}
782
783/// `table.createTHead()`/`.createTFoot()`/`.createCaption()`(丸ごと未対応
784/// だった。2026-07-17 発見。仕様上「既存の該当要素があればそれを返す、
785/// 無ければ新規作成して挿入する」冪等な動作)。直接の子のみを対象とする
786/// (`tHead`/`tFoot`/`caption`ゲッターと同じ制約)。`caption`は最初の子、
787/// `thead`は最初の子(`caption`の後)、`tfoot`は最後の子として挿入する
788/// 簡略実装(`colgroup`との相対位置関係は厳密には対象外)。
789fn table_create_section(it: &mut Interp, table_idx: usize, tag: &str, append: bool) -> Value {
790    let existing = {
791        let dom = it.dom().borrow();
792        dom.nodes[table_idx].children.iter().find(|&&c| dom.nodes[c].tag == tag).copied()
793    };
794    if let Some(i) = existing {
795        return it.dom_val(i);
796    }
797    let new_idx = it.dom().borrow_mut().create_element(tag);
798    let ref_child = if append {
799        None
800    } else {
801        it.dom().borrow().nodes[table_idx].children.first().copied()
802    };
803    it.dom().borrow_mut().insert_before(table_idx, new_idx, ref_child);
804    it.dom_val(new_idx)
805}
806fn table_delete_section(it: &mut Interp, table_idx: usize, tag: &str) {
807    let existing = {
808        let dom = it.dom().borrow();
809        dom.nodes[table_idx].children.iter().find(|&&c| dom.nodes[c].tag == tag).copied()
810    };
811    if let Some(i) = existing {
812        it.dom().borrow_mut().remove_node(i);
813    }
814}
815pub fn dom_table_create_thead(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
816    Ok(match this_dom_idx(&this) {
817        Some(idx) => table_create_section(it, idx, "thead", false),
818        None => Value::Undefined,
819    })
820}
821pub fn dom_table_create_tfoot(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
822    Ok(match this_dom_idx(&this) {
823        Some(idx) => table_create_section(it, idx, "tfoot", true),
824        None => Value::Undefined,
825    })
826}
827pub fn dom_table_create_caption(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
828    Ok(match this_dom_idx(&this) {
829        Some(idx) => table_create_section(it, idx, "caption", false),
830        None => Value::Undefined,
831    })
832}
833pub fn dom_table_delete_thead(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
834    if let Some(idx) = this_dom_idx(&this) {
835        table_delete_section(it, idx, "thead");
836    }
837    Ok(Value::Undefined)
838}
839pub fn dom_table_delete_tfoot(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
840    if let Some(idx) = this_dom_idx(&this) {
841        table_delete_section(it, idx, "tfoot");
842    }
843    Ok(Value::Undefined)
844}
845pub fn dom_table_delete_caption(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
846    if let Some(idx) = this_dom_idx(&this) {
847        table_delete_section(it, idx, "caption");
848    }
849    Ok(Value::Undefined)
850}
851
852/// `img.decode()`(丸ごと未対応だった。2026-07-17 発見)。実デコード成否を
853/// 追跡する経路が無いため、`complete`ゲッターと同じ「`src`があれば
854/// ロード試行済み」前提で、`src`があれば解決・無ければ`DOMException
855/// ("EncodingError")`で拒否するPromiseを返す簡略実装。
856pub fn dom_img_decode(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
857    let has_src = this_dom_idx(&this)
858        .map(|idx| it.dom().borrow().get_attr(idx, "src").map(|s| !s.is_empty()).unwrap_or(false))
859        .unwrap_or(false);
860    if has_src {
861        Ok(resolved_promise(it, Value::Undefined))
862    } else {
863        let reason = it.dom_exception("EncodingError", "The source image cannot be decoded");
864        Ok(rejected_promise(it, reason))
865    }
866}
867
868/// 現在の`.value`文字列を読む(`textarea`は`value`属性優先、無ければ
869/// `initial_text`にフォールバック。`interp/dom_props.rs`の`value`
870/// ゲッターと同じロジック)。
871fn current_field_value(it: &Interp, idx: usize) -> String {
872    let dom = it.dom().borrow();
873    let tag = dom.nodes.get(idx).map(|n| n.tag.as_str()).unwrap_or("");
874    if tag == "textarea" {
875        dom.get_attr(idx, "_live_value")
876            .or_else(|| dom.get_attr(idx, "value"))
877            .unwrap_or_else(|| dom.nodes.get(idx).map(|n| n.initial_text.clone()).unwrap_or_default())
878    } else {
879        dom.get_attr(idx, "_live_value")
880            .or_else(|| dom.get_attr(idx, "value"))
881            .unwrap_or_default()
882    }
883}
884/// `input`/`textarea.setSelectionRange(start, end, direction?)`(丸ごと
885/// 未対応だった。`selectionStart`/`.selectionEnd`/`.selectionDirection`
886/// と対になる一括設定メソッド。2026-07-17 発見・実装)。3プロパティへの
887/// 個別代入と同じ内部専用属性へまとめて保存する簡略実装。
888pub fn dom_set_selection_range(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
889    if let Some(idx) = this_dom_idx(&this) {
890        let start = arg(a, 0).to_number();
891        let end = arg(a, 1).to_number();
892        let direction = if matches!(arg(a, 2), Value::Undefined) {
893            String::from("none")
894        } else {
895            arg(a, 2).to_js_string()
896        };
897        let mut dom = it.dom().borrow_mut();
898        dom.set_attr(idx, "_selection_start", &Value::Number(start).to_js_string());
899        dom.set_attr(idx, "_selection_end", &Value::Number(end).to_js_string());
900        dom.set_attr(idx, "_selection_direction", &direction);
901    }
902    Ok(Value::Undefined)
903}
904/// `input`/`textarea.setRangeText(replacement, start?, end?, selectMode?)`
905/// (丸ごと未対応だった。2026-07-17 発見・実装)。`start`/`end`省略時は
906/// 現在の`selectionStart`/`.selectionEnd`を使う(仕様どおり)。
907/// `selectMode`は`"select"`(置換後の範囲を選択)/`"start"`(キャレットを
908/// 置換範囲の先頭へ)/`"end"`(末尾へ、既定)/`"preserve"`(元の選択位置を
909/// 維持しようと試みる)に対応する簡略実装。
910pub fn dom_set_range_text(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
911    if let Some(idx) = this_dom_idx(&this) {
912        let replacement = arg(a, 0).to_js_string();
913        let chars: alloc::vec::Vec<char> = current_field_value(it, idx).chars().collect();
914        let len = chars.len();
915        let cur_start = it
916            .dom()
917            .borrow()
918            .get_attr(idx, "_selection_start")
919            .and_then(|v| v.parse::<f64>().ok())
920            .unwrap_or(0.0);
921        let cur_end = it
922            .dom()
923            .borrow()
924            .get_attr(idx, "_selection_end")
925            .and_then(|v| v.parse::<f64>().ok())
926            .unwrap_or(0.0);
927        let start = if matches!(arg(a, 1), Value::Undefined) { cur_start } else { arg(a, 1).to_number() };
928        let end = if matches!(arg(a, 2), Value::Undefined) { cur_end } else { arg(a, 2).to_number() };
929        let start = (start.max(0.0) as usize).min(len);
930        let end = (end.max(0.0) as usize).min(len).max(start);
931        let select_mode = if matches!(arg(a, 3), Value::Undefined) { String::from("preserve") } else { arg(a, 3).to_js_string() };
932        let new_value: String =
933            chars[..start].iter().chain(replacement.chars().collect::<alloc::vec::Vec<_>>().iter()).chain(chars[end..].iter()).collect();
934        let new_end = start + replacement.chars().count();
935        let (sel_start, sel_end) = match select_mode.as_str() {
936            "select" => (start, new_end),
937            "start" => (start, start),
938            "end" => (new_end, new_end),
939            _ => (start, new_end), // "preserve" は簡略実装として置換範囲を返す
940        };
941        let mut dom = it.dom().borrow_mut();
942        dom.set_attr(idx, "_live_value", &new_value);
943        dom.set_attr(idx, "_selection_start", &Value::Number(sel_start as f64).to_js_string());
944        dom.set_attr(idx, "_selection_end", &Value::Number(sel_end as f64).to_js_string());
945    }
946    Ok(Value::Undefined)
947}
948/// `node.isSameNode(other)`(丸ごと未対応だった。DOM 標準の参照同一性判定。`===` と
949/// 同義だが、DOM ノードを扱うライブラリで明示的に使われる定番メソッド)。
950pub fn dom_is_same_node(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
951    let self_idx = this_dom_idx(&this);
952    let other_idx = this_dom_idx(&arg(a, 0));
953    Ok(Value::Bool(self_idx.is_some() && self_idx == other_idx))
954}
955/// `node.isEqualNode(other)`(丸ごと未対応だった。参照ではなく構造的な等価性
956/// — タグ名/属性/子要素が全て一致するか — を見る DOM 標準メソッド)。既存の
957/// `outerHTML` シリアライズを再利用し、文字列として一致するかで近似する
958/// (属性は `BTreeMap` 由来で常に同じ順序にシリアライズされるため、挿入順序に
959/// 依存しない安定した比較になる)。
960fn nodes_equal(dom: &crate::os_lib::web_apis::dom_bridge::DomBridge, a: usize, b: usize) -> bool {
961    let (Some(na), Some(nb)) = (dom.nodes.get(a), dom.nodes.get(b)) else {
962        return false;
963    };
964    let kind_of = |n: &crate::os_lib::web_apis::dom_bridge::DomNode| -> u8 {
965        if n.is_text {
966            if n.attrs.contains_key("_cdata") { 4 } else { 3 }
967        } else {
968            match n.tag.as_str() {
969                "#attr" => 2,
970                "#pi" => 7,
971                "#comment" => 8,
972                "#document" => 9,
973                "#doctype" => 10,
974                "#fragment" | "#document-fragment" => 11,
975                _ => 1,
976            }
977        }
978    };
979    let ka = kind_of(na);
980    if ka != kind_of(nb) {
981        return false;
982    }
983    match ka {
984        1 => {
985            if super::dom_ns::node_namespace(na) != super::dom_ns::node_namespace(nb)
986                || na.attrs.get("_prefix") != nb.attrs.get("_prefix")
987                || super::dom_ns::node_local_name(na) != super::dom_ns::node_local_name(nb)
988            {
989                return false;
990            }
991            let aa = dom.attr_entries(a);
992            let ab = dom.attr_entries(b);
993            if aa.len() != ab.len() {
994                return false;
995            }
996            for (ns_a, qn_a) in &aa {
997                let l_a = if ns_a.is_some() {
998                    qn_a.split_once(':').map(|(_, l)| l).unwrap_or(qn_a.as_str())
999                } else {
1000                    qn_a.as_str()
1001                };
1002                let val_a = dom.get_attr_ns(a, ns_a.as_deref(), l_a);
1003                let matched = ab.iter().any(|(ns_b, qn_b)| {
1004                    let l_b = if ns_b.is_some() {
1005                        qn_b.split_once(':').map(|(_, l)| l).unwrap_or(qn_b.as_str())
1006                    } else {
1007                        qn_b.as_str()
1008                    };
1009                    ns_a == ns_b && l_a == l_b && dom.get_attr_ns(b, ns_b.as_deref(), l_b) == val_a
1010                });
1011                if !matched {
1012                    return false;
1013                }
1014            }
1015        }
1016        10 if na.attrs.get("_name") != nb.attrs.get("_name")
1017            || na.attrs.get("_publicId") != nb.attrs.get("_publicId")
1018            || na.attrs.get("_systemId") != nb.attrs.get("_systemId") =>
1019        {
1020            return false;
1021        }
1022        7 if na.attrs.get("_target") != nb.attrs.get("_target")
1023            || dom.get_text_content(a) != dom.get_text_content(b) =>
1024        {
1025            return false;
1026        }
1027        3 | 4 | 8 if dom.get_text_content(a) != dom.get_text_content(b) => {
1028            return false;
1029        }
1030        2 if na.attrs.get("_ans") != nb.attrs.get("_ans")
1031            || na.attrs.get("_aname") != nb.attrs.get("_aname")
1032            || dom.attr_value(a) != dom.attr_value(b) =>
1033        {
1034            return false;
1035        }
1036        _ => {}
1037    }
1038    if na.children.len() != nb.children.len() {
1039        return false;
1040    }
1041    na.children.iter().zip(nb.children.iter()).all(|(&ca, &cb)| nodes_equal(dom, ca, cb))
1042}
1043
1044pub fn dom_is_equal_node(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1045    let self_idx = this_dom_idx(&this);
1046    let other_idx = this_dom_idx(&arg(a, 0));
1047    match (self_idx, other_idx) {
1048        (Some(ai), Some(bi)) => {
1049            let dom = it.dom().borrow();
1050            Ok(Value::Bool(nodes_equal(&dom, ai, bi)))
1051        }
1052        _ => Ok(Value::Bool(false)),
1053    }
1054}
1055
1056/// element.getBoundingClientRect(): レイアウト後の矩形(DomBridge.rects、ページ座標)から
1057/// DOMRect 風オブジェクト {x,left,y,top,width,height,right,bottom} を返す。未登録なら 0。
1058/// `element.setPointerCapture(pointerId)`(Pointer Events。丸ごと未対応
1059/// だった。ドラッグ操作で `el.setPointerCapture(e.pointerId)` する定番
1060/// パターン)。
1061pub fn dom_set_pointer_capture(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1062    if let Some(idx) = this_dom_idx(&this) {
1063        it.dom().borrow_mut().set_pointer_capture(idx, arg(a, 0).to_number() as i32);
1064    }
1065    Ok(Value::Undefined)
1066}
1067/// `element.releasePointerCapture(pointerId)`。
1068pub fn dom_release_pointer_capture(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1069    if let Some(idx) = this_dom_idx(&this) {
1070        it.dom()
1071            .borrow_mut()
1072            .release_pointer_capture(idx, arg(a, 0).to_number() as i32);
1073    }
1074    Ok(Value::Undefined)
1075}
1076/// `element.hasPointerCapture(pointerId)`。
1077pub fn dom_has_pointer_capture(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1078    let has = this_dom_idx(&this)
1079        .map(|idx| it.dom().borrow().has_pointer_capture(idx, arg(a, 0).to_number() as i32))
1080        .unwrap_or(false);
1081    Ok(Value::Bool(has))
1082}
1083
1084/// `(x,y,w,h)` から `DOMRect` 相当のプレーンオブジェクトを組み立てる。
1085/// `getBoundingClientRect`/`getClientRects` で共有する。
1086/// `new DOMRect(x, y, width, height)`(丸ごと未対応だった。手動で矩形を
1087/// 構築する定番パターン。2026-07-17 発見)。`getBoundingClientRect()`が
1088/// 返す`make_dom_rect`と同じプロパティ形状(`x`/`y`/`left`/`top`/
1089/// `width`/`height`/`right`/`bottom`)だが、引数は整数丸め無しの浮動小数
1090/// 点のまま保持する(手動構築ではサブピクセル値も仕様上有効なため)。
1091/// `DOMRectReadOnly`も同じ形状のため区別せず同一コンストラクタで代用する
1092/// 簡略実装(`fromRect`静的メソッド・書き込み可能プロパティの違いは
1093/// 対象外)。
1094pub(crate) fn dom_rect_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1095    let x = arg(a, 0).to_number();
1096    let y = arg(a, 1).to_number();
1097    let w = arg(a, 2).to_number();
1098    let h = arg(a, 3).to_number();
1099    let x = if x.is_nan() { 0.0 } else { x };
1100    let y = if y.is_nan() { 0.0 } else { y };
1101    let w = if w.is_nan() { 0.0 } else { w };
1102    let h = if h.is_nan() { 0.0 } else { h };
1103    let o = Obj::plain();
1104    {
1105        let mut b = o.borrow_mut();
1106        b.props.insert("x".into(), Value::Number(x));
1107        b.props.insert("left".into(), Value::Number(x));
1108        b.props.insert("y".into(), Value::Number(y));
1109        b.props.insert("top".into(), Value::Number(y));
1110        b.props.insert("width".into(), Value::Number(w));
1111        b.props.insert("height".into(), Value::Number(h));
1112        b.props.insert("right".into(), Value::Number(x + w));
1113        b.props.insert("bottom".into(), Value::Number(y + h));
1114        b.props.insert(
1115            "toJSON".into(),
1116            nv("toJSON", |_: &mut Interp, this: Value, _: &[Value]| {
1117                if let Value::Object(o) = &this {
1118                    let clone = Obj::plain();
1119                    for (k, v) in o.borrow().props.iter() {
1120                        if k != "toJSON" {
1121                            clone.borrow_mut().props.insert(k.clone(), v.clone());
1122                        }
1123                    }
1124                    return Ok(Value::Object(clone));
1125                }
1126                Ok(Value::Undefined)
1127            }),
1128        );
1129    }
1130    Ok(Value::Object(o))
1131}
1132fn get_num_prop(it: &mut Interp, val: &Value, name: &str, default: f64) -> f64 {
1133    it.get_property(val, name).map(|v| v.to_number()).unwrap_or(default)
1134}
1135
1136pub fn dom_point_matrix_transform(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1137    let px = get_num_prop(it, &this, "x", 0.0);
1138    let py = get_num_prop(it, &this, "y", 0.0);
1139    let pz = get_num_prop(it, &this, "z", 0.0);
1140    let pw = get_num_prop(it, &this, "w", 1.0);
1141    let m = arg(a, 0);
1142
1143    let def_a = get_num_prop(it, &m, "a", 1.0);
1144    let m11 = get_num_prop(it, &m, "m11", def_a);
1145    let def_b = get_num_prop(it, &m, "b", 0.0);
1146    let m12 = get_num_prop(it, &m, "m12", def_b);
1147    let m13 = get_num_prop(it, &m, "m13", 0.0);
1148    let m14 = get_num_prop(it, &m, "m14", 0.0);
1149
1150    let def_c = get_num_prop(it, &m, "c", 0.0);
1151    let m21 = get_num_prop(it, &m, "m21", def_c);
1152    let def_d = get_num_prop(it, &m, "d", 1.0);
1153    let m22 = get_num_prop(it, &m, "m22", def_d);
1154    let m23 = get_num_prop(it, &m, "m23", 0.0);
1155    let m24 = get_num_prop(it, &m, "m24", 0.0);
1156
1157    let m31 = get_num_prop(it, &m, "m31", 0.0);
1158    let m32 = get_num_prop(it, &m, "m32", 0.0);
1159    let m33 = get_num_prop(it, &m, "m33", 1.0);
1160    let m34 = get_num_prop(it, &m, "m34", 0.0);
1161
1162    let def_e = get_num_prop(it, &m, "e", 0.0);
1163    let m41 = get_num_prop(it, &m, "m41", def_e);
1164    let def_f = get_num_prop(it, &m, "f", 0.0);
1165    let m42 = get_num_prop(it, &m, "m42", def_f);
1166    let m43 = get_num_prop(it, &m, "m43", 0.0);
1167    let m44 = get_num_prop(it, &m, "m44", 1.0);
1168
1169    let nx = m11 * px + m21 * py + m31 * pz + m41 * pw;
1170    let ny = m12 * px + m22 * py + m32 * pz + m42 * pw;
1171    let nz = m13 * px + m23 * py + m33 * pz + m43 * pw;
1172    let nw = m14 * px + m24 * py + m34 * pz + m44 * pw;
1173    dom_point_ctor(it, Value::Undefined, &[Value::Number(nx), Value::Number(ny), Value::Number(nz), Value::Number(nw)])
1174}
1175
1176/// `new DOMPoint(x, y, z, w)`(幾何形体プリミティブ。2026-07-17 発見、2026-07-21 拡張)。
1177/// 仕様どおり `z`/`w` 省略時の既定値はそれぞれ `0`/`1`。`DOMPointReadOnly` も同形状で代用。
1178/// `matrixTransform(matrix)` で `DOMMatrix` による座標変換に対応。
1179pub(crate) fn dom_point_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1180    let x = arg(a, 0).to_number();
1181    let y = arg(a, 1).to_number();
1182    let z = arg(a, 2).to_number();
1183    let w = arg(a, 3).to_number();
1184    let x = if x.is_nan() { 0.0 } else { x };
1185    let y = if y.is_nan() { 0.0 } else { y };
1186    let z = if z.is_nan() { 0.0 } else { z };
1187    let w = if matches!(arg(a, 3), Value::Undefined) || w.is_nan() { 1.0 } else { w };
1188    let o = Obj::plain();
1189    {
1190        let mut b = o.borrow_mut();
1191        b.props.insert("x".into(), Value::Number(x));
1192        b.props.insert("y".into(), Value::Number(y));
1193        b.props.insert("z".into(), Value::Number(z));
1194        b.props.insert("w".into(), Value::Number(w));
1195        b.props.insert(
1196            "matrixTransform".into(),
1197            nv("matrixTransform", dom_point_matrix_transform),
1198        );
1199        b.props.insert(
1200            "toJSON".into(),
1201            nv("toJSON", |_: &mut Interp, this: Value, _: &[Value]| {
1202                if let Value::Object(o) = &this {
1203                    let clone = Obj::plain();
1204                    for (k, v) in o.borrow().props.iter() {
1205                        if k != "toJSON" && k != "matrixTransform" {
1206                            clone.borrow_mut().props.insert(k.clone(), v.clone());
1207                        }
1208                    }
1209                    return Ok(Value::Object(clone));
1210                }
1211                Ok(Value::Undefined)
1212            }),
1213        );
1214    }
1215    Ok(Value::Object(o))
1216}
1217
1218pub(crate) fn dom_rect_from_rect(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1219    let r = arg(a, 0);
1220    let x = get_num_prop(it, &r, "x", 0.0);
1221    let y = get_num_prop(it, &r, "y", 0.0);
1222    let w = get_num_prop(it, &r, "width", 0.0);
1223    let h = get_num_prop(it, &r, "height", 0.0);
1224    dom_rect_ctor(it, Value::Undefined, &[Value::Number(x), Value::Number(y), Value::Number(w), Value::Number(h)])
1225}
1226
1227pub(crate) fn dom_point_from_point(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1228    let p = arg(a, 0);
1229    let x = get_num_prop(it, &p, "x", 0.0);
1230    let y = get_num_prop(it, &p, "y", 0.0);
1231    let z = get_num_prop(it, &p, "z", 0.0);
1232    let w = get_num_prop(it, &p, "w", 1.0);
1233    dom_point_ctor(it, Value::Undefined, &[Value::Number(x), Value::Number(y), Value::Number(z), Value::Number(w)])
1234}
1235
1236pub fn dom_matrix_to_string(it: &mut Interp, this: Value, _: &[Value]) -> Result<Value, Value> {
1237    let is_2d = it.get_property(&this, "is2D").map(|v| v.truthy()).unwrap_or(true);
1238    let m11 = get_num_prop(it, &this, "m11", 1.0);
1239    let m12 = get_num_prop(it, &this, "m12", 0.0);
1240    let m13 = get_num_prop(it, &this, "m13", 0.0);
1241    let m14 = get_num_prop(it, &this, "m14", 0.0);
1242    let m21 = get_num_prop(it, &this, "m21", 0.0);
1243    let m22 = get_num_prop(it, &this, "m22", 1.0);
1244    let m23 = get_num_prop(it, &this, "m23", 0.0);
1245    let m24 = get_num_prop(it, &this, "m24", 0.0);
1246    let m31 = get_num_prop(it, &this, "m31", 0.0);
1247    let m32 = get_num_prop(it, &this, "m32", 0.0);
1248    let m33 = get_num_prop(it, &this, "m33", 1.0);
1249    let m34 = get_num_prop(it, &this, "m34", 0.0);
1250    let m41 = get_num_prop(it, &this, "m41", 0.0);
1251    let m42 = get_num_prop(it, &this, "m42", 0.0);
1252    let m43 = get_num_prop(it, &this, "m43", 0.0);
1253    let m44 = get_num_prop(it, &this, "m44", 1.0);
1254    if is_2d {
1255        Ok(Value::str(alloc::format!("matrix({}, {}, {}, {}, {}, {})", m11, m12, m21, m22, m41, m42)))
1256    } else {
1257        Ok(Value::str(alloc::format!(
1258            "matrix3d({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})",
1259            m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44
1260        )))
1261    }
1262}
1263
1264pub fn dom_matrix_multiply(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1265    let m11 = get_num_prop(it, &this, "m11", 1.0);
1266    let m12 = get_num_prop(it, &this, "m12", 0.0);
1267    let m21 = get_num_prop(it, &this, "m21", 0.0);
1268    let m22 = get_num_prop(it, &this, "m22", 1.0);
1269    let m41 = get_num_prop(it, &this, "m41", 0.0);
1270    let m42 = get_num_prop(it, &this, "m42", 0.0);
1271
1272    let other = arg(a, 0);
1273    let om11 = get_num_prop(it, &other, "m11", 1.0);
1274    let om12 = get_num_prop(it, &other, "m12", 0.0);
1275    let om21 = get_num_prop(it, &other, "m21", 0.0);
1276    let om22 = get_num_prop(it, &other, "m22", 1.0);
1277    let om41 = get_num_prop(it, &other, "m41", 0.0);
1278    let om42 = get_num_prop(it, &other, "m42", 0.0);
1279
1280    let res_a = m11 * om11 + m21 * om12;
1281    let res_b = m12 * om11 + m22 * om12;
1282    let res_c = m11 * om21 + m21 * om22;
1283    let res_d = m12 * om21 + m22 * om22;
1284    let res_e = m11 * om41 + m21 * om42 + m41;
1285    let res_f = m12 * om41 + m22 * om42 + m42;
1286
1287    let arr = Value::Object(Obj::array(alloc::vec![
1288        Value::Number(res_a), Value::Number(res_b),
1289        Value::Number(res_c), Value::Number(res_d),
1290        Value::Number(res_e), Value::Number(res_f)
1291    ]));
1292    dom_matrix_ctor(it, Value::Undefined, &[arr])
1293}
1294
1295pub fn dom_matrix_translate(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1296    let m11 = get_num_prop(it, &this, "m11", 1.0);
1297    let m12 = get_num_prop(it, &this, "m12", 0.0);
1298    let m21 = get_num_prop(it, &this, "m21", 0.0);
1299    let m22 = get_num_prop(it, &this, "m22", 1.0);
1300    let m41 = get_num_prop(it, &this, "m41", 0.0);
1301    let m42 = get_num_prop(it, &this, "m42", 0.0);
1302
1303    let tx = arg(a, 0).to_number();
1304    let ty = arg(a, 1).to_number();
1305    let tx = if tx.is_nan() { 0.0 } else { tx };
1306    let ty = if ty.is_nan() { 0.0 } else { ty };
1307
1308    let res_e = m11 * tx + m21 * ty + m41;
1309    let res_f = m12 * tx + m22 * ty + m42;
1310
1311    let arr = Value::Object(Obj::array(alloc::vec![
1312        Value::Number(m11), Value::Number(m12),
1313        Value::Number(m21), Value::Number(m22),
1314        Value::Number(res_e), Value::Number(res_f)
1315    ]));
1316    dom_matrix_ctor(it, Value::Undefined, &[arr])
1317}
1318
1319pub fn dom_matrix_scale(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1320    let m11 = get_num_prop(it, &this, "m11", 1.0);
1321    let m12 = get_num_prop(it, &this, "m12", 0.0);
1322    let m21 = get_num_prop(it, &this, "m21", 0.0);
1323    let m22 = get_num_prop(it, &this, "m22", 1.0);
1324    let m41 = get_num_prop(it, &this, "m41", 0.0);
1325    let m42 = get_num_prop(it, &this, "m42", 0.0);
1326
1327    let sx = arg(a, 0).to_number();
1328    let sy = arg(a, 1).to_number();
1329    let sx = if sx.is_nan() { 1.0 } else { sx };
1330    let sy = if matches!(arg(a, 1), Value::Undefined) || sy.is_nan() { sx } else { sy };
1331
1332    let arr = Value::Object(Obj::array(alloc::vec![
1333        Value::Number(m11 * sx), Value::Number(m12 * sx),
1334        Value::Number(m21 * sy), Value::Number(m22 * sy),
1335        Value::Number(m41), Value::Number(m42)
1336    ]));
1337    dom_matrix_ctor(it, Value::Undefined, &[arr])
1338}
1339
1340pub fn dom_matrix_rotate(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1341    let m11 = get_num_prop(it, &this, "m11", 1.0);
1342    let m12 = get_num_prop(it, &this, "m12", 0.0);
1343    let m21 = get_num_prop(it, &this, "m21", 0.0);
1344    let m22 = get_num_prop(it, &this, "m22", 1.0);
1345    let m41 = get_num_prop(it, &this, "m41", 0.0);
1346    let m42 = get_num_prop(it, &this, "m42", 0.0);
1347
1348    let angle_deg = arg(a, 0).to_number();
1349    let angle_deg = if angle_deg.is_nan() { 0.0 } else { angle_deg };
1350    let rad = angle_deg * core::f64::consts::PI / 180.0;
1351    let cos_a = libm::cos(rad);
1352    let sin_a = libm::sin(rad);
1353
1354    let res_a = m11 * cos_a + m21 * sin_a;
1355    let res_b = m12 * cos_a + m22 * sin_a;
1356    let res_c = m11 * (-sin_a) + m21 * cos_a;
1357    let res_d = m12 * (-sin_a) + m22 * cos_a;
1358
1359    let arr = Value::Object(Obj::array(alloc::vec![
1360        Value::Number(res_a), Value::Number(res_b),
1361        Value::Number(res_c), Value::Number(res_d),
1362        Value::Number(m41), Value::Number(m42)
1363    ]));
1364    dom_matrix_ctor(it, Value::Undefined, &[arr])
1365}
1366
1367pub fn dom_matrix_invert(it: &mut Interp, this: Value, _: &[Value]) -> Result<Value, Value> {
1368    let a = get_num_prop(it, &this, "m11", 1.0);
1369    let b = get_num_prop(it, &this, "m12", 0.0);
1370    let c = get_num_prop(it, &this, "m21", 0.0);
1371    let d = get_num_prop(it, &this, "m22", 1.0);
1372    let e = get_num_prop(it, &this, "m41", 0.0);
1373    let f = get_num_prop(it, &this, "m42", 0.0);
1374
1375    let det = a * d - b * c;
1376    if det == 0.0 || det.is_nan() {
1377        let arr = Value::Object(Obj::array(alloc::vec![
1378            Value::Number(f64::NAN), Value::Number(f64::NAN),
1379            Value::Number(f64::NAN), Value::Number(f64::NAN),
1380            Value::Number(f64::NAN), Value::Number(f64::NAN)
1381        ]));
1382        return dom_matrix_ctor(it, Value::Undefined, &[arr]);
1383    }
1384    let inv_a = d / det;
1385    let inv_b = -b / det;
1386    let inv_c = -c / det;
1387    let inv_d = a / det;
1388    let inv_e = (c * f - d * e) / det;
1389    let inv_f = (b * e - a * f) / det;
1390
1391    let arr = Value::Object(Obj::array(alloc::vec![
1392        Value::Number(inv_a), Value::Number(inv_b),
1393        Value::Number(inv_c), Value::Number(inv_d),
1394        Value::Number(inv_e), Value::Number(inv_f)
1395    ]));
1396    dom_matrix_ctor(it, Value::Undefined, &[arr])
1397}
1398
1399fn update_matrix_props(target: &Value, new_m: Value) {
1400    if let (Value::Object(to), Value::Object(from)) = (target, &new_m) {
1401        let from_props = from.borrow().props.clone();
1402        let mut b = to.borrow_mut();
1403        for (k, v) in from_props {
1404            if k != "toJSON" && k != "toString" && k != "multiply" && k != "translate" && k != "scale" && k != "rotate" && k != "invert"
1405                && k != "multiplySelf" && k != "translateSelf" && k != "scaleSelf" && k != "rotateSelf" && k != "invertSelf" {
1406                b.props.insert(k, v);
1407            }
1408        }
1409    }
1410}
1411
1412pub fn dom_matrix_translate_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1413    let new_m = dom_matrix_translate(it, this.clone(), a)?;
1414    update_matrix_props(&this, new_m);
1415    Ok(this)
1416}
1417
1418pub fn dom_matrix_scale_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1419    let new_m = dom_matrix_scale(it, this.clone(), a)?;
1420    update_matrix_props(&this, new_m);
1421    Ok(this)
1422}
1423
1424pub fn dom_matrix_rotate_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1425    let new_m = dom_matrix_rotate(it, this.clone(), a)?;
1426    update_matrix_props(&this, new_m);
1427    Ok(this)
1428}
1429
1430pub fn dom_matrix_multiply_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1431    let new_m = dom_matrix_multiply(it, this.clone(), a)?;
1432    update_matrix_props(&this, new_m);
1433    Ok(this)
1434}
1435
1436pub fn dom_matrix_invert_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1437    let new_m = dom_matrix_invert(it, this.clone(), a)?;
1438    update_matrix_props(&this, new_m);
1439    Ok(this)
1440}
1441
1442pub fn dom_matrix_skew_x(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1443    let deg = arg(a, 0).to_number();
1444    let rad = deg * core::f64::consts::PI / 180.0;
1445    let tan_val = libm::tan(rad);
1446    let skew_m = dom_matrix_ctor(
1447        it,
1448        Value::Undefined,
1449        &[
1450            Value::Number(1.0),
1451            Value::Number(0.0),
1452            Value::Number(tan_val),
1453            Value::Number(1.0),
1454            Value::Number(0.0),
1455            Value::Number(0.0),
1456        ],
1457    )?;
1458    dom_matrix_multiply(it, this, &[skew_m])
1459}
1460
1461pub fn dom_matrix_skew_y(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1462    let deg = arg(a, 0).to_number();
1463    let rad = deg * core::f64::consts::PI / 180.0;
1464    let tan_val = libm::tan(rad);
1465    let skew_m = dom_matrix_ctor(
1466        it,
1467        Value::Undefined,
1468        &[
1469            Value::Number(1.0),
1470            Value::Number(tan_val),
1471            Value::Number(0.0),
1472            Value::Number(1.0),
1473            Value::Number(0.0),
1474            Value::Number(0.0),
1475        ],
1476    )?;
1477    dom_matrix_multiply(it, this, &[skew_m])
1478}
1479
1480pub fn dom_matrix_skew_x_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1481    let new_m = dom_matrix_skew_x(it, this.clone(), a)?;
1482    update_matrix_props(&this, new_m);
1483    Ok(this)
1484}
1485
1486pub fn dom_matrix_skew_y_self(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1487    let new_m = dom_matrix_skew_y(it, this.clone(), a)?;
1488    update_matrix_props(&this, new_m);
1489    Ok(this)
1490}
1491
1492pub fn dom_matrix_transform_point(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1493    let pt = arg(a, 0);
1494    dom_point_matrix_transform(it, pt, &[this])
1495}
1496
1497/// `new DOMMatrix([init])` / `DOMMatrixReadOnly` (Geometry Interfaces Module Level 1)
1498/// 2D / 3D 変換行列コンストラクタ。
1499pub(crate) fn dom_matrix_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1500    let mut m11 = 1.0; let mut m12 = 0.0; let mut m13 = 0.0; let mut m14 = 0.0;
1501    let mut m21 = 0.0; let mut m22 = 1.0; let mut m23 = 0.0; let mut m24 = 0.0;
1502    let mut m31 = 0.0; let mut m32 = 0.0; let mut m33 = 1.0; let mut m34 = 0.0;
1503    let mut m41 = 0.0; let mut m42 = 0.0; let mut m43 = 0.0; let mut m44 = 1.0;
1504
1505    let init = arg(a, 0);
1506    if let Value::Object(o) = &init {
1507        // `DOMMatrixInit`は仕様上「数値6/16個のシーケンス(配列/TypedArray、この
1508        // エンジンではどちらも`ObjKind::Array`)」か「`{a,b,c,d,e,f,...}`形式の
1509        // 平オブジェクト」のいずれか。以前は非配列オブジェクトも`it.iterate_values`
1510        // へ通していたが、この関数はプレーンオブジェクトに対しても(`Symbol.
1511        // iterator`を持たないにも関わらず)自身の列挙可能プロパティ値をそのまま
1512        // 返す簡略実装のため、`{a:2,d:3,e:5,f:10}`(4値)のような非配列dictでも
1513        // 空でないVecが返ってしまい、`arr.len()>=16`/`>=6`のどちらにも該当せず
1514        // 何も設定されないまま、本来読むべき`.a`/`.b`/`.c`/`.d`/`.e`/`.f`
1515        // プロパティ読み取りのelseブランチへ一切到達できないバグだった
1516        // (`DOMMatrix.fromMatrix({...})`が常に単位行列のまま返る)。
1517        // `ObjKind::Array`(TypedArrayもこの表現を流用)のときのみ数値シーケンス
1518        // として扱い、それ以外は無条件でプロパティ読み取り側へ回す。
1519        // 【2026-07-23続報】この修正自体だけでは`m2.a`/`m2.e`が期待値にならない
1520        // ことが判明しており、原因はこの関数の別の箇所(`.a`/`.e`プロパティの
1521        // 最終露出ロジック)に残っている可能性が高い。ロジックとしては正しい
1522        // 改善のため残すが、根本解決は未完了として記録する。
1523        let vals_opt = match &o.borrow().kind {
1524            crate::os_lib::ecma::value::ObjKind::Array(arr) => Some(arr.clone()),
1525            crate::os_lib::ecma::value::ObjKind::Bytes(st) => Some(st.values()),
1526            _ => None,
1527        };
1528        if let Some(arr) = vals_opt {
1529            if arr.len() >= 16 {
1530                m11 = arr[0].to_number(); m12 = arr[1].to_number(); m13 = arr[2].to_number(); m14 = arr[3].to_number();
1531                m21 = arr[4].to_number(); m22 = arr[5].to_number(); m23 = arr[6].to_number(); m24 = arr[7].to_number();
1532                m31 = arr[8].to_number(); m32 = arr[9].to_number(); m33 = arr[10].to_number(); m34 = arr[11].to_number();
1533                m41 = arr[12].to_number(); m42 = arr[13].to_number(); m43 = arr[14].to_number(); m44 = arr[15].to_number();
1534            } else if arr.len() >= 6 {
1535                m11 = arr[0].to_number(); m12 = arr[1].to_number();
1536                m21 = arr[2].to_number(); m22 = arr[3].to_number();
1537                m41 = arr[4].to_number(); m42 = arr[5].to_number();
1538            }
1539        } else {
1540            if let Ok(v) = it.get_property(&init, "a") { if !matches!(v, Value::Undefined) { m11 = v.to_number(); } }
1541            if let Ok(v) = it.get_property(&init, "b") { if !matches!(v, Value::Undefined) { m12 = v.to_number(); } }
1542            if let Ok(v) = it.get_property(&init, "c") { if !matches!(v, Value::Undefined) { m21 = v.to_number(); } }
1543            if let Ok(v) = it.get_property(&init, "d") { if !matches!(v, Value::Undefined) { m22 = v.to_number(); } }
1544            if let Ok(v) = it.get_property(&init, "e") { if !matches!(v, Value::Undefined) { m41 = v.to_number(); } }
1545            if let Ok(v) = it.get_property(&init, "f") { if !matches!(v, Value::Undefined) { m42 = v.to_number(); } }
1546
1547            if let Ok(v) = it.get_property(&init, "m11") { if !matches!(v, Value::Undefined) { m11 = v.to_number(); } }
1548            if let Ok(v) = it.get_property(&init, "m12") { if !matches!(v, Value::Undefined) { m12 = v.to_number(); } }
1549            if let Ok(v) = it.get_property(&init, "m13") { if !matches!(v, Value::Undefined) { m13 = v.to_number(); } }
1550            if let Ok(v) = it.get_property(&init, "m14") { if !matches!(v, Value::Undefined) { m14 = v.to_number(); } }
1551            if let Ok(v) = it.get_property(&init, "m21") { if !matches!(v, Value::Undefined) { m21 = v.to_number(); } }
1552            if let Ok(v) = it.get_property(&init, "m22") { if !matches!(v, Value::Undefined) { m22 = v.to_number(); } }
1553            if let Ok(v) = it.get_property(&init, "m23") { if !matches!(v, Value::Undefined) { m23 = v.to_number(); } }
1554            if let Ok(v) = it.get_property(&init, "m24") { if !matches!(v, Value::Undefined) { m24 = v.to_number(); } }
1555            if let Ok(v) = it.get_property(&init, "m31") { if !matches!(v, Value::Undefined) { m31 = v.to_number(); } }
1556            if let Ok(v) = it.get_property(&init, "m32") { if !matches!(v, Value::Undefined) { m32 = v.to_number(); } }
1557            if let Ok(v) = it.get_property(&init, "m33") { if !matches!(v, Value::Undefined) { m33 = v.to_number(); } }
1558            if let Ok(v) = it.get_property(&init, "m34") { if !matches!(v, Value::Undefined) { m34 = v.to_number(); } }
1559            if let Ok(v) = it.get_property(&init, "m41") { if !matches!(v, Value::Undefined) { m41 = v.to_number(); } }
1560            if let Ok(v) = it.get_property(&init, "m42") { if !matches!(v, Value::Undefined) { m42 = v.to_number(); } }
1561            if let Ok(v) = it.get_property(&init, "m43") { if !matches!(v, Value::Undefined) { m43 = v.to_number(); } }
1562            if let Ok(v) = it.get_property(&init, "m44") { if !matches!(v, Value::Undefined) { m44 = v.to_number(); } }
1563        }
1564    }
1565
1566    let is_2d = m13 == 0.0 && m14 == 0.0 && m23 == 0.0 && m24 == 0.0 && m31 == 0.0 && m32 == 0.0 && m33 == 1.0 && m34 == 0.0 && m43 == 0.0;
1567    let is_identity = m11 == 1.0 && m12 == 0.0 && m13 == 0.0 && m14 == 0.0
1568        && m21 == 0.0 && m22 == 1.0 && m23 == 0.0 && m24 == 0.0
1569        && m31 == 0.0 && m32 == 0.0 && m33 == 1.0 && m34 == 0.0
1570        && m41 == 0.0 && m42 == 0.0 && m43 == 0.0 && m44 == 1.0;
1571
1572    let o = Obj::plain();
1573    {
1574        let mut b = o.borrow_mut();
1575        b.props.insert("a".into(), Value::Number(m11));
1576        b.props.insert("b".into(), Value::Number(m12));
1577        b.props.insert("c".into(), Value::Number(m21));
1578        b.props.insert("d".into(), Value::Number(m22));
1579        b.props.insert("e".into(), Value::Number(m41));
1580        b.props.insert("f".into(), Value::Number(m42));
1581
1582        b.props.insert("m11".into(), Value::Number(m11));
1583        b.props.insert("m12".into(), Value::Number(m12));
1584        b.props.insert("m13".into(), Value::Number(m13));
1585        b.props.insert("m14".into(), Value::Number(m14));
1586        b.props.insert("m21".into(), Value::Number(m21));
1587        b.props.insert("m22".into(), Value::Number(m22));
1588        b.props.insert("m23".into(), Value::Number(m23));
1589        b.props.insert("m24".into(), Value::Number(m24));
1590        b.props.insert("m31".into(), Value::Number(m31));
1591        b.props.insert("m32".into(), Value::Number(m32));
1592        b.props.insert("m33".into(), Value::Number(m33));
1593        b.props.insert("m34".into(), Value::Number(m34));
1594        b.props.insert("m41".into(), Value::Number(m41));
1595        b.props.insert("m42".into(), Value::Number(m42));
1596        b.props.insert("m43".into(), Value::Number(m43));
1597        b.props.insert("m44".into(), Value::Number(m44));
1598
1599        b.props.insert("is2D".into(), Value::Bool(is_2d));
1600        b.props.insert("isIdentity".into(), Value::Bool(is_identity));
1601
1602        b.props.insert("toString".into(), nv("toString", dom_matrix_to_string));
1603        b.props.insert("multiply".into(), nv("multiply", dom_matrix_multiply));
1604        b.props.insert("translate".into(), nv("translate", dom_matrix_translate));
1605        b.props.insert("scale".into(), nv("scale", dom_matrix_scale));
1606        b.props.insert("rotate".into(), nv("rotate", dom_matrix_rotate));
1607        b.props.insert("skewX".into(), nv("skewX", dom_matrix_skew_x));
1608        b.props.insert("skewY".into(), nv("skewY", dom_matrix_skew_y));
1609        b.props.insert("invert".into(), nv("invert", dom_matrix_invert));
1610
1611        b.props.insert("multiplySelf".into(), nv("multiplySelf", dom_matrix_multiply_self));
1612        b.props.insert("translateSelf".into(), nv("translateSelf", dom_matrix_translate_self));
1613        b.props.insert("scaleSelf".into(), nv("scaleSelf", dom_matrix_scale_self));
1614        b.props.insert("rotateSelf".into(), nv("rotateSelf", dom_matrix_rotate_self));
1615        b.props.insert("skewXSelf".into(), nv("skewXSelf", dom_matrix_skew_x_self));
1616        b.props.insert("skewYSelf".into(), nv("skewYSelf", dom_matrix_skew_y_self));
1617        b.props.insert("invertSelf".into(), nv("invertSelf", dom_matrix_invert_self));
1618
1619        b.props.insert("transformPoint".into(), nv("transformPoint", dom_matrix_transform_point));
1620        b.props.insert(
1621            "toJSON".into(),
1622            nv("toJSON", |_: &mut Interp, this: Value, _: &[Value]| {
1623                if let Value::Object(o) = &this {
1624                    let clone = Obj::plain();
1625                    for (k, v) in o.borrow().props.iter() {
1626                        if k != "toJSON" && k != "toString" && k != "multiply" && k != "translate" && k != "scale" && k != "rotate" && k != "invert"
1627                            && k != "multiplySelf" && k != "translateSelf" && k != "scaleSelf" && k != "rotateSelf" && k != "invertSelf"
1628                            && k != "skewX" && k != "skewY" && k != "skewXSelf" && k != "skewYSelf" && k != "transformPoint" {
1629                            clone.borrow_mut().props.insert(k.clone(), v.clone());
1630                        }
1631                    }
1632                    return Ok(Value::Object(clone));
1633                }
1634                Ok(Value::Undefined)
1635            }),
1636        );
1637    }
1638    Ok(Value::Object(o))
1639}
1640
1641pub fn dom_quad_get_bounds(it: &mut Interp, this: Value, _: &[Value]) -> Result<Value, Value> {
1642    let p1 = it.get_property(&this, "p1").unwrap_or(Value::Undefined);
1643    let p2 = it.get_property(&this, "p2").unwrap_or(Value::Undefined);
1644    let p3 = it.get_property(&this, "p3").unwrap_or(Value::Undefined);
1645    let p4 = it.get_property(&this, "p4").unwrap_or(Value::Undefined);
1646
1647    let x1 = get_num_prop(it, &p1, "x", 0.0);
1648    let y1 = get_num_prop(it, &p1, "y", 0.0);
1649    let x2 = get_num_prop(it, &p2, "x", 0.0);
1650    let y2 = get_num_prop(it, &p2, "y", 0.0);
1651    let x3 = get_num_prop(it, &p3, "x", 0.0);
1652    let y3 = get_num_prop(it, &p3, "y", 0.0);
1653    let x4 = get_num_prop(it, &p4, "x", 0.0);
1654    let y4 = get_num_prop(it, &p4, "y", 0.0);
1655
1656    let min_x = x1.min(x2).min(x3).min(x4);
1657    let max_x = x1.max(x2).max(x3).max(x4);
1658    let min_y = y1.min(y2).min(y3).min(y4);
1659    let max_y = y1.max(y2).max(y3).max(y4);
1660
1661    let w = (max_x - min_x).max(0.0) as i32;
1662    let h = (max_y - min_y).max(0.0) as i32;
1663    Ok(Value::Object(make_dom_rect(min_x as i32, min_y as i32, w, h)))
1664}
1665
1666
1667
1668/// `new DOMQuad(p1, p2, p3, p4)` (Geometry Interfaces Module Level 1)
1669pub(crate) fn dom_quad_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1670    let p1 = if matches!(arg(a, 0), Value::Undefined) { dom_point_ctor(it, Value::Undefined, &[])? } else { arg(a, 0) };
1671    let p2 = if matches!(arg(a, 1), Value::Undefined) { dom_point_ctor(it, Value::Undefined, &[])? } else { arg(a, 1) };
1672    let p3 = if matches!(arg(a, 2), Value::Undefined) { dom_point_ctor(it, Value::Undefined, &[])? } else { arg(a, 2) };
1673    let p4 = if matches!(arg(a, 3), Value::Undefined) { dom_point_ctor(it, Value::Undefined, &[])? } else { arg(a, 3) };
1674
1675    let o = Obj::plain();
1676    {
1677        let mut b = o.borrow_mut();
1678        b.props.insert("p1".into(), p1.clone());
1679        b.props.insert("p2".into(), p2.clone());
1680        b.props.insert("p3".into(), p3.clone());
1681        b.props.insert("p4".into(), p4.clone());
1682
1683        b.props.insert("getBounds".into(), nv("getBounds", dom_quad_get_bounds));
1684        b.props.insert(
1685            "toJSON".into(),
1686            nv("toJSON", |_: &mut Interp, this: Value, _: &[Value]| {
1687                if let Value::Object(o) = &this {
1688                    let clone = Obj::plain();
1689                    for (k, v) in o.borrow().props.iter() {
1690                        if k != "toJSON" && k != "getBounds" {
1691                            clone.borrow_mut().props.insert(k.clone(), v.clone());
1692                        }
1693                    }
1694                    return Ok(Value::Object(clone));
1695                }
1696                Ok(Value::Undefined)
1697            }),
1698        );
1699    }
1700    Ok(Value::Object(o))
1701}
1702pub(crate) fn make_dom_rect(x: i32, y: i32, w: i32, h: i32) -> ObjRef {
1703    let o = Obj::plain();
1704    {
1705        let mut b = o.borrow_mut();
1706        b.props.insert("x".into(), Value::Number(x as f64));
1707        b.props.insert("left".into(), Value::Number(x as f64));
1708        b.props.insert("y".into(), Value::Number(y as f64));
1709        b.props.insert("top".into(), Value::Number(y as f64));
1710        b.props.insert("width".into(), Value::Number(w as f64));
1711        b.props.insert("height".into(), Value::Number(h as f64));
1712        b.props
1713            .insert("right".into(), Value::Number((x + w) as f64));
1714        b.props
1715            .insert("bottom".into(), Value::Number((y + h) as f64));
1716    }
1717    o
1718}
1719
1720pub fn dom_get_bounding_client_rect(
1721    it: &mut Interp,
1722    this: Value,
1723    _a: &[Value],
1724) -> Result<Value, Value> {
1725    if let Some(idx) = this_dom_idx(&this) {
1726        it.dom().borrow_mut().note_measured(idx);
1727    }
1728    let (x, y, w, h) = this_dom_idx(&this)
1729        .and_then(|idx| it.dom().borrow().get_rect(idx))
1730        .unwrap_or((0, 0, 0, 0));
1731    Ok(Value::Object(make_dom_rect(x, y, w, h)))
1732}
1733
1734/// `element.getClientRects()`(DOM 標準。丸ごと未対応だった。本来は行ボックス
1735/// 単位で複数の `DOMRect` を返すが、この処理系にはテキストの行フラグメント
1736/// モデル自体が無い(`text-overflow`/インライン折返し等と同じ既存の簡略化と
1737/// 同方針)ため、要素1つにつき `getBoundingClientRect()` と同じ矩形を0個
1738/// (未レンダリング)か1個だけ持つ配列として返す)。
1739pub fn dom_get_client_rects(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1740    let rect = this_dom_idx(&this).and_then(|idx| it.dom().borrow().get_rect(idx));
1741    let items = match rect {
1742        Some((x, y, w, h)) => alloc::vec![Value::Object(make_dom_rect(x, y, w, h))],
1743        None => Vec::new(),
1744    };
1745    Ok(Value::Object(Obj::array(items)))
1746}
1747
1748/// getComputedStyle(el): 算出スタイルを読む host プロキシ `computed:idx` を返す。
1749pub(crate) fn get_computed_style(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1750    match this_dom_idx(&arg(a, 0)) {
1751        Some(idx) => Ok(Value::Object(Obj::dom_host(HOST_COMPUTED, idx))),
1752        None => Ok(Value::Object(Obj::dom_host(HOST_COMPUTED, usize::MAX))), // 無効idx
1753    }
1754}
1755
1756/// computedStyle.getPropertyValue(name): kebab-case のプロパティ値を返す。
1757pub fn computed_get_property_value(
1758    it: &mut Interp,
1759    this: Value,
1760    a: &[Value],
1761) -> Result<Value, Value> {
1762    if let Some(idx) = this_host_idx(&this, HOST_COMPUTED) {
1763        let prop = arg(a, 0).to_js_string();
1764        return Ok(Value::str(it.dom().borrow().get_computed(idx, &prop)));
1765    }
1766    Ok(Value::str(""))
1767}
1768
1769pub fn dom_matches(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1770    let sel = it.to_string_value(arg(a, 0))?;
1771    check_selector_syntax(it, &sel)?;
1772    if let Some(idx) = this_dom_idx(&this) {
1773        // `:scope`(丸ごと未対応だった)。`el.matches()` における `:scope` は
1774        // 呼び出し元の要素自身を指す。
1775        return Ok(Value::Bool(it.dom().borrow().node_matches_scoped(idx, &sel, Some(idx))));
1776    }
1777    Ok(Value::Bool(false))
1778}
1779
1780/// closest(selector): 自身を含め祖先方向へ最初にマッチする要素。無ければ null。
1781pub fn dom_closest(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1782    let sel = it.to_string_value(arg(a, 0))?;
1783    check_selector_syntax(it, &sel)?;
1784    if let Some(start) = this_dom_idx(&this) {
1785        let groups = crate::os_lib::web_apis::dom_bridge::parse_selector_groups(sel.trim());
1786        let dom = it.dom().borrow();
1787        let mut cur = Some(start);
1788        let mut guard = 0;
1789        while let Some(c) = cur {
1790            // `:scope`(丸ごと未対応だった)。`el.closest()` における `:scope` は
1791            // 探索中の祖先ではなく、呼び出し元の起点要素(`start`)を指す。
1792            if dom.node_matches_parsed(c, &groups, Some(start)) {
1793                return Ok(dom_handle(it, Some(c)));
1794            }
1795            cur = dom.nodes.get(c).and_then(|n| n.parent);
1796            guard += 1;
1797            if guard > dom.nodes.len() {
1798                break;
1799            }
1800        }
1801    }
1802    Ok(Value::Null)
1803}
1804
1805/// element.querySelector: 子孫に限定して最初にマッチする要素。`:scope`
1806/// (Selectors Level 4。丸ごと未対応だった)は呼び出し元の要素自身を指す。
1807pub fn dom_element_query_selector(
1808    it: &mut Interp,
1809    this: Value,
1810    a: &[Value],
1811) -> Result<Value, Value> {
1812    let sel = it.to_string_value(arg(a, 0))?;
1813    check_selector_syntax(it, &sel)?;
1814    if let Some(idx) = this_dom_idx(&this) {
1815        let dom = it.dom().borrow();
1816        for c in dom.query_all_scoped(&sel, Some(idx)) {
1817            if dom.is_ancestor_of(idx, c) {
1818                return Ok(dom_handle(it, Some(c)));
1819            }
1820        }
1821    }
1822    Ok(Value::Null)
1823}
1824
1825/// element.querySelectorAll: 子孫に限定してマッチする要素配列。`:scope`
1826/// (Selectors Level 4。丸ごと未対応だった)は呼び出し元の要素自身を指す。
1827pub fn dom_element_query_selector_all(
1828    it: &mut Interp,
1829    this: Value,
1830    a: &[Value],
1831) -> Result<Value, Value> {
1832    let sel = it.to_string_value(arg(a, 0))?;
1833    check_selector_syntax(it, &sel)?;
1834    let mut items: Vec<usize> = Vec::new();
1835    if let Some(idx) = this_dom_idx(&this) {
1836        let dom = it.dom().borrow();
1837        for c in dom.query_all_scoped(&sel, Some(idx)) {
1838            if dom.is_ancestor_of(idx, c) {
1839                items.push(c);
1840            }
1841        }
1842    }
1843    Ok(make_static_node_list(it, items))
1844}
1845
1846/// `element.getElementsByClassName(name)`(`document.getElementsByClassName` は
1847/// 対応済みだったが、要素インスタンス版が丸ごと未対応だった。`querySelectorAll` と
1848/// 同じ「自身の子孫のみに絞り込む」ロジックを再利用する)。
1849pub fn dom_element_get_elements_by_class_name(
1850    it: &mut Interp,
1851    this: Value,
1852    a: &[Value],
1853) -> Result<Value, Value> {
1854    if let Some(idx) = this_dom_idx(&this) {
1855        let raw = arg(a, 0).to_js_string();
1856        return Ok(make_live_html_collection(
1857            it,
1858            crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind::ByClassName {
1859                root: Some(idx),
1860                class_names: raw,
1861            },
1862        ));
1863    }
1864    Ok(Value::Object(Obj::array(Vec::new())))
1865}
1866/// `element.getElementsByTagName(tag)`(上記と同じ理由で丸ごと未対応だった)。
1867pub(crate) use super::dom_ns::element_get_elements_by_tag_name as dom_element_get_elements_by_tag_name;
1868/// `element.getElementsByTagNameNS(namespace, localName)`(丸ごと未対応だった)。
1869pub(crate) use super::dom_ns::element_get_elements_by_tag_name_ns as dom_element_get_elements_by_tag_name_ns;
1870
1871pub fn dom_set_attribute(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1872    if let Some(r) = super::dom_pi::pi_attr(it, &this, "setAttribute", a) {
1873        return r;
1874    }
1875    if let Some(idx) = this_dom_idx(&this) {
1876        let raw = arg(a, 0).to_js_string();
1877        // 【2026-11-20】名前は XML の `Name`(違えば `InvalidCharacterError`)。HTML の要素は小文字にする。
1878        super::dom_attr::check_attr_name(it, &raw)?;
1879        let name = super::dom_attr::fix_name(it, idx, &raw);
1880        // 値は ToString(利用者定義の toString を呼ぶ。Trusted Types の TrustedScriptURL 等)。
1881        let val = it.to_string_value(arg(a, 1))?;
1882        {
1883            let mut dom = it.dom().borrow_mut();
1884            if name.starts_with("on") && !dom.on_handlers.is_empty() {
1885                dom.on_handlers.remove(&(idx, name.clone()));
1886            }
1887            let first_match = dom.attr_entries(idx).into_iter().find(|(_, qn)| qn == &name);
1888            match first_match {
1889                Some((Some(u), qn)) => dom.set_attr_ns(idx, Some(&u), &qn, &val),
1890                _ => dom.set_attr(idx, &name, &val),
1891            }
1892        }
1893        super::dom_handlers::attr_changed(it, idx, &name, Some(&val));
1894        if name == "src" && val.starts_with("blob:") {
1895            let is_media = it
1896                .dom()
1897                .borrow()
1898                .nodes
1899                .get(idx)
1900                .map(|n| n.tag == "video" || n.tag == "audio")
1901                .unwrap_or(false);
1902            if is_media {
1903                let ms_val = match it.global.borrow().vars.get("__media_source_urls") {
1904                    Some(Value::Object(r)) => r.borrow().props.get(&val).cloned(),
1905                    _ => None,
1906                };
1907                if let Some(ms) = ms_val {
1908                    super::media_source_open_internal(it, &ms);
1909                }
1910            }
1911        }
1912    }
1913    Ok(Value::Undefined)
1914}
1915
1916/// 制約検証の対象になっている要素 `idx` を検証し、違反なら `invalid` イベント(バブリングなし・取消可)を発火して `false`。
1917/// 対象外(barred・対象候補でない)の要素は常に `true`(イベントなし)。
1918fn static_validate_element(it: &mut Interp, idx: usize) -> bool {
1919    let valid = {
1920        let dom = it.dom().borrow();
1921        dom.barred_from_validation(idx) || dom.validity_flags(idx, "").valid()
1922    };
1923    if !valid {
1924        let extra = [(String::from("bubbles"), Value::Bool(false)), (String::from("cancelable"), Value::Bool(true))];
1925        let _ = it.dispatch_event_in_interp(idx, "invalid", &extra);
1926    }
1927    valid
1928}
1929
1930/// `element.checkValidity()` / `reportValidity()`(§4.10.20.3)。
1931/// 要素: 対象外なら `true`。違反があれば `invalid` を発火して `false`。
1932/// `<form>`: form owner がこのフォームの全コントロールを検証し(違反した各要素に `invalid`)、1 つでも違反なら `false`。
1933/// `<fieldset>`・`<output>`・`<object>`: 対象候補でないので `true`。
1934/// `reportValidity()` は本来さらに UI で報告するが、ここでは判定と `invalid` の発火だけ。
1935pub fn dom_check_validity(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1936    if let Some(idx) = this_dom_idx(&this) {
1937        let tag = it.dom().borrow().nodes.get(idx).map(|n| n.tag.clone()).unwrap_or_default();
1938        if tag == "form" {
1939            let fields = it.dom().borrow().form_associated_controls(idx, &["button", "input", "select", "textarea"]);
1940            let mut all_valid = true;
1941            for node in fields {
1942                if !static_validate_element(it, node) {
1943                    all_valid = false;
1944                }
1945            }
1946            return Ok(Value::Bool(all_valid));
1947        }
1948        return Ok(Value::Bool(static_validate_element(it, idx)));
1949    }
1950    Ok(Value::Bool(true))
1951}
1952
1953/// element.setCustomValidity(msg): カスタム検証メッセージを設定。空文字でクリア。
1954/// 内部的には隠し属性 `_custom_validity` に保存し、validate_field が最優先で参照する。
1955pub fn dom_set_custom_validity(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1956    if let Some(idx) = this_dom_idx(&this) {
1957        let msg = arg(a, 0).to_js_string();
1958        if msg.is_empty() {
1959            it.dom().borrow_mut().remove_attr(idx, "_custom_validity");
1960        } else {
1961            it.dom().borrow_mut().set_attr(idx, "_custom_validity", &msg);
1962        }
1963    }
1964    Ok(Value::Undefined)
1965}
1966
1967/// `this` が `DOMTokenList` 系ホストオブジェクトなら `(要素のノード index, 属性名)` を返す。
1968pub(crate) fn this_token_list(this: &Value) -> Option<(usize, &'static str)> {
1969    if let Value::Object(o) = this {
1970        if let ObjKind::HostRef(h) = &o.borrow().kind {
1971            return crate::os_lib::web_apis::dom_bridge::token_list_attr(h.class)
1972                .map(|attr| (h.id, attr));
1973        }
1974    }
1975    None
1976}
1977
1978/// `DOMTokenList.prototype.forEach`(通常は `Array.prototype.forEach` をプロトタイプ共有)。
1979pub fn dom_classlist_for_each(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1980    if let Some((idx, attr)) = this_token_list(&this) {
1981        let classes = token_list_tokens(it, idx, attr);
1982        let cb = arg(a, 0);
1983        let this_arg = arg(a, 1);
1984        for (i, c) in classes.into_iter().enumerate() {
1985            it.call_value(&cb, this_arg.clone(), &[Value::str(c), Value::Number(i as f64), this.clone()])?;
1986        }
1987    }
1988    Ok(Value::Undefined)
1989}
1990/// `DOMTokenList` のトークン列を取得(2026-11-19、DOM Standard §7.1。WPT `dom/nodes/Element-classlist.html` / `dom/lists`)。
1991/// 指定属性を ASCII 空白で区切った**重複なし**のトークン列(順序は最初の出現順)。
1992pub(crate) fn token_list_tokens_pub(it: &Interp, idx: usize, attr: &str) -> Vec<String> {
1993    token_list_tokens(it, idx, attr)
1994}
1995pub(crate) fn class_tokens_pub(it: &Interp, idx: usize) -> Vec<String> {
1996    token_list_tokens(it, idx, "class")
1997}
1998fn token_list_tokens(it: &Interp, idx: usize, attr: &str) -> Vec<String> {
1999    let mut out: Vec<String> = Vec::new();
2000    let dom = it.dom().borrow();
2001    if attr == "class" {
2002        if let Some(n) = dom.nodes.get(idx) {
2003            for c in &n.classes {
2004                if !out.iter().any(|x| x == c) {
2005                    out.push(c.clone());
2006                }
2007            }
2008        }
2009    } else if let Some(raw) = dom.get_attr(idx, attr) {
2010        for tok in raw.split([' ', '\t', '\n', '\x0c', '\r']) {
2011            if !tok.is_empty() && !out.iter().any(|x| x == tok) {
2012                out.push(String::from(tok));
2013            }
2014        }
2015    }
2016    out
2017}
2018
2019/// トークンの検査。空なら `SyntaxError`、ASCII 空白を含めば `InvalidCharacterError`。
2020fn class_validate(it: &Interp, tok: &str) -> Result<(), Value> {
2021    if tok.is_empty() {
2022        return Err(it.dom_exception("SyntaxError", "The token provided must not be empty."));
2023    }
2024    if tok.chars().any(|c| matches!(c, ' ' | '\t' | '\n' | '\x0c' | '\r')) {
2025        return Err(it.dom_exception("InvalidCharacterError", "The token provided contains HTML space characters, which are not valid in tokens."));
2026    }
2027    Ok(())
2028}
2029
2030/// DOMTokenList の「更新の手順」。属性が無くトークンも空なら何もしない。そうでなければ対象属性を書く
2031/// (変わらなくても属性の設定として MutationObserver へ知らせる)。
2032fn token_list_write(it: &mut Interp, idx: usize, attr: &str, tokens: &[String]) {
2033    let has = it.dom().borrow().has_attr(idx, attr);
2034    if !has && tokens.is_empty() {
2035        return;
2036    }
2037    it.dom().borrow_mut().set_attr(idx, attr, &tokens.join(" "));
2038}
2039
2040pub fn dom_tokenlist_length(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2041    let Some((idx, attr)) = this_token_list(&this) else {
2042        return Err(it.type_error("Illegal invocation"));
2043    };
2044    Ok(Value::Number(token_list_tokens(it, idx, attr).len() as f64))
2045}
2046
2047pub fn dom_tokenlist_value_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2048    let Some((idx, attr)) = this_token_list(&this) else {
2049        return Err(it.type_error("Illegal invocation"));
2050    };
2051    Ok(Value::str(it.dom().borrow().get_attr(idx, attr).unwrap_or_default()))
2052}
2053
2054pub fn dom_tokenlist_value_set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2055    let Some((idx, attr)) = this_token_list(&this) else {
2056        return Err(it.type_error("Illegal invocation"));
2057    };
2058    let s = arg(a, 0).to_js_string();
2059    it.dom().borrow_mut().set_attr(idx, attr, &s);
2060    Ok(Value::Undefined)
2061}
2062
2063pub fn dom_classlist_add(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2064    if let Some((idx, attr)) = this_token_list(&this) {
2065        let toks: Vec<String> = a.iter().map(|v| v.to_js_string()).collect();
2066        for t in &toks {
2067            class_validate(it, t)?;
2068        }
2069        let mut cur = token_list_tokens(it, idx, attr);
2070        for t in toks {
2071            if !cur.contains(&t) {
2072                cur.push(t);
2073            }
2074        }
2075        token_list_write(it, idx, attr, &cur);
2076    }
2077    Ok(Value::Undefined)
2078}
2079
2080pub fn dom_classlist_remove(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2081    if let Some((idx, attr)) = this_token_list(&this) {
2082        let toks: Vec<String> = a.iter().map(|v| v.to_js_string()).collect();
2083        for t in &toks {
2084            class_validate(it, t)?;
2085        }
2086        let mut cur = token_list_tokens(it, idx, attr);
2087        cur.retain(|c| !toks.contains(c));
2088        token_list_write(it, idx, attr, &cur);
2089    }
2090    Ok(Value::Undefined)
2091}
2092
2093/// `DOMTokenList.prototype.supports(token)`(DOM Standard §4.3 / HTML 仕様)。
2094pub fn dom_classlist_supports(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2095    let Some((idx, attr)) = this_token_list(&this) else {
2096        return Err(it.type_error("Illegal invocation"));
2097    };
2098    let tok = arg(a, 0).to_js_string().to_ascii_lowercase();
2099    match attr {
2100        "sandbox" => Ok(Value::Bool(matches!(
2101            tok.as_str(),
2102            "allow-downloads"
2103                | "allow-forms"
2104                | "allow-modals"
2105                | "allow-orientation-lock"
2106                | "allow-pointer-lock"
2107                | "allow-popups"
2108                | "allow-popups-to-escape-sandbox"
2109                | "allow-presentation"
2110                | "allow-same-origin"
2111                | "allow-scripts"
2112                | "allow-top-navigation"
2113                | "allow-top-navigation-by-user-activation"
2114                | "allow-top-navigation-to-custom-protocols"
2115        ))),
2116        "blocking" => Ok(Value::Bool(tok == "render")),
2117        "rel" => {
2118            let tag = it.dom().borrow().nodes.get(idx).map(super::dom_ns::node_local_name).unwrap_or_default();
2119            let supported = match tag.as_str() {
2120                "a" | "area" => matches!(
2121                    tok.as_str(),
2122                    "alternate"
2123                        | "author"
2124                        | "bookmark"
2125                        | "external"
2126                        | "help"
2127                        | "license"
2128                        | "next"
2129                        | "nofollow"
2130                        | "noopener"
2131                        | "noreferrer"
2132                        | "opener"
2133                        | "prev"
2134                        | "privacy-policy"
2135                        | "search"
2136                        | "tag"
2137                        | "terms-of-service"
2138                ),
2139                "link" => matches!(
2140                    tok.as_str(),
2141                    "alternate"
2142                        | "canonical"
2143                        | "author"
2144                        | "dns-prefetch"
2145                        | "expect"
2146                        | "help"
2147                        | "icon"
2148                        | "license"
2149                        | "manifest"
2150                        | "modulepreload"
2151                        | "next"
2152                        | "pingback"
2153                        | "preconnect"
2154                        | "prefetch"
2155                        | "preload"
2156                        | "prev"
2157                        | "privacy-policy"
2158                        | "search"
2159                        | "stylesheet"
2160                        | "terms-of-service"
2161                ),
2162                "form" => matches!(
2163                    tok.as_str(),
2164                    "external"
2165                        | "help"
2166                        | "license"
2167                        | "next"
2168                        | "nofollow"
2169                        | "noopener"
2170                        | "noreferrer"
2171                        | "opener"
2172                        | "prev"
2173                        | "search"
2174                ),
2175                _ => false,
2176            };
2177            Ok(Value::Bool(supported))
2178        }
2179        _ => Err(it.type_error("Failed to execute 'supports' on 'DOMTokenList': DOMTokenList has no supported tokens.")),
2180    }
2181}
2182
2183
2184/// `DOMTokenList.prototype.toggle(name, force)`。
2185pub fn dom_classlist_toggle(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2186    if let Some((idx, attr)) = this_token_list(&this) {
2187        let tok = arg(a, 0).to_js_string();
2188        class_validate(it, &tok)?;
2189        let mut cur = token_list_tokens(it, idx, attr);
2190        let has = cur.contains(&tok);
2191        let force = match arg(a, 1) {
2192            Value::Undefined => None,
2193            v => Some(v.truthy()),
2194        };
2195        if has {
2196            if force != Some(true) {
2197                cur.retain(|c| c != &tok);
2198                token_list_write(it, idx, attr, &cur);
2199                return Ok(Value::Bool(false));
2200            }
2201            // 既にあって force が真: 属性は更新せず true。
2202            return Ok(Value::Bool(true));
2203        }
2204        if force != Some(false) {
2205            cur.push(tok);
2206            token_list_write(it, idx, attr, &cur);
2207            return Ok(Value::Bool(true));
2208        }
2209        return Ok(Value::Bool(false));
2210    }
2211    Ok(Value::Bool(false))
2212}
2213
2214pub fn dom_classlist_contains(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2215    if let Some((idx, attr)) = this_token_list(&this) {
2216        let tok = arg(a, 0).to_js_string();
2217        return Ok(Value::Bool(token_list_tokens(it, idx, attr).contains(&tok)));
2218    }
2219    Ok(Value::Bool(false))
2220}
2221
2222/// `DOMTokenList.prototype.entries()`/`.keys()`/`.values()`(通常は `Array.prototype` のメソッドをプロトタイプ共有)。
2223pub fn dom_classlist_entries(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2224    if let Some((idx, attr)) = this_token_list(&this) {
2225        let classes = token_list_tokens(it, idx, attr);
2226        let out: Vec<Value> = classes
2227            .into_iter()
2228            .enumerate()
2229            .map(|(i, c)| Value::Object(Obj::array(alloc::vec![Value::Number(i as f64), Value::str(c)])))
2230            .collect();
2231        return Ok(Value::Object(make_iterator(out)));
2232    }
2233    Ok(Value::Object(make_iterator(alloc::vec![])))
2234}
2235pub fn dom_classlist_keys(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2236    if let Some((idx, attr)) = this_token_list(&this) {
2237        let n = token_list_tokens(it, idx, attr).len();
2238        return Ok(Value::Object(make_iterator(
2239            (0..n).map(|i| Value::Number(i as f64)).collect(),
2240        )));
2241    }
2242    Ok(Value::Object(make_iterator(alloc::vec![])))
2243}
2244pub fn dom_classlist_values(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2245    if let Some((idx, attr)) = this_token_list(&this) {
2246        let classes = token_list_tokens(it, idx, attr);
2247        return Ok(Value::Object(make_iterator(
2248            classes.into_iter().map(Value::str).collect(),
2249        )));
2250    }
2251    Ok(Value::Object(make_iterator(alloc::vec![])))
2252}
2253
2254pub(crate) fn document_create_element(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2255    let tag = arg(a, 0).to_js_string();
2256    // 【2026-11-19】名前として使えない文字列は `InvalidCharacterError`(WPT `Document-createElement.html`)。
2257    super::dom_ns::check_name(it, &tag)?;
2258    // 主文書以外の文書(`dom_doc.rs`): XML 文書は名前の大文字小文字をそのまま持ち、`application/xhtml+xml` 以外は名前空間なし。
2259    let owner = super::dom_doc::owner_of_this(it, &t);
2260    if let Some(d) = owner {
2261        let (html, ctype) = {
2262            let dom = it.dom().borrow();
2263            (dom.doc_is_html(Some(d)), dom.nodes[d].attrs.get("_ctype").cloned().unwrap_or_default())
2264        };
2265        if !html {
2266            let ns = if ctype == "application/xhtml+xml" { Some(String::from(super::dom_ns::HTML_NS)) } else { None };
2267            let idx = super::dom_ns::make_element_ns(it, owner, ns, None, &tag, &tag);
2268            return Ok(it.dom_val(idx));
2269        }
2270    }
2271    let idx = it.dom().borrow_mut().create_element(&tag);
2272    super::dom_doc::note_created(it, owner, idx);
2273    // 定義済みのカスタム要素ならその場で構築する(仕様の「同期カスタム要素フラグ」)。
2274    if tag.contains('-') {
2275        it.ce_try_upgrade(idx, false);
2276    }
2277    Ok(it.dom_val(idx))
2278}
2279// `document.createElementNS` は `dom_ns.rs`(名前空間つきの要素)へ移した(2026-11-19)。
2280
2281/// `new Option(text?, value?, defaultSelected?, selected?)`(HTML5。丸ごと
2282/// 未対応だった)。`document.createElement('option')` を土台に組み立てる。
2283pub(crate) fn option_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
2284    let idx = it.dom().borrow_mut().create_element("option");
2285    let text = arg(a, 0);
2286    if !matches!(text, Value::Undefined) {
2287        it.dom().borrow_mut().set_text_content(idx, &text.to_js_string());
2288    }
2289    let value = arg(a, 1);
2290    if !matches!(value, Value::Undefined) {
2291        it.dom().borrow_mut().set_attr(idx, "value", &value.to_js_string());
2292    }
2293    if arg(a, 2).truthy() || arg(a, 3).truthy() {
2294        it.dom().borrow_mut().set_attr(idx, "selected", "selected");
2295    }
2296    Ok(it.dom_val(idx))
2297}
2298
2299pub(crate) fn document_create_text_node(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2300    let text = arg(a, 0).to_js_string();
2301    let idx = it.dom().borrow_mut().create_text_node(&text);
2302    super::dom_doc::note_created(it, super::dom_doc::owner_of_this(it, &t), idx);
2303    Ok(it.dom_val(idx))
2304}
2305
2306pub(crate) fn document_create_comment(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2307    let text = arg(a, 0).to_js_string();
2308    let idx = it.dom().borrow_mut().create_comment(&text);
2309    super::dom_doc::note_created(it, super::dom_doc::owner_of_this(it, &t), idx);
2310    Ok(it.dom_val(idx))
2311}
2312
2313pub(crate) fn document_create_document_fragment(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2314    let idx = it.dom().borrow_mut().create_document_fragment();
2315    super::dom_doc::note_created(it, super::dom_doc::owner_of_this(it, &t), idx);
2316    Ok(it.dom_val(idx))
2317}
2318
2319pub(crate) fn split_css_rules(css: &str) -> alloc::vec::Vec<String> {
2320    let mut rules = alloc::vec![];
2321    let mut current_rule = String::new();
2322    let mut depth = 0;
2323    for c in css.chars() {
2324        current_rule.push(c);
2325        if c == '{' {
2326            depth += 1;
2327        } else if c == '}' {
2328            if depth > 0 {
2329                depth -= 1;
2330            }
2331            if depth == 0 {
2332                let trimmed = current_rule.trim();
2333                if !trimmed.is_empty() {
2334                    rules.push(trimmed.to_string());
2335                }
2336                current_rule.clear();
2337            }
2338        }
2339    }
2340    let trimmed = current_rule.trim();
2341    if !trimmed.is_empty() {
2342        rules.push(trimmed.to_string());
2343    }
2344    rules
2345}
2346
2347pub(crate) fn dom_stylesheet_insert_rule(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2348    let rule_text = arg(a, 0).to_js_string();
2349    let insert_index = arg(a, 1).to_number() as usize;
2350    if let Value::Object(o) = this {
2351        if let ObjKind::HostRef(h) = &o.borrow().kind {
2352            if h.class == HOST_STYLESHEET {
2353                let idx: usize = h.id;
2354                let text = it.dom().borrow().get_text_content(idx);
2355                let mut rules = split_css_rules(&text);
2356                let actual_index = insert_index.min(rules.len());
2357                rules.insert(actual_index, rule_text);
2358                let new_css = rules.join("\n");
2359                it.dom().borrow_mut().set_text_content(idx, &new_css);
2360                return Ok(Value::Number(actual_index as f64));
2361            }
2362        }
2363    }
2364    Ok(Value::Number(0.0))
2365}
2366
2367pub(crate) fn dom_stylesheet_delete_rule(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2368    let delete_index = arg(a, 0).to_number() as usize;
2369    if let Value::Object(o) = this {
2370        if let ObjKind::HostRef(h) = &o.borrow().kind {
2371            if h.class == HOST_STYLESHEET {
2372                let idx: usize = h.id;
2373                let text = it.dom().borrow().get_text_content(idx);
2374                let mut rules = split_css_rules(&text);
2375                if delete_index < rules.len() {
2376                    rules.remove(delete_index);
2377                    let new_css = rules.join("\n");
2378                    it.dom().borrow_mut().set_text_content(idx, &new_css);
2379                }
2380            }
2381        }
2382    }
2383    Ok(Value::Undefined)
2384}
2385
2386
2387/// `parent.moveBefore(movedNode, referenceNode)`(DOM。2025年にChromeへ
2388/// 実装が入った比較的新しいAPI。丸ごと未対応だった)。仕様上の主眼は
2389/// 「`remove()`してから`insertBefore()`する」場合と異なり、`<iframe>`の
2390/// 読み込み状態・`<video>`の再生状態・カスタム要素のライフサイクル
2391/// コールバック発火等を保持したまま木構造内を移動できる点にあるが、
2392/// この処理系にはそれらの「保持すべき生きた状態」自体が実装されて
2393/// いない(`<iframe>`は実際のナビゲーション状態を持たず、`<video>`は
2394/// 実再生をしない等)ため、実務上は`insertBefore`と同じ「detachしてから
2395/// 指定位置へ挿入」の`insert_before`(`dom_bridge.rs`。既に自動で元の
2396/// 親から外す実装)をそのまま再利用する誠実な簡略実装で十分に仕様どおり
2397/// 動作する。`referenceNode`(`null`可)が`this`の子でない場合は
2398/// `insertBefore`と同じ`NotFoundError`規則を踏襲。2026-07-18 発見・実装。
2399pub fn dom_move_before(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2400    if a.len() < 2 {
2401        return Err(it.type_error(alloc::format!(
2402            "Failed to execute 'moveBefore' on 'Node': 2 arguments required, but only {} present.",
2403            a.len()
2404        )));
2405    }
2406    let Some(par) = super::dom_tree::par_of(&this) else {
2407        return Err(it.dom_exception("HierarchyRequestError", "Invalid parent node."));
2408    };
2409    let moved_node = arg(a, 0);
2410    let refv = arg(a, 1);
2411    let rc = match &refv {
2412        Value::Null | Value::Undefined => None,
2413        v => match this_dom_idx(v) {
2414            Some(i) => Some(i),
2415            None => {
2416                return Err(it.type_error(
2417                    "Failed to execute 'moveBefore' on 'Node': parameter 2 is not of type 'Node'.",
2418                ));
2419            }
2420        },
2421    };
2422    super::dom_tree::validate_insert(it, par, &moved_node, rc, false)?;
2423    let Some(mn) = this_dom_idx(&moved_node) else {
2424        return Err(it.dom_exception("HierarchyRequestError", "Cannot move a Document."));
2425    };
2426    {
2427        let dom = it.dom().borrow();
2428        let is_movable = dom.nodes.get(mn).is_some_and(|n| {
2429            n.is_text || (!n.tag.starts_with('#') || n.tag == "#comment" || n.tag == "#pi")
2430        });
2431        if !is_movable {
2432            return Err(it.dom_exception(
2433                "HierarchyRequestError",
2434                "Only Element or CharacterData nodes can be moved with moveBefore.",
2435            ));
2436        }
2437        let shadow_including_root = |start: usize| -> usize {
2438            let mut cur = start;
2439            for _ in 0..=dom.nodes.len() + 64 {
2440                if cur == 0 || dom.main_doctype == Some(cur) {
2441                    return crate::os_lib::web_apis::dom_bridge::MAIN_DOC;
2442                }
2443                match dom.nodes.get(cur).and_then(|n| n.parent) {
2444                    Some(p) => cur = p,
2445                    None => match dom.shadow_tree.get_host_by_root(cur) {
2446                        Some(h) => cur = h,
2447                        None => return cur,
2448                    },
2449                }
2450            }
2451            cur
2452        };
2453        let par_root = match par {
2454            super::dom_tree::Par::MainDoc => crate::os_lib::web_apis::dom_bridge::MAIN_DOC,
2455            super::dom_tree::Par::Node(p) => shadow_including_root(p),
2456        };
2457        let node_root = shadow_including_root(mn);
2458        if par_root != node_root {
2459            return Err(it.dom_exception(
2460                "HierarchyRequestError",
2461                "The parent and moved node must share the same shadow-including root.",
2462            ));
2463        }
2464    }
2465    if let super::dom_tree::Par::Node(p) = par {
2466        it.dom().borrow_mut().move_before(p, mn, rc);
2467    }
2468    Ok(Value::Undefined)
2469}
2470
2471/// `select.options.add(option, before?)`(HTML5 `HTMLOptionsCollection`。
2472/// 動的にドロップダウンを構築する `select.options.add(new Option(...))` という
2473/// 定番イディオムが、`options` が素の配列(メソッドを一切持たない)を返す
2474/// だけだったため丸ごと未対応(`TypeError: not a function`)だった。`options`
2475/// 取得時に配列オブジェクト自身へ `_select_idx`(隠しプロパティ。既存の
2476/// `_is_headers`/`_ta_kind` 等と同じ内部タグ付けパターン)を仕込んでおき、
2477/// この配列を経由して元の `<select>` を辿れるようにする。`before` は仕様どおり
2478/// 省略時は末尾追加、数値ならその位置の既存 option の前、`<option>` 要素
2479/// そのものでもよい。
2480pub fn select_options_add(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2481    let select_idx = match &this {
2482        Value::Object(o) => o.borrow().props.get("_select_idx").map(|v| v.to_number() as usize),
2483        _ => None,
2484    };
2485    let (Some(select_idx), Some(opt_idx)) = (select_idx, this_dom_idx(&arg(a, 0))) else {
2486        return Ok(Value::Undefined);
2487    };
2488    let before = arg(a, 1);
2489    let ref_idx = match &before {
2490        Value::Number(n) => it.dom().borrow().select_options(select_idx).get(*n as usize).copied(),
2491        Value::Object(_) => this_dom_idx(&before),
2492        _ => None,
2493    };
2494    it.dom().borrow_mut().insert_before(select_idx, opt_idx, ref_idx);
2495    Ok(Value::Undefined)
2496}
2497/// `select.add(element, before)`(`HTMLSelectElement`直下の便利メソッド。
2498/// `select.options.add`と全く同じ意味だが、`this`が`options`コレクション
2499/// 配列ではなく`<select>`要素自身になる点だけが違う。丸ごと未対応
2500/// だった。`select_options_add`とほぼ同じロジックだが、`_select_idx`
2501/// 隠しプロパティ経由ではなく`this_dom_idx`で直接`<select>`のインデックス
2502/// を取る。2026-07-18 発見・実装)。
2503pub fn dom_select_add(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2504    let (Some(select_idx), Some(opt_idx)) = (this_dom_idx(&this), this_dom_idx(&arg(a, 0))) else {
2505        return Ok(Value::Undefined);
2506    };
2507    let before = arg(a, 1);
2508    let ref_idx = match &before {
2509        Value::Number(n) => it.dom().borrow().select_options(select_idx).get(*n as usize).copied(),
2510        Value::Object(_) => this_dom_idx(&before),
2511        _ => None,
2512    };
2513    it.dom().borrow_mut().insert_before(select_idx, opt_idx, ref_idx);
2514    Ok(Value::Undefined)
2515}
2516/// `select.options.remove(index)`(`HTMLOptionsCollection`。上記 `add` と対に
2517/// なる、指定インデックスの `<option>` を取り除く定番メソッド)。
2518pub fn select_options_remove(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2519    let select_idx = match &this {
2520        Value::Object(o) => o.borrow().props.get("_select_idx").map(|v| v.to_number() as usize),
2521        _ => None,
2522    };
2523    let Some(select_idx) = select_idx else {
2524        return Ok(Value::Undefined);
2525    };
2526    let n = arg(a, 0).to_number() as usize;
2527    // `if let Some(x) = obj.borrow()...` は scrutinee の一時 `Ref` が if-let ブロック
2528    // 終端まで生き続けるため、ブロック内で `borrow_mut()` すると「RefCell already
2529    // borrowed」で panic する(このファイルの `report_error` 修正と同型のバグ。
2530    // 一度 owned な値へ materialize してから `if let` することで回避する)。
2531    let opt_idx = it.dom().borrow().select_options(select_idx).get(n).copied();
2532    if let Some(opt_idx) = opt_idx {
2533        it.dom().borrow_mut().remove_child(select_idx, opt_idx);
2534    }
2535    Ok(Value::Undefined)
2536}
2537/// `select.options.namedItem(name)`(`HTMLOptionsCollection`。`id`/`name`
2538/// 属性が一致する `<option>` を探す定番メソッド。見つからなければ仕様どおり
2539/// `null`)。
2540pub fn select_options_named_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2541    let select_idx = match &this {
2542        Value::Object(o) => o.borrow().props.get("_select_idx").map(|v| v.to_number() as usize),
2543        _ => None,
2544    };
2545    let Some(select_idx) = select_idx else {
2546        return Ok(Value::Null);
2547    };
2548    let name = arg(a, 0).to_js_string();
2549    let dom = it.dom().borrow();
2550    for opt_idx in dom.select_options(select_idx) {
2551        if dom.get_attr(opt_idx, "id").as_deref() == Some(name.as_str())
2552            || dom.get_attr(opt_idx, "name").as_deref() == Some(name.as_str())
2553        {
2554            return Ok(it.dom_val(opt_idx));
2555        }
2556    }
2557    Ok(Value::Null)
2558}
2559
2560/// 引数を DOM ノード idx に解決(要素はそのまま、文字列はテキストノード生成)。
2561pub(crate) fn arg_to_node(it: &mut Interp, v: &Value) -> Option<usize> {
2562    match this_dom_idx(v) {
2563        Some(i) => Some(i),
2564        None => match v {
2565            Value::Undefined | Value::Null => None,
2566            other => Some(it.dom().borrow_mut().create_text_node(&other.to_js_string())),
2567        },
2568    }
2569}
2570
2571/// element.insertAdjacentHTML(position, html)。
2572/// `element.getHTML(options?)`(DOM。`innerHTML`ゲッターの明示的メソッド版
2573/// として2024年頃に標準化。丸ごと未対応だった)。仕様上の`options`
2574/// (`{serializableShadowRoots, shadowRoots}`)はShadow DOM自体が
2575/// この処理系に存在しないため意味を持たず無視する。`innerHTML`と全く同じ
2576/// `get_inner_html`をそのまま呼ぶだけの簡略実装。2026-07-18 発見・実装。
2577pub fn dom_get_html(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2578    if let Some(idx) = this_dom_idx(&this) {
2579        return Ok(Value::str(it.dom().borrow().get_inner_html(idx)));
2580    }
2581    Ok(Value::str(""))
2582}
2583
2584/// `element.setHTMLUnsafe(html)`(DOM。`innerHTML`セッターのTrusted
2585/// Types検証を明示的にバイパスする版として標準化。丸ごと未対応だった)。
2586/// この処理系にはTrusted Typesの強制自体が実装されていないため、
2587/// `innerHTML`セッターと全く同じ`set_inner_html`をそのまま呼ぶだけの
2588/// 簡略実装で仕様上の可視的な違いは無い。2026-07-18 発見・実装。
2589pub fn dom_set_html_unsafe(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2590    if let Some(idx) = this_dom_idx(&this) {
2591        let html = arg(a, 0).to_js_string();
2592        it.dom().borrow_mut().set_inner_html(idx, &html);
2593    }
2594    Ok(Value::Undefined)
2595}
2596
2597pub fn dom_insert_adjacent_html(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2598    if let Some(idx) = this_dom_idx(&this) {
2599        // `position` は仕様上 ASCII 大文字小文字を無視して照合すべきだが
2600        // (`"beforeBegin"`/`"BEFOREEND"` 等も有効)、以前は完全一致のみで
2601        // 小文字以外を渡すと静かに no-op になっていた。
2602        let pos = arg(a, 0).to_js_string().to_lowercase();
2603        let html = arg(a, 1).to_js_string();
2604        it.dom().borrow_mut().insert_adjacent_html(idx, &pos, &html);
2605    }
2606    Ok(Value::Undefined)
2607}
2608/// element.insertAdjacentElement(position, element)。
2609pub fn dom_insert_adjacent_element(
2610    it: &mut Interp,
2611    this: Value,
2612    a: &[Value],
2613) -> Result<Value, Value> {
2614    let Some(idx) = this_dom_idx(&this).filter(|&i| {
2615        let dom = it.dom().borrow();
2616        dom.nodes.get(i).is_some_and(|n| !n.is_text && !n.tag.starts_with('#'))
2617    }) else {
2618        return Err(it.type_error("Illegal invocation"));
2619    };
2620    let pos = arg(a, 0).to_js_string().to_ascii_lowercase();
2621    let el = arg(a, 1);
2622    let Some(node) = this_dom_idx(&el) else {
2623        return Err(it.type_error("Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'."));
2624    };
2625    if !matches!(pos.as_str(), "beforebegin" | "afterbegin" | "beforeend" | "afterend") {
2626        return Err(it.dom_exception("SyntaxError", "The value provided is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'."));
2627    }
2628    let (parent_opt, is_doc_parent) = {
2629        let dom = it.dom().borrow();
2630        let p = dom.nodes.get(idx).and_then(|n| n.parent);
2631        let is_doc = idx == 0 || p.is_some_and(|pi| dom.is_doc_node(pi));
2632        (p, is_doc)
2633    };
2634    if matches!(pos.as_str(), "beforebegin" | "afterend") {
2635        if is_doc_parent {
2636            return Err(it.dom_exception("HierarchyRequestError", "The operation would yield an incorrect node tree."));
2637        }
2638        if parent_opt.is_none() {
2639            return Ok(Value::Null);
2640        }
2641    }
2642    it.dom().borrow_mut().insert_adjacent_node(idx, &pos, node);
2643    Ok(el)
2644}
2645/// element.insertAdjacentText(position, text)。
2646pub fn dom_insert_adjacent_text(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2647    let Some(idx) = this_dom_idx(&this).filter(|&i| {
2648        let dom = it.dom().borrow();
2649        dom.nodes.get(i).is_some_and(|n| !n.is_text && !n.tag.starts_with('#'))
2650    }) else {
2651        return Err(it.type_error("Illegal invocation"));
2652    };
2653    let pos = arg(a, 0).to_js_string().to_ascii_lowercase();
2654    if !matches!(pos.as_str(), "beforebegin" | "afterbegin" | "beforeend" | "afterend") {
2655        return Err(it.dom_exception("SyntaxError", "The value provided is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'."));
2656    }
2657    let (parent_opt, is_doc_parent) = {
2658        let dom = it.dom().borrow();
2659        let p = dom.nodes.get(idx).and_then(|n| n.parent);
2660        let is_doc = idx == 0 || p.is_some_and(|pi| dom.is_doc_node(pi));
2661        (p, is_doc)
2662    };
2663    if matches!(pos.as_str(), "beforebegin" | "afterend") {
2664        if is_doc_parent {
2665            return Err(it.dom_exception("HierarchyRequestError", "The operation would yield an incorrect node tree."));
2666        }
2667        if parent_opt.is_none() {
2668            return Ok(Value::Undefined);
2669        }
2670    }
2671    let text = arg(a, 1).to_js_string();
2672    let node = it.dom().borrow_mut().create_text_node(&text);
2673    it.dom().borrow_mut().insert_adjacent_node(idx, &pos, node);
2674    Ok(Value::Undefined)
2675}
2676/// element.toggleAttribute(name[, force]) → 操作後の存在を返す。
2677pub fn dom_toggle_attribute(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2678    if let Some(r) = super::dom_pi::pi_attr(it, &this, "toggleAttribute", a) {
2679        return r;
2680    }
2681    if let Some(idx) = this_dom_idx(&this) {
2682        let raw = arg(a, 0).to_js_string();
2683        super::dom_attr::check_attr_name(it, &raw)?;
2684        let name = super::dom_attr::fix_name(it, idx, &raw);
2685        let first_match = it
2686            .dom()
2687            .borrow()
2688            .attr_entries(idx)
2689            .into_iter()
2690            .find(|(_, qn)| qn == &name);
2691        let has = if name.starts_with('_') {
2692            it.dom().borrow().has_attr(idx, &name)
2693        } else {
2694            first_match.is_some()
2695        };
2696        let new_state = if a.len() > 1 && !matches!(arg(a, 1), Value::Undefined) {
2697            arg(a, 1).truthy()
2698        } else {
2699            !has
2700        };
2701        if new_state {
2702            {
2703                let mut dom = it.dom().borrow_mut();
2704                if name.starts_with("on") && !dom.on_handlers.is_empty() {
2705                    dom.on_handlers.remove(&(idx, name.clone()));
2706                }
2707                match &first_match {
2708                    Some((Some(u), qn)) => dom.set_attr_ns(idx, Some(u), qn, ""),
2709                    _ => dom.set_attr(idx, &name, ""),
2710                }
2711            }
2712            super::dom_handlers::attr_changed(it, idx, &name, Some(""));
2713        } else {
2714            {
2715                let mut dom = it.dom().borrow_mut();
2716                if name.starts_with("on") && !dom.on_handlers.is_empty() {
2717                    dom.on_handlers.remove(&(idx, name.clone()));
2718                }
2719                match &first_match {
2720                    Some((Some(u), qn)) => {
2721                        let local = qn.split_once(':').map(|(_, l)| l).unwrap_or(qn);
2722                        dom.remove_attr_ns(idx, Some(u), local);
2723                    }
2724                    Some((None, _)) => dom.remove_attr(idx, &name),
2725                    None => {}
2726                }
2727            }
2728            super::dom_handlers::attr_changed(it, idx, &name, None);
2729        }
2730        return Ok(Value::Bool(new_state));
2731    }
2732    Ok(Value::Bool(false))
2733}
2734
2735/// `dialog.show()`(`<dialog>` が丸ごと未対応だった)。`open` 属性を付ける
2736/// だけの簡略実装。
2737pub fn dom_dialog_show(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2738    if let Some(idx) = this_dom_idx(&this) {
2739        it.dom().borrow_mut().set_attr(idx, "open", "open");
2740    }
2741    Ok(Value::Undefined)
2742}
2743
2744/// `dialog.showModal()`。以前は`.show()`と全く同じ`dom_dialog_show`を共有して
2745/// おり、モーダル/非モーダルの区別自体が存在しなかった(`showModal()`本来の
2746/// モーダルフォーカストラップ・`::backdrop`描画は依然対象外だが対象外)。CSS
2747/// `:modal`疑似クラス(丸ごと未対応だった。2026-07-18 発見・実装)が判定
2748/// できるよう、`open`属性に加え`:fullscreen`と同じ内部専用属性パターンで
2749/// `_modal`を書き込む点だけが`.show()`と異なる。
2750pub fn dom_dialog_show_modal(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2751    if let Some(idx) = this_dom_idx(&this) {
2752        let mut dom = it.dom().borrow_mut();
2753        dom.set_attr(idx, "open", "open");
2754        dom.set_attr(idx, "_modal", "1");
2755    }
2756    Ok(Value::Undefined)
2757}
2758
2759/// `dialog.close(returnValue?)`。`open` 属性を外し、`returnValue` を設定してから
2760/// `close` イベントを発火する(仕様どおり)。DOM 要素は汎用の `Obj.props` ではなく
2761/// `interp.rs` 側の明示的なプロパティ一覧を介してアクセスされるため、`checked`/
2762/// `indeterminate` と同じ「内部専用の `_` プレフィックス属性キー」パターン
2763/// (`_return_value`)で持たせる(`this.props` へ直接書いても読み出し経路が
2764/// 無く反映されない)。
2765pub fn dom_dialog_close(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2766    if let Some(idx) = this_dom_idx(&this) {
2767        {
2768            let mut dom = it.dom().borrow_mut();
2769            dom.remove_attr(idx, "open");
2770            dom.remove_attr(idx, "_modal");
2771        }
2772        if !a.is_empty() {
2773            it.dom()
2774                .borrow_mut()
2775                .set_attr(idx, "_return_value", &arg(a, 0).to_js_string());
2776        }
2777        let _ = it.dispatch_event_in_interp(idx, "close", &[]);
2778    }
2779    Ok(Value::Undefined)
2780}
2781
2782// `dialog.requestClose(returnValue?)`(HTML Living Standard。`.close()`と
2783// 違い、閉じる直前に取消可能な`cancel`イベントを発火し、リスナが
2784// `preventDefault()`すればダイアログを開いたままにできる。丸ごと
2785// 未対応だった。`.close()`自体は無条件クローズのため対になるこちらの
2786// 「ユーザーの閉じる操作を横取り可能にする」経路が漏れていた。
2787// `popover_toggle_extra`と同じ「取消可能イベント→未阻止なら実処理」
2788// パターンを再利用する。2026-07-18 発見・実装)。
2789pub fn dom_dialog_request_close(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2790    if let Some(idx) = this_dom_idx(&this) {
2791        let (_, prevented) = it.dispatch_event_in_interp(idx, "cancel", &[]);
2792        if !prevented {
2793            {
2794                let mut dom = it.dom().borrow_mut();
2795                dom.remove_attr(idx, "open");
2796                dom.remove_attr(idx, "_modal");
2797            }
2798            if !a.is_empty() {
2799                it.dom()
2800                    .borrow_mut()
2801                    .set_attr(idx, "_return_value", &arg(a, 0).to_js_string());
2802            }
2803            let _ = it.dispatch_event_in_interp(idx, "close", &[]);
2804        }
2805    }
2806    Ok(Value::Undefined)
2807}
2808
2809/// `element.showPopover()`/`.hidePopover()`/`.togglePopover(force?)`(Popover
2810/// API。丸ごと未対応だった)。`<dialog>` の `open` 属性と同じく、内部専用属性
2811/// (`_popover_open`)を付け外しするだけの簡略実装(`css.rs` 側の UA 既定
2812/// display 切り替えと対)。`beforetoggle`/`toggle` イベント発火・
2813/// `:popover-open` 疑似クラス・ライトディスミスは対象外。
2814// `showPopover`/`hidePopover`/`togglePopover`が状態変化を`toggle`イベント
2815// として発火していなかった(丸ごと未対応だった。`<dialog>.close()`は既に
2816// `"close"`イベントを発火していたのに、同じ「開閉状態変化を通知する」
2817// 役目のPopover側だけ漏れていた非対称ギャップ。2026-07-17 発見)。仕様上は
2818// `oldState`/`newState`を持つ`ToggleEvent`だが、この処理系に`ToggleEvent`
2819// コンストラクタ自体が無いため、`<details>`の`toggle`イベント修正と同じ
2820// 簡略方針で`dispatch_event_in_interp`にプレーンな`Event`へ同名プロパティ
2821// を追加する形(`extra`引数)で代用する。対になる取消可能な`beforetoggle`
2822// (状態変更「前」に発火し`preventDefault()`で開閉を中止できる。同じく
2823// 丸ごと未対応だった)も同時に実装。
2824fn popover_toggle_extra(old_open: bool, new_open: bool) -> alloc::vec::Vec<(String, Value)> {
2825    alloc::vec![
2826        (String::from("oldState"), Value::str(if old_open { "open" } else { "closed" })),
2827        (String::from("newState"), Value::str(if new_open { "open" } else { "closed" })),
2828    ]
2829}
2830pub fn dom_show_popover(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2831    if let Some(idx) = this_dom_idx(&this) {
2832        let was_open = it.dom().borrow().has_attr(idx, "_popover_open");
2833        // `beforetoggle`(状態変更「前」に発火する取消可能なイベント。
2834        // `preventDefault()`で開閉自体を中止できる。丸ごと未対応だった。
2835        // 2026-07-17 発見・実装)。
2836        let (_, prevented) =
2837            it.dispatch_event_in_interp(idx, "beforetoggle", &popover_toggle_extra(was_open, true));
2838        if prevented {
2839            return Ok(Value::Undefined);
2840        }
2841        it.dom().borrow_mut().set_attr(idx, "_popover_open", "");
2842        let _ = it.dispatch_event_in_interp(idx, "toggle", &popover_toggle_extra(was_open, true));
2843    }
2844    Ok(Value::Undefined)
2845}
2846pub fn dom_hide_popover(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
2847    if let Some(idx) = this_dom_idx(&this) {
2848        let was_open = it.dom().borrow().has_attr(idx, "_popover_open");
2849        let (_, prevented) =
2850            it.dispatch_event_in_interp(idx, "beforetoggle", &popover_toggle_extra(was_open, false));
2851        if prevented {
2852            return Ok(Value::Undefined);
2853        }
2854        it.dom().borrow_mut().remove_attr(idx, "_popover_open");
2855        let _ = it.dispatch_event_in_interp(idx, "toggle", &popover_toggle_extra(was_open, false));
2856    }
2857    Ok(Value::Undefined)
2858}
2859pub fn dom_toggle_popover(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2860    if let Some(idx) = this_dom_idx(&this) {
2861        let was_open = it.dom().borrow().has_attr(idx, "_popover_open");
2862        let force = if matches!(arg(a, 0), Value::Undefined) {
2863            !was_open
2864        } else {
2865            arg(a, 0).truthy()
2866        };
2867        let (_, prevented) =
2868            it.dispatch_event_in_interp(idx, "beforetoggle", &popover_toggle_extra(was_open, force));
2869        if prevented {
2870            return Ok(Value::Bool(was_open));
2871        }
2872        if force {
2873            it.dom().borrow_mut().set_attr(idx, "_popover_open", "");
2874        } else {
2875            it.dom().borrow_mut().remove_attr(idx, "_popover_open");
2876        }
2877        let _ = it.dispatch_event_in_interp(idx, "toggle", &popover_toggle_extra(was_open, force));
2878        return Ok(Value::Bool(force));
2879    }
2880    Ok(Value::Bool(false))
2881}
2882
2883/// element.append(...nodes):末尾に複数追加(文字列はテキスト)。
2884/// `element.replaceChildren(...nodes)`(DOM 標準。`el.innerHTML=''; el.append(...)`
2885/// の1行版として使われる定番イディオム)が丸ごと未対応だった。既存の
2886/// `set_inner_html(idx, "")`(子を丸ごとクリア)と `append`/`arg_to_node` と同じ
2887/// 「文字列は text node、DOM ノードはそのまま」変換を組み合わせて実装する。
2888/// node.cloneNode(deep)。複製ノード(親なし)を返す。
2889pub fn dom_clone_node(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2890    if let Some(idx) = this_dom_idx(&this) {
2891        let deep = arg(a, 0).truthy();
2892        let new_idx = it.dom().borrow_mut().clone_node(idx, deep);
2893        return Ok(dom_handle(it, Some(new_idx)));
2894    }
2895    Ok(Value::Null)
2896}
2897/// `document.importNode(externalNode, deep)`(丸ごと未対応だった。
2898/// `<template>` の中身を複製して自文書へ取り込む定番パターン
2899/// `document.importNode(template.content, true)` で使われる)。この処理系は
2900/// 単一文書(複数 `Document` オブジェクトという概念自体が無い)のため、
2901/// 「別文書から取り込む」という仕様上の意味は無く、実質 `node.cloneNode(deep)`
2902/// と同じ結果になる簡略実装。仕様上 `deep` は省略時 `false` だが、実務では
2903/// ほぼ常に明示的に `true` が渡される。
2904pub fn document_import_node(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
2905    let r = dom_clone_node(it, arg(a, 0), a.get(1..).unwrap_or(&[]))?;
2906    // XML 文書から取り込んだ要素は HTML 文書のもの(`tagName` は大文字に戻る)。
2907    if let Some(idx) = this_dom_idx(&r) {
2908        it.dom().borrow_mut().unmark_subtree_xml(idx);
2909    }
2910    Ok(r)
2911}
2912/// `document.adoptNode(node)`(丸ごと未対応だった)。単一文書のこの処理系
2913/// では「別文書から養子縁組する」という意味は無いため、仕様の副作用
2914/// (現在の親から取り外す)のみを再現し、渡されたノードをそのまま返す。
2915/// カスタム要素の場合は `adoptedCallback` を発火する。
2916pub fn document_adopt_node(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
2917    let node = arg(a, 0);
2918    if let Some(idx) = this_dom_idx(&node) {
2919        it.dom().borrow_mut().remove_node(idx);
2920        it.ce_adopted_callback(idx);
2921    }
2922    Ok(node)
2923}
2924
2925/// `element.getElementById(id)` / `shadowRoot.getElementById(id)`
2926pub(crate) fn dom_node_get_element_by_id(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2927    let Some(root_idx) = this_dom_idx(&this) else {
2928        return Ok(Value::Null);
2929    };
2930    let id = arg(a, 0).to_js_string();
2931    if id.is_empty() {
2932        return Ok(Value::Null);
2933    }
2934    let dom = it.dom().borrow();
2935    if let Some(n) = dom.nodes.get(root_idx) {
2936        if !n.is_text && n.id == id {
2937            return Ok(dom_handle(it, Some(root_idx)));
2938        }
2939    }
2940    for desc in dom.descendants_by_tag_name(root_idx, "*") {
2941        if let Some(n) = dom.nodes.get(desc) {
2942            if !n.is_text && n.id == id {
2943                return Ok(dom_handle(it, Some(desc)));
2944            }
2945        }
2946    }
2947    Ok(Value::Null)
2948}
2949
2950/// `element.click()`。以前は単なる no-op で、実際のクリック
2951/// (`onclick`/`addEventListener('click', ...)` リスナの発火)を一切引き起こさな
2952/// かった。実マウス操作からも呼ばれる既存の `dispatch_click()` を再利用する。
2953/// `checkbox`/`radio` は仕様上クリックすると(リスナの実行前に)自身の選択状態が
2954/// 切り替わる。以前は `element.checked` という JS プロパティ自体が丸ごと未実装
2955/// だったため、この状態切替もできていなかった。**重要**: 同じ `name` を持つ
2956/// ラジオボタン間の排他選択(1つを選ぶと他が自動で解除される、ラジオボタンの
2957/// 最も基本的な仕様上の挙動)も以前は非対応の簡略化として明示的に見送られていたが、
2958/// `uncheck_radio_group_siblings` を新設し配線した。
2959/// `element.scrollTo(x, y)`/`.scrollTo({top, left, behavior})` が丸ごと未対応
2960/// `element.scrollTop`/`element.scrollLeft` および `scrollTo`/`scrollBy`/`scroll`
2961/// の対象座標を引数から抽出する。オブジェクト引数 `{top, left}` または
2962/// 位置引数 `(x, y)` の両方に対応する。
2963pub(crate) fn scroll_top_target(a: &[Value]) -> Option<i32> {
2964    match arg(a, 0) {
2965        Value::Object(_) => obj_prop(&arg(a, 0), "top").map(|v| v.to_number() as i32),
2966        Value::Undefined => None,
2967        _ => Some(arg(a, 1).to_number() as i32),
2968    }
2969}
2970
2971pub(crate) fn scroll_left_target(a: &[Value]) -> Option<i32> {
2972    match arg(a, 0) {
2973        Value::Object(_) => obj_prop(&arg(a, 0), "left").map(|v| v.to_number() as i32),
2974        Value::Undefined => None,
2975        _ => Some(arg(a, 0).to_number() as i32),
2976    }
2977}
2978
2979pub fn dom_scroll_to(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2980    if let Some(idx) = this_dom_idx(&this) {
2981        let top = scroll_top_target(a);
2982        let left = scroll_left_target(a);
2983        if top.is_some() || left.is_some() {
2984            let mut dom = it.dom().borrow_mut();
2985            if let Some(t) = top {
2986                dom.scroll_tops.insert(idx, t.max(0));
2987            }
2988            if let Some(l) = left {
2989                dom.scroll_lefts.insert(idx, l.max(0));
2990            }
2991            dom.dirty = true;
2992        }
2993    }
2994    Ok(Value::Undefined)
2995}
2996
2997/// `element.scrollBy(x, y)`/`.scrollBy({top, left})`。現在値からの相対移動である点
2998/// のみ `scrollTo` と異なる。
2999pub fn dom_scroll_by(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3000    if let Some(idx) = this_dom_idx(&this) {
3001        let delta_top = scroll_top_target(a);
3002        let delta_left = scroll_left_target(a);
3003        if delta_top.is_some() || delta_left.is_some() {
3004            let mut dom = it.dom().borrow_mut();
3005            if let Some(dt) = delta_top {
3006                let cur = dom.scroll_tops.get(&idx).copied().unwrap_or(0);
3007                dom.scroll_tops.insert(idx, (cur + dt).max(0));
3008            }
3009            if let Some(dl) = delta_left {
3010                let cur = dom.scroll_lefts.get(&idx).copied().unwrap_or(0);
3011                dom.scroll_lefts.insert(idx, (cur + dl).max(0));
3012            }
3013            dom.dirty = true;
3014        }
3015    }
3016    Ok(Value::Undefined)
3017}
3018/// `element.scrollIntoView()`/`.scrollIntoView({behavior, block})`が丸ごと
3019/// no-opだった(HTML Standard §"scroll into view"の簡略実装が丸ごと欠落。
3020/// 実サイト www.sugi-lab.net のナビゲーションリンク(`target.scrollIntoView(
3021/// {behavior:'smooth', block:'start'})`)が完全に無効化されており、クリック
3022/// しても一切スクロールしないという実害があった。2026-07-22発見・修正)。
3023/// 既存の`window.scrollTo`と同じ`pending_scroll_abs_y`機構(`render.rs`の
3024/// `draw()`冒頭で消費・`fire_scroll()`呼び出しまで行う、既に動作確認済みの
3025/// 経路)を再利用する。対象要素の現在のビューポート相対Y座標
3026/// (`get_rect`。`getBoundingClientRect`と同じ値)に現在のスクロール量
3027/// (`window.scrollY`)を加算し、文書内の絶対Y座標を求めて要素の上端が
3028/// ビューポート上端に来るようにスクロールする(`block:'start'`相当。
3029/// `center`/`end`/`nearest`は簡略化しすべて`start`と同一視する。`behavior`
3030/// は既存の`scrollTo`と同様、実時間アニメーションの概念が無いため即座に
3031/// 反映する)。
3032pub fn dom_scroll_into_view(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3033    let Some(idx) = this_dom_idx(&this) else {
3034        return Ok(Value::Undefined);
3035    };
3036    let Some((_, y, _, _)) = it.dom().borrow().get_rect(idx) else {
3037        return Ok(Value::Undefined);
3038    };
3039    let current_scroll_y = it
3040        .global
3041        .borrow()
3042        .vars
3043        .get("scrollY")
3044        .map(|v| v.to_number())
3045        .unwrap_or(0.0);
3046    let target_abs_y = (current_scroll_y + y as f64).max(0.0);
3047    it.dom().borrow_mut().pending_scroll_abs_y = Some(target_abs_y as i32);
3048    Ok(Value::Undefined)
3049}
3050pub fn dom_click(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3051    if let Some(idx) = this_dom_idx(&this) {
3052        let disabled_form_ctrl = {
3053            let dom = it.dom().borrow();
3054            let tag = dom.nodes.get(idx).map(|n| n.tag.as_str()).unwrap_or("");
3055            matches!(tag, "button" | "input" | "select" | "textarea") && dom.is_disabled(idx)
3056        };
3057        if disabled_form_ctrl {
3058            return Ok(Value::Undefined);
3059        }
3060        // `MouseEvent("click", {bubbles: true, cancelable: true, composed: true})` を構築して配送。
3061        // activation behavior(checkbox/radio/form/a/details/label 等)は dispatch_event_object 内で統一処理する。
3062        let ctor = it.global.borrow().vars.get("MouseEvent").cloned();
3063        let init_dict = Obj::plain();
3064        {
3065            let mut d = init_dict.borrow_mut();
3066            d.props.insert("bubbles".into(), Value::Bool(true));
3067            d.props.insert("cancelable".into(), Value::Bool(true));
3068            d.props.insert("composed".into(), Value::Bool(true));
3069        }
3070        let mouse_ev = if let Some(c) = ctor {
3071            match it.construct_value(&c, &[Value::str("click"), Value::Object(init_dict)]) {
3072                Ok(Value::Object(eo)) => Some(eo),
3073                _ => None,
3074            }
3075        } else {
3076            None
3077        };
3078        it.dispatch_event_object(
3079            idx,
3080            "click",
3081            &[
3082                (String::from("bubbles"), Value::Bool(true)),
3083                (String::from("cancelable"), Value::Bool(true)),
3084                (String::from("composed"), Value::Bool(true)),
3085            ],
3086            mouse_ev,
3087        );
3088    }
3089    Ok(Value::Undefined)
3090}
3091
3092/// `element.focus()`(HTML5。丸ごと未対応だった。`document.activeElement`
3093/// と対になる書き込み側。以前は `scrollIntoView` と同じ no-op で
3094/// `document.activeElement` が常に `null` 固定になっていた)。`DomBridge::
3095/// focused_idx` を直接更新し、仕様どおりの順序(旧要素の `blur`/
3096/// `focusout` → 新要素の `focus`/`focusin`)でイベントを発火する。レンダラ側
3097/// の `WebEngine::focused_id`(実クリック/`autofocus` 用の文字列キー版状態)
3098/// との同期は対象外(詳細は `DomBridge::focused_idx` のコメント参照)。
3099pub fn dom_focus(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3100    if let Some(idx) = this_dom_idx(&this) {
3101        let prev = it.dom().borrow().focused_idx;
3102        if prev == Some(idx) {
3103            return Ok(Value::Undefined);
3104        }
3105        let target_val = it.dom_val(idx);
3106        if let Some(p) = prev {
3107            it.dom().borrow_mut().focused_idx = None;
3108            let _ = it.dispatch_event_in_interp(p, "blur", &[
3109                (String::from("bubbles"), Value::Bool(false)),
3110                (String::from("cancelable"), Value::Bool(false)),
3111                (String::from("relatedTarget"), target_val.clone()),
3112            ]);
3113            let _ = it.dispatch_event_in_interp(p, "focusout", &[
3114                (String::from("bubbles"), Value::Bool(true)),
3115                (String::from("cancelable"), Value::Bool(false)),
3116                (String::from("relatedTarget"), target_val),
3117            ]);
3118        }
3119        it.dom().borrow_mut().focused_idx = Some(idx);
3120        let prev_val = prev.map(|p| it.dom_val(p)).unwrap_or(Value::Null);
3121        let _ = it.dispatch_event_in_interp(idx, "focus", &[
3122            (String::from("bubbles"), Value::Bool(false)),
3123            (String::from("cancelable"), Value::Bool(false)),
3124            (String::from("relatedTarget"), prev_val.clone()),
3125        ]);
3126        let _ = it.dispatch_event_in_interp(idx, "focusin", &[
3127            (String::from("bubbles"), Value::Bool(true)),
3128            (String::from("cancelable"), Value::Bool(false)),
3129            (String::from("relatedTarget"), prev_val),
3130        ]);
3131    }
3132    Ok(Value::Undefined)
3133}
3134/// `element.blur()`(HTML5。丸ごと未対応だった。`dom_focus` の対)。自身が
3135/// 現在のフォーカス対象である場合のみ解除して `blur`/`focusout` を発火する
3136/// (仕様どおり、フォーカスされていない要素での `.blur()` は no-op)。
3137pub fn dom_blur(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3138    if let Some(idx) = this_dom_idx(&this) {
3139        let is_focused = it.dom().borrow().focused_idx == Some(idx);
3140        if is_focused {
3141            it.dom().borrow_mut().focused_idx = None;
3142            let _ = it.dispatch_event_in_interp(idx, "blur", &[
3143                (String::from("bubbles"), Value::Bool(false)),
3144                (String::from("cancelable"), Value::Bool(false)),
3145                (String::from("relatedTarget"), Value::Null),
3146            ]);
3147            let _ = it.dispatch_event_in_interp(idx, "focusout", &[
3148                (String::from("bubbles"), Value::Bool(true)),
3149                (String::from("cancelable"), Value::Bool(false)),
3150                (String::from("relatedTarget"), Value::Null),
3151            ]);
3152        }
3153    }
3154    Ok(Value::Undefined)
3155}
3156
3157/// 小数点以下の桁数(指数表記なら `None`)。
3158fn decimals_of(s: &str) -> Option<usize> {
3159    let t = s.trim();
3160    if t.contains(['e', 'E']) {
3161        return None;
3162    }
3163    Some(t.split_once('.').map(|(_, f)| f.len()).unwrap_or(0))
3164}
3165
3166/// `input.stepUp(n?)`/`.stepDown(n?)`(HTML Standard §4.10.5.1「step up/down」)。
3167/// - step が適用されない種類・`step="any"` は `InvalidStateError`。
3168/// - 値が step に合っていないときは、その向きの最も近い合う値まで動かして(1 回分と数える)残りの回数を進める。
3169/// - `min`/`max` の外へ出るなら範囲内の最も近い合う値にし、向きが逆になる(上げたのに下がる等)ときは何もしない。
3170/// - 時刻・日付・月・週・ローカル日時も対象(`form_value.rs` の変換)。
3171pub(crate) fn dom_step_by(it: &mut Interp, this: Value, a: &[Value], sign: f64) -> Result<Value, Value> {
3172    use crate::os_lib::web_apis::form_value as fv;
3173    let Some(idx) = this_dom_idx(&this) else { return Ok(Value::Undefined) };
3174    let (k, value_s, min_s, max_s, step_s, attr_value) = {
3175        let dom = it.dom().borrow();
3176        if dom.nodes.get(idx).map(|n| n.tag != "input").unwrap_or(true) {
3177            return Ok(Value::Undefined);
3178        }
3179        (
3180            dom.input_kind(idx),
3181            dom.input_value(idx),
3182            dom.get_attr(idx, "min"),
3183            dom.get_attr(idx, "max"),
3184            dom.get_attr(idx, "step"),
3185            dom.get_attr(idx, "value"),
3186        )
3187    };
3188    if !fv::has_number_semantics(k) {
3189        return Err(it.dom_exception("InvalidStateError", "stepUp/stepDown: the input type does not support stepping."));
3190    }
3191    let at = fv::Attrs { min: min_s.as_deref(), max: max_s.as_deref(), step: step_s.as_deref(), multiple: false };
3192    let Some(step) = fv::allowed_step(k, at.step) else {
3193        return Err(it.dom_exception("InvalidStateError", "stepUp/stepDown: step is 'any'."));
3194    };
3195    let n = match arg(a, 0) {
3196        Value::Undefined => 1.0,
3197        v => libm::trunc(v.to_number()),
3198    };
3199    let n = if n.is_finite() { n } else { 0.0 };
3200    let min = min_s.as_deref().and_then(|m| fv::string_to_number(k, m));
3201    let max = max_s.as_deref().and_then(|m| fv::string_to_number(k, m));
3202    let base = fv::step_base(k, at.min, attr_value.as_deref());
3203    // 範囲が逆(time を除く)・範囲内に合う値が無いときは何もしない。
3204    if let (Some(mn), Some(mx)) = (min, max) {
3205        if mn > mx && k != fv::Kind::Time {
3206            return Ok(Value::Undefined);
3207        }
3208        let first = base + libm::ceil((mn - base) / step - 1e-9) * step;
3209        if first > mx && k != fv::Kind::Time {
3210            return Ok(Value::Undefined);
3211        }
3212    }
3213    let before = fv::string_to_number(k, &value_s).unwrap_or(0.0);
3214    let q = (before - base) / step;
3215    let on_grid = libm::fabs(q - libm::round(q)) <= 1e-9 * libm::fmax(1.0, libm::fabs(q));
3216    let mut v = if on_grid {
3217        base + (libm::round(q) + sign * n) * step
3218    } else if sign > 0.0 {
3219        base + (libm::floor(q) + n) * step
3220    } else {
3221        base + (libm::ceil(q) - n) * step
3222    };
3223    if let Some(mn) = min {
3224        if v < mn {
3225            v = base + libm::ceil((mn - base) / step - 1e-9) * step;
3226        }
3227    }
3228    if let Some(mx) = max {
3229        if v > mx {
3230            v = base + libm::floor((mx - base) / step + 1e-9) * step;
3231        }
3232    }
3233    if (sign < 0.0 && v > before) || (sign > 0.0 && v < before) {
3234        return Ok(Value::Undefined);
3235    }
3236    // 小数の丸め誤差(0.1 + 0.2)を、入力に現れる桁数で丸めて消す。
3237    if matches!(k, fv::Kind::Number | fv::Kind::Range) {
3238        let digits = [Some(value_s.as_str()), step_s.as_deref(), min_s.as_deref()]
3239            .iter()
3240            .filter_map(|x| x.and_then(decimals_of))
3241            .max()
3242            .unwrap_or(0)
3243            .min(12);
3244        let f = libm::pow(10.0, digits as f64);
3245        v = libm::round(v * f) / f;
3246    }
3247    if let Some(sv) = fv::number_to_value_string(k, v) {
3248        it.dom().borrow_mut().set_input_value(idx, &sv);
3249    }
3250    Ok(Value::Undefined)
3251}
3252pub fn dom_step_up(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3253    dom_step_by(it, this, a, 1.0)
3254}
3255pub fn dom_step_down(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3256    dom_step_by(it, this, a, -1.0)
3257}
3258
3259/// `form.requestSubmit(submitter?)`(HTML5)が丸ごと未対応だった。既存の
3260/// `dom_click` と同じ `dispatch_event_in_interp` 経由で `submit` イベントを
3261/// 発火する(`preventDefault()` で中止可能。`submitter` 引数は現状無視)。
3262pub fn dom_request_submit(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3263    if let Some(idx) = this_dom_idx(&this) {
3264        it.dispatch_event_in_interp(idx, "submit", &[]);
3265    }
3266    Ok(Value::Undefined)
3267}
3268
3269/// `node.contains(other)`(DOM 標準。`other` が `node` 自身または子孫かどうか。
3270/// click-outside 判定などで広く使われる)が丸ごと未対応だった。既存の
3271/// `is_ancestor_of()` は「`idx` 自身は含まない」仕様のため、仕様どおり自身も
3272/// 含めるにはここで等価チェックを補う。
3273pub fn dom_contains(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3274    let other = arg(a, 0);
3275    if let (Some(anc), Some(desc)) = (this_dom_idx(&this), this_dom_idx(&other)) {
3276        let contains = anc == desc || it.dom().borrow().is_ancestor_of(anc, desc);
3277        return Ok(Value::Bool(contains));
3278    }
3279    Ok(Value::Bool(false))
3280}
3281
3282/// `node.getRootNode(options)`(DOM標準。`el.getRootNode({composed: true}) === document` や
3283/// `el.getRootNode() === shadowRoot` の判定に使われる)。
3284pub fn dom_get_root_node(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3285    let is_doc = matches!(
3286        &this,
3287        Value::Object(o) if matches!(&o.borrow().kind, ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_DOCUMENT)
3288    );
3289    if is_doc {
3290        return Ok(this);
3291    }
3292    let composed = if let Some(Value::Object(o)) = a.first() {
3293        o.borrow().props.get("composed").map(|v| v.truthy()).unwrap_or(false)
3294    } else {
3295        false
3296    };
3297    if let Some(idx) = this_dom_idx(&this) {
3298        let mut cur = idx;
3299        let mut guard = 0;
3300        let limit = it.dom().borrow().nodes.len() + 64;
3301        loop {
3302            let parent = it.dom().borrow().nodes.get(cur).and_then(|n| n.parent);
3303            match parent {
3304                Some(p) => {
3305                    cur = p;
3306                    guard += 1;
3307                    if guard > limit {
3308                        break;
3309                    }
3310                }
3311                None => {
3312                    if composed {
3313                        if let Some(host) = it.dom().borrow().shadow_tree.get_host_by_root(cur) {
3314                            cur = host;
3315                            guard += 1;
3316                            if guard > limit {
3317                                break;
3318                            }
3319                            continue;
3320                        }
3321                    }
3322                    break;
3323                }
3324            }
3325        }
3326        if cur == 0 {
3327            if let Some(doc) = it.global.borrow().vars.get("document").cloned() {
3328                return Ok(doc);
3329            }
3330        }
3331        return Ok(it.dom_val(cur));
3332    }
3333    if matches!(this, Value::Object(_)) {
3334        if let Ok(parent) = it.get_property(&this, "parentNode") {
3335            if !matches!(parent, Value::Null | Value::Undefined) {
3336                return dom_get_root_node(it, parent, a);
3337            }
3338        }
3339        return Ok(this);
3340    }
3341    Ok(Value::Undefined)
3342}
3343
3344/// `element.checkVisibility()`(DOM 標準。丸ごと未対応だった)。オプション引数
3345/// (`checkOpacity`/`checkVisibilityCSS`/`contentVisibilityAuto` 等)は未対応で
3346/// 常に無視する簡略実装。自身の算出 `visibility` が `hidden`/`collapse` の場合、
3347/// および自身または祖先のいずれかの算出 `display` が `none` の場合に `false` を返す。
3348/// `node.lookupNamespaceURI(prefix)`/`.lookupPrefix(namespace)`/
3349/// `.isDefaultNamespace(namespace)`(丸ごと未対応だった。2026-07-16
3350/// 発見)。この処理系は `*AttributeNS`/`createElementNS` と同じく XML
3351/// 名前空間を一切モデル化していない(`document_create_element_ns` は
3352/// namespace 引数を無視して委譲するのみ)ため、`xmlns`/`xmlns:*` 属性を
3353/// 祖先チェーンから探索する誠実な実装は行わず、常に「名前空間なし」を表す
3354/// 値(`lookupNamespaceURI`/`lookupPrefix` は `null`)を返す簡略実装。
3355/// `isDefaultNamespace(namespace)` は仕様上 `lookupNamespaceURI(null) ===
3356/// namespace` と等価なので、`lookupNamespaceURI` が常に `null` を返す
3357/// このモデルでは `namespace` が `null`/`undefined` の時のみ `true` になる。
3358pub use super::dom_ns::{dom_is_default_namespace, dom_lookup_namespace_uri, dom_lookup_prefix};
3359
3360pub fn dom_check_visibility(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3361    if let Some(idx) = this_dom_idx(&this) {
3362        let visibility = it.dom().borrow().get_computed(idx, "visibility");
3363        if visibility == "hidden" || visibility == "collapse" {
3364            return Ok(Value::Bool(false));
3365        }
3366        let mut cur = idx;
3367        let mut guard = 0;
3368        loop {
3369            if it.dom().borrow().get_computed(cur, "display") == "none" {
3370                return Ok(Value::Bool(false));
3371            }
3372            let parent = it.dom().borrow().nodes.get(cur).and_then(|n| n.parent);
3373            match parent {
3374                Some(p) => {
3375                    cur = p;
3376                    guard += 1;
3377                    if guard > it.dom().borrow().nodes.len() {
3378                        break;
3379                    }
3380                }
3381                None => break,
3382            }
3383        }
3384        return Ok(Value::Bool(true));
3385    }
3386    Ok(Value::Bool(false))
3387}
3388
3389/// `node.compareDocumentPosition(other)`(DOM標準)が丸ごと未対応だった。
3390/// `DomBridge::document_position` にビットマスク計算を委譲する。`other` が DOM ノードで
3391/// なければ仕様上 `TypeError` だが、この処理系では簡略化して disconnected 扱いにする。
3392pub fn dom_compare_document_position(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3393    super::range::compare_position(it, this, a)
3394}
3395
3396/// DOMTokenList.replace(oldToken, newToken)。old があれば new に置換し true、無ければ false。
3397pub fn dom_classlist_replace(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3398    if let Some((idx, attr)) = this_token_list(&this) {
3399        let old = arg(a, 0).to_js_string();
3400        let new = arg(a, 1).to_js_string();
3401        if old.is_empty() || new.is_empty() {
3402            return Err(it.dom_exception("SyntaxError", "The token provided must not be empty."));
3403        }
3404        class_validate(it, &old)?;
3405        class_validate(it, &new)?;
3406        let mut cur = token_list_tokens(it, idx, attr);
3407        let Some(pos) = cur.iter().position(|c| c == &old) else {
3408            return Ok(Value::Bool(false));
3409        };
3410        if cur.contains(&new) && new != old {
3411            // 新しいトークンが既にあるときは、古いほうを消して新しいほうを残す(仕様: 最初に見つけた位置に置き、他を消す)。
3412            let first = cur.iter().position(|c| c == &old || c == &new).unwrap_or(pos);
3413            cur[first] = new.clone();
3414            let mut seen = false;
3415            cur.retain(|c| {
3416                if c == &new {
3417                    if seen { return false; }
3418                    seen = true;
3419                }
3420                c != &old
3421            });
3422        } else {
3423            cur[pos] = new;
3424        }
3425        token_list_write(it, idx, attr, &cur);
3426        return Ok(Value::Bool(true));
3427    }
3428    Ok(Value::Bool(false))
3429}
3430
3431
3432/// `element.remove()`(`ChildNode.remove()`。引数無しで自身を親から取り外す)。
3433/// ただし`<select>`だけは`HTMLSelectElement.remove(index)`という別物の
3434/// オーバーロードを持ち、数値引数が渡された場合は「自身を削除」ではなく
3435/// 「指定インデックスのoptionを削除」という全く異なる意味になる(仕様上の
3436/// 別メソッドがたまたま同名なだけ)。以前はこの区別が無く、`select.remove(1)`
3437/// が常にselect自身を親から削除してしまう(`options`側の削除ではなく)
3438/// バグだった。
3439pub fn dom_remove(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3440    if let Some(idx) = this_dom_idx(&this) {
3441        let is_select = it.dom().borrow().nodes.get(idx).map(|n| n.tag == "select").unwrap_or(false);
3442        if is_select {
3443            if let Some(v) = a.first() {
3444                let n = v.to_number();
3445                if n.is_finite() {
3446                    // 負のインデックスは仕様上 no-op(`as usize` は負の f64 を 0 へ
3447                    // 飽和させてしまい、`remove(-1)` が誤って先頭optionを削除する
3448                    // バグになるため明示的に弾く)。
3449                    if n >= 0.0 {
3450                        let options = it.dom().borrow().select_options(idx);
3451                        if let Some(&opt) = options.get(n as usize) {
3452                            it.dom().borrow_mut().remove_child(idx, opt);
3453                        }
3454                    }
3455                    return Ok(Value::Undefined);
3456                }
3457            }
3458        }
3459        it.dom().borrow_mut().remove_node(idx);
3460    }
3461    Ok(Value::Undefined)
3462}
3463
3464fn this_html_collection_id(this: &Value) -> Option<usize> {
3465    match this {
3466        Value::Object(o) => match &o.borrow().kind {
3467            ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_HTMLCOLLECTION => Some(h.id),
3468            _ => None,
3469        },
3470        _ => None,
3471    }
3472}
3473
3474/// `HTMLCollection.prototype.length` getter(DOM Standard §4.2.1)。
3475pub fn html_collection_length(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3476    let Some(col_id) = this_html_collection_id(&this) else {
3477        return Err(it.type_error("Illegal invocation"));
3478    };
3479    let len = it.dom().borrow().html_collection_items(col_id).len();
3480    Ok(Value::Number(len as f64))
3481}
3482
3483/// `HTMLCollection.prototype.item(index)`(DOM Standard §4.2.1)。
3484pub fn html_collection_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3485    let n = arg(a, 0).to_number();
3486    let idx = if n.is_finite() && n.abs() < 9_007_199_254_740_992.0 {
3487        (n as i64).rem_euclid(4_294_967_296) as usize
3488    } else {
3489        0
3490    };
3491    if let Some(col_id) = this_html_collection_id(&this) {
3492        let item = it.dom().borrow().html_collection_items(col_id).get(idx).copied();
3493        return Ok(item.map(|i| it.dom_val(i)).unwrap_or(Value::Null));
3494    }
3495    if let Value::Object(o) = &this {
3496        let borrow = o.borrow();
3497        if let ObjKind::Array(ref vec) = borrow.kind {
3498            if let Some(val) = vec.get(idx) {
3499                return Ok(val.clone());
3500            }
3501            return Ok(Value::Null);
3502        }
3503    }
3504    Err(it.type_error("Illegal invocation"))
3505}
3506
3507/// `HTMLCollection.prototype.namedItem(name)`(DOM Standard §4.2.1 / HTML Standard §4.10.21)。
3508/// 同名/同IDのコントロールが複数ある場合は `RadioNodeList` を返す(Array 版の `form.elements` 用)。
3509pub fn html_collection_named_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3510    let target = arg(a, 0).to_js_string();
3511    if let Some(col_id) = this_html_collection_id(&this) {
3512        let item = it.dom().borrow().html_collection_named_item(col_id, &target);
3513        return Ok(item.map(|i| it.dom_val(i)).unwrap_or(Value::Null));
3514    }
3515    if let Value::Object(o) = &this {
3516        if !target.is_empty() {
3517            let borrow = o.borrow();
3518            if let ObjKind::Array(ref vec) = borrow.kind {
3519                let dom = it.dom().borrow();
3520                let mut matches: Vec<Value> = Vec::new();
3521                let mut match_indices: Vec<usize> = Vec::new();
3522                for val in vec {
3523                    if let Value::Object(item_obj) = val {
3524                        if let Some(elem_idx) = item_obj.borrow().kind.dom_node() {
3525                            let id_match = dom.get_attr(elem_idx, "id").map(|id| id == target).unwrap_or(false);
3526                            let name_match = dom.get_attr(elem_idx, "name").map(|name| name == target).unwrap_or(false);
3527                            if id_match || name_match {
3528                                matches.push(val.clone());
3529                                match_indices.push(elem_idx);
3530                            }
3531                        }
3532                    }
3533                }
3534                if matches.len() == 1 {
3535                    return Ok(matches[0].clone());
3536                } else if matches.len() > 1 {
3537                    return Ok(make_radio_node_list(it, match_indices));
3538                }
3539            }
3540        }
3541        return Ok(Value::Null);
3542    }
3543    Err(it.type_error("Illegal invocation"))
3544}
3545
3546/// `HTMLCollection.prototype[Symbol.iterator]`。
3547pub fn html_collection_iterator(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3548    let Some(col_id) = this_html_collection_id(&this) else {
3549        return Err(it.type_error("Illegal invocation"));
3550    };
3551    let items: Vec<Value> = it
3552        .dom()
3553        .borrow()
3554        .html_collection_items(col_id)
3555        .into_iter()
3556        .map(|i| it.dom_val(i))
3557        .collect();
3558    let arr = Value::Object(Obj::array(items));
3559    let iter_fn = it.get_property(&arr, "Symbol(Symbol.iterator)")?;
3560    it.call_value(&iter_fn, arr, &[])
3561}
3562
3563/// 生きている `HTMLCollection`(`HOST_HTMLCOLLECTION`)を生成する。
3564pub fn make_live_html_collection(
3565    it: &Interp,
3566    kind: crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind,
3567) -> Value {
3568    let col_id = it.dom().borrow_mut().new_html_collection(kind);
3569    Value::Object(Obj::dom_host(crate::os_lib::web_apis::dom_bridge::HOST_HTMLCOLLECTION, col_id))
3570}
3571
3572fn this_node_list_id(this: &Value) -> Option<usize> {
3573    match this {
3574        Value::Object(o) => match &o.borrow().kind {
3575            ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_NODELIST => Some(h.id),
3576            _ => None,
3577        },
3578        _ => None,
3579    }
3580}
3581
3582fn this_static_node_list_id(this: &Value) -> Option<usize> {
3583    match this {
3584        Value::Object(o) => match &o.borrow().kind {
3585            ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_STATIC_NODELIST => Some(h.id),
3586            _ => None,
3587        },
3588        _ => None,
3589    }
3590}
3591
3592/// 静的 `NodeList`(配列オブジェクトに `NodeList.prototype` を継承させる高速表現)を生成する。
3593pub fn make_static_node_list(it: &Interp, items: Vec<usize>) -> Value {
3594    let vals: Vec<Value> = items.into_iter().map(|i| it.dom_val(i)).collect();
3595    let arr = Obj::array(vals);
3596    if let Some(Value::Object(c)) = it.global.borrow().vars.get("NodeList") {
3597        if let Some(Value::Object(p)) = c.borrow().props.get("prototype") {
3598            arr.borrow_mut().proto = Some(p.clone());
3599        }
3600    }
3601    Value::Object(arr)
3602}
3603
3604/// `NodeList.prototype.length` getter。
3605pub fn node_list_length(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3606    if let Some(id) = this_node_list_id(&this) {
3607        let len = it.dom().borrow().node_list_items(id).len();
3608        return Ok(Value::Number(len as f64));
3609    }
3610    if let Some(id) = this_static_node_list_id(&this) {
3611        let len = it.dom().borrow().static_node_list_items(id).len();
3612        return Ok(Value::Number(len as f64));
3613    }
3614    if let Value::Object(o) = &this {
3615        let b = o.borrow();
3616        if let Some(Value::Number(len)) = b.props.get("Symbol(staticNodeListLength)") {
3617            return Ok(Value::Number(*len));
3618        }
3619        if let ObjKind::Array(ref vec) = b.kind {
3620            return Ok(Value::Number(vec.len() as f64));
3621        }
3622    }
3623    Err(it.type_error("Illegal invocation"))
3624}
3625
3626/// `NodeList.prototype.item(index)`。
3627pub fn node_list_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3628    let n = arg(a, 0).to_number();
3629    let idx = if n.is_finite() && n.abs() < 9_007_199_254_740_992.0 {
3630        (n as i64).rem_euclid(4_294_967_296) as usize
3631    } else {
3632        0
3633    };
3634    if let Some(id) = this_node_list_id(&this) {
3635        let item = it.dom().borrow().node_list_items(id).get(idx).copied();
3636        return Ok(item.map(|i| it.dom_val(i)).unwrap_or(Value::Null));
3637    }
3638    if let Some(id) = this_static_node_list_id(&this) {
3639        let item = it.dom().borrow().static_node_list_items(id).get(idx).copied();
3640        return Ok(item.map(|i| it.dom_val(i)).unwrap_or(Value::Null));
3641    }
3642    if let Value::Object(o) = &this {
3643        let b = o.borrow();
3644        if let Some(Value::Number(len)) = b.props.get("Symbol(staticNodeListLength)") {
3645            if idx < *len as usize {
3646                if let Some(v) = b.props.get(&idx.to_string()) {
3647                    return Ok(v.clone());
3648                }
3649            }
3650            return Ok(Value::Null);
3651        }
3652        if let ObjKind::Array(ref vec) = b.kind {
3653            return Ok(vec.get(idx).cloned().unwrap_or(Value::Null));
3654        }
3655    }
3656    Err(it.type_error("Illegal invocation"))
3657}
3658
3659fn node_list_items_vec(it: &Interp, this: &Value) -> Result<Vec<Value>, Value> {
3660    if let Some(id) = this_node_list_id(this) {
3661        return Ok(it
3662            .dom()
3663            .borrow()
3664            .node_list_items(id)
3665            .into_iter()
3666            .map(|i| it.dom_val(i))
3667            .collect());
3668    }
3669    if let Some(id) = this_static_node_list_id(this) {
3670        let ids: Vec<usize> = it.dom().borrow().static_node_list_items(id).to_vec();
3671        return Ok(ids.into_iter().map(|i| it.dom_val(i)).collect());
3672    }
3673    if let Value::Object(o) = this {
3674        let b = o.borrow();
3675        if let Some(Value::Number(len)) = b.props.get("Symbol(staticNodeListLength)") {
3676            let n = *len as usize;
3677            let mut out = Vec::with_capacity(n);
3678            for i in 0..n {
3679                out.push(b.props.get(&i.to_string()).cloned().unwrap_or(Value::Undefined));
3680            }
3681            return Ok(out);
3682        }
3683        if let ObjKind::Array(ref vec) = b.kind {
3684            return Ok(vec.clone());
3685        }
3686    }
3687    Err(it.type_error("Illegal invocation"))
3688}
3689
3690pub fn node_list_for_each(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
3691    let cb = arg(a, 0);
3692    let this_arg = a.get(1).cloned().unwrap_or(Value::Undefined);
3693    let items = node_list_items_vec(it, &this)?;
3694    for (idx, val) in items.into_iter().enumerate() {
3695        it.call_value(&cb, this_arg.clone(), &[val, Value::Number(idx as f64), this.clone()])?;
3696    }
3697    Ok(Value::Undefined)
3698}
3699
3700pub fn node_list_values(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3701    let items = node_list_items_vec(it, &this)?;
3702    let arr = Value::Object(Obj::array(items));
3703    let iter_fn = it.get_property(&arr, "Symbol(Symbol.iterator)")?;
3704    it.call_value(&iter_fn, arr, &[])
3705}
3706
3707pub fn node_list_keys(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3708    let items = node_list_items_vec(it, &this)?;
3709    let keys: Vec<Value> = (0..items.len()).map(|i| Value::Number(i as f64)).collect();
3710    let arr = Value::Object(Obj::array(keys));
3711    let iter_fn = it.get_property(&arr, "Symbol(Symbol.iterator)")?;
3712    it.call_value(&iter_fn, arr, &[])
3713}
3714
3715pub fn node_list_entries(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
3716    let items = node_list_items_vec(it, &this)?;
3717    let entries: Vec<Value> = items
3718        .into_iter()
3719        .enumerate()
3720        .map(|(i, v)| Value::Object(Obj::array(alloc::vec![Value::Number(i as f64), v])))
3721        .collect();
3722    let arr = Value::Object(Obj::array(entries));
3723    let iter_fn = it.get_property(&arr, "Symbol(Symbol.iterator)")?;
3724    it.call_value(&iter_fn, arr, &[])
3725}
3726
3727/// `RadioNodeList` オブジェクトを生成するヘルパー(HTML Standard §4.10.21.1)。
3728/// 配列構造に加え `.value` (getter/setter) アクセスおよび `item(index)` メソッドをサポートする。
3729pub fn make_radio_node_list(it: &Interp, elements: Vec<usize>) -> Value {
3730    let mut arr: Vec<Value> = Vec::with_capacity(elements.len());
3731    for &idx in &elements {
3732        arr.push(it.dom_val(idx));
3733    }
3734    let obj = Obj::array(arr);
3735    obj.borrow_mut().props.insert("_is_radio_nodelist".into(), Value::Bool(true));
3736    obj.borrow_mut().props.insert("item".into(), nv("item", html_collection_item));
3737    Value::Object(obj)
3738}
3739
3740/// `HTMLCollection` / `HTMLFormControlsCollection` オブジェクトを生成するヘルパー。
3741/// 配列機能に加え、DOM Standard §4.2.1 に準拠して `item(index)` および
3742/// `namedItem(name)` メソッドを持つ。
3743pub fn make_html_collection(it: &Interp, elements: Vec<usize>) -> Value {
3744    let mut arr: Vec<Value> = Vec::with_capacity(elements.len());
3745    for &idx in &elements {
3746        arr.push(it.dom_val(idx));
3747    }
3748    let obj = Obj::array(arr);
3749    obj.borrow_mut().props.insert("item".into(), nv("item", html_collection_item));
3750    obj.borrow_mut().props.insert("namedItem".into(), nv("namedItem", html_collection_named_item));
3751    Value::Object(obj)
3752}
3753
3754/// `DOMParser.prototype.parseFromString(str, type)` (DOM Parsing and Serialization §4.1)。
3755/// 入力された文字列を指定された MIME タイプ(text/html, text/xml, application/xml, image/svg+xml 等)でパースし、
3756/// 独立した Document(主文書以外の文書。`#document` ノード、`dom_doc.rs`)を返す。XML エラー時は `<parsererror>` 要素を持つ文書。
3757/// 【2026-11-20】HTML は仕様どおりの木(`parse_html_document`。補った `head`/`body`・DOCTYPE・コメントを残す)で作る。
3758pub fn dom_parser_parse_from_string(it: &mut Interp, _this: Value, args: &[Value]) -> Result<Value, Value> {
3759    let raw_input = args.first().map(|v| v.to_js_string()).unwrap_or_default();
3760    let mime = args.get(1).map(|v| v.to_js_string()).unwrap_or_default();
3761    let mime_type = crate::os_lib::xml_parser::parse_mime_type(&mime);
3762    if mime_type == crate::os_lib::xml_parser::SupportedMimeType::Unsupported {
3763        return Err(it.type_error("Failed to execute 'parseFromString' on 'DOMParser': The provided value '".to_string() + &mime + "' is not a valid enum value of type DOMParserSupportedType."));
3764    }
3765    use crate::os_lib::xml_parser::SupportedMimeType as M;
3766    let is_html = mime_type == M::Html;
3767    let top: Vec<crate::os_lib::dom::Node> = match mime_type {
3768        M::Html => crate::os_lib::dom::parse_html_document(&raw_input).children,
3769        M::Xml | M::Svg | M::Xhtml => parse_xml_document_nodes(&raw_input),
3770        M::Unsupported => Vec::new(),
3771    };
3772    let ctype = match mime_type {
3773        M::Html => "text/html",
3774        M::Xml => {
3775            let base = mime.split(';').next().unwrap_or("").trim();
3776            if base.eq_ignore_ascii_case("application/xml") {
3777                "application/xml"
3778            } else {
3779                "text/xml"
3780            }
3781        }
3782        M::Svg => "image/svg+xml",
3783        _ => "application/xhtml+xml",
3784    };
3785    let doc_url = super::location_href(&it.global)
3786        .filter(|s| !s.is_empty())
3787        .unwrap_or_else(|| it.base_url.clone());
3788    let d = {
3789        let mut dom = it.dom().borrow_mut();
3790        let d = dom.create_document_node(ctype, is_html);
3791        if let Some(n) = dom.nodes.get_mut(d) {
3792            if !doc_url.is_empty() {
3793                n.attrs.insert(String::from("_url"), doc_url);
3794            }
3795            if !is_html {
3796                n.attrs.insert(String::from("_xmldoc"), String::from("1"));
3797            }
3798        }
3799        for node in &top {
3800            let i = dom.import_node(node);
3801            dom.set_owner_subtree(i, Some(d));
3802            if !is_html {
3803                dom.mark_subtree_xml(i);
3804            }
3805            dom.append_child(d, i);
3806        }
3807        d
3808    };
3809    Ok(it.dom_val(d))
3810}
3811
3812/// DOMParser 用 XML 文書パーサ。`<?xml ...?>` 宣言以外の `<?target data?>` 処理命令やコメントを
3813/// ルートの前後および要素内にそのまま `#pi` / `#comment` ノードとして保持し、構文エラー時は
3814/// 既に読めたトップレベルノード列の後ろに `<parsererror>` を追加して返す。
3815pub(crate) fn parse_xml_document_nodes(input: &str) -> Vec<crate::os_lib::dom::Node> {
3816    use crate::os_lib::dom::{Node, NodeType, COMMENT_TAG};
3817    use crate::os_lib::xml_parser::{create_parsererror_node, XmlError};
3818
3819    fn is_ws(c: char) -> bool {
3820        matches!(c, ' ' | '\t' | '\r' | '\n')
3821    }
3822    fn is_name_char_xml(c: char) -> bool {
3823        !is_ws(c) && !matches!(c, '<' | '>' | '/' | '=' | '"' | '\'' | '?' | '!')
3824    }
3825    fn skip_ws(chars: &[char], pos: &mut usize) {
3826        while *pos < chars.len() && is_ws(chars[*pos]) {
3827            *pos += 1;
3828        }
3829    }
3830    fn read_xml_name(chars: &[char], pos: &mut usize) -> String {
3831        let start = *pos;
3832        while *pos < chars.len() && is_name_char_xml(chars[*pos]) {
3833            *pos += 1;
3834        }
3835        chars[start..*pos].iter().collect()
3836    }
3837    fn matches_at(chars: &[char], pos: usize, pat: &str) -> bool {
3838        let p: Vec<char> = pat.chars().collect();
3839        pos + p.len() <= chars.len() && p.iter().enumerate().all(|(i, &c)| chars[pos + i] == c)
3840    }
3841    fn unescape_xml(s: &str) -> String {
3842        let mut out = String::with_capacity(s.len());
3843        let cs: Vec<char> = s.chars().collect();
3844        let mut i = 0;
3845        while i < cs.len() {
3846            if cs[i] == '&' {
3847                if let Some(semi) = cs[i + 1..].iter().position(|&c| c == ';') {
3848                    let body: String = cs[i + 1..i + 1 + semi].iter().collect();
3849                    let ch = match body.as_str() {
3850                        "lt" => Some('<'),
3851                        "gt" => Some('>'),
3852                        "amp" => Some('&'),
3853                        "quot" => Some('"'),
3854                        "apos" => Some('\''),
3855                        _ if body.starts_with("#x") || body.starts_with("#X") => {
3856                            body.get(2..).and_then(|s| u32::from_str_radix(s, 16).ok()).and_then(char::from_u32)
3857                        }
3858                        _ if body.starts_with('#') => {
3859                            body.get(1..).and_then(|s| s.parse::<u32>().ok()).and_then(char::from_u32)
3860                        }
3861                        _ => None,
3862                    };
3863                    if let Some(c) = ch {
3864                        out.push(c);
3865                        i += semi + 2;
3866                        continue;
3867                    }
3868                }
3869            }
3870            out.push(cs[i]);
3871            i += 1;
3872        }
3873        out
3874    }
3875    fn read_attrs(chars: &[char], pos: &mut usize) -> alloc::collections::BTreeMap<String, String> {
3876        let mut attrs = alloc::collections::BTreeMap::new();
3877        loop {
3878            skip_ws(chars, pos);
3879            if *pos >= chars.len() || chars[*pos] == '>' || chars[*pos] == '/' {
3880                break;
3881            }
3882            let name = read_xml_name(chars, pos);
3883            if name.is_empty() {
3884                break;
3885            }
3886            skip_ws(chars, pos);
3887            let mut val = String::new();
3888            if *pos < chars.len() && chars[*pos] == '=' {
3889                *pos += 1;
3890                skip_ws(chars, pos);
3891                if *pos < chars.len() && (chars[*pos] == '"' || chars[*pos] == '\'') {
3892                    let q = chars[*pos];
3893                    *pos += 1;
3894                    let vs = *pos;
3895                    while *pos < chars.len() && chars[*pos] != q {
3896                        *pos += 1;
3897                    }
3898                    let raw: String = chars[vs..*pos].iter().collect();
3899                    val = unescape_xml(&raw);
3900                    if *pos < chars.len() {
3901                        *pos += 1;
3902                    }
3903                }
3904            }
3905            attrs.insert(name, val);
3906        }
3907        attrs
3908    }
3909    fn make_pi(target: String, data: String) -> Node {
3910        let mut attrs = alloc::collections::BTreeMap::new();
3911        attrs.insert(String::from("_target"), target);
3912        attrs.insert(String::from("data"), data);
3913        Node::new_element_preserve_case(String::from("#pi"), attrs)
3914    }
3915    fn make_comment(data: String) -> Node {
3916        let mut attrs = alloc::collections::BTreeMap::new();
3917        attrs.insert(String::from("data"), data);
3918        Node::new_element_preserve_case(String::from(COMMENT_TAG), attrs)
3919    }
3920
3921    let chars: Vec<char> = input.strip_prefix('\u{FEFF}').unwrap_or(input).chars().collect();
3922    let len = chars.len();
3923    let mut pos = 0usize;
3924    let mut top: Vec<Node> = Vec::new();
3925    let mut stack: Vec<Node> = Vec::new();
3926    let mut ns_stack: Vec<alloc::collections::BTreeMap<String, String>> = Vec::new();
3927    let mut has_root = false;
3928
3929    let mut parse_loop = || -> Result<(), XmlError> {
3930        while pos < len {
3931            if stack.is_empty() {
3932                skip_ws(&chars, &mut pos);
3933                if pos >= len {
3934                    break;
3935                }
3936            }
3937            if chars[pos] == '<' {
3938                if pos + 1 < len && chars[pos + 1] == '?' {
3939                    pos += 2;
3940                    let t_start = pos;
3941                    while pos < len && !is_ws(chars[pos]) && !matches_at(&chars, pos, "?>") {
3942                        pos += 1;
3943                    }
3944                    let target: String = chars[t_start..pos].iter().collect();
3945                    if target.is_empty() {
3946                        return Err(XmlError {
3947                            message: "Empty processing instruction target".to_string(),
3948                            line: 1,
3949                            column: pos,
3950                        });
3951                    }
3952                    if pos < len && is_ws(chars[pos]) {
3953                        skip_ws(&chars, &mut pos);
3954                    }
3955                    let d_start = pos;
3956                    while pos + 1 < len && !(chars[pos] == '?' && chars[pos + 1] == '>') {
3957                        pos += 1;
3958                    }
3959                    if pos + 1 >= len {
3960                        return Err(XmlError {
3961                            message: "Unterminated processing instruction".to_string(),
3962                            line: 1,
3963                            column: pos,
3964                        });
3965                    }
3966                    let data: String = chars[d_start..pos].iter().collect();
3967                    pos += 2;
3968                    if target.eq_ignore_ascii_case("xml") && top.is_empty() && stack.is_empty() && !has_root {
3969                        continue;
3970                    }
3971                    let pi = make_pi(target, data);
3972                    if let Some(parent) = stack.last_mut() {
3973                        parent.children.push(pi);
3974                    } else {
3975                        top.push(pi);
3976                    }
3977                } else if matches_at(&chars, pos, "<!--") {
3978                    pos += 4;
3979                    let c_start = pos;
3980                    while pos + 2 < len && !matches_at(&chars, pos, "-->") {
3981                        pos += 1;
3982                    }
3983                    if pos + 2 >= len {
3984                        return Err(XmlError {
3985                            message: "Unterminated comment".to_string(),
3986                            line: 1,
3987                            column: pos,
3988                        });
3989                    }
3990                    let data: String = chars[c_start..pos].iter().collect();
3991                    pos += 3;
3992                    let cmt = make_comment(data);
3993                    if let Some(parent) = stack.last_mut() {
3994                        parent.children.push(cmt);
3995                    } else {
3996                        top.push(cmt);
3997                    }
3998                } else if matches_at(&chars, pos, "<![CDATA[") {
3999                    if stack.is_empty() {
4000                        return Err(XmlError {
4001                            message: "CDATA section outside root element".to_string(),
4002                            line: 1,
4003                            column: pos,
4004                        });
4005                    }
4006                    pos += 9;
4007                    let cs = pos;
4008                    while pos + 2 < len && !matches_at(&chars, pos, "]]>") {
4009                        pos += 1;
4010                    }
4011                    if pos + 2 >= len {
4012                        return Err(XmlError {
4013                            message: "Unterminated CDATA section".to_string(),
4014                            line: 1,
4015                            column: pos,
4016                        });
4017                    }
4018                    let text: String = chars[cs..pos].iter().collect();
4019                    pos += 3;
4020                    if let Some(parent) = stack.last_mut() {
4021                        parent.children.push(Node::new_text(text));
4022                    }
4023                } else if pos + 1 < len && chars[pos + 1] == '!' {
4024                    // DOCTYPE 宣言等を読み飛ばす
4025                    pos += 2;
4026                    let mut bracket = 0usize;
4027                    let mut quote: Option<char> = None;
4028                    while pos < len {
4029                        let c = chars[pos];
4030                        pos += 1;
4031                        if let Some(q) = quote {
4032                            if c == q {
4033                                quote = None;
4034                            }
4035                        } else if c == '"' || c == '\'' {
4036                            quote = Some(c);
4037                        } else if c == '[' {
4038                            bracket += 1;
4039                        } else if c == ']' && bracket > 0 {
4040                            bracket -= 1;
4041                        } else if c == '>' && bracket == 0 {
4042                            break;
4043                        }
4044                    }
4045                } else if pos + 1 < len && chars[pos + 1] == '/' {
4046                    pos += 2;
4047                    let tag_name = read_xml_name(&chars, &mut pos);
4048                    skip_ws(&chars, &mut pos);
4049                    if pos < len && chars[pos] == '>' {
4050                        pos += 1;
4051                    }
4052                    let Some(mut popped) = stack.pop() else {
4053                        return Err(XmlError {
4054                            message: alloc::format!("Unexpected closing tag </{}> without open tag", tag_name),
4055                            line: 1,
4056                            column: pos,
4057                        });
4058                    };
4059                    let popped_tag = match &popped.node_type {
4060                        NodeType::Element { tag_name: t, attributes, .. } => {
4061                            attributes.get("_qname").cloned().unwrap_or_else(|| t.clone())
4062                        }
4063                        _ => String::new(),
4064                    };
4065                    if popped_tag != tag_name {
4066                        return Err(XmlError {
4067                            message: alloc::format!("Mismatched closing tag: expected </{}>, got </{}>", popped_tag, tag_name),
4068                            line: 1,
4069                            column: pos,
4070                        });
4071                    }
4072                    ns_stack.pop();
4073                    if let Some(parent) = stack.last_mut() {
4074                        parent.children.push(popped);
4075                    } else {
4076                        if has_root {
4077                            return Err(XmlError {
4078                                message: "Multiple root elements in XML document".to_string(),
4079                                line: 1,
4080                                column: pos,
4081                            });
4082                        }
4083                        popped.refresh_dependent_hashes();
4084                        has_root = true;
4085                        top.push(popped);
4086                    }
4087                } else {
4088                    pos += 1;
4089                    let tag_name = read_xml_name(&chars, &mut pos);
4090                    if tag_name.is_empty() {
4091                        return Err(XmlError {
4092                            message: "Invalid empty element name".to_string(),
4093                            line: 1,
4094                            column: pos,
4095                        });
4096                    }
4097                    let mut attrs = read_attrs(&chars, &mut pos);
4098                    skip_ws(&chars, &mut pos);
4099                    let is_self_closing = if pos + 1 < len && chars[pos] == '/' && chars[pos + 1] == '>' {
4100                        pos += 2;
4101                        true
4102                    } else if pos < len && chars[pos] == '>' {
4103                        pos += 1;
4104                        false
4105                    } else {
4106                        return Err(XmlError {
4107                            message: alloc::format!("Unclosed element <{}>", tag_name),
4108                            line: 1,
4109                            column: pos,
4110                        });
4111                    };
4112                    let mut scope = ns_stack.last().cloned().unwrap_or_default();
4113                    for (k, v) in &attrs {
4114                        if k == "xmlns" {
4115                            scope.insert(String::new(), v.clone());
4116                        } else if let Some(p) = k.strip_prefix("xmlns:") {
4117                            scope.insert(p.to_string(), v.clone());
4118                        }
4119                    }
4120                    let local_tag = if let Some((p, l)) = tag_name.split_once(':') {
4121                        attrs.insert(String::from("_qname"), tag_name.clone());
4122                        attrs.insert(String::from("_prefix"), p.to_string());
4123                        if let Some(uri) = scope.get(p) {
4124                            attrs.insert(String::from("_ns"), uri.clone());
4125                        }
4126                        l.to_string()
4127                    } else {
4128                        if let Some(uri) = scope.get("") {
4129                            if !uri.is_empty() {
4130                                attrs.insert(String::from("_ns"), uri.clone());
4131                            }
4132                        }
4133                        tag_name
4134                    };
4135                    let node = Node::new_element_preserve_case(local_tag, attrs);
4136                    if is_self_closing {
4137                        if let Some(parent) = stack.last_mut() {
4138                            parent.children.push(node);
4139                        } else {
4140                            if has_root {
4141                                return Err(XmlError {
4142                                    message: "Multiple root elements in XML document".to_string(),
4143                                    line: 1,
4144                                    column: pos,
4145                                });
4146                            }
4147                            has_root = true;
4148                            top.push(node);
4149                        }
4150                    } else {
4151                        if stack.is_empty() && has_root {
4152                            return Err(XmlError {
4153                                message: "Multiple root elements in XML document".to_string(),
4154                                line: 1,
4155                                column: pos,
4156                            });
4157                        }
4158                        ns_stack.push(scope);
4159                        stack.push(node);
4160                    }
4161                }
4162            } else {
4163                if stack.is_empty() {
4164                    return Err(XmlError {
4165                        message: "Text outside root element in XML document".to_string(),
4166                        line: 1,
4167                        column: pos,
4168                    });
4169                }
4170                let ts = pos;
4171                while pos < len && chars[pos] != '<' {
4172                    pos += 1;
4173                }
4174                let raw: String = chars[ts..pos].iter().collect();
4175                let unescaped = unescape_xml(&raw);
4176                if !unescaped.is_empty() {
4177                    if let Some(parent) = stack.last_mut() {
4178                        parent.children.push(Node::new_text(unescaped));
4179                    }
4180                }
4181            }
4182        }
4183        if let Some(unclosed) = stack.pop() {
4184            let tag = match &unclosed.node_type {
4185                NodeType::Element { tag_name: t, .. } => t.clone(),
4186                _ => String::new(),
4187            };
4188            return Err(XmlError {
4189                message: alloc::format!("Unclosed tag <{}> at end of document", tag),
4190                line: 1,
4191                column: pos,
4192            });
4193        }
4194        if !has_root {
4195            return Err(XmlError {
4196                message: "No root element found in XML document".to_string(),
4197                line: 1,
4198                column: pos,
4199            });
4200        }
4201        Ok(())
4202    };
4203
4204    if let Err(e) = parse_loop() {
4205        top.push(create_parsererror_node(&e));
4206    }
4207    top
4208}
4209
4210/// `DOMParser` コンストラクタ。
4211pub fn dom_parser_ctor(_it: &mut Interp, _this: Value, _args: &[Value]) -> Result<Value, Value> {
4212    let obj = Obj::plain();
4213    obj.borrow_mut().props.insert(
4214        "parseFromString".into(),
4215        nv("parseFromString", dom_parser_parse_from_string),
4216    );
4217    Ok(Value::Object(obj))
4218}
4219
4220/// `form.reset()`(HTML5)の実装。
4221/// フォーム要素配下のすべての `<input>`, `<select>`, `<textarea>` のフォームライブ値を初期状態にリセットする。
4222pub fn dom_form_reset(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
4223    let Some(form_idx) = this_dom_idx(&this) else {
4224        return Ok(Value::Undefined);
4225    };
4226    let child_indices: alloc::vec::Vec<usize> = {
4227        let dom = it.dom().borrow();
4228        let mut list = alloc::vec::Vec::new();
4229        fn collect_descendants(dom: &crate::os_lib::web_apis::dom_bridge::DomBridge, node_idx: usize, out: &mut alloc::vec::Vec<usize>) {
4230            if let Some(node) = dom.nodes.get(node_idx) {
4231                for &child in &node.children {
4232                    out.push(child);
4233                    collect_descendants(dom, child, out);
4234                }
4235            }
4236        }
4237        collect_descendants(&dom, form_idx, &mut list);
4238        list
4239    };
4240
4241    let mut dom = it.dom().borrow_mut();
4242    for idx in child_indices {
4243        let tag = dom.nodes.get(idx).map(|n| n.tag.clone()).unwrap_or_default();
4244        match tag.as_str() {
4245            "input" => {
4246                let ty = dom.get_attr(idx, "type").unwrap_or_default().to_lowercase();
4247                if ty == "checkbox" || ty == "radio" {
4248                    let default_checked = dom.has_attr(idx, "checked");
4249                    dom.set_attr(idx, "_live_checked", if default_checked { "true" } else { "false" });
4250                } else {
4251                    let default_val = dom.get_attr(idx, "value").unwrap_or_default();
4252                    dom.set_attr(idx, "_live_value", &default_val);
4253                }
4254            }
4255            "textarea" => {
4256                let default_val = dom.get_text_content(idx);
4257                dom.set_attr(idx, "_live_value", &default_val);
4258            }
4259            "select" => {
4260                dom.remove_attr(idx, "_live_value");
4261            }
4262            _ => {}
4263        }
4264    }
4265    Ok(Value::Undefined)
4266}
4267
4268/// `<canvas>` 2D context の `measureText(text)` メソッドの実装。
4269pub fn dom_canvas_measure_text(_it: &mut Interp, _this: Value, args: &[Value]) -> Result<Value, Value> {
4270    let text = args.first().map(|v| v.to_js_string()).unwrap_or_default();
4271    let width = (text.len() * 8) as f64;
4272    let obj = Obj::plain();
4273    {
4274        let mut b = obj.borrow_mut();
4275        b.props.insert("width".into(), Value::Number(width));
4276        b.props.insert("actualBoundingBoxAscent".into(), Value::Number(10.0));
4277        b.props.insert("actualBoundingBoxDescent".into(), Value::Number(2.0));
4278        b.props.insert("fontBoundingBoxAscent".into(), Value::Number(10.0));
4279        b.props.insert("fontBoundingBoxDescent".into(), Value::Number(2.0));
4280        b.props.insert("actualBoundingBoxLeft".into(), Value::Number(0.0));
4281        b.props.insert("actualBoundingBoxRight".into(), Value::Number(width));
4282    }
4283    Ok(Value::Object(obj))
4284}
4285
4286/// ImageDataSettings オブジェクトから colorSpace ("srgb" | "display-p3") を取り出す。
4287pub fn parse_image_data_color_space(val: Option<&Value>) -> &'static str {
4288    if let Some(Value::Object(obj)) = val {
4289        let b = obj.borrow();
4290        if let Some(Value::Str(s)) = b.props.get("colorSpace") {
4291            if s.eq_ignore_ascii_case("display-p3") {
4292                return "display-p3";
4293            }
4294        }
4295    }
4296    "srgb"
4297}
4298
4299/// width, height, data, colorSpace を持つ標準 ImageData オブジェクトを構築する。
4300pub fn make_image_data_object(
4301    w: usize,
4302    h: usize,
4303    data_items: alloc::vec::Vec<Value>,
4304    color_space: &str,
4305) -> Value {
4306    let img = Obj::plain();
4307    {
4308        let mut b = img.borrow_mut();
4309        b.props.insert("width".into(), Value::Number(w as f64));
4310        b.props.insert("height".into(), Value::Number(h as f64));
4311        b.props.insert("data".into(), Value::Object(Obj::array(data_items)));
4312        b.props.insert("colorSpace".into(), Value::Str(alloc::rc::Rc::new(color_space.into())));
4313    }
4314    Value::Object(img)
4315}
4316
4317/// `createImageData` は透明(全 0)の新しい `ImageData` を返す(仕様)。
4318///
4319/// 呼出形式:
4320/// 1. `ctx.createImageData(anotherImageData)`
4321/// 2. `ctx.createImageData(width, height, [settings])`
4322pub fn dom_canvas_create_image_data(
4323    _it: &mut Interp,
4324    _this: Value,
4325    args: &[Value],
4326) -> Result<Value, Value> {
4327    // パターン1: 別の ImageData オブジェクトが渡された場合
4328    if let Some(Value::Object(other)) = args.first() {
4329        let b = other.borrow();
4330        if let (Some(w_val), Some(h_val)) = (b.props.get("width"), b.props.get("height")) {
4331            let w = (w_val.to_number().abs() as usize).max(1);
4332            let h = (h_val.to_number().abs() as usize).max(1);
4333            let cs = b
4334                .props
4335                .get("colorSpace")
4336                .map(|v| v.to_js_string())
4337                .unwrap_or_else(|| "srgb".into());
4338            let items = alloc::vec![Value::Number(0.0); w * h * 4];
4339            return Ok(make_image_data_object(w, h, items, &cs));
4340        }
4341    }
4342
4343    // パターン2: width, height, [settings]
4344    let w = args.first().map(|v| v.to_number().abs() as usize).unwrap_or(1).max(1);
4345    let h = args.get(1).map(|v| v.to_number().abs() as usize).unwrap_or(1).max(1);
4346    let cs = parse_image_data_color_space(args.get(2));
4347    let items = alloc::vec![Value::Number(0.0); w * h * 4];
4348    Ok(make_image_data_object(w, h, items, cs))
4349}
4350
4351/// グローバル `ImageData` コンストラクタ (WHATWG HTML ImageData API)。
4352///
4353/// 呼出形式:
4354/// 1. `new ImageData(width, height, [settings])`
4355/// 2. `new ImageData(dataArray, width, [height], [settings])`
4356pub fn dom_image_data_ctor(
4357    _it: &mut Interp,
4358    _this: Value,
4359    args: &[Value],
4360) -> Result<Value, Value> {
4361    if let Some(Value::Object(arr_obj)) = args.first() {
4362        let b = arr_obj.borrow();
4363        if let ObjKind::Array(items) = &b.kind {
4364            let w = args.get(1).map(|v| v.to_number().abs() as usize).unwrap_or(1).max(1);
4365            let h = if let Some(Value::Number(n)) = args.get(2) {
4366                (*n).abs() as usize
4367            } else {
4368                items.len() / (w * 4)
4369            }.max(1);
4370            let settings_arg = if args.len() > 3 { args.get(3) } else { args.get(2) };
4371            let cs = parse_image_data_color_space(settings_arg);
4372            return Ok(make_image_data_object(w, h, items.clone(), cs));
4373        }
4374    }
4375
4376    // width, height, [settings]
4377    let w = args.first().map(|v| v.to_number().abs() as usize).unwrap_or(1).max(1);
4378    let h = args.get(1).map(|v| v.to_number().abs() as usize).unwrap_or(1).max(1);
4379    let cs = parse_image_data_color_space(args.get(2));
4380    let items = alloc::vec![Value::Number(0.0); w * h * 4];
4381    Ok(make_image_data_object(w, h, items, cs))
4382}
4383
4384pub fn dom_canvas_is_point_in_path(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4385    let (subpaths, x, y, rule_str) = if let Some(pid) = args.first().and_then(path2d_id) {
4386        let subpaths = crate::os_lib::canvas2d::get_path2d_subpaths(pid).unwrap_or_default();
4387        let x = canvas_arg_f32(args, 1);
4388        let y = canvas_arg_f32(args, 2);
4389        let rule_str = args.get(3).map(|v| v.to_js_string());
4390        (subpaths, x, y, rule_str)
4391    } else {
4392        let ctx_id = canvas_ctx_id(&this);
4393        let subpaths = ctx_id
4394            .and_then(|id| crate::os_lib::canvas2d::with_context(id, |c| c.path.finish()))
4395            .unwrap_or_default();
4396        let x = canvas_arg_f32(args, 0);
4397        let y = canvas_arg_f32(args, 1);
4398        let rule_str = args.get(2).map(|v| v.to_js_string());
4399        (subpaths, x, y, rule_str)
4400    };
4401
4402    let rule = if rule_str
4403        .as_deref()
4404        .map(|s| s.eq_ignore_ascii_case("evenodd"))
4405        .unwrap_or(false)
4406    {
4407        crate::os_lib::canvas2d::FillRule::EvenOdd
4408    } else {
4409        crate::os_lib::canvas2d::FillRule::NonZero
4410    };
4411
4412    let inside = crate::os_lib::canvas2d::is_point_in_path(&subpaths, x, y, rule);
4413    Ok(Value::Bool(inside))
4414}
4415
4416pub fn dom_canvas_is_point_in_stroke(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4417    let ctx_id = canvas_ctx_id(&this);
4418
4419    let (subpaths, x, y) = if let Some(pid) = args.first().and_then(path2d_id) {
4420        let subpaths = crate::os_lib::canvas2d::get_path2d_subpaths(pid).unwrap_or_default();
4421        let x = canvas_arg_f32(args, 1);
4422        let y = canvas_arg_f32(args, 2);
4423        (subpaths, x, y)
4424    } else {
4425        let subpaths = ctx_id
4426            .and_then(|id| crate::os_lib::canvas2d::with_context(id, |c| c.path.finish()))
4427            .unwrap_or_default();
4428        let x = canvas_arg_f32(args, 0);
4429        let y = canvas_arg_f32(args, 1);
4430        (subpaths, x, y)
4431    };
4432
4433    let inside = if let Some(id) = ctx_id {
4434        crate::os_lib::canvas2d::with_context(id, |c| {
4435            canvas_sync_state(&this, c);
4436            c.is_point_in_stroke(&subpaths, x, y)
4437        })
4438        .unwrap_or(false)
4439    } else {
4440        crate::os_lib::canvas2d::is_point_in_stroke(&subpaths, x, y, 1.0)
4441    };
4442    Ok(Value::Bool(inside))
4443}
4444
4445pub fn dom_canvas_get_transform(it: &mut Interp, this: Value, _args: &[Value]) -> Result<Value, Value> {
4446    let (a, b, c, d, e, f) = canvas_ctx_id(&this)
4447        .and_then(|id| {
4448            crate::os_lib::canvas2d::with_context(id, |ctx| {
4449                (
4450                    ctx.state.transform.a,
4451                    ctx.state.transform.b,
4452                    ctx.state.transform.c,
4453                    ctx.state.transform.d,
4454                    ctx.state.transform.e,
4455                    ctx.state.transform.f,
4456                )
4457            })
4458        })
4459        .unwrap_or((1.0, 0.0, 0.0, 1.0, 0.0, 0.0));
4460
4461    let nums = alloc::vec![
4462        Value::Number(a as f64),
4463        Value::Number(b as f64),
4464        Value::Number(c as f64),
4465        Value::Number(d as f64),
4466        Value::Number(e as f64),
4467        Value::Number(f as f64),
4468    ];
4469    let arr = Value::Object(Obj::array(nums));
4470    dom_matrix_ctor(it, Value::Undefined, &[arr])
4471}
4472
4473pub fn dom_canvas_set_line_dash(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4474    if let Value::Object(o) = &this {
4475        let segs = args.first().cloned().unwrap_or(Value::Undefined);
4476        let items = this_items(&segs);
4477        let mut nums: alloc::vec::Vec<Value> = items.into_iter().map(|v| Value::Number(v.to_number())).collect();
4478        if !nums.len().is_multiple_of(2) {
4479            let dup = nums.clone();
4480            nums.extend(dup);
4481        }
4482        o.borrow_mut().props.insert("_line_dash".into(), Value::Object(Obj::array(nums)));
4483    }
4484    Ok(Value::Undefined)
4485}
4486
4487pub fn dom_canvas_get_line_dash(_it: &mut Interp, this: Value, _args: &[Value]) -> Result<Value, Value> {
4488    if let Value::Object(o) = &this {
4489        if let Some(Value::Object(arr)) = o.borrow().props.get("_line_dash") {
4490            let items = this_items(&Value::Object(arr.clone()));
4491            return Ok(Value::Object(Obj::array(items)));
4492        }
4493    }
4494    Ok(Value::Object(Obj::array(alloc::vec![])))
4495}
4496
4497pub fn dom_canvas_round_rect(it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4498    canvas_round_rect(it, this, args)
4499}
4500
4501/// `<canvas>` 2D context の `reset()` メソッド (WHATWG HTML Standard)。
4502pub fn dom_canvas_reset(_it: &mut Interp, this: Value, _args: &[Value]) -> Result<Value, Value> {
4503    if let Value::Object(ref ctx) = this {
4504        let mut b = ctx.borrow_mut();
4505        b.props.insert("fillStyle".into(), Value::str("#000000"));
4506        b.props.insert("strokeStyle".into(), Value::str("#000000"));
4507        b.props.insert("lineWidth".into(), Value::Number(1.0));
4508        b.props.insert("lineCap".into(), Value::str("butt"));
4509        b.props.insert("lineJoin".into(), Value::str("miter"));
4510        b.props.insert("miterLimit".into(), Value::Number(10.0));
4511        b.props.insert("lineDashOffset".into(), Value::Number(0.0));
4512        b.props.insert("font".into(), Value::str("10px sans-serif"));
4513        b.props.insert("textAlign".into(), Value::str("start"));
4514        b.props.insert("textBaseline".into(), Value::str("alphabetic"));
4515        b.props.insert("globalAlpha".into(), Value::Number(1.0));
4516        b.props.insert("globalCompositeOperation".into(), Value::str("source-over"));
4517        b.props.insert("shadowBlur".into(), Value::Number(0.0));
4518        b.props.insert("shadowColor".into(), Value::str("rgba(0, 0, 0, 0)"));
4519        b.props.insert("shadowOffsetX".into(), Value::Number(0.0));
4520        b.props.insert("shadowOffsetY".into(), Value::Number(0.0));
4521        b.props.insert("imageSmoothingEnabled".into(), Value::Bool(true));
4522        b.props.insert("direction".into(), Value::str("inherit"));
4523        b.props.insert("filter".into(), Value::str("none"));
4524        b.props.shift_remove("_line_dash");
4525    }
4526    Ok(Value::Undefined)
4527}
4528
4529fn dom_matrix_arg_to_matrix(it: &mut Interp, val: &Value) -> Option<crate::os_lib::canvas2d::Matrix> {
4530    if let Value::Object(_) = val {
4531        let a = it.get_property(val, "a").ok().map(|v| v.to_number()).unwrap_or(1.0);
4532        let b = it.get_property(val, "b").ok().map(|v| v.to_number()).unwrap_or(0.0);
4533        let c = it.get_property(val, "c").ok().map(|v| v.to_number()).unwrap_or(0.0);
4534        let d = it.get_property(val, "d").ok().map(|v| v.to_number()).unwrap_or(1.0);
4535        let e = it.get_property(val, "e").ok().map(|v| v.to_number()).unwrap_or(0.0);
4536        let f = it.get_property(val, "f").ok().map(|v| v.to_number()).unwrap_or(0.0);
4537
4538        if a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite() && e.is_finite() && f.is_finite() {
4539            Some(crate::os_lib::canvas2d::Matrix {
4540                a: a as f32,
4541                b: b as f32,
4542                c: c as f32,
4543                d: d as f32,
4544                e: e as f32,
4545                f: f as f32,
4546            })
4547        } else {
4548            None
4549        }
4550    } else {
4551        None
4552    }
4553}
4554
4555pub fn dom_path2d_add_path(it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4556    if let Some(id) = path2d_id(&this) {
4557        if let Some(src_arg) = args.first() {
4558            if let Some(src_id) = path2d_id(src_arg) {
4559                let transform = args.get(1).and_then(|v| dom_matrix_arg_to_matrix(it, v));
4560                crate::os_lib::canvas2d::add_path_to_path2d(id, src_id, transform.as_ref());
4561            }
4562        }
4563    }
4564    Ok(Value::Undefined)
4565}
4566
4567pub fn dom_path2d_close_path(_it: &mut Interp, this: Value, _args: &[Value]) -> Result<Value, Value> {
4568    if let Some(id) = path2d_id(&this) {
4569        crate::os_lib::canvas2d::with_path2d(id, |p| p.close_path());
4570    }
4571    Ok(Value::Undefined)
4572}
4573
4574pub fn dom_path2d_move_to(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4575    if let Some(id) = path2d_id(&this) {
4576        let (x, y) = (canvas_arg_f32(args, 0), canvas_arg_f32(args, 1));
4577        crate::os_lib::canvas2d::with_path2d(id, |p| p.move_to(&crate::os_lib::canvas2d::Matrix::identity(), x, y));
4578    }
4579    Ok(Value::Undefined)
4580}
4581
4582pub fn dom_path2d_line_to(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4583    if let Some(id) = path2d_id(&this) {
4584        let (x, y) = (canvas_arg_f32(args, 0), canvas_arg_f32(args, 1));
4585        crate::os_lib::canvas2d::with_path2d(id, |p| p.line_to(&crate::os_lib::canvas2d::Matrix::identity(), x, y));
4586    }
4587    Ok(Value::Undefined)
4588}
4589
4590pub fn dom_path2d_arc(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4591    if let Some(id) = path2d_id(&this) {
4592        let (cx, cy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4593        let r = canvas_arg_f32(a, 2);
4594        let start = canvas_arg_f32(a, 3);
4595        let end = canvas_arg_f32(a, 4);
4596        let ccw = a.get(5).map(|v| v.truthy()).unwrap_or(false);
4597        crate::os_lib::canvas2d::with_path2d(id, |p| {
4598            p.arc(&crate::os_lib::canvas2d::Matrix::identity(), cx, cy, r, start, end, ccw);
4599        });
4600    }
4601    Ok(Value::Undefined)
4602}
4603
4604pub fn dom_path2d_arc_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4605    if let Some(id) = path2d_id(&this) {
4606        let (x1, y1) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4607        let (x2, y2) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4608        let radius = canvas_arg_f32(a, 4);
4609        crate::os_lib::canvas2d::with_path2d(id, |p| {
4610            p.arc_to(&crate::os_lib::canvas2d::Matrix::identity(), x1, y1, x2, y2, radius);
4611        });
4612    }
4613    Ok(Value::Undefined)
4614}
4615
4616pub fn dom_path2d_rect(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4617    if let Some(id) = path2d_id(&this) {
4618        let (x, y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4619        let (w, h) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4620        crate::os_lib::canvas2d::with_path2d(id, |p| {
4621            p.rect(&crate::os_lib::canvas2d::Matrix::identity(), x, y, w, h);
4622        });
4623    }
4624    Ok(Value::Undefined)
4625}
4626
4627/// `roundRect` の `radii` 引数をパース・検証する。
4628/// W3C HTML Canvas 2D Context 仕様準拠:
4629/// - 負の半径指定時は `RangeError`
4630/// - 配列長が 0 または 5 以上の時は `RangeError`
4631/// - 1〜4 個の半径は CSS `border-radius` と同様に 4 隅へ補完
4632fn parse_round_rect_radii(it: &Interp, radii_val: Option<&Value>) -> Result<[f32; 4], Value> {
4633    match radii_val {
4634        None | Some(Value::Undefined) => Ok([0.0; 4]),
4635        Some(Value::Object(o)) => {
4636            let b = o.borrow();
4637            if let ObjKind::Array(items) = &b.kind {
4638                if items.is_empty() || items.len() > 4 {
4639                    return Err(set_error_props(
4640                        it,
4641                        Value::Undefined,
4642                        alloc::format!(
4643                            "Failed to execute 'roundRect': 1 to 4 radii expected, got {}",
4644                            items.len()
4645                        ),
4646                        "RangeError",
4647                    ));
4648                }
4649                let mut vals = alloc::vec::Vec::with_capacity(items.len());
4650                for item in items {
4651                    let n = item.to_number();
4652                    let f = if n.is_finite() { n as f32 } else { 0.0 };
4653                    if f < 0.0 {
4654                        return Err(set_error_props(
4655                            it,
4656                            Value::Undefined,
4657                            alloc::format!(
4658                                "Failed to execute 'roundRect': radius must be non-negative, got {f}"
4659                            ),
4660                            "RangeError",
4661                        ));
4662                    }
4663                    vals.push(f);
4664                }
4665                let radii = match vals.len() {
4666                    1 => [vals[0]; 4],
4667                    2 => [vals[0], vals[1], vals[0], vals[1]],
4668                    3 => [vals[0], vals[1], vals[2], vals[1]],
4669                    4 => [vals[0], vals[1], vals[2], vals[3]],
4670                    _ => [0.0; 4],
4671                };
4672                Ok(radii)
4673            } else {
4674                let n = radii_val.map_or(f64::NAN, |v| v.to_number());
4675                let f = if n.is_finite() { n as f32 } else { 0.0 };
4676                if f < 0.0 {
4677                    return Err(set_error_props(
4678                        it,
4679                        Value::Undefined,
4680                        alloc::format!(
4681                            "Failed to execute 'roundRect': radius must be non-negative, got {f}"
4682                        ),
4683                        "RangeError",
4684                    ));
4685                }
4686                Ok([f; 4])
4687            }
4688        }
4689        Some(v) => {
4690            let n = v.to_number();
4691            let f = if n.is_finite() { n as f32 } else { 0.0 };
4692            if f < 0.0 {
4693                return Err(set_error_props(
4694                    it,
4695                    Value::Undefined,
4696                    alloc::format!(
4697                        "Failed to execute 'roundRect': radius must be non-negative, got {f}"
4698                    ),
4699                    "RangeError",
4700                ));
4701            }
4702            Ok([f; 4])
4703        }
4704    }
4705}
4706
4707pub fn dom_path2d_round_rect(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4708    if let Some(id) = path2d_id(&this) {
4709        let (x, y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4710        let (w, h) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4711        let radii = parse_round_rect_radii(it, a.get(4))?;
4712        crate::os_lib::canvas2d::with_path2d(id, |p| {
4713            p.round_rect(&crate::os_lib::canvas2d::Matrix::identity(), x, y, w, h, radii);
4714        });
4715    }
4716    Ok(Value::Undefined)
4717}
4718
4719pub fn dom_path2d_ellipse(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4720    if let Some(id) = path2d_id(&this) {
4721        let (cx, cy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4722        let (rx, ry) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4723        let rot = canvas_arg_f32(a, 4);
4724        let start = canvas_arg_f32(a, 5);
4725        let end = canvas_arg_f32(a, 6);
4726        let ccw = a.get(7).map(|v| v.truthy()).unwrap_or(false);
4727        crate::os_lib::canvas2d::with_path2d(id, |p| {
4728            p.ellipse(&crate::os_lib::canvas2d::Matrix::identity(), cx, cy, rx, ry, rot, start, end, ccw);
4729        });
4730    }
4731    Ok(Value::Undefined)
4732}
4733
4734pub fn dom_path2d_bezier_curve_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4735    if let Some(id) = path2d_id(&this) {
4736        let (c1x, c1y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4737        let (c2x, c2y) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4738        let (x, y) = (canvas_arg_f32(a, 4), canvas_arg_f32(a, 5));
4739        crate::os_lib::canvas2d::with_path2d(id, |p| {
4740            p.bezier_curve_to(&crate::os_lib::canvas2d::Matrix::identity(), c1x, c1y, c2x, c2y, x, y);
4741        });
4742    }
4743    Ok(Value::Undefined)
4744}
4745
4746pub fn dom_path2d_quadratic_curve_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4747    if let Some(id) = path2d_id(&this) {
4748        let (cx, cy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
4749        let (x, y) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
4750        crate::os_lib::canvas2d::with_path2d(id, |p| {
4751            p.quadratic_curve_to(&crate::os_lib::canvas2d::Matrix::identity(), cx, cy, x, y);
4752        });
4753    }
4754    Ok(Value::Undefined)
4755}
4756
4757/// `Path2D` コンストラクタ (WHATWG HTML Canvas 2D Path2D API)。
4758pub fn dom_path2d_ctor(_it: &mut Interp, _this: Value, args: &[Value]) -> Result<Value, Value> {
4759    let p = Obj::plain();
4760    let id = if let Some(arg) = args.first() {
4761        if let Some(src_id) = path2d_id(arg) {
4762            crate::os_lib::canvas2d::clone_path2d(src_id)
4763        } else if let Value::Str(s) = arg {
4764            crate::os_lib::canvas2d::create_path2d(Some(s))
4765        } else if !matches!(arg, Value::Undefined | Value::Null) {
4766            let s = arg.to_js_string();
4767            crate::os_lib::canvas2d::create_path2d(Some(&s))
4768        } else {
4769            crate::os_lib::canvas2d::create_path2d(None)
4770        }
4771    } else {
4772        crate::os_lib::canvas2d::create_path2d(None)
4773    };
4774    {
4775        let mut b = p.borrow_mut();
4776        b.props.insert("_path2d_id".into(), Value::Number(id as f64));
4777        b.props.insert("addPath".into(), nv("addPath", dom_path2d_add_path));
4778        b.props.insert("closePath".into(), nv("closePath", dom_path2d_close_path));
4779        b.props.insert("moveTo".into(), nv("moveTo", dom_path2d_move_to));
4780        b.props.insert("lineTo".into(), nv("lineTo", dom_path2d_line_to));
4781        b.props.insert("arc".into(), nv("arc", dom_path2d_arc));
4782        b.props.insert("arcTo".into(), nv("arcTo", dom_path2d_arc_to));
4783        b.props.insert("rect".into(), nv("rect", dom_path2d_rect));
4784        b.props.insert("roundRect".into(), nv("roundRect", dom_path2d_round_rect));
4785        b.props.insert("ellipse".into(), nv("ellipse", dom_path2d_ellipse));
4786        b.props.insert("bezierCurveTo".into(), nv("bezierCurveTo", dom_path2d_bezier_curve_to));
4787        b.props.insert("quadraticCurveTo".into(), nv("quadraticCurveTo", dom_path2d_quadratic_curve_to));
4788    }
4789    Ok(Value::Object(p))
4790}
4791
4792/// `<canvas>` 2D context の `createLinearGradient(x0, y0, x1, y1)`。
4793pub fn dom_canvas_create_linear_gradient(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
4794    let x0 = canvas_arg_f32(a, 0);
4795    let y0 = canvas_arg_f32(a, 1);
4796    let x1 = canvas_arg_f32(a, 2);
4797    let y1 = canvas_arg_f32(a, 3);
4798    let id = crate::os_lib::canvas2d::create_linear_gradient(x0, y0, x1, y1);
4799    let grad = Obj::plain();
4800    {
4801        let mut b = grad.borrow_mut();
4802        b.props.insert("_gradient_id".into(), Value::Number(id as f64));
4803        b.props.insert("addColorStop".into(), nv("addColorStop", dom_gradient_add_color_stop));
4804    }
4805    Ok(Value::Object(grad))
4806}
4807
4808/// `<canvas>` 2D context の `createRadialGradient(x0, y0, r0, x1, y1, r1)`。
4809pub fn dom_canvas_create_radial_gradient(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
4810    let x0 = canvas_arg_f32(a, 0);
4811    let y0 = canvas_arg_f32(a, 1);
4812    let r0 = canvas_arg_f32(a, 2);
4813    let x1 = canvas_arg_f32(a, 3);
4814    let y1 = canvas_arg_f32(a, 4);
4815    let r1 = canvas_arg_f32(a, 5);
4816    let id = crate::os_lib::canvas2d::create_radial_gradient(x0, y0, r0, x1, y1, r1);
4817    let grad = Obj::plain();
4818    {
4819        let mut b = grad.borrow_mut();
4820        b.props.insert("_gradient_id".into(), Value::Number(id as f64));
4821        b.props.insert("addColorStop".into(), nv("addColorStop", dom_gradient_add_color_stop));
4822    }
4823    Ok(Value::Object(grad))
4824}
4825
4826/// `CanvasGradient.prototype.addColorStop(offset, color)`。
4827pub fn dom_gradient_add_color_stop(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4828    let id = match &this {
4829        Value::Object(o) => {
4830            let b = o.borrow();
4831            b.props.get("_gradient_id").and_then(|v| match v {
4832                Value::Number(n) => Some(*n as u32),
4833                _ => None,
4834            })
4835        }
4836        _ => None,
4837    };
4838    let Some(id) = id else {
4839        return Ok(Value::Undefined);
4840    };
4841    let offset = canvas_arg_f32(a, 0);
4842    let color_str = a.get(1).map(|v| v.to_js_string()).unwrap_or_default();
4843    let color = crate::os_lib::css::parse_color(&color_str).unwrap_or(0xFF00_0000);
4844    crate::os_lib::canvas2d::add_color_stop_to_gradient(id, offset, color);
4845    Ok(Value::Undefined)
4846}
4847
4848/// `<canvas>` 2D context の `createConicGradient(startAngle, x, y)`。
4849pub fn dom_canvas_create_conic_gradient(_it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
4850    let start_angle = canvas_arg_f32(a, 0);
4851    let cx = canvas_arg_f32(a, 1);
4852    let cy = canvas_arg_f32(a, 2);
4853    let id = crate::os_lib::canvas2d::create_conic_gradient(start_angle, cx, cy);
4854    let grad = Obj::plain();
4855    {
4856        let mut b = grad.borrow_mut();
4857        b.props.insert("_gradient_id".into(), Value::Number(id as f64));
4858        b.props.insert("addColorStop".into(), nv("addColorStop", dom_gradient_add_color_stop));
4859    }
4860    Ok(Value::Object(grad))
4861}
4862
4863/// `createPattern` の引数(ImageData, HTMLCanvasElement, HTMLImageElement)からピクセルデータを抽出する。
4864fn extract_pattern_pixels(it: &mut Interp, v: &Value) -> Option<(u32, u32, alloc::vec::Vec<u32>)> {
4865    let Value::Object(o) = v else {
4866        return None;
4867    };
4868
4869    // 1. ImageData か? (width, height, data を持つ)
4870    {
4871        let b = o.borrow();
4872        if let (Some(Value::Number(w_num)), Some(Value::Number(h_num)), Some(Value::Object(data_arr))) =
4873            (b.props.get("width"), b.props.get("height"), b.props.get("data"))
4874        {
4875            let w = *w_num as u32;
4876            let h = *h_num as u32;
4877            if w > 0 && h > 0 {
4878                let ab = data_arr.borrow();
4879                // Uint8ClampedArray(記憶域)も受け付ける。
4880                let items_owned: alloc::vec::Vec<Value> = match &ab.kind {
4881                    ObjKind::Bytes(st) => st.values(),
4882                    _ => alloc::vec::Vec::new(),
4883                };
4884                let items_ref = match &ab.kind {
4885                    ObjKind::Array(items) => Some(items),
4886                    ObjKind::Bytes(_) => Some(&items_owned),
4887                    _ => None,
4888                };
4889                if let Some(items) = items_ref {
4890                    let total = (w * h) as usize;
4891                    let mut pixels = alloc::vec::Vec::with_capacity(total);
4892                    for chunk in items.chunks(4) {
4893                        if chunk.len() == 4 {
4894                            let r = chunk[0].to_number().clamp(0.0, 255.0) as u32;
4895                            let g = chunk[1].to_number().clamp(0.0, 255.0) as u32;
4896                            let b = chunk[2].to_number().clamp(0.0, 255.0) as u32;
4897                            let a = chunk[3].to_number().clamp(0.0, 255.0) as u32;
4898                            pixels.push((a << 24) | (r << 16) | (g << 8) | b);
4899                        } else {
4900                            pixels.push(0);
4901                        }
4902                    }
4903                    if pixels.len() == total {
4904                        return Some((w, h, pixels));
4905                    }
4906                }
4907            }
4908        }
4909    }
4910
4911    // 2. DOM 要素(<img> または <canvas>)か?
4912    let idx = o.borrow().kind.dom_node()?;
4913    let (tag, src, cid) = {
4914        let dom = it.dom().borrow();
4915        let tag = dom.nodes.get(idx).map(|n| n.tag.clone()).unwrap_or_default();
4916        let src = dom.get_attr(idx, "src").unwrap_or_default();
4917        let cid = dom
4918            .get_attr(idx, "_c2d_id")
4919            .and_then(|s| s.parse::<u32>().ok());
4920        (tag, src, cid)
4921    };
4922
4923    if tag == "canvas" {
4924        let id = cid?;
4925        return crate::os_lib::canvas2d::with_context(id, |c| {
4926            let (w, h) = (c.surface.width, c.surface.height);
4927            if w == 0 || h == 0 {
4928                None
4929            } else {
4930                Some((w, h, c.surface.pixels.clone()))
4931            }
4932        }).flatten();
4933    }
4934
4935    if let Some(img) = crate::os_lib::web_engine::shared_image(&src) {
4936        let (w, h) = (img.width, img.height);
4937        if w > 0 && h > 0 {
4938            let mut pixels = alloc::vec::Vec::with_capacity((w * h) as usize);
4939            for chunk in img.rgba.chunks_exact(4) {
4940                let r = chunk[0] as u32;
4941                let g = chunk[1] as u32;
4942                let b = chunk[2] as u32;
4943                let a = chunk[3] as u32;
4944                pixels.push((a << 24) | (r << 16) | (g << 8) | b);
4945            }
4946            return Some((w, h, pixels));
4947        }
4948    }
4949
4950    None
4951}
4952
4953/// `pattern.setTransform(matrix)`。
4954pub fn dom_pattern_set_transform(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
4955    let Value::Object(o) = &this else {
4956        return Ok(Value::Undefined);
4957    };
4958    let pid = match o.borrow().props.get("_pattern_id") {
4959        Some(Value::Number(n)) if *n >= 0.0 => *n as u32,
4960        _ => return Ok(Value::Undefined),
4961    };
4962    let matrix = if let Some(arg) = a.first() {
4963        dom_matrix_arg_to_matrix(it, arg).unwrap_or_else(crate::os_lib::canvas2d::Matrix::identity)
4964    } else {
4965        crate::os_lib::canvas2d::Matrix::identity()
4966    };
4967    crate::os_lib::canvas2d::set_pattern_transform(pid, matrix);
4968    Ok(Value::Undefined)
4969}
4970
4971/// `<canvas>` 2D context の `createPattern(image, repetition)`。
4972pub fn dom_canvas_create_pattern(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
4973    let Some(image_arg) = a.first() else {
4974        return Ok(Value::Null);
4975    };
4976    let Some((w, h, pixels)) = extract_pattern_pixels(it, image_arg) else {
4977        return Ok(Value::Null);
4978    };
4979    let rep_str = a.get(1).map(|v| v.to_js_string()).unwrap_or_else(|| String::from("repeat"));
4980    let repetition = crate::os_lib::canvas2d::parse_repetition(&rep_str);
4981    let id = crate::os_lib::canvas2d::create_pattern(w, h, pixels, repetition);
4982
4983    let pat = Obj::plain();
4984    {
4985        let mut b = pat.borrow_mut();
4986        b.props.insert("_pattern_id".into(), Value::Number(id as f64));
4987        b.props.insert("setTransform".into(), nv("setTransform", dom_pattern_set_transform));
4988    }
4989    Ok(Value::Object(pat))
4990}
4991
4992/// `<canvas>` 要素の `getContext(contextId, options?)` (HTML5 Canvas 2D Context API)。
4993pub fn dom_canvas_get_context(_it: &mut Interp, this: Value, args: &[Value]) -> Result<Value, Value> {
4994    let ctx_type = args.first().map(|v| v.to_js_string()).unwrap_or_default();
4995    if ctx_type.eq_ignore_ascii_case("2d") {
4996        // 面のサイズは `<canvas width height>` 属性から取る。
4997        // 属性が無い場合の既定は仕様どおり 300x150。
4998        // `this` はこの後 props へ move されるので、その前に読む。
4999        let (cw, ch) = match &this {
5000            Value::Object(o) => {
5001                let kind = o.borrow().kind.clone();
5002                if let Some(idx) = kind.dom_node() {
5003                    let d = _it.dom().borrow();
5004                    let w = d
5005                        .get_attr(idx, "width")
5006                        .and_then(|s| s.trim().parse::<u32>().ok())
5007                        .unwrap_or(300);
5008                    let h = d
5009                        .get_attr(idx, "height")
5010                        .and_then(|s| s.trim().parse::<u32>().ok())
5011                        .unwrap_or(150);
5012                    (w, h)
5013                } else {
5014                    (300, 150)
5015                }
5016            }
5017            _ => (300, 150),
5018        };
5019        let c2d_id = crate::os_lib::canvas2d::create_context(cw, ch);
5020        // レイアウト側(`web_engine/layout.rs`)は `StyledNode` しか見ないので、
5021        // id を DOM 属性へ書いて橋渡しする。JS のオブジェクトを直接引かせると
5022        // 層をまたぐ依存になる。
5023        if let (Some(id), Value::Object(o)) = (c2d_id, &this) {
5024            let kind = o.borrow().kind.clone();
5025            if let Some(idx) = kind.dom_node() {
5026                _it.dom()
5027                    .borrow_mut()
5028                    .set_attr(idx, "_c2d_id", &alloc::format!("{}", id));
5029            }
5030        }
5031        let ctx = Obj::plain();
5032        {
5033            let mut b = ctx.borrow_mut();
5034            b.props.insert("canvas".into(), this);
5035            b.props.insert("fillStyle".into(), Value::str("#000000"));
5036            b.props.insert("strokeStyle".into(), Value::str("#000000"));
5037            b.props.insert("lineWidth".into(), Value::Number(1.0));
5038            b.props.insert("lineCap".into(), Value::str("butt"));
5039            b.props.insert("lineJoin".into(), Value::str("miter"));
5040            b.props.insert("miterLimit".into(), Value::Number(10.0));
5041            b.props.insert("lineDashOffset".into(), Value::Number(0.0));
5042            b.props.insert("font".into(), Value::str("10px sans-serif"));
5043            b.props.insert("textAlign".into(), Value::str("start"));
5044            b.props.insert("textBaseline".into(), Value::str("alphabetic"));
5045            b.props.insert("globalAlpha".into(), Value::Number(1.0));
5046            b.props.insert("globalCompositeOperation".into(), Value::str("source-over"));
5047            b.props.insert("shadowBlur".into(), Value::Number(0.0));
5048            b.props.insert("shadowColor".into(), Value::str("rgba(0, 0, 0, 0)"));
5049            b.props.insert("shadowOffsetX".into(), Value::Number(0.0));
5050            b.props.insert("shadowOffsetY".into(), Value::Number(0.0));
5051            b.props.insert("imageSmoothingEnabled".into(), Value::Bool(true));
5052            b.props.insert("direction".into(), Value::str("inherit"));
5053            b.props.insert("filter".into(), Value::str("none"));
5054            // 【2026-09-03】実描画へ接続する。従来これらは全て `dom_noop` で、
5055            // API 表面だけが存在し canvas は一切描画されなかった。
5056            // 幾何・ラスタライズは `os_lib/canvas2d.rs`(試験済み)にあり、
5057            // ここは registry の id を持たせて各メソッドから引くだけにする。
5058            if let Some(id) = c2d_id {
5059                b.props.insert("_c2d_id".into(), Value::Number(id as f64));
5060            }
5061
5062            // 【2026-09-03】実描画へ接続する。
5063            //
5064            // 従来これらは全て `dom_noop` で、API 表面だけが存在し
5065            // canvas は一切描画されなかった。`os_lib/canvas2d.rs` の
5066            // `Canvas2dContext`(試験済み)を registry へ作り、その id を
5067            // `_c2d_id` として持たせて各メソッドから引く。
5068            //
5069            b.props.insert("fillRect".into(), nv("fillRect", canvas_fill_rect));
5070            b.props.insert("strokeRect".into(), nv("strokeRect", canvas_stroke_rect));
5071            b.props.insert("clearRect".into(), nv("clearRect", canvas_clear_rect));
5072
5073            b.props.insert("beginPath".into(), nv("beginPath", canvas_begin_path));
5074            b.props.insert("closePath".into(), nv("closePath", canvas_close_path));
5075            b.props.insert("moveTo".into(), nv("moveTo", canvas_move_to));
5076            b.props.insert("lineTo".into(), nv("lineTo", canvas_line_to));
5077            b.props.insert("arc".into(), nv("arc", canvas_arc));
5078            b.props.insert("arcTo".into(), nv("arcTo", canvas_arc_to));
5079            b.props.insert("bezierCurveTo".into(), nv("bezierCurveTo", canvas_bezier_curve_to));
5080            b.props.insert("quadraticCurveTo".into(), nv("quadraticCurveTo", canvas_quadratic_curve_to));
5081            b.props.insert("ellipse".into(), nv("ellipse", canvas_ellipse));
5082            b.props.insert("rect".into(), nv("rect", canvas_rect));
5083            b.props.insert("roundRect".into(), nv("roundRect", canvas_round_rect));
5084
5085            b.props.insert("fill".into(), nv("fill", canvas_fill));
5086            b.props.insert("stroke".into(), nv("stroke", canvas_stroke));
5087            b.props.insert("clip".into(), nv("clip", canvas_clip));
5088
5089            b.props.insert("fillText".into(), nv("fillText", canvas_fill_text));
5090            b.props.insert("strokeText".into(), nv("strokeText", canvas_stroke_text));
5091            b.props.insert("measureText".into(), nv("measureText", canvas_measure_text));
5092
5093            b.props.insert("drawImage".into(), nv("drawImage", canvas_draw_image));
5094            b.props.insert("getImageData".into(), nv("getImageData", canvas_get_image_data));
5095            b.props.insert("createImageData".into(), nv("createImageData", dom_canvas_create_image_data));
5096            b.props.insert("putImageData".into(), nv("putImageData", canvas_put_image_data));
5097            b.props.insert("isPointInPath".into(), nv("isPointInPath", dom_canvas_is_point_in_path));
5098            b.props.insert("isPointInStroke".into(), nv("isPointInStroke", dom_canvas_is_point_in_stroke));
5099            b.props.insert("getTransform".into(), nv("getTransform", dom_canvas_get_transform));
5100            b.props.insert("setLineDash".into(), nv("setLineDash", dom_canvas_set_line_dash));
5101            b.props.insert("getLineDash".into(), nv("getLineDash", dom_canvas_get_line_dash));
5102            b.props.insert("reset".into(), nv("reset", dom_canvas_reset));
5103
5104            b.props.insert("createLinearGradient".into(), nv("createLinearGradient", dom_canvas_create_linear_gradient));
5105            b.props.insert("createRadialGradient".into(), nv("createRadialGradient", dom_canvas_create_radial_gradient));
5106            b.props.insert("createConicGradient".into(), nv("createConicGradient", dom_canvas_create_conic_gradient));
5107            b.props.insert("createPattern".into(), nv("createPattern", dom_canvas_create_pattern));
5108
5109            b.props.insert("save".into(), nv("save", canvas_save));
5110            b.props.insert("restore".into(), nv("restore", canvas_restore));
5111            b.props.insert("scale".into(), nv("scale", canvas_scale));
5112            b.props.insert("rotate".into(), nv("rotate", canvas_rotate));
5113            b.props.insert("translate".into(), nv("translate", canvas_translate));
5114            b.props.insert("transform".into(), nv("transform", canvas_transform));
5115            b.props.insert("setTransform".into(), nv("setTransform", canvas_set_transform));
5116            b.props.insert("resetTransform".into(), nv("resetTransform", canvas_reset_transform));
5117        }
5118        return Ok(Value::Object(ctx));
5119    }
5120    // webgl/webgl2/bitmaprenderer は未実装なので、ブラウザが対応しない場合と同じく null を返す。
5121    // 【2026-10-17】従来はメソッドの無い空オブジェクトを返しており、機能判定(`ctx && ctx.getExtension(...)`)
5122    // が「対応している」と誤認して落ちていた(YouTube player の `getDebugText`)。
5123    Ok(Value::Null)
5124}
5125
5126/// `<canvas>` 要素の `toDataURL(type, quality)` (HTML5 Canvas)。
5127pub fn dom_canvas_to_data_url(_it: &mut Interp, _this: Value, args: &[Value]) -> Result<Value, Value> {
5128    let mime = args.first().map(|v| v.to_js_string()).unwrap_or_else(|| String::from("image/png"));
5129    let header = if mime.eq_ignore_ascii_case("image/jpeg") {
5130        "data:image/jpeg;base64,"
5131    } else if mime.eq_ignore_ascii_case("image/webp") {
5132        "data:image/webp;base64,"
5133    } else {
5134        "data:image/png;base64,"
5135    };
5136    // 1x1 透明 PNG の最小限データ URL
5137    let dummy_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
5138    Ok(Value::str(alloc::format!("{}{}", header, dummy_base64)))
5139}
5140
5141/// `<canvas>` 要素の `toBlob(callback, type, quality)` (HTML5 Canvas)。
5142pub fn dom_canvas_to_blob(it: &mut Interp, _this: Value, args: &[Value]) -> Result<Value, Value> {
5143    let cb = args.first().cloned().unwrap_or(Value::Undefined);
5144    let mime = args.get(1).map(|v| v.to_js_string()).unwrap_or_else(|| String::from("image/png"));
5145    if matches!(cb, Value::Object(_)) {
5146        let blob = Obj::plain();
5147        {
5148            let mut b = blob.borrow_mut();
5149            b.props.insert("size".into(), Value::Number(68.0));
5150            b.props.insert("type".into(), Value::str(mime));
5151        }
5152        it.call_value(&cb, Value::Undefined, &[Value::Object(blob)])?;
5153    }
5154    Ok(Value::Undefined)
5155}
5156
5157
5158// ───────────── Canvas 2D の実描画(2026-09-03 追加) ─────────────
5159//
5160// これらは以前すべて `dom_noop` に接続されており、API 表面だけが存在して
5161// 一切描画されなかった。幾何とラスタライズは `os_lib/canvas2d.rs`
5162// (純粋モジュール・試験済み)にあり、ここは「JS の値を取り出して
5163// コンテキストへ渡す」薄い層に徹する。
5164
5165/// Path2D オブジェクトから registry の id を取り出す。
5166fn path2d_id(this: &Value) -> Option<u32> {
5167    match this {
5168        Value::Object(o) => match o.borrow().props.get("_path2d_id") {
5169            Some(Value::Number(n)) if *n >= 0.0 => Some(*n as u32),
5170            _ => None,
5171        },
5172        _ => None,
5173    }
5174}
5175
5176/// コンテキストオブジェクトから registry の id を取り出す。
5177fn canvas_ctx_id(this: &Value) -> Option<u32> {
5178    match this {
5179        Value::Object(o) => match o.borrow().props.get("_c2d_id") {
5180            Some(Value::Number(n)) if *n >= 0.0 => Some(*n as u32),
5181            _ => None,
5182        },
5183        _ => None,
5184    }
5185}
5186
5187/// 引数を f32 で取る。非有限値は 0 とみなす(描画系でパニックさせない)。
5188fn canvas_arg_f32(a: &[Value], i: usize) -> f32 {
5189    let v = a.get(i).map(|v| v.to_number()).unwrap_or(0.0);
5190    if v.is_finite() {
5191        v as f32
5192    } else {
5193        0.0
5194    }
5195}
5196
5197/// JS 側のスタイル文字列を ARGB へ解決する。
5198///
5199/// CSS の色解析(`css::parse_color`)をそのまま使う。解釈できない値は
5200/// 仕様上「無視して直前の値を保つ」だが、ここでは不透明な黒へ倒す
5201/// (描かれないより、既定色で描かれた方が原因に気づきやすい)。
5202fn canvas_style_argb(this: &Value, key: &str) -> u32 {
5203    let s = match this {
5204        Value::Object(o) => o
5205            .borrow()
5206            .props
5207            .get(key)
5208            .map(|v| v.to_js_string())
5209            .unwrap_or_default(),
5210        _ => String::new(),
5211    };
5212    crate::os_lib::css::parse_color(&s).unwrap_or(0xFF00_0000)
5213}
5214
5215/// 描画前に、JS 側で書き換えられた状態をコンテキストへ反映する。
5216///
5217/// `fillStyle` 等は JS の素のプロパティなので、代入は検知できない。
5218/// 各描画メソッドの入口で毎回読み直すのが確実。
5219fn canvas_sync_state(this: &Value, ctx: &mut crate::os_lib::canvas2d::Canvas2dContext) {
5220    ctx.state.fill = canvas_style_argb(this, "fillStyle");
5221    ctx.state.stroke = canvas_style_argb(this, "strokeStyle");
5222    if let Value::Object(o) = this {
5223        let b = o.borrow();
5224        if let Some(Value::Number(n)) = b.props.get("globalAlpha") {
5225            if n.is_finite() {
5226                ctx.state.global_alpha = (*n as f32).clamp(0.0, 1.0);
5227            }
5228        }
5229        if let Some(Value::Number(n)) = b.props.get("lineWidth") {
5230            if n.is_finite() && *n > 0.0 {
5231                ctx.state.line_width = *n as f32;
5232            }
5233        }
5234        // 未知の値は無視して既定を保つ(仕様どおり代入を捨てる)。
5235        if let Some(Value::Str(s)) = b.props.get("lineCap") {
5236            if let Some(v) = crate::os_lib::canvas2d::parse_line_cap(s) {
5237                ctx.state.line_cap = v;
5238            }
5239        }
5240        if let Some(Value::Str(s)) = b.props.get("lineJoin") {
5241            if let Some(v) = crate::os_lib::canvas2d::parse_line_join(s) {
5242                ctx.state.line_join = v;
5243            }
5244        }
5245        if let Some(Value::Number(n)) = b.props.get("miterLimit") {
5246            if n.is_finite() && *n > 0.0 {
5247                ctx.state.miter_limit = *n as f32;
5248            }
5249        }
5250        // `setLineDash` が入れた配列。値の検査は `normalize_dash` に任せる
5251        // (不正なパターンはまるごと捨てるのが仕様)。
5252        ctx.state.line_dash.clear();
5253        if let Some(Value::Object(arr)) = b.props.get("_line_dash") {
5254            let ab = arr.borrow();
5255            if let ObjKind::Array(items) = &ab.kind {
5256                for v in items {
5257                    ctx.state.line_dash.push(v.to_number() as f32);
5258                }
5259            }
5260        }
5261        if let Some(Value::Number(n)) = b.props.get("lineDashOffset") {
5262            if n.is_finite() {
5263                ctx.state.line_dash_offset = *n as f32;
5264            }
5265        }
5266        if let Some(Value::Str(s)) = b.props.get("fillStyle") {
5267            ctx.state.fill_str = (**s).clone();
5268            ctx.state.fill_gradient = None;
5269            ctx.state.fill_pattern = None;
5270        } else if let Some(Value::Object(style_obj)) = b.props.get("fillStyle") {
5271            let sb = style_obj.borrow();
5272            if let Some(Value::Number(gid)) = sb.props.get("_gradient_id") {
5273                ctx.state.fill_gradient = crate::os_lib::canvas2d::get_gradient(*gid as u32);
5274                ctx.state.fill_pattern = None;
5275            } else if let Some(Value::Number(pid)) = sb.props.get("_pattern_id") {
5276                ctx.state.fill_pattern = crate::os_lib::canvas2d::get_pattern(*pid as u32);
5277                ctx.state.fill_gradient = None;
5278            } else {
5279                ctx.state.fill_gradient = None;
5280                ctx.state.fill_pattern = None;
5281            }
5282        } else {
5283            ctx.state.fill_gradient = None;
5284            ctx.state.fill_pattern = None;
5285        }
5286        if let Some(Value::Str(s)) = b.props.get("strokeStyle") {
5287            ctx.state.stroke_str = (**s).clone();
5288            ctx.state.stroke_gradient = None;
5289            ctx.state.stroke_pattern = None;
5290        } else if let Some(Value::Object(style_obj)) = b.props.get("strokeStyle") {
5291            let sb = style_obj.borrow();
5292            if let Some(Value::Number(gid)) = sb.props.get("_gradient_id") {
5293                ctx.state.stroke_gradient = crate::os_lib::canvas2d::get_gradient(*gid as u32);
5294                ctx.state.stroke_pattern = None;
5295            } else if let Some(Value::Number(pid)) = sb.props.get("_pattern_id") {
5296                ctx.state.stroke_pattern = crate::os_lib::canvas2d::get_pattern(*pid as u32);
5297                ctx.state.stroke_gradient = None;
5298            } else {
5299                ctx.state.stroke_gradient = None;
5300                ctx.state.stroke_pattern = None;
5301            }
5302        } else {
5303            ctx.state.stroke_gradient = None;
5304            ctx.state.stroke_pattern = None;
5305        }
5306        if let Some(Value::Str(s)) = b.props.get("font") {
5307            ctx.state.font_str = (**s).clone();
5308        }
5309        if let Some(Value::Str(s)) = b.props.get("textAlign") {
5310            ctx.state.text_align_str = (**s).clone();
5311        }
5312        if let Some(Value::Str(s)) = b.props.get("textBaseline") {
5313            ctx.state.text_baseline_str = (**s).clone();
5314        }
5315        if let Some(Value::Bool(sm)) = b.props.get("imageSmoothingEnabled") {
5316            ctx.state.image_smoothing_enabled = *sm;
5317        }
5318        if let Some(Value::Str(s)) = b.props.get("shadowColor") {
5319            ctx.state.shadow_color_str = (**s).clone();
5320            if let Some(c) = crate::os_lib::css::parse_color(s) {
5321                ctx.state.shadow_color = c;
5322            }
5323        }
5324        if let Some(Value::Number(n)) = b.props.get("shadowBlur") {
5325            if n.is_finite() && *n >= 0.0 {
5326                ctx.state.shadow_blur = *n as f32;
5327            }
5328        }
5329        if let Some(Value::Number(n)) = b.props.get("shadowOffsetX") {
5330            if n.is_finite() {
5331                ctx.state.shadow_offset_x = *n as f32;
5332            }
5333        }
5334        if let Some(Value::Number(n)) = b.props.get("shadowOffsetY") {
5335            if n.is_finite() {
5336                ctx.state.shadow_offset_y = *n as f32;
5337            }
5338        }
5339        if let Some(Value::Str(s)) = b.props.get("filter") {
5340            ctx.state.filter = (**s).clone();
5341        }
5342        if let Some(Value::Str(s)) = b.props.get("globalCompositeOperation") {
5343            ctx.state.global_composite_operation_str = (**s).clone();
5344            if let Some(op) = crate::os_lib::canvas2d::parse_composite_operation(s) {
5345                ctx.state.global_composite_operation = op;
5346            }
5347        }
5348        if let Some(Value::Str(s)) = b.props.get("direction") {
5349            if let Some(dir) = crate::os_lib::canvas2d::parse_canvas_direction(s) {
5350                ctx.state.direction = dir;
5351                ctx.state.direction_str = (**s).clone();
5352            }
5353        }
5354    }
5355}
5356
5357pub fn canvas_fill_rect(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5358    if let Some(id) = canvas_ctx_id(&this) {
5359        let (x, y, w, h) = (
5360            canvas_arg_f32(a, 0),
5361            canvas_arg_f32(a, 1),
5362            canvas_arg_f32(a, 2),
5363            canvas_arg_f32(a, 3),
5364        );
5365        crate::os_lib::canvas2d::with_context(id, |c| {
5366            canvas_sync_state(&this, c);
5367            c.fill_rect(x, y, w, h);
5368        });
5369    }
5370    Ok(Value::Undefined)
5371}
5372
5373pub fn canvas_stroke_rect(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5374    if let Some(id) = canvas_ctx_id(&this) {
5375        let (x, y, w, h) = (
5376            canvas_arg_f32(a, 0),
5377            canvas_arg_f32(a, 1),
5378            canvas_arg_f32(a, 2),
5379            canvas_arg_f32(a, 3),
5380        );
5381        crate::os_lib::canvas2d::with_context(id, |c| {
5382            canvas_sync_state(&this, c);
5383            c.stroke_rect(x, y, w, h);
5384        });
5385    }
5386    Ok(Value::Undefined)
5387}
5388
5389pub fn canvas_clear_rect(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5390    if let Some(id) = canvas_ctx_id(&this) {
5391        let (x, y, w, h) = (
5392            canvas_arg_f32(a, 0),
5393            canvas_arg_f32(a, 1),
5394            canvas_arg_f32(a, 2),
5395            canvas_arg_f32(a, 3),
5396        );
5397        crate::os_lib::canvas2d::with_context(id, |c| c.clear_rect(x, y, w, h));
5398    }
5399    Ok(Value::Undefined)
5400}
5401
5402pub fn canvas_begin_path(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
5403    if let Some(id) = canvas_ctx_id(&this) {
5404        crate::os_lib::canvas2d::with_context(id, |c| c.path.begin_path());
5405    }
5406    Ok(Value::Undefined)
5407}
5408
5409pub fn canvas_close_path(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
5410    if let Some(id) = canvas_ctx_id(&this) {
5411        crate::os_lib::canvas2d::with_context(id, |c| c.path.close_path());
5412    }
5413    Ok(Value::Undefined)
5414}
5415
5416pub fn canvas_move_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5417    if let Some(id) = canvas_ctx_id(&this) {
5418        let (x, y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5419        crate::os_lib::canvas2d::with_context(id, |c| {
5420            let m = c.state.transform;
5421            c.path.move_to(&m, x, y);
5422        });
5423    }
5424    Ok(Value::Undefined)
5425}
5426
5427pub fn canvas_line_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5428    if let Some(id) = canvas_ctx_id(&this) {
5429        let (x, y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5430        crate::os_lib::canvas2d::with_context(id, |c| {
5431            let m = c.state.transform;
5432            c.path.line_to(&m, x, y);
5433        });
5434    }
5435    Ok(Value::Undefined)
5436}
5437
5438pub fn canvas_rect(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5439    if let Some(id) = canvas_ctx_id(&this) {
5440        let (x, y, w, h) = (
5441            canvas_arg_f32(a, 0),
5442            canvas_arg_f32(a, 1),
5443            canvas_arg_f32(a, 2),
5444            canvas_arg_f32(a, 3),
5445        );
5446        crate::os_lib::canvas2d::with_context(id, |c| {
5447            let m = c.state.transform;
5448            c.path.rect(&m, x, y, w, h);
5449        });
5450    }
5451    Ok(Value::Undefined)
5452}
5453
5454pub fn canvas_arc(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5455    if let Some(id) = canvas_ctx_id(&this) {
5456        let (cx, cy, r) = (
5457            canvas_arg_f32(a, 0),
5458            canvas_arg_f32(a, 1),
5459            canvas_arg_f32(a, 2),
5460        );
5461        let start = canvas_arg_f32(a, 3);
5462        let end = canvas_arg_f32(a, 4);
5463        let ccw = a.get(5).map(|v| v.truthy()).unwrap_or(false);
5464        crate::os_lib::canvas2d::with_context(id, |c| {
5465            let m = c.state.transform;
5466            c.path.arc(&m, cx, cy, r, start, end, ccw);
5467        });
5468    }
5469    Ok(Value::Undefined)
5470}
5471
5472pub fn canvas_arc_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5473    if let Some(id) = canvas_ctx_id(&this) {
5474        let (x1, y1) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5475        let (x2, y2) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
5476        let radius = canvas_arg_f32(a, 4);
5477        crate::os_lib::canvas2d::with_context(id, |c| {
5478            let m = c.state.transform;
5479            c.path.arc_to(&m, x1, y1, x2, y2, radius);
5480        });
5481    }
5482    Ok(Value::Undefined)
5483}
5484
5485pub fn canvas_fill(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5486    if let Some(id) = canvas_ctx_id(&this) {
5487        if let Some(pid) = a.first().and_then(path2d_id) {
5488            let rule = match a.get(1).map(|v| v.to_js_string()) {
5489                Some(s) if s.eq_ignore_ascii_case("evenodd") => {
5490                    crate::os_lib::canvas2d::FillRule::EvenOdd
5491                }
5492                _ => crate::os_lib::canvas2d::FillRule::NonZero,
5493            };
5494            if let Some(subpaths) = crate::os_lib::canvas2d::get_path2d_subpaths(pid) {
5495                crate::os_lib::canvas2d::with_context(id, |c| {
5496                    canvas_sync_state(&this, c);
5497                    c.fill_subpaths(&subpaths, rule);
5498                });
5499            }
5500        } else {
5501            // 第 1 引数は塗りつぶし規則(省略時は nonzero)。
5502            let rule = match a.first().map(|v| v.to_js_string()) {
5503                Some(s) if s.eq_ignore_ascii_case("evenodd") => {
5504                    crate::os_lib::canvas2d::FillRule::EvenOdd
5505                }
5506                _ => crate::os_lib::canvas2d::FillRule::NonZero,
5507            };
5508            crate::os_lib::canvas2d::with_context(id, |c| {
5509                canvas_sync_state(&this, c);
5510                c.fill(rule);
5511            });
5512        }
5513    }
5514    Ok(Value::Undefined)
5515}
5516
5517pub fn canvas_stroke(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5518    if let Some(id) = canvas_ctx_id(&this) {
5519        if let Some(pid) = a.first().and_then(path2d_id) {
5520            if let Some(subpaths) = crate::os_lib::canvas2d::get_path2d_subpaths(pid) {
5521                crate::os_lib::canvas2d::with_context(id, |c| {
5522                    canvas_sync_state(&this, c);
5523                    c.stroke_subpaths(&subpaths);
5524                });
5525            }
5526        } else {
5527            crate::os_lib::canvas2d::with_context(id, |c| {
5528                canvas_sync_state(&this, c);
5529                // `lineWidth` を反映する(1 以下なら 1px 線の高速路へ落ちる)。
5530                c.stroke_with_width();
5531            });
5532        }
5533    }
5534    Ok(Value::Undefined)
5535}
5536
5537
5538/// `save()` — 現在の描画状態を退避する。
5539pub fn canvas_save(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
5540    if let Some(id) = canvas_ctx_id(&this) {
5541        crate::os_lib::canvas2d::with_context(id, |c| {
5542            // JS 側で書き換えられた状態も含めて退避したいので、
5543            // 先に読み直してから積む。
5544            canvas_sync_state(&this, c);
5545            c.save();
5546        });
5547    }
5548    Ok(Value::Undefined)
5549}
5550
5551/// `restore()` — 直近の退避状態へ戻す。
5552///
5553/// 変換だけでなく `fillStyle` 等も戻すのが仕様だが、それらは JS の素の
5554/// プロパティなので、Rust 側で戻した値を JS へ書き戻す必要がある。
5555pub fn canvas_restore(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
5556    if let Some(id) = canvas_ctx_id(&this) {
5557        let restored = crate::os_lib::canvas2d::with_context(id, |c| {
5558            c.restore();
5559            (
5560                c.state.global_alpha,
5561                c.state.line_width,
5562                c.state.fill_str.clone(),
5563                c.state.stroke_str.clone(),
5564                c.state.font_str.clone(),
5565                c.state.text_align_str.clone(),
5566                c.state.text_baseline_str.clone(),
5567                c.state.miter_limit,
5568                c.state.line_dash_offset,
5569                c.state.line_dash.clone(),
5570                c.state.image_smoothing_enabled,
5571                match c.state.line_cap {
5572                    crate::os_lib::canvas2d::LineCap::Butt => "butt",
5573                    crate::os_lib::canvas2d::LineCap::Round => "round",
5574                    crate::os_lib::canvas2d::LineCap::Square => "square",
5575                },
5576                match c.state.line_join {
5577                    crate::os_lib::canvas2d::LineJoin::Miter => "miter",
5578                    crate::os_lib::canvas2d::LineJoin::Round => "round",
5579                    crate::os_lib::canvas2d::LineJoin::Bevel => "bevel",
5580                },
5581                c.state.shadow_blur,
5582                c.state.shadow_color_str.clone(),
5583                c.state.shadow_offset_x,
5584                c.state.shadow_offset_y,
5585                c.state.filter.clone(),
5586                c.state.global_composite_operation_str.clone(),
5587                c.state.direction_str.clone(),
5588            )
5589        });
5590        if let (Some(r), Value::Object(o)) = (restored, &this) {
5591            let mut b = o.borrow_mut();
5592            b.props.insert("globalAlpha".into(), Value::Number(r.0 as f64));
5593            b.props.insert("lineWidth".into(), Value::Number(r.1 as f64));
5594            b.props.insert("fillStyle".into(), Value::str(&r.2));
5595            b.props.insert("strokeStyle".into(), Value::str(&r.3));
5596            b.props.insert("font".into(), Value::str(&r.4));
5597            b.props.insert("textAlign".into(), Value::str(&r.5));
5598            b.props.insert("textBaseline".into(), Value::str(&r.6));
5599            b.props.insert("miterLimit".into(), Value::Number(r.7 as f64));
5600            b.props.insert("lineDashOffset".into(), Value::Number(r.8 as f64));
5601            b.props.insert("imageSmoothingEnabled".into(), Value::Bool(r.10));
5602            b.props.insert("lineCap".into(), Value::str(r.11));
5603            b.props.insert("lineJoin".into(), Value::str(r.12));
5604            b.props.insert("shadowBlur".into(), Value::Number(r.13 as f64));
5605            b.props.insert("shadowColor".into(), Value::str(&r.14));
5606            b.props.insert("shadowOffsetX".into(), Value::Number(r.15 as f64));
5607            b.props.insert("shadowOffsetY".into(), Value::Number(r.16 as f64));
5608            b.props.insert("filter".into(), Value::str(&r.17));
5609            b.props.insert("globalCompositeOperation".into(), Value::str(&r.18));
5610            b.props.insert("direction".into(), Value::str(&r.19));
5611
5612            let dash_objs = r.9.iter().map(|d| Value::Number(*d as f64)).collect();
5613            b.props.insert("_line_dash".into(), Value::Object(Obj::array(dash_objs)));
5614        }
5615    }
5616    Ok(Value::Undefined)
5617}
5618
5619pub fn canvas_translate(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5620    if let Some(id) = canvas_ctx_id(&this) {
5621        let (tx, ty) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5622        crate::os_lib::canvas2d::with_context(id, |c| c.translate(tx, ty));
5623    }
5624    Ok(Value::Undefined)
5625}
5626
5627pub fn canvas_scale(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5628    if let Some(id) = canvas_ctx_id(&this) {
5629        let (sx, sy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5630        crate::os_lib::canvas2d::with_context(id, |c| c.scale(sx, sy));
5631    }
5632    Ok(Value::Undefined)
5633}
5634
5635pub fn canvas_rotate(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5636    if let Some(id) = canvas_ctx_id(&this) {
5637        let rad = canvas_arg_f32(a, 0);
5638        crate::os_lib::canvas2d::with_context(id, |c| c.rotate(rad));
5639    }
5640    Ok(Value::Undefined)
5641}
5642
5643/// `transform(a,b,c,d,e,f)` — 現在の行列へ右から掛ける。
5644pub fn canvas_transform(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5645    if let Some(id) = canvas_ctx_id(&this) {
5646        let m = crate::os_lib::canvas2d::Matrix {
5647            a: canvas_arg_f32(a, 0),
5648            b: canvas_arg_f32(a, 1),
5649            c: canvas_arg_f32(a, 2),
5650            d: canvas_arg_f32(a, 3),
5651            e: canvas_arg_f32(a, 4),
5652            f: canvas_arg_f32(a, 5),
5653        };
5654        crate::os_lib::canvas2d::with_context(id, |ctx| {
5655            let cur = ctx.state.transform;
5656            ctx.set_transform(cur.multiply(&m));
5657        });
5658    }
5659    Ok(Value::Undefined)
5660}
5661
5662/// `setTransform(a,b,c,d,e,f)` — 行列を置き換える(積まない)。
5663pub fn canvas_set_transform(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5664    if let Some(id) = canvas_ctx_id(&this) {
5665        let m = crate::os_lib::canvas2d::Matrix {
5666            a: canvas_arg_f32(a, 0),
5667            b: canvas_arg_f32(a, 1),
5668            c: canvas_arg_f32(a, 2),
5669            d: canvas_arg_f32(a, 3),
5670            e: canvas_arg_f32(a, 4),
5671            f: canvas_arg_f32(a, 5),
5672        };
5673        crate::os_lib::canvas2d::with_context(id, |ctx| ctx.set_transform(m));
5674    }
5675    Ok(Value::Undefined)
5676}
5677
5678pub fn canvas_reset_transform(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
5679    if let Some(id) = canvas_ctx_id(&this) {
5680        crate::os_lib::canvas2d::with_context(id, |c| c.reset_transform());
5681    }
5682    Ok(Value::Undefined)
5683}
5684
5685pub fn canvas_bezier_curve_to(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5686    if let Some(id) = canvas_ctx_id(&this) {
5687        let (c1x, c1y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5688        let (c2x, c2y) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
5689        let (x, y) = (canvas_arg_f32(a, 4), canvas_arg_f32(a, 5));
5690        crate::os_lib::canvas2d::with_context(id, |c| {
5691            let m = c.state.transform;
5692            c.path.bezier_curve_to(&m, c1x, c1y, c2x, c2y, x, y);
5693        });
5694    }
5695    Ok(Value::Undefined)
5696}
5697
5698pub fn canvas_quadratic_curve_to(
5699    _it: &mut Interp,
5700    this: Value,
5701    a: &[Value],
5702) -> Result<Value, Value> {
5703    if let Some(id) = canvas_ctx_id(&this) {
5704        let (cx, cy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5705        let (x, y) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
5706        crate::os_lib::canvas2d::with_context(id, |c| {
5707            let m = c.state.transform;
5708            c.path.quadratic_curve_to(&m, cx, cy, x, y);
5709        });
5710    }
5711    Ok(Value::Undefined)
5712}
5713
5714
5715/// `ellipse(cx, cy, rx, ry, rotation, start, end, anticlockwise)`。
5716pub fn canvas_ellipse(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5717    if let Some(id) = canvas_ctx_id(&this) {
5718        let (cx, cy) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5719        let (rx, ry) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
5720        let rot = canvas_arg_f32(a, 4);
5721        let start = canvas_arg_f32(a, 5);
5722        let end = canvas_arg_f32(a, 6);
5723        let ccw = a.get(7).map(|v| v.truthy()).unwrap_or(false);
5724        crate::os_lib::canvas2d::with_context(id, |c| {
5725            let m = c.state.transform;
5726            c.path.ellipse(&m, cx, cy, rx, ry, rot, start, end, ccw);
5727        });
5728    }
5729    Ok(Value::Undefined)
5730}
5731
5732/// `roundRect(x, y, w, h, radii)`。
5733///
5734/// `radii` は数値 1 個・配列(1〜4 要素)のどちらも取りうる。
5735/// CSS の `border-radius` と同じ補完規則(1 個なら全隅、2 個なら
5736/// 対角の組、3 個なら左上・対角・右下)に従う。
5737pub fn canvas_round_rect(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5738    if let Some(id) = canvas_ctx_id(&this) {
5739        let (x, y) = (canvas_arg_f32(a, 0), canvas_arg_f32(a, 1));
5740        let (w, h) = (canvas_arg_f32(a, 2), canvas_arg_f32(a, 3));
5741        let radii = parse_round_rect_radii(it, a.get(4))?;
5742        crate::os_lib::canvas2d::with_context(id, |c| {
5743            let m = c.state.transform;
5744            c.path.round_rect(&m, x, y, w, h, radii);
5745        });
5746    }
5747    Ok(Value::Undefined)
5748}
5749
5750
5751/// `clip(fillRule)` または `clip(path, fillRule)`。クリップ領域を狭める。
5752pub fn canvas_clip(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5753    if let Some(id) = canvas_ctx_id(&this) {
5754        if let Some(pid) = a.first().and_then(path2d_id) {
5755            let rule = match a.get(1).map(|v| v.to_js_string()) {
5756                Some(s) if s.eq_ignore_ascii_case("evenodd") => {
5757                    crate::os_lib::canvas2d::FillRule::EvenOdd
5758                }
5759                _ => crate::os_lib::canvas2d::FillRule::NonZero,
5760            };
5761            if let Some(subpaths) = crate::os_lib::canvas2d::get_path2d_subpaths(pid) {
5762                crate::os_lib::canvas2d::with_context(id, |c| {
5763                    c.clip_subpaths(&subpaths, rule);
5764                });
5765            }
5766        } else {
5767            let rule = match a.first().map(|v| v.to_js_string()) {
5768                Some(s) if s.eq_ignore_ascii_case("evenodd") => {
5769                    crate::os_lib::canvas2d::FillRule::EvenOdd
5770                }
5771                _ => crate::os_lib::canvas2d::FillRule::NonZero,
5772            };
5773            crate::os_lib::canvas2d::with_context(id, |c| {
5774                c.clip(rule);
5775            });
5776        }
5777    }
5778    Ok(Value::Undefined)
5779}
5780
5781
5782/// `getImageData(x, y, w, h, [settings])`。面の内容を読んで `ImageData` を返す。
5783pub fn canvas_get_image_data(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5784    let (x, y) = (canvas_arg_f32(a, 0) as i32, canvas_arg_f32(a, 1) as i32);
5785    let w = (canvas_arg_f32(a, 2).abs() as usize).max(1);
5786    let h = (canvas_arg_f32(a, 3).abs() as usize).max(1);
5787    let cs = parse_image_data_color_space(a.get(4));
5788
5789    let items = if let Some(id) = canvas_ctx_id(&this) {
5790        crate::os_lib::canvas2d::with_context(id, |c| {
5791            let bytes = crate::os_lib::canvas2d::get_image_data(&c.surface, x, y, w as i32, h as i32);
5792            bytes.into_iter().map(|b| Value::Number(b as f64)).collect()
5793        }).unwrap_or_else(|| alloc::vec![Value::Number(0.0); w * h * 4])
5794    } else {
5795        alloc::vec![Value::Number(0.0); w * h * 4]
5796    };
5797
5798    Ok(make_image_data_object(w, h, items, cs))
5799}
5800
5801/// `putImageData(imageData, dx, dy)`。
5802///
5803/// 合成せず上書きし、クリップも無視する(仕様。`fill` 系と意味論が違う)。
5804pub fn canvas_put_image_data(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5805    let Some(id) = canvas_ctx_id(&this) else {
5806        return Ok(Value::Undefined);
5807    };
5808    let Some(Value::Object(img)) = a.first() else {
5809        return Ok(Value::Undefined);
5810    };
5811    let (w, h, bytes) = {
5812        let b = img.borrow();
5813        let w = b
5814            .props
5815            .get("width")
5816            .map(|v| v.to_number() as i32)
5817            .unwrap_or(0);
5818        let h = b
5819            .props
5820            .get("height")
5821            .map(|v| v.to_number() as i32)
5822            .unwrap_or(0);
5823        let mut bytes: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
5824        if let Some(Value::Object(arr)) = b.props.get("data") {
5825            let ab = arr.borrow();
5826            if let ObjKind::Bytes(st) = &ab.kind {
5827                bytes = st.to_vec();
5828            }
5829            if let ObjKind::Array(items) = &ab.kind {
5830                bytes.reserve(items.len());
5831                for v in items {
5832                    let n = v.to_number();
5833                    // 仕様どおり 0〜255 へ丸めて収める。
5834                    bytes.push(if n.is_finite() {
5835                        n.clamp(0.0, 255.0) as u8
5836                    } else {
5837                        0
5838                    });
5839                }
5840            }
5841        }
5842        (w, h, bytes)
5843    };
5844    let (dx, dy) = (canvas_arg_f32(a, 1) as i32, canvas_arg_f32(a, 2) as i32);
5845    crate::os_lib::canvas2d::with_context(id, |c| {
5846        crate::os_lib::canvas2d::put_image_data(&mut c.surface, &bytes, w, h, dx, dy);
5847    });
5848    Ok(Value::Undefined)
5849}
5850
5851
5852/// `drawImage` の転送元。`<img>` と別の canvas を扱う。
5853enum DrawSrc {
5854    /// デコード済み画像(`<img>`)。
5855    Image(alloc::sync::Arc<crate::os_lib::web_engine::DecodedImage>),
5856    /// 別の canvas の画素を RGBA8 へ写したもの。
5857    Canvas(u32, u32, alloc::vec::Vec<u8>),
5858}
5859
5860/// 転送元の値から画素を取り出す。
5861///
5862/// `<img>` は `src` 属性で共有の置き場を引く。
5863/// canvas は `_c2d_id` からコンテキストを引いて画素を写す
5864/// (同じコンテキストを二重に借りないよう、ここで写しを作る)。
5865fn draw_src_from(it: &mut Interp, v: &Value) -> Option<DrawSrc> {
5866    let Value::Object(o) = v else {
5867        return None;
5868    };
5869    let idx = o.borrow().kind.dom_node()?;
5870    let (tag, src, cid) = {
5871        let dom = it.dom().borrow();
5872        let tag = dom.nodes.get(idx).map(|n| n.tag.clone()).unwrap_or_default();
5873        let src = dom.get_attr(idx, "src").unwrap_or_default();
5874        let cid = dom
5875            .get_attr(idx, "_c2d_id")
5876            .and_then(|s| s.parse::<u32>().ok());
5877        (tag, src, cid)
5878    };
5879    if tag == "canvas" {
5880        let id = cid?;
5881        return crate::os_lib::canvas2d::with_context(id, |c| {
5882            let (w, h) = (c.surface.width, c.surface.height);
5883            DrawSrc::Canvas(w, h, crate::os_lib::canvas2d::get_image_data(
5884                &c.surface, 0, 0, w as i32, h as i32,
5885            ))
5886        });
5887    }
5888    crate::os_lib::web_engine::shared_image(&src).map(DrawSrc::Image)
5889}
5890
5891/// `drawImage(img, dx, dy)` / `(img, dx, dy, dw, dh)` /
5892/// `(img, sx, sy, sw, sh, dx, dy, dw, dh)`。
5893pub fn canvas_draw_image(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
5894    let Some(id) = canvas_ctx_id(&this) else {
5895        return Ok(Value::Undefined);
5896    };
5897    let Some(src) = a.first().and_then(|v| draw_src_from(it, v)) else {
5898        return Ok(Value::Undefined);
5899    };
5900    let (sw, sh, bytes): (u32, u32, &[u8]) = match &src {
5901        DrawSrc::Image(img) => (img.width, img.height, &img.rgba),
5902        DrawSrc::Canvas(w, h, b) => (*w, *h, b),
5903    };
5904    // 引数の個数で意味が変わる(仕様)。3・5・9 個のいずれか。
5905    let spec = match a.len() {
5906        0..=2 => return Ok(Value::Undefined),
5907        3 | 4 => crate::os_lib::canvas2d::BlitSpec {
5908            sx: 0.0,
5909            sy: 0.0,
5910            sw: sw as f32,
5911            sh: sh as f32,
5912            dx: canvas_arg_f32(a, 1),
5913            dy: canvas_arg_f32(a, 2),
5914            dw: sw as f32,
5915            dh: sh as f32,
5916        },
5917        5..=8 => crate::os_lib::canvas2d::BlitSpec {
5918            sx: 0.0,
5919            sy: 0.0,
5920            sw: sw as f32,
5921            sh: sh as f32,
5922            dx: canvas_arg_f32(a, 1),
5923            dy: canvas_arg_f32(a, 2),
5924            dw: canvas_arg_f32(a, 3),
5925            dh: canvas_arg_f32(a, 4),
5926        },
5927        _ => crate::os_lib::canvas2d::BlitSpec {
5928            sx: canvas_arg_f32(a, 1),
5929            sy: canvas_arg_f32(a, 2),
5930            sw: canvas_arg_f32(a, 3),
5931            sh: canvas_arg_f32(a, 4),
5932            dx: canvas_arg_f32(a, 5),
5933            dy: canvas_arg_f32(a, 6),
5934            dw: canvas_arg_f32(a, 7),
5935            dh: canvas_arg_f32(a, 8),
5936        },
5937    };
5938    let image = crate::os_lib::canvas2d::ImageSource {
5939        width: sw,
5940        height: sh,
5941        rgba: bytes,
5942    };
5943    crate::os_lib::canvas2d::with_context(id, |c| {
5944        canvas_sync_state(&this, c);
5945        c.sync_clip();
5946        let m = c.state.transform;
5947        let alpha = c.state.global_alpha;
5948        let smooth = c.state.image_smoothing_enabled;
5949        let filter = c.state.filter.clone();
5950        c.surface.draw_image_with_filter(&image, &spec, &m, alpha, smooth, &filter);
5951    });
5952    Ok(Value::Undefined)
5953}
5954
5955
5956/// 1 文字ぶんの字形を、フォントの錠を**持たずに**扱えるよう写したもの。
5957struct OwnedGlyph {
5958    width: u32,
5959    height: u32,
5960    x_offset: i32,
5961    y_offset: i32,
5962    advance: f32,
5963    alpha: alloc::vec::Vec<u8>,
5964}
5965
5966/// 文字列ぶんの字形を取り出す。
5967///
5968/// 【重要】フォントの錠を**描画中に持ち続けない**。
5969/// `GLOBAL_VECTOR_FONT` は毎フレームの文字描画が使う。低優先度の側が
5970/// 握ったまま長く走ると、提示ループが `spin::Mutex` で回り続けて
5971/// 優先度逆転を起こす(`image_results_ready` で実際に踏んだ)。
5972/// ここで写しを作って錠を放し、描画は錠の外で行う。
5973fn glyphs_for(text: &str, size_px: u32) -> alloc::vec::Vec<OwnedGlyph> {
5974    let mut out = alloc::vec::Vec::new();
5975    let mut font_lock = crate::os_lib::platform::vector_font();
5976    let Some(font) = font_lock.as_mut() else {
5977        return out;
5978    };
5979    for c in text.chars() {
5980        if let Some(g) = font.get_glyph(c, size_px) {
5981            out.push(OwnedGlyph {
5982                width: g.width,
5983                height: g.height,
5984                x_offset: g.x_offset,
5985                y_offset: g.y_offset,
5986                advance: g.advance as f32,
5987                alpha: g.data.clone(),
5988            });
5989        }
5990    }
5991    out
5992}
5993
5994/// コンテキストの `font` から文字の大きさ(px)を得る。既定は 10px。
5995fn canvas_font_size(this: &Value) -> f32 {
5996    let Value::Object(o) = this else {
5997        return 10.0;
5998    };
5999    let b = o.borrow();
6000    let Some(Value::Str(s)) = b.props.get("font") else {
6001        return 10.0;
6002    };
6003    crate::os_lib::canvas2d::parse_font_size(s).unwrap_or(10.0)
6004}
6005
6006/// 2D コンテキストの textAlign / textBaseline / direction を読み取る。
6007fn canvas_text_layout_params(
6008    this: &Value,
6009) -> (
6010    crate::os_lib::canvas2d::TextAlign,
6011    crate::os_lib::canvas2d::TextBaseline,
6012    crate::os_lib::canvas2d::CanvasDirection,
6013) {
6014    let mut al = crate::os_lib::canvas2d::TextAlign::Start;
6015    let mut bl = crate::os_lib::canvas2d::TextBaseline::Alphabetic;
6016    let mut dir = crate::os_lib::canvas2d::CanvasDirection::Inherit;
6017    if let Value::Object(o) = this {
6018        let b = o.borrow();
6019        if let Some(Value::Str(s)) = b.props.get("textAlign") {
6020            if let Some(v) = crate::os_lib::canvas2d::parse_text_align(s) {
6021                al = v;
6022            }
6023        }
6024        if let Some(Value::Str(s)) = b.props.get("textBaseline") {
6025            if let Some(v) = crate::os_lib::canvas2d::parse_text_baseline(s) {
6026                bl = v;
6027            }
6028        }
6029        if let Some(Value::Str(s)) = b.props.get("direction") {
6030            if let Some(v) = crate::os_lib::canvas2d::parse_canvas_direction(s) {
6031                dir = v;
6032            }
6033        }
6034    }
6035    (al, bl, dir)
6036}
6037
6038/// `strokeText(text, x, y)`。
6039///
6040/// `strokeStyle` と `lineWidth` を反映して輪郭線を描く。
6041pub fn canvas_stroke_text(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6042    let Some(id) = canvas_ctx_id(&this) else {
6043        return Ok(Value::Undefined);
6044    };
6045    let text = a.first().map(|v| v.to_js_string()).unwrap_or_default();
6046    if text.is_empty() {
6047        return Ok(Value::Undefined);
6048    }
6049    let (x, y) = (canvas_arg_f32(a, 1), canvas_arg_f32(a, 2));
6050    if !x.is_finite() || !y.is_finite() {
6051        return Ok(Value::Undefined);
6052    }
6053    let size = canvas_font_size(&this);
6054    let glyphs = glyphs_for(&text, size as u32);
6055    if glyphs.is_empty() {
6056        return Ok(Value::Undefined);
6057    }
6058    let total: f32 = glyphs.iter().map(|g| g.advance).sum();
6059
6060    let (align, baseline, dir) = canvas_text_layout_params(&this);
6061    let x0 = x + crate::os_lib::canvas2d::align_offset_with_direction(align, total, dir);
6062    let y0 = y + crate::os_lib::canvas2d::baseline_offset(baseline, size);
6063
6064    crate::os_lib::canvas2d::with_context(id, |c| {
6065        canvas_sync_state(&this, c);
6066        c.sync_clip();
6067        let stroke_color = c.apply_alpha(c.state.stroke);
6068        let line_width = c.state.line_width;
6069        let m = c.state.transform;
6070        if c.state.has_shadow() {
6071            let shadow_color = c.shadow_color_argb();
6072            let mut pen = x0 + c.state.shadow_offset_x;
6073            let sy = y0 + c.state.shadow_offset_y;
6074            for g in &glyphs {
6075                let bm = crate::os_lib::canvas2d::GlyphBitmap {
6076                    width: g.width,
6077                    height: g.height,
6078                    x_offset: g.x_offset,
6079                    y_offset: g.y_offset,
6080                    advance: g.advance,
6081                    alpha: &g.alpha,
6082                };
6083                c.surface.draw_glyph_stroke(&bm, pen, sy, shadow_color, line_width, &m);
6084                pen += g.advance;
6085            }
6086        }
6087        let mut pen = x0;
6088        for g in &glyphs {
6089            let bm = crate::os_lib::canvas2d::GlyphBitmap {
6090                width: g.width,
6091                height: g.height,
6092                x_offset: g.x_offset,
6093                y_offset: g.y_offset,
6094                advance: g.advance,
6095                alpha: &g.alpha,
6096            };
6097            c.surface.draw_glyph_stroke(&bm, pen, y0, stroke_color, line_width, &m);
6098            pen += g.advance;
6099        }
6100    });
6101    Ok(Value::Undefined)
6102}
6103
6104pub fn canvas_fill_text(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6105    let Some(id) = canvas_ctx_id(&this) else {
6106        return Ok(Value::Undefined);
6107    };
6108    let text = a.first().map(|v| v.to_js_string()).unwrap_or_default();
6109    if text.is_empty() {
6110        return Ok(Value::Undefined);
6111    }
6112    let (x, y) = (canvas_arg_f32(a, 1), canvas_arg_f32(a, 2));
6113    if !x.is_finite() || !y.is_finite() {
6114        return Ok(Value::Undefined);
6115    }
6116    let size = canvas_font_size(&this);
6117    let glyphs = glyphs_for(&text, size as u32);
6118    if glyphs.is_empty() {
6119        return Ok(Value::Undefined);
6120    }
6121    let total: f32 = glyphs.iter().map(|g| g.advance).sum();
6122
6123    let (align, baseline, dir) = canvas_text_layout_params(&this);
6124    let x0 = x + crate::os_lib::canvas2d::align_offset_with_direction(align, total, dir);
6125    let y0 = y + crate::os_lib::canvas2d::baseline_offset(baseline, size);
6126
6127    crate::os_lib::canvas2d::with_context(id, |c| {
6128        canvas_sync_state(&this, c);
6129        c.sync_clip();
6130        let color = c.apply_alpha(c.state.fill);
6131        let m = c.state.transform;
6132        if c.state.has_shadow() {
6133            let shadow_color = c.shadow_color_argb();
6134            let mut pen = x0 + c.state.shadow_offset_x;
6135            let sy = y0 + c.state.shadow_offset_y;
6136            for g in &glyphs {
6137                let bm = crate::os_lib::canvas2d::GlyphBitmap {
6138                    width: g.width,
6139                    height: g.height,
6140                    x_offset: g.x_offset,
6141                    y_offset: g.y_offset,
6142                    advance: g.advance,
6143                    alpha: &g.alpha,
6144                };
6145                c.surface.draw_glyph(&bm, pen, sy, shadow_color, &m);
6146                pen += g.advance;
6147            }
6148        }
6149        let mut pen = x0;
6150        for g in &glyphs {
6151            let bm = crate::os_lib::canvas2d::GlyphBitmap {
6152                width: g.width,
6153                height: g.height,
6154                x_offset: g.x_offset,
6155                y_offset: g.y_offset,
6156                advance: g.advance,
6157                alpha: &g.alpha,
6158            };
6159            c.surface.draw_glyph(&bm, pen, y0, color, &m);
6160            pen += g.advance;
6161        }
6162    });
6163    Ok(Value::Undefined)
6164}
6165
6166/// `measureText(text)`。
6167///
6168/// 従来はバイト長 × 8 を返していた。日本語では実際と大きくずれ、
6169/// `font` の大きさも無視していた。字形の送り幅を実測する。
6170pub fn canvas_measure_text(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6171    let text = a.first().map(|v| v.to_js_string()).unwrap_or_default();
6172    let size = canvas_font_size(&this);
6173    let glyphs = glyphs_for(&text, size as u32);
6174    if glyphs.is_empty() && !text.is_empty() {
6175        // フォントが無い(未初期化)ときは従来の概算へ落ちる。
6176        return dom_canvas_measure_text(it, this, a);
6177    }
6178    let width: f32 = glyphs.iter().map(|g| g.advance).sum();
6179    let obj = Obj::plain();
6180    {
6181        let mut b = obj.borrow_mut();
6182        b.props.insert("width".into(), Value::Number(width as f64));
6183        // 上下の張り出しは字形の実測から出す。
6184        let ascent = glyphs
6185            .iter()
6186            .map(|g| -g.y_offset)
6187            .max()
6188            .unwrap_or(0)
6189            .max(0) as f64;
6190        let descent = glyphs
6191            .iter()
6192            .map(|g| g.y_offset + g.height as i32)
6193            .max()
6194            .unwrap_or(0)
6195            .max(0) as f64;
6196        b.props
6197            .insert("actualBoundingBoxAscent".into(), Value::Number(ascent));
6198        b.props
6199            .insert("actualBoundingBoxDescent".into(), Value::Number(descent));
6200        b.props.insert(
6201            "fontBoundingBoxAscent".into(),
6202            Value::Number((size * 0.85) as f64),
6203        );
6204        b.props.insert(
6205            "fontBoundingBoxDescent".into(),
6206            Value::Number((size * 0.15) as f64),
6207        );
6208        let (align, _, dir) = canvas_text_layout_params(&this);
6209        let align_off = crate::os_lib::canvas2d::align_offset_with_direction(align, width, dir);
6210        let actual_left = -align_off;
6211        let actual_right = width + align_off;
6212        b.props
6213            .insert("actualBoundingBoxLeft".into(), Value::Number(actual_left as f64));
6214        b.props.insert(
6215            "actualBoundingBoxRight".into(),
6216            Value::Number(actual_right as f64),
6217        );
6218    }
6219    Ok(Value::Object(obj))
6220}
6221
6222/// Web Components: `element.attachShadow({ mode: 'open' | 'closed' })`
6223pub(crate) fn dom_attach_shadow(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6224    let host_idx = match this_dom_idx(&this) {
6225        Some(i) => i,
6226        None => return Err(it.type_error("attachShadow must be called on an Element")),
6227    };
6228
6229    let opt = arg(a, 0);
6230    let mode_str = match &opt {
6231        Value::Object(o) => o
6232            .borrow()
6233            .props
6234            .get("mode")
6235            .map(|v| v.to_js_string())
6236            .unwrap_or_default(),
6237        _ => alloc::string::String::new(),
6238    };
6239
6240    let mode = match crate::os_lib::shadow_dom::ShadowRootMode::parse(&mode_str) {
6241        Some(m) => m,
6242        None => {
6243            return Err(it.type_error(
6244                "Failed to execute 'attachShadow' on 'Element': The provided value is not a valid enum value of type ShadowRootMode ('open' or 'closed')",
6245            ))
6246        }
6247    };
6248
6249    match it.dom().borrow_mut().attach_shadow(host_idx, mode) {
6250        Ok(root_idx) => {
6251            let root_obj = it.dom_obj(root_idx);
6252            {
6253                let mut ro = root_obj.borrow_mut();
6254                ro.props.insert("mode".into(), Value::str(mode.as_str()));
6255                ro.props.insert("host".into(), this.clone());
6256            }
6257            Ok(Value::Object(root_obj))
6258        }
6259        Err(crate::os_lib::shadow_dom::AttachShadowError::AlreadyHasShadowRoot) => {
6260            Err(it.dom_exception(
6261                "InvalidStateError",
6262                "Shadow root cannot be created on a host which already hosts a shadow tree",
6263            ))
6264        }
6265        Err(crate::os_lib::shadow_dom::AttachShadowError::DisallowedTag) => {
6266            Err(it.dom_exception(
6267                "NotSupportedError",
6268                "This element does not support attachShadow",
6269            ))
6270        }
6271        Err(_) => Err(it.dom_exception(
6272            "NotSupportedError",
6273            "Failed to attach shadow root",
6274        )),
6275    }
6276}
6277
6278/// Web Components: `customElements.define(name, constructor, options)`
6279pub(crate) fn custom_elements_define(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6280    let name = arg(a, 0).to_js_string();
6281    let ctor = arg(a, 1);
6282
6283    if !crate::os_lib::custom_elements::is_valid_custom_element_name(&name) {
6284        return Err(it.type_error(alloc::format!("Failed to execute 'define' on 'CustomElementRegistry': \"{}\" is not a valid custom element name", name)));
6285    }
6286
6287    if !matches!(ctor, Value::Object(_)) {
6288        return Err(it.type_error("Failed to execute 'define' on 'CustomElementRegistry': The referenced script is not a constructor"));
6289    }
6290
6291    // observedAttributes をコンストラクタから取得(静的 getter もある。Polymer は
6292    // `static get observedAttributes()` で返す。【2026-10-20】従来は props しか見ず空だった)。
6293    let mut observed_attrs = alloc::vec::Vec::new();
6294    let obs_val = it.get_property(&ctor, "observedAttributes")?;
6295    if !matches!(obs_val, Value::Undefined | Value::Null) {
6296        for item in array_like_items(it, &obs_val) {
6297            observed_attrs.push(item.to_js_string());
6298        }
6299    }
6300
6301    // DomBridge の custom_elements レジストリに登録
6302    match it.dom().borrow_mut().custom_elements.define(&name, observed_attrs) {
6303        Ok(()) => {}
6304        Err(crate::os_lib::custom_elements::DefineError::AlreadyDefined) => {
6305            return Err(it.dom_exception(
6306                "NotSupportedError",
6307                &alloc::format!("Failed to execute 'define' on 'CustomElementRegistry': the name \"{}\" has already been used with this registry", name),
6308            ));
6309        }
6310        Err(crate::os_lib::custom_elements::DefineError::InvalidName) => {
6311            return Err(it.type_error(alloc::format!("\"{}\" is not a valid custom element name", name)));
6312        }
6313    }
6314
6315    // JS 側の this (CustomElementRegistry オブジェクト) の `_registry` にコンストラクタを保持
6316    if let Value::Object(reg_obj) = &this {
6317        if let Some(Value::Object(map)) = reg_obj.borrow().props.get("_registry") {
6318            map.borrow_mut().props.insert(name.clone().into(), ctor.clone());
6319        }
6320    }
6321
6322    // 文書に接続済みの同名要素を木順に昇格する(コンストラクタ → connectedCallback)。
6323    // 【2026-10-20】従来は使い捨てのハンドルに原型を付けるだけで、昇格していなかった。
6324    let matching_indices: alloc::vec::Vec<usize> = {
6325        let mut dom = it.dom().borrow_mut();
6326        for n in dom.nodes.iter_mut().filter(|n| !n.is_text && n.tag.eq_ignore_ascii_case(&name)) {
6327            n.attrs.insert(alloc::string::String::from("_defined"), alloc::string::String::from("true"));
6328        }
6329        let root = 0;
6330        dom.subtree_elements(root)
6331            .into_iter()
6332            .filter(|&i| dom.nodes[i].tag.eq_ignore_ascii_case(&name))
6333            .collect()
6334    };
6335    for idx in matching_indices {
6336        it.ce_try_upgrade(idx, true);
6337    }
6338
6339    // `whenDefined` で待機中の Promise があれば、登録されたコンストラクタで解決する(仕様準拠)。
6340    if let Value::Object(reg_obj) = &this {
6341        let when_def_promise = {
6342            if let Some(Value::Object(map)) = reg_obj.borrow().props.get("_when_defined") {
6343                map.borrow_mut().props.shift_remove(&name)
6344            } else {
6345                None
6346            }
6347        };
6348        if let Some(Value::Object(p_obj)) = when_def_promise {
6349            if let Some(state) = super::promise::this_promise_state(&Value::Object(p_obj)) {
6350                it.promise_resolve(&state, ctor.clone());
6351            }
6352        }
6353    }
6354
6355    Ok(Value::Undefined)
6356}
6357
6358/// Web Components: `customElements.get(name)`
6359pub(crate) fn custom_elements_get(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6360    let name = arg(a, 0).to_js_string();
6361    if let Value::Object(reg_obj) = this {
6362        if let Some(Value::Object(map)) = reg_obj.borrow().props.get("_registry") {
6363            if let Some(ctor) = map.borrow().props.get(&name) {
6364                return Ok(ctor.clone());
6365            }
6366        }
6367    }
6368    Ok(Value::Undefined)
6369}
6370
6371/// Web Components: `customElements.whenDefined(name)`
6372pub(crate) fn custom_elements_when_defined(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
6373    let name = arg(a, 0).to_js_string();
6374    if !crate::os_lib::custom_elements::is_valid_custom_element_name(&name) {
6375        let err = it.type_error(alloc::format!("\"{}\" is not a valid custom element name", name));
6376        return Ok(rejected_promise(it, err));
6377    }
6378    let ctor_opt = if let Value::Object(reg_obj) = &this {
6379        if let Some(Value::Object(map)) = reg_obj.borrow().props.get("_registry") {
6380            map.borrow().props.get(&name).cloned()
6381        } else {
6382            None
6383        }
6384    } else {
6385        None
6386    };
6387
6388    if let Some(ctor) = ctor_opt {
6389        // すでに定義済みなら即時解決 Promise を返す
6390        Ok(resolved_promise(it, ctor))
6391    } else {
6392        // 未定義なら保留中の Promise を作成し、_when_defined マップに保持して返す
6393        if let Value::Object(reg_obj) = &this {
6394            let mut reg = reg_obj.borrow_mut();
6395            let when_map = reg.props.entry(alloc::string::String::from("_when_defined").into())
6396                .or_insert_with(|| Value::Object(Obj::plain()));
6397            if let Value::Object(map) = when_map {
6398                if let Some(existing) = map.borrow().props.get(&name) {
6399                    return Ok(existing.clone());
6400                }
6401                let state = super::promise::new_pending();
6402                let p = Value::Object(Obj::promise(state));
6403                map.borrow_mut().props.insert(name.into(), p.clone());
6404                return Ok(p);
6405            }
6406        }
6407        let state = super::promise::new_pending();
6408        Ok(Value::Object(Obj::promise(state)))
6409    }
6410}
6411
6412/// Web Components: `customElements.upgrade(root)`
6413pub(crate) fn custom_elements_upgrade(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
6414    let node_val = arg(a, 0);
6415    let Some(root_idx) = this_dom_idx(&node_val) else {
6416        return Ok(Value::Undefined);
6417    };
6418    let connected = it.dom().borrow().is_attached(root_idx);
6419    let els = it.dom().borrow().subtree_elements(root_idx);
6420    for idx in els {
6421        it.ce_try_upgrade(idx, connected);
6422    }
6423    it.process_ce_reactions();
6424    Ok(Value::Undefined)
6425}
6426
6427
6428
6429/// `new Image(width?, height?)`: `<img>` 要素を作る(`document.createElement('img')` と同じ)。
6430pub(crate) fn image_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
6431    let idx = it.dom().borrow_mut().create_element("img");
6432    for (i, name) in ["width", "height"].iter().enumerate() {
6433        if let Some(v) = a.get(i).filter(|v| !matches!(v, Value::Undefined)) {
6434            let n = v.to_number();
6435            if n.is_finite() {
6436                it.dom().borrow_mut().set_attr(idx, name, &alloc::format!("{}", n as i64));
6437            }
6438        }
6439    }
6440    Ok(it.dom_val(idx))
6441}
6442
6443/// `new Audio(src?)`: `<audio preload="auto">` 要素を作る。
6444pub(crate) fn audio_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
6445    let idx = it.dom().borrow_mut().create_element("audio");
6446    it.dom().borrow_mut().set_attr(idx, "preload", "auto");
6447    if let Some(v) = a.first().filter(|v| !matches!(v, Value::Undefined)) {
6448        let src = v.to_js_string();
6449        it.dom().borrow_mut().set_attr(idx, "src", &src);
6450    }
6451    Ok(it.dom_val(idx))
6452}
6453
6454/// `new DocumentFragment()`(DOM Standard §4.7)。
6455pub(crate) fn dom_fragment_ctor(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
6456    let idx = it.dom().borrow_mut().create_document_fragment();
6457    Ok(it.dom_val(idx))
6458}
6459
6460/// `new Text(data = "")`(DOM Standard §4.11)。
6461pub(crate) fn dom_text_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
6462    let text = match arg(a, 0) {
6463        Value::Undefined => String::new(),
6464        v => it.to_string_value(v)?,
6465    };
6466    let idx = it.dom().borrow_mut().create_text_node(&text);
6467    Ok(it.dom_val(idx))
6468}
6469
6470/// `new Comment(data = "")`。
6471pub(crate) fn dom_comment_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
6472    let text = match arg(a, 0) {
6473        Value::Undefined => String::new(),
6474        v => it.to_string_value(v)?,
6475    };
6476    let idx = it.dom().borrow_mut().create_comment(&text);
6477    Ok(it.dom_val(idx))
6478}
6479
6480/// `document.createProcessingInstruction(target, data)`(DOM Standard §4.5)。`target` は名前、`data` は `?>` を含まない。
6481pub(crate) fn document_create_processing_instruction(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
6482    if a.len() < 2 {
6483        return Err(it.type_error(alloc::format!(
6484            "Failed to execute 'createProcessingInstruction' on 'Document': 2 arguments required, but only {} present.",
6485            a.len()
6486        )));
6487    }
6488    let target = arg(a, 0).to_js_string();
6489    let data = arg(a, 1).to_js_string();
6490    // 【2026-11-20】target は XML の `Name`(`dom_pi.rs`)。
6491    if !super::dom_pi::is_xml_name(&target) {
6492        return Err(it.dom_exception("InvalidCharacterError", "The target is not a valid XML name."));
6493    }
6494    if data.contains("?>") {
6495        return Err(it.dom_exception("InvalidCharacterError", "The data contains '?>'."));
6496    }
6497    let idx = it.dom().borrow_mut().create_processing_instruction(&target, &data);
6498    super::dom_doc::note_created(it, super::dom_doc::owner_of_this(it, &t), idx);
6499    Ok(it.dom_val(idx))
6500}