1use crate::host::{with_host, JsObj};
22use fusevm::Value;
23use indexmap::IndexMap;
24
25pub const CLASSES: &[&str] = &["Event", "EventTarget", "CustomEvent"];
27
28pub const EVENT_TARGET_METHODS: &[&str] =
29 &["addEventListener", "removeEventListener", "dispatchEvent"];
30pub const EVENT_METHODS: &[&str] = &["initEvent", "stopImmediatePropagation", "preventDefault"];
36pub const EVENT_LATE_METHODS: &[&str] = &["composedPath", "stopPropagation"];
37
38pub const EVENT_ACCESSORS: &[(&str, bool)] = &[
42 ("target", false),
43 ("currentTarget", false),
44 ("srcElement", false),
45 ("type", false),
46 ("cancelable", false),
47 ("defaultPrevented", false),
48 ("timeStamp", false),
49 ("returnValue", true),
50 ("bubbles", false),
51 ("composed", false),
52 ("eventPhase", false),
53 ("cancelBubble", true),
54 ("isTrusted", false),
55];
56
57pub fn constant(name: &str) -> Option<Value> {
59 Some(Value::Int(match name {
60 "NONE" => 0,
61 "CAPTURING_PHASE" => 1,
62 "AT_TARGET" => 2,
63 "BUBBLING_PHASE" => 3,
64 _ => return None,
65 }))
66}
67
68pub fn is_class(name: &str) -> bool {
69 CLASSES.contains(&name)
70}
71
72fn slot(recv: &Value, key: &str) -> Option<Value> {
75 with_host(|h| match h.get(recv) {
76 Some(JsObj::Object(p)) => p.get(key).cloned(),
77 _ => None,
78 })
79}
80
81fn set_slot(recv: &Value, key: &str, val: Value) {
82 with_host(|h| {
83 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
84 p.insert(key.to_string(), val);
85 }
86 });
87}
88
89fn flag(recv: &Value, key: &str) -> bool {
90 matches!(slot(recv, key), Some(Value::Bool(true)))
91}
92
93fn is_object(v: &Value) -> bool {
94 with_host(|h| matches!(h.get(v), Some(JsObj::Object(_)) | Some(JsObj::Array(_))))
95}
96
97fn is_event(v: &Value) -> bool {
100 matches!(v, Value::Obj(_)) && slot(v, "@@type").is_some()
101}
102
103fn is_event_target(v: &Value) -> bool {
106 matches!(v, Value::Obj(_)) && slot(v, "@@listeners").is_some()
107}
108
109fn missing_args(what: &str) -> String {
110 crate::host::coded_error(
111 "TypeError",
112 "ERR_MISSING_ARGS",
113 &format!("The {what} must be specified"),
114 )
115}
116
117fn invalid_this(class: &str) -> String {
118 crate::host::coded_error(
119 "TypeError",
120 "ERR_INVALID_THIS",
121 &format!("Value of \"this\" must be of type {class}"),
122 )
123}
124
125pub(crate) fn throw_value(v: Value) -> String {
128 let msg = with_host(|h| h.str_of(&v));
129 with_host(|h| h.exc = Some(v));
130 msg
131}
132
133fn rethrow_on_next_tick(msg: &str) {
137 let err = with_host(|h| h.exc.take())
138 .unwrap_or_else(|| with_host(|h| crate::builtins::synth_error(h, msg)));
139 let Value::Obj(idx) = err else {
140 return;
141 };
142 with_host(|h| {
143 let thunk = h.alloc(JsObj::Builtin(format!("@@rethrow:{idx}")));
144 h.queue_nexttick(thunk, Vec::new());
145 });
146}
147
148pub fn rethrow(idx: u32) -> Result<Value, String> {
150 Err(throw_value(Value::Obj(idx)))
151}
152
153pub fn new_listener_map() -> Value {
157 with_host(|h| h.new_object(IndexMap::new()))
158}
159
160fn construct_event_target() -> Value {
161 let listeners = new_listener_map();
162 with_host(|h| {
163 let mut m = IndexMap::new();
164 m.insert("@@native".into(), h.new_str("EventTarget"));
165 m.insert("@@listeners".into(), listeners);
166 h.new_object(m)
167 })
168}
169
170fn event_slots(tag: &str, args: &[Value]) -> Result<IndexMap<String, Value>, String> {
172 if args.is_empty() {
173 return Err(missing_args("\"type\" argument"));
174 }
175 let ty = with_host(|h| h.str_of(&args[0]));
176 let init = args.get(1).cloned().unwrap_or(Value::Undef);
177 let option = |name: &str| -> bool {
178 if !is_object(&init) {
179 return false;
180 }
181 let v = crate::builtins::get_property(&init, name).unwrap_or(Value::Undef);
182 with_host(|h| h.truthy(&v))
183 };
184 let bubbles = option("bubbles");
185 let cancelable = option("cancelable");
186 let composed = option("composed");
187 Ok(with_host(|h| {
188 let mut m = IndexMap::new();
189 m.insert("@@native".into(), h.new_str(tag));
190 m.insert("@@type".into(), h.new_str(ty));
191 m.insert("@@bubbles".into(), Value::Bool(bubbles));
192 m.insert("@@cancelable".into(), Value::Bool(cancelable));
193 m.insert("@@composed".into(), Value::Bool(composed));
194 m.insert("@@defaultPrevented".into(), Value::Bool(false));
195 m.insert(
196 "@@timeStamp".into(),
197 Value::Float(super::perf_hooks::now_ms()),
198 );
199 m.insert("@@target".into(), h.null());
200 m.insert("@@currentTarget".into(), h.null());
201 m.insert("@@eventPhase".into(), Value::Int(0));
202 m.insert("@@isTrusted".into(), Value::Bool(false));
203 m.insert("@@propagationStopped".into(), Value::Bool(false));
204 m.insert("@@stopImmediate".into(), Value::Bool(false));
205 m.insert("@@dispatching".into(), Value::Bool(false));
206 m
207 }))
208}
209
210pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
211 Some(match name {
212 "EventTarget" => Ok(construct_event_target()),
213 "Event" => event_slots("Event", args).map(|m| with_host(|h| h.new_object(m))),
214 "CustomEvent" => event_slots("CustomEvent", args).map(|mut m| {
216 let init = args.get(1).cloned().unwrap_or(Value::Undef);
217 let detail = if is_object(&init) {
218 crate::builtins::get_property(&init, "detail").unwrap_or(Value::Undef)
219 } else {
220 Value::Undef
221 };
222 with_host(|h| {
223 let detail = if matches!(detail, Value::Undef) {
224 h.null()
225 } else {
226 detail
227 };
228 m.insert("@@detail".into(), detail);
229 h.new_object(m)
230 })
231 }),
232 _ => return None,
233 })
234}
235
236fn listener_list(target: &Value, ty: &str, create: bool) -> Option<Value> {
240 let map = slot(target, "@@listeners")?;
241 let existing = with_host(|h| match h.get(&map) {
242 Some(JsObj::Object(p)) => p.get(ty).cloned(),
243 _ => None,
244 });
245 match existing {
246 Some(list) => Some(list),
247 None if create => Some(with_host(|h| {
248 let list = h.new_array(Vec::new());
249 if let Some(JsObj::Object(p)) = h.get_mut(&map) {
250 p.insert(ty.to_string(), list.clone());
251 }
252 list
253 })),
254 None => None,
255 }
256}
257
258fn list_items(list: &Value) -> Vec<Value> {
259 with_host(|h| match h.get(list) {
260 Some(JsObj::Array(items)) => items.clone(),
261 _ => Vec::new(),
262 })
263}
264
265fn new_record(cb: Value, capture: bool, once: bool, handler: bool) -> Value {
266 with_host(|h| {
267 let mut m = IndexMap::new();
268 m.insert("@@cb".into(), cb);
269 m.insert("@@capture".into(), Value::Bool(capture));
270 m.insert("@@once".into(), Value::Bool(once));
271 m.insert("@@handler".into(), Value::Bool(handler));
272 m.insert("@@removed".into(), Value::Bool(false));
273 h.new_object(m)
274 })
275}
276
277fn find_record(list: &Value, cb: &Value, capture: bool) -> Option<Value> {
280 list_items(list).into_iter().find(|rec| {
281 !flag(rec, "@@handler")
282 && flag(rec, "@@capture") == capture
283 && slot(rec, "@@cb")
284 .map(|c| with_host(|h| h.strict_eq(&c, cb)))
285 .unwrap_or(false)
286 })
287}
288
289fn remove_record(list: &Value, rec: &Value) {
292 set_slot(rec, "@@removed", Value::Bool(true));
293 with_host(|h| {
294 if let Some(JsObj::Array(items)) = h.get_mut(list) {
295 items.retain(|r| r != rec);
296 }
297 });
298}
299
300fn parse_options(opts: &Value) -> (bool, bool, Option<Value>) {
303 if let Value::Bool(b) = opts {
304 return (*b, false, None);
305 }
306 if !is_object(opts) {
307 return (false, false, None);
308 }
309 let read = |name: &str| crate::builtins::get_property(opts, name).unwrap_or(Value::Undef);
312 let capture = read("capture");
313 let capture = with_host(|h| h.truthy(&capture));
314 let once = read("once");
315 let once = with_host(|h| h.truthy(&once));
316 let signal = Some(read("signal")).filter(|s| !matches!(s, Value::Undef));
317 (capture, once, signal)
318}
319
320pub fn add_listener(target: &Value, args: &[Value]) -> Result<Value, String> {
322 if args.len() < 2 {
323 return Err(missing_args("\"type\" and \"listener\" arguments"));
324 }
325 let ty = with_host(|h| h.str_of(&args[0]));
326 let listener = args[1].clone();
327 if with_host(|h| h.is_nullish(&listener)) {
330 let shown = if with_host(|h| h.is_null(&listener)) {
331 "null"
332 } else {
333 "undefined"
334 };
335 super::process::emit_warning(
336 "AddEventListenerArgumentTypeWarning",
337 None,
338 &format!("addEventListener called with {shown} which has no effect."),
339 None,
340 );
341 return Ok(Value::Undef);
342 }
343 let callable = with_host(|h| crate::host::is_callable(h, &listener));
344 if !callable && !is_object(&listener) {
345 return Err(crate::host::coded_error(
346 "TypeError",
347 "ERR_INVALID_ARG_TYPE",
348 &format!(
349 "The \"listener\" argument must be an instance of EventListener. Received {}",
350 super::received_desc(&listener)
351 ),
352 ));
353 }
354 let (capture, once, signal) = parse_options(&args.get(2).cloned().unwrap_or(Value::Undef));
355 if let Some(sig) = &signal {
357 if matches!(slot(sig, "@@aborted"), Some(Value::Bool(true))) {
358 return Ok(Value::Undef);
359 }
360 }
361 let list = listener_list(target, &ty, true).ok_or_else(|| invalid_this("EventTarget"))?;
362 if find_record(&list, &listener, capture).is_some() {
363 return Ok(Value::Undef);
364 }
365 let rec = new_record(listener.clone(), capture, once, false);
366 with_host(|h| {
367 if let Some(JsObj::Array(items)) = h.get_mut(&list) {
368 items.push(rec);
369 }
370 });
371 if let Some(sig) = signal {
375 if is_event_target(&sig) {
376 let record = with_host(|h| {
377 let mut m = IndexMap::new();
378 m.insert("@@target".into(), target.clone());
379 m.insert("@@type".into(), h.new_str(ty.clone()));
380 m.insert("@@cb".into(), listener);
381 m.insert("@@capture".into(), Value::Bool(capture));
382 h.new_object(m)
383 });
384 if let Value::Obj(idx) = record {
385 let thunk = with_host(|h| h.alloc(JsObj::Builtin(format!("@@evunlisten:{idx}"))));
386 let abort = with_host(|h| h.new_str("abort"));
387 let once = with_host(|h| {
388 let mut m = IndexMap::new();
389 m.insert("once".into(), Value::Bool(true));
390 h.new_object(m)
391 });
392 add_listener(&sig, &[abort, thunk, once])?;
393 }
394 }
395 }
396 Ok(Value::Undef)
397}
398
399pub fn unlisten(idx: u32) -> Result<Value, String> {
402 let record = Value::Obj(idx);
403 let Some(target) = slot(&record, "@@target") else {
404 return Ok(Value::Undef);
405 };
406 let ty = slot(&record, "@@type").unwrap_or(Value::Undef);
407 let cb = slot(&record, "@@cb").unwrap_or(Value::Undef);
408 let capture = slot(&record, "@@capture").unwrap_or(Value::Bool(false));
409 remove_listener(&target, &[ty, cb, capture])
410}
411
412pub fn remove_listener(target: &Value, args: &[Value]) -> Result<Value, String> {
414 if args.len() < 2 {
415 return Err(missing_args("\"type\" and \"listener\" arguments"));
416 }
417 let ty = with_host(|h| h.str_of(&args[0]));
418 let (capture, _, _) = parse_options(&args.get(2).cloned().unwrap_or(Value::Undef));
419 if let Some(list) = listener_list(target, &ty, false) {
420 if let Some(rec) = find_record(&list, &args[1], capture) {
421 remove_record(&list, &rec);
422 }
423 }
424 Ok(Value::Undef)
425}
426
427pub fn ensure_handler_slot(target: &Value, ty: &str) {
432 let Some(list) = listener_list(target, ty, true) else {
433 return;
434 };
435 if list_items(&list).iter().any(|rec| flag(rec, "@@handler")) {
436 return;
437 }
438 let rec = new_record(Value::Undef, false, false, true);
439 with_host(|h| {
440 if let Some(JsObj::Array(items)) = h.get_mut(&list) {
441 items.push(rec);
442 }
443 });
444}
445
446pub fn dispatch(target: &Value, args: &[Value]) -> Result<Value, String> {
449 if !is_event_target(target) {
450 return Err(invalid_this("EventTarget"));
451 }
452 let Some(event) = args.first() else {
453 return Err(missing_args("\"event\" argument"));
454 };
455 if !is_event(event) {
456 return Err(crate::host::coded_error(
457 "TypeError",
458 "ERR_INVALID_ARG_TYPE",
459 &format!(
460 "The \"event\" argument must be an instance of Event. Received {}",
461 super::received_desc(event)
462 ),
463 ));
464 }
465 let ty = slot(event, "@@type")
466 .map(|v| with_host(|h| h.str_of(&v)))
467 .unwrap_or_default();
468 if flag(event, "@@dispatching") {
469 return Err(crate::host::coded_error(
470 "Error",
471 "ERR_EVENT_RECURSION",
472 &format!("The event \"{ty}\" is already being dispatched"),
473 ));
474 }
475 set_slot(event, "@@target", target.clone());
476 set_slot(event, "@@currentTarget", target.clone());
477 set_slot(event, "@@eventPhase", Value::Int(2));
478 set_slot(event, "@@dispatching", Value::Bool(true));
479
480 let records = listener_list(target, &ty, false)
483 .map(|list| (list_items(&list), list))
484 .unwrap_or_else(|| (Vec::new(), Value::Undef));
485 for rec in &records.0 {
486 if flag(event, "@@stopImmediate") {
487 break;
488 }
489 if flag(rec, "@@removed") {
490 continue;
491 }
492 if flag(rec, "@@once") {
493 remove_record(&records.1, rec);
494 }
495 let cb = if flag(rec, "@@handler") {
496 slot(target, &format!("@@on{ty}")).unwrap_or(Value::Undef)
497 } else {
498 slot(rec, "@@cb").unwrap_or(Value::Undef)
499 };
500 let result = if with_host(|h| crate::host::is_callable(h, &cb)) {
501 crate::host::invoke(&cb, vec![event.clone()], Some(target.clone()))
502 } else if flag(rec, "@@handler") {
503 Ok(Value::Undef)
505 } else {
506 match crate::builtins::get_property(&cb, "handleEvent") {
511 Ok(h) if !with_host(|host| host.truthy(&h)) => Ok(Value::Undef),
512 Ok(_) => crate::host::call_method(&cb, "handleEvent", vec![event.clone()]),
513 Err(e) => Err(e),
514 }
515 };
516 if let Err(msg) = result {
517 rethrow_on_next_tick(&msg);
518 }
519 }
520
521 set_slot(event, "@@eventPhase", Value::Int(0));
522 set_slot(event, "@@currentTarget", with_host(|h| h.null()));
523 set_slot(event, "@@dispatching", Value::Bool(false));
524 Ok(Value::Bool(!flag(event, "@@defaultPrevented")))
525}
526
527pub fn instance_call(
530 tag: &str,
531 recv: &Value,
532 method: &str,
533 args: &[Value],
534) -> Result<Value, String> {
535 match tag {
536 "EventTarget" => event_target_call(recv, method, args),
537 _ => event_call(recv, method, args),
538 }
539}
540
541pub fn event_target_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
543 if !is_event_target(recv) {
544 return Err(invalid_this("EventTarget"));
545 }
546 match method {
547 "addEventListener" => add_listener(recv, args),
548 "removeEventListener" => remove_listener(recv, args),
549 "dispatchEvent" => dispatch(recv, args),
550 _ => Err(crate::host::type_error(&format!(
551 "{method} is not a function"
552 ))),
553 }
554}
555
556fn event_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
557 if !is_event(recv) {
558 return Err(invalid_this("Event"));
559 }
560 match method {
561 "initEvent" => {
563 if args.is_empty() {
564 return Err(missing_args("\"type\" argument"));
565 }
566 if !flag(recv, "@@dispatching") {
567 let ty = with_host(|h| h.str_of(&args[0]));
568 let bubbles = args
569 .get(1)
570 .map(|v| with_host(|h| h.truthy(v)))
571 .unwrap_or(false);
572 let cancelable = args
573 .get(2)
574 .map(|v| with_host(|h| h.truthy(v)))
575 .unwrap_or(false);
576 set_slot(recv, "@@type", with_host(|h| h.new_str(ty)));
577 set_slot(recv, "@@bubbles", Value::Bool(bubbles));
578 set_slot(recv, "@@cancelable", Value::Bool(cancelable));
579 }
580 Ok(Value::Undef)
581 }
582 "stopImmediatePropagation" => {
583 set_slot(recv, "@@propagationStopped", Value::Bool(true));
584 set_slot(recv, "@@stopImmediate", Value::Bool(true));
585 Ok(Value::Undef)
586 }
587 "stopPropagation" => {
588 set_slot(recv, "@@propagationStopped", Value::Bool(true));
589 Ok(Value::Undef)
590 }
591 "preventDefault" => {
593 if flag(recv, "@@cancelable") {
594 set_slot(recv, "@@defaultPrevented", Value::Bool(true));
595 }
596 Ok(Value::Undef)
597 }
598 "composedPath" => {
601 let path = if flag(recv, "@@dispatching") {
602 vec![slot(recv, "@@target").unwrap_or(Value::Undef)]
603 } else {
604 Vec::new()
605 };
606 Ok(with_host(|h| h.new_array(path)))
607 }
608 "@get@srcElement" => Ok(slot(recv, "@@target").unwrap_or(Value::Undef)),
610 "@get@returnValue" => Ok(Value::Bool(!flag(recv, "@@defaultPrevented"))),
611 "@get@cancelBubble" => Ok(Value::Bool(flag(recv, "@@propagationStopped"))),
612 _ => Err(crate::host::type_error(&format!(
613 "{method} is not a function"
614 ))),
615 }
616}
617
618pub fn accessor_written(recv: &Value, key: &str, value: &Value) -> Result<(), String> {
621 if !is_event(recv) {
622 return Err(invalid_this("Event"));
623 }
624 let truthy = with_host(|h| h.truthy(value));
625 match key {
626 "cancelBubble" if truthy => set_slot(recv, "@@propagationStopped", Value::Bool(true)),
627 "returnValue" if !truthy && flag(recv, "@@cancelable") => {
628 set_slot(recv, "@@defaultPrevented", Value::Bool(true))
629 }
630 _ => {}
631 }
632 Ok(())
633}