Skip to main content

script/dom/attributes/
domstringmap.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use html5ever::{LocalName, ns};
7use js::context::{JSContext, NoGC};
8use script_bindings::reflector::{Reflector, reflect_dom_object};
9
10use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods;
11use crate::dom::bindings::error::{Error, ErrorResult};
12use crate::dom::bindings::root::{Dom, DomRoot};
13use crate::dom::bindings::str::DOMString;
14use crate::dom::bindings::xmlname::matches_name_production;
15use crate::dom::element::Element;
16use crate::dom::node::NodeTraits;
17
18#[dom_struct]
19pub(crate) struct DOMStringMap {
20    reflector_: Reflector,
21    element: Dom<Element>,
22}
23
24static DATA_PREFIX: &str = "data-";
25static DATA_HYPHEN_SEPARATOR: char = '\x2d';
26
27/// <https://html.spec.whatwg.org/multipage/#concept-domstringmap-pairs>
28fn to_camel_case(name: &str) -> Option<DOMString> {
29    // Step 2. For each content attribute on the DOMStringMap's associated element whose
30    // first five characters are the string "data-" and whose remaining characters (if any)
31    // do not include any ASCII upper alphas, in the order that those attributes
32    // are listed in the element's attribute list,
33    // add a name-value pair to list whose name is the attribute's name with the first
34    // five characters removed and whose value is the attribute's value.
35    let name = name.strip_prefix(DATA_PREFIX)?;
36    let has_uppercase = name.chars().any(|curr_char| curr_char.is_ascii_uppercase());
37    if has_uppercase {
38        return None;
39    }
40    // Step 3. For each name in list, for each U+002D HYPHEN-MINUS character (-)
41    // in the name that is followed by an ASCII lower alpha, remove the
42    // U+002D HYPHEN-MINUS character (-) and replace the character that followed
43    // it by the same character converted to ASCII uppercase.
44    let mut result = String::with_capacity(name.len().saturating_sub(DATA_PREFIX.len()));
45    let mut name_chars = name.chars().peekable();
46    while let Some(curr_char) = name_chars.next() {
47        // Note that we first need to peek, since we shouldn't advance the iterator twice
48        // in case there are two consecutive dashes and then followed by a ASCII lower alpha
49        if curr_char == DATA_HYPHEN_SEPARATOR &&
50            name_chars
51                .peek()
52                .is_some_and(|next_char| next_char.is_ascii_lowercase())
53        {
54            result.push(
55                name_chars
56                    .next()
57                    .expect("Already called peek")
58                    .to_ascii_uppercase(),
59            );
60            continue;
61        }
62        result.push(curr_char);
63    }
64    // Step 1. Let list be an empty list of name-value pairs.
65    // Step 4. Return list.
66    //
67    // We do the iteration in the calling function, to avoid needlessly computing attribute
68    // values when we only need the names. Therefore, we only return the name.
69    Some(DOMString::from(result))
70}
71
72/// <https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem>
73/// and <https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem>
74fn to_snake_case(name: &DOMString, should_throw: bool) -> Option<String> {
75    let name = name.str();
76    let mut result = String::with_capacity(DATA_PREFIX.len() + name.len());
77    // > Insert the string data- at the front of name.
78    result.push_str(DATA_PREFIX);
79    let mut name_chars = name.chars();
80    while let Some(curr_char) = name_chars.next() {
81        if curr_char == DATA_HYPHEN_SEPARATOR {
82            result.push(curr_char);
83
84            if let Some(next_char) = name_chars.next() {
85                // Only relevant for https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem
86                //
87                // > If name contains a U+002D HYPHEN-MINUS character (-) followed by an ASCII lower alpha,
88                // > then throw a "SyntaxError" DOMException.
89                if next_char.is_ascii_lowercase() {
90                    if should_throw {
91                        return None;
92                    }
93                    result.push(next_char);
94                } else {
95                    // > For each ASCII upper alpha in name, insert a U+002D HYPHEN-MINUS character (-) before the character
96                    // > and replace the character with the same character converted to ASCII lowercase.
97                    result.push(DATA_HYPHEN_SEPARATOR);
98                    result.push(next_char.to_ascii_lowercase());
99                }
100            }
101        } else {
102            // > For each ASCII upper alpha in name, insert a U+002D HYPHEN-MINUS character (-) before the character
103            // > and replace the character with the same character converted to ASCII lowercase.
104            if curr_char.is_ascii_uppercase() {
105                result.push(DATA_HYPHEN_SEPARATOR);
106                result.push(curr_char.to_ascii_lowercase());
107            } else {
108                result.push(curr_char);
109            }
110        }
111    }
112    Some(result)
113}
114
115impl DOMStringMap {
116    fn new_inherited(element: &Element) -> DOMStringMap {
117        DOMStringMap {
118            reflector_: Reflector::new(),
119            element: Dom::from_ref(element),
120        }
121    }
122
123    pub(crate) fn new(cx: &mut JSContext, element: &Element) -> DomRoot<DOMStringMap> {
124        reflect_dom_object(
125            cx,
126            Box::new(DOMStringMap::new_inherited(element)),
127            &*element.owner_window(),
128        )
129    }
130
131    fn as_element(&self) -> &Element {
132        &self.element
133    }
134}
135
136// https://html.spec.whatwg.org/multipage/#domstringmap
137impl DOMStringMapMethods<crate::DomTypeHolder> for DOMStringMap {
138    /// <https://html.spec.whatwg.org/multipage/#dom-domstringmap-removeitem>
139    fn NamedDeleter(&self, cx: &mut JSContext, name: DOMString) {
140        // Step 1. For each ASCII upper alpha in name, insert a U+002D HYPHEN-MINUS character (-) before the character
141        // and replace the character with the same character converted to ASCII lowercase.
142        // Step 2. Insert the string data- at the front of name.
143        let name = to_snake_case(&name, false).expect("Must always succeed");
144        // Step 3. Remove an attribute by name given name and the DOMStringMap's associated element.
145        self.as_element()
146            .remove_attribute(cx, &ns!(), &LocalName::from(name));
147    }
148
149    /// <https://html.spec.whatwg.org/multipage/#dom-domstringmap-setitem>
150    fn NamedSetter(&self, cx: &mut JSContext, name: DOMString, value: DOMString) -> ErrorResult {
151        // Step 2. For each ASCII upper alpha in name, insert a U+002D HYPHEN-MINUS character (-)
152        // before the character and replace the character with the same character converted to ASCII lowercase.
153        // Step 3. Insert the string data- at the front of name.
154        let Some(name) = to_snake_case(&name, true) else {
155            // Step 1. If name contains a U+002D HYPHEN-MINUS character (-) followed by an ASCII lower alpha,
156            // then throw a "SyntaxError" DOMException.
157            return Err(Error::Syntax(Some(
158                "Name contains a hyphen followed by a lowercase ASCII letter".into(),
159            )));
160        };
161        // Step 4. If name is not a valid attribute local name, then throw an "InvalidCharacterError" DOMException.
162        if !matches_name_production(&name) {
163            return Err(Error::InvalidCharacter(Some(
164                "Invalid attribute name".into(),
165            )));
166        }
167        // Step 5. Set an attribute value for the DOMStringMap's associated element using name and value.
168        let name = LocalName::from(name);
169        let element = self.as_element();
170        let value = element.parse_attribute(&ns!(), &name, value);
171        element.set_attribute_with_namespace(cx, name.clone(), value, name, ns!(), None);
172        Ok(())
173    }
174
175    /// <https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem>
176    fn NamedGetter(&self, name: DOMString) -> Option<DOMString> {
177        // > To determine the value of a named property name for a DOMStringMap,
178        // > return the value component of the name-value pair whose name component is
179        // > name in the list returned from getting the DOMStringMap's name-value pairs.
180        self.as_element()
181            .attrs()
182            .borrow()
183            .iter()
184            .find(|attr| to_camel_case(attr.local_name()).as_ref() == Some(&name))
185            .map(|attr| DOMString::from(&**attr.value()))
186    }
187
188    /// <https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names>
189    fn SupportedPropertyNames(&self, _: &NoGC) -> Vec<DOMString> {
190        // > The supported property names on a DOMStringMap object at any instant are
191        // > the names of each pair returned from getting the DOMStringMap's name-value
192        // > pairs at that instant, in the order returned.
193        self.as_element()
194            .attrs()
195            .borrow()
196            .iter()
197            .filter_map(|attr| to_camel_case(attr.local_name()))
198            .collect()
199    }
200}