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, 2005, 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
6 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * Copyright (C) 2007 Samuel Weinig (sam@webkit.org)
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 #include "core/html/HTMLTextAreaElement.h"
29 #include "bindings/core/v8/ExceptionState.h"
30 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
31 #include "core/CSSValueKeywords.h"
32 #include "core/HTMLNames.h"
33 #include "core/dom/Document.h"
34 #include "core/dom/ExceptionCode.h"
35 #include "core/dom/Text.h"
36 #include "core/dom/shadow/ShadowRoot.h"
37 #include "core/editing/FrameSelection.h"
38 #include "core/editing/SpellChecker.h"
39 #include "core/editing/TextIterator.h"
40 #include "core/events/BeforeTextInsertedEvent.h"
41 #include "core/events/Event.h"
42 #include "core/frame/FrameHost.h"
43 #include "core/frame/LocalFrame.h"
44 #include "core/html/FormDataList.h"
45 #include "core/html/forms/FormController.h"
46 #include "core/html/parser/HTMLParserIdioms.h"
47 #include "core/html/shadow/ShadowElementNames.h"
48 #include "core/html/shadow/TextControlInnerElements.h"
49 #include "core/page/Chrome.h"
50 #include "core/page/ChromeClient.h"
51 #include "core/rendering/RenderTextControlMultiLine.h"
52 #include "platform/text/PlatformLocale.h"
53 #include "wtf/StdLibExtras.h"
54 #include "wtf/text/StringBuilder.h"
58 using namespace HTMLNames;
60 static const int defaultRows = 2;
61 static const int defaultCols = 20;
63 // On submission, LF characters are converted into CRLF.
64 // This function returns number of characters considering this.
65 static unsigned numberOfLineBreaks(const String& text)
67 unsigned length = text.length();
69 for (unsigned i = 0; i < length; i++) {
76 static inline unsigned computeLengthForSubmission(const String& text)
78 return text.length() + numberOfLineBreaks(text);
81 HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* form)
82 : HTMLTextFormControlElement(textareaTag, document, form)
87 , m_valueIsUpToDate(true)
91 PassRefPtrWillBeRawPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
93 RefPtrWillBeRawPtr<HTMLTextAreaElement> textArea = adoptRefWillBeNoop(new HTMLTextAreaElement(document, form));
94 textArea->ensureUserAgentShadowRoot();
95 return textArea.release();
98 void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
100 root.appendChild(TextControlInnerEditorElement::create(document()));
103 const AtomicString& HTMLTextAreaElement::formControlType() const
105 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea", AtomicString::ConstructFromLiteral));
109 FormControlState HTMLTextAreaElement::saveFormControlState() const
111 return m_isDirty ? FormControlState(value()) : FormControlState();
114 void HTMLTextAreaElement::restoreFormControlState(const FormControlState& state)
119 void HTMLTextAreaElement::childrenChanged(const ChildrenChange& change)
121 HTMLElement::childrenChanged(change);
122 setLastChangeWasNotUserEdit();
124 setInnerEditorValue(value());
126 setNonDirtyValue(defaultValue());
129 bool HTMLTextAreaElement::isPresentationAttribute(const QualifiedName& name) const
131 if (name == alignAttr) {
132 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
133 // See http://bugs.webkit.org/show_bug.cgi?id=7075
137 if (name == wrapAttr)
139 return HTMLTextFormControlElement::isPresentationAttribute(name);
142 void HTMLTextAreaElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
144 if (name == wrapAttr) {
145 if (shouldWrapText()) {
146 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
147 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
149 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
150 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
153 HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
156 void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
158 if (name == rowsAttr) {
159 int rows = value.toInt();
162 if (m_rows != rows) {
165 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
167 } else if (name == colsAttr) {
168 int cols = value.toInt();
171 if (m_cols != cols) {
174 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
176 } else if (name == wrapAttr) {
177 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
178 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
180 if (equalIgnoringCase(value, "physical") || equalIgnoringCase(value, "hard") || equalIgnoringCase(value, "on"))
182 else if (equalIgnoringCase(value, "off"))
186 if (wrap != m_wrap) {
189 renderer()->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
191 } else if (name == accesskeyAttr) {
192 // ignore for the moment
193 } else if (name == maxlengthAttr) {
194 setNeedsValidityCheck();
195 } else if (name == minlengthAttr) {
196 setNeedsValidityCheck();
198 HTMLTextFormControlElement::parseAttribute(name, value);
201 RenderObject* HTMLTextAreaElement::createRenderer(RenderStyle*)
203 return new RenderTextControlMultiLine(this);
206 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
208 if (name().isEmpty())
211 document().updateLayout();
213 const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
214 encoding.appendData(name(), text);
216 const AtomicString& dirnameAttrValue = fastGetAttribute(dirnameAttr);
217 if (!dirnameAttrValue.isNull())
218 encoding.appendData(dirnameAttrValue, directionForFormData());
222 void HTMLTextAreaElement::resetImpl()
224 setNonDirtyValue(defaultValue());
227 bool HTMLTextAreaElement::hasCustomFocusLogic() const
232 bool HTMLTextAreaElement::isKeyboardFocusable() const
234 // If a given text area can be focused at all, then it will always be keyboard focusable.
235 return isFocusable();
238 bool HTMLTextAreaElement::shouldShowFocusRingOnMouseFocus() const
243 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
245 if (!restorePreviousSelection)
246 setSelectionRange(0, 0);
248 restoreCachedSelection();
250 if (document().frame())
251 document().frame()->selection().revealSelection();
254 void HTMLTextAreaElement::defaultEventHandler(Event* event)
256 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur))
258 else if (renderer() && event->isBeforeTextInsertedEvent())
259 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
261 HTMLTextFormControlElement::defaultEventHandler(event);
264 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusType)
266 if (LocalFrame* frame = document().frame())
267 frame->spellChecker().didBeginEditing(this);
270 void HTMLTextAreaElement::subtreeHasChanged()
272 setChangedSinceLastFormControlChangeEvent(true);
273 m_valueIsUpToDate = false;
274 setNeedsValidityCheck();
275 setAutofilled(false);
280 // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
281 calculateAndAdjustDirectionality();
283 ASSERT(document().isActive());
284 document().frameHost()->chrome().client().didChangeValueInTextField(*this);
287 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
291 int signedMaxLength = maxLength();
292 if (signedMaxLength < 0)
294 unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
296 const String& currentValue = innerEditorValue();
297 unsigned currentLength = computeLengthForSubmission(currentValue);
298 if (currentLength + computeLengthForSubmission(event->text()) < unsignedMaxLength)
301 // selectionLength represents the selection length of this text field to be
302 // removed by this insertion.
303 // If the text field has no focus, we don't need to take account of the
304 // selection length. The selection is the source of text drag-and-drop in
305 // that case, and nothing in the text field will be removed.
306 unsigned selectionLength = 0;
309 document().frame()->selection().selection().toNormalizedPositions(start, end);
310 selectionLength = computeLengthForSubmission(plainText(start, end));
312 ASSERT(currentLength >= selectionLength);
313 unsigned baseLength = currentLength - selectionLength;
314 unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
315 event->setText(sanitizeUserInputValue(event->text(), appendableLength));
318 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
320 if (maxLength > 0 && U16_IS_LEAD(proposedValue[maxLength - 1]))
322 return proposedValue.left(maxLength);
325 void HTMLTextAreaElement::updateValue() const
327 if (m_valueIsUpToDate)
330 m_value = innerEditorValue();
331 const_cast<HTMLTextAreaElement*>(this)->m_valueIsUpToDate = true;
332 const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
334 const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
337 String HTMLTextAreaElement::value() const
343 void HTMLTextAreaElement::setValue(const String& value, TextFieldEventBehavior eventBehavior)
345 RefPtrWillBeRawPtr<HTMLTextAreaElement> protector(this);
346 setValueCommon(value, eventBehavior);
348 if (document().focusedElement() == this)
349 document().frameHost()->chrome().client().didUpdateTextOfFocusedElementByNonUserInput();
352 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
354 setValueCommon(value, DispatchNoEvent, SetSeletion);
358 void HTMLTextAreaElement::setValueCommon(const String& newValue, TextFieldEventBehavior eventBehavior, SetValueCommonOption setValueOption)
360 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
361 // We normalize line endings coming from JavaScript here.
362 String normalizedValue = newValue.isNull() ? "" : newValue;
363 normalizedValue.replace("\r\n", "\n");
364 normalizedValue.replace('\r', '\n');
366 // Return early because we don't want to trigger other side effects
367 // when the value isn't changing.
368 // FIXME: Simple early return doesn't match the Firefox ever.
369 // Remove these lines.
370 if (normalizedValue == value()) {
371 if (setValueOption == SetSeletion) {
372 setNeedsValidityCheck();
373 if (isFinishedParsingChildren()) {
374 // Set the caret to the end of the text value except for initialize.
375 unsigned endOfString = m_value.length();
376 setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, ChangeSelectionIfFocused);
382 m_value = normalizedValue;
383 setInnerEditorValue(m_value);
384 if (eventBehavior == DispatchNoEvent)
385 setLastChangeWasNotUserEdit();
386 updatePlaceholderVisibility(false);
387 setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::ControlValue));
388 m_suggestedValue = String();
389 setNeedsValidityCheck();
390 if (isFinishedParsingChildren()) {
391 // Set the caret to the end of the text value except for initialize.
392 unsigned endOfString = m_value.length();
393 setSelectionRange(endOfString, endOfString, SelectionHasNoDirection, ChangeSelectionIfFocused);
396 notifyFormStateChanged();
397 if (eventBehavior == DispatchNoEvent) {
398 setTextAsOfLastFormControlChangeEvent(normalizedValue);
400 if (eventBehavior == DispatchInputAndChangeEvent)
401 dispatchFormControlInputEvent();
402 dispatchFormControlChangeEvent();
406 void HTMLTextAreaElement::setInnerEditorValue(const String& value)
408 HTMLTextFormControlElement::setInnerEditorValue(value);
409 m_valueIsUpToDate = true;
412 String HTMLTextAreaElement::defaultValue() const
416 // Since there may be comments, ignore nodes other than text nodes.
417 for (Node* n = firstChild(); n; n = n->nextSibling()) {
419 value.append(toText(n)->data());
422 return value.toString();
425 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
427 RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this);
429 // To preserve comments, remove only the text nodes, then add a single text node.
430 WillBeHeapVector<RefPtrWillBeMember<Node>> textNodes;
431 for (Node* n = firstChild(); n; n = n->nextSibling()) {
435 size_t size = textNodes.size();
436 for (size_t i = 0; i < size; ++i)
437 removeChild(textNodes[i].get(), IGNORE_EXCEPTION);
439 // Normalize line endings.
440 String value = defaultValue;
441 value.replace("\r\n", "\n");
442 value.replace('\r', '\n');
444 insertBefore(document().createTextNode(value), firstChild(), IGNORE_EXCEPTION);
447 setNonDirtyValue(value);
450 int HTMLTextAreaElement::maxLength() const
453 if (!parseHTMLInteger(getAttribute(maxlengthAttr), value))
455 return value >= 0 ? value : -1;
458 int HTMLTextAreaElement::minLength() const
461 if (!parseHTMLInteger(getAttribute(minlengthAttr), value))
463 return value >= 0 ? value : -1;
466 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
468 int min = minLength();
470 exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
471 else if (min >= 0 && newValue < min)
472 exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMinimumBound("maxLength", newValue, min));
474 setIntegralAttribute(maxlengthAttr, newValue);
477 void HTMLTextAreaElement::setMinLength(int newValue, ExceptionState& exceptionState)
479 int max = maxLength();
481 exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
482 else if (max >= 0 && newValue > max)
483 exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexExceedsMaximumBound("minLength", newValue, max));
485 setIntegralAttribute(minlengthAttr, newValue);
488 String HTMLTextAreaElement::suggestedValue() const
490 return m_suggestedValue;
493 void HTMLTextAreaElement::setSuggestedValue(const String& value)
495 m_suggestedValue = value;
498 setInnerEditorValue(m_suggestedValue);
500 setInnerEditorValue(m_value);
501 updatePlaceholderVisibility(false);
502 setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::ControlValue));
505 String HTMLTextAreaElement::validationMessage() const
511 return customValidationMessage();
514 return locale().queryString(blink::WebLocalizedString::ValidationValueMissing);
517 return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
520 return locale().validationMessageTooShortText(computeLengthForSubmission(value()), minLength());
525 bool HTMLTextAreaElement::valueMissing() const
527 // We should not call value() for performance.
528 return willValidate() && valueMissing(0);
531 bool HTMLTextAreaElement::valueMissing(const String* value) const
533 return isRequiredFormControl() && !isDisabledOrReadOnly() && (value ? *value : this->value()).isEmpty();
536 bool HTMLTextAreaElement::tooLong() const
538 // We should not call value() for performance.
539 return willValidate() && tooLong(0, CheckDirtyFlag);
542 bool HTMLTextAreaElement::tooShort() const
544 // We should not call value() for performance.
545 return willValidate() && tooShort(0, CheckDirtyFlag);
548 bool HTMLTextAreaElement::tooLong(const String* value, NeedsToCheckDirtyFlag check) const
550 // Return false for the default value or value set by script even if it is
551 // longer than maxLength.
552 if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
555 int max = maxLength();
558 return computeLengthForSubmission(value ? *value : this->value()) > static_cast<unsigned>(max);
561 bool HTMLTextAreaElement::tooShort(const String* value, NeedsToCheckDirtyFlag check) const
563 // Return false for the default value or value set by script even if it is
564 // shorter than minLength.
565 if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
568 int min = minLength();
571 // An empty string is excluded from minlength check.
572 unsigned len = computeLengthForSubmission(value ? *value : this->value());
573 return len > 0 && len < static_cast<unsigned>(min);
576 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
578 return !valueMissing(&candidate) && !tooLong(&candidate, IgnoreDirtyFlag) && !tooShort(&candidate, IgnoreDirtyFlag);
581 void HTMLTextAreaElement::accessKeyAction(bool)
586 void HTMLTextAreaElement::setCols(int cols)
588 setIntegralAttribute(colsAttr, cols);
591 void HTMLTextAreaElement::setRows(int rows)
593 setIntegralAttribute(rowsAttr, rows);
596 bool HTMLTextAreaElement::matchesReadOnlyPseudoClass() const
601 bool HTMLTextAreaElement::matchesReadWritePseudoClass() const
603 return !isReadOnly();
606 void HTMLTextAreaElement::updatePlaceholderText()
608 HTMLElement* placeholder = placeholderElement();
609 const AtomicString& placeholderText = fastGetAttribute(placeholderAttr);
610 if (placeholderText.isEmpty()) {
612 userAgentShadowRoot()->removeChild(placeholder);
616 RefPtrWillBeRawPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
617 placeholder = newElement.get();
618 placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
619 placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
620 userAgentShadowRoot()->insertBefore(placeholder, innerEditorElement()->nextSibling());
622 placeholder->setTextContent(placeholderText);
625 bool HTMLTextAreaElement::isInteractiveContent() const
630 bool HTMLTextAreaElement::supportsAutofocus() const