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 "Attribute.h"
29 #include "CSSPropertyNames.h"
30 #include "CSSValueKeywords.h"
31 #include "ChildListMutationScope.h"
32 #include "DocumentFragment.h"
34 #include "EventListener.h"
35 #include "EventNames.h"
36 #include "ExceptionCode.h"
38 #include "HTMLBRElement.h"
39 #include "HTMLCollection.h"
40 #include "HTMLDocument.h"
41 #include "HTMLElementFactory.h"
42 #include "HTMLFormElement.h"
43 #include "HTMLNames.h"
44 #include "HTMLParserIdioms.h"
45 #include "HTMLTextFormControlElement.h"
46 #include "RenderWordBreak.h"
47 #include "ScriptEventListener.h"
50 #include "TextIterator.h"
52 #include <wtf/StdLibExtras.h>
53 #include <wtf/text/CString.h>
56 #include "MicroDataItemValue.h"
61 using namespace HTMLNames;
67 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
69 return adoptRef(new HTMLElement(tagName, document));
72 String HTMLElement::nodeName() const
74 // FIXME: Would be nice to have an atomicstring lookup based off uppercase
75 // chars that does not have to copy the string on a hit in the hash.
76 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
77 if (document()->isHTMLDocument() && !tagQName().hasPrefix())
78 return tagQName().localNameUpper();
79 return Element::nodeName();
82 bool HTMLElement::ieForbidsInsertHTML() const
84 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
85 // and createContextualFragment on these tags. We have no tests to
86 // verify this however, so this list could be totally wrong.
87 // This list was moved from the previous endTagRequirement() implementation.
88 // This is also called from editing and assumed to be the list of tags
89 // for which no end tag should be serialized. It's unclear if the list for
90 // IE compat and the list for serialization sanity are the same.
91 if (hasLocalName(areaTag)
92 || hasLocalName(baseTag)
93 || hasLocalName(basefontTag)
94 || hasLocalName(brTag)
95 || hasLocalName(colTag)
96 || hasLocalName(embedTag)
97 || hasLocalName(frameTag)
98 || hasLocalName(hrTag)
99 || hasLocalName(imageTag)
100 || hasLocalName(imgTag)
101 || hasLocalName(inputTag)
102 || hasLocalName(isindexTag)
103 || hasLocalName(linkTag)
104 || hasLocalName(metaTag)
105 || hasLocalName(paramTag)
106 || hasLocalName(sourceTag)
107 || hasLocalName(wbrTag))
109 // FIXME: I'm not sure why dashboard mode would want to change the
110 // serialization of <canvas>, that seems like a bad idea.
111 #if ENABLE(DASHBOARD_SUPPORT)
112 if (hasLocalName(canvasTag)) {
113 Settings* settings = document()->settings();
114 if (settings && settings->usesDashboardBackwardCompatibilityMode())
121 bool HTMLElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
123 if (attrName == alignAttr
124 || attrName == contenteditableAttr
125 || attrName == hiddenAttr) {
129 if (attrName == dirAttr) {
130 if (hasLocalName(bdoTag))
132 else if (hasLocalName(bdiTag))
139 return StyledElement::mapToEntry(attrName, result);
142 static inline int unicodeBidiAttributeForDirAuto(HTMLElement* element)
144 if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
145 return CSSValueWebkitPlaintext;
146 // FIXME: For bdo element, dir="auto" should result in "bidi-override isolate" but we don't support having multiple values in unicode-bidi yet.
147 // See https://bugs.webkit.org/show_bug.cgi?id=73164.
148 return CSSValueWebkitIsolate;
151 static unsigned parseBorderWidthAttribute(Attribute* attr)
153 ASSERT(attr && attr->name() == borderAttr);
155 unsigned borderWidth = 0;
156 if (!attr->value().isEmpty())
157 parseHTMLNonNegativeInteger(attr->value(), borderWidth);
162 void HTMLElement::applyBorderAttribute(Attribute* attr)
164 addCSSLength(attr, CSSPropertyBorderWidth, String::number(parseBorderWidthAttribute(attr)));
165 addCSSProperty(attr, CSSPropertyBorderTopStyle, CSSValueSolid);
166 addCSSProperty(attr, CSSPropertyBorderRightStyle, CSSValueSolid);
167 addCSSProperty(attr, CSSPropertyBorderBottomStyle, CSSValueSolid);
168 addCSSProperty(attr, CSSPropertyBorderLeftStyle, CSSValueSolid);
171 void HTMLElement::parseMappedAttribute(Attribute* attr)
173 if (isIdAttributeName(attr->name()) || attr->name() == classAttr || attr->name() == styleAttr)
174 return StyledElement::parseMappedAttribute(attr);
177 if (attr->name() == alignAttr) {
178 if (equalIgnoringCase(attr->value(), "middle"))
179 addCSSProperty(attr, CSSPropertyTextAlign, "center");
181 addCSSProperty(attr, CSSPropertyTextAlign, attr->value());
182 } else if (attr->name() == contenteditableAttr) {
183 setContentEditable(attr);
184 } else if (attr->name() == hiddenAttr) {
185 addCSSProperty(attr, CSSPropertyDisplay, CSSValueNone);
186 } else if (attr->name() == tabindexAttr) {
187 indexstring = getAttribute(tabindexAttr);
189 if (!indexstring.length()) {
190 clearTabIndexExplicitly();
191 } else if (parseHTMLInteger(indexstring, tabindex)) {
192 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
193 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
195 } else if (attr->name() == langAttr) {
197 } else if (attr->name() == dirAttr) {
198 bool dirIsAuto = equalIgnoringCase(attr->value(), "auto");
200 addCSSProperty(attr, CSSPropertyDirection, attr->value());
201 dirAttributeChanged(attr);
203 addCSSProperty(attr, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
204 else if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
205 addCSSProperty(attr, CSSPropertyUnicodeBidi, CSSValueEmbed);
206 } else if (attr->name() == draggableAttr) {
207 const AtomicString& value = attr->value();
208 if (equalIgnoringCase(value, "true")) {
209 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueElement);
210 addCSSProperty(attr, CSSPropertyWebkitUserSelect, CSSValueNone);
211 } else if (equalIgnoringCase(value, "false"))
212 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueNone);
213 #if ENABLE(MICRODATA)
214 } else if (attr->name() == itempropAttr) {
215 setItemProp(attr->value());
216 } else if (attr->name() == itemrefAttr) {
217 setItemRef(attr->value());
218 } else if (attr->name() == itemtypeAttr) {
219 setItemType(attr->value());
220 itemTypeAttributeChanged();
224 else if (attr->name() == onclickAttr) {
225 setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attr));
226 } else if (attr->name() == oncontextmenuAttr) {
227 setAttributeEventListener(eventNames().contextmenuEvent, createAttributeEventListener(this, attr));
228 } else if (attr->name() == ondblclickAttr) {
229 setAttributeEventListener(eventNames().dblclickEvent, createAttributeEventListener(this, attr));
230 } else if (attr->name() == onmousedownAttr) {
231 setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, attr));
232 } else if (attr->name() == onmousemoveAttr) {
233 setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, attr));
234 } else if (attr->name() == onmouseoutAttr) {
235 setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, attr));
236 } else if (attr->name() == onmouseoverAttr) {
237 setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, attr));
238 } else if (attr->name() == onmouseupAttr) {
239 setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, attr));
240 } else if (attr->name() == onmousewheelAttr) {
241 setAttributeEventListener(eventNames().mousewheelEvent, createAttributeEventListener(this, attr));
242 } else if (attr->name() == onfocusAttr) {
243 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
244 } else if (attr->name() == onfocusinAttr) {
245 setAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(this, attr));
246 } else if (attr->name() == onfocusoutAttr) {
247 setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, attr));
248 } else if (attr->name() == onblurAttr) {
249 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
250 } else if (attr->name() == onkeydownAttr) {
251 setAttributeEventListener(eventNames().keydownEvent, createAttributeEventListener(this, attr));
252 } else if (attr->name() == onkeypressAttr) {
253 setAttributeEventListener(eventNames().keypressEvent, createAttributeEventListener(this, attr));
254 } else if (attr->name() == onkeyupAttr) {
255 setAttributeEventListener(eventNames().keyupEvent, createAttributeEventListener(this, attr));
256 } else if (attr->name() == onscrollAttr) {
257 setAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(this, attr));
258 } else if (attr->name() == onbeforecutAttr) {
259 setAttributeEventListener(eventNames().beforecutEvent, createAttributeEventListener(this, attr));
260 } else if (attr->name() == oncutAttr) {
261 setAttributeEventListener(eventNames().cutEvent, createAttributeEventListener(this, attr));
262 } else if (attr->name() == onbeforecopyAttr) {
263 setAttributeEventListener(eventNames().beforecopyEvent, createAttributeEventListener(this, attr));
264 } else if (attr->name() == oncopyAttr) {
265 setAttributeEventListener(eventNames().copyEvent, createAttributeEventListener(this, attr));
266 } else if (attr->name() == onbeforepasteAttr) {
267 setAttributeEventListener(eventNames().beforepasteEvent, createAttributeEventListener(this, attr));
268 } else if (attr->name() == onpasteAttr) {
269 setAttributeEventListener(eventNames().pasteEvent, createAttributeEventListener(this, attr));
270 } else if (attr->name() == ondragenterAttr) {
271 setAttributeEventListener(eventNames().dragenterEvent, createAttributeEventListener(this, attr));
272 } else if (attr->name() == ondragoverAttr) {
273 setAttributeEventListener(eventNames().dragoverEvent, createAttributeEventListener(this, attr));
274 } else if (attr->name() == ondragleaveAttr) {
275 setAttributeEventListener(eventNames().dragleaveEvent, createAttributeEventListener(this, attr));
276 } else if (attr->name() == ondropAttr) {
277 setAttributeEventListener(eventNames().dropEvent, createAttributeEventListener(this, attr));
278 } else if (attr->name() == ondragstartAttr) {
279 setAttributeEventListener(eventNames().dragstartEvent, createAttributeEventListener(this, attr));
280 } else if (attr->name() == ondragAttr) {
281 setAttributeEventListener(eventNames().dragEvent, createAttributeEventListener(this, attr));
282 } else if (attr->name() == ondragendAttr) {
283 setAttributeEventListener(eventNames().dragendEvent, createAttributeEventListener(this, attr));
284 } else if (attr->name() == onselectstartAttr) {
285 setAttributeEventListener(eventNames().selectstartEvent, createAttributeEventListener(this, attr));
286 } else if (attr->name() == onsubmitAttr) {
287 setAttributeEventListener(eventNames().submitEvent, createAttributeEventListener(this, attr));
288 } else if (attr->name() == onerrorAttr) {
289 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attr));
290 } else if (attr->name() == onwebkitanimationstartAttr) {
291 setAttributeEventListener(eventNames().webkitAnimationStartEvent, createAttributeEventListener(this, attr));
292 } else if (attr->name() == onwebkitanimationiterationAttr) {
293 setAttributeEventListener(eventNames().webkitAnimationIterationEvent, createAttributeEventListener(this, attr));
294 } else if (attr->name() == onwebkitanimationendAttr) {
295 setAttributeEventListener(eventNames().webkitAnimationEndEvent, createAttributeEventListener(this, attr));
296 } else if (attr->name() == onwebkittransitionendAttr) {
297 setAttributeEventListener(eventNames().webkitTransitionEndEvent, createAttributeEventListener(this, attr));
298 } else if (attr->name() == oninputAttr) {
299 setAttributeEventListener(eventNames().inputEvent, createAttributeEventListener(this, attr));
300 } else if (attr->name() == oninvalidAttr) {
301 setAttributeEventListener(eventNames().invalidEvent, createAttributeEventListener(this, attr));
302 } else if (attr->name() == ontouchstartAttr) {
303 setAttributeEventListener(eventNames().touchstartEvent, createAttributeEventListener(this, attr));
304 } else if (attr->name() == ontouchmoveAttr) {
305 setAttributeEventListener(eventNames().touchmoveEvent, createAttributeEventListener(this, attr));
306 } else if (attr->name() == ontouchendAttr) {
307 setAttributeEventListener(eventNames().touchendEvent, createAttributeEventListener(this, attr));
308 } else if (attr->name() == ontouchcancelAttr) {
309 setAttributeEventListener(eventNames().touchcancelEvent, createAttributeEventListener(this, attr));
310 #if ENABLE(FULLSCREEN_API)
311 } else if (attr->name() == onwebkitfullscreenchangeAttr) {
312 setAttributeEventListener(eventNames().webkitfullscreenchangeEvent, createAttributeEventListener(this, attr));
317 String HTMLElement::innerHTML() const
319 return createMarkup(this, ChildrenOnly);
322 String HTMLElement::outerHTML() const
324 return createMarkup(this);
327 static inline bool hasOneChild(ContainerNode* node)
329 Node* firstChild = node->firstChild();
330 return firstChild && !firstChild->nextSibling();
333 static inline bool hasOneTextChild(ContainerNode* node)
335 return hasOneChild(node) && node->firstChild()->isTextNode();
338 static void replaceChildrenWithFragment(HTMLElement* element, PassRefPtr<DocumentFragment> fragment, ExceptionCode& ec)
340 #if ENABLE(MUTATION_OBSERVERS)
341 ChildListMutationScope mutation(element);
344 if (!fragment->firstChild()) {
345 element->removeChildren();
349 if (hasOneTextChild(element) && hasOneTextChild(fragment.get())) {
350 static_cast<Text*>(element->firstChild())->setData(static_cast<Text*>(fragment->firstChild())->data(), ec);
354 if (hasOneChild(element)) {
355 element->replaceChild(fragment, element->firstChild(), ec);
359 element->removeChildren();
360 element->appendChild(fragment, ec);
363 static void replaceChildrenWithText(HTMLElement* element, const String& text, ExceptionCode& ec)
365 #if ENABLE(MUTATION_OBSERVERS)
366 ChildListMutationScope mutation(element);
369 if (hasOneTextChild(element)) {
370 static_cast<Text*>(element->firstChild())->setData(text, ec);
374 RefPtr<Text> textNode = Text::create(element->document(), text);
376 if (hasOneChild(element)) {
377 element->replaceChild(textNode.release(), element->firstChild(), ec);
381 element->removeChildren();
382 element->appendChild(textNode.release(), ec);
385 // We may want to move a version of this function into DocumentFragment.h/cpp
386 static PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
388 Document* document = contextElement->document();
389 RefPtr<DocumentFragment> fragment;
391 fragment = DocumentFragment::create(document);
392 if (document->isHTMLDocument()) {
393 fragment->parseHTML(markup, contextElement);
397 bool wasValid = fragment->parseXML(markup, contextElement);
399 ec = INVALID_STATE_ERR;
405 void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec)
407 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, this, ec);
409 replaceChildrenWithFragment(this, fragment.release(), ec);
412 static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionCode& ec)
414 ASSERT(node && node->isTextNode());
415 Node* next = node->nextSibling();
416 if (!next || !next->isTextNode())
419 RefPtr<Text> textNode = static_cast<Text*>(node.get());
420 RefPtr<Text> textNext = static_cast<Text*>(next);
421 textNode->appendData(textNext->data(), ec);
424 if (textNext->parentNode()) // Might have been removed by mutation event.
425 textNext->remove(ec);
428 void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
430 Node* p = parentNode();
431 if (!p || !p->isHTMLElement()) {
432 ec = NO_MODIFICATION_ALLOWED_ERR;
435 RefPtr<HTMLElement> parent = toHTMLElement(p);
436 RefPtr<Node> prev = previousSibling();
437 RefPtr<Node> next = nextSibling();
439 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, parent.get(), ec);
443 parent->replaceChild(fragment.release(), this, ec);
444 RefPtr<Node> node = next ? next->previousSibling() : 0;
445 if (!ec && node && node->isTextNode())
446 mergeWithNextTextNode(node.release(), ec);
448 if (!ec && prev && prev->isTextNode())
449 mergeWithNextTextNode(prev.release(), ec);
452 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionCode& ec)
454 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
455 unsigned int i, length = text.length();
457 for (unsigned int start = 0; start < length; ) {
459 // Find next line break.
460 for (i = start; i < length; i++) {
462 if (c == '\r' || c == '\n')
466 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), ec);
470 if (c == '\r' || c == '\n') {
471 fragment->appendChild(HTMLBRElement::create(document()), ec);
474 // Make sure \r\n doesn't result in two line breaks.
475 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
479 start = i + 1; // Character after line break.
485 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
487 if (ieForbidsInsertHTML()) {
488 ec = NO_MODIFICATION_ALLOWED_ERR;
491 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
492 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
493 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
494 hasLocalName(trTag)) {
495 ec = NO_MODIFICATION_ALLOWED_ERR;
499 // FIXME: This doesn't take whitespace collapsing into account at all.
501 if (!text.contains('\n') && !text.contains('\r')) {
502 if (text.isEmpty()) {
506 replaceChildrenWithText(this, text, ec);
510 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
511 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
512 // For example, for the contents of textarea elements that are display:none?
513 RenderObject* r = renderer();
514 if (r && r->style()->preserveNewline()) {
515 if (!text.contains('\r')) {
516 replaceChildrenWithText(this, text, ec);
519 String textWithConsistentLineBreaks = text;
520 textWithConsistentLineBreaks.replace("\r\n", "\n");
521 textWithConsistentLineBreaks.replace('\r', '\n');
522 replaceChildrenWithText(this, textWithConsistentLineBreaks, ec);
526 // Add text nodes and <br> elements.
528 RefPtr<DocumentFragment> fragment = textToFragment(text, ec);
530 replaceChildrenWithFragment(this, fragment.release(), ec);
533 void HTMLElement::setOuterText(const String &text, ExceptionCode& ec)
535 if (ieForbidsInsertHTML()) {
536 ec = NO_MODIFICATION_ALLOWED_ERR;
539 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
540 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
541 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
542 hasLocalName(trTag)) {
543 ec = NO_MODIFICATION_ALLOWED_ERR;
547 ContainerNode* parent = parentNode();
549 ec = NO_MODIFICATION_ALLOWED_ERR;
553 RefPtr<Node> prev = previousSibling();
554 RefPtr<Node> next = nextSibling();
555 RefPtr<Node> newChild;
558 // Convert text to fragment with <br> tags instead of linebreaks if needed.
559 if (text.contains('\r') || text.contains('\n'))
560 newChild = textToFragment(text, ec);
562 newChild = Text::create(document(), text);
564 if (!this || !parentNode())
565 ec = HIERARCHY_REQUEST_ERR;
568 parent->replaceChild(newChild.release(), this, ec);
570 RefPtr<Node> node = next ? next->previousSibling() : 0;
571 if (!ec && node && node->isTextNode())
572 mergeWithNextTextNode(node.release(), ec);
574 if (!ec && prev && prev->isTextNode())
575 mergeWithNextTextNode(prev.release(), ec);
578 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionCode& ec)
580 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
581 // a document fragment is created and the elements appended in the correct order. This document
582 // fragment isn't returned anywhere.
584 // This is impossible for us to implement as the DOM tree does not allow for such structures,
585 // Opera also appears to disallow such usage.
587 if (equalIgnoringCase(where, "beforeBegin")) {
588 ContainerNode* parent = this->parentNode();
589 return (parent && parent->insertBefore(newChild, this, ec)) ? newChild : 0;
592 if (equalIgnoringCase(where, "afterBegin"))
593 return insertBefore(newChild, firstChild(), ec) ? newChild : 0;
595 if (equalIgnoringCase(where, "beforeEnd"))
596 return appendChild(newChild, ec) ? newChild : 0;
598 if (equalIgnoringCase(where, "afterEnd")) {
599 ContainerNode* parent = this->parentNode();
600 return (parent && parent->insertBefore(newChild, nextSibling(), ec)) ? newChild : 0;
603 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
604 ec = NOT_SUPPORTED_ERR;
608 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
611 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
612 ec = TYPE_MISMATCH_ERR;
616 Node* returnValue = insertAdjacent(where, newChild, ec);
617 ASSERT(!returnValue || returnValue->isElementNode());
618 return static_cast<Element*>(returnValue);
621 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
622 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionCode& ec)
624 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
625 ContainerNode* parent = element->parentNode();
626 if (parent && parent->isDocumentNode()) {
627 ec = NO_MODIFICATION_ALLOWED_ERR;
630 ASSERT(!parent || parent->isElementNode());
631 return static_cast<Element*>(parent);
633 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
639 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec)
641 RefPtr<DocumentFragment> fragment = document()->createDocumentFragment();
642 Element* contextElement = contextElementForInsertion(where, this, ec);
646 if (document()->isHTMLDocument())
647 fragment->parseHTML(markup, contextElement);
649 if (!fragment->parseXML(markup, contextElement))
650 // FIXME: We should propagate a syntax error exception out here.
654 insertAdjacent(where, fragment.get(), ec);
657 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
659 RefPtr<Text> textNode = document()->createTextNode(text);
660 insertAdjacent(where, textNode.get(), ec);
663 void HTMLElement::addHTMLAlignment(Attribute* attr)
665 addHTMLAlignmentToStyledElement(this, attr);
668 void HTMLElement::addHTMLAlignmentToStyledElement(StyledElement* element, Attribute* attr)
670 // Vertical alignment with respect to the current baseline of the text
671 // right or left means floating images.
672 int floatValue = CSSValueInvalid;
673 int verticalAlignValue = CSSValueInvalid;
675 const AtomicString& alignment = attr->value();
676 if (equalIgnoringCase(alignment, "absmiddle"))
677 verticalAlignValue = CSSValueMiddle;
678 else if (equalIgnoringCase(alignment, "absbottom"))
679 verticalAlignValue = CSSValueBottom;
680 else if (equalIgnoringCase(alignment, "left")) {
681 floatValue = CSSValueLeft;
682 verticalAlignValue = CSSValueTop;
683 } else if (equalIgnoringCase(alignment, "right")) {
684 floatValue = CSSValueRight;
685 verticalAlignValue = CSSValueTop;
686 } else if (equalIgnoringCase(alignment, "top"))
687 verticalAlignValue = CSSValueTop;
688 else if (equalIgnoringCase(alignment, "middle"))
689 verticalAlignValue = CSSValueWebkitBaselineMiddle;
690 else if (equalIgnoringCase(alignment, "center"))
691 verticalAlignValue = CSSValueMiddle;
692 else if (equalIgnoringCase(alignment, "bottom"))
693 verticalAlignValue = CSSValueBaseline;
694 else if (equalIgnoringCase(alignment, "texttop"))
695 verticalAlignValue = CSSValueTextTop;
697 if (floatValue != CSSValueInvalid)
698 element->addCSSProperty(attr, CSSPropertyFloat, floatValue);
700 if (verticalAlignValue != CSSValueInvalid)
701 element->addCSSProperty(attr, CSSPropertyVerticalAlign, verticalAlignValue);
704 bool HTMLElement::supportsFocus() const
706 return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable());
709 String HTMLElement::contentEditable() const
711 const AtomicString& value = fastGetAttribute(contenteditableAttr);
715 if (value.isEmpty() || equalIgnoringCase(value, "true"))
717 if (equalIgnoringCase(value, "false"))
719 if (equalIgnoringCase(value, "plaintext-only"))
720 return "plaintext-only";
725 void HTMLElement::setContentEditable(Attribute* attr)
727 const AtomicString& enabled = attr->value();
728 if (enabled.isEmpty() || equalIgnoringCase(enabled, "true")) {
729 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWrite);
730 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
731 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
732 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
733 } else if (equalIgnoringCase(enabled, "false")) {
734 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadOnly);
735 attr->decl()->removeProperty(CSSPropertyWordWrap);
736 attr->decl()->removeProperty(CSSPropertyWebkitNbspMode);
737 attr->decl()->removeProperty(CSSPropertyWebkitLineBreak);
738 } else if (equalIgnoringCase(enabled, "plaintext-only")) {
739 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
740 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
741 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
742 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
746 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
748 if (equalIgnoringCase(enabled, "true"))
749 setAttribute(contenteditableAttr, "true", ec);
750 else if (equalIgnoringCase(enabled, "false"))
751 setAttribute(contenteditableAttr, "false", ec);
752 else if (equalIgnoringCase(enabled, "plaintext-only"))
753 setAttribute(contenteditableAttr, "plaintext-only");
754 else if (equalIgnoringCase(enabled, "inherit"))
755 removeAttribute(contenteditableAttr, ec);
760 bool HTMLElement::draggable() const
762 return equalIgnoringCase(getAttribute(draggableAttr), "true");
765 void HTMLElement::setDraggable(bool value)
767 setAttribute(draggableAttr, value ? "true" : "false");
770 bool HTMLElement::spellcheck() const
772 return isSpellCheckingEnabled();
775 void HTMLElement::setSpellcheck(bool enable)
777 setAttribute(spellcheckAttr, enable ? "true" : "false");
781 void HTMLElement::click()
783 dispatchSimulatedClick(0, false, false);
786 void HTMLElement::accessKeyAction(bool sendMouseEvents)
788 dispatchSimulatedClick(0, sendMouseEvents);
791 String HTMLElement::title() const
793 return getAttribute(titleAttr);
796 short HTMLElement::tabIndex() const
799 return Element::tabIndex();
803 void HTMLElement::setTabIndex(int value)
805 setAttribute(tabindexAttr, String::number(value));
808 PassRefPtr<HTMLCollection> HTMLElement::children()
810 return HTMLCollection::create(this, NodeChildren);
813 bool HTMLElement::rendererIsNeeded(const NodeRenderingContext& context)
815 if (hasLocalName(noscriptTag)) {
816 Frame* frame = document()->frame();
817 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
819 } else if (hasLocalName(noembedTag)) {
820 Frame* frame = document()->frame();
821 if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
824 return StyledElement::rendererIsNeeded(context);
827 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
829 if (hasLocalName(wbrTag))
830 return new (arena) RenderWordBreak(this);
831 return RenderObject::createObject(this, style);
834 HTMLFormElement* HTMLElement::findFormAncestor() const
836 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
837 if (ancestor->hasTagName(formTag))
838 return static_cast<HTMLFormElement*>(ancestor);
843 HTMLFormElement* HTMLElement::virtualForm() const
845 return findFormAncestor();
848 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
850 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
852 Node* node = firstNode->firstChild();
855 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
858 if (node->isHTMLElement() && toElement(node)->hasAttribute(dirAttr)) {
859 if (node == lastNode)
861 node = node->traverseNextSibling(firstNode);
864 node->setSelfOrAncestorHasDirAutoAttribute(flag);
865 if (node == lastNode)
867 node = node->traverseNextNode(firstNode);
871 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
873 StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
874 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
877 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
879 if (!(selfOrAncestorHasDirAutoAttribute() && equalIgnoringCase(getAttribute(dirAttr), "auto"))) {
885 return directionality();
888 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
890 if (HTMLTextFormControlElement* textElement = toTextFormControl(const_cast<HTMLElement*>(this))) {
891 bool hasStrongDirectionality;
892 Unicode::Direction textDirection = textElement->value().defaultWritingDirection(&hasStrongDirectionality);
893 if (strongDirectionalityTextNode)
894 *strongDirectionalityTextNode = hasStrongDirectionality ? textElement : 0;
895 return (textDirection == Unicode::LeftToRight) ? LTR : RTL;
898 Node* node = firstChild();
900 // Skip bdi, script, style and text form controls.
901 if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
902 || (node->isElementNode() && toElement(node)->isTextFormControl())) {
903 node = node->traverseNextSibling(this);
907 // Skip elements with valid dir attribute
908 if (node->isElementNode()) {
909 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
910 if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
911 node = node->traverseNextSibling(this);
916 if (node->isTextNode()) {
917 bool hasStrongDirectionality;
918 WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
919 if (hasStrongDirectionality) {
920 if (strongDirectionalityTextNode)
921 *strongDirectionalityTextNode = node;
922 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
925 node = node->traverseNextNode(this);
927 if (strongDirectionalityTextNode)
928 *strongDirectionalityTextNode = 0;
932 void HTMLElement::dirAttributeChanged(Attribute* attribute)
934 Element* parent = parentElement();
936 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
937 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
939 if (equalIgnoringCase(attribute->value(), "auto"))
940 calculateAndAdjustDirectionality();
943 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
945 ASSERT(selfOrAncestorHasDirAutoAttribute());
946 Node* strongDirectionalityTextNode;
947 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
948 setHasDirAutoFlagRecursively(child, false);
949 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
950 Element* elementToAdjust = this;
951 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
952 if (elementToAdjust->hasAttribute(dirAttr)) {
953 elementToAdjust->setNeedsStyleRecalc();
960 void HTMLElement::calculateAndAdjustDirectionality()
962 Node* strongDirectionalityTextNode;
963 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
964 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
965 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
966 setNeedsStyleRecalc();
969 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
971 if ((!document() || document()->renderer()) && childCountDelta < 0) {
972 Node* node = beforeChange ? beforeChange->traverseNextSibling() : 0;
973 for (int counter = 0; node && counter < childCountDelta; counter++, node = node->traverseNextSibling()) {
974 if (node->isElementNode() && toElement(node)->hasAttribute(dirAttr))
977 setHasDirAutoFlagRecursively(node, false);
981 if (!selfOrAncestorHasDirAutoAttribute())
984 Node* oldMarkedNode = beforeChange ? beforeChange->traverseNextSibling() : 0;
985 while (oldMarkedNode && oldMarkedNode->isHTMLElement() && toHTMLElement(oldMarkedNode)->hasAttribute(dirAttr))
986 oldMarkedNode = oldMarkedNode->traverseNextSibling(this);
988 setHasDirAutoFlagRecursively(oldMarkedNode, false);
990 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
991 if (elementToAdjust->isHTMLElement() && elementToAdjust->hasAttribute(dirAttr)) {
992 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
998 bool HTMLElement::isURLAttribute(Attribute* attribute) const
1000 #if ENABLE(MICRODATA)
1001 return attribute->name() == itemidAttr;
1003 UNUSED_PARAM(attribute);
1008 #if ENABLE(MICRODATA)
1009 void HTMLElement::setItemValue(const String& value, ExceptionCode& ec)
1011 if (!hasAttribute(itempropAttr) || hasAttribute(itemscopeAttr)) {
1012 ec = INVALID_ACCESS_ERR;
1016 setItemValueText(value, ec);
1019 PassRefPtr<MicroDataItemValue> HTMLElement::itemValue() const
1021 if (!hasAttribute(itempropAttr))
1024 if (hasAttribute(itemscopeAttr))
1025 return MicroDataItemValue::createFromNode(const_cast<HTMLElement* const>(this));
1027 return MicroDataItemValue::createFromString(itemValueText());
1030 String HTMLElement::itemValueText() const
1032 return textContent(true);
1035 void HTMLElement::setItemValueText(const String& value, ExceptionCode& ec)
1037 setTextContent(value, ec);
1041 } // namespace WebCore
1045 // For use in the debugger
1046 void dumpInnerHTML(WebCore::HTMLElement*);
1048 void dumpInnerHTML(WebCore::HTMLElement* element)
1050 printf("%s\n", element->innerHTML().ascii().data());