Skip to main content

script/dom/html/form_controls/
htmlformelement.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 std::borrow::{Cow, ToOwned};
6use std::cell::Cell;
7
8use content_security_policy::sandboxing_directive::SandboxingFlagSet;
9use dom_struct::dom_struct;
10use encoding_rs::{Encoding, UTF_8};
11use headers::{ContentType, HeaderMapExt};
12use html5ever::{LocalName, Prefix, local_name};
13use http::Method;
14use js::context::{JSContext, NoGC};
15use js::rust::HandleObject;
16use mime::{self, Mime};
17use net_traits::request::Referrer;
18use rand::random;
19use rustc_hash::FxBuildHasher;
20use script_bindings::cell::DomRefCell;
21use script_bindings::codegen::GenericBindings::DocumentFragmentBinding::DocumentFragmentMethods;
22use script_bindings::dom::UnrootedDom;
23use script_bindings::domstring::TracedDOMString;
24use script_bindings::match_domstring_ascii;
25use script_bindings::reflector::DomObject;
26use servo_constellation_traits::{LoadData, LoadOrigin, NavigationHistoryBehavior};
27use style::attr::AttrValue;
28use style::str::split_html_space_chars;
29use stylo_atoms::Atom;
30use stylo_dom::ElementState;
31
32use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
33use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
34use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
35use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
36use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
37use crate::dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods;
38use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding::HTMLFormElementMethods;
39use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
40use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
41use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
42use crate::dom::bindings::codegen::Bindings::NodeBinding::{NodeConstants, NodeMethods};
43use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
44use crate::dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods;
45use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
46use crate::dom::bindings::error::{Error, Fallible};
47use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
48use crate::dom::bindings::refcounted::Trusted;
49use crate::dom::bindings::reflector::DomGlobal;
50use crate::dom::bindings::root::{Dom, DomOnceCell, DomRoot, MutNullableDom};
51use crate::dom::bindings::str::DOMString;
52use crate::dom::bindings::trace::{HashMapTracedValues, NoTrace};
53use crate::dom::blob::Blob;
54use crate::dom::customelementregistry::CallbackReaction;
55use crate::dom::document::Document;
56use crate::dom::domtokenlist::DOMTokenList;
57use crate::dom::element::attributes::storage::AttrRef;
58use crate::dom::element::{AttributeMutation, Element};
59use crate::dom::event::{Event, EventBubbles, EventCancelable};
60use crate::dom::eventtarget::EventTarget;
61use crate::dom::file::File;
62use crate::dom::formdata::FormData;
63use crate::dom::formdataevent::FormDataEvent;
64use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
65use crate::dom::html::form_controls::input_type::InputType;
66use crate::dom::html::htmlbuttonelement::HTMLButtonElement;
67use crate::dom::html::htmlcollection::CollectionFilter;
68use crate::dom::html::htmldatalistelement::HTMLDataListElement;
69use crate::dom::html::htmlelement::HTMLElement;
70use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
71use crate::dom::html::htmlformcontrolscollection::HTMLFormControlsCollection;
72use crate::dom::html::htmlimageelement::HTMLImageElement;
73use crate::dom::html::htmllegendelement::HTMLLegendElement;
74use crate::dom::html::htmlobjectelement::HTMLObjectElement;
75use crate::dom::html::htmloutputelement::HTMLOutputElement;
76use crate::dom::html::htmlselectelement::HTMLSelectElement;
77use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
78use crate::dom::html::links::relations::{
79    LinkRelations, get_element_target, valid_navigable_target_name_or_keyword,
80};
81use crate::dom::node::virtualmethods::VirtualMethods;
82use crate::dom::node::{Node, NodeFlags, NodeTraits, UnbindContext, VecPreOrderInsertionHelper};
83use crate::dom::nodelist::{NodeList, RadioListMode};
84use crate::dom::radionodelist::RadioNodeList;
85use crate::dom::submitevent::SubmitEvent;
86use crate::dom::types::{DocumentFragment, HTMLIFrameElement};
87use crate::dom::window::Window;
88use crate::event_loop::script_thread::ScriptThread;
89use crate::fetch::body::Extractable;
90use crate::navigation::navigate;
91
92/// <https://html.spec.whatwg.org/multipage/#the-form-element>
93#[dom_struct]
94pub(crate) struct HTMLFormElement {
95    htmlelement: HTMLElement,
96    marked_for_reset: Cell<bool>,
97    /// <https://html.spec.whatwg.org/multipage/#constructing-entry-list>
98    constructing_entry_list: Cell<bool>,
99    elements: DomOnceCell<HTMLFormControlsCollection>,
100    controls: DomRefCell<Vec<Dom<Element>>>,
101
102    /// It is safe to use FxBuildHasher here as `Atom` is in the string_cache.
103    #[expect(clippy::type_complexity)]
104    past_names_map:
105        DomRefCell<HashMapTracedValues<Atom, (Dom<Element>, NoTrace<usize>), FxBuildHasher>>,
106
107    /// The current generation of past names, i.e., the number of name changes to the name.
108    current_name_generation: Cell<usize>,
109
110    firing_submission_events: Cell<bool>,
111    rel_list: MutNullableDom<DOMTokenList>,
112
113    /// <https://html.spec.whatwg.org/multipage/#planned-navigation>
114    planned_navigation: Cell<usize>,
115
116    /// <https://html.spec.whatwg.org/multipage/#attr-form-rel>
117    #[no_trace]
118    relations: Cell<LinkRelations>,
119}
120
121impl HTMLFormElement {
122    fn new_inherited(
123        local_name: LocalName,
124        prefix: Option<Prefix>,
125        document: &Document,
126    ) -> HTMLFormElement {
127        HTMLFormElement {
128            htmlelement: HTMLElement::new_inherited_with_state(
129                ElementState::VALID,
130                local_name,
131                prefix,
132                document,
133            ),
134            marked_for_reset: Cell::new(false),
135            constructing_entry_list: Cell::new(false),
136            elements: Default::default(),
137            controls: DomRefCell::new(Vec::new()),
138            past_names_map: DomRefCell::new(HashMapTracedValues::new_fx()),
139            current_name_generation: Cell::new(0),
140            firing_submission_events: Cell::new(false),
141            rel_list: Default::default(),
142            planned_navigation: Default::default(),
143            relations: Cell::new(LinkRelations::empty()),
144        }
145    }
146
147    pub(crate) fn new(
148        cx: &mut JSContext,
149        local_name: LocalName,
150        prefix: Option<Prefix>,
151        document: &Document,
152        proto: Option<HandleObject>,
153    ) -> DomRoot<HTMLFormElement> {
154        Node::reflect_node_with_proto(
155            cx,
156            Box::new(HTMLFormElement::new_inherited(local_name, prefix, document)),
157            document,
158            proto,
159        )
160    }
161
162    fn filter_for_radio_list(mode: RadioListMode, child: &Element, name: &Atom) -> bool {
163        if let Some(child) = child.downcast::<Element>() {
164            match mode {
165                RadioListMode::ControlsExceptImageInputs => {
166                    if child
167                        .downcast::<HTMLElement>()
168                        .is_some_and(|c| c.is_listed_element()) &&
169                        (child.get_id().is_some_and(|i| i == *name) ||
170                            child.get_name().is_some_and(|n| n == *name))
171                    {
172                        if let Some(inp) = child.downcast::<HTMLInputElement>() {
173                            // input, only return it if it's not image-button state
174                            return !matches!(*inp.input_type(), InputType::Image(_));
175                        } else {
176                            // control, but not an input
177                            return true;
178                        }
179                    }
180                    return false;
181                },
182                RadioListMode::Images => {
183                    return child.is::<HTMLImageElement>() &&
184                        (child.get_id().is_some_and(|i| i == *name) ||
185                            child.get_name().is_some_and(|n| n == *name));
186                },
187            }
188        }
189        false
190    }
191
192    pub(crate) fn nth_for_radio_list<'a>(
193        &self,
194        no_gc: &'a NoGC,
195        index: u32,
196        mode: RadioListMode,
197        name: &Atom,
198    ) -> Option<UnrootedDom<'a, Node>> {
199        self.controls
200            .borrow()
201            .iter()
202            .filter(|n| HTMLFormElement::filter_for_radio_list(mode, n, name))
203            .nth(index as usize)
204            .map(|node| UnrootedDom::upcast(node.as_unrooted(no_gc)))
205    }
206
207    pub(crate) fn count_for_radio_list(&self, mode: RadioListMode, name: &Atom) -> u32 {
208        self.controls
209            .borrow()
210            .iter()
211            .filter(|n| HTMLFormElement::filter_for_radio_list(mode, n, name))
212            .count() as u32
213    }
214
215    /// <https://html.spec.whatwg.org/multipage/#default-button>
216    pub(crate) fn default_button(&self) -> Option<DomRoot<Element>> {
217        // > A form element's default button is the first submit button in tree order whose form owner
218        // > is that form element. `controls` holds exactly the elements owned by this form, kept in
219        // > tree order.
220        self.controls
221            .borrow()
222            .iter()
223            .find(|control| {
224                control
225                    .downcast::<HTMLInputElement>()
226                    .is_some_and(HTMLInputElement::is_submit_button) ||
227                    control
228                        .downcast::<HTMLButtonElement>()
229                        .is_some_and(HTMLButtonElement::is_submit_button)
230            })
231            .map(|control| control.as_rooted())
232    }
233
234    pub(crate) fn invalidate_default_button(&self, no_gc: &NoGC) {
235        let default_button = self.default_button();
236        for control in self.controls.borrow().iter() {
237            Self::update_control_default_state(
238                no_gc,
239                control,
240                default_button.as_deref() == Some(&**control),
241            );
242        }
243    }
244
245    fn update_control_default_state(no_gc: &NoGC, control: &Element, is_default_button: bool) {
246        if let Some(button) = control.downcast::<HTMLButtonElement>() {
247            button.update_default_state(is_default_button, no_gc);
248        } else if let Some(input) = control.downcast::<HTMLInputElement>() {
249            input.update_default_state(is_default_button, no_gc);
250        }
251    }
252}
253
254impl HTMLFormElementMethods<crate::DomTypeHolder> for HTMLFormElement {
255    // https://html.spec.whatwg.org/multipage/#dom-form-acceptcharset
256    make_getter!(AcceptCharset, "accept-charset");
257
258    // https://html.spec.whatwg.org/multipage/#dom-form-acceptcharset
259    make_setter!(SetAcceptCharset, "accept-charset");
260
261    // https://html.spec.whatwg.org/multipage/#dom-fs-action
262    make_form_action_getter!(Action, "action");
263
264    // https://html.spec.whatwg.org/multipage/#dom-fs-action
265    make_setter!(SetAction, "action");
266
267    // https://html.spec.whatwg.org/multipage/#dom-form-autocomplete
268    make_enumerated_getter!(
269        Autocomplete,
270        "autocomplete",
271        "on" | "off",
272        missing => "on",
273        invalid => "on"
274    );
275
276    // https://html.spec.whatwg.org/multipage/#dom-form-autocomplete
277    make_setter!(SetAutocomplete, "autocomplete");
278
279    // https://html.spec.whatwg.org/multipage/#dom-fs-enctype
280    make_enumerated_getter!(
281        Enctype,
282        "enctype",
283        "application/x-www-form-urlencoded" | "text/plain" | "multipart/form-data",
284        missing => "application/x-www-form-urlencoded",
285        invalid => "application/x-www-form-urlencoded"
286    );
287
288    // https://html.spec.whatwg.org/multipage/#dom-fs-enctype
289    make_setter!(SetEnctype, "enctype");
290
291    /// <https://html.spec.whatwg.org/multipage/#dom-fs-encoding>
292    fn Encoding(&self) -> DOMString {
293        self.Enctype()
294    }
295
296    /// <https://html.spec.whatwg.org/multipage/#dom-fs-encoding>
297    fn SetEncoding(&self, cx: &mut JSContext, value: DOMString) {
298        self.SetEnctype(cx, value)
299    }
300
301    // https://html.spec.whatwg.org/multipage/#dom-fs-method
302    make_enumerated_getter!(
303        Method,
304        "method",
305        "get" | "post" | "dialog",
306        missing => "get",
307        invalid => "get"
308    );
309
310    // https://html.spec.whatwg.org/multipage/#dom-fs-method
311    make_setter!(SetMethod, "method");
312
313    // https://html.spec.whatwg.org/multipage/#dom-form-name
314    make_getter!(Name, "name");
315
316    // https://html.spec.whatwg.org/multipage/#dom-form-name
317    make_atomic_setter!(SetName, "name");
318
319    // https://html.spec.whatwg.org/multipage/#dom-fs-novalidate
320    make_bool_getter!(NoValidate, "novalidate");
321
322    // https://html.spec.whatwg.org/multipage/#dom-fs-novalidate
323    make_bool_setter!(SetNoValidate, "novalidate");
324
325    // https://html.spec.whatwg.org/multipage/#dom-fs-target
326    make_getter!(Target, "target");
327
328    // https://html.spec.whatwg.org/multipage/#dom-fs-target
329    make_setter!(SetTarget, "target");
330
331    // https://html.spec.whatwg.org/multipage/#dom-a-rel
332    make_getter!(Rel, "rel");
333
334    /// <https://html.spec.whatwg.org/multipage/#the-form-element:concept-form-submit>
335    fn Submit(&self, cx: &mut JSContext) {
336        self.submit(
337            cx,
338            SubmittedFrom::FromForm,
339            FormSubmitterElement::Form(self),
340        );
341    }
342
343    /// <https://html.spec.whatwg.org/multipage/#dom-form-requestsubmit>
344    fn RequestSubmit(&self, cx: &mut JSContext, submitter: Option<&HTMLElement>) -> Fallible<()> {
345        let submitter: FormSubmitterElement = match submitter {
346            Some(submitter_element) => {
347                // Step 1.1
348                let error_not_a_submit_button =
349                    Err(Error::Type(c"submitter must be a submit button".to_owned()));
350
351                let element = match submitter_element.upcast::<Node>().type_id() {
352                    NodeTypeId::Element(ElementTypeId::HTMLElement(element)) => element,
353                    _ => {
354                        return error_not_a_submit_button;
355                    },
356                };
357
358                let submit_button = match element {
359                    HTMLElementTypeId::HTMLInputElement => FormSubmitterElement::Input(
360                        submitter_element
361                            .downcast::<HTMLInputElement>()
362                            .expect("Failed to downcast submitter elem to HTMLInputElement."),
363                    ),
364                    HTMLElementTypeId::HTMLButtonElement => FormSubmitterElement::Button(
365                        submitter_element
366                            .downcast::<HTMLButtonElement>()
367                            .expect("Failed to downcast submitter elem to HTMLButtonElement."),
368                    ),
369                    _ => {
370                        return error_not_a_submit_button;
371                    },
372                };
373
374                if !submit_button.is_submit_button() {
375                    return error_not_a_submit_button;
376                }
377
378                let submitters_owner = submit_button.form_owner();
379
380                // Step 1.2
381                let owner = match submitters_owner {
382                    Some(owner) => owner,
383                    None => {
384                        return Err(Error::NotFound(Some(
385                            "Form element's owner does not exist".into(),
386                        )));
387                    },
388                };
389
390                if *owner != *self {
391                    return Err(Error::NotFound(Some("The form that owns this submitter element does not match the form element provided".into())));
392                }
393
394                submit_button
395            },
396            None => {
397                // Step 2
398                FormSubmitterElement::Form(self)
399            },
400        };
401        // Step 3
402        self.submit(cx, SubmittedFrom::NotFromForm, submitter);
403        Ok(())
404    }
405
406    /// <https://html.spec.whatwg.org/multipage/#dom-form-reset>
407    fn Reset(&self, cx: &mut JSContext) {
408        self.reset(cx, ResetFrom::FromForm);
409    }
410
411    /// <https://html.spec.whatwg.org/multipage/#dom-form-elements>
412    fn Elements(&self, cx: &mut JSContext) -> DomRoot<HTMLFormControlsCollection> {
413        #[derive(JSTraceable, MallocSizeOf)]
414        #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
415        struct ElementsFilter {
416            form: Dom<HTMLFormElement>,
417        }
418        impl CollectionFilter for ElementsFilter {
419            fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool {
420                let form_owner = match elem.upcast::<Node>().type_id() {
421                    NodeTypeId::Element(ElementTypeId::HTMLElement(t)) => match t {
422                        HTMLElementTypeId::HTMLButtonElement => {
423                            elem.downcast::<HTMLButtonElement>().unwrap().form_owner()
424                        },
425                        HTMLElementTypeId::HTMLFieldSetElement => {
426                            elem.downcast::<HTMLFieldSetElement>().unwrap().form_owner()
427                        },
428                        HTMLElementTypeId::HTMLInputElement => {
429                            let input_elem = elem.downcast::<HTMLInputElement>().unwrap();
430                            if matches!(*input_elem.input_type(), InputType::Image(_)) {
431                                return false;
432                            }
433                            input_elem.form_owner()
434                        },
435                        HTMLElementTypeId::HTMLObjectElement => {
436                            elem.downcast::<HTMLObjectElement>().unwrap().form_owner()
437                        },
438                        HTMLElementTypeId::HTMLOutputElement => {
439                            elem.downcast::<HTMLOutputElement>().unwrap().form_owner()
440                        },
441                        HTMLElementTypeId::HTMLSelectElement => {
442                            elem.downcast::<HTMLSelectElement>().unwrap().form_owner()
443                        },
444                        HTMLElementTypeId::HTMLTextAreaElement => {
445                            elem.downcast::<HTMLTextAreaElement>().unwrap().form_owner()
446                        },
447                        HTMLElementTypeId::HTMLElement => {
448                            let html_element = elem.downcast::<HTMLElement>().unwrap();
449                            if html_element.is_form_associated_custom_element() {
450                                html_element.form_owner()
451                            } else {
452                                return false;
453                            }
454                        },
455                        _ => {
456                            debug_assert!(
457                                !elem.downcast::<HTMLElement>().unwrap().is_listed_element()
458                            );
459                            return false;
460                        },
461                    },
462                    _ => return false,
463                };
464
465                form_owner
466                    .as_deref()
467                    .is_some_and(|form_owner| self.form == form_owner)
468            }
469        }
470        DomRoot::from_ref(self.elements.init_once(|| {
471            let window = self.owner_window();
472            HTMLFormControlsCollection::new(
473                cx,
474                &window,
475                self,
476                Box::new(ElementsFilter {
477                    form: Dom::from_ref(self),
478                }),
479            )
480        }))
481    }
482
483    /// <https://html.spec.whatwg.org/multipage/#dom-form-length>
484    fn Length(&self, cx: &mut JSContext) -> u32 {
485        self.Elements(cx).Length(cx)
486    }
487
488    /// <https://html.spec.whatwg.org/multipage/#dom-form-item>
489    fn IndexedGetter(&self, cx: &mut JSContext, index: u32) -> Option<DomRoot<Element>> {
490        let elements = self.Elements(cx);
491        elements.IndexedGetter(cx, index)
492    }
493
494    /// <https://html.spec.whatwg.org/multipage/#the-form-element%3Adetermine-the-value-of-a-named-property>
495    fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<RadioNodeListOrElement> {
496        let window = self.owner_window();
497
498        let name = Atom::from(name);
499
500        // Step 1
501        let mut candidates =
502            RadioNodeList::new_controls_except_image_inputs(cx, &window, self, &name);
503        let mut candidates_length = candidates.Length(cx);
504
505        // Step 2
506        if candidates_length == 0 {
507            candidates = RadioNodeList::new_images(cx, &window, self, &name);
508            candidates_length = candidates.Length(cx);
509        }
510
511        let mut past_names_map = self.past_names_map.safe_borrow_mut(cx.no_gc());
512
513        // Step 3
514        if candidates_length == 0 {
515            if past_names_map.contains_key(&name) {
516                return Some(RadioNodeListOrElement::Element(DomRoot::from_ref(
517                    &*past_names_map.get(&name).unwrap().0,
518                )));
519            }
520            return None;
521        }
522
523        // Step 4
524        if candidates_length > 1 {
525            return Some(RadioNodeListOrElement::RadioNodeList(candidates));
526        }
527
528        // Step 5
529        // candidates_length is 1, so we can unwrap item 0
530        let element_node = candidates.upcast::<NodeList>().Item(cx, 0).unwrap();
531        past_names_map.insert(
532            name,
533            (
534                Dom::from_ref(element_node.downcast::<Element>().unwrap()),
535                NoTrace(self.current_name_generation.get() + 1),
536            ),
537        );
538        self.current_name_generation
539            .set(self.current_name_generation.get() + 1);
540
541        // Step 6
542        Some(RadioNodeListOrElement::Element(DomRoot::from_ref(
543            element_node.downcast::<Element>().unwrap(),
544        )))
545    }
546
547    /// <https://html.spec.whatwg.org/multipage/#dom-a-rel>
548    fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
549        self.upcast::<Element>()
550            .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
551    }
552
553    /// <https://html.spec.whatwg.org/multipage/#dom-a-rellist>
554    fn RelList(&self, cx: &mut JSContext) -> DomRoot<DOMTokenList> {
555        self.rel_list.or_init(|| {
556            DOMTokenList::new(
557                cx,
558                self.upcast(),
559                &local_name!("rel"),
560                Some(vec![
561                    Atom::from("noopener"),
562                    Atom::from("noreferrer"),
563                    Atom::from("opener"),
564                ]),
565            )
566        })
567    }
568
569    /// <https://html.spec.whatwg.org/multipage/#the-form-element:supported-property-names>
570    fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
571        // Step 1
572        #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
573        enum SourcedNameSource {
574            Id,
575            Name,
576            Past(usize),
577        }
578
579        impl SourcedNameSource {
580            fn is_past(&self) -> bool {
581                matches!(self, SourcedNameSource::Past(..))
582            }
583        }
584
585        struct SourcedName {
586            name: Atom,
587            element: DomRoot<Element>,
588            source: SourcedNameSource,
589        }
590
591        let mut sourced_names_vec: Vec<SourcedName> = Vec::new();
592
593        // Step 2
594        for child in self.controls.borrow().iter() {
595            if child
596                .downcast::<HTMLElement>()
597                .is_some_and(|c| c.is_listed_element())
598            {
599                if let Some(id_atom) = child.get_id() {
600                    let entry = SourcedName {
601                        name: id_atom,
602                        element: DomRoot::from_ref(child),
603                        source: SourcedNameSource::Id,
604                    };
605                    sourced_names_vec.push(entry);
606                }
607                if let Some(name_atom) = child.get_name() {
608                    let entry = SourcedName {
609                        name: name_atom,
610                        element: DomRoot::from_ref(child),
611                        source: SourcedNameSource::Name,
612                    };
613                    sourced_names_vec.push(entry);
614                }
615            }
616        }
617
618        // Step 3
619        for child in self.controls.borrow().iter() {
620            if child.is::<HTMLImageElement>() {
621                if let Some(id_atom) = child.get_id() {
622                    let entry = SourcedName {
623                        name: id_atom,
624                        element: DomRoot::from_ref(child),
625                        source: SourcedNameSource::Id,
626                    };
627                    sourced_names_vec.push(entry);
628                }
629                if let Some(name_atom) = child.get_name() {
630                    let entry = SourcedName {
631                        name: name_atom,
632                        element: DomRoot::from_ref(child),
633                        source: SourcedNameSource::Name,
634                    };
635                    sourced_names_vec.push(entry);
636                }
637            }
638        }
639
640        // Step 4
641        let past_names_map = self.past_names_map.borrow();
642        for (key, val) in past_names_map.iter() {
643            let entry = SourcedName {
644                name: key.clone(),
645                element: DomRoot::from_ref(&*val.0),
646                source: SourcedNameSource::Past(self.current_name_generation.get() - val.1.0),
647            };
648            sourced_names_vec.push(entry);
649        }
650
651        // Step 5
652        // TODO need to sort as per spec.
653        // if a.CompareDocumentPosition(b) returns 0 that means a=b in which case
654        // the remaining part where sorting is to be done by putting entries whose source is id first,
655        // then entries whose source is name, and finally entries whose source is past,
656        // and sorting entries with the same element and source by their age, oldest first.
657
658        // if a.CompareDocumentPosition(b) has set NodeConstants::DOCUMENT_POSITION_FOLLOWING
659        // (this can be checked by bitwise operations) then b would follow a in tree order and
660        // Ordering::Less should be returned in the closure else Ordering::Greater
661
662        sourced_names_vec.sort_by(|a, b| {
663            if a.element
664                .upcast::<Node>()
665                .CompareDocumentPosition(no_gc, b.element.upcast::<Node>()) ==
666                0
667            {
668                if a.source.is_past() && b.source.is_past() {
669                    b.source.cmp(&a.source)
670                } else {
671                    a.source.cmp(&b.source)
672                }
673            } else if a
674                .element
675                .upcast::<Node>()
676                .CompareDocumentPosition(no_gc, b.element.upcast::<Node>()) &
677                NodeConstants::DOCUMENT_POSITION_FOLLOWING ==
678                NodeConstants::DOCUMENT_POSITION_FOLLOWING
679            {
680                std::cmp::Ordering::Less
681            } else {
682                std::cmp::Ordering::Greater
683            }
684        });
685
686        // Step 6
687        sourced_names_vec.retain(|sn| !sn.name.to_string().is_empty());
688
689        // Step 7-8
690        let mut names_vec: Vec<DOMString> = Vec::new();
691        for elem in sourced_names_vec.iter() {
692            if !names_vec.iter().any(|name| *name == *elem.name) {
693                names_vec.push(TracedDOMString::from(elem.name.clone()).root());
694            }
695        }
696
697        names_vec
698    }
699
700    /// <https://html.spec.whatwg.org/multipage/#dom-form-checkvalidity>
701    fn CheckValidity(&self, cx: &mut JSContext) -> bool {
702        self.static_validation(cx).is_ok()
703    }
704
705    /// <https://html.spec.whatwg.org/multipage/#dom-form-reportvalidity>
706    fn ReportValidity(&self, cx: &mut JSContext) -> bool {
707        self.interactive_validation(cx).is_ok()
708    }
709}
710
711#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
712pub(crate) enum SubmittedFrom {
713    FromForm,
714    NotFromForm,
715}
716
717#[derive(Clone, Copy, MallocSizeOf)]
718pub(crate) enum ResetFrom {
719    FromForm,
720    NotFromForm,
721}
722
723impl HTMLFormElement {
724    /// <https://html.spec.whatwg.org/multipage/#picking-an-encoding-for-the-form>
725    fn pick_encoding(&self) -> &'static Encoding {
726        // Step 2
727        if self
728            .upcast::<Element>()
729            .has_attribute(&local_name!("accept-charset"))
730        {
731            // Substep 1
732            let input = self
733                .upcast::<Element>()
734                .get_string_attribute(&local_name!("accept-charset"));
735
736            // Substep 2, 3, 4
737            let input = input.str();
738            let mut candidate_encodings =
739                split_html_space_chars(&input).filter_map(|c| Encoding::for_label(c.as_bytes()));
740
741            // Substep 5, 6
742            return candidate_encodings.next().unwrap_or(UTF_8);
743        }
744
745        // Step 1, 3
746        self.owner_document().encoding()
747    }
748
749    pub(crate) fn update_validity(&self, cx: &mut JSContext) {
750        let is_any_invalid = self
751            .controls
752            .borrow()
753            .iter()
754            .any(|control| control.is_invalid(cx, false));
755
756        self.upcast::<Element>()
757            .set_state(cx.no_gc(), ElementState::VALID, !is_any_invalid);
758        self.upcast::<Element>()
759            .set_state(cx.no_gc(), ElementState::INVALID, is_any_invalid);
760    }
761
762    /// [Form submission](https://html.spec.whatwg.org/multipage/#concept-form-submit)
763    pub(crate) fn submit(
764        &self,
765        cx: &mut JSContext,
766        submit_method_flag: SubmittedFrom,
767        submitter: FormSubmitterElement,
768    ) {
769        // Step 1
770        if self.upcast::<Element>().cannot_navigate() {
771            return;
772        }
773
774        // Step 2
775        if self.constructing_entry_list.get() {
776            return;
777        }
778        // Step 3. Let form document be form's node document.
779        let doc = self.owner_document();
780
781        // Step 4. If form document's active sandboxing flag set has its sandboxed forms browsing
782        // context flag set, then return.
783        if doc.has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_FORMS_BROWSING_CONTEXT_FLAG)
784        {
785            return;
786        }
787
788        let base = doc.base_url();
789        // TODO: Handle browsing contexts (Step 5)
790        // Step 6
791        if submit_method_flag == SubmittedFrom::NotFromForm {
792            // Step 6.1
793            if self.firing_submission_events.get() {
794                return;
795            }
796            // Step 6.2
797            self.firing_submission_events.set(true);
798            // Step 6.3
799            if !submitter.no_validate(self) && self.interactive_validation(cx).is_err() {
800                self.firing_submission_events.set(false);
801                return;
802            }
803            // Step 6.4
804            // spec calls this "submitterButton" but it doesn't have to be a button,
805            // just not be the form itself
806            let submitter_button = match submitter {
807                FormSubmitterElement::Form(f) => {
808                    if f == self {
809                        None
810                    } else {
811                        Some(f.upcast::<HTMLElement>())
812                    }
813                },
814                FormSubmitterElement::Input(i) => Some(i.upcast::<HTMLElement>()),
815                FormSubmitterElement::Button(b) => Some(b.upcast::<HTMLElement>()),
816            };
817
818            // Step 6.5
819            let event = SubmitEvent::new(
820                cx,
821                self.global().as_window(),
822                atom!("submit"),
823                true,
824                true,
825                submitter_button,
826            );
827            let event = event.upcast::<Event>();
828            event.fire(cx, self.upcast::<EventTarget>());
829
830            // Step 6.6
831            self.firing_submission_events.set(false);
832            // Step 6.7
833            if event.DefaultPrevented() {
834                return;
835            }
836            // Step 6.8
837            if self.upcast::<Element>().cannot_navigate() {
838                return;
839            }
840        }
841
842        // Step 7
843        let encoding = self.pick_encoding();
844
845        // Step 8
846        let mut form_data = match self.get_form_dataset(cx, Some(submitter), Some(encoding)) {
847            Some(form_data) => form_data,
848            None => return,
849        };
850
851        // Step 9. If form cannot navigate, then return.
852        if self.upcast::<Element>().cannot_navigate() {
853            return;
854        }
855
856        // Step 10. Let method be the submitter element's method.
857        let method = submitter.method();
858        // Step 11. If method is dialog, then:
859        // TODO
860
861        // Step 12. Let action be the submitter element's action.
862        let mut action = submitter.action();
863
864        // Step 13. If action is the empty string, let action be the URL of the form document.
865        if action.is_empty() {
866            action = DOMString::from(base.as_str());
867        }
868        // Step 14. Let parsed action be the result of encoding-parsing a URL given action, relative to submitter's node document.
869        let action_components = match doc.encoding_parse_a_url(&action.str()) {
870            Ok(url) => url,
871            // Step 15. If parsed action is failure, then return.
872            Err(_) => return,
873        };
874        // Step 16. Let scheme be the scheme of parsed action.
875        let scheme = action_components.scheme().to_owned();
876        // Step 17. Let enctype be the submitter element's enctype.
877        let enctype = submitter.enctype();
878
879        // Step 19. If the submitter element is a submit button and it has a formtarget attribute,
880        // then set formTarget to the formtarget attribute value.
881        let form_target_attribute = submitter.target();
882        let form_target = if submitter.is_submit_button() &&
883            valid_navigable_target_name_or_keyword(&form_target_attribute)
884        {
885            Some(form_target_attribute)
886        } else {
887            // Step 18. Let formTarget be null.
888            None
889        };
890        // Step 20. Let target be the result of getting an element's target given
891        // submitter's form owner and formTarget.
892        let form_owner = submitter.form_owner();
893        let form = form_owner.as_deref().unwrap_or(self);
894        let target = get_element_target(form.upcast::<Element>(), form_target);
895
896        // Step 21. Let noopener be the result of getting an element's noopener with form,
897        // parsed action, and target.
898        let noopener = self.relations.get().get_element_noopener(target.as_ref());
899
900        // Step 22. Let targetNavigable be the first return value of applying the rules
901        // for choosing a navigable given target, form's node navigable, and noopener.
902        let Some(chosen) = doc.browsing_context().and_then(|source| {
903            source
904                .choose_a_navigable(cx, &target.unwrap_or_default(), noopener)
905                .0
906        }) else {
907            // Step 23. If targetNavigable is null, then return.
908            return;
909        };
910
911        let Some(target_document) = chosen.document() else {
912            return;
913        };
914
915        // Step 24. Let historyHandling be "auto".
916        // Step 25. If form document equals targetNavigable's active document, and form
917        // document has not yet completely loaded, then set historyHandling to "replace".
918        let history_handling = if doc == target_document && !doc.completely_loaded() {
919            NavigationHistoryBehavior::Replace
920        } else {
921            NavigationHistoryBehavior::Auto
922        };
923
924        let target_window = target_document.window();
925        let mut load_data = LoadData::new(
926            LoadOrigin::Script(doc.origin().snapshot()),
927            action_components,
928            target_document.about_base_url(),
929            Some(doc.pipeline_id()),
930            target_window.as_global_scope().get_referrer(),
931            target_document.get_referrer_policy(),
932            Some(target_window.as_global_scope().is_secure_context()),
933            Some(target_document.insecure_requests_policy()),
934            target_window
935                .as_global_scope()
936                .upgrade_insecure_navigations_set()
937                .clone(),
938            target_document.has_trustworthy_ancestor_origin(),
939            target_document.creation_sandboxing_flag_set_considering_parent_iframe(),
940        );
941
942        // Step 26. Select the appropriate row in the table below based on scheme as given by the first cell of each row.
943        // Then, select the appropriate cell on that row based on method as given in the first cell of each column.
944        // Then, jump to the steps named in that cell and defined below the table.
945        match (&*scheme, method) {
946            (_, FormMethod::Dialog) => {
947                // TODO: Submit dialog
948                // https://html.spec.whatwg.org/multipage/#submit-dialog
949            },
950            // https://html.spec.whatwg.org/multipage/#submit-mutate-action
951            ("http", FormMethod::Get) | ("https", FormMethod::Get) | ("data", FormMethod::Get) => {
952                load_data
953                    .headers
954                    .typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED));
955                self.mutate_action_url(&mut form_data, load_data, target_window, history_handling);
956            },
957            // https://html.spec.whatwg.org/multipage/#submit-body
958            ("http", FormMethod::Post) | ("https", FormMethod::Post) => {
959                load_data.method = Method::POST;
960                self.submit_entity_body(
961                    cx,
962                    &mut form_data,
963                    load_data,
964                    enctype,
965                    encoding,
966                    target_window,
967                    history_handling,
968                );
969            },
970            // https://html.spec.whatwg.org/multipage/#submit-get-action
971            ("file", _) |
972            ("about", _) |
973            ("data", FormMethod::Post) |
974            ("ftp", _) |
975            ("javascript", _) => {
976                self.plan_to_navigate(load_data, target_window, history_handling);
977            },
978            ("mailto", FormMethod::Post) => {
979                // TODO: Mail as body
980                // https://html.spec.whatwg.org/multipage/#submit-mailto-body
981            },
982            ("mailto", FormMethod::Get) => {
983                // TODO: Mail with headers
984                // https://html.spec.whatwg.org/multipage/#submit-mailto-headers
985            },
986            _ => (),
987        }
988    }
989
990    /// <https://html.spec.whatwg.org/multipage/#submit-mutate-action>
991    fn mutate_action_url(
992        &self,
993        form_data: &mut [FormDatum],
994        mut load_data: LoadData,
995        target: &Window,
996        history_handling: NavigationHistoryBehavior,
997    ) {
998        self.set_url_query_pairs(
999            &mut load_data.url,
1000            form_data.iter().map(|field| {
1001                (
1002                    field.name.normalize_crlf(),
1003                    field.replace_value().normalize_crlf(),
1004                )
1005            }),
1006        );
1007
1008        self.plan_to_navigate(load_data, target, history_handling);
1009    }
1010
1011    /// <https://html.spec.whatwg.org/multipage/#submit-body>
1012    #[allow(clippy::too_many_arguments)]
1013    fn submit_entity_body(
1014        &self,
1015        cx: &mut JSContext,
1016        form_data: &mut [FormDatum],
1017        mut load_data: LoadData,
1018        enctype: FormEncType,
1019        encoding: &'static Encoding,
1020        target: &Window,
1021        history_handling: NavigationHistoryBehavior,
1022    ) {
1023        let boundary = generate_boundary();
1024        let bytes = match enctype {
1025            FormEncType::UrlEncoded => {
1026                load_data
1027                    .headers
1028                    .typed_insert(ContentType::from(mime::APPLICATION_WWW_FORM_URLENCODED));
1029
1030                let mut url = load_data.url.clone();
1031                self.set_url_query_pairs(
1032                    &mut url,
1033                    // Let pairs be the result of
1034                    // converting to a list of name-value pairs with entry list.
1035                    // <https://html.spec.whatwg.org/multipage/#convert-to-a-list-of-name-value-pairs>
1036                    form_data.iter().map(|field| {
1037                        (
1038                            field.name.normalize_crlf(),
1039                            field.replace_value().normalize_crlf(),
1040                        )
1041                    }),
1042                );
1043
1044                url.query().unwrap_or("").to_string().into_bytes()
1045            },
1046            FormEncType::MultipartFormData => {
1047                let mime: Mime = format!("multipart/form-data; boundary={}", boundary)
1048                    .parse()
1049                    .unwrap();
1050                load_data.headers.typed_insert(ContentType::from(mime));
1051                encode_multipart_form_data(form_data, boundary, encoding)
1052            },
1053            FormEncType::TextPlain => {
1054                load_data
1055                    .headers
1056                    .typed_insert(ContentType::from(mime::TEXT_PLAIN));
1057                // Step 1: Let pairs be the result of converting to a list
1058                // of name-value pairs with entry list.
1059                // <https://html.spec.whatwg.org/multipage/#convert-to-a-list-of-name-value-pairs>
1060                let pairs = form_data.iter().map(|field| {
1061                    (
1062                        field.name.normalize_crlf(),
1063                        field.replace_value().normalize_crlf(),
1064                    )
1065                });
1066                // Step 2: Let body be the result of running the text/plain
1067                // encoding algorithm with pairs.
1068                let body = encode_plaintext(pairs);
1069                // Step 3: Set body to the result of encoding body using encoding.
1070                encode_with_html_fallback(&body, encoding).into_owned()
1071            },
1072        };
1073
1074        let global = self.global();
1075
1076        let request_body = bytes
1077            .extract(cx, &global, false)
1078            .expect("Couldn't extract body.")
1079            .into_net_request_body(cx)
1080            .0;
1081        load_data.data = Some(request_body);
1082
1083        self.plan_to_navigate(load_data, target, history_handling);
1084    }
1085
1086    fn set_url_query_pairs<T>(
1087        &self,
1088        url: &mut servo_url::ServoUrl,
1089        pairs: impl Iterator<Item = (T, String)>,
1090    ) where
1091        T: AsRef<str>,
1092    {
1093        let encoding = self.pick_encoding();
1094        url.as_mut_url()
1095            .query_pairs_mut()
1096            .encoding_override(Some(&|s| encode_with_html_fallback(s, encoding)))
1097            .clear()
1098            .extend_pairs(pairs);
1099    }
1100
1101    /// [Planned navigation](https://html.spec.whatwg.org/multipage/#planned-navigation)
1102    fn plan_to_navigate(
1103        &self,
1104        mut load_data: LoadData,
1105        target: &Window,
1106        history_handling: NavigationHistoryBehavior,
1107    ) {
1108        // 1. Let referrerPolicy be the empty string.
1109        // 2. If the form element's link types include the noreferrer keyword,
1110        //    then set referrerPolicy to "no-referrer".
1111        // Note: both steps done below.
1112        let document = self.owner_document();
1113        let element = self.upcast::<Element>();
1114        let referrer = match element.get_attribute_string_value(&local_name!("rel")) {
1115            Some(link_types) if link_types.contains("noreferrer") => Referrer::NoReferrer,
1116            _ => document.window().as_global_scope().get_referrer(),
1117        };
1118
1119        // 3. If the form has a non-null planned navigation, remove it from its task queue.
1120        // Note: done by incrementing `planned_navigation`.
1121        self.planned_navigation
1122            .set(self.planned_navigation.get().wrapping_add(1));
1123        let planned_navigation = self.planned_navigation.get();
1124
1125        // Note: we start to use the beginnings of an `ongoing_navigation` concept, to
1126        // cancel planned navigations as part of
1127        // <https://html.spec.whatwg.org/multipage/#nav-stop>
1128        //
1129        // The concept of ongoing navigation must be separated from the form's
1130        // planned navigation concept, because each planned navigation cancels the previous one
1131        // for a given form, whereas an ongoing navigation is a per navigable (read: window for now)
1132        // concept.
1133        //
1134        // Setting the ongoing navigation now means the navigation could be cancelled
1135        // even if the below task has not run yet. This is not how the spec is written: it
1136        // seems instead to imply that a `window.stop` should only cancel the navigation
1137        // that has already started (here the task is queued, but the navigation starts only
1138        // in the task). See <https://github.com/whatwg/html/issues/11562>.
1139        let ongoing_navigation = target.set_ongoing_navigation();
1140
1141        let referrer_policy = document.get_referrer_policy();
1142        load_data.referrer = referrer;
1143        load_data.referrer_policy = referrer_policy;
1144
1145        // Note the pending form navigation if this is an iframe;
1146        // necessary for deciding whether to run the iframe load event steps.
1147        if let Some(window_proxy) = target.undiscarded_window_proxy() &&
1148            let Some(frame) = window_proxy
1149                .frame_element()
1150                .and_then(|e| e.downcast::<HTMLIFrameElement>())
1151        {
1152            frame.note_pending_navigation()
1153        }
1154
1155        // 4. Queue an element task on the DOM manipulation task source
1156        // given the form element and the following steps:
1157        let form = Trusted::new(self);
1158        let window = Trusted::new(target);
1159        let task = task!(navigate_to_form_planned_navigation: move |cx| {
1160            // 4.1 Set the form's planned navigation to null.
1161            // Note: we implement the equivalent by incrementing the counter above,
1162            // and checking it here.
1163            if planned_navigation != form.root().planned_navigation.get() {
1164                return;
1165            }
1166
1167            // Note: we also check if the navigation has been cancelled,
1168            // see https://github.com/whatwg/html/issues/11562
1169            if ongoing_navigation != window.root().ongoing_navigation() {
1170                return;
1171            }
1172
1173            // 4.2 Navigate targetNavigable to url
1174            navigate(
1175                cx,
1176                &window.root(),
1177                history_handling,
1178                false,
1179                load_data,
1180            )
1181        });
1182
1183        // 5. Set the form's planned navigation to the just-queued task.
1184        // Done above as part of incrementing the planned navigation counter.
1185
1186        // Note: task queued here.
1187        target
1188            .global()
1189            .task_manager()
1190            .dom_manipulation_task_source()
1191            .queue(task)
1192    }
1193
1194    /// Interactively validate the constraints of form elements
1195    /// <https://html.spec.whatwg.org/multipage/#interactively-validate-the-constraints>
1196    fn interactive_validation(&self, cx: &mut JSContext) -> Result<(), ()> {
1197        // Step 1 - 2: Statically validate the constraints of form,
1198        // and let `unhandled invalid controls` be the list of elements
1199        // returned if the result was negative.
1200        // If the result was positive, then return that result.
1201        let unhandled_invalid_controls = match self.static_validation(cx) {
1202            Ok(()) => return Ok(()),
1203            Err(err) => err,
1204        };
1205
1206        // Step 3: Report the problems with the constraints of at least one of the elements
1207        // given in unhandled invalid controls to the user.
1208        let mut first = true;
1209
1210        for elem in unhandled_invalid_controls {
1211            if let Some(validatable) = elem.as_maybe_validatable() {
1212                error!("Validation error: {}", validatable.validation_message(cx));
1213            }
1214            if first && let Some(html_elem) = elem.downcast::<HTMLElement>() {
1215                // Step 3.1: User agents may focus one of those elements in the process,
1216                // by running the focusing steps for that element,
1217                // and may change the scrolling position of the document, or perform
1218                // some other action that brings the element to the user's attention.
1219
1220                // Here we run focusing steps and scroll element into view.
1221                html_elem.Focus(cx, &FocusOptions::default());
1222                first = false;
1223            }
1224        }
1225
1226        // If it's form-associated and has a validation anchor, point the
1227        //  user there instead of the element itself.
1228        // Step 4
1229        Err(())
1230    }
1231
1232    /// Statitically validate the constraints of form elements
1233    /// <https://html.spec.whatwg.org/multipage/#statically-validate-the-constraints>
1234    fn static_validation(&self, cx: &mut JSContext) -> Result<(), Vec<DomRoot<Element>>> {
1235        // Step 1-3
1236        let invalid_controls = self
1237            .controls
1238            .borrow()
1239            .iter()
1240            .filter_map(|field| {
1241                if let Some(element) = field.downcast::<Element>() {
1242                    if element.is_invalid(cx, true) {
1243                        Some(DomRoot::from_ref(element))
1244                    } else {
1245                        None
1246                    }
1247                } else {
1248                    None
1249                }
1250            })
1251            .collect::<Vec<DomRoot<Element>>>();
1252        // Step 4: If invalid controls is empty, then return a positive result.
1253        if invalid_controls.is_empty() {
1254            return Ok(());
1255        }
1256        // Step 5-6
1257        let unhandled_invalid_controls = invalid_controls
1258            .into_iter()
1259            .filter_map(|field| {
1260                // Step 6.1: Let notCanceled be the result of firing an event named invalid at
1261                // field, with the cancelable attribute initialized to true.
1262                let not_canceled = field
1263                    .upcast::<EventTarget>()
1264                    .fire_cancelable_event(cx, atom!("invalid"));
1265                // Step 6.2: If notCanceled is true, then add field to unhandled invalid controls.
1266                if not_canceled {
1267                    return Some(field);
1268                }
1269                None
1270            })
1271            .collect::<Vec<DomRoot<Element>>>();
1272        // Step 7
1273        Err(unhandled_invalid_controls)
1274    }
1275
1276    /// <https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set>
1277    /// terminology note:  "form data set" = "entry list"
1278    /// Steps range from 3 to 5
1279    /// 5.x substeps are mostly handled inside element-specific methods
1280    fn get_unclean_dataset(
1281        &self,
1282        cx: &mut JSContext,
1283        submitter: Option<FormSubmitterElement>,
1284        encoding: Option<&'static Encoding>,
1285    ) -> Vec<FormDatum> {
1286        let mut data_set = Vec::new();
1287        for child in self.controls.borrow().iter() {
1288            // Step 5.1: The field element is disabled.
1289            if child.disabled_state() {
1290                continue;
1291            }
1292            let child = child.upcast::<Node>();
1293
1294            // Step 5.1: The field element has a datalist element ancestor.
1295            if child.ancestors().any(|a| a.is::<HTMLDataListElement>()) {
1296                continue;
1297            }
1298            if let NodeTypeId::Element(ElementTypeId::HTMLElement(element)) = child.type_id() {
1299                match element {
1300                    HTMLElementTypeId::HTMLInputElement => {
1301                        let input = child.downcast::<HTMLInputElement>().unwrap();
1302                        let (ref mut form_datums, should_continue) =
1303                            input.form_datums(submitter, encoding);
1304                        data_set.append(form_datums);
1305                        if should_continue {
1306                            continue;
1307                        }
1308                    },
1309                    HTMLElementTypeId::HTMLButtonElement => {
1310                        let button = child.downcast::<HTMLButtonElement>().unwrap();
1311                        if let Some(datum) = button.form_datum(submitter) {
1312                            data_set.push(datum);
1313                        }
1314                    },
1315                    HTMLElementTypeId::HTMLObjectElement => {
1316                        // Unimplemented
1317                    },
1318                    HTMLElementTypeId::HTMLSelectElement => {
1319                        let select = child.downcast::<HTMLSelectElement>().unwrap();
1320                        select.push_form_data(cx.no_gc(), &mut data_set);
1321                    },
1322                    HTMLElementTypeId::HTMLTextAreaElement => {
1323                        let textarea = child.downcast::<HTMLTextAreaElement>().unwrap();
1324                        let name = textarea.Name();
1325                        if !name.is_empty() {
1326                            data_set.push(FormDatum {
1327                                ty: textarea.Type(),
1328                                name,
1329                                value: FormDatumValue::String(textarea.Value()),
1330                            });
1331                        }
1332                    },
1333                    HTMLElementTypeId::HTMLElement => {
1334                        let custom = child.downcast::<HTMLElement>().unwrap();
1335                        if custom.is_form_associated_custom_element() {
1336                            // https://html.spec.whatwg.org/multipage/#face-entry-construction
1337                            let internals = custom.ensure_element_internals(cx);
1338                            internals.perform_entry_construction(&mut data_set);
1339                            // Otherwise no form value has been set so there is nothing to do.
1340                        }
1341                    },
1342                    _ => (),
1343                }
1344            }
1345
1346            // Step: 5.11.1 Let dirname be the value of the element's dirname attribute.
1347            let child_element = child.downcast::<Element>().unwrap();
1348            let dirname = child_element.get_string_attribute(&local_name!("dirname"));
1349
1350            // Step: 5.11. If the element has a dirname attribute, that attribute's value is not the empty
1351            // string, and the element is an auto-directionality form-associated element:
1352            // From: <https://html.spec.whatwg.org/multipage/#auto-directionality-form-associated-elements>
1353            // Input elements whose type attribute is in the Hidden, Text, Search, Telephone, URL, Email,
1354            // Password, Submit Button, Reset Button, or Button state, and textarea elements.
1355            let is_input_auto_directionality_form_associated_element = child_element
1356                .downcast::<HTMLInputElement>()
1357                .is_some_and(|input| input.is_auto_directionality_form_associated_element());
1358            let is_textarea_element = child_element.is::<HTMLTextAreaElement>();
1359            if !dirname.is_empty() &&
1360                (is_input_auto_directionality_form_associated_element || is_textarea_element)
1361            {
1362                // Step: 5.11.2 Let dir be the string "ltr" if the directionality of the element is 'ltr',
1363                // and "rtl" otherwise (i.e., when the directionality of the element is 'rtl').
1364                let dir = DOMString::from(child_element.directionality());
1365
1366                // Step: 5.11.3 Create an entry with dirname and dir, and append it to entry list.
1367                data_set.push(FormDatum {
1368                    ty: DOMString::from_static("string"),
1369                    name: dirname,
1370                    value: FormDatumValue::String(dir),
1371                });
1372            }
1373        }
1374        data_set
1375    }
1376
1377    /// <https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set>
1378    pub(crate) fn get_form_dataset(
1379        &self,
1380        cx: &mut JSContext,
1381        submitter: Option<FormSubmitterElement>,
1382        encoding: Option<&'static Encoding>,
1383    ) -> Option<Vec<FormDatum>> {
1384        // Step 1
1385        if self.constructing_entry_list.get() {
1386            return None;
1387        }
1388
1389        // Step 2
1390        self.constructing_entry_list.set(true);
1391
1392        // Step 3-6
1393        let ret = self.get_unclean_dataset(cx, submitter, encoding);
1394
1395        let window = self.owner_window();
1396
1397        // Step 6
1398        let form_data = FormData::new(cx, Some(ret), &window.global());
1399
1400        // Step 7
1401        let event = FormDataEvent::new(
1402            cx,
1403            &window,
1404            atom!("formdata"),
1405            EventBubbles::Bubbles,
1406            EventCancelable::NotCancelable,
1407            &form_data,
1408        );
1409
1410        event
1411            .upcast::<Event>()
1412            .fire(cx, self.upcast::<EventTarget>());
1413
1414        // Step 8
1415        self.constructing_entry_list.set(false);
1416
1417        // Step 9
1418        Some(form_data.datums())
1419    }
1420
1421    /// <https://html.spec.whatwg.org/multipage/#dom-form-reset>
1422    pub(crate) fn reset(&self, cx: &mut JSContext, _reset_method_flag: ResetFrom) {
1423        // https://html.spec.whatwg.org/multipage/#locked-for-reset
1424        if self.marked_for_reset.get() {
1425            return;
1426        } else {
1427            self.marked_for_reset.set(true);
1428        }
1429
1430        // https://html.spec.whatwg.org/multipage/#concept-form-reset
1431        // Let reset be the result of firing an event named reset at form,
1432        // with the bubbles and cancelable attributes initialized to true.
1433        let reset = self
1434            .upcast::<EventTarget>()
1435            .fire_bubbling_cancelable_event(cx, atom!("reset"));
1436        if !reset {
1437            return;
1438        }
1439
1440        let controls: Vec<_> = self
1441            .controls
1442            .borrow()
1443            .iter()
1444            .map(|c| c.as_rooted())
1445            .collect();
1446
1447        for child in controls {
1448            child.reset(cx);
1449        }
1450        self.marked_for_reset.set(false);
1451    }
1452
1453    fn add_control<T: ?Sized + FormControl>(&self, cx: &mut JSContext, control: &T) {
1454        {
1455            let root = self.upcast::<Element>().root_element();
1456            let root = root.upcast::<Node>();
1457            let mut controls = self.controls.safe_borrow_mut(cx.no_gc());
1458
1459            // https://html.spec.whatwg.org/multipage/#create-an-element-for-the-token
1460            // associates form control elements with a form before they are bound to the tree.
1461            //
1462            // In that case we can't use insert_pre_order, because the position of a element not in
1463            // the tree can't be compared to anything in the DOM tree.
1464            let control_element = control.to_element();
1465            if control_element.upcast::<Node>().is_in_a_document_tree() {
1466                controls.insert_pre_order(control_element, root);
1467            } else {
1468                controls.push(Dom::from_ref(control_element));
1469            }
1470        }
1471        self.update_validity(cx);
1472    }
1473
1474    fn remove_control<T: ?Sized + FormControl>(&self, cx: &mut JSContext, control: &T) {
1475        {
1476            let control = control.to_element();
1477            let mut controls = self.controls.safe_borrow_mut(cx.no_gc());
1478            controls
1479                .iter()
1480                .position(|c| &**c == control)
1481                .map(|idx| controls.remove(idx));
1482
1483            // https://html.spec.whatwg.org/multipage#forms.html#the-form-element:past-names-map-5
1484            // "If an element listed in a form element's past names map
1485            // changes form owner, then its entries must be removed
1486            // from that map."
1487            let mut past_names_map = self.past_names_map.safe_borrow_mut(cx.no_gc());
1488            past_names_map.0.retain(|_k, v| v.0 != control);
1489        }
1490        self.update_validity(cx);
1491    }
1492}
1493
1494impl Element {
1495    pub(crate) fn is_resettable(&self) -> bool {
1496        let NodeTypeId::Element(ElementTypeId::HTMLElement(element_type)) =
1497            self.upcast::<Node>().type_id()
1498        else {
1499            return false;
1500        };
1501        matches!(
1502            element_type,
1503            HTMLElementTypeId::HTMLInputElement |
1504                HTMLElementTypeId::HTMLSelectElement |
1505                HTMLElementTypeId::HTMLTextAreaElement |
1506                HTMLElementTypeId::HTMLOutputElement |
1507                HTMLElementTypeId::HTMLElement
1508        )
1509    }
1510
1511    pub(crate) fn reset(&self, cx: &mut JSContext) {
1512        if !self.is_resettable() {
1513            return;
1514        }
1515
1516        if let Some(input_element) = self.downcast::<HTMLInputElement>() {
1517            input_element.reset(cx);
1518        } else if let Some(select_element) = self.downcast::<HTMLSelectElement>() {
1519            select_element.reset(cx);
1520        } else if let Some(textarea_element) = self.downcast::<HTMLTextAreaElement>() {
1521            textarea_element.reset(cx);
1522        } else if let Some(output_element) = self.downcast::<HTMLOutputElement>() {
1523            output_element.reset(cx);
1524        } else if let Some(html_element) = self.downcast::<HTMLElement>() &&
1525            html_element.is_form_associated_custom_element()
1526        {
1527            ScriptThread::enqueue_callback_reaction(
1528                cx,
1529                html_element.upcast::<Element>(),
1530                CallbackReaction::FormReset,
1531                None,
1532            )
1533        }
1534    }
1535}
1536
1537#[derive(JSTraceable, MallocSizeOf)]
1538#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
1539pub(crate) enum FormDatumValueUnrooted {
1540    File(Dom<File>),
1541    String(DOMString),
1542}
1543
1544#[derive(JSTraceable, MallocSizeOf)]
1545#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
1546pub(crate) struct FormDatumUnrooted {
1547    pub(crate) ty: DOMString,
1548    pub(crate) name: DOMString,
1549    pub(crate) value: FormDatumValueUnrooted,
1550}
1551
1552impl FormDatumUnrooted {
1553    pub(crate) fn root(&self) -> FormDatum {
1554        FormDatum {
1555            ty: self.ty.clone(),
1556            name: self.name.clone(),
1557            value: match &self.value {
1558                FormDatumValueUnrooted::File(file) => FormDatumValue::File(file.as_rooted()),
1559                FormDatumValueUnrooted::String(s) => FormDatumValue::String(s.clone()),
1560            },
1561        }
1562    }
1563}
1564
1565impl From<FormDatum> for FormDatumUnrooted {
1566    fn from(value: FormDatum) -> Self {
1567        Self {
1568            ty: value.ty,
1569            name: value.name,
1570            value: match value.value {
1571                FormDatumValue::File(file) => FormDatumValueUnrooted::File(file.as_traced()),
1572                FormDatumValue::String(s) => FormDatumValueUnrooted::String(s),
1573            },
1574        }
1575    }
1576}
1577
1578#[derive(JSTraceable, MallocSizeOf)]
1579pub(crate) enum FormDatumValue {
1580    File(DomRoot<File>),
1581    String(DOMString),
1582}
1583
1584#[derive(JSTraceable, MallocSizeOf)]
1585pub(crate) struct FormDatum {
1586    pub(crate) ty: DOMString,
1587    pub(crate) name: DOMString,
1588    pub(crate) value: FormDatumValue,
1589}
1590
1591impl FormDatum {
1592    pub(crate) fn replace_value(&self) -> DOMString {
1593        match self.value {
1594            FormDatumValue::File(ref f) => f.name().clone().root(),
1595            FormDatumValue::String(ref s) => s.clone(),
1596        }
1597    }
1598}
1599
1600#[derive(Clone, Copy, MallocSizeOf)]
1601pub(crate) enum FormEncType {
1602    TextPlain,
1603    UrlEncoded,
1604    MultipartFormData,
1605}
1606
1607#[derive(Clone, Copy, MallocSizeOf)]
1608pub(crate) enum FormMethod {
1609    Get,
1610    Post,
1611    Dialog,
1612}
1613
1614/// <https://html.spec.whatwg.org/multipage/#form-associated-element>
1615#[derive(Clone, Copy, MallocSizeOf)]
1616pub(crate) enum FormSubmitterElement<'a> {
1617    Form(&'a HTMLFormElement),
1618    Input(&'a HTMLInputElement),
1619    Button(&'a HTMLButtonElement),
1620    // TODO: implement other types of form associated elements
1621    // (including custom elements) that can be passed as submitter.
1622}
1623
1624impl FormSubmitterElement<'_> {
1625    /// <https://html.spec.whatwg.org/multipage/#concept-fs-action>
1626    fn action(&self) -> DOMString {
1627        match *self {
1628            FormSubmitterElement::Form(form) => form.Action(),
1629            FormSubmitterElement::Input(input_element) => input_element
1630                .to_element()
1631                .get_nullable_string_attribute(&local_name!("formaction"))
1632                .unwrap_or_else(|| {
1633                    input_element
1634                        .form_owner()
1635                        .map(|form| form.Action())
1636                        .unwrap_or_default()
1637                }),
1638            FormSubmitterElement::Button(button_element) => button_element
1639                .to_element()
1640                .get_nullable_string_attribute(&local_name!("formaction"))
1641                .unwrap_or_else(|| {
1642                    button_element
1643                        .form_owner()
1644                        .map(|form| form.Action())
1645                        .unwrap_or_default()
1646                }),
1647        }
1648    }
1649
1650    fn enctype(&self) -> FormEncType {
1651        let attr = match *self {
1652            FormSubmitterElement::Form(form) => form.Enctype(),
1653            FormSubmitterElement::Input(input_element) => input_element.get_form_attribute(
1654                &local_name!("formenctype"),
1655                |i| i.FormEnctype(),
1656                |f| f.Enctype(),
1657            ),
1658            FormSubmitterElement::Button(button_element) => button_element.get_form_attribute(
1659                &local_name!("formenctype"),
1660                |i| i.FormEnctype(),
1661                |f| f.Enctype(),
1662            ),
1663        };
1664        // https://html.spec.whatwg.org/multipage/#attr-fs-enctype
1665        // urlencoded is the default
1666        match_domstring_ascii!(attr,
1667            "multipart/form-data" => FormEncType::MultipartFormData,
1668            "text/plain" => FormEncType::TextPlain,
1669            _ => FormEncType::UrlEncoded,
1670        )
1671    }
1672
1673    fn method(&self) -> FormMethod {
1674        let attr = match *self {
1675            FormSubmitterElement::Form(form) => form.Method(),
1676            FormSubmitterElement::Input(input_element) => input_element.get_form_attribute(
1677                &local_name!("formmethod"),
1678                |i| i.FormMethod(),
1679                |f| f.Method(),
1680            ),
1681            FormSubmitterElement::Button(button_element) => button_element.get_form_attribute(
1682                &local_name!("formmethod"),
1683                |i| i.FormMethod(),
1684                |f| f.Method(),
1685            ),
1686        };
1687        match_domstring_ascii!(attr,
1688            "dialog" => FormMethod::Dialog,
1689            "post" => FormMethod::Post,
1690            _ => FormMethod::Get,
1691        )
1692    }
1693
1694    fn target(&self) -> DOMString {
1695        match *self {
1696            FormSubmitterElement::Form(form) => form.Target(),
1697            FormSubmitterElement::Input(input_element) => input_element.get_form_attribute(
1698                &local_name!("formtarget"),
1699                |i| i.FormTarget(),
1700                |f| f.Target(),
1701            ),
1702            FormSubmitterElement::Button(button_element) => button_element.get_form_attribute(
1703                &local_name!("formtarget"),
1704                |i| i.FormTarget(),
1705                |f| f.Target(),
1706            ),
1707        }
1708    }
1709
1710    fn no_validate(&self, _form_owner: &HTMLFormElement) -> bool {
1711        match *self {
1712            FormSubmitterElement::Form(form) => form.NoValidate(),
1713            FormSubmitterElement::Input(input_element) => input_element.get_form_boolean_attribute(
1714                &local_name!("formnovalidate"),
1715                |i| i.FormNoValidate(),
1716                |f| f.NoValidate(),
1717            ),
1718            FormSubmitterElement::Button(button_element) => button_element
1719                .get_form_boolean_attribute(
1720                    &local_name!("formnovalidate"),
1721                    |i| i.FormNoValidate(),
1722                    |f| f.NoValidate(),
1723                ),
1724        }
1725    }
1726
1727    /// <https://html.spec.whatwg.org/multipage/#concept-submit-button>
1728    pub(crate) fn is_submit_button(&self) -> bool {
1729        match *self {
1730            // https://html.spec.whatwg.org/multipage/#image-button-state-(type=image)
1731            // https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit)
1732            FormSubmitterElement::Input(input_element) => input_element.is_submit_button(),
1733            // https://html.spec.whatwg.org/multipage/#attr-button-type-submit-state
1734            FormSubmitterElement::Button(button_element) => button_element.is_submit_button(),
1735            _ => false,
1736        }
1737    }
1738
1739    /// <https://html.spec.whatwg.org/multipage/#form-owner>
1740    pub(crate) fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
1741        match *self {
1742            FormSubmitterElement::Button(button_el) => button_el.form_owner(),
1743            FormSubmitterElement::Input(input_el) => input_el.form_owner(),
1744            _ => None,
1745        }
1746    }
1747}
1748
1749pub(crate) trait FormControl: DomObject<ReflectorType = ()> + NodeTraits {
1750    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>>;
1751    fn set_form_owner(&self, cx: &mut JSContext, form: Option<&HTMLFormElement>);
1752    fn to_html_element(&self) -> &HTMLElement;
1753
1754    fn to_element(&self) -> &Element {
1755        self.to_html_element().upcast::<Element>()
1756    }
1757
1758    fn is_listed(&self) -> bool {
1759        self.to_html_element().is_listed_element()
1760    }
1761
1762    // https://html.spec.whatwg.org/multipage/#create-an-element-for-the-token
1763    // Part of step 12.
1764    // '..suppress the running of the reset the form owner algorithm
1765    // when the parser subsequently attempts to insert the element..'
1766    fn set_form_owner_from_parser(&self, cx: &mut JSContext, form: &HTMLFormElement) {
1767        let elem = self.to_element();
1768        let node = elem.upcast::<Node>();
1769        node.set_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER, true);
1770        form.add_control(cx, self);
1771        self.set_form_owner(cx, Some(form));
1772        form.invalidate_default_button(cx.no_gc());
1773    }
1774
1775    /// <https://html.spec.whatwg.org/multipage/#reset-the-form-owner>
1776    fn reset_form_owner(&self, cx: &mut JSContext) {
1777        let elem = self.to_element();
1778        let node = elem.upcast::<Node>();
1779        let old_owner = self.form_owner();
1780        let has_form_id = elem.has_attribute(&local_name!("form"));
1781        let nearest_form_ancestor = node
1782            .ancestors()
1783            .find_map(DomRoot::downcast::<HTMLFormElement>);
1784
1785        // Step 1
1786        if old_owner.is_some() &&
1787            !(self.is_listed() && has_form_id) &&
1788            nearest_form_ancestor == old_owner
1789        {
1790            return;
1791        }
1792
1793        // Step 4. If element is listed, has a form content attribute, and is connected, then:
1794        let new_owner = if self.is_listed() && has_form_id && elem.is_connected() {
1795            // Step 4.1 If the first element in element's tree, in tree order, to have an ID that is identical
1796            // to element's form content attribute's value, is a form element, then associate the element
1797            // with that form element.
1798            let form_id = elem.get_string_attribute(&local_name!("form"));
1799            let first_relevant_element = if let Some(shadow_root) = self.containing_shadow_root() {
1800                shadow_root
1801                    .upcast::<DocumentFragment>()
1802                    .GetElementById(cx, form_id)
1803            } else {
1804                node.owner_document().GetElementById(cx, form_id)
1805            };
1806
1807            first_relevant_element.and_then(DomRoot::downcast::<HTMLFormElement>)
1808        } else {
1809            // Step 4
1810            nearest_form_ancestor
1811        };
1812
1813        if old_owner != new_owner {
1814            if let Some(ref old_owner) = old_owner {
1815                old_owner.remove_control(cx, self);
1816            }
1817            if let Some(ref new_owner) = new_owner {
1818                new_owner.add_control(cx, self);
1819            }
1820            // https://html.spec.whatwg.org/multipage/#custom-element-reactions:reset-the-form-owner
1821            if let Some(html_elem) = elem.downcast::<HTMLElement>() &&
1822                html_elem.is_form_associated_custom_element()
1823            {
1824                ScriptThread::enqueue_callback_reaction(
1825                    cx,
1826                    elem,
1827                    CallbackReaction::FormAssociated(
1828                        new_owner.as_ref().map(|form| DomRoot::from_ref(&**form)),
1829                    ),
1830                    None,
1831                )
1832            }
1833            self.set_form_owner(cx, new_owner.as_deref());
1834
1835            if let Some(old_owner) = old_owner {
1836                old_owner.invalidate_default_button(cx.no_gc());
1837            }
1838            match new_owner {
1839                Some(new_owner) => new_owner.invalidate_default_button(cx.no_gc()),
1840                None => HTMLFormElement::update_control_default_state(cx.no_gc(), elem, false),
1841            }
1842        }
1843    }
1844
1845    /// <https://html.spec.whatwg.org/multipage/#association-of-controls-and-forms>
1846    fn form_attribute_mutated(&self, cx: &mut JSContext, mutation: AttributeMutation) {
1847        match mutation {
1848            AttributeMutation::Set(_) => {
1849                self.register_if_necessary();
1850            },
1851            AttributeMutation::Removed => {
1852                self.unregister_if_necessary();
1853            },
1854        }
1855
1856        self.reset_form_owner(cx);
1857    }
1858
1859    /// <https://html.spec.whatwg.org/multipage/#association-of-controls-and-forms>
1860    fn register_if_necessary(&self) {
1861        let elem = self.to_element();
1862        let form_id = elem.get_string_attribute(&local_name!("form"));
1863        let node = elem.upcast::<Node>();
1864
1865        if self.is_listed() && !form_id.is_empty() && node.is_connected() {
1866            node.owner_document()
1867                .register_form_id_listener(form_id, self);
1868        }
1869    }
1870
1871    fn unregister_if_necessary(&self) {
1872        let elem = self.to_element();
1873        let form_id = elem.get_string_attribute(&local_name!("form"));
1874
1875        if self.is_listed() && !form_id.is_empty() {
1876            elem.owner_document()
1877                .unregister_form_id_listener(form_id, self);
1878        }
1879    }
1880
1881    /// <https://html.spec.whatwg.org/multipage/#association-of-controls-and-forms>
1882    fn bind_form_control_to_tree(&self, cx: &mut JSContext) {
1883        let elem = self.to_element();
1884        let node = elem.upcast::<Node>();
1885
1886        // https://html.spec.whatwg.org/multipage/#create-an-element-for-the-token
1887        // Part of step 12.
1888        // '..suppress the running of the reset the form owner algorithm
1889        // when the parser subsequently attempts to insert the element..'
1890        let must_skip_reset = node.get_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER);
1891        node.set_flag(NodeFlags::PARSER_ASSOCIATED_FORM_OWNER, false);
1892
1893        if !must_skip_reset {
1894            self.form_attribute_mutated(cx, AttributeMutation::Set(None));
1895        }
1896    }
1897
1898    /// <https://html.spec.whatwg.org/multipage/#association-of-controls-and-forms>
1899    fn unbind_form_control_from_tree(&self, cx: &mut JSContext) {
1900        let element = self.to_element();
1901        let has_form_attr = element.has_attribute(&local_name!("form"));
1902        let same_subtree = self
1903            .form_owner()
1904            .is_none_or(|form| element.is_in_same_home_subtree(&*form));
1905
1906        self.unregister_if_necessary();
1907
1908        // Since this control has been unregistered from the id->listener map
1909        // in the previous step, reset_form_owner will not be invoked on it
1910        // when the form owner element is unbound (i.e it is in the same
1911        // subtree) if it appears later in the tree order. Hence invoke
1912        // reset from here if this control has the form attribute set.
1913        if !same_subtree || (self.is_listed() && has_form_attr) {
1914            self.reset_form_owner(cx);
1915        }
1916
1917        // Unbinding from a tree might enable a form control, if a fieldset ancestor is the only
1918        // reason it was disabled. The fact that it's enabled doesn't do much while it's
1919        // disconnected, but it is an observable fact to keep track of.
1920        self.to_html_element()
1921            .maybe_update_form_control_disabled(cx);
1922    }
1923
1924    fn get_form_attribute<InputFn, OwnerFn>(
1925        &self,
1926        attr: &LocalName,
1927        input: InputFn,
1928        owner: OwnerFn,
1929    ) -> DOMString
1930    where
1931        InputFn: Fn(&Self) -> DOMString,
1932        OwnerFn: Fn(&HTMLFormElement) -> DOMString,
1933        Self: Sized,
1934    {
1935        if self.to_element().has_attribute(attr) {
1936            input(self)
1937        } else {
1938            self.form_owner().map_or(DOMString::new(), |t| owner(&t))
1939        }
1940    }
1941
1942    fn get_form_boolean_attribute<InputFn, OwnerFn>(
1943        &self,
1944        attr: &LocalName,
1945        input: InputFn,
1946        owner: OwnerFn,
1947    ) -> bool
1948    where
1949        InputFn: Fn(&Self) -> bool,
1950        OwnerFn: Fn(&HTMLFormElement) -> bool,
1951        Self: Sized,
1952    {
1953        if self.to_element().has_attribute(attr) {
1954            input(self)
1955        } else {
1956            self.form_owner().is_some_and(|t| owner(&t))
1957        }
1958    }
1959
1960    /// <https://html.spec.whatwg.org/multipage/#candidate-for-constraint-validation>
1961    fn is_candidate_for_constraint_validation(&self, no_gc: &NoGC) -> bool {
1962        let element = self.to_element();
1963        let html_element = element.downcast::<HTMLElement>();
1964        if let Some(html_element) = html_element {
1965            html_element.is_submittable_element() || element.is_instance_validatable(no_gc)
1966        } else {
1967            false
1968        }
1969    }
1970
1971    fn moving_steps(&self, cx: &mut JSContext) {
1972        // If movedNode is a form-associated element with a non-null form owner and movedNode and
1973        // its form owner are no longer in the same tree, then reset the form owner of movedNode.
1974        let same_subtree = self
1975            .form_owner()
1976            .is_none_or(|form| self.to_element().is_in_same_home_subtree(&*form));
1977        if !same_subtree {
1978            self.reset_form_owner(cx)
1979        }
1980    }
1981
1982    // XXXKiChjang: Implement these on inheritors
1983    // fn satisfies_constraints(&self) -> bool;
1984}
1985
1986impl VirtualMethods for HTMLFormElement {
1987    fn super_type(&self) -> Option<&dyn VirtualMethods> {
1988        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
1989    }
1990
1991    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
1992        self.super_type().unwrap().unbind_from_tree(cx, context);
1993
1994        // Collect the controls to reset because reset_form_owner
1995        // will mutably borrow self.controls
1996        rooted_vec!(let mut to_reset);
1997        to_reset.extend(
1998            self.controls
1999                .borrow()
2000                .iter()
2001                .filter(|c| !c.is_in_same_home_subtree(self))
2002                .cloned(),
2003        );
2004
2005        for control in to_reset.iter() {
2006            control
2007                .as_maybe_form_control()
2008                .expect("Element must be a form control")
2009                .reset_form_owner(cx);
2010        }
2011    }
2012
2013    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
2014        match name {
2015            &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
2016            _ => self
2017                .super_type()
2018                .unwrap()
2019                .parse_plain_attribute(name, value),
2020        }
2021    }
2022
2023    fn attribute_mutated(
2024        &self,
2025        cx: &mut JSContext,
2026        attr: AttrRef<'_>,
2027        mutation: AttributeMutation,
2028    ) {
2029        self.super_type()
2030            .unwrap()
2031            .attribute_mutated(cx, attr, mutation);
2032
2033        match *attr.local_name() {
2034            local_name!("rel") | local_name!("rev") => {
2035                self.relations
2036                    .set(LinkRelations::for_element(self.upcast()));
2037            },
2038            _ => {},
2039        }
2040    }
2041}
2042
2043pub(crate) trait FormControlElementHelpers {
2044    fn as_maybe_form_control(&self) -> Option<&dyn FormControl>;
2045}
2046
2047impl FormControlElementHelpers for Element {
2048    fn as_maybe_form_control(&self) -> Option<&dyn FormControl> {
2049        let node = self.upcast::<Node>();
2050
2051        match node.type_id() {
2052            NodeTypeId::Element(ElementTypeId::HTMLElement(
2053                HTMLElementTypeId::HTMLButtonElement,
2054            )) => Some(self.downcast::<HTMLButtonElement>().unwrap() as &dyn FormControl),
2055            NodeTypeId::Element(ElementTypeId::HTMLElement(
2056                HTMLElementTypeId::HTMLFieldSetElement,
2057            )) => Some(self.downcast::<HTMLFieldSetElement>().unwrap() as &dyn FormControl),
2058            NodeTypeId::Element(ElementTypeId::HTMLElement(
2059                HTMLElementTypeId::HTMLImageElement,
2060            )) => Some(self.downcast::<HTMLImageElement>().unwrap() as &dyn FormControl),
2061            NodeTypeId::Element(ElementTypeId::HTMLElement(
2062                HTMLElementTypeId::HTMLInputElement,
2063            )) => Some(self.downcast::<HTMLInputElement>().unwrap() as &dyn FormControl),
2064            NodeTypeId::Element(ElementTypeId::HTMLElement(
2065                HTMLElementTypeId::HTMLLegendElement,
2066            )) => Some(self.downcast::<HTMLLegendElement>().unwrap() as &dyn FormControl),
2067            NodeTypeId::Element(ElementTypeId::HTMLElement(
2068                HTMLElementTypeId::HTMLObjectElement,
2069            )) => Some(self.downcast::<HTMLObjectElement>().unwrap() as &dyn FormControl),
2070            NodeTypeId::Element(ElementTypeId::HTMLElement(
2071                HTMLElementTypeId::HTMLOutputElement,
2072            )) => Some(self.downcast::<HTMLOutputElement>().unwrap() as &dyn FormControl),
2073            NodeTypeId::Element(ElementTypeId::HTMLElement(
2074                HTMLElementTypeId::HTMLSelectElement,
2075            )) => Some(self.downcast::<HTMLSelectElement>().unwrap() as &dyn FormControl),
2076            NodeTypeId::Element(ElementTypeId::HTMLElement(
2077                HTMLElementTypeId::HTMLTextAreaElement,
2078            )) => Some(self.downcast::<HTMLTextAreaElement>().unwrap() as &dyn FormControl),
2079            _ => self.downcast::<HTMLElement>().and_then(|elem| {
2080                if elem.is_form_associated_custom_element() {
2081                    Some(elem as &dyn FormControl)
2082                } else {
2083                    None
2084                }
2085            }),
2086        }
2087    }
2088}
2089
2090/// <https://html.spec.whatwg.org/multipage/#text/plain-encoding-algorithm>
2091fn encode_plaintext(pairs: impl Iterator<Item = (String, String)>) -> String {
2092    // Step 1. Let result be the empty string.
2093    let mut result = String::new();
2094    // Step 2. For each pair in pairs:
2095    for (name, value) in pairs {
2096        // Step 2.1. Append pair's name to result.
2097        result.push_str(&name);
2098        // Step 2.2. Append a single U+003D EQUALS SIGN character (=) to result.
2099        result.push('=');
2100        // Step 2.3. Append pair's value to result.
2101        result.push_str(&value);
2102        // Step 2.4. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF)
2103        // character pair to result.
2104        result.push_str("\r\n");
2105    }
2106    // Step 3. Return result.
2107    result
2108}
2109
2110/// Encode a string with the form's encoding, converted to a byte sequence.
2111/// <https://encoding.spec.whatwg.org/#encode>
2112///
2113/// Characters that can't be encoded in the given charset are replaced
2114/// with HTML decimal numeric character references (e.g. 😂 → &#128514;).
2115fn encode_with_html_fallback<'a>(input: &'a str, encoding: &'static Encoding) -> Cow<'a, [u8]> {
2116    encoding.encode(input).0
2117}
2118
2119/// <https://html.spec.whatwg.org/multipage/#multipart/form-data-encoding-algorithm>
2120pub(crate) fn encode_multipart_form_data(
2121    form_data: &mut [FormDatum],
2122    boundary: String,
2123    encoding: &'static Encoding,
2124) -> Vec<u8> {
2125    let mut result = vec![];
2126
2127    // Step 2.4: For field names and filenames for file fields, the result
2128    // of the encoding must be escaped by replacing:
2129    //   0x0A (LF) bytes with `%0A`,
2130    //   0x0D (CR) bytes with `%0D`,
2131    //   0x22 (") bytes with `%22`.
2132    // The user agent must not perform any other escapes.
2133    fn escape_header_bytes(input: &[u8]) -> Vec<u8> {
2134        let mut output = Vec::with_capacity(input.len());
2135        for &b in input {
2136            match b {
2137                b'\n' => output.extend(b"%0A"),
2138                b'\r' => output.extend(b"%0D"),
2139                b'"' => output.extend(b"%22"),
2140                _ => output.push(b),
2141            }
2142        }
2143        output
2144    }
2145
2146    for entry in form_data.iter_mut() {
2147        // Step 1.1: Replace every occurrence of U+000D (CR) not followed by U+000A (LF),
2148        // and every occurrence of U+000A (LF) not preceded by U+000D (CR),
2149        // in entry's name, by a string consisting of a U+000D (CR) and U+000A (LF).
2150        entry.name = entry.name.normalize_crlf().into();
2151
2152        // Step 1.2: If entry's value is not a File object,
2153        // then replace every occurrence of U+000D (CR) not followed by U+000A (LF),
2154        // and every occurrence of U+000A (LF) not preceded by U+000D (CR), in entry's value,
2155        // by a string consisting of a U+000D (CR) and U+000A (LF).
2156        if let FormDatumValue::String(ref s) = entry.value {
2157            entry.value = FormDatumValue::String(s.normalize_crlf().into());
2158        }
2159
2160        // Step 2.6: Boundary string
2161        let mut boundary_bytes = format!("--{}\r\n", boundary).into_bytes();
2162        result.append(&mut boundary_bytes);
2163
2164        // Step 2.3: Encode name with the form's encoding
2165        let name_str = &*entry.name.str();
2166        let encoded_name = encode_with_html_fallback(name_str, encoding);
2167        // Step 2.4: Escape name for header
2168        let escaped_name = escape_header_bytes(&encoded_name);
2169
2170        match entry.value {
2171            FormDatumValue::String(ref s) => {
2172                // Step 2.3: Encode value with the form's encoding
2173                let value_str = &*s.str();
2174                let encoded_value = encode_with_html_fallback(value_str, encoding);
2175
2176                // Step 2.5: Non-file fields must not have `Content-Type` header specified
2177                result.extend(b"Content-Disposition: form-data; name=\"");
2178                result.extend(&escaped_name);
2179                result.extend(b"\"\r\n\r\n");
2180                result.extend_from_slice(&encoded_value);
2181                result.extend(b"\r\n");
2182            },
2183            FormDatumValue::File(ref f) => {
2184                // Step 2.3: Encode filename with the form's encoding
2185                let filename_str = &*f.name().str();
2186                let encoded_filename = encode_with_html_fallback(filename_str, encoding);
2187                // Step 2.4: Escape filename for header
2188                let escaped_filename = escape_header_bytes(&encoded_filename);
2189
2190                result.extend(b"Content-Disposition: form-data; name=\"");
2191                result.extend(&escaped_name);
2192                result.extend(b"\"; filename=\"");
2193                result.extend(&escaped_filename);
2194
2195                // https://tools.ietf.org/html/rfc7578#section-4.4
2196                result.extend(b"\"\r\nContent-Type: ");
2197
2198                let content_type: Mime = f
2199                    .upcast::<Blob>()
2200                    .Type()
2201                    .parse()
2202                    .unwrap_or(mime::TEXT_PLAIN);
2203                result.extend(content_type.as_ref().as_bytes());
2204                result.extend(b"\r\n\r\n");
2205
2206                let mut bytes = f.upcast::<Blob>().get_bytes().unwrap_or_default();
2207
2208                result.append(&mut bytes);
2209                result.extend(b"\r\n");
2210            },
2211        }
2212    }
2213
2214    // Step 2.6: Closing boundary string
2215    let mut boundary_bytes = format!("--{boundary}--\r\n").into_bytes();
2216    result.append(&mut boundary_bytes);
2217
2218    result
2219}
2220
2221// https://tools.ietf.org/html/rfc7578#section-4.1
2222pub(crate) fn generate_boundary() -> String {
2223    let i1 = random::<u32>();
2224    let i2 = random::<u32>();
2225
2226    format!("---------------------------{0}{1}", i1, i2)
2227}