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/)
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
25 #include "HTMLElement.h"
27 #include "Attribute.h"
28 #include "CSSPropertyNames.h"
29 #include "CSSValueKeywords.h"
30 #include "DocumentFragment.h"
32 #include "EventListener.h"
33 #include "EventNames.h"
34 #include "ExceptionCode.h"
36 #include "HTMLBRElement.h"
37 #include "HTMLCollection.h"
38 #include "HTMLDocument.h"
39 #include "HTMLElementFactory.h"
40 #include "HTMLFormElement.h"
41 #include "HTMLNames.h"
42 #include "HTMLParserIdioms.h"
43 #include "HTMLTextFormControlElement.h"
44 #include "RenderWordBreak.h"
45 #include "ScriptEventListener.h"
48 #include "TextIterator.h"
50 #include <wtf/StdLibExtras.h>
51 #include <wtf/text/CString.h>
55 using namespace HTMLNames;
61 PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
63 return adoptRef(new HTMLElement(tagName, document));
66 String HTMLElement::nodeName() const
68 // FIXME: Would be nice to have an atomicstring lookup based off uppercase
69 // chars that does not have to copy the string on a hit in the hash.
70 // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
71 if (document()->isHTMLDocument() && !tagQName().hasPrefix())
72 return tagQName().localNameUpper();
73 return Element::nodeName();
76 bool HTMLElement::ieForbidsInsertHTML() const
78 // FIXME: Supposedly IE disallows settting innerHTML, outerHTML
79 // and createContextualFragment on these tags. We have no tests to
80 // verify this however, so this list could be totally wrong.
81 // This list was moved from the previous endTagRequirement() implementation.
82 // This is also called from editing and assumed to be the list of tags
83 // for which no end tag should be serialized. It's unclear if the list for
84 // IE compat and the list for serialization sanity are the same.
85 if (hasLocalName(areaTag)
86 || hasLocalName(baseTag)
87 || hasLocalName(basefontTag)
88 || hasLocalName(brTag)
89 || hasLocalName(colTag)
90 || hasLocalName(embedTag)
91 || hasLocalName(frameTag)
92 || hasLocalName(hrTag)
93 || hasLocalName(imageTag)
94 || hasLocalName(imgTag)
95 || hasLocalName(inputTag)
96 || hasLocalName(isindexTag)
97 || hasLocalName(linkTag)
98 || hasLocalName(metaTag)
99 || hasLocalName(paramTag)
100 || hasLocalName(sourceTag)
101 || hasLocalName(wbrTag))
103 // FIXME: I'm not sure why dashboard mode would want to change the
104 // serialization of <canvas>, that seems like a bad idea.
105 #if ENABLE(DASHBOARD_SUPPORT)
106 if (hasLocalName(canvasTag)) {
107 Settings* settings = document()->settings();
108 if (settings && settings->usesDashboardBackwardCompatibilityMode())
115 bool HTMLElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
117 if (attrName == alignAttr
118 || attrName == contenteditableAttr
119 || attrName == hiddenAttr) {
123 if (attrName == dirAttr) {
124 result = hasLocalName(bdoTag) ? eBDO : eUniversal;
128 return StyledElement::mapToEntry(attrName, result);
131 static inline int unicodeBidiAttributeForDirAuto(HTMLElement* element)
133 if (element->hasLocalName(bdoTag))
134 return CSSValueBidiOverride;
135 if (element->hasLocalName(preTag) || element->hasLocalName(textareaTag))
136 return CSSValueWebkitPlaintext;
137 return CSSValueEmbed;
140 static unsigned parseBorderWidthAttribute(Attribute* attr)
142 ASSERT(attr && attr->name() == borderAttr);
144 unsigned borderWidth = 0;
145 if (!attr->value().isEmpty())
146 parseHTMLNonNegativeInteger(attr->value(), borderWidth);
151 void HTMLElement::applyBorderAttribute(Attribute* attr)
153 addCSSLength(attr, CSSPropertyBorderWidth, String::number(parseBorderWidthAttribute(attr)));
154 addCSSProperty(attr, CSSPropertyBorderTopStyle, CSSValueSolid);
155 addCSSProperty(attr, CSSPropertyBorderRightStyle, CSSValueSolid);
156 addCSSProperty(attr, CSSPropertyBorderBottomStyle, CSSValueSolid);
157 addCSSProperty(attr, CSSPropertyBorderLeftStyle, CSSValueSolid);
160 void HTMLElement::parseMappedAttribute(Attribute* attr)
162 if (isIdAttributeName(attr->name()) || attr->name() == classAttr || attr->name() == styleAttr)
163 return StyledElement::parseMappedAttribute(attr);
166 if (attr->name() == alignAttr) {
167 if (equalIgnoringCase(attr->value(), "middle"))
168 addCSSProperty(attr, CSSPropertyTextAlign, "center");
170 addCSSProperty(attr, CSSPropertyTextAlign, attr->value());
171 } else if (attr->name() == contenteditableAttr) {
172 setContentEditable(attr);
173 } else if (attr->name() == hiddenAttr) {
174 addCSSProperty(attr, CSSPropertyDisplay, CSSValueNone);
175 } else if (attr->name() == tabindexAttr) {
176 indexstring = getAttribute(tabindexAttr);
178 if (!indexstring.length()) {
179 clearTabIndexExplicitly();
180 } else if (parseHTMLInteger(indexstring, tabindex)) {
181 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
182 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
184 } else if (attr->name() == langAttr) {
186 } else if (attr->name() == dirAttr) {
187 if (!equalIgnoringCase(attr->value(), "auto"))
188 addCSSProperty(attr, CSSPropertyDirection, attr->value());
189 dirAttributeChanged(attr);
190 addCSSProperty(attr, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
191 } else if (attr->name() == draggableAttr) {
192 const AtomicString& value = attr->value();
193 if (equalIgnoringCase(value, "true")) {
194 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueElement);
195 addCSSProperty(attr, CSSPropertyWebkitUserSelect, CSSValueNone);
196 } else if (equalIgnoringCase(value, "false"))
197 addCSSProperty(attr, CSSPropertyWebkitUserDrag, CSSValueNone);
200 else if (attr->name() == onclickAttr) {
201 setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attr));
202 } else if (attr->name() == oncontextmenuAttr) {
203 setAttributeEventListener(eventNames().contextmenuEvent, createAttributeEventListener(this, attr));
204 } else if (attr->name() == ondblclickAttr) {
205 setAttributeEventListener(eventNames().dblclickEvent, createAttributeEventListener(this, attr));
206 } else if (attr->name() == onmousedownAttr) {
207 setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, attr));
208 } else if (attr->name() == onmousemoveAttr) {
209 setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, attr));
210 } else if (attr->name() == onmouseoutAttr) {
211 setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, attr));
212 } else if (attr->name() == onmouseoverAttr) {
213 setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, attr));
214 } else if (attr->name() == onmouseupAttr) {
215 setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, attr));
216 } else if (attr->name() == onmousewheelAttr) {
217 setAttributeEventListener(eventNames().mousewheelEvent, createAttributeEventListener(this, attr));
218 } else if (attr->name() == onfocusAttr) {
219 setAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(this, attr));
220 } else if (attr->name() == onfocusinAttr) {
221 setAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(this, attr));
222 } else if (attr->name() == onfocusoutAttr) {
223 setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, attr));
224 } else if (attr->name() == onblurAttr) {
225 setAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(this, attr));
226 } else if (attr->name() == onkeydownAttr) {
227 setAttributeEventListener(eventNames().keydownEvent, createAttributeEventListener(this, attr));
228 } else if (attr->name() == onkeypressAttr) {
229 setAttributeEventListener(eventNames().keypressEvent, createAttributeEventListener(this, attr));
230 } else if (attr->name() == onkeyupAttr) {
231 setAttributeEventListener(eventNames().keyupEvent, createAttributeEventListener(this, attr));
232 } else if (attr->name() == onscrollAttr) {
233 setAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(this, attr));
234 } else if (attr->name() == onbeforecutAttr) {
235 setAttributeEventListener(eventNames().beforecutEvent, createAttributeEventListener(this, attr));
236 } else if (attr->name() == oncutAttr) {
237 setAttributeEventListener(eventNames().cutEvent, createAttributeEventListener(this, attr));
238 } else if (attr->name() == onbeforecopyAttr) {
239 setAttributeEventListener(eventNames().beforecopyEvent, createAttributeEventListener(this, attr));
240 } else if (attr->name() == oncopyAttr) {
241 setAttributeEventListener(eventNames().copyEvent, createAttributeEventListener(this, attr));
242 } else if (attr->name() == onbeforepasteAttr) {
243 setAttributeEventListener(eventNames().beforepasteEvent, createAttributeEventListener(this, attr));
244 } else if (attr->name() == onpasteAttr) {
245 setAttributeEventListener(eventNames().pasteEvent, createAttributeEventListener(this, attr));
246 } else if (attr->name() == ondragenterAttr) {
247 setAttributeEventListener(eventNames().dragenterEvent, createAttributeEventListener(this, attr));
248 } else if (attr->name() == ondragoverAttr) {
249 setAttributeEventListener(eventNames().dragoverEvent, createAttributeEventListener(this, attr));
250 } else if (attr->name() == ondragleaveAttr) {
251 setAttributeEventListener(eventNames().dragleaveEvent, createAttributeEventListener(this, attr));
252 } else if (attr->name() == ondropAttr) {
253 setAttributeEventListener(eventNames().dropEvent, createAttributeEventListener(this, attr));
254 } else if (attr->name() == ondragstartAttr) {
255 setAttributeEventListener(eventNames().dragstartEvent, createAttributeEventListener(this, attr));
256 } else if (attr->name() == ondragAttr) {
257 setAttributeEventListener(eventNames().dragEvent, createAttributeEventListener(this, attr));
258 } else if (attr->name() == ondragendAttr) {
259 setAttributeEventListener(eventNames().dragendEvent, createAttributeEventListener(this, attr));
260 } else if (attr->name() == onselectstartAttr) {
261 setAttributeEventListener(eventNames().selectstartEvent, createAttributeEventListener(this, attr));
262 } else if (attr->name() == onsubmitAttr) {
263 setAttributeEventListener(eventNames().submitEvent, createAttributeEventListener(this, attr));
264 } else if (attr->name() == onerrorAttr) {
265 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attr));
266 } else if (attr->name() == onwebkitanimationstartAttr) {
267 setAttributeEventListener(eventNames().webkitAnimationStartEvent, createAttributeEventListener(this, attr));
268 } else if (attr->name() == onwebkitanimationiterationAttr) {
269 setAttributeEventListener(eventNames().webkitAnimationIterationEvent, createAttributeEventListener(this, attr));
270 } else if (attr->name() == onwebkitanimationendAttr) {
271 setAttributeEventListener(eventNames().webkitAnimationEndEvent, createAttributeEventListener(this, attr));
272 } else if (attr->name() == onwebkittransitionendAttr) {
273 setAttributeEventListener(eventNames().webkitTransitionEndEvent, createAttributeEventListener(this, attr));
274 } else if (attr->name() == oninputAttr) {
275 setAttributeEventListener(eventNames().inputEvent, createAttributeEventListener(this, attr));
276 } else if (attr->name() == oninvalidAttr) {
277 setAttributeEventListener(eventNames().invalidEvent, createAttributeEventListener(this, attr));
278 } else if (attr->name() == ontouchstartAttr) {
279 setAttributeEventListener(eventNames().touchstartEvent, createAttributeEventListener(this, attr));
280 } else if (attr->name() == ontouchmoveAttr) {
281 setAttributeEventListener(eventNames().touchmoveEvent, createAttributeEventListener(this, attr));
282 } else if (attr->name() == ontouchendAttr) {
283 setAttributeEventListener(eventNames().touchendEvent, createAttributeEventListener(this, attr));
284 } else if (attr->name() == ontouchcancelAttr) {
285 setAttributeEventListener(eventNames().touchcancelEvent, createAttributeEventListener(this, attr));
286 #if ENABLE(FULLSCREEN_API)
287 } else if (attr->name() == onwebkitfullscreenchangeAttr) {
288 setAttributeEventListener(eventNames().webkitfullscreenchangeEvent, createAttributeEventListener(this, attr));
293 String HTMLElement::innerHTML() const
295 return createMarkup(this, ChildrenOnly);
298 String HTMLElement::outerHTML() const
300 return createMarkup(this);
303 static inline bool hasOneChild(ContainerNode* node)
305 Node* firstChild = node->firstChild();
306 return firstChild && !firstChild->nextSibling();
309 static inline bool hasOneTextChild(ContainerNode* node)
311 return hasOneChild(node) && node->firstChild()->isTextNode();
314 static void replaceChildrenWithFragment(HTMLElement* element, PassRefPtr<DocumentFragment> fragment, ExceptionCode& ec)
316 if (!fragment->firstChild()) {
317 element->removeChildren();
321 if (hasOneTextChild(element) && hasOneTextChild(fragment.get())) {
322 static_cast<Text*>(element->firstChild())->setData(static_cast<Text*>(fragment->firstChild())->data(), ec);
326 if (hasOneChild(element)) {
327 element->replaceChild(fragment, element->firstChild(), ec);
331 element->removeChildren();
332 element->appendChild(fragment, ec);
335 static void replaceChildrenWithText(HTMLElement* element, const String& text, ExceptionCode& ec)
337 if (hasOneTextChild(element)) {
338 static_cast<Text*>(element->firstChild())->setData(text, ec);
342 RefPtr<Text> textNode = Text::create(element->document(), text);
344 if (hasOneChild(element)) {
345 element->replaceChild(textNode.release(), element->firstChild(), ec);
349 element->removeChildren();
350 element->appendChild(textNode.release(), ec);
353 // We may want to move a version of this function into DocumentFragment.h/cpp
354 static PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
356 Document* document = contextElement->document();
357 RefPtr<DocumentFragment> fragment;
359 fragment = DocumentFragment::create(document);
360 if (document->isHTMLDocument()) {
361 fragment->parseHTML(markup, contextElement);
365 bool wasValid = fragment->parseXML(markup, contextElement);
367 ec = INVALID_STATE_ERR;
373 void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec)
375 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, this, ec);
377 replaceChildrenWithFragment(this, fragment.release(), ec);
380 static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionCode& ec)
382 ASSERT(node && node->isTextNode());
383 Node* next = node->nextSibling();
384 if (!next || !next->isTextNode())
387 RefPtr<Text> textNode = static_cast<Text*>(node.get());
388 RefPtr<Text> textNext = static_cast<Text*>(next);
389 textNode->appendData(textNext->data(), ec);
392 if (textNext->parentNode()) // Might have been removed by mutation event.
393 textNext->remove(ec);
396 void HTMLElement::setOuterHTML(const String& html, ExceptionCode& ec)
398 Node* p = parentNode();
399 if (!p || !p->isHTMLElement()) {
400 ec = NO_MODIFICATION_ALLOWED_ERR;
403 RefPtr<HTMLElement> parent = static_cast<HTMLElement*>(p);
404 RefPtr<Node> prev = previousSibling();
405 RefPtr<Node> next = nextSibling();
407 RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, parent.get(), ec);
411 parent->replaceChild(fragment.release(), this, ec);
412 RefPtr<Node> node = next ? next->previousSibling() : 0;
413 if (!ec && node && node->isTextNode())
414 mergeWithNextTextNode(node.release(), ec);
416 if (!ec && prev && prev->isTextNode())
417 mergeWithNextTextNode(prev.release(), ec);
420 PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionCode& ec)
422 RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
423 unsigned int i, length = text.length();
425 for (unsigned int start = 0; start < length; ) {
427 // Find next line break.
428 for (i = start; i < length; i++) {
430 if (c == '\r' || c == '\n')
434 fragment->appendChild(Text::create(document(), text.substring(start, i - start)), ec);
438 if (c == '\r' || c == '\n') {
439 fragment->appendChild(HTMLBRElement::create(document()), ec);
442 // Make sure \r\n doesn't result in two line breaks.
443 if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
447 start = i + 1; // Character after line break.
453 void HTMLElement::setInnerText(const String& text, ExceptionCode& ec)
455 if (ieForbidsInsertHTML()) {
456 ec = NO_MODIFICATION_ALLOWED_ERR;
459 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
460 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
461 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
462 hasLocalName(trTag)) {
463 ec = NO_MODIFICATION_ALLOWED_ERR;
467 // FIXME: This doesn't take whitespace collapsing into account at all.
469 if (!text.contains('\n') && !text.contains('\r')) {
470 if (text.isEmpty()) {
474 replaceChildrenWithText(this, text, ec);
478 // FIXME: Do we need to be able to detect preserveNewline style even when there's no renderer?
479 // FIXME: Can the renderer be out of date here? Do we need to call updateStyleIfNeeded?
480 // For example, for the contents of textarea elements that are display:none?
481 RenderObject* r = renderer();
482 if (r && r->style()->preserveNewline()) {
483 if (!text.contains('\r')) {
484 replaceChildrenWithText(this, text, ec);
487 String textWithConsistentLineBreaks = text;
488 textWithConsistentLineBreaks.replace("\r\n", "\n");
489 textWithConsistentLineBreaks.replace('\r', '\n');
490 replaceChildrenWithText(this, textWithConsistentLineBreaks, ec);
494 // Add text nodes and <br> elements.
496 RefPtr<DocumentFragment> fragment = textToFragment(text, ec);
498 replaceChildrenWithFragment(this, fragment.release(), ec);
501 void HTMLElement::setOuterText(const String &text, ExceptionCode& ec)
503 if (ieForbidsInsertHTML()) {
504 ec = NO_MODIFICATION_ALLOWED_ERR;
507 if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
508 hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
509 hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
510 hasLocalName(trTag)) {
511 ec = NO_MODIFICATION_ALLOWED_ERR;
515 ContainerNode* parent = parentNode();
517 ec = NO_MODIFICATION_ALLOWED_ERR;
521 RefPtr<Node> prev = previousSibling();
522 RefPtr<Node> next = nextSibling();
523 RefPtr<Node> newChild;
526 // Convert text to fragment with <br> tags instead of linebreaks if needed.
527 if (text.contains('\r') || text.contains('\n'))
528 newChild = textToFragment(text, ec);
530 newChild = Text::create(document(), text);
532 if (!this || !parentNode())
533 ec = HIERARCHY_REQUEST_ERR;
536 parent->replaceChild(newChild.release(), this, ec);
538 RefPtr<Node> node = next ? next->previousSibling() : 0;
539 if (!ec && node && node->isTextNode())
540 mergeWithNextTextNode(node.release(), ec);
542 if (!ec && prev && prev->isTextNode())
543 mergeWithNextTextNode(prev.release(), ec);
546 Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionCode& ec)
548 // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
549 // a document fragment is created and the elements appended in the correct order. This document
550 // fragment isn't returned anywhere.
552 // This is impossible for us to implement as the DOM tree does not allow for such structures,
553 // Opera also appears to disallow such usage.
555 if (equalIgnoringCase(where, "beforeBegin")) {
556 ContainerNode* parent = this->parentNode();
557 return (parent && parent->insertBefore(newChild, this, ec)) ? newChild : 0;
560 if (equalIgnoringCase(where, "afterBegin"))
561 return insertBefore(newChild, firstChild(), ec) ? newChild : 0;
563 if (equalIgnoringCase(where, "beforeEnd"))
564 return appendChild(newChild, ec) ? newChild : 0;
566 if (equalIgnoringCase(where, "afterEnd")) {
567 ContainerNode* parent = this->parentNode();
568 return (parent && parent->insertBefore(newChild, nextSibling(), ec)) ? newChild : 0;
571 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
572 ec = NOT_SUPPORTED_ERR;
576 Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionCode& ec)
579 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
580 ec = TYPE_MISMATCH_ERR;
584 Node* returnValue = insertAdjacent(where, newChild, ec);
585 ASSERT(!returnValue || returnValue->isElementNode());
586 return static_cast<Element*>(returnValue);
589 // Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
590 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionCode& ec)
592 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
593 ContainerNode* parent = element->parentNode();
594 if (parent && parent->isDocumentNode()) {
595 ec = NO_MODIFICATION_ALLOWED_ERR;
598 ASSERT(!parent || parent->isElementNode());
599 return static_cast<Element*>(parent);
601 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
607 void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec)
609 RefPtr<DocumentFragment> fragment = document()->createDocumentFragment();
610 Element* contextElement = contextElementForInsertion(where, this, ec);
614 if (document()->isHTMLDocument())
615 fragment->parseHTML(markup, contextElement);
617 if (!fragment->parseXML(markup, contextElement))
618 // FIXME: We should propagate a syntax error exception out here.
622 insertAdjacent(where, fragment.get(), ec);
625 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionCode& ec)
627 RefPtr<Text> textNode = document()->createTextNode(text);
628 insertAdjacent(where, textNode.get(), ec);
631 void HTMLElement::addHTMLAlignment(Attribute* attr)
633 addHTMLAlignmentToStyledElement(this, attr);
636 void HTMLElement::addHTMLAlignmentToStyledElement(StyledElement* element, Attribute* attr)
638 // Vertical alignment with respect to the current baseline of the text
639 // right or left means floating images.
640 int floatValue = CSSValueInvalid;
641 int verticalAlignValue = CSSValueInvalid;
643 const AtomicString& alignment = attr->value();
644 if (equalIgnoringCase(alignment, "absmiddle"))
645 verticalAlignValue = CSSValueMiddle;
646 else if (equalIgnoringCase(alignment, "absbottom"))
647 verticalAlignValue = CSSValueBottom;
648 else if (equalIgnoringCase(alignment, "left")) {
649 floatValue = CSSValueLeft;
650 verticalAlignValue = CSSValueTop;
651 } else if (equalIgnoringCase(alignment, "right")) {
652 floatValue = CSSValueRight;
653 verticalAlignValue = CSSValueTop;
654 } else if (equalIgnoringCase(alignment, "top"))
655 verticalAlignValue = CSSValueTop;
656 else if (equalIgnoringCase(alignment, "middle"))
657 verticalAlignValue = CSSValueWebkitBaselineMiddle;
658 else if (equalIgnoringCase(alignment, "center"))
659 verticalAlignValue = CSSValueMiddle;
660 else if (equalIgnoringCase(alignment, "bottom"))
661 verticalAlignValue = CSSValueBaseline;
662 else if (equalIgnoringCase(alignment, "texttop"))
663 verticalAlignValue = CSSValueTextTop;
665 if (floatValue != CSSValueInvalid)
666 element->addCSSProperty(attr, CSSPropertyFloat, floatValue);
668 if (verticalAlignValue != CSSValueInvalid)
669 element->addCSSProperty(attr, CSSPropertyVerticalAlign, verticalAlignValue);
672 bool HTMLElement::supportsFocus() const
674 return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable());
677 String HTMLElement::contentEditable() const
679 const AtomicString& value = fastGetAttribute(contenteditableAttr);
683 if (value.isEmpty() || equalIgnoringCase(value, "true"))
685 if (equalIgnoringCase(value, "false"))
687 if (equalIgnoringCase(value, "plaintext-only"))
688 return "plaintext-only";
693 void HTMLElement::setContentEditable(Attribute* attr)
695 const AtomicString& enabled = attr->value();
696 if (enabled.isEmpty() || equalIgnoringCase(enabled, "true")) {
697 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWrite);
698 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
699 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
700 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
701 } else if (equalIgnoringCase(enabled, "false")) {
702 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadOnly);
703 attr->decl()->removeProperty(CSSPropertyWordWrap, false);
704 attr->decl()->removeProperty(CSSPropertyWebkitNbspMode, false);
705 attr->decl()->removeProperty(CSSPropertyWebkitLineBreak, false);
706 } else if (equalIgnoringCase(enabled, "plaintext-only")) {
707 addCSSProperty(attr, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
708 addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
709 addCSSProperty(attr, CSSPropertyWebkitNbspMode, CSSValueSpace);
710 addCSSProperty(attr, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
714 void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
716 if (equalIgnoringCase(enabled, "true"))
717 setAttribute(contenteditableAttr, "true", ec);
718 else if (equalIgnoringCase(enabled, "false"))
719 setAttribute(contenteditableAttr, "false", ec);
720 else if (equalIgnoringCase(enabled, "plaintext-only"))
721 setAttribute(contenteditableAttr, "plaintext-only");
722 else if (equalIgnoringCase(enabled, "inherit"))
723 removeAttribute(contenteditableAttr, ec);
728 bool HTMLElement::draggable() const
730 return equalIgnoringCase(getAttribute(draggableAttr), "true");
733 void HTMLElement::setDraggable(bool value)
735 setAttribute(draggableAttr, value ? "true" : "false");
738 bool HTMLElement::spellcheck() const
740 return isSpellCheckingEnabled();
743 void HTMLElement::setSpellcheck(bool enable)
745 setAttribute(spellcheckAttr, enable ? "true" : "false");
749 void HTMLElement::click()
751 dispatchSimulatedClick(0, false, false);
754 // accessKeyAction is used by the accessibility support code
755 // to send events to elements that our JavaScript caller does
756 // does not. The elements JS is interested in have subclasses
757 // that override this method to direct the click appropriately.
758 // Here in the base class, then, we only send the click if
759 // the caller wants it to go to any HTMLElement, and we say
760 // to send the mouse events in addition to the click.
761 void HTMLElement::accessKeyAction(bool sendToAnyElement)
763 if (sendToAnyElement)
764 dispatchSimulatedClick(0, true);
767 String HTMLElement::title() const
769 return getAttribute(titleAttr);
772 short HTMLElement::tabIndex() const
775 return Element::tabIndex();
779 void HTMLElement::setTabIndex(int value)
781 setAttribute(tabindexAttr, String::number(value));
784 PassRefPtr<HTMLCollection> HTMLElement::children()
786 return HTMLCollection::create(this, NodeChildren);
789 bool HTMLElement::rendererIsNeeded(const NodeRenderingContext& context)
791 if (hasLocalName(noscriptTag)) {
792 Frame* frame = document()->frame();
794 if (!document()->shouldProcessNoscriptElement())
797 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
800 } else if (hasLocalName(noembedTag)) {
801 Frame* frame = document()->frame();
802 if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
805 return StyledElement::rendererIsNeeded(context);
808 RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
810 if (hasLocalName(wbrTag))
811 return new (arena) RenderWordBreak(this);
812 return RenderObject::createObject(this, style);
815 HTMLFormElement* HTMLElement::findFormAncestor() const
817 for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
818 if (ancestor->hasTagName(formTag))
819 return static_cast<HTMLFormElement*>(ancestor);
824 HTMLFormElement* HTMLElement::virtualForm() const
826 return findFormAncestor();
829 static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastNode = 0)
831 firstNode->setSelfOrAncestorHasDirAutoAttribute(flag);
833 Node* node = firstNode->firstChild();
836 if (node->selfOrAncestorHasDirAutoAttribute() == flag)
839 if (node->isHTMLElement() && toElement(node)->hasAttribute(dirAttr)) {
840 if (node == lastNode)
842 node = node->traverseNextSibling(firstNode);
845 node->setSelfOrAncestorHasDirAutoAttribute(flag);
846 if (node == lastNode)
848 node = node->traverseNextNode(firstNode);
852 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
854 StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
855 adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
858 TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) const
860 if (!(selfOrAncestorHasDirAutoAttribute() && equalIgnoringCase(getAttribute(dirAttr), "auto"))) {
866 return directionality();
869 TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
871 if (HTMLTextFormControlElement* textElement = toTextFormControl(const_cast<HTMLElement*>(this))) {
872 bool hasStrongDirectionality;
873 Unicode::Direction textDirection = textElement->value().defaultWritingDirection(&hasStrongDirectionality);
874 if (hasStrongDirectionality && strongDirectionalityTextNode)
875 *strongDirectionalityTextNode = textElement;
876 return (textDirection == Unicode::LeftToRight) ? LTR : RTL;
879 Node* node = firstChild();
881 // Skip bdi, script, style and text form controls.
882 if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
883 || (node->isElementNode() && toElement(node)->isTextFormControl())) {
884 node = node->traverseNextSibling(this);
888 // Skip elements with valid dir attribute
889 if (node->isElementNode()) {
890 AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
891 if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
892 node = node->traverseNextSibling(this);
897 if (node->isTextNode()) {
898 bool hasStrongDirectionality;
899 WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
900 if (hasStrongDirectionality) {
901 if (strongDirectionalityTextNode)
902 *strongDirectionalityTextNode = node;
903 return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
906 node = node->traverseNextNode(this);
908 if (strongDirectionalityTextNode)
909 *strongDirectionalityTextNode = 0;
913 void HTMLElement::dirAttributeChanged(Attribute* attribute)
915 Element* parent = parentElement();
917 if (parent && parent->isHTMLElement() && parent->selfOrAncestorHasDirAutoAttribute())
918 toHTMLElement(parent)->adjustDirectionalityIfNeededAfterChildAttributeChanged(this);
920 if (equalIgnoringCase(attribute->value(), "auto"))
921 calculateAndAdjustDirectionality();
924 void HTMLElement::adjustDirectionalityIfNeededAfterChildAttributeChanged(Element* child)
926 ASSERT(selfOrAncestorHasDirAutoAttribute());
927 Node* strongDirectionalityTextNode;
928 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
929 setHasDirAutoFlagRecursively(child, false);
930 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection) {
931 Element* elementToAdjust = this;
932 for (; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
933 if (elementToAdjust->hasAttribute(dirAttr)) {
934 elementToAdjust->setNeedsStyleRecalc();
941 void HTMLElement::calculateAndAdjustDirectionality()
943 Node* strongDirectionalityTextNode;
944 TextDirection textDirection = directionality(&strongDirectionalityTextNode);
945 setHasDirAutoFlagRecursively(this, true, strongDirectionalityTextNode);
946 if (renderer() && renderer()->style() && renderer()->style()->direction() != textDirection)
947 setNeedsStyleRecalc();
950 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
952 if ((!document() || document()->renderer()) && childCountDelta < 0) {
953 Node* node = beforeChange ? beforeChange->traverseNextSibling() : 0;
954 for (int counter = 0; node && counter < childCountDelta; counter++, node = node->traverseNextSibling()) {
955 if (node->isElementNode() && toElement(node)->hasAttribute(dirAttr))
958 setHasDirAutoFlagRecursively(node, false);
962 if (!selfOrAncestorHasDirAutoAttribute())
965 Node* oldMarkedNode = beforeChange ? beforeChange->traverseNextSibling() : 0;
966 while (oldMarkedNode && oldMarkedNode->isHTMLElement() && toHTMLElement(oldMarkedNode)->hasAttribute(dirAttr))
967 oldMarkedNode = oldMarkedNode->traverseNextSibling(this);
969 setHasDirAutoFlagRecursively(oldMarkedNode, false);
971 for (Element* elementToAdjust = this; elementToAdjust; elementToAdjust = elementToAdjust->parentElement()) {
972 if (elementToAdjust->isHTMLElement() && elementToAdjust->hasAttribute(dirAttr)) {
973 toHTMLElement(elementToAdjust)->calculateAndAdjustDirectionality();
979 } // namespace WebCore
983 // For use in the debugger
984 void dumpInnerHTML(WebCore::HTMLElement*);
986 void dumpInnerHTML(WebCore::HTMLElement* element)
988 printf("%s\n", element->innerHTML().ascii().data());