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