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.as_ref())), 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);
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),
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    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
153    // https://xhr.spec.whatwg.org/#dom-formdata-append
154    fn Append_(&self, name: USVString, blob: &Blob, filename: Option<USVString>) {
155        let datum = FormDatum {
156            ty: DOMString::from("file"),
157            name: DOMString::from(name.0.clone()),
158            value: FormDatumValue::File(DomRoot::from_ref(&*self.create_an_entry(
159                blob,
160                filename,
161                CanGc::note(),
162            ))),
163        };
164
165        self.data
166            .borrow_mut()
167            .push((NoTrace(LocalName::from(name.0)), datum));
168    }
169
170    // https://xhr.spec.whatwg.org/#dom-formdata-delete
171    fn Delete(&self, name: USVString) {
172        self.data
173            .borrow_mut()
174            .retain(|(datum_name, _)| datum_name.0 != name.0);
175    }
176
177    // https://xhr.spec.whatwg.org/#dom-formdata-get
178    fn Get(&self, name: USVString) -> Option<FileOrUSVString> {
179        self.data
180            .borrow()
181            .iter()
182            .find(|(datum_name, _)| datum_name.0 == name.0)
183            .map(|(_, datum)| match &datum.value {
184                FormDatumValue::String(s) => FileOrUSVString::USVString(USVString(s.to_string())),
185                FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
186            })
187    }
188
189    // https://xhr.spec.whatwg.org/#dom-formdata-getall
190    fn GetAll(&self, name: USVString) -> Vec<FileOrUSVString> {
191        self.data
192            .borrow()
193            .iter()
194            .filter_map(|(datum_name, datum)| {
195                if datum_name.0 != name.0 {
196                    return None;
197                }
198
199                Some(match &datum.value {
200                    FormDatumValue::String(s) => {
201                        FileOrUSVString::USVString(USVString(s.to_string()))
202                    },
203                    FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
204                })
205            })
206            .collect()
207    }
208
209    // https://xhr.spec.whatwg.org/#dom-formdata-has
210    fn Has(&self, name: USVString) -> bool {
211        self.data
212            .borrow()
213            .iter()
214            .any(|(datum_name, _0)| datum_name.0 == name.0)
215    }
216
217    // https://xhr.spec.whatwg.org/#dom-formdata-set
218    fn Set(&self, name: USVString, str_value: USVString) {
219        let mut data = self.data.borrow_mut();
220        let local_name = LocalName::from(name.0.clone());
221
222        data.retain(|(datum_name, _)| datum_name.0 != local_name);
223
224        data.push((
225            NoTrace(local_name),
226            FormDatum {
227                ty: DOMString::from("string"),
228                name: DOMString::from(name.0),
229                value: FormDatumValue::String(DOMString::from(str_value.0)),
230            },
231        ));
232    }
233
234    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
235    // https://xhr.spec.whatwg.org/#dom-formdata-set
236    fn Set_(&self, name: USVString, blob: &Blob, filename: Option<USVString>) {
237        let file = self.create_an_entry(blob, filename, CanGc::note());
238
239        let mut data = self.data.borrow_mut();
240        let local_name = LocalName::from(name.0.clone());
241
242        data.retain(|(datum_name, _)| datum_name.0 != local_name);
243
244        data.push((
245            NoTrace(LocalName::from(name.0.clone())),
246            FormDatum {
247                ty: DOMString::from("file"),
248                name: DOMString::from(name.0),
249                value: FormDatumValue::File(file),
250            },
251        ));
252    }
253}
254
255impl FormData {
256    // https://xhr.spec.whatwg.org/#create-an-entry
257    fn create_an_entry(
258        &self,
259        blob: &Blob,
260        opt_filename: Option<USVString>,
261        can_gc: CanGc,
262    ) -> DomRoot<File> {
263        // Steps 3-4
264        let name = match opt_filename {
265            Some(filename) => DOMString::from(filename.0),
266            None => match blob.downcast::<File>() {
267                None => DOMString::from("blob"),
268                // If it is already a file and no filename was given,
269                // then neither step 3 nor step 4 happens, so instead of
270                // creating a new File object we use the existing one.
271                Some(file) => {
272                    return DomRoot::from_ref(file);
273                },
274            },
275        };
276
277        let bytes = blob.get_bytes().unwrap_or_default();
278        let last_modified = blob.downcast::<File>().map(|file| file.get_modified());
279
280        File::new(
281            &self.global(),
282            BlobImpl::new_from_bytes(bytes, blob.type_string()),
283            name,
284            last_modified,
285            can_gc,
286        )
287    }
288
289    pub(crate) fn datums(&self) -> Vec<FormDatum> {
290        self.data
291            .borrow()
292            .iter()
293            .map(|(_, datum)| datum.clone())
294            .collect()
295    }
296}
297
298impl Iterable for FormData {
299    type Key = USVString;
300    type Value = FileOrUSVString;
301
302    fn get_iterable_length(&self) -> u32 {
303        self.data.borrow().len() as u32
304    }
305
306    fn get_value_at_index(&self, n: u32) -> FileOrUSVString {
307        let data = self.data.borrow();
308        let datum = &data.get(n as usize).unwrap().1;
309        match &datum.value {
310            FormDatumValue::String(s) => FileOrUSVString::USVString(USVString(s.to_string())),
311            FormDatumValue::File(b) => FileOrUSVString::File(DomRoot::from_ref(b)),
312        }
313    }
314
315    fn get_key_at_index(&self, n: u32) -> USVString {
316        let data = self.data.borrow();
317        let key = &data.get(n as usize).unwrap().0;
318        USVString(key.to_string())
319    }
320}