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 "HTMLTextAreaElement.h"
29 #include "Attribute.h"
30 #include "BeforeTextInsertedEvent.h"
31 #include "CSSValueKeywords.h"
33 #include "ElementShadow.h"
35 #include "EventNames.h"
36 #include "ExceptionCode.h"
37 #include "FormDataList.h"
39 #include "HTMLNames.h"
40 #include "LocalizedStrings.h"
41 #include "RenderTextControlMultiLine.h"
42 #include "ShadowRoot.h"
44 #include "TextControlInnerElements.h"
45 #include "TextIterator.h"
46 #include <wtf/StdLibExtras.h>
47 #include <wtf/text/StringBuilder.h>
51 using namespace HTMLNames;
53 static const int defaultRows = 2;
54 static const int defaultCols = 20;
56 // On submission, LF characters are converted into CRLF.
57 // This function returns number of characters considering this.
58 static unsigned computeLengthForSubmission(const String& text)
60 unsigned count = numGraphemeClusters(text);
61 unsigned length = text.length();
62 for (unsigned i = 0; i < length; i++) {
69 HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
70 : HTMLTextFormControlElement(tagName, document, form)
75 , m_wasModifiedByUser(false)
77 ASSERT(hasTagName(textareaTag));
78 setFormControlValueMatchesRenderer(true);
81 PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
83 RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(tagName, document, form));
84 textArea->createShadowSubtree();
85 return textArea.release();
88 void HTMLTextAreaElement::createShadowSubtree()
91 RefPtr<ShadowRoot> root = ShadowRoot::create(this, ShadowRoot::CreatingUserAgentShadowRoot);
92 root->appendChild(TextControlInnerTextElement::create(document()), ASSERT_NO_EXCEPTION);
95 const AtomicString& HTMLTextAreaElement::formControlType() const
97 DEFINE_STATIC_LOCAL(const AtomicString, textarea, ("textarea"));
101 bool HTMLTextAreaElement::saveFormControlState(String& result) const
103 String currentValue = value();
104 if (currentValue == defaultValue())
106 result = currentValue;
110 void HTMLTextAreaElement::restoreFormControlState(const String& state)
115 void HTMLTextAreaElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
117 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
118 setLastChangeWasNotUserEdit();
120 setInnerTextValue(value());
122 setNonDirtyValue(defaultValue());
125 bool HTMLTextAreaElement::isPresentationAttribute(const QualifiedName& name) const
127 if (name == alignAttr) {
128 // Don't map 'align' attribute. This matches what Firefox, Opera and IE do.
129 // See http://bugs.webkit.org/show_bug.cgi?id=7075
133 if (name == wrapAttr)
135 return HTMLTextFormControlElement::isPresentationAttribute(name);
138 void HTMLTextAreaElement::collectStyleForAttribute(const Attribute& attribute, StylePropertySet* style)
140 if (attribute.name() == wrapAttr) {
141 if (shouldWrapText()) {
142 addPropertyToAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
143 addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
145 addPropertyToAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
146 addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
149 HTMLTextFormControlElement::collectStyleForAttribute(attribute, style);
152 void HTMLTextAreaElement::parseAttribute(const Attribute& attribute)
154 if (attribute.name() == rowsAttr) {
155 int rows = attribute.value().toInt();
158 if (m_rows != rows) {
161 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
163 } else if (attribute.name() == colsAttr) {
164 int cols = attribute.value().toInt();
167 if (m_cols != cols) {
170 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
172 } else if (attribute.name() == wrapAttr) {
173 // The virtual/physical values were a Netscape extension of HTML 3.0, now deprecated.
174 // The soft/hard /off values are a recommendation for HTML 4 extension by IE and NS 4.
176 if (equalIgnoringCase(attribute.value(), "physical") || equalIgnoringCase(attribute.value(), "hard") || equalIgnoringCase(attribute.value(), "on"))
178 else if (equalIgnoringCase(attribute.value(), "off"))
182 if (wrap != m_wrap) {
185 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
187 } else if (attribute.name() == accesskeyAttr) {
188 // ignore for the moment
189 } else if (attribute.name() == maxlengthAttr)
190 setNeedsValidityCheck();
192 HTMLTextFormControlElement::parseAttribute(attribute);
195 RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
197 return new (arena) RenderTextControlMultiLine(this);
200 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
202 if (name().isEmpty())
205 document()->updateLayout();
207 const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
208 encoding.appendData(name(), text);
210 const AtomicString& dirnameAttrValue = fastGetAttribute(dirnameAttr);
211 if (!dirnameAttrValue.isNull())
212 encoding.appendData(dirnameAttrValue, directionForFormData());
216 void HTMLTextAreaElement::reset()
218 setNonDirtyValue(defaultValue());
221 bool HTMLTextAreaElement::isKeyboardFocusable(KeyboardEvent*) const
223 // If a given text area can be focused at all, then it will always be keyboard focusable.
224 return isFocusable();
227 bool HTMLTextAreaElement::isMouseFocusable() const
229 return isFocusable();
232 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
234 if (!restorePreviousSelection || !hasCachedSelection()) {
235 // If this is the first focus, set a caret at the beginning of the text.
236 // This matches some browsers' behavior; see bug 11746 Comment #15.
237 // http://bugs.webkit.org/show_bug.cgi?id=11746#c15
238 setSelectionRange(0, 0);
240 restoreCachedSelection();
242 if (document()->frame())
243 document()->frame()->selection()->revealSelection();
246 void HTMLTextAreaElement::defaultEventHandler(Event* event)
248 if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(eventNames().interfaceForWheelEvent) || event->type() == eventNames().blurEvent))
250 else if (renderer() && event->isBeforeTextInsertedEvent())
251 handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
253 HTMLTextFormControlElement::defaultEventHandler(event);
256 void HTMLTextAreaElement::subtreeHasChanged()
258 setChangedSinceLastFormControlChangeEvent(true);
259 setFormControlValueMatchesRenderer(false);
260 setNeedsValidityCheck();
265 if (Frame* frame = document()->frame())
266 frame->editor()->textDidChangeInTextArea(this);
267 // When typing in a textarea, childrenChanged is not called, so we need to force the directionality check.
268 calculateAndAdjustDirectionality();
271 void HTMLTextAreaElement::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event) const
275 int signedMaxLength = maxLength();
276 if (signedMaxLength < 0)
278 unsigned unsignedMaxLength = static_cast<unsigned>(signedMaxLength);
280 unsigned currentLength = computeLengthForSubmission(innerTextValue());
281 // selectionLength represents the selection length of this text field to be
282 // removed by this insertion.
283 // If the text field has no focus, we don't need to take account of the
284 // selection length. The selection is the source of text drag-and-drop in
285 // that case, and nothing in the text field will be removed.
286 unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document()->frame()->selection()->selection().toNormalizedRange().get())) : 0;
287 ASSERT(currentLength >= selectionLength);
288 unsigned baseLength = currentLength - selectionLength;
289 unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
290 event->setText(sanitizeUserInputValue(event->text(), appendableLength));
293 String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue, unsigned maxLength)
295 return proposedValue.left(numCharactersInGraphemeClusters(proposedValue, maxLength));
298 HTMLElement* HTMLTextAreaElement::innerTextElement() const
300 Node* node = shadow()->oldestShadowRoot()->firstChild();
301 ASSERT(!node || node->hasTagName(divTag));
302 return toHTMLElement(node);
305 void HTMLTextAreaElement::rendererWillBeDestroyed()
310 void HTMLTextAreaElement::updateValue() const
312 if (formControlValueMatchesRenderer())
316 m_value = innerTextValue();
317 const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
318 const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
320 m_wasModifiedByUser = true;
321 const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
324 String HTMLTextAreaElement::value() const
330 void HTMLTextAreaElement::setValue(const String& value)
332 setValueCommon(value);
334 setNeedsValidityCheck();
337 void HTMLTextAreaElement::setNonDirtyValue(const String& value)
339 setValueCommon(value);
341 setNeedsValidityCheck();
344 void HTMLTextAreaElement::setValueCommon(const String& newValue)
346 m_wasModifiedByUser = false;
347 // Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
348 // We normalize line endings coming from JavaScript here.
349 String normalizedValue = newValue.isNull() ? "" : newValue;
350 normalizedValue.replace("\r\n", "\n");
351 normalizedValue.replace('\r', '\n');
353 // Return early because we don't want to move the caret or trigger other side effects
354 // when the value isn't changing. This matches Firefox behavior, at least.
355 if (normalizedValue == value())
358 m_value = normalizedValue;
359 setInnerTextValue(m_value);
360 setLastChangeWasNotUserEdit();
361 updatePlaceholderVisibility(false);
362 setNeedsStyleRecalc();
363 setFormControlValueMatchesRenderer(true);
365 // Set the caret to the end of the text value.
366 if (document()->focusedNode() == this) {
367 unsigned endOfString = m_value.length();
368 setSelectionRange(endOfString, endOfString);
371 notifyFormStateChanged();
372 setTextAsOfLastFormControlChangeEvent(normalizedValue);
375 String HTMLTextAreaElement::defaultValue() const
379 // Since there may be comments, ignore nodes other than text nodes.
380 for (Node* n = firstChild(); n; n = n->nextSibling()) {
382 value.append(toText(n)->data());
385 return value.toString();
388 void HTMLTextAreaElement::setDefaultValue(const String& defaultValue)
390 RefPtr<Node> protectFromMutationEvents(this);
392 // To preserve comments, remove only the text nodes, then add a single text node.
393 Vector<RefPtr<Node> > textNodes;
394 for (Node* n = firstChild(); n; n = n->nextSibling()) {
399 size_t size = textNodes.size();
400 for (size_t i = 0; i < size; ++i)
401 removeChild(textNodes[i].get(), ec);
403 // Normalize line endings.
404 String value = defaultValue;
405 value.replace("\r\n", "\n");
406 value.replace('\r', '\n');
408 insertBefore(document()->createTextNode(value), firstChild(), ec);
411 setNonDirtyValue(value);
414 int HTMLTextAreaElement::maxLength() const
417 int value = getAttribute(maxlengthAttr).string().toInt(&ok);
418 return ok && value >= 0 ? value : -1;
421 void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionCode& ec)
426 setAttribute(maxlengthAttr, String::number(newValue));
429 String HTMLTextAreaElement::validationMessage() const
435 return customValidationMessage();
438 return validationMessageValueMissingText();
441 return validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
446 bool HTMLTextAreaElement::valueMissing() const
448 return willValidate() && valueMissing(value());
451 bool HTMLTextAreaElement::tooLong() const
453 return willValidate() && tooLong(value(), CheckDirtyFlag);
456 bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag check) const
458 // Return false for the default value or value set by script even if it is
459 // longer than maxLength.
460 if (check == CheckDirtyFlag && !m_wasModifiedByUser)
463 int max = maxLength();
466 return computeLengthForSubmission(value) > static_cast<unsigned>(max);
469 bool HTMLTextAreaElement::isValidValue(const String& candidate) const
471 return !valueMissing(candidate) && !tooLong(candidate, IgnoreDirtyFlag);
474 void HTMLTextAreaElement::accessKeyAction(bool)
479 void HTMLTextAreaElement::setCols(int cols)
481 setAttribute(colsAttr, String::number(cols));
484 void HTMLTextAreaElement::setRows(int rows)
486 setAttribute(rowsAttr, String::number(rows));
489 bool HTMLTextAreaElement::shouldUseInputMethod()
494 HTMLElement* HTMLTextAreaElement::placeholderElement() const
496 return m_placeholder.get();
499 void HTMLTextAreaElement::attach()
501 HTMLTextFormControlElement::attach();
502 fixPlaceholderRenderer(m_placeholder.get(), innerTextElement());
505 void HTMLTextAreaElement::updatePlaceholderText()
507 ExceptionCode ec = 0;
508 String placeholderText = strippedPlaceholder();
509 if (placeholderText.isEmpty()) {
511 shadow()->oldestShadowRoot()->removeChild(m_placeholder.get(), ec);
513 m_placeholder.clear();
517 if (!m_placeholder) {
518 m_placeholder = HTMLDivElement::create(document());
519 m_placeholder->setShadowPseudoId("-webkit-input-placeholder");
520 shadow()->oldestShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling(), ec);
523 m_placeholder->setInnerText(placeholderText, ec);
525 fixPlaceholderRenderer(m_placeholder.get(), innerTextElement());