Skip to main content

script/dom/document/
interactive_element_command.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;
6use layout_api::QueryMsg;
7use script_bindings::codegen::GenericBindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
8use script_bindings::codegen::GenericBindings::HTMLElementBinding::HTMLElementMethods;
9use script_bindings::codegen::GenericBindings::HTMLInputElementBinding::HTMLInputElementMethods;
10use script_bindings::codegen::GenericBindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
11use script_bindings::codegen::GenericBindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
12use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods;
13use script_bindings::inheritance::Castable;
14use script_bindings::root::DomRoot;
15
16use crate::dom::iterators::ShadowIncluding;
17use crate::dom::node::focus::FocusTrigger;
18use crate::dom::node::{Node, NodeTraits};
19use crate::dom::types::{
20    HTMLAnchorElement, HTMLButtonElement, HTMLElement, HTMLFieldSetElement, HTMLInputElement,
21    HTMLLabelElement, HTMLLegendElement, HTMLOptionElement,
22};
23
24/// This is an implementation of <https://html.spec.whatwg.org/multipage/#concept-command>. Note
25/// that there are various things called "commands" on the web platform, but this is the one that
26/// is mainly associated with access keys.
27pub(crate) enum InteractiveElementCommand {
28    Anchor(DomRoot<HTMLAnchorElement>),
29    Button(DomRoot<HTMLButtonElement>),
30    Input(DomRoot<HTMLInputElement>),
31    Option(DomRoot<HTMLOptionElement>),
32    HTMLElement(DomRoot<HTMLElement>),
33}
34
35impl TryFrom<&HTMLLegendElement> for InteractiveElementCommand {
36    type Error = ();
37
38    /// From <https://html.spec.whatwg.org/multipage/#using-the-accesskey-attribute-on-a-legend-element-to-define-a-command>
39    /// A legend element defines a command if all of the following are true:
40    ///  - It has an assigned access key.
41    ///  - It is a child of a fieldset element.
42    ///  - Its parent has a descendant that defines a command that is neither a label element nor
43    ///    a legend element. This element, if it exists, is the legend element's accesskey
44    ///    delegatee.
45    fn try_from(legend_element: &HTMLLegendElement) -> Result<Self, Self::Error> {
46        if !legend_element
47            .owner_document()
48            .event_handler()
49            .has_assigned_access_key(legend_element.upcast())
50        {
51            return Err(());
52        }
53
54        let node = legend_element.upcast::<Node>();
55        let Some(parent) = node.GetParentElement() else {
56            return Err(());
57        };
58        if !parent.is::<HTMLFieldSetElement>() {
59            return Err(());
60        }
61        for node in parent
62            .upcast::<Node>()
63            .traverse_preorder(ShadowIncluding::No)
64        {
65            if node.is::<HTMLLabelElement>() || node.is::<HTMLLegendElement>() {
66                continue;
67            }
68            let Some(html_element) = node.downcast::<HTMLElement>() else {
69                continue;
70            };
71            if let Ok(command) = Self::try_from(html_element) {
72                return Ok(command);
73            }
74        }
75
76        Err(())
77    }
78}
79
80impl TryFrom<&HTMLElement> for InteractiveElementCommand {
81    type Error = ();
82
83    fn try_from(html_element: &HTMLElement) -> Result<Self, Self::Error> {
84        if let Some(anchor_element) = html_element.downcast::<HTMLAnchorElement>() {
85            return Ok(Self::Anchor(DomRoot::from_ref(anchor_element)));
86        }
87        if let Some(button_element) = html_element.downcast::<HTMLButtonElement>() {
88            return Ok(Self::Button(DomRoot::from_ref(button_element)));
89        }
90        if let Some(input_element) = html_element.downcast::<HTMLInputElement>() {
91            return Ok(Self::Input(DomRoot::from_ref(input_element)));
92        }
93        if let Some(option_element) = html_element.downcast::<HTMLOptionElement>() {
94            return Ok(Self::Option(DomRoot::from_ref(option_element)));
95        }
96        if let Some(legend_element) = html_element.downcast::<HTMLLegendElement>() {
97            return Self::try_from(legend_element);
98        }
99        if html_element
100            .owner_document()
101            .event_handler()
102            .has_assigned_access_key(html_element)
103        {
104            return Ok(Self::HTMLElement(DomRoot::from_ref(html_element)));
105        }
106
107        Err(())
108    }
109}
110
111impl InteractiveElementCommand {
112    fn is_node_or_ancestor_inert(cx: &mut JSContext, node: &Node) -> bool {
113        node.owner_window().layout_reflow(cx, QueryMsg::StyleQuery);
114        node.inclusive_ancestors(ShadowIncluding::No)
115            .any(|node| node.is_inert_without_reflow())
116    }
117
118    pub(crate) fn disabled(&self, cx: &mut JSContext) -> bool {
119        match self {
120            // <https://html.spec.whatwg.org/multipage#using-the-a-element-to-define-a-command>
121            // > The Disabled State facet of the command is true if the element or one of its
122            // > ancestors is inert, and false otherwise.
123            InteractiveElementCommand::Anchor(anchor) => {
124                Self::is_node_or_ancestor_inert(cx, anchor.upcast::<Node>())
125            },
126            // <https://html.spec.whatwg.org/multipage/#using-the-button-element-to-define-a-command>
127            // > The Disabled State of the command is true if the element or one of its ancestors
128            // > is inert, or if the element's disabled state is set, and false otherwise.
129            InteractiveElementCommand::Button(button) => {
130                Self::is_node_or_ancestor_inert(cx, button.upcast::<Node>()) || button.Disabled()
131            },
132            // <https://html.spec.whatwg.org/multipage/#using-the-input-element-to-define-a-command>
133            // > The Disabled State of the command is true if the element or one of its ancestors is
134            // > inert, or if the element's disabled state is set, and false otherwise.
135            InteractiveElementCommand::Input(input) => {
136                Self::is_node_or_ancestor_inert(cx, input.upcast::<Node>()) || input.Disabled()
137            },
138            // <https://html.spec.whatwg.org/multipage/#using-the-option-element-to-define-a-command>
139            // > The Disabled State of the command is true if the element is disabled, or if its
140            // > nearest ancestor select element is disabled, or if it or one of its ancestors is
141            // > inert, and false otherwise.
142            InteractiveElementCommand::Option(option) => {
143                option.Disabled() ||
144                    option
145                        .nearest_ancestor_select()
146                        .is_some_and(|select| select.Disabled()) ||
147                    Self::is_node_or_ancestor_inert(cx, option.upcast::<Node>())
148            },
149            // <https://html.spec.whatwg.org/multipage#using-the-accesskey-attribute-to-define-a-command-on-other-elements>
150            // > The Disabled State of the command is true if the element or one of its ancestors is
151            // > inert, and false otherwise.
152            InteractiveElementCommand::HTMLElement(element) => {
153                Self::is_node_or_ancestor_inert(cx, element.upcast::<Node>())
154            },
155        }
156    }
157
158    pub(crate) fn hidden(&self) -> bool {
159        let html_element: &HTMLElement = match self {
160            InteractiveElementCommand::Anchor(anchor_element) => anchor_element.upcast(),
161            InteractiveElementCommand::Button(button_element) => button_element.upcast(),
162            InteractiveElementCommand::Input(input_element) => input_element.upcast(),
163            InteractiveElementCommand::Option(option_element) => option_element.upcast(),
164            InteractiveElementCommand::HTMLElement(html_element) => html_element,
165        };
166        html_element.Hidden()
167    }
168
169    pub(crate) fn perform_action(&self, cx: &mut JSContext) {
170        match self {
171            // <https://html.spec.whatwg.org/multipage#using-the-a-element-to-define-a-command>
172            // > The Action of the command is to fire a click event at the element.
173            // <https://html.spec.whatwg.org/multipage/#fire-a-click-event>
174            // > Firing a click event at target means firing a synthetic pointer event named click at target.
175            InteractiveElementCommand::Anchor(anchor_element) => anchor_element
176                .upcast::<Node>()
177                .fire_synthetic_pointer_event_not_trusted(cx, atom!("click")),
178            // <https://html.spec.whatwg.org/multipage/#using-the-button-element-to-define-a-command>
179            // > The Label, Access Key, Hidden State, and Action facets of the command are
180            // > determined as for a elements (see the previous section).
181            InteractiveElementCommand::Button(button_element) => button_element
182                .upcast::<Node>()
183                .fire_synthetic_pointer_event_not_trusted(cx, atom!("click")),
184            // <https://html.spec.whatwg.org/multipage/#using-the-input-element-to-define-a-command>
185            // > The Action of the command is to fire a click event at the element.
186            InteractiveElementCommand::Input(input_element) => input_element
187                .upcast::<Node>()
188                .fire_synthetic_pointer_event_not_trusted(cx, atom!("click")),
189            // <https://html.spec.whatwg.org/multipage/#using-the-option-element-to-define-a-command>
190            // > If the option's nearest ancestor select element has a multiple attribute, the
191            // > Action of the command is to toggle the option element. Otherwise, the Action is to
192            // > pick the option element.
193            // Note: setSelected takes care of whether or not the owner has the `multiple` attribute.
194            InteractiveElementCommand::Option(option_element) => {
195                option_element.SetSelected(cx, true)
196            },
197            // > The Action of the command is to run the following steps:
198            // >  1. Run the focusing steps for the element.
199            // >  2. Fire a click event at the element.
200            InteractiveElementCommand::HTMLElement(html_element) => {
201                let node: &Node = html_element.upcast();
202                node.run_the_focusing_steps(cx, None, FocusTrigger::Click);
203                node.fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
204            },
205        }
206    }
207}