Skip to main content

script/dom/document/
focus.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, Ref};
6use std::cmp::Ordering;
7
8use bitflags::bitflags;
9use embedder_traits::FocusSequenceNumber;
10use js::context::{JSContext, NoGC};
11use js::gc::RootedGuard;
12use keyboard_types::{KeyboardEvent as KeyboardTypesEvent, Modifiers};
13use script_bindings::cell::DomRefCell;
14use script_bindings::codegen::GenericBindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
15use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
16use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
17use script_bindings::inheritance::Castable;
18use script_bindings::root::{Dom, DomRoot};
19use servo_base::id::BrowsingContextId;
20use servo_constellation_traits::{
21    RemoteFocusOperation, ScriptToConstellationMessage, SequentialFocusDirection,
22};
23
24use crate::dom::bindings::root::MutNullableDom;
25use crate::dom::focusevent::FocusEventType;
26use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
27use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
28use crate::dom::node::focus::{FocusNavigationScopeOwner, FocusTrigger};
29use crate::dom::types::{Element, EventTarget, FocusEvent, HTMLElement, HTMLIFrameElement, Window};
30use crate::dom::{Document, Event, EventBubbles, EventCancelable, Node, NodeTraits};
31use crate::realms::enter_auto_realm;
32
33/// The kind of focusable area a [`FocusableArea`] is. A [`FocusableArea`] may be click focusable,
34/// sequentially focusable, or both.
35#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
36pub(crate) struct FocusableAreaKind(u8);
37
38bitflags! {
39    impl FocusableAreaKind: u8 {
40        /// <https://html.spec.whatwg.org/multipage/#click-focusable>
41        ///
42        /// > A focusable area is said to be click focusable if the user agent determines that it is
43        /// > click focusable. User agents should consider focusable areas with non-null tabindex values
44        /// > to be click focusable.
45        const Click = 1 << 0;
46        /// <https://html.spec.whatwg.org/multipage/#sequentially-focusable>.
47        ///
48        /// > A focusable area is said to be sequentially focusable if it is included in its
49        /// > Document's sequential focus navigation order and the user agent determines that it is
50        /// > sequentially focusable.
51        const Sequential = 1 << 1;
52    }
53}
54
55/// <https://html.spec.whatwg.org/multipage/#focusable-area>
56#[derive(Clone, Default, JSTraceable, MallocSizeOf, PartialEq)]
57#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
58pub(crate) enum FocusableArea {
59    Node {
60        node: Dom<Node>,
61        kind: FocusableAreaKind,
62    },
63    /// The viewport of an `<iframe>` element in its containing `Document`. `<iframe>`s
64    /// are focusable areas, but have special behavior when focusing.
65    IFrameViewport {
66        iframe_element: Dom<HTMLIFrameElement>,
67        kind: FocusableAreaKind,
68    },
69    #[default]
70    Viewport,
71}
72
73impl js::gc::Rootable for FocusableArea {}
74
75impl std::fmt::Debug for FocusableArea {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::Node { node, kind } => f
79                .debug_struct("Node")
80                .field("node", node)
81                .field("kind", kind)
82                .finish(),
83            Self::IFrameViewport {
84                iframe_element,
85                kind,
86            } => f
87                .debug_struct("IFrameViewport")
88                .field("pipeline", &iframe_element.pipeline_id())
89                .field("kind", kind)
90                .finish(),
91            Self::Viewport => write!(f, "Viewport"),
92        }
93    }
94}
95
96impl FocusableArea {
97    pub(crate) fn kind(&self) -> FocusableAreaKind {
98        match self {
99            Self::Node { kind, .. } | Self::IFrameViewport { kind, .. } => *kind,
100            Self::Viewport => FocusableAreaKind::Click | FocusableAreaKind::Sequential,
101        }
102    }
103
104    /// If this focusable area is a node, return it as an [`Element`] if it is possible, otherwise
105    /// return `None`. This is the [`Element`] to use for applying `:focus` state and for firing
106    /// `blur` and `focus` events if any.
107    ///
108    /// Note: This is currently in a transitional state while the code moves more toward the
109    /// specification.
110    pub(crate) fn element(&self) -> Option<&Element> {
111        match self {
112            Self::Node { node, .. } => node.downcast(),
113            Self::IFrameViewport { iframe_element, .. } => Some(iframe_element.upcast()),
114            Self::Viewport => None,
115        }
116    }
117
118    /// <https://html.spec.whatwg.org/multipage/#dom-anchor>
119    pub(crate) fn dom_anchor(&self, document: &Document) -> DomRoot<Node> {
120        match self {
121            Self::Node { node, .. } => node.as_rooted(),
122            Self::IFrameViewport { iframe_element, .. } => {
123                DomRoot::from_ref(iframe_element.upcast())
124            },
125            Self::Viewport => DomRoot::from_ref(document.upcast()),
126        }
127    }
128
129    pub(crate) fn focus_chain(&self) -> Vec<FocusableArea> {
130        match self {
131            FocusableArea::Node { .. } | FocusableArea::IFrameViewport { .. } => {
132                vec![self.clone(), FocusableArea::Viewport]
133            },
134            FocusableArea::Viewport => vec![self.clone()],
135        }
136    }
137
138    /// Step 4.2 from <https://html.spec.whatwg.org/multipage/#focus-update-steps>:
139    /// > - If entry is an element, let focus event target be entry.
140    /// > - If entry is a Document object, let focus event target be that Document
141    /// >   object's relevant global object.
142    /// > - Otherwise, let focus event target be null.
143    pub(crate) fn event_target<'a>(&'a self, window: &'a Window) -> &'a EventTarget {
144        match self {
145            FocusableArea::Node { node, .. } => node.upcast::<EventTarget>(),
146            FocusableArea::IFrameViewport { iframe_element, .. } => iframe_element.upcast(),
147            FocusableArea::Viewport => window.upcast::<EventTarget>(),
148        }
149    }
150}
151
152/// The [`DocumentFocusHandler`] is a structure responsible for handling and storing data related to
153/// focus for the `Document`. It exists to decrease the size of the `Document`.
154/// structure.
155#[derive(JSTraceable, MallocSizeOf)]
156#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
157pub(crate) struct DocumentFocusHandler {
158    /// The [`Window`] element for this [`DocumentFocusHandler`].
159    window: Dom<Window>,
160    /// The focused area of the [`Document`].
161    ///
162    /// <https://html.spec.whatwg.org/multipage/#focused-area-of-the-document>
163    focused_area: DomRefCell<FocusableArea>,
164    /// The last sequence number sent to the constellation.
165    #[no_trace]
166    focus_sequence: Cell<FocusSequenceNumber>,
167    /// Indicates whether the container is included in the top-level browsing
168    /// context's focus chain (not considering system focus). This is independent
169    /// of the whether or not all `Document`s in a `WebView` have system focus.
170    has_focus: Cell<bool>,
171    /// <https://html.spec.whatwg.org/multipage/#sequential-focus-navigation-starting-point>
172    sequential_focus_navigation_starting_point: MutNullableDom<Node>,
173    last_user_interaction_was_keyboard: Cell<bool>,
174}
175
176impl DocumentFocusHandler {
177    pub(crate) fn new(window: &Window, has_focus: bool) -> Self {
178        Self {
179            window: Dom::from_ref(window),
180            focused_area: Default::default(),
181            focus_sequence: Cell::new(FocusSequenceNumber::default()),
182            has_focus: Cell::new(has_focus),
183            sequential_focus_navigation_starting_point: Default::default(),
184            last_user_interaction_was_keyboard: Cell::new(true),
185        }
186    }
187
188    pub(crate) fn has_focus(&self) -> bool {
189        self.has_focus.get()
190    }
191
192    pub(crate) fn set_has_focus(&self, has_focus: bool) {
193        self.has_focus.set(has_focus);
194    }
195
196    pub(crate) fn set_last_user_interaction_was_keyboard(
197        &self,
198        last_user_interaction_was_keyboard: bool,
199    ) {
200        self.last_user_interaction_was_keyboard
201            .set(last_user_interaction_was_keyboard);
202    }
203
204    /// Return the element that currently has focus. If `None` is returned the viewport itself has focus.
205    pub(crate) fn focused_area(&self) -> Ref<'_, FocusableArea> {
206        self.focused_area.borrow()
207    }
208
209    /// <https://drafts.csswg.org/selectors/#the-focus-visible-pseudo>
210    fn focused_element_supports_keyboard_input(element: &Element) -> bool {
211        // > If the element supports keyboard input (such as an input element,
212        // > or any other element that would triggers a virtual keyboard
213        // > to be shown on focus if a physical keyboard were not present), indicate focus.
214        element.is::<HTMLTextAreaElement>() ||
215            element
216                .downcast::<HTMLInputElement>()
217                .is_some_and(|input| input.is_textual_or_password()) ||
218            element
219                .downcast::<HTMLElement>()
220                .is_some_and(|html_element| html_element.is_editing_host())
221    }
222
223    /// Updates the focus-within state for all relevent ancestors. In case there were both
224    /// a previous and new focused element, all ancestors up to the common ancestor are
225    /// traversed. If that's not the case, all ancestors of the respective nodes are updated up
226    /// to the root node.
227    fn update_focus_within_state(
228        no_gc: &NoGC,
229        previous_element: Option<&Element>,
230        new_element: Option<&Element>,
231    ) {
232        let maybe_common_ancestor = match (previous_element, new_element) {
233            (Some(previous_element), Some(new_element)) => previous_element
234                .upcast::<Node>()
235                .common_ancestor_in_flat_tree(no_gc, new_element.upcast()),
236            _ => None,
237        };
238        if let Some(previous_element) = previous_element {
239            previous_element.set_focus_within_state_for_inclusive_ancestors(
240                no_gc,
241                maybe_common_ancestor.as_deref(),
242                false,
243            );
244        }
245        if let Some(new_element) = new_element {
246            new_element.set_focus_within_state_for_inclusive_ancestors(
247                no_gc,
248                maybe_common_ancestor.as_deref(),
249                true,
250            );
251        }
252    }
253
254    /// Set the element that currently has focus and update the focus state for both the previously
255    /// set element (if any) and the new one, as well as the new one. This will not do anything if
256    /// the new element is the same as the previous one. Note that this *will not* fire any focus
257    /// events. If that is necessary the [`DocumentFocusHandler::focus`] should be used.
258    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
259    pub(crate) fn set_focused_area(&self, no_gc: &NoGC, new_focusable_area: FocusableArea) {
260        if new_focusable_area == *self.focused_area.borrow() {
261            return;
262        }
263        self.window
264            .layout()
265            .set_force_accessibility_update_if_active();
266
267        // From <https://html.spec.whatwg.org/multipage/#selector-focus>
268        // > For the purposes of the CSS :focus pseudo-class, an element has the focus when:
269        // >  - it is not itself a navigable container; and
270        // >  - any of the following are true:
271        // >    - it is one of the elements listed in the current focus chain of the top-level
272        // >      traversable; or
273        // >    - its shadow root shadowRoot is not null and shadowRoot is the root of at least one
274        // >      element that has the focus.
275        //
276        // We are trying to accomplish the last requirement here, by walking up the tree and
277        // marking each shadow host as focused.
278        fn recursively_set_focus_status(no_gc: &NoGC, element: &Element, new_state: bool) {
279            element.set_focus_state(no_gc, new_state);
280
281            let Some(shadow_root) = element.containing_shadow_root() else {
282                return;
283            };
284            recursively_set_focus_status(no_gc, &shadow_root.Host(), new_state);
285        }
286
287        if let Some(previously_focused_element) = self.focused_area.borrow().element() {
288            recursively_set_focus_status(no_gc, previously_focused_element, false);
289            previously_focused_element.set_focusring_state(no_gc, false);
290        }
291        if let Some(newly_focused_element) = new_focusable_area.element() {
292            recursively_set_focus_status(no_gc, newly_focused_element, true);
293
294            // We should never show a focus ring on an iframe, since focus is handled separately
295            // inside of that iframe
296            if !newly_focused_element.is::<HTMLIFrameElement>() &&
297                (self.last_user_interaction_was_keyboard.get() ||
298                    Self::focused_element_supports_keyboard_input(newly_focused_element))
299            {
300                newly_focused_element.set_focusring_state(no_gc, true);
301            }
302        }
303
304        Self::update_focus_within_state(
305            no_gc,
306            self.focused_area.borrow().element(),
307            new_focusable_area.element(),
308        );
309
310        *self.focused_area.borrow_mut() = new_focusable_area;
311    }
312
313    /// Get the last sequence number sent to the constellation.
314    ///
315    /// Received focus-related messages with sequence numbers less than the one
316    /// returned by this method must be discarded.
317    pub fn focus_sequence(&self) -> FocusSequenceNumber {
318        self.focus_sequence.get()
319    }
320
321    /// Generate the next sequence number for focus-related messages.
322    fn increment_fetch_focus_sequence(&self) -> FocusSequenceNumber {
323        self.focus_sequence.set(FocusSequenceNumber(
324            self.focus_sequence
325                .get()
326                .0
327                .checked_add(1)
328                .expect("too many focus messages have been sent"),
329        ));
330        self.focus_sequence.get()
331    }
332
333    /// <https://html.spec.whatwg.org/multipage/#current-focus-chain-of-a-top-level-traversable>
334    pub(crate) fn current_focus_chain(&self) -> Vec<FocusableArea> {
335        // > The current focus chain of a top-level traversable is the focus chain of the
336        // > currently focused area of traversable, if traversable is non-null, or an empty list
337        // > otherwise.
338
339        // We cannot easily get the full focus chain of the top-level traversable, so we just
340        // get the bits that intersect with this `Document`. The rest will be handled
341        // internally in [`Self::focus_update_steps`].
342        if !self.has_focus() {
343            return vec![];
344        }
345        self.focused_area().focus_chain()
346    }
347
348    /// Reassign the focus context to the element that last requested focus during this
349    /// transaction, or the document if no elements requested it.
350    pub(crate) fn focus(
351        &self,
352        cx: &mut JSContext,
353        new_focus_target: &FocusableArea,
354        focus_trigger: FocusTrigger,
355    ) {
356        rooted!(&in(cx) let new_focus_chain = new_focus_target.focus_chain());
357        rooted!(&in(cx) let old_focus_chain = self.current_focus_chain());
358
359        self.focus_update_steps(
360            cx,
361            new_focus_chain,
362            old_focus_chain,
363            new_focus_target,
364            false, /* for_system_focus_change */
365            focus_trigger,
366        );
367
368        // Advertise the change in the focus chain.
369        // <https://html.spec.whatwg.org/multipage/#focus-chain>
370        // <https://html.spec.whatwg.org/multipage/#focusing-steps>
371        //
372        // TODO: Integrate this into the "focus update steps."
373        //
374        // If the top-level BC doesn't have system focus, this won't
375        // have an immediate effect, but it will when we gain system
376        // focus again. Therefore we still have to send `ScriptMsg::
377        // Focus`.
378        //
379        // When a container with a non-null nested browsing context is
380        // focused, its active document becomes the focused area of the
381        // top-level browsing context instead. Therefore we need to let
382        // the constellation know if such a container is focused.
383        //
384        // > The focusing steps for an object `new focus target` [...]
385        // >
386        // >  3. If `new focus target` is a browsing context container
387        // >     with non-null nested browsing context, then set
388        // >     `new focus target` to the nested browsing context's
389        // >     active document.
390        let child_browsing_context_id = match new_focus_target {
391            FocusableArea::IFrameViewport { iframe_element, .. } => {
392                iframe_element.browsing_context_id()
393            },
394            _ => None,
395        };
396        let sequence = self.increment_fetch_focus_sequence();
397
398        debug!(
399            "Advertising the focus request to the constellation \
400                        with sequence number {sequence:?} and child \
401                        {child_browsing_context_id:?}",
402        );
403        self.window.send_to_constellation(
404            ScriptToConstellationMessage::FocusAncestorBrowsingContextsForFocusingSteps(
405                child_browsing_context_id,
406                sequence,
407            ),
408        );
409    }
410
411    /// <https://html.spec.whatwg.org/multipage/#focus-update-steps>
412    ///
413    /// When the `for_system_focus_change` argument is true only events are fired,
414    /// but the internal state of the [`DocumentFocusHandler`] is not updated. This
415    /// is so that the focus state is preserved when the `WebView` regains system
416    /// focus.
417    pub(crate) fn focus_update_steps(
418        &self,
419        cx: &mut JSContext,
420        mut new_focus_chain: RootedGuard<'_, Vec<FocusableArea>>,
421        mut old_focus_chain: RootedGuard<'_, Vec<FocusableArea>>,
422        new_focus_target: &FocusableArea,
423        for_system_focus_change: bool,
424        focus_trigger: FocusTrigger,
425    ) {
426        let new_focus_chain_was_empty = new_focus_chain.is_empty();
427
428        // Step 1: If the last entry in old chain and the last entry in new chain are the same,
429        // pop the last entry from old chain and the last entry from new chain and redo this
430        // step.
431        //
432        // We avoid recursion here.
433        while let (Some(last_new), Some(last_old)) =
434            (new_focus_chain.last(), old_focus_chain.last())
435        {
436            if last_new == last_old {
437                new_focus_chain.as_mut_ref(cx.no_gc()).pop();
438                old_focus_chain.as_mut_ref(cx.no_gc()).pop();
439            } else {
440                break;
441            }
442        }
443
444        // If the two focus chains are both empty, focus hasn't changed. This isn't in the
445        // specification, but we must do it because we set the focused area to the viewport
446        // before blurring. If no focus changes, that would mean the currently focused element
447        // loses focus.
448        if old_focus_chain.is_empty() && new_focus_chain.is_empty() {
449            return;
450        }
451
452        // https://drafts.csswg.org/selectors/#the-focus-visible-pseudo
453        // > If the previously-focused element indicated focus,
454        // > and a script causes focus to move elsewhere,
455        // > indicate focus on the newly focused element.
456        // > Conversely, if the previously-focused element did not indicate focus,
457        // > and a script causes focus to move elsewhere,
458        // > don’t indicate focus on the newly focused element.
459        //
460        // We use `last_user_interaction_was_keyboard` to track whether the last non-script
461        // trigger was a keyboard trigger.
462        match focus_trigger {
463            FocusTrigger::Keyboard => {
464                self.last_user_interaction_was_keyboard.set(true);
465            },
466            FocusTrigger::Click => {
467                self.last_user_interaction_was_keyboard.set(false);
468            },
469            FocusTrigger::Script => {
470                // Explicitly not updating anything
471            },
472        }
473
474        // Although the "focusing steps" in the HTML specification say to wait until after firing
475        // the "blur" event to change the currently focused area of the Document, browsers tend
476        // to set it to the viewport before firing the "blur" event.
477        //
478        // See https://github.com/whatwg/html/issues/1569
479        if !for_system_focus_change {
480            self.set_focused_area(cx.no_gc(), FocusableArea::Viewport);
481        }
482
483        // Step 2: For each entry entry in old chain, in order, run these substeps:
484        // Note: `old_focus_chain` might be empty!
485        let last_old_focus_chain_entry = old_focus_chain.len().saturating_sub(1);
486        for (index, entry) in old_focus_chain.iter().enumerate() {
487            // Step 2.1: If entry is an input element, and the change event applies to the element,
488            // and the element does not have a defined activation behavior, and the user has
489            // changed the element's value or its list of selected files while the control was
490            // focused without committing that change (such that it is different to what it was
491            // when the control was first focused), then:
492            // Step 2.1.1: Set entry's user validity to true.
493            // Step 2.1.2: Fire an event named change at the element, with the bubbles attribute initialized to true.
494            // TODO: Implement this.
495
496            // Step 2.2:
497            // - If entry is an element, let blur event target be entry.
498            // - If entry is a Document object, let blur event target be that Document object's
499            //    relevant global object.
500            // - Otherwise, let blur event target be null.
501            //
502            // Note: We always send focus and blur events for `<iframe>` elements, but other
503            // browsers only seem to do that conditionally. This needs a bit more research.
504            let blur_event_target = entry.event_target(&self.window);
505
506            // Step 2.3: If entry is the last entry in old chain, and entry is an Element, and
507            // the last entry in new chain is also an Element, then let related blur target be
508            // the last entry in new chain. Otherwise, let related blur target be null.
509            //
510            // Note: This can only happen when the focused `Document` doesn't change and we are
511            // moving focus from one element to another. These elements are the last in the chain
512            // because of the popping we do at the start of these steps.
513            let related_blur_target = match new_focus_chain.last() {
514                Some(FocusableArea::Node { node, .. })
515                    if index == last_old_focus_chain_entry &&
516                        matches!(entry, FocusableArea::Node { .. }) =>
517                {
518                    Some(node.upcast())
519                },
520                _ => None,
521            };
522
523            // Step 2.4: If blur event target is not null, fire a focus event named blur at
524            // blur event target, with related blur target as the related target.
525            //
526            // <https://w3c.github.io/uievents/#focusout>
527            // "blur" must be fired before "focusout".
528            self.fire_focus_event(
529                cx,
530                FocusEventType::Blur,
531                blur_event_target,
532                related_blur_target,
533            );
534
535            self.fire_focus_event(
536                cx,
537                FocusEventType::FocusOut,
538                blur_event_target,
539                related_blur_target,
540            );
541        }
542
543        if !for_system_focus_change {
544            // Step 3: Apply any relevant platform-specific conventions for focusing new focus
545            // target. (For example, some platforms select the contents of a text control when that
546            // control is focused.)
547            if &*self.focused_area() != new_focus_target &&
548                let Some(html_element) = new_focus_target
549                    .element()
550                    .and_then(|element| element.downcast::<HTMLElement>())
551            {
552                html_element.handle_focus_state_for_contenteditable(cx);
553            }
554
555            self.set_has_focus(!new_focus_chain_was_empty);
556        }
557
558        // Step 4: For each entry entry in new chain, in reverse order, run these substeps:
559        // Note: `new_focus_chain` might be empty!
560        let last_new_focus_chain_entry = new_focus_chain.len().saturating_sub(1); // Might be empty, so calculated here.
561        for (index, entry) in new_focus_chain.iter().enumerate().rev() {
562            // Step 4.1: If entry is a focusable area, and the focused area of the document is
563            // not entry:
564            //
565            // Here we deviate from the specification a bit, as all focus chain elements are
566            // focusable areas currently. We just assume that it means the first entry of the
567            // chain, which is the new focus target
568            if index == 0 {
569                // Step 4.1.1: Set document's relevant global object's navigation API's focus
570                // changed during ongoing navigation to true.
571                // TODO: Implement this.
572
573                // Step 4.1.2: Designate entry as the focused area of the document.
574                if !for_system_focus_change {
575                    self.set_focused_area(cx.no_gc(), entry.clone());
576                }
577            }
578
579            // Step 4.2:
580            // - If entry is an element, let focus event target be entry.
581            // - If entry is a Document object, let focus event target be that Document
582            //   object's relevant global object.
583            // - Otherwise, let focus event target be null.
584            //
585            // Note: We always send focus and blur events for `<iframe>` elements, but other
586            // browsers only seem to do that conditionally. This needs a bit more research.
587            let focus_event_target = entry.event_target(&self.window);
588
589            // Step 4.3: If entry is the last entry in new chain, and entry is an Element, and
590            // the last entry in old chain is also an Element, then let related focus target be
591            // the last entry in old chain. Otherwise, let related focus target be null.
592            //
593            // Note: This can only happen when the focused `Document` doesn't change and we are
594            // moving focus from one element to another. These elements are the last in the chain
595            // because of the popping we do at the start of these steps.
596            let related_focus_target = match old_focus_chain.last() {
597                Some(FocusableArea::Node { node, .. })
598                    if index == last_new_focus_chain_entry &&
599                        matches!(entry, FocusableArea::Node { .. }) =>
600                {
601                    Some(node.upcast())
602                },
603                _ => None,
604            };
605
606            // Step 4.4: If focus event target is not null, fire a focus event named focus at
607            // focus event target, with related focus target as the related target.
608            //
609            // <https://w3c.github.io/uievents/#focusin>
610            // "focus" must be fired before "focusIn".
611            self.fire_focus_event(
612                cx,
613                FocusEventType::Focus,
614                focus_event_target,
615                related_focus_target,
616            );
617
618            self.fire_focus_event(
619                cx,
620                FocusEventType::FocusIn,
621                focus_event_target,
622                related_focus_target,
623            );
624        }
625    }
626
627    /// <https://html.spec.whatwg.org/multipage/#fire-a-focus-event>
628    pub(crate) fn fire_focus_event(
629        &self,
630        cx: &mut JSContext,
631        focus_event_type: FocusEventType,
632        event_target: &EventTarget,
633        related_target: Option<&EventTarget>,
634    ) {
635        let event_name = match focus_event_type {
636            FocusEventType::Focus => "focus".into(),
637            FocusEventType::Blur => "blur".into(),
638            FocusEventType::FocusIn => "focusin".into(),
639            FocusEventType::FocusOut => "focusout".into(),
640        };
641
642        let event_bubbles = match focus_event_type {
643            FocusEventType::Focus | FocusEventType::Blur => EventBubbles::DoesNotBubble,
644            FocusEventType::FocusIn | FocusEventType::FocusOut => EventBubbles::Bubbles,
645        };
646
647        let event = FocusEvent::new(
648            cx,
649            &self.window,
650            event_name,
651            event_bubbles,
652            EventCancelable::NotCancelable,
653            Some(&self.window),
654            0i32,
655            related_target,
656        );
657        let event = event.upcast::<Event>();
658        event.set_trusted(true);
659        event.set_composed(true);
660        event.fire(cx, event_target);
661    }
662
663    /// <https://html.spec.whatwg.org/multipage/#focus-fixup-rule>
664    /// > For each doc of docs, if the focused area of doc is not a focusable area, then run the
665    /// > focusing steps for doc's viewport, and set doc's relevant global object's navigation API's
666    /// > focus changed during ongoing navigation to false.
667    ///
668    /// TODO: Handle the "focus changed during ongoing navigation" flag.
669    pub(crate) fn perform_focus_fixup_rule(&self, cx: &mut JSContext) {
670        if self
671            .focused_area
672            .borrow()
673            .element()
674            .is_none_or(|focused| focused.is_focusable_area(cx))
675        {
676            return;
677        }
678        self.focus(cx, &FocusableArea::Viewport, FocusTrigger::Script);
679    }
680
681    pub(crate) fn set_sequential_focus_navigation_starting_point(&self, node: &Node) {
682        self.sequential_focus_navigation_starting_point
683            .set(Some(node));
684    }
685
686    fn sequential_focus_navigation_starting_point(&self) -> Option<DomRoot<Node>> {
687        self.sequential_focus_navigation_starting_point
688            .get()
689            .filter(|node| node.is_connected())
690    }
691
692    pub(crate) fn sequential_focus_navigation_via_keyboard_event(
693        &self,
694        cx: &mut JSContext,
695        event: &KeyboardTypesEvent,
696    ) {
697        let direction = if event.modifiers.contains(Modifiers::SHIFT) {
698            SequentialFocusDirection::Backward
699        } else {
700            SequentialFocusDirection::Forward
701        };
702
703        self.sequential_focus_navigation(cx, direction);
704    }
705
706    /// <https://html.spec.whatwg.org/multipage/#sequential-focus-navigation:currently-focused-area-of-a-top-level-traversable>
707    fn sequential_focus_navigation(&self, cx: &mut JSContext, direction: SequentialFocusDirection) {
708        // > When the user requests that focus move from the currently focused area of a top-level
709        // > traversable to the next or previous focusable area (e.g., as the default action of
710        // > pressing the tab key), or when the user requests that focus sequentially move to a
711        // > top-level traversable in the first place (e.g., from the browser's location bar), the
712        // > user agent must use the following algorithm:
713
714        // > 1. Let starting point be the currently focused area of a top-level traversable, if the
715        // > user requested to move focus sequentially from there, or else the top-level traversable
716        // > itself, if the user instead requested to move focus from outside the top-level
717        // > traversable.
718        //
719        // Note: Here `None` represents the current traversible.
720        let mut starting_point = self
721            .focused_area()
722            .element()
723            .map(|element| DomRoot::from_ref(element.upcast::<Node>()));
724
725        // > 2. If there is a sequential focus navigation starting point defined and it is inside
726        // > starting point, then let starting point be the sequential focus navigation starting point
727        // > instead.
728        if let Some(sequential_focus_navigation_starting_point) =
729            self.sequential_focus_navigation_starting_point() &&
730            starting_point.as_ref().is_none_or(|starting_point| {
731                starting_point.is_ancestor_of(&sequential_focus_navigation_starting_point)
732            })
733        {
734            starting_point = Some(sequential_focus_navigation_starting_point);
735        }
736
737        // > 3. Let direction be "forward" if the user requested the next control, and "backward" if
738        // > the user requested the previous control.
739        //
740        // Note: This is handled by the `direction` argument to this method.
741        self.sequential_focus_navigation_loop(
742            cx,
743            starting_point,
744            direction,
745            false, /* allow_focusing_viewport */
746        );
747    }
748
749    /// The inner loop ("Loop") of:
750    /// <https://html.spec.whatwg.org/multipage/#sequential-focus-navigation:currently-focused-area-of-a-top-level-traversable>
751    fn sequential_focus_navigation_loop(
752        &self,
753        cx: &mut JSContext,
754        starting_point: Option<DomRoot<Node>>,
755        direction: SequentialFocusDirection,
756        allow_focusing_viewport: bool,
757    ) {
758        // > 4. Loop: Let selection mechanism be "sequential" if starting point is a navigable or if
759        // > starting point is in its Document's sequential focus navigation order.
760        // > Otherwise, starting point is not in its Document's sequential focus navigation order;
761        // > let selection mechanism be "DOM".
762        let starting_point_is_navigable = starting_point
763            .as_ref()
764            .is_none_or(|starting_point| starting_point.is::<HTMLIFrameElement>());
765        let selection_mechanism = starting_point
766            .as_ref()
767            .and_then(|node| node.downcast::<Element>())
768            .filter(|element| element.is_sequentially_focusable(cx))
769            .map(|element| {
770                SequentialFocusNavigationMechanism::Sequential(
771                    element.explicitly_set_tab_index().unwrap_or_default(),
772                )
773            })
774            .unwrap_or_else(|| {
775                if starting_point_is_navigable {
776                    SequentialFocusNavigationMechanism::FirstOrLast
777                } else {
778                    SequentialFocusNavigationMechanism::Dom
779                }
780            });
781
782        // > 5. Let candidate be the result of running the sequential navigation search algorithm
783        // > with starting point, direction, and selection mechanism.
784        let candidate = SequentialFocusNavigationSearch::new(
785            starting_point
786                .as_ref()
787                .and_then(|node| node.containing_focus_navigation_scope_owner())
788                .unwrap_or_else(|| FocusNavigationScopeOwner::Document(self.window.Document())),
789            direction,
790            selection_mechanism,
791            starting_point,
792        )
793        .search(cx);
794
795        // > 6. If candidate is not null, then run the focusing steps for candidate and return.
796        if let Some(candidate) = candidate {
797            let document = self.window.Document();
798            let event_handler = document.event_handler();
799            event_handler.focus_and_scroll_to_element_for_key_event(cx, &candidate);
800            // We can't simply run the focusing steps, because:
801            //  1. The focusing steps do not scroll to the element.
802            //  2. When focus shifts to a child navigable (iframe) we have special behavior to reach
803            //     across document boundaries to focus the first focusable element in the iframe.
804            match candidate.downcast::<HTMLIFrameElement>() {
805                Some(iframe_element) => self.sequentially_focus_child_iframe_local_or_remote(
806                    cx,
807                    iframe_element,
808                    direction,
809                ),
810                None => event_handler.focus_and_scroll_to_element_for_key_event(cx, &candidate),
811            }
812            return;
813        }
814
815        // > 7. Otherwise, unset the sequential focus navigation starting point.
816        self.sequential_focus_navigation_starting_point.clear();
817
818        // This is not in the specification, but there's a difference between moving focus into
819        // a child `<iframe>` and within a Document. If no suitable focusable area can be found
820        // when moving into an `<iframe>`, we want to focus the `<iframe>`'s viewport itself.
821        if allow_focusing_viewport {
822            self.focus(cx, &FocusableArea::Viewport, FocusTrigger::Keyboard);
823            return;
824        }
825
826        // > 8. If starting point is a top-level traversable, or a focusable area in the top-level
827        // > traversable, the user agent should transfer focus to its own controls appropriately (if
828        // > any), honouring direction, and then return.
829        // TODO: Implement this.
830        if self.window.is_top_level() {
831            return;
832        }
833
834        // > 9. Otherwise, starting point is a focusable area in a child navigable. Set starting
835        // > point to that child navigable's parent and return to the step labeled loop.
836        self.sequentially_focus_parent_local_or_remote(cx, direction);
837    }
838
839    fn sequentially_focus_child_iframe_local_or_remote(
840        &self,
841        cx: &mut JSContext,
842        iframe_element: &HTMLIFrameElement,
843        direction: SequentialFocusDirection,
844    ) {
845        if let Some(content_document) = iframe_element.GetContentDocument() {
846            // The <iframe> is in the same `ScriptThread` and we have direct access to it. We can
847            // move the focus directly.
848            content_document
849                .focus_handler()
850                .sequential_focus_from_another_document(cx, None, direction);
851        } else if let Some(browsing_context_id) = iframe_element.browsing_context_id() {
852            self.window.send_to_constellation(
853                ScriptToConstellationMessage::FocusRemoteBrowsingContext(
854                    browsing_context_id,
855                    RemoteFocusOperation::Sequential(direction, None),
856                ),
857            );
858        } else {
859            iframe_element.upcast::<Node>().run_the_focusing_steps(
860                cx,
861                None,
862                FocusTrigger::Keyboard,
863            );
864        }
865    }
866
867    fn sequentially_focus_parent_local_or_remote(
868        &self,
869        cx: &mut JSContext,
870        direction: SequentialFocusDirection,
871    ) {
872        let window_proxy = self.window.window_proxy();
873        if let Some(iframe) = window_proxy.frame_element() {
874            // The parent browsing context is in the same `ScriptThread` and we have direct access
875            // to it. We can move the focus directly.
876            let browsing_context_id = iframe
877                .downcast::<HTMLIFrameElement>()
878                .and_then(|iframe_element| iframe_element.browsing_context_id());
879            iframe
880                .owner_document()
881                .focus_handler()
882                .sequential_focus_from_another_document(cx, browsing_context_id, direction);
883        } else if let Some(browsing_context_id) = window_proxy
884            .parent()
885            .map(|parent| parent.browsing_context_id())
886        {
887            self.window.send_to_constellation(
888                ScriptToConstellationMessage::FocusRemoteBrowsingContext(
889                    browsing_context_id,
890                    RemoteFocusOperation::Sequential(
891                        direction,
892                        Some(window_proxy.browsing_context_id()),
893                    ),
894                ),
895            );
896        }
897    }
898
899    pub(crate) fn sequential_focus_from_another_document(
900        &self,
901        cx: &mut JSContext,
902        browsing_context_id: Option<BrowsingContextId>,
903        direction: SequentialFocusDirection,
904    ) {
905        let mut realm = enter_auto_realm(cx, &*self.window);
906        let cx = &mut realm.current_realm();
907        let starting_point = browsing_context_id.and_then(|browsing_context_id| {
908            self.window
909                .Document()
910                .iframes()
911                .element(browsing_context_id)
912                .map(DomRoot::upcast::<Node>)
913        });
914        self.sequential_focus_navigation_loop(
915            cx,
916            starting_point,
917            direction,
918            true, /* allow focusing viewport */
919        );
920    }
921
922    pub(crate) fn gained_or_lost_system_focus(&self, cx: &mut JSContext, gained_focus: bool) {
923        if !self.has_focus() {
924            return;
925        }
926
927        rooted!(&in(cx) let focused_area = self.focused_area().clone());
928        rooted!(&in(cx) let new_focus_chain = if gained_focus {
929            self.current_focus_chain()
930        } else {
931            vec![]
932        });
933        rooted!(&in(cx) let old_focus_chain = if !gained_focus {
934            self.current_focus_chain()
935        } else {
936            vec![]
937        });
938
939        self.focus_update_steps(
940            cx,
941            new_focus_chain,
942            old_focus_chain,
943            &focused_area,
944            true, /* for_system_focus_change */
945            FocusTrigger::Script,
946        );
947    }
948}
949
950/// <https://html.spec.whatwg.org/multipage/#selection-mechanism>
951///
952/// This also incorporates the case where the starting point is a navigable
953/// as that is a distinct set of behaviors from the two kinds of mechanisms
954/// listed in the specification.
955#[derive(Clone, Copy, Debug)]
956pub(crate) enum SequentialFocusNavigationMechanism {
957    Dom,
958    Sequential(i32 /* focused_element_tab_index */),
959    /// This case isn't mentioned explicitly in the specification, but it's implied. It works
960    /// like `Sequential`, but without a starting point. This kind of search will return the
961    /// first or last (depending on direction) sequentially focusable element in sequential
962    /// focus order. This is used in two situations:
963    ///
964    ///  - When the starting point is a navigable
965    ///  - When descending into a nested focus scope
966    FirstOrLast,
967}
968
969#[derive(PartialEq)]
970enum Continue {
971    Yes,
972    No,
973}
974
975#[derive(PartialEq)]
976pub(crate) enum SequentialFocusNavigationSearchContext {
977    /// The focus scope that initiated this search. Containing contexts and nested contexts can
978    /// both be searched.
979    Original,
980    /// The search has descended into a nested search scope. Containing contexts should never
981    /// be searched.
982    Nested,
983    /// The search has ascended to search a containing search scope. The starting point's focus
984    /// scope should never be searched to avoid cycles.
985    Containing,
986}
987
988/// This structure is used to do a traversal search of the DOM in order to find an
989/// appropriate target when doing sequential focus navigation, such as when handling
990/// tab key presses.
991///
992/// The specification talks about the [flattened tabindex-ordered focus navigation scope],
993/// which represents all of the [tabindex-ordered focus navigation scope]s of a particular
994/// page, flattened into a single list of all the sequentially focusable areas of the
995/// page. Then, the specification describes how to search this list during sequential focus
996/// navigation.
997///
998/// The choice that Servo and other browsers make is to trade updating this flattened list
999/// during every DOM mutation (frequent) with a DOM traversal of, potentially, the entire
1000/// document during sequential focus navigation (infrequent).
1001///
1002/// The search done via [`SequentialFocusNavigationSearch`] matches the semantics of the
1003/// flattened tabindex-ordered focus navigation scope without having to maintain the
1004/// flattened list. It uses a series of nested traversals (one per focus scope) that
1005/// only considers each focusable area of a page at most once.
1006///
1007/// The search performs a linear DOM traversal starting at the containing focus scope of
1008/// the search start point. When encountering a nested focus scope, if that scope could
1009/// contain the final target for the search, the search recurses into the nested scope. If
1010/// the search reaches the end of a focus scope without finding a candidate, the search
1011/// continues in the focus scope's containing scope (though never re-ascending back into a
1012/// scope it recursed from).
1013///
1014/// [flattened tabindex-ordered focus navigation scope]: https://html.spec.whatwg.org/multipage/#flattened-tabindex-ordered-focus-navigation-scope
1015/// [tabindex-ordered focus navigation scope]: https://html.spec.whatwg.org/multipage/#tabindex-ordered-focus-navigation-scope
1016pub(crate) struct SequentialFocusNavigationSearch {
1017    focus_navigation_scope_owner: FocusNavigationScopeOwner,
1018    direction: SequentialFocusDirection,
1019    mechanism: SequentialFocusNavigationMechanism,
1020    starting_point: Option<DomRoot<Node>>,
1021    current_winner: Option<(DomRoot<Element>, i32)>,
1022    passed_starting_point: bool,
1023    search_context: SequentialFocusNavigationSearchContext,
1024}
1025
1026impl SequentialFocusNavigationSearch {
1027    pub(crate) fn new(
1028        focus_navigation_scope_owner: FocusNavigationScopeOwner,
1029        direction: SequentialFocusDirection,
1030        mechanism: SequentialFocusNavigationMechanism,
1031        starting_point: Option<DomRoot<Node>>,
1032    ) -> Self {
1033        // If there's no starting point, the starting point is actually the root element, which
1034        // we always have passed.
1035        let passed_starting_point = starting_point.is_none();
1036        Self {
1037            focus_navigation_scope_owner,
1038            direction,
1039            mechanism,
1040            starting_point,
1041            current_winner: Default::default(),
1042            passed_starting_point,
1043            search_context: SequentialFocusNavigationSearchContext::Original,
1044        }
1045    }
1046
1047    pub(crate) fn search(mut self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1048        for node in self.focus_navigation_scope_owner.iterator() {
1049            if self.process_node(cx, &node) == Continue::No {
1050                break;
1051            }
1052        }
1053
1054        if let Some(winner) = self.current_winner.take() {
1055            return Some(winner.0);
1056        }
1057
1058        // If searching a nested focus navigation scope, never try to search the containing
1059        // scope, as that will lead to an endless cycle.
1060        if self.search_context != SequentialFocusNavigationSearchContext::Nested {
1061            return self.maybe_search_in_containing_focus_navigation_scope(cx);
1062        }
1063
1064        None
1065    }
1066
1067    fn maybe_search_in_containing_focus_navigation_scope(
1068        &self,
1069        cx: &mut JSContext,
1070    ) -> Option<DomRoot<Element>> {
1071        let containing_node = self.focus_navigation_scope_owner.node();
1072        let containing_focus_navigation_scope_owner =
1073            containing_node.containing_focus_navigation_scope_owner()?;
1074
1075        let tab_index = containing_node
1076            .downcast::<Element>()?
1077            .explicitly_set_tab_index()
1078            .unwrap_or_default();
1079        let mechanism = match &self.mechanism {
1080            // If the traversal was sequential, but the containing focus navigation scope owner was
1081            // explicitly marked as not sequentially focusable, the search in the containing scope
1082            // needs to work like a DOM traversal i.e. take the first sequentially focusable target
1083            // after this one in the parent traversal.
1084            SequentialFocusNavigationMechanism::Sequential(..) if tab_index == -1 => {
1085                SequentialFocusNavigationMechanism::Dom
1086            },
1087            SequentialFocusNavigationMechanism::Sequential(..) => {
1088                SequentialFocusNavigationMechanism::Sequential(tab_index)
1089            },
1090            mechanism => *mechanism,
1091        };
1092
1093        if self.direction == SequentialFocusDirection::Backward &&
1094            let Some(containing_element) = containing_node.downcast::<Element>() &&
1095            containing_element.is_sequentially_focusable(cx)
1096        {
1097            return Some(DomRoot::from_ref(containing_element));
1098        }
1099
1100        Self {
1101            focus_navigation_scope_owner: containing_focus_navigation_scope_owner,
1102            direction: self.direction,
1103            mechanism,
1104            starting_point: Some(DomRoot::from_ref(containing_node)),
1105            current_winner: Default::default(),
1106            passed_starting_point: false,
1107            search_context: SequentialFocusNavigationSearchContext::Containing,
1108        }
1109        .search(cx)
1110    }
1111
1112    fn process_node(&mut self, cx: &mut JSContext, node: &Node) -> Continue {
1113        if Some(node) == self.starting_point.as_deref() {
1114            self.passed_starting_point = true;
1115        } else if self.process_node_as_sequentially_focusable_node(cx, node) == Continue::No {
1116            return Continue::No;
1117        }
1118
1119        self.process_node_as_focus_scope_owner(cx, node)
1120    }
1121
1122    /// If this node is sequentially focusable, consider whether or not to accept it
1123    /// as the new winner.
1124    fn process_node_as_sequentially_focusable_node(
1125        &mut self,
1126        cx: &mut JSContext,
1127        node: &Node,
1128    ) -> Continue {
1129        let Some(element) = node.downcast::<Element>() else {
1130            return Continue::Yes;
1131        };
1132        if !element.is_sequentially_focusable(cx) {
1133            return Continue::Yes;
1134        }
1135
1136        let tab_index = element.explicitly_set_tab_index().unwrap_or_default();
1137        let (is_new_winner, should_continue) = self.process_candidate_with_tab_index(tab_index);
1138        if is_new_winner {
1139            self.current_winner = Some((DomRoot::from_ref(element), tab_index));
1140        }
1141        should_continue
1142    }
1143
1144    /// If this node itself forms a nested sequential focus scope, decide whether or
1145    /// not to descend and consider its contained focusable areas as candidates.
1146    fn process_node_as_focus_scope_owner(&mut self, cx: &mut JSContext, node: &Node) -> Continue {
1147        // Never try to recurse into the same focus scope that we are in. This path
1148        // might be reached if we are in the root focus scope where the document is
1149        // one of the nodes processed.
1150        if self.focus_navigation_scope_owner.node() == node {
1151            return Continue::Yes;
1152        }
1153
1154        // If the search has ascended into a containing scope, never try to search back down
1155        // into the scope that originated this part of the search. Otherwise the search would
1156        // cycle endlessly.
1157        if Some(node) == self.starting_point.as_deref() &&
1158            self.search_context == SequentialFocusNavigationSearchContext::Containing
1159        {
1160            return Continue::Yes;
1161        }
1162
1163        let Some(focus_navigation_scope_owner) = node.as_focus_navigation_scope_owner() else {
1164            return Continue::Yes;
1165        };
1166
1167        // The candidate inherits the tab index of the node that establishes its containing
1168        // sequential focus navigation scope.
1169        let tab_index = focus_navigation_scope_owner
1170            .node()
1171            .downcast::<Element>()
1172            .and_then(Element::explicitly_set_tab_index)
1173            .unwrap_or_default();
1174        let (is_new_winner, should_continue) = self.process_candidate_with_tab_index(tab_index);
1175        if !is_new_winner {
1176            return should_continue;
1177        }
1178
1179        let mechanism = match self.mechanism {
1180            // If we were searching without regard to sequential focus order, keep doing that.
1181            SequentialFocusNavigationMechanism::Dom => SequentialFocusNavigationMechanism::Dom,
1182            // If we were searching taking into account sequential focus order, keep doing that, but
1183            // take the first candidate in sequential focus order without regard to the outer scope's
1184            // starting point or tab index.
1185            _ => SequentialFocusNavigationMechanism::FirstOrLast,
1186        };
1187
1188        let element = Self {
1189            focus_navigation_scope_owner,
1190            direction: self.direction,
1191            mechanism,
1192            starting_point: None,
1193            current_winner: Default::default(),
1194            passed_starting_point: self.passed_starting_point,
1195            search_context: SequentialFocusNavigationSearchContext::Nested,
1196        }
1197        .search(cx);
1198
1199        let Some(element) = element else {
1200            return Continue::Yes;
1201        };
1202
1203        self.current_winner = Some((element, tab_index));
1204        should_continue
1205    }
1206
1207    /// Process the node or focus scope owner with the provided tab index according to this
1208    /// search's search mechanism. Returns a boolean that is true if this candidate is the new
1209    /// winner and a [`Continue`] which says whether to keep searching or stop.
1210    fn process_candidate_with_tab_index(&mut self, candidate_tab_index: i32) -> (bool, Continue) {
1211        match self.mechanism {
1212            SequentialFocusNavigationMechanism::Dom => self.process_element_for_dom_traversal(),
1213            SequentialFocusNavigationMechanism::Sequential(focused_element_tab_index) => self
1214                .process_element_for_sequential_traversal(
1215                    candidate_tab_index,
1216                    focused_element_tab_index,
1217                ),
1218            SequentialFocusNavigationMechanism::FirstOrLast => (
1219                self.process_element_for_first_or_last_traversal(candidate_tab_index),
1220                Continue::Yes,
1221            ),
1222        }
1223    }
1224
1225    /// Process the node or focus scope owner, given the state of [`Self::passed_starting_point`]
1226    /// with for searches with the [`SequentialFocusNavigationMechanism::Dom`] search mechanism.
1227    /// Returns a boolean that is true if this candidate is the new winner and a [`Continue`] which
1228    /// says whether to keep searching or stop.
1229    fn process_element_for_dom_traversal(&self) -> (bool, Continue) {
1230        match self.direction {
1231            // direction is "forward"
1232            // > Let candidate be the first suitable sequentially focusable area after starting point,
1233            // > in starting point's Document's sequential focus navigation order, if any; or else
1234            // > null
1235            SequentialFocusDirection::Forward if self.passed_starting_point => (true, Continue::No),
1236            // If searching forward, do not consider anything until passing the starting point.
1237            SequentialFocusDirection::Forward => (false, Continue::Yes),
1238            // direction is "backward"
1239            // > Let candidate be the last suitable sequentially focusable area before starting
1240            // > point, in starting point's Document's sequential focus navigation order, if any; or
1241            // > else null
1242            SequentialFocusDirection::Backward if !self.passed_starting_point => {
1243                (true, Continue::Yes)
1244            },
1245            // There is no possible winner after the starting point when searching backward.
1246            SequentialFocusDirection::Backward => (false, Continue::No),
1247        }
1248    }
1249
1250    /// Process the node or focus scope owner with the provided tab index for searches with the
1251    /// [`SequentialFocusNavigationMechanism::FirstOrLast`] search mechanism. Returns a boolean
1252    /// that is true if this candidate is the new winner.
1253    fn process_element_for_first_or_last_traversal(
1254        &self,
1255        candidate_element_tab_index: i32,
1256    ) -> bool {
1257        let Some((_, winning_tab_index)) = self.current_winner else {
1258            return true;
1259        };
1260
1261        let candidate_and_current_winner_ordering =
1262            compare_tab_indices(candidate_element_tab_index, winning_tab_index);
1263        match self.direction {
1264            // direction is "forward"
1265            // > Let candidate be the first suitable sequentially focusable area in starting point's
1266            // > active document, if any; or else null
1267            //
1268            // There's an ambiguity in the specification here. In this case it says to choose
1269            // the "first suitable sequentially focusable area." It's possible to interpret this
1270            // as the first in DOM order, but browsers seem to agree to follow tab index
1271            // order instead.
1272            //
1273            // Pick the lowest, prioritizing the earlier node when equal.
1274            SequentialFocusDirection::Forward
1275                if candidate_and_current_winner_ordering == Ordering::Less =>
1276            {
1277                true
1278            },
1279            // direction is "backward"
1280            // > Let candidate be the last suitable sequentially focusable area in starting point's
1281            // > active document, if any; or else null
1282            //
1283            // There's an ambiguity in the specification here. In this case it says to choose
1284            // the "last suitable sequentially focusable area" It's possible to interpret this
1285            // as the first in DOM order, but browsers seem to agree to following tab index
1286            // order instead.
1287            //
1288            // Pick the highest, prioritizing the later node when equal.
1289            SequentialFocusDirection::Backward
1290                if candidate_and_current_winner_ordering != Ordering::Less =>
1291            {
1292                true
1293            },
1294            _ => false,
1295        }
1296    }
1297
1298    /// Process the node or focus scope owner with the provided tab index for searches with the
1299    /// [`SequentialFocusNavigationMechanism::Sequential`] search mechanism. Returns a boolean
1300    /// that is true if this candidate is the new winner and a [`Continue`] which says whether to
1301    /// keep searching or stop.
1302    fn process_element_for_sequential_traversal(
1303        &self,
1304        candidate_element_tab_index: i32,
1305        focused_element_tab_index: i32,
1306    ) -> (bool, Continue) {
1307        let candidate_and_focused_ordering =
1308            compare_tab_indices(candidate_element_tab_index, focused_element_tab_index);
1309        match self.direction {
1310            SequentialFocusDirection::Forward => {
1311                // If moving forward the first element with equal tab index after the current
1312                // element is the winner.
1313                if self.passed_starting_point && candidate_and_focused_ordering == Ordering::Equal {
1314                    return (true, Continue::No);
1315                }
1316                // If the candidate element does not have a greater tab index, then discard it.
1317                if candidate_and_focused_ordering != Ordering::Greater {
1318                    return (false, Continue::Yes);
1319                }
1320                let Some((_, winning_tab_index)) = self.current_winner else {
1321                    // If this candidate has a tab index which is one greater than the current
1322                    // tab index, then we know it is the winner, because we give precedence to
1323                    // elements earlier in the DOM.
1324                    if candidate_element_tab_index == focused_element_tab_index + 1 {
1325                        return (true, Continue::No);
1326                    }
1327
1328                    return (true, Continue::Yes);
1329                };
1330
1331                // If the candidate element has a lesser tab index than the current winner,
1332                // then it becomes the winner.
1333                let should_select =
1334                    compare_tab_indices(candidate_element_tab_index, winning_tab_index) ==
1335                        Ordering::Less;
1336
1337                (should_select, Continue::Yes)
1338            },
1339            SequentialFocusDirection::Backward => {
1340                // If moving backward the last element with an equal tab index that precedes
1341                // the focused element in the DOM is the winner.
1342                if !self.passed_starting_point && candidate_and_focused_ordering == Ordering::Equal
1343                {
1344                    return (true, Continue::Yes);
1345                }
1346                // If the candidate does not have a lesser tab index, then discard it.
1347                if candidate_and_focused_ordering != Ordering::Less {
1348                    return (false, Continue::Yes);
1349                }
1350                let Some((_, winning_tab_index)) = self.current_winner else {
1351                    return (true, Continue::Yes);
1352                };
1353                // If the candidate element's tab index is not less than the current winner,
1354                // then it becomes the new winner. This means that when the tab indices are
1355                // equal, we give preference to the last one in DOM order.
1356                let should_select =
1357                    compare_tab_indices(candidate_element_tab_index, winning_tab_index) !=
1358                        Ordering::Less;
1359                (should_select, Continue::Yes)
1360            },
1361        }
1362    }
1363}
1364
1365/// Compare two tab indices according to <https://html.spec.whatwg.org/multipage/#tabindex-value>.
1366///
1367/// `Ordering::Less`: The index should come before the other in sequential focus order.
1368/// `Ordering::Equal`: The two indices should be processed in DOM order, respecting focus direction
1369/// and focus scopes.
1370/// `Ordering::Greater`: The index should come after the other in sequential focus order.
1371///
1372/// Note that a tabindex of 0 should come after all others, which is essentially why we need this
1373/// function.
1374fn compare_tab_indices(a: i32, b: i32) -> Ordering {
1375    if a == b {
1376        Ordering::Equal
1377    } else if a == 0 {
1378        Ordering::Greater
1379    } else if b == 0 {
1380        Ordering::Less
1381    } else {
1382        a.cmp(&b)
1383    }
1384}