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;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_NAMED_PROPERTIES_OWN_PROPERTY_NAMES_INCLUDE_HIDDEN;
18  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.List;
22  import java.util.Locale;
23  
24  import org.htmlunit.corejs.javascript.CompoundOperationMap;
25  import org.htmlunit.corejs.javascript.Context;
26  import org.htmlunit.corejs.javascript.Scriptable;
27  import org.htmlunit.corejs.javascript.ScriptableObject;
28  import org.htmlunit.html.DomElement;
29  import org.htmlunit.html.DomNode;
30  import org.htmlunit.html.HtmlElement;
31  import org.htmlunit.javascript.HtmlUnitScriptable;
32  import org.htmlunit.javascript.JavaScriptEngine;
33  import org.htmlunit.javascript.configuration.JsxClass;
34  import org.htmlunit.javascript.configuration.JsxConstructor;
35  import org.htmlunit.javascript.configuration.JsxFunction;
36  import org.htmlunit.javascript.configuration.JsxGetter;
37  import org.htmlunit.javascript.configuration.JsxSymbol;
38  import org.htmlunit.javascript.host.dom.Attr;
39  import org.htmlunit.javascript.host.dom.Node;
40  
41  /**
42   * A collection of nodes that can be accessed by name. String comparisons in this class are case-insensitive when
43   * used with an {@link org.htmlunit.html.HtmlElement},
44   * but case-sensitive when used with a {@link org.htmlunit.html.DomElement}.
45   *
46   * @author Daniel Gredler
47   * @author Ahmed Ashour
48   * @author Marc Guillemot
49   * @author Ronald Brill
50   * @author Frank Danek
51   *
52   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap">MDN Documentation</a>
53   */
54  @JsxClass
55  public class NamedNodeMap extends HtmlUnitScriptable {
56  
57      private final org.w3c.dom.NamedNodeMap attributes_;
58  
59      /**
60       * Default constructor for prototype instantiation.
61       */
62      public NamedNodeMap() {
63          super();
64          attributes_ = null;
65      }
66  
67      /**
68       * Creates an instance of this object.
69       */
70      @JsxConstructor
71      public void jsConstructor() {
72          // nothing to do
73      }
74  
75      /**
76       * Creates a new named node map for the specified element.
77       *
78       * @param element the owning element
79       */
80      public NamedNodeMap(final DomElement element) {
81          super();
82          setParentScope(element.getScriptableObject().getParentScope());
83          setPrototype(getPrototype(getClass()));
84  
85          attributes_ = element.getAttributes();
86          setDomNode(element, false);
87      }
88  
89      /**
90       * {@inheritDoc}
91       */
92      @Override
93      protected int getIndexedPropertyCount() {
94          if (attributes_ == null) {
95              return 0;
96          }
97          return getLength();
98      }
99  
100     /**
101      * {@inheritDoc}
102      */
103     @Override
104     public final Object get(final int index, final Scriptable start) {
105         final NamedNodeMap startMap = (NamedNodeMap) start;
106         final Object response = startMap.item(index);
107         if (response != null) {
108             return response;
109         }
110         return NOT_FOUND;
111     }
112 
113     /**
114      * {@inheritDoc}
115      */
116     @Override
117     public Object get(final String name, final Scriptable start) {
118         Object response = super.get(name, start);
119         if (response != NOT_FOUND) {
120             return response;
121         }
122 
123         response = getNamedProperty(name);
124         if (response != null) {
125             return response;
126         }
127 
128         return NOT_FOUND;
129     }
130 
131     /**
132      * Overridden to support the named properties (the attribute names).
133      * {@inheritDoc}
134      */
135     @Override
136     public boolean has(final String name, final Scriptable start) {
137         if (super.has(name, start)) {
138             return true;
139         }
140         return getNamedProperty(name) != null;
141     }
142 
143     /**
144      * Overridden to list the named properties (the attribute names) after the indexed properties;
145      * the named properties are not enumerable.
146      * {@inheritDoc}
147      */
148     @Override
149     protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
150             final boolean getNonEnumerable, final boolean getSymbols) {
151         final Object[] ids = super.getIds(map, getNonEnumerable, getSymbols);
152         if (attributes_ == null || !getNonEnumerable) {
153             return ids;
154         }
155 
156         final boolean includeHidden =
157                 getBrowserVersion().hasFeature(JS_NAMED_PROPERTIES_OWN_PROPERTY_NAMES_INCLUDE_HIDDEN);
158         final List<Object> result = new ArrayList<>(Arrays.asList(ids));
159         for (final String name : getSupportedPropertyNames()) {
160             if (!result.contains(name) && (includeHidden || !isPrototypeProperty(name))) {
161                 result.add(name);
162             }
163         }
164         return result.toArray();
165     }
166 
167     /**
168      * Overridden to provide property descriptors for the named properties.
169      * {@inheritDoc}
170      */
171     @Override
172     protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
173         final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
174         if (descInfo != null) {
175             return descInfo;
176         }
177 
178         if (id instanceof CharSequence) {
179             final HtmlUnitScriptable attr = getNamedProperty(id.toString());
180             if (attr != null) {
181                 return ScriptableObject.buildDataDescriptor(attr,
182                         ScriptableObject.READONLY | ScriptableObject.DONTENUM);
183             }
184         }
185         return null;
186     }
187 
188     /**
189      * Returns the supported property names (the qualified names of the attributes).
190      * For html elements in a html document names containing upper case letters are excluded.
191      *
192      * @return the names
193      * @see <a href="https://dom.spec.whatwg.org/#ref-for-dfn-supported-property-names%E2%91%A0">
194      *     DOM Standard - NamedNodeMap supported property names</a>
195      */
196     private List<String> getSupportedPropertyNames() {
197         final boolean skipUpperCase = isHtmlElementInHtmlDocument();
198 
199         final List<String> names = new ArrayList<>();
200         for (int i = 0; i < attributes_.getLength(); i++) {
201             final String name = attributes_.item(i).getNodeName();
202             if (names.contains(name)) {
203                 continue;
204             }
205             if (skipUpperCase && !name.equals(name.toLowerCase(Locale.ROOT))) {
206                 continue;
207             }
208             names.add(name);
209         }
210         return names;
211     }
212 
213     /**
214      * Returns the attribute for the given named property (the named property getter).
215      * For html elements in a html document the name is converted to lower case first;
216      * the attribute name has to match exactly. The named property is not visible
217      * if the prototype chain has a property with this name.
218      *
219      * @param name the property name
220      * @return the attribute or {@code null}
221      * @see <a href="https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name">
222      *     DOM Standard - get an attribute by name</a>
223      */
224     private HtmlUnitScriptable getNamedProperty(final String name) {
225         if (attributes_ == null || isPrototypeProperty(name)) {
226             return null;
227         }
228 
229         final String qualifiedName = isHtmlElementInHtmlDocument() ? name.toLowerCase(Locale.ROOT) : name;
230         for (int i = 0; i < attributes_.getLength(); i++) {
231             final DomNode attr = (DomNode) attributes_.item(i);
232             if (qualifiedName.equals(attr.getNodeName())) {
233                 return attr.getScriptableObject();
234             }
235         }
236         return null;
237     }
238 
239     private boolean isHtmlElementInHtmlDocument() {
240         final DomNode domNode = getDomNodeOrNull();
241         return domNode instanceof HtmlElement && !domNode.getPage().hasCaseSensitiveTagNames();
242     }
243 
244     private boolean isPrototypeProperty(final String name) {
245         final Scriptable prototype = getPrototype();
246         return prototype != null && ScriptableObject.hasProperty(prototype, name);
247     }
248 
249     /**
250      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
251      *
252      * Gets the specified attribute without handling the synthetic class attribute.
253      *
254      * @param name the attribute name
255      * @return the attribute node, or {@code null} if not found
256      * @see #getNamedItem(String)
257      */
258     public HtmlUnitScriptable getNamedItemWithoutSytheticClassAttr(final String name) {
259         if (attributes_ != null) {
260             final DomNode attr = (DomNode) attributes_.getNamedItem(name);
261             if (attr != null) {
262                 return attr.getScriptableObject();
263             }
264         }
265 
266         return null;
267     }
268 
269     /**
270      * Returns the attribute node with the specified name.
271      *
272      * @param name the attribute name
273      * @return the attribute node, or {@code null} if not defined
274      */
275     @JsxFunction
276     public HtmlUnitScriptable getNamedItem(final String name) {
277         return getNamedItemWithoutSytheticClassAttr(name);
278     }
279 
280     /**
281      * Returns the attribute node with the given namespace URI and local name.
282      *
283      * @param namespaceURI the namespace URI of the node to retrieve
284      * @param localName the local name of the node to retrieve
285      * @return the attribute node, or {@code null} if not found
286      */
287     @JsxFunction
288     public Node getNamedItemNS(final String namespaceURI, final String localName) {
289         if (attributes_ != null) {
290             final DomNode attr = (DomNode) attributes_.getNamedItemNS(namespaceURI, localName);
291             if (attr != null) {
292                 return attr.getScriptableObject();
293             }
294         }
295 
296         return null;
297     }
298 
299     /**
300      * Sets the specified attribute node.
301      *
302      * @param node the attribute node to set
303      */
304     @JsxFunction
305     public void setNamedItem(final Node node) {
306         attributes_.setNamedItem(node.getDomNodeOrDie());
307     }
308 
309     /**
310      * Sets the specified attribute node using its namespace URI and local name.
311      *
312      * @param node the attribute node to set
313      */
314     @JsxFunction
315     public void setNamedItemNS(final Node node) {
316         attributes_.setNamedItemNS(node.getDomNodeOrDie());
317     }
318 
319     /**
320      * Removes the attribute with the specified name.
321      *
322      * @param name the name of the attribute to remove
323      */
324     @JsxFunction
325     public void removeNamedItem(final String name) {
326         attributes_.removeNamedItem(name);
327     }
328 
329     /**
330      * Removes the attribute with the given namespace URI and local name.
331      *
332      * @param namespaceURI the namespace URI of the attribute to remove
333      * @param localName the local name of the attribute to remove
334      * @return the removed attribute node, or {@code null} if not found
335      */
336     @JsxFunction
337     public Attr removeNamedItemNS(final String namespaceURI, final String localName) {
338         return (Attr) attributes_.removeNamedItemNS(namespaceURI, localName);
339     }
340 
341     /**
342      * Returns the attribute node at the specified index.
343      *
344      * @param index the index
345      * @return the attribute node at the given index, or {@code null} if out of range
346      */
347     @JsxFunction
348     public HtmlUnitScriptable item(final int index) {
349         if (attributes_ == null) {
350             return null;
351         }
352         final DomNode attr = (DomNode) attributes_.item(index);
353         if (attr != null) {
354             return attr.getScriptableObject();
355         }
356         return null;
357     }
358 
359     /**
360      * Returns the number of attributes in this map.
361      *
362      * @return the number of attributes
363      */
364     @JsxGetter
365     public int getLength() {
366         return attributes_.getLength();
367     }
368 
369     /**
370      * {@inheritDoc}
371      */
372     @Override
373     public boolean has(final int index, final Scriptable start) {
374         // the prototype has no attributes
375         return index >= 0 && index < getIndexedPropertyCount();
376     }
377 
378     /**
379      * Returns an iterator over the values in this map.
380      *
381      * @return the iterator
382      */
383     @JsxSymbol
384     public Scriptable iterator() {
385         return JavaScriptEngine.newArrayIteratorTypeValues(getParentScope(), this);
386     }
387 }