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