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/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/html/HTMLDataListElement.h"
38 #include "core/html/HTMLSelectElement.h"
39 #include "core/html/parser/HTMLParserIdioms.h"
40 #include "core/rendering/RenderTheme.h"
41 #include "wtf/Vector.h"
42 #include "wtf/text/StringBuilder.h"
46 using namespace HTMLNames;
48 HTMLOptionElement::HTMLOptionElement(Document& document)
49 : HTMLElement(optionTag, document)
53 setHasCustomStyleCallbacks();
54 ScriptWrappable::init(this);
57 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
59 return adoptRefWillBeNoop(new HTMLOptionElement(document));
62 PassRefPtrWillBeRawPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const AtomicString& value,
63 bool defaultSelected, bool selected, ExceptionState& exceptionState)
65 RefPtrWillBeRawPtr<HTMLOptionElement> element = adoptRefWillBeNoop(new HTMLOptionElement(document));
66 element->appendChild(Text::create(document, data.isNull() ? "" : data), exceptionState);
67 if (exceptionState.hadException())
71 element->setValue(value);
73 element->setAttribute(selectedAttr, emptyAtom);
74 element->setSelected(selected);
76 return element.release();
79 void HTMLOptionElement::attach(const AttachContext& context)
81 AttachContext optionContext(context);
82 if (context.resolvedStyle) {
83 ASSERT(!m_style || m_style == context.resolvedStyle);
84 m_style = context.resolvedStyle;
86 updateNonRenderStyle();
87 optionContext.resolvedStyle = m_style.get();
89 HTMLElement::attach(optionContext);
92 void HTMLOptionElement::detach(const AttachContext& context)
95 HTMLElement::detach(context);
98 bool HTMLOptionElement::rendererIsFocusable() const
100 // Option elements do not have a renderer so we check the renderStyle instead.
101 return renderStyle() && renderStyle()->display() != NONE;
104 String HTMLOptionElement::text() const
106 Document& document = this->document();
109 // WinIE does not use the label attribute, so as a quirk, we ignore it.
110 if (!document.inQuirksMode())
111 text = fastGetAttribute(labelAttr);
113 // FIXME: The following treats an element with the label attribute set to
114 // the empty string the same as an element with no label attribute at all.
115 // Is that correct? If it is, then should the label function work the same way?
117 text = collectOptionInnerText();
119 return text.stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
122 void HTMLOptionElement::setText(const String &text, ExceptionState& exceptionState)
124 RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this);
126 // Changing the text causes a recalc of a select's items, which will reset the selected
127 // index to the first item if the select is single selection with a menu list. We attempt to
128 // preserve the selected item.
129 RefPtrWillBeRawPtr<HTMLSelectElement> select = ownerSelectElement();
130 bool selectIsMenuList = select && select->usesMenuList();
131 int oldSelectedIndex = selectIsMenuList ? select->selectedIndex() : -1;
133 // Handle the common special case where there's exactly 1 child node, and it's a text node.
134 Node* child = firstChild();
135 if (child && child->isTextNode() && !child->nextSibling())
136 toText(child)->setData(text);
139 appendChild(Text::create(document(), text), exceptionState);
142 if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
143 select->setSelectedIndex(oldSelectedIndex);
146 void HTMLOptionElement::accessKeyAction(bool)
148 if (HTMLSelectElement* select = ownerSelectElement())
149 select->accessKeySetSelectedIndex(index());
152 int HTMLOptionElement::index() const
154 // It would be faster to cache the index, but harder to get it right in all cases.
156 HTMLSelectElement* selectElement = ownerSelectElement();
162 const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& items = selectElement->listItems();
163 size_t length = items.size();
164 for (size_t i = 0; i < length; ++i) {
165 if (!isHTMLOptionElement(*items[i]))
167 if (items[i].get() == this)
175 void HTMLOptionElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
177 if (name == valueAttr) {
178 if (HTMLDataListElement* dataList = ownerDataListElement())
179 dataList->optionElementChildrenChanged();
180 } else if (name == disabledAttr) {
181 bool oldDisabled = m_disabled;
182 m_disabled = !value.isNull();
183 if (oldDisabled != m_disabled) {
184 didAffectSelector(AffectedSelectorDisabled | AffectedSelectorEnabled);
185 if (renderer() && renderer()->style()->hasAppearance())
186 RenderTheme::theme().stateChanged(renderer(), EnabledControlState);
188 } else if (name == selectedAttr) {
189 if (bool willBeSelected = !value.isNull())
190 setSelected(willBeSelected);
192 HTMLElement::parseAttribute(name, value);
195 String HTMLOptionElement::value() const
197 const AtomicString& value = fastGetAttribute(valueAttr);
200 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
203 void HTMLOptionElement::setValue(const AtomicString& value)
205 setAttribute(valueAttr, value);
208 bool HTMLOptionElement::selected() const
210 if (HTMLSelectElement* select = ownerSelectElement()) {
211 // If a stylesheet contains option:checked selectors, this function is
212 // called during parsing. updateListItemSelectedStates() is O(N) where N
213 // is the number of option elements, so the <select> parsing would be
214 // O(N^2) without the isFinishedParsingChildren check. Also,
215 // updateListItemSelectedStates() determines default selection, and we'd
216 // like to avoid to determine default selection with incomplete option
218 if (!select->isFinishedParsingChildren())
220 select->updateListItemSelectedStates();
225 void HTMLOptionElement::setSelected(bool selected)
227 if (m_isSelected == selected)
230 setSelectedState(selected);
232 if (HTMLSelectElement* select = ownerSelectElement())
233 select->optionSelectionStateChanged(this, selected);
236 void HTMLOptionElement::setSelectedState(bool selected)
238 if (m_isSelected == selected)
241 m_isSelected = selected;
242 didAffectSelector(AffectedSelectorChecked);
244 if (HTMLSelectElement* select = ownerSelectElement())
245 select->invalidateSelectedItems();
248 void HTMLOptionElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
250 if (HTMLDataListElement* dataList = ownerDataListElement())
251 dataList->optionElementChildrenChanged();
252 else if (HTMLSelectElement* select = ownerSelectElement())
253 select->optionElementChildrenChanged();
254 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
257 HTMLDataListElement* HTMLOptionElement::ownerDataListElement() const
259 return Traversal<HTMLDataListElement>::firstAncestor(*this);
262 HTMLSelectElement* HTMLOptionElement::ownerSelectElement() const
264 return Traversal<HTMLSelectElement>::firstAncestor(*this);
267 String HTMLOptionElement::label() const
269 const AtomicString& label = fastGetAttribute(labelAttr);
272 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
275 void HTMLOptionElement::setLabel(const AtomicString& label)
277 setAttribute(labelAttr, label);
280 void HTMLOptionElement::updateNonRenderStyle()
282 bool oldDisplayNoneStatus = isDisplayNone();
283 m_style = originalStyleForRenderer();
284 if (oldDisplayNoneStatus != isDisplayNone()) {
285 if (HTMLSelectElement* select = ownerSelectElement())
286 select->updateListOnRenderer();
290 RenderStyle* HTMLOptionElement::nonRendererStyle() const
292 return m_style.get();
295 PassRefPtr<RenderStyle> HTMLOptionElement::customStyleForRenderer()
297 updateNonRenderStyle();
301 void HTMLOptionElement::didRecalcStyle(StyleRecalcChange change)
303 if (change == NoChange)
306 // FIXME: We ask our owner select to repaint regardless of which property changed.
307 if (HTMLSelectElement* select = ownerSelectElement()) {
308 if (RenderObject* renderer = select->renderer())
309 renderer->paintInvalidationForWholeRenderer();
313 String HTMLOptionElement::textIndentedToRespectGroupLabel() const
315 ContainerNode* parent = parentNode();
316 if (parent && isHTMLOptGroupElement(*parent))
321 bool HTMLOptionElement::isDisabledFormControl() const
323 if (ownElementDisabled())
325 if (Element* parent = parentElement())
326 return isHTMLOptGroupElement(*parent) && parent->isDisabledFormControl();
330 Node::InsertionNotificationRequest HTMLOptionElement::insertedInto(ContainerNode* insertionPoint)
332 if (HTMLSelectElement* select = ownerSelectElement()) {
333 select->setRecalcListItems();
334 // Do not call selected() since calling updateListItemSelectedStates()
335 // at this time won't do the right thing. (Why, exactly?)
336 // FIXME: Might be better to call this unconditionally, always passing m_isSelected,
337 // rather than only calling it if we are selected.
339 select->optionSelectionStateChanged(this, true);
340 select->scrollToSelection();
343 return HTMLElement::insertedInto(insertionPoint);
346 String HTMLOptionElement::collectOptionInnerText() const
349 for (Node* node = firstChild(); node; ) {
350 if (node->isTextNode())
351 text.append(node->nodeValue());
352 // Text nodes inside script elements are not part of the option text.
353 if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
354 node = NodeTraversal::nextSkippingChildren(*node, this);
356 node = NodeTraversal::next(*node, this);
358 return text.toString();
361 HTMLFormElement* HTMLOptionElement::form() const
363 if (HTMLSelectElement* selectElement = ownerSelectElement())
364 return selectElement->formOwner();
369 bool HTMLOptionElement::isDisplayNone() const
371 ContainerNode* parent = parentNode();
372 // Check for parent optgroup having display NONE
373 if (parent && isHTMLOptGroupElement(*parent)) {
374 if (toHTMLOptGroupElement(*parent).isDisplayNone())
377 RenderStyle* style = nonRendererStyle();
378 return style && style->display() == NONE;
381 } // namespace WebCore