Skip to main content

script/dom/
formdata.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;
7use js::context::JSContext;
8use js::rust::HandleObject;
9use script_bindings::cell::DomRefCell;
10use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
11use servo_constellation_traits::BlobImpl;
12
13use super::bindings::trace::NoTrace;
14use crate::dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
15use crate::dom::bindings::codegen::UnionTypes::FileOrUSVString;
16use crate::dom::bindings::error::{Error, Fallible};
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::bindings::iterable::Iterable;
19use crate::dom::bindings::reflector::DomGlobal;
20use crate::dom::bindings::root::DomRoot;
21use crate::dom::bindings::str::{DOMString, USVString};
22use crate::dom::blob::Blob;
23use crate::dom::file::File;
24use crate::dom::globalscope::GlobalScope;
25use crate::dom::html::htmlbuttonelement::HTMLButtonElement;
26use crate::dom::html::htmlelement::HTMLElement;
27use crate::dom::html::htmlformelement::{
28    FormDatum, FormDatumValue, FormSubmitterElement, HTMLFormElement,
29};
30use crate::dom::html::input_element::HTMLInputElement;
31use crate::script_runtime::CanGc;
32
33#[dom_struct]
34pub(crate) struct FormData {
35    reflector_: Reflector,
36    data: DomRefCell<Vec<(NoTrace<LocalName>, FormDatum)>>,
37}
38
39impl FormData {
40    fn new_inherited(form_datums: Option<Vec<FormDatum>>) -> FormData {
41        let data = match form_datums {
42            Some(data) => data
43                .iter()
44                .map(|datum| (NoTrace(LocalName::from(&datum.name)), datum.clone()))
45                .collect::<Vec<(NoTrace<LocalName>, FormDatum)>>(),
46            None => Vec::new(),
47        };
48
49        FormData {
50            reflector_: Reflector::new(),
51            data: DomRefCell::new(data),
52        }
53    }
54
55    pub(crate) fn new(
56        form_datums: Option<Vec<FormDatum>>,
57        global: &GlobalScope,
58        can_gc: CanGc,
59    ) -> DomRoot<FormData> {
60        Self::new_with_proto(form_datums, global, None, can_gc)
61    }
62
63    fn new_with_proto(
64        form_datums: Option<Vec<FormDatum>>,
65        global: &GlobalScope,
66        proto: Option<HandleObject>,
67        can_gc: CanGc,
68    ) -> DomRoot<FormData> {
69        reflect_dom_object_with_proto(
70            Box::new(FormData::new_inherited(form_datums)),
71            global,
72            proto,
73            can_gc,
74        )
75    }
76}
77
78impl FormDataMethods<crate::DomTypeHolder> for FormData {
79    /// <https://xhr.spec.whatwg.org/#dom-formdata>
80    fn Constructor<'a>(
81        cx: &mut JSContext,
82        global: &GlobalScope,
83        proto: Option<HandleObject>,
84        form: Option<&'a HTMLFormElement>,
85        submitter: Option<&'a HTMLElement>,
86    ) -> Fallible<DomRoot<FormData>> {
87        // Helper to validate the submitter
88        fn validate_submitter<'b>(
89            submitter: &'b HTMLElement,
90            form: &'b HTMLFormElement,
91        ) -> Result<FormSubmitterElement<'b>, Error> {
92            let submit_button = submitter
93                .downcast::<HTMLButtonElement>()
94                .map(FormSubmitterElement::Button)
95                .or_else(|| {
96                    submitter
97                        .downcast::<HTMLInputElement>()
98                        .map(FormSubmitterElement::Input)
99                })
100                .ok_or(Error::Type(
101                    c"submitter is not a form submitter element".to_owned(),
102                ))?;
103
104            // Step 1.1.1. If submitter is not a submit button, then throw a TypeError.
105            if !submit_button.is_submit_button() {
106                return Err(Error::Type(c"submitter is not a submit button".to_owned()));
107            }
108
109            // Step 1.1.2. If submitter’s form owner is not form, then throw a "NotFoundError"
110            // DOMException.
111            if !matches!(submit_button.form_owner(), Some(owner) if *owner == *form) {
112                return Err(Error::NotFound(None));
113            }
114
115            Ok(submit_button)
116        }
117
118        // Step 1. If form is given, then:
119        if let Some(opt_form) = form {
120            // Step 1.1. If submitter is non-null, then:
121            let submitter_element = submitter
122                .map(|s| validate_submitter(s, opt_form))
123                .transpose()?;
124
125            // Step 1.2. Let list be the result of constructing the entry list for form and submitter.
126            return match opt_form.get_form_dataset(cx, submitter_element, None) {
127                Some(form_datums) => Ok(FormData::new_with_proto(
128                    Some(form_datums),
129                    global,
130                    proto,
131                    CanGc::from_cx(cx),
132                )),
133                // Step 1.3. If list is null, then throw an "InvalidStateError" DOMException.
134                None => Err(Error::InvalidState(None)),
135            };
136        }
137
138        Ok(FormData::new_with_proto(
139            None,
140            global,
141            proto,
142            CanGc::from_cx(cx),
143        ))
144    }
145
146    /// <https://xhr.spec.whatwg.org/#dom-formdata-append>
147    fn Append(&self, name: USVString, str_value: USVString) {
148        let datum = FormDatum {
149            ty: DOMString::from("string"),
150            name: DOMString::from(name.0.clone()),
151            value: FormDatumValue::String(DOMString::from(str_value.0)),
152        };
153
154        self.data
155            .borrow_mut()
156            .push((NoTrace(LocalName::from(name.0)), datum));
157    }
158
159    /// <https://xhr.spec.whatwg.org/#dom-formdata-append>
160    fn Append_(&self, name: USVString, blob: &Blob, filename: Option<USVString>) {
161        let datum = FormDatum {
162            ty: DOMString::from("file"),
163            name: DOMString::from(name.0.clone()),
164            value: FormDatumValue::File(DomRoot::from_ref(&*self.create_an_entry(
165                blob,
166                filename,
167                CanGc::deprecated_note(),
168            ))),
169        };
170
171        self.data
172            .borrow_mut()
173            .push((NoTrace(LocalName::from(name.0)), datum));
174    }
175
176    /// <https://xhr.spec.whatwg.org/#dom-formdata-delete>
177    fn Delete(&self, name: USVString) {
178        self.data
179            .borrow_mut()
180            .retain(|(datum_name, _)| datum_name.0 != name.0);
181    }
182
183    /// <https://xhr.spec.whatwg.org/#dom-formdata-get>
184    fn Get(&self, name: USVString) -> Option<FileOrUSVString> {
185        self.data
186            .borrow()
187            .iter()
188            .find(|(datum_name, _)| datum_name.0 == name.0)
189            .map(|(_, datum)| match &datum.value {
190                FormDatumValue::String(s) => FileOrUSVString::USVString(USVString(s.to_string())),
191                FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
192            })
193    }
194
195    /// <https://xhr.spec.whatwg.org/#dom-formdata-getall>
196    fn GetAll(&self, name: USVString) -> Vec<FileOrUSVString> {
197        self.data
198            .borrow()
199            .iter()
200            .filter_map(|(datum_name, datum)| {
201                if datum_name.0 != name.0 {
202                    return None;
203                }
204
205                Some(match &datum.value {
206                    FormDatumValue::String(s) => {
207                        FileOrUSVString::USVString(USVString(s.to_string()))
208                    },
209                    FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
210                })
211            })
212            .collect()
213    }
214
215    /// <https://xhr.spec.whatwg.org/#dom-formdata-has>
216    fn Has(&self, name: USVString) -> bool {
217        self.data
218            .borrow()
219            .iter()
220            .any(|(datum_name, _0)| datum_name.0 == name.0)
221    }
222
223    /// <https://xhr.spec.whatwg.org/#dom-formdata-set>
224    fn Set(&self, name: USVString, str_value: USVString) {
225        let mut data = self.data.borrow_mut();
226        let local_name = LocalName::from(name.0.clone());
227
228        data.retain(|(datum_name, _)| datum_name.0 != local_name);
229
230        data.push((
231            NoTrace(local_name),
232            FormDatum {
233                ty: DOMString::from("string"),
234                name: DOMString::from(name.0),
235                value: FormDatumValue::String(DOMString::from(str_value.0)),
236            },
237        ));
238    }
239
240    /// <https://xhr.spec.whatwg.org/#dom-formdata-set>
241    fn Set_(&self, name: USVString, blob: &Blob, filename: Option<USVString>) {
242        let file = self.create_an_entry(blob, filename, CanGc::deprecated_note());
243
244        let mut data = self.data.borrow_mut();
245        let local_name = LocalName::from(name.0.clone());
246
247        data.retain(|(datum_name, _)| datum_name.0 != local_name);
248
249        data.push((
250            NoTrace(LocalName::from(name.0.clone())),
251            FormDatum {
252                ty: DOMString::from("file"),
253                name: DOMString::from(name.0),
254                value: FormDatumValue::File(file),
255            },
256        ));
257    }
258}
259
260impl FormData {
261    /// <https://xhr.spec.whatwg.org/#create-an-entry>
262    fn create_an_entry(
263        &self,
264        blob: &Blob,
265        opt_filename: Option<USVString>,
266        can_gc: CanGc,
267    ) -> DomRoot<File> {
268        // Steps 3-4
269        let name = match opt_filename {
270            Some(filename) => DOMString::from(filename.0),
271            None => match blob.downcast::<File>() {
272                None => DOMString::from("blob"),
273                // If it is already a file and no filename was given,
274                // then neither step 3 nor step 4 happens, so instead of
275                // creating a new File object we use the existing one.
276                Some(file) => {
277                    return DomRoot::from_ref(file);
278                },
279            },
280        };
281
282        let bytes = blob.get_bytes().unwrap_or_default();
283        let last_modified = blob.downcast::<File>().map(|file| file.get_modified());
284
285        File::new(
286            &self.global(),
287            BlobImpl::new_from_bytes(bytes, blob.type_string()),
288            name,
289            last_modified,
290            can_gc,
291        )
292    }
293
294    pub(crate) fn datums(&self) -> Vec<FormDatum> {
295        self.data
296            .borrow()
297            .iter()
298            .map(|(_, datum)| datum.clone())
299            .collect()
300    }
301}
302
303impl Iterable for FormData {
304    type Key = USVString;
305    type Value = FileOrUSVString;
306
307    fn get_iterable_length(&self) -> u32 {
308        self.data.borrow().len() as u32
309    }
310
311    fn get_value_at_index(&self, n: u32) -> FileOrUSVString {
312        let data = self.data.borrow();
313        let datum = &data.get(n as usize).unwrap().1;
314        match &datum.value {
315            FormDatumValue::String(s) => FileOrUSVString::USVString(USVString(s.to_string())),
316            FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
317        }
318    }
319
320    fn get_key_at_index(&self, n: u32) -> USVString {
321        let data = self.data.borrow();
322        let key = &data.get(n as usize).unwrap().0;
323        USVString(key.to_string())
324    }
325}