View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import java.io.PrintWriter;
18  import java.util.Map;
19  
20  import org.htmlunit.SgmlPage;
21  import org.htmlunit.html.impl.SelectableTextInput;
22  import org.htmlunit.html.impl.SelectableTextSelectionDelegate;
23  import org.htmlunit.javascript.host.event.Event;
24  import org.htmlunit.javascript.host.event.MouseEvent;
25  import org.htmlunit.util.NameValuePair;
26  import org.htmlunit.util.StringUtils;
27  
28  /**
29   * Wrapper for the HTML element "textarea".
30   *
31   * @author Mike Bowler
32   * @author Barnaby Court
33   * @author David K. Taylor
34   * @author Christian Sell
35   * @author David D. Kilzer
36   * @author Marc Guillemot
37   * @author Daniel Gredler
38   * @author Ahmed Ashour
39   * @author Sudhan Moghe
40   * @author Amit Khanna
41   * @author Ronald Brill
42   * @author Frank Danek
43   * @author Lai Quang Duong
44   */
45  public class HtmlTextArea extends HtmlElement implements DisabledElement, SubmittableElement,
46                  LabelableElement, SelectableTextInput, ValidatableHtmlElement {
47      /** The HTML tag represented by this element. */
48      public static final String TAG_NAME = "textarea";
49  
50      private String defaultValue_;
51  
52      /**
53       * The element's raw value (spec term), decoupled from the DOM child nodes
54       * once {@link #isValueDirty_} is {@code true}. Mirrors {@code HtmlInput}'s
55       * dirty-value-flag model rather than reading/writing child text nodes directly.
56       */
57      private String rawValue_;
58  
59      /**
60       * The dirty value flag (spec term). While {@code false}, the raw value tracks
61       * the element's child text content automatically. Once {@code true} (set by
62       * the {@code value} setter, or by a user edit/type), child mutations no
63       * longer affect the raw value until {@link #reset()} clears the flag again.
64       */
65      private boolean isValueDirty_;
66  
67      private String valueAtFocus_;
68      private String customValidity_;
69  
70      /** Whether the last typed char was a '\r' (to type a '\r\n' sequence as a single line feed). */
71      private boolean lastTypedCarriageReturn_;
72  
73      private SelectableTextSelectionDelegate selectionDelegate_ = new SelectableTextSelectionDelegate(this);
74      private DoTypeProcessor doTypeProcessor_ = new DoTypeProcessor(this);
75  
76      /**
77       * Creates an instance.
78       *
79       * @param qualifiedName the qualified name of the element type to instantiate
80       * @param page the page that contains this element
81       * @param attributes the initial attributes
82       */
83      HtmlTextArea(final String qualifiedName, final SgmlPage page,
84              final Map<String, DomAttr> attributes) {
85          super(qualifiedName, page, attributes);
86      }
87  
88      /**
89       * Initializes the default value if necessary. We cannot do it in the constructor
90       * because the child node variable will not have been initialized yet. Must be called
91       * from all methods that use the default value.
92       */
93      private void initDefaultValue() {
94          if (defaultValue_ == null) {
95              defaultValue_ = computeValueFromChildText();
96          }
97      }
98  
99      /**
100      * {@inheritDoc}
101      */
102     @Override
103     public boolean handles(final Event event) {
104         if (event instanceof MouseEvent) {
105             return true;
106         }
107 
108         return super.handles(event);
109     }
110 
111     /**
112      * Returns the value that would be displayed in the text area.
113      * This is the element's "raw value" (spec term). While the dirty value
114      * flag is {@code false}, this is always computed fresh from the current
115      * child text content -- deliberately NOT cached and re-synced via
116      * mutation hooks, since that approach cannot reliably catch every way the
117      * children can change (e.g. a child {@code DomText}'s {@code data} being
118      * reassigned directly bypasses any hook on this element). Once the dirty
119      * flag becomes {@code true} (via {@link #setText(String)} or typing), the
120      * value is held in {@link #rawValue_} and is fully decoupled from the
121      * children until {@link #reset()} clears the flag again.
122      *
123      * @return the text
124      */
125     @Override
126     public final String getText() {
127         if (isValueDirty_) {
128             return rawValue_;
129         }
130         return computeValueFromChildText();
131     }
132 
133     /**
134      * Computes what the raw value would be purely from the current child text
135      * content -- i.e. the spec's "child text content" used both for the initial/
136      * reset raw value and for {@code defaultValue}. Renamed from the old
137      * {@code readValue()}.
138      *
139      * @return the concatenated child text content (a line feed directly after
140      *     the start tag is already removed by the HTML parser)
141      */
142     private String computeValueFromChildText() {
143         final StringBuilder builder = new StringBuilder();
144         for (final DomNode node : getChildren()) {
145             if (node instanceof DomText text) {
146                 builder.append(text.getData());
147             }
148         }
149         return builder.toString();
150     }
151 
152     /**
153      * Sets the new value of this text area. Per spec, this sets the raw value
154      * directly and marks the dirty flag -- it must NOT touch the DOM child
155      * nodes at all, and no subsequent child mutation may affect this value
156      * again until {@link #reset()}.
157      * <p>
158      * Note that this acts like 'pasting' the text, but to simulate characters entry
159      * you should use {@link #type(String)}.
160      * </p>
161      *
162      * @param newValue the new value
163      */
164     @Override
165     public final void setText(final String newValue) {
166         setTextInternal(newValue);
167 
168         HtmlInput.executeOnChangeHandlerIfAppropriate(this);
169     }
170 
171     private void setTextInternal(final String newValue) {
172         final String oldValue = getText();
173 
174         rawValue_ = newValue;
175         isValueDirty_ = true;
176 
177         if (!newValue.equals(oldValue)) {
178             final int pos = newValue.length();
179             setSelectionStart(pos);
180             setSelectionEnd(pos);
181         }
182     }
183 
184     /**
185      * {@inheritDoc}
186      */
187     @Override
188     public NameValuePair[] getSubmitNameValuePairs() {
189         String text = getText();
190         text = text.replace("\r\n", "\n").replace("\n", "\r\n");
191 
192         return new NameValuePair[]{new NameValuePair(getNameAttribute(), text)};
193     }
194 
195     /**
196      * {@inheritDoc}
197      * Per the spec's reset algorithm for textarea elements: clears the dirty
198      * value flag. Once clear, {@link #getText()} automatically recomputes from
199      * the CURRENT child text content (not the page's originally-parsed text,
200      * and not {@link #defaultValue_} -- those can differ from the live
201      * children if the children were mutated while the dirty flag was
202      * {@code true}). Deliberately does not call {@link #setText(String)} /
203      * fire the onchange handler: a form reset fires a {@code reset} event,
204      * not a {@code change} event.
205      * @see SubmittableElement#reset()
206      */
207     @Override
208     public void reset() {
209         final String oldValue = getText();
210 
211         isValueDirty_ = false;
212 
213         final String newValue = computeValueFromChildText();
214         if (!newValue.equals(oldValue)) {
215             final int pos = newValue.length();
216             setSelectionStart(pos);
217             setSelectionEnd(pos);
218         }
219     }
220 
221     /**
222      * {@inheritDoc}
223      * Per spec, {@code defaultValue} is specified in terms of the element's
224      * child text content -- setting it mutates the children (here, via the
225      * same node-replacement helper the old {@code setTextInternal()} used).
226      * Since {@link #getText()} recomputes directly from the current children
227      * whenever the dirty flag is {@code false}, {@code value} is automatically
228      * updated as a side effect ONLY while still clean -- exactly matching
229      * observed real-browser behavior (replacing the old, less precise "if
230      * value still equals old default value" equality check).
231      * @see SubmittableElement#setDefaultValue(String)
232      */
233     @Override
234     public void setDefaultValue(final String defaultValue) {
235         initDefaultValue();
236         final String value = defaultValue == null ? "" : defaultValue;
237 
238         replaceChildTextContent(value);
239         defaultValue_ = value;
240     }
241 
242     /**
243      * Replaces this element's child text content with {@code newText}, reusing
244      * an existing text-node child in place where possible rather than always
245      * removing and recreating one (avoids unnecessary DOM node identity churn).
246      * Used only for mutating the DOM representation (e.g. from
247      * {@link #setDefaultValue(String)}) -- NOT for the {@code value}
248      * setter, which must not touch the children at all.
249      *
250      * @param newText the new child text content
251      */
252     private void replaceChildTextContent(final String newText) {
253         DomNode child = getFirstChild();
254         if (child == null) {
255             appendChild(new DomText(getPage(), newText));
256         }
257         else if (child instanceof DomText) {
258             ((DomText) child).setData(newText);
259         }
260         else {
261             DomNode next = child.getNextSibling();
262             while (next != null && !(next instanceof DomText)) {
263                 child = next;
264                 next = child.getNextSibling();
265             }
266 
267             if (next == null) {
268                 removeChild(child);
269                 appendChild(new DomText(getPage(), newText));
270             }
271             else {
272                 ((DomText) next).setData(newText);
273             }
274         }
275     }
276 
277     /**
278      * {@inheritDoc}
279      * @see SubmittableElement#getDefaultValue()
280      */
281     @Override
282     public String getDefaultValue() {
283         initDefaultValue();
284         return defaultValue_;
285     }
286 
287     /**
288      * {@inheritDoc}
289      * This implementation is empty; only check boxes and radio buttons
290      * really care what the default checked value is.
291      * @see SubmittableElement#setDefaultChecked(boolean)
292      * @see HtmlRadioButtonInput#setDefaultChecked(boolean)
293      * @see HtmlCheckBoxInput#setDefaultChecked(boolean)
294      */
295     @Override
296     public void setDefaultChecked(final boolean defaultChecked) {
297         // Empty.
298     }
299 
300     /**
301      * {@inheritDoc} This implementation returns {@code false}; only checkboxes and
302      * radio buttons really care what the default checked value is.
303      * @see SubmittableElement#isDefaultChecked()
304      * @see HtmlRadioButtonInput#isDefaultChecked()
305      * @see HtmlCheckBoxInput#isDefaultChecked()
306      */
307     @Override
308     public boolean isDefaultChecked() {
309         return false;
310     }
311 
312     /**
313      * Returns the value of the attribute {@code name}. Refer to the
314      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
315      * documentation for details on the use of this attribute.
316      *
317      * @return the value of the attribute {@code name} or an empty string if that attribute isn't defined
318      */
319     public final String getNameAttribute() {
320         return getAttributeDirect(DomElement.NAME_ATTRIBUTE);
321     }
322 
323     /**
324      * Returns the value of the attribute {@code rows}. Refer to the
325      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
326      * documentation for details on the use of this attribute.
327      *
328      * @return the value of the attribute {@code rows} or an empty string if that attribute isn't defined
329      */
330     public final String getRowsAttribute() {
331         return getAttributeDirect("rows");
332     }
333 
334     /**
335      * Returns the value of the attribute {@code cols}. Refer to the
336      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
337      * documentation for details on the use of this attribute.
338      *
339      * @return the value of the attribute {@code cols} or an empty string if that attribute isn't defined
340      */
341     public final String getColumnsAttribute() {
342         return getAttributeDirect("cols");
343     }
344 
345     /**
346      * {@inheritDoc}
347      */
348     @Override
349     public final String getDisabledAttribute() {
350         return getAttributeDirect(ATTRIBUTE_DISABLED);
351     }
352 
353     /**
354      * Returns the value of the attribute {@code readonly}. Refer to the
355      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
356      * documentation for details on the use of this attribute.
357      *
358      * @return the value of the attribute {@code readonly} or an empty string if that attribute isn't defined
359      */
360     public final String getReadOnlyAttribute() {
361         return getAttributeDirect(ATTRIBUTE_READONLY);
362     }
363 
364     /**
365      * Returns the value of the attribute {@code tabindex}. Refer to the
366      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
367      * documentation for details on the use of this attribute.
368      *
369      * @return the value of the attribute {@code tabindex} or an empty string if that attribute isn't defined
370      */
371     public final String getTabIndexAttribute() {
372         return getAttributeDirect("tabindex");
373     }
374 
375     /**
376      * Returns the value of the attribute {@code accesskey}. Refer to the
377      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
378      * documentation for details on the use of this attribute.
379      *
380      * @return the value of the attribute {@code accesskey} or an empty string if that attribute isn't defined
381      */
382     public final String getAccessKeyAttribute() {
383         return getAttributeDirect("accesskey");
384     }
385 
386     /**
387      * Returns the value of the attribute {@code onfocus}. Refer to the
388      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
389      * documentation for details on the use of this attribute.
390      *
391      * @return the value of the attribute {@code onfocus} or an empty string if that attribute isn't defined
392      */
393     public final String getOnFocusAttribute() {
394         return getAttributeDirect("onfocus");
395     }
396 
397     /**
398      * Returns the value of the attribute {@code onblur}. Refer to the
399      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
400      * documentation for details on the use of this attribute.
401      *
402      * @return the value of the attribute {@code onblur} or an empty string if that attribute isn't defined
403      */
404     public final String getOnBlurAttribute() {
405         return getAttributeDirect("onblur");
406     }
407 
408     /**
409      * Returns the value of the attribute {@code onselect}. Refer to the
410      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
411      * documentation for details on the use of this attribute.
412      *
413      * @return the value of the attribute {@code onselect} or an empty string if that attribute isn't defined
414      */
415     public final String getOnSelectAttribute() {
416         return getAttributeDirect("onselect");
417     }
418 
419     /**
420      * Returns the value of the attribute {@code onchange}. Refer to the
421      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
422      * documentation for details on the use of this attribute.
423      *
424      * @return the value of the attribute {@code onchange} or an empty string if that attribute isn't defined
425      */
426     public final String getOnChangeAttribute() {
427         return getAttributeDirect("onchange");
428     }
429 
430     /**
431      * {@inheritDoc}
432      */
433     @Override
434     public void select() {
435         selectionDelegate_.select();
436     }
437 
438     /**
439      * {@inheritDoc}
440      */
441     @Override
442     public String getSelectedText() {
443         return selectionDelegate_.getSelectedText();
444     }
445 
446     /**
447      * {@inheritDoc}
448      */
449     @Override
450     public int getSelectionStart() {
451         return selectionDelegate_.getSelectionStart();
452     }
453 
454     /**
455      * {@inheritDoc}
456      */
457     @Override
458     public void setSelectionStart(final int selectionStart) {
459         selectionDelegate_.setSelectionStart(selectionStart);
460     }
461 
462     /**
463      * {@inheritDoc}
464      */
465     @Override
466     public int getSelectionEnd() {
467         return selectionDelegate_.getSelectionEnd();
468     }
469 
470     /**
471      * {@inheritDoc}
472      */
473     @Override
474     public void setSelectionEnd(final int selectionEnd) {
475         selectionDelegate_.setSelectionEnd(selectionEnd);
476     }
477 
478     /**
479      * {@inheritDoc}
480      */
481     @Override
482     protected boolean printXml(final String indent, final boolean indentBefore, final PrintWriter printWriter) {
483         printWriter.print(indent + "<");
484         printOpeningTagContentAsXml(printWriter);
485 
486         printWriter.print(">");
487         printWriter.print(StringUtils.escapeXml(getText()));
488         printWriter.print("</textarea>");
489         return true;
490     }
491 
492     /**
493      * {@inheritDoc}
494      */
495     @Override
496     protected void doType(final char c, final boolean lastType) {
497         // like in the browsers, the value uses line feeds only; a typed '\r' (the enter key)
498         // inserts a line feed and a '\r\n' sequence inserts a single one
499         if (c == '\n' && lastTypedCarriageReturn_) {
500             lastTypedCarriageReturn_ = false;
501             return;
502         }
503         lastTypedCarriageReturn_ = c == '\r';
504         doTypeProcessor_.doType(getText(), selectionDelegate_, lastTypedCarriageReturn_ ? '\n' : c, this, lastType);
505     }
506 
507     /**
508      * {@inheritDoc}
509      */
510     @Override
511     protected void doType(final int keyCode, final boolean lastType) {
512         lastTypedCarriageReturn_ = false;
513         doTypeProcessor_.doType(getText(), selectionDelegate_, keyCode, this, lastType);
514     }
515 
516     /**
517      * {@inheritDoc}
518      */
519     @Override
520     protected void typeDone(final String newValue, final boolean notifyAttributeChangeListeners) {
521         setTextInternal(newValue);
522     }
523 
524     /**
525      * {@inheritDoc}
526      */
527     @Override
528     protected boolean acceptChar(final char c) {
529         return super.acceptChar(c) || c == '\n' || c == '\r';
530     }
531 
532     /**
533      * {@inheritDoc}
534      */
535     @Override
536     public void focus() {
537         super.focus();
538         valueAtFocus_ = getText();
539     }
540 
541     /**
542      * {@inheritDoc}
543      */
544     @Override
545     public void removeFocus() {
546         super.removeFocus();
547         if (valueAtFocus_ != null && !valueAtFocus_.equals(getText())) {
548             HtmlInput.executeOnChangeHandlerIfAppropriate(this);
549         }
550         valueAtFocus_ = null;
551     }
552 
553     /**
554      * Sets the {@code readOnly} attribute.
555      *
556      * @param isReadOnly {@code true} if this element is read only
557      */
558     public void setReadOnly(final boolean isReadOnly) {
559         if (isReadOnly) {
560             setAttribute(ATTRIBUTE_READONLY, "");
561         }
562         else {
563             removeAttribute(ATTRIBUTE_READONLY);
564         }
565     }
566 
567     /**
568      * Returns {@code true} if this element is read only.
569      * @return {@code true} if this element is read only
570      */
571     public boolean isReadOnly() {
572         return hasAttribute(ATTRIBUTE_READONLY);
573     }
574 
575     /**
576      * {@inheritDoc}
577      */
578     @Override
579     public DisplayStyle getDefaultStyleDisplay() {
580         return DisplayStyle.INLINE_BLOCK;
581     }
582 
583     /**
584      * Returns the value of the {@code placeholder} attribute.
585      *
586      * @return the value of the {@code placeholder} attribute
587      */
588     public String getPlaceholder() {
589         return getAttributeDirect("placeholder");
590     }
591 
592     /**
593      * Sets the {@code placeholder} attribute.
594      *
595      * @param placeholder the {@code placeholder} attribute
596      */
597     public void setPlaceholder(final String placeholder) {
598         setAttribute("placeholder", placeholder);
599     }
600 
601     /**
602      * {@inheritDoc}
603      */
604     @Override
605     protected boolean isRequiredSupported() {
606         return true;
607     }
608 
609     /**
610      * {@inheritDoc}
611      */
612     @Override
613     public DomNode cloneNode(final boolean deep) {
614         final HtmlTextArea newnode = (HtmlTextArea) super.cloneNode(deep);
615         newnode.selectionDelegate_ = new SelectableTextSelectionDelegate(newnode);
616         newnode.doTypeProcessor_ = new DoTypeProcessor(newnode);
617 
618         return newnode;
619     }
620 
621     /**
622      * {@inheritDoc}
623      */
624     @Override
625     public boolean willValidate() {
626         return !isDisabled() && !isReadOnly();
627     }
628 
629     /**
630      * {@inheritDoc}
631      */
632     @Override
633     public String getCustomValidity() {
634         return customValidity_;
635     }
636 
637     /**
638      * {@inheritDoc}
639      */
640     @Override
641     public void setCustomValidity(final String message) {
642         customValidity_ = message;
643     }
644 
645     /**
646      * {@inheritDoc}
647      */
648     @Override
649     public boolean isValid() {
650         return isValidValidityState();
651     }
652 
653     /**
654      * {@inheritDoc}
655      */
656     @Override
657     public boolean isCustomErrorValidityState() {
658         return !StringUtils.isEmptyOrNull(customValidity_);
659     }
660 
661     @Override
662     public boolean isValidValidityState() {
663         return !isCustomErrorValidityState()
664                 && !isValueMissingValidityState();
665     }
666 
667     /**
668      * {@inheritDoc}
669      */
670     @Override
671     public boolean isValueMissingValidityState() {
672         return ATTRIBUTE_NOT_DEFINED != getAttributeDirect(ATTRIBUTE_REQUIRED)
673                 && getText().isEmpty();
674     }
675 }