2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
5 * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
6 * Copyright (C) 2011 Motorola Mobility. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
26 #include "HTMLElement.h"
28 #include "CSSParser.h"
29 #include "CSSPropertyNames.h"
30 #include "CSSValueKeywords.h"
31 #include "CSSValuePool.h"
32 #include "DOMSettableTokenList.h"
33 #include "DocumentFragment.h"
34 #include "ElementAncestorIterator.h"
36 #include "EventListener.h"
37 #include "EventNames.h"
38 #include "ExceptionCode.h"
40 #include "FrameLoader.h"
41 #include "FrameView.h"
42 #include "HTMLBDIElement.h"
43 #include "HTMLBRElement.h"
44 #include "HTMLCollection.h"
45 #include "HTMLDocument.h"
46 #include "HTMLElementFactory.h"
47 #include "HTMLFormElement.h"
48 #include "HTMLNames.h"
49 #include "HTMLParserIdioms.h"
50 #include "HTMLTextFormControlElement.h"
51 #include "NodeTraversal.h"
52 #include "RenderElement.h"
53 #include "ScriptController.h"
55 #include "StyleProperties.h"
56 #include "SubframeLoader.h"
60 #include <wtf/NeverDestroyed.h>
61 #include <wtf/StdLibExtras.h>
62 #include <wtf/text/CString.h>
66 using namespace HTMLNames;
69 Ref<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document& document)
71 return adoptRef(*new HTMLElement(tagName, document));
74 String HTMLElement::nodeName() const
76 // FIXME: Would be nice to have an AtomicString lookup based off uppercase
77 // ASCII characters that does not have to copy the string on a hit in the hash.
78 if (document().isHTMLDocument()) {
79 if (LIKELY(!tagQName().hasPrefix()))
80 return tagQName().localNameUpper();
81 return Element::nodeName().convertToASCIIUppercase();
83 return Element::nodeName();
86 bool HTMLElement::ieForbidsInsertHTML() const
88 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
89 // and createContextualFragment on these tags. We have no tests to
90 // verify this however, so this list could be totally wrong.
91 // This list was moved from the previous endTagRequirement() implementation.
92 // This is also called from editing and assumed to be the list of tags
93 // for which no end tag should be serialized. It's unclear if the list for
94 // IE compat and the list for serialization sanity are the same.
95 if (hasTagName(areaTag)
96 || hasTagName(baseTag)
97 || hasTagName(basefontTag)
100 || hasTagName(embedTag)
101 || hasTagName(frameTag)
103 || hasTagName(imageTag)
104 || hasTagName(imgTag)
105 || hasTagName(inputTag)
106 || hasTagName(isindexTag)
107 || hasTagName(linkTag)
108 || hasTagName(metaTag)
109 || hasTagName(paramTag)
110 || hasTagName(sourceTag)
111 || hasTagName(wbrTag))
113 // FIXME: I'm not sure why dashboard mode would want to change the
114 // serialization of <canvas>, that seems like a bad idea.
115 #if ENABLE(DASHBOARD_SUPPORT)
116 if (hasTagName(canvasTag)) {
117 Settings* settings = document().settings();
118 if (settings && settings->usesDashboardBackwardCompatibilityMode())
125 static inline CSSValueID unicodeBidiAttributeForDirAuto(HTMLElement& element)
127 if (element.hasTagName(preTag) || element.hasTagName(textareaTag))
128 return CSSValueWebkitPlaintext;
129 // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
130 // See https://bugs.webkit.org/show_bug.cgi?id=73164.
131 return CSSValueWebkitIsolate;
134 unsigned HTMLElement::parseBorderWidthAttribute(const AtomicString& value) const
136 unsigned borderWidth = 0;
137 if (value.isEmpty() || !parseHTMLNonNegativeInteger(value, borderWidth))
138 return hasTagName(tableTag) ? 1 : borderWidth;
142 void HTMLElement::applyBorderAttributeToStyle(const AtomicString& value, MutableStyleProperties& style)
144 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(value), CSSPrimitiveValue::CSS_PX);
145 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
148 void HTMLElement::mapLanguageAttributeToLocale(const AtomicString& value, MutableStyleProperties& style)
150 if (!value.isEmpty()) {
151 // Have to quote so the locale id is treated as a string instead of as a CSS keyword.
152 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, quoteCSSString(value));
154 // The empty string means the language is explicitly unknown.
155 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
159 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
161 if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
163 return StyledElement::isPresentationAttribute(name);
166 static bool isLTROrRTLIgnoringCase(const AtomicString& dirAttributeValue)
168 return equalLettersIgnoringASCIICase(dirAttributeValue, "rtl") || equalLettersIgnoringASCIICase(dirAttributeValue, "ltr");
171 enum class ContentEditableType {
178 static inline ContentEditableType contentEditableType(const AtomicString& value)
181 return ContentEditableType::Inherit;
182 if (value.isEmpty() || equalLettersIgnoringASCIICase(value, "true"))
183 return ContentEditableType::True;
184 if (equalLettersIgnoringASCIICase(value, "false"))
185 return ContentEditableType::False;
186 if (equalLettersIgnoringASCIICase(value, "plaintext-only"))
187 return ContentEditableType::PlaintextOnly;
189 return ContentEditableType::Inherit;
192 static ContentEditableType contentEditableType(const HTMLElement& element)
194 return contentEditableType(element.fastGetAttribute(contenteditableAttr));
197 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStyleProperties& style)
199 if (name == alignAttr) {
200 if (equalLettersIgnoringASCIICase(value, "middle"))
201 addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
203 addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, value);
204 } else if (name == contenteditableAttr) {
205 CSSValueID userModifyValue = CSSValueReadWrite;
206 switch (contentEditableType(value)) {
207 case ContentEditableType::Inherit:
209 case ContentEditableType::False:
210 userModifyValue = CSSValueReadOnly;
212 case ContentEditableType::PlaintextOnly:
213 userModifyValue = CSSValueReadWritePlaintextOnly;
215 case ContentEditableType::True:
216 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
217 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitNbspMode, CSSValueSpace);
218 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
220 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitTextSizeAdjust, CSSValueNone);
224 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, userModifyValue);
225 } else if (name == hiddenAttr) {
226 addPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
227 } else if (name == draggableAttr) {
228 if (equalLettersIgnoringASCIICase(value, "true")) {
229 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
230 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
231 } else if (equalLettersIgnoringASCIICase(value, "false"))
232 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
233 } else if (name == dirAttr) {
234 if (equalLettersIgnoringASCIICase(value, "auto"))
235 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(*this));
237 if (isLTROrRTLIgnoringCase(value))
238 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
239 if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
240 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
242 } else if (name.matches(XMLNames::langAttr))
243 mapLanguageAttributeToLocale(value, style);
244 else if (name == langAttr) {
245 // xml:lang has a higher priority than lang.
246 if (!fastHasAttribute(XMLNames::langAttr))
247 mapLanguageAttributeToLocale(value, style);
249 StyledElement::collectStyleForPresentationAttribute(name, value, style);
252 HTMLElement::EventHandlerNameMap HTMLElement::createEventHandlerNameMap()
254 EventHandlerNameMap map;
256 static const QualifiedName* const table[] = {
259 &onanimationiterationAttr,
260 &onanimationstartAttr,
262 &onautocompleteerrorAttr,
269 &oncanplaythroughAttr,
283 &ondurationchangeAttr,
290 &ongesturechangeAttr,
300 &onloadedmetadataAttr,
331 &ontransitionendAttr,
334 &onwebkitbeginfullscreenAttr,
335 &onwebkitcurrentplaybacktargetiswirelesschangedAttr,
336 &onwebkitendfullscreenAttr,
337 &onwebkitfullscreenchangeAttr,
338 &onwebkitfullscreenerrorAttr,
339 &onwebkitkeyaddedAttr,
340 &onwebkitkeyerrorAttr,
341 &onwebkitkeymessageAttr,
342 &onwebkitmouseforcechangedAttr,
343 &onwebkitmouseforcedownAttr,
344 &onwebkitmouseforcewillbeginAttr,
345 &onwebkitmouseforceupAttr,
346 &onwebkitneedkeyAttr,
347 &onwebkitplaybacktargetavailabilitychangedAttr,
348 &onwebkitpresentationmodechangedAttr,
349 &onwebkitwillrevealbottomAttr,
350 &onwebkitwillrevealleftAttr,
351 &onwebkitwillrevealrightAttr,
352 &onwebkitwillrevealtopAttr,
356 populateEventHandlerNameMap(map, table);
358 struct UnusualMapping {
359 const QualifiedName& attributeName;
360 const AtomicString& eventName;
363 const UnusualMapping unusualPairsTable[] = {
364 { onwebkitanimationendAttr, eventNames().webkitAnimationEndEvent },
365 { onwebkitanimationiterationAttr, eventNames().webkitAnimationIterationEvent },
366 { onwebkitanimationstartAttr, eventNames().webkitAnimationStartEvent },
367 { onwebkittransitionendAttr, eventNames().webkitTransitionEndEvent },
370 for (auto& entry : unusualPairsTable)
371 map.add(entry.attributeName.localName().impl(), entry.eventName);
376 void HTMLElement::populateEventHandlerNameMap(EventHandlerNameMap& map, const QualifiedName* const table[], size_t tableSize)
378 for (size_t i = 0; i < tableSize; ++i) {
379 auto* entry = table[i];
381 // FIXME: Would be nice to check these against the actual event names in eventNames().
382 // Not obvious how to do that simply, though.
383 auto& attributeName = entry->localName();
385 // Remove the "on" prefix. Requires some memory allocation and computing a hash, but by not
386 // using pointers from eventNames(), the passed-in table can be initialized at compile time.
387 AtomicString eventName = attributeName.string().substring(2);
389 map.add(attributeName.impl(), WTFMove(eventName));
393 const AtomicString& HTMLElement::eventNameForEventHandlerAttribute(const QualifiedName& attributeName, const EventHandlerNameMap& map)
395 ASSERT(!attributeName.localName().isNull());
397 // Event handler attributes have no namespace.
398 if (!attributeName.namespaceURI().isNull())
401 // Fast early return for names that don't start with "on".
402 AtomicStringImpl& localName = *attributeName.localName().impl();
403 if (localName.length() < 3 || localName[0] != 'o' || localName[1] != 'n')
406 auto it = map.find(&localName);
407 return it == map.end() ? nullAtom : it->value;
410 const AtomicString& HTMLElement::eventNameForEventHandlerAttribute(const QualifiedName& attributeName)
412 static NeverDestroyed<EventHandlerNameMap> map = createEventHandlerNameMap();
413 return eventNameForEventHandlerAttribute(attributeName, map.get());
416 Node::Editability HTMLElement::editabilityFromContentEditableAttr(const Node& node)
418 if (auto* startElement = is<Element>(node) ? &downcast<Element>(node) : node.parentElement()) {
419 for (auto& element : lineageOfType<HTMLElement>(*startElement)) {
420 switch (contentEditableType(element)) {
421 case ContentEditableType::True:
422 return Editability::CanEditRichly;
423 case ContentEditableType::PlaintextOnly:
424 return Editability::CanEditPlainText;
425 case ContentEditableType::False:
426 return Editability::ReadOnly;
427 case ContentEditableType::Inherit:
433 auto& document = node.document();
434 if (is<HTMLDocument>(document))
435 return downcast<HTMLDocument>(document).inDesignMode() ? Editability::CanEditRichly : Editability::ReadOnly;
437 return Editability::ReadOnly;
440 bool HTMLElement::matchesReadWritePseudoClass() const
442 return editabilityFromContentEditableAttr(*this) != Editability::ReadOnly;
445 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
447 if (name == dirAttr) {
448 dirAttributeChanged(value);
452 if (name == tabindexAttr) {
455 clearTabIndexExplicitlyIfNeeded();
456 else if (parseHTMLInteger(value, tabIndex)) {
457 // Clamp tab index to a 16-bit value to match Firefox's behavior.
458 setTabIndexExplicitly(std::max(-0x8000, std::min(tabIndex, 0x7FFF)));
463 auto& eventName = eventNameForEventHandlerAttribute(name);
464 if (!eventName.isNull())
465 setAttributeEventListener(eventName, name, value);
468 Ref<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionCode& ec)
472 auto fragment = DocumentFragment::create(document());
474 for (unsigned start = 0, length = text.length(); start < length; ) {
476 // Find next line break.
479 for (i = start; i < length; i++) {
481 if (c == '\r' || c == '\n')
485 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), ec);
492 fragment->appendChild(HTMLBRElement::create(document()), ec);
496 // Make sure \r\n doesn't result in two line breaks.
497 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
500 start = i + 1; // Character after line break.
506 static inline bool shouldProhibitSetInnerOuterText(const HTMLElement& element)
508 return element.hasTagName(colTag)
509 || element.hasTagName(colgroupTag)
510 || element.hasTagName(framesetTag)
511 || element.hasTagName(headTag)
512 || element.hasTagName(htmlTag)
513 || element.hasTagName(tableTag)
514 || element.hasTagName(tbodyTag)
515 || element.hasTagName(tfootTag)
516 || element.hasTagName(theadTag)
517 || element.hasTagName(trTag);
520 // Returns the conforming 'dir' value associated with the state the attribute is in (in its canonical case), if any,
521 // or the empty string if the attribute is in a state that has no associated keyword value or if the attribute is
522 // not in a defined state (e.g. the attribute is missing and there is no missing value default).
523 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#limited-to-only-known-values
524 static inline const AtomicString& toValidDirValue(const AtomicString& value)
526 static NeverDestroyed<AtomicString> ltrValue("ltr", AtomicString::ConstructFromLiteral);
527 static NeverDestroyed<AtomicString> rtlValue("rtl", AtomicString::ConstructFromLiteral);
528 static NeverDestroyed<AtomicString> autoValue("auto", AtomicString::ConstructFromLiteral);
529 if (equalLettersIgnoringASCIICase(value, "ltr"))
531 if (equalLettersIgnoringASCIICase(value, "rtl"))
533 if (equalLettersIgnoringASCIICase(value, "auto"))
538 const AtomicString& HTMLElement::dir() const
540 return toValidDirValue(fastGetAttribute(dirAttr));
543 void HTMLElement::setDir(const AtomicString& value)
545 setAttribute(dirAttr, value);
548 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
550 if (ieForbidsInsertHTML()) {
551 ec = NO_MODIFICATION_ALLOWED_ERR;
554 if (shouldProhibitSetInnerOuterText(*this)) {
555 ec = NO_MODIFICATION_ALLOWED_ERR;
559 // FIXME: This doesn't take whitespace collapsing into account at all.
561 if (!text.contains('\n') && !text.contains('\r')) {
562 if (text.isEmpty()) {
566 replaceChildrenWithText(*this, text, ec);
570 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
571 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
572 // For example, for the contents of textarea elements that are display:none?
574 if ((r && r->style().preserveNewline()) || (inDocument() && isTextControlInnerTextElement())) {
575 if (!text.contains('\r')) {
576 replaceChildrenWithText(*this, text, ec);
579 String textWithConsistentLineBreaks = text;
580 textWithConsistentLineBreaks.replace("\r\n", "\n");
581 textWithConsistentLineBreaks.replace('\r', '\n');
582 replaceChildrenWithText(*this, textWithConsistentLineBreaks, ec);
586 // Add text nodes and <br> elements.
588 Ref<DocumentFragment> fragment = textToFragment(text, ec);
590 replaceChildrenWithFragment(*this, WTFMove(fragment), ec);
593 void HTMLElement::setOuterText(const String& text, ExceptionCode& ec)
595 if (ieForbidsInsertHTML()) {
596 ec = NO_MODIFICATION_ALLOWED_ERR;
599 if (shouldProhibitSetInnerOuterText(*this)) {
600 ec = NO_MODIFICATION_ALLOWED_ERR;
604 RefPtr<ContainerNode> parent = parentNode();
606 ec = NO_MODIFICATION_ALLOWED_ERR;
610 RefPtr<Node> prev = previousSibling();
611 RefPtr<Node> next = nextSibling();
612 RefPtr<Node> newChild;
615 // Convert text to fragment with <br> tags instead of linebreaks if needed.
616 if (text.contains('\r') || text.contains('\n'))
617 newChild = textToFragment(text, ec);
619 newChild = Text::create(document(), text);
622 ec = HIERARCHY_REQUEST_ERR;
625 parent->replaceChild(newChild.releaseNonNull(), *this, ec);
627 RefPtr<Node> node = next ? next->previousSibling() : nullptr;
628 if (!ec && is<Text>(node.get()))
629 mergeWithNextTextNode(downcast<Text>(*node), ec);
630 if (!ec && is<Text>(prev.get()))
631 mergeWithNextTextNode(downcast<Text>(*prev), ec);
634 Node* HTMLElement::insertAdjacent(const String& where, Ref<Node>&& newChild, ExceptionCode& ec)
636 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
637 // a document fragment is created and the elements appended in the correct order. This document
638 // fragment isn't returned anywhere.
640 // This is impossible for us to implement as the DOM tree does not allow for such structures,
641 // Opera also appears to disallow such usage.
643 if (equalLettersIgnoringASCIICase(where, "beforebegin")) {
644 ContainerNode* parent = this->parentNode();
645 return (parent && parent->insertBefore(newChild.copyRef(), this, ec)) ? newChild.ptr() : nullptr;
648 if (equalLettersIgnoringASCIICase(where, "afterbegin"))
649 return insertBefore(newChild.copyRef(), firstChild(), ec) ? newChild.ptr() : nullptr;
651 if (equalLettersIgnoringASCIICase(where, "beforeend"))
652 return appendChild(newChild.copyRef(), ec) ? newChild.ptr() : nullptr;
654 if (equalLettersIgnoringASCIICase(where, "afterend")) {
655 ContainerNode* parent = this->parentNode();
656 return (parent && parent->insertBefore(newChild.copyRef(), nextSibling(), ec)) ? newChild.ptr() : nullptr;
659 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
660 ec = NOT_SUPPORTED_ERR;
664 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
667 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
668 ec = TYPE_MISMATCH_ERR;
672 Node* returnValue = insertAdjacent(where, *newChild, ec);
673 ASSERT_WITH_SECURITY_IMPLICATION(!returnValue || is<Element>(*returnValue));
674 return downcast<Element>(returnValue);
677 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
678 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionCode& ec)
680 if (equalLettersIgnoringASCIICase(where, "beforebegin") || equalLettersIgnoringASCIICase(where, "afterend")) {
681 ContainerNode* parent = element->parentNode();
682 if (parent && !is<Element>(*parent)) {
683 ec = NO_MODIFICATION_ALLOWED_ERR;
686 ASSERT_WITH_SECURITY_IMPLICATION(!parent || is<Element>(*parent));
687 return downcast<Element>(parent);
689 if (equalLettersIgnoringASCIICase(where, "afterbegin") || equalLettersIgnoringASCIICase(where, "beforeend"))
695 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec)
697 Element* contextElement = contextElementForInsertion(where, this, ec);
700 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, ec);
703 insertAdjacent(where, fragment.releaseNonNull(), ec);
706 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
708 insertAdjacent(where, document().createTextNode(text), ec);
711 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStyleProperties& style)
713 // Vertical alignment with respect to the current baseline of the text
714 // right or left means floating images.
715 CSSValueID floatValue = CSSValueInvalid;
716 CSSValueID verticalAlignValue = CSSValueInvalid;
718 if (equalLettersIgnoringASCIICase(alignment, "absmiddle"))
719 verticalAlignValue = CSSValueMiddle;
720 else if (equalLettersIgnoringASCIICase(alignment, "absbottom"))
721 verticalAlignValue = CSSValueBottom;
722 else if (equalLettersIgnoringASCIICase(alignment, "left")) {
723 floatValue = CSSValueLeft;
724 verticalAlignValue = CSSValueTop;
725 } else if (equalLettersIgnoringASCIICase(alignment, "right")) {
726 floatValue = CSSValueRight;
727 verticalAlignValue = CSSValueTop;
728 } else if (equalLettersIgnoringASCIICase(alignment, "top"))
729 verticalAlignValue = CSSValueTop;
730 else if (equalLettersIgnoringASCIICase(alignment, "middle"))
731 verticalAlignValue = CSSValueWebkitBaselineMiddle;
732 else if (equalLettersIgnoringASCIICase(alignment, "center"))
733 verticalAlignValue = CSSValueMiddle;
734 else if (equalLettersIgnoringASCIICase(alignment, "bottom"))
735 verticalAlignValue = CSSValueBaseline;
736 else if (equalLettersIgnoringASCIICase(alignment, "texttop"))
737 verticalAlignValue = CSSValueTextTop;
739 if (floatValue != CSSValueInvalid)
740 addPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, floatValue);
742 if (verticalAlignValue != CSSValueInvalid)
743 addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
746 bool HTMLElement::hasCustomFocusLogic() const
751 bool HTMLElement::supportsFocus() const
753 return Element::supportsFocus() || (hasEditableStyle() && parentNode() && !parentNode()->hasEditableStyle());
756 String HTMLElement::contentEditable() const
758 switch (contentEditableType(*this)) {
759 case ContentEditableType::Inherit:
760 return ASCIILiteral("inherit");
761 case ContentEditableType::True:
762 return ASCIILiteral("true");
763 case ContentEditableType::False:
764 return ASCIILiteral("false");
765 case ContentEditableType::PlaintextOnly:
766 return ASCIILiteral("plaintext-only");
768 return ASCIILiteral("inherit");
771 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
773 if (equalLettersIgnoringASCIICase(enabled, "true"))
774 setAttribute(contenteditableAttr, AtomicString("true", AtomicString::ConstructFromLiteral));
775 else if (equalLettersIgnoringASCIICase(enabled, "false"))
776 setAttribute(contenteditableAttr, AtomicString("false", AtomicString::ConstructFromLiteral));
777 else if (equalLettersIgnoringASCIICase(enabled, "plaintext-only"))
778 setAttribute(contenteditableAttr, AtomicString("plaintext-only", AtomicString::ConstructFromLiteral));
779 else if (equalLettersIgnoringASCIICase(enabled, "inherit"))
780 removeAttribute(contenteditableAttr);
785 bool HTMLElement::draggable() const
787 return equalLettersIgnoringASCIICase(fastGetAttribute(draggableAttr), "true");
790 void HTMLElement::setDraggable(bool value)
792 setAttribute(draggableAttr, value
793 ? AtomicString("true", AtomicString::ConstructFromLiteral)
794 : AtomicString("false", AtomicString::ConstructFromLiteral));
797 bool HTMLElement::spellcheck() const
799 return isSpellCheckingEnabled();
802 void HTMLElement::setSpellcheck(bool enable)
804 setAttribute(spellcheckAttr, enable
805 ? AtomicString("true", AtomicString::ConstructFromLiteral)
806 : AtomicString("false", AtomicString::ConstructFromLiteral));
809 void HTMLElement::click()
811 dispatchSimulatedClick(nullptr, SendNoEvents, DoNotShowPressedLook);
814 void HTMLElement::accessKeyAction(bool sendMouseEvents)
816 dispatchSimulatedClick(nullptr, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
819 String HTMLElement::title() const
821 return fastGetAttribute(titleAttr);
824 short HTMLElement::tabIndex() const
827 return Element::tabIndex();
831 TranslateAttributeMode HTMLElement::translateAttributeMode() const
833 const AtomicString& value = fastGetAttribute(translateAttr);
836 return TranslateAttributeInherit;
837 if (equalLettersIgnoringASCIICase(value, "yes") || value.isEmpty())
838 return TranslateAttributeYes;
839 if (equalLettersIgnoringASCIICase(value, "no"))
840 return TranslateAttributeNo;
842 return TranslateAttributeInherit;
845 bool HTMLElement::translate() const
847 for (auto& element : lineageOfType<HTMLElement>(*this)) {
848 TranslateAttributeMode mode = element.translateAttributeMode();
849 if (mode == TranslateAttributeInherit)
851 ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
852 return mode == TranslateAttributeYes;
855 // Default on the root element is translate=yes.
859 void HTMLElement::setTranslate(bool enable)
861 setAttribute(translateAttr, enable ? "yes" : "no");
864 bool HTMLElement::rendererIsNeeded(const RenderStyle& style)
866 if (hasTagName(noscriptTag)) {
867 Frame* frame = document().frame();
868 if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
870 } else if (hasTagName(noembedTag)) {
871 Frame* frame = document().frame();
872 if (frame && frame->loader().subframeLoader().allowPlugins())
875 return StyledElement::rendererIsNeeded(style);
878 RenderPtr<RenderElement> HTMLElement::createElementRenderer(Ref<RenderStyle>&& style, const RenderTreePosition&)
880 return RenderElement::createFor(*this, WTFMove(style));
883 HTMLFormElement* HTMLElement::virtualForm() const
885 return HTMLFormElement::findClosestFormAncestor(*this);
888 static inline bool elementAffectsDirectionality(const Node& node)
890 if (!is<HTMLElement>(node))
892 const HTMLElement& element = downcast<HTMLElement>(node);
893 return is<HTMLBDIElement>(element) || element.fastHasAttribute(dirAttr);
896 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = nullptr)
898 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
900 Node* node = firstNode->firstChild();
903 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
906 if (elementAffectsDirectionality(*node)) {
907 if (node == lastNode)
909 node = NodeTraversal::nextSkippingChildren(*node, firstNode);
912 node->setSelfOrAncestorHasDirAutoAttribute(flag);
913 if (node == lastNode)
915 node = NodeTraversal::next(*node, firstNode);
919 void HTMLElement::childrenChanged(const ChildChange& change)
921 StyledElement::childrenChanged(change);
922 adjustDirectionalityIfNeededAfterChildrenChanged(change.previousSiblingElement, change.type);
925 bool HTMLElement::hasDirectionAuto() const
927 const AtomicString& direction = fastGetAttribute(dirAttr);
928 return (hasTagName(bdiTag) && direction.isNull()) || equalLettersIgnoringASCIICase(direction, "auto");
931 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
933 if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
939 return directionality();
942 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
944 if (is<HTMLTextFormControlElement>(*this)) {
945 HTMLTextFormControlElement& textElement = downcast<HTMLTextFormControlElement>(const_cast<HTMLElement&>(*this));
946 bool hasStrongDirectionality;
947 UCharDirection textDirection = textElement.value().defaultWritingDirection(&hasStrongDirectionality);
948 if (strongDirectionalityTextNode)
949 *strongDirectionalityTextNode = hasStrongDirectionality ? &textElement : nullptr;
950 return (textDirection == U_LEFT_TO_RIGHT) ? LTR : RTL;
953 Node* node = firstChild();
955 // Skip bdi, script, style and text form controls.
956 if (equalLettersIgnoringASCIICase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
957 || (is<Element>(*node) && downcast<Element>(*node).isTextFormControl())) {
958 node = NodeTraversal::nextSkippingChildren(*node, this);
962 // Skip elements with valid dir attribute
963 if (is<Element>(*node)) {
964 AtomicString dirAttributeValue = downcast<Element>(*node).fastGetAttribute(dirAttr);
965 if (isLTROrRTLIgnoringCase(dirAttributeValue) || equalLettersIgnoringASCIICase(dirAttributeValue, "auto")) {
966 node = NodeTraversal::nextSkippingChildren(*node, this);
971 if (node->isTextNode()) {
972 bool hasStrongDirectionality;
973 UCharDirection textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
974 if (hasStrongDirectionality) {
975 if (strongDirectionalityTextNode)
976 *strongDirectionalityTextNode = node;
977 return (textDirection == U_LEFT_TO_RIGHT) ? LTR : RTL;
980 node = NodeTraversal::next(*node, this);
982 if (strongDirectionalityTextNode)
983 *strongDirectionalityTextNode = nullptr;
987 void HTMLElement::dirAttributeChanged(const AtomicString& value)
989 Element* parent = parentElement();
991 if (is<HTMLElement>(parent) && parent->selfOrAncestorHasDirAutoAttribute())
992 downcast<HTMLElement>(*parent).adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
994 if (equalLettersIgnoringASCIICase(value, "auto"))
995 calculateAndAdjustDirectionality();
998 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
1000 ASSERT(selfOrAncestorHasDirAutoAttribute());
1001 Node* strongDirectionalityTextNode;
1002 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
1003 setHasDirAutoFlagRecursively(child, false);
1004 if (!renderer() || renderer()->style().direction() == textDirection)
1006 for (auto& elementToAdjust : elementLineage(this)) {
1007 if (elementAffectsDirectionality(elementToAdjust)) {
1008 elementToAdjust.setNeedsStyleRecalc();
1014 void HTMLElement::calculateAndAdjustDirectionality()
1016 Node* strongDirectionalityTextNode;
1017 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
1018 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
1019 if (renderer() && renderer()->style().direction() != textDirection)
1020 setNeedsStyleRecalc();
1023 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Element* beforeChange, ChildChangeType changeType)
1025 // FIXME: This function looks suspicious.
1027 if (!selfOrAncestorHasDirAutoAttribute())
1030 Node* oldMarkedNode = nullptr;
1032 oldMarkedNode = changeType == ElementInserted ? ElementTraversal::nextSibling(*beforeChange) : beforeChange->nextSibling();
1034 while (oldMarkedNode && elementAffectsDirectionality(*oldMarkedNode))
1035 oldMarkedNode = oldMarkedNode->nextSibling();
1037 setHasDirAutoFlagRecursively(oldMarkedNode, false);
1039 for (auto& elementToAdjust : lineageOfType<HTMLElement>(*this)) {
1040 if (elementAffectsDirectionality(elementToAdjust)) {
1041 elementToAdjust.calculateAndAdjustDirectionality();
1047 void HTMLElement::addHTMLLengthToStyle(MutableStyleProperties& style, CSSPropertyID propertyID, const String& value)
1049 // FIXME: This function should not spin up the CSS parser, but should instead just figure out the correct
1050 // length unit and make the appropriate parsed value.
1052 if (StringImpl* string = value.impl()) {
1053 unsigned parsedLength = 0;
1055 while (parsedLength < string->length() && (*string)[parsedLength] <= ' ')
1058 for (; parsedLength < string->length(); ++parsedLength) {
1059 UChar cc = (*string)[parsedLength];
1063 if (cc == '%' || cc == '*')
1070 if (parsedLength != string->length()) {
1071 addPropertyToPresentationAttributeStyle(style, propertyID, string->substring(0, parsedLength));
1076 addPropertyToPresentationAttributeStyle(style, propertyID, value);
1079 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
1081 // Per spec, only look at the first 128 digits of the string.
1082 const size_t maxColorLength = 128;
1083 // We'll pad the buffer with two extra 0s later, so reserve two more than the max.
1084 Vector<char, maxColorLength+2> digitBuffer;
1087 // Skip a leading #.
1088 if (colorString[0] == '#')
1091 // Grab the first 128 characters, replacing non-hex characters with 0.
1092 // Non-BMP characters are replaced with "00" due to them appearing as two "characters" in the String.
1093 for (; i < colorString.length() && digitBuffer.size() < maxColorLength; i++) {
1094 if (!isASCIIHexDigit(colorString[i]))
1095 digitBuffer.append('0');
1097 digitBuffer.append(colorString[i]);
1100 if (!digitBuffer.size())
1101 return Color::black;
1103 // Pad the buffer out to at least the next multiple of three in size.
1104 digitBuffer.append('0');
1105 digitBuffer.append('0');
1107 if (digitBuffer.size() < 6)
1108 return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
1110 // Split the digits into three components, then search the last 8 digits of each component.
1111 ASSERT(digitBuffer.size() >= 6);
1112 size_t componentLength = digitBuffer.size() / 3;
1113 size_t componentSearchWindowLength = std::min<size_t>(componentLength, 8);
1114 size_t redIndex = componentLength - componentSearchWindowLength;
1115 size_t greenIndex = componentLength * 2 - componentSearchWindowLength;
1116 size_t blueIndex = componentLength * 3 - componentSearchWindowLength;
1117 // Skip digits until one of them is non-zero, or we've only got two digits left in the component.
1118 while (digitBuffer[redIndex] == '0' && digitBuffer[greenIndex] == '0' && digitBuffer[blueIndex] == '0' && (componentLength - redIndex) > 2) {
1123 ASSERT(redIndex + 1 < componentLength);
1124 ASSERT(greenIndex >= componentLength);
1125 ASSERT(greenIndex + 1 < componentLength * 2);
1126 ASSERT(blueIndex >= componentLength * 2);
1127 ASSERT_WITH_SECURITY_IMPLICATION(blueIndex + 1 < digitBuffer.size());
1129 int redValue = toASCIIHexValue(digitBuffer[redIndex], digitBuffer[redIndex + 1]);
1130 int greenValue = toASCIIHexValue(digitBuffer[greenIndex], digitBuffer[greenIndex + 1]);
1131 int blueValue = toASCIIHexValue(digitBuffer[blueIndex], digitBuffer[blueIndex + 1]);
1132 return makeRGB(redValue, greenValue, blueValue);
1135 // Color parsing that matches HTML's "rules for parsing a legacy color value"
1136 void HTMLElement::addHTMLColorToStyle(MutableStyleProperties& style, CSSPropertyID propertyID, const String& attributeValue)
1138 // An empty string doesn't apply a color. (One containing only whitespace does, which is why this check occurs before stripping.)
1139 if (attributeValue.isEmpty())
1142 String colorString = attributeValue.stripWhiteSpace();
1144 // "transparent" doesn't apply a color either.
1145 if (equalLettersIgnoringASCIICase(colorString, "transparent"))
1148 // If the string is a named CSS color or a 3/6-digit hex color, use that.
1149 Color parsedColor(colorString);
1150 if (!parsedColor.isValid())
1151 parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
1153 style.setProperty(propertyID, CSSValuePool::singleton().createColorValue(parsedColor.rgb()));
1156 bool HTMLElement::willRespondToMouseMoveEvents()
1158 return !isDisabledFormControl() && Element::willRespondToMouseMoveEvents();
1161 bool HTMLElement::willRespondToMouseWheelEvents()
1163 return !isDisabledFormControl() && Element::willRespondToMouseWheelEvents();
1166 bool HTMLElement::willRespondToMouseClickEvents()
1168 return !isDisabledFormControl() && Element::willRespondToMouseClickEvents();
1171 } // namespace WebCore
1175 // For use in the debugger
1176 void dumpInnerHTML(WebCore::HTMLElement*);
1178 void dumpInnerHTML(WebCore::HTMLElement* element)
1180 printf("%s\n", element->innerHTML().ascii().data());