script/dom/event.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::default::Default;
7
8use base::cross_process_instant::CrossProcessInstant;
9use bitflags::bitflags;
10use devtools_traits::{TimelineMarker, TimelineMarkerType};
11use dom_struct::dom_struct;
12use embedder_traits::InputEventResult;
13use js::rust::HandleObject;
14use keyboard_types::{Key, NamedKey};
15use script_bindings::codegen::GenericBindings::PointerEventBinding::PointerEventMethods;
16use script_bindings::match_domstring_ascii;
17use stylo_atoms::Atom;
18
19use crate::dom::bindings::callback::ExceptionHandling;
20use crate::dom::bindings::cell::DomRefCell;
21use crate::dom::bindings::codegen::Bindings::EventBinding;
22use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
23use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
24use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
25use crate::dom::bindings::codegen::Bindings::PerformanceBinding::DOMHighResTimeStamp;
26use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
27 ShadowRootMethods, ShadowRootMode,
28};
29use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
30use crate::dom::bindings::error::Fallible;
31use crate::dom::bindings::inheritance::Castable;
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object_with_proto};
34use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
35use crate::dom::bindings::str::DOMString;
36use crate::dom::element::Element;
37use crate::dom::eventtarget::{EventListeners, EventTarget, ListenerPhase};
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::html::htmlinputelement::InputActivationState;
40use crate::dom::html::htmlslotelement::HTMLSlotElement;
41use crate::dom::mouseevent::MouseEvent;
42use crate::dom::node::{Node, NodeTraits};
43use crate::dom::shadowroot::ShadowRoot;
44use crate::dom::types::{KeyboardEvent, PointerEvent, UserActivation};
45use crate::dom::virtualmethods::vtable_for;
46use crate::dom::window::Window;
47use crate::script_runtime::CanGc;
48use crate::task::TaskOnce;
49
50/// <https://dom.spec.whatwg.org/#concept-event>
51#[dom_struct]
52pub(crate) struct Event {
53 reflector_: Reflector,
54
55 /// <https://dom.spec.whatwg.org/#dom-event-currenttarget>
56 current_target: MutNullableDom<EventTarget>,
57
58 /// <https://dom.spec.whatwg.org/#event-target>
59 target: MutNullableDom<EventTarget>,
60
61 /// <https://dom.spec.whatwg.org/#dom-event-type>
62 #[no_trace]
63 type_: DomRefCell<Atom>,
64
65 /// <https://dom.spec.whatwg.org/#dom-event-eventphase>
66 phase: Cell<EventPhase>,
67
68 /// The various specification-defined flags set on this event.
69 flags: Cell<EventFlags>,
70
71 /// <https://dom.spec.whatwg.org/#dom-event-cancelable>
72 cancelable: Cell<bool>,
73
74 /// <https://dom.spec.whatwg.org/#dom-event-bubbles>
75 bubbles: Cell<bool>,
76
77 /// <https://dom.spec.whatwg.org/#dom-event-istrusted>
78 is_trusted: Cell<bool>,
79
80 /// <https://dom.spec.whatwg.org/#dom-event-timestamp>
81 #[no_trace]
82 time_stamp: CrossProcessInstant,
83
84 /// <https://dom.spec.whatwg.org/#event-path>
85 path: DomRefCell<Vec<EventPathSegment>>,
86
87 /// <https://dom.spec.whatwg.org/#event-relatedtarget>
88 related_target: MutNullableDom<EventTarget>,
89}
90
91/// An element on an [event path](https://dom.spec.whatwg.org/#event-path)
92#[derive(JSTraceable, MallocSizeOf)]
93#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
94pub(crate) struct EventPathSegment {
95 /// <https://dom.spec.whatwg.org/#event-path-invocation-target>
96 invocation_target: Dom<EventTarget>,
97
98 /// <https://dom.spec.whatwg.org/#event-path-invocation-target-in-shadow-tree>
99 invocation_target_in_shadow_tree: bool,
100
101 /// <https://dom.spec.whatwg.org/#event-path-shadow-adjusted-target>
102 shadow_adjusted_target: Option<Dom<EventTarget>>,
103
104 /// <https://dom.spec.whatwg.org/#event-path-relatedtarget>
105 related_target: Option<Dom<EventTarget>>,
106
107 /// <https://dom.spec.whatwg.org/#event-path-root-of-closed-tree>
108 root_of_closed_tree: bool,
109
110 /// <https://dom.spec.whatwg.org/#event-path-slot-in-closed-tree>
111 slot_in_closed_tree: bool,
112}
113
114impl Event {
115 pub(crate) fn new_inherited() -> Event {
116 Event {
117 reflector_: Reflector::new(),
118 current_target: Default::default(),
119 target: Default::default(),
120 type_: DomRefCell::new(atom!("")),
121 phase: Cell::new(EventPhase::None),
122 flags: Cell::new(EventFlags::empty()),
123 cancelable: Cell::new(false),
124 bubbles: Cell::new(false),
125 is_trusted: Cell::new(false),
126 time_stamp: CrossProcessInstant::now(),
127 path: DomRefCell::default(),
128 related_target: Default::default(),
129 }
130 }
131
132 pub(crate) fn new_uninitialized(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Event> {
133 Self::new_uninitialized_with_proto(global, None, can_gc)
134 }
135
136 pub(crate) fn new_uninitialized_with_proto(
137 global: &GlobalScope,
138 proto: Option<HandleObject>,
139 can_gc: CanGc,
140 ) -> DomRoot<Event> {
141 reflect_dom_object_with_proto(Box::new(Event::new_inherited()), global, proto, can_gc)
142 }
143
144 pub(crate) fn new(
145 global: &GlobalScope,
146 type_: Atom,
147 bubbles: EventBubbles,
148 cancelable: EventCancelable,
149 can_gc: CanGc,
150 ) -> DomRoot<Event> {
151 Self::new_with_proto(global, None, type_, bubbles, cancelable, can_gc)
152 }
153
154 fn new_with_proto(
155 global: &GlobalScope,
156 proto: Option<HandleObject>,
157 type_: Atom,
158 bubbles: EventBubbles,
159 cancelable: EventCancelable,
160 can_gc: CanGc,
161 ) -> DomRoot<Event> {
162 let event = Event::new_uninitialized_with_proto(global, proto, can_gc);
163
164 // NOTE: The spec doesn't tell us to call init event here, it just happens to do what we need.
165 event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
166 event
167 }
168
169 /// <https://dom.spec.whatwg.org/#dom-event-initevent>
170 /// and <https://dom.spec.whatwg.org/#concept-event-initialize>
171 pub(crate) fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) {
172 // https://dom.spec.whatwg.org/#dom-event-initevent
173 if self.has_flag(EventFlags::Dispatch) {
174 return;
175 }
176
177 // https://dom.spec.whatwg.org/#concept-event-initialize
178 // Step 1. Set event’s initialized flag.
179 self.set_flags(EventFlags::Initialized);
180
181 // Step 2. Unset event’s stop propagation flag, stop immediate propagation flag, and canceled flag.
182 self.unset_flags(EventFlags::StopPropagation);
183 self.unset_flags(EventFlags::StopImmediatePropagation);
184 self.unset_flags(EventFlags::Canceled);
185
186 // This flag isn't in the specification, but we need to unset it anyway.
187 self.unset_flags(EventFlags::Handled);
188
189 // Step 3. Set event’s isTrusted attribute to false.
190 self.is_trusted.set(false);
191
192 // Step 4. Set event’s target to null.
193 self.target.set(None);
194
195 // Step 5. Set event’s type attribute to type.
196 *self.type_.borrow_mut() = type_;
197
198 // Step 6. Set event’s bubbles attribute to bubbles.
199 self.bubbles.set(bubbles);
200
201 // Step 7. Set event’s cancelable attribute to cancelable.
202 self.cancelable.set(cancelable);
203 }
204
205 fn set_flags(&self, flags_to_set: EventFlags) {
206 self.flags.set(self.flags.get().union(flags_to_set))
207 }
208
209 fn unset_flags(&self, flags_to_unset: EventFlags) {
210 let mut flags = self.flags.get();
211 flags.remove(flags_to_unset);
212 self.flags.set(flags);
213 }
214
215 fn has_flag(&self, flag: EventFlags) -> bool {
216 self.flags.get().contains(flag)
217 }
218
219 pub(crate) fn set_target(&self, target_: Option<&EventTarget>) {
220 self.target.set(target_);
221 }
222
223 pub(crate) fn set_related_target(&self, related_target: Option<&EventTarget>) {
224 self.related_target.set(related_target);
225 }
226
227 pub(crate) fn related_target(&self) -> Option<DomRoot<EventTarget>> {
228 self.related_target.get()
229 }
230
231 fn set_in_passive_listener(&self, value: bool) {
232 if value {
233 self.set_flags(EventFlags::InPassiveListener);
234 } else {
235 self.unset_flags(EventFlags::InPassiveListener);
236 }
237 }
238
239 /// <https://dom.spec.whatwg.org/#concept-event-path-append>
240 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
241 pub(crate) fn append_to_path(
242 &self,
243 invocation_target: &EventTarget,
244 shadow_adjusted_target: Option<&EventTarget>,
245 related_target: Option<&EventTarget>,
246 slot_in_closed_tree: bool,
247 ) {
248 // Step 1. Let invocationTargetInShadowTree be false.
249 let mut invocation_target_in_shadow_tree = false;
250
251 // Step 2. If invocationTarget is a node and its root is a shadow root,
252 // then set invocationTargetInShadowTree to true.
253 if invocation_target
254 .downcast::<Node>()
255 .is_some_and(Node::is_in_a_shadow_tree)
256 {
257 invocation_target_in_shadow_tree = true;
258 }
259
260 // Step 3. Let root-of-closed-tree be false.
261 let mut root_of_closed_tree = false;
262
263 // Step 4. If invocationTarget is a shadow root whose mode is "closed", then set root-of-closed-tree to true.
264 if invocation_target
265 .downcast::<ShadowRoot>()
266 .is_some_and(|shadow_root| shadow_root.Mode() == ShadowRootMode::Closed)
267 {
268 root_of_closed_tree = true;
269 }
270
271 // Step 5. Append a new struct to event’s path whose invocation target is invocationTarget,
272 // invocation-target-in-shadow-tree is invocationTargetInShadowTree, shadow-adjusted target is
273 // shadowAdjustedTarget, relatedTarget is relatedTarget, touch target list is touchTargets,
274 // root-of-closed-tree is root-of-closed-tree, and slot-in-closed-tree is slot-in-closed-tree.
275 let event_path_segment = EventPathSegment {
276 invocation_target: Dom::from_ref(invocation_target),
277 shadow_adjusted_target: shadow_adjusted_target.map(Dom::from_ref),
278 related_target: related_target.map(Dom::from_ref),
279 invocation_target_in_shadow_tree,
280 root_of_closed_tree,
281 slot_in_closed_tree,
282 };
283 self.path.borrow_mut().push(event_path_segment);
284 }
285
286 /// <https://dom.spec.whatwg.org/#concept-event-dispatch>
287 pub(crate) fn dispatch(
288 &self,
289 target: &EventTarget,
290 legacy_target_override: bool,
291 can_gc: CanGc,
292 // TODO legacy_did_output_listeners_throw_flag for indexeddb
293 ) -> bool {
294 // > When a user interaction causes firing of an activation triggering input event in a Document document, the user agent
295 // > must perform the following activation notification steps before dispatching the event:
296 // <https://html.spec.whatwg.org/multipage/#user-activation-processing-model>
297 if self.is_an_activation_triggering_input_event() {
298 // TODO: it is not quite clear what does the spec mean by in a `Document`. https://github.com/whatwg/html/issues/12126
299 if let Some(document) = target.downcast::<Node>().map(|node| node.owner_doc()) {
300 UserActivation::handle_user_activation_notification(&document);
301 }
302 }
303
304 let mut target = DomRoot::from_ref(target);
305
306 // Step 1. Set event’s dispatch flag.
307 self.set_flags(EventFlags::Dispatch);
308
309 // Step 2. Let targetOverride be target, if legacy target override flag is not given,
310 // and target’s associated Document otherwise.
311 let target_override_document; // upcasted EventTarget's lifetime depends on this
312 let target_override = if legacy_target_override {
313 target_override_document = target
314 .downcast::<Window>()
315 .expect("legacy_target_override must be true only when target is a Window")
316 .Document();
317 DomRoot::from_ref(target_override_document.upcast::<EventTarget>())
318 } else {
319 target.clone()
320 };
321
322 // Step 3. Let activationTarget be null.
323 let mut activation_target = None;
324
325 // Step 4. Let relatedTarget be the result of retargeting event’s relatedTarget against target.
326 let related_target = self
327 .related_target
328 .get()
329 .map(|related_target| related_target.retarget(&target));
330
331 // Step 5. Let clearTargets be false.
332 let mut clear_targets = false;
333
334 // Step 6. If target is not relatedTarget or target is event’s relatedTarget:
335 let mut pre_activation_result: Option<InputActivationState> = None;
336 if related_target.as_ref() != Some(&target) ||
337 self.related_target.get().as_ref() == Some(&target)
338 {
339 // Step 6.1. Let touchTargets be a new list.
340 // TODO
341
342 // Step 6.2. For each touchTarget of event’s touch target list, append the result of retargeting
343 // TODO
344
345 // touchTarget against target to touchTargets.
346
347 // Step 6.3. Append to an event path with event, target, targetOverride, relatedTarget,
348 // touchTargets, and false.
349 self.append_to_path(
350 &target,
351 Some(target_override.upcast::<EventTarget>()),
352 related_target.as_deref(),
353 false,
354 );
355
356 // Step 6.4. Let isActivationEvent be true, if event is a MouseEvent object and
357 // event’s type attribute is "click"; otherwise false.
358 let is_activation_event = self.is::<MouseEvent>() && self.type_() == atom!("click");
359
360 // Step 6.5. If isActivationEvent is true and target has activation behavior,
361 // then set activationTarget to target.
362 if is_activation_event {
363 if let Some(element) = target.downcast::<Element>() {
364 if element.as_maybe_activatable().is_some() {
365 activation_target = Some(DomRoot::from_ref(element));
366 }
367 }
368 }
369
370 // Step 6.6. Let slottable be target, if target is a slottable and is assigned, and null otherwise.
371 let mut slottable = if target
372 .downcast::<Node>()
373 .and_then(Node::assigned_slot)
374 .is_some()
375 {
376 Some(target.clone())
377 } else {
378 None
379 };
380
381 // Step 6.7. Let slot-in-closed-tree be false
382 let mut slot_in_closed_tree = false;
383
384 // Step 6.8. Let parent be the result of invoking target’s get the parent with event.
385 let mut parent_or_none = target.get_the_parent(self);
386 let mut done = false;
387
388 // Step 6.9. While parent is non-null:
389 while let Some(parent) = parent_or_none.clone() {
390 // Step 6.9.1. If slottable is non-null:
391 if slottable.is_some() {
392 // Step 6.9.1.1. Assert: parent is a slot.
393 let slot = parent
394 .downcast::<HTMLSlotElement>()
395 .expect("parent of slottable is not a slot");
396
397 // Step 6.9.1.2. Set slottable to null.
398 slottable = None;
399
400 // Step 6.9.1.3. If parent’s root is a shadow root whose mode is "closed",
401 // then set slot-in-closed-tree to true.
402 if slot
403 .containing_shadow_root()
404 .is_some_and(|root| root.Mode() == ShadowRootMode::Closed)
405 {
406 slot_in_closed_tree = true;
407 }
408 }
409
410 // Step 6.9.2. If parent is a slottable and is assigned, then set slottable to parent.
411 if parent
412 .downcast::<Node>()
413 .and_then(Node::assigned_slot)
414 .is_some()
415 {
416 slottable = Some(parent.clone());
417 }
418
419 // Step 6.9.3. Let relatedTarget be the result of retargeting event’s relatedTarget against parent.
420 let related_target = self
421 .related_target
422 .get()
423 .map(|related_target| related_target.retarget(&parent));
424
425 // Step 6.9.4. Let touchTargets be a new list.
426 // TODO
427
428 // Step 6.9.5. For each touchTarget of event’s touch target list, append the result of retargeting
429 // touchTarget against parent to touchTargets.
430 // TODO
431
432 // Step 6.9.6. If parent is a Window object, or parent is a node and target’s root is a
433 // shadow-including inclusive ancestor of parent:
434 let root_is_shadow_inclusive_ancestor = parent
435 .downcast::<Node>()
436 .zip(target.downcast::<Node>())
437 .is_some_and(|(parent, target)| {
438 target
439 .GetRootNode(&GetRootNodeOptions::empty())
440 .is_shadow_including_inclusive_ancestor_of(parent)
441 });
442 if parent.is::<Window>() || root_is_shadow_inclusive_ancestor {
443 // Step 6.9.6.1. If isActivationEvent is true, event’s bubbles attribute is true, activationTarget
444 // is null, and parent has activation behavior, then set activationTarget to parent.
445 if is_activation_event && activation_target.is_none() && self.bubbles.get() {
446 if let Some(element) = parent.downcast::<Element>() {
447 if element.as_maybe_activatable().is_some() {
448 activation_target = Some(DomRoot::from_ref(element));
449 }
450 }
451 }
452
453 // Step 6.9.6.2. Append to an event path with event, parent, null, relatedTarget, touchTargets,
454 // and slot-in-closed-tree.
455 self.append_to_path(
456 &parent,
457 None,
458 related_target.as_deref(),
459 slot_in_closed_tree,
460 );
461 }
462 // Step 6.9.7. Otherwise, if parent is relatedTarget, then set parent to null.
463 else if Some(&parent) == related_target.as_ref() {
464 // NOTE: This causes some lifetime shenanigans. Instead of making things complicated,
465 // we just remember to treat parent as null later
466 done = true;
467 }
468 // Step 6.9.8. Otherwise:
469 else {
470 // Step 6.9.8.1. Set target to parent.
471 target = parent.clone();
472
473 // Step 6.9.8.2. If isActivationEvent is true, activationTarget is null, and target has
474 // activation behavior, then set activationTarget to target.
475 if is_activation_event && activation_target.is_none() {
476 if let Some(element) = parent.downcast::<Element>() {
477 if element.as_maybe_activatable().is_some() {
478 activation_target = Some(DomRoot::from_ref(element));
479 }
480 }
481 }
482
483 // Step 6.9.8.3. Append to an event path with event, parent, target, relatedTarget,
484 // touchTargets, and slot-in-closed-tree.
485 self.append_to_path(
486 &parent,
487 Some(&target),
488 related_target.as_deref(),
489 slot_in_closed_tree,
490 );
491 }
492
493 // Step 6.9.9. If parent is non-null, then set parent to the result of invoking parent’s
494 // get the parent with event
495 if !done {
496 parent_or_none = parent.get_the_parent(self);
497 } else {
498 parent_or_none = None;
499 }
500
501 // Step 6.9.10. Set slot-in-closed-tree to false.
502 slot_in_closed_tree = false;
503 }
504
505 // Step 6.10. Let clearTargetsStruct be the last struct in event’s path whose shadow-adjusted target
506 // is non-null.
507 // Step 6.11. Let clearTargets be true if clearTargetsStruct’s shadow-adjusted target,
508 // clearTargetsStruct’s relatedTarget, or an EventTarget object in clearTargetsStruct’s
509 // touch target list is a node and its root is a shadow root; otherwise false.
510 // TODO: Handle touch target list
511 clear_targets = self
512 .path
513 .borrow()
514 .iter()
515 .rev()
516 .find(|segment| segment.shadow_adjusted_target.is_some())
517 // This is "clearTargetsStruct"
518 .is_some_and(|clear_targets| {
519 clear_targets
520 .shadow_adjusted_target
521 .as_ref()
522 .and_then(|target| target.downcast::<Node>())
523 .is_some_and(Node::is_in_a_shadow_tree) ||
524 clear_targets
525 .related_target
526 .as_ref()
527 .and_then(|target| target.downcast::<Node>())
528 .is_some_and(Node::is_in_a_shadow_tree)
529 });
530
531 // Step 6.12. If activationTarget is non-null and activationTarget has legacy-pre-activation behavior,
532 // then run activationTarget’s legacy-pre-activation behavior.
533 if let Some(activation_target) = activation_target.as_ref() {
534 // Not specified in dispatch spec overtly; this is because
535 // the legacy canceled activation behavior of a checkbox
536 // or radio button needs to know what happened in the
537 // corresponding pre-activation behavior.
538 pre_activation_result = activation_target
539 .as_maybe_activatable()
540 .and_then(|activatable| activatable.legacy_pre_activation_behavior(can_gc));
541 }
542
543 let timeline_window = DomRoot::downcast::<Window>(target.global())
544 .filter(|window| window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent));
545
546 // Step 6.13. For each struct in event’s path, in reverse order:
547 for (index, segment) in self.path.borrow().iter().enumerate().rev() {
548 // Step 6.13.1. If struct’s shadow-adjusted target is non-null, then set event’s
549 // eventPhase attribute to AT_TARGET.
550 if segment.shadow_adjusted_target.is_some() {
551 self.phase.set(EventPhase::AtTarget);
552 }
553 // Step 6.13.2. Otherwise, set event’s eventPhase attribute to CAPTURING_PHASE.
554 else {
555 self.phase.set(EventPhase::Capturing);
556 }
557
558 // Step 6.13.3. Invoke with struct, event, "capturing", and legacyOutputDidListenersThrowFlag if given.
559 invoke(
560 segment,
561 index,
562 self,
563 ListenerPhase::Capturing,
564 timeline_window.as_deref(),
565 can_gc,
566 )
567 }
568
569 // Step 6.14. For each struct in event’s path:
570 for (index, segment) in self.path.borrow().iter().enumerate() {
571 // Step 6.14.1. If struct’s shadow-adjusted target is non-null, then set event’s
572 // eventPhase attribute to AT_TARGET.
573 if segment.shadow_adjusted_target.is_some() {
574 self.phase.set(EventPhase::AtTarget);
575 }
576 // Step 6.14.2. Otherwise:
577 else {
578 // Step 6.14.2.1. If event’s bubbles attribute is false, then continue.
579 if !self.bubbles.get() {
580 continue;
581 }
582
583 // Step 6.14.2.2. Set event’s eventPhase attribute to BUBBLING_PHASE.
584 self.phase.set(EventPhase::Bubbling);
585 }
586
587 // Step 6.14.3. Invoke with struct, event, "bubbling", and legacyOutputDidListenersThrowFlag if given.
588 invoke(
589 segment,
590 index,
591 self,
592 ListenerPhase::Bubbling,
593 timeline_window.as_deref(),
594 can_gc,
595 );
596 }
597 }
598
599 // Step 7. Set event’s eventPhase attribute to NONE.
600 self.phase.set(EventPhase::None);
601
602 // FIXME: The UIEvents spec still expects firing an event
603 // to carry a "default action" semantic, but the HTML spec
604 // has removed this concept. Nothing in either spec currently
605 // (as of Jan 11 2020) says that, e.g., a keydown event on an
606 // input element causes a character to be typed; the UIEvents
607 // spec assumes the HTML spec is covering it, and the HTML spec
608 // no longer specifies any UI event other than mouse click as
609 // causing an element to perform an action.
610 // Compare:
611 // https://w3c.github.io/uievents/#default-action
612 // https://dom.spec.whatwg.org/#action-versus-occurance
613 if !self.DefaultPrevented() {
614 if let Some(target) = self.GetTarget() {
615 if let Some(node) = target.downcast::<Node>() {
616 let vtable = vtable_for(node);
617 vtable.handle_event(self, can_gc);
618 }
619 }
620 }
621
622 // Step 8. Set event’s currentTarget attribute to null.
623 self.current_target.set(None);
624
625 // Step 9. Set event’s path to the empty list.
626 self.path.borrow_mut().clear();
627
628 // Step 10. Unset event’s dispatch flag, stop propagation flag, and stop immediate propagation flag.
629 self.unset_flags(EventFlags::Dispatch);
630 self.unset_flags(EventFlags::StopPropagation);
631 self.unset_flags(EventFlags::StopImmediatePropagation);
632
633 // Step 11. If clearTargets is true:
634 if clear_targets {
635 // Step 11.1. Set event’s target to null.
636 self.target.set(None);
637
638 // Step 11.2. Set event’s relatedTarget to null.
639 self.related_target.set(None);
640
641 // Step 11.3. Set event’s touch target list to the empty list.
642 // TODO
643 }
644
645 // Step 12. If activationTarget is non-null:
646 if let Some(activation_target) = activation_target {
647 // NOTE: The activation target may have been disabled by an event handler
648 if let Some(activatable) = activation_target.as_maybe_activatable() {
649 // Step 12.1. If event’s canceled flag is unset, then run activationTarget’s
650 // activation behavior with event.
651 if !self.DefaultPrevented() {
652 activatable.activation_behavior(self, &target, can_gc);
653 }
654 // Step 12.2. Otherwise, if activationTarget has legacy-canceled-activation behavior, then run
655 // activationTarget’s legacy-canceled-activation behavior.
656 else {
657 activatable.legacy_canceled_activation_behavior(pre_activation_result, can_gc);
658 }
659 }
660 }
661
662 // Step 13. Return false if event’s canceled flag is set; otherwise true.
663 !self.DefaultPrevented()
664 }
665
666 #[inline]
667 pub(crate) fn dispatching(&self) -> bool {
668 self.has_flag(EventFlags::Dispatch)
669 }
670
671 #[inline]
672 pub(crate) fn initialized(&self) -> bool {
673 self.has_flag(EventFlags::Initialized)
674 }
675
676 #[inline]
677 pub(crate) fn type_(&self) -> Atom {
678 self.type_.borrow().clone()
679 }
680
681 #[inline]
682 pub(crate) fn mark_as_handled(&self) {
683 self.set_flags(EventFlags::Handled);
684 }
685
686 #[inline]
687 pub(crate) fn flags(&self) -> EventFlags {
688 self.flags.get()
689 }
690
691 pub(crate) fn set_trusted(&self, trusted: bool) {
692 self.is_trusted.set(trusted);
693 }
694
695 pub(crate) fn set_composed(&self, composed: bool) {
696 if composed {
697 self.set_flags(EventFlags::Composed);
698 } else {
699 self.unset_flags(EventFlags::Composed);
700 }
701 }
702
703 /// <https://html.spec.whatwg.org/multipage/#activation-triggering-input-event>
704 fn is_an_activation_triggering_input_event(&self) -> bool {
705 // > An activation triggering input event is any event whose isTrusted attribute is true ..
706 if !self.is_trusted.get() {
707 return false;
708 }
709
710 // > and whose type is one of:
711 let event_type = self.Type();
712 match_domstring_ascii!(event_type,
713 // > - "keydown", provided the key is neither the Esc key nor a shortcut key reserved by the user agent;
714 "keydown" => self.downcast::<KeyboardEvent>().expect("`Event` with type `keydown` should be a `KeyboardEvent` interface").key() != Key::Named(NamedKey::Escape),
715 // > - "mousedown";
716 "mousedown" => true,
717 // > - "pointerdown", provided the event's pointerType is "mouse";
718 "pointerdown" => self.downcast::<PointerEvent>().expect("`Event` with type `pointerdown` should be a `PointerEvent` interface").PointerType().eq("mouse"),
719 // > - "pointerup", provided the event's pointerType is not "mouse"; or
720 "pointerup" => !self.downcast::<PointerEvent>().expect("`Event` with type `pointerup` should be a `PointerEvent` interface").PointerType().eq("mouse"),
721 // > - "touchend".
722 "touchend" => true,
723 _ => false,
724 )
725 }
726
727 /// <https://dom.spec.whatwg.org/#firing-events>
728 pub(crate) fn fire(&self, target: &EventTarget, can_gc: CanGc) -> bool {
729 self.set_trusted(true);
730
731 target.dispatch_event(self, can_gc)
732 }
733
734 /// <https://dom.spec.whatwg.org/#inner-event-creation-steps>
735 fn inner_creation_steps(
736 global: &GlobalScope,
737 proto: Option<HandleObject>,
738 init: &EventBinding::EventInit,
739 can_gc: CanGc,
740 ) -> DomRoot<Event> {
741 // Step 1. Let event be the result of creating a new object using eventInterface.
742 // If realm is non-null, then use that realm; otherwise, use the default behavior defined in Web IDL.
743 let event = Event::new_uninitialized_with_proto(global, proto, can_gc);
744
745 // Step 2. Set event’s initialized flag.
746 event.set_flags(EventFlags::Initialized);
747
748 // Step 3. Initialize event’s timeStamp attribute to the relative high resolution
749 // coarse time given time and event’s relevant global object.
750 // NOTE: This is done inside Event::new_inherited
751
752 // Step 3. For each member → value in dictionary, if event has an attribute whose
753 // identifier is member, then initialize that attribute to value.#
754 event.bubbles.set(init.bubbles);
755 event.cancelable.set(init.cancelable);
756 event.set_composed(init.composed);
757
758 // Step 5. Run the event constructing steps with event and dictionary.
759 // NOTE: Event construction steps may be defined by subclasses
760
761 // Step 6. Return event.
762 event
763 }
764
765 /// Implements the logic behind the [get the parent](https://dom.spec.whatwg.org/#get-the-parent)
766 /// algorithm for shadow roots.
767 pub(crate) fn should_pass_shadow_boundary(&self, shadow_root: &ShadowRoot) -> bool {
768 debug_assert!(self.dispatching());
769
770 // > A shadow root’s get the parent algorithm, given an event, returns null if event’s composed flag
771 // > is unset and shadow root is the root of event’s path’s first struct’s invocation target;
772 // > otherwise shadow root’s host.
773 if self.Composed() {
774 return true;
775 }
776
777 let path = self.path.borrow();
778 let first_invocation_target = &path
779 .first()
780 .expect("Event path is empty despite event currently being dispatched")
781 .invocation_target
782 .as_rooted();
783
784 // The spec doesn't tell us what should happen if the invocation target is not a node
785 let Some(target_node) = first_invocation_target.downcast::<Node>() else {
786 return false;
787 };
788
789 &*target_node.GetRootNode(&GetRootNodeOptions::empty()) != shadow_root.upcast::<Node>()
790 }
791
792 /// <https://dom.spec.whatwg.org/#set-the-canceled-flag>
793 fn set_the_cancelled_flag(&self) {
794 if self.cancelable.get() && !self.has_flag(EventFlags::InPassiveListener) {
795 self.set_flags(EventFlags::Canceled);
796 }
797 }
798}
799
800impl EventMethods<crate::DomTypeHolder> for Event {
801 /// <https://dom.spec.whatwg.org/#concept-event-constructor>
802 fn Constructor(
803 global: &GlobalScope,
804 proto: Option<HandleObject>,
805 can_gc: CanGc,
806 type_: DOMString,
807 init: &EventBinding::EventInit,
808 ) -> Fallible<DomRoot<Event>> {
809 // Step 1. Let event be the result of running the inner event creation steps with
810 // this interface, null, now, and eventInitDict.
811 let event = Event::inner_creation_steps(global, proto, init, can_gc);
812
813 // Step 2. Initialize event’s type attribute to type.
814 *event.type_.borrow_mut() = Atom::from(type_);
815
816 // Step 3. Return event.
817 Ok(event)
818 }
819
820 /// <https://dom.spec.whatwg.org/#dom-event-eventphase>
821 fn EventPhase(&self) -> u16 {
822 self.phase.get() as u16
823 }
824
825 /// <https://dom.spec.whatwg.org/#dom-event-type>
826 fn Type(&self) -> DOMString {
827 DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString
828 }
829
830 /// <https://dom.spec.whatwg.org/#dom-event-target>
831 fn GetTarget(&self) -> Option<DomRoot<EventTarget>> {
832 self.target.get()
833 }
834
835 /// <https://dom.spec.whatwg.org/#dom-event-srcelement>
836 fn GetSrcElement(&self) -> Option<DomRoot<EventTarget>> {
837 self.target.get()
838 }
839
840 /// <https://dom.spec.whatwg.org/#dom-event-currenttarget>
841 fn GetCurrentTarget(&self) -> Option<DomRoot<EventTarget>> {
842 self.current_target.get()
843 }
844
845 /// <https://dom.spec.whatwg.org/#dom-event-composedpath>
846 fn ComposedPath(&self) -> Vec<DomRoot<EventTarget>> {
847 // Step 1. Let composedPath be an empty list.
848 let mut composed_path = vec![];
849
850 // Step 2. Let path be this’s path.
851 let path = self.path.borrow();
852
853 // Step 3. If path is empty, then return composedPath.
854 if path.is_empty() {
855 return composed_path;
856 }
857
858 // Step 4. Let currentTarget be this’s currentTarget attribute value.
859 let current_target = self.GetCurrentTarget();
860
861 // Step 5. Append currentTarget to composedPath.
862 // TODO: https://github.com/whatwg/dom/issues/1343
863 composed_path.push(current_target.clone().expect(
864 "Since the event's path is not empty it is being dispatched and must have a current target",
865 ));
866
867 // Step 6. Let currentTargetIndex be 0.
868 let mut current_target_index = 0;
869
870 // Step 7. Let currentTargetHiddenSubtreeLevel be 0.
871 let mut current_target_hidden_subtree_level = 0;
872
873 // Step 8. Let index be path’s size − 1.
874 // Step 9. While index is greater than or equal to 0:
875 // NOTE: This is just iterating the path in reverse
876 for (index, element) in path.iter().enumerate().rev() {
877 // Step 9.1 If path[index]'s root-of-closed-tree is true, then increase
878 // currentTargetHiddenSubtreeLevel by 1.
879 if element.root_of_closed_tree {
880 current_target_hidden_subtree_level += 1;
881 }
882
883 // Step 9.2 If path[index]'s invocation target is currentTarget, then set
884 // currentTargetIndex to index and break.
885 if current_target
886 .as_ref()
887 .is_some_and(|target| target.as_traced() == element.invocation_target)
888 {
889 current_target_index = index;
890 break;
891 }
892
893 // Step 9.3 If path[index]'s slot-in-closed-tree is true, then decrease
894 // currentTargetHiddenSubtreeLevel by 1.
895 if element.slot_in_closed_tree {
896 current_target_hidden_subtree_level -= 1;
897 }
898
899 // Step 9.4 Decrease index by 1.
900 }
901
902 // Step 10. Let currentHiddenLevel and maxHiddenLevel be currentTargetHiddenSubtreeLevel.
903 let mut current_hidden_level = current_target_hidden_subtree_level;
904 let mut max_hidden_level = current_target_hidden_subtree_level;
905
906 // Step 11. Set index to currentTargetIndex − 1.
907 // Step 12. While index is greater than or equal to 0:
908 // NOTE: This is just iterating part of the path in reverse
909 for element in path.iter().take(current_target_index).rev() {
910 // Step 12.1 If path[index]'s root-of-closed-tree is true, then increase currentHiddenLevel by 1.
911 if element.root_of_closed_tree {
912 current_hidden_level += 1;
913 }
914
915 // Step 12.2 If currentHiddenLevel is less than or equal to maxHiddenLevel,
916 // then prepend path[index]'s invocation target to composedPath.
917 if current_hidden_level <= max_hidden_level {
918 composed_path.insert(0, element.invocation_target.as_rooted());
919 }
920
921 // Step 12.3 If path[index]'s slot-in-closed-tree is true:
922 if element.slot_in_closed_tree {
923 // Step 12.3.1 Decrease currentHiddenLevel by 1.
924 current_hidden_level -= 1;
925
926 // Step 12.3.2 If currentHiddenLevel is less than maxHiddenLevel, then set
927 // maxHiddenLevel to currentHiddenLevel.
928 if current_hidden_level < max_hidden_level {
929 max_hidden_level = current_hidden_level;
930 }
931 }
932
933 // Step 12.4 Decrease index by 1.
934 }
935
936 // Step 13. Set currentHiddenLevel and maxHiddenLevel to currentTargetHiddenSubtreeLevel.
937 current_hidden_level = current_target_hidden_subtree_level;
938 max_hidden_level = current_target_hidden_subtree_level;
939
940 // Step 14. Set index to currentTargetIndex + 1.
941 // Step 15. While index is less than path’s size:
942 // NOTE: This is just iterating the list and skipping the first current_target_index + 1 elements
943 // (The +1 is necessary because the index is 0-based and the skip method is not)
944 for element in path.iter().skip(current_target_index + 1) {
945 // Step 15.1 If path[index]'s slot-in-closed-tree is true, then increase currentHiddenLevel by 1.
946 if element.slot_in_closed_tree {
947 current_hidden_level += 1;
948 }
949
950 // Step 15.2 If currentHiddenLevel is less than or equal to maxHiddenLevel,
951 // then append path[index]'s invocation target to composedPath.
952 if current_hidden_level <= max_hidden_level {
953 composed_path.push(element.invocation_target.as_rooted());
954 }
955
956 // Step 15.3 If path[index]'s root-of-closed-tree is true:
957 if element.root_of_closed_tree {
958 // Step 15.3.1 Decrease currentHiddenLevel by 1.
959 current_hidden_level -= 1;
960
961 // Step 15.3.2 If currentHiddenLevel is less than maxHiddenLevel, then set
962 // maxHiddenLevel to currentHiddenLevel.
963 if current_hidden_level < max_hidden_level {
964 max_hidden_level = current_hidden_level;
965 }
966 }
967
968 // Step 15.4 Increase index by 1.
969 }
970
971 // Step 16. Return composedPath.
972 composed_path
973 }
974
975 /// <https://dom.spec.whatwg.org/#dom-event-defaultprevented>
976 fn DefaultPrevented(&self) -> bool {
977 self.has_flag(EventFlags::Canceled)
978 }
979
980 /// <https://dom.spec.whatwg.org/#dom-event-composed>
981 fn Composed(&self) -> bool {
982 self.has_flag(EventFlags::Composed)
983 }
984
985 /// <https://dom.spec.whatwg.org/#dom-event-preventdefault>
986 fn PreventDefault(&self) {
987 self.set_the_cancelled_flag();
988 }
989
990 /// <https://dom.spec.whatwg.org/#dom-event-stoppropagation>
991 fn StopPropagation(&self) {
992 self.set_flags(EventFlags::StopPropagation);
993 }
994
995 /// <https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation>
996 fn StopImmediatePropagation(&self) {
997 self.set_flags(EventFlags::StopPropagation | EventFlags::StopImmediatePropagation);
998 }
999
1000 /// <https://dom.spec.whatwg.org/#dom-event-bubbles>
1001 fn Bubbles(&self) -> bool {
1002 self.bubbles.get()
1003 }
1004
1005 /// <https://dom.spec.whatwg.org/#dom-event-cancelable>
1006 fn Cancelable(&self) -> bool {
1007 self.cancelable.get()
1008 }
1009
1010 /// <https://dom.spec.whatwg.org/#dom-event-returnvalue>
1011 fn ReturnValue(&self) -> bool {
1012 !self.has_flag(EventFlags::Canceled)
1013 }
1014
1015 /// <https://dom.spec.whatwg.org/#dom-event-returnvalue>
1016 fn SetReturnValue(&self, val: bool) {
1017 if !val {
1018 self.set_the_cancelled_flag();
1019 }
1020 }
1021
1022 /// <https://dom.spec.whatwg.org/#dom-event-cancelbubble>
1023 fn CancelBubble(&self) -> bool {
1024 self.has_flag(EventFlags::StopPropagation)
1025 }
1026
1027 /// <https://dom.spec.whatwg.org/#dom-event-cancelbubble>
1028 fn SetCancelBubble(&self, value: bool) {
1029 if value {
1030 self.set_flags(EventFlags::StopPropagation);
1031 }
1032 }
1033
1034 /// <https://dom.spec.whatwg.org/#dom-event-timestamp>
1035 fn TimeStamp(&self) -> DOMHighResTimeStamp {
1036 self.global()
1037 .performance()
1038 .to_dom_high_res_time_stamp(self.time_stamp)
1039 }
1040
1041 /// <https://dom.spec.whatwg.org/#dom-event-initevent>
1042 fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) {
1043 self.init_event(Atom::from(type_), bubbles, cancelable)
1044 }
1045
1046 /// <https://dom.spec.whatwg.org/#dom-event-istrusted>
1047 fn IsTrusted(&self) -> bool {
1048 self.is_trusted.get()
1049 }
1050}
1051
1052#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
1053pub(crate) enum EventBubbles {
1054 Bubbles,
1055 DoesNotBubble,
1056}
1057
1058impl From<bool> for EventBubbles {
1059 fn from(boolean: bool) -> Self {
1060 if boolean {
1061 EventBubbles::Bubbles
1062 } else {
1063 EventBubbles::DoesNotBubble
1064 }
1065 }
1066}
1067
1068impl From<EventBubbles> for bool {
1069 fn from(bubbles: EventBubbles) -> Self {
1070 match bubbles {
1071 EventBubbles::Bubbles => true,
1072 EventBubbles::DoesNotBubble => false,
1073 }
1074 }
1075}
1076
1077#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
1078pub(crate) enum EventCancelable {
1079 Cancelable,
1080 NotCancelable,
1081}
1082
1083impl From<bool> for EventCancelable {
1084 fn from(boolean: bool) -> Self {
1085 if boolean {
1086 EventCancelable::Cancelable
1087 } else {
1088 EventCancelable::NotCancelable
1089 }
1090 }
1091}
1092
1093impl From<EventCancelable> for bool {
1094 fn from(cancelable: EventCancelable) -> Self {
1095 match cancelable {
1096 EventCancelable::Cancelable => true,
1097 EventCancelable::NotCancelable => false,
1098 }
1099 }
1100}
1101
1102#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
1103pub(crate) enum EventComposed {
1104 Composed,
1105 NotComposed,
1106}
1107
1108impl From<bool> for EventComposed {
1109 fn from(boolean: bool) -> Self {
1110 if boolean {
1111 EventComposed::Composed
1112 } else {
1113 EventComposed::NotComposed
1114 }
1115 }
1116}
1117
1118impl From<EventComposed> for bool {
1119 fn from(composed: EventComposed) -> Self {
1120 match composed {
1121 EventComposed::Composed => true,
1122 EventComposed::NotComposed => false,
1123 }
1124 }
1125}
1126
1127#[derive(Clone, Copy, Debug, Eq, JSTraceable, PartialEq)]
1128#[repr(u16)]
1129#[derive(MallocSizeOf)]
1130pub(crate) enum EventPhase {
1131 None = EventConstants::NONE,
1132 Capturing = EventConstants::CAPTURING_PHASE,
1133 AtTarget = EventConstants::AT_TARGET,
1134 Bubbling = EventConstants::BUBBLING_PHASE,
1135}
1136
1137/// [`EventFlags`] tracks which specification-defined flags in an [`Event`] are enabled.
1138#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
1139pub(crate) struct EventFlags(u8);
1140
1141bitflags! {
1142 impl EventFlags: u8 {
1143 /// <https://dom.spec.whatwg.org/#canceled-flag>
1144 const Canceled = 1 << 0;
1145 /// <https://dom.spec.whatwg.org/#composed-flag>
1146 const Composed = 1 << 1;
1147 /// <https://dom.spec.whatwg.org/#dispatch-flag>
1148 const Dispatch = 1 << 2;
1149 /// The event has been handled somewhere in the DOM, and it should be prevented from being
1150 /// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
1151 const Handled = 1 << 3;
1152 /// <https://dom.spec.whatwg.org/#in-passive-listener-flag>
1153 const InPassiveListener = 1 << 4;
1154 /// <https://dom.spec.whatwg.org/#initialized-flag>
1155 const Initialized = 1 << 5;
1156 /// <https://dom.spec.whatwg.org/#stop-propagation-flag>
1157 const StopPropagation = 1 << 6;
1158 /// <https://dom.spec.whatwg.org/#stop-immediate-propagation-flag>
1159 const StopImmediatePropagation = 1 << 7;
1160 }
1161}
1162
1163impl From<EventFlags> for InputEventResult {
1164 fn from(event_flags: EventFlags) -> Self {
1165 let mut result = Self::default();
1166 if event_flags.contains(EventFlags::Canceled) {
1167 result |= Self::DefaultPrevented;
1168 }
1169 if event_flags.contains(EventFlags::Handled) {
1170 result |= Self::Consumed;
1171 }
1172 result
1173 }
1174}
1175
1176/// <https://dom.spec.whatwg.org/#concept-event-fire>
1177pub(crate) struct EventTask {
1178 pub(crate) target: Trusted<EventTarget>,
1179 pub(crate) name: Atom,
1180 pub(crate) bubbles: EventBubbles,
1181 pub(crate) cancelable: EventCancelable,
1182}
1183
1184impl TaskOnce for EventTask {
1185 fn run_once(self, cx: &mut js::context::JSContext) {
1186 let target = self.target.root();
1187 let bubbles = self.bubbles;
1188 let cancelable = self.cancelable;
1189 target.fire_event_with_params(
1190 self.name,
1191 bubbles,
1192 cancelable,
1193 EventComposed::NotComposed,
1194 CanGc::from_cx(cx),
1195 );
1196 }
1197}
1198
1199/// <https://html.spec.whatwg.org/multipage/#fire-a-simple-event>
1200pub(crate) struct SimpleEventTask {
1201 pub(crate) target: Trusted<EventTarget>,
1202 pub(crate) name: Atom,
1203}
1204
1205impl TaskOnce for SimpleEventTask {
1206 fn run_once(self, cx: &mut js::context::JSContext) {
1207 let target = self.target.root();
1208 target.fire_event(self.name, CanGc::from_cx(cx));
1209 }
1210}
1211
1212/// <https://dom.spec.whatwg.org/#concept-event-listener-invoke>
1213fn invoke(
1214 segment: &EventPathSegment,
1215 segment_index_in_path: usize,
1216 event: &Event,
1217 phase: ListenerPhase,
1218 timeline_window: Option<&Window>,
1219 can_gc: CanGc,
1220 // TODO legacy_output_did_listeners_throw for indexeddb
1221) {
1222 // Step 1. Set event’s target to the shadow-adjusted target of the last struct in event’s path,
1223 // that is either struct or preceding struct, whose shadow-adjusted target is non-null.
1224 event.target.set(
1225 event.path.borrow()[..segment_index_in_path + 1]
1226 .iter()
1227 .rev()
1228 .flat_map(|segment| segment.shadow_adjusted_target.clone())
1229 .next()
1230 .as_deref(),
1231 );
1232
1233 // Step 2. Set event’s relatedTarget to struct’s relatedTarget.
1234 event.related_target.set(segment.related_target.as_deref());
1235
1236 // TODO: Set event’s touch target list to struct’s touch target list.
1237
1238 // Step 4. If event’s stop propagation flag is set, then return.
1239 if event.has_flag(EventFlags::StopPropagation) {
1240 return;
1241 }
1242
1243 // Step 5. Initialize event’s currentTarget attribute to struct’s invocation target.
1244 event.current_target.set(Some(&segment.invocation_target));
1245
1246 // Step 6. Let listeners be a clone of event’s currentTarget attribute value’s event listener list.
1247 let listeners = segment.invocation_target.get_listeners_for(&event.type_());
1248
1249 // Step 7. Let invocationTargetInShadowTree be struct’s invocation-target-in-shadow-tree.
1250 let invocation_target_in_shadow_tree = segment.invocation_target_in_shadow_tree;
1251
1252 // Step 8. Let found be the result of running inner invoke with event, listeners, phase,
1253 // invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.
1254 let found = inner_invoke(
1255 event,
1256 &listeners,
1257 phase,
1258 invocation_target_in_shadow_tree,
1259 timeline_window,
1260 can_gc,
1261 );
1262
1263 // Step 9. If found is false and event’s isTrusted attribute is true:
1264 if !found && event.is_trusted.get() {
1265 // Step 9.1 Let originalEventType be event’s type attribute value.
1266 let original_type = event.type_();
1267
1268 // Step 9.2 If event’s type attribute value is a match for any of the strings in the first column
1269 // in the following table, set event’s type attribute value to the string in the second column on
1270 // the same row as the matching string, and return otherwise.
1271 let legacy_type = match event.type_() {
1272 atom!("animationend") => atom!("webkitAnimationEnd"),
1273 atom!("animationiteration") => atom!("webkitAnimationIteration"),
1274 atom!("animationstart") => atom!("webkitAnimationStart"),
1275 atom!("transitionend") => atom!("webkitTransitionEnd"),
1276 atom!("transitionrun") => atom!("webkitTransitionRun"),
1277 _ => return,
1278 };
1279 *event.type_.borrow_mut() = legacy_type;
1280
1281 // Step 9.3 Inner invoke with event, listeners, phase, invocationTargetInShadowTree,
1282 // and legacyOutputDidListenersThrowFlag if given.
1283 inner_invoke(
1284 event,
1285 &listeners,
1286 phase,
1287 invocation_target_in_shadow_tree,
1288 timeline_window,
1289 can_gc,
1290 );
1291
1292 // Step 9.4 Set event’s type attribute value to originalEventType.
1293 *event.type_.borrow_mut() = original_type;
1294 }
1295}
1296
1297/// <https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke>
1298fn inner_invoke(
1299 event: &Event,
1300 listeners: &EventListeners,
1301 phase: ListenerPhase,
1302 invocation_target_in_shadow_tree: bool,
1303 timeline_window: Option<&Window>,
1304 can_gc: CanGc,
1305) -> bool {
1306 // Step 1. Let found be false.
1307 let mut found = false;
1308
1309 // Step 2. For each listener in listeners, whose removed is false:
1310 for listener in listeners.iter() {
1311 if listener.borrow().removed() {
1312 continue;
1313 }
1314
1315 // Step 2.1 If event’s type attribute value is not listener’s type, then continue.
1316
1317 // Step 2.2. Set found to true.
1318 found = true;
1319
1320 // Step 2.3 If phase is "capturing" and listener’s capture is false, then continue.
1321 // Step 2.4 If phase is "bubbling" and listener’s capture is true, then continue.
1322 if listener.borrow().phase() != phase {
1323 continue;
1324 }
1325
1326 let event_target = event
1327 .GetCurrentTarget()
1328 .expect("event target was initialized as part of \"invoke\"");
1329
1330 // Step 2.5 If listener’s once is true, then remove an event listener given event’s currentTarget
1331 // attribute value and listener.
1332 if listener.borrow().once() {
1333 event_target.remove_listener(&event.type_(), listener);
1334 }
1335
1336 let Some(compiled_listener) =
1337 listener
1338 .borrow()
1339 .get_compiled_listener(&event_target, &event.type_(), can_gc)
1340 else {
1341 continue;
1342 };
1343
1344 // Step 2.6 Let global be listener callback’s associated realm’s global object.
1345 let global = compiled_listener.associated_global();
1346
1347 // Step 2.7 Let currentEvent be undefined.
1348 let mut current_event = None;
1349 // Step 2.8 If global is a Window object:
1350 if let Some(window) = global.downcast::<Window>() {
1351 // Step 2.8.1 Set currentEvent to global’s current event.
1352 current_event = window.current_event();
1353
1354 // Step 2.8.2 If invocationTargetInShadowTree is false, then set global’s current event to event.
1355 if !invocation_target_in_shadow_tree {
1356 current_event = window.set_current_event(Some(event))
1357 }
1358 }
1359
1360 // Step 2.9 If listener’s passive is true, then set event's in passive listener flag.
1361 event.set_in_passive_listener(event_target.is_passive(listener));
1362
1363 // Step 2.10 If global is a Window object, then record timing info for event listener
1364 // given event and listener.
1365 // Step 2.11 Call a user object’s operation with listener’s callback, "handleEvent", « event »,
1366 // and event’s currentTarget attribute value. If this throws an exception exception:
1367 // Step 2.10.1 Report exception for listener’s callback’s corresponding JavaScript object’s
1368 // associated realm’s global object.
1369 // TODO Step 2.10.2 Set legacyOutputDidListenersThrowFlag if given.
1370 let marker = TimelineMarker::start("DOMEvent".to_owned());
1371 compiled_listener.call_or_handle_event(
1372 &event_target,
1373 event,
1374 ExceptionHandling::Report,
1375 can_gc,
1376 );
1377 if let Some(window) = timeline_window {
1378 window.emit_timeline_marker(marker.end());
1379 }
1380
1381 // Step 2.12 Unset event’s in passive listener flag.
1382 event.set_in_passive_listener(false);
1383
1384 // Step 2.13 If global is a Window object, then set global’s current event to currentEvent.
1385 if let Some(window) = global.downcast::<Window>() {
1386 window.set_current_event(current_event.as_deref());
1387 }
1388
1389 // Step 2.13: If event’s stop immediate propagation flag is set, then break.
1390 if event.has_flag(EventFlags::StopImmediatePropagation) {
1391 break;
1392 }
1393 }
1394
1395 // Step 3.
1396 found
1397}