View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.html;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_HTMLOPTIONSCOLLECTION_NAMED_PROPERTIES_ENUMERABLE;
18  import static org.htmlunit.BrowserVersionFeatures.JS_NAMED_PROPERTIES_OWN_PROPERTY_NAMES_INCLUDE_HIDDEN;
19  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
20  
21  import java.util.ArrayList;
22  import java.util.Arrays;
23  import java.util.List;
24  
25  import org.htmlunit.SgmlPage;
26  import org.htmlunit.WebAssert;
27  import org.htmlunit.corejs.javascript.CompoundOperationMap;
28  import org.htmlunit.corejs.javascript.Context;
29  import org.htmlunit.corejs.javascript.Scriptable;
30  import org.htmlunit.corejs.javascript.ScriptableObject;
31  import org.htmlunit.corejs.javascript.VarScope;
32  import org.htmlunit.html.DomElement;
33  import org.htmlunit.html.ElementFactory;
34  import org.htmlunit.html.HtmlOption;
35  import org.htmlunit.html.HtmlSelect;
36  import org.htmlunit.javascript.HtmlUnitScriptable;
37  import org.htmlunit.javascript.JavaScriptEngine;
38  import org.htmlunit.javascript.configuration.JsxClass;
39  import org.htmlunit.javascript.configuration.JsxConstructor;
40  import org.htmlunit.javascript.configuration.JsxFunction;
41  import org.htmlunit.javascript.configuration.JsxGetter;
42  import org.htmlunit.javascript.configuration.JsxSetter;
43  import org.htmlunit.javascript.configuration.JsxSymbol;
44  import org.htmlunit.javascript.host.dom.DOMException;
45  
46  /**
47   * This is the array returned by the "options" property of Select.
48   *
49   * @author David K. Taylor
50   * @author Christian Sell
51   * @author Marc Guillemot
52   * @author Daniel Gredler
53   * @author Bruce Faulkner
54   * @author Ahmed Ashour
55   * @author Ronald Brill
56   *
57   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection">MDN Documentation</a>
58   */
59  @JsxClass
60  public class HTMLOptionsCollection extends HtmlUnitScriptable {
61  
62      private HtmlSelect htmlSelect_;
63  
64      /**
65       * Creates an instance.
66       */
67      public HTMLOptionsCollection() {
68          super();
69      }
70  
71      /**
72       * JavaScript constructor.
73       */
74      @JsxConstructor
75      public void jsConstructor() {
76          // nothing to do
77      }
78  
79      /**
80       * Creates an instance.
81       * @param parentScope parent scope
82       */
83      public HTMLOptionsCollection(final VarScope parentScope) {
84          super();
85          setParentScope(parentScope);
86          setPrototype(getPrototype(getClass()));
87      }
88  
89      /**
90       * Initializes this object.
91       * @param select the HtmlSelect that this object will retrieve elements from
92       */
93      public void initialize(final HtmlSelect select) {
94          WebAssert.notNull("select", select);
95          htmlSelect_ = select;
96      }
97  
98      /**
99       * {@inheritDoc}
100      */
101     @Override
102     protected int getIndexedPropertyCount() {
103         if (htmlSelect_ == null) {
104             return 0;
105         }
106         return getLength();
107     }
108 
109     /**
110      * {@inheritDoc}
111      */
112     @Override
113     protected boolean isIndexedPropertyWritable() {
114         return true;
115     }
116 
117     /**
118      * Overridden to support the named properties (the ids and names of the options).
119      * {@inheritDoc}
120      */
121     @Override
122     public Object get(final String name, final Scriptable start) {
123         final Object response = super.get(name, start);
124         if (response != NOT_FOUND) {
125             return response;
126         }
127 
128         final HtmlOption option = getNamedOption(name);
129         if (option != null) {
130             return getScriptableFor(option);
131         }
132         return NOT_FOUND;
133     }
134 
135     /**
136      * Overridden to support the named properties (the ids and names of the options).
137      * {@inheritDoc}
138      */
139     @Override
140     public boolean has(final String name, final Scriptable start) {
141         return super.has(name, start) || getNamedOption(name) != null;
142     }
143 
144     /**
145      * Overridden to list the named properties (the ids and names of the options)
146      * after the indexed properties.
147      * {@inheritDoc}
148      */
149     @Override
150     protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
151             final boolean getNonEnumerable, final boolean getSymbols) {
152         final Object[] ids = super.getIds(map, getNonEnumerable, getSymbols);
153         if (htmlSelect_ == null
154                 || !(getNonEnumerable
155                         || getBrowserVersion().hasFeature(JS_HTMLOPTIONSCOLLECTION_NAMED_PROPERTIES_ENUMERABLE))) {
156             return ids;
157         }
158 
159         // Object.getOwnPropertyNames() (but not Object.keys()) may list the hidden names also
160         final boolean includeHidden = getNonEnumerable
161                 && getBrowserVersion().hasFeature(JS_NAMED_PROPERTIES_OWN_PROPERTY_NAMES_INCLUDE_HIDDEN);
162         final List<Object> result = new ArrayList<>(Arrays.asList(ids));
163         for (final String name : getSupportedPropertyNames()) {
164             if (!result.contains(name) && (includeHidden || getNamedOption(name) != null)) {
165                 result.add(name);
166             }
167         }
168         return result.toArray();
169     }
170 
171     /**
172      * Overridden to provide property descriptors for the named properties.
173      * {@inheritDoc}
174      */
175     @Override
176     protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
177         final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
178         if (descInfo != null) {
179             return descInfo;
180         }
181 
182         if (id instanceof CharSequence) {
183             final HtmlOption option = getNamedOption(id.toString());
184             if (option != null) {
185                 int attributes = ScriptableObject.READONLY;
186                 if (!getBrowserVersion().hasFeature(JS_HTMLOPTIONSCOLLECTION_NAMED_PROPERTIES_ENUMERABLE)) {
187                     attributes |= ScriptableObject.DONTENUM;
188                 }
189                 return ScriptableObject.buildDataDescriptor(getScriptableFor(option), attributes);
190             }
191         }
192         return null;
193     }
194 
195     /**
196      * Returns the supported property names (the ids and names of the options in tree order).
197      *
198      * @return the names
199      * @see <a href="https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-names">
200      *     DOM Standard - HTMLCollection supported property names</a>
201      */
202     private List<String> getSupportedPropertyNames() {
203         final List<String> names = new ArrayList<>();
204         for (final HtmlOption option : htmlSelect_.getOptions()) {
205             final String id = option.getId();
206             if (!id.isEmpty() && !names.contains(id)) {
207                 names.add(id);
208             }
209             final String name = option.getAttributeDirect(DomElement.NAME_ATTRIBUTE);
210             if (ATTRIBUTE_NOT_DEFINED != name && !name.isEmpty() && !names.contains(name)) {
211                 names.add(name);
212             }
213         }
214         return names;
215     }
216 
217     /**
218      * Returns the option for the given named property; the named property is not visible
219      * if the prototype chain has a property with this name.
220      *
221      * @param name the property name
222      * @return the option or {@code null}
223      */
224     private HtmlOption getNamedOption(final String name) {
225         if (htmlSelect_ == null || name == null || name.isEmpty()) {
226             return null;
227         }
228         final Scriptable prototype = getPrototype();
229         if (prototype != null && ScriptableObject.hasProperty(prototype, name)) {
230             return null;
231         }
232 
233         for (final HtmlOption option : htmlSelect_.getOptions()) {
234             if (name.equals(option.getId())
235                     || name.equals(option.getAttributeDirect(DomElement.NAME_ATTRIBUTE))) {
236                 return option;
237             }
238         }
239         return null;
240     }
241 
242     /**
243      * Returns the object at the specified index.
244      *
245      * @param index the index
246      * @param start the object that get is being called on
247      * @return the object or NOT_FOUND
248      */
249     @Override
250     public Object get(final int index, final Scriptable start) {
251         if (htmlSelect_ == null || index < 0) {
252             return JavaScriptEngine.UNDEFINED;
253         }
254 
255         if (index >= htmlSelect_.getOptionSize()) {
256             return JavaScriptEngine.UNDEFINED;
257         }
258 
259         return getScriptableFor(htmlSelect_.getOption(index));
260     }
261 
262     /**
263      * {@inheritDoc}
264      */
265     @Override
266     public void put(final String name, final Scriptable start, final Object value) {
267         if (htmlSelect_ == null) {
268             // This object hasn't been initialized; it's probably being used as a prototype.
269             // Just pretend we didn't even see this invocation and let Rhino handle it.
270             super.put(name, start, value);
271             return;
272         }
273 
274         final HTMLSelectElement parent = htmlSelect_.getScriptableObject();
275 
276         if (!super.has(name, start) && ScriptableObject.hasProperty(parent, name)) {
277             ScriptableObject.putProperty(parent, name, value);
278         }
279         else {
280             super.put(name, start, value);
281         }
282     }
283 
284     /**
285      * Returns the object at the specified index.
286      *
287      * @param index the index
288      * @return the object or NOT_FOUND
289      */
290     @JsxFunction
291     public Object item(final int index) {
292         final Object item = get(index, this);
293         if (JavaScriptEngine.UNDEFINED == item) {
294             return null;
295         }
296         return item;
297     }
298 
299     /**
300      * Sets the index property.
301      * @param index the index
302      * @param start the scriptable object that was originally invoked for this property
303      * @param newValue the new value
304      */
305     @Override
306     public void put(final int index, final Scriptable start, final Object newValue) {
307         if (newValue == null) {
308             // Remove the indexed option.
309             htmlSelect_.removeOption(index);
310         }
311         else {
312             final HTMLOptionElement option = (HTMLOptionElement) newValue;
313             final HtmlOption htmlOption = (HtmlOption) option.getDomNodeOrNull();
314             if (index >= getLength()) {
315                 setLength(index);
316                 // Add a new option at the end.
317                 htmlSelect_.appendOption(htmlOption);
318             }
319             else {
320                 // Replace the indexed option.
321                 htmlSelect_.replaceOption(index, htmlOption);
322             }
323         }
324     }
325 
326     /**
327      * Returns the number of elements in this array.
328      *
329      * @return the number of elements in the array
330      */
331     @JsxGetter
332     public int getLength() {
333         return htmlSelect_.getOptionSize();
334     }
335 
336     /**
337      * Changes the number of options: removes options if the new length
338      * is less than the current one else add new empty options to reach the
339      * new length.
340      * @param newLength the new length property value
341      */
342     @JsxSetter
343     public void setLength(final int newLength) {
344         if (newLength < 0) {
345             return;
346         }
347 
348         final int currentLength = htmlSelect_.getOptionSize();
349         if (currentLength > newLength) {
350             htmlSelect_.setOptionSize(newLength);
351         }
352         else {
353             final SgmlPage page = htmlSelect_.getPage();
354             final ElementFactory factory = page.getWebClient().getPageCreator()
355                                             .getHtmlParser().getFactory(HtmlOption.TAG_NAME);
356             for (int i = currentLength; i < newLength; i++) {
357                 final HtmlOption option = (HtmlOption) factory.createElement(page, HtmlOption.TAG_NAME, null);
358                 htmlSelect_.appendOption(option);
359             }
360         }
361     }
362 
363     /**
364      * Adds a new item to the option collection.
365      *
366      * <p><b><i>Implementation Note:</i></b> The specification for the JavaScript add() method
367      * actually calls for the optional newIndex parameter to be an integer. However, the
368      * newIndex parameter is specified as an Object here rather than an int because of the
369      * way Rhino and HtmlUnit process optional parameters for the JavaScript method calls.
370      * If the newIndex parameter were specified as an int, then the Undefined value for an
371      * integer is specified as NaN (Not A Number, which is a Double value), but Rhino
372      * translates this value into 0 (perhaps correctly?) when converting NaN into an int.
373      * As a result, when the newIndex parameter is not specified, it is impossible to make
374      * a distinction between a caller of the form add(someObject) and add (someObject, 0).
375      * Since the behavior of these two call forms is different, the newIndex parameter is
376      * specified as an Object. If the newIndex parameter is not specified by the actual
377      * JavaScript code being run, then newIndex is of type org.htmlunit.corejs.javascript.Undefined.
378      * If the newIndex parameter is specified, then it should be of type java.lang.Number and
379      * can be converted into an integer value.</p>
380      *
381      * <p>This method will call the {@link #put(int, Scriptable, Object)} method for actually
382      * adding the element to the collection.</p>
383      *
384      * <p>Per the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection/add">MDN
385      * documentation</a> for the JavaScript add() method of the options collection,
386      * the index parameter is specified as follows:
387      * </p>
388      * <p>
389      * <i>Optional. Integer that specifies the index position in the collection where the element is
390      * placed. If no value is given, the method places the element at the end of the collection.</i>
391      * </p>
392      *
393      * @param newOptionObject the DomNode to insert in the collection
394      * @param beforeOptionObject An optional parameter which specifies the index position in the
395      *        collection where the element is placed. If no value is given, the method places
396      *        the element at the end of the collection.
397      *
398      * @see #put(int, Scriptable, Object)
399      */
400     @JsxFunction
401     public void add(final Object newOptionObject, final Object beforeOptionObject) {
402         final HtmlOption htmlOption = (HtmlOption) ((HTMLOptionElement) newOptionObject).getDomNodeOrNull();
403 
404         HtmlOption beforeOption = null;
405         // If newIndex was specified, then use it
406         if (beforeOptionObject instanceof Number) {
407             final int index = ((Integer) Context.jsToJava(beforeOptionObject, Integer.class)).intValue();
408             if (index < 0 || index >= getLength()) {
409                 // Add a new option at the end.
410                 htmlSelect_.appendOption(htmlOption);
411                 return;
412             }
413 
414             beforeOption = (HtmlOption) ((HTMLOptionElement) item(index)).getDomNodeOrDie();
415         }
416         else if (beforeOptionObject instanceof HTMLOptionElement element) {
417             beforeOption = (HtmlOption) element.getDomNodeOrDie();
418             if (beforeOption.getParentNode() != htmlSelect_) {
419                 throw JavaScriptEngine.asJavaScriptException(
420                         getWindow(),
421                         "Unknown option.",
422                         DOMException.NOT_FOUND_ERR);
423 
424             }
425         }
426 
427         if (beforeOption == null) {
428             htmlSelect_.appendOption(htmlOption);
429             return;
430         }
431 
432         beforeOption.insertBefore(htmlOption);
433     }
434 
435     /**
436      * Removes the option at the specified index.
437      * @param index the option index
438      */
439     @JsxFunction
440     public void remove(final int index) {
441         if (index < 0 || index >= getLength()) {
442             return;
443         }
444 
445         htmlSelect_.removeOption(index);
446     }
447 
448     /**
449      * Returns the value of the {@code selectedIndex} property.
450      * @return the {@code selectedIndex} property
451      */
452     @JsxGetter
453     public int getSelectedIndex() {
454         return htmlSelect_.getSelectedIndex();
455     }
456 
457     /**
458      * Sets the value of the {@code selectedIndex} property.
459      * @param index the new value
460      */
461     @JsxSetter
462     public void setSelectedIndex(final int index) {
463         htmlSelect_.setSelectedIndex(index);
464     }
465 
466     /**
467      * Returns the {@code Symbol.iterator} function that allows iterating over this collection.
468      * @return the Iterator symbol
469      */
470     @JsxSymbol
471     public Scriptable iterator() {
472         return JavaScriptEngine.newArrayIteratorTypeValues(getParentScope(), this);
473     }
474 }