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 static org.htmlunit.BrowserVersionFeatures.HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT;
18  import static org.htmlunit.BrowserVersionFeatures.KEYBOARD_EVENT_META_NO_KEYPRESS;
19  import static org.htmlunit.css.CssStyleSheet.ABSOLUTE;
20  import static org.htmlunit.css.CssStyleSheet.FIXED;
21  import static org.htmlunit.css.CssStyleSheet.STATIC;
22  
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.Locale;
27  import java.util.Map;
28  import java.util.Set;
29  
30  import org.htmlunit.ClipboardHandler;
31  import org.htmlunit.ElementNotFoundException;
32  import org.htmlunit.Page;
33  import org.htmlunit.ScriptResult;
34  import org.htmlunit.SgmlPage;
35  import org.htmlunit.WebAssert;
36  import org.htmlunit.WebClient;
37  import org.htmlunit.WebWindow;
38  import org.htmlunit.css.ComputedCssStyleDeclaration;
39  import org.htmlunit.html.impl.SelectableTextInput;
40  import org.htmlunit.javascript.HtmlUnitScriptable;
41  import org.htmlunit.javascript.host.dom.Document;
42  import org.htmlunit.javascript.host.dom.MutationObserver;
43  import org.htmlunit.javascript.host.event.Event;
44  import org.htmlunit.javascript.host.event.EventTarget;
45  import org.htmlunit.javascript.host.event.InputEvent;
46  import org.htmlunit.javascript.host.event.KeyboardEvent;
47  import org.htmlunit.javascript.host.html.HTMLDocument;
48  import org.htmlunit.javascript.host.html.HTMLElement;
49  import org.htmlunit.util.StringUtils;
50  import org.w3c.dom.Attr;
51  import org.w3c.dom.CDATASection;
52  import org.w3c.dom.Comment;
53  import org.w3c.dom.DOMException;
54  import org.w3c.dom.Element;
55  import org.w3c.dom.EntityReference;
56  import org.w3c.dom.Node;
57  import org.w3c.dom.ProcessingInstruction;
58  import org.w3c.dom.Text;
59  
60  /**
61   * An abstract wrapper for HTML elements.
62   *
63   * @author Mike Bowler
64   * @author Mike J. Bresnahan
65   * @author David K. Taylor
66   * @author Christian Sell
67   * @author David D. Kilzer
68   * @author Mike Gallaher
69   * @author Denis N. Antonioli
70   * @author Marc Guillemot
71   * @author Ahmed Ashour
72   * @author Daniel Gredler
73   * @author Dmitri Zoubkov
74   * @author Sudhan Moghe
75   * @author Ronald Brill
76   * @author Frank Danek
77   * @author Ronny Shapiro
78   * @author Lai Quang Duong
79   */
80  public abstract class HtmlElement extends DomElement {
81  
82      /**
83       * Enum for the different display styles.
84       */
85      public enum DisplayStyle {
86          /** Empty string. */
87          EMPTY(""),
88          /** none. */
89          NONE("none"),
90          /** block. */
91          BLOCK("block"),
92          /** contents. */
93          CONTENTS("contents"),
94          /** inline. */
95          INLINE("inline"),
96          /** inline-block. */
97          INLINE_BLOCK("inline-block"),
98          /** list-item. */
99          LIST_ITEM("list-item"),
100         /** table. */
101         TABLE("table"),
102         /** table-cell. */
103         TABLE_CELL("table-cell"),
104         /** table-column. */
105         TABLE_COLUMN("table-column"),
106         /** table-column-group. */
107         TABLE_COLUMN_GROUP("table-column-group"),
108         /** table-row. */
109         TABLE_ROW("table-row"),
110         /** table-row-group. */
111         TABLE_ROW_GROUP("table-row-group"),
112         /** table-header-group. */
113         TABLE_HEADER_GROUP("table-header-group"),
114         /** table-footer-group. */
115         TABLE_FOOTER_GROUP("table-footer-group"),
116         /** table-caption. */
117         TABLE_CAPTION("table-caption"),
118         /** ruby. */
119         RUBY("ruby"),
120         /** ruby-base. */
121         RUBY_BASE("ruby-base"),
122         /** ruby-text-container. */
123         RUBY_TEXT("ruby-text"),
124         /** ruby-text-container. */
125         RUBY_TEXT_CONTAINER("ruby-text-container");
126 
127         private final String value_;
128         DisplayStyle(final String value) {
129             value_ = value;
130         }
131 
132         /**
133          * The string used from js.
134          * @return the value as string
135          */
136         public String value() {
137             return value_;
138         }
139     }
140 
141     /**
142      * Constant indicating that a tab index value is out of bounds (less than <code>0</code> or greater
143      * than <code>32767</code>).
144      *
145      * @see #getTabIndex()
146      */
147     public static final Short TAB_INDEX_OUT_OF_BOUNDS = Short.valueOf(Short.MIN_VALUE);
148 
149     /** Constant 'required'. */
150     protected static final String ATTRIBUTE_REQUIRED = "required";
151     /** Constant 'checked'. */
152     protected static final String ATTRIBUTE_CHECKED = "checked";
153     /** Constant 'hidden'. */
154     protected static final String ATTRIBUTE_HIDDEN = "hidden";
155     /** Constant 'readonly'. */
156     protected static final String ATTRIBUTE_READONLY = "readonly";
157 
158     /**
159      * The HTML void elements (the elements the HTML serialization writes without an end tag).
160      * @see <a href="https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments">
161      *     HTML Living Standard - Serializing HTML fragments</a>
162      */
163     private static final Set<String> VOID_ELEMENTS = Set.of("area", "base", "basefont", "bgsound", "br", "col",
164             "embed", "frame", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr");
165 
166     /** The listeners which are to be notified of attribute changes. */
167     private final List<HtmlAttributeChangeListener> attributeListeners_ = new ArrayList<>();
168 
169     /** The owning form for lost form children. */
170     private HtmlForm owningForm_;
171 
172     private boolean shiftPressed_;
173     private boolean ctrlPressed_;
174     private boolean altPressed_;
175     private boolean metaPressed_;
176 
177     /**
178      * Creates an instance.
179      *
180      * @param qualifiedName the qualified name of the element type to instantiate
181      * @param page the page that contains this element
182      * @param attributes a map ready initialized with the attributes for this element, or
183      *        {@code null}. The map will be stored as is, not copied.
184      */
185     protected HtmlElement(final String qualifiedName, final SgmlPage page,
186             final Map<String, DomAttr> attributes) {
187         this(Html.XHTML_NAMESPACE, qualifiedName, page, attributes);
188     }
189 
190     /**
191      * Creates an instance of a DOM element that can have a namespace.
192      *
193      * @param namespaceURI the URI that identifies an XML namespace
194      * @param qualifiedName the qualified name of the element type to instantiate
195      * @param page the page that contains this element
196      * @param attributes a map ready initialized with the attributes for this element, or
197      *        {@code null}. The map will be stored as is, not copied.
198      */
199     protected HtmlElement(final String namespaceURI, final String qualifiedName, final SgmlPage page,
200             final Map<String, DomAttr> attributes) {
201         super(namespaceURI, qualifiedName, page, attributes);
202     }
203 
204     /**
205      * {@inheritDoc}
206      */
207     @Override
208     protected void setAttributeNS(final String namespaceURI, final String qualifiedName,
209             final String attributeValue, final boolean notifyAttributeChangeListeners,
210             final boolean notifyMutationObservers) {
211 
212         final HtmlPage htmlPage = getHtmlPageOrNull();
213 
214         // TODO: Clean up; this is a hack for HtmlElement living within an XmlPage.
215         if (htmlPage == null) {
216             super.setAttributeNS(namespaceURI, qualifiedName, attributeValue, notifyAttributeChangeListeners,
217                     notifyMutationObservers);
218             return;
219         }
220 
221         final String oldAttributeValue = getAttribute(qualifiedName);
222         final boolean mappedElement = isAttachedToPage()
223                 && (DomElement.NAME_ATTRIBUTE.equals(qualifiedName) || DomElement.ID_ATTRIBUTE.equals(qualifiedName));
224         if (mappedElement) {
225             // cast is safe here because isMappedElement checks for HtmlPage
226             htmlPage.removeMappedElement(this, false, false);
227         }
228 
229         final HtmlAttributeChangeEvent event;
230         if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
231             event = new HtmlAttributeChangeEvent(this, qualifiedName, attributeValue);
232         }
233         else {
234             event = new HtmlAttributeChangeEvent(this, qualifiedName, oldAttributeValue);
235         }
236 
237         super.setAttributeNS(namespaceURI, qualifiedName, attributeValue, notifyAttributeChangeListeners,
238                 notifyMutationObservers);
239 
240         if (notifyAttributeChangeListeners) {
241             notifyAttributeChangeListeners(event, this, oldAttributeValue, notifyMutationObservers);
242         }
243 
244         fireAttributeChangeImpl(event, htmlPage, mappedElement, oldAttributeValue);
245     }
246 
247     /**
248      * Recursively notifies all {@link HtmlAttributeChangeListener}s.
249      * @param event the event
250      * @param element the element
251      * @param oldAttributeValue the old attribute value
252      * @param notifyMutationObservers whether to notify {@link MutationObserver}s or not
253      */
254     protected static void notifyAttributeChangeListeners(final HtmlAttributeChangeEvent event,
255             final HtmlElement element, final String oldAttributeValue, final boolean notifyMutationObservers) {
256         final List<HtmlAttributeChangeListener> listeners = new ArrayList<>(element.attributeListeners_);
257         if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
258             synchronized (listeners) {
259                 for (final HtmlAttributeChangeListener listener : listeners) {
260                     if (notifyMutationObservers || !(listener instanceof MutationObserver)) {
261                         listener.attributeAdded(event);
262                     }
263                 }
264             }
265         }
266         else {
267             synchronized (listeners) {
268                 for (final HtmlAttributeChangeListener listener : listeners) {
269                     if (notifyMutationObservers || !(listener instanceof MutationObserver)) {
270                         listener.attributeReplaced(event);
271                     }
272                 }
273             }
274         }
275 
276         final DomNode parentNode = element.getParentNode();
277         if (parentNode instanceof HtmlElement htmlElement) {
278             notifyAttributeChangeListeners(event, htmlElement, oldAttributeValue, notifyMutationObservers);
279         }
280     }
281 
282     private void fireAttributeChangeImpl(final HtmlAttributeChangeEvent event,
283             final HtmlPage htmlPage, final boolean mappedElement, final String oldAttributeValue) {
284         if (mappedElement) {
285             htmlPage.addMappedElement(this, false);
286         }
287 
288         if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
289             fireHtmlAttributeAdded(event);
290             htmlPage.fireHtmlAttributeAdded(event);
291         }
292         else {
293             fireHtmlAttributeReplaced(event);
294             htmlPage.fireHtmlAttributeReplaced(event);
295         }
296     }
297 
298     /**
299      * Sets the specified attribute. This method may be overridden by subclasses
300      * which are interested in specific attribute value changes, but such methods <b>must</b>
301      * invoke <code>super.setAttributeNode()</code>, and <b>should</b> consider the value of the
302      * <code>cloning</code> parameter when deciding whether or not to execute custom logic.
303      *
304      * @param attribute the attribute to set
305      * @return {@inheritDoc}
306      */
307     @Override
308     public Attr setAttributeNode(final Attr attribute) {
309         final HtmlPage htmlPage = getHtmlPageOrNull();
310 
311         // TODO: Clean up; this is a hack for HtmlElement living within an XmlPage.
312         if (htmlPage == null) {
313             return super.setAttributeNode(attribute);
314         }
315 
316         final String qualifiedName = attribute.getName();
317         final String oldAttributeValue = getAttribute(qualifiedName);
318 
319         final boolean mappedElement = isAttachedToPage()
320                 && (DomElement.NAME_ATTRIBUTE.equals(qualifiedName)
321                         || DomElement.ID_ATTRIBUTE.equals(qualifiedName));
322         if (mappedElement) {
323             htmlPage.removeMappedElement(this, false, false);
324         }
325 
326         final HtmlAttributeChangeEvent event;
327         if (ATTRIBUTE_NOT_DEFINED == oldAttributeValue) {
328             event = new HtmlAttributeChangeEvent(this, qualifiedName, attribute.getValue());
329         }
330         else {
331             event = new HtmlAttributeChangeEvent(this, qualifiedName, oldAttributeValue);
332         }
333         notifyAttributeChangeListeners(event, this, oldAttributeValue, true);
334 
335         final Attr result = super.setAttributeNode(attribute);
336 
337         fireAttributeChangeImpl(event, htmlPage, mappedElement, oldAttributeValue);
338 
339         return result;
340     }
341 
342     /**
343      * Removes an attribute specified by name from this element.
344      * @param attributeName the attribute attributeName
345      */
346     @Override
347     public void removeAttribute(final String attributeName) {
348         final String value = getAttribute(attributeName);
349         if (ATTRIBUTE_NOT_DEFINED == value) {
350             return;
351         }
352 
353         final HtmlPage htmlPage = getHtmlPageOrNull();
354 
355         // TODO: Clean up; this is a hack for HtmlElement living within an XmlPage.
356         if (htmlPage == null) {
357             super.removeAttribute(attributeName);
358             return;
359         }
360 
361         final boolean mapped = DomElement.NAME_ATTRIBUTE.equals(attributeName)
362                                 || DomElement.ID_ATTRIBUTE.equals(attributeName);
363         if (mapped) {
364             htmlPage.removeMappedElement(this, false, false);
365         }
366 
367         super.removeAttribute(attributeName);
368 
369         if (mapped) {
370             htmlPage.addMappedElement(this, false);
371         }
372 
373         final HtmlAttributeChangeEvent event = new HtmlAttributeChangeEvent(this, attributeName, value);
374         fireHtmlAttributeRemoved(event);
375         htmlPage.fireHtmlAttributeRemoved(event);
376     }
377 
378     /**
379      * Support for reporting HTML attribute changes. This method can be called when an attribute
380      * has been added, and it will send the appropriate {@link HtmlAttributeChangeEvent} to any
381      * registered {@link HtmlAttributeChangeListener}s.
382      * <p>
383      * Note that this method recursively calls this element's parent's
384      * {@link #fireHtmlAttributeAdded(HtmlAttributeChangeEvent)} method.
385      * </p>
386      *
387      * @param event the event
388      * @see #addHtmlAttributeChangeListener(HtmlAttributeChangeListener)
389      */
390     protected void fireHtmlAttributeAdded(final HtmlAttributeChangeEvent event) {
391         final DomNode parentNode = getParentNode();
392         if (parentNode instanceof HtmlElement element) {
393             element.fireHtmlAttributeAdded(event);
394         }
395     }
396 
397     /**
398      * Support for reporting HTML attribute changes. This method can be called when an attribute
399      * has been replaced, and it will send the appropriate {@link HtmlAttributeChangeEvent} to any
400      * registered {@link HtmlAttributeChangeListener}s.
401      * <p>
402      * Note that this method recursively calls this element's parent's
403      * {@link #fireHtmlAttributeReplaced(HtmlAttributeChangeEvent)} method.
404      * </p>
405      *
406      * @param event the event
407      * @see #addHtmlAttributeChangeListener(HtmlAttributeChangeListener)
408      */
409     protected void fireHtmlAttributeReplaced(final HtmlAttributeChangeEvent event) {
410         final DomNode parentNode = getParentNode();
411         if (parentNode instanceof HtmlElement element) {
412             element.fireHtmlAttributeReplaced(event);
413         }
414     }
415 
416     /**
417      * Support for reporting HTML attribute changes. This method can be called when an attribute
418      * has been removed, and it will send the appropriate {@link HtmlAttributeChangeEvent} to any
419      * registered {@link HtmlAttributeChangeListener}s.
420      * <p>
421      * Note that this method recursively calls this element's parent's
422      * {@link #fireHtmlAttributeRemoved(HtmlAttributeChangeEvent)} method.
423      * </p>
424      *
425      * @param event the event
426      * @see #addHtmlAttributeChangeListener(HtmlAttributeChangeListener)
427      */
428     protected void fireHtmlAttributeRemoved(final HtmlAttributeChangeEvent event) {
429         synchronized (attributeListeners_) {
430             for (final HtmlAttributeChangeListener listener : attributeListeners_) {
431                 listener.attributeRemoved(event);
432             }
433         }
434         final DomNode parentNode = getParentNode();
435         if (parentNode instanceof HtmlElement element) {
436             element.fireHtmlAttributeRemoved(event);
437         }
438     }
439 
440     /**
441      * Returns the same value as returned by {@link #getTagName()}.
442      *
443      * @return the same value as returned by {@link #getTagName()}
444      */
445     @Override
446     public String getNodeName() {
447         final String prefix = getPrefix();
448         if (prefix != null) {
449             // create string builder only if needed (performance)
450             final StringBuilder name = new StringBuilder(prefix.toLowerCase(Locale.ROOT))
451                 .append(':')
452                 .append(getLocalName().toLowerCase(Locale.ROOT));
453             return name.toString();
454         }
455         return getLocalName().toLowerCase(Locale.ROOT);
456     }
457 
458     /**
459      * Returns this element's tab index, if it has one. If the tab index is outside the
460      * valid range (less than <code>0</code> or greater than <code>32767</code>), this method
461      * returns {@link #TAB_INDEX_OUT_OF_BOUNDS}. If this element does not have
462      * a tab index, or its tab index is otherwise invalid, this method returns {@code null}.
463      *
464      * @return this element's tab index
465      */
466     public Short getTabIndex() {
467         final String index = getAttributeDirect("tabindex");
468         if (index == null || index.isEmpty()) {
469             return null;
470         }
471         try {
472             final long l = Long.parseLong(index);
473             if (l >= 0 && l <= Short.MAX_VALUE) {
474                 return Short.valueOf((short) l);
475             }
476             return TAB_INDEX_OUT_OF_BOUNDS;
477         }
478         catch (final NumberFormatException e) {
479             return null;
480         }
481     }
482 
483     /**
484      * Returns the first element with the specified tag name that is an ancestor to this element, or
485      * {@code null} if no such element is found.
486      * @param tagName the name of the tag searched (case insensitive)
487      * @return the first element with the specified tag name that is an ancestor to this element
488      */
489     public HtmlElement getEnclosingElement(final String tagName) {
490         final String tagNameLC = tagName.toLowerCase(Locale.ROOT);
491 
492         for (DomNode currentNode = getParentNode(); currentNode != null; currentNode = currentNode.getParentNode()) {
493             if (currentNode instanceof HtmlElement element && currentNode.getNodeName().equals(tagNameLC)) {
494                 return element;
495             }
496         }
497         return null;
498     }
499 
500     /**
501      * Returns the form which contains this element, or {@code null} if this element is not inside
502      * a form.
503      * @return the form which contains this element
504      */
505     public HtmlForm getEnclosingForm() {
506         final String formId = getAttribute("form");
507         if (ATTRIBUTE_NOT_DEFINED != formId) {
508             final Element formById = getPage().getElementById(formId);
509             if (formById instanceof HtmlForm form) {
510                 return form;
511             }
512             return null;
513         }
514 
515         if (owningForm_ != null) {
516             return owningForm_;
517         }
518         return (HtmlForm) getEnclosingElement("form");
519     }
520 
521     /**
522      * Returns the form which contains this element. If this element is not inside a form, this method
523      * throws an {@link IllegalStateException}.
524      * @return the form which contains this element
525      */
526     public HtmlForm getEnclosingFormOrDie() {
527         final HtmlForm form = getEnclosingForm();
528         if (form == null) {
529             throw new IllegalStateException("Element is not contained within a form: " + this);
530         }
531         return form;
532     }
533 
534     /**
535      * Simulates typing the specified text while this element has focus.
536      * Note that for some elements, typing '\n' submits the enclosed form.
537      * @param text the text you with to simulate typing
538      * @throws IOException If an IO error occurs
539      */
540     public void type(final String text) throws IOException {
541         for (final char ch : text.toCharArray()) {
542             type(ch);
543         }
544     }
545 
546     /**
547      * Simulates typing the specified character while this element has focus, returning the page contained
548      * by this element's window after typing. Note that it may or may not be the same as the original page,
549      * depending on the JavaScript event handlers, etc. Note also that for some elements, typing <code>'\n'</code>
550      * submits the enclosed form.
551      *
552      * @param c the character you wish to simulate typing
553      * @return the page that occupies this window after typing
554      * @throws IOException if an IO error occurs
555      */
556     public Page type(final char c) throws IOException {
557         return type(c, true);
558     }
559 
560     /**
561      * Simulates typing the specified character while this element has focus, returning the page contained
562      * by this element's window after typing. Note that it may or may not be the same as the original page,
563      * depending on the JavaScript event handlers, etc. Note also that for some elements, typing <code>'\n'</code>
564      * submits the enclosed form.
565      *
566      * @param c the character you wish to simulate typing
567      * @param lastType is this the last character to type
568      * @return the page contained in the current window as returned by {@link WebClient#getCurrentWindow()}
569      * @throws IOException if an IO error occurs
570      */
571     private Page type(final char c, final boolean lastType)
572         throws IOException {
573         return typeChar(c, lastType, true, true);
574     }
575 
576     /**
577      * Simulates typing (or only pressing or only releasing the key of) the specified character.
578      *
579      * @param c the character
580      * @param lastType is this the last character to type
581      * @param fireDown whether to press the key (keydown, keypress, typing the char and the input event)
582      * @param fireUp whether to release the key (keyup)
583      * @return the page contained in the current window as returned by {@link WebClient#getCurrentWindow()}
584      * @throws IOException if an IO error occurs
585      */
586     private Page typeChar(final char c, final boolean lastType, final boolean fireDown, final boolean fireUp)
587         throws IOException {
588         if (isDisabledElementAndDisabled()) {
589             return getPage();
590         }
591 
592         // make enclosing window the current one
593         final HtmlPage page = (HtmlPage) getPage();
594         page.getWebClient().setCurrentWindow(page.getEnclosingWindow());
595 
596         if (page.getFocusedElement() != this) {
597             focus();
598         }
599         final WebClient webClient = page.getWebClient();
600 
601         // the implicit shift key is only used if the char is typed completely
602         final boolean isShiftNeeded = fireDown && fireUp && KeyboardEvent.isShiftNeeded(c, shiftPressed_);
603         final boolean shift = shiftPressed_ || isShiftNeeded;
604 
605         final Event shiftDown;
606         final ScriptResult shiftDownResult;
607         if (isShiftNeeded) {
608             shiftDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, KeyboardEvent.DOM_VK_SHIFT,
609                     true, ctrlPressed_, altPressed_);
610             shiftDownResult = fireEvent(shiftDown);
611         }
612         else {
613             shiftDown = null;
614             shiftDownResult = null;
615         }
616 
617         if (fireDown) {
618             final String textBefore = getTextForInputEvent();
619 
620             final Event keyDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, c,
621                                                     shift, ctrlPressed_, altPressed_, metaPressed_);
622             final ScriptResult keyDownResult = fireEvent(keyDown);
623 
624             if (!keyDown.isAborted(keyDownResult)) {
625                 // like in the browsers, there is no keypress if the control key
626                 // (or for some browsers the meta key) is pressed
627                 boolean keyPressAborted = false;
628                 if (!isTypingSuppressedByModifiers()) {
629                     final Event keyPress = new KeyboardEvent(this, Event.TYPE_KEY_PRESS, c,
630                             shift, ctrlPressed_, altPressed_, metaPressed_);
631                     final ScriptResult keyPressResult = fireEvent(keyPress);
632                     keyPressAborted = keyPress.isAborted(keyPressResult);
633                 }
634 
635                 if ((shiftDown == null || !shiftDown.isAborted(shiftDownResult))
636                         && !keyPressAborted) {
637                     doType(c, lastType);
638                 }
639             }
640 
641             if (isTextChanged(textBefore)) {
642                 fireEvent(createInputEvent(c));
643             }
644         }
645 
646         HtmlElement eventSource = this;
647         if (!isAttachedToPage()) {
648             eventSource = page.getBody();
649         }
650 
651         if (fireUp && eventSource != null) {
652             final Event keyUp = new KeyboardEvent(this, Event.TYPE_KEY_UP, c,
653                                                     shift, ctrlPressed_, altPressed_, metaPressed_);
654             eventSource.fireEvent(keyUp);
655 
656             if (isShiftNeeded) {
657                 final Event shiftUp = new KeyboardEvent(this, Event.TYPE_KEY_UP,
658                                         KeyboardEvent.DOM_VK_SHIFT,
659                                         false, ctrlPressed_, altPressed_);
660                 eventSource.fireEvent(shiftUp);
661             }
662         }
663 
664         final HtmlForm form = getEnclosingForm();
665         if (fireDown && form != null && c == '\n' && isSubmittableByEnter()) {
666             for (final DomElement descendant : form.getDomElementDescendants()) {
667                 if (descendant instanceof HtmlSubmitInput) {
668                     return descendant.click();
669                 }
670             }
671 
672             form.submit((SubmittableElement) this);
673 
674             if (webClient.isJavaScriptEnabled()) {
675                 webClient.getJavaScriptEngine().processPostponedActions();
676             }
677         }
678 
679         return webClient.getCurrentWindow().getEnclosedPage();
680     }
681 
682     /**
683      * Simulates typing the specified key code while this element has focus, returning the page contained
684      * by this element's window after typing. Note that it may or may not be the same as the original page,
685      * depending on the JavaScript event handlers, etc.
686      * Note also that for some elements, typing <code>XXXXXXXXXXX</code>
687      * submits the enclosed form.
688      * <p>
689      * An example of predefined values is {@link KeyboardEvent#DOM_VK_PAGE_DOWN}.
690      * </p>
691      *
692      * @param keyCode the key code to simulate typing
693      * @return the page that occupies this window after typing
694      * @throws IOException in case of problems
695      */
696     public Page type(final int keyCode) throws IOException {
697         return type(keyCode, Keyboard.DEFAULT_LOCATION, true, true, true, true);
698     }
699 
700     /**
701      * Simulates typing the specified {@link Keyboard} while this element has focus, returning the page contained
702      * by this element's window after typing. Note that it may or may not be the same as the original page,
703      * depending on the JavaScript event handlers, etc.
704      * Note also that for some elements, typing <code>XXXXXXXXXXX</code>
705      * submits the enclosed form.
706      *
707      * @param keyboard the keyboard
708      * @return the page that occupies this window after typing
709      * @throws IOException if an IO error occurs
710      */
711     public Page type(final Keyboard keyboard) throws IOException {
712         final List<Keyboard.KeyAction> keys = keyboard.getKeys();
713 
714         if (keyboard.isStartAtEnd()) {
715             if (this instanceof SelectableTextInput textInput) {
716                 textInput.setSelectionStart(textInput.getText().length());
717             }
718             else {
719                 final DomText domText = getDoTypeNode();
720                 if (domText != null) {
721                     domText.moveSelectionToEnd();
722                 }
723             }
724         }
725 
726         final boolean[] pressedModifiers = keyboard.getPressedModifiers();
727         if (pressedModifiers != null) {
728             shiftPressed_ = pressedModifiers[0];
729             ctrlPressed_ = pressedModifiers[1];
730             altPressed_ = pressedModifiers[2];
731             metaPressed_ = pressedModifiers[3];
732         }
733 
734         return type(keys);
735     }
736 
737     /**
738      * Simulates typing the specified key actions while this element has focus.
739      * If the tab key moves the focus to another element, the remaining actions are
740      * typed into that element (like in the browsers).
741      *
742      * @param keys the key actions
743      * @return the page that occupies this window after typing
744      * @throws IOException if an IO error occurs
745      */
746     private Page type(final List<Keyboard.KeyAction> keys) throws IOException {
747         Page page = null;
748 
749         final int size = keys.size();
750         int i = 0;
751         for (final Keyboard.KeyAction keyAction : keys) {
752             i++;
753             final boolean lastType = i == size;
754 
755             if (keyAction instanceof Keyboard.TypedChar typedChar) {
756                 page = type(typedChar.ch(), lastType);
757             }
758             else if (keyAction instanceof Keyboard.CharKeyAction charKeyAction) {
759                 page = typeChar(charKeyAction.ch(), lastType, charKeyAction.down(), !charKeyAction.down());
760             }
761             else if (keyAction instanceof Keyboard.KeyCodeKeyAction keyCodeKeyAction) {
762                 final int key = keyCodeKeyAction.keyCode();
763                 final boolean down = keyCodeKeyAction.down();
764                 updateModifiers(key, down);
765                 page = type(key, keyCodeKeyAction.location(), down, down, !down, lastType);
766             }
767             else if (keyAction instanceof Keyboard.KeyCodeAction keyCodeAction) {
768                 final int key = keyCodeAction.keyCode();
769                 final boolean pressed = keyCodeAction.pressed();
770 
771                 if (updateModifiers(key, pressed)) {
772                     page = type(key, Keyboard.DEFAULT_LOCATION, pressed, false, !pressed, lastType);
773                 }
774                 else if (pressed) {
775                     page = type(key, Keyboard.DEFAULT_LOCATION, true, true, true, lastType);
776                 }
777                 else {
778                     page = type(key, Keyboard.DEFAULT_LOCATION, false, false, true, lastType);
779                 }
780             }
781 
782             // the tab key has moved the focus; the remaining keys are typed into the focused element
783             if (i < size && isTabKeyDown(keyAction) && getPage() instanceof HtmlPage htmlPage) {
784                 final DomElement focusedElement = htmlPage.getFocusedElement();
785                 if (focusedElement == null) {
786                     // the focus has left the page (moved to the browser ui); the remaining keys are lost
787                     return page;
788                 }
789                 if (focusedElement instanceof HtmlElement focused && focused != this) {
790                     focused.shiftPressed_ = shiftPressed_;
791                     focused.ctrlPressed_ = ctrlPressed_;
792                     focused.altPressed_ = altPressed_;
793                     focused.metaPressed_ = metaPressed_;
794                     return focused.type(keys.subList(i, size));
795                 }
796             }
797         }
798 
799         return page;
800     }
801 
802     private static boolean isTabKeyDown(final Keyboard.KeyAction keyAction) {
803         if (keyAction instanceof Keyboard.KeyCodeAction keyCodeAction) {
804             return keyCodeAction.keyCode() == KeyboardEvent.DOM_VK_TAB && keyCodeAction.pressed();
805         }
806         if (keyAction instanceof Keyboard.KeyCodeKeyAction keyCodeKeyAction) {
807             return keyCodeKeyAction.keyCode() == KeyboardEvent.DOM_VK_TAB && keyCodeKeyAction.down();
808         }
809         return false;
810     }
811 
812     /**
813      * Moves the focus to the next (or with shift to the previous) element in the tab order,
814      * like the tab key does in the browsers. The whole text of a text input getting the focus is selected.
815      * Tab from the last (shift+tab from the first) element moves the focus out of the page
816      * (in the browsers to the browser ui); no element has the focus afterwards.
817      *
818      * @param page the page
819      * @return the element that has the focus now or {@code null}
820      */
821     private HtmlElement moveFocusByTab(final HtmlPage page) {
822         final List<HtmlElement> tabbableElements = page.getTabbableElements();
823         final int index = tabbableElements.indexOf(this);
824         if (index != -1 && index == (shiftPressed_ ? 0 : tabbableElements.size() - 1)) {
825             page.setFocusedElement(null);
826             return null;
827         }
828 
829         final HtmlElement focused = shiftPressed_ ? page.tabToPreviousElement() : page.tabToNextElement();
830         if (focused instanceof HtmlInput && focused instanceof SelectableTextInput textInput) {
831             textInput.setSelectionStart(0);
832             textInput.setSelectionEnd(textInput.getText().length());
833         }
834         return focused;
835     }
836 
837     /**
838      * Returns whether the pressed modifier keys suppress the keypress event and the typing of chars;
839      * this is the case if the control key (or for some browsers the meta key) is pressed.
840      *
841      * @return {@code true} if chars are not typed
842      */
843     boolean isTypingSuppressedByModifiers() {
844         return ctrlPressed_
845                 || (metaPressed_ && getPage().getWebClient().getBrowserVersion()
846                                     .hasFeature(KEYBOARD_EVENT_META_NO_KEYPRESS));
847     }
848 
849     /**
850      * Updates the state of the modifier keys.
851      *
852      * @param keyCode the key code of the pressed or released key
853      * @param pressed whether the key is pressed or released
854      * @return {@code true} if the key is a modifier key
855      */
856     private boolean updateModifiers(final int keyCode, final boolean pressed) {
857         switch (keyCode) {
858             case KeyboardEvent.DOM_VK_SHIFT -> shiftPressed_ = pressed;
859             case KeyboardEvent.DOM_VK_CONTROL -> ctrlPressed_ = pressed;
860             case KeyboardEvent.DOM_VK_ALT -> altPressed_ = pressed;
861             case KeyboardEvent.DOM_VK_META, KeyboardEvent.DOM_VK_WIN -> metaPressed_ = pressed;
862             default -> {
863                 return false;
864             }
865         }
866         return true;
867     }
868 
869     private Page type(final int keyCode, final int location,
870                     final boolean fireKeyDown, final boolean fireKeyPress, final boolean fireKeyUp,
871                     final boolean lastType) throws IOException {
872         if (isDisabledElementAndDisabled()) {
873             return getPage();
874         }
875 
876         final HtmlPage page = (HtmlPage) getPage();
877         if (page.getFocusedElement() != this) {
878             focus();
879         }
880 
881         final String textBefore = getTextForInputEvent();
882 
883         final Event keyDown;
884         final ScriptResult keyDownResult;
885         if (fireKeyDown) {
886             keyDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, keyCode, location,
887                     shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
888             keyDownResult = fireEvent(keyDown);
889         }
890         else {
891             keyDown = null;
892             keyDownResult = null;
893         }
894 
895         final Event keyPress;
896         final ScriptResult keyPressResult;
897         if (fireKeyPress && KeyboardEvent.isCharacterKey(keyCode) && !isTypingSuppressedByModifiers()) {
898             keyPress = new KeyboardEvent(this, Event.TYPE_KEY_PRESS, keyCode, location,
899                     shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
900 
901             keyPressResult = fireEvent(keyPress);
902         }
903         else {
904             keyPress = null;
905             keyPressResult = null;
906         }
907 
908         // the element getting the keyup event; the tab key moves the focus before
909         HtmlElement keyUpTarget = this;
910         if (keyDown != null && !keyDown.isAborted(keyDownResult)
911                 && (keyPress == null || !keyPress.isAborted(keyPressResult))) {
912             if (keyCode == KeyboardEvent.DOM_VK_TAB) {
913                 final HtmlElement focused = moveFocusByTab(page);
914                 if (focused != null) {
915                     keyUpTarget = focused;
916                 }
917                 else if (page.getBody() != null) {
918                     keyUpTarget = page.getBody();
919                 }
920             }
921             else {
922                 doType(keyCode, lastType);
923             }
924         }
925 
926         if (isTextChanged(textBefore)) {
927             fireEvent(createInputEvent(keyCode));
928         }
929 
930         if (fireKeyUp) {
931             final Event keyUp = new KeyboardEvent(keyUpTarget, Event.TYPE_KEY_UP, keyCode, location,
932                     shiftPressed_, ctrlPressed_, altPressed_, metaPressed_);
933             keyUpTarget.fireEvent(keyUp);
934         }
935 
936         return page.getWebClient().getCurrentWindow().getEnclosedPage();
937     }
938 
939     /**
940      * Creates the input event for a typed char that has changed the text.
941      *
942      * @param c the typed char
943      * @return the input event with the {@code inputType} and {@code data} like in the browsers
944      */
945     private InputEvent createInputEvent(final char c) {
946         final String inputType;
947         String data = null;
948         if (c == '\b') {
949             inputType = "deleteContentBackward";
950         }
951         else if (c == '\r' || c == '\n') {
952             inputType = "insertLineBreak";
953         }
954         else if (ctrlPressed_ && (c == 'x' || c == 'X')) {
955             inputType = "deleteByCut";
956         }
957         else if (ctrlPressed_ && (c == 'v' || c == 'V')) {
958             inputType = "insertFromPaste";
959             final ClipboardHandler clipboardHandler = getPage().getWebClient().getClipboardHandler();
960             if (clipboardHandler != null) {
961                 data = clipboardHandler.getClipboardContent();
962             }
963         }
964         else {
965             inputType = "insertText";
966             data = String.valueOf(c);
967         }
968         return new InputEvent(this, Event.TYPE_INPUT, inputType, data);
969     }
970 
971     /**
972      * Creates the input event for a typed key that has changed the text.
973      *
974      * @param keyCode the key code of the typed key
975      * @return the input event with the {@code inputType} and {@code data} like in the browsers
976      */
977     private InputEvent createInputEvent(final int keyCode) {
978         final String inputType;
979         String data = null;
980         if (keyCode == KeyboardEvent.DOM_VK_BACK_SPACE) {
981             inputType = ctrlPressed_ ? "deleteWordBackward" : "deleteContentBackward";
982         }
983         else if (keyCode == KeyboardEvent.DOM_VK_DELETE) {
984             inputType = ctrlPressed_ ? "deleteWordForward" : "deleteContentForward";
985         }
986         else if (keyCode == KeyboardEvent.DOM_VK_RETURN) {
987             inputType = "insertLineBreak";
988         }
989         else {
990             inputType = "insertText";
991             final int charCode = KeyboardEvent.getCharCode(keyCode);
992             if (charCode != 0) {
993                 data = String.valueOf((char) charCode);
994             }
995         }
996         return new InputEvent(this, Event.TYPE_INPUT, inputType, data);
997     }
998 
999     /**
1000      * Returns the current text of this element if this is a text control that fires
1001      * input events while typing ({@code input} elements with text and {@code textarea}).
1002      *
1003      * @return the text or {@code null} if this is not such a control
1004      */
1005     private String getTextForInputEvent() {
1006         if (this instanceof SelectableTextInput textInput) {
1007             return textInput.getText();
1008         }
1009         return null;
1010     }
1011 
1012     /**
1013      * Returns whether the text of this text control was changed by typing; like in the browsers,
1014      * the input event is only fired if the text has changed (e.g. not for the arrow keys, if
1015      * the event was canceled or if the maximum length was already reached).
1016      *
1017      * @param textBefore the text before typing (see {@link #getTextForInputEvent()})
1018      * @return whether the text has changed
1019      */
1020     private boolean isTextChanged(final String textBefore) {
1021         return textBefore != null && !textBefore.equals(getTextForInputEvent());
1022     }
1023 
1024     /**
1025      * Performs the effective type action, called after the keyPress event and before the keyUp event.
1026      * @param c the character you with to simulate typing
1027      * @param lastType is this the last character to type
1028      */
1029     protected void doType(final char c, final boolean lastType) {
1030         final DomText domText = getDoTypeNode();
1031         if (domText != null) {
1032             domText.doType(c, this, lastType);
1033         }
1034     }
1035 
1036     /**
1037      * Performs the effective type action, called after the keyPress event and before the keyUp event.
1038      * <p>
1039      * An example of predefined values is {@link KeyboardEvent#DOM_VK_PAGE_DOWN}.
1040      * </p>
1041      *
1042      * @param keyCode the key code wish to simulate typing
1043      * @param lastType is this the last to type
1044      * @throws IOException in case of problems
1045      */
1046     protected void doType(final int keyCode, final boolean lastType) throws IOException {
1047         final DomText domText = getDoTypeNode();
1048         if (domText != null) {
1049             domText.doType(keyCode, this, lastType);
1050         }
1051     }
1052 
1053     /**
1054      * Returns the node to type into.
1055      * @return the node
1056      */
1057     private DomText getDoTypeNode() {
1058         final HTMLElement scriptElement = getScriptableObject();
1059         if (scriptElement.isIsContentEditable()
1060                 || "on".equals(((Document) scriptElement.getOwnerDocument()).getDesignMode())) {
1061 
1062             DomNode node = this;
1063             while (node.getLastChild() != null) {
1064                 node = node.getLastChild();
1065             }
1066 
1067             if (node instanceof DomText text) {
1068                 return text;
1069             }
1070 
1071             final DomText domText = new DomText(getPage(), "");
1072             appendChild(domText);
1073             return domText;
1074         }
1075         return null;
1076     }
1077 
1078     /**
1079      * Called from {@link DoTypeProcessor}.
1080      * @param newValue the new value
1081      * @param notifyAttributeChangeListeners to notify the associated {@link HtmlAttributeChangeListener}s
1082      */
1083     protected void typeDone(final String newValue, final boolean notifyAttributeChangeListeners) {
1084         // nothing
1085     }
1086 
1087     /**
1088      * Indicates if the provided character can be "typed" in the element.
1089      * @param c the character
1090      * @return {@code true} if it is accepted
1091      */
1092     protected boolean acceptChar(final char c) {
1093         // This range is this is private use area
1094         // see http://www.unicode.org/charts/PDF/UE000.pdf
1095         return (c < '\uE000' || c > '\uF8FF')
1096                 && (c == ' ' || c == '\t' || c == '\u3000' || c == '\u2006' || !Character.isWhitespace(c));
1097     }
1098 
1099     /**
1100      * Returns {@code true} if clicking Enter (ASCII 10, or '\n') should submit the enclosed form (if any).
1101      * The default implementation returns {@code false}.
1102      * @return {@code true} if clicking Enter should submit the enclosed form (if any)
1103      */
1104     protected boolean isSubmittableByEnter() {
1105         return false;
1106     }
1107 
1108     /**
1109      * Searches for an element based on the specified criteria, returning the first element which matches
1110      * said criteria. Only elements which are descendants of this element are included in the search.
1111      *
1112      * @param elementName the name of the element to search for
1113      * @param attributeName the name of the attribute to search for
1114      * @param attributeValue the value of the attribute to search for
1115      * @param <E> the sub-element type
1116      * @return the first element which matches the specified search criteria
1117      * @throws ElementNotFoundException if no element matches the specified search criteria
1118      */
1119     public final <E extends HtmlElement> E getOneHtmlElementByAttribute(final String elementName,
1120             final String attributeName,
1121         final String attributeValue) throws ElementNotFoundException {
1122 
1123         WebAssert.notNull("elementName", elementName);
1124         WebAssert.notNull("attributeName", attributeName);
1125         WebAssert.notNull("attributeValue", attributeValue);
1126 
1127         final List<E> list = getElementsByAttribute(elementName, attributeName, attributeValue);
1128 
1129         if (list.isEmpty()) {
1130             throw new ElementNotFoundException(elementName, attributeName, attributeValue);
1131         }
1132 
1133         return list.get(0);
1134     }
1135 
1136     /**
1137      * Returns all elements which are descendants of this element and match the specified search criteria.
1138      *
1139      * @param elementName the name of the element to search for
1140      * @param attributeName the name of the attribute to search for
1141      * @param attributeValue the value of the attribute to search for
1142      * @param <E> the sub-element type
1143      * @return all elements which are descendants of this element and match the specified search criteria
1144      */
1145     @SuppressWarnings("unchecked")
1146     public final <E extends HtmlElement> List<E> getElementsByAttribute(
1147             final String elementName,
1148             final String attributeName,
1149             final String attributeValue) {
1150 
1151         final List<E> list = new ArrayList<>();
1152         final String lowerCaseTagName = elementName.toLowerCase(Locale.ROOT);
1153 
1154         for (final HtmlElement next : getHtmlElementDescendants()) {
1155             if (next.getTagName().equals(lowerCaseTagName)) {
1156                 final String attValue = next.getAttribute(attributeName);
1157                 if (attValue.equals(attributeValue)) {
1158                     list.add((E) next);
1159                 }
1160             }
1161         }
1162         return list;
1163     }
1164 
1165     /**
1166      * Appends a child element to this HTML element with the specified tag name
1167      * if this HTML element does not already have a child with that tag name.
1168      * Returns the appended child element, or the first existent child element
1169      * with the specified tag name if none was appended.
1170      * @param tagName the tag name of the child to append
1171      * @return the added child, or the first existing child if none was added
1172      */
1173     public final HtmlElement appendChildIfNoneExists(final String tagName) {
1174         final HtmlElement child;
1175         final List<HtmlElement> children = getStaticElementsByTagName(tagName);
1176         if (children.isEmpty()) {
1177             // Add a new child and return it.
1178             child = (HtmlElement) ((HtmlPage) getPage()).createElement(tagName);
1179             appendChild(child);
1180         }
1181         else {
1182             // Return the first existing child.
1183             child = children.get(0);
1184         }
1185         return child;
1186     }
1187 
1188     /**
1189      * Removes the <code>i</code>th child element with the specified tag name
1190      * from all relationships, if possible.
1191      * @param tagName the tag name of the child to remove
1192      * @param i the index of the child to remove
1193      */
1194     public final void removeChild(final String tagName, final int i) {
1195         final List<HtmlElement> children = getStaticElementsByTagName(tagName);
1196         if (i >= 0 && i < children.size()) {
1197             children.get(i).remove();
1198         }
1199     }
1200 
1201     /**
1202      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1203      * Returns {@code true} if this element has any JavaScript functions that need to be executed when the
1204      * specified event occurs.
1205      * @param eventName the name of the event, such as "onclick" or "onblur", etc
1206      * @return true if an event handler has been defined otherwise false
1207      */
1208     public final boolean hasEventHandlers(final String eventName) {
1209         if (getPage().getWebClient().isJavaScriptEngineEnabled()) {
1210             final HtmlUnitScriptable jsObj = getScriptableObject();
1211             if (jsObj instanceof EventTarget target) {
1212                 return target.hasEventHandlers(eventName);
1213             }
1214         }
1215         return false;
1216     }
1217 
1218     /**
1219      * Adds an HtmlAttributeChangeListener to the listener list.
1220      * The listener is registered for all attributes of this HtmlElement,
1221      * as well as descendant elements.
1222      *
1223      * @param listener the attribute change listener to be added
1224      * @see #removeHtmlAttributeChangeListener(HtmlAttributeChangeListener)
1225      */
1226     public void addHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
1227         WebAssert.notNull("listener", listener);
1228         synchronized (attributeListeners_) {
1229             attributeListeners_.add(listener);
1230         }
1231     }
1232 
1233     /**
1234      * Removes an HtmlAttributeChangeListener from the listener list.
1235      * This method should be used to remove HtmlAttributeChangeListener that were registered
1236      * for all attributes of this HtmlElement, as well as descendant elements.
1237      *
1238      * @param listener the attribute change listener to be removed
1239      * @see #addHtmlAttributeChangeListener(HtmlAttributeChangeListener)
1240      */
1241     public void removeHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
1242         WebAssert.notNull("listener", listener);
1243         synchronized (attributeListeners_) {
1244             attributeListeners_.remove(listener);
1245         }
1246     }
1247 
1248     /**
1249      * {@inheritDoc}
1250      */
1251     @Override
1252     protected void checkChildHierarchy(final Node childNode) throws DOMException {
1253         if (!((childNode instanceof Element) || (childNode instanceof Text)
1254             || (childNode instanceof Comment) || (childNode instanceof ProcessingInstruction)
1255             || (childNode instanceof CDATASection) || (childNode instanceof EntityReference))) {
1256             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
1257                 "The Element may not have a child of this type: " + childNode.getNodeType());
1258         }
1259         super.checkChildHierarchy(childNode);
1260     }
1261 
1262     /**
1263      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1264      *
1265      * Allows the parser to connect to a form that is not a parent of this due to malformed HTML code
1266      * @param form the owning form
1267      */
1268     public void setOwningForm(final HtmlForm form) {
1269         owningForm_ = form;
1270     }
1271 
1272     /**
1273      * Indicates if the attribute names are case sensitive.
1274      * @return {@code false}
1275      */
1276     @Override
1277     protected boolean isAttributeCaseSensitive() {
1278         return false;
1279     }
1280 
1281     /**
1282      * {@inheritDoc}
1283      * An HTML parser does not close a non-void element at "/&gt;".
1284      * @return {@code true} for non-void elements in the HTML namespace
1285      */
1286     @Override
1287     protected boolean isEmptyXmlTagExpanded() {
1288         return Html.XHTML_NAMESPACE.equals(getNamespaceURI())
1289                 && !isVoidElement(getLowercaseName());
1290     }
1291 
1292     /**
1293      * Returns whether the given local name is the name of one of the HTML void elements
1294      * (the elements written without an end tag, e.g. {@code br} or {@code img}).
1295      * The check is case-sensitive; the void element names are lower case.
1296      *
1297      * @param localName the local name of the element
1298      * @return {@code true} if the name is the name of a void element
1299      */
1300     public static boolean isVoidElement(final String localName) {
1301         return VOID_ELEMENTS.contains(localName);
1302     }
1303 
1304     /**
1305      * Returns the value of the attribute {@code lang}. Refer to the
1306      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1307      * documentation for details on the use of this attribute.
1308      *
1309      * @return the value of the attribute {@code lang} or an empty string if that attribute isn't defined
1310      */
1311     public final String getLangAttribute() {
1312         return getAttributeDirect("lang");
1313     }
1314 
1315     /**
1316      * Returns the value of the attribute {@code xml:lang}. Refer to the
1317      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1318      * documentation for details on the use of this attribute.
1319      *
1320      * @return the value of the attribute {@code xml:lang} or an empty string if that attribute isn't defined
1321      */
1322     public final String getXmlLangAttribute() {
1323         return getAttribute("xml:lang");
1324     }
1325 
1326     /**
1327      * Returns the value of the attribute {@code dir}. Refer to the
1328      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1329      * documentation for details on the use of this attribute.
1330      *
1331      * @return the value of the attribute {@code dir} or an empty string if that attribute isn't defined
1332      */
1333     public final String getTextDirectionAttribute() {
1334         return getAttributeDirect("dir");
1335     }
1336 
1337     /**
1338      * Returns the value of the attribute {@code onclick}. Refer to the
1339      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1340      * documentation for details on the use of this attribute.
1341      *
1342      * @return the value of the attribute {@code onclick} or an empty string if that attribute isn't defined
1343      */
1344     public final String getOnClickAttribute() {
1345         return getAttributeDirect("onclick");
1346     }
1347 
1348     /**
1349      * Returns the value of the attribute {@code ondblclick}. Refer to the
1350      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1351      * documentation for details on the use of this attribute.
1352      *
1353      * @return the value of the attribute {@code ondblclick} or an empty string if that attribute isn't defined
1354      */
1355     public final String getOnDblClickAttribute() {
1356         return getAttributeDirect("ondblclick");
1357     }
1358 
1359     /**
1360      * Returns the value of the attribute {@code onmousedown}. Refer to the
1361      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1362      * documentation for details on the use of this attribute.
1363      *
1364      * @return the value of the attribute {@code onmousedown} or an empty string if that attribute isn't defined
1365      */
1366     public final String getOnMouseDownAttribute() {
1367         return getAttributeDirect("onmousedown");
1368     }
1369 
1370     /**
1371      * Returns the value of the attribute {@code onmouseup}. Refer to the
1372      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1373      * documentation for details on the use of this attribute.
1374      *
1375      * @return the value of the attribute {@code onmouseup} or an empty string if that attribute isn't defined
1376      */
1377     public final String getOnMouseUpAttribute() {
1378         return getAttributeDirect("onmouseup");
1379     }
1380 
1381     /**
1382      * Returns the value of the attribute {@code onmouseover}. Refer to the
1383      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1384      * documentation for details on the use of this attribute.
1385      *
1386      * @return the value of the attribute {@code onmouseover} or an empty string if that attribute isn't defined
1387      */
1388     public final String getOnMouseOverAttribute() {
1389         return getAttributeDirect("onmouseover");
1390     }
1391 
1392     /**
1393      * Returns the value of the attribute {@code onmousemove}. Refer to the
1394      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1395      * documentation for details on the use of this attribute.
1396      *
1397      * @return the value of the attribute {@code onmousemove} or an empty string if that attribute isn't defined
1398      */
1399     public final String getOnMouseMoveAttribute() {
1400         return getAttributeDirect("onmousemove");
1401     }
1402 
1403     /**
1404      * Returns the value of the attribute {@code onmouseout}. Refer to the
1405      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1406      * documentation for details on the use of this attribute.
1407      *
1408      * @return the value of the attribute {@code onmouseout} or an empty string if that attribute isn't defined
1409      */
1410     public final String getOnMouseOutAttribute() {
1411         return getAttributeDirect("onmouseout");
1412     }
1413 
1414     /**
1415      * Returns the value of the attribute {@code onkeypress}. Refer to the
1416      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1417      * documentation for details on the use of this attribute.
1418      *
1419      * @return the value of the attribute {@code onkeypress} or an empty string if that attribute isn't defined
1420      */
1421     public final String getOnKeyPressAttribute() {
1422         return getAttributeDirect("onkeypress");
1423     }
1424 
1425     /**
1426      * Returns the value of the attribute {@code onkeydown}. Refer to the
1427      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1428      * documentation for details on the use of this attribute.
1429      *
1430      * @return the value of the attribute {@code onkeydown} or an empty string if that attribute isn't defined
1431      */
1432     public final String getOnKeyDownAttribute() {
1433         return getAttributeDirect("onkeydown");
1434     }
1435 
1436     /**
1437      * Returns the value of the attribute {@code onkeyup}. Refer to the
1438      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
1439      * documentation for details on the use of this attribute.
1440      *
1441      * @return the value of the attribute {@code onkeyup} or an empty string if that attribute isn't defined
1442      */
1443     public final String getOnKeyUpAttribute() {
1444         return getAttributeDirect("onkeyup");
1445     }
1446 
1447     /**
1448      * {@inheritDoc}
1449      */
1450     @Override
1451     public String getCanonicalXPath() {
1452         final DomNode parent = getParentNode();
1453         if (parent.getNodeType() == DOCUMENT_NODE) {
1454             return "/" + getNodeName();
1455         }
1456         return parent.getCanonicalXPath() + '/' + getXPathToken();
1457     }
1458 
1459     /**
1460      * Returns the XPath token for this node only.
1461      */
1462     private String getXPathToken() {
1463         final DomNode parent = getParentNode();
1464         int total = 0;
1465         int nodeIndex = 0;
1466         for (final DomNode child : parent.getChildren()) {
1467             if (child.getNodeType() == ELEMENT_NODE && child.getNodeName().equals(getNodeName())) {
1468                 total++;
1469             }
1470             if (child == this) {
1471                 nodeIndex = total;
1472             }
1473         }
1474 
1475         if (nodeIndex == 1 && total == 1) {
1476             return getNodeName();
1477         }
1478         return getNodeName() + '[' + nodeIndex + ']';
1479     }
1480 
1481     /**
1482      * Returns the value of the 'hidden' attribute or an empty string if not set.
1483      *
1484      * @return the value of the 'hidden' attribute or an empty string if not set.
1485      */
1486     public String getHidden() {
1487         return getAttributeDirect(ATTRIBUTE_HIDDEN);
1488     }
1489 
1490     /**
1491      * Returns true if the hidden attribute is set.
1492      *
1493      * @return true if the hidden attribute is set.
1494      */
1495     public boolean isHidden() {
1496         return ATTRIBUTE_NOT_DEFINED != getAttributeDirect(ATTRIBUTE_HIDDEN);
1497     }
1498 
1499     /**
1500      * Sets the {@code hidden} property.
1501      * If the provided string is empty, the 'hidden' attribute will be removed.
1502      * If the provided string is 'until-found' then the attribute value will be 'until-found'.
1503      * For all other provided strings the attribute will be set to ''.
1504      * @see #setHidden(boolean)
1505      * @param hidden the {@code hidden} property
1506      */
1507     public void setHidden(final String hidden) {
1508         if ("until-found".equalsIgnoreCase(hidden)) {
1509             setAttribute(ATTRIBUTE_HIDDEN, "until-found");
1510             return;
1511         }
1512 
1513         if (StringUtils.isEmptyString(hidden)) {
1514             removeAttribute(ATTRIBUTE_HIDDEN);
1515             return;
1516         }
1517 
1518         setAttribute(ATTRIBUTE_HIDDEN, "");
1519     }
1520 
1521     /**
1522      * Sets the {@code hidden} property.
1523      * @param hidden the {@code hidden} property
1524      */
1525     public void setHidden(final boolean hidden) {
1526         if (hidden) {
1527             setAttribute(ATTRIBUTE_HIDDEN, "");
1528             return;
1529         }
1530 
1531         removeAttribute(ATTRIBUTE_HIDDEN);
1532     }
1533 
1534     /**
1535      * {@inheritDoc}
1536      * Overwritten to support the hidden attribute (html5).
1537      */
1538     @Override
1539     public boolean isDisplayed() {
1540         // if css is enabled, the hidden attribute is handled by the computed display style
1541         if (isHidden() && !getPage().getWebClient().getOptions().isCssEnabled()) {
1542             return false;
1543         }
1544         return super.isDisplayed();
1545     }
1546 
1547     /**
1548      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1549      *
1550      * Returns the default display style.
1551      *
1552      * @return the default display style
1553      */
1554     public DisplayStyle getDefaultStyleDisplay() {
1555         return DisplayStyle.BLOCK;
1556     }
1557 
1558     /**
1559      * Helper for src retrieval and normalization.
1560      *
1561      * @return the value of the attribute {@code src} with all line breaks removed
1562      *         or an empty string if that attribute isn't defined.
1563      */
1564     protected final String getSrcAttributeNormalized() {
1565         final String attrib = getAttributeDirect(SRC_ATTRIBUTE);
1566         if (ATTRIBUTE_NOT_DEFINED == attrib) {
1567             return attrib;
1568         }
1569 
1570         return StringUtils.replaceChars(attrib, "\r\n", "");
1571     }
1572 
1573     /**
1574      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1575      *
1576      * Detach this node from all relationships with other nodes.
1577      * This is the first step of a move.
1578      */
1579     @Override
1580     protected void detach() {
1581         final SgmlPage page = getPage();
1582         if (!page.getWebClient().isJavaScriptEngineEnabled()) {
1583             super.detach();
1584             return;
1585         }
1586 
1587         final HtmlUnitScriptable document = page.getScriptableObject();
1588 
1589         if (document instanceof HTMLDocument doc) {
1590             final Object activeElement = doc.getActiveElement();
1591 
1592             if (activeElement == getScriptableObject()) {
1593                 if (hasFeature(HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT)) {
1594                     ((HtmlPage) page).setFocusedElement(null);
1595                 }
1596                 else {
1597                     ((HtmlPage) page).setElementWithFocus(null);
1598                 }
1599             }
1600             else {
1601                 for (final DomNode child : getChildNodes()) {
1602                     if (activeElement == child.getScriptableObject()) {
1603                         if (hasFeature(HTMLELEMENT_REMOVE_ACTIVE_TRIGGERS_BLUR_EVENT)) {
1604                             ((HtmlPage) page).setFocusedElement(null);
1605                         }
1606                         else {
1607                             ((HtmlPage) page).setElementWithFocus(null);
1608                         }
1609 
1610                         break;
1611                     }
1612                 }
1613             }
1614         }
1615         super.detach();
1616     }
1617 
1618     /**
1619      * {@inheritDoc}
1620      */
1621     @Override
1622     public boolean handles(final Event event) {
1623         if (Event.TYPE_BLUR.equals(event.getType()) || Event.TYPE_FOCUS.equals(event.getType())) {
1624             return this instanceof SubmittableElement || getTabIndex() != null;
1625         }
1626 
1627         if (isDisabledElementAndDisabled()) {
1628             return false;
1629         }
1630         return super.handles(event);
1631     }
1632 
1633     /**
1634      * Returns whether the {@code SHIFT} is currently pressed.
1635      * @return whether the {@code SHIFT} is currently pressed
1636      */
1637     protected boolean isShiftPressed() {
1638         return shiftPressed_;
1639     }
1640 
1641     /**
1642      * Returns whether the {@code CTRL} is currently pressed.
1643      * @return whether the {@code CTRL} is currently pressed
1644      */
1645     public boolean isCtrlPressed() {
1646         return ctrlPressed_;
1647     }
1648 
1649     /**
1650      * Returns whether the {@code ALT} is currently pressed.
1651      * @return whether the {@code ALT} is currently pressed
1652      */
1653     public boolean isAltPressed() {
1654         return altPressed_;
1655     }
1656 
1657     /**
1658      * Returns whether the {@code META} is currently pressed.
1659      * @return whether the {@code META} is currently pressed
1660      */
1661     public boolean isMetaPressed() {
1662         return metaPressed_;
1663     }
1664 
1665     /**
1666      * Returns whether this element satisfies all form validation constraints set.
1667      * @return whether this element satisfies all form validation constraints set
1668      */
1669     public boolean isValid() {
1670         return !isRequiredSupported()
1671                 || ATTRIBUTE_NOT_DEFINED == getAttributeDirect(ATTRIBUTE_REQUIRED)
1672                 || !getAttributeDirect(VALUE_ATTRIBUTE).isEmpty();
1673     }
1674 
1675     /**
1676      * Returns whether this element supports the {@code required} constraint.
1677      * @return whether this element supports the {@code required} constraint
1678      */
1679     protected boolean isRequiredSupported() {
1680         return false;
1681     }
1682 
1683     /**
1684      * Returns the true if the required attribute is set.
1685      *
1686      * @return the true if the required attribute is set
1687      */
1688     public boolean isRequired() {
1689         return isRequiredSupported() && hasAttribute(ATTRIBUTE_REQUIRED);
1690     }
1691 
1692     /**
1693      * Returns the true if the required attribute is supported and set.
1694      *
1695      * @return the true if the required attribute is supported and set
1696      */
1697     public boolean isOptional() {
1698         return isRequiredSupported() && !hasAttribute(ATTRIBUTE_REQUIRED);
1699     }
1700 
1701     /**
1702      * Sets the {@code required} attribute.
1703      * @param required the new attribute value
1704      */
1705     public void setRequired(final boolean required) {
1706         if (isRequiredSupported()) {
1707             if (required) {
1708                 setAttribute(ATTRIBUTE_REQUIRED, ATTRIBUTE_REQUIRED);
1709             }
1710             else {
1711                 removeAttribute(ATTRIBUTE_REQUIRED);
1712             }
1713         }
1714     }
1715 
1716     /**
1717      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1718      *
1719      * @param returnNullIfFixed if position is 'fixed' return null
1720      * @return the offset parent {@link HtmlElement}
1721      */
1722     public HtmlElement getOffsetParentInternal(final boolean returnNullIfFixed) {
1723         if (getParentNode() == null) {
1724             return null;
1725         }
1726 
1727         final WebWindow webWindow = getPage().getEnclosingWindow();
1728         final ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1729         final String position = style.getPositionWithInheritance();
1730 
1731         if (returnNullIfFixed && FIXED.equals(position)) {
1732             return null;
1733         }
1734 
1735         final boolean staticPos = STATIC.equals(position);
1736 
1737         DomNode currentElement = this;
1738         while (currentElement != null) {
1739 
1740             final DomNode parentNode = currentElement.getParentNode();
1741             if (parentNode instanceof HtmlBody
1742                 || (staticPos && parentNode instanceof HtmlTableDataCell)
1743                 || (staticPos && parentNode instanceof HtmlTable)) {
1744                 return (HtmlElement) parentNode;
1745             }
1746 
1747             if (parentNode instanceof HtmlElement element) {
1748                 final ComputedCssStyleDeclaration parentStyle =
1749                         webWindow.getComputedStyle(element, null);
1750                 final String parentPosition = parentStyle.getPositionWithInheritance();
1751                 if (!STATIC.equals(parentPosition)) {
1752                     return element;
1753                 }
1754             }
1755 
1756             currentElement = currentElement.getParentNode();
1757         }
1758 
1759         return null;
1760     }
1761 
1762     /**
1763      * Returns this element's top offset, which is the calculated left position of this.
1764      *
1765      * @return this element's top offset, which is the calculated left position of this
1766      *         element relative to the <code>offsetParent</code>.
1767      */
1768     public int getOffsetTop() {
1769         if (this instanceof HtmlBody) {
1770             return 0;
1771         }
1772 
1773         int top = 0;
1774 
1775         // Add the offset for this node.
1776         final WebWindow webWindow = getPage().getEnclosingWindow();
1777         ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1778         top += style.getTop(true, false, false);
1779 
1780         // If this node is absolutely positioned, we're done.
1781         final String position = style.getPositionWithInheritance();
1782         if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1783             return top;
1784         }
1785 
1786         final HtmlElement offsetParent = getOffsetParentInternal(false);
1787 
1788         // Add the offset for the ancestor nodes.
1789         DomNode parentNode = getParentNode();
1790         while (parentNode != null && parentNode != offsetParent) {
1791             if (parentNode instanceof HtmlElement element) {
1792                 style = webWindow.getComputedStyle(element, null);
1793                 top += style.getTop(false, true, true);
1794             }
1795             parentNode = parentNode.getParentNode();
1796         }
1797 
1798         if (offsetParent != null) {
1799             style = webWindow.getComputedStyle(this, null);
1800             final boolean thisElementHasTopMargin = style.getMarginTopValue() != 0;
1801 
1802             style = webWindow.getComputedStyle(offsetParent, null);
1803             if (!thisElementHasTopMargin) {
1804                 top += style.getMarginTopValue();
1805             }
1806             top += style.getPaddingTopValue();
1807         }
1808 
1809         return top;
1810     }
1811 
1812     /**
1813      * Returns this element's left offset, which is the calculated left position of this.
1814      *
1815      * @return this element's left offset, which is the calculated left position of this
1816      *         element relative to the <code>offsetParent</code>.
1817      */
1818     public int getOffsetLeft() {
1819         if (this instanceof HtmlBody) {
1820             return 0;
1821         }
1822 
1823         int left = 0;
1824 
1825         // Add the offset for this node.
1826         final WebWindow webWindow = getPage().getEnclosingWindow();
1827         ComputedCssStyleDeclaration style = webWindow.getComputedStyle(this, null);
1828         left += style.getLeft(true, false, false);
1829 
1830         // If this node is absolutely positioned, we're done.
1831         final String position = style.getPositionWithInheritance();
1832         if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1833             return left;
1834         }
1835 
1836         final HtmlElement offsetParent = getOffsetParentInternal(false);
1837 
1838         DomNode parentNode = getParentNode();
1839         while (parentNode != null && parentNode != offsetParent) {
1840             if (parentNode instanceof HtmlElement element) {
1841                 style = webWindow.getComputedStyle(element, null);
1842                 left += style.getLeft(true, true, true);
1843             }
1844             parentNode = parentNode.getParentNode();
1845         }
1846 
1847         if (offsetParent != null) {
1848             style = webWindow.getComputedStyle(offsetParent, null);
1849             left += style.getMarginLeftValue();
1850             left += style.getPaddingLeftValue();
1851         }
1852 
1853         return left;
1854     }
1855 
1856     /**
1857      * Returns this element's X position.
1858      * @return this element's X position
1859      */
1860     public int getPosX() {
1861         int cumulativeOffset = 0;
1862         final WebWindow webWindow = getPage().getEnclosingWindow();
1863 
1864         HtmlElement element = this;
1865         while (element != null) {
1866             cumulativeOffset += element.getOffsetLeft();
1867             if (element != this) {
1868                 final ComputedCssStyleDeclaration style =
1869                         webWindow.getComputedStyle(element, null);
1870                 cumulativeOffset += style.getBorderLeftValue();
1871             }
1872             element = element.getOffsetParentInternal(false);
1873         }
1874 
1875         return cumulativeOffset;
1876     }
1877 
1878     /**
1879      * Returns this element's Y position.
1880      * @return this element's Y position
1881      */
1882     public int getPosY() {
1883         int cumulativeOffset = 0;
1884         final WebWindow webWindow = getPage().getEnclosingWindow();
1885 
1886         HtmlElement element = this;
1887         while (element != null) {
1888             cumulativeOffset += element.getOffsetTop();
1889             if (element != this) {
1890                 final ComputedCssStyleDeclaration style =
1891                         webWindow.getComputedStyle(element, null);
1892                 cumulativeOffset += style.getBorderTopValue();
1893             }
1894             element = element.getOffsetParentInternal(false);
1895         }
1896 
1897         return cumulativeOffset;
1898     }
1899 
1900     /**
1901      * {@inheritDoc}
1902      */
1903     @Override
1904     public DomNode cloneNode(final boolean deep) {
1905         final HtmlElement newNode = (HtmlElement) super.cloneNode(deep);
1906         if (!deep) {
1907             synchronized (attributeListeners_) {
1908                 newNode.attributeListeners_.clear();
1909                 newNode.attributeListeners_.addAll(attributeListeners_);
1910             }
1911         }
1912 
1913         return newNode;
1914     }
1915 }