2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
6 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
8 * Copyright (C) 2010 Google Inc. All rights reserved.
9 * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
10 * Copyright (C) 2012 Samsung Electronics. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
30 #include "HTMLInputElement.h"
32 #include "AXObjectCache.h"
33 #include "BeforeTextInsertedEvent.h"
34 #include "CSSPropertyNames.h"
35 #include "DateTimeChooser.h"
38 #include "EventNames.h"
39 #include "FileInputType.h"
41 #include "FormController.h"
43 #include "FrameSelection.h"
44 #include "FrameView.h"
45 #include "HTMLDataListElement.h"
46 #include "HTMLFormElement.h"
47 #include "HTMLImageLoader.h"
48 #include "HTMLOptionElement.h"
49 #include "HTMLParserIdioms.h"
50 #include "IdTargetObserver.h"
51 #include "KeyboardEvent.h"
52 #include "LocalizedStrings.h"
53 #include "MouseEvent.h"
54 #include "PlatformMouseEvent.h"
55 #include "RenderTextControlSingleLine.h"
56 #include "RenderTheme.h"
57 #include "ScopedEventQueue.h"
58 #include "SearchInputType.h"
60 #include "StyleResolver.h"
61 #include <wtf/Language.h>
62 #include <wtf/MathExtras.h>
65 #if ENABLE(TOUCH_EVENTS)
66 #include "TouchEvent.h"
71 using namespace HTMLNames;
73 #if ENABLE(DATALIST_ELEMENT)
74 class ListAttributeTargetObserver : IdTargetObserver {
75 WTF_MAKE_FAST_ALLOCATED;
77 ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement*);
79 void idTargetChanged() override;
82 HTMLInputElement* m_element;
86 // FIXME: According to HTML4, the length attribute's value can be arbitrarily
87 // large. However, due to https://bugs.webkit.org/show_bug.cgi?id=14536 things
88 // get rather sluggish when a text field has a larger number of characters than
89 // this, even when just clicking in the text field.
90 const unsigned HTMLInputElement::maxEffectiveLength = 524288;
91 const int defaultSize = 20;
92 const int maxSavedResults = 256;
94 HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
95 : HTMLTextFormControlElement(tagName, document, form)
99 , m_reflectsCheckedAttribute(true)
100 , m_isIndeterminate(false)
102 , m_isActivatedSubmit(false)
103 , m_autocomplete(Uninitialized)
104 , m_isAutoFilled(false)
105 , m_autoFillButtonType(static_cast<uint8_t>(AutoFillButtonType::None))
106 , m_isAutoFillAvailable(false)
107 #if ENABLE(DATALIST_ELEMENT)
108 , m_hasNonEmptyList(false)
110 , m_stateRestored(false)
111 , m_parsingInProgress(createdByParser)
112 , m_valueAttributeWasUpdatedAfterParsing(false)
113 , m_wasModifiedByUser(false)
114 , m_canReceiveDroppedFiles(false)
115 #if ENABLE(TOUCH_EVENTS)
116 , m_hasTouchEventHandler(false)
118 , m_isSpellcheckDisabledExceptTextReplacement(false)
119 // m_inputType is lazily created when constructed by the parser to avoid constructing unnecessarily a text inputType and
120 // its shadow subtree, just to destroy them when the |type| attribute gets set by the parser to something else than 'text'.
121 , m_inputType(createdByParser ? nullptr : InputType::createText(*this))
123 ASSERT(hasTagName(inputTag));
124 setHasCustomStyleResolveCallbacks();
127 Ref<HTMLInputElement> HTMLInputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
129 bool shouldCreateShadowRootLazily = createdByParser;
130 Ref<HTMLInputElement> inputElement = adoptRef(*new HTMLInputElement(tagName, document, form, createdByParser));
131 if (!shouldCreateShadowRootLazily)
132 inputElement->ensureUserAgentShadowRoot();
136 HTMLImageLoader& HTMLInputElement::ensureImageLoader()
139 m_imageLoader = std::make_unique<HTMLImageLoader>(*this);
140 return *m_imageLoader;
143 void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot*)
145 m_inputType->createShadowSubtree();
146 updateInnerTextElementEditability();
149 HTMLInputElement::~HTMLInputElement()
151 if (needsSuspensionCallback())
152 document().unregisterForDocumentSuspensionCallbacks(this);
154 // Need to remove form association while this is still an HTMLInputElement
155 // so that virtual functions are called correctly.
157 // setForm(0) may register this to a document-level radio button group.
158 // We should unregister it to avoid accessing a deleted object.
160 document().formController().radioButtonGroups().removeButton(this);
161 #if ENABLE(TOUCH_EVENTS)
162 if (m_hasTouchEventHandler)
163 document().didRemoveEventTargetNode(*this);
167 const AtomicString& HTMLInputElement::name() const
169 return m_name.isNull() ? emptyAtom() : m_name;
172 Vector<FileChooserFileInfo> HTMLInputElement::filesFromFileInputFormControlState(const FormControlState& state)
174 return FileInputType::filesFromFormControlState(state);
177 HTMLElement* HTMLInputElement::containerElement() const
179 return m_inputType->containerElement();
182 TextControlInnerTextElement* HTMLInputElement::innerTextElement() const
184 return m_inputType->innerTextElement();
187 HTMLElement* HTMLInputElement::innerBlockElement() const
189 return m_inputType->innerBlockElement();
192 HTMLElement* HTMLInputElement::innerSpinButtonElement() const
194 return m_inputType->innerSpinButtonElement();
197 HTMLElement* HTMLInputElement::capsLockIndicatorElement() const
199 return m_inputType->capsLockIndicatorElement();
202 HTMLElement* HTMLInputElement::autoFillButtonElement() const
204 return m_inputType->autoFillButtonElement();
207 HTMLElement* HTMLInputElement::resultsButtonElement() const
209 return m_inputType->resultsButtonElement();
212 HTMLElement* HTMLInputElement::cancelButtonElement() const
214 return m_inputType->cancelButtonElement();
217 HTMLElement* HTMLInputElement::sliderThumbElement() const
219 return m_inputType->sliderThumbElement();
222 HTMLElement* HTMLInputElement::sliderTrackElement() const
224 return m_inputType->sliderTrackElement();
227 HTMLElement* HTMLInputElement::placeholderElement() const
229 return m_inputType->placeholderElement();
232 bool HTMLInputElement::shouldAutocomplete() const
234 if (m_autocomplete != Uninitialized)
235 return m_autocomplete == On;
236 return HTMLTextFormControlElement::shouldAutocomplete();
239 bool HTMLInputElement::isValidValue(const String& value) const
241 if (!m_inputType->canSetStringValue()) {
242 ASSERT_NOT_REACHED();
245 return !m_inputType->typeMismatchFor(value)
246 && !m_inputType->stepMismatch(value)
247 && !m_inputType->rangeUnderflow(value)
248 && !m_inputType->rangeOverflow(value)
249 && !tooShort(value, IgnoreDirtyFlag)
250 && !tooLong(value, IgnoreDirtyFlag)
251 && !m_inputType->patternMismatch(value)
252 && !m_inputType->valueMissing(value);
255 bool HTMLInputElement::tooShort() const
257 return willValidate() && tooShort(value(), CheckDirtyFlag);
260 bool HTMLInputElement::tooLong() const
262 return willValidate() && tooLong(value(), CheckDirtyFlag);
265 bool HTMLInputElement::typeMismatch() const
267 return willValidate() && m_inputType->typeMismatch();
270 bool HTMLInputElement::valueMissing() const
272 return willValidate() && m_inputType->valueMissing(value());
275 bool HTMLInputElement::hasBadInput() const
277 return willValidate() && m_inputType->hasBadInput();
280 bool HTMLInputElement::patternMismatch() const
282 return willValidate() && m_inputType->patternMismatch(value());
285 bool HTMLInputElement::tooShort(StringView value, NeedsToCheckDirtyFlag check) const
287 if (!supportsMinLength())
290 int min = minLength();
294 if (check == CheckDirtyFlag) {
295 // Return false for the default value or a value set by a script even if
296 // it is shorter than minLength.
297 if (!hasDirtyValue() || !m_wasModifiedByUser)
301 // The empty string is excluded from tooShort validation.
305 // FIXME: The HTML specification says that the "number of characters" is measured using code-unit length.
306 return numGraphemeClusters(value) < static_cast<unsigned>(min);
309 bool HTMLInputElement::tooLong(StringView value, NeedsToCheckDirtyFlag check) const
311 if (!supportsMaxLength())
313 unsigned max = effectiveMaxLength();
314 if (check == CheckDirtyFlag) {
315 // Return false for the default value or a value set by a script even if
316 // it is longer than maxLength.
317 if (!hasDirtyValue() || !m_wasModifiedByUser)
320 // FIXME: The HTML specification says that the "number of characters" is measured using code-unit length.
321 return numGraphemeClusters(value) > max;
324 bool HTMLInputElement::rangeUnderflow() const
326 return willValidate() && m_inputType->rangeUnderflow(value());
329 bool HTMLInputElement::rangeOverflow() const
331 return willValidate() && m_inputType->rangeOverflow(value());
334 String HTMLInputElement::validationMessage() const
340 return customValidationMessage();
342 return m_inputType->validationMessage();
345 double HTMLInputElement::minimum() const
347 return m_inputType->minimum();
350 double HTMLInputElement::maximum() const
352 return m_inputType->maximum();
355 bool HTMLInputElement::stepMismatch() const
357 return willValidate() && m_inputType->stepMismatch(value());
360 bool HTMLInputElement::isValid() const
365 String value = this->value();
366 bool someError = m_inputType->typeMismatch() || m_inputType->stepMismatch(value) || m_inputType->rangeUnderflow(value) || m_inputType->rangeOverflow(value)
367 || tooShort(value, CheckDirtyFlag) || tooLong(value, CheckDirtyFlag) || m_inputType->patternMismatch(value) || m_inputType->valueMissing(value)
368 || m_inputType->hasBadInput() || customError();
372 bool HTMLInputElement::getAllowedValueStep(Decimal* step) const
374 return m_inputType->getAllowedValueStep(step);
377 StepRange HTMLInputElement::createStepRange(AnyStepHandling anyStepHandling) const
379 return m_inputType->createStepRange(anyStepHandling);
382 #if ENABLE(DATALIST_ELEMENT)
383 std::optional<Decimal> HTMLInputElement::findClosestTickMarkValue(const Decimal& value)
385 return m_inputType->findClosestTickMarkValue(value);
389 ExceptionOr<void> HTMLInputElement::stepUp(int n)
391 return m_inputType->stepUp(n);
394 ExceptionOr<void> HTMLInputElement::stepDown(int n)
396 return m_inputType->stepUp(-n);
399 void HTMLInputElement::blur()
404 void HTMLInputElement::defaultBlur()
406 HTMLTextFormControlElement::blur();
409 bool HTMLInputElement::hasCustomFocusLogic() const
411 return m_inputType->hasCustomFocusLogic();
414 bool HTMLInputElement::isKeyboardFocusable(KeyboardEvent& event) const
416 return m_inputType->isKeyboardFocusable(event);
419 bool HTMLInputElement::isMouseFocusable() const
421 return m_inputType->isMouseFocusable();
424 bool HTMLInputElement::isTextFormControlFocusable() const
426 return HTMLTextFormControlElement::isFocusable();
429 bool HTMLInputElement::isTextFormControlKeyboardFocusable(KeyboardEvent& event) const
431 return HTMLTextFormControlElement::isKeyboardFocusable(event);
434 bool HTMLInputElement::isTextFormControlMouseFocusable() const
436 return HTMLTextFormControlElement::isMouseFocusable();
439 void HTMLInputElement::updateFocusAppearance(SelectionRestorationMode restorationMode, SelectionRevealMode revealMode)
442 if (restorationMode == SelectionRestorationMode::SetDefault || !hasCachedSelection())
443 select(Element::defaultFocusTextStateChangeIntent());
445 restoreCachedSelection();
446 if (document().frame())
447 document().frame()->selection().revealSelection(revealMode);
449 HTMLTextFormControlElement::updateFocusAppearance(restorationMode, revealMode);
452 void HTMLInputElement::endEditing()
457 if (Frame* frame = document().frame())
458 frame->editor().textFieldDidEndEditing(this);
461 bool HTMLInputElement::shouldUseInputMethod()
463 return m_inputType->shouldUseInputMethod();
466 void HTMLInputElement::handleFocusEvent(Node* oldFocusedNode, FocusDirection direction)
468 m_inputType->handleFocusEvent(oldFocusedNode, direction);
471 void HTMLInputElement::handleBlurEvent()
473 m_inputType->handleBlurEvent();
476 void HTMLInputElement::setType(const AtomicString& type)
478 setAttributeWithoutSynchronization(typeAttr, type);
481 void HTMLInputElement::updateType()
484 auto newType = InputType::create(*this, attributeWithoutSynchronization(typeAttr));
486 if (m_inputType->formControlType() == newType->formControlType())
489 removeFromRadioButtonGroup();
491 bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
492 bool neededSuspensionCallback = needsSuspensionCallback();
493 bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
494 bool wasSuccessfulSubmitButtonCandidate = m_inputType->canBeSuccessfulSubmitButton();
496 m_inputType->destroyShadowSubtree();
498 m_inputType = WTFMove(newType);
499 m_inputType->createShadowSubtree();
500 updateInnerTextElementEditability();
502 setNeedsWillValidateCheck();
504 bool willStoreValue = m_inputType->storesValueSeparateFromAttribute();
506 if (didStoreValue && !willStoreValue && hasDirtyValue()) {
507 setAttributeWithoutSynchronization(valueAttr, m_valueIfDirty);
508 m_valueIfDirty = String();
510 if (!didStoreValue && willStoreValue)
511 m_valueIfDirty = sanitizeValue(attributeWithoutSynchronization(valueAttr));
513 updateValueIfNeeded();
515 setFormControlValueMatchesRenderer(false);
516 m_inputType->updateInnerTextValue();
518 m_wasModifiedByUser = false;
520 if (neededSuspensionCallback)
521 unregisterForSuspensionCallbackIfNeeded();
523 registerForSuspensionCallbackIfNeeded();
525 if (didRespectHeightAndWidth != m_inputType->shouldRespectHeightAndWidthAttributes()) {
526 ASSERT(elementData());
527 // FIXME: We don't have the old attribute values so we pretend that we didn't have the old values.
528 if (const Attribute* height = findAttributeByName(heightAttr))
529 attributeChanged(heightAttr, nullAtom(), height->value());
530 if (const Attribute* width = findAttributeByName(widthAttr))
531 attributeChanged(widthAttr, nullAtom(), width->value());
532 if (const Attribute* align = findAttributeByName(alignAttr))
533 attributeChanged(alignAttr, nullAtom(), align->value());
536 if (form() && wasSuccessfulSubmitButtonCandidate != m_inputType->canBeSuccessfulSubmitButton())
537 form()->resetDefaultButton();
539 runPostTypeUpdateTasks();
542 inline void HTMLInputElement::runPostTypeUpdateTasks()
545 #if ENABLE(TOUCH_EVENTS)
546 bool hasTouchEventHandler = m_inputType->hasTouchEventHandler();
547 if (hasTouchEventHandler != m_hasTouchEventHandler) {
548 if (hasTouchEventHandler)
549 document().didAddTouchEventHandler(*this);
551 document().didRemoveTouchEventHandler(*this);
552 m_hasTouchEventHandler = hasTouchEventHandler;
557 invalidateStyleAndRenderersForSubtree();
559 if (document().focusedElement() == this)
560 updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::Reveal);
562 setChangedSinceLastFormControlChangeEvent(false);
564 addToRadioButtonGroup();
569 void HTMLInputElement::subtreeHasChanged()
571 m_inputType->subtreeHasChanged();
572 // When typing in an input field, childrenChanged is not called, so we need to force the directionality check.
573 calculateAndAdjustDirectionality();
576 const AtomicString& HTMLInputElement::formControlType() const
578 return m_inputType->formControlType();
581 bool HTMLInputElement::shouldSaveAndRestoreFormControlState() const
583 if (!m_inputType->shouldSaveAndRestoreFormControlState())
585 return HTMLTextFormControlElement::shouldSaveAndRestoreFormControlState();
588 FormControlState HTMLInputElement::saveFormControlState() const
590 return m_inputType->saveFormControlState();
593 void HTMLInputElement::restoreFormControlState(const FormControlState& state)
595 m_inputType->restoreFormControlState(state);
596 m_stateRestored = true;
599 bool HTMLInputElement::canStartSelection() const
603 return HTMLTextFormControlElement::canStartSelection();
606 bool HTMLInputElement::canHaveSelection() const
608 return isTextField();
611 void HTMLInputElement::accessKeyAction(bool sendMouseEvents)
613 m_inputType->accessKeyAction(sendMouseEvents);
616 bool HTMLInputElement::isPresentationAttribute(const QualifiedName& name) const
618 if (name == vspaceAttr || name == hspaceAttr || name == alignAttr || name == widthAttr || name == heightAttr || (name == borderAttr && isImageButton()))
620 return HTMLTextFormControlElement::isPresentationAttribute(name);
623 void HTMLInputElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStyleProperties& style)
625 if (name == vspaceAttr) {
626 addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
627 addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
628 } else if (name == hspaceAttr) {
629 addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
630 addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
631 } else if (name == alignAttr) {
632 if (m_inputType->shouldRespectAlignAttribute())
633 applyAlignmentAttributeToStyle(value, style);
634 } else if (name == widthAttr) {
635 if (m_inputType->shouldRespectHeightAndWidthAttributes())
636 addHTMLLengthToStyle(style, CSSPropertyWidth, value);
637 } else if (name == heightAttr) {
638 if (m_inputType->shouldRespectHeightAndWidthAttributes())
639 addHTMLLengthToStyle(style, CSSPropertyHeight, value);
640 } else if (name == borderAttr && isImageButton())
641 applyBorderAttributeToStyle(value, style);
643 HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
646 inline void HTMLInputElement::initializeInputType()
648 ASSERT(m_parsingInProgress);
649 ASSERT(!m_inputType);
651 const AtomicString& type = attributeWithoutSynchronization(typeAttr);
653 m_inputType = InputType::createText(*this);
654 ensureUserAgentShadowRoot();
655 setNeedsWillValidateCheck();
660 m_inputType = InputType::create(*this, type);
661 ensureUserAgentShadowRoot();
662 setNeedsWillValidateCheck();
663 registerForSuspensionCallbackIfNeeded();
664 runPostTypeUpdateTasks();
667 void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
671 if (name == nameAttr) {
672 removeFromRadioButtonGroup();
674 addToRadioButtonGroup();
675 HTMLTextFormControlElement::parseAttribute(name, value);
676 } else if (name == autocompleteAttr) {
677 if (equalLettersIgnoringASCIICase(value, "off")) {
678 m_autocomplete = Off;
679 registerForSuspensionCallbackIfNeeded();
681 bool needsToUnregister = m_autocomplete == Off;
684 m_autocomplete = Uninitialized;
688 if (needsToUnregister)
689 unregisterForSuspensionCallbackIfNeeded();
691 } else if (name == typeAttr)
693 else if (name == valueAttr) {
694 // Changes to the value attribute may change whether or not this element has a default value.
695 // If this field is autocomplete=off that might affect the return value of needsSuspensionCallback.
696 if (m_autocomplete == Off) {
697 unregisterForSuspensionCallbackIfNeeded();
698 registerForSuspensionCallbackIfNeeded();
700 // We only need to setChanged if the form is looking at the default value right now.
701 if (!hasDirtyValue()) {
702 updatePlaceholderVisibility();
703 invalidateStyleForSubtree();
705 setFormControlValueMatchesRenderer(false);
707 m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress;
708 } else if (name == checkedAttr) {
709 if (m_inputType->isCheckable())
710 invalidateStyleForSubtree();
712 // Another radio button in the same group might be checked by state
713 // restore. We shouldn't call setChecked() even if this has the checked
714 // attribute. So, delay the setChecked() call until
715 // finishParsingChildren() is called if parsing is in progress.
716 if (!m_parsingInProgress && m_reflectsCheckedAttribute) {
717 setChecked(!value.isNull());
718 m_reflectsCheckedAttribute = true;
720 } else if (name == maxlengthAttr)
721 maxLengthAttributeChanged(value);
722 else if (name == minlengthAttr)
723 minLengthAttributeChanged(value);
724 else if (name == sizeAttr) {
725 unsigned oldSize = m_size;
726 m_size = limitToOnlyHTMLNonNegativeNumbersGreaterThanZero(value, defaultSize);
727 if (m_size != oldSize && renderer())
728 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
729 } else if (name == altAttr)
730 m_inputType->altAttributeChanged();
731 else if (name == srcAttr)
732 m_inputType->srcAttributeChanged();
733 else if (name == usemapAttr || name == accesskeyAttr) {
734 // FIXME: ignore for the moment
735 } else if (name == resultsAttr) {
736 m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
737 m_inputType->maxResultsAttributeChanged();
738 } else if (name == autosaveAttr) {
739 invalidateStyleForSubtree();
740 } else if (name == incrementalAttr) {
741 invalidateStyleForSubtree();
742 } else if (name == minAttr) {
743 m_inputType->minOrMaxAttributeChanged();
745 } else if (name == maxAttr) {
746 m_inputType->minOrMaxAttributeChanged();
748 } else if (name == multipleAttr) {
749 m_inputType->multipleAttributeChanged();
751 } else if (name == stepAttr) {
752 m_inputType->stepAttributeChanged();
754 } else if (name == patternAttr) {
756 } else if (name == precisionAttr) {
758 } else if (name == disabledAttr) {
759 HTMLTextFormControlElement::parseAttribute(name, value);
760 m_inputType->disabledAttributeChanged();
761 } else if (name == readonlyAttr) {
762 HTMLTextFormControlElement::parseAttribute(name, value);
763 m_inputType->readonlyAttributeChanged();
765 #if ENABLE(DATALIST_ELEMENT)
766 else if (name == listAttr) {
767 m_hasNonEmptyList = !value.isEmpty();
768 if (m_hasNonEmptyList) {
769 resetListAttributeTargetObserver();
770 listAttributeTargetChanged();
775 HTMLTextFormControlElement::parseAttribute(name, value);
777 m_inputType->attributeChanged(name);
780 void HTMLInputElement::parserDidSetAttributes()
782 ASSERT(m_parsingInProgress);
783 initializeInputType();
786 void HTMLInputElement::finishParsingChildren()
788 m_parsingInProgress = false;
790 HTMLTextFormControlElement::finishParsingChildren();
791 if (!m_stateRestored) {
792 bool checked = hasAttributeWithoutSynchronization(checkedAttr);
795 m_reflectsCheckedAttribute = true;
799 bool HTMLInputElement::rendererIsNeeded(const RenderStyle& style)
801 return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(style);
804 RenderPtr<RenderElement> HTMLInputElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
806 return m_inputType->createInputRenderer(WTFMove(style));
809 void HTMLInputElement::willAttachRenderers()
815 void HTMLInputElement::didAttachRenderers()
817 HTMLTextFormControlElement::didAttachRenderers();
819 m_inputType->attach();
821 if (document().focusedElement() == this) {
822 document().view()->queuePostLayoutCallback([protectedThis = makeRef(*this)] {
823 protectedThis->updateFocusAppearance(SelectionRestorationMode::Restore, SelectionRevealMode::Reveal);
828 void HTMLInputElement::didDetachRenderers()
830 setFormControlValueMatchesRenderer(false);
831 m_inputType->detach();
834 String HTMLInputElement::altText() const
836 // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
837 // also heavily discussed by Hixie on bugzilla
838 // note this is intentionally different to HTMLImageElement::altText()
839 String alt = attributeWithoutSynchronization(altAttr);
840 // fall back to title attribute
842 alt = attributeWithoutSynchronization(titleAttr);
844 alt = attributeWithoutSynchronization(valueAttr);
846 alt = inputElementAltText();
850 bool HTMLInputElement::isSuccessfulSubmitButton() const
852 // HTML spec says that buttons must have names to be considered successful.
853 // However, other browsers do not impose this constraint. So we do not.
854 return !isDisabledFormControl() && m_inputType->canBeSuccessfulSubmitButton();
857 bool HTMLInputElement::matchesDefaultPseudoClass() const
860 if (m_inputType->canBeSuccessfulSubmitButton())
861 return !isDisabledFormControl() && form() && form()->defaultButton() == this;
862 return m_inputType->isCheckable() && hasAttributeWithoutSynchronization(checkedAttr);
865 bool HTMLInputElement::isActivatedSubmit() const
867 return m_isActivatedSubmit;
870 void HTMLInputElement::setActivatedSubmit(bool flag)
872 m_isActivatedSubmit = flag;
875 bool HTMLInputElement::appendFormData(DOMFormData& formData, bool multipart)
877 return m_inputType->isFormDataAppendable() && m_inputType->appendFormData(formData, multipart);
880 void HTMLInputElement::reset()
882 if (m_inputType->storesValueSeparateFromAttribute())
885 setAutoFilled(false);
886 setChecked(hasAttributeWithoutSynchronization(checkedAttr));
887 m_reflectsCheckedAttribute = true;
890 bool HTMLInputElement::isTextField() const
892 return m_inputType->isTextField();
895 bool HTMLInputElement::isTextType() const
897 return m_inputType->isTextType();
900 void HTMLInputElement::setChecked(bool nowChecked, TextFieldEventBehavior eventBehavior)
902 if (checked() == nowChecked)
905 m_reflectsCheckedAttribute = false;
906 m_isChecked = nowChecked;
907 invalidateStyleForSubtree();
909 if (RadioButtonGroups* buttons = radioButtonGroups())
910 buttons->updateCheckedState(this);
911 if (renderer() && renderer()->style().hasAppearance())
912 renderer()->theme().stateChanged(*renderer(), ControlStates::CheckedState);
915 // Ideally we'd do this from the render tree (matching
916 // RenderTextView), but it's not possible to do it at the moment
917 // because of the way the code is structured.
919 if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
920 cache->checkedStateChanged(this);
923 // Only send a change event for items in the document (avoid firing during
924 // parsing) and don't send a change event for a radio button that's getting
925 // unchecked to match other browsers. DOM is not a useful standard for this
926 // because it says only to fire change events at "lose focus" time, which is
927 // definitely wrong in practice for these types of elements.
928 if (eventBehavior != DispatchNoEvent && isConnected() && m_inputType->shouldSendChangeEventAfterCheckedChanged()) {
929 setTextAsOfLastFormControlChangeEvent(String());
930 dispatchFormControlChangeEvent();
933 invalidateStyleForSubtree();
936 void HTMLInputElement::setIndeterminate(bool newValue)
938 if (indeterminate() == newValue)
941 m_isIndeterminate = newValue;
943 invalidateStyleForSubtree();
945 if (renderer() && renderer()->style().hasAppearance())
946 renderer()->theme().stateChanged(*renderer(), ControlStates::CheckedState);
949 unsigned HTMLInputElement::size() const
954 bool HTMLInputElement::sizeShouldIncludeDecoration(int& preferredSize) const
956 return m_inputType->sizeShouldIncludeDecoration(defaultSize, preferredSize);
959 float HTMLInputElement::decorationWidth() const
961 return m_inputType->decorationWidth();
964 void HTMLInputElement::copyNonAttributePropertiesFromElement(const Element& source)
966 auto& sourceElement = downcast<HTMLInputElement>(source);
968 m_valueIfDirty = sourceElement.m_valueIfDirty;
969 m_wasModifiedByUser = false;
970 setChecked(sourceElement.m_isChecked);
971 m_reflectsCheckedAttribute = sourceElement.m_reflectsCheckedAttribute;
972 m_isIndeterminate = sourceElement.m_isIndeterminate;
974 HTMLTextFormControlElement::copyNonAttributePropertiesFromElement(source);
977 setFormControlValueMatchesRenderer(false);
978 m_inputType->updateInnerTextValue();
981 String HTMLInputElement::value() const
984 if (m_inputType->getTypeSpecificValue(value))
987 value = m_valueIfDirty;
991 auto& valueString = attributeWithoutSynchronization(valueAttr);
992 value = sanitizeValue(valueString);
996 return m_inputType->fallbackValue();
999 String HTMLInputElement::valueWithDefault() const
1001 String value = this->value();
1002 if (!value.isNull())
1005 return m_inputType->defaultValue();
1008 void HTMLInputElement::setValueForUser(const String& value)
1010 // Call setValue and make it send a change event.
1011 setValue(value, DispatchChangeEvent);
1014 void HTMLInputElement::setEditingValue(const String& value)
1016 if (!renderer() || !isTextField())
1018 setInnerTextValue(value);
1019 subtreeHasChanged();
1021 unsigned max = value.length();
1023 setSelectionRange(max, max);
1025 cacheSelectionInResponseToSetValue(max);
1027 dispatchInputEvent();
1030 ExceptionOr<void> HTMLInputElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
1032 if (isFileUpload() && !value.isEmpty())
1033 return Exception { InvalidStateError };
1035 if (!m_inputType->canSetValue(value))
1038 Ref<HTMLInputElement> protectedThis(*this);
1039 EventQueueScope scope;
1040 String sanitizedValue = sanitizeValue(value);
1041 bool valueChanged = sanitizedValue != this->value();
1043 setLastChangeWasNotUserEdit();
1044 setFormControlValueMatchesRenderer(false);
1045 m_inputType->setValue(sanitizedValue, valueChanged, eventBehavior);
1049 void HTMLInputElement::setValueInternal(const String& sanitizedValue, TextFieldEventBehavior eventBehavior)
1051 m_valueIfDirty = sanitizedValue;
1052 m_wasModifiedByUser = eventBehavior != DispatchNoEvent;
1056 double HTMLInputElement::valueAsDate() const
1058 return m_inputType->valueAsDate();
1061 ExceptionOr<void> HTMLInputElement::setValueAsDate(double value)
1063 return m_inputType->setValueAsDate(value);
1066 double HTMLInputElement::valueAsNumber() const
1068 return m_inputType->valueAsDouble();
1071 ExceptionOr<void> HTMLInputElement::setValueAsNumber(double newValue, TextFieldEventBehavior eventBehavior)
1073 if (!std::isfinite(newValue))
1074 return Exception { NotSupportedError };
1075 return m_inputType->setValueAsDouble(newValue, eventBehavior);
1078 void HTMLInputElement::setValueFromRenderer(const String& value)
1080 // File upload controls will never use this.
1081 ASSERT(!isFileUpload());
1083 // Renderer and our event handler are responsible for sanitizing values.
1084 // Input types that support the selection API do *not* sanitize their
1085 // user input in order to retain parity between what's in the model and
1086 // what's on the screen.
1087 ASSERT(m_inputType->supportsSelectionAPI() || value == sanitizeValue(value) || sanitizeValue(value).isEmpty());
1089 // Workaround for bug where trailing \n is included in the result of textContent.
1090 // The assert macro above may also be simplified by removing the expression
1091 // that calls isEmpty.
1092 // http://bugs.webkit.org/show_bug.cgi?id=9661
1093 m_valueIfDirty = value == "\n" ? emptyString() : value;
1095 setFormControlValueMatchesRenderer(true);
1096 m_wasModifiedByUser = true;
1098 // Input event is fired by the Node::defaultEventHandler for editable controls.
1100 dispatchInputEvent();
1104 // Clear auto fill flag (and yellow background) on user edit.
1105 setAutoFilled(false);
1108 void HTMLInputElement::willDispatchEvent(Event& event, InputElementClickState& state)
1110 if (event.type() == eventNames().textInputEvent && m_inputType->shouldSubmitImplicitly(event))
1111 event.stopPropagation();
1112 if (event.type() == eventNames().clickEvent && is<MouseEvent>(event) && downcast<MouseEvent>(event).button() == LeftButton) {
1113 m_inputType->willDispatchClick(state);
1114 state.stateful = true;
1118 void HTMLInputElement::didDispatchClickEvent(Event& event, const InputElementClickState& state)
1120 m_inputType->didDispatchClick(&event, state);
1123 void HTMLInputElement::didBlur()
1125 // We need to update style here, rather than in InputType itself, since style recomputation may fire events
1126 // that could change the input's type.
1127 document().updateStyleIfNeeded();
1128 m_inputType->elementDidBlur();
1131 void HTMLInputElement::defaultEventHandler(Event& event)
1133 if (is<MouseEvent>(event) && event.type() == eventNames().clickEvent && downcast<MouseEvent>(event).button() == LeftButton) {
1134 m_inputType->handleClickEvent(downcast<MouseEvent>(event));
1135 if (event.defaultHandled())
1139 #if ENABLE(TOUCH_EVENTS)
1140 if (is<TouchEvent>(event)) {
1141 m_inputType->handleTouchEvent(downcast<TouchEvent>(event));
1142 if (event.defaultHandled())
1147 if (is<KeyboardEvent>(event) && event.type() == eventNames().keydownEvent) {
1148 m_inputType->handleKeydownEvent(downcast<KeyboardEvent>(event));
1149 if (event.defaultHandled())
1153 // Call the base event handler before any of our own event handling for almost all events in text fields.
1154 // Makes editing keyboard handling take precedence over the keydown and keypress handling in this function.
1155 bool callBaseClassEarly = isTextField() && (event.type() == eventNames().keydownEvent || event.type() == eventNames().keypressEvent);
1156 if (callBaseClassEarly) {
1157 HTMLTextFormControlElement::defaultEventHandler(event);
1158 if (event.defaultHandled())
1162 // DOMActivate events cause the input to be "activated" - in the case of image and submit inputs, this means
1163 // actually submitting the form. For reset inputs, the form is reset. These events are sent when the user clicks
1164 // on the element, or presses enter while it is the active element. JavaScript code wishing to activate the element
1165 // must dispatch a DOMActivate event - a click event will not do the job.
1166 if (event.type() == eventNames().DOMActivateEvent) {
1167 m_inputType->handleDOMActivateEvent(event);
1168 if (event.defaultHandled())
1172 // Use key press event here since sending simulated mouse events
1173 // on key down blocks the proper sending of the key press event.
1174 if (is<KeyboardEvent>(event)) {
1175 KeyboardEvent& keyboardEvent = downcast<KeyboardEvent>(event);
1176 if (keyboardEvent.type() == eventNames().keypressEvent) {
1177 m_inputType->handleKeypressEvent(keyboardEvent);
1178 if (keyboardEvent.defaultHandled())
1180 } else if (keyboardEvent.type() == eventNames().keyupEvent) {
1181 m_inputType->handleKeyupEvent(keyboardEvent);
1182 if (keyboardEvent.defaultHandled())
1187 if (m_inputType->shouldSubmitImplicitly(event)) {
1188 if (isSearchField()) {
1192 // Form submission finishes editing, just as loss of focus does.
1193 // If there was a change, send the event now.
1194 if (wasChangedSinceLastFormControlChangeEvent())
1195 dispatchFormControlChangeEvent();
1197 // Form may never have been present, or may have been destroyed by code responding to the change event.
1198 if (auto* formElement = form())
1199 formElement->submitImplicitly(event, canTriggerImplicitSubmission());
1201 event.setDefaultHandled();
1205 if (is<BeforeTextInsertedEvent>(event))
1206 m_inputType->handleBeforeTextInsertedEvent(downcast<BeforeTextInsertedEvent>(event));
1208 if (is<MouseEvent>(event) && event.type() == eventNames().mousedownEvent) {
1209 m_inputType->handleMouseDownEvent(downcast<MouseEvent>(event));
1210 if (event.defaultHandled())
1214 m_inputType->forwardEvent(event);
1216 if (!callBaseClassEarly && !event.defaultHandled())
1217 HTMLTextFormControlElement::defaultEventHandler(event);
1220 bool HTMLInputElement::willRespondToMouseClickEvents()
1222 if (!isDisabledFormControl())
1225 return HTMLTextFormControlElement::willRespondToMouseClickEvents();
1228 bool HTMLInputElement::isURLAttribute(const Attribute& attribute) const
1230 return attribute.name() == srcAttr || attribute.name() == formactionAttr || HTMLTextFormControlElement::isURLAttribute(attribute);
1233 String HTMLInputElement::defaultValue() const
1235 return attributeWithoutSynchronization(valueAttr);
1238 void HTMLInputElement::setDefaultValue(const String &value)
1240 setAttributeWithoutSynchronization(valueAttr, value);
1243 static inline bool isRFC2616TokenCharacter(UChar ch)
1245 return isASCII(ch) && ch > ' ' && ch != '"' && ch != '(' && ch != ')' && ch != ',' && ch != '/' && (ch < ':' || ch > '@') && (ch < '[' || ch > ']') && ch != '{' && ch != '}' && ch != 0x7f;
1248 static bool isValidMIMEType(const String& type)
1250 size_t slashPosition = type.find('/');
1251 if (slashPosition == notFound || !slashPosition || slashPosition == type.length() - 1)
1253 for (size_t i = 0; i < type.length(); ++i) {
1254 if (!isRFC2616TokenCharacter(type[i]) && i != slashPosition)
1260 static bool isValidFileExtension(const String& type)
1262 if (type.length() < 2)
1264 return type[0] == '.';
1267 static Vector<String> parseAcceptAttribute(const String& acceptString, bool (*predicate)(const String&))
1269 Vector<String> types;
1270 if (acceptString.isEmpty())
1273 Vector<String> splitTypes;
1274 acceptString.split(',', false, splitTypes);
1275 for (auto& splitType : splitTypes) {
1276 String trimmedType = stripLeadingAndTrailingHTMLSpaces(splitType);
1277 if (trimmedType.isEmpty())
1279 if (!predicate(trimmedType))
1281 types.append(trimmedType.convertToASCIILowercase());
1287 Vector<String> HTMLInputElement::acceptMIMETypes()
1289 return parseAcceptAttribute(attributeWithoutSynchronization(acceptAttr), isValidMIMEType);
1292 Vector<String> HTMLInputElement::acceptFileExtensions()
1294 return parseAcceptAttribute(attributeWithoutSynchronization(acceptAttr), isValidFileExtension);
1297 String HTMLInputElement::accept() const
1299 return attributeWithoutSynchronization(acceptAttr);
1302 String HTMLInputElement::alt() const
1304 return attributeWithoutSynchronization(altAttr);
1307 unsigned HTMLInputElement::effectiveMaxLength() const
1309 // The number -1 represents no maximum at all; conveniently it becomes a super-large value when converted to unsigned.
1310 return std::min<unsigned>(maxLength(), maxEffectiveLength);
1313 bool HTMLInputElement::multiple() const
1315 return hasAttributeWithoutSynchronization(multipleAttr);
1318 ExceptionOr<void> HTMLInputElement::setSize(unsigned size)
1321 return Exception { IndexSizeError };
1322 setUnsignedIntegralAttribute(sizeAttr, limitToOnlyHTMLNonNegativeNumbersGreaterThanZero(size, defaultSize));
1326 URL HTMLInputElement::src() const
1328 return document().completeURL(attributeWithoutSynchronization(srcAttr));
1331 void HTMLInputElement::setAutoFilled(bool autoFilled)
1333 if (autoFilled == m_isAutoFilled)
1336 m_isAutoFilled = autoFilled;
1337 invalidateStyleForSubtree();
1340 void HTMLInputElement::setShowAutoFillButton(AutoFillButtonType autoFillButtonType)
1342 if (static_cast<uint8_t>(autoFillButtonType) == m_autoFillButtonType)
1345 m_autoFillButtonType = static_cast<uint8_t>(autoFillButtonType);
1346 m_inputType->updateAutoFillButton();
1349 FileList* HTMLInputElement::files()
1351 return m_inputType->files();
1354 void HTMLInputElement::setFiles(RefPtr<FileList>&& files)
1356 m_inputType->setFiles(WTFMove(files));
1359 #if ENABLE(DRAG_SUPPORT)
1360 bool HTMLInputElement::receiveDroppedFiles(const DragData& dragData)
1362 return m_inputType->receiveDroppedFiles(dragData);
1366 Icon* HTMLInputElement::icon() const
1368 return m_inputType->icon();
1371 String HTMLInputElement::displayString() const
1373 return m_inputType->displayString();
1376 bool HTMLInputElement::canReceiveDroppedFiles() const
1378 return m_canReceiveDroppedFiles;
1381 void HTMLInputElement::setCanReceiveDroppedFiles(bool canReceiveDroppedFiles)
1383 if (m_canReceiveDroppedFiles == canReceiveDroppedFiles)
1385 m_canReceiveDroppedFiles = canReceiveDroppedFiles;
1387 renderer()->updateFromElement();
1390 String HTMLInputElement::visibleValue() const
1392 return m_inputType->visibleValue();
1395 String HTMLInputElement::sanitizeValue(const String& proposedValue) const
1397 if (proposedValue.isNull())
1398 return proposedValue;
1399 return m_inputType->sanitizeValue(proposedValue);
1402 String HTMLInputElement::localizeValue(const String& proposedValue) const
1404 if (proposedValue.isNull())
1405 return proposedValue;
1406 return m_inputType->localizeValue(proposedValue);
1409 bool HTMLInputElement::isInRange() const
1411 return willValidate() && m_inputType->isInRange(value());
1414 bool HTMLInputElement::isOutOfRange() const
1416 return willValidate() && m_inputType->isOutOfRange(value());
1419 bool HTMLInputElement::needsSuspensionCallback()
1421 if (m_inputType->shouldResetOnDocumentActivation())
1424 // Sensitive input elements are marked with autocomplete=off, and we want to wipe them out
1425 // when going back; returning true here arranges for us to call reset at the time
1426 // the page is restored. Non-empty textual default values indicate that the field
1427 // is not really sensitive -- there's no default value for an account number --
1428 // and we would see unexpected results if we reset to something other than blank.
1429 bool isSensitive = m_autocomplete == Off && !(m_inputType->isTextType() && !defaultValue().isEmpty());
1434 void HTMLInputElement::registerForSuspensionCallbackIfNeeded()
1436 if (needsSuspensionCallback())
1437 document().registerForDocumentSuspensionCallbacks(this);
1440 void HTMLInputElement::unregisterForSuspensionCallbackIfNeeded()
1442 if (!needsSuspensionCallback())
1443 document().unregisterForDocumentSuspensionCallbacks(this);
1446 bool HTMLInputElement::isRequiredFormControl() const
1448 return m_inputType->supportsRequired() && isRequired();
1451 bool HTMLInputElement::matchesReadWritePseudoClass() const
1453 return m_inputType->supportsReadOnly() && !isDisabledOrReadOnly();
1456 void HTMLInputElement::addSearchResult()
1458 m_inputType->addSearchResult();
1461 void HTMLInputElement::onSearch()
1463 // The type of the input element could have changed during event handling. If we are no longer
1464 // a search field, don't try to do search things.
1465 if (!isSearchField())
1469 downcast<SearchInputType>(*m_inputType.get()).stopSearchEventTimer();
1470 dispatchEvent(Event::create(eventNames().searchEvent, true, false));
1473 void HTMLInputElement::resumeFromDocumentSuspension()
1475 ASSERT(needsSuspensionCallback());
1477 #if ENABLE(INPUT_TYPE_COLOR)
1478 // <input type=color> uses prepareForDocumentSuspension to detach the color picker UI,
1479 // so it should not be reset when being loaded from page cache.
1480 if (isColorControl())
1482 #endif // ENABLE(INPUT_TYPE_COLOR)
1486 #if ENABLE(INPUT_TYPE_COLOR)
1487 void HTMLInputElement::prepareForDocumentSuspension()
1489 if (!isColorControl())
1491 m_inputType->detach();
1493 #endif // ENABLE(INPUT_TYPE_COLOR)
1496 void HTMLInputElement::willChangeForm()
1498 removeFromRadioButtonGroup();
1499 HTMLTextFormControlElement::willChangeForm();
1502 void HTMLInputElement::didChangeForm()
1504 HTMLTextFormControlElement::didChangeForm();
1505 addToRadioButtonGroup();
1508 Node::InsertionNotificationRequest HTMLInputElement::insertedInto(ContainerNode& insertionPoint)
1510 HTMLTextFormControlElement::insertedInto(insertionPoint);
1511 #if ENABLE(DATALIST_ELEMENT)
1512 resetListAttributeTargetObserver();
1514 return InsertionShouldCallFinishedInsertingSubtree;
1517 void HTMLInputElement::finishedInsertingSubtree()
1519 HTMLTextFormControlElement::finishedInsertingSubtree();
1520 if (isConnected() && !form())
1521 addToRadioButtonGroup();
1524 void HTMLInputElement::removedFrom(ContainerNode& insertionPoint)
1526 if (insertionPoint.isConnected() && !form())
1527 removeFromRadioButtonGroup();
1528 HTMLTextFormControlElement::removedFrom(insertionPoint);
1529 ASSERT(!isConnected());
1530 #if ENABLE(DATALIST_ELEMENT)
1531 resetListAttributeTargetObserver();
1535 void HTMLInputElement::didMoveToNewDocument(Document& oldDocument, Document& newDocument)
1538 imageLoader()->elementDidMoveToNewDocument();
1540 // Always unregister for cache callbacks when leaving a document, even if we would otherwise like to be registered
1541 if (needsSuspensionCallback()) {
1542 oldDocument.unregisterForDocumentSuspensionCallbacks(this);
1543 newDocument.registerForDocumentSuspensionCallbacks(this);
1545 if (isRadioButton())
1546 oldDocument.formController().radioButtonGroups().removeButton(this);
1547 #if ENABLE(TOUCH_EVENTS)
1548 if (m_hasTouchEventHandler) {
1549 oldDocument.didRemoveEventTargetNode(*this);
1550 newDocument.didAddTouchEventHandler(*this);
1554 HTMLTextFormControlElement::didMoveToNewDocument(oldDocument, newDocument);
1557 void HTMLInputElement::addSubresourceAttributeURLs(ListHashSet<URL>& urls) const
1559 HTMLTextFormControlElement::addSubresourceAttributeURLs(urls);
1561 addSubresourceURL(urls, src());
1564 bool HTMLInputElement::computeWillValidate() const
1566 return m_inputType->supportsValidation() && HTMLTextFormControlElement::computeWillValidate();
1569 void HTMLInputElement::requiredAttributeChanged()
1571 HTMLTextFormControlElement::requiredAttributeChanged();
1572 if (RadioButtonGroups* buttons = radioButtonGroups())
1573 buttons->requiredAttributeChanged(this);
1574 m_inputType->requiredAttributeChanged();
1577 Color HTMLInputElement::valueAsColor() const
1579 return m_inputType->valueAsColor();
1582 void HTMLInputElement::selectColor(const Color& color)
1584 m_inputType->selectColor(color);
1587 #if ENABLE(DATALIST_ELEMENT)
1588 HTMLElement* HTMLInputElement::list() const
1593 HTMLDataListElement* HTMLInputElement::dataList() const
1595 if (!m_hasNonEmptyList)
1598 if (!m_inputType->shouldRespectListAttribute())
1601 Element* element = treeScope().getElementById(attributeWithoutSynchronization(listAttr));
1602 if (!is<HTMLDataListElement>(element))
1605 return downcast<HTMLDataListElement>(element);
1608 void HTMLInputElement::resetListAttributeTargetObserver()
1611 m_listAttributeTargetObserver = std::make_unique<ListAttributeTargetObserver>(attributeWithoutSynchronization(listAttr), this);
1613 m_listAttributeTargetObserver = nullptr;
1616 void HTMLInputElement::listAttributeTargetChanged()
1618 m_inputType->listAttributeTargetChanged();
1620 #endif // ENABLE(DATALIST_ELEMENT)
1622 bool HTMLInputElement::isSteppable() const
1624 return m_inputType->isSteppable();
1628 DateComponents::Type HTMLInputElement::dateType() const
1630 return m_inputType->dateType();
1634 bool HTMLInputElement::isTextButton() const
1636 return m_inputType->isTextButton();
1639 bool HTMLInputElement::isRadioButton() const
1641 return m_inputType->isRadioButton();
1644 bool HTMLInputElement::isSearchField() const
1646 return m_inputType->isSearchField();
1649 bool HTMLInputElement::isInputTypeHidden() const
1651 return m_inputType->isHiddenType();
1654 bool HTMLInputElement::isPasswordField() const
1656 return m_inputType->isPasswordField();
1659 bool HTMLInputElement::isCheckbox() const
1661 return m_inputType->isCheckbox();
1664 bool HTMLInputElement::isRangeControl() const
1666 return m_inputType->isRangeControl();
1669 #if ENABLE(INPUT_TYPE_COLOR)
1670 bool HTMLInputElement::isColorControl() const
1672 return m_inputType->isColorControl();
1676 bool HTMLInputElement::isText() const
1678 return m_inputType->isTextType();
1681 bool HTMLInputElement::isEmailField() const
1683 return m_inputType->isEmailField();
1686 bool HTMLInputElement::isFileUpload() const
1688 return m_inputType->isFileUpload();
1691 bool HTMLInputElement::isImageButton() const
1693 return m_inputType->isImageButton();
1696 bool HTMLInputElement::isNumberField() const
1698 return m_inputType->isNumberField();
1701 bool HTMLInputElement::isSubmitButton() const
1703 return m_inputType->isSubmitButton();
1706 bool HTMLInputElement::isTelephoneField() const
1708 return m_inputType->isTelephoneField();
1711 bool HTMLInputElement::isURLField() const
1713 return m_inputType->isURLField();
1716 bool HTMLInputElement::isDateField() const
1718 return m_inputType->isDateField();
1721 bool HTMLInputElement::isDateTimeField() const
1723 return m_inputType->isDateTimeField();
1726 bool HTMLInputElement::isDateTimeLocalField() const
1728 return m_inputType->isDateTimeLocalField();
1731 bool HTMLInputElement::isMonthField() const
1733 return m_inputType->isMonthField();
1736 bool HTMLInputElement::isTimeField() const
1738 return m_inputType->isTimeField();
1741 bool HTMLInputElement::isWeekField() const
1743 return m_inputType->isWeekField();
1746 bool HTMLInputElement::isEnumeratable() const
1748 return m_inputType->isEnumeratable();
1751 bool HTMLInputElement::supportLabels() const
1753 return m_inputType->supportLabels();
1756 bool HTMLInputElement::shouldAppearChecked() const
1758 return checked() && m_inputType->isCheckable();
1761 bool HTMLInputElement::supportsPlaceholder() const
1763 return m_inputType->supportsPlaceholder();
1766 void HTMLInputElement::updatePlaceholderText()
1768 return m_inputType->updatePlaceholderText();
1771 bool HTMLInputElement::isEmptyValue() const
1773 return m_inputType->isEmptyValue();
1776 void HTMLInputElement::maxLengthAttributeChanged(const AtomicString& newValue)
1778 unsigned oldEffectiveMaxLength = effectiveMaxLength();
1779 internalSetMaxLength(parseHTMLNonNegativeInteger(newValue).valueOr(-1));
1780 if (oldEffectiveMaxLength != effectiveMaxLength())
1781 updateValueIfNeeded();
1783 // FIXME: Do we really need to do this if the effective maxLength has not changed?
1784 invalidateStyleForSubtree();
1788 void HTMLInputElement::minLengthAttributeChanged(const AtomicString& newValue)
1790 int oldMinLength = minLength();
1791 internalSetMinLength(parseHTMLNonNegativeInteger(newValue).valueOr(-1));
1792 if (oldMinLength != minLength())
1793 updateValueIfNeeded();
1795 // FIXME: Do we really need to do this if the effective minLength has not changed?
1796 invalidateStyleForSubtree();
1800 void HTMLInputElement::updateValueIfNeeded()
1802 String newValue = sanitizeValue(m_valueIfDirty);
1803 ASSERT(!m_valueIfDirty.isNull() || newValue.isNull());
1804 if (newValue != m_valueIfDirty)
1808 String HTMLInputElement::defaultToolTip() const
1810 return m_inputType->defaultToolTip();
1813 bool HTMLInputElement::matchesIndeterminatePseudoClass() const
1815 // For input elements, matchesIndeterminatePseudoClass()
1816 // is not equivalent to shouldAppearIndeterminate() because of radio button.
1818 // A group of radio button without any checked button is indeterminate
1819 // for the :indeterminate selector. On the other hand, RenderTheme
1820 // currently only supports single element being indeterminate.
1821 // Because of this, radio is indetermindate for CSS but not for render theme.
1822 return m_inputType->matchesIndeterminatePseudoClass();
1825 bool HTMLInputElement::shouldAppearIndeterminate() const
1827 return m_inputType->shouldAppearIndeterminate();
1830 #if ENABLE(MEDIA_CAPTURE)
1831 MediaCaptureType HTMLInputElement::mediaCaptureType() const
1833 if (!isFileUpload())
1834 return MediaCaptureTypeNone;
1836 auto& captureAttribute = attributeWithoutSynchronization(captureAttr);
1837 if (captureAttribute.isNull())
1838 return MediaCaptureTypeNone;
1840 if (equalLettersIgnoringASCIICase(captureAttribute, "user"))
1841 return MediaCaptureTypeUser;
1843 return MediaCaptureTypeEnvironment;
1847 bool HTMLInputElement::isInRequiredRadioButtonGroup()
1849 ASSERT(isRadioButton());
1850 if (RadioButtonGroups* buttons = radioButtonGroups())
1851 return buttons->isInRequiredGroup(this);
1855 Vector<HTMLInputElement*> HTMLInputElement::radioButtonGroup() const
1857 RadioButtonGroups* buttons = radioButtonGroups();
1860 return buttons->groupMembers(*this);
1863 HTMLInputElement* HTMLInputElement::checkedRadioButtonForGroup() const
1865 if (RadioButtonGroups* buttons = radioButtonGroups())
1866 return buttons->checkedButtonForGroup(name());
1870 RadioButtonGroups* HTMLInputElement::radioButtonGroups() const
1872 if (!isRadioButton())
1874 if (auto* formElement = form())
1875 return &formElement->radioButtonGroups();
1877 return &document().formController().radioButtonGroups();
1881 inline void HTMLInputElement::addToRadioButtonGroup()
1883 if (RadioButtonGroups* buttons = radioButtonGroups())
1884 buttons->addButton(this);
1887 inline void HTMLInputElement::removeFromRadioButtonGroup()
1889 if (RadioButtonGroups* buttons = radioButtonGroups())
1890 buttons->removeButton(this);
1893 unsigned HTMLInputElement::height() const
1895 return m_inputType->height();
1898 unsigned HTMLInputElement::width() const
1900 return m_inputType->width();
1903 void HTMLInputElement::setHeight(unsigned height)
1905 setUnsignedIntegralAttribute(heightAttr, height);
1908 void HTMLInputElement::setWidth(unsigned width)
1910 setUnsignedIntegralAttribute(widthAttr, width);
1913 #if ENABLE(DATALIST_ELEMENT)
1914 ListAttributeTargetObserver::ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement* element)
1915 : IdTargetObserver(element->treeScope().idTargetObserverRegistry(), id)
1916 , m_element(element)
1920 void ListAttributeTargetObserver::idTargetChanged()
1922 m_element->listAttributeTargetChanged();
1926 ExceptionOr<void> HTMLInputElement::setRangeText(const String& replacement)
1928 if (!m_inputType->supportsSelectionAPI())
1929 return Exception { InvalidStateError };
1931 return HTMLTextFormControlElement::setRangeText(replacement);
1934 ExceptionOr<void> HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode)
1936 if (!m_inputType->supportsSelectionAPI())
1937 return Exception { InvalidStateError };
1939 return HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode);
1942 bool HTMLInputElement::shouldTruncateText(const RenderStyle& style) const
1946 return document().focusedElement() != this && style.textOverflow() == TextOverflowEllipsis;
1949 ExceptionOr<int> HTMLInputElement::selectionStartForBindings() const
1951 if (!canHaveSelection())
1952 return Exception { TypeError };
1954 return selectionStart();
1957 ExceptionOr<void> HTMLInputElement::setSelectionStartForBindings(int start)
1959 if (!canHaveSelection())
1960 return Exception { TypeError };
1962 setSelectionStart(start);
1966 ExceptionOr<int> HTMLInputElement::selectionEndForBindings() const
1968 if (!canHaveSelection())
1969 return Exception { TypeError };
1971 return selectionEnd();
1974 ExceptionOr<void> HTMLInputElement::setSelectionEndForBindings(int end)
1976 if (!canHaveSelection())
1977 return Exception { TypeError };
1979 setSelectionEnd(end);
1983 ExceptionOr<String> HTMLInputElement::selectionDirectionForBindings() const
1985 if (!canHaveSelection())
1986 return Exception { TypeError };
1988 return String { selectionDirection() };
1991 ExceptionOr<void> HTMLInputElement::setSelectionDirectionForBindings(const String& direction)
1993 if (!canHaveSelection())
1994 return Exception { TypeError };
1996 setSelectionDirection(direction);
2000 ExceptionOr<void> HTMLInputElement::setSelectionRangeForBindings(int start, int end, const String& direction)
2002 if (!canHaveSelection())
2003 return Exception { TypeError };
2005 setSelectionRange(start, end, direction);
2009 RenderStyle HTMLInputElement::createInnerTextStyle(const RenderStyle& style) const
2011 auto textBlockStyle = RenderStyle::create();
2012 textBlockStyle.inheritFrom(style);
2013 adjustInnerTextStyle(style, textBlockStyle);
2015 textBlockStyle.setWhiteSpace(PRE);
2016 textBlockStyle.setOverflowWrap(NormalOverflowWrap);
2017 textBlockStyle.setOverflowX(OHIDDEN);
2018 textBlockStyle.setOverflowY(OHIDDEN);
2019 textBlockStyle.setTextOverflow(shouldTruncateText(style) ? TextOverflowEllipsis : TextOverflowClip);
2021 // Do not allow line-height to be smaller than our default.
2022 if (textBlockStyle.fontMetrics().lineSpacing() > style.computedLineHeight())
2023 textBlockStyle.setLineHeight(RenderStyle::initialLineHeight());
2025 textBlockStyle.setDisplay(BLOCK);
2027 return textBlockStyle;
2030 #if ENABLE(DATE_AND_TIME_INPUT_TYPES)
2031 bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
2033 if (!document().view())
2036 parameters.type = type();
2037 parameters.minimum = minimum();
2038 parameters.maximum = maximum();
2039 parameters.required = isRequired();
2041 if (!document().settings().langAttributeAwareFormControlUIEnabled())
2042 parameters.locale = defaultLanguage();
2044 AtomicString computedLocale = computeInheritedLanguage();
2045 parameters.locale = computedLocale.isEmpty() ? AtomicString(defaultLanguage()) : computedLocale;
2048 StepRange stepRange = createStepRange(RejectAny);
2049 if (stepRange.hasStep()) {
2050 parameters.step = stepRange.step().toDouble();
2051 parameters.stepBase = stepRange.stepBase().toDouble();
2053 parameters.step = 1.0;
2054 parameters.stepBase = 0;
2057 if (RenderElement* renderer = this->renderer())
2058 parameters.anchorRectInRootView = document().view()->contentsToRootView(renderer->absoluteBoundingBoxRect());
2060 parameters.anchorRectInRootView = IntRect();
2061 parameters.currentValue = value();
2062 parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
2063 #if ENABLE(DATALIST_ELEMENT)
2064 if (HTMLDataListElement* dataList = this->dataList()) {
2065 Ref<HTMLCollection> options = dataList->options();
2066 for (unsigned i = 0; HTMLOptionElement* option = downcast<HTMLOptionElement>(options->item(i)); ++i) {
2067 if (!isValidValue(option->value()))
2069 parameters.suggestionValues.append(sanitizeValue(option->value()));
2070 parameters.localizedSuggestionValues.append(localizeValue(option->value()));
2071 parameters.suggestionLabels.append(option->value() == option->label() ? String() : option->label());
2079 void HTMLInputElement::capsLockStateMayHaveChanged()
2081 m_inputType->capsLockStateMayHaveChanged();