1use 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::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::FlatTreeParent;
19use crate::dom::activation::Activatable;
20use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
21use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
22use crate::dom::bindings::inheritance::Castable;
23use crate::dom::bindings::root::{DomRoot, MutNullableDom};
24use crate::dom::bindings::str::DOMString;
25use crate::dom::commandevent::CommandEvent;
26use crate::dom::document::Document;
27use crate::dom::documentfragment::DocumentFragment;
28use crate::dom::element::attributes::storage::AttrRef;
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::virtualmethods::{VirtualMethods, vtable_for};
39use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
40use crate::dom::nodelist::NodeList;
41use crate::dom::types::HTMLInputElement;
42use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
43use crate::dom::validitystate::{ValidationFlags, ValidityState};
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 cx: &mut js::context::JSContext,
83 local_name: LocalName,
84 prefix: Option<Prefix>,
85 document: &Document,
86 proto: Option<HandleObject>,
87 ) -> DomRoot<HTMLButtonElement> {
88 Node::reflect_node_with_proto(
89 cx,
90 Box::new(HTMLButtonElement::new_inherited(
91 local_name, prefix, document,
92 )),
93 document,
94 proto,
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 fn Command(&self) -> DOMString {
107 match self.command_state() {
109 CommandState::Custom => self
111 .upcast::<Element>()
112 .get_string_attribute(&local_name!("command")),
113 CommandState::Unknown => DOMString::default(),
115 CommandState::Close => DOMString::from("close"),
117 CommandState::ShowModal => DOMString::from("show-modal"),
118 }
119 }
120
121 make_setter!(SetCommand, "command");
123
124 make_bool_getter!(Disabled, "disabled");
126
127 make_bool_setter!(SetDisabled, "disabled");
129
130 fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
132 self.form_owner()
133 }
134
135 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 make_setter!(SetType, "type");
146
147 make_form_action_getter!(FormAction, "formaction");
149
150 make_setter!(SetFormAction, "formaction");
152
153 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 make_setter!(SetFormEnctype, "formenctype");
163
164 make_enumerated_getter!(
166 FormMethod,
167 "formmethod",
168 "get" | "post" | "dialog",
169 invalid => "get"
170 );
171
172 make_setter!(SetFormMethod, "formmethod");
174
175 make_getter!(FormTarget, "formtarget");
177
178 make_setter!(SetFormTarget, "formtarget");
180
181 make_bool_getter!(FormNoValidate, "formnovalidate");
183
184 make_bool_setter!(SetFormNoValidate, "formnovalidate");
186
187 make_getter!(Name, "name");
189
190 make_atomic_setter!(SetName, "name");
192
193 make_getter!(Value, "value");
195
196 make_setter!(SetValue, "value");
198
199 make_labels_getter!(Labels, labels_node_list);
201
202 fn WillValidate(&self) -> bool {
204 self.is_instance_validatable()
205 }
206
207 fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
209 self.validity_state(cx)
210 }
211
212 fn CheckValidity(&self, cx: &mut JSContext) -> bool {
214 self.check_validity(cx)
215 }
216
217 fn ReportValidity(&self, cx: &mut JSContext) -> bool {
219 self.report_validity(cx)
220 }
221
222 fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
224 self.validation_message(cx)
225 }
226
227 fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
229 self.validity_state(cx).set_custom_error_message(cx, error);
230 }
231}
232
233impl HTMLButtonElement {
234 pub(crate) fn form_datum(&self, submitter: Option<FormSubmitterElement>) -> Option<FormDatum> {
237 if let Some(FormSubmitterElement::Button(submitter)) = submitter {
241 if submitter != self {
242 return None;
243 }
244 } else {
245 return None;
246 }
247 let ty = self.Type();
249 let name = self.Name();
251
252 if name.is_empty() {
253 return None;
255 }
256
257 Some(FormDatum {
259 ty,
260 name,
261 value: FormDatumValue::String(self.Value()),
262 })
263 }
264
265 fn set_type(&self, cx: &mut JSContext, value: DOMString) {
266 let value = match value.to_ascii_lowercase().as_str() {
267 "reset" => ButtonType::Reset,
268 "button" => ButtonType::Button,
269 "submit" => ButtonType::Submit,
270 _ => {
271 let element = self.upcast::<Element>();
272 if element.has_attribute(&local_name!("command")) ||
273 element.has_attribute(&local_name!("commandfor"))
274 {
275 ButtonType::Button
276 } else {
277 ButtonType::Submit
278 }
279 },
280 };
281 self.button_type.set(value);
282 self.validity_state(cx)
283 .perform_validation_and_update(cx, ValidationFlags::all());
284 }
285
286 fn command_for_element(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
287 let command_for_value = self
288 .upcast::<Element>()
289 .get_attribute_string_value(&local_name!("commandfor"))?
290 .into();
291
292 let root_node = self
293 .upcast::<Node>()
294 .GetRootNode(&GetRootNodeOptions::empty());
295
296 if let Some(document) = root_node.downcast::<Document>() {
297 return document.GetElementById(cx, command_for_value);
298 } else if let Some(document_fragment) = root_node.downcast::<DocumentFragment>() {
299 return document_fragment.GetElementById(cx, command_for_value);
300 }
301 unreachable!("Button element must be in a document or document fragment");
302 }
303
304 fn command_state(&self) -> CommandState {
305 let command = self
306 .upcast::<Element>()
307 .get_string_attribute(&local_name!("command"));
308 if command.starts_with_str("--") {
309 return CommandState::Custom;
310 }
311 let value = command.to_ascii_lowercase();
312 if value == "close" {
313 return CommandState::Close;
314 }
315 if value == "show-modal" {
316 return CommandState::ShowModal;
317 }
318
319 CommandState::Unknown
320 }
321
322 fn determine_if_command_is_valid_for_target(command: CommandState, target: &Element) -> bool {
324 if command == CommandState::Unknown {
326 return false;
327 }
328 if command == CommandState::Custom {
330 return true;
331 }
332 if !target.is_html_element() {
334 return false;
335 }
336 vtable_for(target.upcast::<Node>()).is_valid_command_steps(command)
344 }
345
346 pub(crate) fn optional_value(&self) -> Option<DOMString> {
348 self.upcast::<Element>()
351 .get_attribute_string_value(&local_name!("value"))
352 .map(|value| value.into())
353 }
354}
355
356impl VirtualMethods for HTMLButtonElement {
357 fn super_type(&self) -> Option<&dyn VirtualMethods> {
358 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
359 }
360
361 fn attribute_mutated(
362 &self,
363 cx: &mut js::context::JSContext,
364 attr: AttrRef<'_>,
365 mutation: AttributeMutation,
366 ) {
367 self.super_type()
368 .unwrap()
369 .attribute_mutated(cx, attr, mutation);
370 match *attr.local_name() {
371 local_name!("disabled") => {
372 let el = self.upcast::<Element>();
373 match mutation {
374 AttributeMutation::Set(Some(_), _) => {},
375 AttributeMutation::Set(None, _) => {
376 el.set_disabled_state(true);
377 el.set_enabled_state(false);
378 },
379 AttributeMutation::Removed => {
380 el.set_disabled_state(false);
381 el.set_enabled_state(true);
382 el.check_ancestors_disabled_state_for_form_control();
383 },
384 }
385 self.validity_state(cx)
386 .perform_validation_and_update(cx, ValidationFlags::all());
387 },
388 local_name!("type") => self.set_type(cx, attr.to_dom_string()),
389 local_name!("command") => self.set_type(
390 cx,
391 self.upcast::<Element>()
392 .get_string_attribute(&local_name!("type")),
393 ),
394 local_name!("commandfor") => self.set_type(
395 cx,
396 self.upcast::<Element>()
397 .get_string_attribute(&local_name!("type")),
398 ),
399 local_name!("form") => {
400 self.form_attribute_mutated(cx, mutation);
401 self.validity_state(cx)
402 .perform_validation_and_update(cx, ValidationFlags::empty());
403 },
404 _ => {},
405 }
406 }
407
408 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
409 if let Some(s) = self.super_type() {
410 s.bind_to_tree(cx, context);
411 }
412
413 self.upcast::<Element>()
414 .check_ancestors_disabled_state_for_form_control();
415 }
416
417 fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
418 self.super_type().unwrap().unbind_from_tree(cx, context);
419
420 let node = self.upcast::<Node>();
421 let el = self.upcast::<Element>();
422 if node
423 .ancestors()
424 .any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
425 {
426 el.check_ancestors_disabled_state_for_form_control();
427 } else {
428 el.check_disabled_attribute();
429 }
430 }
431}
432
433impl FormControl for HTMLButtonElement {
434 fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
435 self.form_owner.get()
436 }
437
438 fn set_form_owner(&self, _cx: &mut JSContext, form: Option<&HTMLFormElement>) {
439 self.form_owner.set(form);
440 }
441
442 fn to_html_element(&self) -> &HTMLElement {
443 self.upcast::<HTMLElement>()
444 }
445}
446
447impl Validatable for HTMLButtonElement {
448 fn as_element(&self) -> &Element {
449 self.upcast()
450 }
451
452 fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
453 self.validity_state
454 .or_init(|| ValidityState::new(cx, &self.owner_window(), self.upcast()))
455 }
456
457 fn is_instance_validatable(&self) -> bool {
458 self.button_type.get() == ButtonType::Submit &&
462 !self.upcast::<Element>().disabled_state() &&
463 !is_barred_by_datalist_ancestor(self.upcast())
464 }
465}
466
467impl Activatable for HTMLButtonElement {
468 fn as_element(&self) -> &Element {
469 self.upcast()
470 }
471
472 fn is_instance_activatable(&self) -> bool {
473 !self.upcast::<Element>().disabled_state()
475 }
476
477 fn activation_behavior(
479 &self,
480 cx: &mut js::context::JSContext,
481 event: &Event,
482 target: &EventTarget,
483 ) {
484 if !target
486 .downcast::<Node>()
487 .is_none_or(|node| node.owner_document().is_fully_active())
488 {
489 return;
490 }
491
492 let button_type = self.button_type.get();
493 if let Some(owner) = self.form_owner() {
495 if button_type == ButtonType::Submit {
498 owner.submit(
499 cx,
500 SubmittedFrom::NotFromForm,
501 FormSubmitterElement::Button(self),
502 );
503 return;
504 }
505 if button_type == ButtonType::Reset {
508 owner.reset(cx, ResetFrom::NotFromForm);
509 return;
510 }
511 if button_type == ButtonType::Button &&
513 self.upcast::<Element>()
514 .get_string_attribute(&local_name!("type"))
515 .to_ascii_lowercase() !=
516 "button"
517 {
518 return;
519 }
520 }
521 if let Some(pseudo_element) = self.upcast::<Node>().implemented_pseudo_element() {
523 if pseudo_element == PseudoElement::FileSelectorButton {
524 let FlatTreeParent::Parent(parent) = self.upcast::<Node>().parent_in_flat_tree()
525 else {
526 return;
527 };
528
529 parent
530 .downcast::<HTMLInputElement>()
531 .expect("File select button should always be a child of an input element")
532 .activation_behavior(cx, event, target);
533 }
534
535 return;
536 }
537
538 if let Some(target) = self.command_for_element(cx) {
542 let command = self.command_state();
544 if !Self::determine_if_command_is_valid_for_target(command, &target) {
546 return;
547 }
548 let event = CommandEvent::new(
554 cx,
555 &self.owner_window(),
556 atom!("command"),
557 EventBubbles::DoesNotBubble,
558 EventCancelable::Cancelable,
559 Some(self.upcast()),
560 self.upcast::<Element>()
561 .get_string_attribute(&local_name!("command")),
562 );
563 let event = event.upcast::<Event>();
564 if !event.fire(cx, target.upcast::<EventTarget>()) {
565 return;
566 }
567 let target_node = target.upcast::<Node>();
569 if !target_node.is_connected() {
570 return;
571 }
572 if command == CommandState::Custom {
574 return;
575 }
576 let _ = vtable_for(target_node).command_steps(cx, DomRoot::from_ref(self), command);
580 }
581 }
584}
585
586#[derive(Copy, Clone, Eq, PartialEq, Debug)]
587pub(crate) enum CommandState {
588 Unknown,
589 Custom,
590 ShowModal,
591 Close,
592}