Skip to main content

atmos/os_lib/web_apis/builtins/
dom_handlers.rs

1// イベントハンドラ IDL 属性(`element.onclick` ほか)と、HTMLBodyElement / HTMLFrameSetElement の
2// window へ転送されるハンドラ(2026-11-24。HTML Standard「event handlers」、WPT `dom/events/Body-FrameSet-Event-Handlers.html`)。
3//
4// - 値は `DomBridge::on_handlers`(要素ごとの永続表)。関数なら関数、`Null` は「IDL で null にした」(属性が残っていても無効)。
5//   表に無ければ content 属性(`onclick="…"`)を関数に直して表へ入れる(毎回別の関数にならないよう一度だけ)。
6//   属性が変わると `DomBridge::set_attr`/`remove_attr` が表の項目を消すので、次に読むときに作り直される。
7// - `<body>`/`<frameset>` の `onblur` など(`WINDOW_FORWARDED`)は window のハンドラへ転送する。
8use super::*;
9
10/// `<body>`/`<frameset>` が window へ転送するハンドラ名(GlobalEventHandlers のうち window 側に持つもの+WindowEventHandlers)。
11pub(crate) const WINDOW_FORWARDED: &[&str] = &[
12    "onafterprint",
13    "onbeforeprint",
14    "onbeforeunload",
15    "onblur",
16    "onerror",
17    "onfocus",
18    "onhashchange",
19    "onlanguagechange",
20    "onload",
21    "onmessage",
22    "onmessageerror",
23    "onoffline",
24    "ononline",
25    "onpagehide",
26    "onpageshow",
27    "onpopstate",
28    "onrejectionhandled",
29    "onresize",
30    "onscroll",
31    "onstorage",
32    "onunhandledrejection",
33    "onunload",
34];
35
36fn is_forwarding_tag(it: &Interp, idx: usize) -> bool {
37    it.dom().borrow().nodes.get(idx).is_some_and(|n| {
38        (n.tag == "body" || n.tag == "frameset")
39            && super::dom_ns::node_namespace(n).as_deref() == Some(super::dom_ns::HTML_NS)
40    })
41}
42
43/// この要素・この名前が window へ転送されるか。
44pub(crate) fn is_forwarded(it: &Interp, idx: usize, key: &str) -> bool {
45    WINDOW_FORWARDED.contains(&key) && is_forwarding_tag(it, idx)
46}
47
48fn is_callable(v: &Value) -> bool {
49    matches!(v, Value::Object(f) if f.borrow().is_callable())
50}
51
52/// content 属性の値を関数に直す(失敗なら `Null`)。`onerror` は 5 引数。
53fn compile(it: &mut Interp, key: &str, code: &str) -> Value {
54    let params = if key == "onerror" { "event, source, lineno, colno, error" } else { "event" };
55    let wrapped = alloc::format!("(function({}){{\n{}\n}})", params, code);
56    match it.eval_source(&wrapped) {
57        Ok(f) if is_callable(&f) => f,
58        _ => Value::Null,
59    }
60}
61
62fn window_obj(it: &Interp) -> Option<ObjRef> {
63    match it.global.borrow().vars.get("window") {
64        Some(Value::Object(w)) => Some(w.clone()),
65        _ => None,
66    }
67}
68
69/// `element.onXXX` の読み出し。
70pub(crate) fn handler_get(it: &mut Interp, idx: usize, key: &str) -> Value {
71    if is_forwarded(it, idx, key) {
72        return match window_obj(it).and_then(|w| w.borrow().props.get(key).cloned()) {
73            Some(v) if is_callable(&v) => v,
74            _ => Value::Null,
75        };
76    }
77    let stored = it.dom().borrow().get_on_handler(idx, key);
78    match stored {
79        Some(v) if is_callable(&v) => return v,
80        Some(Value::Null) => return Value::Null,
81        _ => {}
82    }
83    let attr = it.dom().borrow().get_attr(idx, key);
84    match attr {
85        Some(code) => {
86            let f = compile(it, key, &code);
87            it.dom().borrow_mut().set_on_handler(idx, key, f.clone());
88            f
89        }
90        None => Value::Null,
91    }
92}
93
94/// `element.onXXX = value`。関数以外は `null`。
95pub(crate) fn handler_set(it: &mut Interp, idx: usize, key: &str, val: Value) {
96    let v = if is_callable(&val) { val } else { Value::Null };
97    if is_forwarded(it, idx, key) {
98        if let Some(w) = window_obj(it) {
99            w.borrow_mut().props.insert(String::from(key).into(), v);
100        }
101        return;
102    }
103    it.dom().borrow_mut().set_on_handler(idx, key, v);
104}
105
106/// content 属性 `name` が設定(`Some(値)`)・削除(`None`)された後の処理。`<body>`/`<frameset>` なら window のハンドラへ反映する。
107pub(crate) fn attr_changed(it: &mut Interp, idx: usize, name: &str, value: Option<&str>) {
108    if !name.starts_with("on") || !is_forwarded(it, idx, name) {
109        return;
110    }
111    let f = match value {
112        Some(code) => compile(it, name, code),
113        None => Value::Null,
114    };
115    if let Some(w) = window_obj(it) {
116        w.borrow_mut().props.insert(String::from(name).into(), f);
117    }
118}
119
120/// `HTMLBodyElement.prototype`/`HTMLFrameSetElement.prototype` に転送ハンドラの名前を列挙可能な自分のプロパティとして置く
121/// (`for (k in body)` で見える。値の読み書きは要素側が受け持つ)。
122pub(crate) fn install_forwarded_names(proto: &ObjRef) {
123    let mut p = proto.borrow_mut();
124    for name in WINDOW_FORWARDED {
125        p.props.insert(String::from(*name).into(), Value::Null);
126    }
127}