Skip to main content

script/dom/element/
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 js::context::NoGC;
6use script_bindings::codegen::GenericBindings::ElementBinding::ElementMethods;
7use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
8use script_bindings::codegen::InheritTypes::{ElementTypeId, HTMLElementTypeId, NodeTypeId};
9use script_bindings::inheritance::Castable;
10use style::computed_values::visibility::T as Visibility;
11use style::values::computed::Overflow;
12use xml5ever::local_name;
13
14use crate::dom::Node;
15use crate::dom::document::focus::FocusableAreaKind;
16use crate::dom::types::{Element, HTMLElement};
17
18impl Element {
19    /// <https://html.spec.whatwg.org/multipage/#focusable-area>
20    ///
21    /// The list of focusable areas at this point in the specification is both incomplete and leaves
22    /// a lot up to the user agent. In addition, the specifications for "click focusable" and
23    /// "sequentially focusable" are written in a way that they are subsets of all focusable areas.
24    /// In order to avoid having to first determine whether an element is a focusable area and then
25    /// work backwards to figure out what kind it is, this function attempts to classify the
26    /// different types of focusable areas ahead of time so that the logic is useful for answering
27    /// both "Is this element a focusable area?" and "Is this element click (or sequentially)
28    /// focusable."
29    pub(crate) fn focusable_area_kind(&self, no_gc: &NoGC) -> FocusableAreaKind {
30        // Do not allow unrendered, disconnected, or disabled nodes to be focusable areas ever.
31        let node: &Node = self.upcast();
32        if !node.is_connected() || !self.has_css_layout_box() || self.is_actually_disabled() {
33            return Default::default();
34        }
35
36        // <https://www.w3.org/TR/css-display-4/#visibility>
37        // Invisible elements are removed from navigation.
38        if self
39            .style()
40            .is_some_and(|style| style.get_inherited_box().visibility != Visibility::Visible)
41        {
42            return Default::default();
43        }
44
45        // An element with a shadow root that delegates focus should never itself be a focusable area.
46        if self
47            .shadow_root()
48            .is_some_and(|shadow_root| shadow_root.DelegatesFocus())
49        {
50            return Default::default();
51        }
52
53        // > Elements that meet all the following criteria:
54        // > the element's tabindex value is non-null, or the element is determined by the user agent to be focusable;
55        // > the element is either not a shadow host, or has a shadow root whose delegates focus is false;
56        // Note: Checked above
57        // > the element is not actually disabled;
58        // Note: Checked above
59        // > the element is not inert;
60        // TODO: Handle this.
61        // > the element is either being rendered, delegating its rendering to its children, or
62        // > being used as relevant canvas fallback content.
63        // Note: Checked above
64        // TODO: Handle fallback canvas content.
65        match self.explicitly_set_tab_index() {
66            // From <https://html.spec.whatwg.org/multipage/#tabindex-ordered-focus-navigation-scope>:
67            // > A tabindex-ordered focus navigation scope is a list of focusable areas and focus
68            // > navigation scope owners. Every focus navigation scope owner owner has tabindex-ordered
69            // > focus navigation scope, whose contents are determined as follows:
70            // >  - It contains all elements in owner's focus navigation scope that are themselves focus
71            // >    navigation scope owners, except the elements whose tabindex value is a negative integer.
72            // >  - It contains all of the focusable areas whose DOM anchor is an element in owner's focus
73            // >    navigation scope, except the focusable areas whose tabindex value is a negative integer.
74            Some(tab_index) if tab_index < 0 => return FocusableAreaKind::Click,
75            Some(_) => return FocusableAreaKind::Click | FocusableAreaKind::Sequential,
76            None => {},
77        }
78
79        // From <https://html.spec.whatwg.org/multipage/#tabindex-value>
80        // > If the value is null
81        // > ...
82        // > Modulo platform conventions, it is suggested that the following elements should be
83        // > considered as focusable areas and be sequentially focusable:
84        let type_id = node.type_id();
85        let is_focusable_area_due_to_type = match type_id {
86            // >  - a elements that have an href attribute
87            NodeTypeId::Element(ElementTypeId::HTMLElement(
88                HTMLElementTypeId::HTMLAnchorElement,
89            )) => self.has_attribute(&local_name!("href")),
90
91            // >  - input elements whose type attribute are not in the Hidden state
92            // >  - button elements
93            // >  - select elements
94            // >  - textarea elements
95            // >  - Navigable containers
96            //
97            // Note: the `hidden` attribute is checked above for all elements.
98            NodeTypeId::Element(ElementTypeId::HTMLElement(
99                HTMLElementTypeId::HTMLInputElement |
100                HTMLElementTypeId::HTMLButtonElement |
101                HTMLElementTypeId::HTMLSelectElement |
102                HTMLElementTypeId::HTMLTextAreaElement |
103                HTMLElementTypeId::HTMLIFrameElement,
104            )) => true,
105            _ => {
106                // >  - summary elements that are the first summary element child of a details element
107                // >  - Editing hosts
108                // > -  Elements with a draggable attribute set, if that would enable the user agent to allow
109                // >    the user to begin drag operations for those elements without the use of a pointing device
110                self.downcast::<HTMLElement>()
111                    .is_some_and(|html_element| html_element.is_a_summary_for_its_parent_details()) ||
112                    self.is_editing_host() ||
113                    self.get_string_attribute(&local_name!("draggable")) == "true"
114            },
115        };
116
117        if is_focusable_area_due_to_type {
118            return FocusableAreaKind::Click | FocusableAreaKind::Sequential;
119        }
120
121        // > The scrollable regions of elements that are being rendered and are not inert.
122        //
123        // Note that these kind of focusable areas are only focusable via the keyboard.
124        //
125        // TODO: Handle inert.
126        if self
127            .upcast::<Node>()
128            .effective_overflow()
129            .is_some_and(|axes_overflow| {
130                // This is checking whether there is an input event scrollable overflow value in
131                // a given axis and also overflow in that same axis.
132                (matches!(axes_overflow.x, Overflow::Auto | Overflow::Scroll) &&
133                    self.ScrollWidth() > self.ClientWidth(no_gc)) ||
134                    (matches!(axes_overflow.y, Overflow::Auto | Overflow::Scroll) &&
135                        self.ScrollHeight() > self.ClientHeight(no_gc))
136            })
137        {
138            return FocusableAreaKind::Sequential;
139        }
140
141        // > Any other element or part of an element determined by the user agent to be a focusable
142        // > area, especially to aid with accessibility or to better match platform conventions.
143        match type_id {
144            NodeTypeId::Element(ElementTypeId::HTMLElement(
145                HTMLElementTypeId::HTMLDialogElement,
146            )) => FocusableAreaKind::Click,
147            _ => Default::default(),
148        }
149    }
150
151    /// <https://html.spec.whatwg.org/multipage/#sequentially-focusable>.
152    pub(crate) fn is_sequentially_focusable(&self, no_gc: &NoGC) -> bool {
153        self.focusable_area_kind(no_gc)
154            .contains(FocusableAreaKind::Sequential)
155    }
156
157    /// <https://html.spec.whatwg.org/multipage/#focusable-area>
158    pub(crate) fn is_focusable_area(&self, no_gc: &NoGC) -> bool {
159        !self.focusable_area_kind(no_gc).is_empty()
160    }
161}