2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
6 * Copyright (C) 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
7 * Copyright (C) 2010 Google Inc. All rights reserved.
8 * Copyright (C) 2011 Motorola Mobility, Inc. All rights reserved.
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
28 #include "core/html/HTMLOptionElement.h"
30 #include "bindings/core/v8/ExceptionState.h"
31 #include "core/HTMLNames.h"
32 #include "core/dom/Document.h"
33 #include "core/dom/NodeRenderStyle.h"
34 #include "core/dom/NodeTraversal.h"
35 #include "core/dom/ScriptLoader.h"
36 #include "core/dom/Text.h"
37 #include "core/dom/shadow/ShadowRoot.h"
38 #include "core/html/HTMLDataListElement.h"
39 #include "core/html/HTMLOptGroupElement.h"
40 #include "core/html/HTMLSelectElement.h"
41 #include "core/html/parser/HTMLParserIdioms.h"
42 #include "core/rendering/RenderTheme.h"
43 #include "wtf/Vector.h"
44 #include "wtf/text/StringBuilder.h"
48 using namespace HTMLNames;
50 HTMLOptionElement::HTMLOptionElement(Document& document)
51 : HTMLElement(optionTag, document)
55 setHasCustomStyleCallbacks();
56 ScriptWrappable::init(this);
59 HTMLOptionElement::~HTMLOptionElement()
63 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
65 RefPtrWillBeRawPtr<HTMLOptionElement> option = adoptRefWillBeNoop(new HTMLOptionElement(document));
66 option->ensureUserAgentShadowRoot();
67 return option.release();
70 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const AtomicString& value,
71 bool defaultSelected, bool selected, ExceptionState& exceptionState)
73 RefPtrWillBeRawPtr<HTMLOptionElement> element = adoptRefWillBeNoop(new HTMLOptionElement(document));
74 element->ensureUserAgentShadowRoot();
75 element->appendChild(Text::create(document, data.isNull() ? "" : data), exceptionState);
76 if (exceptionState.hadException())
80 element->setValue(value);
82 element->setAttribute(selectedAttr, emptyAtom);
83 element->setSelected(selected);
85 return element.release();
88 void HTMLOptionElement::attach(const AttachContext& context)
90 AttachContext optionContext(context);
91 if (context.resolvedStyle) {
92 ASSERT(!m_style || m_style == context.resolvedStyle);
93 m_style = context.resolvedStyle;
95 updateNonRenderStyle();
96 optionContext.resolvedStyle = m_style.get();
98 HTMLElement::attach(optionContext);
101 void HTMLOptionElement::detach(const AttachContext& context)
104 HTMLElement::detach(context);
107 String HTMLOptionElement::text() const
109 Document& document = this->document();
112 // WinIE does not use the label attribute, so as a quirk, we ignore it.
113 if (!document.inQuirksMode())
114 text = fastGetAttribute(labelAttr);
116 // FIXME: The following treats an element with the label attribute set to
117 // the empty string the same as an element with no label attribute at all.
118 // Is that correct? If it is, then should the label function work the same way?
120 text = collectOptionInnerText();
122 return text.stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
125 void HTMLOptionElement::setText(const String &text, ExceptionState& exceptionState)
127 RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this);
129 // Changing the text causes a recalc of a select's items, which will reset the selected
130 // index to the first item if the select is single selection with a menu list. We attempt to
131 // preserve the selected item.
132 RefPtrWillBeRawPtr<HTMLSelectElement> select = ownerSelectElement();
133 bool selectIsMenuList = select && select->usesMenuList();
134 int oldSelectedIndex = selectIsMenuList ? select->selectedIndex() : -1;
136 // Handle the common special case where there's exactly 1 child node, and it's a text node.
137 Node* child = firstChild();
138 if (child && child->isTextNode() && !child->nextSibling())
139 toText(child)->setData(text);
142 appendChild(Text::create(document(), text), exceptionState);
145 if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
146 select->setSelectedIndex(oldSelectedIndex);
149 void HTMLOptionElement::accessKeyAction(bool)
151 if (HTMLSelectElement* select = ownerSelectElement())
152 select->accessKeySetSelectedIndex(index());
155 int HTMLOptionElement::index() const
157 // It would be faster to cache the index, but harder to get it right in all cases.
159 HTMLSelectElement* selectElement = ownerSelectElement();
165 const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& items = selectElement->listItems();
166 size_t length = items.size();
167 for (size_t i = 0; i < length; ++i) {
168 if (!isHTMLOptionElement(*items[i]))
170 if (items[i].get() == this)
178 void HTMLOptionElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
180 if (name == valueAttr) {
181 if (HTMLDataListElement* dataList = ownerDataListElement())
182 dataList->optionElementChildrenChanged();
183 } else if (name == disabledAttr) {
184 bool oldDisabled = m_disabled;
185 m_disabled = !value.isNull();
186 if (oldDisabled != m_disabled) {
187 didAffectSelector(AffectedSelectorDisabled | AffectedSelectorEnabled);
188 if (renderer() && renderer()->style()->hasAppearance())
189 RenderTheme::theme().stateChanged(renderer(), EnabledControlState);
191 } else if (name == selectedAttr) {
192 if (bool willBeSelected = !value.isNull())
193 setSelected(willBeSelected);
194 } else if (name == labelAttr) {
197 HTMLElement::parseAttribute(name, value);
200 String HTMLOptionElement::value() const
202 const AtomicString& value = fastGetAttribute(valueAttr);
205 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
208 void HTMLOptionElement::setValue(const AtomicString& value)
210 setAttribute(valueAttr, value);
213 bool HTMLOptionElement::selected() const
215 if (HTMLSelectElement* select = ownerSelectElement()) {
216 // If a stylesheet contains option:checked selectors, this function is
217 // called during parsing. updateListItemSelectedStates() is O(N) where N
218 // is the number of option elements, so the <select> parsing would be
219 // O(N^2) without the isFinishedParsingChildren check. Also,
220 // updateListItemSelectedStates() determines default selection, and we'd
221 // like to avoid to determine default selection with incomplete option
223 if (!select->isFinishedParsingChildren())
225 select->updateListItemSelectedStates();
230 void HTMLOptionElement::setSelected(bool selected)
232 if (m_isSelected == selected)
235 setSelectedState(selected);
237 if (HTMLSelectElement* select = ownerSelectElement())
238 select->optionSelectionStateChanged(this, selected);
241 void HTMLOptionElement::setSelectedState(bool selected)
243 if (m_isSelected == selected)
246 m_isSelected = selected;
247 didAffectSelector(AffectedSelectorChecked);
249 if (HTMLSelectElement* select = ownerSelectElement())
250 select->invalidateSelectedItems();
253 void HTMLOptionElement::childrenChanged(const ChildrenChange& change)
255 if (HTMLDataListElement* dataList = ownerDataListElement())
256 dataList->optionElementChildrenChanged();
257 else if (HTMLSelectElement* select = ownerSelectElement())
258 select->optionElementChildrenChanged();
260 HTMLElement::childrenChanged(change);
263 HTMLDataListElement* HTMLOptionElement::ownerDataListElement() const
265 return Traversal<HTMLDataListElement>::firstAncestor(*this);
268 HTMLSelectElement* HTMLOptionElement::ownerSelectElement() const
270 return Traversal<HTMLSelectElement>::firstAncestor(*this);
273 String HTMLOptionElement::label() const
275 const AtomicString& label = fastGetAttribute(labelAttr);
278 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
281 void HTMLOptionElement::setLabel(const AtomicString& label)
283 setAttribute(labelAttr, label);
286 void HTMLOptionElement::updateNonRenderStyle()
288 m_style = originalStyleForRenderer();
289 if (HTMLSelectElement* select = ownerSelectElement())
290 select->updateListOnRenderer();
293 RenderStyle* HTMLOptionElement::nonRendererStyle() const
295 return m_style.get();
298 PassRefPtr<RenderStyle> HTMLOptionElement::customStyleForRenderer()
300 updateNonRenderStyle();
304 void HTMLOptionElement::didRecalcStyle(StyleRecalcChange change)
306 if (change == NoChange)
309 // FIXME: We ask our owner select to repaint regardless of which property changed.
310 if (HTMLSelectElement* select = ownerSelectElement()) {
311 if (RenderObject* renderer = select->renderer())
312 renderer->paintInvalidationForWholeRenderer();
316 String HTMLOptionElement::textIndentedToRespectGroupLabel() const
318 ContainerNode* parent = parentNode();
319 if (parent && isHTMLOptGroupElement(*parent))
324 bool HTMLOptionElement::isDisabledFormControl() const
326 if (ownElementDisabled())
328 if (Element* parent = parentElement())
329 return isHTMLOptGroupElement(*parent) && parent->isDisabledFormControl();
333 Node::InsertionNotificationRequest HTMLOptionElement::insertedInto(ContainerNode* insertionPoint)
335 if (HTMLSelectElement* select = ownerSelectElement()) {
336 select->setRecalcListItems();
337 // Do not call selected() since calling updateListItemSelectedStates()
338 // at this time won't do the right thing. (Why, exactly?)
339 // FIXME: Might be better to call this unconditionally, always passing m_isSelected,
340 // rather than only calling it if we are selected.
342 select->optionSelectionStateChanged(this, true);
343 select->scrollToSelection();
346 return HTMLElement::insertedInto(insertionPoint);
349 void HTMLOptionElement::removedFrom(ContainerNode* insertionPoint)
351 if (HTMLSelectElement* select = Traversal<HTMLSelectElement>::firstAncestorOrSelf(*insertionPoint)) {
352 select->setRecalcListItems();
353 select->optionRemoved(*this);
355 HTMLElement::removedFrom(insertionPoint);
358 String HTMLOptionElement::collectOptionInnerText() const
361 for (Node* node = firstChild(); node; ) {
362 if (node->isTextNode())
363 text.append(node->nodeValue());
364 // Text nodes inside script elements are not part of the option text.
365 if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
366 node = NodeTraversal::nextSkippingChildren(*node, this);
368 node = NodeTraversal::next(*node, this);
370 return text.toString();
373 HTMLFormElement* HTMLOptionElement::form() const
375 if (HTMLSelectElement* selectElement = ownerSelectElement())
376 return selectElement->formOwner();
381 void HTMLOptionElement::didAddUserAgentShadowRoot(ShadowRoot& root)
386 void HTMLOptionElement::updateLabel()
388 if (ShadowRoot* root = userAgentShadowRoot())
389 root->setTextContent(textIndentedToRespectGroupLabel());
392 bool HTMLOptionElement::spatialNavigationFocused() const
394 HTMLSelectElement* select = ownerSelectElement();
395 if (!select || !select->focused())
397 return select->spatialNavigationFocusedOption() == this;
400 bool HTMLOptionElement::isDisplayNone() const
402 // If m_style is not set, then the node is still unattached.
403 // We have to wait till it gets attached to read the display property.
407 if (m_style->display() != NONE) {
408 Element* parent = parentElement();
410 if (isHTMLOptGroupElement(*parent)) {
411 RenderStyle* parentStyle = parent->renderStyle() ? parent->renderStyle() : parent->computedStyle();
412 return !parentStyle || parentStyle->display() == NONE;
415 return m_style->display() == NONE;