Skip to main content

atmos/os_lib/web_apis/
dom_bridge.rs

1//! JS ⇄ レンダラの DOM ブリッジ。
2//!
3//! `dom::parse_html` の結果を **ドキュメント順** にフラット化した軽量アリーナを持ち、
4//! JS から `document.getElementById` 等で参照されるノードと、`textContent` /
5//! `style` / `classList` の変更、`addEventListener('click')` で登録されたリスナを保持する。
6//!
7//! レンダラは毎レイアウトで `last_html` を再パースするため、ブリッジは
8//! 「同一 HTML を同一ドキュメント順で歩けばインデックスが一致する」性質を使い、
9//! `apply_overrides` で再パース木へ JS の変更を焼き戻してから CSS カスケードに渡す。
10//! これにより既存のレンダリング経路をそのまま再利用できる(HTML 再シリアライズ不要)。
11
12use alloc::collections::BTreeMap;
13use alloc::collections::BTreeSet;
14use alloc::format;
15use alloc::string::String;
16use alloc::string::ToString;
17use alloc::vec::Vec;
18
19use crate::os_lib::ecma::value::{HostRef, Obj, ObjKind, ObjRef, Value, HOST_CLASS_BY_ID};
20use crate::os_lib::dom::{Node, NodeType};
21use crate::os_lib::viewport::intersection_observer::RootMargin;
22use crate::os_lib::viewport::resize_observer::ResizeObserverBoxOptions;
23
24/// ブリッジ上の 1 ノード。要素またはテキスト。
25pub struct DomNode {
26    /// 要素タグ(小文字)。テキストノードは空。
27    pub tag: String,
28    pub is_text: bool,
29    pub id: String,
30    pub classes: Vec<String>,
31    /// インライン style(プロパティ→値)。
32    pub style: BTreeMap<String, String>,
33    /// その他の属性(id/class/style 以外も含む生の値)。
34    pub attrs: BTreeMap<String, String>,
35    /// テキストノードの内容、または textContent 上書き値。
36    pub text_override: Option<String>,
37    /// 構築時のテキスト(textContent ゲッタ用)。
38    pub initial_text: String,
39    pub parent: Option<usize>,
40    pub children: Vec<usize>,
41    /// JS が classes を変更したか(apply で焼き戻す)。
42    pub classes_dirty: bool,
43    /// JS が style を変更したか。
44    pub style_dirty: bool,
45}
46
47/// IntersectionObserver の監視対象要素
48#[derive(Clone)]
49pub struct ObservedTarget {
50    pub target: Value,
51    pub target_idx: usize,
52    pub prev_ratio: Option<f64>,
53    pub prev_is_intersecting: bool,
54}
55
56/// IntersectionObserver の登録エントリ
57#[derive(Clone)]
58pub struct IntersectionObserverReg {
59    pub id: u32,
60    pub callback: Value,
61    pub root: Value,
62    pub root_margin: RootMargin,
63    pub thresholds: Vec<f64>,
64    pub targets: Vec<ObservedTarget>,
65    pub queued_records: Vec<Value>,
66}
67
68/// ResizeObserver の監視対象要素
69#[derive(Clone)]
70pub struct ObservedResizeTarget {
71    pub target: Value,
72    pub target_idx: usize,
73    pub box_option: ResizeObserverBoxOptions,
74    pub last_inline_size: f64,
75    pub last_block_size: f64,
76}
77
78/// ResizeObserver の登録エントリ
79#[derive(Clone)]
80pub struct ResizeObserverReg {
81    pub id: u32,
82    pub callback: Value,
83    pub targets: Vec<ObservedResizeTarget>,
84}
85
86/// MutationObserver の登録エントリ。
87#[derive(Clone)]
88pub struct MutObsReg {
89    pub id: u32,
90    pub target_idx: usize,
91    pub child_list: bool,
92    pub attributes: bool,
93    pub subtree: bool,
94    pub callback: Value,
95    pub observer: Value,
96    /// `observe(target, {attributeOldValue: true})`。変更前の属性値を
97    /// レコードの `oldValue` として公開するかどうか。
98    pub attribute_old_value: bool,
99    /// `observe(target, {attributeFilter: [...]})`。指定時はこの一覧に
100    /// 含まれる属性名の変化のみ通知する(`None` は全属性を監視)。
101    pub attribute_filter: Option<Vec<String>>,
102    /// `observe(target, {characterData: true})`(丸ごと未対応だった。
103    /// テキストノードの`.data`/`.nodeValue`/`textContent`変更を監視する
104    /// オプション自体が存在せず、対応する通知ヘルパ〔`notify_character_
105    /// data`〕も無かったため、`characterData`を指定してもコールバックが
106    /// 一切呼ばれなかった。`childList`/`attributes`は既に対応済みで
107    /// `characterData`だけ抜けていた兄弟ギャップ。2026-07-17 発見・実装)。
108    pub character_data: bool,
109    /// `observe(target, {characterDataOldValue: true})`。変更前のテキスト
110    /// 値をレコードの`oldValue`として公開するかどうか(`attributeOldValue`
111    /// と対)。
112    pub character_data_old_value: bool,
113    /// transient registered observer の元の登録対象ノード(`None` は通常登録)。
114    pub transient_source: Option<usize>,
115}
116
117/// MutationObserver に届けるレコード(Rust 側内部表現)。
118pub struct MutRec {
119    pub type_: &'static str, // "childList" | "attributes"
120    pub target_idx: usize,
121    pub added: Vec<usize>,
122    pub removed: Vec<usize>,
123    pub prev_sibling: Option<usize>,
124    pub next_sibling: Option<usize>,
125    pub attribute_name: Option<String>,
126    pub attribute_namespace: Option<String>,
127    /// `attributeOldValue: true` が指定された観察者向けにのみ Some を積む。
128    pub old_value: Option<String>,
129}
130
131/// click 等のイベントリスナ登録。
132pub struct Listener {
133    pub node: usize,
134    pub event: String,
135    pub func: Value,
136    /// キャプチャフェーズで発火するリスナか(addEventListener の capture オプション)。
137    pub capture: bool,
138    /// 一度発火したら自動削除されるか(once オプション)。
139    pub once: bool,
140    /// `preventDefault()` を無視するパッシブリスナか(passive オプション / passive-by-default)。
141    pub passive: bool,
142    /// 一意 ID(once 削除や removeEventListener の照合に使う)。
143    pub id: u64,
144    /// `addEventListener(type, fn, {signal})`(丸ごと未対応だった。
145    /// `AbortController` でリスナを一括解除する定番パターン。2026-07-14
146    /// 発見・実装)。`signal.aborted` を都度チェックし、abort 済みなら
147    /// 発火しない簡略実装(`abort` イベント発火と同時に即座に物理削除は
148    /// せず、次回参照時に遅延評価する。実務上は「以後発火しなくなる」
149    /// という観測可能な挙動が同じであれば十分なため)。
150    pub signal: Option<Value>,
151}
152
153/// `AbortSignal` オブジェクトの `.aborted` が `true` か。
154pub fn is_signal_aborted(signal: &Value) -> bool {
155    matches!(signal, Value::Object(o) if matches!(o.borrow().props.get("aborted"), Some(Value::Bool(true))))
156}
157
158fn is_listener_aborted(l: &Listener) -> bool {
159    l.signal.as_ref().is_some_and(is_signal_aborted)
160}
161
162/// 境界点の容器として「主文書の `document`」を表す番号(アリーナのノードではないので添字が余っている値を使う)。
163pub const MAIN_DOC: usize = usize::MAX - 1;
164
165/// 生きている Range の記録(`Range` の JS オブジェクトは弱参照で持つ。落ちたら次の変更のときに捨てる)。
166#[derive(Clone)]
167pub struct RangeRec {
168    pub obj: alloc::rc::Weak<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>,
169    pub sc: usize,
170    pub so: usize,
171    pub ec: usize,
172    pub eo: usize,
173}
174
175/// 生きている `NodeIterator` の状態(JS のオブジェクトは弱参照。`referenceNode` などはここに持ち、ノードの取り外しで直す)。
176#[derive(Clone)]
177pub struct NiRec {
178    pub obj: alloc::rc::Weak<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>,
179    pub root: usize,
180    pub reference: usize,
181    pub before: bool,
182    pub in_flight: Option<(usize, bool)>,
183}
184
185/// DOM ブリッジ本体。`JsRuntime` が `Rc<RefCell<>>` で保持し、レンダラと共有する。
186pub struct DomBridge {
187    pub nodes: Vec<DomNode>,
188    /// `#document` ノード(`new Document()`・`createHTMLDocument` など主文書以外の `Document`)の数。
189    /// 0 のあいだは所有文書の管理(`node_doc`)に一切触れない(主文書だけのページの速い経路を変えない)。
190    pub extra_docs: usize,
191    /// `Attr` ノード(`#attr`。`builtins/dom_attr.rs`)の表: (要素, 属性の修飾名) → ノード。要素に付いているものだけ。
192    pub attr_nodes: BTreeMap<(usize, String), usize>,
193    /// `#attr` ノードを作ったか(作るまで `Attr` のメンバーの解決へは入らない)。
194    pub has_attr_nodes: bool,
195    /// 属性の挿入順(【2026-11-20】仕様は挿入順。`attrs` は `BTreeMap`(名前順)のまま、順序が名前順(id・class を先頭)と
196    /// 食い違うノードだけ別に持つ疎な表。無いノードは既定の並び。描画用の木・CSS の照合・特徴ハッシュは見ない)。
197    pub attr_order: BTreeMap<usize, Vec<String>>,
198    /// 名前空間つき属性(`ns.is_some()` のみ)。要素 → `(ns, qname, value)` のリスト。
199    /// HTML の `style`・`id`・`class`・`on*` 等の非名前空間属性と完全に分離する。
200    pub ns_attrs: BTreeMap<usize, Vec<(String, String, String)>>,
201    /// 名前空間つき属性を持つ要素の、全属性 `(ns, qname)` 挿入順リスト(`ns_attrs` が空でない要素のみ)。
202    pub attr_ns_order: BTreeMap<usize, Vec<(Option<String>, String)>>,
203    /// 主文書の `<!DOCTYPE>` のノード(親の無い `#doctype`。ブラウザ用の解析は DOCTYPE を木に入れないので、ふだんは `None`。
204    /// 仕様どおりの木で組むホスト実行器(`tests/wpt_dom_host`)が `set_main_doctype` で入れる)。
205    pub main_doctype: Option<usize>,
206    /// 生きている Range(`builtins/range.rs`)。DOM の変更のたびに境界点を直す。空のあいだは何もしない。
207    pub ranges: BTreeMap<u32, RangeRec>,
208    /// `replace_data` が `set_text_content` の中の Range の更新を止めるための印。
209    pub suppress_range_hook: bool,
210    pub next_range_id: u32,
211    /// 生きている `NodeIterator`(`createNodeIterator` が作ったものだけ。空のあいだは取り外しの処理に何も足さない)。
212    pub node_iters: BTreeMap<u32, NiRec>,
213    pub next_ni_id: u32,
214    /// 生きている `HTMLCollection` の定義(`HOST_HTMLCOLLECTION` の `id` が添字)。
215    pub html_collections: Vec<HtmlCollectionKind>,
216    /// `HTMLCollection` インスタンスへの expando プロパティ。
217    pub html_collection_expandos: BTreeMap<usize, BTreeMap<String, Value>>,
218    /// 静的 `NodeList`(`querySelectorAll` 等、`HOST_STATIC_NODELIST` の `id` が添字)。
219    pub static_node_lists: Vec<Vec<usize>>,
220    /// 補った `<head>`/`<body>` の殻(`ensure_shells`)を作ったか。描画用の木・走査順では殻を飛ばす(`_implicit` 属性の要素)。
221    pub has_shells: bool,
222    /// 主文書以外の文書が所有するノード → その `#document` ノードの添字。載っていないノードは主文書のもの。
223    pub node_doc: BTreeMap<usize, usize>,
224    /// 文書(`None` は主文書)→ `<template>.content` 用の所有者 `#document` ノード。
225    pub template_owner_docs: BTreeMap<Option<usize>, usize>,
226    /// 文書が Quirks モードで解析されたか(WPT ホストが設定)。
227    pub quirks_mode: bool,
228    /// `#document` ノード → その `document.implementation`(同一性を保つためのキャッシュ)。
229    pub doc_impls: BTreeMap<usize, Value>,
230    pub listeners: Vec<Listener>,
231    /// JS が DOM を変更したフラグ。ホストはこれを見て再レイアウトする。
232    pub dirty: bool,
233    /// `id` 属性や接続状態が変わったか(`window[id]` 同期用)。
234    pub id_dirty: bool,
235    /// set_style 以外の DOM 変更(ノード追加/削除/クラス/テキスト/属性変更等)や set_css_text があったか
236    pub structural_dirty: bool,
237    /// 組み直しを招いた変更の、原因ごとの回数(TODO P4 a。`note_dirty_cause`)。
238    pub dirty_causes: BTreeMap<String, u32>,
239    /// set_style で変更されたプロパティの一覧: (node_idx, prop_kebab, new_val)
240    pub pending_style_updates: Vec<(usize, String, String)>,
241    /// 単一テキスト子の軽量置換一覧: (elem_node_idx, text_node_idx, new_text)
242    pub pending_text_updates: Vec<(usize, usize, String)>,
243    /// JS が `createElement('script')` で作った `<script>`(文書へ挿入されたら実行する)。
244    pub js_created_scripts: alloc::collections::BTreeSet<usize>,
245    /// 文書へ挿入されて実行待ちの `<script>`(ホストが取得・実行し `load`/`error` を発火する)。
246    /// 【2026-10-17】動的に挿入した script を実行する仕組みが無く、YouTube の埋め込み等
247    /// (スクリプトを挿入して `onload` を待つ)が先へ進まなかった。
248    pub pending_dynamic_scripts: Vec<usize>,
249    /// JS が `createElement('link')` で作った `<link>`(文書へ挿入されたら `load` を送る)。
250    pub js_created_links: alloc::collections::BTreeSet<usize>,
251    /// 文書へ挿入されて `load` 待ちの `<link rel="stylesheet">`。
252    /// 【2026-11-04】挿入した `<link>` に `load` を一度も送っておらず、YouTube の kevlar がプレーヤーの CSS
253    /// (`player-css`)の `load` を `Promise.all` で待つ所(`FXM`)で止まった。従来の `Promise.all` は未決の要素を
254    /// 即座に完了扱いにしていたので素通りしていた(TODO B0 の調査で判明)。
255    pub pending_dynamic_links: Vec<usize>,
256    /// 木の操作の後に「post-connection steps」を走らせる要素(ツリー順。`<script>`・`<iframe>`・`<frame>`)。
257    /// 挿入の DOM 変更をすべて終えてから、JS 側(`Interp::run_post_connection_steps`)が先頭から 1 つずつ処理する
258    /// (HTML 標準・DOM 標準 §4.2.3 insert の手順 11。2026-11-27 Wave L)。
259    pub pending_post_connection: Vec<usize>,
260    /// 接続されたが post-connection steps がまだの `<iframe>`/`<frame>`(その間は `contentWindow` が null)。
261    pub frames_pending_setup: alloc::collections::BTreeSet<usize>,
262    /// 子フレーム(閲覧コンテキスト)の集合が変わり、`window.length`・`window[i]` を直す必要があるか。
263    pub frames_dirty: bool,
264    /// 子フレームを持ちうる部分木が外れたかもしれない(次の `run_post_connection_steps` で外れた枠を捨てる)。
265    pub frames_check: bool,
266    /// 要素に JS が付けた独自プロパティ(expando。`el.foo = 1`、組込みメソッドの上書きも含む)。
267    /// 【2026-10-17】要素のハンドル(`Obj::dom`)はアクセスのたびに作り直すため、未知の
268    /// プロパティへの代入は捨てられていた。YouTube の player は API メソッドを要素自身に付け、
269    /// 埋め込み側は `getElementById(...).getApiInterface` で準備完了を待つ。
270    pub expandos: BTreeMap<usize, BTreeMap<String, Value>>,
271    /// `Object.defineProperty(element, key, {get, set})` で要素に付けたアクセサ(ハンドルは
272    /// 毎回作り直されるので要素側に持つ)。キー → (getter, setter)。
273    pub node_accessors: BTreeMap<usize, BTreeMap<String, (Option<Value>, Option<Value>)>>,
274    /// 昇格済みのカスタム要素の原型(要素の添字 → 定義したクラスの prototype)。
275    /// 【2026-10-20】要素のハンドルはアクセスのたびに作り直すので、原型は要素側に持たせる。
276    pub node_protos: BTreeMap<usize, crate::os_lib::ecma::value::ObjRef>,
277    /// カスタム要素の反応(昇格・connected/disconnected)の待ち行列。
278    /// DOM の変更(`notify_child_list`・複製)が積み、`Interp::process_ce_reactions` が処理する。
279    pub ce_queue: Vec<CeEvent>,
280    /// 構築済みかどうか(未構築なら getElementById 等は空を返す)。
281    pub built: bool,
282    /// レイアウト後の要素矩形 (x, y, w, h)(ページ座標)。getBoundingClientRect /
283    /// offsetWidth 等が参照。レンダラが flatten 後に populate する。
284    pub rects: BTreeMap<usize, (i32, i32, i32, i32)>,
285    /// JS が寸法(clientWidth/offsetWidth/getBoundingClientRect 等)を読んだ要素と、その時の (幅, 高さ)。
286    /// 次のレイアウトで大きさが変わっていたら、測り直しを促す resize を出す(`Runtime::notify_layout_settled`)。
287    pub measured: BTreeMap<usize, (i32, i32)>,
288    /// レイアウト後の各要素のborder幅 (top, right, bottom, left)。
289    pub border_widths: BTreeMap<usize, (i32, i32, i32, i32)>,
290    /// 算出スタイル(カスケード後の specified_values、kebab-case キー)。
291    /// getComputedStyle が参照。レンダラがスタイル適用後に populate する。
292    /// レイアウトの `StyledNode::specified_values` を写さずに共有する(2026-11-04)。
293    pub computed_styles: BTreeMap<usize, alloc::rc::Rc<BTreeMap<String, String>>>,
294    /// サブスクロールコンテナの現在 scrollTop (node_idx → px)。
295    /// JS が `el.scrollTop = N` で書き込み、レンダラが再レイアウト後に同期する。
296    pub scroll_tops: BTreeMap<usize, i32>,
297    /// サブスクロールコンテナの現在 scrollLeft (node_idx → px)。
298    /// JS が `el.scrollLeft = N` で書き込み、レンダラが再レイアウト後に同期する。
299    pub scroll_lefts: BTreeMap<usize, i32>,
300    /// サブスクロールコンテナの scrollHeight (node_idx → px)。
301    /// レンダラが parse_and_layout 後に populate する(コンテナ高 + scroll_max_y)。
302    pub scroll_heights: BTreeMap<usize, i32>,
303    /// サブスクロールコンテナの scrollWidth (node_idx → px)。
304    /// レンダラが parse_and_layout 後に populate する(コンテナ幅 + scroll_max_x)。
305    pub scroll_widths: BTreeMap<usize, i32>,
306    /// リスナ ID の発番カウンタ(once / removeEventListener 照合用)。
307    pub next_listener_id: u64,
308    /// 登録済み MutationObserver。
309    pub mut_observers: Vec<MutObsReg>,
310    /// DOM 変更時に積まれるレコードキュー(observer_id, record)。
311    pub mut_records: Vec<(u32, MutRec)>,
312    /// MutationObserver の ID 発番カウンタ。
313    pub next_mut_obs_id: u32,
314    /// MutationObserver 通知用マイクロタスクのキュー待ちフラグ。
315    pub mut_microtask_pending: bool,
316    /// 登録済み IntersectionObserver。
317    pub io_observers: Vec<IntersectionObserverReg>,
318    /// IntersectionObserver の ID 発番カウンタ。
319    pub next_io_obs_id: u32,
320    /// 登録済み ResizeObserver。
321    pub ro_observers: Vec<ResizeObserverReg>,
322    /// ResizeObserver の ID 発番カウンタ。
323    pub next_ro_obs_id: u32,
324    /// `setPointerCapture`/`releasePointerCapture`/`hasPointerCapture`
325    /// (Pointer Events。丸ごと未対応だった)が捕捉中の (node_idx, pointerId) 集合。
326    /// この処理系のイベント配信はヒットテストベースのため、実際にその後の
327    /// pointer イベントをこの要素へ強制配送するところまでは配線しない
328    /// (`hasPointerCapture` が仕様どおりの真偽を返せるようにする状態管理のみの
329    /// 簡略実装。`inert` 属性のポインタ操作抑制のみ実装と同種の部分対応)。
330    pub pointer_captures: BTreeSet<(usize, i32)>,
331    /// `document.activeElement`/`element.focus()`/`.blur()`(HTML5。丸ごと
332    /// 未対応だった)。現在フォーカス中のノード index。`WebEngine::focused_id`
333    /// (レンダラ側の文字列キー版フォーカス状態)とは別に、JS 側から直接
334    /// 読み書きできる node index ベースの状態としてここに持つ。レンダラの
335    /// 実クリック/`autofocus` によるフォーカス変更も同期される(詳細は
336    /// `layout.rs`/`render.rs` の `focused_id` 代入箇所を参照)。id/name 属性を
337    /// 持たない要素へのレンダラ起点フォーカスは同期対象外(レンダラ自身の
338    /// 既存の制約と同じ)。
339    pub focused_idx: Option<usize>,
340    /// `window.scrollTo(x, y)`/`window.scroll(x, y)`(丸ごと未対応だった。
341    /// 実装はあったが `SCROLL_Y` という孤立した `static` へ書き込むのみで、
342    /// `window.scrollY`/実際のレンダラ描画位置のどちらにも一切反映されない
343    /// 死んだ経路だった。2026-07-16 発見)。JS→レンダラの片方向同期用の
344    /// 「保留中の絶対スクロール先」。`focused_idx`と同じ「レンダラが毎フレーム
345    /// 消費する」設計だが、フォーカスと違い同一フレーム内での即時反映が
346    /// 不要(次の描画で反映されれば十分)なため、`render.rs`の`draw()`冒頭
347    /// 1箇所でのみ消費すればよく、`.focus()`のような10箇所以上への配線は
348    /// 不要(改修規模がずっと小さい)。
349    pub pending_scroll_abs_y: Option<i32>,
350    /// `window.scrollBy(x, y)`(丸ごと未対応だった。`dom_noop`のまま)。
351    /// 複数回呼ばれた場合は加算し、次の描画で一括反映する。
352    pub pending_scroll_by_y: Option<i32>,
353    /// `element.onchange = fn`のような GlobalEventHandlers IDL 属性(関数値)の
354    /// 永続的な保管先。以前は`Obj::dom(idx)`(呼び出す度に新規生成される使い捨ての
355    /// ラッパーオブジェクト)自身の`.props`へ書き込んでいたため、代入直後に
356    /// そのRcが破棄されると値ごと消え、`dispatchEvent`側が同じ`Obj::dom(idx)`を
357    /// 新規生成して読み直しても常に見つからない(=ハンドラが一切発火しない)
358    /// 静かなバグだった。`listeners`(addEventListener系)と同じくDOM構造体側に
359    /// 持たせることで、どの`Obj::dom(idx)`インスタンス経由でも一貫して読み書き
360    /// できるようにする。キーは`(node_idx, "onchange"等のプロパティ名)`。
361    pub on_handlers: BTreeMap<(usize, String), Value>,
362    /// Document に紐づく単一の Selection オブジェクト(W3C Selection API)。
363    pub selection: Option<Value>,
364    /// Web Components: カスタム要素レジストリ
365    pub custom_elements: crate::os_lib::custom_elements::CustomElementRegistry,
366    /// Web Components: Shadow DOM レジストリ
367    pub shadow_tree: crate::os_lib::shadow_dom::ShadowTreeRegistry,
368    /// 子 `<iframe>` から `window.parent.postMessage` / `window.top.postMessage` で送られた保留メッセージ列 `(data, origin)`
369    pub pending_parent_messages: Vec<(Value, String)>,
370    /// 親ページから `<iframe src="...">` の `contentWindow.postMessage` で送られた保留メッセージ列 `(target_src, data, origin)`
371    pub pending_child_messages: Vec<(String, Value, String)>,
372    /// 各 iframe 要素ノードインデックスから生成済み `contentWindow` オブジェクトへのキャッシュ
373    pub iframe_content_windows: BTreeMap<usize, alloc::rc::Rc<core::cell::RefCell<crate::os_lib::ecma::value::Obj>>>,
374    /// 各 iframe 要素ノードインデックス → 子文書の `#document` ノードインデックス(WPT/接続済みフレーム用)
375    pub iframe_docs: BTreeMap<usize, usize>,
376    /// 逆引き: 子文書の `#document` ノードインデックス → iframe 要素ノードインデックス(`doc.defaultView` 用)
377    pub iframe_doc_to_elem: BTreeMap<usize, usize>,
378    /// 組み込みのグローバル名(ページのスクリプトを実行する前に決まっていたもの)。iframe の `contentWindow` にも置く。
379    pub builtin_global_names: Vec<String>,
380    /// 現在のスタイルシート(`RuleIndex`)で参照されている属性名(小文字)の集合。
381    /// `Some` のとき、ここに含まれず HTML 固有の表示属性でもない属性の `set_attr` / `remove_attr` は
382    /// レイアウトやスタイルに影響しないため `structural_dirty` を立てない(TODO P4b)。
383    pub css_referenced_attrs: Option<BTreeSet<String>>,
384}
385
386impl Default for DomBridge {
387    fn default() -> Self {
388        Self::new()
389    }
390}
391
392/// `ValidityState`(HTML5 制約検証)の個別フラグ。以前は `element.validity` が
393/// `valid`/`valueMissing`/`customError` の3つしか公開せず、`input.validity.
394/// patternMismatch`/`.typeMismatch`/`.rangeOverflow` 等、特定の制約だけを狙い撃ちして
395/// カスタムエラーメッセージを出し分ける定番パターンが常に `undefined`(falsy)に
396/// なっていた。
397#[derive(Default)]
398pub struct ValidityFlags {
399    pub value_missing: bool,
400    pub type_mismatch: bool,
401    pub pattern_mismatch: bool,
402    pub too_long: bool,
403    pub too_short: bool,
404    pub range_overflow: bool,
405    pub range_underflow: bool,
406    pub step_mismatch: bool,
407    pub bad_input: bool,
408    pub custom_error: bool,
409}
410impl ValidityFlags {
411    pub fn valid(&self) -> bool {
412        !(self.value_missing
413            || self.type_mismatch
414            || self.pattern_mismatch
415            || self.too_long
416            || self.too_short
417            || self.range_overflow
418            || self.range_underflow
419            || self.step_mismatch
420            || self.bad_input
421            || self.custom_error)
422    }
423}
424
425// ===== セレクタパーサ(`matches`/`closest`/`querySelector(All)` 共通) =====
426// 純粋ロジックは `crate::os_lib::dom_selector` に集約。
427use crate::os_lib::dom_selector::*;
428
429/// セレクタ(カンマ区切り)を群ごとの段に解析する(空の群は除く)。
430pub fn parse_selector_groups(selector: &str) -> Vec<Vec<SelStep>> {
431    split_top_level_commas(selector)
432        .iter()
433        .map(|part| build_steps(&tokenize_selector_group(part.trim())))
434        .filter(|steps| !steps.is_empty())
435        .collect()
436}
437
438impl DomBridge {
439    pub fn new() -> Self {
440        DomBridge {
441            nodes: Vec::new(),
442            extra_docs: 0,
443            attr_nodes: BTreeMap::new(),
444            has_attr_nodes: false,
445            attr_order: BTreeMap::new(),
446            ns_attrs: BTreeMap::new(),
447            attr_ns_order: BTreeMap::new(),
448            main_doctype: None,
449            ranges: BTreeMap::new(),
450            suppress_range_hook: false,
451            next_range_id: 1,
452            node_iters: BTreeMap::new(),
453            next_ni_id: 1,
454            html_collections: Vec::new(),
455            html_collection_expandos: BTreeMap::new(),
456            static_node_lists: Vec::new(),
457            has_shells: false,
458            node_doc: BTreeMap::new(),
459            template_owner_docs: BTreeMap::new(),
460            quirks_mode: false,
461            doc_impls: BTreeMap::new(),
462            listeners: Vec::new(),
463            dirty: false,
464            id_dirty: true,
465            structural_dirty: false,
466            dirty_causes: BTreeMap::new(),
467            pending_style_updates: Vec::new(),
468            pending_text_updates: Vec::new(),
469            js_created_scripts: alloc::collections::BTreeSet::new(),
470            pending_dynamic_scripts: Vec::new(),
471            js_created_links: alloc::collections::BTreeSet::new(),
472            pending_dynamic_links: Vec::new(),
473            pending_post_connection: Vec::new(),
474            frames_pending_setup: alloc::collections::BTreeSet::new(),
475            frames_dirty: false,
476            frames_check: false,
477            expandos: BTreeMap::new(),
478            node_accessors: BTreeMap::new(),
479            node_protos: BTreeMap::new(),
480            ce_queue: Vec::new(),
481            built: false,
482            rects: BTreeMap::new(),
483            measured: BTreeMap::new(),
484            border_widths: BTreeMap::new(),
485            computed_styles: BTreeMap::new(),
486            scroll_tops: BTreeMap::new(),
487            scroll_lefts: BTreeMap::new(),
488            scroll_heights: BTreeMap::new(),
489            scroll_widths: BTreeMap::new(),
490            next_listener_id: 1,
491            mut_observers: Vec::new(),
492            mut_records: Vec::new(),
493            next_mut_obs_id: 1,
494            mut_microtask_pending: false,
495            io_observers: Vec::new(),
496            next_io_obs_id: 1,
497            ro_observers: Vec::new(),
498            next_ro_obs_id: 1,
499            pointer_captures: BTreeSet::new(),
500            focused_idx: None,
501            pending_scroll_abs_y: None,
502            pending_scroll_by_y: None,
503            on_handlers: BTreeMap::new(),
504            selection: None,
505            custom_elements: crate::os_lib::custom_elements::CustomElementRegistry::new(),
506            shadow_tree: crate::os_lib::shadow_dom::ShadowTreeRegistry::new(),
507            pending_parent_messages: Vec::new(),
508            pending_child_messages: Vec::new(),
509            iframe_content_windows: BTreeMap::new(),
510            iframe_docs: BTreeMap::new(),
511            iframe_doc_to_elem: BTreeMap::new(),
512            builtin_global_names: Vec::new(),
513            css_referenced_attrs: None,
514        }
515    }
516
517    /// 未初期化の DOM ブリッジに最小限の html/head/body 骨格を遅延生成する。
518    pub fn ensure_default_document(&mut self) {
519        if self.nodes.is_empty() {
520            self.nodes.push(DomNode {
521                tag: String::from("html"),
522                is_text: false,
523                id: String::new(),
524                classes: Vec::new(),
525                style: BTreeMap::new(),
526                attrs: BTreeMap::new(),
527                text_override: None,
528                initial_text: String::new(),
529                parent: None,
530                children: alloc::vec![1, 2],
531                classes_dirty: false,
532                style_dirty: false,
533            });
534            self.nodes.push(DomNode {
535                tag: String::from("head"),
536                is_text: false,
537                id: String::new(),
538                classes: Vec::new(),
539                style: BTreeMap::new(),
540                attrs: BTreeMap::new(),
541                text_override: None,
542                initial_text: String::new(),
543                parent: Some(0),
544                children: Vec::new(),
545                classes_dirty: false,
546                style_dirty: false,
547            });
548            self.nodes.push(DomNode {
549                tag: String::from("body"),
550                is_text: false,
551                id: String::new(),
552                classes: Vec::new(),
553                style: BTreeMap::new(),
554                attrs: BTreeMap::new(),
555                text_override: None,
556                initial_text: String::new(),
557                parent: Some(0),
558                children: Vec::new(),
559                classes_dirty: false,
560                style_dirty: false,
561            });
562            self.built = true;
563        }
564    }
565
566    /// `element.onXXX = fn`(関数値)の永続的な書き込み。
567    pub fn set_on_handler(&mut self, node: usize, key: &str, val: Value) {
568        self.on_handlers.insert((node, key.to_string()), val);
569    }
570    /// `element.onXXX`の読み出し。未設定なら`None`。
571    pub fn get_on_handler(&self, node: usize, key: &str) -> Option<Value> {
572        self.on_handlers.get(&(node, key.to_string())).cloned()
573    }
574
575    /// `element.setPointerCapture(pointerId)`。
576    pub fn set_pointer_capture(&mut self, idx: usize, pointer_id: i32) {
577        self.pointer_captures.insert((idx, pointer_id));
578    }
579    /// `element.releasePointerCapture(pointerId)`。
580    pub fn release_pointer_capture(&mut self, idx: usize, pointer_id: i32) {
581        self.pointer_captures.remove(&(idx, pointer_id));
582    }
583    /// `element.hasPointerCapture(pointerId)`。
584    pub fn has_pointer_capture(&self, idx: usize, pointer_id: i32) -> bool {
585        self.pointer_captures.contains(&(idx, pointer_id))
586    }
587
588    /// MutationObserver: `parent_idx`(または `subtree: true` の祖先)で `childList` を監視している観察者がいるか。
589    fn has_child_list_observer(&self, parent_idx: usize) -> bool {
590        self.mut_observers.iter().any(|obs| {
591            obs.child_list
592                && (obs.target_idx == parent_idx
593                    || (obs.subtree && self.is_ancestor_of(obs.target_idx, parent_idx)))
594        })
595    }
596
597    /// MutationObserver: childList 変化を記録するヘルパ(兄弟情報なし版)。
598    fn notify_child_list(&mut self, parent_idx: usize, added: Vec<usize>, removed: Vec<usize>) {
599        self.notify_child_list_sib(parent_idx, added, removed, None, None);
600    }
601
602    /// MutationObserver: childList 変化を `previousSibling`/`nextSibling` 付きで記録するヘルパ。
603    fn notify_child_list_sib(
604        &mut self,
605        parent_idx: usize,
606        added: Vec<usize>,
607        removed: Vec<usize>,
608        prev_sibling: Option<usize>,
609        next_sibling: Option<usize>,
610    ) {
611        self.id_dirty = true;
612        if !removed.is_empty() && !self.iframe_docs.is_empty() {
613            self.frames_check = true;
614        }
615        if !self.custom_elements.is_empty() {
616            for &a in &added {
617                self.ce_queue.push(CeEvent::Inserted(a));
618            }
619            if self.is_attached(parent_idx) {
620                for &r in &removed {
621                    self.ce_queue.push(CeEvent::Removed(r));
622                }
623            }
624        }
625        let mut seen_ids: Vec<u32> = Vec::new();
626        for obs in &self.mut_observers {
627            if seen_ids.contains(&obs.id) {
628                continue;
629            }
630            let watches = obs.child_list
631                && (obs.target_idx == parent_idx
632                    || (obs.subtree && self.is_ancestor_of(obs.target_idx, parent_idx)));
633            if watches {
634                seen_ids.push(obs.id);
635                self.mut_microtask_pending = true;
636                self.mut_records.push((
637                    obs.id,
638                    MutRec {
639                        type_: "childList",
640                        target_idx: parent_idx,
641                        added: added.clone(),
642                        removed: removed.clone(),
643                        prev_sibling,
644                        next_sibling,
645                        attribute_name: None,
646                        attribute_namespace: None,
647                        old_value: None,
648                    },
649                ));
650            }
651        }
652        // DOM §4.3.3.1: 削除された部分木へ祖先(または親)の subtree 監視を transient registered observer として引き継ぐ。
653        if !removed.is_empty() && !self.mut_observers.is_empty() {
654            let mut transients: Vec<MutObsReg> = Vec::new();
655            for obs in &self.mut_observers {
656                if !obs.subtree {
657                    continue;
658                }
659                if obs.target_idx == parent_idx || self.is_ancestor_of(obs.target_idx, parent_idx) {
660                    let src = obs.transient_source.unwrap_or(obs.target_idx);
661                    for &r in &removed {
662                        let exists = self.mut_observers.iter().any(|o| o.id == obs.id && o.target_idx == r)
663                            || transients.iter().any(|o| o.id == obs.id && o.target_idx == r);
664                        if !exists {
665                            let mut t = obs.clone();
666                            t.target_idx = r;
667                            t.transient_source = Some(src);
668                            transients.push(t);
669                        }
670                    }
671                }
672            }
673            if !transients.is_empty() {
674                self.mut_microtask_pending = true;
675                self.mut_observers.extend(transients);
676            }
677        }
678    }
679
680    /// `idx` の直前の兄弟・直後の兄弟を `children` から取得する(削除・置換の MutationRecord 用)。
681    fn siblings_of_child(&self, parent: usize, child: usize) -> (Option<usize>, Option<usize>) {
682        let Some(kids) = self.nodes.get(parent).map(|n| &n.children) else {
683            return (None, None);
684        };
685        let Some(pos) = kids.iter().position(|&c| c == child) else {
686            return (None, None);
687        };
688        let prev = if pos > 0 { kids.get(pos - 1).copied() } else { None };
689        let next = kids.get(pos + 1).copied();
690        (prev, next)
691    }
692
693    /// `idx` が親を持っていれば外し、旧親の `childList` removal レコード(`prev/next` 付き)も積む。
694    fn detach_with_notify(&mut self, idx: usize) {
695        if idx >= self.nodes.len() {
696            return;
697        }
698        let old = self.nodes[idx].parent.map(|p| (p, self.siblings_of_child(p, idx)));
699        self.detach(idx);
700        if let Some((old_p, (prev, next))) = old {
701            self.notify_child_list_sib(old_p, Vec::new(), alloc::vec![idx], prev, next);
702        }
703    }
704
705    /// MutationObserver: 属性変化を記録するヘルパ。`attributeFilter` が指定された
706    /// 観察者はその一覧に無い属性名を無視し、`attributeOldValue` が指定された
707    /// 観察者にのみ変更前の値をレコードへ積む(以前はどちらのオプションも
708    /// 読み取られておらず、`attributeFilter` 指定時も無関係な属性の変化まで
709    /// 全て通知され、`oldValue` は常に `null` 固定だった)。
710    fn notify_attribute(&mut self, idx: usize, attr_name: &str, old_value: Option<&str>) {
711        self.notify_attribute_ns(idx, attr_name, None, old_value);
712    }
713
714    fn notify_attribute_ns(
715        &mut self,
716        idx: usize,
717        attr_name: &str,
718        attr_ns: Option<&str>,
719        old_value: Option<&str>,
720    ) {
721        // 昇格済みのカスタム要素で監視対象の属性なら attributeChangedCallback を積む。
722        if attr_ns.is_none() && self.node_protos.contains_key(&idx) && !attr_name.starts_with('_') {
723            let observed = self
724                .nodes
725                .get(idx)
726                .and_then(|n| self.custom_elements.get(&n.tag.to_lowercase()))
727                .is_some_and(|d| d.observes_attribute(attr_name));
728            if observed {
729                let new_value = self.get_attr(idx, attr_name);
730                self.ce_queue.push(CeEvent::Attr(
731                    idx,
732                    attr_name.to_string(),
733                    old_value.map(String::from),
734                    new_value,
735                ));
736            }
737        }
738        // DOM §4.3.3 queue a mutation record: 同一 observer が複数登録(例: target と ancestor で
739        // attributeOldValue が異なる)で一致するとき、いずれか 1 つでも oldValue を要求していれば付ける。
740        let mut matched_obs: Vec<(u32, bool)> = Vec::new();
741        for obs in &self.mut_observers {
742            let watches = obs.attributes
743                && (obs.target_idx == idx
744                    || (obs.subtree && self.is_ancestor_of(obs.target_idx, idx)))
745                && obs
746                    .attribute_filter
747                    .as_ref()
748                    .is_none_or(|f| f.iter().any(|n| n == attr_name));
749            if watches {
750                if let Some(entry) = matched_obs.iter_mut().find(|(id, _)| *id == obs.id) {
751                    entry.1 |= obs.attribute_old_value;
752                } else {
753                    matched_obs.push((obs.id, obs.attribute_old_value));
754                }
755            }
756        }
757        for (id, want_old) in matched_obs {
758            self.mut_microtask_pending = true;
759            self.mut_records.push((
760                id,
761                MutRec {
762                    type_: "attributes",
763                    target_idx: idx,
764                    added: Vec::new(),
765                    removed: Vec::new(),
766                    prev_sibling: None,
767                    next_sibling: None,
768                    attribute_name: Some(String::from(attr_name)),
769                    attribute_namespace: attr_ns.map(String::from),
770                    // 属性がまだ無かった(`old_value` が `None`)ときの oldValue は null。
771                    old_value: if want_old {
772                        old_value.map(String::from)
773                    } else {
774                        None
775                    },
776                },
777            ));
778        }
779    }
780
781    /// MutationObserver: テキストノードの内容変化を記録するヘルパ(丸ごと
782    /// 未対応だった。`notify_attribute`と対になる`characterData`版。
783    /// `idx`は変化した**テキストノード自身**のインデックス〔仕様上
784    /// `CharacterData`のmutationはテキストノード自身がtargetになる〕。
785    /// 2026-07-17 発見・実装)。
786    fn notify_character_data(&mut self, idx: usize, old_value: Option<&str>) {
787        let mut matched_obs: Vec<(u32, bool)> = Vec::new();
788        for obs in &self.mut_observers {
789            let watches = obs.character_data
790                && (obs.target_idx == idx
791                    || (obs.subtree && self.is_ancestor_of(obs.target_idx, idx)));
792            if watches {
793                if let Some(entry) = matched_obs.iter_mut().find(|(id, _)| *id == obs.id) {
794                    entry.1 |= obs.character_data_old_value;
795                } else {
796                    matched_obs.push((obs.id, obs.character_data_old_value));
797                }
798            }
799        }
800        for (id, want_old) in matched_obs {
801            self.mut_microtask_pending = true;
802            self.mut_records.push((
803                id,
804                MutRec {
805                    type_: "characterData",
806                    target_idx: idx,
807                    added: Vec::new(),
808                    removed: Vec::new(),
809                    prev_sibling: None,
810                    next_sibling: None,
811                    attribute_name: None,
812                    attribute_namespace: None,
813                    old_value: if want_old {
814                        Some(old_value.unwrap_or("").to_string())
815                    } else {
816                        None
817                    },
818                },
819            ));
820        }
821    }
822
823    /// レンダラがレイアウト後に要素矩形を登録する(getBoundingClientRect 等が参照)。
824    pub fn set_rect(&mut self, idx: usize, x: i32, y: i32, w: i32, h: i32) {
825        self.rects.insert(idx, (x, y, w, h));
826    }
827    pub fn get_rect(&self, idx: usize) -> Option<(i32, i32, i32, i32)> {
828        if let Some(r) = self.rects.get(&idx).copied() {
829            return Some(r);
830        }
831        // 未レイアウト時のインラインスタイル・属性・HTML5規定の固有寸法(intrinsic dimensions)フォールバック
832        let node = self.nodes.get(idx)?;
833        if node.is_text {
834            return None;
835        }
836        if node.style.get("display").map(|d| d.trim() == "none").unwrap_or(false) {
837            return Some((0, 0, 0, 0));
838        }
839
840        let parse_dim = |val: &str| -> Option<i32> {
841            let v = val.trim();
842            if let Some(px) = v.strip_suffix("px") {
843                px.trim().parse::<f64>().ok().map(|n| n as i32)
844            } else if let Ok(n) = v.parse::<f64>() {
845                Some(n as i32)
846            } else {
847                None
848            }
849        };
850
851        let mut w = node.style.get("width")
852            .and_then(|v| parse_dim(v))
853            .or_else(|| node.attrs.get("width").and_then(|v| parse_dim(v)));
854        let mut h = node.style.get("height")
855            .and_then(|v| parse_dim(v))
856            .or_else(|| node.attrs.get("height").and_then(|v| parse_dim(v)));
857
858        // HTML5 規定の固有寸法(canvas, video, audio 等)
859        match node.tag.as_str() {
860            "canvas" | "video" => {
861                if w.is_none() { w = Some(300); }
862                if h.is_none() { h = Some(150); }
863            }
864            "audio" => {
865                if w.is_none() { w = Some(300); }
866                if h.is_none() { h = Some(32); }
867            }
868            _ => {}
869        }
870
871        if let (Some(w_val), Some(h_val)) = (w, h) {
872            Some((0, 0, w_val.max(0), h_val.max(0)))
873        } else if let Some(w_val) = w {
874            Some((0, 0, w_val.max(0), 0))
875        } else { h.map(|h_val| (0, 0, 0, h_val.max(0))) }
876    }
877    /// JS が要素 `idx` の寸法を読んだことを記録する(読んだ時点の大きさ)。
878    pub fn note_measured(&mut self, idx: usize) {
879        let (w, h) = self.rects.get(&idx).map(|r| (r.2, r.3)).unwrap_or((0, 0));
880        self.measured.insert(idx, (w, h));
881    }
882    /// 記録した測定のうち、今の矩形と大きさが違うものがあるか(記録は消す)。
883    pub fn take_stale_measurements(&mut self) -> bool {
884        let m = core::mem::take(&mut self.measured);
885        m.iter().any(|(i, wh)| self.rects.get(i).map(|r| (r.2, r.3)).unwrap_or((0, 0)) != *wh)
886    }
887    pub fn set_border_widths(&mut self, idx: usize, top: i32, right: i32, bottom: i32, left: i32) {
888        self.border_widths.insert(idx, (top, right, bottom, left));
889    }
890    pub fn get_border_widths(&self, idx: usize) -> (i32, i32, i32, i32) {
891        self.border_widths.get(&idx).copied().unwrap_or((0, 0, 0, 0))
892    }
893    pub fn clear_rects(&mut self) {
894        self.rects.clear();
895        self.border_widths.clear();
896    }
897
898    /// 算出スタイルを登録(kebab-case プロパティ→値)。
899    pub fn set_computed_style(&mut self, idx: usize, prop: &str, val: &str) {
900        alloc::rc::Rc::make_mut(self.computed_styles.entry(idx).or_default())
901            .insert(String::from(prop), String::from(val));
902    }
903    /// 算出スタイルを取得(無ければインライン style → 空)。
904    pub fn get_computed(&self, idx: usize, prop: &str) -> String {
905        // `font-size` の算出値は常に px(レイアウト前・インラインの % / em でも)。
906        // 【2026-10-25】レイアウト前はインラインの値をそのまま返しており、YouTube の
907        // `Number(getComputedStyle(document.documentElement).fontSize.replace("px",""))`(html の
908        // `font-size: 62.5%`)が NaN になって、再生回数の回転表示の 1 行の高さが 0 になっていた。
909        if prop == "font-size" {
910            return alloc::format!("{}px", self.font_size_px(idx));
911        }
912        let raw = if let Some(v) = self.computed_styles.get(&idx).and_then(|m| m.get(prop)) {
913            v.clone()
914        } else {
915            self.nodes
916                .get(idx)
917                .and_then(|n| n.style.get(prop))
918                .cloned()
919                .unwrap_or_default()
920        };
921        // 指定値の文字列を算出値の形(`display: block flow` → `block`、`background-position: right 7%` → `93% 50%`、
922        // グラデーションの色は `rgb()` 等)へ整える。WPT ホスト実行器と同じ関数(2026-11-30)。カスタムプロパティは触らない。
923        if raw.is_empty() || prop.starts_with("--") {
924            return raw;
925        }
926        let font_px = self.font_size_px(idx) as f32;
927        crate::os_lib::css::serialize_computed_value(prop, &raw, font_px, 0.0).unwrap_or(raw)
928    }
929    /// 要素の文字サイズ(px)。算出済みの px、無ければインラインの指定を親の大きさで解き、
930    /// 無ければ親から継承する(ルートの既定は 16px)。
931    fn font_size_px(&self, idx: usize) -> u32 {
932        let mut chain = Vec::new();
933        let mut cur = Some(idx);
934        while let Some(i) = cur {
935            if chain.len() > 256 {
936                break;
937            }
938            chain.push(i);
939            cur = self.nodes.get(i).and_then(|n| n.parent);
940        }
941        // ルート側から順に解く。
942        let mut px: u32 = 16;
943        for &i in chain.iter().rev() {
944            let computed = self
945                .computed_styles
946                .get(&i)
947                .and_then(|m| m.get("font-size"))
948                .and_then(|v| v.trim().strip_suffix("px").and_then(|n| n.trim().parse::<f32>().ok()));
949            if let Some(v) = computed {
950                px = v as u32;
951                continue;
952            }
953            if let Some(v) = self.nodes.get(i).and_then(|n| n.style.get("font-size")) {
954                if let Some(n) = crate::os_lib::css::units::parse_font_size_with_parent(v, px as f32) {
955                    px = n;
956                }
957            }
958        }
959        px
960    }
961
962    /// このノードか祖先のどれかが `display: none` か(直前の配置で決まった値と、その後のインラインの指定で見る)。
963    /// 文書につながっていないノードも「表示されない」として true。
964    /// 【2026-11-14】TODO P4: 表示されていない要素のアニメの値を、全体の組み直しの理由にしないため。
965    pub fn is_in_display_none_subtree(&self, idx: usize) -> bool {
966        if !self.is_attached(idx) {
967            return true;
968        }
969        let mut cur = Some(idx);
970        let mut guard = 0usize;
971        while let Some(i) = cur {
972            let Some(n) = self.nodes.get(i) else { return false };
973            let inline = n.style.get("display").map(|v| v.trim().eq_ignore_ascii_case("none"));
974            let none = match inline {
975                Some(v) => v,
976                None => self
977                    .computed_styles
978                    .get(&i)
979                    .and_then(|m| m.get("display"))
980                    .is_some_and(|v| v.trim().eq_ignore_ascii_case("none")),
981            };
982            if none {
983                return true;
984            }
985            cur = n.parent;
986            guard += 1;
987            if guard > 4096 {
988                return false;
989            }
990        }
991        false
992    }
993
994    pub fn clear_computed(&mut self) {
995        self.computed_styles.clear();
996    }
997
998    /// ダーティ状態を全クリアする。
999    pub fn clear_dirty(&mut self) {
1000        self.dirty = false;
1001        self.structural_dirty = false;
1002        self.pending_style_updates.clear();
1003        self.pending_text_updates.clear();
1004    }
1005
1006    /// 単一テキスト子の軽量テキスト更新を記録する(TODO P4c/d)。
1007    /// 空文字・改行入り・style/script/title/textarea/option 要素は対象外とし、通常の構造ダーティへ落とす。
1008    pub fn record_text_update(&mut self, elem_idx: usize, text_idx: usize, val: &str) {
1009        let is_special_tag = self.nodes.get(elem_idx).is_some_and(|n| {
1010            matches!(
1011                n.tag.as_str(),
1012                "style" | "script" | "title" | "textarea" | "option"
1013            )
1014        });
1015        if val.is_empty() || val.contains('\n') || val.contains('\r') || is_special_tag {
1016            self.mark_structural_dirty_for("textContent");
1017            return;
1018        }
1019        self.dirty = true;
1020        Self::count_relayout_request();
1021        if let Some(pos) = self
1022            .pending_text_updates
1023            .iter()
1024            .position(|(_, t, _)| *t == text_idx)
1025        {
1026            self.pending_text_updates[pos] = (elem_idx, text_idx, val.to_string());
1027        } else {
1028            self.pending_text_updates
1029                .push((elem_idx, text_idx, val.to_string()));
1030        }
1031    }
1032
1033    /// 構造的な DOM 変更(ノード追加/削除/クラス/テキスト/属性変更等)を記録する。
1034    pub fn mark_structural_dirty(&mut self) {
1035        self.dirty = true;
1036        self.structural_dirty = true;
1037        Self::count_relayout_request();
1038        self.note_dirty_cause("other");
1039    }
1040
1041    /// 構造的な変更を、原因の名前つきで記録する(TODO P4 a、2026-11-14)。
1042    pub fn mark_structural_dirty_for(&mut self, cause: &str) {
1043        self.dirty = true;
1044        self.structural_dirty = true;
1045        Self::count_relayout_request();
1046        self.note_dirty_cause(cause);
1047    }
1048
1049    /// 属性の変更による構造的な変更を記録する(原因は `attr:名前`)。
1050    pub fn mark_structural_dirty_attr(&mut self, name: &str) {
1051        self.dirty = true;
1052        self.structural_dirty = true;
1053        Self::count_relayout_request();
1054        let key = alloc::format!("attr:{}", name);
1055        self.note_dirty_cause(&key);
1056    }
1057
1058    /// 「組み直しを要求した変更」を 1 件、`[PERF][SUMMARY]` の数え物へ足す(2026-11-18 TODO P9 (a))。
1059    /// 要求した場所で数えるので、組み直しの間引き(時間で決まる)に左右されない。
1060    /// 同じ試験ページなら実行ごとに同じ数になり、再レイアウトの回数の揺れに代わる比較の物差しになる。
1061    fn count_relayout_request() {
1062        crate::os_lib::platform::responsiveness_add(crate::os_lib::platform::Qty::RelayoutRequests, 1);
1063    }
1064
1065    /// 組み直しを招いた変更を、原因ごとに数える(`[LAYOUT][CAUSE]` で出す。出すたびに 0 へ戻す)。
1066    /// 原因の種類が増えすぎないよう、種類の数に上限を置く(超えた分は `…` にまとめる)。
1067    pub fn note_dirty_cause(&mut self, cause: &str) {
1068        if let Some(c) = self.dirty_causes.get_mut(cause) {
1069            *c = c.saturating_add(1);
1070            return;
1071        }
1072        let key = if self.dirty_causes.len() >= 96 { "…" } else { cause };
1073        *self.dirty_causes.entry(String::from(key)).or_insert(0) += 1;
1074    }
1075
1076    /// 数えた原因を多い順に取り出して 0 へ戻す。
1077    pub fn take_dirty_causes(&mut self) -> Vec<(String, u32)> {
1078        let mut v: Vec<(String, u32)> = core::mem::take(&mut self.dirty_causes).into_iter().collect();
1079        v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1080        v
1081    }
1082
1083    /// 新しいページの DOM 木からブリッジを再構築する(リスナはクリア)。
1084    ///
1085    /// 【2026-11-18 TODO R2 (b) ②】ノードの数だけ回るので、64 個ごとに止める確かめを呼ぶ([`bridge_poll`])。
1086    /// このタブだけ止める合図なら途中でやめ、`built` を偽のままにする(次のレイアウトはブリッジを使わず HTML から組み直す)。
1087    pub fn build_from(&mut self, root: &Node) {
1088        self.build_from_ordered(root, None);
1089    }
1090
1091    pub fn build_from_ordered(
1092        &mut self,
1093        root: &Node,
1094        order: Option<&crate::os_lib::dom::treebuilder::AttrOrderNode>,
1095    ) {
1096        self.nodes.clear();
1097        self.extra_docs = 0;
1098        self.attr_nodes.clear();
1099        self.has_attr_nodes = false;
1100        self.attr_order.clear();
1101        self.ns_attrs.clear();
1102        self.attr_ns_order.clear();
1103        self.node_iters.clear();
1104        self.static_node_lists.clear();
1105        self.main_doctype = None;
1106        self.ranges.clear();
1107        self.has_shells = false;
1108        self.node_doc.clear();
1109        self.template_owner_docs.clear();
1110        self.quirks_mode = false;
1111        self.doc_impls.clear();
1112        self.iframe_docs.clear();
1113        self.iframe_doc_to_elem.clear();
1114        self.js_created_scripts.clear();
1115        self.js_created_links.clear();
1116        self.pending_post_connection.clear();
1117        self.frames_pending_setup.clear();
1118        self.frames_dirty = false;
1119        self.frames_check = false;
1120        self.listeners.clear();
1121        self.selection = None;
1122        self.css_referenced_attrs = None;
1123        self.clear_dirty();
1124        self.built = true;
1125        // 【2026-11-18 TODO R5 (c)】ノードの数を先に数えて、配列をちょうどの大きさで 1 回だけ確保する。
1126        // 以前は 1 個ずつ足して倍々に伸ばしていたので、伸ばす瞬間に古い配列と 2 倍の新しい配列が同時に要り、
1127        // 4MB の入れ子の多い HTML(約 54 万ノード、1 ノード 216 バイト)では 226MB を一度に確保しようとして失敗していた。
1128        // 前のページの配列も先に手放す(`clear` は大きさを残すので、小さいページへ移っても大きな配列を持ち続けていた)。
1129        self.nodes = Vec::new();
1130        let total = Self::count_nodes(root);
1131        if self.nodes.try_reserve_exact(total).is_err() {
1132            crate::warn!("[JS] DOM ブリッジ: ノード {} 個の配列を確保できない(ヒープ不足)。ブリッジを組まない", total);
1133            self.built = false;
1134            return;
1135        }
1136        Self::collect(root, None, &mut self.nodes, order, &mut self.attr_order);
1137        if bridge_aborting() {
1138            self.built = false;
1139            return;
1140        }
1141        // 要素の initial_text を集める。
1142        // 【2026-11-18 TODO R5 (c)】要素の initial_text を読むのは textarea・option・output の値の既定値
1143        // (`value`・`defaultValue`・`text`)と title だけなので、その要素だけ集める。以前は全部の要素に
1144        // 部分木の文字全体の写しを持たせており、量が「文字の量 × 木の深さ」になっていた(深く入れ子にした
1145        // 大きなページでは、深さ 500 段で 2MB の文字が約 1GB の写しになる)。ほかの要素の文字は `collect_text` で毎回集める。
1146        let n = self.nodes.len();
1147        for i in 0..n {
1148            if bridge_poll() {
1149                self.built = false;
1150                return;
1151            }
1152            self.normalize_foreign_attrs(i);
1153            if !self.nodes[i].is_text && matches!(self.nodes[i].tag.as_str(), "textarea" | "option" | "output" | "title") {
1154                let t = self.collect_text(i);
1155                self.nodes[i].initial_text = t;
1156            }
1157            // パーサが作った中身の無い `<script>`(src も無い)は「already started」にならない(HTML の prepare は
1158            // 本文が空なら印を付けずに戻る)。後で子が足されたら 1 回だけ実行するので、未実行の集合へ入れる。
1159            if !self.nodes[i].is_text && self.nodes[i].tag == "script" && !self.nodes[i].attrs.contains_key("src") {
1160                let (_, _, text) = self.script_source(i);
1161                if text.is_empty() {
1162                    self.js_created_scripts.insert(i);
1163                }
1164            }
1165        }
1166        // `<details name="...">`排他グループの初期状態正規化(HTML5。丸ごと
1167        // 未対応だった)。クリック操作時の排他挙動は`render.rs`側で対応
1168        // 済みだが、HTML記述時点で同じ`name`を持つ複数の`<details open>`が
1169        // 並んでいた場合、仕様上は文書順で最後の1つだけが開いた状態のまま
1170        // 残り、それより前のものは自動的に閉じられる必要がある。この
1171        // パース直後の正規化が漏れていた。2026-07-18 発見・実装)。
1172        {
1173            let mut last_open_by_name: alloc::collections::BTreeMap<String, usize> = alloc::collections::BTreeMap::new();
1174            for i in 0..n {
1175                let node = &self.nodes[i];
1176                if node.tag == "details" && node.attrs.contains_key("open") {
1177                    if let Some(name) = node.attrs.get("name").filter(|s| !s.is_empty()) {
1178                        last_open_by_name.insert(name.clone(), i);
1179                    }
1180                }
1181            }
1182            for i in 0..n {
1183                let node = &self.nodes[i];
1184                if node.tag == "details" && node.attrs.contains_key("open") {
1185                    if let Some(name) = node.attrs.get("name").filter(|s| !s.is_empty()) {
1186                        if last_open_by_name.get(name) != Some(&i) {
1187                            self.nodes[i].attrs.remove("open");
1188                        }
1189                    }
1190                }
1191            }
1192        }
1193    }
1194
1195    /// 木のノードの数(根を含む)。深さは解析の上限(`dom::MAX_DOM_DEPTH`)で抑えてある。
1196    fn count_nodes(node: &Node) -> usize {
1197        1 + node.children.iter().map(Self::count_nodes).sum::<usize>()
1198    }
1199
1200    /// 木をドキュメント順(プリオーダ)に再帰収集。子インデックスを記録する。
1201    fn collect(
1202        node: &Node,
1203        parent: Option<usize>,
1204        out: &mut Vec<DomNode>,
1205        order: Option<&crate::os_lib::dom::treebuilder::AttrOrderNode>,
1206        attr_order: &mut BTreeMap<usize, Vec<String>>,
1207    ) -> usize {
1208        let idx = out.len();
1209        let dn = match &node.node_type {
1210            NodeType::Text(t) => DomNode {
1211                tag: String::new(),
1212                is_text: true,
1213                id: String::new(),
1214                classes: Vec::new(),
1215                style: BTreeMap::new(),
1216                attrs: BTreeMap::new(),
1217                text_override: None,
1218                initial_text: t.clone(),
1219                parent,
1220                children: Vec::new(),
1221                classes_dirty: false,
1222                style_dirty: false,
1223            },
1224            NodeType::Element {
1225                tag_name,
1226                attributes,
1227                classes,
1228                id,
1229            } => {
1230                if let Some(ord) = order {
1231                    if !ord.order.is_empty() {
1232                        attr_order.insert(idx, ord.order.clone());
1233                    }
1234                }
1235                let style =
1236                    parse_inline_style(attributes.get("style").map(|s| s.as_str()).unwrap_or(""));
1237                let (attrs, text) = Self::special_node_parts(tag_name, attributes);
1238                // HTML/DOM の class トークン分割は ASCII 空白のみ(`\v` や NBSP 等は区切らない)。
1239                let ascii_classes = match attributes.get("class") {
1240                    Some(cs) => split_ascii_ws(cs),
1241                    None => classes.clone(),
1242                };
1243                DomNode {
1244                    tag: tag_name.clone(),
1245                    is_text: false,
1246                    id: id.clone().unwrap_or_default(),
1247                    classes: ascii_classes,
1248                    style,
1249                    attrs,
1250                    text_override: text.clone(),
1251                    initial_text: text.unwrap_or_default(),
1252                    parent,
1253                    children: Vec::new(),
1254                    classes_dirty: false,
1255                    style_dirty: false,
1256                }
1257            }
1258        };
1259        out.push(dn);
1260        let mut kids = Vec::with_capacity(node.children.len());
1261        for (ci, c) in node.children.iter().enumerate() {
1262            // このタブだけ止める合図なら残りの子を読まない(`build_from` が後で `built` を偽にする)。
1263            if bridge_poll() {
1264                break;
1265            }
1266            let child_ord = order.and_then(|o| o.children.get(ci));
1267            kids.push(Self::collect(c, Some(idx), out, child_ord, attr_order));
1268        }
1269        out[idx].children = kids;
1270        idx
1271    }
1272
1273    /// 仕様どおりの木(`parse_html_document`)のコメント・DOCTYPE のノードを、ブリッジの表現(`#comment` はテキスト、
1274    /// `#doctype` は `_name`・`_publicId`・`_systemId`)へ直す。ふつうの要素は属性をそのまま返す。
1275    fn special_node_parts(tag: &str, attributes: &BTreeMap<String, String>) -> (BTreeMap<String, String>, Option<String>) {
1276        match tag {
1277            crate::os_lib::dom::COMMENT_TAG => (BTreeMap::new(), Some(attributes.get("data").cloned().unwrap_or_default())),
1278            "#pi" => {
1279                let mut m = BTreeMap::new();
1280                if let Some(t) = attributes.get("_target") {
1281                    m.insert(String::from("_target"), t.clone());
1282                }
1283                (m, Some(attributes.get("data").cloned().unwrap_or_default()))
1284            }
1285            crate::os_lib::dom::DOCTYPE_TAG => {
1286                let mut m = BTreeMap::new();
1287                m.insert(String::from("_name"), attributes.get("name").cloned().unwrap_or_default());
1288                m.insert(String::from("_publicId"), attributes.get("publicid").cloned().unwrap_or_default());
1289                m.insert(String::from("_systemId"), attributes.get("systemid").cloned().unwrap_or_default());
1290                (m, None)
1291            }
1292            _ => (attributes.clone(), None),
1293        }
1294    }
1295
1296    /// 補った `<head>`/`<body>` の殻を作る(`document.head`/`document.body` が `null` になる問題。2026-11-20 TODO S3)。
1297    ///
1298    /// ブラウザ用の解析(`parse_html`)は、`<head>`/`<body>` を書かないページの補った殻を外して中身を `<html>` の直下に並べる
1299    /// (レイアウトがその形を前提にしている)。DOM の仕様では `document.head`/`body` は常にあるので、最初に必要になったときだけ
1300    /// 殻を作り、`<html>` の子を移す。殻は `_implicit` 属性で印を付け、描画用の木(`to_dom_node`)・走査順(`tree_order`)では
1301    /// 飛ばして中身を直接並べる。このため描画の結果は殻が無いときと同じ。変更の通知・再レイアウトは起こさない。
1302    pub fn ensure_shells(&mut self) {
1303        if self.has_shells || self.nodes.is_empty() || self.nodes[0].tag != "html" {
1304            return;
1305        }
1306        self.has_shells = true;
1307        let kids = self.nodes[0].children.clone();
1308        let find = |dom: &DomBridge, names: &[&str]| kids.iter().position(|&c| dom.nodes.get(c).is_some_and(|n| !n.is_text && names.contains(&n.tag.as_str())));
1309        let head_pos = find(self, &["head"]);
1310        let body_pos = find(self, &["body", "frameset"]);
1311        if head_pos.is_some() && body_pos.is_some() {
1312            return;
1313        }
1314        // 先頭の「メタデータ」要素の並び(と、その間の空白だけのテキスト・コメント)が head の中身。
1315        let is_meta = |dom: &DomBridge, c: usize| -> bool {
1316            dom.nodes.get(c).is_some_and(|n| {
1317                if n.is_text {
1318                    n.text_override.as_deref().unwrap_or(&n.initial_text).trim().is_empty()
1319                } else {
1320                    n.tag == "#comment" || matches!(n.tag.as_str(), "title" | "meta" | "link" | "style" | "script" | "base" | "noscript" | "template")
1321                }
1322            })
1323        };
1324        let new_shell = |dom: &mut DomBridge, tag: &str| -> usize {
1325            let i = dom.new_element_node(tag);
1326            dom.nodes[i].attrs.insert(String::from("_implicit"), String::from("1"));
1327            i
1328        };
1329        let mut rest: Vec<usize> = kids.clone();
1330        let mut head_kids: Vec<usize> = Vec::new();
1331        let mut new_head = None;
1332        if head_pos.is_none() {
1333            let limit = body_pos.unwrap_or(kids.len());
1334            let n = (0..limit).take_while(|&i| is_meta(self, kids[i])).count();
1335            // 末尾の空白テキストは head に入れない(本文との間の空白)。
1336            head_kids = kids[..n].to_vec();
1337            rest = kids[n..].to_vec();
1338            new_head = Some(new_shell(self, "head"));
1339        }
1340        let mut new_body = None;
1341        if body_pos.is_none() {
1342            let b = new_shell(self, "body");
1343            let mut body_kids = Vec::new();
1344            let mut keep = Vec::new();
1345            let hp = head_pos.map(|p| kids[p]);
1346            let mut after_head = hp.is_none();
1347            for &c in &rest {
1348                if Some(c) == hp {
1349                    after_head = true;
1350                    keep.push(c);
1351                } else if after_head {
1352                    body_kids.push(c);
1353                } else {
1354                    keep.push(c);
1355                }
1356            }
1357            for &c in &body_kids {
1358                self.nodes[c].parent = Some(b);
1359            }
1360            self.nodes[b].children = body_kids;
1361            rest = keep;
1362            new_body = Some(b);
1363        }
1364        if let Some(h) = new_head {
1365            for &c in &head_kids {
1366                self.nodes[c].parent = Some(h);
1367            }
1368            self.nodes[h].children = head_kids;
1369            rest.insert(0, h);
1370        }
1371        if let Some(b) = new_body {
1372            rest.push(b);
1373        }
1374        for &c in &rest {
1375            self.nodes[c].parent = Some(0);
1376        }
1377        self.nodes[0].children = rest;
1378    }
1379
1380    /// `parent` の子を描画用の木の並びで列挙する(補った殻 `_implicit` は飛ばして中身を並べる)。
1381    fn flat_kids(&self, parent: usize, out: &mut Vec<usize>) {
1382        for &c in &self.nodes[parent].children {
1383            if self.nodes.get(c).is_some_and(|n| n.attrs.contains_key("_implicit")) {
1384                self.flat_kids(c, out);
1385            } else {
1386                out.push(c);
1387            }
1388        }
1389    }
1390
1391    /// 部分木のテキストを連結(textContent 相当)。現在値(override 優先)で集約。
1392    fn collect_text(&self, idx: usize) -> String {
1393        let node = &self.nodes[idx];
1394        if node.tag == "#comment" || node.tag == "#pi" {
1395            return node.text_override.clone().unwrap_or_else(|| node.initial_text.clone());
1396        }
1397        let mut s = String::new();
1398        self.collect_text_into(idx, &mut s);
1399        s
1400    }
1401    fn collect_text_into(&self, idx: usize, out: &mut String) {
1402        let node = &self.nodes[idx];
1403        if node.is_text {
1404            out.push_str(node.text_override.as_deref().unwrap_or(&node.initial_text));
1405            return;
1406        }
1407        for &c in &node.children {
1408            self.collect_text_into(c, out);
1409        }
1410    }
1411
1412    // ---- 参照系 ----
1413
1414    /// id → ノード添字の対応表を 1 回で作る。
1415    ///
1416    /// 【2026-08-05】`get_element_by_id` は全ノードの線形走査で、
1417    /// しかも各ノードで `is_attached` が親を辿る。
1418    /// レイアウト後の矩形反映では**要素 1 個ごとに**これを呼んでおり、
1419    /// O(要素 × ノード × 深さ) になっていた(実測で要素・ノードとも約 369)。
1420    ///
1421    /// 走査 1 回で表を作れば、引く側は O(log N) で済む。
1422    /// 条件(テキストノードでない・id が空でない・ルートから到達可能)は
1423    /// `get_element_by_id` と揃えてある。同じ id が複数あれば先勝ち
1424    /// (`find` と同じ)。
1425    ///
1426    /// 計算量: **O(N × D)**(N はノード数、D は木の深さ)。
1427    pub fn build_id_index(&self) -> alloc::collections::BTreeMap<&str, usize> {
1428        let mut map: alloc::collections::BTreeMap<&str, usize> =
1429            alloc::collections::BTreeMap::new();
1430        if !self.built {
1431            return map;
1432        }
1433        for i in 0..self.nodes.len() {
1434            let n = &self.nodes[i];
1435            if n.is_text || n.id.is_empty() {
1436                continue;
1437            }
1438            if !self.is_attached(i) {
1439                continue;
1440            }
1441            map.entry(n.id.as_str()).or_insert(i);
1442        }
1443        map
1444    }
1445
1446    /// 描画要素の `element_id` からノードの添字を引く。`id` の無い要素は `to_dom_node` が付けた
1447    /// 内部名 `_node_idx_<添字>` なので、`build_id_index` の表には載っていない。
1448    pub fn resolve_element_id(id_map: &BTreeMap<&str, usize>, element_id: &str) -> Option<usize> {
1449        if let Some(n) = element_id.strip_prefix("_node_idx_") {
1450            return n.parse().ok();
1451        }
1452        id_map.get(element_id).copied()
1453    }
1454
1455    pub fn get_element_by_id(&self, id: &str) -> Option<usize> {
1456        if !self.built || id.is_empty() {
1457            return None;
1458        }
1459        if let Some(rest) = id.strip_prefix("_node_idx_") {
1460            if let Ok(idx) = rest.parse::<usize>() {
1461                if idx < self.nodes.len() && !self.nodes[idx].is_text && self.is_attached(idx) {
1462                    return Some(idx);
1463                }
1464            }
1465        }
1466        (0..self.nodes.len())
1467            .find(|&i| !self.nodes[i].is_text && self.nodes[i].id == id && self.is_attached(i))
1468    }
1469
1470    /// node[0](ルート)から到達可能か。createElement 直後や remove 済みは false。
1471    /// Shadow DOM の要素は、ShadowRoot の host がルートから到達可能であれば接続中(true)。
1472    /// `node.isConnected`(丸ごと未対応だった)向けに公開する。
1473    pub fn is_attached(&self, idx: usize) -> bool {
1474        if self.main_doctype == Some(idx) {
1475            return true;
1476        }
1477        let mut cur = idx;
1478        let mut guard = 0;
1479        let limit = self.nodes.len() + 64;
1480        loop {
1481            if cur == 0 {
1482                return true;
1483            }
1484            match self.nodes.get(cur).and_then(|n| n.parent) {
1485                Some(p) => {
1486                    cur = p;
1487                    guard += 1;
1488                    if guard > limit {
1489                        return false;
1490                    }
1491                }
1492                None => {
1493                    if let Some(host) = self.shadow_tree.get_host_by_root(cur) {
1494                        cur = host;
1495                        guard += 1;
1496                        if guard > limit {
1497                            return false;
1498                        }
1499                    } else {
1500                        return false;
1501                    }
1502                }
1503            }
1504        }
1505    }
1506
1507    /// 単純セレクタ(`#id` / `.class` / `tag`、先頭一致)にマッチする最初のノード。
1508    pub fn query(&self, selector: &str) -> Option<usize> {
1509        self.query_scoped(selector, None, true).into_iter().next()
1510    }
1511
1512    /// セレクタにマッチする全ノード(ドキュメント順)。以前は `node_matches` と同じ
1513    /// 単純セレクタ限定の簡略実装が独立に重複しており、`querySelectorAll('div.active')`
1514    /// 等のコンパウンドセレクタが常に空になる同型のバグだった。`node_matches` と
1515    /// 共通の `compound_matches`/`match_selector_chain` に統一して解消する。
1516    /// DOM Standard §4.2.6 `getElementsByClassName`: ASCII 空白区切りで全クラスを持つ子孫を文書順に返す。
1517    pub fn get_elements_by_class_name(&self, root: Option<usize>, class_names: &str) -> Vec<usize> {
1518        let want = split_ascii_ws(class_names);
1519        if want.is_empty() || (!self.built && root.is_none()) || self.nodes.is_empty() {
1520            return Vec::new();
1521        }
1522        let mut out = Vec::new();
1523        let quirks = self.quirks_mode;
1524        let matches_all = |n: &DomNode| -> bool {
1525            !n.is_text
1526                && !n.tag.starts_with('#')
1527                && want.iter().all(|w| {
1528                    n.classes.iter().any(|c| {
1529                        if quirks {
1530                            c.eq_ignore_ascii_case(w)
1531                        } else {
1532                            c == w
1533                        }
1534                    })
1535                })
1536        };
1537        let mut stack: Vec<usize> = match root {
1538            Some(r) => self.nodes.get(r).map(|n| n.children.iter().rev().copied().collect()).unwrap_or_default(),
1539            None => alloc::vec![0],
1540        };
1541        let mut guard = 0usize;
1542        while let Some(i) = stack.pop() {
1543            guard += 1;
1544            if guard > self.nodes.len() + 1 {
1545                break;
1546            }
1547            if let Some(n) = self.nodes.get(i) {
1548                if matches_all(n) {
1549                    out.push(i);
1550                }
1551                stack.extend(n.children.iter().rev().copied());
1552            }
1553        }
1554        out
1555    }
1556
1557    pub fn query_all(&self, selector: &str) -> Vec<usize> {
1558        self.query_all_scoped(selector, None)
1559    }
1560
1561    /// `query_all` の `:scope` 対応版。`element.querySelectorAll`/`querySelector`
1562    /// の起点要素を `scope_root` として渡すと、セレクタ中の `:scope` 疑似クラス
1563    /// (Selectors Level 4。丸ごと未対応だった)がそのノードにのみ一致するように
1564    /// なる(詳細は `node_matches_scoped` 参照)。
1565    pub fn query_all_scoped(&self, selector: &str, scope_root: Option<usize>) -> Vec<usize> {
1566        self.query_scoped(selector, scope_root, false)
1567    }
1568
1569    /// `query_all_scoped` の本体。`first` なら最初の 1 個で止める。
1570    ///
1571    /// 【2026-10-24】従来はノードごとにセレクタの文字列を解析し直し、起点があっても全ノードを
1572    /// 祖先判定しながら走査していた。YouTube の視聴ページの JS 実行で確保の約 3 割が
1573    /// ここだった(`document.body` 等の参照も `query("body")` で全ノードを解析していた)。
1574    /// セレクタは 1 回だけ解析し、起点があればその部分木だけを文書順にたどる。
1575    fn query_scoped(&self, selector: &str, scope_root: Option<usize>, first: bool) -> Vec<usize> {
1576        let sel = selector.trim();
1577        let mut out = Vec::new();
1578        if (!self.built && scope_root.is_none()) || sel.is_empty() {
1579            return out;
1580        }
1581        let groups = parse_selector_groups(sel);
1582        if groups.is_empty() {
1583            return out;
1584        }
1585        if let Some(root) = scope_root {
1586            // 起点(自身を含む)の部分木を文書順(行きがけ順)にたどる。
1587            let mut stack: Vec<usize> = alloc::vec![root];
1588            let mut guard = 0usize;
1589            while let Some(i) = stack.pop() {
1590                guard += 1;
1591                if guard > self.nodes.len() + 1 {
1592                    break;
1593                }
1594                if self.node_matches_parsed(i, &groups, scope_root) {
1595                    out.push(i);
1596                    if first {
1597                        return out;
1598                    }
1599                }
1600                if let Some(n) = self.nodes.get(i) {
1601                    stack.extend(n.children.iter().rev().copied());
1602                }
1603            }
1604            return out;
1605        }
1606        for i in 0..self.nodes.len() {
1607            if self.nodes[i].is_text || !self.node_matches_parsed(i, &groups, None) || !self.is_attached(i) {
1608                continue;
1609            }
1610            out.push(i);
1611            if first {
1612                break;
1613            }
1614        }
1615        out
1616    }
1617
1618    // ---- 変更系 ----
1619
1620    /// 要素の textContent を設定。子孫テキストノードがあれば最初に値を入れ残りを空に、
1621    /// 無ければ既存の子を捨てて単一テキスト子を作る(createElement したノード等)。
1622    pub fn set_text_content(&mut self, idx: usize, val: &str) {
1623        self.set_text_content_raw(idx, val);
1624        // 未実行の `<script>`(またはその子のテキスト)の中身が変わった: children changed steps。
1625        if !self.js_created_scripts.is_empty() {
1626            self.script_children_changed(idx);
1627        }
1628    }
1629
1630    fn set_text_content_raw(&mut self, idx: usize, val: &str) {
1631        if idx >= self.nodes.len() || self.nodes[idx].tag == "#doctype" || self.nodes[idx].tag == "#document" {
1632            return;
1633        }
1634        if self.nodes[idx].tag == "#comment" || self.nodes[idx].tag == "#pi" {
1635            let old_val = self.nodes[idx]
1636                .text_override
1637                .as_deref()
1638                .unwrap_or(&self.nodes[idx].initial_text)
1639                .to_string();
1640            self.nodes[idx].text_override = Some(val.to_string());
1641            if !self.suppress_range_hook {
1642                self.ranges_replace_data(idx, 0, old_val.encode_utf16().count(), val.encode_utf16().count());
1643            }
1644            self.notify_character_data(idx, Some(&old_val));
1645            return;
1646        }
1647        // 要素の textContent への代入は、子をすべて取り除き、値が空でなければテキストノード
1648        // 1 つに置き換える(DOM 標準)。【2026-10-18】従来は子孫のテキストノードの中身を
1649        // 書き換えるだけで子の要素を残していた。YouTube のレンダラは `textContent = ""` の後に
1650        // 新しい中身を追加して差し替えるため、古い操作部が残り二重になっていた(押しても
1651        // 破棄済みの古いボタンに当たり、一時停止できなかった)。
1652        if !self.nodes[idx].is_text {
1653            if self.nodes[idx].children.is_empty() && val.is_empty() {
1654                return;
1655            }
1656            let attached = self.is_attached(idx);
1657            let is_meta_text = matches!(self.nodes[idx].tag.as_str(), "style" | "script" | "title");
1658            // 【2026-11-15】TODO P4b/P4d & A7: 子が既に単一のテキストノードだけで、`childList` を監視する
1659            // MutationObserver が無い場合(動画の再生時刻表示 `0:01` → `0:02` の毎秒更新など)、
1660            // 毎回新しい `DomNode` を `self.nodes` に push して古いノードを孤児化させるのを止め、
1661            // 既存のテキストノードをその場で書き換える。さらに文字列自体が同じなら再レイアウトも起こさない。
1662            if !val.is_empty() && self.nodes[idx].children.len() == 1 {
1663                let c0 = self.nodes[idx].children[0];
1664                if self.nodes.get(c0).is_some_and(|n| n.is_text)
1665                    && !self.has_child_list_observer(idx)
1666                    && self.ranges.is_empty()
1667                {
1668                    let cur_text = self.nodes[c0]
1669                        .text_override
1670                        .as_deref()
1671                        .unwrap_or(&self.nodes[c0].initial_text);
1672                    if !cur_text.is_empty() {
1673                        let same_text = cur_text == val;
1674                    if !same_text {
1675                        self.nodes[c0].text_override = Some(val.to_string());
1676                        if attached && (is_meta_text || !self.is_in_display_none_subtree(idx)) {
1677                            if is_meta_text {
1678                                self.mark_structural_dirty_for("textContent");
1679                            } else {
1680                                self.record_text_update(idx, c0, val);
1681                            }
1682                        }
1683                        }
1684                        return;
1685                    }
1686                }
1687            }
1688            let removed_now: Vec<usize> = self.nodes[idx].children.clone();
1689            self.ranges_children_cleared(idx, &removed_now);
1690            let removed: Vec<usize> = core::mem::take(&mut self.nodes[idx].children);
1691            for &c in &removed {
1692                if let Some(n) = self.nodes.get_mut(c) {
1693                    n.parent = None;
1694                }
1695            }
1696            let mut added = Vec::new();
1697            if !val.is_empty() {
1698                let t = self.new_text_node(val);
1699                self.inherit_owner(t, idx);
1700                self.nodes[t].parent = Some(idx);
1701                self.nodes[idx].children.push(t);
1702                added.push(t);
1703            }
1704            if !removed.is_empty() || !added.is_empty() {
1705                self.notify_child_list(idx, added, removed);
1706            }
1707            if attached && (is_meta_text || !self.is_in_display_none_subtree(idx)) {
1708                self.mark_structural_dirty_for("textContent");
1709            }
1710            return;
1711        }
1712        let text_nodes = self.descendant_text_nodes(idx);
1713        let mut any_changed = false;
1714        {
1715            for (k, t) in text_nodes.iter().enumerate() {
1716                let new_val = if k == 0 { val.to_string() } else { String::new() };
1717                // `characterData`監視(丸ごと未対応だった。テキストノードの
1718                // 内容が実際に変わった場合のみ通知する。詳細は
1719                // `notify_character_data`のdocコメント参照。2026-07-17
1720                // 発見・実装)。
1721                let old_val = self.nodes[*t]
1722                    .text_override
1723                    .as_deref()
1724                    .unwrap_or(&self.nodes[*t].initial_text)
1725                    .to_string();
1726                self.nodes[*t].text_override = Some(new_val.clone());
1727                if !self.suppress_range_hook {
1728                    self.ranges_replace_data(*t, 0, old_val.encode_utf16().count(), new_val.encode_utf16().count());
1729                }
1730                self.notify_character_data(*t, Some(&old_val));
1731                if old_val != new_val {
1732                    any_changed = true;
1733                }
1734            }
1735        }
1736        if any_changed && self.is_attached(idx) && !self.is_in_display_none_subtree(idx) {
1737            if text_nodes.len() == 1 && text_nodes[0] == idx {
1738                if let Some(parent_idx) = self.nodes[idx].parent {
1739                    if self
1740                        .nodes
1741                        .get(parent_idx)
1742                        .is_some_and(|p| !p.is_text && p.children.len() == 1)
1743                    {
1744                        self.record_text_update(parent_idx, idx, val);
1745                        return;
1746                    }
1747                }
1748            }
1749            self.mark_structural_dirty_for("text-node");
1750        }
1751    }
1752
1753    /// `node.normalize()`(丸ごと未対応だった。DOM 標準メソッドで、連続する隣接テキスト
1754    fn is_exclusive_text(&self, idx: usize) -> bool {
1755        self.nodes
1756            .get(idx)
1757            .is_some_and(|n| n.is_text && !n.attrs.contains_key("_cdata"))
1758    }
1759    /// ノードを1つに連結し、空のテキストノードを取り除く。`textContent` を何度も
1760    /// 部分的に書き換えた後などに呼ばれる定番の掃除用メソッド)。子孫を再帰的に処理する。
1761    pub fn normalize_node(&mut self, idx: usize) {
1762        if idx >= self.nodes.len() || self.nodes[idx].is_text {
1763            return;
1764        }
1765        // 部分木のテキストノードを文書順に集める(DOM Standard の normalize: 各 exclusive Text について、空なら取り除き、
1766        // そうでなければ直後に連なる exclusive Text を併せる。CDATASection は対象外)。
1767        let mut texts: Vec<usize> = Vec::new();
1768        let mut stack: Vec<usize> = self.nodes[idx].children.iter().rev().copied().collect();
1769        while let Some(i) = stack.pop() {
1770            if self.is_exclusive_text(i) {
1771                texts.push(i);
1772            } else {
1773                stack.extend(self.nodes[i].children.iter().rev().copied());
1774            }
1775        }
1776        for t in texts {
1777            let Some(parent) = self.nodes[t].parent else { continue };
1778            let mut length = self.text_of(t).encode_utf16().count();
1779            if length == 0 {
1780                self.remove_node(t);
1781                continue;
1782            }
1783            let siblings = self.nodes[parent].children.clone();
1784            let Some(pos) = siblings.iter().position(|&c| c == t) else { continue };
1785            let mut merged = self.text_of(t);
1786            let mut run: Vec<usize> = Vec::new();
1787            for &c in siblings.iter().skip(pos + 1) {
1788                if !self.is_exclusive_text(c) {
1789                    break;
1790                }
1791                let index = self.nodes[parent].children.iter().position(|&x| x == c).unwrap_or(0);
1792                self.ranges_normalize_merge(t, c, parent, index, length);
1793                let more = self.text_of(c);
1794                length += more.encode_utf16().count();
1795                merged.push_str(&more);
1796                run.push(c);
1797            }
1798            if !run.is_empty() {
1799                self.nodes[t].text_override = Some(merged);
1800                for c in run {
1801                    self.remove_node(c);
1802                }
1803            }
1804        }
1805    }
1806    /// テキストノードの実効テキスト(`text_override` があればそれ、無ければ
1807    /// `initial_text`)。`collect_text_into` と同じ参照パターン。
1808    fn text_of(&self, idx: usize) -> String {
1809        let n = &self.nodes[idx];
1810        n.text_override.as_deref().unwrap_or(&n.initial_text).to_string()
1811    }
1812
1813    // ---- 構造変更(createElement / appendChild / removeChild / innerHTML) ----
1814
1815    fn new_element_node(&mut self, tag: &str) -> usize {
1816        let idx = self.nodes.len();
1817        let lower_tag = tag.to_ascii_lowercase();
1818        let mut attrs = BTreeMap::new();
1819        if self.custom_elements.is_defined(&lower_tag) {
1820            attrs.insert(String::from("_defined"), String::from("true"));
1821        }
1822        self.nodes.push(DomNode {
1823            tag: lower_tag,
1824            is_text: false,
1825            id: String::new(),
1826            classes: Vec::new(),
1827            style: BTreeMap::new(),
1828            attrs,
1829            text_override: None,
1830            initial_text: String::new(),
1831            parent: None,
1832            children: Vec::new(),
1833            classes_dirty: false,
1834            style_dirty: false,
1835        });
1836        idx
1837    }
1838
1839    fn new_text_node(&mut self, text: &str) -> usize {
1840        let idx = self.nodes.len();
1841        self.nodes.push(DomNode {
1842            tag: String::new(),
1843            is_text: true,
1844            id: String::new(),
1845            classes: Vec::new(),
1846            style: BTreeMap::new(),
1847            attrs: BTreeMap::new(),
1848            text_override: Some(text.to_string()),
1849            initial_text: text.to_string(),
1850            parent: None,
1851            children: Vec::new(),
1852            classes_dirty: false,
1853            style_dirty: false,
1854        });
1855        idx
1856    }
1857
1858    /// `document.createElement(tag)`。デタッチ状態のノードを返す。
1859    /// W3C HTML 仕様準拠: `<script>` 要素は生成時に `async = true` が初期設定される。
1860    /// 名前空間つきの(HTML 以外の)要素を作る。`script`・`link` の特別扱いをしない(`createElementNS`)。
1861    pub fn create_element_plain(&mut self, tag: &str) -> usize {
1862        self.new_element_node(tag)
1863    }
1864
1865    pub fn create_element(&mut self, tag: &str) -> usize {
1866        let idx = self.new_element_node(tag);
1867        if tag.eq_ignore_ascii_case("script") {
1868            self.js_created_scripts.insert(idx);
1869            self.set_attr(idx, "async", "async");
1870        } else if tag.eq_ignore_ascii_case("link") {
1871            self.js_created_links.insert(idx);
1872        }
1873        idx
1874    }
1875
1876    /// `<script>` の `(src 属性, type 属性, 本文)`。
1877    pub fn script_source(&self, idx: usize) -> (Option<String>, String, String) {
1878        let Some(n) = self.nodes.get(idx) else { return (None, String::new(), String::new()) };
1879        let src = n.attrs.get("src").filter(|s| !s.trim().is_empty()).cloned();
1880        let ty = n.attrs.get("type").cloned().unwrap_or_default();
1881        let text = match &n.text_override {
1882            Some(t) => t.clone(),
1883            None => n
1884                .children
1885                .iter()
1886                .filter_map(|&c| self.nodes.get(c))
1887                .filter(|c| c.is_text)
1888                .map(|c| c.text_override.clone().unwrap_or_else(|| c.initial_text.clone()))
1889                .collect(),
1890        };
1891        (src, ty, text)
1892    }
1893
1894    /// 文書(ノード 0 を根とする木)に繋がっているか。
1895    pub fn is_connected(&self, mut idx: usize) -> bool {
1896        let mut guard = 0;
1897        while let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
1898            idx = p;
1899            guard += 1;
1900            if guard > 10_000 {
1901                return false;
1902            }
1903        }
1904        idx == 0
1905    }
1906
1907    /// `<iframe>`・`<frame>`(子の閲覧コンテキストを持つ要素)か。
1908    pub fn is_frame_element(&self, idx: usize) -> bool {
1909        self.nodes.get(idx).is_some_and(|n| !n.is_text && matches!(n.tag.as_str(), "iframe" | "frame"))
1910    }
1911
1912    /// ノードが閲覧コンテキストを持つ文書に(Shadow tree 経由も含めて)繋がっていれば、その文書を返す
1913    /// (`Some(None)` は主文書、`Some(Some(d))` は子フレームの `#document` ノード `d`)。
1914    /// `createHTMLDocument()` などの閲覧コンテキストの無い文書や、どこにも繋がっていなければ `None`。
1915    pub fn browsing_context_doc(&self, idx: usize) -> Option<Option<usize>> {
1916        let mut cur = idx;
1917        let mut guard = 0usize;
1918        let limit = self.nodes.len() + 64;
1919        loop {
1920            guard += 1;
1921            if guard > limit {
1922                return None;
1923            }
1924            if cur == 0 || self.main_doctype == Some(cur) {
1925                return Some(None);
1926            }
1927            match self.nodes.get(cur).and_then(|n| n.parent) {
1928                Some(p) => cur = p,
1929                None => {
1930                    if let Some(h) = self.shadow_tree.get_host_by_root(cur) {
1931                        cur = h;
1932                    } else if let Some(&fe) = self.iframe_doc_to_elem.get(&cur) {
1933                        // 子フレームの文書: 枠の要素がさらに閲覧コンテキストのある文書に繋がっているか。
1934                        return self.browsing_context_doc(fe).map(|_| Some(cur));
1935                    } else {
1936                        return None;
1937                    }
1938                }
1939            }
1940        }
1941    }
1942
1943    /// 挿入(または子の変化)の後で、post-connection steps の対象を `pending_post_connection` へツリー順に積む。
1944    /// `parent` が未実行の `<script>` なら、その「children changed steps」として先に積む(挿入された子より前に走る)。
1945    /// 部分木は前順(Shadow root も含む shadow-including tree order)でたどる。
1946    fn queue_post_connection(&mut self, parent: Option<usize>, roots: &[usize]) {
1947        if let Some(p) = parent {
1948            self.script_children_changed(p);
1949        }
1950        let mut stack: Vec<usize> = roots.iter().rev().copied().collect();
1951        let mut guard = 0usize;
1952        while let Some(i) = stack.pop() {
1953            guard += 1;
1954            if guard > self.nodes.len() + 64 {
1955                break;
1956            }
1957            let Some(n) = self.nodes.get(i) else { continue };
1958            if n.is_text {
1959                continue;
1960            }
1961            let is_script = n.tag == "script";
1962            let is_frame = matches!(n.tag.as_str(), "iframe" | "frame");
1963            if ((is_script && self.js_created_scripts.contains(&i)) || is_frame) && self.browsing_context_doc(i).is_some() {
1964                if is_frame {
1965                    self.frames_pending_setup.insert(i);
1966                }
1967                self.pending_post_connection.push(i);
1968            }
1969            // JS が作った `<link rel="stylesheet" href>` も挿入時に 1 回だけ `load` 待ちへ積む。
1970            if self.js_created_links.contains(&i) && self.is_connected(i) {
1971                let is_css = self.get_attr(i, "rel").is_some_and(|r| r.to_ascii_lowercase().contains("stylesheet"));
1972                if is_css && self.get_attr(i, "href").is_some_and(|h| !h.is_empty()) {
1973                    self.js_created_links.remove(&i);
1974                    self.pending_dynamic_links.push(i);
1975                }
1976            }
1977            let kids: Vec<usize> = self.nodes.get(i).map(|n| n.children.clone()).unwrap_or_default();
1978            for &c in kids.iter().rev() {
1979                stack.push(c);
1980            }
1981            if let Some(r) = self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx) {
1982                stack.push(r);
1983            }
1984        }
1985    }
1986
1987    /// 未実行の `<script>` の子が変わった(HTML の「children changed steps」)。閲覧コンテキストのある文書に
1988    /// 繋がっていれば、post-connection の処理で準備(本文があれば実行)する。テキストノードなら親の script を見る。
1989    pub fn script_children_changed(&mut self, idx: usize) {
1990        let target = match self.nodes.get(idx) {
1991            Some(n) if n.is_text => match n.parent {
1992                Some(p) => p,
1993                None => return,
1994            },
1995            Some(_) => idx,
1996            None => return,
1997        };
1998        if self.js_created_scripts.contains(&target) && self.browsing_context_doc(target).is_some() {
1999            self.pending_post_connection.push(target);
2000        }
2001    }
2002
2003    /// `<iframe>`/`<frame>` の子文書(about:blank)を作る(既にあれば何もしない)。作ったら true。
2004    pub fn ensure_frame_doc(&mut self, idx: usize) -> bool {
2005        if self.iframe_docs.contains_key(&idx) || !self.is_frame_element(idx) {
2006            return false;
2007        }
2008        let doc_idx = self.create_document_node("text/html", true);
2009        if let Some(dn) = self.nodes.get_mut(doc_idx) {
2010            dn.attrs.insert(String::from("_url"), String::from("about:blank"));
2011        }
2012        let html = self.create_element("html");
2013        let head = self.create_element("head");
2014        let body = self.create_element("body");
2015        self.append_child(html, head);
2016        self.append_child(html, body);
2017        self.set_owner_subtree(html, Some(doc_idx));
2018        self.append_child(doc_idx, html);
2019        self.iframe_docs.insert(idx, doc_idx);
2020        self.iframe_doc_to_elem.insert(doc_idx, idx);
2021        self.frames_dirty = true;
2022        true
2023    }
2024
2025    /// 閲覧コンテキストのある文書から外れた `<iframe>`/`<frame>` の子文書・`contentWindow` を捨てる
2026    /// (HTML の removing steps の「destroy a child navigable」。unload/pagehide は同期で送らない)。
2027    /// 何か捨てたら true(`frames_dirty` も立てる)。
2028    pub fn prune_disconnected_frames(&mut self) -> bool {
2029        let mut any = false;
2030        loop {
2031            let gone: Vec<usize> = self
2032                .iframe_docs
2033                .keys()
2034                .copied()
2035                .filter(|&e| self.browsing_context_doc(e).is_none())
2036                .collect();
2037            if gone.is_empty() {
2038                break;
2039            }
2040            for e in gone {
2041                if let Some(d) = self.iframe_docs.remove(&e) {
2042                    self.iframe_doc_to_elem.remove(&d);
2043                }
2044                self.iframe_content_windows.remove(&e);
2045                self.frames_pending_setup.remove(&e);
2046                if let Some(n) = self.nodes.get_mut(e) {
2047                    n.attrs.remove("_iframe_loaded");
2048                }
2049            }
2050            any = true;
2051        }
2052        if any {
2053            self.frames_dirty = true;
2054        }
2055        any
2056    }
2057
2058    /// 部分木 `root` の子孫のうち、子文書を持つ `<iframe>`/`<frame>`(ツリー順。Shadow tree は含めない)。
2059    pub fn child_frames_of(&self, root: usize) -> Vec<usize> {
2060        let mut out = Vec::new();
2061        let mut stack: Vec<usize> = self.nodes.get(root).map(|n| n.children.iter().rev().copied().collect()).unwrap_or_default();
2062        let mut guard = 0usize;
2063        while let Some(i) = stack.pop() {
2064            guard += 1;
2065            if guard > self.nodes.len() + 64 {
2066                break;
2067            }
2068            let Some(n) = self.nodes.get(i) else { continue };
2069            if n.is_text {
2070                continue;
2071            }
2072            if matches!(n.tag.as_str(), "iframe" | "frame") && self.iframe_docs.contains_key(&i) {
2073                out.push(i);
2074            }
2075            stack.extend(n.children.iter().rev().copied());
2076        }
2077        out
2078    }
2079
2080    /// `document.createTextNode(text)`。
2081    pub fn create_text_node(&mut self, text: &str) -> usize {
2082        self.new_text_node(text)
2083    }
2084
2085    /// `document.createComment(text)`。
2086    pub fn create_comment(&mut self, text: &str) -> usize {
2087        let idx = self.nodes.len();
2088        self.nodes.push(DomNode {
2089            tag: String::from("#comment"),
2090            is_text: false,
2091            id: String::new(),
2092            classes: Vec::new(),
2093            style: BTreeMap::new(),
2094            attrs: BTreeMap::new(),
2095            text_override: Some(text.to_string()),
2096            initial_text: text.to_string(),
2097            parent: None,
2098            children: Vec::new(),
2099            classes_dirty: false,
2100            style_dirty: false,
2101        });
2102        idx
2103    }
2104
2105    /// `document.implementation.createDocumentType(name, publicId, systemId)`。`#doctype` という特殊タグのノード
2106    /// (`name`・`publicId`・`systemId` は内部属性 `_name`・`_publicId`・`_systemId`)。
2107    pub fn create_doctype(&mut self, name: &str, public_id: &str, system_id: &str) -> usize {
2108        let idx = self.nodes.len();
2109        let mut attrs = BTreeMap::new();
2110        attrs.insert(String::from("_name"), name.to_string());
2111        attrs.insert(String::from("_publicId"), public_id.to_string());
2112        attrs.insert(String::from("_systemId"), system_id.to_string());
2113        self.nodes.push(DomNode {
2114            tag: String::from("#doctype"),
2115            is_text: false,
2116            id: String::new(),
2117            classes: Vec::new(),
2118            style: BTreeMap::new(),
2119            attrs,
2120            text_override: None,
2121            initial_text: String::new(),
2122            parent: None,
2123            children: Vec::new(),
2124            classes_dirty: false,
2125            style_dirty: false,
2126        });
2127        idx
2128    }
2129
2130    /// `document.createProcessingInstruction(target, data)`。`#pi` という特殊タグのノードで、対象は内部属性 `_target`、
2131    /// データは `text_override`(コメントと同じ CharacterData)。
2132    pub fn create_processing_instruction(&mut self, target: &str, data: &str) -> usize {
2133        let idx = self.nodes.len();
2134        let mut attrs = BTreeMap::new();
2135        attrs.insert(String::from("_target"), target.to_string());
2136        self.nodes.push(DomNode {
2137            tag: String::from("#pi"),
2138            is_text: false,
2139            id: String::new(),
2140            classes: Vec::new(),
2141            style: BTreeMap::new(),
2142            attrs,
2143            text_override: Some(data.to_string()),
2144            initial_text: data.to_string(),
2145            parent: None,
2146            children: Vec::new(),
2147            classes_dirty: false,
2148            style_dirty: false,
2149        });
2150        idx
2151    }
2152
2153    /// `document.createDocumentFragment()`(丸ごと未対応だった)。仕様どおり、
2154    /// `#fragment` という特殊タグの要素として表現する。この要素自身は決して
2155    /// `root` から到達可能(`is_attached`)にならず、`append_child`/`insert_before`
2156    /// に渡されると自身ではなく子要素群がそのまま挿入先へ移動し、自身は空になる
2157    /// (実 DOM の DocumentFragment の「挿入すると中身だけが移動する」挙動を再現)。
2158    pub fn create_document_fragment(&mut self) -> usize {
2159        self.new_element_node("#fragment")
2160    }
2161
2162    // ---- Attr ノード(`#attr`。DOM Standard §4.9。2026-11-20 TODO S3)----
2163    //
2164    // 属性の実体はこれまでどおり要素の `attrs`(名前 → 値)。`Attr` ノードは `getAttributeNode`・`attributes[i]` などで
2165    // 必要になったときに作り(`attr_nodes` に (要素, 修飾名) で覚えるので同じ属性は同じノード)、`value` は要素の属性を読み書きする。
2166    // 要素から外れる(`removeAttribute` など)と `_aval` に最後の値を持った孤立ノードになる。
2167    // 内部属性: `_aname` 修飾名・`_ans` 名前空間・`_aval` 孤立時の値・`_aowner` 持ち主の要素。要素側の名前空間は `_ans:修飾名`。
2168
2169    /// 要素 `elem` の属性 `qname` の名前空間。
2170    pub fn attr_ns(&self, elem: usize, qname: &str) -> Option<String> {
2171        if let Some(ns) = self.ns_attrs.get(&elem).and_then(|list| {
2172            list.iter()
2173                .find(|(_, qn, _)| qn == qname)
2174                .map(|(ns, _, _)| ns.clone())
2175        }) {
2176            return Some(ns);
2177        }
2178        self.nodes.get(elem)?.attrs.get(&format!("_ans:{}", qname)).cloned()
2179    }
2180
2181    /// 孤立した `Attr` ノードを作る。
2182    pub fn new_attr_node(&mut self, qname: &str, ns: Option<&str>, value: &str) -> usize {
2183        let idx = self.nodes.len();
2184        let mut attrs = BTreeMap::new();
2185        attrs.insert(String::from("_aname"), qname.to_string());
2186        attrs.insert(String::from("_aval"), value.to_string());
2187        if let Some(n) = ns {
2188            attrs.insert(String::from("_ans"), n.to_string());
2189        }
2190        self.nodes.push(DomNode {
2191            tag: String::from("#attr"),
2192            is_text: false,
2193            id: String::new(),
2194            classes: Vec::new(),
2195            style: BTreeMap::new(),
2196            attrs,
2197            text_override: None,
2198            initial_text: String::new(),
2199            parent: None,
2200            children: Vec::new(),
2201            classes_dirty: false,
2202            style_dirty: false,
2203        });
2204        self.has_attr_nodes = true;
2205        idx
2206    }
2207
2208    /// 要素 `elem` の属性 `qname` の `Attr` ノード(無ければ作る。属性が無ければ `None`)。
2209    pub fn attr_node_for(&mut self, elem: usize, qname: &str) -> Option<usize> {
2210        if qname.starts_with('_') {
2211            return None;
2212        }
2213        for (ns, qn) in self.attr_entries(elem) {
2214            if qn == qname {
2215                return self.attr_node_for_ns(elem, ns.as_deref(), &qn);
2216            }
2217        }
2218        None
2219    }
2220
2221    /// 名前空間つき属性の `Attr` ノードを取得または生成する。
2222    pub fn attr_node_for_ns(&mut self, elem: usize, ns: Option<&str>, qname: &str) -> Option<usize> {
2223        if qname.starts_with('_') {
2224            return None;
2225        }
2226        let ns_clean = ns.filter(|s| !s.is_empty());
2227        let val = match ns_clean {
2228            None => {
2229                if !self.has_attr(elem, qname) {
2230                    return None;
2231                }
2232                self.get_attr(elem, qname).unwrap_or_default()
2233            }
2234            Some(u) => {
2235                let local = qname.split_once(':').map(|(_, l)| l).unwrap_or(qname);
2236                self.get_attr_ns(elem, Some(u), local)?
2237            }
2238        };
2239        let key = match ns_clean {
2240            None => qname.to_string(),
2241            Some(u) => format!("{}\x01{}", u, qname),
2242        };
2243        if let Some(&i) = self.attr_nodes.get(&(elem, key.clone())) {
2244            return Some(i);
2245        }
2246        let i = self.new_attr_node(qname, ns_clean, &val);
2247        self.nodes[i].attrs.insert(String::from("_aowner"), elem.to_string());
2248        if let Some(own) = self.node_document(elem) {
2249            self.node_doc.insert(i, own);
2250        }
2251        self.attr_nodes.insert((elem, key), i);
2252        Some(i)
2253    }
2254
2255    /// 属性 `qname` が要素から外れるとき、`Attr` ノードを孤立させて最後の値を持たせる。
2256    pub fn detach_attr_node(&mut self, elem: usize, qname: &str, last_value: &str) {
2257        if let Some(i) = self.attr_nodes.remove(&(elem, qname.to_string())) {
2258            if let Some(n) = self.nodes.get_mut(i) {
2259                n.attrs.remove("_aowner");
2260                n.attrs.insert(String::from("_aval"), last_value.to_string());
2261            }
2262        }
2263    }
2264
2265    /// `Attr` ノードの現在値(持ち主があれば要素の属性)。
2266    pub fn attr_value(&self, attr: usize) -> String {
2267        let Some(n) = self.nodes.get(attr) else { return String::new() };
2268        if let (Some(o), Some(name)) = (n.attrs.get("_aowner").and_then(|s| s.parse::<usize>().ok()), n.attrs.get("_aname")) {
2269            if let Some(ns) = n.attrs.get("_ans") {
2270                let local = name.split_once(':').map(|(_, l)| l).unwrap_or(name.as_str());
2271                return self.get_attr_ns(o, Some(ns), local).unwrap_or_default();
2272            }
2273            return self.get_attr(o, name).unwrap_or_default();
2274        }
2275        n.attrs.get("_aval").cloned().unwrap_or_default()
2276    }
2277
2278    /// 名前空間つきで属性を設定する(`setAttributeNS`)。
2279    /// `ns.is_some()` のときは `ns_attrs` に分離し、HTML の `style`/`id`/`class`/`on*` 等に干渉させない。
2280    pub fn set_attr_ns(&mut self, elem: usize, ns: Option<&str>, qname: &str, value: &str) {
2281        let Some(u) = ns.filter(|s| !s.is_empty()) else {
2282            self.set_attr(elem, qname, value);
2283            return;
2284        };
2285        self.has_attr_nodes = true;
2286        self.ensure_attr_ns_order(elem);
2287        let local = qname.split_once(':').map(|(_, l)| l).unwrap_or(qname);
2288        let list = self.ns_attrs.entry(elem).or_default();
2289        let old_val = if let Some(entry) = list.iter_mut().find(|(a_ns, a_qn, _)| {
2290            let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2291            a_ns == u && a_l == local
2292        }) {
2293            let old = entry.2.clone();
2294            entry.2 = value.to_string();
2295            Some(old)
2296        } else {
2297            list.push((u.to_string(), qname.to_string(), value.to_string()));
2298            if let Some(ord) = self.attr_ns_order.get_mut(&elem) {
2299                ord.push((Some(u.to_string()), qname.to_string()));
2300            }
2301            None
2302        };
2303        self.notify_attribute_ns(elem, local, Some(u), old_val.as_deref());
2304    }
2305
2306    /// 名前空間 `ns` と局所名 `local` の属性の修飾名。
2307    pub fn find_attr_ns(&self, elem: usize, ns: Option<&str>, local: &str) -> Option<String> {
2308        match ns.filter(|s| !s.is_empty()) {
2309            None => {
2310                let n = self.nodes.get(elem)?;
2311                for name in self.attr_names_default(elem) {
2312                    if name == local && !n.attrs.contains_key(&format!("_ans:{}", name)) {
2313                        return Some(name);
2314                    }
2315                }
2316                None
2317            }
2318            Some(u) => self.ns_attrs.get(&elem).and_then(|list| {
2319                list.iter().find_map(|(a_ns, a_qn, _)| {
2320                    let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2321                    if a_ns == u && a_l == local {
2322                        Some(a_qn.clone())
2323                    } else {
2324                        None
2325                    }
2326                })
2327            }),
2328        }
2329    }
2330
2331    /// 名前空間 `ns` と局所名 `local` の属性値。
2332    pub fn get_attr_ns(&self, elem: usize, ns: Option<&str>, local: &str) -> Option<String> {
2333        match ns.filter(|s| !s.is_empty()) {
2334            None => self.get_attr(elem, local),
2335            Some(u) => self.ns_attrs.get(&elem).and_then(|list| {
2336                list.iter().find_map(|(a_ns, a_qn, v)| {
2337                    let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2338                    if a_ns == u && a_l == local {
2339                        Some(v.clone())
2340                    } else {
2341                        None
2342                    }
2343                })
2344            }),
2345        }
2346    }
2347
2348    /// 名前空間 `ns` と局所名 `local` の属性を削除する。
2349    pub fn remove_attr_ns(&mut self, elem: usize, ns: Option<&str>, local: &str) {
2350        let Some(u) = ns.filter(|s| !s.is_empty()) else {
2351            self.remove_attr(elem, local);
2352            return;
2353        };
2354        let removed = if let Some(list) = self.ns_attrs.get_mut(&elem) {
2355            if let Some(pos) = list.iter().position(|(a_ns, a_qn, _)| {
2356                let a_l = a_qn.split_once(':').map(|(_, l)| l).unwrap_or(a_qn.as_str());
2357                a_ns == u && a_l == local
2358            }) {
2359                let (_, qn, val) = list.remove(pos);
2360                Some((qn, val))
2361            } else {
2362                None
2363            }
2364        } else {
2365            None
2366        };
2367        if let Some((qn, old_val)) = removed {
2368            if let Some(ord) = self.attr_ns_order.get_mut(&elem) {
2369                ord.retain(|(a_ns, a_qn)| !(a_ns.as_deref() == Some(u) && a_qn == &qn));
2370            }
2371            self.remove_attr_ns_notify(elem, Some(u), local, &qn, &old_val);
2372        }
2373    }
2374
2375    pub fn remove_attr_ns_notify(
2376        &mut self,
2377        elem: usize,
2378        ns: Option<&str>,
2379        local: &str,
2380        qn: &str,
2381        old_val: &str,
2382    ) {
2383        if self.has_attr_nodes {
2384            let key = match ns {
2385                None => qn.to_string(),
2386                Some(u) => format!("{}\x01{}", u, qn),
2387            };
2388            self.detach_attr_node(elem, &key, old_val);
2389        }
2390        self.notify_attribute_ns(elem, local, ns, Some(old_val));
2391    }
2392
2393    // ---- 生きている Range の境界点の更新(DOM Standard §4.2.3 insert・§4.2.4 remove・§4.10 CharacterData・§4.11 Text)----
2394    // どれも `ranges` が空なら何もしない(Range を使わないページの速い経路を変えない)。
2395
2396    /// `n` は `anc` の包含的な子孫か。
2397    fn range_inclusive_descendant(&self, mut n: usize, anc: usize) -> bool {
2398        let mut guard = 0usize;
2399        loop {
2400            if n == anc {
2401                return true;
2402            }
2403            match self.nodes.get(n).and_then(|x| x.parent) {
2404                Some(p) => n = p,
2405                None => return false,
2406            }
2407            guard += 1;
2408            if guard > self.nodes.len() + 8 {
2409                return false;
2410            }
2411        }
2412    }
2413
2414    /// `NodeIterator` を登録する(`root` が最初の `referenceNode`)。
2415    pub fn ni_register(&mut self, obj: &crate::os_lib::ecma::value::ObjRef, root: usize) -> u32 {
2416        if self.node_iters.len() >= 64 && self.node_iters.len().is_power_of_two() {
2417            self.node_iters.retain(|_, r| r.obj.strong_count() > 0);
2418        }
2419        let id = self.next_ni_id;
2420        self.next_ni_id = self.next_ni_id.wrapping_add(1).max(1);
2421        self.node_iters.insert(
2422            id,
2423            NiRec {
2424                obj: alloc::rc::Rc::downgrade(obj),
2425                root,
2426                reference: root,
2427                before: true,
2428                in_flight: None,
2429            },
2430        );
2431        id
2432    }
2433
2434    /// 主文書(`document`)直下の子(`doctype` 等)を取り除く(`NodeIterator-removal` 用)。
2435    pub fn remove_main_doc_child(&mut self, child: usize) {
2436        self.iters_pre_remove(child);
2437        if self.main_doctype == Some(child) {
2438            self.main_doctype = None;
2439        }
2440        if let Some(n) = self.nodes.get_mut(child) {
2441            n.parent = None;
2442        }
2443    }
2444
2445    fn ni_retarget_pos(&self, root: usize, node: usize, pos: usize, before_in: bool) -> (usize, bool) {
2446        if self.range_inclusive_descendant(root, node) || !self.range_inclusive_descendant(pos, node) {
2447            return (pos, before_in);
2448        }
2449        let mut before = before_in;
2450        if before {
2451            if self.main_doctype == Some(node) && root == MAIN_DOC && !self.nodes.is_empty() {
2452                return (0, true);
2453            }
2454            // node の部分木のあとに続く最初のノード(root の中のもの)。
2455            let mut cur = node;
2456            let mut next = None;
2457            while cur != root {
2458                let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) else { break };
2459                let p_pos = self.nodes[p].children.iter().position(|&c| c == cur);
2460                if let Some(sib) = p_pos.and_then(|i| self.nodes[p].children.get(i + 1).copied()) {
2461                    next = Some(sib);
2462                    break;
2463                }
2464                cur = p;
2465            }
2466            if let Some(nx) = next {
2467                return (nx, true);
2468            }
2469            before = false;
2470        }
2471        if self.main_doctype == Some(node) {
2472            return (MAIN_DOC, before);
2473        }
2474        let new_ref = match self.nodes.get(node).and_then(|n| n.parent) {
2475            Some(p) => {
2476                let p_pos = self.nodes[p].children.iter().position(|&c| c == node).unwrap_or(0);
2477                if p_pos == 0 {
2478                    p
2479                } else {
2480                    let mut d = self.nodes[p].children[p_pos - 1];
2481                    while let Some(&last) = self.nodes[d].children.last() {
2482                        d = last;
2483                    }
2484                    d
2485                }
2486            }
2487            None => pos,
2488        };
2489        (new_ref, before)
2490    }
2491
2492    /// `node` を木から取り除く直前の NodeIterator の更新(DOM Standard「NodeIterator pre-removing steps」)。
2493    fn iters_pre_remove(&mut self, node: usize) {
2494        if self.node_iters.is_empty() {
2495            return;
2496        }
2497        self.node_iters.retain(|_, r| r.obj.strong_count() > 0);
2498        let keys: Vec<u32> = self.node_iters.keys().copied().collect();
2499        for k in keys {
2500            let Some(r) = self.node_iters.get(&k).cloned() else { continue };
2501            let (nr, nb) = self.ni_retarget_pos(r.root, node, r.reference, r.before);
2502            let nf = r.in_flight.map(|(fp, fb)| self.ni_retarget_pos(r.root, node, fp, fb));
2503            if let Some(m) = self.node_iters.get_mut(&k) {
2504                m.reference = nr;
2505                m.before = nb;
2506                m.in_flight = nf;
2507            }
2508        }
2509    }
2510
2511    /// 弱参照が切れた Range を捨てる。
2512    fn range_prune(&mut self) {
2513        if self.ranges.len() >= 64 && self.ranges.len().is_power_of_two() {
2514            self.ranges.retain(|_, r| r.obj.strong_count() > 0);
2515        }
2516    }
2517
2518    /// 生きている Range があるか(落ちたものはここで捨てる。DOM の変更のたびに呼ぶので、Range が無ければ即座に偽)。
2519    #[inline]
2520    fn live_ranges(&mut self) -> bool {
2521        if self.ranges.is_empty() {
2522            return false;
2523        }
2524        self.ranges.retain(|_, r| r.obj.strong_count() > 0);
2525        !self.ranges.is_empty()
2526    }
2527
2528    /// `node`(親 `parent` の `index` 番目)を取り除くとき。
2529    pub fn ranges_node_removed(&mut self, node: usize, parent: usize, index: usize) {
2530        self.iters_pre_remove(node);
2531        if !self.live_ranges() {
2532            return;
2533        }
2534        let keys: Vec<u32> = self.ranges.keys().copied().collect();
2535        for k in keys {
2536            let Some(r) = self.ranges.get(&k).cloned() else { continue };
2537            let (mut sc, mut so, mut ec, mut eo) = (r.sc, r.so, r.ec, r.eo);
2538            if sc != MAIN_DOC && self.range_inclusive_descendant(sc, node) {
2539                sc = parent;
2540                so = index;
2541            } else if sc == parent && so > index {
2542                so -= 1;
2543            }
2544            if ec != MAIN_DOC && self.range_inclusive_descendant(ec, node) {
2545                ec = parent;
2546                eo = index;
2547            } else if ec == parent && eo > index {
2548                eo -= 1;
2549            }
2550            if let Some(m) = self.ranges.get_mut(&k) {
2551                m.sc = sc;
2552                m.so = so;
2553                m.ec = ec;
2554                m.eo = eo;
2555            }
2556        }
2557    }
2558
2559    /// `parent` の子が全部取り除かれるとき(`innerHTML`・`textContent`・`replaceChildren`。順に先頭から取り除くのと同じ)。
2560    pub fn ranges_children_cleared(&mut self, parent: usize, kids: &[usize]) {
2561        if !self.live_ranges() {
2562            if !self.node_iters.is_empty() {
2563                for &k in kids {
2564                    self.iters_pre_remove(k);
2565                }
2566            }
2567            return;
2568        }
2569        for &k in kids {
2570            self.ranges_node_removed(k, parent, 0);
2571        }
2572    }
2573
2574    /// `parent` の `index` 番目の子の前に `count` 個挿入したあと。
2575    pub fn ranges_inserted(&mut self, parent: usize, index: usize, count: usize) {
2576        if !self.live_ranges() {
2577            return;
2578        }
2579        for r in self.ranges.values_mut() {
2580            if r.sc == parent && r.so > index {
2581                r.so += count;
2582            }
2583            if r.ec == parent && r.eo > index {
2584                r.eo += count;
2585            }
2586        }
2587    }
2588
2589    /// CharacterData の `replace data`(`offset` から `count` 個を UTF-16 で `new_len` 個に)。
2590    pub fn ranges_replace_data(&mut self, node: usize, offset: usize, count: usize, new_len: usize) {
2591        if !self.live_ranges() {
2592            return;
2593        }
2594        for r in self.ranges.values_mut() {
2595            if r.sc == node {
2596                if r.so > offset && r.so <= offset + count {
2597                    r.so = offset;
2598                } else if r.so > offset + count {
2599                    r.so = r.so + new_len - count;
2600                }
2601            }
2602            if r.ec == node {
2603                if r.eo > offset && r.eo <= offset + count {
2604                    r.eo = offset;
2605                } else if r.eo > offset + count {
2606                    r.eo = r.eo + new_len - count;
2607                }
2608            }
2609        }
2610    }
2611
2612    /// `Text.splitText`: `node` を `offset` で分け、後ろを `new_node`(`parent` の `node` の次)にしたとき。
2613    pub fn ranges_split(&mut self, node: usize, new_node: usize, parent: Option<usize>, offset: usize) {
2614        if parent.is_none() || !self.live_ranges() {
2615            return;
2616        }
2617        let index = parent.and_then(|p| self.nodes.get(p)).and_then(|p| p.children.iter().position(|&c| c == node));
2618        for r in self.ranges.values_mut() {
2619            if r.sc == node && r.so > offset {
2620                r.sc = new_node;
2621                r.so -= offset;
2622            } else if parent.is_some() && r.sc == parent.unwrap_or(0) && index.is_some_and(|i| r.so == i + 1) {
2623                r.so += 1;
2624            }
2625            if r.ec == node && r.eo > offset {
2626                r.ec = new_node;
2627                r.eo -= offset;
2628            } else if parent.is_some() && r.ec == parent.unwrap_or(0) && index.is_some_and(|i| r.eo == i + 1) {
2629                r.eo += 1;
2630            }
2631        }
2632    }
2633
2634    /// `normalize` で `cur`(`parent` の `index` 番目)を直前のテキスト `node`(取り込み前の長さ `length`)へ併せるとき。
2635    pub fn ranges_normalize_merge(&mut self, node: usize, cur: usize, parent: usize, index: usize, length: usize) {
2636        if !self.live_ranges() {
2637            return;
2638        }
2639        for r in self.ranges.values_mut() {
2640            if r.sc == cur {
2641                r.sc = node;
2642                r.so += length;
2643            } else if r.sc == parent && r.so == index {
2644                r.sc = node;
2645                r.so = length;
2646            }
2647            if r.ec == cur {
2648                r.ec = node;
2649                r.eo += length;
2650            } else if r.ec == parent && r.eo == index {
2651                r.ec = node;
2652                r.eo = length;
2653            }
2654        }
2655    }
2656
2657    /// 主文書の DOCTYPE を設定する(仕様どおりの木で組むホスト実行器用)。
2658    pub fn set_main_doctype(&mut self, name: &str, public_id: &str, system_id: &str) {
2659        let d = self.create_doctype(name, public_id, system_id);
2660        self.main_doctype = Some(d);
2661    }
2662
2663    /// 新しい Range を登録して番号を返す。
2664    pub fn range_register(&mut self, obj: &crate::os_lib::ecma::value::ObjRef, node: usize) -> u32 {
2665        self.range_prune();
2666        let id = self.next_range_id;
2667        self.next_range_id = self.next_range_id.wrapping_add(1).max(1);
2668        self.ranges.insert(id, RangeRec { obj: alloc::rc::Rc::downgrade(obj), sc: node, so: 0, ec: node, eo: 0 });
2669        id
2670    }
2671
2672    /// CharacterData の内容を `new_text` にして、Range の境界点を `replace data(offset, count, new_len)` どおりに直す。
2673    pub fn replace_data(&mut self, idx: usize, offset: usize, count: usize, new_len: usize, new_text: &str) {
2674        self.suppress_range_hook = true;
2675        self.set_text_content(idx, new_text);
2676        self.suppress_range_hook = false;
2677        self.ranges_replace_data(idx, offset, count, new_len);
2678    }
2679
2680    // ---- 主文書以外の Document(`#document` ノード。2026-11-20 TODO S3)----
2681    //
2682    // 主文書(`nodes[0]` の `<html>` を根にする木)はこれまでどおり `HostRef(HOST_DOCUMENT)` の `document` が受け持つ。
2683    // `new Document()`・`createHTMLDocument`・`createDocument`・`DOMParser` が返す文書は、アリーナの中の
2684    // `#document` ノード(`#fragment` や `#doctype` と同じく特殊タグのノード)として持ち、ふつうの DOM ノードのハンドル
2685    // (`===` で同一・リスナ・子の操作)をそのまま使う。ノードがどの文書のものかは `node_doc`(主文書以外のものだけを記録)。
2686
2687    /// `#document` ノードを作る。`ctype` は `contentType`、`html` は HTML 文書か(`createElement` が小文字にするか)。
2688    pub fn create_document_node(&mut self, ctype: &str, html: bool) -> usize {
2689        let idx = self.nodes.len();
2690        let mut attrs = BTreeMap::new();
2691        attrs.insert(String::from("_ctype"), ctype.to_string());
2692        if html {
2693            attrs.insert(String::from("_html"), String::from("1"));
2694        }
2695        self.nodes.push(DomNode {
2696            tag: String::from("#document"),
2697            is_text: false,
2698            id: String::new(),
2699            classes: Vec::new(),
2700            style: BTreeMap::new(),
2701            attrs,
2702            text_override: None,
2703            initial_text: String::new(),
2704            parent: None,
2705            children: Vec::new(),
2706            classes_dirty: false,
2707            style_dirty: false,
2708        });
2709        self.extra_docs += 1;
2710        idx
2711    }
2712
2713    /// `idx` が主文書以外の `#document` ノードか。
2714    #[inline]
2715    pub fn is_doc_node(&self, idx: usize) -> bool {
2716        self.extra_docs > 0 && self.nodes.get(idx).is_some_and(|n| n.tag == "#document")
2717    }
2718
2719    /// 文書(`None` は主文書)が HTML 文書か。
2720    pub fn doc_is_html(&self, doc: Option<usize>) -> bool {
2721        match doc {
2722            None => true,
2723            Some(d) => self.nodes.get(d).is_some_and(|n| n.attrs.contains_key("_html")),
2724        }
2725    }
2726
2727    /// 「ノードの文書」。`None` は主文書。`#document` ノード自身は自分。
2728    #[inline]
2729    pub fn node_document(&self, idx: usize) -> Option<usize> {
2730        if self.extra_docs == 0 {
2731            return None;
2732        }
2733        if self.is_doc_node(idx) {
2734            return Some(idx);
2735        }
2736        self.node_doc.get(&idx).copied()
2737    }
2738
2739    /// 親をたどった先の根(シャドウ木は越えない)。
2740    pub fn root_of(&self, mut idx: usize) -> usize {
2741        let mut guard = 0;
2742        while let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
2743            idx = p;
2744            guard += 1;
2745            if guard > self.nodes.len() + 64 {
2746                break;
2747            }
2748        }
2749        idx
2750    }
2751
2752    /// 部分木のノードの所有文書を `doc`(`None` は主文書)にする。XML 文書の要素には `_xml` の印を付け、HTML 文書では外す。
2753    pub fn set_owner_subtree(&mut self, idx: usize, doc: Option<usize>) {
2754        let html = self.doc_is_html(doc);
2755        let mut stack: Vec<usize> = alloc::vec![idx];
2756        let mut guard = 0usize;
2757        while let Some(i) = stack.pop() {
2758            guard += 1;
2759            if guard > self.nodes.len() + 8 {
2760                break;
2761            }
2762            match doc {
2763                Some(d) => {
2764                    self.node_doc.insert(i, d);
2765                }
2766                None => {
2767                    self.node_doc.remove(&i);
2768                }
2769            }
2770            let shadow = self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx);
2771            let Some(n) = self.nodes.get_mut(i) else { continue };
2772            if !n.is_text && !n.tag.starts_with('#') {
2773                if html {
2774                    n.attrs.remove("_xml");
2775                } else {
2776                    n.attrs.insert(String::from("_xml"), String::from("1"));
2777                }
2778            }
2779            stack.extend(n.children.iter().copied());
2780            if let Some(f) = n.attrs.get("_content_frag").and_then(|s| s.parse::<usize>().ok()) {
2781                stack.push(f);
2782            }
2783            if let Some(r) = shadow {
2784                stack.push(r);
2785            }
2786        }
2787    }
2788
2789    /// 新しく作った `idx` が `from` と同じ文書のものになるようにする(`cloneNode`・`splitText`・`innerHTML` の新ノード)。
2790    #[inline]
2791    pub fn inherit_owner(&mut self, idx: usize, from: usize) {
2792        if self.extra_docs == 0 {
2793            return;
2794        }
2795        if let Some(d) = self.node_document(from) {
2796            self.set_owner_subtree(idx, Some(d));
2797        }
2798    }
2799
2800    /// 挿入された子(部分木)の所有文書を親の文書へ移す(仕様の「adopt」)。
2801    fn sync_owner_on_insert(&mut self, parent: usize, kids: &[usize]) {
2802        let target = self.node_document(parent);
2803        for &k in kids {
2804            if self.node_document(k) != target {
2805                self.set_owner_subtree(k, target);
2806            }
2807        }
2808    }
2809
2810    /// Web Components: `element.attachShadow({ mode: 'open' | 'closed' })`
2811    pub fn attach_shadow(
2812        &mut self,
2813        host_idx: usize,
2814        mode: crate::os_lib::shadow_dom::ShadowRootMode,
2815    ) -> Result<usize, crate::os_lib::shadow_dom::AttachShadowError> {
2816        let tag = match self.nodes.get(host_idx) {
2817            Some(n) if !n.is_text => n.tag.clone(),
2818            _ => return Err(crate::os_lib::shadow_dom::AttachShadowError::DisallowedTag),
2819        };
2820        // ShadowRoot は DocumentFragment 相当の仮想ルートノード `#shadow-root` として生成
2821        let root_idx = self.new_element_node("#shadow-root");
2822        self.shadow_tree.attach_shadow(host_idx, &tag, mode, root_idx)?;
2823        if self.extra_docs > 0 {
2824            if let Some(doc_idx) = self.node_document(host_idx) {
2825                self.set_owner_subtree(root_idx, Some(doc_idx));
2826            }
2827        }
2828        self.structural_dirty = true;
2829        Self::count_relayout_request();
2830        self.note_dirty_cause("attachShadow");
2831        self.dirty = true;
2832        Ok(root_idx)
2833    }
2834
2835    /// ホスト要素の ShadowRoot ノード index を取得(accessible な場合のみ)。
2836    pub fn get_shadow_root(&self, host_idx: usize) -> Option<usize> {
2837        self.shadow_tree
2838            .get_by_host(host_idx)
2839            .filter(|d| d.is_accessible_via_element())
2840            .map(|d| d.root_node_idx)
2841    }
2842
2843    /// W3C DOM Parsing: `Range.prototype.createContextualFragment(fragment)`
2844    pub fn create_contextual_fragment(&mut self, context_node_idx: Option<usize>, html: &str) -> usize {
2845        let mut context_tag = alloc::string::String::from("div");
2846        if let Some(idx) = context_node_idx {
2847            if let Some(node) = self.nodes.get(idx) {
2848                if node.is_text {
2849                    if let Some(p) = node.parent {
2850                        if let Some(pn) = self.nodes.get(p) {
2851                            if !pn.is_text && !pn.tag.starts_with('#') {
2852                                context_tag = pn.tag.clone();
2853                            }
2854                        }
2855                    }
2856                } else if !node.tag.starts_with('#') {
2857                    context_tag = node.tag.clone();
2858                }
2859            }
2860        }
2861
2862        let (wrapped, depth) = crate::os_lib::dom_fragment::context_wrapper(&context_tag, html);
2863        let root = crate::os_lib::dom::parse_html_app_flat(&wrapped);
2864        let frag_idx = self.create_document_fragment();
2865        let children = crate::os_lib::dom_fragment::extract_fragment_children(&root, depth);
2866
2867        let mut imported_children = Vec::new();
2868        for child in children {
2869            let ci = self.import_node(child);
2870            self.nodes[ci].parent = Some(frag_idx);
2871            imported_children.push(ci);
2872        }
2873        self.nodes[frag_idx].children = imported_children;
2874        frag_idx
2875    }
2876
2877    /// `template.content`(`<template>` が丸ごと未対応だった)。仕様上 `<template>`
2878    /// の子は「不活性」で通常の DOM ツリーには存在せず、代わりに `.content`
2879    /// (`DocumentFragment`)経由でのみアクセスできる。この処理系は HTML パース時に
2880    /// `template` を特別扱いしないため子が普通にライブツリーへ入ってしまうが、
2881    /// 初回アクセス時にその子を `#fragment` ノードへ移し替え(内部専用属性
2882    /// `_content_frag` にフラグメントの index をキャッシュ)、以後は同じフラグメントを
2883    /// 返すことで「以後 `<template>` 自身は空、`.content` だけが中身を持つ」という
2884    /// 仕様どおりの見た目に近づける。
2885    pub fn template_content(&mut self, idx: usize) -> usize {
2886        if let Some(f) = self
2887            .get_attr(idx, "_content_frag")
2888            .or_else(|| self.get_attr(idx, "_template_content_idx"))
2889            .and_then(|s| s.parse::<usize>().ok())
2890        {
2891            let fs = f.to_string();
2892            self.set_attr(idx, "_content_frag", &fs);
2893            self.set_attr(idx, "_template_content_idx", &fs);
2894            return f;
2895        }
2896        let owner_doc = self.node_document(idx);
2897        let tmpl_doc = match self.template_owner_docs.get(&owner_doc).copied() {
2898            Some(d) => d,
2899            None => {
2900                let d = self.create_document_node("text/html", true);
2901                self.template_owner_docs.insert(owner_doc, d);
2902                d
2903            }
2904        };
2905        let f = self.create_document_fragment();
2906        let kids = core::mem::take(&mut self.nodes[idx].children);
2907        for &k in &kids {
2908            self.nodes[k].parent = Some(f);
2909        }
2910        self.nodes[f].children = kids;
2911        self.set_owner_subtree(f, Some(tmpl_doc));
2912        let fs = f.to_string();
2913        self.set_attr(idx, "_content_frag", &fs);
2914        self.set_attr(idx, "_template_content_idx", &fs);
2915        f
2916    }
2917
2918    /// `child` が DocumentFragment(`#fragment` タグ)なら、その子要素群を
2919    /// 親から切り離して返し、フラグメント自身は空にする。それ以外は `[child]` を
2920    /// そのまま返す(`append_child`/`insert_before` の共通前処理)。
2921    fn expand_fragment(&mut self, child: usize) -> Vec<usize> {
2922        if self.nodes.get(child).map(|n| matches!(n.tag.as_str(), "#fragment" | "#document-fragment" | "#shadow-root")).unwrap_or(false) {
2923            let kids = core::mem::take(&mut self.nodes[child].children);
2924            if !self.ranges.is_empty() {
2925                // 取り除く前の親子関係で境界点を直す。
2926                for &k in &kids {
2927                    self.nodes[k].parent = Some(child);
2928                }
2929                self.ranges_children_cleared(child, &kids);
2930            }
2931            for &k in &kids {
2932                self.nodes[k].parent = None;
2933            }
2934            kids
2935        } else {
2936            alloc::vec![child]
2937        }
2938    }
2939
2940    /// `parent.appendChild(child)`。既存の親から外して付け替える。`child` が
2941    /// DocumentFragment の場合は仕様どおりその子要素群を代わりに追加する。
2942    pub fn append_child(&mut self, parent: usize, child: usize) {
2943        if parent >= self.nodes.len() || child >= self.nodes.len() || parent == child {
2944            return;
2945        }
2946        let kids = self.expand_fragment(child);
2947        if kids.is_empty() {
2948            return;
2949        }
2950        let any_kid_was_attached = kids.iter().any(|&k| self.is_attached(k));
2951        for &k in &kids {
2952            self.detach_with_notify(k);
2953        }
2954        let prev_sib = self.nodes[parent].children.last().copied();
2955        for &k in &kids {
2956            self.nodes[k].parent = Some(parent);
2957            self.nodes[parent].children.push(k);
2958        }
2959        if self.extra_docs > 0 {
2960            self.sync_owner_on_insert(parent, &kids);
2961        }
2962        if self.is_attached(parent) || any_kid_was_attached {
2963            self.mark_structural_dirty_for("appendChild");
2964        }
2965        self.queue_post_connection(Some(parent), &kids);
2966        self.notify_child_list_sib(parent, kids, Vec::new(), prev_sib, None);
2967    }
2968
2969    /// `ParentNode.replaceChildren(...)`: 既存の子を取り外し、新しい子(あれば)を 1 回の MutationRecord で置き換える。
2970    pub fn replace_children(&mut self, parent: usize, new_child: Option<usize>) {
2971        if parent >= self.nodes.len() {
2972            return;
2973        }
2974        let kids = match new_child {
2975            Some(c) if c < self.nodes.len() && c != parent => self.expand_fragment(c),
2976            _ => Vec::new(),
2977        };
2978        for &k in &kids {
2979            if self.nodes.get(k).and_then(|n| n.parent) != Some(parent) {
2980                self.detach_with_notify(k);
2981            }
2982        }
2983        let old: Vec<usize> = core::mem::take(&mut self.nodes[parent].children);
2984        if !old.is_empty() {
2985            self.ranges_children_cleared(parent, &old);
2986            for &c in &old {
2987                self.nodes[c].parent = None;
2988            }
2989        }
2990        for &k in &kids {
2991            self.nodes[k].parent = Some(parent);
2992            self.nodes[parent].children.push(k);
2993        }
2994        if self.extra_docs > 0 && !kids.is_empty() {
2995            self.sync_owner_on_insert(parent, &kids);
2996        }
2997        if !kids.is_empty() {
2998            self.ranges_inserted(parent, 0, kids.len());
2999        }
3000        if !old.is_empty() || !kids.is_empty() {
3001            self.queue_post_connection(Some(parent), &kids);
3002            self.notify_child_list(parent, kids, old);
3003            if self.is_attached(parent) {
3004                self.mark_structural_dirty_for("replaceChildren");
3005            }
3006        }
3007    }
3008
3009    /// `parent.removeChild(child)` / `child.remove()`。
3010    pub fn remove_child(&mut self, parent: usize, child: usize) {
3011        let p = if parent < self.nodes.len() { Some(parent) } else { self.nodes.get(child).and_then(|n| n.parent) };
3012        let sibs = p.map(|pi| self.siblings_of_child(pi, child)).unwrap_or((None, None));
3013        let was_attached = self.is_attached(child) && self.nodes.get(child).and_then(|n| n.parent).is_some();
3014        self.detach(child);
3015        if was_attached {
3016            self.mark_structural_dirty_for("removeChild");
3017        }
3018        if let Some(p) = p {
3019            self.notify_child_list_sib(p, Vec::new(), alloc::vec![child], sibs.0, sibs.1);
3020        }
3021    }
3022    pub fn remove_node(&mut self, idx: usize) {
3023        let p = self.nodes.get(idx).and_then(|n| n.parent);
3024        let sibs = p.map(|pi| self.siblings_of_child(pi, idx)).unwrap_or((None, None));
3025        let was_attached = p.is_some() && self.is_attached(idx);
3026        self.detach(idx);
3027        if was_attached {
3028            self.mark_structural_dirty_for("remove");
3029        }
3030        if let Some(p) = p {
3031            self.notify_child_list_sib(p, Vec::new(), alloc::vec![idx], sibs.0, sibs.1);
3032        }
3033    }
3034
3035    /// `parent.insertBefore(new_child, ref_child)`。ref が None/不在なら末尾に追加。
3036    /// `new_child` が DocumentFragment の場合は仕様どおりその子要素群を代わりに挿入する。
3037    /// 【2026-11-20】基準(`ref_child`)の位置は、挿入するノードを元の親から外した後に引く(同じ親の中で前から後ろへ動かすと
3038    /// 添字がずれていた)。`ref_child` が挿入するノード自身なら、その次の兄弟を基準にする(DOM 標準)。
3039    pub fn insert_before(&mut self, parent: usize, new_child: usize, ref_child: Option<usize>) {
3040        if parent >= self.nodes.len() || new_child >= self.nodes.len() || parent == new_child {
3041            return;
3042        }
3043        let mut ref_child = ref_child;
3044        if ref_child == Some(new_child) {
3045            let sib = self.nodes[parent].children.iter().position(|&c| c == new_child).and_then(|i| self.nodes[parent].children.get(i + 1).copied());
3046            ref_child = sib;
3047        }
3048        let kids = self.expand_fragment(new_child);
3049        if kids.is_empty() {
3050            return;
3051        }
3052        let any_kid_was_attached = kids.iter().any(|&k| self.is_attached(k));
3053        for &k in &kids {
3054            self.detach_with_notify(k);
3055        }
3056        let pos = ref_child.and_then(|r| self.nodes[parent].children.iter().position(|&c| c == r));
3057        let (prev_sib, next_sib) = match pos {
3058            Some(p) => (
3059                if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None },
3060                self.nodes[parent].children.get(p).copied(),
3061            ),
3062            None => (self.nodes[parent].children.last().copied(), None),
3063        };
3064        if let Some(p) = pos {
3065            self.ranges_inserted(parent, p, kids.len());
3066        }
3067        for (i, &k) in kids.iter().enumerate() {
3068            self.nodes[k].parent = Some(parent);
3069            match pos {
3070                Some(p) => self.nodes[parent].children.insert(p + i, k),
3071                None => self.nodes[parent].children.push(k),
3072            }
3073        }
3074        if self.extra_docs > 0 {
3075            self.sync_owner_on_insert(parent, &kids);
3076        }
3077        if self.is_attached(parent) || any_kid_was_attached {
3078            self.mark_structural_dirty_for("insertBefore");
3079        }
3080        self.queue_post_connection(Some(parent), &kids);
3081        self.notify_child_list_sib(parent, kids, Vec::new(), prev_sib, next_sib);
3082    }
3083
3084    /// `parent.replaceChild(new_child, old_child)`。old を new で置換。`new_child` が DocumentFragment ならその子群で置き換える。
3085    pub fn replace_child(&mut self, parent: usize, new_child: usize, old_child: usize) {
3086        if parent >= self.nodes.len() || new_child >= self.nodes.len() || old_child >= self.nodes.len() {
3087            return;
3088        }
3089        if !self.nodes[parent].children.contains(&old_child) {
3090            return;
3091        }
3092        if new_child == old_child {
3093            if let Some(p) = self.nodes[parent].children.iter().position(|&c| c == old_child) {
3094                let prev_sib = if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None };
3095                let next_sib = self.nodes[parent].children.get(p + 1).copied();
3096                self.ranges_node_removed(old_child, parent, p);
3097                self.ranges_inserted(parent, p, 1);
3098                self.notify_child_list_sib(
3099                    parent,
3100                    Vec::new(),
3101                    alloc::vec![old_child],
3102                    prev_sib,
3103                    next_sib,
3104                );
3105                self.notify_child_list_sib(
3106                    parent,
3107                    alloc::vec![old_child],
3108                    Vec::new(),
3109                    prev_sib,
3110                    next_sib,
3111                );
3112            }
3113            return;
3114        }
3115        let kids = self.expand_fragment(new_child);
3116        let new_was_attached = kids.iter().any(|&k| self.is_attached(k));
3117        for &k in &kids {
3118            self.detach_with_notify(k); // どこかに属していれば外す(位置が変わりうる)
3119        }
3120        if let Some(p) = self.nodes[parent].children.iter().position(|&c| c == old_child) {
3121            let prev_sib = if p > 0 { self.nodes[parent].children.get(p - 1).copied() } else { None };
3122            let next_sib = self.nodes[parent].children.get(p + 1).copied();
3123            self.ranges_node_removed(old_child, parent, p);
3124            if p + 1 < self.nodes[parent].children.len() {
3125                self.ranges_inserted(parent, p, kids.len());
3126            }
3127            self.nodes[old_child].parent = None;
3128            for &k in &kids {
3129                self.nodes[k].parent = Some(parent);
3130            }
3131            self.nodes[parent].children.splice(p..p + 1, kids.iter().copied());
3132            if self.extra_docs > 0 {
3133                self.sync_owner_on_insert(parent, &kids);
3134            }
3135            if self.is_attached(parent) || new_was_attached {
3136                self.mark_structural_dirty_for("replaceChild");
3137            }
3138            self.queue_post_connection(Some(parent), &kids);
3139            self.notify_child_list_sib(parent, kids, alloc::vec![old_child], prev_sib, next_sib);
3140        }
3141    }
3142
3143    /// `node.cloneNode(deep)`。属性/テキストをコピーした新ノードを作る(親なし)。deep なら子も再帰。
3144    pub fn clone_node(&mut self, idx: usize, deep: bool) -> usize {
3145        let c = self.clone_node_inner(idx, deep);
3146        if c != idx {
3147            self.inherit_owner(c, idx);
3148        }
3149        if c != idx && !self.custom_elements.is_empty() {
3150            self.ce_queue.push(CeEvent::Created(c));
3151        }
3152        c
3153    }
3154
3155    fn clone_node_inner(&mut self, idx: usize, deep: bool) -> usize {
3156        if idx >= self.nodes.len() {
3157            return idx;
3158        }
3159        let (is_text, tag, id, classes, style, attrs, text_override, initial_text, children) = {
3160            let n = &self.nodes[idx];
3161            (
3162                n.is_text,
3163                n.tag.clone(),
3164                n.id.clone(),
3165                n.classes.clone(),
3166                n.style.clone(),
3167                n.attrs.clone(),
3168                n.text_override.clone(),
3169                n.initial_text.clone(),
3170                n.children.clone(),
3171            )
3172        };
3173        let new_idx = self.nodes.len();
3174        if !self.attr_order.is_empty() {
3175            if let Some(o) = self.attr_order.get(&idx).cloned() {
3176                self.attr_order.insert(new_idx, o);
3177            }
3178        }
3179        if !self.ns_attrs.is_empty() {
3180            if let Some(ns) = self.ns_attrs.get(&idx).cloned() {
3181                self.ns_attrs.insert(new_idx, ns);
3182            }
3183        }
3184        if !self.attr_ns_order.is_empty() {
3185            if let Some(ord) = self.attr_ns_order.get(&idx).cloned() {
3186                self.attr_ns_order.insert(new_idx, ord);
3187            }
3188        }
3189        self.nodes.push(DomNode {
3190            tag,
3191            is_text,
3192            id,
3193            classes,
3194            style,
3195            attrs,
3196            text_override,
3197            initial_text,
3198            parent: None,
3199            children: Vec::new(),
3200            classes_dirty: false,
3201            style_dirty: false,
3202        });
3203        if deep && !is_text {
3204            for c in children {
3205                let cc = self.clone_node_inner(c, true);
3206                self.nodes[cc].parent = Some(new_idx);
3207                self.nodes[new_idx].children.push(cc);
3208            }
3209        }
3210        // `<template>.content` は通常の `children` ではなく `_content_frag` 属性
3211        // 経由で参照される遅延切り出し済み `#fragment` のため、上の通常の
3212        // children クローンでは複製されない。属性は他の属性と同様に文字列と
3213        // してそのままコピーされるので、対処しないとクローン先の
3214        // `template.content` が元の(同じ)フラグメントを指したまま共有されて
3215        // しまうバグだった(`.content` に一度でもアクセス済みの `<template>` を
3216        // `cloneNode()` した場合にのみ顕在化する)。仕様上 `<template>` の
3217        // content クローンは `deep` フラグに関わらず常に行われる特殊規則のため、
3218        // `if deep` の外で無条件に複製する。
3219        let frag_attr = self.nodes[new_idx]
3220            .attrs
3221            .get("_template_content_idx")
3222            .or_else(|| self.nodes[new_idx].attrs.get("_content_frag"))
3223            .cloned();
3224        if let Some(frag_idx) = frag_attr.and_then(|s| s.parse::<usize>().ok()) {
3225            let new_frag = self.clone_node_inner(frag_idx, true);
3226            let new_frag_str = new_frag.to_string();
3227            self.nodes[new_idx]
3228                .attrs
3229                .insert("_template_content_idx".to_string(), new_frag_str.clone());
3230            self.nodes[new_idx]
3231                .attrs
3232                .insert("_content_frag".to_string(), new_frag_str);
3233        }
3234        // クローンされたノードは常に親なし(未接続)なので、文書へ挿入されるまで構造ダーティにしない(TODO P4b)。
3235        new_idx
3236    }
3237
3238    /// 親の children から idx を外す。
3239    fn subtree_contains(&self, root: usize, target: usize) -> bool {
3240        let mut cur = Some(target);
3241        let mut guard = 0;
3242        while let Some(c) = cur {
3243            if c == root {
3244                return true;
3245            }
3246            guard += 1;
3247            if guard > self.nodes.len() + 1 {
3248                break;
3249            }
3250            cur = self.nodes.get(c).and_then(|n| n.parent);
3251        }
3252        false
3253    }
3254
3255    fn detach(&mut self, idx: usize) {
3256        if idx >= self.nodes.len() {
3257            return;
3258        }
3259        if self.focused_idx.is_some_and(|f| self.subtree_contains(idx, f)) {
3260            self.focused_idx = None;
3261        }
3262        if let Some(p) = self.nodes[idx].parent {
3263            if let Some(pos) = self.nodes[p].children.iter().position(|&c| c == idx) {
3264                self.ranges_node_removed(idx, p, pos);
3265                self.nodes[p].children.remove(pos);
3266            }
3267        }
3268        self.nodes[idx].parent = None;
3269    }
3270
3271    pub fn move_before(&mut self, parent: usize, new_child: usize, ref_child: Option<usize>) {
3272        let saved_focus = self.focused_idx;
3273        let queued = self.pending_post_connection.len();
3274        self.insert_before(parent, new_child, ref_child);
3275        self.focused_idx = saved_focus;
3276        // 移動(moveBefore)は挿入の手順・post-connection steps を走らせない(script を実行せず、枠も作り直さない)。
3277        for i in self.pending_post_connection.split_off(queued) {
3278            self.frames_pending_setup.remove(&i);
3279        }
3280    }
3281
3282    /// 単一ノードを基準ノード idx の相対位置へ挿入(insertAdjacent* 共通)。
3283    pub fn insert_adjacent_node(&mut self, idx: usize, position: &str, node: usize) {
3284        match position {
3285            "beforeend" => self.append_child(idx, node),
3286            "afterbegin" => {
3287                let first = self
3288                    .nodes
3289                    .get(idx)
3290                    .and_then(|n| n.children.first().copied());
3291                self.insert_before(idx, node, first);
3292            }
3293            "beforebegin" => {
3294                if let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
3295                    self.insert_before(p, node, Some(idx));
3296                }
3297            }
3298            "afterend" => {
3299                if let Some(p) = self.nodes.get(idx).and_then(|n| n.parent) {
3300                    let next = self.nodes.get(p).and_then(|n| {
3301                        n.children
3302                            .iter()
3303                            .position(|&c| c == idx)
3304                            .and_then(|i| n.children.get(i + 1).copied())
3305                    });
3306                    self.insert_before(p, node, next);
3307                }
3308            }
3309            _ => {}
3310        }
3311    }
3312
3313    /// `element.insertAdjacentHTML(position, html)`。html をパースして相対位置へ挿入。
3314    pub fn insert_adjacent_html(&mut self, idx: usize, position: &str, html: &str) {
3315        let root = crate::os_lib::dom::parse_html_app_flat(html);
3316        let imported: Vec<usize> = root.children.iter().map(|c| self.import_node(c)).collect();
3317        if position == "afterbegin" {
3318            // 基準(元の先頭子)を一度だけ捕捉して順序保持で前挿入。
3319            let first = self
3320                .nodes
3321                .get(idx)
3322                .and_then(|n| n.children.first().copied());
3323            for node in imported {
3324                self.insert_before(idx, node, first);
3325            }
3326        } else {
3327            for node in imported {
3328                self.insert_adjacent_node(idx, position, node);
3329            }
3330        }
3331        self.mark_structural_dirty_for("insertAdjacentHTML");
3332    }
3333
3334    /// 属性 `name` の変更がスタイル計算やレイアウト(HTML 固有の表示属性を含む)に影響し得るか(TODO P4b)。
3335    pub fn attr_affects_layout(&self, idx: usize, name: &str) -> bool {
3336        let lower = name.to_ascii_lowercase();
3337        // 1. HTML / SVG の固有表示・寸法・内容に関わる属性は常にレイアウトに影響する。
3338        let is_intrinsic = matches!(
3339            lower.as_str(),
3340            "id"
3341                | "class"
3342                | "style"
3343                | "hidden"
3344                | "open"
3345                | "src"
3346                | "srcset"
3347                | "href"
3348                | "rel"
3349                | "type"
3350                | "value"
3351                | "checked"
3352                | "selected"
3353                | "disabled"
3354                | "placeholder"
3355                | "width"
3356                | "height"
3357                | "cols"
3358                | "rows"
3359                | "size"
3360                | "colspan"
3361                | "rowspan"
3362                | "span"
3363                | "dir"
3364                | "lang"
3365                | "poster"
3366                | "controls"
3367                | "Reversed"
3368                | "reversed"
3369                | "start"
3370                | "align"
3371                | "valign"
3372                | "bgcolor"
3373                | "color"
3374                | "border"
3375                | "cellpadding"
3376                | "cellspacing"
3377                | "viewbox"
3378                | "d"
3379                | "fill"
3380                | "stroke"
3381                | "stroke-width"
3382                | "points"
3383                | "x"
3384                | "y"
3385                | "x1"
3386                | "y1"
3387                | "x2"
3388                | "y2"
3389                | "cx"
3390                | "cy"
3391                | "r"
3392                | "rx"
3393                | "ry"
3394                | "transform"
3395        );
3396        // 2. スタイルシートの属性セレクタで参照されているか(未解析の間は安全側で true)。
3397        let in_css = match &self.css_referenced_attrs {
3398            Some(set) => set.contains(&lower),
3399            None => true,
3400        };
3401        if !is_intrinsic && !in_css {
3402            return false;
3403        }
3404        // 3. 対象要素が既に文書から切り離されている場合や、親以上の祖先が `display: none` の部分木にある場合、
3405        //    その属性変更が祖先の `display: none` を解除し得ないなら画面の配置は変わらない。
3406        //    (要素自身が `display: none` の場合は `class` / `id` / `style` / `hidden` や CSS 属性セレクタで
3407        //     要素自身の `display` が変わり得るので、**親**が `display: none` 部分木にあるときだけ省く
3408        //     —— ただしスタイルシートが `:has()` を使う可能性を考慮し、CSS 参照属性でも無い非表示属性は上で既に false、
3409        //     親が非表示で `id` / `style` 以外の属性変更なら画面には出ない)。
3410        if !self.is_attached(idx) {
3411            return false;
3412        }
3413        if let Some(parent) = self.nodes.get(idx).and_then(|n| n.parent) {
3414            if self.is_in_display_none_subtree(parent) && !matches!(lower.as_str(), "id" | "class" | "style" | "hidden" | "open") && !in_css {
3415                return false;
3416            }
3417        }
3418        true
3419    }
3420
3421    /// `element.innerHTML = html`。フラグメントをパースして子を置換する。
3422    /// `appendChild`/`removeChild`/`insertBefore`/`replaceChild` は全て
3423    /// `notify_child_list` 経由で MutationObserver に通知していたが、
3424    /// `innerHTML` 代入だけがこの呼び出しを欠いており、最も頻繁に使われる
3425    /// DOM 書き換え手段にもかかわらず childList 変化が一切観察できなかった。
3426    pub fn set_inner_html(&mut self, idx: usize, html: &str) {
3427        if idx >= self.nodes.len() || self.nodes[idx].is_text {
3428            return;
3429        }
3430        if self.nodes[idx].children.is_empty() && html.is_empty() {
3431            return;
3432        }
3433        let frag_children = if html.contains("<?") {
3434            let context = self.nodes[idx].tag.clone();
3435            crate::os_lib::dom::parse_html_fragment(&context, html)
3436        } else {
3437            crate::os_lib::dom::parse_html_app_flat(html).children
3438        };
3439        // 既存の子を切り離す。
3440        let old: Vec<usize> = self.nodes[idx].children.clone();
3441        self.ranges_children_cleared(idx, &old);
3442        for &c in &old {
3443            self.nodes[c].parent = None;
3444        }
3445        self.nodes[idx].children.clear();
3446        // パース結果を import して付ける。
3447        let mut new_children = Vec::new();
3448        for child in &frag_children {
3449            let ci = self.import_node(child);
3450            self.nodes[ci].parent = Some(idx);
3451            new_children.push(ci);
3452        }
3453        self.nodes[idx].children = new_children.clone();
3454        if self.extra_docs > 0 {
3455            for &c in &new_children {
3456                self.inherit_owner(c, idx);
3457            }
3458        }
3459        if self.is_attached(idx) {
3460            self.mark_structural_dirty_for("innerHTML");
3461        }
3462        // innerHTML で解析した `<script>` は実行しない(未実行の集合に入らない)。`<iframe>` 等の post-connection だけ積む。
3463        self.queue_post_connection(Some(idx), &new_children);
3464        self.notify_child_list(idx, new_children, old);
3465    }
3466
3467    /// `element.outerHTML = html`。自ノードを HTML パース結果のノード群で置き換える。
3468    pub fn set_outer_html(&mut self, idx: usize, html: &str) {
3469        if idx >= self.nodes.len() {
3470            return;
3471        }
3472        let parent = match self.nodes[idx].parent {
3473            Some(p) => p,
3474            None => return,
3475        };
3476        let pos = match self.nodes[parent].children.iter().position(|&c| c == idx) {
3477            Some(p) => p,
3478            None => return,
3479        };
3480        let root = crate::os_lib::dom::parse_html_app_flat(html);
3481        let mut new_inserted = Vec::new();
3482        for child in &root.children {
3483            let ci = self.import_node(child);
3484            self.nodes[ci].parent = Some(parent);
3485            new_inserted.push(ci);
3486        }
3487        self.nodes[idx].parent = None;
3488        self.nodes[parent].children.remove(pos);
3489        for (i, &ci) in new_inserted.iter().enumerate() {
3490            self.nodes[parent].children.insert(pos + i, ci);
3491        }
3492        if self.is_attached(parent) {
3493            self.mark_structural_dirty_for("outerHTML");
3494        }
3495        self.queue_post_connection(None, &new_inserted);
3496        self.notify_child_list(parent, new_inserted, alloc::vec![idx]);
3497    }
3498
3499    /// `dom::Node` 部分木をブリッジへ取り込み、ルート idx を返す。
3500    pub fn import_node(&mut self, node: &Node) -> usize {
3501        match &node.node_type {
3502            NodeType::Text(t) => self.new_text_node(t),
3503            NodeType::Element {
3504                tag_name,
3505                attributes,
3506                classes,
3507                id,
3508            } => {
3509                let idx = self.new_element_node(tag_name);
3510                {
3511                    let style = parse_inline_style(
3512                        attributes.get("style").map(|s| s.as_str()).unwrap_or(""),
3513                    );
3514                    let (attrs, text) = Self::special_node_parts(tag_name, attributes);
3515                    let n = &mut self.nodes[idx];
3516                    n.tag = tag_name.clone();
3517                    n.id = id.clone().unwrap_or_default();
3518                    n.classes = classes.clone();
3519                    n.style = style;
3520                    n.attrs = attrs;
3521                    if let Some(t) = text {
3522                        n.initial_text = t.clone();
3523                        n.text_override = Some(t);
3524                    }
3525                }
3526                let mut kids = Vec::new();
3527                for c in &node.children {
3528                    let ci = self.import_node(c);
3529                    self.nodes[ci].parent = Some(idx);
3530                    kids.push(ci);
3531                }
3532                self.nodes[idx].children = kids;
3533                self.normalize_foreign_attrs(idx);
3534                idx
3535            }
3536        }
3537    }
3538
3539    /// SVG / MathML / XML 要素にある `xlink href`・`xml lang`・`xmlns xlink` 等を名前空間付き属性 `ns_attrs` へ正規化する。
3540    pub fn normalize_foreign_attrs(&mut self, idx: usize) {
3541        let (is_foreign, is_xml) = match self.nodes.get(idx) {
3542            Some(n) if !n.is_text && !n.tag.starts_with('#') => (
3543                matches!(n.attrs.get("#ns").map(|s| s.as_str()), Some("svg") | Some("math")),
3544                n.attrs.contains_key("_xml"),
3545            ),
3546            _ => return,
3547        };
3548        if !is_foreign && !is_xml {
3549            return;
3550        }
3551        let keys: Vec<String> = self.nodes[idx].attrs.keys().cloned().collect();
3552        let mut moved: Vec<(String, String, String, String)> = Vec::new();
3553        for k in keys {
3554            if k.starts_with('_') || k.starts_with('#') {
3555                continue;
3556            }
3557            let mapped: Option<(&str, String)> = if let Some(l) = k.strip_prefix("xlink ") {
3558                Some(("http://www.w3.org/1999/xlink", format!("xlink:{}", l)))
3559            } else if let Some(l) = k.strip_prefix("xml ") {
3560                Some(("http://www.w3.org/XML/1998/namespace", format!("xml:{}", l)))
3561            } else if let Some(l) = k.strip_prefix("xmlns ") {
3562                Some(("http://www.w3.org/2000/xmlns/", format!("xmlns:{}", l)))
3563            } else if k == "xmlns" {
3564                Some(("http://www.w3.org/2000/xmlns/", String::from("xmlns")))
3565            } else if let Some(l) = k.strip_prefix("xmlns:") {
3566                Some(("http://www.w3.org/2000/xmlns/", format!("xmlns:{}", l)))
3567            } else if let Some(l) = k.strip_prefix("xlink:") {
3568                Some(("http://www.w3.org/1999/xlink", format!("xlink:{}", l)))
3569            } else if let Some(l) = k.strip_prefix("xml:") {
3570                Some(("http://www.w3.org/XML/1998/namespace", format!("xml:{}", l)))
3571            } else {
3572                None
3573            };
3574            if let Some((ns, qn)) = mapped {
3575                if let Some(val) = self.nodes[idx].attrs.get(&k).cloned() {
3576                    moved.push((k, ns.to_string(), qn, val));
3577                }
3578            }
3579        }
3580        if moved.is_empty() {
3581            return;
3582        }
3583        self.has_attr_nodes = true;
3584        for (old_k, ns, qn, val) in moved {
3585            self.nodes[idx].attrs.remove(&old_k);
3586            let list = self.ns_attrs.entry(idx).or_default();
3587            if !list.iter().any(|(a_ns, a_qn, _)| a_ns == &ns && a_qn == &qn) {
3588                list.push((ns, qn, val));
3589            }
3590        }
3591    }
3592
3593    /// XML/SVG パースで取り込まれた部分木をマークする(tagName で元のケースを保持するため)。
3594    /// `mark_subtree_xml` の逆(XML 文書から HTML 文書へ取り込んだ(`importNode`)部分木に使う)。
3595    pub fn unmark_subtree_xml(&mut self, idx: usize) {
3596        if let Some(n) = self.nodes.get_mut(idx) {
3597            n.attrs.remove("_xml");
3598            let kids = n.children.clone();
3599            for k in kids {
3600                self.unmark_subtree_xml(k);
3601            }
3602        }
3603    }
3604
3605    pub fn mark_subtree_xml(&mut self, idx: usize) {
3606        if let Some(n) = self.nodes.get_mut(idx) {
3607            n.attrs.insert("_xml".into(), "1".into());
3608            let kids = n.children.clone();
3609            self.normalize_foreign_attrs(idx);
3610            for k in kids {
3611                self.mark_subtree_xml(k);
3612            }
3613        }
3614    }
3615
3616    /// ブリッジツリー(node[0] をルート)を `dom::Node` へ変換する。
3617    /// JS の変更(textContent/style/class/動的ノード)が反映された描画用ツリー。
3618    pub fn to_dom_node(&self) -> Node {
3619        if self.nodes.is_empty() {
3620            return Node::new_text(String::new());
3621        }
3622        self.build_node(0)
3623    }
3624
3625    /// `to_dom_node` の木の pre-order 走査順に、ノードの添字を並べたもの。
3626    /// 動的に作った要素があると「走査順」と「`nodes` の添字」は一致しないので、
3627    /// 木の位置からノードへ戻すときはこの表を使う。
3628    pub fn tree_order(&self) -> Vec<usize> {
3629        let mut out = Vec::with_capacity(self.nodes.len());
3630        if !self.nodes.is_empty() {
3631            self.tree_order_into(0, &mut out);
3632        }
3633        out
3634    }
3635
3636    fn tree_order_into(&self, idx: usize, out: &mut Vec<usize>) {
3637        out.push(idx);
3638        if self.has_shells {
3639            let mut v = Vec::new();
3640            self.flat_kids(idx, &mut v);
3641            for c in v {
3642                self.tree_order_into(c, out);
3643            }
3644            return;
3645        }
3646        for &c in &self.nodes[idx].children {
3647            self.tree_order_into(c, out);
3648        }
3649    }
3650
3651    fn build_node(&self, idx: usize) -> Node {
3652        let n = &self.nodes[idx];
3653        if n.is_text {
3654            let mut node = Node::new_text(
3655                n.text_override
3656                    .clone()
3657                    .unwrap_or_else(|| n.initial_text.clone()),
3658            );
3659            node.node_idx = Some(idx);
3660            return node;
3661        }
3662        let mut attrs = n.attrs.clone();
3663        // 名前空間用の内部属性(`dom_ns.rs`)は描画用の木へ渡さない。インライン SVG は要素の属性を
3664        // そのままマークアップに書き出すので、渡すと `_ns="http://…"` などが SVG の解析を壊す(YouTube のロゴが赤い帯になった)。
3665        attrs.remove("_ns");
3666        attrs.remove("_qname");
3667        attrs.remove("_prefix");
3668        let id = if n.id.is_empty() {
3669            let gen_id = alloc::format!("_node_idx_{}", idx);
3670            attrs.insert("id".to_string(), gen_id.clone());
3671            Some(gen_id)
3672        } else {
3673            attrs.insert("id".to_string(), n.id.clone());
3674            Some(n.id.clone())
3675        };
3676        if n.classes.is_empty() {
3677            attrs.remove("class");
3678        } else {
3679            attrs.insert("class".to_string(), n.classes.join(" "));
3680        }
3681        if n.style.is_empty() {
3682            attrs.remove("style");
3683        } else {
3684            attrs.insert("style".to_string(), serialize_inline_style(&n.style));
3685        }
3686        let mut node = Node::new_element_direct(n.tag.clone(), attrs, id, n.classes.clone());
3687        node.node_idx = Some(idx);
3688        node.children.reserve(n.children.len());
3689        let flat: Vec<usize>;
3690        let kids: &[usize] = if self.has_shells {
3691            let mut v = Vec::new();
3692            self.flat_kids(idx, &mut v);
3693            flat = v;
3694            &flat
3695        } else {
3696            &n.children
3697        };
3698        for &c in kids {
3699            // 【2026-11-18 TODO R2 (b) ②】`to_dom_node` もノードの数だけ回るので確かめる。このタブだけ止める合図なら
3700            // 残りの子を作らない(途中までの木は `parse_and_layout` が合図を見て捨てる)。
3701            if bridge_poll() {
3702                break;
3703            }
3704            node.children.push(self.build_node(c));
3705        }
3706        node.update_dependent_hashes();
3707        node
3708    }
3709
3710    /// 要素の textContent(現在値)を取得。
3711    pub fn get_text_content(&self, idx: usize) -> String {
3712        if idx >= self.nodes.len() {
3713            return String::new();
3714        }
3715        self.collect_text(idx)
3716    }
3717
3718    fn descendant_text_nodes(&self, idx: usize) -> Vec<usize> {
3719        let mut out = Vec::new();
3720        self.descendant_text_into(idx, &mut out);
3721        out
3722    }
3723    fn descendant_text_into(&self, idx: usize, out: &mut Vec<usize>) {
3724        let node = &self.nodes[idx];
3725        if node.is_text {
3726            out.push(idx);
3727            return;
3728        }
3729        for &c in &node.children {
3730            self.descendant_text_into(c, out);
3731        }
3732    }
3733
3734    // `style.xxx = ...`/`style.cssText = ...` は `class`/他の属性と同じく
3735    // `MutationObserver`(`attributes:true` + `attributeFilter:['style']` 等)が
3736    // 観察できるべき「style」属性の変化にもかかわらず、`class_add`/`class_remove`
3737    // と同型で `notify_attribute` を一切呼んでいなかった非対称バグ。
3738    pub fn set_style(&mut self, idx: usize, prop: &str, val: &str) {
3739        let key = css_prop_from_camel(prop);
3740        let (old_value, changed, had_attr) = {
3741            let Some(n) = self.nodes.get_mut(idx) else {
3742                return;
3743            };
3744            let old_value = serialize_inline_style(&n.style);
3745            let changed = if val.is_empty() {
3746                n.style.remove(&key).is_some()
3747            } else {
3748                n.style.insert(key.clone(), val.to_string()).as_deref() != Some(val)
3749            };
3750            let style_str = serialize_inline_style(&n.style);
3751            let had_attr = n.attrs.contains_key("style");
3752            n.attrs.insert(String::from("style"), style_str);
3753            if changed {
3754                n.style_dirty = true;
3755            }
3756            (old_value, changed, had_attr)
3757        };
3758        if !had_attr {
3759            self.attr_order_push(idx, "style");
3760        }
3761        // 【2026-10-09】値が変わらない代入では再レイアウトを要求しない。scroll リスナが
3762        // 毎回同じ値を入れる定番の書き方(sugi-lab.net の `header.style.background = ...`)で、
3763        // スクロールの度に全体の再レイアウト(QEMU で約 350ms)が走っていた。
3764        // MutationObserver への通知は仕様どおり続ける(属性の再設定は記録される)。
3765        // 【2026-11-15】TODO P4b: 未接続要素や、`display: none` 部分木内の非 `display` プロパティ変更では
3766        // 画面の見た目も配置も変わらないため、`dirty` / `pending_style_updates` へ積まない。
3767        if changed && self.is_attached(idx) && !(key != "display" && self.is_in_display_none_subtree(idx)) {
3768            self.dirty = true;
3769            Self::count_relayout_request();
3770            if let Some(pos) = self.pending_style_updates.iter().position(|(i, k, _)| *i == idx && k == &key) {
3771                self.pending_style_updates[pos].2 = val.to_string();
3772            } else {
3773                let cause = alloc::format!("style:{}", key);
3774                self.note_dirty_cause(&cause);
3775                self.pending_style_updates.push((idx, key, val.to_string()));
3776            }
3777        }
3778        self.notify_attribute(idx, "style", Some(&old_value));
3779    }
3780
3781    pub fn get_style(&self, idx: usize, prop: &str) -> String {
3782        let raw = self
3783            .nodes
3784            .get(idx)
3785            .and_then(|n| n.style.get(&css_prop_from_camel(prop)).cloned())
3786            .unwrap_or_default();
3787        strip_style_priority(&raw).0.to_string()
3788    }
3789
3790    /// `element.style.getPropertyPriority(name)`(丸ごと未対応だった。
3791    /// 2026-07-16 発見)。`!important` は生の値文字列末尾にそのまま保持
3792    /// されている(`set_style`/`css_prop_from_camel` 参照)ため、
3793    /// `strip_style_priority` で判定するだけで済む。
3794    pub fn get_style_priority(&self, idx: usize, prop: &str) -> String {
3795        let raw = self
3796            .nodes
3797            .get(idx)
3798            .and_then(|n| n.style.get(&css_prop_from_camel(prop)).cloned())
3799            .unwrap_or_default();
3800        if strip_style_priority(&raw).1 {
3801            "important".to_string()
3802        } else {
3803            String::new()
3804        }
3805    }
3806
3807    /// `element.style.cssText` の読み出し。以前は丸ごと未対応で、`cssText` を単なる
3808    /// 通常の CSS プロパティ名として扱う既存の汎用経路(`get_style`)に落ちてしまい、
3809    /// 常に空文字列を返していた(`serialize_inline_style` 自体は属性文字列の再構築で
3810    /// 既に使われていたが、JS からの読み出しには配線されていなかった)。
3811    pub fn get_css_text(&self, idx: usize) -> String {
3812        self.nodes
3813            .get(idx)
3814            .map(|n| serialize_inline_style(&n.style))
3815            .unwrap_or_default()
3816    }
3817    /// `element.style.cssText = "..."` の書き込み。単一プロパティとして扱われ常に
3818    /// 無視されていたのを、既存のスタイル属性パーサ(`parse_inline_style`)で丸ごと
3819    /// 置き換えるよう実装する。
3820    pub fn set_css_text(&mut self, idx: usize, text: &str) {
3821        let (old_value, changed, had_attr) = {
3822            let Some(n) = self.nodes.get_mut(idx) else {
3823                return;
3824            };
3825            let old_value = serialize_inline_style(&n.style);
3826            n.style = parse_inline_style(text);
3827            let new_value = serialize_inline_style(&n.style);
3828            let changed = new_value != old_value;
3829            let had_attr = n.attrs.contains_key("style");
3830            n.attrs.insert(String::from("style"), new_value);
3831            if changed {
3832                n.style_dirty = true;
3833            }
3834            (old_value, changed, had_attr)
3835        };
3836        if !had_attr {
3837            self.attr_order_push(idx, "style");
3838        }
3839        if changed && self.is_attached(idx) {
3840            self.mark_structural_dirty_for("cssText");
3841        }
3842        self.notify_attribute(idx, "style", Some(&old_value));
3843    }
3844
3845    /// 診断用: DOM の骨組み(`tag#id.class [style]`)を字下げ付きで最大 `max` 行返す。
3846    /// テキストノードは省く。実サイトの JS がどんな要素を組み立てたかを追うためのもの。
3847    pub fn outline(&self, max: usize) -> Vec<String> {
3848        let mut out = Vec::new();
3849        let mut stack: Vec<(usize, usize)> = self
3850            .nodes
3851            .iter()
3852            .enumerate()
3853            .filter(|(_, n)| n.parent.is_none() && !n.is_text)
3854            .map(|(i, _)| (i, 0))
3855            .rev()
3856            .collect();
3857        while let Some((idx, depth)) = stack.pop() {
3858            if out.len() >= max {
3859                break;
3860            }
3861            let Some(n) = self.nodes.get(idx) else { continue };
3862            if n.is_text {
3863                continue;
3864            }
3865            let mut line = String::new();
3866            for _ in 0..depth.min(30) {
3867                line.push(' ');
3868            }
3869            line.push_str(&n.tag);
3870            if !n.id.is_empty() {
3871                line.push('#');
3872                line.push_str(&n.id);
3873            }
3874            for c in n.classes.iter().take(3) {
3875                line.push('.');
3876                line.push_str(c);
3877            }
3878            if !n.style.is_empty() {
3879                line.push_str(" [");
3880                for (k, v) in n.style.iter().take(4) {
3881                    line.push_str(k);
3882                    line.push(':');
3883                    line.extend(v.chars().take(70));
3884                    line.push(';');
3885                }
3886                line.push(']');
3887            }
3888            if let Some(src) = n.attrs.get("src") {
3889                line.push_str(" src=");
3890                line.extend(src.chars().take(60));
3891            }
3892            // 直下のテキスト(エラー表示の文言などを読むため)。
3893            let text: String = n
3894                .children
3895                .iter()
3896                .filter_map(|&c| self.nodes.get(c))
3897                .filter(|c| c.is_text)
3898                .map(|c| c.text_override.as_deref().unwrap_or(&c.initial_text))
3899                .collect::<Vec<_>>()
3900                .join("");
3901            let text = n.text_override.as_deref().filter(|t| !t.is_empty()).unwrap_or(text.as_str()).trim();
3902            if !text.is_empty() && n.tag != "script" && n.tag != "style" {
3903                line.push_str(" \"");
3904                line.extend(text.chars().take(80));
3905                line.push('"');
3906            }
3907            out.push(line);
3908            for &c in n.children.iter().rev() {
3909                stack.push((c, depth + 1));
3910            }
3911        }
3912        out
3913    }
3914
3915    /// `element.outerHTML`(読み出し専用。書き込み側は要素の親子関係の組み替えが
3916    /// 必要で改修規模が大きいため今回は見送り)が丸ごと未対応だった。自身のタグ・属性
3917    /// (id/class/style を含む)・子孫を再帰的に HTML 文字列へ直列化する。
3918    pub fn get_outer_html(&self, idx: usize) -> String {
3919        let mut out = String::new();
3920        self.serialize_node_html(idx, &mut out);
3921        out
3922    }
3923    /// `element.innerHTML` の読み出しが、実際にはマークアップ(子要素タグ)を含めず
3924    /// `textContent` と同じ「全テキストを連結しただけ」の値を返してしまっていたバグ。
3925    /// `<div>a<b>bold</b></div>` の `innerHTML` が仕様どおりの `"a<b>bold</b>"` ではなく
3926    /// `"abold"` になっていた。自身のタグは含めず、子ノードだけを直列化する。
3927    pub fn get_inner_html(&self, idx: usize) -> String {
3928        let mut out = String::new();
3929        if let Some(n) = self.nodes.get(idx) {
3930            for &c in &n.children {
3931                self.serialize_node_html(c, &mut out);
3932            }
3933        }
3934        out
3935    }
3936    fn serialize_node_html(&self, idx: usize, out: &mut String) {
3937        let Some(n) = self.nodes.get(idx) else { return };
3938        if n.is_text {
3939            let text = n.text_override.as_deref().unwrap_or(&n.initial_text);
3940            // 生テキスト要素(script/style 等)の中身はエスケープしない(HTML の直列化アルゴリズム)。
3941            // 【2026-10-18】`<style>` の `a>b` が `a&gt;b` になり、取り出した CSS が壊れていた。
3942            let raw_parent = n
3943                .parent
3944                .and_then(|p| self.nodes.get(p))
3945                .is_some_and(|p| crate::os_lib::dom::serializer::is_raw_text_element(p.tag.as_str(), true));
3946            if raw_parent {
3947                out.push_str(text);
3948            } else {
3949                crate::os_lib::dom::serializer::escape_text(text, out);
3950            }
3951            return;
3952        }
3953        if n.tag == "#doctype" {
3954            out.push_str("<!DOCTYPE ");
3955            out.push_str(n.attrs.get("_name").map(|s| s.as_str()).unwrap_or(""));
3956            out.push('>');
3957            return;
3958        }
3959        if n.tag == "#pi" {
3960            out.push_str("<?");
3961            out.push_str(n.attrs.get("_target").map(|s| s.as_str()).unwrap_or(""));
3962            out.push(' ');
3963            out.push_str(n.text_override.as_deref().unwrap_or(&n.initial_text));
3964            out.push('>');
3965            return;
3966        }
3967        if n.tag == "#comment" {
3968            out.push_str("<!--");
3969            out.push_str(n.text_override.as_deref().unwrap_or(&n.initial_text));
3970            out.push_str("-->");
3971            return;
3972        }
3973        if n.tag == "#document" {
3974            for &c in &n.children {
3975                self.serialize_node_html(c, out);
3976            }
3977            return;
3978        }
3979        out.push('<');
3980        out.push_str(&n.tag);
3981        if !n.id.is_empty() {
3982            out.push_str(&format!(" id=\"{}\"", html_escape_attr(&n.id)));
3983        }
3984        if !n.classes.is_empty() {
3985            out.push_str(&format!(" class=\"{}\"", html_escape_attr(&n.classes.join(" "))));
3986        }
3987        if !n.style.is_empty() {
3988            out.push_str(&format!(
3989                " style=\"{}\"",
3990                html_escape_attr(&serialize_inline_style(&n.style))
3991            ));
3992        }
3993        // `n.attrs` には HTML パース時の生の `id`/`class` もそのまま残っている場合が
3994        // あり(`n.id`/`n.classes` は別途専用フィールドとして持つ)、除外しないと
3995        // `id="t" id="t"` のように重複出力してしまう。`_` 始まりの内部専用属性
3996        // (`_content_frag`/`_return_value`/`_custom_validity` 等、実装詳細を
3997        // `set_attr`/`get_attr` 経由で持ち回るための housekeeping 用の値)も
3998        // 除外しないと `outerHTML`/`innerHTML` にそのまま漏れて見えてしまう
3999        // バグだった。
4000        for (k, v) in &n.attrs {
4001            if k == "id" || k == "class" || k == "style" || k.starts_with('_') {
4002                continue;
4003            }
4004            out.push(' ');
4005            out.push_str(k);
4006            out.push_str("=\"");
4007            out.push_str(&html_escape_attr(v));
4008            out.push('"');
4009        }
4010        out.push('>');
4011        // void 要素(自身終了タグを持たない)。
4012        if crate::os_lib::dom::serializer::is_void_element(n.tag.as_str()) {
4013            return;
4014        }
4015        for &c in &n.children {
4016            self.serialize_node_html(c, out);
4017        }
4018        out.push_str("</");
4019        out.push_str(&n.tag);
4020        out.push('>');
4021    }
4022
4023    // `classList.add`/`.remove` は `class` 属性を書き換えるにもかかわらず、
4024    // `setAttribute('class', ...)`/`removeAttribute()` と違って `notify_attribute`
4025    // を一切呼んでおらず、`MutationObserver` に「class」の変化が通知されない
4026    // 非対称バグだった(`set_attr`/`remove_attr` は既に通知していた)。
4027    pub fn class_add(&mut self, idx: usize, cls: &str) {
4028        if self.nodes.get(idx).is_some_and(|n| !n.attrs.contains_key("class") && !n.classes.iter().any(|c| c == cls)) {
4029            self.attr_order_push(idx, "class");
4030        }
4031        let old_value = {
4032            let Some(n) = self.nodes.get_mut(idx) else {
4033                return;
4034            };
4035            if n.classes.iter().any(|c| c == cls) {
4036                return;
4037            };
4038            // class 属性がまだ無いときの oldValue は null(空文字列ではない)。
4039            let old_value = if n.classes.is_empty() && !n.attrs.contains_key("class") { None } else { Some(n.classes.join(" ")) };
4040            n.classes.push(cls.to_string());
4041            n.classes_dirty = true;
4042            n.attrs.insert(String::from("class"), n.classes.join(" "));
4043            old_value
4044        };
4045        if self.is_attached(idx) {
4046            self.mark_structural_dirty_for("class");
4047        }
4048        self.notify_attribute(idx, "class", old_value.as_deref());
4049    }
4050    pub fn class_remove(&mut self, idx: usize, cls: &str) {
4051        let old_value = {
4052            let Some(n) = self.nodes.get_mut(idx) else {
4053                return;
4054            };
4055            let before = n.classes.len();
4056            // class 属性がまだ無いときの oldValue は null(空文字列ではない)。
4057            let old_value = if n.classes.is_empty() && !n.attrs.contains_key("class") { None } else { Some(n.classes.join(" ")) };
4058            n.classes.retain(|c| c != cls);
4059            if n.classes.len() == before {
4060                return;
4061            }
4062            n.classes_dirty = true;
4063            n.attrs.insert(String::from("class"), n.classes.join(" "));
4064            old_value
4065        };
4066        if self.is_attached(idx) {
4067            self.mark_structural_dirty_for("class");
4068        }
4069        self.notify_attribute(idx, "class", old_value.as_deref());
4070    }
4071    pub fn class_toggle(&mut self, idx: usize, cls: &str) -> bool {
4072        if self.class_contains(idx, cls) {
4073            self.class_remove(idx, cls);
4074            false
4075        } else {
4076            self.class_add(idx, cls);
4077            true
4078        }
4079    }
4080    pub fn class_contains(&self, idx: usize, cls: &str) -> bool {
4081        self.nodes
4082            .get(idx)
4083            .map(|n| n.classes.iter().any(|c| c == cls))
4084            .unwrap_or(false)
4085    }
4086
4087    /// `<select>`配下の`<option>`要素を全て集める(`<optgroup>`でグループ化
4088    /// された`<option>`も含む再帰探索。丸ごと未対応だった。以前は直接の子
4089    /// のみを見る実装だったため、`<select><optgroup label="Fruits">
4090    /// <option>Apple</option></optgroup></select>`という非常によく使われる
4091    /// カテゴリ分けパターンで、`<optgroup>`配下の`<option>`が`select.
4092    /// options`/フォーム送信のどちらからも一切見えなくなる実害のある
4093    /// バグだった。`<option>`要素自身は子に更に`<option>`を持たない
4094    /// (仕様上そのような入れ子は無意味)ため、`<option>`に達したら
4095    /// そこで再帰を打ち切る。2026-07-17 発見・実装)。
4096    fn collect_descendant_options(&self, idx: usize, out: &mut Vec<usize>) {
4097        let Some(n) = self.nodes.get(idx) else { return };
4098        for &c in &n.children {
4099            let Some(cn) = self.nodes.get(c) else { continue };
4100            if cn.tag == "option" {
4101                out.push(c);
4102            } else {
4103                self.collect_descendant_options(c, out);
4104            }
4105        }
4106    }
4107    /// `<select>` の option 子要素一覧(`<optgroup>`配下も含む)。`select.
4108    /// options`(丸ごと未対応だった。動的にドロップダウンを構築する定番
4109    /// イディオムで使われる)向けに公開する。
4110    pub fn select_options(&self, idx: usize) -> Vec<usize> {
4111        let mut out = Vec::new();
4112        self.collect_descendant_options(idx, &mut out);
4113        out
4114    }
4115    /// option 要素の実効値: `value` 属性があればそれ、無ければテキスト内容
4116    /// (仕様どおり。`collect_form_data` の select フォールバックと同じ規則)。
4117    fn option_value(&self, opt_idx: usize) -> String {
4118        self.get_attr(opt_idx, "value").unwrap_or_else(|| {
4119            self.nodes
4120                .get(opt_idx)
4121                .map(|n| n.text_override.clone().unwrap_or_else(|| n.initial_text.clone()))
4122                .unwrap_or_default()
4123        })
4124    }
4125    /// `select.selectedOptions`(`<select multiple>` で選択中の option 一覧を得る
4126    /// 定番イディオム。`FormData` の multi-select 対応と同じく `selected` 属性を
4127    /// 真実源とする)。単一選択の `<select>` でも仕様どおり動作する
4128    /// (`selected` が無ければ既定選択の最初の option を1件返す)。
4129    pub fn selected_option_indices(&self, idx: usize) -> Vec<usize> {
4130        let options = self.select_options(idx);
4131        let selected: Vec<usize> = options.iter().copied().filter(|&o| self.has_attr(o, "selected")).collect();
4132        if !selected.is_empty() {
4133            selected
4134        } else {
4135            options.first().copied().into_iter().collect()
4136        }
4137    }
4138    /// `select.value`(丸ごと未対応だった。`<select>` 自身に `value` 属性は無く、
4139    /// 選択状態は子の `<option selected>` が持つため、汎用の属性直結 getter では
4140    /// 常に空文字列になっていた)。`selected` な option を優先し、無ければ
4141    /// HTML の既定選択どおり最初の option にフォールバックする。
4142    pub fn select_effective_value(&self, idx: usize) -> String {
4143        let options = self.select_options(idx);
4144        let target = options
4145            .iter()
4146            .copied()
4147            .find(|&o| self.has_attr(o, "selected"))
4148            .or_else(|| options.first().copied());
4149        match target {
4150            Some(o) => self.option_value(o),
4151            None => String::new(),
4152        }
4153    }
4154    /// フォーム系コントロールの「現在の実効値」を文字列で解決する。
4155    /// `checkValidity()`/`.validationMessage`/`.validity`が素朴に
4156    /// `get_attr(idx,"value")`だけを見ており、`value`属性を持たない
4157    /// `<select>`(選択状態は子`<option selected>`が持つ)や、初期値が
4158    /// `value`属性ではなくテキストノードで表現される`<textarea>`では
4159    /// 常に空文字列として(=未入力として)誤って検証されてしまうバグの
4160    /// 共通修正用。`.value`ゲッター(`dom_props.rs`)と同じフォールバック
4161    /// 規則をここに一本化する。
4162    pub fn effective_form_value(&self, idx: usize) -> String {
4163        let tag = self.nodes.get(idx).map(|n| n.tag.as_str()).unwrap_or("");
4164        if tag == "select" {
4165            self.select_effective_value(idx)
4166        } else if tag == "textarea" {
4167            self.get_attr(idx, "_live_value").or_else(|| self.get_attr(idx, "value")).unwrap_or_else(|| {
4168                self.nodes
4169                    .get(idx)
4170                    .map(|n| n.initial_text.clone())
4171                    .unwrap_or_default()
4172            })
4173        } else if tag == "input" {
4174            self.input_value(idx)
4175        } else {
4176            self.get_attr(idx, "value").unwrap_or_default()
4177        }
4178    }
4179    /// `select.value = v`(丸ごと未対応だった)。value が一致する最初の option へ
4180    /// 選択を移す(他の option の `selected` は解除。仕様どおり単一選択)。
4181    pub fn set_select_value(&mut self, idx: usize, val: &str) {
4182        let options = self.select_options(idx);
4183        for &o in &options {
4184            if self.option_value(o) == val {
4185                self.set_attr(o, "selected", "selected");
4186            } else {
4187                self.remove_attr(o, "selected");
4188            }
4189        }
4190        self.mark_structural_dirty_for("select");
4191    }
4192    /// `select.selectedIndex`(丸ごと未対応だった)。`selected` な option の位置、
4193    /// 無ければ option が1つ以上あれば `0`(既定選択)、無ければ `-1`。
4194    pub fn select_selected_index(&self, idx: usize) -> i32 {
4195        let options = self.select_options(idx);
4196        match options.iter().position(|&o| self.has_attr(o, "selected")) {
4197            Some(p) => p as i32,
4198            None if !options.is_empty()
4199                && !self.nodes.get(idx).is_some_and(|n| n.attrs.contains_key("_sel_none")) => 0,
4200            None => -1,
4201        }
4202    }
4203    /// `select.selectedIndex = n`。
4204    pub fn set_select_selected_index(&mut self, idx: usize, n: i32) {
4205        let options = self.select_options(idx);
4206        if n < 0 || (n as usize) >= options.len() {
4207            if let Some(node) = self.nodes.get_mut(idx) {
4208                node.attrs.insert(String::from("_sel_none"), String::from("1"));
4209            }
4210        } else if let Some(node) = self.nodes.get_mut(idx) {
4211            node.attrs.remove("_sel_none");
4212        }
4213        for (i, &o) in options.iter().enumerate() {
4214            if i as i32 == n {
4215                self.set_attr(o, "selected", "selected");
4216            } else {
4217                self.remove_attr(o, "selected");
4218            }
4219        }
4220        self.mark_structural_dirty_for("select");
4221    }
4222    /// `select.length = n`(HTML5。`select.options.length`と同じ値を返す
4223    /// ゲッター兼、`n`より末尾のoptionを切り捨てる/不足分を空の`<option>`で
4224    /// 埋めるセッター。丸ごと未対応だった)。仕様どおり、新しい長さが現在より
4225    /// 小さければ末尾から削除、大きければ空の`<option>`を追加する。
4226    pub fn set_select_length(&mut self, idx: usize, n: usize) {
4227        let options = self.select_options(idx);
4228        if n < options.len() {
4229            for &o in &options[n..] {
4230                if let Some(parent) = self.nodes.get(o).and_then(|node| node.parent) {
4231                    self.remove_child(parent, o);
4232                }
4233            }
4234        } else {
4235            for _ in options.len()..n {
4236                let opt = self.create_element("option");
4237                self.append_child(idx, opt);
4238            }
4239        }
4240        self.mark_structural_dirty_for("select");
4241    }
4242    /// `option.index`(HTML5。自身が属する`<select>`内での0始まりの位置。
4243    /// `select.selectedIndex`の対になる、`<option>`側のIDL属性だが丸ごと
4244    /// 未対応だった)。`<select>`祖先が無い場合は仕様どおり`0`(要素が
4245    /// 「optionのリスト」に属さない場合の既定値。`<datalist>`配下は
4246    /// 対象外の簡略実装)。
4247    pub fn option_index(&self, idx: usize) -> i32 {
4248        match self.closest_tag(idx, "select") {
4249            Some(sel) => self
4250                .select_options(sel)
4251                .iter()
4252                .position(|&o| o == idx)
4253                .map(|p| p as i32)
4254                .unwrap_or(0),
4255            None => 0,
4256        }
4257    }
4258
4259    pub fn get_attr(&self, idx: usize, name: &str) -> Option<String> {
4260        let n = self.nodes.get(idx)?;
4261        match name {
4262            // 【2026-11-19】属性が無いとき(`null`)と空のとき(`""`)を区別する。生の文字列は `attrs` に残す
4263            // (`class="  a  b "` は `getAttribute("class")` で空白のまま返る。WPT `dom/nodes/Element-classlist.html`)。
4264            "id" => match n.attrs.get("id") {
4265                Some(v) => Some(v.clone()),
4266                None if !n.id.is_empty() => Some(n.id.clone()),
4267                None => None,
4268            },
4269            "class" => match n.attrs.get("class") {
4270                Some(v) => Some(v.clone()),
4271                None if !n.classes.is_empty() => Some(n.classes.join(" ")),
4272                None => None,
4273            },
4274            _ => n.attrs.get(name).cloned(),
4275        }
4276    }
4277    pub fn set_attr(&mut self, idx: usize, name: &str, val: &str) {
4278        let old_value = self.get_attr(idx, name);
4279        // 【2026-10-18】値が変わらない設定と、処理系の内部属性(`_paused` 等、`_` 始まり)は
4280        // レイアウトに影響しないので再レイアウトを招かない(MutationObserver への通知は従来どおり)。
4281        // YouTube の操作部は再生中に同じ属性を毎回設定し直し、1 回 2 秒の再レイアウトが続いていた。
4282        let unchanged = old_value.as_deref() == Some(val) && (name != "id" || !val.is_empty());
4283        if unchanged || name.starts_with('_') {
4284            if let Some(n) = self.nodes.get_mut(idx) {
4285                match name {
4286                    "id" => {
4287                        n.id = val.to_string();
4288                        n.attrs.insert(name.to_string(), val.to_string());
4289                        self.id_dirty = true;
4290                    }
4291                    "class" => {
4292                        n.attrs.insert(name.to_string(), val.to_string());
4293                    }
4294                    _ => {
4295                        n.attrs.insert(name.to_string(), val.to_string());
4296                    }
4297                }
4298            }
4299            self.notify_attribute(idx, name, old_value.as_deref());
4300            return;
4301        }
4302        if old_value.is_none() {
4303            self.attr_order_push(idx, name);
4304            if let Some(ord) = self.attr_ns_order.get_mut(&idx) {
4305                if !ord.iter().any(|(ns, qn)| ns.is_none() && qn == name) {
4306                    ord.push((None, name.to_string()));
4307                }
4308            }
4309        }
4310        let affects_layout = self.attr_affects_layout(idx, name);
4311        let clear_sel_none = name == "selected" && self.nodes.get(idx).is_some_and(|n| !n.is_text && n.tag == "option");
4312        if let Some(n) = self.nodes.get_mut(idx) {
4313            match name {
4314                "id" => {
4315                    n.id = val.to_string();
4316                    n.attrs.insert(name.to_string(), val.to_string());
4317                    self.id_dirty = true;
4318                }
4319                "class" => {
4320                    n.classes = split_ascii_ws(val);
4321                    n.classes_dirty = true;
4322                    n.attrs.insert(name.to_string(), val.to_string());
4323                }
4324                _ => {
4325                    n.attrs.insert(name.to_string(), val.to_string());
4326                }
4327            }
4328            if affects_layout {
4329                self.mark_structural_dirty_attr(name);
4330            }
4331        }
4332        if clear_sel_none {
4333            let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4334            while let Some(p) = cur {
4335                if self.nodes.get(p).is_some_and(|n| !n.is_text && n.tag == "select") {
4336                    if let Some(sn) = self.nodes.get_mut(p) {
4337                        sn.attrs.remove("_sel_none");
4338                    }
4339                    break;
4340                }
4341                cur = self.nodes.get(p).and_then(|n| n.parent);
4342            }
4343        }
4344        if name == "type" && self.nodes.get(idx).is_some_and(|n| n.tag == "input") {
4345            self.input_type_changed(idx, old_value.as_deref());
4346        }
4347        self.notify_attribute(idx, name, old_value.as_deref());
4348    }
4349
4350    /// 属性が存在するか(空値の boolean 属性も存在として true。id/class は専用フィールド)。
4351    pub fn has_attr(&self, idx: usize, name: &str) -> bool {
4352        match self.nodes.get(idx) {
4353            Some(n) => match name {
4354                "id" => !n.id.is_empty() || n.attrs.contains_key("id"),
4355                "class" => !n.classes.is_empty() || n.attrs.contains_key("class"),
4356                _ => n.attrs.contains_key(name),
4357            },
4358            None => false,
4359        }
4360    }
4361
4362    /// 属性を削除(id/class フィールドも同期)。
4363    pub fn remove_attr(&mut self, idx: usize, name: &str) {
4364        // `set_attr` は属性変化を MutationObserver へ通知していたが、`remove_attr`
4365        // だけこの通知呼び出しが漏れていた非対称ペア(`removeAttribute()` も仕様上
4366        // "attributes" タイプの MutationRecord を発行すべき)。
4367        let old_value = self.get_attr(idx, name);
4368        if self.has_attr_nodes && !name.starts_with('_') {
4369            self.detach_attr_node(idx, name, old_value.as_deref().unwrap_or(""));
4370            if let Some(n) = self.nodes.get_mut(idx) {
4371                n.attrs.remove(&format!("_ans:{}", name));
4372            }
4373        }
4374        // 無い属性の削除は MutationObserver へ通知しない(DOM Standard §4.9)。
4375        if name.starts_with('_') {
4376            if let Some(n) = self.nodes.get_mut(idx) {
4377                n.attrs.remove(name);
4378            }
4379            return;
4380        }
4381        if !self.has_attr(idx, name) {
4382            let found_ns = self.ns_attrs.get_mut(&idx).and_then(|list| {
4383                list.iter()
4384                    .position(|(_, qn, _)| qn == name)
4385                    .map(|pos| list.remove(pos))
4386            });
4387            if let Some((u, qn, old_val)) = found_ns {
4388                if self.ns_attrs.get(&idx).is_some_and(|l| l.is_empty()) {
4389                    self.ns_attrs.remove(&idx);
4390                }
4391                let local = qn.split_once(':').map(|(_, l)| l).unwrap_or(&qn);
4392                self.remove_attr_ns_notify(idx, Some(&u), local, &qn, &old_val);
4393            }
4394            return;
4395        }
4396        if !self.attr_order.is_empty() {
4397            if let Some(o) = self.attr_order.get_mut(&idx) {
4398                o.retain(|k| k != name);
4399            }
4400        }
4401        if let Some(ord) = self.attr_ns_order.get_mut(&idx) {
4402            ord.retain(|(ns, qn)| !(ns.is_none() && qn == name));
4403        }
4404        let affects_layout = self.attr_affects_layout(idx, name);
4405        if let Some(n) = self.nodes.get_mut(idx) {
4406            match name {
4407                "id" => {
4408                    n.id = String::new();
4409                    n.attrs.remove("id");
4410                    self.id_dirty = true;
4411                }
4412                "class" => {
4413                    n.classes.clear();
4414                    n.classes_dirty = true;
4415                    n.attrs.remove("class");
4416                }
4417                "style" => {
4418                    n.style.clear();
4419                    n.style_dirty = true;
4420                    n.attrs.remove("style");
4421                }
4422                _ => {
4423                    n.attrs.remove(name);
4424                }
4425            }
4426            if affects_layout {
4427                self.mark_structural_dirty_attr(name);
4428            }
4429        }
4430        if name == "type" && self.nodes.get(idx).is_some_and(|n| n.tag == "input") {
4431            self.input_type_changed(idx, old_value.as_deref());
4432        }
4433        self.notify_attribute(idx, name, old_value.as_deref());
4434    }
4435
4436    /// W3C HTML5 §3.2.6.2 / DOMStringMap: `data-*` 属性から camelCase の dataset マップを抽出する。
4437    pub fn get_dataset(&self, idx: usize) -> BTreeMap<String, String> {
4438        match self.nodes.get(idx) {
4439            Some(n) => crate::os_lib::dom_dataset::extract_dataset(&n.attrs),
4440            None => BTreeMap::new(),
4441        }
4442    }
4443
4444    /// `<input type="radio">` の排他選択(同じ `name` を持つグループ内で1つだけが
4445    /// `checked` になる、というラジオボタンの最も基本的な仕様上の挙動)。`idx` を
4446    /// checked にする際、同じ `name` を持つ他の radio 全ての `checked` 属性を外す。
4447    /// フォーム所有者(`<form>` 単位のスコープ)は区別せず、同じ `name` を持つ
4448    /// document 内の全 radio を対象にする簡略実装。
4449    /// `<details name="...">`(HTML5。同じ`name`を持つ`<details>`同士は
4450    /// ラジオボタングループのように排他的に開閉する——1つを開くと同じ
4451    /// グループの他の`<details>`は自動的に閉じる——仕様が丸ごと未対応
4452    /// だった。`uncheck_radio_group_siblings`と同じ「`name`属性が一致する
4453    /// 兄弟(ドキュメント全体、DOM上の兄弟関係は問わない)を探して状態を
4454    /// 揃える」パターンをそのまま適用する。2026-07-18 発見・実装)。
4455    pub fn close_details_group_siblings(&mut self, idx: usize) -> alloc::vec::Vec<usize> {
4456        let name = match self.nodes.get(idx).and_then(|n| n.attrs.get("name")) {
4457            Some(n) if !n.is_empty() => n.clone(),
4458            _ => return alloc::vec::Vec::new(),
4459        };
4460        let siblings: alloc::vec::Vec<usize> = self
4461            .nodes
4462            .iter()
4463            .enumerate()
4464            .filter(|(i, n)| {
4465                *i != idx
4466                    && n.tag == "details"
4467                    && n.attrs.get("name").map(|s| s.as_str()) == Some(name.as_str())
4468                    && n.attrs.contains_key("open")
4469            })
4470            .map(|(i, _)| i)
4471            .collect();
4472        for &i in &siblings {
4473            self.remove_attr(i, "open");
4474        }
4475        siblings
4476    }
4477
4478    fn node_tree_root(&self, idx: usize) -> usize {
4479        let mut cur = idx;
4480        for _ in 0..=self.nodes.len() {
4481            match self.nodes.get(cur).and_then(|n| n.parent) {
4482                Some(p) => cur = p,
4483                None => break,
4484            }
4485        }
4486        cur
4487    }
4488
4489    fn radio_form_owner(&self, idx: usize, root: usize) -> Option<usize> {
4490        if let Some(fid) = self.nodes.get(idx).and_then(|n| n.attrs.get("form")).filter(|s| !s.is_empty()) {
4491            let mut stack = alloc::vec![root];
4492            while let Some(c) = stack.pop() {
4493                if let Some(n) = self.nodes.get(c) {
4494                    if !n.is_text && n.tag == "form" && n.id == *fid {
4495                        return Some(c);
4496                    }
4497                    stack.extend(n.children.iter().rev().copied());
4498                }
4499            }
4500        }
4501        let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4502        for _ in 0..=self.nodes.len() {
4503            let Some(p) = cur else { break };
4504            if self.nodes.get(p).is_some_and(|n| !n.is_text && n.tag == "form") {
4505                return Some(p);
4506            }
4507            cur = self.nodes.get(p).and_then(|n| n.parent);
4508        }
4509        None
4510    }
4511
4512    pub fn same_radio_group(&self, a: usize, b: usize) -> bool {
4513        let Some(na) = self.nodes.get(a) else { return false };
4514        let Some(nb) = self.nodes.get(b) else { return false };
4515        if na.is_text || nb.is_text || na.tag != "input" || nb.tag != "input" {
4516            return false;
4517        }
4518        let is_radio = |n: &DomNode| n.attrs.get("type").is_some_and(|t| t.eq_ignore_ascii_case("radio"));
4519        if !is_radio(na) || !is_radio(nb) {
4520            return false;
4521        }
4522        let name_a = na.attrs.get("name").map(|s| s.as_str()).unwrap_or("");
4523        let name_b = nb.attrs.get("name").map(|s| s.as_str()).unwrap_or("");
4524        if name_a.is_empty() || name_a != name_b {
4525            return false;
4526        }
4527        let ra = self.node_tree_root(a);
4528        let rb = self.node_tree_root(b);
4529        let fa = self.radio_form_owner(a, ra);
4530        let fb = self.radio_form_owner(b, rb);
4531        match (fa, fb) {
4532            (Some(x), Some(y)) => x == y,
4533            (None, None) => ra == rb,
4534            _ => false,
4535        }
4536    }
4537
4538    pub fn uncheck_radio_group_siblings(&mut self, idx: usize) {
4539        let siblings: Vec<usize> = (0..self.nodes.len())
4540            .filter(|&i| i != idx && self.same_radio_group(idx, i))
4541            .collect();
4542        for i in siblings {
4543            self.remove_attr(i, "checked");
4544            self.set_attr(i, "_live_checked", "false");
4545        }
4546    }
4547
4548    pub fn assigned_slot_for(&self, idx: usize) -> Option<usize> {
4549        let p = self.nodes.get(idx)?.parent?;
4550        let d = self.shadow_tree.get_by_host(p)?;
4551        if !d.is_accessible_via_element() {
4552            return None;
4553        }
4554        let slot_name = self.get_attr(idx, "slot").unwrap_or_default();
4555        self.descendants_by_tag_name(d.root_node_idx, "slot")
4556            .into_iter()
4557            .find(|&s| self.get_attr(s, "name").unwrap_or_default() == slot_name)
4558    }
4559
4560    pub fn slot_assigned_nodes(&self, slot_idx: usize, elem_only: bool) -> Vec<usize> {
4561        let mut cur = self.nodes.get(slot_idx).and_then(|n| n.parent);
4562        let mut root = slot_idx;
4563        while let Some(p) = cur {
4564            root = p;
4565            cur = self.nodes.get(p).and_then(|n| n.parent);
4566        }
4567        let Some(host) = self.shadow_tree.get_host_by_root(root) else {
4568            return Vec::new();
4569        };
4570        let slot_name = self.get_attr(slot_idx, "name").unwrap_or_default();
4571        let Some(hn) = self.nodes.get(host) else {
4572            return Vec::new();
4573        };
4574        hn.children
4575            .iter()
4576            .copied()
4577            .filter(|&c| {
4578                let Some(cn) = self.nodes.get(c) else { return false };
4579                if cn.is_text {
4580                    !elem_only && slot_name.is_empty()
4581                } else {
4582                    !cn.tag.starts_with('#') && self.get_attr(c, "slot").unwrap_or_default() == slot_name
4583                }
4584            })
4585            .collect()
4586    }
4587
4588    /// 単一ノードがセレクタ(コンパウンド + 結合子、カンマ区切りは OR)にマッチするか。
4589    /// `matches()`/`closest()`/`querySelector(All)` 共通の実装本体。以前は `#id`/`.class`/
4590    /// `tag`/`*` の単純セレクタしか認識せず、`div.active`(コンパウンド)や `[data-x]`
4591    /// (属性セレクタ)、`.a > .b`(結合子)を渡すと文字列全体を tag 名として比較する
4592    /// 分岐に落ち、常に false になる静かな破壊バグだった(`:not()`/`:nth-child()`/
4593    /// `:is()`/`:where()` 等の疑似クラスは引き続き非対応。改修規模を絞るための
4594    /// 意図的な割り切り)。
4595    pub fn node_matches(&self, idx: usize, selector: &str) -> bool {
4596        self.node_matches_scoped(idx, selector, None)
4597    }
4598
4599    /// `node_matches` の `:scope` 対応版。`scope_root` に `element.
4600    /// querySelectorAll`/`matches`/`closest` 等の起点ノードを渡すと、セレクタ中の
4601    /// `:scope` 疑似クラス(Selectors Level 4。丸ごと未対応だった)がそのノードに
4602    /// のみ一致するようになる。`scope_root` が `None`(`document.querySelectorAll`
4603    /// 等、起点を持たない文脈)の場合は `:scope` は常に不一致として扱う簡略実装。
4604    pub fn node_matches_scoped(&self, idx: usize, selector: &str, scope_root: Option<usize>) -> bool {
4605        if self.nodes.get(idx).map(|n| n.is_text).unwrap_or(true) {
4606            return false;
4607        }
4608        self.node_matches_parsed(idx, &parse_selector_groups(selector), scope_root)
4609    }
4610
4611    /// 解析済みのセレクタ(`parse_selector_groups`)に `idx` が一致するか。
4612    pub fn node_matches_parsed(&self, idx: usize, groups: &[Vec<SelStep>], scope_root: Option<usize>) -> bool {
4613        self.node_matches_parsed_with_anchor(idx, groups, scope_root, None)
4614    }
4615
4616    fn node_matches_parsed_with_anchor(
4617        &self,
4618        idx: usize,
4619        groups: &[Vec<SelStep>],
4620        scope_root: Option<usize>,
4621        has_anchor: Option<usize>,
4622    ) -> bool {
4623        if self.nodes.get(idx).map(|n| n.is_text || n.tag.starts_with('#')).unwrap_or(true) {
4624            return false;
4625        }
4626        for steps in groups {
4627            let last = steps.len() - 1;
4628            if self.compound_matches_with_anchor(idx, &steps[last].compound, scope_root, has_anchor)
4629                && self.match_selector_chain_with_anchor(idx, steps, last, scope_root, has_anchor)
4630            {
4631                return true;
4632            }
4633        }
4634        false
4635    }
4636
4637    /// `idx` がコンパウンドセレクタ(タグ/`#id`/`.class`/`[attr...]`)に一致するか。
4638    fn compound_matches(&self, idx: usize, c: &CompoundSel, scope_root: Option<usize>) -> bool {
4639        self.compound_matches_with_anchor(idx, c, scope_root, None)
4640    }
4641
4642    fn compound_matches_with_anchor(
4643        &self,
4644        idx: usize,
4645        c: &CompoundSel,
4646        scope_root: Option<usize>,
4647        has_anchor: Option<usize>,
4648    ) -> bool {
4649        if c.is_has_anchor && Some(idx) != has_anchor {
4650            return false;
4651        }
4652        if c.is_scope && Some(idx) != scope_root {
4653            return false;
4654        }
4655        let n = match self.nodes.get(idx) {
4656            Some(n) if !n.is_text && !n.tag.starts_with('#') => n,
4657            _ => return false,
4658        };
4659        let ns_uri = node_namespace(n);
4660        if c.no_namespace && ns_uri.is_some() {
4661            return false;
4662        }
4663        let html_el_in_html_doc = !n.attrs.contains_key("_xml")
4664            && ns_uri.as_deref() == Some(HTML_NS_URI)
4665            && self.doc_is_html(self.node_document(idx));
4666        if !type_selector_matches(c, &node_local_name(n), html_el_in_html_doc) {
4667            return false;
4668        }
4669        if let Some(id) = &c.id {
4670            if &n.id != id {
4671                return false;
4672            }
4673        }
4674        if !c.classes.iter().all(|cls| n.classes.iter().any(|nc| nc == cls)) {
4675            return false;
4676        }
4677        for (k, attr) in c.attrs.iter().enumerate() {
4678            let ext = c.attr_ext.get(k).copied().unwrap_or_default();
4679            let ok = if ext.any_ns {
4680                let in_plain = n.attrs.iter().any(|(qn, val)| {
4681                    !qn.starts_with('_')
4682                        && !qn.starts_with('#')
4683                        && attr_qname_has_local_name(qn, &attr.name)
4684                        && attr_value_matches(
4685                            attr.op,
4686                            &attr.value,
4687                            val,
4688                            ext,
4689                            html_el_in_html_doc && html_attr_value_is_case_insensitive(qn),
4690                        )
4691                });
4692                let in_ns = !in_plain
4693                    && self.ns_attrs.get(&idx).is_some_and(|list| {
4694                        list.iter().any(|(_, qn, val)| {
4695                            attr_qname_has_local_name(qn, &attr.name)
4696                                && attr_value_matches(
4697                                    attr.op,
4698                                    &attr.value,
4699                                    val,
4700                                    ext,
4701                                    html_el_in_html_doc && html_attr_value_is_case_insensitive(qn),
4702                                )
4703                        })
4704                    });
4705                in_plain || in_ns
4706            } else {
4707                let lookup = attr_lookup_name(&attr.name, html_el_in_html_doc);
4708                let val_opt = if lookup.starts_with('_') {
4709                    None
4710                } else {
4711                    n.attrs.get(&lookup).map(|s| s.as_str()).or_else(|| {
4712                        self.ns_attrs.get(&idx).and_then(|list| {
4713                            list.iter()
4714                                .find(|(_, qn, _)| qn == &lookup)
4715                                .map(|(_, _, v)| v.as_str())
4716                        })
4717                    })
4718                };
4719                match val_opt {
4720                    Some(actual) => attr_value_matches(
4721                        attr.op,
4722                        &attr.value,
4723                        actual,
4724                        ext,
4725                        html_el_in_html_doc && html_attr_value_is_case_insensitive(&lookup),
4726                    ),
4727                    None => false,
4728                }
4729            };
4730            if !ok {
4731                return false;
4732            }
4733        }
4734        for not_sel in &c.not {
4735            if self.compound_matches_with_anchor(idx, not_sel, scope_root, has_anchor) {
4736                return false;
4737            }
4738        }
4739        for not_steps in &c.not_complex {
4740            if self.node_matches_parsed_with_anchor(
4741                idx,
4742                core::slice::from_ref(not_steps),
4743                scope_root,
4744                has_anchor,
4745            ) {
4746                return false;
4747            }
4748        }
4749        if !c.is_list.is_empty() || !c.is_complex.is_empty() {
4750            let ok = c
4751                .is_list
4752                .iter()
4753                .any(|s| self.compound_matches_with_anchor(idx, s, scope_root, has_anchor))
4754                || c.is_complex.iter().any(|g| {
4755                    self.node_matches_parsed_with_anchor(
4756                        idx,
4757                        core::slice::from_ref(g),
4758                        scope_root,
4759                        has_anchor,
4760                    )
4761                });
4762            if !ok {
4763                return false;
4764            }
4765        }
4766        for rel in &c.has {
4767            let candidates: Vec<usize> = match rel.combinator {
4768                Combinator::Child | Combinator::Descendant => walk_elements(self, idx, false),
4769                Combinator::Adjacent | Combinator::General => self.following_sibling_elements_and_descendants(idx),
4770            };
4771            let anchored = core::slice::from_ref(&rel.anchored);
4772            if !candidates
4773                .into_iter()
4774                .any(|cand| self.node_matches_parsed_with_anchor(cand, anchored, scope_root, Some(idx)))
4775            {
4776                return false;
4777            }
4778        }
4779        if !c.pos.is_empty() {
4780            let (position, count) = self.element_sibling_position(idx);
4781            for p in &c.pos {
4782                let ok = match p {
4783                    PosPseudo::First => position == 1,
4784                    PosPseudo::Last => position == count,
4785                    PosPseudo::Only => position == 1 && count == 1,
4786                    PosPseudo::Nth(f) => nth_formula_matches(*f, position),
4787                    PosPseudo::NthLast(f) => nth_formula_matches(*f, count - position + 1),
4788                };
4789                if !ok {
4790                    return false;
4791                }
4792            }
4793        }
4794        if !c.pos_of_type.is_empty() {
4795            let (position, count) = self.element_type_sibling_position(idx);
4796            for p in &c.pos_of_type {
4797                let ok = match p {
4798                    PosPseudo::First => position == 1,
4799                    PosPseudo::Last => position == count,
4800                    PosPseudo::Only => position == 1 && count == 1,
4801                    PosPseudo::Nth(f) => nth_formula_matches(*f, position),
4802                    PosPseudo::NthLast(f) => nth_formula_matches(*f, count - position + 1),
4803                };
4804                if !ok {
4805                    return false;
4806                }
4807            }
4808        }
4809        if c.is_root {
4810            // :root は通常 <html> 要素、または親を持たないツリールート要素
4811            let is_root_elem = n.tag == "html" || n.parent.is_none();
4812            if !is_root_elem {
4813                return false;
4814            }
4815        }
4816        if c.is_empty {
4817            // :empty は子要素(Element)および非空テキストノードを持たない要素
4818            let has_content = n.children.iter().any(|&cid| {
4819                if let Some(child) = self.nodes.get(cid) {
4820                    !child.is_text || !child.text_override.as_deref().unwrap_or(&child.initial_text).is_empty()
4821                } else {
4822                    false
4823                }
4824            });
4825            if has_content {
4826                return false;
4827            }
4828        }
4829        if c.is_checked {
4830            let checked = if let Some(lc) = n.attrs.get("_live_checked") {
4831                lc == "true"
4832            } else {
4833                n.attrs.contains_key("checked")
4834            };
4835            if !checked {
4836                return false;
4837            }
4838        }
4839        if c.is_disabled && !self.is_disabled(idx) {
4840            return false;
4841        }
4842        if c.is_enabled {
4843            let can_disable = matches!(
4844                n.tag.as_str(),
4845                "button" | "input" | "select" | "textarea" | "optgroup" | "option" | "fieldset"
4846            );
4847            if !can_disable || self.is_disabled(idx) {
4848                return false;
4849            }
4850        }
4851        if c.is_valid || c.is_invalid {
4852            let is_ctrl_cand = !n.is_text && !self.barred_from_validation(idx);
4853            let valid_opt = if is_ctrl_cand {
4854                Some(self.validity_flags(idx, "").valid())
4855            } else if !n.is_text && n.tag == "form" {
4856                let controls = self.form_associated_controls(idx, &["button", "input", "select", "textarea"]);
4857                let any_invalid =
4858                    controls.iter().any(|&ci| !self.barred_from_validation(ci) && !self.validity_flags(ci, "").valid());
4859                Some(!any_invalid)
4860            } else if !n.is_text && n.tag == "fieldset" {
4861                let first_legend = n.children.iter().copied().find(|&ch| {
4862                    self.nodes.get(ch).is_some_and(|cn| !cn.is_text && cn.tag == "legend")
4863                });
4864                let mut stack: Vec<usize> = n.children.iter().copied().filter(|&ch| Some(ch) != first_legend).collect();
4865                let mut any_invalid = false;
4866                while let Some(ci) = stack.pop() {
4867                    if let Some(cn) = self.nodes.get(ci) {
4868                        if !cn.is_text {
4869                            if matches!(cn.tag.as_str(), "button" | "input" | "select" | "textarea")
4870                                && !self.barred_from_validation(ci)
4871                                && !self.validity_flags(ci, "").valid()
4872                            {
4873                                any_invalid = true;
4874                                break;
4875                            }
4876                            stack.extend(cn.children.iter().copied());
4877                        }
4878                    }
4879                }
4880                Some(!any_invalid)
4881            } else {
4882                None
4883            };
4884            match valid_opt {
4885                Some(valid) => {
4886                    if (c.is_valid && !valid) || (c.is_invalid && valid) {
4887                        return false;
4888                    }
4889                }
4890                None => return false,
4891            }
4892        }
4893        true
4894    }
4895
4896    /// `idx` の「要素兄弟のみを数えた」1始まりの位置と、要素兄弟の総数を返す
4897    /// (テキストノードは数えない。CSS の `:nth-child()` 等と同じ規則)。
4898    fn element_sibling_position(&self, idx: usize) -> (usize, usize) {
4899        let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
4900            Some(p) => p,
4901            None => return (1, 1),
4902        };
4903        let siblings = match self.nodes.get(parent) {
4904            Some(n) => &n.children,
4905            None => return (1, 1),
4906        };
4907        let elements: Vec<usize> = siblings
4908            .iter()
4909            .filter(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
4910            .copied()
4911            .collect();
4912        let count = elements.len();
4913        let position = elements.iter().position(|&c| c == idx).map(|p| p + 1).unwrap_or(0);
4914        (position, count)
4915    }
4916
4917    fn following_sibling_elements_and_descendants(&self, idx: usize) -> Vec<usize> {
4918        let Some(parent) = self.nodes.get(idx).and_then(|n| n.parent) else {
4919            return Vec::new();
4920        };
4921        let Some(siblings) = self.nodes.get(parent).map(|n| &n.children) else {
4922            return Vec::new();
4923        };
4924        let Some(pos) = siblings.iter().position(|&c| c == idx) else {
4925            return Vec::new();
4926        };
4927        let mut out = Vec::new();
4928        for &sib in &siblings[pos + 1..] {
4929            out.extend(walk_elements(self, sib, true));
4930        }
4931        out
4932    }
4933
4934    /// `element_sibling_position` と同じだが、同じタグ名の兄弟のみを数える
4935    /// (`:first-of-type`/`:last-of-type`/`:nth-of-type()` 用)。
4936    fn element_type_sibling_position(&self, idx: usize) -> (usize, usize) {
4937        let tag = match self.nodes.get(idx) {
4938            Some(n) => n.tag.clone(),
4939            None => return (1, 1),
4940        };
4941        let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
4942            Some(p) => p,
4943            None => return (1, 1),
4944        };
4945        let siblings = match self.nodes.get(parent) {
4946            Some(n) => &n.children,
4947            None => return (1, 1),
4948        };
4949        let same_type: Vec<usize> = siblings
4950            .iter()
4951            .filter(|&&c| self.nodes.get(c).map(|n| !n.is_text && n.tag == tag).unwrap_or(false))
4952            .copied()
4953            .collect();
4954        let count = same_type.len();
4955        let position = same_type.iter().position(|&c| c == idx).map(|p| p + 1).unwrap_or(0);
4956        (position, count)
4957    }
4958
4959    /// `idx` は `steps[step_i]` に既に一致した状態で呼ばれる。`steps[0..step_i]` を
4960    /// 結合子に従って祖先/兄弟方向へ再帰的に検証する。
4961    fn match_selector_chain(
4962        &self,
4963        idx: usize,
4964        steps: &[SelStep],
4965        step_i: usize,
4966        scope_root: Option<usize>,
4967    ) -> bool {
4968        self.match_selector_chain_with_anchor(idx, steps, step_i, scope_root, None)
4969    }
4970
4971    fn match_selector_chain_with_anchor(
4972        &self,
4973        idx: usize,
4974        steps: &[SelStep],
4975        step_i: usize,
4976        scope_root: Option<usize>,
4977        has_anchor: Option<usize>,
4978    ) -> bool {
4979        if step_i == 0 {
4980            return true;
4981        }
4982        let combinator = match steps[step_i].combinator {
4983            Some(c) => c,
4984            None => return true,
4985        };
4986        match combinator {
4987            Combinator::Descendant => {
4988                let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
4989                let mut guard = 0;
4990                while let Some(p) = cur {
4991                    if self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
4992                        && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
4993                    {
4994                        return true;
4995                    }
4996                    cur = self.nodes.get(p).and_then(|n| n.parent);
4997                    guard += 1;
4998                    if guard > self.nodes.len() {
4999                        break;
5000                    }
5001                }
5002                false
5003            }
5004            Combinator::Child => match self.nodes.get(idx).and_then(|n| n.parent) {
5005                Some(p) => {
5006                    self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5007                        && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5008                }
5009                None => false,
5010            },
5011            Combinator::Adjacent => match self.prev_element_sibling(idx) {
5012                Some(p) => {
5013                    self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5014                        && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5015                }
5016                None => false,
5017            },
5018            Combinator::General => {
5019                for p in self.preceding_element_siblings(idx) {
5020                    if self.compound_matches_with_anchor(p, &steps[step_i - 1].compound, scope_root, has_anchor)
5021                        && self.match_selector_chain_with_anchor(p, steps, step_i - 1, scope_root, has_anchor)
5022                    {
5023                        return true;
5024                    }
5025                }
5026                false
5027            }
5028        }
5029    }
5030
5031    /// `idx` の直前の要素兄弟(テキストノード・コメント等は飛ばす)。
5032    fn prev_element_sibling(&self, idx: usize) -> Option<usize> {
5033        let parent = self.nodes.get(idx)?.parent?;
5034        let siblings = &self.nodes.get(parent)?.children;
5035        let pos = siblings.iter().position(|&c| c == idx)?;
5036        siblings[..pos]
5037            .iter()
5038            .rev()
5039            .find(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
5040            .copied()
5041    }
5042
5043    /// `idx` より前にある全ての要素兄弟(テキストノード・コメント等は飛ばす、ドキュメント順)。
5044    fn preceding_element_siblings(&self, idx: usize) -> Vec<usize> {
5045        let parent = match self.nodes.get(idx).and_then(|n| n.parent) {
5046            Some(p) => p,
5047            None => return Vec::new(),
5048        };
5049        let siblings = match self.nodes.get(parent) {
5050            Some(n) => &n.children,
5051            None => return Vec::new(),
5052        };
5053        let pos = match siblings.iter().position(|&c| c == idx) {
5054            Some(p) => p,
5055            None => return Vec::new(),
5056        };
5057        siblings[..pos]
5058            .iter()
5059            .filter(|&&c| self.nodes.get(c).is_some_and(|n| !n.is_text && !n.tag.starts_with('#')))
5060            .copied()
5061            .collect()
5062    }
5063
5064    /// anc が idx の祖先か(idx 自身は含まない)。
5065    pub fn is_ancestor_of(&self, anc: usize, idx: usize) -> bool {
5066        let mut cur = idx;
5067        let mut guard = 0;
5068        while let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) {
5069            if p == anc {
5070                return true;
5071            }
5072            cur = p;
5073            guard += 1;
5074            if guard > self.nodes.len() {
5075                break;
5076            }
5077        }
5078        false
5079    }
5080
5081    /// `Node.compareDocumentPosition(other)`(DOM標準)が丸ごと未対応だった。
5082    /// `this_idx`(reference node)から見た `other_idx` の位置関係をビットマスクで返す
5083    /// (`DOCUMENT_POSITION_*` 定数は呼び出し側 `builtins.rs` で定義)。祖先/子孫関係は
5084    /// 既存の `is_ancestor_of` で判定し、それ以外(兄弟や別分岐)は両者の祖先鎖を根まで
5085    /// 辿って最も近い共通祖先(LCA)の子リスト内での順序を比較する。根が異なる
5086    /// (disconnected)場合、仕様上 PRECEDING/FOLLOWING の割当ては実装依存でよいため
5087    /// ノードindexの大小で決定的に決める。
5088    pub fn document_position(&self, this_idx: usize, other_idx: usize) -> u32 {
5089        const DISCONNECTED: u32 = 0x01;
5090        const PRECEDING: u32 = 0x02;
5091        const FOLLOWING: u32 = 0x04;
5092        const CONTAINS: u32 = 0x08;
5093        const CONTAINED_BY: u32 = 0x10;
5094        const IMPLEMENTATION_SPECIFIC: u32 = 0x20;
5095
5096        if this_idx == other_idx {
5097            return 0;
5098        }
5099        if self.is_ancestor_of(other_idx, this_idx) {
5100            // other は this の祖先(other が this を含む)。
5101            return CONTAINS | PRECEDING;
5102        }
5103        if self.is_ancestor_of(this_idx, other_idx) {
5104            // other は this の子孫(this が other を含む)。
5105            return CONTAINED_BY | FOLLOWING;
5106        }
5107        let chain_of = |start: usize| -> Vec<usize> {
5108            let mut chain = alloc::vec![start];
5109            let mut cur = start;
5110            let mut guard = 0;
5111            while let Some(p) = self.nodes.get(cur).and_then(|n| n.parent) {
5112                chain.push(p);
5113                cur = p;
5114                guard += 1;
5115                if guard > self.nodes.len() {
5116                    break;
5117                }
5118            }
5119            chain.reverse(); // ルート→自身の順に。
5120            chain
5121        };
5122        let chain_a = chain_of(this_idx);
5123        let chain_b = chain_of(other_idx);
5124        if chain_a.first() != chain_b.first() {
5125            // 根が異なる = disconnected。順序は実装依存でよいので index で決定的に決める。
5126            let order = if this_idx < other_idx { FOLLOWING } else { PRECEDING };
5127            return DISCONNECTED | IMPLEMENTATION_SPECIFIC | order;
5128        }
5129        let mut i = 0;
5130        while i < chain_a.len() && i < chain_b.len() && chain_a[i] == chain_b[i] {
5131            i += 1;
5132        }
5133        if i == 0 || i >= chain_a.len() || i >= chain_b.len() {
5134            // 分岐点が見つからない(理論上到達しないはずだが防御的に)。
5135            return DISCONNECTED | IMPLEMENTATION_SPECIFIC;
5136        }
5137        let lca = chain_a[i - 1];
5138        let child_a = chain_a[i];
5139        let child_b = chain_b[i];
5140        let siblings = match self.nodes.get(lca) {
5141            Some(n) => &n.children,
5142            None => return DISCONNECTED | IMPLEMENTATION_SPECIFIC,
5143        };
5144        let pos_a = siblings.iter().position(|&c| c == child_a);
5145        let pos_b = siblings.iter().position(|&c| c == child_b);
5146        match (pos_a, pos_b) {
5147            (Some(pa), Some(pb)) if pa < pb => FOLLOWING,
5148            (Some(pa), Some(pb)) if pa > pb => PRECEDING,
5149            _ => DISCONNECTED | IMPLEMENTATION_SPECIFIC,
5150        }
5151    }
5152
5153    /// idx 自身を含め祖先方向へ、指定タグの最初の要素を返す(`<form>` 解決等)。
5154    /// `element.offsetParent`(HTML5。丸ごと未対応だった)。祖先を遡り、算出
5155    /// `position` が `static` 以外の最初の要素を返す。無ければ `<body>`
5156    /// (見つからなければ `None` = 仕様どおり `null`)。
5157    pub fn offset_parent(&self, idx: usize) -> Option<usize> {
5158        let mut cur = self.nodes.get(idx).and_then(|n| n.parent);
5159        let mut body_idx = None;
5160        let mut guard = 0;
5161        while let Some(c) = cur {
5162            if self.nodes.get(c).map(|n| !n.is_text && n.tag == "body").unwrap_or(false) {
5163                body_idx = Some(c);
5164            }
5165            let pos = self.get_computed(c, "position");
5166            if pos == "absolute" || pos == "relative" || pos == "fixed" || pos == "sticky" {
5167                return Some(c);
5168            }
5169            cur = self.nodes.get(c).and_then(|n| n.parent);
5170            guard += 1;
5171            if guard > self.nodes.len() {
5172                break;
5173            }
5174        }
5175        body_idx
5176    }
5177
5178    pub fn closest_tag(&self, idx: usize, tag: &str) -> Option<usize> {
5179        let mut cur = Some(idx);
5180        let mut guard = 0;
5181        while let Some(c) = cur {
5182            if self
5183                .nodes
5184                .get(c)
5185                .map(|n| !n.is_text && n.tag == tag)
5186                .unwrap_or(false)
5187            {
5188                return Some(c);
5189            }
5190            cur = self.nodes.get(c).and_then(|n| n.parent);
5191            guard += 1;
5192            if guard > self.nodes.len() {
5193                break;
5194            }
5195        }
5196        None
5197    }
5198
5199    /// フォーム系コントロールが実際に属する`<form>`を解決する。HTML5仕様では
5200    /// `form="formId"`属性(`<form>`の子孫でなくても、その`id`で明示的に関連付ける
5201    /// 「form owner」機構)が祖先探索より優先される。以前は`closest_tag(idx,
5202    /// "form")`(祖先探索のみ)しか実装されておらず、`<form id="f1">`の外に置かれた
5203    /// `<input form="f1">`(フォーム外配置は`<form>`の視覚レイアウトを変えずに
5204    /// コントロールだけ離れた場所に置きたい場合の定番パターン)が
5205    /// `element.form`で`null`になり、`<form>.checkValidity()`/送信データ収集からも
5206    /// 漏れる、という兄弟ギャップだった。
5207    pub fn associated_form(&self, idx: usize) -> Option<usize> {
5208        // `form` 属性があれば、それが唯一の候補(同じ木の中で、その `id` を持つ最初の要素が `<form>` のときだけ。
5209        // 空・無い・`<form>` でない・別の木にある場合は form owner なし)。無ければ最も近い祖先の `<form>`。
5210        if let Some(form_id) = self.get_attr(idx, "form") {
5211            if form_id.is_empty() {
5212                return None;
5213            }
5214            let found = if self.is_attached(idx) {
5215                self.get_element_by_id(&form_id)
5216            } else {
5217                let mut root = idx;
5218                while let Some(p) = self.nodes.get(root).and_then(|n| n.parent) {
5219                    root = p;
5220                }
5221                if self.nodes.get(root).is_some_and(|n| !n.is_text && n.id == form_id) {
5222                    Some(root)
5223                } else {
5224                    self.descendants_by_tag_name(root, "*")
5225                        .into_iter()
5226                        .find(|&d| self.nodes.get(d).is_some_and(|n| !n.is_text && n.id == form_id))
5227                }
5228            };
5229            return found.filter(|&fi| self.nodes.get(fi).map(|n| n.tag == "form").unwrap_or(false));
5230        }
5231        self.closest_tag(idx, "form")
5232    }
5233
5234    /// `<form id="f1">`に属する`tags`に含まれるタグの全フォームコントロールを
5235    /// 収集する(form owner が当該フォームのもの。子孫でも `form="他の id"` で別のフォームに属するものは除く。
5236    /// 子孫でなくても `form="f1"` で関連付けられたものは含む)。
5237    /// `checkValidity()`/`FormData`収集/`form.elements`が使う
5238    /// (呼び出し側ごとに対象タグが異なる: `checkValidity`/`FormData`は
5239    /// `input`/`select`/`textarea`のみ、`form.elements`はそれに`button`も含む)。
5240    pub fn form_associated_controls(&self, form_idx: usize, tags: &[&str]) -> Vec<usize> {
5241        let mut out: Vec<usize> = self
5242            .descendants_by_tags(form_idx, tags)
5243            .into_iter()
5244            .filter(|&c| !self.has_attr(c, "form") || self.associated_form(c) == Some(form_idx))
5245            .collect();
5246        let form_attached = self.is_attached(form_idx);
5247        if let Some(form_id) = self.get_attr(form_idx, "id") {
5248            if !form_id.is_empty() {
5249                for (i, n) in self.nodes.iter().enumerate() {
5250                    if n.is_text || out.contains(&i) {
5251                        continue;
5252                    }
5253                    if form_attached && !self.is_attached(i) {
5254                        continue;
5255                    }
5256                    if !tags.contains(&n.tag.as_str()) {
5257                        continue;
5258                    }
5259                    if n.attrs.get("form").map(|v| v == &form_id).unwrap_or(false) && self.associated_form(i) == Some(form_idx) {
5260                        out.push(i);
5261                    }
5262                }
5263            }
5264        }
5265        out
5266    }
5267
5268    /// ドキュメント順で最初の指定タグ要素。
5269    pub fn first_by_tag(&self, tag: &str) -> Option<usize> {
5270        (0..self.nodes.len())
5271            .find(|&i| !self.nodes[i].is_text && self.nodes[i].tag == tag && self.is_attached(i))
5272    }
5273
5274    /// 子のうち要素ノードの index 一覧(テキスト・コメント・PI・DOCTYPE 等は除外)。
5275    pub fn element_children(&self, idx: usize) -> Vec<usize> {
5276        self.nodes
5277            .get(idx)
5278            .map(|n| {
5279                n.children
5280                    .iter()
5281                    .copied()
5282                    .filter(|c| self.nodes.get(*c).map(|cn| !cn.is_text && !cn.tag.starts_with('#')).unwrap_or(false))
5283                    .collect()
5284            })
5285            .unwrap_or_default()
5286    }
5287
5288    /// `root` 以下(自身は含まない)の子孫のうち、tag が `tags` のいずれかに一致するものを
5289    /// 文書順で収集する。フォーム配下の入力欄列挙(バリデーション)に使用。
5290    /// `element.getElementsByTagName(tag)` 用の子孫走査。`tag` が `"*"` なら全要素。
5291    ///
5292    /// # なぜ文書全体の検索を使わないか
5293    ///
5294    /// `query_all` は `is_attached` で**文書に繋がっていないノードを除外**する。
5295    /// 仕様では `getElementsByTagName` は**文書への接続に関係なく**自分の子孫を
5296    /// 返すので、切り離した要素(`createElement` した直後など)では結果が
5297    /// 空になってしまう。
5298    ///
5299    /// jQuery 1.8.2 の機能検出はまさにこれをやる:
5300    /// 切り離した `<div>` に `innerHTML` を入れ、`getElementsByTagName("a")[0]`
5301    /// の `style` を触る。空が返ると `undefined` の `style` を読んで落ち、
5302    /// **jQuery 全体が初期化できなくなっていた**。
5303    ///
5304    /// なお `is_attached` は根(索引 0)まで遡る実装のため、**空の DOM では
5305    /// 最初に作った要素自身が索引 0 になり偶然「接続済み」になる**。
5306    /// 単体試験を空のランタイムで書くとこの不具合を再現できない
5307    /// (実際に 5 回取り逃がした)。試験は実ページの DOM で確かめること。
5308    pub fn descendants_by_tag_name(&self, root: usize, tag: &str) -> Vec<usize> {
5309        let want_all = tag == "*";
5310        let lower = tag.to_ascii_lowercase();
5311        let mut out = Vec::new();
5312        let mut stack: Vec<usize> = self.element_children(root).into_iter().rev().collect();
5313        while let Some(idx) = stack.pop() {
5314            if let Some(n) = self.nodes.get(idx) {
5315                // 名前空間つきで作った要素(`createElementNS`。`_qname` に修飾名が残る)は、修飾名で照合する
5316                // (HTML 名前空間なら小文字どうし、それ以外は完全一致。DOM Standard「getElementsByTagName」)。
5317                let matched = match n.attrs.get("_qname") {
5318                    Some(q) => {
5319                        if n.attrs.get("_ns").is_none_or(|v| v == "http://www.w3.org/1999/xhtml") {
5320                            *q == lower
5321                        } else {
5322                            q == tag
5323                        }
5324                    }
5325                    None => n.tag.eq_ignore_ascii_case(&lower),
5326                };
5327                if !n.is_text && (want_all || matched) {
5328                    out.push(idx);
5329                }
5330                for &c in n.children.iter().rev() {
5331                    if self.nodes.get(c).map(|cn| !cn.is_text).unwrap_or(false) {
5332                        stack.push(c);
5333                    }
5334                }
5335            }
5336        }
5337        out
5338    }
5339
5340    pub fn descendants_by_tags(&self, root: usize, tags: &[&str]) -> Vec<usize> {
5341        let mut out = Vec::new();
5342        let mut stack: Vec<usize> = self.element_children(root).into_iter().rev().collect();
5343        while let Some(idx) = stack.pop() {
5344            if let Some(n) = self.nodes.get(idx) {
5345                if !n.is_text && tags.iter().any(|t| n.tag == *t) {
5346                    out.push(idx);
5347                }
5348                for &c in n.children.iter().rev() {
5349                    if self.nodes.get(c).map(|cn| !cn.is_text).unwrap_or(false) {
5350                        stack.push(c);
5351                    }
5352                }
5353            }
5354        }
5355        out
5356    }
5357
5358    /// `<fieldset disabled>`の子孫コントロールは、自身に`disabled`属性が無くても
5359    /// 暗黙に無効化される(HTML5仕様の「fieldset disabling」)。以前は要素自身の
5360    /// `disabled`属性の有無しか見ておらず、`<fieldset disabled>`配下の`<input>`は
5361    /// `.disabled`が常に`false`、制約バリデーションも無効化されずに常に対象内の
5362    /// ままになっていた。祖先を`parent`で遡り`<fieldset disabled>`が1つでも
5363    /// あれば無効とみなす(`<fieldset>`の最初の子`<legend>`直下のコントロールは
5364    /// 無効化対象外という仕様上の例外は、この処理系のフォーム系テストでは実用上
5365    /// ほぼ現れないため今回は簡略化して見送る)。
5366    pub fn is_disabled(&self, idx: usize) -> bool {
5367        let n = match self.nodes.get(idx) {
5368            Some(n) => n,
5369            None => return false,
5370        };
5371        if n.attrs.contains_key("disabled") {
5372            return true;
5373        }
5374        let mut cur = n.parent;
5375        while let Some(i) = cur {
5376            let anc = match self.nodes.get(i) {
5377                Some(a) => a,
5378                None => break,
5379            };
5380            if anc.tag == "fieldset" && anc.attrs.contains_key("disabled") {
5381                return true;
5382            }
5383            cur = anc.parent;
5384        }
5385        false
5386    }
5387
5388    // ===== 入力欄の値と制約検証(規則の本体は `form_value.rs`。2026-11-30)=====
5389
5390    /// `<input>` の type 状態。
5391    pub fn input_kind(&self, idx: usize) -> crate::os_lib::web_apis::form_value::Kind {
5392        crate::os_lib::web_apis::form_value::kind_of(
5393            self.nodes.get(idx).and_then(|n| n.attrs.get("type")).map(|s| s.as_str()),
5394        )
5395    }
5396
5397    /// `<input>` の値(IDL の `value`)。モードに従い、`value` モードの種類は値のサニタイズを通す
5398    /// (内部の値は `_live_value`、無ければ `value` 属性)。属性(`min`/`max`/`step`)の変更や `type` の変更の後も、
5399    /// 取得の度にサニタイズし直すので、`type` を切り替えた直後の値も仕様どおりになる。
5400    pub fn input_value(&self, idx: usize) -> String {
5401        use crate::os_lib::web_apis::form_value::{mode_of, sanitize, Attrs, Mode};
5402        let Some(n) = self.nodes.get(idx) else { return String::new() };
5403        let k = self.input_kind(idx);
5404        match mode_of(k) {
5405            Mode::Value => {
5406                let raw = n
5407                    .attrs
5408                    .get("_live_value")
5409                    .or_else(|| n.attrs.get("value"))
5410                    .map(|s| s.as_str())
5411                    .unwrap_or("");
5412                let at = Attrs {
5413                    min: n.attrs.get("min").map(|s| s.as_str()),
5414                    max: n.attrs.get("max").map(|s| s.as_str()),
5415                    step: n.attrs.get("step").map(|s| s.as_str()),
5416                    multiple: n.attrs.contains_key("multiple"),
5417                };
5418                sanitize(k, raw, &at)
5419            }
5420            Mode::Default => n.attrs.get("value").cloned().unwrap_or_default(),
5421            Mode::DefaultOn => n.attrs.get("value").cloned().unwrap_or_else(|| String::from("on")),
5422            Mode::Filename => String::new(),
5423        }
5424    }
5425
5426    /// `<input>` に値を代入する(`value` モードはサニタイズして内部の値へ、`default`/`default/on` は `value` 属性へ)。
5427    /// `file` は空文字列のときだけ受け付ける(本来は `InvalidStateError`。代入のフックは例外を返せない)。
5428    pub fn set_input_value(&mut self, idx: usize, v: &str) {
5429        use crate::os_lib::web_apis::form_value::{mode_of, sanitize, Attrs, Mode};
5430        let k = self.input_kind(idx);
5431        match mode_of(k) {
5432            Mode::Value => {
5433                let s = {
5434                    let Some(n) = self.nodes.get(idx) else { return };
5435                    let at = Attrs {
5436                        min: n.attrs.get("min").map(|s| s.as_str()),
5437                        max: n.attrs.get("max").map(|s| s.as_str()),
5438                        step: n.attrs.get("step").map(|s| s.as_str()),
5439                        multiple: n.attrs.contains_key("multiple"),
5440                    };
5441                    sanitize(k, v, &at)
5442                };
5443                self.set_attr(idx, "_live_value", &s);
5444            }
5445            Mode::Default | Mode::DefaultOn => self.set_attr(idx, "value", v),
5446            Mode::Filename => {}
5447        }
5448    }
5449
5450    /// `type` 属性が変わったときの値の引き継ぎ(§4.10.5.4「When the type attribute changes state」)。
5451    /// `old` は変更前の type 属性の値(無ければ `None`)。呼び出しは `set_attr`/`remove_attr` から(`type` を持つ `input` のみ)。
5452    pub fn input_type_changed(&mut self, idx: usize, old: Option<&str>) {
5453        use crate::os_lib::web_apis::form_value::{kind_of, mode_of, Mode};
5454        let ok = kind_of(old);
5455        let nk = self.input_kind(idx);
5456        if ok == nk {
5457            return;
5458        }
5459        let (om, nm) = (mode_of(ok), mode_of(nk));
5460        match (om, nm) {
5461            (Mode::Value, Mode::Default) | (Mode::Value, Mode::DefaultOn) => {
5462                // 旧モードの値(旧 type のサニタイズ後)を `value` 属性へ。
5463                let n = match self.nodes.get_mut(idx) {
5464                    Some(n) => n,
5465                    None => return,
5466                };
5467                let live = n.attrs.get("_live_value").cloned();
5468                if let Some(v) = live {
5469                    // 旧 type で値を取り直す(`type` はもう新しい値なので、旧 type を一時的に差し戻して評価する)。
5470                    let cur_type = n.attrs.get("type").cloned();
5471                    match old {
5472                        Some(o) => {
5473                            n.attrs.insert(String::from("type"), o.to_string());
5474                        }
5475                        None => {
5476                            n.attrs.remove("type");
5477                        }
5478                    }
5479                    let _ = v;
5480                    let val = self.input_value(idx);
5481                    if let Some(n) = self.nodes.get_mut(idx) {
5482                        match cur_type {
5483                            Some(c) => {
5484                                n.attrs.insert(String::from("type"), c);
5485                            }
5486                            None => {
5487                                n.attrs.remove("type");
5488                            }
5489                        }
5490                        // 値が空でなければ `value` 属性へ(空なら触らない。default/on の既定値 "on" が見えるように)。
5491                        if !val.is_empty() {
5492                            n.attrs.insert(String::from("value"), val);
5493                        }
5494                        n.attrs.remove("_live_value");
5495                    }
5496                }
5497            }
5498            (Mode::Default, Mode::Value) | (Mode::DefaultOn, Mode::Value) => {
5499                // `value` 属性があればそれが内部の値になる(dirty)。無ければ空。
5500                if let Some(n) = self.nodes.get_mut(idx) {
5501                    let v = n.attrs.get("value").cloned().unwrap_or_default();
5502                    n.attrs.insert(String::from("_live_value"), v);
5503                }
5504            }
5505            (Mode::Filename, Mode::Value) => {
5506                if let Some(n) = self.nodes.get_mut(idx) {
5507                    n.attrs.insert(String::from("_live_value"), String::new());
5508                }
5509            }
5510            (Mode::Value, Mode::Filename) => {
5511                if let Some(n) = self.nodes.get_mut(idx) {
5512                    n.attrs.remove("_live_value");
5513                }
5514            }
5515            (Mode::Value, Mode::Value) => {
5516                // 旧 type のサニタイズ後の値を新 type のサニタイズへ通す(取得時に行うので、ここでは内部の値を確定させる)。
5517                if self.nodes.get(idx).is_some_and(|n| n.attrs.contains_key("_live_value")) {
5518                    let cur_type = self.nodes.get(idx).and_then(|n| n.attrs.get("type").cloned());
5519                    if let Some(n) = self.nodes.get_mut(idx) {
5520                        match old {
5521                            Some(o) => {
5522                                n.attrs.insert(String::from("type"), o.to_string());
5523                            }
5524                            None => {
5525                                n.attrs.remove("type");
5526                            }
5527                        }
5528                    }
5529                    let val = self.input_value(idx);
5530                    if let Some(n) = self.nodes.get_mut(idx) {
5531                        match cur_type {
5532                            Some(c) => {
5533                                n.attrs.insert(String::from("type"), c);
5534                            }
5535                            None => {
5536                                n.attrs.remove("type");
5537                            }
5538                        }
5539                        n.attrs.insert(String::from("_live_value"), val);
5540                    }
5541                }
5542            }
5543            _ => {}
5544        }
5545    }
5546
5547    /// 制約検証の対象から外れている(barred)か、そもそも対象候補でない要素か。
5548    /// 対象候補: `button`(type が submit)・`input`(hidden・reset・button 以外)・`select`・`textarea`。
5549    /// 外れる条件: 無効(`disabled`・`<fieldset disabled>` の子孫)・`readonly`(適用される種類の input と textarea)・
5550    /// 祖先に `<datalist>`。
5551    pub fn barred_from_validation(&self, idx: usize) -> bool {
5552        use crate::os_lib::web_apis::form_value::Kind;
5553        let Some(n) = self.nodes.get(idx) else { return true };
5554        if n.is_text {
5555            return true;
5556        }
5557        match n.tag.as_str() {
5558            "input" => {
5559                let k = self.input_kind(idx);
5560                // readonly は(属性が適用されない種類でも)指定されていれば対象外にする(WPT willValidate)。
5561                if matches!(k, Kind::Hidden | Kind::Reset | Kind::Button) || n.attrs.contains_key("readonly") {
5562                    return true;
5563                }
5564            }
5565            "button" => {
5566                if let Some(t) = n.attrs.get("type") {
5567                    if t.eq_ignore_ascii_case("reset") || t.eq_ignore_ascii_case("button") {
5568                        return true;
5569                    }
5570                }
5571            }
5572            "textarea" => {
5573                if n.attrs.contains_key("readonly") {
5574                    return true;
5575                }
5576            }
5577            "select" => {}
5578            _ => return true,
5579        }
5580        if self.is_disabled(idx) {
5581            return true;
5582        }
5583        let mut cur = n.parent;
5584        while let Some(i) = cur {
5585            match self.nodes.get(i) {
5586                Some(a) => {
5587                    if a.tag == "datalist" {
5588                        return true;
5589                    }
5590                    cur = a.parent;
5591                }
5592                None => break,
5593            }
5594        }
5595        false
5596    }
5597
5598    /// `ValidityState` の各フラグ(§4.10.20.2)。無効・readonly などで対象外の要素でも、フラグ自体は計算する
5599    /// (`validity.customError` などは対象外でも読める。対象外のとき `checkValidity()` が `true` を返すのは呼び出し側)。
5600    /// `_value` は互換のための引数(値は要素から取り直す)。
5601    pub fn validity_flags(&self, idx: usize, _value: &str) -> ValidityFlags {
5602        use crate::os_lib::web_apis::form_value as fv;
5603        use crate::os_lib::web_apis::form_value::Kind;
5604        let mut f = ValidityFlags::default();
5605        let n = match self.nodes.get(idx) {
5606            Some(n) if !n.is_text && matches!(n.tag.as_str(), "button" | "input" | "select" | "textarea") => n,
5607            _ => return f,
5608        };
5609        f.custom_error = n.attrs.get("_custom_validity").map(|s| !s.is_empty()).unwrap_or(false);
5610        let required = n.attrs.contains_key("required");
5611        let readonly = n.attrs.contains_key("readonly");
5612        let disabled = self.is_disabled(idx);
5613        match n.tag.as_str() {
5614            "button" => {}
5615            "select" => {
5616                if required {
5617                    f.value_missing = self.select_effective_value(idx).is_empty();
5618                }
5619            }
5620            "textarea" => {
5621                let v = self.effective_form_value(idx);
5622                f.value_missing = required && !readonly && !disabled && v.is_empty();
5623                // tooShort/tooLong はユーザーの編集で値が変わったときだけ(スクリプトで代入した値は対象外)。
5624                if !v.is_empty() && !n.attrs.contains_key("_live_value") {
5625                    let len = v.chars().count();
5626                    if let Some(ml) = n.attrs.get("minlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5627                        f.too_short = len < ml;
5628                    }
5629                    if let Some(ml) = n.attrs.get("maxlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5630                        f.too_long = len > ml;
5631                    }
5632                }
5633            }
5634            _ => {
5635                let k = self.input_kind(idx);
5636                let v = self.input_value(idx);
5637                let mutable = !disabled && !(readonly && fv::readonly_applies(k));
5638                if required && fv::required_applies(k) {
5639                    f.value_missing = match k {
5640                        Kind::Checkbox => !self.is_checked_node(idx),
5641                        Kind::Radio => {
5642                            // 同じ名前のグループのどれかが required で、どれも checked でない。
5643                            let group: alloc::vec::Vec<usize> = if n.attrs.get("name").map(|s| s.is_empty()).unwrap_or(true) {
5644                                alloc::vec![idx]
5645                            } else {
5646                                (0..self.nodes.len()).filter(|&i| self.same_radio_group(idx, i)).collect()
5647                            };
5648                            let any_required = group.iter().any(|&i| self.nodes[i].attrs.contains_key("required"));
5649                            any_required && !group.iter().any(|&i| self.is_checked_node(i))
5650                        }
5651                        Kind::File => true,
5652                        _ => mutable && v.is_empty(),
5653                    };
5654                }
5655                if !v.is_empty() {
5656                    if fv::text_constraints_apply(k) {
5657                        if !n.attrs.contains_key("_live_value") {
5658                            let len = v.chars().count();
5659                            if let Some(ml) = n.attrs.get("minlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5660                                f.too_short = len < ml;
5661                            }
5662                            if let Some(ml) = n.attrs.get("maxlength").and_then(|x| x.trim().parse::<usize>().ok()) {
5663                                f.too_long = len > ml;
5664                            }
5665                        }
5666                        match k {
5667                            Kind::Email => {
5668                                f.type_mismatch = if n.attrs.contains_key("multiple") {
5669                                    !v.split(',').all(|p| fv::is_valid_email(p.trim()))
5670                                } else {
5671                                    !fv::is_valid_email(&v)
5672                                };
5673                            }
5674                            Kind::Url => f.type_mismatch = !fv::looks_like_absolute_url(&v),
5675                            _ => {}
5676                        }
5677                        if let Some(pat) = n.attrs.get("pattern") {
5678                            if !pat.is_empty() {
5679                                f.pattern_mismatch = if k == Kind::Email && n.attrs.contains_key("multiple") {
5680                                    !v.split(',').all(|p| Self::pattern_matches(pat, p.trim()))
5681                                } else {
5682                                    !Self::pattern_matches(pat, &v)
5683                                };
5684                            }
5685                        }
5686                    }
5687                    if fv::has_number_semantics(k) {
5688                        if let Some(num) = fv::string_to_number(k, &v) {
5689                            let min = n.attrs.get("min").and_then(|m| fv::string_to_number(k, m));
5690                            let max = n.attrs.get("max").and_then(|m| fv::string_to_number(k, m));
5691                            let reversed = k == Kind::Time && matches!((min, max), (Some(a), Some(b)) if b < a);
5692                            if reversed {
5693                                if let (Some(a), Some(b)) = (min, max) {
5694                                    if num > b && num < a {
5695                                        f.range_underflow = true;
5696                                        f.range_overflow = true;
5697                                    }
5698                                }
5699                            } else {
5700                                if let Some(a) = min {
5701                                    f.range_underflow = num < a;
5702                                }
5703                                if let Some(b) = max {
5704                                    f.range_overflow = num > b;
5705                                }
5706                            }
5707                            let at = fv::Attrs {
5708                                min: n.attrs.get("min").map(|s| s.as_str()),
5709                                max: n.attrs.get("max").map(|s| s.as_str()),
5710                                step: n.attrs.get("step").map(|s| s.as_str()),
5711                                multiple: false,
5712                            };
5713                            f.step_mismatch = fv::step_mismatch(k, num, &at, n.attrs.get("value").map(|s| s.as_str()));
5714                        }
5715                    }
5716                }
5717            }
5718        }
5719        f
5720    }
5721
5722    /// checkbox/radio の checked(`_live_checked` が優先、無ければ `checked` 属性)。
5723    fn is_checked_node(&self, idx: usize) -> bool {
5724        match self.nodes.get(idx) {
5725            Some(node) => match node.attrs.get("_live_checked") {
5726                Some(lc) => lc == "true",
5727                None => node.attrs.contains_key("checked"),
5728            },
5729            None => false,
5730        }
5731    }
5732
5733    /// 制約検証のメッセージ(違反が無い・対象外なら `None`)。フラグから決める(最初に見つかった違反)。
5734    pub fn validate_field(&self, idx: usize, _value: &str) -> Option<String> {
5735        if self.barred_from_validation(idx) {
5736            return None;
5737        }
5738        let n = self.nodes.get(idx)?;
5739        let f = self.validity_flags(idx, "");
5740        if f.custom_error {
5741            return n.attrs.get("_custom_validity").cloned();
5742        }
5743        let ty = if n.tag == "input" { crate::os_lib::web_apis::form_value::kind_name(self.input_kind(idx)) } else { "" };
5744        if f.value_missing {
5745            return Some(String::from(match ty {
5746                "checkbox" => "このフィールドをオンにしてください。",
5747                "radio" => "いずれかを選択してください。",
5748                _ => "このフィールドを入力してください。",
5749            }));
5750        }
5751        if f.too_short {
5752            let min = n.attrs.get("minlength").cloned().unwrap_or_default();
5753            let len = self.effective_form_value(idx).chars().count();
5754            return Some(alloc::format!("{}文字以上で入力してください(現在{}文字)。", min.trim(), len));
5755        }
5756        if f.too_long {
5757            let max = n.attrs.get("maxlength").cloned().unwrap_or_default();
5758            let len = self.effective_form_value(idx).chars().count();
5759            return Some(alloc::format!("{}文字以下で入力してください(現在{}文字)。", max.trim(), len));
5760        }
5761        if f.type_mismatch {
5762            return Some(String::from(match ty {
5763                "email" => "メールアドレスを入力してください。",
5764                _ => "URL を入力してください。",
5765            }));
5766        }
5767        if f.range_underflow {
5768            return Some(alloc::format!("{}以上の値を入力してください。", n.attrs.get("min").cloned().unwrap_or_default()));
5769        }
5770        if f.range_overflow {
5771            return Some(alloc::format!("{}以下の値を入力してください。", n.attrs.get("max").cloned().unwrap_or_default()));
5772        }
5773        if f.step_mismatch {
5774            return Some(String::from("有効な値を入力してください。"));
5775        }
5776        if f.bad_input {
5777            return Some(String::from("数値を入力してください。"));
5778        }
5779        if f.pattern_mismatch {
5780            return Some(String::from("要求された形式で入力してください。"));
5781        }
5782        None
5783    }
5784
5785    /// `<input pattern="...">`(HTML Living Standard の制約検証。仕様上は値全体を
5786    /// `^(?:pattern)$` として完全一致させる)が、以前はメタ文字を含む複雑なパターンを
5787    /// 「誤検知で送信を妨げないため」全て無条件で通過させる簡易近似だった。この
5788    /// エンジンには既に本物の正規表現実装(`js::regex::Regex`)があるため、それを
5789    /// そのまま使えば近似ではなく正しく検証できる(`\d`/`[...]`/`+`/`.*` 等、
5790    /// HTML pattern で使われる構文は通常の JS RegExp と同じ)。
5791    fn pattern_matches(pat: &str, val: &str) -> bool {
5792        // 仕様は `v` フラグ付きの `^(?:pattern)$`。パターンに構文の誤りがあれば無視する(一致とみなす)。
5793        if crate::os_lib::ecma::regex_syntax::pattern_error(pat, "v").is_some() {
5794            return true;
5795        }
5796        let anchored = format!("^(?:{})$", pat);
5797        let re = crate::os_lib::ecma::regex::Regex::new(&anchored, "v");
5798        let chars: alloc::vec::Vec<char> = val.chars().collect();
5799        re.find_at(&chars, 0).is_some()
5800    }
5801
5802    /// 既定の並び(id・class を先頭に、続いて名前順)の属性名。
5803    fn attr_names_default(&self, idx: usize) -> Vec<String> {
5804        let mut out = Vec::new();
5805        if let Some(n) = self.nodes.get(idx) {
5806            if !n.id.is_empty() || n.attrs.contains_key("id") {
5807                out.push(String::from("id"));
5808            }
5809            if !n.classes.is_empty() || n.attrs.contains_key("class") {
5810                out.push(String::from("class"));
5811            }
5812            // id/class は専用フィールドで既に出力済みなので attrs 側では除外。
5813            // `_` 始まりの内部専用属性(`_content_frag` 等)も
5814            // `serialize_node_html` と同じ理由で除外する(以前は
5815            // `getAttributeNames()`/`hasAttributes()` にそのまま漏れていた)。
5816            for k in n.attrs.keys() {
5817                if k != "id" && k != "class" && !k.starts_with('_') && !k.starts_with('#') {
5818                    out.push(k.clone());
5819                }
5820            }
5821        }
5822        out
5823    }
5824
5825    /// 属性名の一覧(挿入順。順序の記録が無いノードは id/class を先頭にした名前順 + `ns_attrs`)。
5826    pub fn attr_names(&self, idx: usize) -> Vec<String> {
5827        if let Some(ord) = self.attr_ns_order.get(&idx) {
5828            return ord.iter().map(|(_, qn)| qn.clone()).collect();
5829        }
5830        let mut out = self.attr_names_default(idx);
5831        if !self.attr_order.is_empty() {
5832            if let Some(order) = self.attr_order.get(&idx) {
5833                let mut ordered: Vec<String> = Vec::with_capacity(out.len());
5834                for k in order {
5835                    if let Some(p) = out.iter().position(|x| x == k) {
5836                        ordered.push(out.remove(p));
5837                    }
5838                }
5839                ordered.extend(out);
5840                out = ordered;
5841            }
5842        }
5843        if let Some(ns_list) = self.ns_attrs.get(&idx) {
5844            for (_, qn, _) in ns_list {
5845                out.push(qn.clone());
5846            }
5847        }
5848        out
5849    }
5850
5851    /// 属性 `(ns, qname)` の全一覧(挿入順)。
5852    pub fn attr_entries(&self, idx: usize) -> Vec<(Option<String>, String)> {
5853        if let Some(ord) = self.attr_ns_order.get(&idx) {
5854            return ord.clone();
5855        }
5856        let mut out: Vec<(Option<String>, String)> = self
5857            .attr_names_ordered_plain(idx)
5858            .into_iter()
5859            .map(|q| (None, q))
5860            .collect();
5861        if let Some(ns_list) = self.ns_attrs.get(&idx) {
5862            for (ns, qn, _) in ns_list {
5863                out.push((Some(ns.clone()), qn.clone()));
5864            }
5865        }
5866        out
5867    }
5868
5869    fn attr_names_ordered_plain(&self, idx: usize) -> Vec<String> {
5870        let mut out = self.attr_names_default(idx);
5871        if !self.attr_order.is_empty() {
5872            if let Some(order) = self.attr_order.get(&idx) {
5873                let mut ordered: Vec<String> = Vec::with_capacity(out.len());
5874                for k in order {
5875                    if let Some(p) = out.iter().position(|x| x == k) {
5876                        ordered.push(out.remove(p));
5877                    }
5878                }
5879                ordered.extend(out);
5880                out = ordered;
5881            }
5882        }
5883        out
5884    }
5885
5886    fn ensure_attr_ns_order(&mut self, idx: usize) {
5887        if self.attr_ns_order.contains_key(&idx) {
5888            return;
5889        }
5890        let mut entries: Vec<(Option<String>, String)> = self
5891            .attr_names_ordered_plain(idx)
5892            .into_iter()
5893            .map(|q| (None, q))
5894            .collect();
5895        if let Some(ns_list) = self.ns_attrs.get(&idx) {
5896            for (ns, qn, _) in ns_list {
5897                entries.push((Some(ns.clone()), qn.clone()));
5898            }
5899        }
5900        self.attr_ns_order.insert(idx, entries);
5901    }
5902
5903    /// インデックス `pos` 番目の属性に対応する `Attr` ノード(同名異名前空間でも正確)。
5904    pub fn attr_node_at(&mut self, elem: usize, pos: usize) -> Option<usize> {
5905        let (ns, qn) = self.attr_entries(elem).get(pos)?.clone();
5906        self.attr_node_for_ns(elem, ns.as_deref(), &qn)
5907    }
5908
5909    /// 属性 `old` を `new` で置き換えた(位置は変えない)。`before` は置き換え前の属性名の並び。
5910    pub fn attr_order_replace(&mut self, idx: usize, before: Vec<String>, old: &str, new: &str) {
5911        let mut want: Vec<String> = Vec::with_capacity(before.len());
5912        for k in before {
5913            if k == old {
5914                want.push(new.to_string());
5915            } else if k != new {
5916                want.push(k);
5917            }
5918        }
5919        if self.attr_names(idx) != want {
5920            self.attr_order.insert(idx, want);
5921        }
5922    }
5923
5924    /// 名前空間付きを含めた属性置き換え時に元の挿入順を保持する。
5925    pub fn attr_ns_order_replace(
5926        &mut self,
5927        idx: usize,
5928        before: Vec<(Option<String>, String)>,
5929        old_ns: Option<&str>,
5930        old_q: &str,
5931        new_ns: Option<&str>,
5932        new_q: &str,
5933    ) {
5934        if self.attr_ns_order.contains_key(&idx)
5935            || old_ns.is_some()
5936            || new_ns.is_some()
5937            || before.iter().any(|(ns, _)| ns.is_some())
5938        {
5939            let mut want: Vec<(Option<String>, String)> = Vec::with_capacity(before.len());
5940            for (ns, q) in before {
5941                if ns.as_deref() == old_ns && q == old_q {
5942                    want.push((new_ns.map(String::from), String::from(new_q)));
5943                } else if !(ns.as_deref() == new_ns && q == new_q) {
5944                    want.push((ns, q));
5945                }
5946            }
5947            self.attr_ns_order.insert(idx, want);
5948            return;
5949        }
5950        let plain_before: Vec<String> = before.into_iter().map(|(_, q)| q).collect();
5951        self.attr_order_replace(idx, plain_before, old_q, new_q);
5952    }
5953
5954    /// 新しい属性 `name` を足す直前に呼ぶ。名前順の既定の並びと食い違うときだけ挿入順を記録する。
5955    fn attr_order_push(&mut self, idx: usize, name: &str) {
5956        if name.starts_with('_') {
5957            return;
5958        }
5959        if let Some(o) = self.attr_order.get_mut(&idx) {
5960            o.retain(|k| k != name);
5961            o.push(name.to_string());
5962            return;
5963        }
5964        let base = self.attr_names_default(idx);
5965        let rank = |k: &str| -> (u8, String) {
5966            match k {
5967                "id" => (0, String::new()),
5968                "class" => (1, String::new()),
5969                _ => (2, k.to_string()),
5970            }
5971        };
5972        if let Some(last) = base.last() {
5973            if rank(name) < rank(last) {
5974                let mut o = base;
5975                o.push(name.to_string());
5976                self.attr_order.insert(idx, o);
5977            }
5978        }
5979    }
5980
5981    pub fn add_listener(&mut self, node: usize, event: &str, func: Value) {
5982        self.add_listener_opts(node, event, func, false, false);
5983    }
5984
5985    /// capture / once オプション付きでリスナを登録する。重複(同一 node+event+func+capture)
5986    /// は DOM 仕様どおり無視する。戻り値は発番した ID。
5987    pub fn add_listener_opts(
5988        &mut self,
5989        node: usize,
5990        event: &str,
5991        func: Value,
5992        capture: bool,
5993        once: bool,
5994    ) -> u64 {
5995        self.add_listener_opts_signal(node, event, func, capture, once, None)
5996    }
5997
5998    /// `add_listener_opts` の `{signal}` 対応版。`signal` が既に abort 済みなら
5999    /// 仕様どおり登録自体を行わない。
6000    pub fn add_listener_opts_signal(
6001        &mut self,
6002        node: usize,
6003        event: &str,
6004        func: Value,
6005        capture: bool,
6006        once: bool,
6007        signal: Option<Value>,
6008    ) -> u64 {
6009        self.add_listener_full(node, event, func, capture, once, false, signal)
6010    }
6011
6012    /// `capture` / `once` / `passive` / `signal` 全オプション対応のリスナ登録。
6013    #[allow(clippy::too_many_arguments)]
6014    pub fn add_listener_full(
6015        &mut self,
6016        node: usize,
6017        event: &str,
6018        func: Value,
6019        capture: bool,
6020        once: bool,
6021        passive: bool,
6022        signal: Option<Value>,
6023    ) -> u64 {
6024        if signal.as_ref().is_some_and(is_signal_aborted) {
6025            return 0;
6026        }
6027        // 同一 (node, event, func, capture) の重複登録は無視(DOM 仕様)。
6028        if self.listeners.iter().any(|l| {
6029            l.node == node && l.event == event && l.capture == capture && l.func.same_ref(&func)
6030        }) {
6031            return 0;
6032        }
6033        let id = self.next_listener_id;
6034        self.next_listener_id += 1;
6035        self.listeners.push(Listener {
6036            node,
6037            event: event.to_string(),
6038            func,
6039            capture,
6040            once,
6041            passive,
6042            id,
6043            signal,
6044        });
6045        id
6046    }
6047
6048    /// removeEventListener: 同一 (node, event, func, capture) のリスナを削除する。
6049    pub fn remove_listener(&mut self, node: usize, event: &str, func: &Value, capture: bool) {
6050        self.listeners.retain(|l| {
6051            !(l.node == node && l.event == event && l.capture == capture && l.func.same_ref(func))
6052        });
6053    }
6054
6055    /// ID 指定でリスナを削除する(once 発火後の自動削除に使う)。
6056    pub fn remove_listener_by_id(&mut self, id: u64) {
6057        self.listeners.retain(|l| l.id != id);
6058    }
6059
6060    pub fn has_listener_by_id(&self, id: u64) -> bool {
6061        self.listeners.iter().any(|l| l.id == id)
6062    }
6063
6064    /// 指定イベント型のリスナがページ内に1つでも登録されているか(ホバー判定の省略用)。
6065    pub fn has_listener(&self, event: &str) -> bool {
6066        self.listeners.iter().any(|l| l.event == event)
6067    }
6068
6069    /// 指定ノードに登録された指定イベントのリスナ関数を返す(呼び出しは呼び元で)。
6070    /// バブリングフェーズ用(capture=false のみ)。`{signal}` が abort 済みの
6071    /// リスナは除外する。
6072    pub fn listeners_for(&self, node: usize, event: &str) -> Vec<Value> {
6073        self.listeners
6074            .iter()
6075            .filter(|l| l.node == node && l.event == event && !l.capture && !is_listener_aborted(l))
6076            .map(|l| l.func.clone())
6077            .collect()
6078    }
6079
6080    /// 指定ノード・イベントのリスナを `(func, once, passive, id, signal)` 付きで返す。
6081    /// `want_capture` でキャプチャ/バブルのどちらのフェーズかを絞り込む。
6082    /// `{signal}` が abort 済みのリスナは除外する。
6083    pub fn listeners_phase(
6084        &self,
6085        node: usize,
6086        event: &str,
6087        want_capture: bool,
6088    ) -> Vec<(Value, bool, bool, u64, Option<Value>)> {
6089        self.listeners
6090            .iter()
6091            .filter(|l| l.node == node && l.event == event && l.capture == want_capture && !is_listener_aborted(l))
6092            .map(|l| (l.func.clone(), l.once, l.passive, l.id, l.signal.clone()))
6093            .collect()
6094    }
6095
6096    /// 指定ノードに当該イベントのリスナ(フェーズ問わず)が在るか。
6097    pub fn has_listener_on(&self, node: usize, event: &str) -> bool {
6098        self.listeners
6099            .iter()
6100            .any(|l| l.node == node && l.event == event)
6101    }
6102
6103    /// 再パースした DOM 木へ JS の変更を焼き戻す。木はビルド時と同一ドキュメント順前提。
6104    pub fn apply_overrides(&self, root: &mut Node) {
6105        let mut counter = 0usize;
6106        self.apply_node(root, &mut counter);
6107    }
6108    fn apply_node(&self, node: &mut Node, counter: &mut usize) {
6109        let idx = *counter;
6110        *counter += 1;
6111        if let Some(dn) = self.nodes.get(idx) {
6112            match &mut node.node_type {
6113                NodeType::Text(t) => {
6114                    if let Some(ov) = &dn.text_override {
6115                        *t = ov.clone();
6116                    }
6117                }
6118                NodeType::Element {
6119                    attributes,
6120                    classes,
6121                    ..
6122                } => {
6123                    if dn.classes_dirty {
6124                        *classes = dn.classes.clone();
6125                        attributes.insert("class".to_string(), dn.classes.join(" "));
6126                    }
6127                    if dn.style_dirty {
6128                        attributes.insert("style".to_string(), serialize_inline_style(&dn.style));
6129                    }
6130                }
6131            }
6132        }
6133        for c in &mut node.children {
6134            self.apply_node(c, counter);
6135        }
6136    }
6137}
6138
6139/// `outerHTML` 直列化用の HTML エスケープ(属性値。WHATWG §13.3: `&`・U+00A0・`"`・`<`・`>`)。
6140fn html_escape_attr(s: &str) -> String {
6141    let mut o = String::new();
6142    crate::os_lib::dom::serializer::escape_attr_value(s, Some('"'), &mut o);
6143    o
6144}
6145
6146/// 生の宣言値末尾の `!important`(大小文字・空白ゆれ許容)を切り離す。
6147/// `(値本体, important か)` を返す。CSS カスケード側(`css.rs`)の
6148/// `!important` パーサとは別実装だが、`element.style.getPropertyValue`/
6149/// `.getPropertyPriority`(丸ごと未対応だった。2026-07-16 発見)専用の
6150/// 軽量版。
6151fn strip_style_priority(raw: &str) -> (&str, bool) {
6152    let trimmed = raw.trim_end();
6153    if let Some(pos) = trimmed.to_ascii_lowercase().rfind("!important") {
6154        if trimmed.get(pos..).unwrap_or("").eq_ignore_ascii_case("!important") {
6155            let before = trimmed.get(..pos).unwrap_or("").trim_end();
6156            return (before, true);
6157        }
6158    }
6159    (raw, false)
6160}
6161
6162/// `color: red; font-size: 12px` → マップ。
6163pub(crate) fn parse_inline_style(s: &str) -> BTreeMap<String, String> {
6164    let mut m = BTreeMap::new();
6165    for decl in s.split(';') {
6166        let decl = decl.trim();
6167        if decl.is_empty() {
6168            continue;
6169        }
6170        if let Some(colon) = decl.find(':') {
6171            let k = decl.get(..colon).unwrap_or("").trim().to_lowercase();
6172            let v = decl.get(colon + 1..).unwrap_or("").trim().to_string();
6173            // 値が空の宣言は不正なので持たない(`style.cssText = "display: "` 等。カスタムプロパティは除く)。
6174            if !k.is_empty() && (!v.is_empty() || k.starts_with("--")) {
6175                m.insert(k, v);
6176            }
6177        }
6178    }
6179    m
6180}
6181
6182fn serialize_inline_style(m: &BTreeMap<String, String>) -> String {
6183    let mut parts = Vec::new();
6184    for (k, v) in m {
6185        parts.push(format!("{}: {}", k, v));
6186    }
6187    parts.join("; ")
6188}
6189
6190/// `backgroundColor` → `background-color`。既にケバブならそのまま。
6191fn css_prop_from_camel(prop: &str) -> String {
6192    if prop.contains('-') || !prop.chars().any(|c| c.is_ascii_uppercase()) {
6193        return prop.to_lowercase();
6194    }
6195    let mut out = String::new();
6196    for c in prop.chars() {
6197        if c.is_ascii_uppercase() {
6198            out.push('-');
6199            out.push(c.to_ascii_lowercase());
6200        } else {
6201            out.push(c);
6202        }
6203    }
6204    out
6205}
6206
6207/// カスタム要素の反応の契機。
6208#[derive(Debug, Clone, PartialEq)]
6209pub enum CeEvent {
6210    /// 監視対象の属性が変わった(要素, 属性名, 旧値, 新値)。
6211    Attr(usize, String, Option<String>, Option<String>),
6212    /// 部分木が挿入された(根の添字)。
6213    Inserted(usize),
6214    /// 接続された部分木が取り除かれた(根の添字)。
6215    Removed(usize),
6216    /// 複製で部分木が作られた(根の添字。未接続)。
6217    Created(usize),
6218}
6219
6220impl DomBridge {
6221    /// `root` を含む部分木の要素の添字(木順、シャドウ木を含む)。
6222    pub fn subtree_elements(&self, root: usize) -> Vec<usize> {
6223        let mut out = Vec::new();
6224        let mut stack = alloc::vec![root];
6225        while let Some(i) = stack.pop() {
6226            let Some(n) = self.nodes.get(i) else { continue };
6227            if n.is_text {
6228                continue;
6229            }
6230            out.push(i);
6231            // シャドウ木(ShadowRoot)の要素も探索・昇格対象に含める
6232            if let Some(shadow_desc) = self.shadow_tree.get_by_host(i) {
6233                stack.push(shadow_desc.root_node_idx);
6234            }
6235            for &c in n.children.iter().rev() {
6236                stack.push(c);
6237            }
6238        }
6239        out
6240    }
6241
6242    /// 文書ツリーに属しておらず、かつ JS からも参照されていない孤立ノード群を検出し、
6243    /// そのノードに紐づく listeners, expandos, node_accessors, node_protos 等の強参照を一掃する。
6244    ///
6245    /// 【2026-11-06】YouTube 等の SPA では、画面更新や自動再生(次動画への遷移)で大量の要素が
6246    /// 切り離されるが、`DomBridge` が強参照を持ち続けるため `cycle_gc` で回収されず
6247    /// 生存オブジェクトが 70 万個を超えてヒープが尽きていた(TODO A7)。
6248    /// このクリーンアップにより、死んだノード配下の JS オブジェクト・クロージャを循環 GC の対象へ引き渡す。
6249    pub fn clean_unreachable_nodes<F>(&mut self, is_node_referenced: F) -> usize
6250    where
6251        F: Fn(usize) -> bool,
6252    {
6253        if self.nodes.is_empty() {
6254            return 0;
6255        }
6256
6257        let total_nodes = self.nodes.len();
6258        let get_parent = |i: usize| -> Option<usize> {
6259            self.nodes.get(i).and_then(|n| n.parent)
6260        };
6261        // 【2026-11-19】木の辺は「子」と「シャドウ木の根」に加えて「`<template>` の `.content` のフラグメント」も要る。
6262        // フラグメントは親子ではなく属性 `_content_frag` の添字でだけ `<template>` につながる(`template_content`)。
6263        // これを辺に数えていなかったため、生きている `<template>` の中身(Polymer の `dom-if`・`dom-repeat` など)が
6264        // 孤立と見なされ、原型(`node_protos`)・expando が消えて `q.__render is not a function` になっていた(TODO Y)。
6265        let get_children = |i: usize| -> Vec<usize> {
6266            let Some(n) = self.nodes.get(i) else { return Vec::new() };
6267            crate::os_lib::ecma::gc_policy::children_with_links(
6268                &n.children,
6269                self.shadow_tree.get_by_host(i).map(|d| d.root_node_idx),
6270                crate::os_lib::ecma::gc_policy::parse_content_frag(n.attrs.get("_content_frag").map(|s| s.as_str())),
6271            )
6272        };
6273
6274        let mut reachable = crate::os_lib::ecma::gc_policy::find_reachable_dom_nodes(total_nodes, get_parent, get_children, is_node_referenced);
6275
6276        // 【2026-11-18】ShadyDOM の影の根(親の無い `#fragment`。JS の `host` プロパティで持ち主の要素につながる)は、
6277        // 持ち主の要素が生きている間は残す。持ち主は `__shady` 経由でしか根を持たず、JS の変数に根が直接
6278        // 残らないので、上の判定では孤立に見え、原型・`__shady`(論理の子の表)が消えて `querySelector` が
6279        // null になっていた(YouTube の `ytd-mini-guide-renderer` の `this.items` が null、TODO「Wiz の文脈エラー」)。
6280        loop {
6281            let mut add: Vec<usize> = Vec::new();
6282            for (&i, m) in self.expandos.iter() {
6283                if reachable.contains(&i) {
6284                    continue;
6285                }
6286                if let Some(Value::Object(o)) = m.get("host") {
6287                    if let Ok(b) = o.try_borrow() {
6288                        if let Some(h) = b.kind.dom_node() {
6289                            if reachable.contains(&h) {
6290                                add.push(i);
6291                            }
6292                        }
6293                    }
6294                }
6295                // 【2026-11-19】ShadyDOM の論理木(`__shady.parentNode`)が到達可能な親を指すノードも残す。
6296                // `<slot>` は分配のあと実の木から外れ(親が無くなり)、持ち主の論理の子の表にしか残らない。
6297                // 孤立と見て `__shady`(親・兄弟の記録)を消すと、`querySelector` の論理の走査が slot の次で
6298                // 途切れ、同じ親の後ろの兄弟(YouTube の masthead の `#logo`)が引けなくなっていた。
6299                if let Some(Value::Object(sh)) = m.get("__shady") {
6300                    if let Ok(sb) = sh.try_borrow() {
6301                        if let Some(Value::Object(po)) = sb.props.get("parentNode") {
6302                            if let Ok(pb) = po.try_borrow() {
6303                                if let Some(h) = pb.kind.dom_node() {
6304                                    if reachable.contains(&h) {
6305                                        add.push(i);
6306                                    }
6307                                }
6308                            }
6309                        }
6310                    }
6311                }
6312            }
6313            if add.is_empty() {
6314                break;
6315            }
6316            // 根だけでなく、その下の子孫も残す(影の根の中身が消えないように)。
6317            let mut stack = add;
6318            while let Some(i) = stack.pop() {
6319                if !reachable.insert(i) {
6320                    continue;
6321                }
6322                if let Some(n) = self.nodes.get(i) {
6323                    for &c in n.children.iter() {
6324                        if c < total_nodes && !reachable.contains(&c) {
6325                            stack.push(c);
6326                        }
6327                    }
6328                    // `<template>` の中身のフラグメントも残す(上の `get_children` と同じ辺)。
6329                    if let Some(f) = crate::os_lib::ecma::gc_policy::parse_content_frag(n.attrs.get("_content_frag").map(|s| s.as_str())) {
6330                        if f < total_nodes && !reachable.contains(&f) {
6331                            stack.push(f);
6332                        }
6333                    }
6334                }
6335            }
6336        }
6337
6338        // 3. 到達不能なノードのリソースを一掃
6339        let mut cleaned_nodes = 0;
6340        for i in 1..total_nodes {
6341            if reachable.contains(&i) {
6342                continue;
6343            }
6344            let had_expando = self.expandos.remove(&i).is_some();
6345            let had_accessor = self.node_accessors.remove(&i).is_some();
6346            let had_proto = self.node_protos.remove(&i).is_some();
6347            let had_rect = self.rects.remove(&i).is_some();
6348            let had_measured = self.measured.remove(&i).is_some();
6349            let had_border = self.border_widths.remove(&i).is_some();
6350            let had_style = self.computed_styles.remove(&i).is_some();
6351            let had_scroll = self.scroll_tops.remove(&i).is_some()
6352                || self.scroll_lefts.remove(&i).is_some()
6353                || self.scroll_heights.remove(&i).is_some()
6354                || self.scroll_widths.remove(&i).is_some();
6355
6356            if had_expando || had_accessor || had_proto || had_rect || had_measured || had_border || had_style || had_scroll {
6357                cleaned_nodes += 1;
6358            }
6359        }
6360
6361        // リスナも到達可能なノードだけに絞る
6362        let prev_listeners_len = self.listeners.len();
6363        self.listeners.retain(|l| reachable.contains(&l.node));
6364        let cleaned_listeners = prev_listeners_len.saturating_sub(self.listeners.len());
6365
6366        cleaned_nodes + cleaned_listeners
6367    }
6368}
6369
6370/// DOM ブリッジの組み立て(`build_from`・`to_dom_node`)の止める確かめ(`window_mgr::layout_poll`。2026-11-18、TODO R2 (b) ②)。
6371/// 64 回に 1 回 `kill_checkpoint` を呼ぶ(ウィンドウごと止めるならその中で終わる)。真ならこのタブだけ止める合図。
6372/// 呼ぶのは `parse_and_layout` の中(錠を持っていない。持っているのは DOM の `RefCell` の借用だけ)。ホストの試験では何もしない。
6373#[inline]
6374fn bridge_poll() -> bool {
6375    #[cfg(target_os = "none")]
6376    return crate::os_lib::platform::layout_poll();
6377    #[cfg(not(target_os = "none"))]
6378    false
6379}
6380
6381/// このタブだけ止める合図が立っているか(確かめを呼ばない読み出しだけ)。ホストの試験では偽。
6382#[inline]
6383fn bridge_aborting() -> bool {
6384    #[cfg(target_os = "none")]
6385    return crate::os_lib::platform::layout_aborting();
6386    #[cfg(not(target_os = "none"))]
6387    false
6388}
6389
6390// ============ ホスト物としての DOM 要素(2026-11-19 手順 7)============
6391
6392/// `HostRef::class` の番号。`id` の意味は種類ごとに決まる。
6393/// DOM 要素(`id` は DOM アリーナのノード index。同じ `id` のハンドルは `===` で等しい)。
6394pub const HOST_DOM_ELEMENT: u8 = HOST_CLASS_BY_ID;
6395/// `document`(`id` は使わない)。
6396pub const HOST_DOCUMENT: u8 = 1;
6397/// `element.style`(`id` はノード index。同じ要素の `style`・`classList`・`dataset` のハンドルは `===` で等しい。2026-11-19)。
6398pub const HOST_STYLE: u8 = 2 | HOST_CLASS_BY_ID;
6399/// `element.classList`(同)。
6400pub const HOST_CLASSLIST: u8 = 3 | HOST_CLASS_BY_ID;
6401/// `element.dataset`(同)。
6402pub const HOST_DATASET: u8 = 4 | HOST_CLASS_BY_ID;
6403/// `getComputedStyle(el)`(同。無効な要素は `usize::MAX`)。
6404pub const HOST_COMPUTED: u8 = 5;
6405/// `document.styleSheets[i]`(`id` は `<style>` のノード index)。
6406pub const HOST_STYLESHEET: u8 = 6;
6407/// `localStorage`(`id` = 0)・`sessionStorage`(`id` = 1)。
6408pub const HOST_STORAGE: u8 = 7;
6409/// `CSSStyleSheet.cssRules[i]`(`id` は `ノード index << 32 | 規則の番号`)。
6410pub const HOST_CSSRULE: u8 = 8;
6411/// `element.attributes`(`NamedNodeMap`。`id` は要素のノード index。`builtins/dom_attr.rs`)。
6412pub const HOST_ATTRS: u8 = 9 | HOST_CLASS_BY_ID;
6413/// `a`/`area`/`link`/`form.relList`(`rel` 属性の `DOMTokenList`。`id` は要素のノード index)。
6414pub const HOST_TOKENLIST_RELLIST: u8 = 10 | HOST_CLASS_BY_ID;
6415/// `iframe.sandbox`(`sandbox` 属性の `DOMTokenList`。`id` は要素のノード index)。
6416pub const HOST_TOKENLIST_SANDBOX: u8 = 11 | HOST_CLASS_BY_ID;
6417/// `output.htmlFor`(`for` 属性の `DOMTokenList`。`id` は要素のノード index)。
6418pub const HOST_TOKENLIST_HTMLFOR: u8 = 12 | HOST_CLASS_BY_ID;
6419/// `link.sizes`(`sizes` 属性の `DOMTokenList`。`id` は要素のノード index)。
6420pub const HOST_TOKENLIST_SIZES: u8 = 13 | HOST_CLASS_BY_ID;
6421/// `link`/`script`/`style.blocking`(`blocking` 属性の `DOMTokenList`。`id` は要素のノード index)。
6422pub const HOST_TOKENLIST_BLOCKING: u8 = 14 | HOST_CLASS_BY_ID;
6423/// `element.part`(`part` 属性の `DOMTokenList`。`id` は要素のノード index)。
6424pub const HOST_TOKENLIST_PART: u8 = 15 | HOST_CLASS_BY_ID;
6425/// 生きている `HTMLCollection`(`id` は `DomBridge::html_collections` の添字)。
6426pub const HOST_HTMLCOLLECTION: u8 = 16;
6427/// 生きている `NodeList`(`childNodes` 用。`id` は親ノード index、または `usize::MAX - 1` が主文書)。
6428pub const HOST_NODELIST: u8 = 17 | HOST_CLASS_BY_ID;
6429/// 静的 `NodeList`(`querySelectorAll` 用。`id` は `DomBridge::static_node_lists` の添字)。
6430pub const HOST_STATIC_NODELIST: u8 = 18;
6431
6432/// 生きている `HTMLCollection` の種別(DOM Standard §4.2.1)。
6433#[derive(Clone)]
6434pub enum HtmlCollectionKind {
6435    ByTagName { root: Option<usize>, include_root: bool, qname: String },
6436    ByTagNameNS { root: Option<usize>, include_root: bool, ns: Option<String>, local: String },
6437    ByClassName { root: Option<usize>, class_names: String },
6438    Children { root: Option<usize> },
6439}
6440
6441impl DomBridge {
6442    /// 生きている `HTMLCollection` を登録して `col_id` を返す。
6443    pub fn new_html_collection(&mut self, kind: HtmlCollectionKind) -> usize {
6444        let id = self.html_collections.len();
6445        self.html_collections.push(kind);
6446        id
6447    }
6448
6449    /// `col_id` の `HTMLCollection` に現在マッチする要素のノード index 一覧(文書順)。
6450    pub fn html_collection_items(&self, col_id: usize) -> Vec<usize> {
6451        let Some(kind) = self.html_collections.get(col_id) else {
6452            return Vec::new();
6453        };
6454        match kind {
6455            HtmlCollectionKind::ByTagName { root, include_root, qname } => {
6456                let r = match root {
6457                    Some(i) => *i,
6458                    None => {
6459                        if self.nodes.is_empty() {
6460                            return Vec::new();
6461                        }
6462                        0
6463                    }
6464                };
6465                walk_elements(self, r, *include_root)
6466                    .into_iter()
6467                    .filter(|&i| {
6468                        self.nodes
6469                            .get(i)
6470                            .is_some_and(|n| matches_qualified_name(n, qname))
6471                    })
6472                    .collect()
6473            }
6474            HtmlCollectionKind::ByTagNameNS { root, include_root, ns, local } => {
6475                let r = match root {
6476                    Some(i) => *i,
6477                    None => {
6478                        if self.nodes.is_empty() {
6479                            return Vec::new();
6480                        }
6481                        0
6482                    }
6483                };
6484                walk_elements(self, r, *include_root)
6485                    .into_iter()
6486                    .filter(|&i| {
6487                        self.nodes
6488                            .get(i)
6489                            .is_some_and(|n| matches_ns_local(n, ns.as_deref(), local))
6490                    })
6491                    .collect()
6492            }
6493            HtmlCollectionKind::ByClassName { root, class_names } => {
6494                self.get_elements_by_class_name(*root, class_names)
6495            }
6496            HtmlCollectionKind::Children { root } => match root {
6497                Some(idx) => {
6498                    if self.nodes.get(*idx).is_some_and(|n| n.tag == "template") {
6499                        Vec::new()
6500                    } else {
6501                        self.element_children(*idx)
6502                    }
6503                }
6504                None => self.query("html").into_iter().collect(),
6505            },
6506        }
6507    }
6508
6509    /// `HTMLCollection.namedItem(name)`(DOM Standard §4.2.1)。空文字列は `None`。
6510    pub fn html_collection_named_item(&self, col_id: usize, name: &str) -> Option<usize> {
6511        if name.is_empty() {
6512            return None;
6513        }
6514        for idx in self.html_collection_items(col_id) {
6515            if self.get_attr(idx, "id").as_deref() == Some(name) {
6516                return Some(idx);
6517            }
6518            let is_html = self
6519                .nodes
6520                .get(idx)
6521                .and_then(node_namespace)
6522                .as_deref()
6523                == Some(HTML_NS_URI);
6524            if is_html && self.get_attr(idx, "name").as_deref() == Some(name) {
6525                return Some(idx);
6526            }
6527        }
6528        None
6529    }
6530
6531    /// `HTMLCollection` の supported property names(DOM Standard §4.2.1)。
6532    pub fn html_collection_supported_names(&self, col_id: usize) -> Vec<String> {
6533        let mut out = Vec::new();
6534        let mut seen = BTreeSet::new();
6535        for idx in self.html_collection_items(col_id) {
6536            if let Some(id) = self.get_attr(idx, "id").filter(|s| !s.is_empty()) {
6537                if seen.insert(id.clone()) {
6538                    out.push(id);
6539                }
6540            }
6541            let is_html = self
6542                .nodes
6543                .get(idx)
6544                .and_then(node_namespace)
6545                .as_deref()
6546                == Some(HTML_NS_URI);
6547            if is_html {
6548                if let Some(nm) = self.get_attr(idx, "name").filter(|s| !s.is_empty()) {
6549                    if seen.insert(nm.clone()) {
6550                        out.push(nm);
6551                    }
6552                }
6553            }
6554        }
6555        out
6556    }
6557
6558    /// `HTMLCollection` の `Object.getOwnPropertyNames` 用キー一覧(index + supported names + expandos)。
6559    pub fn html_collection_entries(&self, col_id: usize) -> Vec<(String, String)> {
6560        let items = self.html_collection_items(col_id);
6561        let mut out = Vec::with_capacity(items.len());
6562        let mut seen = BTreeSet::new();
6563        for i in 0..items.len() {
6564            let k = i.to_string();
6565            seen.insert(k.clone());
6566            out.push((k, String::new()));
6567        }
6568        for name in self.html_collection_supported_names(col_id) {
6569            if seen.insert(name.clone()) {
6570                out.push((name, String::new()));
6571            }
6572        }
6573        if let Some(exp) = self.html_collection_expandos.get(&col_id) {
6574            for k in exp.keys() {
6575                if seen.insert(k.clone()) {
6576                    out.push((k.clone(), String::new()));
6577                }
6578            }
6579        }
6580        out
6581    }
6582
6583    /// `NamedNodeMap` (`HOST_ATTRS`) の `Object.getOwnPropertyNames` 用キー一覧(index + supported property names)。
6584    pub fn attrs_map_entries(&self, elem_idx: usize) -> Vec<(String, String)> {
6585        let entries = self.attr_entries(elem_idx);
6586        let mut out = Vec::with_capacity(entries.len() * 2);
6587        let mut seen = BTreeSet::new();
6588        for i in 0..entries.len() {
6589            let k = i.to_string();
6590            seen.insert(k.clone());
6591            out.push((k, String::new()));
6592        }
6593        let html_elem_in_html_doc = self.nodes.get(elem_idx).is_some_and(|n| {
6594            !n.attrs.contains_key("_xml")
6595                && node_namespace(n).as_deref() == Some(HTML_NS_URI)
6596                && self.doc_is_html(self.node_document(elem_idx))
6597        });
6598        for (_, name) in entries {
6599            if html_elem_in_html_doc && name.bytes().any(|b| b.is_ascii_uppercase()) {
6600                continue;
6601            }
6602            if seen.insert(name.clone()) {
6603                out.push((name, String::new()));
6604            }
6605        }
6606        out
6607    }
6608
6609    /// 生きている `NodeList` (`childNodes`) の子ノード一覧。
6610    pub fn node_list_items(&self, id: usize) -> Vec<usize> {
6611        if id == usize::MAX - 1 {
6612            let mut v: Vec<usize> = self.main_doctype.into_iter().collect();
6613            if !self.nodes.is_empty() {
6614                v.push(0);
6615            }
6616            return v;
6617        }
6618        match self.nodes.get(id) {
6619            Some(n) if n.tag != "template" => n.children.clone(),
6620            _ => Vec::new(),
6621        }
6622    }
6623
6624    /// `NodeList` (`HOST_NODELIST`) の `Object.getOwnPropertyNames` 用キー一覧(`0..len`)。
6625    pub fn node_list_entries(&self, id: usize) -> Vec<(String, String)> {
6626        let len = self.node_list_items(id).len();
6627        (0..len).map(|i| (i.to_string(), String::new())).collect()
6628    }
6629
6630    /// 静的 `NodeList` を登録して `id` を返す。
6631    pub fn new_static_node_list(&mut self, items: Vec<usize>) -> usize {
6632        let id = self.static_node_lists.len();
6633        self.static_node_lists.push(items);
6634        id
6635    }
6636
6637    /// 静的 `NodeList` の要素一覧。
6638    pub fn static_node_list_items(&self, id: usize) -> &[usize] {
6639        self.static_node_lists.get(id).map(|v| v.as_slice()).unwrap_or(&[])
6640    }
6641
6642    /// 静的 `NodeList` の `Object.getOwnPropertyNames` 用キー一覧(`0..len`)。
6643    pub fn static_node_list_entries(&self, id: usize) -> Vec<(String, String)> {
6644        let len = self.static_node_list_items(id).len();
6645        (0..len).map(|i| (i.to_string(), String::new())).collect()
6646    }
6647}
6648
6649/// `HostRef::class` が `DOMTokenList` 系(`classList` / `relList` / `sandbox` / `htmlFor` / `sizes` / `blocking` / `part`)か。
6650#[inline]
6651pub const fn is_token_list_host(class: u8) -> bool {
6652    matches!(
6653        class,
6654        HOST_CLASSLIST
6655            | HOST_TOKENLIST_RELLIST
6656            | HOST_TOKENLIST_SANDBOX
6657            | HOST_TOKENLIST_HTMLFOR
6658            | HOST_TOKENLIST_SIZES
6659            | HOST_TOKENLIST_BLOCKING
6660            | HOST_TOKENLIST_PART
6661    )
6662}
6663
6664/// `DOMTokenList` 系ホストクラスに対応する属性名。
6665#[inline]
6666pub const fn token_list_attr(class: u8) -> Option<&'static str> {
6667    match class {
6668        HOST_CLASSLIST => Some("class"),
6669        HOST_TOKENLIST_RELLIST => Some("rel"),
6670        HOST_TOKENLIST_SANDBOX => Some("sandbox"),
6671        HOST_TOKENLIST_HTMLFOR => Some("for"),
6672        HOST_TOKENLIST_SIZES => Some("sizes"),
6673        HOST_TOKENLIST_BLOCKING => Some("blocking"),
6674        HOST_TOKENLIST_PART => Some("part"),
6675        _ => None,
6676    }
6677}
6678/// `HOST_STORAGE` の `id`。
6679pub const STORAGE_LOCAL: usize = 0;
6680pub const STORAGE_SESSION: usize = 1;
6681
6682impl ObjKind {
6683    /// DOM 要素のハンドルなら、そのノード index。
6684    #[inline]
6685    pub fn dom_node(&self) -> Option<usize> {
6686        match self {
6687            ObjKind::HostRef(h) if h.class == HOST_DOM_ELEMENT => Some(h.id),
6688            _ => None,
6689        }
6690    }
6691}
6692
6693impl Obj {
6694    /// DOM 要素のハンドルを作る(ノード index 1 つ。同じノードのハンドルは `===` で等しい)。
6695    pub fn dom(node_idx: usize) -> ObjRef {
6696        Obj::host_ref(HostRef { class: HOST_DOM_ELEMENT, id: node_idx })
6697    }
6698    /// DOM のプロキシ(`style`・`classList`・`document` など。`HOST_*` の番号と `id`)を作る。
6699    pub fn dom_host(class: u8, id: usize) -> ObjRef {
6700        Obj::host_ref(HostRef { class, id })
6701    }
6702}
6703
6704/// ASCII 空白(SP, HT, LF, FF, CR)のみで空でないトークンへ分割する(DOM ordered set parser)。
6705pub(crate) fn split_ascii_ws(s: &str) -> Vec<String> {
6706    s.split([' ', '\t', '\n', '\x0c', '\r'])
6707        .filter(|t| !t.is_empty())
6708        .map(String::from)
6709        .collect()
6710}
6711
6712const HTML_NS_URI: &str = "http://www.w3.org/1999/xhtml";
6713const SVG_NS_URI: &str = "http://www.w3.org/2000/svg";
6714const MATHML_NS_URI: &str = "http://www.w3.org/1998/Math/MathML";
6715
6716/// 要素の名前空間 URI(`null` は `None`)。内部属性 `_ns` →(仕様どおりの木を組んだ場合の)`#ns` → HTML。
6717pub(crate) fn node_namespace(n: &DomNode) -> Option<String> {
6718    if let Some(v) = n.attrs.get("_ns") {
6719        return if v.is_empty() { None } else { Some(v.clone()) };
6720    }
6721    match n.attrs.get("#ns").map(|s| s.as_str()) {
6722        Some("svg") => Some(String::from(SVG_NS_URI)),
6723        Some("math") => Some(String::from(MATHML_NS_URI)),
6724        _ => Some(String::from(HTML_NS_URI)),
6725    }
6726}
6727
6728/// `localName`。
6729pub(crate) fn node_local_name(n: &DomNode) -> String {
6730    match n.attrs.get("_qname") {
6731        Some(q) => match q.split_once(':') {
6732            Some((_, l)) if n.attrs.contains_key("_prefix") => String::from(l),
6733            _ => q.clone(),
6734        },
6735        None => n.tag.clone(),
6736    }
6737}
6738
6739/// `root` 以下の要素を文書順(行きがけ順)に並べる。`include_root` なら `root` 自身も。
6740pub(crate) fn walk_elements(dom: &DomBridge, root: usize, include_root: bool) -> Vec<usize> {
6741    let mut out = Vec::new();
6742    let mut stack: Vec<usize> = alloc::vec![root];
6743    while let Some(i) = stack.pop() {
6744        let Some(n) = dom.nodes.get(i) else { continue };
6745        if n.is_text {
6746            continue;
6747        }
6748        if (i != root || include_root) && !n.tag.starts_with('#') {
6749            out.push(i);
6750        }
6751        for &c in n.children.iter().rev() {
6752            stack.push(c);
6753        }
6754    }
6755    out
6756}
6757
6758/// `getElementsByTagName(qualifiedName)` の照合(DOM Standard)。
6759pub(crate) fn matches_qualified_name(n: &DomNode, name: &str) -> bool {
6760    if name == "*" {
6761        return true;
6762    }
6763    let qname = n.attrs.get("_qname").cloned().unwrap_or_else(|| n.tag.clone());
6764    if node_namespace(n).as_deref() == Some(HTML_NS_URI) && !n.attrs.contains_key("_xml") {
6765        qname == name.to_ascii_lowercase()
6766    } else {
6767        qname == name
6768    }
6769}
6770
6771/// `getElementsByTagNameNS(namespace, localName)` の照合。`*` はどれにも一致。
6772pub(crate) fn matches_ns_local(n: &DomNode, ns: Option<&str>, local: &str) -> bool {
6773    let ns_ok = match ns {
6774        Some("*") => true,
6775        other => node_namespace(n).as_deref() == other.filter(|s| !s.is_empty()),
6776    };
6777    ns_ok && (local == "*" || node_local_name(n) == local)
6778}