Skip to main content

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