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.dom;
16  
17  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
18  
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.htmlunit.corejs.javascript.CompoundOperationMap;
23  import org.htmlunit.corejs.javascript.Context;
24  import org.htmlunit.corejs.javascript.Scriptable;
25  import org.htmlunit.corejs.javascript.ScriptableObject;
26  import org.htmlunit.html.DomAttr;
27  import org.htmlunit.html.HtmlElement;
28  import org.htmlunit.javascript.HtmlUnitScriptable;
29  import org.htmlunit.javascript.JavaScriptEngine;
30  import org.htmlunit.javascript.configuration.JsxClass;
31  import org.htmlunit.javascript.configuration.JsxConstructor;
32  
33  /**
34   * A JavaScript object for {@code DOMStringMap}.
35   *
36   * @author Ahmed Ashour
37   * @author Ronald Brill
38   *
39   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap">MDN Documentation</a>
40   */
41  @JsxClass
42  public final class DOMStringMap extends HtmlUnitScriptable {
43  
44      private static final String DATA_PREFIX = "data-";
45  
46      /**
47       * Creates an instance.
48       */
49      public DOMStringMap() {
50          super();
51      }
52  
53      /**
54       * JavaScript constructor.
55       */
56      @JsxConstructor
57      public void jsConstructor() {
58          // nothing to do
59      }
60  
61      /**
62       * Creates an instance.
63       * @param node the node which contains the underlying string
64       */
65      public DOMStringMap(final Node node) {
66          super();
67          setDomNode(node.getDomNodeOrDie(), false);
68          setParentScope(node.getParentScope());
69          setPrototype(getPrototype(getClass()));
70      }
71  
72      /**
73       * {@inheritDoc}
74       */
75      @Override
76      public Object get(final String name, final Scriptable start) {
77          final HtmlElement e = (HtmlElement) getDomNodeOrNull();
78          if (e != null) {
79              final String value = e.getAttribute(DATA_PREFIX + deCamelize(name));
80              if (ATTRIBUTE_NOT_DEFINED != value) {
81                  return value;
82              }
83          }
84          return super.get(name, start);
85      }
86  
87      /**
88       * Overridden to make the data attributes visible as own properties ('in' operator).
89       * {@inheritDoc}
90       */
91      @Override
92      public boolean has(final String name, final Scriptable start) {
93          final HtmlElement e = (HtmlElement) getDomNodeOrNull();
94          if (e != null && e.hasAttribute(DATA_PREFIX + deCamelize(name))) {
95              return true;
96          }
97          return super.has(name, start);
98      }
99  
100     /**
101      * Overridden to enumerate the data attributes as own properties
102      * (Object.keys(), Object.getOwnPropertyNames(), for...in, ...).
103      * {@inheritDoc}
104      */
105     @Override
106     protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
107             final boolean getNonEnumerable, final boolean getSymbols) {
108         final Object[] ids = super.getIds(map, getNonEnumerable, getSymbols);
109 
110         final HtmlElement e = (HtmlElement) getDomNodeOrNull();
111         if (e == null) {
112             return ids;
113         }
114 
115         final List<Object> result = new ArrayList<>();
116         for (final DomAttr attr : e.getAttributesMap().values()) {
117             final String name = camelize(attr.getName());
118             if (name != null && !result.contains(name)) {
119                 result.add(name);
120             }
121         }
122         for (final Object id : ids) {
123             if (!result.contains(id)) {
124                 result.add(id);
125             }
126         }
127         return result.toArray();
128     }
129 
130     /**
131      * Overridden to provide property descriptors for the data attributes.
132      * {@inheritDoc}
133      */
134     @Override
135     protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
136         final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
137         if (descInfo != null) {
138             return descInfo;
139         }
140 
141         final HtmlElement e = (HtmlElement) getDomNodeOrNull();
142         if (e != null && id instanceof CharSequence) {
143             final String value = e.getAttribute(DATA_PREFIX + deCamelize(id.toString()));
144             if (ATTRIBUTE_NOT_DEFINED != value) {
145                 return ScriptableObject.buildDataDescriptor(value, ScriptableObject.EMPTY);
146             }
147         }
148         return null;
149     }
150 
151     /**
152      * {@inheritDoc}
153      */
154     @Override
155     public void put(final String name, final Scriptable start, final Object value) {
156         final HtmlElement e = (HtmlElement) getDomNodeOrNull();
157         if (e == null) {
158             super.put(name, start, value);
159         }
160         else {
161             e.setAttribute("data-" + deCamelize(name), JavaScriptEngine.toString(value));
162         }
163     }
164 
165     /**
166      * {@inheritDoc}
167      */
168     @Override
169     public void delete(final String name) {
170         final HtmlElement e = (HtmlElement) getDomNodeOrNull();
171         if (e == null) {
172             super.delete(name);
173         }
174         else {
175             e.removeAttribute("data-" + deCamelize(name));
176         }
177     }
178 
179     /**
180      * Transforms the specified attribute name into the name of the dataset property.
181      *
182      * @param attributeName the attribute name
183      * @return the property name or {@code null} if the attribute is not a data attribute
184      * @see <a href="https://html.spec.whatwg.org/multipage/dom.html#dom-domstringmap-interface">
185      *      HTML Living Standard - The DOMStringMap interface</a>
186      */
187     private static String camelize(final String attributeName) {
188         if (!attributeName.startsWith(DATA_PREFIX)) {
189             return null;
190         }
191         final String name = attributeName.substring(DATA_PREFIX.length());
192         final StringBuilder builder = new StringBuilder();
193         boolean dash = false;
194         for (int i = 0; i < name.length(); i++) {
195             final char ch = name.charAt(i);
196             if (ch >= 'A' && ch <= 'Z') {
197                 return null;
198             }
199             if (dash && ch >= 'a' && ch <= 'z') {
200                 // a dash followed by a lower case letter is replaced by the upper case letter
201                 builder.setLength(builder.length() - 1);
202                 builder.append(Character.toUpperCase(ch));
203                 dash = false;
204             }
205             else {
206                 builder.append(ch);
207                 dash = ch == '-';
208             }
209         }
210         return builder.toString();
211     }
212 
213     /**
214      * Transforms the specified string from camel-cased to dash separated.
215      *
216      * @param string the string to decamelize
217      * @return the transformed string
218      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#name_conversion">
219      *      MDN - HTMLElement.dataset - Name conversion</a>
220      */
221     private static String deCamelize(final String string) {
222         if (string == null || string.isEmpty()) {
223             return string;
224         }
225 
226         final StringBuilder builder = new StringBuilder();
227         for (int i = 0; i < string.length(); i++) {
228             final char ch = string.charAt(i);
229             if (Character.isUpperCase(ch)) {
230                 builder.append('-').append(Character.toLowerCase(ch));
231             }
232             else {
233                 builder.append(ch);
234             }
235         }
236         return builder.toString();
237     }
238 
239 }