Skip to main content

script/dom/html/form_controls/
htmlbuttonelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::default::Default;
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix, local_name};
10use js::context::{JSContext, NoGC};
11use js::rust::HandleObject;
12use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
13use script_bindings::codegen::GenericBindings::DocumentFragmentBinding::DocumentFragmentMethods;
14use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods;
15use style::selector_parser::PseudoElement;
16use stylo_dom::ElementState;
17
18use crate::dom::activation::Activatable;
19use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
20use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
21use crate::dom::bindings::inheritance::Castable;
22use crate::dom::bindings::root::{DomRoot, MutNullableDom};
23use crate::dom::bindings::str::DOMString;
24use crate::dom::commandevent::CommandEvent;
25use crate::dom::document::Document;
26use crate::dom::documentfragment::DocumentFragment;
27use crate::dom::element::attributes::storage::AttrRef;
28use crate::dom::element::{AttributeMutation, Element};
29use crate::dom::event::{Event, EventBubbles, EventCancelable};
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::html::form_controls::htmlselectelement::HTMLSelectElement;
32use crate::dom::html::htmlelement::HTMLElement;
33use crate::dom::html::htmlformelement::{
34    FormControl, FormDatum, FormDatumValue, FormSubmitterElement, HTMLFormElement, ResetFrom,
35    SubmittedFrom,
36};
37use crate::dom::node::virtualmethods::{VirtualMethods, vtable_for};
38use crate::dom::node::{Node, NodeTraits};
39use crate::dom::nodelist::NodeList;
40use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
41use crate::dom::validitystate::{ValidationFlags, ValidityState};
42
43#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
44enum ButtonType {
45    Submit,
46    Reset,
47    Button,
48    Auto,
49}
50
51#[dom_struct]
52pub(crate) struct HTMLButtonElement {
53    htmlelement: HTMLElement,
54    button_type: Cell<ButtonType>,
55    form_owner: MutNullableDom<HTMLFormElement>,
56    labels_node_list: MutNullableDom<NodeList>,
57    validity_state: MutNullableDom<ValidityState>,
58}
59
60impl HTMLButtonElement {
61    fn new_inherited(
62        local_name: LocalName,
63        prefix: Option<Prefix>,
64        document: &Document,
65    ) -> HTMLButtonElement {
66        HTMLButtonElement {
67            htmlelement: HTMLElement::new_inherited_with_state(
68                ElementState::ENABLED,
69                local_name,
70                prefix,
71                document,
72            ),
73            button_type: Cell::new(ButtonType::Auto),
74            form_owner: Default::default(),
75            labels_node_list: Default::default(),
76            validity_state: Default::default(),
77        }
78    }
79
80    pub(crate) fn new(
81        cx: &mut js::context::JSContext,
82        local_name: LocalName,
83        prefix: Option<Prefix>,
84        document: &Document,
85        proto: Option<HandleObject>,
86    ) -> DomRoot<HTMLButtonElement> {
87        Node::reflect_node_with_proto(
88            cx,
89            Box::new(HTMLButtonElement::new_inherited(
90                local_name, prefix, document,
91            )),
92            document,
93            proto,
94        )
95    }
96
97    pub(crate) fn is_submit_button(&self) -> bool {
98        match self.button_type.get() {
99            ButtonType::Auto => {
100                let element = self.upcast::<Element>();
101
102                !element.has_attribute(&local_name!("command")) &&
103                    !element.has_attribute(&local_name!("commandfor")) &&
104                    self.upcast::<Node>()
105                        .GetParentNode()
106                        .is_none_or(|node| !node.is::<HTMLSelectElement>())
107            },
108            ButtonType::Submit => true,
109            ButtonType::Reset | ButtonType::Button => false,
110        }
111    }
112
113    /// <https://html.spec.whatwg.org/multipage/#selector-default>
114    pub(crate) fn update_default_state(&self, is_default_button: bool, no_gc: &NoGC) {
115        // > The :default pseudo-class must match any element falling into one of the following categories:
116        // > - Submit buttons that are default buttons of their form owner.
117        self.upcast::<Element>().set_state(
118            no_gc,
119            ElementState::DEFAULT,
120            self.is_submit_button() && is_default_button,
121        );
122    }
123}
124
125impl HTMLButtonElementMethods<crate::DomTypeHolder> for HTMLButtonElement {
126    /// <https://html.spec.whatwg.org/multipage/#dom-button-command>
127    fn Command(&self) -> DOMString {
128        // Step 1. Let command be this's command attribute.
129        match self.command_state() {
130            // Step 2. If command is in the Custom state, then return command's value.
131            CommandState::Custom => self
132                .upcast::<Element>()
133                .get_string_attribute(&local_name!("command")),
134            // Step 3. If command is in the Unknown state, then return the empty string.
135            CommandState::Unknown => DOMString::default(),
136            // Step 4. Return the keyword corresponding to the value of command.
137            CommandState::Close => DOMString::from_static("close"),
138            CommandState::ShowModal => DOMString::from_static("show-modal"),
139            CommandState::RequestClose => DOMString::from_static("request-close"),
140        }
141    }
142
143    // https://html.spec.whatwg.org/multipage/#dom-button-command
144    make_setter!(SetCommand, "command");
145
146    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
147    make_bool_getter!(Disabled, "disabled");
148
149    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
150    make_bool_setter!(SetDisabled, "disabled");
151
152    /// <https://html.spec.whatwg.org/multipage/#dom-fae-form>
153    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
154        self.form_owner()
155    }
156
157    /// <https://html.spec.whatwg.org/multipage/#dom-button-type>
158    fn Type(&self) -> DOMString {
159        // Step 1. If this is a submit button, then return "submit".
160        if self.is_submit_button() {
161            return DOMString::from_static("submit");
162        };
163        // Steps 2-5.
164        match self.button_type.get() {
165            ButtonType::Submit => panic!("Should have returned submit already"),
166            ButtonType::Button | ButtonType::Auto => DOMString::from_static("button"),
167            ButtonType::Reset => DOMString::from_static("reset"),
168        }
169    }
170
171    // https://html.spec.whatwg.org/multipage/#dom-button-type
172    make_setter!(SetType, "type");
173
174    // https://html.spec.whatwg.org/multipage/#dom-fs-formaction
175    make_form_action_getter!(FormAction, "formaction");
176
177    // https://html.spec.whatwg.org/multipage/#dom-fs-formaction
178    make_setter!(SetFormAction, "formaction");
179
180    // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype
181    make_enumerated_getter!(
182        FormEnctype,
183        "formenctype",
184        "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain",
185        invalid => "application/x-www-form-urlencoded"
186    );
187
188    // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype
189    make_setter!(SetFormEnctype, "formenctype");
190
191    // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod
192    make_enumerated_getter!(
193        FormMethod,
194        "formmethod",
195        "get" | "post" | "dialog",
196        invalid => "get"
197    );
198
199    // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod
200    make_setter!(SetFormMethod, "formmethod");
201
202    // https://html.spec.whatwg.org/multipage/#dom-fs-formtarget
203    make_getter!(FormTarget, "formtarget");
204
205    // https://html.spec.whatwg.org/multipage/#dom-fs-formtarget
206    make_setter!(SetFormTarget, "formtarget");
207
208    // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
209    make_bool_getter!(FormNoValidate, "formnovalidate");
210
211    // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
212    make_bool_setter!(SetFormNoValidate, "formnovalidate");
213
214    // https://html.spec.whatwg.org/multipage/#dom-fe-name
215    make_getter!(Name, "name");
216
217    // https://html.spec.whatwg.org/multipage/#dom-fe-name
218    make_atomic_setter!(SetName, "name");
219
220    // https://html.spec.whatwg.org/multipage/#dom-button-value
221    make_getter!(Value, "value");
222
223    // https://html.spec.whatwg.org/multipage/#dom-button-value
224    make_setter!(SetValue, "value");
225
226    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
227    make_labels_getter!(Labels, labels_node_list);
228
229    /// <https://html.spec.whatwg.org/multipage/#dom-cva-willvalidate>
230    fn WillValidate(&self, no_gc: &NoGC) -> bool {
231        self.is_instance_validatable(no_gc)
232    }
233
234    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
235    fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
236        self.validity_state(cx)
237    }
238
239    /// <https://html.spec.whatwg.org/multipage/#dom-cva-checkvalidity>
240    fn CheckValidity(&self, cx: &mut JSContext) -> bool {
241        self.check_validity(cx)
242    }
243
244    /// <https://html.spec.whatwg.org/multipage/#dom-cva-reportvalidity>
245    fn ReportValidity(&self, cx: &mut JSContext) -> bool {
246        self.report_validity(cx)
247    }
248
249    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
250    fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
251        self.validation_message(cx)
252    }
253
254    /// <https://html.spec.whatwg.org/multipage/#dom-cva-setcustomvalidity>
255    fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
256        self.validity_state(cx).set_custom_error_message(cx, error);
257    }
258}
259
260impl HTMLButtonElement {
261    /// <https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set>
262    /// Steps range from 3.1 to 3.7 (specific to HTMLButtonElement)
263    pub(crate) fn form_datum(&self, submitter: Option<FormSubmitterElement>) -> Option<FormDatum> {
264        // Step 3.1: disabled state check is in get_unclean_dataset
265
266        // Step 3.1: only run steps if this is the submitter
267        if let Some(FormSubmitterElement::Button(submitter)) = submitter {
268            if submitter != self {
269                return None;
270            }
271        } else {
272            return None;
273        }
274        // Step 3.2
275        let ty = self.Type();
276        // Step 3.4
277        let name = self.Name();
278
279        if name.is_empty() {
280            // Step 3.1: Must have a name
281            return None;
282        }
283
284        // Step 3.9
285        Some(FormDatum {
286            ty,
287            name,
288            value: FormDatumValue::String(self.Value()),
289        })
290    }
291
292    fn set_type(&self, cx: &mut JSContext, value: Option<DOMString>) {
293        let value = if let Some(value) = value {
294            if value.eq_ignore_ascii_case("reset") {
295                ButtonType::Reset
296            } else if value.eq_ignore_ascii_case("button") {
297                ButtonType::Button
298            } else if value.eq_ignore_ascii_case("submit") {
299                ButtonType::Submit
300            } else {
301                ButtonType::Auto
302            }
303        } else {
304            ButtonType::Auto
305        };
306        self.button_type.set(value);
307        self.validity_state(cx)
308            .perform_validation_and_update(cx, ValidationFlags::all());
309
310        if let Some(form) = self.form_owner() {
311            form.invalidate_default_button(cx.no_gc());
312        }
313    }
314
315    fn command_for_element(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
316        let command_for_value = self
317            .upcast::<Element>()
318            .get_attribute_string_value(&local_name!("commandfor"))?
319            .into();
320
321        let root_node = self
322            .upcast::<Node>()
323            .GetRootNode(&GetRootNodeOptions::empty());
324
325        if let Some(document) = root_node.downcast::<Document>() {
326            return document.GetElementById(cx, command_for_value);
327        } else if let Some(document_fragment) = root_node.downcast::<DocumentFragment>() {
328            return document_fragment.GetElementById(cx, command_for_value);
329        }
330        unreachable!("Button element must be in a document or document fragment");
331    }
332
333    fn command_state(&self) -> CommandState {
334        let command = self
335            .upcast::<Element>()
336            .get_string_attribute(&local_name!("command"));
337        if command.starts_with_str("--") {
338            return CommandState::Custom;
339        }
340        if command.eq_ignore_ascii_case("close") {
341            return CommandState::Close;
342        }
343        if command.eq_ignore_ascii_case("request-close") {
344            return CommandState::RequestClose;
345        }
346        if command.eq_ignore_ascii_case("show-modal") {
347            return CommandState::ShowModal;
348        }
349
350        CommandState::Unknown
351    }
352
353    /// <https://html.spec.whatwg.org/multipage/#determine-if-command-is-valid>
354    fn determine_if_command_is_valid_for_target(command: CommandState, target: &Element) -> bool {
355        // Step 1. If command is in the Unknown state, then return false.
356        if command == CommandState::Unknown {
357            return false;
358        }
359        // Step 2. If command is in the Custom state, then return true.
360        if command == CommandState::Custom {
361            return true;
362        }
363        // Step 3. If target is not an HTML element, then return false.
364        if !target.is_html_element() {
365            return false;
366        }
367        // TODO Step 4. If command is in any of the following states:
368        // - Toggle Popover
369        // - Show Popover
370        // - Hide Popover
371        // then return true.
372        // Step 5. If this standard does not define is valid command steps for target's local name, then return false.
373        // Step 6. Otherwise, return the result of running target's corresponding is valid command steps given command.
374        vtable_for(target.upcast::<Node>()).is_valid_command_steps(command)
375    }
376
377    /// <https://html.spec.whatwg.org/multipage/#the-button-element:concept-fe-optional-value>
378    pub(crate) fn optional_value(&self) -> Option<DOMString> {
379        // The element's optional value is the value of the element's value attribute,
380        // if there is one; otherwise null.
381        self.upcast::<Element>()
382            .get_attribute_string_value(&local_name!("value"))
383            .map(|value| value.into())
384    }
385}
386
387impl VirtualMethods for HTMLButtonElement {
388    fn super_type(&self) -> Option<&dyn VirtualMethods> {
389        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
390    }
391
392    fn attribute_mutated(
393        &self,
394        cx: &mut js::context::JSContext,
395        attr: AttrRef<'_>,
396        mutation: AttributeMutation,
397    ) {
398        self.super_type()
399            .unwrap()
400            .attribute_mutated(cx, attr, mutation);
401        match *attr.local_name() {
402            local_name!("disabled") => {
403                self.validity_state(cx)
404                    .perform_validation_and_update(cx, ValidationFlags::all());
405            },
406            local_name!("type") => {
407                match mutation {
408                    AttributeMutation::Set(_) => self.set_type(cx, Some(attr.to_dom_string())),
409                    AttributeMutation::Removed => self.set_type(cx, None),
410                };
411            },
412            local_name!("command") => self.set_type(
413                cx,
414                Some(
415                    self.upcast::<Element>()
416                        .get_string_attribute(&local_name!("type")),
417                ),
418            ),
419            local_name!("commandfor") => self.set_type(
420                cx,
421                Some(
422                    self.upcast::<Element>()
423                        .get_string_attribute(&local_name!("type")),
424                ),
425            ),
426            local_name!("form") => {
427                self.form_attribute_mutated(cx, mutation);
428                self.validity_state(cx)
429                    .perform_validation_and_update(cx, ValidationFlags::empty());
430            },
431            _ => {},
432        }
433    }
434}
435
436impl FormControl for HTMLButtonElement {
437    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
438        self.form_owner.get()
439    }
440
441    fn set_form_owner(&self, _cx: &mut JSContext, form: Option<&HTMLFormElement>) {
442        self.form_owner.set(form);
443    }
444
445    fn to_html_element(&self) -> &HTMLElement {
446        self.upcast::<HTMLElement>()
447    }
448}
449
450impl Validatable for HTMLButtonElement {
451    fn as_element(&self) -> &Element {
452        self.upcast()
453    }
454
455    fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
456        self.validity_state
457            .or_init(|| ValidityState::new(cx, &self.owner_window(), self.upcast()))
458    }
459
460    fn satisfies_constraints(&self) -> bool {
461        let Some(validity_state) = self.validity_state.get() else {
462            return true;
463        };
464        validity_state.invalid_flags().is_empty()
465    }
466
467    fn is_instance_validatable(&self, no_gc: &NoGC) -> bool {
468        // https://html.spec.whatwg.org/multipage/#the-button-element%3Abarred-from-constraint-validation
469        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls%3A-the-disabled-attribute%3Abarred-from-constraint-validation
470        // https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation
471        self.is_submit_button() &&
472            !self.upcast::<Element>().disabled_state() &&
473            !is_barred_by_datalist_ancestor(no_gc, self.upcast())
474    }
475}
476
477impl Activatable for HTMLButtonElement {
478    fn as_element(&self) -> &Element {
479        self.upcast()
480    }
481
482    fn is_instance_activatable(&self) -> bool {
483        // https://html.spec.whatwg.org/multipage/#the-button-element
484        !self.upcast::<Element>().disabled_state() &&
485        // In addition, if this button is the file selector button, let the containing
486        // `<input>` handle activation.
487            self.upcast::<Node>().implemented_pseudo_element() !=
488                Some(PseudoElement::FileSelectorButton)
489    }
490
491    /// <https://html.spec.whatwg.org/multipage/#the-button-element:activation-behaviour>
492    fn activation_behavior(
493        &self,
494        cx: &mut js::context::JSContext,
495        _: &Event,
496        target: &EventTarget,
497    ) {
498        // Step 1. If element is disabled, then return.
499        if self.upcast::<Element>().disabled_state() {
500            return;
501        }
502
503        // Step 2. If element's node document is not fully active, then return.
504        if !target
505            .downcast::<Node>()
506            .is_none_or(|node| node.owner_document().is_fully_active())
507        {
508            return;
509        }
510
511        let button_type = self.button_type.get();
512        // Step 3. If element has a form owner:
513        if let Some(owner) = self.form_owner() {
514            // Step 3.1 If element is a submit button, then submit element's form owner from element
515            // ..., and return.
516            if self.is_submit_button() {
517                owner.submit(
518                    cx,
519                    SubmittedFrom::NotFromForm,
520                    FormSubmitterElement::Button(self),
521                );
522                return;
523            }
524            // Step 3.2 If element's type attribute is in the Reset Button state, then reset
525            // element's form owner and return.
526            if button_type == ButtonType::Reset {
527                owner.reset(cx, ResetFrom::NotFromForm);
528                return;
529            }
530            // Step 3.3 If element's type attribute is in the Auto state, then return.
531            if button_type == ButtonType::Auto {
532                return;
533            }
534        }
535
536        // Step 4. Let target be the result of running element's get the commandfor-associated
537        // element.
538        // Step 5. If target is not null:
539        if let Some(target) = self.command_for_element(cx) {
540            // Steps 5.1 Let command be element's command attribute.
541            let command = self.command_state();
542            // Step 5.2 If the result of determining if a command is valid for a target given command and target is false, then return.
543            if !Self::determine_if_command_is_valid_for_target(command, &target) {
544                return;
545            }
546            // Step 5.3 Let continue be the result of firing an event named command at target, using
547            // CommandEvent, with its command attribute initialized to command, its source attribute
548            // initialized to element, and its cancelable attribute initialized to true.
549            // TODO source attribute
550            // Step 5.4 If continue is false, then return.
551            let event = CommandEvent::new(
552                cx,
553                &self.owner_window(),
554                atom!("command"),
555                EventBubbles::DoesNotBubble,
556                EventCancelable::Cancelable,
557                Some(self.upcast()),
558                self.upcast::<Element>()
559                    .get_string_attribute(&local_name!("command")),
560            );
561            let event = event.upcast::<Event>();
562            if !event.fire(cx, target.upcast::<EventTarget>()) {
563                return;
564            }
565            // Step 5.5 If target is not connected, then return.
566            let target_node = target.upcast::<Node>();
567            if !target_node.is_connected() {
568                return;
569            }
570            // Step 5.6 If command is in the Custom state, then return.
571            if command == CommandState::Custom {
572                return;
573            }
574            // TODO Steps 5.7, 5.8, 5.9
575            // Step 5.10 Otherwise, if this standard defines command steps for target's local name,
576            // then run the corresponding command steps given target, element, and command.
577            let _ = vtable_for(target_node).command_steps(cx, DomRoot::from_ref(self), command);
578        }
579        // TODO Step 6 Otherwise, run the popover target attribute activation behavior given element
580        // and event's target.
581    }
582}
583
584#[derive(Copy, Clone, Eq, PartialEq, Debug)]
585pub(crate) enum CommandState {
586    Unknown,
587    Custom,
588    ShowModal,
589    RequestClose,
590    Close,
591}