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 "HTMLNames.h"
31 #include "bindings/v8/ExceptionState.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 adoptRefWillBeRefCountedGarbageCollected(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 = adoptRefWillBeRefCountedGarbageCollected(new HTMLOptionElement(document));
67 RefPtr<Text> text = Text::create(document, data.isNull() ? "" : data);
69 element->appendChild(text.release(), exceptionState);
70 if (exceptionState.hadException())
74 element->setValue(value);
76 element->setAttribute(selectedAttr, emptyAtom);
77 element->setSelected(selected);
79 return element.release();
82 void HTMLOptionElement::attach(const AttachContext& context)
84 AttachContext optionContext(context);
85 if (context.resolvedStyle) {
86 ASSERT(!m_style || m_style == context.resolvedStyle);
87 m_style = context.resolvedStyle;
89 updateNonRenderStyle();
90 optionContext.resolvedStyle = m_style.get();
92 HTMLElement::attach(optionContext);
95 void HTMLOptionElement::detach(const AttachContext& context)
98 HTMLElement::detach(context);
101 bool HTMLOptionElement::rendererIsFocusable() const
103 // Option elements do not have a renderer so we check the renderStyle instead.
104 return renderStyle() && renderStyle()->display() != NONE;
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 RefPtr<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(), EnabledState);
191 } else if (name == selectedAttr) {
192 if (bool willBeSelected = !value.isNull())
193 setSelected(willBeSelected);
195 HTMLElement::parseAttribute(name, value);
198 String HTMLOptionElement::value() const
200 const AtomicString& value = fastGetAttribute(valueAttr);
203 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
206 void HTMLOptionElement::setValue(const AtomicString& value)
208 setAttribute(valueAttr, value);
211 bool HTMLOptionElement::selected() const
213 if (HTMLSelectElement* select = ownerSelectElement()) {
214 // If a stylesheet contains option:checked selectors, this function is
215 // called during parsing. updateListItemSelectedStates() is O(N) where N
216 // is the number of option elements, so the <select> parsing would be
217 // O(N^2) without the isFinishedParsingChildren check. Also,
218 // updateListItemSelectedStates() determines default selection, and we'd
219 // like to avoid to determine default selection with incomplete option
221 if (!select->isFinishedParsingChildren())
223 select->updateListItemSelectedStates();
228 void HTMLOptionElement::setSelected(bool selected)
230 if (m_isSelected == selected)
233 setSelectedState(selected);
235 if (HTMLSelectElement* select = ownerSelectElement())
236 select->optionSelectionStateChanged(this, selected);
239 void HTMLOptionElement::setSelectedState(bool selected)
241 if (m_isSelected == selected)
244 m_isSelected = selected;
245 didAffectSelector(AffectedSelectorChecked);
247 if (HTMLSelectElement* select = ownerSelectElement())
248 select->invalidateSelectedItems();
251 void HTMLOptionElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
253 if (HTMLDataListElement* dataList = ownerDataListElement())
254 dataList->optionElementChildrenChanged();
255 else if (HTMLSelectElement* select = ownerSelectElement())
256 select->optionElementChildrenChanged();
257 HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
260 HTMLDataListElement* HTMLOptionElement::ownerDataListElement() const
262 return Traversal<HTMLDataListElement>::firstAncestor(*this);
265 HTMLSelectElement* HTMLOptionElement::ownerSelectElement() const
267 return Traversal<HTMLSelectElement>::firstAncestor(*this);
270 String HTMLOptionElement::label() const
272 const AtomicString& label = fastGetAttribute(labelAttr);
275 return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
278 void HTMLOptionElement::setLabel(const AtomicString& label)
280 setAttribute(labelAttr, label);
283 void HTMLOptionElement::updateNonRenderStyle()
285 bool oldDisplayNoneStatus = isDisplayNone();
286 m_style = originalStyleForRenderer();
287 if (oldDisplayNoneStatus != isDisplayNone()) {
288 if (HTMLSelectElement* select = ownerSelectElement())
289 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())
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 String HTMLOptionElement::collectOptionInnerText() const
352 for (Node* node = firstChild(); node; ) {
353 if (node->isTextNode())
354 text.append(node->nodeValue());
355 // Text nodes inside script elements are not part of the option text.
356 if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
357 node = NodeTraversal::nextSkippingChildren(*node, this);
359 node = NodeTraversal::next(*node, this);
361 return text.toString();
364 HTMLFormElement* HTMLOptionElement::form() const
366 if (HTMLSelectElement* selectElement = ownerSelectElement())
367 return selectElement->formOwner();
372 bool HTMLOptionElement::isDisplayNone() const
374 ContainerNode* parent = parentNode();
375 // Check for parent optgroup having display NONE
376 if (parent && isHTMLOptGroupElement(*parent)) {
377 if (toHTMLOptGroupElement(*parent).isDisplayNone())
380 RenderStyle* style = nonRendererStyle();
381 return style && style->display() == NONE;
384 } // namespace WebCore