Skip to main content

atmos/os_lib/web_apis/builtins/
observers.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4use crate::os_lib::viewport::intersection_observer::{
5    compute_intersection, should_trigger_callback, IntersectionRect, RootMargin,
6};
7use crate::os_lib::viewport::resize_observer::{
8    compute_resize_boxes, has_size_changed, ResizeObserverBoxOptions,
9};
10
11// ===== IntersectionObserver =====
12
13pub(crate) fn make_dom_rect_f64(r: &IntersectionRect) -> ObjRef {
14    let o = Obj::plain();
15    {
16        let mut b = o.borrow_mut();
17        b.props.insert("x".into(), Value::Number(r.x));
18        b.props.insert("left".into(), Value::Number(r.x));
19        b.props.insert("y".into(), Value::Number(r.y));
20        b.props.insert("top".into(), Value::Number(r.y));
21        b.props.insert("width".into(), Value::Number(r.width));
22        b.props.insert("height".into(), Value::Number(r.height));
23        b.props.insert("right".into(), Value::Number(r.right()));
24        b.props.insert("bottom".into(), Value::Number(r.bottom()));
25    }
26    o
27}
28
29/// 幾何交差計算に基づく `IntersectionObserverEntry` の構築
30pub(crate) fn compute_io_entry(
31    it: &mut Interp,
32    target: Value,
33    root_val: &Value,
34    root_margin: &RootMargin,
35) -> (Value, f64, bool) {
36    let target_idx = this_dom_idx(&target);
37    let (tx, ty, tw, th) = target_idx
38        .and_then(|idx| it.dom().borrow().get_rect(idx))
39        .unwrap_or((0, 0, 0, 0));
40    let target_rect = IntersectionRect::new(tx as f64, ty as f64, tw as f64, th as f64);
41
42    let root_rect = if let Some(r_idx) = this_dom_idx(root_val) {
43        let (rx, ry, rw, rh) = it.dom().borrow().get_rect(r_idx).unwrap_or((0, 0, 0, 0));
44        IntersectionRect::new(rx as f64, ry as f64, rw as f64, rh as f64)
45    } else {
46        let global_vars = it.global.borrow();
47        let vw = global_vars
48            .vars
49            .get("innerWidth")
50            .and_then(|v| match *v {
51                Value::Number(n) => Some(n),
52                _ => None,
53            })
54            .unwrap_or(800.0);
55        let vh = global_vars
56            .vars
57            .get("innerHeight")
58            .and_then(|v| match *v {
59                Value::Number(n) => Some(n),
60                _ => None,
61            })
62            .unwrap_or(600.0);
63        IntersectionRect::new(0.0, 0.0, vw, vh)
64    };
65
66    let state = compute_intersection(&target_rect, &root_rect, root_margin);
67
68    let entry = Obj::plain();
69    {
70        let mut b = entry.borrow_mut();
71        b.props
72            .insert("isIntersecting".into(), Value::Bool(state.is_intersecting));
73        b.props
74            .insert("intersectionRatio".into(), Value::Number(state.intersection_ratio));
75        let bcr = Value::Object(make_dom_rect_f64(&state.bounding_client_rect));
76        b.props.insert("boundingClientRect".into(), bcr.clone());
77        let ir = if state.is_intersecting
78            && state.bounding_client_rect == state.intersection_rect
79        {
80            bcr
81        } else {
82            Value::Object(make_dom_rect_f64(&state.intersection_rect))
83        };
84        b.props.insert("intersectionRect".into(), ir);
85        let root_bounds = if this_dom_idx(root_val).is_some() {
86            match &state.root_bounds {
87                Some(rb) => Value::Object(make_dom_rect_f64(rb)),
88                None => Value::Null,
89            }
90        } else {
91            Value::Null
92        };
93        b.props.insert("rootBounds".into(), root_bounds);
94        b.props
95            .insert("time".into(), Value::Number(next_perf_timestamp()));
96        b.props.insert("target".into(), target);
97    }
98    (Value::Object(entry), state.intersection_ratio, state.is_intersecting)
99}
100
101/// 互換用ラッパー
102pub(crate) fn make_io_entry(it: &mut Interp, target: Value) -> Value {
103    let (entry, _, _) = compute_io_entry(it, target, &Value::Null, &RootMargin::zero());
104    entry
105}
106
107pub(crate) fn io_observe(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
108    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
109    let obs_id = match self_obj.borrow().props.get("_id") {
110        Some(Value::Number(n)) => *n as u32,
111        _ => return Ok(Value::Undefined),
112    };
113    let target = arg(a, 0);
114    let target_idx = match this_dom_idx(&target) {
115        Some(idx) => idx,
116        None => return Ok(Value::Undefined),
117    };
118
119    let (cb, root_val, root_margin) = {
120        let dom = it.dom().borrow();
121        match dom.io_observers.iter().find(|o| o.id == obs_id) {
122            Some(o) => (o.callback.clone(), o.root.clone(), o.root_margin),
123            None => return Ok(Value::Undefined),
124        }
125    };
126
127    // 初回エントリの計算
128    let (entry, ratio, is_intersecting) =
129        compute_io_entry(it, target.clone(), &root_val, &root_margin);
130
131    // 監視対象ターゲットの追加・更新
132    {
133        let mut dom = it.dom().borrow_mut();
134        if let Some(obs) = dom.io_observers.iter_mut().find(|o| o.id == obs_id) {
135            obs.targets.retain(|t| t.target_idx != target_idx);
136            obs.targets.push(super::super::dom_bridge::ObservedTarget {
137                target: target.clone(),
138                target_idx,
139                prev_ratio: Some(ratio),
140                prev_is_intersecting: is_intersecting,
141            });
142        }
143    }
144
145    // 初回コールバック発火(W3C 仕様: observe 開始時に初回通知を発火)
146    if matches!(cb, Value::Object(_)) {
147        let entries = Value::Object(Obj::array(alloc::vec![entry]));
148        it.call_listener(
149            &cb,
150            Value::Undefined,
151            &[entries, this],
152            "IntersectionObserver callback",
153        );
154    }
155
156    Ok(Value::Undefined)
157}
158
159pub(crate) fn io_unobserve(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
160    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
161    let obs_id = match self_obj.borrow().props.get("_id") {
162        Some(Value::Number(n)) => *n as u32,
163        _ => return Ok(Value::Undefined),
164    };
165    let target = arg(a, 0);
166    if let Some(target_idx) = this_dom_idx(&target) {
167        let mut dom = it.dom().borrow_mut();
168        if let Some(obs) = dom.io_observers.iter_mut().find(|o| o.id == obs_id) {
169            obs.targets.retain(|t| t.target_idx != target_idx);
170        }
171    }
172    Ok(Value::Undefined)
173}
174
175pub(crate) fn io_disconnect(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
176    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
177    let obs_id = match self_obj.borrow().props.get("_id") {
178        Some(Value::Number(n)) => *n as u32,
179        _ => return Ok(Value::Undefined),
180    };
181    let mut dom = it.dom().borrow_mut();
182    if let Some(obs) = dom.io_observers.iter_mut().find(|o| o.id == obs_id) {
183        obs.targets.clear();
184        obs.queued_records.clear();
185    }
186    Ok(Value::Undefined)
187}
188
189pub(crate) fn io_take_records(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
190    let Value::Object(self_obj) = &this else {
191        return Ok(Value::Object(Obj::array(alloc::vec![])));
192    };
193    let obs_id = match self_obj.borrow().props.get("_id") {
194        Some(Value::Number(n)) => *n as u32,
195        _ => return Ok(Value::Object(Obj::array(alloc::vec![]))),
196    };
197    let records = {
198        let mut dom = it.dom().borrow_mut();
199        if let Some(obs) = dom.io_observers.iter_mut().find(|o| o.id == obs_id) {
200            core::mem::take(&mut obs.queued_records)
201        } else {
202            alloc::vec![]
203        }
204    };
205    Ok(Value::Object(Obj::array(records)))
206}
207
208pub(crate) fn intersection_observer_ctor(
209    it: &mut Interp,
210    _t: Value,
211    a: &[Value],
212) -> Result<Value, Value> {
213    let cb = arg(a, 0);
214    let options = arg(a, 1);
215    let root = obj_prop(&options, "root").unwrap_or(Value::Null);
216    let root_margin_str = obj_prop(&options, "rootMargin")
217        .map(|v| v.to_js_string())
218        .unwrap_or_else(|| String::from("0px 0px 0px 0px"));
219    let root_margin = RootMargin::parse(&root_margin_str).unwrap_or_else(|_| RootMargin::zero());
220
221    let threshold_val = obj_prop(&options, "threshold");
222    let thresholds: alloc::vec::Vec<f64> = match threshold_val {
223        Some(v) => {
224            let items = this_items(&v);
225            if items.is_empty() && !matches!(v, Value::Object(_)) {
226                alloc::vec![v.to_number()]
227            } else {
228                items.iter().map(|x| x.to_number()).collect()
229            }
230        }
231        None => alloc::vec![0.0],
232    };
233
234    let obs_id = {
235        let mut dom = it.dom().borrow_mut();
236        let id = dom.next_io_obs_id;
237        dom.next_io_obs_id += 1;
238        dom.io_observers.push(super::super::dom_bridge::IntersectionObserverReg {
239            id,
240            callback: cb.clone(),
241            root: root.clone(),
242            root_margin,
243            thresholds: thresholds.clone(),
244            targets: alloc::vec![],
245            queued_records: alloc::vec![],
246        });
247        id
248    };
249
250    let obs = Obj::plain();
251    {
252        let mut b = obs.borrow_mut();
253        b.props.insert("_cb".into(), cb);
254        b.props.insert("_id".into(), Value::Number(obs_id as f64));
255        b.props.insert("root".into(), root);
256        b.props.insert("rootMargin".into(), Value::str(root_margin_str));
257        b.props.insert(
258            "thresholds".into(),
259            Value::Object(Obj::array(thresholds.into_iter().map(Value::Number).collect())),
260        );
261        b.props.insert("observe".into(), nv("observe", io_observe));
262        b.props
263            .insert("unobserve".into(), nv("unobserve", io_unobserve));
264        b.props
265            .insert("disconnect".into(), nv("disconnect", io_disconnect));
266        b.props
267            .insert("takeRecords".into(), nv("takeRecords", io_take_records));
268    }
269    Ok(Value::Object(obs))
270}
271
272/// 即時 fulfilled な Promise オブジェクトを返す(animate().finished など用)。
273pub fn make_resolved_promise(val: Value) -> ObjRef {
274    use crate::os_lib::ecma::value::PromiseState;
275    let state = alloc::rc::Rc::new(core::cell::RefCell::new(PromiseState::pending()));
276    state.borrow_mut().status = crate::os_lib::ecma::value::PromiseStatus::Fulfilled;
277    state.borrow_mut().value = val;
278    let obj = Obj::plain();
279    obj.borrow_mut().kind = crate::os_lib::ecma::value::ObjKind::PromiseObj(state.clone());
280    // then / catch / finally はスタブ
281    let mut b = obj.borrow_mut();
282    b.props.insert("then".into(), nv("then", dom_noop));
283    b.props.insert("catch".into(), nv("catch", dom_noop));
284    b.props.insert("finally".into(), nv("finally", dom_noop));
285    drop(b);
286    obj
287}
288
289/// スクロール後やレイアウト更新後に IntersectionObserver コールバックを発火する。
290pub fn fire_intersection_observers(it: &mut Interp) {
291    let observers = {
292        let dom = it.dom().borrow();
293        dom.io_observers.clone()
294    };
295    if observers.is_empty() {
296        return;
297    }
298
299    for obs in observers {
300        if obs.targets.is_empty() || !matches!(obs.callback, Value::Object(_)) {
301            continue;
302        }
303
304        let mut triggered_entries = alloc::vec![];
305        let mut updated_targets = alloc::vec![];
306
307        for target_info in &obs.targets {
308            let (entry, ratio, is_intersecting) = compute_io_entry(
309                it,
310                target_info.target.clone(),
311                &obs.root,
312                &obs.root_margin,
313            );
314
315            if should_trigger_callback(
316                target_info.prev_ratio,
317                target_info.prev_is_intersecting,
318                ratio,
319                is_intersecting,
320                &obs.thresholds,
321            ) {
322                triggered_entries.push(entry);
323                updated_targets.push(super::super::dom_bridge::ObservedTarget {
324                    target: target_info.target.clone(),
325                    target_idx: target_info.target_idx,
326                    prev_ratio: Some(ratio),
327                    prev_is_intersecting: is_intersecting,
328                });
329            } else {
330                updated_targets.push(target_info.clone());
331            }
332        }
333
334        // 状態更新
335        {
336            let mut dom = it.dom().borrow_mut();
337            if let Some(reg) = dom.io_observers.iter_mut().find(|o| o.id == obs.id) {
338                reg.targets = updated_targets;
339            }
340        }
341
342        if !triggered_entries.is_empty() {
343            let entries_val = Value::Object(Obj::array(triggered_entries));
344            let obs_obj = Value::Object(Obj::plain());
345            it.call_listener(
346                &obs.callback,
347                Value::Undefined,
348                &[entries_val, obs_obj],
349                "IntersectionObserver callback",
350            );
351        }
352    }
353}
354
355/// DOM 変更後に MutationObserver のコールバックを発火する。
356/// `eval` 末尾と `dispatch_event` 後に呼ぶ。
357pub fn flush_mutation_observers(it: &mut Interp) {
358    // 通知前にすべての transient registered observers を解除する(DOM §4.3.3.1)。
359    // ただしレコードが無くても、あるいはレコードを取得した直後に解除する。
360    let all_recs = drain_mut_records(it);
361    if all_recs.is_empty() {
362        it.dom().borrow_mut().mut_observers.retain(|o| o.transient_source.is_none());
363        return;
364    }
365    it.mark_task_start();
366    // observer_id → (callback, observer_obj, Vec<MutRec>) にグループ化してから transient を解除する。
367    use alloc::collections::BTreeMap;
368    let mut groups: BTreeMap<u32, (Value, Value, alloc::vec::Vec<super::super::dom_bridge::MutRec>)> =
369        BTreeMap::new();
370    {
371        let mut dom = it.dom().borrow_mut();
372        for (id, rec) in all_recs {
373            let (cb, obs_val) = dom
374                .mut_observers
375                .iter()
376                .find(|o| o.id == id)
377                .map(|o| (o.callback.clone(), o.observer.clone()))
378                .unwrap_or((Value::Undefined, Value::Undefined));
379            groups.entry(id).or_insert((cb, obs_val, alloc::vec![])).2.push(rec);
380        }
381        dom.mut_observers.retain(|o| o.transient_source.is_none());
382    }
383    for (_id, (cb, obs_val, recs)) in groups {
384        if !matches!(cb, Value::Object(_)) {
385            continue;
386        }
387        let js_recs: alloc::vec::Vec<Value> =
388            recs.iter().map(|r| make_mut_record(it, r)).collect();
389        let arr = Value::Object(Obj::array(js_recs));
390        // W3C DOM MutationObserver 仕様: 第1引数に records 配列、第2引数に MutationObserver 自身、this も observer を渡す
391        it.call_listener(&cb, obs_val.clone(), &[arr, obs_val], "MutationObserver callback");
392    }
393}
394
395// ===== ResizeObserver =====
396
397pub(crate) fn compute_ro_entry(
398    it: &mut Interp,
399    target: Value,
400    box_opt: ResizeObserverBoxOptions,
401) -> (Value, f64, f64) {
402    let target_idx = this_dom_idx(&target);
403    let (_, _, w, h) = target_idx
404        .and_then(|idx| it.dom().borrow().get_rect(idx))
405        .unwrap_or((0, 0, 0, 0));
406    let (bw, bh) = (w as f64, h as f64);
407
408    // computed style から padding と border-width を取得
409    let (pt, pr, pb, pl, bt, br, bb, bl) = if let Some(idx) = target_idx {
410        let dom = it.dom().borrow();
411        let parse_px = |prop: &str| -> f64 {
412            let s = dom.get_computed(idx, prop);
413            s.trim_end_matches("px").parse::<f64>().unwrap_or(0.0)
414        };
415        (
416            parse_px("padding-top"),
417            parse_px("padding-right"),
418            parse_px("padding-bottom"),
419            parse_px("padding-left"),
420            parse_px("border-top-width"),
421            parse_px("border-right-width"),
422            parse_px("border-bottom-width"),
423            parse_px("border-left-width"),
424        )
425    } else {
426        (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
427    };
428
429    let dims = compute_resize_boxes(bw, bh, pt, pr, pb, pl, bt, br, bb, bl);
430
431    let entry = Obj::plain();
432    {
433        let mut b = entry.borrow_mut();
434        b.props.insert("target".into(), target);
435        let cr = Obj::plain();
436        {
437            let mut c = cr.borrow_mut();
438            c.props.insert("x".into(), Value::Number(dims.content_rect_x));
439            c.props.insert("y".into(), Value::Number(dims.content_rect_y));
440            c.props.insert("width".into(), Value::Number(dims.content_rect_width));
441            c.props.insert("height".into(), Value::Number(dims.content_rect_height));
442            c.props.insert("top".into(), Value::Number(dims.content_rect_y));
443            c.props.insert("left".into(), Value::Number(dims.content_rect_x));
444            c.props.insert(
445                "right".into(),
446                Value::Number(dims.content_rect_x + dims.content_rect_width),
447            );
448            c.props.insert(
449                "bottom".into(),
450                Value::Number(dims.content_rect_y + dims.content_rect_height),
451            );
452        }
453        b.props.insert("contentRect".into(), Value::Object(cr));
454
455        let make_size = |inline: f64, block: f64| {
456            let s = Obj::plain();
457            s.borrow_mut().props.insert("inlineSize".into(), Value::Number(inline));
458            s.borrow_mut().props.insert("blockSize".into(), Value::Number(block));
459            Value::Object(s)
460        };
461
462        b.props.insert(
463            "borderBoxSize".into(),
464            Value::Object(Obj::array(alloc::vec![make_size(
465                dims.border_box_inline_size,
466                dims.border_box_block_size,
467            )])),
468        );
469        b.props.insert(
470            "contentBoxSize".into(),
471            Value::Object(Obj::array(alloc::vec![make_size(
472                dims.content_box_inline_size,
473                dims.content_box_block_size,
474            )])),
475        );
476        b.props.insert(
477            "devicePixelContentBoxSize".into(),
478            Value::Object(Obj::array(alloc::vec![make_size(
479                dims.device_pixel_content_box_inline_size,
480                dims.device_pixel_content_box_block_size,
481            )])),
482        );
483    }
484
485    let (cur_inline, cur_block) = match box_opt {
486        ResizeObserverBoxOptions::BorderBox => (
487            dims.border_box_inline_size,
488            dims.border_box_block_size,
489        ),
490        ResizeObserverBoxOptions::DevicePixelContentBox => (
491            dims.device_pixel_content_box_inline_size,
492            dims.device_pixel_content_box_block_size,
493        ),
494        ResizeObserverBoxOptions::ContentBox => (
495            dims.content_box_inline_size,
496            dims.content_box_block_size,
497        ),
498    };
499
500    (Value::Object(entry), cur_inline, cur_block)
501}
502
503pub(crate) fn ro_observe(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
504    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
505    let obs_id = match self_obj.borrow().props.get("_id") {
506        Some(Value::Number(n)) => *n as u32,
507        _ => return Ok(Value::Undefined),
508    };
509    let cb = self_obj.borrow().props.get("_cb").cloned().unwrap_or(Value::Undefined);
510
511    let target = arg(a, 0);
512    let target_idx = match this_dom_idx(&target) {
513        Some(idx) => idx,
514        None => return Ok(Value::Undefined),
515    };
516
517    let options = arg(a, 1);
518    let box_str = obj_prop(&options, "box").map(|v| v.to_js_string()).unwrap_or_default();
519    let box_opt = ResizeObserverBoxOptions::parse(&box_str);
520
521    let (entry, inline_size, block_size) = compute_ro_entry(it, target.clone(), box_opt);
522
523    // targets に登録
524    let already_observing = {
525        let mut dom = it.dom().borrow_mut();
526        if let Some(obs) = dom.ro_observers.iter_mut().find(|o| o.id == obs_id) {
527            let was = obs.targets.iter().any(|t| t.target_idx == target_idx);
528            obs.targets.retain(|t| t.target_idx != target_idx);
529            obs.targets.push(super::super::dom_bridge::ObservedResizeTarget {
530                target: target.clone(),
531                target_idx,
532                box_option: box_opt,
533                last_inline_size: inline_size,
534                last_block_size: block_size,
535            });
536            was
537        } else {
538            false
539        }
540    };
541
542    // 初回コールバック発火(既に監視中の要素に対する重複 observe では再発火しない)
543    if !already_observing && matches!(cb, Value::Object(_)) {
544        let entries = Value::Object(Obj::array(alloc::vec![entry]));
545        it.call_listener(
546            &cb,
547            Value::Undefined,
548            &[entries, this],
549            "ResizeObserver callback",
550        );
551    }
552
553    Ok(Value::Undefined)
554}
555
556pub(crate) fn ro_unobserve(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
557    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
558    let obs_id = match self_obj.borrow().props.get("_id") {
559        Some(Value::Number(n)) => *n as u32,
560        _ => return Ok(Value::Undefined),
561    };
562    let target = arg(a, 0);
563    if let Some(target_idx) = this_dom_idx(&target) {
564        let mut dom = it.dom().borrow_mut();
565        if let Some(obs) = dom.ro_observers.iter_mut().find(|o| o.id == obs_id) {
566            obs.targets.retain(|t| t.target_idx != target_idx);
567        }
568    }
569    Ok(Value::Undefined)
570}
571
572pub(crate) fn ro_disconnect(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
573    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
574    let obs_id = match self_obj.borrow().props.get("_id") {
575        Some(Value::Number(n)) => *n as u32,
576        _ => return Ok(Value::Undefined),
577    };
578    let mut dom = it.dom().borrow_mut();
579    if let Some(obs) = dom.ro_observers.iter_mut().find(|o| o.id == obs_id) {
580        obs.targets.clear();
581    }
582    Ok(Value::Undefined)
583}
584
585pub(crate) fn resize_observer_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
586    let cb = arg(a, 0);
587    let obs_id = {
588        let mut dom = it.dom().borrow_mut();
589        let id = dom.next_ro_obs_id;
590        dom.next_ro_obs_id += 1;
591        dom.ro_observers.push(super::super::dom_bridge::ResizeObserverReg {
592            id,
593            callback: cb.clone(),
594            targets: alloc::vec![],
595        });
596        id
597    };
598
599    let obs = Obj::plain();
600    {
601        let mut b = obs.borrow_mut();
602        b.props.insert("_cb".into(), cb);
603        b.props.insert("_id".into(), Value::Number(obs_id as f64));
604        b.props.insert("observe".into(), nv("observe", ro_observe));
605        b.props
606            .insert("unobserve".into(), nv("unobserve", ro_unobserve));
607        b.props
608            .insert("disconnect".into(), nv("disconnect", ro_disconnect));
609    }
610    Ok(Value::Object(obs))
611}
612
613/// レイアウト更新後に ResizeObserver コールバックを発火する。
614pub fn fire_resize_observers(it: &mut Interp) {
615    let observers = {
616        let dom = it.dom().borrow();
617        dom.ro_observers.clone()
618    };
619    if observers.is_empty() {
620        return;
621    }
622
623    for obs in observers {
624        if obs.targets.is_empty() || !matches!(obs.callback, Value::Object(_)) {
625            continue;
626        }
627
628        let mut triggered_entries = alloc::vec![];
629        let mut updated_targets = alloc::vec![];
630
631        for target_info in &obs.targets {
632            let (entry, inline_size, block_size) = compute_ro_entry(
633                it,
634                target_info.target.clone(),
635                target_info.box_option,
636            );
637
638            if has_size_changed(
639                target_info.last_inline_size,
640                target_info.last_block_size,
641                inline_size,
642                block_size,
643            ) {
644                triggered_entries.push(entry);
645                updated_targets.push(super::super::dom_bridge::ObservedResizeTarget {
646                    target: target_info.target.clone(),
647                    target_idx: target_info.target_idx,
648                    box_option: target_info.box_option,
649                    last_inline_size: inline_size,
650                    last_block_size: block_size,
651                });
652            } else {
653                updated_targets.push(target_info.clone());
654            }
655        }
656
657        // 状態更新
658        {
659            let mut dom = it.dom().borrow_mut();
660            if let Some(reg) = dom.ro_observers.iter_mut().find(|o| o.id == obs.id) {
661                reg.targets = updated_targets;
662            }
663        }
664
665        if !triggered_entries.is_empty() {
666            let entries_val = Value::Object(Obj::array(triggered_entries));
667            let obs_obj = Value::Object(Obj::plain());
668            it.call_listener(
669                &obs.callback,
670                Value::Undefined,
671                &[entries_val, obs_obj],
672                "ResizeObserver callback",
673            );
674        }
675    }
676}
677
678
679// ===== MutationObserver =====
680pub(crate) fn mo_observe(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
681    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
682    let obs_id = match self_obj.borrow().props.get("_id") {
683        Some(Value::Number(n)) => *n as u32,
684        _ => return Ok(Value::Undefined),
685    };
686    let callback = self_obj.borrow().props.get("_cb").cloned().unwrap_or(Value::Undefined);
687    let target_idx = match arg(a, 0) {
688        Value::Object(o) => match &o.borrow().kind {
689            ObjKind::HostRef(h) if h.class == crate::os_lib::web_apis::dom_bridge::HOST_DOCUMENT => 0,
690            kind => match kind.dom_node() {
691                Some(i) => i,
692                None => return Ok(Value::Undefined),
693            },
694        },
695        _ => return Ok(Value::Undefined),
696    };
697    let opts = arg(a, 1);
698    let child_list = obj_prop(&opts, "childList")
699        .map(|v| v.truthy())
700        .unwrap_or(false);
701    let attributes_specified = obj_prop(&opts, "attributes");
702    let mut attributes = attributes_specified.as_ref().map(|v| v.truthy()).unwrap_or(false);
703    let subtree = obj_prop(&opts, "subtree")
704        .map(|v| v.truthy())
705        .unwrap_or(false);
706    let attribute_old_value_opt = obj_prop(&opts, "attributeOldValue");
707    let has_attribute_old_value = attribute_old_value_opt.is_some();
708    let attribute_old_value = attribute_old_value_opt
709        .map(|v| v.truthy())
710        .unwrap_or(false);
711    let attribute_filter = match obj_prop(&opts, "attributeFilter") {
712        Some(v @ Value::Object(_)) => Some(
713            generic_array_items(it, &v)
714                .iter()
715                .map(|item| item.to_js_string())
716                .collect::<Vec<String>>(),
717        ),
718        _ => None,
719    };
720    // `characterData`/`characterDataOldValue`(丸ごと未対応だった。
721    // `childList`/`attributes`は既に対応済みで`characterData`だけ抜けていた
722    // 兄弟ギャップ。詳細は`MutObsReg::character_data`のdocコメント参照。
723    // 2026-07-17 発見・実装)。
724    let character_data_specified = obj_prop(&opts, "characterData");
725    let mut character_data = character_data_specified.as_ref().map(|v| v.truthy()).unwrap_or(false);
726    let character_data_old_value_opt = obj_prop(&opts, "characterDataOldValue");
727    let has_character_data_old_value = character_data_old_value_opt.is_some();
728    let character_data_old_value = character_data_old_value_opt
729        .map(|v| v.truthy())
730        .unwrap_or(false);
731    // 仕様上(MutationObserver.observe()アルゴリズム)、`attributeOldValue`/
732    // `attributeFilter`が指定されかつ`attributes`自体が省略された場合は
733    // `attributes`を暗黙的に`true`とみなす(`characterDataOldValue`と
734    // `characterData`も同じ関係)。以前はこの省略時の暗黙有効化ロジックが
735    // 丸ごと無く、`observe(el, {attributeOldValue:true})`という定番の
736    // 省略記法(`attributes:true`を明示せずとも動くのが仕様)が黙って
737    // 何も監視しないバグだった。2026-07-17 発見・実装。
738    if attributes_specified.as_ref().is_some_and(|v| !v.truthy())
739        && (has_attribute_old_value || attribute_filter.is_some())
740    {
741        return Err(it.type_error("Failed to execute 'observe' on 'MutationObserver': The options object may only set 'attributeOldValue' or 'attributeFilter' to true when 'attributes' is true or not present."));
742    }
743    if character_data_specified.as_ref().is_some_and(|v| !v.truthy()) && has_character_data_old_value {
744        return Err(it.type_error("Failed to execute 'observe' on 'MutationObserver': The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present."));
745    }
746    if attributes_specified.is_none() && (has_attribute_old_value || attribute_filter.is_some()) {
747        attributes = true;
748    }
749    if character_data_specified.is_none() && has_character_data_old_value {
750        character_data = true;
751    }
752    if !child_list && !attributes && !character_data {
753        return Err(it.type_error("Failed to execute 'observe' on 'MutationObserver': The options object must set at least one of 'attributes', 'characterData', or 'childList' to true."));
754    }
755    use super::super::dom_bridge::MutObsReg;
756    let mut dom = it.dom().borrow_mut();
757    // 同一IDかつ同一target_idxの既存登録のみを置換し、同一Observerの複数ターゲット監視をサポート(W3C DOM 仕様)
758    dom.mut_observers.retain(|o| {
759        !(o.id == obs_id && (o.target_idx == target_idx || o.transient_source == Some(target_idx)))
760    });
761    dom.mut_observers.push(MutObsReg {
762        id: obs_id,
763        target_idx,
764        child_list,
765        attributes,
766        subtree,
767        callback,
768        observer: this,
769        attribute_old_value,
770        attribute_filter,
771        character_data,
772        character_data_old_value,
773        transient_source: None,
774    });
775    Ok(Value::Undefined)
776}
777
778pub(crate) fn mo_disconnect(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
779    let Value::Object(self_obj) = &this else { return Ok(Value::Undefined) };
780    let obs_id = match self_obj.borrow().props.get("_id") {
781        Some(Value::Number(n)) => *n as u32,
782        _ => return Ok(Value::Undefined),
783    };
784    it.dom().borrow_mut().mut_observers.retain(|o| o.id != obs_id);
785    it.dom().borrow_mut().mut_records.retain(|(id, _)| *id != obs_id);
786    Ok(Value::Undefined)
787}
788
789pub(crate) fn mo_take_records(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
790    let Value::Object(self_obj) = &this else {
791        return Ok(Value::Object(Obj::array(alloc::vec![])));
792    };
793    let obs_id = match self_obj.borrow().props.get("_id") {
794        Some(Value::Number(n)) => *n as u32,
795        _ => return Ok(Value::Object(Obj::array(alloc::vec![]))),
796    };
797    let records = build_mut_records_for(it, obs_id);
798    Ok(Value::Object(Obj::array(records)))
799}
800
801pub(crate) fn build_mut_records_for(it: &mut Interp, obs_id: u32) -> alloc::vec::Vec<Value> {
802    let mut matched = alloc::vec![];
803    let mut rest = alloc::vec![];
804    for (id, r) in core::mem::take(&mut it.dom().borrow_mut().mut_records) {
805        if id == obs_id { matched.push(r); } else { rest.push((id, r)); }
806    }
807    it.dom().borrow_mut().mut_records = rest;
808    matched.iter().map(|r| make_mut_record(it, r)).collect()
809}
810
811pub(crate) fn drain_mut_records(it: &mut Interp) -> alloc::vec::Vec<(u32, super::super::dom_bridge::MutRec)> {
812    core::mem::take(&mut it.dom().borrow_mut().mut_records)
813}
814
815pub(crate) fn make_mut_record(it: &mut Interp, r: &super::super::dom_bridge::MutRec) -> Value {
816    let proto = match it.global.borrow().vars.get("MutationRecord") {
817        Some(Value::Object(c)) => match c.borrow().props.get("prototype") {
818            Some(Value::Object(p)) => Some(p.clone()),
819            _ => None,
820        },
821        _ => None,
822    };
823    let rec = Obj::plain();
824    {
825        let mut b = rec.borrow_mut();
826        b.proto = proto;
827        b.props.insert("type".into(), Value::str(r.type_));
828        let target = it.dom_val(r.target_idx);
829        b.props.insert("target".into(), target);
830        let added: alloc::vec::Vec<Value> = r.added.iter().map(|&i| it.dom_val(i)).collect();
831        b.props.insert("addedNodes".into(), Value::Object(Obj::array(added)));
832        let removed: alloc::vec::Vec<Value> = r.removed.iter().map(|&i| it.dom_val(i)).collect();
833        b.props.insert("removedNodes".into(), Value::Object(Obj::array(removed)));
834        b.props.insert(
835            "previousSibling".into(),
836            r.prev_sibling.map(|i| it.dom_val(i)).unwrap_or(Value::Null),
837        );
838        b.props.insert(
839            "nextSibling".into(),
840            r.next_sibling.map(|i| it.dom_val(i)).unwrap_or(Value::Null),
841        );
842        b.props.insert(
843            "attributeName".into(),
844            r.attribute_name
845                .as_deref()
846                .map(Value::str)
847                .unwrap_or(Value::Null),
848        );
849        b.props.insert(
850            "attributeNamespace".into(),
851            r.attribute_namespace
852                .as_deref()
853                .map(Value::str)
854                .unwrap_or(Value::Null),
855        );
856        b.props.insert(
857            "oldValue".into(),
858            r.old_value.as_deref().map(Value::str).unwrap_or(Value::Null),
859        );
860    }
861    let _ = it;
862    Value::Object(rec)
863}
864
865pub(crate) fn mutation_observer_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
866    let cb = arg(a, 0);
867    let obs_id = {
868        let mut dom = it.dom().borrow_mut();
869        let id = dom.next_mut_obs_id;
870        dom.next_mut_obs_id += 1;
871        id
872    };
873    let obs = Obj::plain();
874    {
875        let mut b = obs.borrow_mut();
876        b.props.insert("_cb".into(), cb);
877        b.props.insert("_id".into(), Value::Number(obs_id as f64));
878        b.props.insert("observe".into(), nv("observe", mo_observe));
879        b.props.insert("disconnect".into(), nv("disconnect", mo_disconnect));
880        b.props.insert("takeRecords".into(), nv("takeRecords", mo_take_records));
881    }
882    Ok(Value::Object(obs))
883}
884