1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/dom/HTMLButtonElement.h"
9 #include "HTMLFormSubmissionConstants.h"
10 #include "mozilla/dom/FormData.h"
11 #include "mozilla/dom/HTMLButtonElementBinding.h"
12 #include "nsAttrValueInlines.h"
13 #include "nsIContentInlines.h"
14 #include "nsGkAtoms.h"
15 #include "nsStyleConsts.h"
16 #include "nsPresContext.h"
17 #include "nsIFormControl.h"
19 #include "nsIFormControlFrame.h"
20 #include "mozilla/dom/Document.h"
21 #include "mozilla/ContentEvents.h"
22 #include "mozilla/EventDispatcher.h"
23 #include "mozilla/EventStateManager.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/PresShell.h"
26 #include "mozilla/TextEvents.h"
27 #include "nsUnicharUtils.h"
28 #include "nsLayoutUtils.h"
29 #include "mozilla/PresState.h"
31 #include "nsFocusManager.h"
32 #include "mozilla/dom/HTMLFormElement.h"
33 #include "mozAutoDocUpdate.h"
35 #define NS_IN_SUBMIT_CLICK (1 << 0)
36 #define NS_OUTER_ACTIVATE_EVENT (1 << 1)
38 NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Button
)
40 namespace mozilla::dom
{
42 static const nsAttrValue::EnumTable kButtonTypeTable
[] = {
43 {"button", FormControlType::ButtonButton
},
44 {"reset", FormControlType::ButtonReset
},
45 {"submit", FormControlType::ButtonSubmit
},
48 // Default type is 'submit'.
49 static const nsAttrValue::EnumTable
* kButtonDefaultType
= &kButtonTypeTable
[2];
51 // Construction, destruction
52 HTMLButtonElement::HTMLButtonElement(
53 already_AddRefed
<mozilla::dom::NodeInfo
>&& aNodeInfo
,
54 FromParser aFromParser
)
55 : nsGenericHTMLFormControlElementWithState(
56 std::move(aNodeInfo
), aFromParser
,
57 FormControlType(kButtonDefaultType
->value
)),
58 mDisabledChanged(false),
59 mInInternalActivate(false),
60 mInhibitStateRestoration(aFromParser
& FROM_PARSER_FRAGMENT
) {
61 // Set up our default state: enabled
62 AddStatesSilently(ElementState::ENABLED
);
65 HTMLButtonElement::~HTMLButtonElement() = default;
69 NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLButtonElement
,
70 nsGenericHTMLFormControlElementWithState
,
73 NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(
74 HTMLButtonElement
, nsGenericHTMLFormControlElementWithState
,
75 nsIConstraintValidation
)
77 void HTMLButtonElement::SetCustomValidity(const nsAString
& aError
) {
78 ConstraintValidation::SetCustomValidity(aError
);
79 UpdateValidityElementStates(true);
82 void HTMLButtonElement::UpdateBarredFromConstraintValidation() {
83 SetBarredFromConstraintValidation(
84 mType
== FormControlType::ButtonButton
||
85 mType
== FormControlType::ButtonReset
||
86 HasFlag(ELEMENT_IS_DATALIST_OR_HAS_DATALIST_ANCESTOR
) || IsDisabled());
89 void HTMLButtonElement::FieldSetDisabledChanged(bool aNotify
) {
90 // FieldSetDisabledChanged *has* to be called *before*
91 // UpdateBarredFromConstraintValidation, because the latter depends on our
93 nsGenericHTMLFormControlElementWithState::FieldSetDisabledChanged(aNotify
);
95 UpdateBarredFromConstraintValidation();
96 UpdateValidityElementStates(aNotify
);
99 NS_IMPL_ELEMENT_CLONE(HTMLButtonElement
)
101 void HTMLButtonElement::GetFormEnctype(nsAString
& aFormEncType
) {
102 GetEnumAttr(nsGkAtoms::formenctype
, "", kFormDefaultEnctype
->tag
,
106 void HTMLButtonElement::GetFormMethod(nsAString
& aFormMethod
) {
107 GetEnumAttr(nsGkAtoms::formmethod
, "", kFormDefaultMethod
->tag
, aFormMethod
);
110 void HTMLButtonElement::GetType(nsAString
& aType
) {
111 GetEnumAttr(nsGkAtoms::type
, kButtonDefaultType
->tag
, aType
);
114 int32_t HTMLButtonElement::TabIndexDefault() { return 0; }
116 bool HTMLButtonElement::IsHTMLFocusable(bool aWithMouse
, bool* aIsFocusable
,
117 int32_t* aTabIndex
) {
118 if (nsGenericHTMLFormControlElementWithState::IsHTMLFocusable(
119 aWithMouse
, aIsFocusable
, aTabIndex
)) {
123 *aIsFocusable
= IsFormControlDefaultFocusable(aWithMouse
) && !IsDisabled();
128 bool HTMLButtonElement::ParseAttribute(int32_t aNamespaceID
, nsAtom
* aAttribute
,
129 const nsAString
& aValue
,
130 nsIPrincipal
* aMaybeScriptedPrincipal
,
131 nsAttrValue
& aResult
) {
132 if (aNamespaceID
== kNameSpaceID_None
) {
133 if (aAttribute
== nsGkAtoms::type
) {
134 return aResult
.ParseEnumValue(aValue
, kButtonTypeTable
, false,
138 if (aAttribute
== nsGkAtoms::formmethod
) {
139 return aResult
.ParseEnumValue(aValue
, kFormMethodTable
, false);
141 if (aAttribute
== nsGkAtoms::formenctype
) {
142 return aResult
.ParseEnumValue(aValue
, kFormEnctypeTable
, false);
146 return nsGenericHTMLFormControlElementWithState::ParseAttribute(
147 aNamespaceID
, aAttribute
, aValue
, aMaybeScriptedPrincipal
, aResult
);
150 bool HTMLButtonElement::IsDisabledForEvents(WidgetEvent
* aEvent
) {
151 nsIFormControlFrame
* formControlFrame
= GetFormControlFrame(false);
152 nsIFrame
* formFrame
= do_QueryFrame(formControlFrame
);
153 return IsElementDisabledForEvents(aEvent
, formFrame
);
156 void HTMLButtonElement::GetEventTargetParent(EventChainPreVisitor
& aVisitor
) {
157 aVisitor
.mCanHandle
= false;
159 if (IsDisabledForEvents(aVisitor
.mEvent
)) {
163 // Track whether we're in the outermost Dispatch invocation that will
164 // cause activation of the input. That is, if we're a click event, or a
165 // DOMActivate that was dispatched directly, this will be set, but if we're
166 // a DOMActivate dispatched from click handling, it will not be set.
167 WidgetMouseEvent
* mouseEvent
= aVisitor
.mEvent
->AsMouseEvent();
168 bool outerActivateEvent
=
169 ((mouseEvent
&& mouseEvent
->IsLeftClickEvent()) ||
170 (aVisitor
.mEvent
->mMessage
== eLegacyDOMActivate
&&
171 !mInInternalActivate
&& aVisitor
.mEvent
->mOriginalTarget
== this));
173 if (outerActivateEvent
) {
174 aVisitor
.mItemFlags
|= NS_OUTER_ACTIVATE_EVENT
;
175 aVisitor
.mWantsActivationBehavior
= true;
178 nsGenericHTMLElement::GetEventTargetParent(aVisitor
);
181 void HTMLButtonElement::LegacyPreActivationBehavior(
182 EventChainVisitor
& aVisitor
) {
183 // out-of-spec legacy pre-activation behavior needed because of bug 1803805
184 if (mType
== FormControlType::ButtonSubmit
&& mForm
) {
185 aVisitor
.mItemFlags
|= NS_IN_SUBMIT_CLICK
;
186 aVisitor
.mItemData
= static_cast<Element
*>(mForm
);
187 // tell the form that we are about to enter a click handler.
188 // that means that if there are scripted submissions, the
189 // latest one will be deferred until after the exit point of the handler.
190 mForm
->OnSubmitClickBegin(this);
194 nsresult
HTMLButtonElement::PostHandleEvent(EventChainPostVisitor
& aVisitor
) {
196 if (!aVisitor
.mPresContext
) {
200 if (aVisitor
.mEventStatus
!= nsEventStatus_eConsumeNoDefault
) {
201 WidgetMouseEvent
* mouseEvent
= aVisitor
.mEvent
->AsMouseEvent();
202 if (mouseEvent
&& mouseEvent
->IsLeftClickEvent() &&
203 OwnerDoc()->MayHaveDOMActivateListeners()) {
204 // DOMActive event should be trusted since the activation is actually
205 // occurred even if the cause is an untrusted click event.
206 InternalUIEvent
actEvent(true, eLegacyDOMActivate
, mouseEvent
);
207 actEvent
.mDetail
= 1;
209 if (RefPtr
<PresShell
> presShell
= aVisitor
.mPresContext
->GetPresShell()) {
210 nsEventStatus status
= nsEventStatus_eIgnore
;
211 mInInternalActivate
= true;
212 presShell
->HandleDOMEventWithTarget(this, &actEvent
, &status
);
213 mInInternalActivate
= false;
215 // If activate is cancelled, we must do the same as when click is
216 // cancelled (revert the checkbox to its original value).
217 if (status
== nsEventStatus_eConsumeNoDefault
) {
218 aVisitor
.mEventStatus
= status
;
224 if (nsEventStatus_eIgnore
== aVisitor
.mEventStatus
) {
225 WidgetKeyboardEvent
* keyEvent
= aVisitor
.mEvent
->AsKeyboardEvent();
226 if (keyEvent
&& keyEvent
->IsTrusted()) {
227 HandleKeyboardActivation(aVisitor
);
230 // Bug 1459231: Temporarily needed till links respect activation target
231 // Then also remove NS_OUTER_ACTIVATE_EVENT
232 if ((aVisitor
.mItemFlags
& NS_OUTER_ACTIVATE_EVENT
) && mForm
&&
233 (mType
== FormControlType::ButtonReset
||
234 mType
== FormControlType::ButtonSubmit
)) {
235 aVisitor
.mEvent
->mFlags
.mMultipleActionsPrevented
= true;
242 void EndSubmitClick(EventChainVisitor
& aVisitor
) {
243 if ((aVisitor
.mItemFlags
& NS_IN_SUBMIT_CLICK
)) {
244 nsCOMPtr
<nsIContent
> content(do_QueryInterface(aVisitor
.mItemData
));
245 RefPtr
<HTMLFormElement
> form
= HTMLFormElement::FromNodeOrNull(content
);
247 // Tell the form that we are about to exit a click handler,
248 // so the form knows not to defer subsequent submissions.
249 // The pending ones that were created during the handler
250 // will be flushed or forgotten.
251 form
->OnSubmitClickEnd();
252 // Tell the form to flush a possible pending submission.
253 // the reason is that the script returned false (the event was
254 // not ignored) so if there is a stored submission, it needs to
255 // be submitted immediatelly.
256 // Note, NS_IN_SUBMIT_CLICK is set only when we're in outer activate event.
257 form
->FlushPendingSubmission();
261 void HTMLButtonElement::ActivationBehavior(EventChainPostVisitor
& aVisitor
) {
262 if (!aVisitor
.mPresContext
) {
263 // Should check whether EndSubmitClick is needed here.
269 // Hold a strong ref while dispatching
270 RefPtr
<mozilla::dom::HTMLFormElement
> form(mForm
);
271 if (mType
== FormControlType::ButtonReset
) {
272 form
->MaybeReset(this);
273 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
274 } else if (mType
== FormControlType::ButtonSubmit
) {
275 form
->MaybeSubmit(this);
276 aVisitor
.mEventStatus
= nsEventStatus_eConsumeNoDefault
;
278 // https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type-button-state
279 // NS_FORM_BUTTON_BUTTON do nothing.
281 if (!GetInvokeTargetElement()) {
282 HandlePopoverTargetAction();
284 HandleInvokeTargetAction();
288 EndSubmitClick(aVisitor
);
291 void HTMLButtonElement::LegacyCanceledActivationBehavior(
292 EventChainPostVisitor
& aVisitor
) {
293 // still need to end submission, see bug 1803805
294 // e.g. when parent element of button has event handler preventing default
295 // legacy canceled instead of activation behavior will be run
296 EndSubmitClick(aVisitor
);
299 nsresult
HTMLButtonElement::BindToTree(BindContext
& aContext
,
302 nsGenericHTMLFormControlElementWithState::BindToTree(aContext
, aParent
);
303 NS_ENSURE_SUCCESS(rv
, rv
);
305 UpdateBarredFromConstraintValidation();
306 UpdateValidityElementStates(false);
311 void HTMLButtonElement::UnbindFromTree(UnbindContext
& aContext
) {
312 nsGenericHTMLFormControlElementWithState::UnbindFromTree(aContext
);
314 UpdateBarredFromConstraintValidation();
315 UpdateValidityElementStates(false);
319 HTMLButtonElement::Reset() { return NS_OK
; }
322 HTMLButtonElement::SubmitNamesValues(FormData
* aFormData
) {
324 // We only submit if we were the button pressed
326 if (aFormData
->GetSubmitterElement() != this) {
331 // Get the name (if no name, no submit)
334 GetHTMLAttr(nsGkAtoms::name
, name
);
335 if (name
.IsEmpty()) {
343 GetHTMLAttr(nsGkAtoms::value
, value
);
348 return aFormData
->AddNameValuePair(name
, value
);
351 void HTMLButtonElement::DoneCreatingElement() {
352 if (!mInhibitStateRestoration
) {
354 RestoreFormControlState();
358 void HTMLButtonElement::BeforeSetAttr(int32_t aNameSpaceID
, nsAtom
* aName
,
359 const nsAttrValue
* aValue
, bool aNotify
) {
360 if (aNotify
&& aName
== nsGkAtoms::disabled
&&
361 aNameSpaceID
== kNameSpaceID_None
) {
362 mDisabledChanged
= true;
365 return nsGenericHTMLFormControlElementWithState::BeforeSetAttr(
366 aNameSpaceID
, aName
, aValue
, aNotify
);
369 void HTMLButtonElement::AfterSetAttr(int32_t aNameSpaceID
, nsAtom
* aName
,
370 const nsAttrValue
* aValue
,
371 const nsAttrValue
* aOldValue
,
372 nsIPrincipal
* aSubjectPrincipal
,
374 if (aNameSpaceID
== kNameSpaceID_None
) {
375 if (aName
== nsGkAtoms::type
) {
377 mType
= FormControlType(aValue
->GetEnumValue());
379 mType
= FormControlType(kButtonDefaultType
->value
);
383 if (aName
== nsGkAtoms::type
|| aName
== nsGkAtoms::disabled
) {
384 if (aName
== nsGkAtoms::disabled
) {
385 // This *has* to be called *before* validity state check because
386 // UpdateBarredFromConstraintValidation depends on our disabled state.
387 UpdateDisabledState(aNotify
);
390 UpdateBarredFromConstraintValidation();
391 UpdateValidityElementStates(aNotify
);
395 return nsGenericHTMLFormControlElementWithState::AfterSetAttr(
396 aNameSpaceID
, aName
, aValue
, aOldValue
, aSubjectPrincipal
, aNotify
);
399 void HTMLButtonElement::SaveState() {
400 if (!mDisabledChanged
) {
404 PresState
* state
= GetPrimaryPresState();
406 // We do not want to save the real disabled state but the disabled
408 state
->disabled() = HasAttr(nsGkAtoms::disabled
);
409 state
->disabledSet() = true;
413 bool HTMLButtonElement::RestoreState(PresState
* aState
) {
414 if (aState
&& aState
->disabledSet() && !aState
->disabled()) {
415 SetDisabled(false, IgnoreErrors());
420 void HTMLButtonElement::UpdateValidityElementStates(bool aNotify
) {
421 AutoStateChangeNotifier
notifier(*this, aNotify
);
422 RemoveStatesSilently(ElementState::VALIDITY_STATES
);
423 if (!IsCandidateForConstraintValidation()) {
427 AddStatesSilently(ElementState::VALID
| ElementState::USER_VALID
);
429 AddStatesSilently(ElementState::INVALID
| ElementState::USER_INVALID
);
433 JSObject
* HTMLButtonElement::WrapNode(JSContext
* aCx
,
434 JS::Handle
<JSObject
*> aGivenProto
) {
435 return HTMLButtonElement_Binding::Wrap(aCx
, this, aGivenProto
);
438 } // namespace mozilla::dom