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