Bug 1719855 - Take over preventDefaulted infomation for long-tap events to the origin...
[gecko.git] / dom / html / HTMLFormElement.h
blob80b40c6bcee01cce1d55ee7a483956b94ae18602
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 #ifndef mozilla_dom_HTMLFormElement_h
8 #define mozilla_dom_HTMLFormElement_h
10 #include "mozilla/AsyncEventDispatcher.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/UniquePtr.h"
13 #include "mozilla/dom/AnchorAreaFormRelValues.h"
14 #include "mozilla/dom/BrowsingContext.h"
15 #include "mozilla/dom/PopupBlocker.h"
16 #include "mozilla/dom/RadioGroupManager.h"
17 #include "nsCOMPtr.h"
18 #include "nsIFormControl.h"
19 #include "nsGenericHTMLElement.h"
20 #include "nsIRadioGroupContainer.h"
21 #include "nsIWeakReferenceUtils.h"
22 #include "nsThreadUtils.h"
23 #include "nsInterfaceHashtable.h"
24 #include "nsRefPtrHashtable.h"
25 #include "nsTHashMap.h"
26 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
28 class nsIMutableArray;
29 class nsIURI;
31 namespace mozilla {
32 class EventChainPostVisitor;
33 class EventChainPreVisitor;
34 namespace dom {
35 class DialogFormSubmission;
36 class HTMLFormControlsCollection;
37 class HTMLFormSubmission;
38 class HTMLImageElement;
39 class FormData;
41 class HTMLFormElement final : public nsGenericHTMLElement,
42 public nsIRadioGroupContainer,
43 public AnchorAreaFormRelValues,
44 RadioGroupManager {
45 friend class HTMLFormControlsCollection;
47 public:
48 NS_IMPL_FROMNODE_HTML_WITH_TAG(HTMLFormElement, form)
50 explicit HTMLFormElement(
51 already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
53 enum { FORM_CONTROL_LIST_HASHTABLE_LENGTH = 8 };
55 // nsISupports
56 NS_DECL_ISUPPORTS_INHERITED
58 int32_t IndexOfContent(nsIContent* aContent);
59 nsGenericHTMLFormElement* GetDefaultSubmitElement() const;
61 // nsIRadioGroupContainer
62 void SetCurrentRadioButton(const nsAString& aName,
63 HTMLInputElement* aRadio) override;
64 HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) override;
65 NS_IMETHOD GetNextRadioButton(const nsAString& aName, const bool aPrevious,
66 HTMLInputElement* aFocusedRadio,
67 HTMLInputElement** aRadioOut) override;
68 NS_IMETHOD WalkRadioGroup(const nsAString& aName,
69 nsIRadioVisitor* aVisitor) override;
70 void AddToRadioGroup(const nsAString& aName,
71 HTMLInputElement* aRadio) override;
72 void RemoveFromRadioGroup(const nsAString& aName,
73 HTMLInputElement* aRadio) override;
74 uint32_t GetRequiredRadioCount(const nsAString& aName) const override;
75 void RadioRequiredWillChange(const nsAString& aName,
76 bool aRequiredAdded) override;
77 bool GetValueMissingState(const nsAString& aName) const override;
78 void SetValueMissingState(const nsAString& aName, bool aValue) override;
80 ElementState IntrinsicState() const override;
82 // EventTarget
83 void AsyncEventRunning(AsyncEventDispatcher* aEvent) override;
85 // nsIContent
86 bool ParseAttribute(int32_t aNamespaceID, nsAtom* aAttribute,
87 const nsAString& aValue,
88 nsIPrincipal* aMaybeScriptedPrincipal,
89 nsAttrValue& aResult) override;
90 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
91 void WillHandleEvent(EventChainPostVisitor& aVisitor) override;
92 nsresult PostHandleEvent(EventChainPostVisitor& aVisitor) override;
94 nsresult BindToTree(BindContext&, nsINode& aParent) override;
95 void UnbindFromTree(bool aNullParent = true) override;
96 void BeforeSetAttr(int32_t aNamespaceID, nsAtom* aName,
97 const nsAttrValue* aValue, bool aNotify) override;
99 /**
100 * Forget all information about the current submission (and the fact that we
101 * are currently submitting at all).
103 void ForgetCurrentSubmission();
105 nsresult Clone(dom::NodeInfo*, nsINode** aResult) const override;
107 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLFormElement,
108 nsGenericHTMLElement)
111 * Remove an element from this form's list of elements
113 * @param aElement the element to remove
114 * @param aUpdateValidity If true, updates the form validity.
115 * @return NS_OK if the element was successfully removed.
117 nsresult RemoveElement(nsGenericHTMLFormElement* aElement,
118 bool aUpdateValidity);
121 * Remove an element from the lookup table maintained by the form.
122 * We can't fold this method into RemoveElement() because when
123 * RemoveElement() is called it doesn't know if the element is
124 * removed because the id attribute has changed, or because the
125 * name attribute has changed.
127 * @param aElement the element to remove
128 * @param aName the name or id of the element to remove
129 * @return NS_OK if the element was successfully removed.
131 nsresult RemoveElementFromTable(nsGenericHTMLFormElement* aElement,
132 const nsAString& aName);
135 * Add an element to end of this form's list of elements
137 * @param aElement the element to add
138 * @param aUpdateValidity If true, the form validity will be updated.
139 * @param aNotify If true, send DocumentObserver notifications as needed.
140 * @return NS_OK if the element was successfully added
142 nsresult AddElement(nsGenericHTMLFormElement* aElement, bool aUpdateValidity,
143 bool aNotify);
146 * Add an element to the lookup table maintained by the form.
148 * We can't fold this method into AddElement() because when
149 * AddElement() is called, the form control has no
150 * attributes. The name or id attributes of the form control
151 * are used as a key into the table.
153 nsresult AddElementToTable(nsGenericHTMLFormElement* aChild,
154 const nsAString& aName);
157 * Remove an image element from this form's list of image elements
159 * @param aElement the image element to remove
160 * @return NS_OK if the element was successfully removed.
162 nsresult RemoveImageElement(HTMLImageElement* aElement);
165 * Remove an image element from the lookup table maintained by the form.
166 * We can't fold this method into RemoveImageElement() because when
167 * RemoveImageElement() is called it doesn't know if the element is
168 * removed because the id attribute has changed, or because the
169 * name attribute has changed.
171 * @param aElement the image element to remove
172 * @param aName the name or id of the element to remove
173 * @return NS_OK if the element was successfully removed.
175 nsresult RemoveImageElementFromTable(HTMLImageElement* aElement,
176 const nsAString& aName);
178 * Add an image element to the end of this form's list of image elements
180 * @param aElement the element to add
181 * @return NS_OK if the element was successfully added
183 nsresult AddImageElement(HTMLImageElement* aElement);
186 * Add an image element to the lookup table maintained by the form.
188 * We can't fold this method into AddImageElement() because when
189 * AddImageElement() is called, the image attributes can change.
190 * The name or id attributes of the image are used as a key into the table.
192 nsresult AddImageElementToTable(HTMLImageElement* aChild,
193 const nsAString& aName);
196 * Returns true if implicit submission of this form is disabled. For more
197 * on implicit submission see:
199 * http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#implicit-submission
201 bool ImplicitSubmissionIsDisabled() const;
204 * Check whether a given nsGenericHTMLFormElement is the last single line
205 * input control that is not disabled. aElement is expected to not be null.
207 bool IsLastActiveElement(const nsGenericHTMLFormElement* aElement) const;
210 * Check whether a given nsGenericHTMLFormElement is the default submit
211 * element. This is different from just comparing to
212 * GetDefaultSubmitElement() in certain situations inside an update
213 * when GetDefaultSubmitElement() might not be up to date. aElement
214 * is expected to not be null.
216 bool IsDefaultSubmitElement(const nsGenericHTMLFormElement* aElement) const;
219 * Flag the form to know that a button or image triggered scripted form
220 * submission. In that case the form will defer the submission until the
221 * script handler returns and the return value is known.
223 void OnSubmitClickBegin(Element* aOriginatingElement);
224 void OnSubmitClickEnd();
227 * This method will update the form validity.
229 * This method has to be called by form elements whenever their validity state
230 * or status regarding constraint validation changes.
232 * @note This method isn't used for CheckValidity().
233 * @note If an element becomes barred from constraint validation, it has to be
234 * considered as valid.
236 * @param aElementValidityState the new validity state of the element
238 void UpdateValidity(bool aElementValidityState);
241 * This method check the form validity and make invalid form elements send
242 * invalid event if needed.
244 * @return Whether the form is valid.
246 * @note Do not call this method if novalidate/formnovalidate is used.
247 * @note This method might disappear with bug 592124, hopefuly.
248 * @see
249 * https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#interactively-validate-the-constraints
251 bool CheckValidFormSubmission();
254 * Contruct the entry list to get their data pumped into the FormData and
255 * fire a `formdata` event with the entry list in formData attribute.
256 * <https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-form-data-set>
258 * @param aFormData the form data object
260 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
261 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult ConstructEntryList(FormData* aFormData);
264 * Whether the submission of this form has been ever prevented because of
265 * being invalid.
267 * @return Whether the submission of this form has been prevented because of
268 * being invalid.
270 bool HasEverTriedInvalidSubmit() const { return mEverTriedInvalidSubmit; }
273 * Implements form[name]. Returns form controls in this form with the correct
274 * value of the name attribute.
276 already_AddRefed<nsISupports> FindNamedItem(const nsAString& aName,
277 nsWrapperCache** aCache);
279 // WebIDL
281 void GetAcceptCharset(DOMString& aValue) {
282 GetHTMLAttr(nsGkAtoms::acceptcharset, aValue);
285 void SetAcceptCharset(const nsAString& aValue, ErrorResult& aRv) {
286 SetHTMLAttr(nsGkAtoms::acceptcharset, aValue, aRv);
289 void GetAction(nsString& aValue);
290 void SetAction(const nsAString& aValue, ErrorResult& aRv) {
291 SetHTMLAttr(nsGkAtoms::action, aValue, aRv);
294 void GetAutocomplete(nsAString& aValue);
295 void SetAutocomplete(const nsAString& aValue, ErrorResult& aRv) {
296 SetHTMLAttr(nsGkAtoms::autocomplete, aValue, aRv);
299 void GetEnctype(nsAString& aValue);
300 void SetEnctype(const nsAString& aValue, ErrorResult& aRv) {
301 SetHTMLAttr(nsGkAtoms::enctype, aValue, aRv);
304 void GetEncoding(nsAString& aValue) { GetEnctype(aValue); }
305 void SetEncoding(const nsAString& aValue, ErrorResult& aRv) {
306 SetEnctype(aValue, aRv);
309 void GetMethod(nsAString& aValue);
310 void SetMethod(const nsAString& aValue, ErrorResult& aRv) {
311 SetHTMLAttr(nsGkAtoms::method, aValue, aRv);
314 void GetName(DOMString& aValue) { GetHTMLAttr(nsGkAtoms::name, aValue); }
316 void SetName(const nsAString& aValue, ErrorResult& aRv) {
317 SetHTMLAttr(nsGkAtoms::name, aValue, aRv);
320 bool NoValidate() const { return GetBoolAttr(nsGkAtoms::novalidate); }
322 void SetNoValidate(bool aValue, ErrorResult& aRv) {
323 SetHTMLBoolAttr(nsGkAtoms::novalidate, aValue, aRv);
326 void GetTarget(DOMString& aValue) { GetHTMLAttr(nsGkAtoms::target, aValue); }
328 void SetTarget(const nsAString& aValue, ErrorResult& aRv) {
329 SetHTMLAttr(nsGkAtoms::target, aValue, aRv);
332 void GetRel(DOMString& aValue) { GetHTMLAttr(nsGkAtoms::rel, aValue); }
333 void SetRel(const nsAString& aRel, ErrorResult& aError) {
334 SetHTMLAttr(nsGkAtoms::rel, aRel, aError);
336 nsDOMTokenList* RelList();
338 // it's only out-of-line because the class definition is not available in the
339 // header
340 nsIHTMLCollection* Elements();
342 int32_t Length();
345 * Check whether submission can proceed for this form then fire submit event.
346 * This basically implements steps 1-6 (more or less) of
347 * <https://html.spec.whatwg.org/multipage/forms.html#concept-form-submit>.
348 * @param aSubmitter If not null, is the "submitter" from that algorithm.
349 * Therefore it must be a valid submit control.
351 MOZ_CAN_RUN_SCRIPT void MaybeSubmit(Element* aSubmitter);
352 MOZ_CAN_RUN_SCRIPT void MaybeReset(Element* aSubmitter);
353 void Submit(ErrorResult& aRv);
356 * Requests to submit the form. Unlike submit(), this method includes
357 * interactive constraint validation and firing a submit event,
358 * either of which can cancel submission.
360 * @param aSubmitter The submitter argument can be used to point to a specific
361 * submit button.
362 * @param aRv An ErrorResult.
363 * @see
364 * https://html.spec.whatwg.org/multipage/forms.html#dom-form-requestsubmit
366 MOZ_CAN_RUN_SCRIPT void RequestSubmit(nsGenericHTMLElement* aSubmitter,
367 ErrorResult& aRv);
369 MOZ_CAN_RUN_SCRIPT void Reset();
371 bool CheckValidity() { return CheckFormValidity(nullptr); }
373 bool ReportValidity() { return CheckValidFormSubmission(); }
375 Element* IndexedGetter(uint32_t aIndex, bool& aFound);
377 already_AddRefed<nsISupports> NamedGetter(const nsAString& aName,
378 bool& aFound);
380 void GetSupportedNames(nsTArray<nsString>& aRetval);
382 static int32_t CompareFormControlPosition(Element* aElement1,
383 Element* aElement2,
384 const nsIContent* aForm);
385 #ifdef DEBUG
386 static void AssertDocumentOrder(
387 const nsTArray<nsGenericHTMLFormElement*>& aControls, nsIContent* aForm);
388 static void AssertDocumentOrder(
389 const nsTArray<RefPtr<nsGenericHTMLFormElement>>& aControls,
390 nsIContent* aForm);
391 #endif
393 JS::ExpandoAndGeneration mExpandoAndGeneration;
395 protected:
396 JSObject* WrapNode(JSContext*, JS::Handle<JSObject*> aGivenProto) override;
398 void PostPasswordEvent();
399 void PostPossibleUsernameEvent();
401 RefPtr<AsyncEventDispatcher> mFormPasswordEventDispatcher;
402 RefPtr<AsyncEventDispatcher> mFormPossibleUsernameEventDispatcher;
404 class RemoveElementRunnable;
405 friend class RemoveElementRunnable;
407 class RemoveElementRunnable : public Runnable {
408 public:
409 explicit RemoveElementRunnable(HTMLFormElement* aForm)
410 : Runnable("dom::HTMLFormElement::RemoveElementRunnable"),
411 mForm(aForm) {}
413 NS_IMETHOD Run() override {
414 mForm->HandleDefaultSubmitRemoval();
415 return NS_OK;
418 private:
419 RefPtr<HTMLFormElement> mForm;
422 nsresult DoReset();
424 // Async callback to handle removal of our default submit
425 void HandleDefaultSubmitRemoval();
428 // Submit Helpers
432 * Attempt to submit (submission might be deferred)
434 * @param aPresContext the presentation context
435 * @param aEvent the DOM event that was passed to us for the submit
437 nsresult DoSubmit(Event* aEvent = nullptr);
440 * Prepare the submission object (called by DoSubmit)
442 * @param aFormSubmission the submission object
443 * @param aEvent the DOM event that was passed to us for the submit
445 nsresult BuildSubmission(HTMLFormSubmission** aFormSubmission, Event* aEvent);
447 * Perform the submission (called by DoSubmit and FlushPendingSubmission)
449 * @param aFormSubmission the submission object
451 nsresult SubmitSubmission(HTMLFormSubmission* aFormSubmission);
454 * Submit a form[method=dialog]
455 * @param aFormSubmission the submission object
457 nsresult SubmitDialog(DialogFormSubmission* aFormSubmission);
460 * Notify any submit observers of the submit.
462 * @param aActionURL the URL being submitted to
463 * @param aCancelSubmit out param where submit observers can specify that the
464 * submit should be cancelled.
466 nsresult NotifySubmitObservers(nsIURI* aActionURL, bool* aCancelSubmit,
467 bool aEarlyNotify);
470 * If this form submission is secure -> insecure, ask the user if they want
471 * to continue.
473 * @param aActionURL the URL being submitted to
474 * @param aCancelSubmit out param: will be true if the user wants to cancel
476 nsresult DoSecureToInsecureSubmitCheck(nsIURI* aActionURL,
477 bool* aCancelSubmit);
480 * Find form controls in this form with the correct value in the name
481 * attribute.
483 already_AddRefed<nsISupports> DoResolveName(const nsAString& aName);
486 * Check the form validity following this algorithm:
487 * https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#statically-validate-the-constraints
489 * @param aInvalidElements [out] parameter containing the list of unhandled
490 * invalid controls.
492 * @return Whether the form is currently valid.
494 bool CheckFormValidity(nsTArray<RefPtr<Element>>* aInvalidElements) const;
496 // Clear the mImageNameLookupTable and mImageElements.
497 void Clear();
499 // Insert a element into the past names map.
500 void AddToPastNamesMap(const nsAString& aName, nsISupports* aChild);
502 // Remove the given element from the past names map. The element must be an
503 // nsGenericHTMLFormElement or HTMLImageElement.
504 void RemoveElementFromPastNamesMap(Element* aElement);
506 nsresult AddElementToTableInternal(
507 nsInterfaceHashtable<nsStringHashKey, nsISupports>& aTable,
508 nsIContent* aChild, const nsAString& aName);
510 nsresult RemoveElementFromTableInternal(
511 nsInterfaceHashtable<nsStringHashKey, nsISupports>& aTable,
512 nsIContent* aChild, const nsAString& aName);
514 public:
516 * Flush a possible pending submission. If there was a scripted submission
517 * triggered by a button or image, the submission was defered. This method
518 * forces the pending submission to be submitted. (happens when the handler
519 * returns false or there is an action/target change in the script)
521 void FlushPendingSubmission();
524 * Get the full URL to submit to. Do not submit if the returned URL is null.
526 * @param aActionURL the full, unadulterated URL you'll be submitting to [OUT]
527 * @param aOriginatingElement the originating element of the form submission
528 * [IN]
530 nsresult GetActionURL(nsIURI** aActionURL, Element* aOriginatingElement);
532 // Returns a number for this form that is unique within its owner document.
533 // This is used by nsContentUtils::GenerateStateKey to identify form controls
534 // that are inserted into the document by the parser.
535 int32_t GetFormNumberForStateKey();
538 * Called when we have been cloned and adopted, and the information of the
539 * node has been changed.
541 void NodeInfoChanged(Document* aOldDoc) override;
543 protected:
545 // Data members
547 /** The list of controls (form.elements as well as stuff not in elements) */
548 RefPtr<HTMLFormControlsCollection> mControls;
550 /** The pending submission object */
551 UniquePtr<HTMLFormSubmission> mPendingSubmission;
553 /** The target browsing context, if any. */
554 RefPtr<BrowsingContext> mTargetContext;
555 /** The load identifier for the pending request created for a
556 * submit, used to be able to block double submits. */
557 Maybe<uint64_t> mCurrentLoadId;
559 /** The default submit element -- WEAK */
560 nsGenericHTMLFormElement* mDefaultSubmitElement;
562 /** The first submit element in mElements -- WEAK */
563 nsGenericHTMLFormElement* mFirstSubmitInElements;
565 /** The first submit element in mNotInElements -- WEAK */
566 nsGenericHTMLFormElement* mFirstSubmitNotInElements;
568 // This array holds on to all HTMLImageElement(s).
569 // This is needed to properly clean up the bi-directional references
570 // (both weak and strong) between the form and its HTMLImageElements.
572 nsTArray<HTMLImageElement*> mImageElements; // Holds WEAK references
574 // A map from an ID or NAME attribute to the HTMLImageElement(s), this
575 // hash holds strong references either to the named HTMLImageElement, or
576 // to a list of named HTMLImageElement(s), in the case where this hash
577 // holds on to a list of named HTMLImageElement(s) the list has weak
578 // references to the HTMLImageElement.
580 nsInterfaceHashtable<nsStringHashKey, nsISupports> mImageNameLookupTable;
582 // A map from names to elements that were gotten by those names from this
583 // form in that past. See "past names map" in the HTML5 specification.
585 nsInterfaceHashtable<nsStringHashKey, nsISupports> mPastNameLookupTable;
587 /** Keep track of what the popup state was when the submit was initiated */
588 PopupBlocker::PopupControlState mSubmitPopupState;
590 RefPtr<nsDOMTokenList> mRelList;
593 * Number of invalid and candidate for constraint validation elements in the
594 * form the last time UpdateValidity has been called.
596 int32_t mInvalidElementsCount;
598 // See GetFormNumberForStateKey.
599 int32_t mFormNumber;
601 /** Whether we are currently processing a submit event or not */
602 bool mGeneratingSubmit;
603 /** Whether we are currently processing a reset event or not */
604 bool mGeneratingReset;
605 /** Whether the submission is to be deferred in case a script triggers it */
606 bool mDeferSubmission;
607 /** Whether we notified NS_FORMSUBMIT_SUBJECT listeners already */
608 bool mNotifiedObservers;
609 /** If we notified the listeners early, what was the result? */
610 bool mNotifiedObserversResult;
612 * Whether the submission of this form has been ever prevented because of
613 * being invalid.
615 bool mEverTriedInvalidSubmit;
616 /** Whether we are constructing entry list */
617 bool mIsConstructingEntryList;
618 /** Whether we are firing submission event */
619 bool mIsFiringSubmissionEvents;
621 private:
622 bool IsSubmitting() const;
624 NotNull<const Encoding*> GetSubmitEncoding();
627 * Fire an event when the form is removed from the DOM tree. This is now only
628 * used by the password manager.
630 void MaybeFireFormRemoved();
632 ~HTMLFormElement();
635 } // namespace dom
637 } // namespace mozilla
639 #endif // mozilla_dom_HTMLFormElement_h