1use super::*;
4
5pub(crate) fn event_prevent_default(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
9 if let Value::Object(o) = &this {
10 let (cancelable, in_passive) = {
11 let b = o.borrow();
12 (
13 matches!(b.props.get("cancelable"), Some(Value::Bool(true))),
14 matches!(b.props.get("_inPassiveListener"), Some(Value::Bool(true))),
15 )
16 };
17 if cancelable && !in_passive {
18 let mut b = o.borrow_mut();
19 b.props.insert("defaultPrevented".into(), Value::Bool(true));
20 }
21 }
22 Ok(Value::Undefined)
23}
24
25pub(crate) fn event_target_stop_propagation(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
27 if let Value::Object(o) = &this {
28 let mut b = o.borrow_mut();
29 b.props.insert("_stop".into(), Value::Bool(true));
30 }
31 Ok(Value::Undefined)
32}
33
34pub(crate) fn event_stop_immediate_propagation(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
36 if let Value::Object(o) = &this {
37 let mut b = o.borrow_mut();
38 b.props.insert("_stop".into(), Value::Bool(true));
39 b.props.insert("_stopImmediate".into(), Value::Bool(true));
40 }
41 Ok(Value::Undefined)
42}
43
44pub(crate) fn event_cancel_bubble_get(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
45 let v = match &this {
46 Value::Object(o) => o.borrow().props.get("_stop").is_some_and(|v| v.truthy()),
47 _ => false,
48 };
49 Ok(Value::Bool(v))
50}
51
52pub(crate) fn event_cancel_bubble_set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
53 if arg(a, 0).truthy() {
54 let _ = event_target_stop_propagation(it, this, &[]);
55 }
56 Ok(Value::Undefined)
57}
58
59pub(crate) fn event_return_value_get(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
60 let v = match &this {
61 Value::Object(o) => !o.borrow().props.get("defaultPrevented").is_some_and(|v| v.truthy()),
62 _ => true,
63 };
64 Ok(Value::Bool(v))
65}
66
67pub(crate) fn event_return_value_set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
68 if !arg(a, 0).truthy() {
69 let _ = event_prevent_default(it, this, &[]);
70 }
71 Ok(Value::Undefined)
72}
73
74pub(crate) fn event_is_trusted_get(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
75 let v = match &this {
76 Value::Object(o) => o.borrow().props.get("_isTrusted").is_some_and(|v| v.truthy()),
77 _ => false,
78 };
79 Ok(Value::Bool(v))
80}
81
82fn event_is_trusted_getter(it: &mut Interp) -> Value {
86 let cached = it.global.borrow().vars.get("__event_isTrusted_get").cloned();
87 if let Some(f @ Value::Object(_)) = cached {
88 return f;
89 }
90 let f = nv("get isTrusted", event_is_trusted_get);
91 it.global.borrow_mut().vars.insert("__event_isTrusted_get".into(), f.clone());
92 f
93}
94
95const EVENT_TS_RESOLUTION_US: u64 = 5;
97
98fn event_timestamp() -> f64 {
102 let us = libm::round(next_perf_timestamp() * 1000.0) as u64;
103 let coarse = us.div_ceil(EVENT_TS_RESOLUTION_US) * EVENT_TS_RESOLUTION_US;
104 PERF_TS.fetch_max(coarse, Ordering::Relaxed);
105 coarse as f64 / 1000.0
106}
107
108pub(crate) fn event_target_composed_path(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
110 if let Value::Object(o) = &this {
111 let b = o.borrow();
112 if let Some(p) = b.props.get("_composedPath") {
113 if matches!(b.props.get("_dispatch"), Some(Value::Bool(true))) {
114 return Ok(p.clone());
115 }
116 }
117 if matches!(b.props.get("_dispatch"), Some(Value::Bool(true))) {
118 if let Some(t) = b.props.get("target") {
119 if !matches!(t, Value::Undefined | Value::Null) {
120 return Ok(Value::Object(Obj::array(alloc::vec![t.clone()])));
121 }
122 }
123 }
124 }
125 Ok(Value::Object(Obj::array(alloc::vec::Vec::new())))
126}
127
128fn require_new_event(it: &mut Interp, name: &str, this: Value) -> Result<ObjRef, Value> {
130 if it.take_pending_new_target().is_none() {
131 return Err(it.type_error(alloc::format!(
132 "Failed to construct '{}': Please use the 'new' operator, this DOM object constructor cannot be called as a function.",
133 name
134 )));
135 }
136 Ok(match this {
137 Value::Object(o) => o,
138 _ => Obj::plain(),
139 })
140}
141
142fn require_event_type(it: &mut Interp, name: &str, a: &[Value]) -> Result<String, Value> {
144 if a.is_empty() {
145 return Err(it.type_error(alloc::format!(
146 "Failed to construct '{}': 1 argument required, but only 0 present.",
147 name
148 )));
149 }
150 let prim = it.to_primitive(arg(a, 0), "string")?;
151 Ok(prim.to_js_string())
152}
153
154fn validate_event_dict(it: &mut Interp, options: &Value) -> Result<(), Value> {
156 match options {
157 Value::Undefined | Value::Null | Value::Object(_) => Ok(()),
158 _ => Err(it.type_error("The provided value is not of type 'EventInit'.")),
159 }
160}
161
162fn dict_get(it: &mut Interp, options: &Value, key: &str) -> Result<Option<Value>, Value> {
164 if !matches!(options, Value::Object(_)) {
165 return Ok(None);
166 }
167 let v = it.get_property(options, key)?;
168 if matches!(v, Value::Undefined) {
169 Ok(None)
170 } else {
171 Ok(Some(v))
172 }
173}
174
175fn dict_bool(it: &mut Interp, options: &Value, key: &str, default: bool) -> Result<bool, Value> {
176 Ok(dict_get(it, options, key)?.map(|v| v.truthy()).unwrap_or(default))
177}
178
179fn dict_num(it: &mut Interp, options: &Value, key: &str, default: f64) -> Result<Value, Value> {
180 Ok(match dict_get(it, options, key)? {
181 Some(v) => Value::Number(v.to_number()),
182 None => Value::Number(default),
183 })
184}
185
186fn dict_str(it: &mut Interp, options: &Value, key: &str, default: &str) -> Result<Value, Value> {
187 Ok(match dict_get(it, options, key)? {
188 Some(v) => Value::str(it.to_primitive(v, "string")?.to_js_string()),
189 None => Value::str(default),
190 })
191}
192
193fn dict_nullable_obj(it: &mut Interp, options: &Value, key: &str) -> Result<Value, Value> {
194 Ok(match dict_get(it, options, key)? {
195 Some(Value::Null) | None => Value::Null,
196 Some(v @ Value::Object(_)) => v,
197 Some(_) => return Err(it.type_error(alloc::format!("Failed to convert '{}' member to Object.", key))),
198 })
199}
200
201fn init_event_base(it: &mut Interp, ev: &ObjRef, event_type: &str, options: &Value) -> Result<(), Value> {
203 let bubbles = dict_bool(it, options, "bubbles", false)?;
204 let cancelable = dict_bool(it, options, "cancelable", false)?;
205 let composed = dict_bool(it, options, "composed", false)?;
206 let is_trusted_get = event_is_trusted_getter(it);
207 let mut b = ev.borrow_mut();
208 b.props.insert("_isEvent".into(), Value::Bool(true));
209 b.props.insert("_initialized".into(), Value::Bool(true));
210 b.props.insert("type".into(), Value::str(event_type));
211 b.props.insert("bubbles".into(), Value::Bool(bubbles));
212 b.props.insert("cancelable".into(), Value::Bool(cancelable));
213 b.props.insert("composed".into(), Value::Bool(composed));
214 b.props.insert("defaultPrevented".into(), Value::Bool(false));
215 b.props.insert("_isTrusted".into(), Value::Bool(false));
216 b.insert_accessor(
217 String::from("isTrusted"),
218 Accessor {
219 get: Some(is_trusted_get),
220 set: None,
221 },
222 );
223 b.insert_attr("isTrusted", PropertyAttributes { writable: false, configurable: false, enumerable: true });
225 b.props.insert("target".into(), Value::Null);
226 b.props.insert("srcElement".into(), Value::Null);
227 b.props.insert("currentTarget".into(), Value::Null);
228 b.props.insert("eventPhase".into(), Value::Number(0.0));
229 b.props.insert("timeStamp".into(), Value::Number(event_timestamp()));
230 b.props.insert("preventDefault".into(), nv("preventDefault", event_prevent_default));
231 b.props.insert("stopPropagation".into(), nv("stopPropagation", event_target_stop_propagation));
232 b.props.insert("stopImmediatePropagation".into(), nv("stopImmediatePropagation", event_stop_immediate_propagation));
233 b.props.insert("composedPath".into(), nv("composedPath", event_target_composed_path));
234 Ok(())
235}
236
237pub(crate) fn win_event_get(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
239 let w = match this {
240 Value::Object(o) => o,
241 _ => match it.global.borrow().vars.get("window") {
242 Some(Value::Object(o)) => o.clone(),
243 _ => return Ok(Value::Undefined),
244 },
245 };
246 let wb = w.borrow();
247 if wb.props.get("_event_replaced").is_some_and(|v| v.truthy()) {
248 return Ok(wb.props.get("_event_replaced_val").cloned().unwrap_or(Value::Undefined));
249 }
250 Ok(wb.props.get("_current_event").cloned().unwrap_or(Value::Undefined))
251}
252
253pub(crate) fn win_event_set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
255 let w = match this {
256 Value::Object(o) => o,
257 _ => match it.global.borrow().vars.get("window") {
258 Some(Value::Object(o)) => o.clone(),
259 _ => return Ok(Value::Undefined),
260 },
261 };
262 let v = arg(a, 0);
263 let mut wb = w.borrow_mut();
264 wb.props.insert("_event_replaced".into(), Value::Bool(true));
265 wb.props.insert("_event_replaced_val".into(), v.clone());
266 Ok(v)
267}
268
269pub(crate) fn swap_window_event(it: &mut Interp, new_val: Value) -> Option<Value> {
271 let w = match it.global.borrow().vars.get("window") {
272 Some(Value::Object(w)) => w.clone(),
273 _ => return None,
274 };
275 let mut wb = w.borrow_mut();
276 let prev = wb.props.get("_current_event").cloned().unwrap_or(Value::Undefined);
277 wb.props.insert("_current_event".into(), new_val);
278 Some(prev)
279}
280
281pub(crate) fn restore_window_event(it: &mut Interp, prev: Option<Value>) {
283 let Some(prev) = prev else { return };
284 if let Some(Value::Object(w)) = it.global.borrow().vars.get("window").cloned() {
285 w.borrow_mut().props.insert("_current_event".into(), prev);
286 }
287}
288
289fn init_ui_event_props(it: &mut Interp, ev: &ObjRef, options: &Value) -> Result<(), Value> {
291 let view = dict_nullable_obj(it, options, "view")?;
292 let detail = dict_num(it, options, "detail", 0.0)?;
293 let mut b = ev.borrow_mut();
294 b.props.insert("view".into(), view);
295 b.props.insert("detail".into(), detail);
296 Ok(())
297}
298
299fn init_modifier_props(it: &mut Interp, ev: &ObjRef, options: &Value) -> Result<(), Value> {
301 for k in ["ctrlKey", "shiftKey", "altKey", "metaKey"] {
302 let v = dict_bool(it, options, k, false)?;
303 ev.borrow_mut().props.insert(k.into(), Value::Bool(v));
304 }
305 Ok(())
306}
307
308fn init_mouse_event_props(it: &mut Interp, ev: &ObjRef, options: &Value) -> Result<(), Value> {
310 init_modifier_props(it, ev, options)?;
311 for k in ["screenX", "screenY", "clientX", "clientY", "movementX", "movementY", "button", "buttons"] {
312 let v = dict_num(it, options, k, 0.0)?;
313 ev.borrow_mut().props.insert(k.into(), v);
314 }
315 let related = dict_nullable_obj(it, options, "relatedTarget")?;
316 ev.borrow_mut().props.insert("relatedTarget".into(), related);
317 Ok(())
318}
319
320pub(crate) fn event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
321 let ev = require_new_event(it, "Event", t)?;
322 let event_type = require_event_type(it, "Event", a)?;
323 let options = arg(a, 1);
324 validate_event_dict(it, &options)?;
325 init_event_base(it, &ev, &event_type, &options)?;
326 Ok(Value::Object(ev))
327}
328
329pub(crate) fn event_new_internal(it: &mut Interp, event_type: &str) -> Result<Value, Value> {
332 let ctor = it.global.borrow().vars.get("Event").cloned();
333 match ctor {
334 Some(c @ Value::Object(_)) => it.construct_with_target(&c, &[Value::str(event_type)], &c),
335 _ => Err(it.type_error("Event is not defined")),
336 }
337}
338
339pub(crate) fn ui_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
340 let ev = require_new_event(it, "UIEvent", t)?;
341 let event_type = require_event_type(it, "UIEvent", a)?;
342 let options = arg(a, 1);
343 validate_event_dict(it, &options)?;
344 init_event_base(it, &ev, &event_type, &options)?;
345 init_ui_event_props(it, &ev, &options)?;
346 Ok(Value::Object(ev))
347}
348
349pub(crate) fn keyboard_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
350 let ev = require_new_event(it, "KeyboardEvent", t)?;
351 let event_type = require_event_type(it, "KeyboardEvent", a)?;
352 let options = arg(a, 1);
353 validate_event_dict(it, &options)?;
354 init_event_base(it, &ev, &event_type, &options)?;
355 init_ui_event_props(it, &ev, &options)?;
356 init_modifier_props(it, &ev, &options)?;
357 let key = dict_str(it, &options, "key", "")?;
358 let code = dict_str(it, &options, "code", "")?;
359 let location = dict_num(it, &options, "location", 0.0)?;
360 let repeat = dict_bool(it, &options, "repeat", false)?;
361 let is_composing = dict_bool(it, &options, "isComposing", false)?;
362 let char_code = dict_num(it, &options, "charCode", 0.0)?;
363 let key_code = dict_num(it, &options, "keyCode", 0.0)?;
364 let which = dict_num(it, &options, "which", 0.0)?;
365 {
366 let mut b = ev.borrow_mut();
367 b.props.insert("key".into(), key);
368 b.props.insert("code".into(), code);
369 b.props.insert("location".into(), location);
370 b.props.insert("repeat".into(), Value::Bool(repeat));
371 b.props.insert("isComposing".into(), Value::Bool(is_composing));
372 b.props.insert("charCode".into(), char_code);
373 b.props.insert("keyCode".into(), key_code);
374 b.props.insert("which".into(), which);
375 }
376 Ok(Value::Object(ev))
377}
378
379pub(crate) fn mouse_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
380 let ev = require_new_event(it, "MouseEvent", t)?;
381 let event_type = require_event_type(it, "MouseEvent", a)?;
382 let options = arg(a, 1);
383 validate_event_dict(it, &options)?;
384 init_event_base(it, &ev, &event_type, &options)?;
385 init_ui_event_props(it, &ev, &options)?;
386 init_mouse_event_props(it, &ev, &options)?;
387 Ok(Value::Object(ev))
388}
389
390pub(crate) fn gamepad_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
391 let ev = require_new_event(it, "GamepadEvent", t)?;
392 let event_type = require_event_type(it, "GamepadEvent", a)?;
393 let options = arg(a, 1);
394 validate_event_dict(it, &options)?;
395 init_event_base(it, &ev, &event_type, &options)?;
396 let gamepad = dict_get(it, &options, "gamepad")?.unwrap_or(Value::Null);
397 ev.borrow_mut().props.insert("gamepad".into(), gamepad);
398 Ok(Value::Object(ev))
399}
400
401pub(crate) fn wheel_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
402 let ev = require_new_event(it, "WheelEvent", t)?;
403 let event_type = require_event_type(it, "WheelEvent", a)?;
404 let options = arg(a, 1);
405 validate_event_dict(it, &options)?;
406 init_event_base(it, &ev, &event_type, &options)?;
407 init_ui_event_props(it, &ev, &options)?;
408 init_mouse_event_props(it, &ev, &options)?;
409 for k in ["deltaX", "deltaY", "deltaZ", "deltaMode"] {
410 let v = dict_num(it, &options, k, 0.0)?;
411 ev.borrow_mut().props.insert(k.into(), v);
412 }
413 Ok(Value::Object(ev))
414}
415pub(crate) fn touch_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
421 let options = arg(a, 0);
422 let o = Obj::plain();
423 {
424 let mut b = o.borrow_mut();
425 b.props.insert(
426 "identifier".into(),
427 obj_prop(&options, "identifier").unwrap_or(Value::Number(0.0)),
428 );
429 b.props
430 .insert("target".into(), obj_prop(&options, "target").unwrap_or(Value::Null));
431 for k in ["clientX", "clientY", "pageX", "pageY", "screenX", "screenY"] {
432 b.props.insert(k.into(), obj_prop(&options, k).unwrap_or(Value::Number(0.0)));
433 }
434 b.props
435 .insert("radiusX".into(), obj_prop(&options, "radiusX").unwrap_or(Value::Number(25.0)));
436 b.props
437 .insert("radiusY".into(), obj_prop(&options, "radiusY").unwrap_or(Value::Number(25.0)));
438 b.props.insert(
439 "rotationAngle".into(),
440 obj_prop(&options, "rotationAngle").unwrap_or(Value::Number(0.0)),
441 );
442 b.props
443 .insert("force".into(), obj_prop(&options, "force").unwrap_or(Value::Number(1.0)));
444 }
445 Ok(Value::Object(o))
446}
447pub(crate) fn touch_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
452 let ev = require_new_event(it, "TouchEvent", t)?;
453 let event_type = require_event_type(it, "TouchEvent", a)?;
454 let options = arg(a, 1);
455 validate_event_dict(it, &options)?;
456 init_event_base(it, &ev, &event_type, &options)?;
457 init_ui_event_props(it, &ev, &options)?;
458 init_modifier_props(it, &ev, &options)?;
459 for k in ["touches", "targetTouches", "changedTouches"] {
460 let v = dict_get(it, &options, k)?.unwrap_or_else(|| Value::Object(Obj::array(alloc::vec![])));
461 ev.borrow_mut().props.insert(k.into(), v);
462 }
463 Ok(Value::Object(ev))
464}
465
466pub(crate) fn focus_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
467 let ev = require_new_event(it, "FocusEvent", t)?;
468 let event_type = require_event_type(it, "FocusEvent", a)?;
469 let options = arg(a, 1);
470 validate_event_dict(it, &options)?;
471 init_event_base(it, &ev, &event_type, &options)?;
472 init_ui_event_props(it, &ev, &options)?;
473 let related = dict_nullable_obj(it, &options, "relatedTarget")?;
474 ev.borrow_mut().props.insert("relatedTarget".into(), related);
475 Ok(Value::Object(ev))
476}
477
478pub(crate) fn pointer_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
479 let ev = require_new_event(it, "PointerEvent", t)?;
480 let event_type = require_event_type(it, "PointerEvent", a)?;
481 let options = arg(a, 1);
482 validate_event_dict(it, &options)?;
483 init_event_base(it, &ev, &event_type, &options)?;
484 init_ui_event_props(it, &ev, &options)?;
485 init_mouse_event_props(it, &ev, &options)?;
486 let pointer_id = dict_num(it, &options, "pointerId", 0.0)?;
487 let width = dict_num(it, &options, "width", 1.0)?;
488 let height = dict_num(it, &options, "height", 1.0)?;
489 let pointer_type = dict_str(it, &options, "pointerType", "")?;
490 let is_primary = dict_bool(it, &options, "isPrimary", false)?;
491 for k in ["pressure", "tangentialPressure", "tiltX", "tiltY", "twist"] {
492 let v = dict_num(it, &options, k, 0.0)?;
493 ev.borrow_mut().props.insert(k.into(), v);
494 }
495 {
496 let mut b = ev.borrow_mut();
497 b.props.insert("pointerId".into(), pointer_id);
498 b.props.insert("width".into(), width);
499 b.props.insert("height".into(), height);
500 b.props.insert("pointerType".into(), pointer_type);
501 b.props.insert("isPrimary".into(), Value::Bool(is_primary));
502 }
503 Ok(Value::Object(ev))
504}
505
506pub(crate) fn input_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
507 let ev = require_new_event(it, "InputEvent", t)?;
508 let event_type = require_event_type(it, "InputEvent", a)?;
509 let options = arg(a, 1);
510 validate_event_dict(it, &options)?;
511 init_event_base(it, &ev, &event_type, &options)?;
512 init_ui_event_props(it, &ev, &options)?;
513 let data = match dict_get(it, &options, "data")? {
514 Some(Value::Null) | None => Value::Null,
515 Some(v) => Value::str(it.to_primitive(v, "string")?.to_js_string()),
516 };
517 let input_type = dict_str(it, &options, "inputType", "")?;
518 let is_composing = dict_bool(it, &options, "isComposing", false)?;
519 {
520 let mut b = ev.borrow_mut();
521 b.props.insert("data".into(), data);
522 b.props.insert("inputType".into(), input_type);
523 b.props.insert("isComposing".into(), Value::Bool(is_composing));
524 }
525 Ok(Value::Object(ev))
526}
527
528pub(crate) fn progress_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
529 let ev = require_new_event(it, "ProgressEvent", t)?;
530 let event_type = require_event_type(it, "ProgressEvent", a)?;
531 let options = arg(a, 1);
532 validate_event_dict(it, &options)?;
533 init_event_base(it, &ev, &event_type, &options)?;
534 let lc = dict_bool(it, &options, "lengthComputable", false)?;
535 let loaded = dict_num(it, &options, "loaded", 0.0)?;
536 let total = dict_num(it, &options, "total", 0.0)?;
537 {
538 let mut b = ev.borrow_mut();
539 b.props.insert("lengthComputable".into(), Value::Bool(lc));
540 b.props.insert("loaded".into(), loaded);
541 b.props.insert("total".into(), total);
542 }
543 Ok(Value::Object(ev))
544}
545
546pub(crate) fn storage_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
547 let ev = require_new_event(it, "StorageEvent", t)?;
548 let event_type = require_event_type(it, "StorageEvent", a)?;
549 let options = arg(a, 1);
550 validate_event_dict(it, &options)?;
551 init_event_base(it, &ev, &event_type, &options)?;
552 let key = dict_get(it, &options, "key")?.unwrap_or(Value::Null);
553 let old_val = dict_get(it, &options, "oldValue")?.unwrap_or(Value::Null);
554 let new_val = dict_get(it, &options, "newValue")?.unwrap_or(Value::Null);
555 let url = dict_str(it, &options, "url", "")?;
556 let area = dict_get(it, &options, "storageArea")?.unwrap_or(Value::Null);
557 {
558 let mut b = ev.borrow_mut();
559 b.props.insert("key".into(), key);
560 b.props.insert("oldValue".into(), old_val);
561 b.props.insert("newValue".into(), new_val);
562 b.props.insert("url".into(), url);
563 b.props.insert("storageArea".into(), area);
564 }
565 Ok(Value::Object(ev))
566}
567
568pub(crate) fn pop_state_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
569 let ev = require_new_event(it, "PopStateEvent", t)?;
570 let event_type = require_event_type(it, "PopStateEvent", a)?;
571 let options = arg(a, 1);
572 validate_event_dict(it, &options)?;
573 init_event_base(it, &ev, &event_type, &options)?;
574 let state = dict_get(it, &options, "state")?.unwrap_or(Value::Null);
575 ev.borrow_mut().props.insert("state".into(), state);
576 Ok(Value::Object(ev))
577}
578
579pub(crate) fn hash_change_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
580 let ev = require_new_event(it, "HashChangeEvent", t)?;
581 let event_type = require_event_type(it, "HashChangeEvent", a)?;
582 let options = arg(a, 1);
583 validate_event_dict(it, &options)?;
584 init_event_base(it, &ev, &event_type, &options)?;
585 let old_url = dict_str(it, &options, "oldURL", "")?;
586 let new_url = dict_str(it, &options, "newURL", "")?;
587 {
588 let mut b = ev.borrow_mut();
589 b.props.insert("oldURL".into(), old_url);
590 b.props.insert("newURL".into(), new_url);
591 }
592 Ok(Value::Object(ev))
593}
594
595pub(crate) fn page_transition_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
596 let ev = require_new_event(it, "PageTransitionEvent", t)?;
597 let event_type = require_event_type(it, "PageTransitionEvent", a)?;
598 let options = arg(a, 1);
599 validate_event_dict(it, &options)?;
600 init_event_base(it, &ev, &event_type, &options)?;
601 let persisted = dict_bool(it, &options, "persisted", false)?;
602 ev.borrow_mut().props.insert("persisted".into(), Value::Bool(persisted));
603 Ok(Value::Object(ev))
604}
605
606pub(crate) fn composition_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
607 let ev = require_new_event(it, "CompositionEvent", t)?;
608 let event_type = require_event_type(it, "CompositionEvent", a)?;
609 let options = arg(a, 1);
610 validate_event_dict(it, &options)?;
611 init_event_base(it, &ev, &event_type, &options)?;
612 init_ui_event_props(it, &ev, &options)?;
613 let data = dict_str(it, &options, "data", "")?;
614 ev.borrow_mut().props.insert("data".into(), data);
615 Ok(Value::Object(ev))
616}
617
618pub(crate) fn clipboard_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
619 let ev = require_new_event(it, "ClipboardEvent", t)?;
620 let event_type = require_event_type(it, "ClipboardEvent", a)?;
621 let options = arg(a, 1);
622 validate_event_dict(it, &options)?;
623 init_event_base(it, &ev, &event_type, &options)?;
624 let cd = dict_get(it, &options, "clipboardData")?.unwrap_or(Value::Null);
625 ev.borrow_mut().props.insert("clipboardData".into(), cd);
626 Ok(Value::Object(ev))
627}
628
629pub(crate) fn animation_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
630 let ev = require_new_event(it, "AnimationEvent", t)?;
631 let event_type = require_event_type(it, "AnimationEvent", a)?;
632 let options = arg(a, 1);
633 validate_event_dict(it, &options)?;
634 init_event_base(it, &ev, &event_type, &options)?;
635 let name = dict_str(it, &options, "animationName", "")?;
636 let elapsed = dict_num(it, &options, "elapsedTime", 0.0)?;
637 let pseudo = dict_str(it, &options, "pseudoElement", "")?;
638 {
639 let mut b = ev.borrow_mut();
640 b.props.insert("animationName".into(), name);
641 b.props.insert("elapsedTime".into(), elapsed);
642 b.props.insert("pseudoElement".into(), pseudo);
643 }
644 Ok(Value::Object(ev))
645}
646
647pub(crate) fn transition_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
648 let ev = require_new_event(it, "TransitionEvent", t)?;
649 let event_type = require_event_type(it, "TransitionEvent", a)?;
650 let options = arg(a, 1);
651 validate_event_dict(it, &options)?;
652 init_event_base(it, &ev, &event_type, &options)?;
653 let name = dict_str(it, &options, "propertyName", "")?;
654 let elapsed = dict_num(it, &options, "elapsedTime", 0.0)?;
655 let pseudo = dict_str(it, &options, "pseudoElement", "")?;
656 {
657 let mut b = ev.borrow_mut();
658 b.props.insert("propertyName".into(), name);
659 b.props.insert("elapsedTime".into(), elapsed);
660 b.props.insert("pseudoElement".into(), pseudo);
661 }
662 Ok(Value::Object(ev))
663}
664
665pub(crate) fn drag_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
666 let ev = require_new_event(it, "DragEvent", t)?;
667 let event_type = require_event_type(it, "DragEvent", a)?;
668 let options = arg(a, 1);
669 validate_event_dict(it, &options)?;
670 init_event_base(it, &ev, &event_type, &options)?;
671 init_ui_event_props(it, &ev, &options)?;
672 init_mouse_event_props(it, &ev, &options)?;
673 let dt = dict_get(it, &options, "dataTransfer")?.unwrap_or(Value::Null);
674 ev.borrow_mut().props.insert("dataTransfer".into(), dt);
675 Ok(Value::Object(ev))
676}
677
678pub(crate) fn submit_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
679 let ev = require_new_event(it, "SubmitEvent", t)?;
680 let event_type = require_event_type(it, "SubmitEvent", a)?;
681 let options = arg(a, 1);
682 validate_event_dict(it, &options)?;
683 init_event_base(it, &ev, &event_type, &options)?;
684 let sub = dict_get(it, &options, "submitter")?.unwrap_or(Value::Null);
685 ev.borrow_mut().props.insert("submitter".into(), sub);
686 Ok(Value::Object(ev))
687}
688
689pub(crate) fn message_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
690 let ev = require_new_event(it, "MessageEvent", t)?;
691 let event_type = require_event_type(it, "MessageEvent", a)?;
692 let options = arg(a, 1);
693 validate_event_dict(it, &options)?;
694 init_event_base(it, &ev, &event_type, &options)?;
695 let data = dict_get(it, &options, "data")?.unwrap_or(Value::Null);
696 let origin = dict_str(it, &options, "origin", "")?;
697 let last_id = dict_str(it, &options, "lastEventId", "")?;
698 let source = dict_get(it, &options, "source")?.unwrap_or(Value::Null);
699 let ports = dict_get(it, &options, "ports")?.unwrap_or_else(|| Value::Object(Obj::array(alloc::vec::Vec::new())));
700 {
701 let mut b = ev.borrow_mut();
702 b.props.insert("data".into(), data);
703 b.props.insert("origin".into(), origin);
704 b.props.insert("lastEventId".into(), last_id);
705 b.props.insert("source".into(), source);
706 b.props.insert("ports".into(), ports);
707 }
708 Ok(Value::Object(ev))
709}
710
711pub(crate) fn error_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
712 let ev = require_new_event(it, "ErrorEvent", t)?;
713 let event_type = require_event_type(it, "ErrorEvent", a)?;
714 let options = arg(a, 1);
715 validate_event_dict(it, &options)?;
716 init_event_base(it, &ev, &event_type, &options)?;
717 let msg = dict_str(it, &options, "message", "")?;
718 let filename = dict_str(it, &options, "filename", "")?;
719 let lineno = dict_num(it, &options, "lineno", 0.0)?;
720 let colno = dict_num(it, &options, "colno", 0.0)?;
721 let err = dict_get(it, &options, "error")?.unwrap_or(Value::Null);
722 {
723 let mut b = ev.borrow_mut();
724 b.props.insert("message".into(), msg);
725 b.props.insert("filename".into(), filename);
726 b.props.insert("lineno".into(), lineno);
727 b.props.insert("colno".into(), colno);
728 b.props.insert("error".into(), err);
729 }
730 Ok(Value::Object(ev))
731}
732
733pub(crate) fn promise_rejection_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
734 let ev = require_new_event(it, "PromiseRejectionEvent", t)?;
735 let event_type = require_event_type(it, "PromiseRejectionEvent", a)?;
736 let options = arg(a, 1);
737 validate_event_dict(it, &options)?;
738 init_event_base(it, &ev, &event_type, &options)?;
739 let promise = dict_get(it, &options, "promise")?.unwrap_or(Value::Undefined);
740 let reason = dict_get(it, &options, "reason")?.unwrap_or(Value::Undefined);
741 {
742 let mut b = ev.borrow_mut();
743 b.props.insert("promise".into(), promise);
744 b.props.insert("reason".into(), reason);
745 }
746 Ok(Value::Object(ev))
747}
748
749pub(crate) fn custom_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
750 let ev = require_new_event(it, "CustomEvent", t)?;
751 let event_type = require_event_type(it, "CustomEvent", a)?;
752 let options = arg(a, 1);
753 validate_event_dict(it, &options)?;
754 init_event_base(it, &ev, &event_type, &options)?;
755 let detail = dict_get(it, &options, "detail")?.unwrap_or(Value::Null);
756 ev.borrow_mut().props.insert("detail".into(), detail);
757 Ok(Value::Object(ev))
758}
759
760pub(crate) fn event_target_ctor(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
762 let o = require_new_event(it, "EventTarget", t)?;
763 Ok(event_target_init(o))
764}
765pub(crate) fn event_target_new(_it: &mut Interp) -> Value {
769 event_target_init(Obj::plain())
770}
771fn event_target_init(o: crate::os_lib::ecma::value::ObjRef) -> Value {
772 {
773 let mut b = o.borrow_mut();
774 b.props.insert("_listeners".into(), Value::Object(Obj::plain()));
775 b.props.insert(
776 "addEventListener".into(),
777 nv("addEventListener", event_target_add_event_listener),
778 );
779 b.props.insert(
780 "removeEventListener".into(),
781 nv("removeEventListener", event_target_remove_event_listener),
782 );
783 b.props
784 .insert("dispatchEvent".into(), nv("dispatchEvent", event_target_dispatch_event));
785 }
786 Value::Object(o)
787}
788pub(crate) fn event_target_listeners(this: &Value) -> Option<crate::os_lib::ecma::value::ObjRef> {
789 if let Value::Object(o) = this {
790 if let Some(Value::Object(l)) = o.borrow().props.get("_listeners") {
791 return Some(l.clone());
792 }
793 let l = Obj::plain();
794 o.borrow_mut().props.insert("_listeners".into(), Value::Object(l.clone()));
795 return Some(l);
796 }
797 None
798}
799pub(crate) fn event_target_listener_cb(entry: &Value) -> Value {
801 if let Value::Object(o) = entry {
802 if let ObjKind::Array(items) = &o.borrow().kind {
803 if let Some(cb) = items.first() {
804 return cb.clone();
805 }
806 }
807 }
808 entry.clone()
809}
810pub(crate) fn event_target_listener_once(entry: &Value) -> bool {
812 if let Value::Object(o) = entry {
813 if let ObjKind::Array(items) = &o.borrow().kind {
814 if let Some(v) = items.get(1) {
815 return v.truthy();
816 }
817 }
818 }
819 false
820}
821pub(crate) fn event_target_listener_aborted(entry: &Value) -> bool {
823 if let Value::Object(o) = entry {
824 if let ObjKind::Array(items) = &o.borrow().kind {
825 if let Some(sig) = items.get(2) {
826 return super::super::dom_bridge::is_signal_aborted(sig);
827 }
828 }
829 }
830 false
831}
832pub(crate) fn event_target_listener_capture(entry: &Value) -> bool {
834 if let Value::Object(o) = entry {
835 if let ObjKind::Array(items) = &o.borrow().kind {
836 if let Some(v) = items.get(3) {
837 return v.truthy();
838 }
839 }
840 }
841 false
842}
843pub(crate) fn event_target_listener_passive(entry: &Value) -> bool {
845 if let Value::Object(o) = entry {
846 if let ObjKind::Array(items) = &o.borrow().kind {
847 if let Some(v) = items.get(4) {
848 return v.truthy();
849 }
850 }
851 }
852 false
853}
854
855pub(crate) fn is_abort_signal(v: &Value) -> bool {
857 let Value::Object(o) = v else { return false };
858 let b = o.borrow();
859 b.props.contains_key("_is_abort_signal")
860 || (b.props.contains_key("aborted") && b.props.contains_key("throwIfAborted"))
861}
862
863pub(crate) fn parse_listener_opts_interp(
866 it: &mut Interp,
867 opt: &Value,
868 is_add: bool,
869 default_passive: bool,
870) -> Result<(bool, bool, bool, Option<Value>), Value> {
871 match opt {
872 Value::Undefined | Value::Null => Ok((false, false, default_passive, None)),
873 Value::Bool(b) => Ok((*b, false, default_passive, None)),
874 Value::Object(_) => {
875 let capture = it.get_property(opt, "capture")?.truthy();
876 if !is_add {
877 return Ok((capture, false, false, None));
878 }
879 let once = it.get_property(opt, "once")?.truthy();
880 let passive_val = it.get_property(opt, "passive")?;
881 let passive = if matches!(passive_val, Value::Undefined) {
882 default_passive
883 } else {
884 passive_val.truthy()
885 };
886 let sig_val = it.get_property(opt, "signal")?;
887 let signal = if matches!(sig_val, Value::Undefined) {
888 None
889 } else if is_abort_signal(&sig_val) {
890 Some(sig_val)
891 } else {
892 return Err(it.type_error("Failed to read the 'signal' property from 'AddEventListenerOptions': Failed to convert value to 'AbortSignal'."));
893 };
894 Ok((capture, once, passive, signal))
895 }
896 other => Ok((other.truthy(), false, default_passive, None)),
897 }
898}
899
900pub(crate) fn is_passive_by_default(it: &Interp, target: &Value, etype: &str) -> bool {
902 if !matches!(etype, "touchstart" | "touchmove" | "wheel" | "mousewheel") {
903 return false;
904 }
905 if let Value::Object(o) = target {
906 if it.is_window_obj(o) {
907 return true;
908 }
909 let g = it.global.borrow();
910 if let Some(Value::Object(doc)) = g.vars.get("document") {
911 if Rc::ptr_eq(o, doc) {
912 return true;
913 }
914 }
915 }
916 if let Some(idx) = this_dom_idx(target) {
917 let dom = it.dom().borrow();
918 if idx == 0 || dom.query("body") == Some(idx) {
919 return true;
920 }
921 }
922 false
923}
924
925pub(crate) fn invoke_event_listener(
928 it: &mut Interp,
929 listener: &Value,
930 default_this: Value,
931 ev: &Value,
932 ctx: &str,
933) {
934 let is_callable = matches!(listener, Value::Object(o) if o.borrow().is_callable());
935 let res = if is_callable {
936 it.call_value(listener, default_this, core::slice::from_ref(ev))
937 } else if matches!(listener, Value::Object(_)) {
938 match it.get_property(listener, "handleEvent") {
939 Ok(he) if matches!(&he, Value::Object(ho) if ho.borrow().is_callable()) => {
940 it.call_value(&he, listener.clone(), core::slice::from_ref(ev))
941 }
942 Ok(_) => Err(it.type_error("Property 'handleEvent' is not callable.")),
943 Err(e) => Err(e),
944 }
945 } else {
946 return;
947 };
948 if let Err(thrown) = res {
949 it.report_uncaught(ctx, &thrown);
950 let in_err = it
951 .global
952 .borrow()
953 .vars
954 .get("__in_error_dispatch")
955 .is_some_and(|v| v.truthy());
956 if !in_err {
957 it.global
958 .borrow_mut()
959 .vars
960 .insert("__in_error_dispatch".into(), Value::Bool(true));
961 super::window_api::report_error_quiet(it, thrown);
962 it.global.borrow_mut().vars.shift_remove("__in_error_dispatch");
963 }
964 }
965}
966
967pub(crate) fn validate_dispatch_event(it: &mut Interp, ev: &Value) -> Result<(), Value> {
969 let Value::Object(eo) = ev else {
970 return Err(it.type_error("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'."));
971 };
972 let b = eo.borrow();
973 if matches!(b.props.get("_initialized"), Some(Value::Bool(false))) {
974 return Err(it.dom_exception("InvalidStateError", "Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is uninitialized."));
975 }
976 if matches!(b.props.get("_dispatch"), Some(Value::Bool(true))) {
977 return Err(it.dom_exception("InvalidStateError", "Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched."));
978 }
979 Ok(())
980}
981
982pub(crate) fn event_target_add_event_listener(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
983 let etype = arg(a, 0).to_js_string();
984 let cb = arg(a, 1);
985 let default_passive = is_passive_by_default(it, &this, &etype);
986 let (capture, once, passive, signal) = parse_listener_opts_interp(it, &arg(a, 2), true, default_passive)?;
987 let Some(listeners) = event_target_listeners(&this) else { return Ok(Value::Undefined) };
988 if !matches!(cb, Value::Object(_)) {
989 return Ok(Value::Undefined);
990 }
991 if signal.as_ref().is_some_and(super::super::dom_bridge::is_signal_aborted) {
992 return Ok(Value::Undefined);
993 }
994 let entry = Value::Object(Obj::array(alloc::vec![
995 cb.clone(),
996 Value::Bool(once),
997 signal.unwrap_or(Value::Undefined),
998 Value::Bool(capture),
999 Value::Bool(passive)
1000 ]));
1001 let existing = listeners.borrow().props.get(&etype).cloned();
1002 match existing {
1003 Some(Value::Object(arr)) => {
1004 if let ObjKind::Array(items) = &mut arr.borrow_mut().kind {
1005 let dup = items.iter().any(|v| {
1006 match (&event_target_listener_cb(v), &cb) {
1007 (Value::Object(x), Value::Object(y)) => {
1008 Rc::ptr_eq(x, y) && event_target_listener_capture(v) == capture
1009 }
1010 _ => false,
1011 }
1012 });
1013 if !dup {
1014 items.push(entry);
1015 }
1016 }
1017 }
1018 _ => {
1019 listeners
1020 .borrow_mut()
1021 .props
1022 .insert(etype.into(), Value::Object(Obj::array(alloc::vec![entry])));
1023 }
1024 }
1025 Ok(Value::Undefined)
1026}
1027
1028pub(crate) fn event_target_remove_event_listener(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1029 let etype = arg(a, 0).to_js_string();
1030 let cb = arg(a, 1);
1031 let (capture, _, _, _) = parse_listener_opts_interp(it, &arg(a, 2), false, false)?;
1032 let Some(listeners) = event_target_listeners(&this) else { return Ok(Value::Undefined) };
1033 if let Some(Value::Object(arr)) = listeners.borrow().props.get(&etype).cloned() {
1034 if let ObjKind::Array(items) = &mut arr.borrow_mut().kind {
1035 items.retain(|v| match (&event_target_listener_cb(v), &cb) {
1036 (Value::Object(x), Value::Object(y)) => {
1037 !(Rc::ptr_eq(x, y) && event_target_listener_capture(v) == capture)
1038 }
1039 _ => true,
1040 });
1041 }
1042 }
1043 Ok(Value::Undefined)
1044}
1045
1046fn is_main_document_obj(it: &Interp, v: &Value) -> bool {
1048 let Value::Object(o) = v else { return false };
1049 matches!(it.global.borrow().vars.get("document"), Some(Value::Object(d)) if Rc::ptr_eq(o, d))
1050}
1051
1052fn set_current_target(ev: &Value, cur: &Value, phase: f64) {
1053 if let Value::Object(eo) = ev {
1054 let mut e = eo.borrow_mut();
1055 e.props.insert("currentTarget".into(), cur.clone());
1056 e.props.insert("eventPhase".into(), Value::Number(phase));
1057 }
1058}
1059
1060fn event_is_stopped(ev: &Value) -> bool {
1062 let Value::Object(eo) = ev else { return false };
1063 let b = eo.borrow();
1064 b.props.get("_stop").is_some_and(|v| v.truthy()) || b.props.get("_stopImmediate").is_some_and(|v| v.truthy())
1065}
1066
1067fn event_is_stopped_immediate(ev: &Value) -> bool {
1068 matches!(ev, Value::Object(eo) if matches!(eo.borrow().props.get("_stopImmediate"), Some(Value::Bool(true))))
1069}
1070
1071fn invoke_with_passive(it: &mut Interp, cb: &Value, this: Value, ev: &Value, passive: bool, ctx: &str) {
1073 if passive {
1074 if let Value::Object(eo) = ev {
1075 eo.borrow_mut().props.insert("_inPassiveListener".into(), Value::Bool(true));
1076 }
1077 }
1078 invoke_event_listener(it, cb, this, ev, ctx);
1079 if passive {
1080 if let Value::Object(eo) = ev {
1081 eo.borrow_mut().props.shift_remove("_inPassiveListener");
1082 }
1083 }
1084}
1085
1086fn fire_own_listeners_phase(
1092 it: &mut Interp,
1093 listeners: &ObjRef,
1094 this: &Value,
1095 ev: &Value,
1096 etype: &str,
1097 want_capture: bool,
1098) -> bool {
1099 let cbs = match listeners.borrow().props.get(etype) {
1100 Some(Value::Object(arr)) => match &arr.borrow().kind {
1101 ObjKind::Array(items) => items.clone(),
1102 _ => alloc::vec::Vec::new(),
1103 },
1104 _ => alloc::vec::Vec::new(),
1105 };
1106 let ctx = alloc::format!("{} listener (EventTarget)", etype);
1107 for entry in &cbs {
1108 if event_target_listener_capture(entry) != want_capture {
1109 continue;
1110 }
1111 if event_target_listener_aborted(entry) {
1112 continue;
1113 }
1114 let cb = event_target_listener_cb(entry);
1115 if event_target_listener_once(entry) {
1116 if let Some(Value::Object(arr)) = listeners.borrow().props.get(etype).cloned() {
1117 if let ObjKind::Array(items) = &mut arr.borrow_mut().kind {
1118 items.retain(|v| match (&event_target_listener_cb(v), &cb) {
1119 (Value::Object(x), Value::Object(y)) => {
1120 !(Rc::ptr_eq(x, y) && event_target_listener_capture(v) == want_capture)
1121 }
1122 _ => true,
1123 });
1124 }
1125 }
1126 }
1127 invoke_with_passive(it, &cb, this.clone(), ev, event_target_listener_passive(entry), &ctx);
1128 if event_is_stopped_immediate(ev) {
1129 return true;
1130 }
1131 }
1132 if !want_capture {
1133 let legacy: alloc::vec::Vec<Value> = match this {
1134 Value::Object(o) => match o.borrow().props.get(&alloc::format!("_listeners_{etype}")) {
1135 Some(Value::Object(arr)) => match &arr.borrow().kind {
1136 ObjKind::Array(items) => items.clone(),
1137 _ => alloc::vec::Vec::new(),
1138 },
1139 _ => alloc::vec::Vec::new(),
1140 },
1141 _ => alloc::vec::Vec::new(),
1142 };
1143 for cb in legacy {
1144 invoke_event_listener(it, &cb, this.clone(), ev, &ctx);
1145 if event_is_stopped_immediate(ev) {
1146 return true;
1147 }
1148 }
1149 }
1150 event_is_stopped(ev)
1151}
1152
1153fn fire_window_listeners_phase(it: &mut Interp, w: &ObjRef, ev: &Value, etype: &str, want_capture: bool) -> bool {
1155 let win_val = Value::Object(w.clone());
1156 let key = window_listener_key(etype);
1157 let entries = match w.borrow().props.get(key.as_str()) {
1158 Some(Value::Object(arr)) => match &arr.borrow().kind {
1159 ObjKind::Array(items) => items.clone(),
1160 _ => alloc::vec::Vec::new(),
1161 },
1162 _ => alloc::vec::Vec::new(),
1163 };
1164 set_current_target(ev, &win_val, if want_capture { 1.0 } else { 3.0 });
1165 if !want_capture {
1166 let on_handler = w.borrow().props.get(&alloc::format!("on{etype}")).cloned();
1167 if let Some(f) = on_handler.and_then(callable_or_none) {
1168 invoke_event_listener(it, &f, win_val.clone(), ev, "window.onhandler");
1169 }
1170 }
1171 let ctx = alloc::format!("{} listener (window)", etype);
1172 for entry in &entries {
1173 if window_listener_capture(entry) != want_capture || window_listener_aborted(entry) {
1174 continue;
1175 }
1176 let cb = event_target_listener_cb(entry);
1177 if window_listener_once(entry) {
1178 if let Some(Value::Object(arr)) = w.borrow().props.get(key.as_str()).cloned() {
1179 if let ObjKind::Array(items) = &mut arr.borrow_mut().kind {
1180 items.retain(|v| match (&event_target_listener_cb(v), &cb) {
1181 (Value::Object(x), Value::Object(y)) => {
1182 !(Rc::ptr_eq(x, y) && window_listener_capture(v) == want_capture)
1183 }
1184 _ => true,
1185 });
1186 }
1187 }
1188 }
1189 invoke_with_passive(it, &cb, win_val.clone(), ev, window_listener_passive(entry), &ctx);
1190 if event_is_stopped_immediate(ev) {
1191 return true;
1192 }
1193 }
1194 event_is_stopped(ev)
1195}
1196
1197pub(crate) fn event_target_dispatch_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1198 let ev = arg(a, 0);
1199 validate_dispatch_event(it, &ev)?;
1200 it.retarget_event_related_target(&ev);
1201 let pre_stopped = if let Value::Object(eo) = &ev {
1202 let b = eo.borrow();
1203 b.props.get("_stop").is_some_and(|v| v.truthy())
1204 || b.props.get("_stopImmediate").is_some_and(|v| v.truthy())
1205 || b.props.get("cancelBubble").is_some_and(|v| v.truthy())
1206 } else {
1207 false
1208 };
1209 if let Some(listeners) = event_target_listeners(&this) {
1210 let etype = if let Value::Object(eo) = &ev {
1211 eo.borrow().props.get("type").map(|v| v.to_js_string()).unwrap_or_default()
1212 } else {
1213 String::new()
1214 };
1215 let bubbles = matches!(&ev, Value::Object(eo) if eo.borrow().props.get("bubbles").is_some_and(|v| v.truthy()));
1216 let win = if etype != "load" && is_main_document_obj(it, &this) {
1220 match it.global.borrow().vars.get("window") {
1221 Some(Value::Object(w)) => Some(w.clone()),
1222 _ => None,
1223 }
1224 } else {
1225 None
1226 };
1227 let mut path = alloc::vec![this.clone()];
1228 if let Some(w) = &win {
1229 path.push(Value::Object(w.clone()));
1230 }
1231 if let Value::Object(eo) = &ev {
1232 let mut e = eo.borrow_mut();
1233 e.props.insert("_dispatch".into(), Value::Bool(true));
1234 e.props.insert("target".into(), this.clone());
1235 e.props.insert("srcElement".into(), this.clone());
1236 e.props.insert("_composedPath".into(), Value::Object(Obj::array(path)));
1237 e.props.insert("currentTarget".into(), this.clone());
1238 e.props.insert("eventPhase".into(), Value::Number(2.0));
1239 }
1240 let prev_win_ev = swap_window_event(it, ev.clone());
1241 let mut stopped = pre_stopped;
1242 if !stopped {
1243 if let Some(w) = &win {
1244 stopped = fire_window_listeners_phase(it, w, &ev, &etype, true);
1245 }
1246 }
1247 if !stopped {
1248 set_current_target(&ev, &this, 2.0);
1249 for want_capture in [true, false] {
1252 if fire_own_listeners_phase(it, &listeners, &this, &ev, &etype, want_capture) {
1253 stopped = true;
1254 break;
1255 }
1256 }
1257 }
1258 if !stopped && bubbles {
1259 if let Some(w) = &win {
1260 let _ = fire_window_listeners_phase(it, w, &ev, &etype, false);
1261 }
1262 }
1263 restore_window_event(it, prev_win_ev);
1264 if let Value::Object(eo) = &ev {
1265 let mut e = eo.borrow_mut();
1266 e.props.insert("_dispatch".into(), Value::Bool(false));
1267 e.props.insert("currentTarget".into(), Value::Null);
1268 e.props.insert("eventPhase".into(), Value::Number(0.0));
1269 e.props.insert("_composedPath".into(), Value::Object(Obj::array(alloc::vec::Vec::new())));
1270 e.props.shift_remove("_stop");
1271 e.props.shift_remove("_stopImmediate");
1272 e.props.insert("cancelBubble".into(), Value::Bool(false));
1273 }
1274 }
1275 let default_prevented = if let Value::Object(eo) = &ev {
1276 matches!(eo.borrow().props.get("defaultPrevented"), Some(Value::Bool(true)))
1277 } else {
1278 false
1279 };
1280 Ok(Value::Bool(!default_prevented))
1281}
1282
1283pub(crate) fn message_channel_ctor(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
1288 let port1 = message_port_new(it)?;
1289 let port2 = message_port_new(it)?;
1290 if let (Value::Object(p1), Value::Object(p2)) = (&port1, &port2) {
1291 p1.borrow_mut().props.insert("_peer".into(), port2.clone());
1292 p2.borrow_mut().props.insert("_peer".into(), port1.clone());
1293 }
1294 let ch = Obj::plain();
1295 {
1296 let mut b = ch.borrow_mut();
1297 b.props.insert("port1".into(), port1);
1298 b.props.insert("port2".into(), port2);
1299 }
1300 Ok(Value::Object(ch))
1301}
1302pub(crate) fn message_port_new(it: &mut Interp) -> Result<Value, Value> {
1303 let port = event_target_new(it);
1304 if let Value::Object(o) = &port {
1305 let mut b = o.borrow_mut();
1306 b.props
1307 .insert("postMessage".into(), nv("postMessage", message_port_post_message));
1308 b.props.insert("start".into(), nv("start", dom_noop));
1309 b.props.insert("close".into(), nv("close", message_port_close));
1310 }
1311 Ok(port)
1312}
1313pub(crate) fn message_port_is_closed(port: &Value) -> bool {
1314 matches!(port, Value::Object(o) if o.borrow().props.get("_closed").map(|v| v.truthy()).unwrap_or(false))
1315}
1316pub(crate) fn message_port_post_message(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1320 if message_port_is_closed(&this) {
1321 return Ok(Value::Undefined);
1322 }
1323 let data = structured_clone(it, Value::Undefined, a)?;
1324 let peer = if let Value::Object(o) = &this {
1325 o.borrow().props.get("_peer").cloned()
1326 } else {
1327 None
1328 };
1329 if let Some(peer) = peer {
1330 message_port_deliver(it, &peer, data);
1331 }
1332 Ok(Value::Undefined)
1333}
1334pub(crate) fn message_port_deliver(it: &mut Interp, port: &Value, data: Value) {
1338 if message_port_is_closed(port) {
1339 return;
1340 }
1341 let ev = Obj::plain();
1342 ev.borrow_mut().props.insert("type".into(), Value::str("message"));
1343 ev.borrow_mut().props.insert("data".into(), data);
1344 let onmessage = if let Value::Object(o) = port {
1345 o.borrow().props.get("onmessage").cloned()
1346 } else {
1347 None
1348 };
1349 if let Some(f) = onmessage.and_then(callable_or_none) {
1350 it.call_listener(
1351 &f,
1352 port.clone(),
1353 &[Value::Object(ev.clone())],
1354 "MessagePort onmessage",
1355 );
1356 }
1357 let _ = event_target_dispatch_event(it, port.clone(), &[Value::Object(ev)]);
1358}
1359pub(crate) fn message_port_close(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1360 if let Value::Object(o) = &this {
1361 o.borrow_mut().props.insert("_closed".into(), Value::Bool(true));
1362 }
1363 Ok(Value::Undefined)
1364}
1365
1366pub(crate) fn bc_registry(it: &mut Interp) -> crate::os_lib::ecma::value::ObjRef {
1372 let existing = it.global.borrow().vars.get("__bc_registry").cloned();
1373 if let Some(Value::Object(o)) = existing {
1374 return o;
1375 }
1376 let reg = Obj::plain();
1377 it.global
1378 .borrow_mut()
1379 .vars
1380 .insert("__bc_registry".into(), Value::Object(reg.clone()));
1381 reg
1382}
1383pub(crate) fn broadcast_channel_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1384 let name = arg(a, 0).to_js_string();
1385 let base = event_target_new(it);
1386 if let Value::Object(o) = &base {
1387 let mut b = o.borrow_mut();
1388 b.props.insert("name".into(), Value::str(&name));
1389 b.props
1390 .insert("postMessage".into(), nv("postMessage", broadcast_channel_post_message));
1391 b.props.insert("close".into(), nv("close", message_port_close));
1392 }
1393 let reg = bc_registry(it);
1394 let existing = reg.borrow().props.get(&name).cloned();
1395 match existing {
1396 Some(Value::Object(arr)) => {
1397 if let ObjKind::Array(items) = &mut arr.borrow_mut().kind {
1398 items.push(base.clone());
1399 }
1400 }
1401 _ => {
1402 reg.borrow_mut()
1403 .props
1404 .insert(name.into(), Value::Object(Obj::array(alloc::vec![base.clone()])));
1405 }
1406 }
1407 Ok(base)
1408}
1409pub(crate) fn broadcast_channel_post_message(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1412 if message_port_is_closed(&this) {
1413 return Ok(Value::Undefined);
1414 }
1415 let name = if let Value::Object(o) = &this {
1416 o.borrow().props.get("name").map(|v| v.to_js_string()).unwrap_or_default()
1417 } else {
1418 String::new()
1419 };
1420 let data = structured_clone(it, Value::Undefined, a)?;
1421 let reg = bc_registry(it);
1422 let peers: Vec<Value> = match reg.borrow().props.get(&name) {
1423 Some(Value::Object(arr)) => match &arr.borrow().kind {
1424 ObjKind::Array(items) => items.clone(),
1425 _ => alloc::vec::Vec::new(),
1426 },
1427 _ => alloc::vec::Vec::new(),
1428 };
1429 for peer in peers {
1430 let is_self = matches!((&peer, &this), (Value::Object(p), Value::Object(t)) if Rc::ptr_eq(p, t));
1431 if is_self {
1432 continue;
1433 }
1434 message_port_deliver(it, &peer, data.clone());
1435 }
1436 Ok(Value::Undefined)
1437}
1438
1439pub(crate) fn command_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1440 let ev = require_new_event(it, "CommandEvent", t)?;
1441 let event_type = require_event_type(it, "CommandEvent", a)?;
1442 let options = arg(a, 1);
1443 validate_event_dict(it, &options)?;
1444 init_event_base(it, &ev, &event_type, &options)?;
1445 let cmd = dict_str(it, &options, "command", "")?;
1446 let src = dict_get(it, &options, "source")?.unwrap_or(Value::Null);
1447 {
1448 let mut b = ev.borrow_mut();
1449 b.props.insert("command".into(), cmd);
1450 b.props.insert("source".into(), src);
1451 }
1452 Ok(Value::Object(ev))
1453}
1454
1455pub(crate) fn toggle_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1456 let ev = require_new_event(it, "ToggleEvent", t)?;
1457 let event_type = require_event_type(it, "ToggleEvent", a)?;
1458 let options = arg(a, 1);
1459 validate_event_dict(it, &options)?;
1460 init_event_base(it, &ev, &event_type, &options)?;
1461 let old_state = dict_str(it, &options, "oldState", "closed")?;
1462 let new_state = dict_str(it, &options, "newState", "open")?;
1463 {
1464 let mut b = ev.borrow_mut();
1465 b.props.insert("oldState".into(), old_state);
1466 b.props.insert("newState".into(), new_state);
1467 }
1468 Ok(Value::Object(ev))
1469}
1470
1471pub(crate) fn form_data_event_ctor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1472 let ev = require_new_event(it, "FormDataEvent", t)?;
1473 let event_type = require_event_type(it, "FormDataEvent", a)?;
1474 let options = arg(a, 1);
1475 validate_event_dict(it, &options)?;
1476 init_event_base(it, &ev, &event_type, &options)?;
1477 let fd = dict_get(it, &options, "formData")?.unwrap_or(Value::Null);
1478 ev.borrow_mut().props.insert("formData".into(), fd);
1479 Ok(Value::Object(ev))
1480}
1481
1482pub(crate) fn document_create_event(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1484 let iface = arg(a, 0).to_js_string();
1485 let lower = iface.to_ascii_lowercase();
1486 let target = match lower.as_str() {
1487 "beforeunloadevent" => "BeforeUnloadEvent",
1488 "compositionevent" => "CompositionEvent",
1489 "customevent" => "CustomEvent",
1490 "devicemotionevent" => "DeviceMotionEvent",
1491 "deviceorientationevent" => "DeviceOrientationEvent",
1492 "dragevent" => "DragEvent",
1493 "event" | "events" | "htmlevents" | "svgevents" => "Event",
1494 "focusevent" => "FocusEvent",
1495 "hashchangeevent" => "HashChangeEvent",
1496 "keyboardevent" => "KeyboardEvent",
1497 "messageevent" => "MessageEvent",
1498 "mouseevent" | "mouseevents" => "MouseEvent",
1499 "storageevent" => "StorageEvent",
1500 "textevent" => "TextEvent",
1501 "touchevent" => "TouchEvent",
1502 "uievent" | "uievents" => "UIEvent",
1503 _ => {
1504 return Err(it.dom_exception("NotSupportedError", "The provided event type is not supported."));
1505 }
1506 };
1507 let ctor = it.global.borrow().vars.get(target).cloned();
1508 let Some(ctor) = ctor else {
1509 return Err(it.dom_exception("NotSupportedError", "The provided event type is not supported."));
1510 };
1511 let ev = it.construct_value(&ctor, &[Value::str("")])?;
1512 if let Value::Object(o) = &ev {
1513 let mut b = o.borrow_mut();
1514 b.props.insert("_initialized".into(), Value::Bool(false));
1515 b.props.insert("target".into(), Value::Null);
1516 b.props.insert("srcElement".into(), Value::Null);
1517 b.props.insert("initEvent".into(), nv("initEvent", event_init_event));
1518 b.props.insert("initCustomEvent".into(), nv("initCustomEvent", event_init_custom_event));
1519 b.props.insert("initUIEvent".into(), nv("initUIEvent", event_init_ui_event));
1520 b.props.insert("initMouseEvent".into(), nv("initMouseEvent", event_init_mouse_event));
1521 b.props.insert("initKeyboardEvent".into(), nv("initKeyboardEvent", event_init_keyboard_event));
1522 if target == "CustomEvent" {
1523 b.props.insert("detail".into(), Value::Null);
1524 }
1525 }
1526 Ok(ev)
1527}
1528
1529fn init_event_common(it: &Interp, o: &ObjRef, a: &[Value], method: &str) -> Result<bool, Value> {
1530 if a.is_empty() {
1531 return Err(it.type_error(alloc::format!(
1532 "Failed to execute '{}' on 'Event': 1 argument required, but only 0 present.",
1533 method
1534 )));
1535 }
1536 let mut b = o.borrow_mut();
1537 if matches!(b.props.get("_dispatch"), Some(Value::Bool(true))) {
1538 return Ok(false);
1539 }
1540 b.props.insert("_initialized".into(), Value::Bool(true));
1541 b.props.shift_remove("_stop");
1542 b.props.shift_remove("_stopImmediate");
1543 b.props.insert("defaultPrevented".into(), Value::Bool(false));
1544 b.props.insert("target".into(), Value::Null);
1545 b.props.insert("srcElement".into(), Value::Null);
1546 b.props.insert("type".into(), Value::str(arg(a, 0).to_js_string()));
1547 b.props.insert("bubbles".into(), Value::Bool(arg(a, 1).truthy()));
1548 b.props.insert("cancelable".into(), Value::Bool(arg(a, 2).truthy()));
1549 Ok(true)
1550}
1551
1552pub(crate) fn event_init_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1554 if let Value::Object(o) = &this {
1555 if init_event_common(it, o, a, "initEvent")? && a.len() > 3 && o.borrow().props.contains_key("detail") {
1556 o.borrow_mut().props.insert("detail".into(), arg(a, 3));
1557 }
1558 }
1559 Ok(Value::Undefined)
1560}
1561
1562pub(crate) fn event_init_custom_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1563 if let Value::Object(o) = &this {
1564 if init_event_common(it, o, a, "initCustomEvent")? {
1565 let detail = if a.len() > 3 { arg(a, 3) } else { Value::Null };
1566 o.borrow_mut().props.insert("detail".into(), detail);
1567 }
1568 }
1569 Ok(Value::Undefined)
1570}
1571
1572pub(crate) fn event_init_ui_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1573 if let Value::Object(o) = &this {
1574 if init_event_common(it, o, a, "initUIEvent")? {
1575 let view = match arg(a, 3) {
1576 v @ Value::Object(_) => v,
1577 _ => Value::Null,
1578 };
1579 let detail = Value::Number(arg(a, 4).to_number());
1580 let mut b = o.borrow_mut();
1581 b.props.insert("view".into(), view);
1582 b.props.insert("detail".into(), detail);
1583 }
1584 }
1585 Ok(Value::Undefined)
1586}
1587
1588pub(crate) fn event_init_mouse_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1589 if let Value::Object(o) = &this {
1590 if init_event_common(it, o, a, "initMouseEvent")? {
1591 let view = match arg(a, 3) {
1592 v @ Value::Object(_) => v,
1593 _ => Value::Null,
1594 };
1595 let detail = Value::Number(arg(a, 4).to_number());
1596 let sx = Value::Number(arg(a, 5).to_number());
1597 let sy = Value::Number(arg(a, 6).to_number());
1598 let cx = Value::Number(arg(a, 7).to_number());
1599 let cy = Value::Number(arg(a, 8).to_number());
1600 let ctrl = Value::Bool(arg(a, 9).truthy());
1601 let alt = Value::Bool(arg(a, 10).truthy());
1602 let shift = Value::Bool(arg(a, 11).truthy());
1603 let meta = Value::Bool(arg(a, 12).truthy());
1604 let btn = Value::Number(arg(a, 13).to_number());
1605 let rel = match arg(a, 14) {
1606 v @ Value::Object(_) => v,
1607 _ => Value::Null,
1608 };
1609 let mut b = o.borrow_mut();
1610 b.props.insert("view".into(), view);
1611 b.props.insert("detail".into(), detail);
1612 b.props.insert("screenX".into(), sx);
1613 b.props.insert("screenY".into(), sy);
1614 b.props.insert("clientX".into(), cx);
1615 b.props.insert("clientY".into(), cy);
1616 b.props.insert("ctrlKey".into(), ctrl);
1617 b.props.insert("altKey".into(), alt);
1618 b.props.insert("shiftKey".into(), shift);
1619 b.props.insert("metaKey".into(), meta);
1620 b.props.insert("button".into(), btn);
1621 b.props.insert("relatedTarget".into(), rel);
1622 }
1623 }
1624 Ok(Value::Undefined)
1625}
1626
1627pub(crate) fn event_init_keyboard_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1628 if let Value::Object(o) = &this {
1629 if init_event_common(it, o, a, "initKeyboardEvent")? {
1630 let view = match arg(a, 3) {
1631 v @ Value::Object(_) => v,
1632 _ => Value::Null,
1633 };
1634 let key = Value::str(arg(a, 4).to_js_string());
1635 let location = Value::Number(arg(a, 5).to_number());
1636 let repeat = Value::Bool(arg(a, 7).truthy());
1637 let mut b = o.borrow_mut();
1638 b.props.insert("view".into(), view);
1639 b.props.insert("key".into(), key);
1640 b.props.insert("location".into(), location);
1641 b.props.insert("repeat".into(), repeat);
1642 }
1643 }
1644 Ok(Value::Undefined)
1645}
1646
1647fn event_target_proto_call(it: &mut Interp, this: Value, a: &[Value], name: &str) -> Result<Value, Value> {
1655 let this = match &this {
1656 Value::Null | Value::Undefined => it.global.borrow().vars.get("window").cloned().unwrap_or(this),
1657 _ => this,
1658 };
1659 if let Some(idx) = this_dom_idx(&this) {
1660 let f = it.dom_builtin_get(idx, name);
1662 return it.call_value(&f, this, a);
1663 }
1664 if let Value::Object(o) = &this {
1665 let is_win = matches!(
1666 it.global.borrow().vars.get("window"),
1667 Some(Value::Object(w)) if Rc::ptr_eq(o, w)
1668 );
1669 if is_win {
1670 return match name {
1671 "addEventListener" => super::window_api::window_add_event_listener(it, this, a),
1672 "removeEventListener" => super::window_api::window_remove_event_listener(it, this, a),
1673 _ => super::window_api::window_dispatch_event(it, this, a),
1674 };
1675 }
1676 let own = o.borrow().props.get(name).cloned();
1677 if let Some(ref f @ Value::Object(ref fo)) = own {
1678 let is_proto_self = it
1681 .global
1682 .borrow()
1683 .vars
1684 .get("EventTarget")
1685 .and_then(|v| match v {
1686 Value::Object(c) => c.borrow().props.get("prototype").cloned(),
1687 _ => None,
1688 })
1689 .and_then(|v| match v {
1690 Value::Object(p) => p.borrow().props.get(name).cloned(),
1691 _ => None,
1692 })
1693 .is_some_and(|pv| matches!(pv, Value::Object(po) if Rc::ptr_eq(fo, &po)));
1694 if !is_proto_self {
1695 return it.call_value(f, this, a);
1696 }
1697 }
1698 }
1699 match name {
1700 "addEventListener" => event_target_add_event_listener(it, this, a),
1701 "removeEventListener" => event_target_remove_event_listener(it, this, a),
1702 _ => event_target_dispatch_event(it, this, a),
1703 }
1704}
1705pub(crate) fn event_target_proto_add(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1706 event_target_proto_call(it, this, a, "addEventListener")
1707}
1708pub(crate) fn event_target_proto_remove(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1709 event_target_proto_call(it, this, a, "removeEventListener")
1710}
1711pub(crate) fn event_target_proto_dispatch(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1712 event_target_proto_call(it, this, a, "dispatchEvent")
1713}