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 "CSSValueKeywords.h"
30 #include "HTMLNames.h"
31 #include "bindings/v8/ExceptionState.h"
32 #include "bindings/v8/ExceptionStatePlaceholder.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/events/ThreadLocalEventNames.h"
43 #include "core/html/FormDataList.h"
44 #include "core/html/forms/FormController.h"
45 #include "core/html/shadow/ShadowElementNames.h"
46 #include "core/html/shadow/TextControlInnerElements.h"
47 #include "core/frame/Frame.h"
48 #include "core/rendering/RenderTextControlMultiLine.h"
49 #include "platform/text/PlatformLocale.h"
50 #include "wtf/StdLibExtras.h"
51 #include "wtf/text/StringBuilder.h"
55 using namespace HTMLNames;
57 static const int defaultRows = 2;
58 static const int defaultCols = 20;
60 // On submission, LF characters are converted into CRLF.
61 // This function returns number of characters considering this.
62 static unsigned numberOfLineBreaks(const String& text)
64 unsigned length = text.length();
66 for (unsigned i = 0; i < length; i++) {
73 static inline unsigned computeLengthForSubmission(const String& text)
75 return text.length() + numberOfLineBreaks(text);
78 HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* form)
79 : HTMLTextFormControlElement(textareaTag, document, form)
85 setFormControlValueMatchesRenderer(true);
86 ScriptWrappable::init(this);
89 PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
91 RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(document, form));
92 textArea->ensureUserAgentShadowRoot();
93 return textArea.release();
96 void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
98 root.appendChild(TextControlInnerTextElement::create(document()));
101 const AtomicString& HTMLTextAreaElement::formControlType() const
103 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea", AtomicString::ConstructFromLiteral));
107 FormControlState HTMLTextAreaElement::saveFormControlState() const
109 return m_isDirty ? FormControlState(value()) : FormControlState();
112 void HTMLTextAreaElement::restoreFormControlState(const FormControlState& state)
117 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
119 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
120 setLastChangeWasNotUserEdit();
122 setInnerTextValue(value());
124 setNonDirtyValue(defaultValue());
127 bool HTMLTextAreaElement::isPresentationAttribute(const QualifiedName& name) const
129 if (name == alignAttr) {
130 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
131 // See http://bugs.webkit.org/show_bug.cgi?id=7075
135 if (name == wrapAttr)
137 return HTMLTextFormControlElement::isPresentationAttribute(name);
140 void HTMLTextAreaElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
142 if (name == wrapAttr) {
143 if (shouldWrapText()) {
144 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
145 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
147 addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
148 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
151 HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
154 void HTMLTextAreaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
156 if (name == rowsAttr) {
157 int rows = value.toInt();
160 if (m_rows != rows) {
163 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
165 } else if (name == colsAttr) {
166 int cols = value.toInt();
169 if (m_cols != cols) {
172 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
174 } else if (name == wrapAttr) {
175 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
176 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
178 if (equalIgnoringCase(value, "physical") || equalIgnoringCase(value, "hard") || equalIgnoringCase(value, "on"))
180 else if (equalIgnoringCase(value, "off"))
184 if (wrap != m_wrap) {
187 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
189 } else if (name == accesskeyAttr) {
190 // ignore for the moment
191 } else if (name == maxlengthAttr)
192 setNeedsValidityCheck();
194 HTMLTextFormControlElement::parseAttribute(name, value);
197 RenderObject* HTMLTextAreaElement::createRenderer(RenderStyle*)
199 return new RenderTextControlMultiLine(this);
202 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
204 if (name().isEmpty())
207 document().updateLayout();
209 const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
210 encoding.appendData(name(), text);
212 const AtomicString& dirnameAttrValue = fastGetAttribute(dirnameAttr);
213 if (!dirnameAttrValue.isNull())
214 encoding.appendData(dirnameAttrValue, directionForFormData());
218 void HTMLTextAreaElement::resetImpl()
220 setNonDirtyValue(defaultValue());
223 bool HTMLTextAreaElement::hasCustomFocusLogic() const
228 bool HTMLTextAreaElement::isKeyboardFocusable() const
230 // If a given text area can be focused at all, then it will always be keyboard focusable.
231 return isFocusable();
234 bool HTMLTextAreaElement::shouldShowFocusRingOnMouseFocus() const
239 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
241 if (!restorePreviousSelection || !hasCachedSelection()) {
242 // If this is the first focus, set a caret at the beginning of the text.
243 // This matches some browsers' behavior; see bug 11746 Comment #15.
244 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
245 setSelectionRange(0, 0);
247 restoreCachedSelection();
249 if (document().frame())
250 document().frame()->selection().revealSelection();
253 void HTMLTextAreaElement::defaultEventHandler(Event* event)
255 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur))
257 else if (renderer() && event->isBeforeTextInsertedEvent())
258 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
260 HTMLTextFormControlElement::defaultEventHandler(event);
263 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusType)
265 if (Frame* frame = document().frame())
266 frame->spellChecker().didBeginEditing(this);
269 void HTMLTextAreaElement::subtreeHasChanged()
271 setChangedSinceLastFormControlChangeEvent(true);
272 setFormControlValueMatchesRenderer(false);
273 setNeedsValidityCheck();
278 // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
279 calculateAndAdjustDirectionality();
282 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
286 int signedMaxLength = maxLength();
287 if (signedMaxLength < 0)
289 unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
291 const String& currentValue = innerTextValue();
292 unsigned currentLength = computeLengthForSubmission(currentValue);
293 if (currentLength + computeLengthForSubmission(event->text()) < unsignedMaxLength)
296 // selectionLength represents the selection length of this text field to be
297 // removed by this insertion.
298 // If the text field has no focus, we don't need to take account of the
299 // selection length. The selection is the source of text drag-and-drop in
300 // that case, and nothing in the text field will be removed.
301 unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document().frame()->selection().selection().toNormalizedRange().get())) : 0;
302 ASSERT(currentLength >= selectionLength);
303 unsigned baseLength = currentLength - selectionLength;
304 unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
305 event->setText(sanitizeUserInputValue(event->text(), appendableLength));
308 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
310 if (maxLength > 0 && U16_IS_LEAD(proposedValue[maxLength - 1]))
312 return proposedValue.left(maxLength);
315 void HTMLTextAreaElement::updateValue() const
317 if (formControlValueMatchesRenderer())
321 m_value = innerTextValue();
322 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
323 const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
325 const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
328 String HTMLTextAreaElement::value() const
334 void HTMLTextAreaElement::setValue(const String& value)
336 setValueCommon(value);
338 setNeedsValidityCheck();
341 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
343 setValueCommon(value);
345 setNeedsValidityCheck();
348 void HTMLTextAreaElement::setValueCommon(const String& newValue)
350 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
351 // We normalize line endings coming from JavaScript here.
352 String normalizedValue = newValue.isNull() ? "" : newValue;
353 normalizedValue.replace("\r\n", "\n");
354 normalizedValue.replace('\r', '\n');
356 // Return early because we don't want to move the caret or trigger other side effects
357 // when the value isn't changing. This matches Firefox behavior, at least.
358 if (normalizedValue == value())
361 m_value = normalizedValue;
362 setInnerTextValue(m_value);
363 setLastChangeWasNotUserEdit();
364 updatePlaceholderVisibility(false);
365 setNeedsStyleRecalc(SubtreeStyleChange);
366 setFormControlValueMatchesRenderer(true);
367 m_suggestedValue = String();
369 // Set the caret to the end of the text value.
370 if (document().focusedElement() == this) {
371 unsigned endOfString = m_value.length();
372 setSelectionRange(endOfString, endOfString);
375 notifyFormStateChanged();
376 setTextAsOfLastFormControlChangeEvent(normalizedValue);
379 String HTMLTextAreaElement::defaultValue() const
383 // Since there may be comments, ignore nodes other than text nodes.
384 for (Node* n = firstChild(); n; n = n->nextSibling()) {
386 value.append(toText(n)->data());
389 return value.toString();
392 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
394 RefPtr<Node> protectFromMutationEvents(this);
396 // To preserve comments, remove only the text nodes, then add a single text node.
397 Vector<RefPtr<Node> > textNodes;
398 for (Node* n = firstChild(); n; n = n->nextSibling()) {
402 size_t size = textNodes.size();
403 for (size_t i = 0; i < size; ++i)
404 removeChild(textNodes[i].get(), IGNORE_EXCEPTION);
406 // Normalize line endings.
407 String value = defaultValue;
408 value.replace("\r\n", "\n");
409 value.replace('\r', '\n');
411 insertBefore(document().createTextNode(value), firstChild(), IGNORE_EXCEPTION);
414 setNonDirtyValue(value);
417 int HTMLTextAreaElement::maxLength() const
420 int value = getAttribute(maxlengthAttr).string().toInt(&ok);
421 return ok && value >= 0 ? value : -1;
424 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
427 exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
429 setIntegralAttribute(maxlengthAttr, newValue);
432 String HTMLTextAreaElement::suggestedValue() const
434 return m_suggestedValue;
437 void HTMLTextAreaElement::setSuggestedValue(const String& value)
439 m_suggestedValue = value;
440 setInnerTextValue(m_suggestedValue);
441 updatePlaceholderVisibility(false);
442 setNeedsStyleRecalc(SubtreeStyleChange);
443 setFormControlValueMatchesRenderer(true);
446 String HTMLTextAreaElement::validationMessage() const
452 return customValidationMessage();
455 return locale().queryString(blink::WebLocalizedString::ValidationValueMissing);
458 return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
463 bool HTMLTextAreaElement::valueMissing() const
465 return willValidate() && valueMissing(value());
468 bool HTMLTextAreaElement::tooLong() const
470 return willValidate() && tooLong(value(), CheckDirtyFlag);
473 bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
475 // Return false for the default value or value set by script even if it is
476 // longer than maxLength.
477 if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
480 int max = maxLength();
483 return computeLengthForSubmission(value) > static_cast<unsigned>(max);
486 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
488 return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
491 void HTMLTextAreaElement::accessKeyAction(bool)
496 void HTMLTextAreaElement::setCols(int cols)
498 setIntegralAttribute(colsAttr, cols);
501 void HTMLTextAreaElement::setRows(int rows)
503 setIntegralAttribute(rowsAttr, rows);
506 bool HTMLTextAreaElement::shouldUseInputMethod()
511 bool HTMLTextAreaElement::matchesReadOnlyPseudoClass() const
516 bool HTMLTextAreaElement::matchesReadWritePseudoClass() const
518 return !isReadOnly();
521 void HTMLTextAreaElement::updatePlaceholderText()
523 HTMLElement* placeholder = placeholderElement();
524 String placeholderText = strippedPlaceholder();
525 if (placeholderText.isEmpty()) {
527 userAgentShadowRoot()->removeChild(placeholder);
531 RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
532 placeholder = newElement.get();
533 placeholder->setShadowPseudoId(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
534 placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
535 userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
537 placeholder->setTextContent(placeholderText);
540 bool HTMLTextAreaElement::isInteractiveContent() const
545 bool HTMLTextAreaElement::supportsAutofocus() const