script/dom/
domtokenlist.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 style::str::HTML_SPACE_CHARACTERS;
8use stylo_atoms::Atom;
9
10use crate::dom::attr::Attr;
11use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
12use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
13use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
14use crate::dom::bindings::root::{Dom, DomRoot};
15use crate::dom::bindings::str::DOMString;
16use crate::dom::element::Element;
17use crate::dom::node::NodeTraits;
18use crate::script_runtime::CanGc;
19
20#[dom_struct]
21pub(crate) struct DOMTokenList {
22    reflector_: Reflector,
23    element: Dom<Element>,
24    #[no_trace]
25    local_name: LocalName,
26    #[no_trace]
27    supported_tokens: Option<Vec<Atom>>,
28}
29
30impl DOMTokenList {
31    pub(crate) fn new_inherited(
32        element: &Element,
33        local_name: LocalName,
34        supported_tokens: Option<Vec<Atom>>,
35    ) -> DOMTokenList {
36        DOMTokenList {
37            reflector_: Reflector::new(),
38            element: Dom::from_ref(element),
39            local_name,
40            supported_tokens,
41        }
42    }
43
44    pub(crate) fn new(
45        element: &Element,
46        local_name: &LocalName,
47        supported_tokens: Option<Vec<Atom>>,
48        can_gc: CanGc,
49    ) -> DomRoot<DOMTokenList> {
50        reflect_dom_object(
51            Box::new(DOMTokenList::new_inherited(
52                element,
53                local_name.clone(),
54                supported_tokens,
55            )),
56            &*element.owner_window(),
57            can_gc,
58        )
59    }
60
61    fn attribute(&self) -> Option<DomRoot<Attr>> {
62        self.element.get_attribute(&ns!(), &self.local_name)
63    }
64
65    fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
66        match token {
67            "" => Err(Error::Syntax(None)),
68            slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
69            slice => Ok(Atom::from(slice)),
70        }
71    }
72
73    /// <https://dom.spec.whatwg.org/#concept-dtl-update>
74    fn perform_update_steps(&self, atoms: Vec<Atom>, can_gc: CanGc) {
75        // Step 1
76        if !self.element.has_attribute(&self.local_name) && atoms.is_empty() {
77            return;
78        }
79        // step 2
80        self.element
81            .set_atomic_tokenlist_attribute(&self.local_name, atoms, can_gc)
82    }
83
84    /// <https://dom.spec.whatwg.org/#concept-domtokenlist-validation>
85    fn validation_steps(&self, token: &str) -> Fallible<bool> {
86        match &self.supported_tokens {
87            None => Err(Error::Type(
88                "This attribute has no supported tokens".to_owned(),
89            )),
90            Some(supported_tokens) => {
91                let token = Atom::from(token).to_ascii_lowercase();
92                if supported_tokens.contains(&token) {
93                    return Ok(true);
94                }
95                Ok(false)
96            },
97        }
98    }
99}
100
101/// <https://dom.spec.whatwg.org/#domtokenlist>
102impl DOMTokenListMethods<crate::DomTypeHolder> for DOMTokenList {
103    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-length>
104    fn Length(&self) -> u32 {
105        self.attribute()
106            .map_or(0, |attr| attr.value().as_tokens().len()) as u32
107    }
108
109    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-item>
110    fn Item(&self, index: u32) -> Option<DOMString> {
111        self.attribute().and_then(|attr| {
112            // FIXME(ajeffrey): Convert directly from Atom to DOMString
113            attr.value()
114                .as_tokens()
115                .get(index as usize)
116                .map(|token| DOMString::from(&**token))
117        })
118    }
119
120    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-contains>
121    fn Contains(&self, token: DOMString) -> bool {
122        let token = Atom::from(token);
123        self.attribute()
124            .is_some_and(|attr| attr.value().as_tokens().contains(&token))
125    }
126
127    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-add>
128    fn Add(&self, tokens: Vec<DOMString>, can_gc: CanGc) -> ErrorResult {
129        let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
130        for token in &tokens {
131            let token = self.check_token_exceptions(token)?;
132            if !atoms.contains(&token) {
133                atoms.push(token);
134            }
135        }
136        self.perform_update_steps(atoms, can_gc);
137        Ok(())
138    }
139
140    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-remove>
141    fn Remove(&self, tokens: Vec<DOMString>, can_gc: CanGc) -> ErrorResult {
142        let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
143        for token in &tokens {
144            let token = self.check_token_exceptions(token)?;
145            atoms
146                .iter()
147                .position(|atom| *atom == token)
148                .map(|index| atoms.remove(index));
149        }
150        self.perform_update_steps(atoms, can_gc);
151        Ok(())
152    }
153
154    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-toggle>
155    fn Toggle(&self, token: DOMString, force: Option<bool>, can_gc: CanGc) -> Fallible<bool> {
156        let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
157        let token = self.check_token_exceptions(&token)?;
158        match atoms.iter().position(|atom| *atom == token) {
159            Some(index) => match force {
160                Some(true) => Ok(true),
161                _ => {
162                    atoms.remove(index);
163                    self.perform_update_steps(atoms, can_gc);
164                    Ok(false)
165                },
166            },
167            None => match force {
168                Some(false) => Ok(false),
169                _ => {
170                    atoms.push(token);
171                    self.perform_update_steps(atoms, can_gc);
172                    Ok(true)
173                },
174            },
175        }
176    }
177
178    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-value>
179    fn Value(&self) -> DOMString {
180        self.element.get_string_attribute(&self.local_name)
181    }
182
183    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-value>
184    fn SetValue(&self, value: DOMString, can_gc: CanGc) {
185        self.element
186            .set_tokenlist_attribute(&self.local_name, value, can_gc);
187    }
188
189    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-replace>
190    fn Replace(&self, token: DOMString, new_token: DOMString, can_gc: CanGc) -> Fallible<bool> {
191        if token.is_empty() || new_token.is_empty() {
192            // Step 1.
193            return Err(Error::Syntax(None));
194        }
195        if token.contains(HTML_SPACE_CHARACTERS) || new_token.contains(HTML_SPACE_CHARACTERS) {
196            // Step 2.
197            return Err(Error::InvalidCharacter);
198        }
199        // Steps 3-4.
200        let token = Atom::from(token);
201        let new_token = Atom::from(new_token);
202        let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
203        let mut result = false;
204        if let Some(pos) = atoms.iter().position(|atom| *atom == token) {
205            match atoms.iter().position(|atom| *atom == new_token) {
206                Some(redundant_pos) if redundant_pos > pos => {
207                    // The replacement is already in the list, later,
208                    // so we perform the replacement and remove the
209                    // later copy.
210                    atoms[pos] = new_token;
211                    atoms.remove(redundant_pos);
212                },
213                Some(redundant_pos) if redundant_pos < pos => {
214                    // The replacement is already in the list, earlier,
215                    // so we remove the index where we'd be putting the
216                    // later copy.
217                    atoms.remove(pos);
218                },
219                Some(_) => {
220                    // Else we are replacing the token with itself, nothing to change
221                },
222                None => {
223                    // The replacement is not in the list already
224                    atoms[pos] = new_token;
225                },
226            }
227
228            // Step 5.
229            self.perform_update_steps(atoms, can_gc);
230            result = true;
231        }
232        Ok(result)
233    }
234
235    /// <https://dom.spec.whatwg.org/#dom-domtokenlist-supports>
236    fn Supports(&self, token: DOMString) -> Fallible<bool> {
237        self.validation_steps(&token)
238    }
239
240    // check-tidy: no specs after this line
241    fn IndexedGetter(&self, index: u32) -> Option<DOMString> {
242        self.Item(index)
243    }
244}