1use 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 pub(crate) fn update_default_state(&self, is_default_button: bool, no_gc: &NoGC) {
115 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 fn Command(&self) -> DOMString {
128 match self.command_state() {
130 CommandState::Custom => self
132 .upcast::<Element>()
133 .get_string_attribute(&local_name!("command")),
134 CommandState::Unknown => DOMString::default(),
136 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 make_setter!(SetCommand, "command");
145
146 make_bool_getter!(Disabled, "disabled");
148
149 make_bool_setter!(SetDisabled, "disabled");
151
152 fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
154 self.form_owner()
155 }
156
157 fn Type(&self) -> DOMString {
159 if self.is_submit_button() {
161 return DOMString::from_static("submit");
162 };
163 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 make_setter!(SetType, "type");
173
174 make_form_action_getter!(FormAction, "formaction");
176
177 make_setter!(SetFormAction, "formaction");
179
180 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 make_setter!(SetFormEnctype, "formenctype");
190
191 make_enumerated_getter!(
193 FormMethod,
194 "formmethod",
195 "get" | "post" | "dialog",
196 invalid => "get"
197 );
198
199 make_setter!(SetFormMethod, "formmethod");
201
202 make_getter!(FormTarget, "formtarget");
204
205 make_setter!(SetFormTarget, "formtarget");
207
208 make_bool_getter!(FormNoValidate, "formnovalidate");
210
211 make_bool_setter!(SetFormNoValidate, "formnovalidate");
213
214 make_getter!(Name, "name");
216
217 make_atomic_setter!(SetName, "name");
219
220 make_getter!(Value, "value");
222
223 make_setter!(SetValue, "value");
225
226 make_labels_getter!(Labels, labels_node_list);
228
229 fn WillValidate(&self, no_gc: &NoGC) -> bool {
231 self.is_instance_validatable(no_gc)
232 }
233
234 fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
236 self.validity_state(cx)
237 }
238
239 fn CheckValidity(&self, cx: &mut JSContext) -> bool {
241 self.check_validity(cx)
242 }
243
244 fn ReportValidity(&self, cx: &mut JSContext) -> bool {
246 self.report_validity(cx)
247 }
248
249 fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
251 self.validation_message(cx)
252 }
253
254 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 pub(crate) fn form_datum(&self, submitter: Option<FormSubmitterElement>) -> Option<FormDatum> {
264 if let Some(FormSubmitterElement::Button(submitter)) = submitter {
268 if submitter != self {
269 return None;
270 }
271 } else {
272 return None;
273 }
274 let ty = self.Type();
276 let name = self.Name();
278
279 if name.is_empty() {
280 return None;
282 }
283
284 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 fn determine_if_command_is_valid_for_target(command: CommandState, target: &Element) -> bool {
355 if command == CommandState::Unknown {
357 return false;
358 }
359 if command == CommandState::Custom {
361 return true;
362 }
363 if !target.is_html_element() {
365 return false;
366 }
367 vtable_for(target.upcast::<Node>()).is_valid_command_steps(command)
375 }
376
377 pub(crate) fn optional_value(&self) -> Option<DOMString> {
379 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 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 !self.upcast::<Element>().disabled_state() &&
485 self.upcast::<Node>().implemented_pseudo_element() !=
488 Some(PseudoElement::FileSelectorButton)
489 }
490
491 fn activation_behavior(
493 &self,
494 cx: &mut js::context::JSContext,
495 _: &Event,
496 target: &EventTarget,
497 ) {
498 if self.upcast::<Element>().disabled_state() {
500 return;
501 }
502
503 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 if let Some(owner) = self.form_owner() {
514 if self.is_submit_button() {
517 owner.submit(
518 cx,
519 SubmittedFrom::NotFromForm,
520 FormSubmitterElement::Button(self),
521 );
522 return;
523 }
524 if button_type == ButtonType::Reset {
527 owner.reset(cx, ResetFrom::NotFromForm);
528 return;
529 }
530 if button_type == ButtonType::Auto {
532 return;
533 }
534 }
535
536 if let Some(target) = self.command_for_element(cx) {
540 let command = self.command_state();
542 if !Self::determine_if_command_is_valid_for_target(command, &target) {
544 return;
545 }
546 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 let target_node = target.upcast::<Node>();
567 if !target_node.is_connected() {
568 return;
569 }
570 if command == CommandState::Custom {
572 return;
573 }
574 let _ = vtable_for(target_node).command_steps(cx, DomRoot::from_ref(self), command);
578 }
579 }
582}
583
584#[derive(Copy, Clone, Eq, PartialEq, Debug)]
585pub(crate) enum CommandState {
586 Unknown,
587 Custom,
588 ShowModal,
589 RequestClose,
590 Close,
591}