script/dom/
elementinternals.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 std::cell::Cell;
6
7use dom_struct::dom_struct;
8use html5ever::local_name;
9use js::context::JSContext;
10
11use crate::dom::bindings::cell::DomRefCell;
12use crate::dom::bindings::codegen::Bindings::ElementInternalsBinding::{
13    ElementInternalsMethods, ValidityStateFlags,
14};
15use crate::dom::bindings::codegen::UnionTypes::FileOrUSVStringOrFormData;
16use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
19use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
20use crate::dom::bindings::str::{DOMString, USVString};
21use crate::dom::customstateset::CustomStateSet;
22use crate::dom::element::Element;
23use crate::dom::file::File;
24use crate::dom::html::htmlelement::HTMLElement;
25use crate::dom::html::htmlformelement::{FormDatum, FormDatumValue, HTMLFormElement};
26use crate::dom::node::{Node, NodeTraits};
27use crate::dom::nodelist::NodeList;
28use crate::dom::shadowroot::ShadowRoot;
29use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
30use crate::dom::validitystate::{ValidationFlags, ValidityState};
31use crate::script_runtime::CanGc;
32
33#[derive(Clone, JSTraceable, MallocSizeOf)]
34enum SubmissionValue {
35    File(DomRoot<File>),
36    FormData(Vec<FormDatum>),
37    USVString(USVString),
38    None,
39}
40
41impl From<Option<&FileOrUSVStringOrFormData>> for SubmissionValue {
42    fn from(value: Option<&FileOrUSVStringOrFormData>) -> Self {
43        match value {
44            None => SubmissionValue::None,
45            Some(FileOrUSVStringOrFormData::File(file)) => {
46                SubmissionValue::File(DomRoot::from_ref(file))
47            },
48            Some(FileOrUSVStringOrFormData::USVString(usv_string)) => {
49                SubmissionValue::USVString(usv_string.clone())
50            },
51            Some(FileOrUSVStringOrFormData::FormData(form_data)) => {
52                SubmissionValue::FormData(form_data.datums())
53            },
54        }
55    }
56}
57
58#[dom_struct]
59pub(crate) struct ElementInternals {
60    reflector_: Reflector,
61    /// If `attached` is false, we're using this to hold form-related state
62    /// on an element for which `attachInternals()` wasn't called yet; this is
63    /// necessary because it might have a form owner.
64    attached: Cell<bool>,
65    target_element: Dom<HTMLElement>,
66    validity_state: MutNullableDom<ValidityState>,
67    validation_message: DomRefCell<DOMString>,
68    custom_validity_error_message: DomRefCell<DOMString>,
69    validation_anchor: MutNullableDom<HTMLElement>,
70    submission_value: DomRefCell<SubmissionValue>,
71    state: DomRefCell<SubmissionValue>,
72    form_owner: MutNullableDom<HTMLFormElement>,
73    labels_node_list: MutNullableDom<NodeList>,
74
75    /// <https://html.spec.whatwg.org/multipage/#dom-elementinternals-states>
76    states: MutNullableDom<CustomStateSet>,
77}
78
79impl ElementInternals {
80    fn new_inherited(target_element: &HTMLElement) -> ElementInternals {
81        ElementInternals {
82            reflector_: Reflector::new(),
83            attached: Cell::new(false),
84            target_element: Dom::from_ref(target_element),
85            validity_state: Default::default(),
86            validation_message: DomRefCell::new(DOMString::new()),
87            custom_validity_error_message: DomRefCell::new(DOMString::new()),
88            validation_anchor: MutNullableDom::new(None),
89            submission_value: DomRefCell::new(SubmissionValue::None),
90            state: DomRefCell::new(SubmissionValue::None),
91            form_owner: MutNullableDom::new(None),
92            labels_node_list: MutNullableDom::new(None),
93            states: MutNullableDom::new(None),
94        }
95    }
96
97    pub(crate) fn new(element: &HTMLElement, can_gc: CanGc) -> DomRoot<ElementInternals> {
98        let global = element.owner_window();
99        reflect_dom_object(
100            Box::new(ElementInternals::new_inherited(element)),
101            &*global,
102            can_gc,
103        )
104    }
105
106    fn is_target_form_associated(&self) -> bool {
107        self.target_element.is_form_associated_custom_element()
108    }
109
110    fn set_validation_message(&self, message: DOMString) {
111        *self.validation_message.borrow_mut() = message;
112    }
113
114    fn set_custom_validity_error_message(&self, message: DOMString) {
115        *self.custom_validity_error_message.borrow_mut() = message;
116    }
117
118    fn set_submission_value(&self, value: SubmissionValue) {
119        *self.submission_value.borrow_mut() = value;
120    }
121
122    fn set_state(&self, value: SubmissionValue) {
123        *self.state.borrow_mut() = value;
124    }
125
126    pub(crate) fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
127        self.form_owner.set(form);
128    }
129
130    pub(crate) fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
131        self.form_owner.get()
132    }
133
134    pub(crate) fn set_attached(&self) {
135        self.attached.set(true);
136    }
137
138    pub(crate) fn attached(&self) -> bool {
139        self.attached.get()
140    }
141
142    pub(crate) fn perform_entry_construction(&self, entry_list: &mut Vec<FormDatum>) {
143        if self
144            .target_element
145            .upcast::<Element>()
146            .has_attribute(&local_name!("disabled"))
147        {
148            warn!("We are in perform_entry_construction on an element with disabled attribute!");
149        }
150        if self.target_element.upcast::<Element>().disabled_state() {
151            warn!("We are in perform_entry_construction on an element with disabled bit!");
152        }
153        if !self.target_element.upcast::<Element>().enabled_state() {
154            warn!("We are in perform_entry_construction on an element without enabled bit!");
155        }
156
157        if let SubmissionValue::FormData(datums) = &*self.submission_value.borrow() {
158            entry_list.extend(datums.iter().cloned());
159            return;
160        }
161        let name = self
162            .target_element
163            .upcast::<Element>()
164            .get_string_attribute(&local_name!("name"));
165        if name.is_empty() {
166            return;
167        }
168        match &*self.submission_value.borrow() {
169            SubmissionValue::FormData(_) => unreachable!(
170                "The FormData submission value has been handled before name empty checking"
171            ),
172            SubmissionValue::None => {},
173            SubmissionValue::USVString(string) => {
174                entry_list.push(FormDatum {
175                    ty: DOMString::from("string"),
176                    name,
177                    value: FormDatumValue::String(DOMString::from(string.to_string())),
178                });
179            },
180            SubmissionValue::File(file) => {
181                entry_list.push(FormDatum {
182                    ty: DOMString::from("file"),
183                    name,
184                    value: FormDatumValue::File(DomRoot::from_ref(file)),
185                });
186            },
187        }
188    }
189
190    pub(crate) fn is_invalid(&self, can_gc: CanGc) -> bool {
191        self.is_target_form_associated() &&
192            self.is_instance_validatable() &&
193            !self.satisfies_constraints(can_gc)
194    }
195
196    pub(crate) fn custom_states_for_layout<'a>(&'a self) -> Option<LayoutDom<'a, CustomStateSet>> {
197        #[expect(unsafe_code)]
198        unsafe {
199            self.states.get_inner_as_layout()
200        }
201    }
202}
203
204impl ElementInternalsMethods<crate::DomTypeHolder> for ElementInternals {
205    /// <https://html.spec.whatwg.org/multipage/#dom-elementinternals-shadowroot>
206    fn GetShadowRoot(&self) -> Option<DomRoot<ShadowRoot>> {
207        // Step 1. Let target be this's target element.
208        // Step 2. If target is not a shadow host, then return null.
209        // Step 3. Let shadow be target's shadow root.
210        let shadow = self.target_element.upcast::<Element>().shadow_root()?;
211
212        // Step 4. If shadow's available to element internals is false, then return null.
213        if !shadow.is_available_to_element_internals() {
214            return None;
215        }
216
217        // Step 5. Return shadow.
218        Some(shadow)
219    }
220
221    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-setformvalue>
222    fn SetFormValue(
223        &self,
224        value: Option<FileOrUSVStringOrFormData>,
225        maybe_state: Option<Option<FileOrUSVStringOrFormData>>,
226    ) -> ErrorResult {
227        // Steps 1-2: If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException
228        if !self.is_target_form_associated() {
229            return Err(Error::NotSupported(None));
230        }
231
232        // Step 3: Set target element's submission value
233        self.set_submission_value(value.as_ref().into());
234
235        match maybe_state {
236            // Step 4: If the state argument of the function is omitted, set element's state to its submission value
237            None => self.set_state(value.as_ref().into()),
238            // Steps 5-6: Otherwise, set element's state to state
239            Some(state) => self.set_state(state.as_ref().into()),
240        }
241        Ok(())
242    }
243
244    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-setvalidity>
245    fn SetValidity(
246        &self,
247        flags: &ValidityStateFlags,
248        message: Option<DOMString>,
249        anchor: Option<&HTMLElement>,
250        can_gc: CanGc,
251    ) -> ErrorResult {
252        // Step 1. Let element be this's target element.
253        // Step 2: If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException.
254        if !self.is_target_form_associated() {
255            return Err(Error::NotSupported(None));
256        }
257
258        // Step 3: If flags contains one or more true values and message is not given or is the empty
259        // string, then throw a TypeError.
260        let bits: ValidationFlags = flags.into();
261        if !bits.is_empty() && !message.as_ref().map_or_else(|| false, |m| !m.is_empty()) {
262            return Err(Error::Type(
263                c"Setting an element to invalid requires a message string as the second argument."
264                    .to_owned(),
265            ));
266        }
267
268        // Step 4: For each entry `flag` → `value` of `flags`, set element's validity flag with the name
269        // `flag` to `value`.
270        self.validity_state(can_gc).update_invalid_flags(bits);
271        self.validity_state(can_gc).update_pseudo_classes(can_gc);
272
273        // Step 5: Set element's validation message to the empty string if message is not given
274        // or all of element's validity flags are false, or to message otherwise.
275        if bits.is_empty() {
276            self.set_validation_message(DOMString::new());
277        } else {
278            self.set_validation_message(message.unwrap_or_default());
279        }
280
281        // Step 6: If element's customError validity flag is true, then set element's custom validity error
282        // message to element's validation message. Otherwise, set element's custom validity error
283        // message to the empty string.
284        if bits.contains(ValidationFlags::CUSTOM_ERROR) {
285            self.set_custom_validity_error_message(self.validation_message.borrow().clone());
286        } else {
287            self.set_custom_validity_error_message(DOMString::new());
288        }
289
290        let anchor = match anchor {
291            // Step 7: If anchor is not given, then set it to element.
292            None => &self.target_element,
293            // Step 8. Otherwise, if anchor is not a shadow-including inclusive descendant of element,
294            // then throw a "NotFoundError" DOMException.
295            Some(anchor) => {
296                if !self
297                    .target_element
298                    .upcast::<Node>()
299                    .is_shadow_including_inclusive_ancestor_of(anchor.upcast::<Node>())
300                {
301                    return Err(Error::NotFound(None));
302                }
303                anchor
304            },
305        };
306
307        // Step 9. Set element's validation anchor to anchor.
308        self.validation_anchor.set(Some(anchor));
309
310        Ok(())
311    }
312
313    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-validationmessage>
314    fn GetValidationMessage(&self) -> Fallible<DOMString> {
315        // This check isn't in the spec but it's in WPT tests and it maintains
316        // consistency with other methods that do specify it
317        if !self.is_target_form_associated() {
318            return Err(Error::NotSupported(None));
319        }
320        Ok(self.validation_message.borrow().clone())
321    }
322
323    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-validity>
324    fn GetValidity(&self, can_gc: CanGc) -> Fallible<DomRoot<ValidityState>> {
325        if !self.is_target_form_associated() {
326            return Err(Error::NotSupported(None));
327        }
328        Ok(self.validity_state(can_gc))
329    }
330
331    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-labels>
332    fn GetLabels(&self, can_gc: CanGc) -> Fallible<DomRoot<NodeList>> {
333        if !self.is_target_form_associated() {
334            return Err(Error::NotSupported(None));
335        }
336        Ok(self.labels_node_list.or_init(|| {
337            NodeList::new_labels_list(
338                self.target_element.upcast::<Node>().owner_doc().window(),
339                &self.target_element,
340                can_gc,
341            )
342        }))
343    }
344
345    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-willvalidate>
346    fn GetWillValidate(&self) -> Fallible<bool> {
347        if !self.is_target_form_associated() {
348            return Err(Error::NotSupported(None));
349        }
350        Ok(self.is_instance_validatable())
351    }
352
353    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-form>
354    fn GetForm(&self) -> Fallible<Option<DomRoot<HTMLFormElement>>> {
355        if !self.is_target_form_associated() {
356            return Err(Error::NotSupported(None));
357        }
358        Ok(self.form_owner.get())
359    }
360
361    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-checkvalidity>
362    fn CheckValidity(&self, cx: &mut JSContext) -> Fallible<bool> {
363        if !self.is_target_form_associated() {
364            return Err(Error::NotSupported(None));
365        }
366        Ok(self.check_validity(cx))
367    }
368
369    /// <https://html.spec.whatwg.org/multipage#dom-elementinternals-reportvalidity>
370    fn ReportValidity(&self, cx: &mut JSContext) -> Fallible<bool> {
371        if !self.is_target_form_associated() {
372            return Err(Error::NotSupported(None));
373        }
374        Ok(self.report_validity(cx))
375    }
376
377    /// <https://html.spec.whatwg.org/multipage/#dom-elementinternals-states>
378    fn States(&self, can_gc: CanGc) -> DomRoot<CustomStateSet> {
379        self.states.or_init(|| {
380            CustomStateSet::new(
381                &self.target_element.owner_window(),
382                &self.target_element,
383                can_gc,
384            )
385        })
386    }
387}
388
389// Form-associated custom elements also need the Validatable trait.
390impl Validatable for ElementInternals {
391    fn as_element(&self) -> &Element {
392        debug_assert!(self.is_target_form_associated());
393        self.target_element.upcast::<Element>()
394    }
395
396    fn validity_state(&self, can_gc: CanGc) -> DomRoot<ValidityState> {
397        debug_assert!(self.is_target_form_associated());
398        self.validity_state.or_init(|| {
399            ValidityState::new(
400                &self.target_element.owner_window(),
401                self.target_element.upcast(),
402                can_gc,
403            )
404        })
405    }
406
407    /// <https://html.spec.whatwg.org/multipage#candidate-for-constraint-validation>
408    fn is_instance_validatable(&self) -> bool {
409        debug_assert!(self.is_target_form_associated());
410        if !self.target_element.is_submittable_element() {
411            return false;
412        }
413
414        // The form-associated custom element is barred from constraint validation,
415        // if the readonly attribute is specified, the element is disabled,
416        // or the element has a datalist element ancestor.
417        !self.as_element().read_write_state() &&
418            !self.as_element().disabled_state() &&
419            !is_barred_by_datalist_ancestor(self.target_element.upcast::<Node>())
420    }
421}