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 "core/html/HTMLElement.h"
28 #include "CSSPropertyNames.h"
29 #include "CSSValueKeywords.h"
30 #include "HTMLNames.h"
32 #include "bindings/v8/ExceptionState.h"
33 #include "bindings/v8/ScriptEventListener.h"
34 #include "core/css/CSSMarkup.h"
35 #include "core/css/CSSValuePool.h"
36 #include "core/css/StylePropertySet.h"
37 #include "core/dom/DocumentFragment.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/dom/NodeTraversal.h"
40 #include "core/dom/Text.h"
41 #include "core/editing/markup.h"
42 #include "core/events/EventListener.h"
43 #include "core/events/KeyboardEvent.h"
44 #include "core/frame/Settings.h"
45 #include "core/html/HTMLBRElement.h"
46 #include "core/html/HTMLFormElement.h"
47 #include "core/html/HTMLInputElement.h"
48 #include "core/html/HTMLTemplateElement.h"
49 #include "core/html/HTMLTextFormControlElement.h"
50 #include "core/html/parser/HTMLParserIdioms.h"
51 #include "core/rendering/RenderObject.h"
52 #include "platform/text/BidiResolver.h"
53 #include "platform/text/BidiTextRun.h"
54 #include "platform/text/TextRunIterator.h"
55 #include "wtf/StdLibExtras.h"
56 #include "wtf/text/CString.h"
60 using namespace HTMLNames;
66 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document& document)
68 return adoptRef(new HTMLElement(tagName, document));
71 String HTMLElement::nodeName() const
73 // FIXME: Would be nice to have an atomicstring lookup based off uppercase
74 // chars that does not have to copy the string on a hit in the hash.
75 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
76 if (document().isHTMLDocument() && !tagQName().hasPrefix())
77 return tagQName().localNameUpper();
78 return Element::nodeName();
81 bool HTMLElement::ieForbidsInsertHTML() const
83 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
84 // and createContextualFragment on these tags. We have no tests to
85 // verify this however, so this list could be totally wrong.
86 // This list was moved from the previous endTagRequirement() implementation.
87 // This is also called from editing and assumed to be the list of tags
88 // for which no end tag should be serialized. It's unclear if the list for
89 // IE compat and the list for serialization sanity are the same.
90 if (hasLocalName(areaTag)
91 || hasLocalName(baseTag)
92 || hasLocalName(basefontTag)
93 || hasLocalName(brTag)
94 || hasLocalName(colTag)
95 || hasLocalName(embedTag)
96 || hasLocalName(frameTag)
97 || hasLocalName(hrTag)
98 || hasLocalName(imageTag)
99 || hasLocalName(imgTag)
100 || hasLocalName(inputTag)
101 || hasLocalName(linkTag)
102 || hasLocalName(metaTag)
103 || hasLocalName(paramTag)
104 || hasLocalName(sourceTag)
105 || hasLocalName(wbrTag))
110 static inline CSSValueID unicodeBidiAttributeForDirAuto(HTMLElement* element)
112 if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
113 return CSSValueWebkitPlaintext;
114 // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
115 // See https://bugs.webkit.org/show_bug.cgi?id=73164.
116 return CSSValueWebkitIsolate;
119 unsigned HTMLElement::parseBorderWidthAttribute(const AtomicString& value) const
121 unsigned borderWidth = 0;
122 if (value.isEmpty() || !parseHTMLNonNegativeInteger(value, borderWidth))
123 return hasLocalName(tableTag) ? 1 : borderWidth;
127 void HTMLElement::applyBorderAttributeToStyle(const AtomicString& value, MutableStylePropertySet* style)
129 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderWidth, parseBorderWidthAttribute(value), CSSPrimitiveValue::CSS_PX);
130 addPropertyToPresentationAttributeStyle(style, CSSPropertyBorderStyle, CSSValueSolid);
133 void HTMLElement::mapLanguageAttributeToLocale(const AtomicString& value, MutableStylePropertySet* style)
135 if (!value.isEmpty()) {
136 // Have to quote so the locale id is treated as a string instead of as a CSS keyword.
137 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, quoteCSSString(value));
139 // The empty string means the language is explicitly unknown.
140 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLocale, CSSValueAuto);
144 bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
146 if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
148 return Element::isPresentationAttribute(name);
151 static inline bool isValidDirAttribute(const AtomicString& value)
153 return equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "ltr") || equalIgnoringCase(value, "rtl");
156 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
158 if (name == alignAttr) {
159 if (equalIgnoringCase(value, "middle"))
160 addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
162 addPropertyToPresentationAttributeStyle(style, CSSPropertyTextAlign, value);
163 } else if (name == contenteditableAttr) {
164 if (value.isEmpty() || equalIgnoringCase(value, "true")) {
165 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
166 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
167 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
168 } else if (equalIgnoringCase(value, "plaintext-only")) {
169 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
170 addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
171 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
172 } else if (equalIgnoringCase(value, "false"))
173 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
174 } else if (name == hiddenAttr) {
175 addPropertyToPresentationAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
176 } else if (name == draggableAttr) {
177 if (equalIgnoringCase(value, "true")) {
178 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
179 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
180 } else if (equalIgnoringCase(value, "false"))
181 addPropertyToPresentationAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
182 } else if (name == dirAttr) {
183 if (equalIgnoringCase(value, "auto"))
184 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
186 if (isValidDirAttribute(value))
187 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
189 addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, "ltr");
190 if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
191 addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
193 } else if (name.matches(XMLNames::langAttr))
194 mapLanguageAttributeToLocale(value, style);
195 else if (name == langAttr) {
196 // xml:lang has a higher priority than lang.
197 if (!fastHasAttribute(XMLNames::langAttr))
198 mapLanguageAttributeToLocale(value, style);
200 Element::collectStyleForPresentationAttribute(name, value, style);
203 const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName)
205 if (!attrName.namespaceURI().isNull())
208 typedef HashMap<AtomicString, AtomicString> StringToStringMap;
209 DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
210 if (!attributeNameToEventNameMap.size()) {
211 attributeNameToEventNameMap.set(onanimationstartAttr.localName(), EventTypeNames::animationstart);
212 attributeNameToEventNameMap.set(onanimationiterationAttr.localName(), EventTypeNames::animationiteration);
213 attributeNameToEventNameMap.set(onanimationendAttr.localName(), EventTypeNames::animationend);
214 attributeNameToEventNameMap.set(oncancelAttr.localName(), EventTypeNames::cancel);
215 attributeNameToEventNameMap.set(onclickAttr.localName(), EventTypeNames::click);
216 attributeNameToEventNameMap.set(oncloseAttr.localName(), EventTypeNames::close);
217 attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), EventTypeNames::contextmenu);
218 attributeNameToEventNameMap.set(ondblclickAttr.localName(), EventTypeNames::dblclick);
219 attributeNameToEventNameMap.set(onmousedownAttr.localName(), EventTypeNames::mousedown);
220 attributeNameToEventNameMap.set(onmouseenterAttr.localName(), EventTypeNames::mouseenter);
221 attributeNameToEventNameMap.set(onmouseleaveAttr.localName(), EventTypeNames::mouseleave);
222 attributeNameToEventNameMap.set(onmousemoveAttr.localName(), EventTypeNames::mousemove);
223 attributeNameToEventNameMap.set(onmouseoutAttr.localName(), EventTypeNames::mouseout);
224 attributeNameToEventNameMap.set(onmouseoverAttr.localName(), EventTypeNames::mouseover);
225 attributeNameToEventNameMap.set(onmouseupAttr.localName(), EventTypeNames::mouseup);
226 attributeNameToEventNameMap.set(onmousewheelAttr.localName(), EventTypeNames::mousewheel);
227 attributeNameToEventNameMap.set(onwheelAttr.localName(), EventTypeNames::wheel);
228 attributeNameToEventNameMap.set(onfocusAttr.localName(), EventTypeNames::focus);
229 attributeNameToEventNameMap.set(onfocusinAttr.localName(), EventTypeNames::focusin);
230 attributeNameToEventNameMap.set(onfocusoutAttr.localName(), EventTypeNames::focusout);
231 attributeNameToEventNameMap.set(onblurAttr.localName(), EventTypeNames::blur);
232 attributeNameToEventNameMap.set(onkeydownAttr.localName(), EventTypeNames::keydown);
233 attributeNameToEventNameMap.set(onkeypressAttr.localName(), EventTypeNames::keypress);
234 attributeNameToEventNameMap.set(onkeyupAttr.localName(), EventTypeNames::keyup);
235 attributeNameToEventNameMap.set(onscrollAttr.localName(), EventTypeNames::scroll);
236 attributeNameToEventNameMap.set(onbeforecutAttr.localName(), EventTypeNames::beforecut);
237 attributeNameToEventNameMap.set(oncutAttr.localName(), EventTypeNames::cut);
238 attributeNameToEventNameMap.set(onbeforecopyAttr.localName(), EventTypeNames::beforecopy);
239 attributeNameToEventNameMap.set(oncopyAttr.localName(), EventTypeNames::copy);
240 attributeNameToEventNameMap.set(onbeforepasteAttr.localName(), EventTypeNames::beforepaste);
241 attributeNameToEventNameMap.set(onpasteAttr.localName(), EventTypeNames::paste);
242 attributeNameToEventNameMap.set(ondragenterAttr.localName(), EventTypeNames::dragenter);
243 attributeNameToEventNameMap.set(ondragoverAttr.localName(), EventTypeNames::dragover);
244 attributeNameToEventNameMap.set(ondragleaveAttr.localName(), EventTypeNames::dragleave);
245 attributeNameToEventNameMap.set(ondropAttr.localName(), EventTypeNames::drop);
246 attributeNameToEventNameMap.set(ondragstartAttr.localName(), EventTypeNames::dragstart);
247 attributeNameToEventNameMap.set(ondragAttr.localName(), EventTypeNames::drag);
248 attributeNameToEventNameMap.set(ondragendAttr.localName(), EventTypeNames::dragend);
249 attributeNameToEventNameMap.set(onselectstartAttr.localName(), EventTypeNames::selectstart);
250 attributeNameToEventNameMap.set(onsubmitAttr.localName(), EventTypeNames::submit);
251 attributeNameToEventNameMap.set(onerrorAttr.localName(), EventTypeNames::error);
252 attributeNameToEventNameMap.set(onwebkitanimationstartAttr.localName(), EventTypeNames::webkitAnimationStart);
253 attributeNameToEventNameMap.set(onwebkitanimationiterationAttr.localName(), EventTypeNames::webkitAnimationIteration);
254 attributeNameToEventNameMap.set(onwebkitanimationendAttr.localName(), EventTypeNames::webkitAnimationEnd);
255 attributeNameToEventNameMap.set(onwebkittransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
256 attributeNameToEventNameMap.set(ontransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
257 attributeNameToEventNameMap.set(oninputAttr.localName(), EventTypeNames::input);
258 attributeNameToEventNameMap.set(oninvalidAttr.localName(), EventTypeNames::invalid);
259 attributeNameToEventNameMap.set(ontouchstartAttr.localName(), EventTypeNames::touchstart);
260 attributeNameToEventNameMap.set(ontouchmoveAttr.localName(), EventTypeNames::touchmove);
261 attributeNameToEventNameMap.set(ontouchendAttr.localName(), EventTypeNames::touchend);
262 attributeNameToEventNameMap.set(ontouchcancelAttr.localName(), EventTypeNames::touchcancel);
263 attributeNameToEventNameMap.set(onwebkitfullscreenchangeAttr.localName(), EventTypeNames::webkitfullscreenchange);
264 attributeNameToEventNameMap.set(onwebkitfullscreenerrorAttr.localName(), EventTypeNames::webkitfullscreenerror);
265 attributeNameToEventNameMap.set(onabortAttr.localName(), EventTypeNames::abort);
266 attributeNameToEventNameMap.set(oncanplayAttr.localName(), EventTypeNames::canplay);
267 attributeNameToEventNameMap.set(oncanplaythroughAttr.localName(), EventTypeNames::canplaythrough);
268 attributeNameToEventNameMap.set(onchangeAttr.localName(), EventTypeNames::change);
269 attributeNameToEventNameMap.set(oncuechangeAttr.localName(), EventTypeNames::cuechange);
270 attributeNameToEventNameMap.set(ondurationchangeAttr.localName(), EventTypeNames::durationchange);
271 attributeNameToEventNameMap.set(onemptiedAttr.localName(), EventTypeNames::emptied);
272 attributeNameToEventNameMap.set(onendedAttr.localName(), EventTypeNames::ended);
273 attributeNameToEventNameMap.set(onloadeddataAttr.localName(), EventTypeNames::loadeddata);
274 attributeNameToEventNameMap.set(onloadedmetadataAttr.localName(), EventTypeNames::loadedmetadata);
275 attributeNameToEventNameMap.set(onloadstartAttr.localName(), EventTypeNames::loadstart);
276 attributeNameToEventNameMap.set(onpauseAttr.localName(), EventTypeNames::pause);
277 attributeNameToEventNameMap.set(onplayAttr.localName(), EventTypeNames::play);
278 attributeNameToEventNameMap.set(onplayingAttr.localName(), EventTypeNames::playing);
279 attributeNameToEventNameMap.set(onprogressAttr.localName(), EventTypeNames::progress);
280 attributeNameToEventNameMap.set(onratechangeAttr.localName(), EventTypeNames::ratechange);
281 attributeNameToEventNameMap.set(onresetAttr.localName(), EventTypeNames::reset);
282 attributeNameToEventNameMap.set(onresizeAttr.localName(), EventTypeNames::resize);
283 attributeNameToEventNameMap.set(onseekedAttr.localName(), EventTypeNames::seeked);
284 attributeNameToEventNameMap.set(onseekingAttr.localName(), EventTypeNames::seeking);
285 attributeNameToEventNameMap.set(onselectAttr.localName(), EventTypeNames::select);
286 attributeNameToEventNameMap.set(onshowAttr.localName(), EventTypeNames::show);
287 attributeNameToEventNameMap.set(onstalledAttr.localName(), EventTypeNames::stalled);
288 attributeNameToEventNameMap.set(onsuspendAttr.localName(), EventTypeNames::suspend);
289 attributeNameToEventNameMap.set(ontimeupdateAttr.localName(), EventTypeNames::timeupdate);
290 attributeNameToEventNameMap.set(onvolumechangeAttr.localName(), EventTypeNames::volumechange);
291 attributeNameToEventNameMap.set(onwaitingAttr.localName(), EventTypeNames::waiting);
292 attributeNameToEventNameMap.set(onloadAttr.localName(), EventTypeNames::load);
295 return attributeNameToEventNameMap.get(attrName.localName());
298 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
300 if (isIdAttributeName(name) || name == classAttr || name == styleAttr)
301 return Element::parseAttribute(name, value);
304 dirAttributeChanged(value);
305 else if (name == tabindexAttr) {
307 if (value.isEmpty()) {
308 clearTabIndexExplicitlyIfNeeded();
309 if (treeScope().adjustedFocusedElement() == this) {
310 // We might want to call blur(), but it's dangerous to dispatch
312 document().setNeedsFocusedElementCheck();
314 } else if (parseHTMLInteger(value, tabindex)) {
315 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
316 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
319 const AtomicString& eventName = eventNameForAttributeName(name);
320 if (!eventName.isNull())
321 setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
325 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& exceptionState)
327 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
328 unsigned i, length = text.length();
330 for (unsigned start = 0; start < length; ) {
332 // Find next line break.
333 for (i = start; i < length; i++) {
335 if (c == '\r' || c == '\n')
339 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), exceptionState);
340 if (exceptionState.hadException())
343 if (c == '\r' || c == '\n') {
344 fragment->appendChild(HTMLBRElement::create(document()), exceptionState);
345 if (exceptionState.hadException())
347 // Make sure \r\n doesn't result in two line breaks.
348 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
352 start = i + 1; // Character after line break.
358 void HTMLElement::setInnerText(const String& text, ExceptionState& exceptionState)
360 if (ieForbidsInsertHTML()) {
361 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
364 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
365 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
366 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
367 hasLocalName(trTag)) {
368 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
372 // FIXME: This doesn't take whitespace collapsing into account at all.
374 if (!text.contains('\n') && !text.contains('\r')) {
375 if (text.isEmpty()) {
379 replaceChildrenWithText(this, text, exceptionState);
383 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
384 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
385 // For example, for the contents of textarea elements that are display:none?
386 RenderObject* r = renderer();
387 if (r && r->style()->preserveNewline()) {
388 if (!text.contains('\r')) {
389 replaceChildrenWithText(this, text, exceptionState);
392 String textWithConsistentLineBreaks = text;
393 textWithConsistentLineBreaks.replace("\r\n", "\n");
394 textWithConsistentLineBreaks.replace('\r', '\n');
395 replaceChildrenWithText(this, textWithConsistentLineBreaks, exceptionState);
399 // Add text nodes and <br> elements.
400 RefPtr<DocumentFragment> fragment = textToFragment(text, exceptionState);
401 if (!exceptionState.hadException())
402 replaceChildrenWithFragment(this, fragment.release(), exceptionState);
405 void HTMLElement::setOuterText(const String &text, ExceptionState& exceptionState)
407 if (ieForbidsInsertHTML()) {
408 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
411 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
412 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
413 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
414 hasLocalName(trTag)) {
415 exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
419 ContainerNode* parent = parentNode();
421 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
425 RefPtr<Node> prev = previousSibling();
426 RefPtr<Node> next = nextSibling();
427 RefPtr<Node> newChild;
429 // Convert text to fragment with <br> tags instead of linebreaks if needed.
430 if (text.contains('\r') || text.contains('\n'))
431 newChild = textToFragment(text, exceptionState);
433 newChild = Text::create(document(), text);
435 // textToFragment might cause mutation events.
436 if (!this || !parentNode())
437 exceptionState.throwDOMException(HierarchyRequestError, "The element has no parent.");
439 if (exceptionState.hadException())
442 parent->replaceChild(newChild.release(), this, exceptionState);
444 RefPtr<Node> node = next ? next->previousSibling() : 0;
445 if (!exceptionState.hadException() && node && node->isTextNode())
446 mergeWithNextTextNode(node.release(), exceptionState);
448 if (!exceptionState.hadException() && prev && prev->isTextNode())
449 mergeWithNextTextNode(prev.release(), exceptionState);
452 void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
454 // Vertical alignment with respect to the current baseline of the text
455 // right or left means floating images.
456 CSSValueID floatValue = CSSValueInvalid;
457 CSSValueID verticalAlignValue = CSSValueInvalid;
459 if (equalIgnoringCase(alignment, "absmiddle"))
460 verticalAlignValue = CSSValueMiddle;
461 else if (equalIgnoringCase(alignment, "absbottom"))
462 verticalAlignValue = CSSValueBottom;
463 else if (equalIgnoringCase(alignment, "left")) {
464 floatValue = CSSValueLeft;
465 verticalAlignValue = CSSValueTop;
466 } else if (equalIgnoringCase(alignment, "right")) {
467 floatValue = CSSValueRight;
468 verticalAlignValue = CSSValueTop;
469 } else if (equalIgnoringCase(alignment, "top"))
470 verticalAlignValue = CSSValueTop;
471 else if (equalIgnoringCase(alignment, "middle"))
472 verticalAlignValue = CSSValueWebkitBaselineMiddle;
473 else if (equalIgnoringCase(alignment, "center"))
474 verticalAlignValue = CSSValueMiddle;
475 else if (equalIgnoringCase(alignment, "bottom"))
476 verticalAlignValue = CSSValueBaseline;
477 else if (equalIgnoringCase(alignment, "texttop"))
478 verticalAlignValue = CSSValueTextTop;
480 if (floatValue != CSSValueInvalid)
481 addPropertyToPresentationAttributeStyle(style, CSSPropertyFloat, floatValue);
483 if (verticalAlignValue != CSSValueInvalid)
484 addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, verticalAlignValue);
487 bool HTMLElement::hasCustomFocusLogic() const
492 bool HTMLElement::supportsSpatialNavigationFocus() const
494 // This function checks whether the element satisfies the extended criteria
495 // for the element to be focusable, introduced by spatial navigation feature,
496 // i.e. checks if click or keyboard event handler is specified.
497 // This is the way to make it possible to navigate to (focus) elements
498 // which web designer meant for being active (made them respond to click events).
500 if (!document().settings() || !document().settings()->spatialNavigationEnabled())
502 return hasEventListeners(EventTypeNames::click)
503 || hasEventListeners(EventTypeNames::keydown)
504 || hasEventListeners(EventTypeNames::keypress)
505 || hasEventListeners(EventTypeNames::keyup);
508 bool HTMLElement::supportsFocus() const
510 // FIXME: supportsFocus() can be called when layout is not up to date.
511 // Logic that deals with the renderer should be moved to rendererIsFocusable().
512 // But supportsFocus must return true when the element is editable, or else
513 // it won't be focusable. Furthermore, supportsFocus cannot just return true
514 // always or else tabIndex() will change for all HTML elements.
515 return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable())
516 || supportsSpatialNavigationFocus();
519 String HTMLElement::contentEditable() const
521 const AtomicString& value = fastGetAttribute(contenteditableAttr);
525 if (value.isEmpty() || equalIgnoringCase(value, "true"))
527 if (equalIgnoringCase(value, "false"))
529 if (equalIgnoringCase(value, "plaintext-only"))
530 return "plaintext-only";
535 void HTMLElement::setContentEditable(const String& enabled, ExceptionState& exceptionState)
537 if (equalIgnoringCase(enabled, "true"))
538 setAttribute(contenteditableAttr, "true");
539 else if (equalIgnoringCase(enabled, "false"))
540 setAttribute(contenteditableAttr, "false");
541 else if (equalIgnoringCase(enabled, "plaintext-only"))
542 setAttribute(contenteditableAttr, "plaintext-only");
543 else if (equalIgnoringCase(enabled, "inherit"))
544 removeAttribute(contenteditableAttr);
546 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + enabled + "') is not one of 'true', 'false', 'plaintext-only', or 'inherit'.");
549 bool HTMLElement::draggable() const
551 return equalIgnoringCase(getAttribute(draggableAttr), "true");
554 void HTMLElement::setDraggable(bool value)
556 setAttribute(draggableAttr, value ? "true" : "false");
559 bool HTMLElement::spellcheck() const
561 return isSpellCheckingEnabled();
564 void HTMLElement::setSpellcheck(bool enable)
566 setAttribute(spellcheckAttr, enable ? "true" : "false");
570 void HTMLElement::click()
572 dispatchSimulatedClick(0, SendNoEvents);
575 void HTMLElement::accessKeyAction(bool sendMouseEvents)
577 dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
580 String HTMLElement::title() const
582 return fastGetAttribute(titleAttr);
585 short HTMLElement::tabIndex() const
588 return Element::tabIndex();
592 void HTMLElement::setTabIndex(int value)
594 setIntegralAttribute(tabindexAttr, value);
597 TranslateAttributeMode HTMLElement::translateAttributeMode() const
599 const AtomicString& value = getAttribute(translateAttr);
601 if (value == nullAtom)
602 return TranslateAttributeInherit;
603 if (equalIgnoringCase(value, "yes") || equalIgnoringCase(value, ""))
604 return TranslateAttributeYes;
605 if (equalIgnoringCase(value, "no"))
606 return TranslateAttributeNo;
608 return TranslateAttributeInherit;
611 bool HTMLElement::translate() const
613 for (const HTMLElement* element = this; element; element = Traversal<HTMLElement>::firstAncestor(*element)) {
614 TranslateAttributeMode mode = element->translateAttributeMode();
615 if (mode != TranslateAttributeInherit) {
616 ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
617 return mode == TranslateAttributeYes;
621 // Default on the root element is translate=yes.
625 void HTMLElement::setTranslate(bool enable)
627 setAttribute(translateAttr, enable ? "yes" : "no");
630 HTMLFormElement* HTMLElement::findFormAncestor() const
632 return Traversal<HTMLFormElement>::firstAncestor(*this);
635 static inline bool elementAffectsDirectionality(const Node* node)
637 return node->isHTMLElement() && (isHTMLBDIElement(*node) || toHTMLElement(node)->hasAttribute(dirAttr));
640 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
642 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
644 Node* node = firstNode->firstChild();
647 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
650 if (elementAffectsDirectionality(node)) {
651 if (node == lastNode)
653 node = NodeTraversal::nextSkippingChildren(*node, firstNode);
656 node->setSelfOrAncestorHasDirAutoAttribute(flag);
657 if (node == lastNode)
659 node = NodeTraversal::next(*node, firstNode);
663 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
665 Element::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
666 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
669 bool HTMLElement::hasDirectionAuto() const
671 const AtomicString& direction = fastGetAttribute(dirAttr);
672 return (isHTMLBDIElement(*this) && direction == nullAtom) || equalIgnoringCase(direction, "auto");
675 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
677 if (!(selfOrAncestorHasDirAutoAttribute() && hasDirectionAuto())) {
683 return directionality();
686 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
688 if (isHTMLInputElement(*this)) {
689 HTMLInputElement* inputElement = toHTMLInputElement(const_cast<HTMLElement*>(this));
690 bool hasStrongDirectionality;
691 TextDirection textDirection = determineDirectionality(inputElement->value(), hasStrongDirectionality);
692 if (strongDirectionalityTextNode)
693 *strongDirectionalityTextNode = hasStrongDirectionality ? inputElement : 0;
694 return textDirection;
697 Node* node = firstChild();
699 // Skip bdi, script, style and text form controls.
700 if (equalIgnoringCase(node->nodeName(), "bdi") || isHTMLScriptElement(*node) || isHTMLStyleElement(*node)
701 || (node->isElementNode() && toElement(node)->isTextFormControl())) {
702 node = NodeTraversal::nextSkippingChildren(*node, this);
706 // Skip elements with valid dir attribute
707 if (node->isElementNode()) {
708 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
709 if (isValidDirAttribute(dirAttributeValue)) {
710 node = NodeTraversal::nextSkippingChildren(*node, this);
715 if (node->isTextNode()) {
716 bool hasStrongDirectionality;
717 TextDirection textDirection = determineDirectionality(node->textContent(true), hasStrongDirectionality);
718 if (hasStrongDirectionality) {
719 if (strongDirectionalityTextNode)
720 *strongDirectionalityTextNode = node;
721 return textDirection;
724 node = NodeTraversal::next(*node, this);
726 if (strongDirectionalityTextNode)
727 *strongDirectionalityTextNode = 0;
731 void HTMLElement::dirAttributeChanged(const AtomicString& value)
733 Element* parent = parentElement();
735 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
736 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
738 if (equalIgnoringCase(value, "auto"))
739 calculateAndAdjustDirectionality();
742 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
744 ASSERT(selfOrAncestorHasDirAutoAttribute());
745 Node* strongDirectionalityTextNode;
746 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
747 setHasDirAutoFlagRecursively(child, false);
748 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
749 Element* elementToAdjust = this;
750 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
751 if (elementAffectsDirectionality(elementToAdjust)) {
752 elementToAdjust->setNeedsStyleRecalc(SubtreeStyleChange);
759 void HTMLElement::calculateAndAdjustDirectionality()
761 Node* strongDirectionalityTextNode;
762 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
763 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
764 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
765 setNeedsStyleRecalc(SubtreeStyleChange);
768 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
770 if (document().renderer() && childCountDelta < 0) {
771 Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
772 for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(*node)) {
773 if (elementAffectsDirectionality(node))
776 setHasDirAutoFlagRecursively(node, false);
780 if (!selfOrAncestorHasDirAutoAttribute())
783 Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
784 while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
785 oldMarkedNode = NodeTraversal::nextSkippingChildren(*oldMarkedNode, this);
787 setHasDirAutoFlagRecursively(oldMarkedNode, false);
789 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
790 if (elementAffectsDirectionality(elementToAdjust)) {
791 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
797 void HTMLElement::addHTMLLengthToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
799 // FIXME: This function should not spin up the CSS parser, but should instead just figure out the correct
800 // length unit and make the appropriate parsed value.
802 // strip attribute garbage..
803 StringImpl* v = value.impl();
807 while (length < v->length() && (*v)[length] <= ' ')
810 for (; length < v->length(); length++) {
811 UChar cc = (*v)[length];
815 if (cc == '%' || cc == '*')
822 if (length != v->length()) {
823 addPropertyToPresentationAttributeStyle(style, propertyID, v->substring(0, length));
828 addPropertyToPresentationAttributeStyle(style, propertyID, value);
831 static RGBA32 parseColorStringWithCrazyLegacyRules(const String& colorString)
833 // Per spec, only look at the first 128 digits of the string.
834 const size_t maxColorLength = 128;
835 // We'll pad the buffer with two extra 0s later, so reserve two more than the max.
836 Vector<char, maxColorLength+2> digitBuffer;
840 if (colorString[0] == '#')
843 // Grab the first 128 characters, replacing non-hex characters with 0.
844 // Non-BMP characters are replaced with "00" due to them appearing as two "characters" in the String.
845 for (; i < colorString.length() && digitBuffer.size() < maxColorLength; i++) {
846 if (!isASCIIHexDigit(colorString[i]))
847 digitBuffer.append('0');
849 digitBuffer.append(colorString[i]);
852 if (!digitBuffer.size())
855 // Pad the buffer out to at least the next multiple of three in size.
856 digitBuffer.append('0');
857 digitBuffer.append('0');
859 if (digitBuffer.size() < 6)
860 return makeRGB(toASCIIHexValue(digitBuffer[0]), toASCIIHexValue(digitBuffer[1]), toASCIIHexValue(digitBuffer[2]));
862 // Split the digits into three components, then search the last 8 digits of each component.
863 ASSERT(digitBuffer.size() >= 6);
864 size_t componentLength = digitBuffer.size() / 3;
865 size_t componentSearchWindowLength = min<size_t>(componentLength, 8);
866 size_t redIndex = componentLength - componentSearchWindowLength;
867 size_t greenIndex = componentLength * 2 - componentSearchWindowLength;
868 size_t blueIndex = componentLength * 3 - componentSearchWindowLength;
869 // Skip digits until one of them is non-zero, or we've only got two digits left in the component.
870 while (digitBuffer[redIndex] == '0' && digitBuffer[greenIndex] == '0' && digitBuffer[blueIndex] == '0' && (componentLength - redIndex) > 2) {
875 ASSERT(redIndex + 1 < componentLength);
876 ASSERT(greenIndex >= componentLength);
877 ASSERT(greenIndex + 1 < componentLength * 2);
878 ASSERT(blueIndex >= componentLength * 2);
879 ASSERT_WITH_SECURITY_IMPLICATION(blueIndex + 1 < digitBuffer.size());
881 int redValue = toASCIIHexValue(digitBuffer[redIndex], digitBuffer[redIndex + 1]);
882 int greenValue = toASCIIHexValue(digitBuffer[greenIndex], digitBuffer[greenIndex + 1]);
883 int blueValue = toASCIIHexValue(digitBuffer[blueIndex], digitBuffer[blueIndex + 1]);
884 return makeRGB(redValue, greenValue, blueValue);
887 // Color parsing that matches HTML's "rules for parsing a legacy color value"
888 void HTMLElement::addHTMLColorToStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& attributeValue)
890 // An empty string doesn't apply a color. (One containing only whitespace does, which is why this check occurs before stripping.)
891 if (attributeValue.isEmpty())
894 String colorString = attributeValue.stripWhiteSpace();
896 // "transparent" doesn't apply a color either.
897 if (equalIgnoringCase(colorString, "transparent"))
900 // If the string is a named CSS color or a 3/6-digit hex color, use that.
902 if (!parsedColor.setFromString(colorString))
903 parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
905 style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
908 bool HTMLElement::isInteractiveContent() const
913 void HTMLElement::defaultEventHandler(Event* event)
915 if (event->type() == EventTypeNames::keypress && event->isKeyboardEvent()) {
916 handleKeypressEvent(toKeyboardEvent(event));
917 if (event->defaultHandled())
921 Element::defaultEventHandler(event);
924 bool HTMLElement::matchesReadOnlyPseudoClass() const
926 return !matchesReadWritePseudoClass();
929 bool HTMLElement::matchesReadWritePseudoClass() const
931 const AtomicString& value = fastGetAttribute(contenteditableAttr);
932 if (!value.isNull()) {
933 if (value.isEmpty() || equalIgnoringCase(value, "true") || equalIgnoringCase(value, "plaintext-only"))
935 if (equalIgnoringCase(value, "false"))
937 // All other values should be treated as "inherit".
940 return parentElement() && parentElement()->rendererIsEditable();
943 void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
945 if (!document().settings() || !document().settings()->spatialNavigationEnabled() || !supportsFocus())
947 // if the element is a text form control (like <input type=text> or <textarea>)
948 // or has contentEditable attribute on, we should enter a space or newline
949 // even in spatial navigation mode instead of handling it as a "click" action.
950 if (isTextFormControl() || isContentEditable())
952 int charCode = event->charCode();
953 if (charCode == '\r' || charCode == ' ') {
954 dispatchSimulatedClick(event);
955 event->setDefaultHandled();
959 } // namespace WebCore
963 // For use in the debugger
964 void dumpInnerHTML(WebCore::HTMLElement*);
966 void dumpInnerHTML(WebCore::HTMLElement* element)
968 printf("%s\n", element->innerHTML().ascii().data());