1use std::cell::Cell;
6
7use dom_struct::dom_struct;
8use html5ever::local_name;
9
10use crate::dom::bindings::cell::DomRefCell;
11use crate::dom::bindings::codegen::Bindings::ElementInternalsBinding::{
12 ElementInternalsMethods, ValidityStateFlags,
13};
14use crate::dom::bindings::codegen::UnionTypes::FileOrUSVStringOrFormData;
15use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
16use crate::dom::bindings::inheritance::Castable;
17use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
18use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
19use crate::dom::bindings::str::{DOMString, USVString};
20use crate::dom::customstateset::CustomStateSet;
21use crate::dom::element::Element;
22use crate::dom::file::File;
23use crate::dom::html::htmlelement::HTMLElement;
24use crate::dom::html::htmlformelement::{FormDatum, FormDatumValue, HTMLFormElement};
25use crate::dom::node::{Node, NodeTraits};
26use crate::dom::nodelist::NodeList;
27use crate::dom::shadowroot::ShadowRoot;
28use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
29use crate::dom::validitystate::{ValidationFlags, ValidityState};
30use crate::script_runtime::CanGc;
31
32#[derive(Clone, JSTraceable, MallocSizeOf)]
33enum SubmissionValue {
34 File(DomRoot<File>),
35 FormData(Vec<FormDatum>),
36 USVString(USVString),
37 None,
38}
39
40impl From<Option<&FileOrUSVStringOrFormData>> for SubmissionValue {
41 fn from(value: Option<&FileOrUSVStringOrFormData>) -> Self {
42 match value {
43 None => SubmissionValue::None,
44 Some(FileOrUSVStringOrFormData::File(file)) => {
45 SubmissionValue::File(DomRoot::from_ref(file))
46 },
47 Some(FileOrUSVStringOrFormData::USVString(usv_string)) => {
48 SubmissionValue::USVString(usv_string.clone())
49 },
50 Some(FileOrUSVStringOrFormData::FormData(form_data)) => {
51 SubmissionValue::FormData(form_data.datums())
52 },
53 }
54 }
55}
56
57#[dom_struct]
58pub(crate) struct ElementInternals {
59 reflector_: Reflector,
60 attached: Cell<bool>,
64 target_element: Dom<HTMLElement>,
65 validity_state: MutNullableDom<ValidityState>,
66 validation_message: DomRefCell<DOMString>,
67 custom_validity_error_message: DomRefCell<DOMString>,
68 validation_anchor: MutNullableDom<HTMLElement>,
69 submission_value: DomRefCell<SubmissionValue>,
70 state: DomRefCell<SubmissionValue>,
71 form_owner: MutNullableDom<HTMLFormElement>,
72 labels_node_list: MutNullableDom<NodeList>,
73
74 states: MutNullableDom<CustomStateSet>,
76}
77
78impl ElementInternals {
79 fn new_inherited(target_element: &HTMLElement) -> ElementInternals {
80 ElementInternals {
81 reflector_: Reflector::new(),
82 attached: Cell::new(false),
83 target_element: Dom::from_ref(target_element),
84 validity_state: Default::default(),
85 validation_message: DomRefCell::new(DOMString::new()),
86 custom_validity_error_message: DomRefCell::new(DOMString::new()),
87 validation_anchor: MutNullableDom::new(None),
88 submission_value: DomRefCell::new(SubmissionValue::None),
89 state: DomRefCell::new(SubmissionValue::None),
90 form_owner: MutNullableDom::new(None),
91 labels_node_list: MutNullableDom::new(None),
92 states: MutNullableDom::new(None),
93 }
94 }
95
96 pub(crate) fn new(element: &HTMLElement, can_gc: CanGc) -> DomRoot<ElementInternals> {
97 let global = element.owner_window();
98 reflect_dom_object(
99 Box::new(ElementInternals::new_inherited(element)),
100 &*global,
101 can_gc,
102 )
103 }
104
105 fn is_target_form_associated(&self) -> bool {
106 self.target_element.is_form_associated_custom_element()
107 }
108
109 fn set_validation_message(&self, message: DOMString) {
110 *self.validation_message.borrow_mut() = message;
111 }
112
113 fn set_custom_validity_error_message(&self, message: DOMString) {
114 *self.custom_validity_error_message.borrow_mut() = message;
115 }
116
117 fn set_submission_value(&self, value: SubmissionValue) {
118 *self.submission_value.borrow_mut() = value;
119 }
120
121 fn set_state(&self, value: SubmissionValue) {
122 *self.state.borrow_mut() = value;
123 }
124
125 pub(crate) fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
126 self.form_owner.set(form);
127 }
128
129 pub(crate) fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
130 self.form_owner.get()
131 }
132
133 pub(crate) fn set_attached(&self) {
134 self.attached.set(true);
135 }
136
137 pub(crate) fn attached(&self) -> bool {
138 self.attached.get()
139 }
140
141 pub(crate) fn perform_entry_construction(&self, entry_list: &mut Vec<FormDatum>) {
142 if self
143 .target_element
144 .upcast::<Element>()
145 .has_attribute(&local_name!("disabled"))
146 {
147 warn!("We are in perform_entry_construction on an element with disabled attribute!");
148 }
149 if self.target_element.upcast::<Element>().disabled_state() {
150 warn!("We are in perform_entry_construction on an element with disabled bit!");
151 }
152 if !self.target_element.upcast::<Element>().enabled_state() {
153 warn!("We are in perform_entry_construction on an element without enabled bit!");
154 }
155
156 if let SubmissionValue::FormData(datums) = &*self.submission_value.borrow() {
157 entry_list.extend(datums.iter().cloned());
158 return;
159 }
160 let name = self
161 .target_element
162 .upcast::<Element>()
163 .get_string_attribute(&local_name!("name"));
164 if name.is_empty() {
165 return;
166 }
167 match &*self.submission_value.borrow() {
168 SubmissionValue::FormData(_) => unreachable!(
169 "The FormData submission value has been handled before name empty checking"
170 ),
171 SubmissionValue::None => {},
172 SubmissionValue::USVString(string) => {
173 entry_list.push(FormDatum {
174 ty: DOMString::from("string"),
175 name,
176 value: FormDatumValue::String(DOMString::from(string.to_string())),
177 });
178 },
179 SubmissionValue::File(file) => {
180 entry_list.push(FormDatum {
181 ty: DOMString::from("file"),
182 name,
183 value: FormDatumValue::File(DomRoot::from_ref(file)),
184 });
185 },
186 }
187 }
188
189 pub(crate) fn is_invalid(&self) -> bool {
190 self.is_target_form_associated() &&
191 self.is_instance_validatable() &&
192 !self.satisfies_constraints()
193 }
194
195 pub(crate) fn custom_states(&self) -> Option<DomRoot<CustomStateSet>> {
196 self.states.get()
197 }
198}
199
200impl ElementInternalsMethods<crate::DomTypeHolder> for ElementInternals {
201 fn GetShadowRoot(&self) -> Option<DomRoot<ShadowRoot>> {
203 let shadow = self.target_element.upcast::<Element>().shadow_root()?;
207
208 if !shadow.is_available_to_element_internals() {
210 return None;
211 }
212
213 Some(shadow)
215 }
216
217 fn SetFormValue(
219 &self,
220 value: Option<FileOrUSVStringOrFormData>,
221 maybe_state: Option<Option<FileOrUSVStringOrFormData>>,
222 ) -> ErrorResult {
223 if !self.is_target_form_associated() {
225 return Err(Error::NotSupported);
226 }
227
228 self.set_submission_value(value.as_ref().into());
230
231 match maybe_state {
232 None => self.set_state(value.as_ref().into()),
234 Some(state) => self.set_state(state.as_ref().into()),
236 }
237 Ok(())
238 }
239
240 fn SetValidity(
242 &self,
243 flags: &ValidityStateFlags,
244 message: Option<DOMString>,
245 anchor: Option<&HTMLElement>,
246 can_gc: CanGc,
247 ) -> ErrorResult {
248 if !self.is_target_form_associated() {
250 return Err(Error::NotSupported);
251 }
252
253 let bits: ValidationFlags = flags.into();
256 if !bits.is_empty() && !message.as_ref().map_or_else(|| false, |m| !m.is_empty()) {
257 return Err(Error::Type(
258 "Setting an element to invalid requires a message string as the second argument."
259 .to_string(),
260 ));
261 }
262
263 self.validity_state().update_invalid_flags(bits);
266 self.validity_state().update_pseudo_classes(can_gc);
267
268 if bits.is_empty() {
271 self.set_validation_message(DOMString::new());
272 } else {
273 self.set_validation_message(message.unwrap_or_default());
274 }
275
276 if bits.contains(ValidationFlags::CUSTOM_ERROR) {
280 self.set_custom_validity_error_message(self.validation_message.borrow().clone());
281 } else {
282 self.set_custom_validity_error_message(DOMString::new());
283 }
284
285 match anchor {
287 None => self.validation_anchor.set(None),
288 Some(a) => {
289 if a == &*self.target_element ||
290 !self
291 .target_element
292 .upcast::<Node>()
293 .is_shadow_including_inclusive_ancestor_of(a.upcast::<Node>())
294 {
295 return Err(Error::NotFound);
296 }
297 self.validation_anchor.set(Some(a));
298 },
299 }
300 Ok(())
301 }
302
303 fn GetValidationMessage(&self) -> Fallible<DOMString> {
305 if !self.is_target_form_associated() {
308 return Err(Error::NotSupported);
309 }
310 Ok(self.validation_message.borrow().clone())
311 }
312
313 fn GetValidity(&self) -> Fallible<DomRoot<ValidityState>> {
315 if !self.is_target_form_associated() {
316 return Err(Error::NotSupported);
317 }
318 Ok(self.validity_state())
319 }
320
321 fn GetLabels(&self, can_gc: CanGc) -> Fallible<DomRoot<NodeList>> {
323 if !self.is_target_form_associated() {
324 return Err(Error::NotSupported);
325 }
326 Ok(self.labels_node_list.or_init(|| {
327 NodeList::new_labels_list(
328 self.target_element.upcast::<Node>().owner_doc().window(),
329 &self.target_element,
330 can_gc,
331 )
332 }))
333 }
334
335 fn GetWillValidate(&self) -> Fallible<bool> {
337 if !self.is_target_form_associated() {
338 return Err(Error::NotSupported);
339 }
340 Ok(self.is_instance_validatable())
341 }
342
343 fn GetForm(&self) -> Fallible<Option<DomRoot<HTMLFormElement>>> {
345 if !self.is_target_form_associated() {
346 return Err(Error::NotSupported);
347 }
348 Ok(self.form_owner.get())
349 }
350
351 fn CheckValidity(&self, can_gc: CanGc) -> Fallible<bool> {
353 if !self.is_target_form_associated() {
354 return Err(Error::NotSupported);
355 }
356 Ok(self.check_validity(can_gc))
357 }
358
359 fn ReportValidity(&self, can_gc: CanGc) -> Fallible<bool> {
361 if !self.is_target_form_associated() {
362 return Err(Error::NotSupported);
363 }
364 Ok(self.report_validity(can_gc))
365 }
366
367 fn States(&self, can_gc: CanGc) -> DomRoot<CustomStateSet> {
369 self.states.or_init(|| {
370 CustomStateSet::new(
371 &self.target_element.owner_window(),
372 &self.target_element,
373 can_gc,
374 )
375 })
376 }
377}
378
379impl Validatable for ElementInternals {
381 fn as_element(&self) -> &Element {
382 debug_assert!(self.is_target_form_associated());
383 self.target_element.upcast::<Element>()
384 }
385
386 fn validity_state(&self) -> DomRoot<ValidityState> {
387 debug_assert!(self.is_target_form_associated());
388 self.validity_state.or_init(|| {
389 ValidityState::new(
390 &self.target_element.owner_window(),
391 self.target_element.upcast(),
392 CanGc::note(),
393 )
394 })
395 }
396
397 fn is_instance_validatable(&self) -> bool {
399 debug_assert!(self.is_target_form_associated());
400 if !self.target_element.is_submittable_element() {
401 return false;
402 }
403
404 !self.as_element().read_write_state() &&
408 !self.as_element().disabled_state() &&
409 !is_barred_by_datalist_ancestor(self.target_element.upcast::<Node>())
410 }
411}