1use 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 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 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 if !submit_button.is_submit_button() {
106 return Err(Error::Type(c"submitter is not a submit button".to_owned()));
107 }
108
109 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 if let Some(opt_form) = form {
120 let submitter_element = submitter
122 .map(|s| validate_submitter(s, opt_form))
123 .transpose()?;
124
125 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 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 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 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 fn Delete(&self, name: USVString) {
178 self.data
179 .borrow_mut()
180 .retain(|(datum_name, _)| datum_name.0 != name.0);
181 }
182
183 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 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 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 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 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 fn create_an_entry(
263 &self,
264 blob: &Blob,
265 opt_filename: Option<USVString>,
266 can_gc: CanGc,
267 ) -> DomRoot<File> {
268 let name = match opt_filename {
270 Some(filename) => DOMString::from(filename.0),
271 None => match blob.downcast::<File>() {
272 None => DOMString::from("blob"),
273 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}