Skip to main content

script/dom/html/form_controls/
htmlinputelement.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::cell::{Cell, RefCell};
6use std::ptr;
7
8use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
9use dom_struct::dom_struct;
10use embedder_traits::{EmbedderControlRequest, InputMethodRequest, RgbColor, SelectedFile};
11use encoding_rs::Encoding;
12use html5ever::{LocalName, Prefix, local_name};
13use js::context::{JSContext, NoGC};
14use js::jsapi::{ClippedTime, JSObject, RegExpFlag_UnicodeSets, RegExpFlags};
15use js::jsval::UndefinedValue;
16use js::rust::wrappers2::{
17    CheckRegExpSyntax, DateGetMsecSinceEpoch, ExecuteRegExpNoStatics, JS_ClearPendingException,
18    NewDateObject, NewUCRegExpObject, ObjectIsDate, ObjectIsRegExp,
19};
20use js::rust::{HandleObject, MutableHandleObject, MutableHandleValue};
21use num_traits::ToPrimitive;
22use script_bindings::cell::{DomRefCell, Ref};
23use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
24use script_bindings::domstring::{TracedDOMString, parse_floating_point_number};
25use script_bindings::traits::DomEventTrait;
26use servo_base::generic_channel::GenericSender;
27use servo_base::text::{RangeAny, Utf16CodeUnits, Utf32CodeUnits};
28use style::attr::{AttrValue, LengthOrPercentageOrAuto};
29use style::str::split_commas;
30use stylo_atoms::Atom;
31use stylo_dom::ElementState;
32use time::OffsetDateTime;
33use unicode_bidi::{BidiClass, bidi_class};
34use webdriver::error::ErrorStatus;
35use xml5ever::ns;
36
37use crate::dom::MoveContext;
38use crate::dom::activation::Activatable;
39use crate::dom::bindings::cell::AtomicSafeBorrowMut;
40use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
41use crate::dom::bindings::codegen::Bindings::FileListBinding::FileListMethods;
42use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding::SelectionMode;
43use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
44use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
45use crate::dom::bindings::error::{Error, ErrorResult};
46use crate::dom::bindings::inheritance::Castable;
47use crate::dom::bindings::refcounted::Trusted;
48use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
49use crate::dom::bindings::str::{DOMString, USVString};
50use crate::dom::bindings::utils::to_frozen_array;
51use crate::dom::document::Document;
52use crate::dom::document_embedder_controls::ControlElement;
53use crate::dom::element::attributes::storage::AttrRef;
54use crate::dom::element::{AttributeMutation, Element};
55use crate::dom::event::Event;
56use crate::dom::event::event::{EventBubbles, EventCancelable, EventComposed};
57use crate::dom::eventtarget::EventTarget;
58use crate::dom::filelist::FileList;
59use crate::dom::filesystementry::FileSystemEntry;
60use crate::dom::html::form_controls::input_type::radio_input_type::perform_radio_group_validation;
61use crate::dom::html::form_controls::input_type::{
62    InputActivationType, InputType, ValueChangeEvents,
63};
64use crate::dom::html::form_controls::text_control::TextControlElement;
65use crate::dom::html::form_controls::text_input::{KeyReaction, Lines, TextInput};
66use crate::dom::html::htmldatalistelement::HTMLDataListElement;
67use crate::dom::html::htmlelement::HTMLElement;
68use crate::dom::html::htmlformelement::{
69    FormControl, FormDatum, FormDatumValue, FormSubmitterElement, HTMLFormElement, SubmittedFrom,
70};
71use crate::dom::input_type::radio_input_type::radio_group_iter_unrooted;
72use crate::dom::iterators::ShadowIncluding;
73use crate::dom::node::virtualmethods::VirtualMethods;
74use crate::dom::node::{
75    BindContext, CloneChildrenFlag, Node, NodeDamage, NodeTraits, UnbindContext,
76};
77use crate::dom::nodelist::NodeList;
78use crate::dom::text_input::EmbedderClipboardProvider;
79use crate::dom::types::{FocusEvent, InputEvent};
80use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
81use crate::dom::validitystate::{ValidationFlags, ValidityState};
82use crate::realms::enter_auto_realm;
83
84#[derive(Debug, PartialEq)]
85pub(crate) enum ValueMode {
86    /// <https://html.spec.whatwg.org/multipage/#dom-input-value-value>
87    Value,
88
89    /// <https://html.spec.whatwg.org/multipage/#dom-input-value-default>
90    Default,
91
92    /// <https://html.spec.whatwg.org/multipage/#dom-input-value-default-on>
93    DefaultOn,
94
95    /// <https://html.spec.whatwg.org/multipage/#dom-input-value-filename>
96    Filename,
97}
98
99#[derive(Debug, PartialEq)]
100enum StepDirection {
101    Up,
102    Down,
103}
104
105#[dom_struct]
106pub(crate) struct HTMLInputElement {
107    htmlelement: HTMLElement,
108    input_type: DomRefCell<InputType>,
109
110    /// Whether or not the [`InputType`] for this [`HTMLInputElement`] renders as
111    /// textual input. This is cached so that it can be read during layout.
112    is_textual_or_password: Cell<bool>,
113
114    placeholder: DomRefCell<TracedDOMString>,
115    size: Cell<u32>,
116    maxlength: Cell<i32>,
117    minlength: Cell<i32>,
118    /// <https://html.spec.whatwg.org/multipage/#concept-fe-checked>
119    /// The checkedness of an input is independent of its checked state as every input type can be
120    /// checked, but only checkboxes and radio buttons are in the checked state when they are checked.
121    checkedness: Cell<bool>,
122    /// <https://html.spec.whatwg.org/multipage/#concept-input-checked-dirty-flag>
123    checked_changed: Cell<bool>,
124    /// <https://html.spec.whatwg.org/multipage/#concept-input-indeterminate>
125    /// The indeterminateness of an input is independent of its indeterminate element state.
126    /// Every input type can be indeterminate, but this adds the :indeterminate pseudo class only to
127    /// checkboxes. At the same time, radio boxes are matched by :indeterminate when no button in the
128    /// groupo is checked, which is fully independent of the interminateness of the input element.
129    indeterminateness: Cell<bool>,
130    #[no_trace]
131    text_input: AtomicRefCell<TextInput<EmbedderClipboardProvider>>,
132    form_owner: MutNullableDom<HTMLFormElement>,
133    labels_node_list: MutNullableDom<NodeList>,
134    validity_state: MutNullableDom<ValidityState>,
135    #[no_trace]
136    pending_webdriver_response: RefCell<Option<Box<PendingWebDriverResponse>>>,
137    /// <https://html.spec.whatwg.org/multipage/#concept-input-value-dirty-flag>
138    value_dirty: Cell<bool>,
139    /// <https://html.spec.whatwg.org/multipage/#user-validity>
140    user_validity: Cell<bool>,
141    changed_by_user_while_focused: Cell<bool>,
142
143    /// <https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event>
144    has_scheduled_selectionchange_event: Cell<bool>,
145}
146
147#[derive(JSTraceable)]
148pub(crate) struct InputActivationState {
149    pub(crate) indeterminate: bool,
150    pub(crate) checked: bool,
151    pub(crate) checked_radio: Option<DomRoot<HTMLInputElement>>,
152    pub(crate) was_radio: bool,
153    pub(crate) was_checkbox: bool,
154    // was_mutable is implied: pre-activation would return None if it wasn't
155}
156
157static DEFAULT_INPUT_SIZE: u32 = 20;
158static DEFAULT_MAX_LENGTH: i32 = -1;
159static DEFAULT_MIN_LENGTH: i32 = -1;
160
161#[expect(non_snake_case)]
162impl HTMLInputElement {
163    fn new_inherited(
164        local_name: LocalName,
165        prefix: Option<Prefix>,
166        document: &Document,
167    ) -> HTMLInputElement {
168        let embedder_sender = document
169            .window()
170            .as_global_scope()
171            .script_to_embedder_chan()
172            .clone();
173        HTMLInputElement {
174            htmlelement: HTMLElement::new_inherited_with_state(
175                ElementState::ENABLED | ElementState::READWRITE | ElementState::OPTIONAL_,
176                local_name,
177                prefix,
178                document,
179            ),
180            input_type: DomRefCell::new(InputType::new_text()),
181            is_textual_or_password: Cell::new(true),
182            placeholder: DomRefCell::new(DOMString::new().traced()),
183            checkedness: Cell::new(false),
184            checked_changed: Cell::new(false),
185            indeterminateness: Cell::new(false),
186            maxlength: Cell::new(DEFAULT_MAX_LENGTH),
187            minlength: Cell::new(DEFAULT_MIN_LENGTH),
188            size: Cell::new(DEFAULT_INPUT_SIZE),
189            text_input: AtomicRefCell::new(TextInput::new(
190                Lines::Single,
191                DOMString::new(),
192                EmbedderClipboardProvider {
193                    embedder_sender,
194                    webview_id: document.webview_id(),
195                },
196            )),
197            value_dirty: Cell::new(false),
198            user_validity: Cell::new(false),
199            changed_by_user_while_focused: Cell::new(false),
200            form_owner: Default::default(),
201            labels_node_list: MutNullableDom::new(None),
202            validity_state: Default::default(),
203            pending_webdriver_response: Default::default(),
204            has_scheduled_selectionchange_event: Default::default(),
205        }
206    }
207
208    pub(crate) fn new(
209        cx: &mut JSContext,
210        local_name: LocalName,
211        prefix: Option<Prefix>,
212        document: &Document,
213        proto: Option<HandleObject>,
214    ) -> DomRoot<HTMLInputElement> {
215        Node::reflect_node_with_proto(
216            cx,
217            Box::new(HTMLInputElement::new_inherited(
218                local_name, prefix, document,
219            )),
220            document,
221            proto,
222        )
223    }
224
225    pub(crate) fn auto_directionality(&self) -> Option<String> {
226        match *self.input_type() {
227            InputType::Text(_) | InputType::Search(_) | InputType::Url(_) | InputType::Email(_) => {
228                let value: String = String::from(self.Value());
229                Some(HTMLInputElement::directionality_from_value(&value))
230            },
231            _ => None,
232        }
233    }
234
235    pub(crate) fn directionality_from_value(value: &str) -> String {
236        if HTMLInputElement::is_first_strong_character_rtl(value) {
237            "rtl".to_owned()
238        } else {
239            "ltr".to_owned()
240        }
241    }
242
243    fn is_first_strong_character_rtl(value: &str) -> bool {
244        for ch in value.chars() {
245            return match bidi_class(ch) {
246                BidiClass::L => false,
247                BidiClass::AL => true,
248                BidiClass::R => true,
249                _ => continue,
250            };
251        }
252        false
253    }
254
255    /// <https://html.spec.whatwg.org/multipage/#dom-input-value>
256    /// <https://html.spec.whatwg.org/multipage/#concept-input-apply>
257    pub(crate) fn value_mode(&self) -> ValueMode {
258        match *self.input_type() {
259            InputType::Submit(_) |
260            InputType::Reset(_) |
261            InputType::Button(_) |
262            InputType::Image(_) |
263            InputType::Hidden(_) => ValueMode::Default,
264
265            InputType::Checkbox(_) | InputType::Radio(_) => ValueMode::DefaultOn,
266
267            InputType::Color(_) |
268            InputType::Date(_) |
269            InputType::DatetimeLocal(_) |
270            InputType::Email(_) |
271            InputType::Month(_) |
272            InputType::Number(_) |
273            InputType::Password(_) |
274            InputType::Range(_) |
275            InputType::Search(_) |
276            InputType::Tel(_) |
277            InputType::Text(_) |
278            InputType::Time(_) |
279            InputType::Url(_) |
280            InputType::Week(_) => ValueMode::Value,
281
282            InputType::File(_) => ValueMode::Filename,
283        }
284    }
285
286    #[inline]
287    pub(crate) fn input_type(&self) -> Ref<'_, InputType> {
288        self.input_type.borrow()
289    }
290
291    /// <https://w3c.github.io/webdriver/#dfn-non-typeable-form-control>
292    pub(crate) fn is_nontypeable(&self) -> bool {
293        matches!(
294            *self.input_type(),
295            InputType::Button(_) |
296                InputType::Checkbox(_) |
297                InputType::Color(_) |
298                InputType::File(_) |
299                InputType::Hidden(_) |
300                InputType::Image(_) |
301                InputType::Radio(_) |
302                InputType::Range(_) |
303                InputType::Reset(_) |
304                InputType::Submit(_)
305        )
306    }
307
308    #[inline]
309    pub(crate) fn is_submit_button(&self) -> bool {
310        matches!(
311            *self.input_type(),
312            InputType::Submit(_) | InputType::Image(_)
313        )
314    }
315
316    /// <https://html.spec.whatwg.org/multipage/#auto-directionality-form-associated-elements>
317    pub(crate) fn is_auto_directionality_form_associated_element(&self) -> bool {
318        matches!(
319            *self.input_type(),
320            InputType::Hidden(_) |
321                InputType::Text(_) |
322                InputType::Search(_) |
323                InputType::Tel(_) |
324                InputType::Url(_) |
325                InputType::Email(_) |
326                InputType::Password(_) |
327                InputType::Submit(_) |
328                InputType::Reset(_) |
329                InputType::Button(_)
330        )
331    }
332
333    fn does_minmaxlength_apply(&self) -> bool {
334        matches!(
335            *self.input_type(),
336            InputType::Text(_) |
337                InputType::Search(_) |
338                InputType::Url(_) |
339                InputType::Tel(_) |
340                InputType::Email(_) |
341                InputType::Password(_)
342        )
343    }
344
345    fn does_pattern_apply(&self) -> bool {
346        matches!(
347            *self.input_type(),
348            InputType::Text(_) |
349                InputType::Search(_) |
350                InputType::Url(_) |
351                InputType::Tel(_) |
352                InputType::Email(_) |
353                InputType::Password(_)
354        )
355    }
356
357    fn does_multiple_apply(&self) -> bool {
358        matches!(*self.input_type(), InputType::Email(_))
359    }
360
361    /// <https://html.spec.whatwg.org/multipage/#states-of-the-type-attribute>
362    fn does_required_apply(&self) -> bool {
363        matches!(
364            *self.input_type(),
365            InputType::Text(_) |
366                InputType::Search(_) |
367                InputType::Tel(_) |
368                InputType::Url(_) |
369                InputType::Email(_) |
370                InputType::Password(_) |
371                InputType::Date(_) |
372                InputType::Month(_) |
373                InputType::Week(_) |
374                InputType::Time(_) |
375                InputType::DatetimeLocal(_) |
376                InputType::Number(_) |
377                InputType::Checkbox(_) |
378                InputType::Radio(_) |
379                InputType::File(_)
380        )
381    }
382
383    /// <https://html.spec.whatwg.org/multipage/#the-input-element:event-change>
384    /// These values are taken from the table listed for the "change" event.
385    pub(crate) fn does_change_event_apply(&self) -> bool {
386        matches!(
387            *self.input_type(),
388            InputType::Text(_) |
389                InputType::Search(_) |
390                InputType::Tel(_) |
391                InputType::Url(_) |
392                InputType::Email(_) |
393                InputType::Password(_) |
394                InputType::Date(_) |
395                InputType::Month(_) |
396                InputType::Week(_) |
397                InputType::Time(_) |
398                InputType::DatetimeLocal(_) |
399                InputType::Number(_) |
400                InputType::Range(_) |
401                InputType::Color(_) |
402                InputType::Checkbox(_) |
403                InputType::Radio(_) |
404                InputType::File(_)
405        )
406    }
407
408    /// <https://html.spec.whatwg.org/multipage/#concept-input-apply>
409    /// These values are taken from the table listed for the "readonly" attribute.
410    fn does_readonly_apply(&self) -> bool {
411        matches!(
412            *self.input_type(),
413            InputType::Text(_) |
414                InputType::Search(_) |
415                InputType::Tel(_) |
416                InputType::Url(_) |
417                InputType::Email(_) |
418                InputType::Password(_) |
419                InputType::Date(_) |
420                InputType::Month(_) |
421                InputType::Week(_) |
422                InputType::Time(_) |
423                InputType::DatetimeLocal(_) |
424                InputType::Number(_)
425        )
426    }
427
428    pub(crate) fn has_defined_activation_behavior(&self) -> bool {
429        InputActivationType::new_from_input_type(&self.input_type()).is_some()
430    }
431
432    #[inline]
433    pub(crate) fn changed_by_user_while_focused(&self) -> bool {
434        self.changed_by_user_while_focused.get()
435    }
436
437    pub(crate) fn set_user_validity(&self, no_gc: &NoGC, value: bool) {
438        if self.user_validity.get() != value {
439            self.user_validity.set(value);
440            self.update_user_valid_state(no_gc);
441        }
442    }
443
444    fn update_required_and_optional_state(&self, no_gc: &NoGC) {
445        let element = self.upcast::<Element>();
446        let required_applies = self.does_required_apply();
447        let required = element.has_attribute(&local_name!("required"));
448
449        // https://html.spec.whatwg.org/multipage/#selector-required
450        // > The :required pseudo-class must match any element falling into one of the following categories:
451        // > - input elements that are required
452        element.set_state(no_gc, ElementState::REQUIRED, required_applies && required);
453
454        // https://html.spec.whatwg.org/multipage/#selector-optional
455        // > The :optional pseudo-class must match any element falling into one of the following categories:
456        // > - input elements to which the required attribute applies that are not required
457        element.set_state(
458            no_gc,
459            ElementState::OPTIONAL_,
460            required_applies && !required,
461        );
462    }
463
464    // valueAsNumber, step, min, and max all share the same set of
465    // input types they apply to
466    fn does_value_as_number_apply(&self) -> bool {
467        matches!(
468            *self.input_type(),
469            InputType::Date(_) |
470                InputType::Month(_) |
471                InputType::Week(_) |
472                InputType::Time(_) |
473                InputType::DatetimeLocal(_) |
474                InputType::Number(_) |
475                InputType::Range(_)
476        )
477    }
478
479    fn does_value_as_date_apply(&self) -> bool {
480        matches!(
481            *self.input_type(),
482            InputType::Date(_) | InputType::Month(_) | InputType::Week(_) | InputType::Time(_)
483        )
484    }
485
486    /// <https://html.spec.whatwg.org/multipage#concept-input-step>
487    pub(crate) fn allowed_value_step(&self) -> Option<f64> {
488        // Step 1. If the attribute does not apply, then there is no allowed value step.
489        // NOTE: The attribute applies iff there is a default step
490        let default_step = self.default_step()?;
491
492        // Step 2. Otherwise, if the attribute is absent, then the allowed value step
493        // is the default step multiplied by the step scale factor.
494        let Some(step_value) = self
495            .upcast::<Element>()
496            .get_attribute_string_value(&local_name!("step"))
497        else {
498            return Some(default_step * self.step_scale_factor());
499        };
500
501        // Step 3. Otherwise, if the attribute's value is an ASCII case-insensitive match
502        // for the string "any", then there is no allowed value step.
503        if step_value.eq_ignore_ascii_case("any") {
504            return None;
505        }
506
507        // Step 4. Otherwise, if the rules for parsing floating-point number values, when they
508        // are applied to the attribute's value, return an error, zero, or a number less than zero,
509        // then the allowed value step is the default step multiplied by the step scale factor.
510        let Some(parsed_value) =
511            parse_floating_point_number(&step_value).filter(|value| *value > 0.0)
512        else {
513            return Some(default_step * self.step_scale_factor());
514        };
515
516        // Step 5. Otherwise, the allowed value step is the number returned by the rules for parsing
517        // floating-point number values when they are applied to the attribute's value,
518        // multiplied by the step scale factor.
519        Some(parsed_value * self.step_scale_factor())
520    }
521
522    /// <https://html.spec.whatwg.org/multipage#concept-input-min>
523    pub(crate) fn minimum(&self) -> Option<f64> {
524        self.upcast::<Element>()
525            .get_attribute_string_value(&local_name!("min"))
526            .and_then(|value| self.convert_string_to_number(&value))
527            .or_else(|| self.default_minimum())
528    }
529
530    /// <https://html.spec.whatwg.org/multipage#concept-input-max>
531    pub(crate) fn maximum(&self) -> Option<f64> {
532        self.upcast::<Element>()
533            .get_attribute_string_value(&local_name!("max"))
534            .and_then(|value| self.convert_string_to_number(&value))
535            .or_else(|| self.default_maximum())
536    }
537
538    /// when allowed_value_step and minimum both exist, this is the smallest
539    /// value >= minimum that lies on an integer step
540    pub(crate) fn stepped_minimum(&self) -> Option<f64> {
541        match (self.minimum(), self.allowed_value_step()) {
542            (Some(min), Some(allowed_step)) => {
543                let step_base = self.step_base();
544                // how many steps is min from step_base?
545                let nsteps = (min - step_base) / allowed_step;
546                // count that many integer steps, rounded +, from step_base
547                Some(step_base + (allowed_step * nsteps.ceil()))
548            },
549            (_, _) => None,
550        }
551    }
552
553    /// when allowed_value_step and maximum both exist, this is the smallest
554    /// value <= maximum that lies on an integer step
555    pub(crate) fn stepped_maximum(&self) -> Option<f64> {
556        match (self.maximum(), self.allowed_value_step()) {
557            (Some(max), Some(allowed_step)) => {
558                let step_base = self.step_base();
559                // how many steps is max from step_base?
560                let nsteps = (max - step_base) / allowed_step;
561                // count that many integer steps, rounded -, from step_base
562                Some(step_base + (allowed_step * nsteps.floor()))
563            },
564            (_, _) => None,
565        }
566    }
567
568    /// <https://html.spec.whatwg.org/multipage#concept-input-min-default>
569    fn default_minimum(&self) -> Option<f64> {
570        match *self.input_type() {
571            InputType::Range(_) => Some(0.0),
572            _ => None,
573        }
574    }
575
576    /// <https://html.spec.whatwg.org/multipage#concept-input-max-default>
577    fn default_maximum(&self) -> Option<f64> {
578        match *self.input_type() {
579            InputType::Range(_) => Some(100.0),
580            _ => None,
581        }
582    }
583
584    /// <https://html.spec.whatwg.org/multipage#concept-input-value-default-range>
585    pub(crate) fn default_range_value(&self) -> f64 {
586        let min = self.minimum().unwrap_or(0.0);
587        let max = self.maximum().unwrap_or(100.0);
588        if max < min {
589            min
590        } else {
591            min + (max - min) * 0.5
592        }
593    }
594
595    /// <https://html.spec.whatwg.org/multipage#concept-input-step-default>
596    fn default_step(&self) -> Option<f64> {
597        match *self.input_type() {
598            InputType::Date(_) => Some(1.0),
599            InputType::Month(_) => Some(1.0),
600            InputType::Week(_) => Some(1.0),
601            InputType::Time(_) => Some(60.0),
602            InputType::DatetimeLocal(_) => Some(60.0),
603            InputType::Number(_) => Some(1.0),
604            InputType::Range(_) => Some(1.0),
605            _ => None,
606        }
607    }
608
609    /// <https://html.spec.whatwg.org/multipage#concept-input-step-scale>
610    fn step_scale_factor(&self) -> f64 {
611        match *self.input_type() {
612            InputType::Date(_) => 86400000.0,
613            InputType::Month(_) => 1.0,
614            InputType::Week(_) => 604800000.0,
615            InputType::Time(_) => 1000.0,
616            InputType::DatetimeLocal(_) => 1000.0,
617            InputType::Number(_) => 1.0,
618            InputType::Range(_) => 1.0,
619            _ => unreachable!(),
620        }
621    }
622
623    /// <https://html.spec.whatwg.org/multipage#concept-input-min-zero>
624    pub(crate) fn step_base(&self) -> f64 {
625        // Step 1. If the element has a min content attribute, and the result of applying
626        // the algorithm to convert a string to a number to the value of the min content attribute
627        // is not an error, then return that result.
628        if let Some(minimum) = self
629            .upcast::<Element>()
630            .get_attribute_string_value(&local_name!("min"))
631            .and_then(|value| self.convert_string_to_number(&value))
632        {
633            return minimum;
634        }
635
636        // Step 2. If the element has a value content attribute, and the result of applying the
637        // algorithm to convert a string to a number to the value of the value content attribute
638        // is not an error, then return that result.
639        if let Some(value) = self
640            .upcast::<Element>()
641            .get_attribute_string_value(&local_name!("value"))
642            .and_then(|value| self.convert_string_to_number(&value))
643        {
644            return value;
645        }
646
647        // Step 3. If a default step base is defined for this element given its type attribute's state, then return it.
648        if let Some(default_step_base) = self.default_step_base() {
649            return default_step_base;
650        }
651
652        // Step 4. Return zero.
653        0.0
654    }
655
656    /// <https://html.spec.whatwg.org/multipage#concept-input-step-default-base>
657    fn default_step_base(&self) -> Option<f64> {
658        match *self.input_type() {
659            InputType::Week(_) => Some(-259200000.0),
660            _ => None,
661        }
662    }
663
664    /// <https://html.spec.whatwg.org/multipage/#dom-input-stepup>
665    ///
666    /// <https://html.spec.whatwg.org/multipage/#dom-input-stepdown>
667    fn step_up_or_down(&self, cx: &mut JSContext, n: i32, dir: StepDirection) -> ErrorResult {
668        // Step 1. If the stepDown() and stepUp() methods do not apply, as defined for the
669        // input element's type attribute's current state, then throw an "InvalidStateError" DOMException.
670        if !self.does_value_as_number_apply() {
671            return Err(Error::InvalidState(Some(
672                "Input element does not implement `stepDown()` or `stepUp()`".into(),
673            )));
674        }
675        let step_base = self.step_base();
676
677        // Step 2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.
678        let Some(allowed_value_step) = self.allowed_value_step() else {
679            return Err(Error::InvalidState(Some(
680                "Input element does not have a value step".into(),
681            )));
682        };
683
684        // Step 3. If the element has a minimum and a maximum and the minimum is greater than the maximum,
685        // then return.
686        let minimum = self.minimum();
687        let maximum = self.maximum();
688        if let (Some(min), Some(max)) = (minimum, maximum) {
689            if min > max {
690                return Ok(());
691            }
692
693            // Step 4. If the element has a minimum and a maximum and there is no value greater than or equal to the
694            // element's minimum and less than or equal to the element's maximum that, when subtracted from the step
695            // base, is an integral multiple of the allowed value step, then return.
696            if let Some(stepped_minimum) = self.stepped_minimum() &&
697                stepped_minimum > max
698            {
699                return Ok(());
700            }
701        }
702
703        // Step 5. If applying the algorithm to convert a string to a number to the string given
704        // by the element's value does not result in an error, then let value be the result of
705        // that algorithm. Otherwise, let value be zero.
706        let mut value: f64 = self
707            .convert_string_to_number(&self.Value().str())
708            .unwrap_or(0.0);
709
710        // Step 6. Let valueBeforeStepping be value.
711        let valueBeforeStepping = value;
712
713        // Step 7. If value subtracted from the step base is not an integral multiple of the allowed value step,
714        // then set value to the nearest value that, when subtracted from the step base, is an integral multiple
715        // of the allowed value step, and that is less than value if the method invoked was the stepDown() method,
716        // and more than value otherwise.
717        if (value - step_base) % allowed_value_step != 0.0 {
718            value = match dir {
719                StepDirection::Down =>
720                // step down a fractional step to be on a step multiple
721                {
722                    let intervals_from_base = ((value - step_base) / allowed_value_step).floor();
723                    intervals_from_base * allowed_value_step + step_base
724                },
725                StepDirection::Up =>
726                // step up a fractional step to be on a step multiple
727                {
728                    let intervals_from_base = ((value - step_base) / allowed_value_step).ceil();
729                    intervals_from_base * allowed_value_step + step_base
730                },
731            };
732        }
733        // Otherwise (value subtracted from the step base is an integral multiple of the allowed value step):
734        else {
735            // Step 7.1 Let n be the argument.
736            // Step 7.2 Let delta be the allowed value step multiplied by n.
737            // Step 7.3 If the method invoked was the stepDown() method, negate delta.
738            // Step 7.4 Let value be the result of adding delta to value.
739            value += match dir {
740                StepDirection::Down => -f64::from(n) * allowed_value_step,
741                StepDirection::Up => f64::from(n) * allowed_value_step,
742            };
743        }
744
745        // Step 8. If the element has a minimum, and value is less than that minimum, then set value to the smallest
746        // value that, when subtracted from the step base, is an integral multiple of the allowed value step, and that
747        // is more than or equal to that minimum.
748        if let Some(min) = minimum &&
749            value < min
750        {
751            value = self.stepped_minimum().unwrap_or(value);
752        }
753
754        // Step 9. If the element has a maximum, and value is greater than that maximum, then set value to the largest
755        // value that, when subtracted from the step base, is an integral multiple of the allowed value step, and that
756        // is less than or equal to that maximum.
757        if let Some(max) = maximum &&
758            value > max
759        {
760            value = self.stepped_maximum().unwrap_or(value);
761        }
762
763        // Step 10. If either the method invoked was the stepDown() method and value is greater than
764        // valueBeforeStepping, or the method invoked was the stepUp() method and value is less than
765        // valueBeforeStepping, then return.
766        match dir {
767            StepDirection::Down => {
768                if value > valueBeforeStepping {
769                    return Ok(());
770                }
771            },
772            StepDirection::Up => {
773                if value < valueBeforeStepping {
774                    return Ok(());
775                }
776            },
777        }
778
779        // Step 11. Let value as string be the result of running the algorithm to convert a number to a string,
780        // as defined for the input element's type attribute's current state, on value.
781        // Step 12. Set the value of the element to value as string.
782        self.SetValueAsNumber(cx, value)
783    }
784
785    /// <https://html.spec.whatwg.org/multipage/#concept-input-list>
786    fn suggestions_source_element(&self) -> Option<DomRoot<HTMLDataListElement>> {
787        let list_string = self
788            .upcast::<Element>()
789            .get_string_attribute(&local_name!("list"));
790        if list_string.is_empty() {
791            return None;
792        }
793        let ancestor = self
794            .upcast::<Node>()
795            .GetRootNode(&GetRootNodeOptions::empty());
796        let first_with_id = &ancestor
797            .traverse_preorder(ShadowIncluding::No)
798            .find(|node| {
799                node.downcast::<Element>()
800                    .is_some_and(|e| e.Id() == list_string)
801            });
802        first_with_id
803            .as_ref()
804            .and_then(|el| el.downcast::<HTMLDataListElement>())
805            .map(DomRoot::from_ref)
806    }
807
808    /// <https://html.spec.whatwg.org/multipage/#suffering-from-being-missing>
809    fn suffers_from_being_missing(&self, no_gc: &NoGC, value: &DOMString) -> bool {
810        self.input_type()
811            .as_specific()
812            .suffers_from_being_missing(no_gc, self, value)
813    }
814
815    /// <https://html.spec.whatwg.org/multipage/#suffering-from-a-type-mismatch>
816    fn suffers_from_type_mismatch(&self, value: &DOMString) -> bool {
817        if value.is_empty() {
818            return false;
819        }
820
821        self.input_type()
822            .as_specific()
823            .suffers_from_type_mismatch(self, value)
824    }
825
826    /// <https://html.spec.whatwg.org/multipage/#suffering-from-a-pattern-mismatch>
827    fn suffers_from_pattern_mismatch(&self, cx: &mut JSContext, value: &DOMString) -> bool {
828        // https://html.spec.whatwg.org/multipage/#the-pattern-attribute%3Asuffering-from-a-pattern-mismatch
829        // https://html.spec.whatwg.org/multipage/#the-pattern-attribute%3Asuffering-from-a-pattern-mismatch-2
830        let pattern_str = self.Pattern();
831        if value.is_empty() || pattern_str.is_empty() || !self.does_pattern_apply() {
832            return false;
833        }
834
835        let mut realm = enter_auto_realm(cx, self);
836        let cx = &mut realm;
837
838        // Rust's regex is not compatible, we need to use mozjs RegExp.
839        rooted!(&in(cx) let mut pattern = ptr::null_mut::<JSObject>());
840        if compile_pattern(cx, &pattern_str.str(), pattern.handle_mut()) {
841            if self.Multiple() && self.does_multiple_apply() {
842                !split_commas(&value.str())
843                    .all(|s| matches_js_regex(cx, pattern.handle(), s).unwrap_or(true))
844            } else {
845                !matches_js_regex(cx, pattern.handle(), &value.str()).unwrap_or(true)
846            }
847        } else {
848            // Element doesn't suffer from pattern mismatch if pattern is invalid.
849            false
850        }
851    }
852
853    /// <https://html.spec.whatwg.org/multipage/#suffering-from-bad-input>
854    fn suffers_from_bad_input(&self, value: &DOMString) -> bool {
855        if value.is_empty() {
856            return false;
857        }
858
859        self.input_type()
860            .as_specific()
861            .suffers_from_bad_input(value)
862    }
863
864    /// <https://html.spec.whatwg.org/multipage/#suffering-from-being-too-long>
865    /// <https://html.spec.whatwg.org/multipage/#suffering-from-being-too-short>
866    fn suffers_from_length_issues(&self, value: &DOMString) -> ValidationFlags {
867        // https://html.spec.whatwg.org/multipage/#limiting-user-input-length%3A-the-maxlength-attribute%3Asuffering-from-being-too-long
868        // https://html.spec.whatwg.org/multipage/#setting-minimum-input-length-requirements%3A-the-minlength-attribute%3Asuffering-from-being-too-short
869        let value_dirty = self.value_dirty.get();
870        let text_input = self.text_input.borrow();
871        let edit_by_user = !text_input.was_last_change_by_set_content();
872
873        if value.is_empty() || !value_dirty || !edit_by_user || !self.does_minmaxlength_apply() {
874            return ValidationFlags::empty();
875        }
876
877        let mut failed_flags = ValidationFlags::empty();
878        let Utf16CodeUnits(value_len) = text_input.len_utf16();
879        let min_length = self.MinLength();
880        let max_length = self.MaxLength();
881
882        if min_length != DEFAULT_MIN_LENGTH && value_len < (min_length as u32) {
883            failed_flags.insert(ValidationFlags::TOO_SHORT);
884        }
885
886        if max_length != DEFAULT_MAX_LENGTH && value_len > (max_length as u32) {
887            failed_flags.insert(ValidationFlags::TOO_LONG);
888        }
889
890        failed_flags
891    }
892
893    /// * <https://html.spec.whatwg.org/multipage/#suffering-from-an-underflow>
894    /// * <https://html.spec.whatwg.org/multipage/#suffering-from-an-overflow>
895    /// * <https://html.spec.whatwg.org/multipage/#suffering-from-a-step-mismatch>
896    fn suffers_from_range_issues(&self, value: &DOMString) -> ValidationFlags {
897        if value.is_empty() || !self.does_value_as_number_apply() {
898            return ValidationFlags::empty();
899        }
900
901        let Some(value_as_number) = self.convert_string_to_number(&value.str()) else {
902            return ValidationFlags::empty();
903        };
904
905        let mut failed_flags = ValidationFlags::empty();
906        let min_value = self.minimum();
907        let max_value = self.maximum();
908
909        // https://html.spec.whatwg.org/multipage/#has-a-reversed-range
910        let has_reversed_range = match (min_value, max_value) {
911            (Some(min), Some(max)) => self.input_type().has_periodic_domain() && min > max,
912            _ => false,
913        };
914
915        if has_reversed_range {
916            // https://html.spec.whatwg.org/multipage/#the-min-and-max-attributes:has-a-reversed-range-3
917            if value_as_number > max_value.unwrap() && value_as_number < min_value.unwrap() {
918                failed_flags.insert(ValidationFlags::RANGE_UNDERFLOW);
919                failed_flags.insert(ValidationFlags::RANGE_OVERFLOW);
920            }
921        } else {
922            // https://html.spec.whatwg.org/multipage/#the-min-and-max-attributes%3Asuffering-from-an-underflow-2
923            if let Some(min_value) = min_value &&
924                value_as_number < min_value
925            {
926                failed_flags.insert(ValidationFlags::RANGE_UNDERFLOW);
927            }
928            // https://html.spec.whatwg.org/multipage/#the-min-and-max-attributes%3Asuffering-from-an-overflow-2
929            if let Some(max_value) = max_value &&
930                value_as_number > max_value
931            {
932                failed_flags.insert(ValidationFlags::RANGE_OVERFLOW);
933            }
934        }
935
936        // https://html.spec.whatwg.org/multipage/#the-step-attribute%3Asuffering-from-a-step-mismatch
937        if let Some(step) = self.allowed_value_step() {
938            // TODO: Spec has some issues here, see https://github.com/whatwg/html/issues/5207.
939            // Chrome and Firefox parse values as decimals to get exact results,
940            // we probably should too.
941            let diff = (self.step_base() - value_as_number) % step / value_as_number;
942            if diff.abs() > 1e-12 {
943                failed_flags.insert(ValidationFlags::STEP_MISMATCH);
944            }
945        }
946
947        failed_flags
948    }
949
950    /// Whether this input type renders as a basic text input widget.
951    pub(crate) fn is_textual_or_password(&self) -> bool {
952        self.is_textual_or_password.get()
953    }
954
955    fn may_have_embedder_control(&self) -> bool {
956        matches!(*self.input_type(), InputType::Color(_)) && !self.is_form_element_disabled()
957    }
958
959    /// Return a string that represents the contents of the element in its displayed shadow DOM.
960    pub(crate) fn value_for_shadow_dom(&self) -> DOMString {
961        let input_type = &*self.input_type();
962        match input_type {
963            InputType::Checkbox(_) |
964            InputType::Radio(_) |
965            InputType::Image(_) |
966            InputType::Hidden(_) |
967            InputType::Range(_) => input_type.as_specific().value_for_shadow_dom(self),
968            _ => {
969                if let Some(attribute_value) = self
970                    .upcast::<Element>()
971                    .get_attribute_string_value(&local_name!("value"))
972                {
973                    return attribute_value.into();
974                }
975                input_type.as_specific().value_for_shadow_dom(self)
976            },
977        }
978    }
979
980    /// <https://w3c.github.io/selection-api/#dfn-schedule-a-selectionchange-event>
981    fn schedule_a_selection_change_event(&self) {
982        // Step 1. If target's has scheduled selectionchange event is true, abort these steps.
983        if self.has_scheduled_selectionchange_event.get() {
984            return;
985        }
986        // Step 2. Set target's has scheduled selectionchange event to true.
987        self.has_scheduled_selectionchange_event.set(true);
988        // Step 3. Queue a task on the user interaction task source to fire a selectionchange event on target.
989        let this = Trusted::new(self);
990        self.owner_global()
991            .task_manager()
992            .user_interaction_task_source()
993            .queue(
994                // https://w3c.github.io/selection-api/#firing-selectionchange-event
995                task!(selectionchange_task_steps: move |cx| {
996                    let this = this.root();
997                    // Step 1. Set target's has scheduled selectionchange event to false.
998                    this.has_scheduled_selectionchange_event.set(false);
999                    // Step 2. If target is an element, fire an event named selectionchange, which bubbles and not cancelable, at target.
1000                    this.upcast::<EventTarget>().fire_event_with_params(
1001                        cx,
1002                        atom!("selectionchange"),
1003                        EventBubbles::Bubbles,
1004                        EventCancelable::NotCancelable,
1005                        EventComposed::Composed,
1006                    );
1007                    // Step 3. Otherwise, if target is a document, fire an event named selectionchange,
1008                    // which does not bubble and not cancelable, at target.
1009                    //
1010                    // n/a
1011                }),
1012            );
1013    }
1014
1015    /// <https://html.spec.whatwg.org/multipage/#input-img-dimensions>
1016    fn dimensions(&self, cx: &mut JSContext) -> (u32, u32) {
1017        // Step 1. If input's type attribute is not in the Image Button state,
1018        // then return a width of 0 and a height of 0. (In that case no image is available.)
1019        let InputType::Image(ref image_input_type) = *self.input_type() else {
1020            return Default::default();
1021        };
1022        // The rest of the steps
1023        image_input_type.dimensions(cx, self)
1024    }
1025
1026    /// <https://html.spec.whatwg.org/multipage/#dom-input-value>
1027    pub(crate) fn set_value(
1028        &self,
1029        cx: &mut JSContext,
1030        mut value: DOMString,
1031        changed_by_user: bool,
1032    ) -> ErrorResult {
1033        match self.value_mode() {
1034            ValueMode::Value => {
1035                {
1036                    // Step 3. Set the element's dirty value flag to true.
1037                    self.value_dirty.set(true);
1038
1039                    // Step 4. Invoke the value sanitization algorithm, if the element's type
1040                    // attribute's current state defines one.
1041                    self.sanitize_value(&mut value);
1042
1043                    let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
1044
1045                    // Step 5. If the element's value (after applying the value sanitization algorithm)
1046                    // is different from oldValue, and the element has a text entry cursor position,
1047                    // move the text entry cursor position to the end of the text control,
1048                    // unselecting any selected text and resetting the selection direction to "none".
1049                    if text_input.get_content() != value {
1050                        // Step 2. Set the element's value to the new value.
1051                        text_input.set_content(value);
1052
1053                        text_input.clear_selection_to_end();
1054                    }
1055                }
1056
1057                // Additionally, update the placeholder shown state in another
1058                // scope to prevent the borrow checker issue. This is normally
1059                // being done in the attributed mutated.
1060                self.update_placeholder_shown_state(cx.no_gc());
1061                self.maybe_update_shared_selection();
1062            },
1063            ValueMode::Default | ValueMode::DefaultOn => {
1064                self.upcast::<Element>()
1065                    .set_string_attribute(cx, &local_name!("value"), value);
1066            },
1067            ValueMode::Filename => {
1068                if value.is_empty() {
1069                    let window = self.owner_window();
1070                    let fl = FileList::new(cx, &window, vec![]);
1071                    self.input_type().as_specific().set_files(&fl)
1072                } else {
1073                    return Err(Error::InvalidState(Some(
1074                        "Non-empty value provided for filename".into(),
1075                    )));
1076                }
1077            },
1078        }
1079
1080        self.value_changed(cx, changed_by_user);
1081        self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
1082        Ok(())
1083    }
1084
1085    /// <https://html.spec.whatwg.org/multipage/#dom-input-checked>
1086    pub(crate) fn set_checked(&self, cx: &mut JSContext, checked: bool, changed_by_user: bool) {
1087        self.update_checkedness(cx, checked, true);
1088        self.value_changed(cx, changed_by_user);
1089    }
1090}
1091
1092impl<'dom> LayoutDom<'dom, HTMLInputElement> {
1093    /// Textual input, specifically text entry and domain specific input has
1094    /// a default preferred size.
1095    ///
1096    /// <https://html.spec.whatwg.org/multipage/#the-input-element-as-a-text-entry-widget>
1097    /// <https://html.spec.whatwg.org/multipage/#the-input-element-as-domain-specific-widgets>
1098    // FIXME(stevennovaryo): Implement the calculation of default preferred size
1099    //                       for domain specific input widgets correctly.
1100    // FIXME(#4378): Implement the calculation of average character width for
1101    //               textual input correctly.
1102    pub(crate) fn size_for_layout(self) -> u32 {
1103        self.unsafe_get().size.get()
1104    }
1105
1106    pub(crate) fn selection_for_layout(self) -> Option<RangeAny<Utf32CodeUnits>> {
1107        let element = self.unsafe_get();
1108        if !element.is_textual_or_password.get() {
1109            return None;
1110        }
1111        let text_input = element.text_input.borrow_mut();
1112        text_input.selection_for_layout
1113    }
1114
1115    pub(crate) fn width(self) -> LengthOrPercentageOrAuto {
1116        self.image_button_dimension(&local_name!("width"))
1117    }
1118
1119    pub(crate) fn height(self) -> LengthOrPercentageOrAuto {
1120        self.image_button_dimension(&local_name!("height"))
1121    }
1122
1123    pub(crate) fn margin_right_left(self) -> LengthOrPercentageOrAuto {
1124        self.image_button_dimension(&local_name!("hspace"))
1125    }
1126
1127    pub(crate) fn margin_top_bottom(self) -> LengthOrPercentageOrAuto {
1128        self.image_button_dimension(&local_name!("vspace"))
1129    }
1130
1131    fn image_button_dimension(self, name: &LocalName) -> LengthOrPercentageOrAuto {
1132        let element = self.upcast::<Element>();
1133        let is_image_button = element
1134            .get_attr_val_for_layout(&ns!(), &local_name!("type"))
1135            .is_some_and(|value| value.eq_ignore_ascii_case("image"));
1136
1137        if !is_image_button {
1138            return LengthOrPercentageOrAuto::Auto;
1139        }
1140
1141        element
1142            .get_attr_for_layout(&ns!(), name)
1143            .map(AttrValue::as_dimension)
1144            .cloned()
1145            .unwrap_or(LengthOrPercentageOrAuto::Auto)
1146    }
1147}
1148
1149impl TextControlElement for HTMLInputElement {
1150    fn as_element(&self) -> &Element {
1151        self.upcast()
1152    }
1153
1154    fn text_input(&self) -> AtomicRef<'_, TextInput<EmbedderClipboardProvider>> {
1155        self.text_input.borrow()
1156    }
1157
1158    fn text_input_mut(&self) -> AtomicRefMut<'_, TextInput<EmbedderClipboardProvider>> {
1159        self.text_input.borrow_mut()
1160    }
1161
1162    /// <https://html.spec.whatwg.org/multipage/#concept-input-apply>
1163    fn selection_api_applies(&self) -> bool {
1164        matches!(
1165            *self.input_type(),
1166            InputType::Text(_) |
1167                InputType::Search(_) |
1168                InputType::Url(_) |
1169                InputType::Tel(_) |
1170                InputType::Password(_)
1171        )
1172    }
1173
1174    // https://html.spec.whatwg.org/multipage/#concept-input-apply
1175    //
1176    // Defines input types to which the select() IDL method applies. These are a superset of the
1177    // types for which selection_api_applies() returns true.
1178    //
1179    // Types omitted which could theoretically be included if they were
1180    // rendered as a text control: file
1181    fn has_selectable_text(&self) -> bool {
1182        self.is_textual_or_password() && !self.text_input.borrow().get_content().is_empty()
1183    }
1184
1185    fn has_uncollapsed_selection(&self) -> bool {
1186        self.text_input.borrow().has_uncollapsed_selection()
1187    }
1188
1189    fn set_dirty_value_flag(&self, value: bool) {
1190        self.value_dirty.set(value)
1191    }
1192
1193    fn select_all(&self) {
1194        self.text_input.borrow_mut().select_all();
1195        self.maybe_update_shared_selection();
1196    }
1197
1198    fn maybe_update_shared_selection(&self) {
1199        let selection = {
1200            let mut text_input = self.text_input.borrow_mut();
1201            let selection_range = text_input.selection_start()..text_input.selection_end();
1202            let enabled = self.is_textual_or_password() && self.upcast::<Element>().focus_state();
1203
1204            let range_remained_equal = selection_range == text_input.previous_selection_range;
1205            if range_remained_equal && enabled == text_input.selection_for_layout.is_some() {
1206                return;
1207            }
1208
1209            if !range_remained_equal {
1210                // https://w3c.github.io/selection-api/#selectionchange-event
1211                // > When an input or textarea element provide a text selection and its selection changes
1212                // > (in either extent or direction),
1213                // > the user agent must schedule a selectionchange event on the element.
1214                self.schedule_a_selection_change_event();
1215            }
1216
1217            let selection = enabled.then(|| text_input.sorted_selection_character_offsets_range());
1218            text_input.previous_selection_range = selection_range;
1219            text_input.selection_for_layout = selection;
1220            selection
1221        };
1222
1223        // If an already laid out text run exists, we only need to repaint. If it doesn't
1224        // exist (or the layout box is for different element type), it indicates that
1225        // layout is not up-to-date and layout will get the selection value from the DOM
1226        // when it rebuilds the box tree.
1227        if let Some(text_input_widget) = self.input_type.borrow().as_specific().text_input_widget() &&
1228            text_input_widget.borrow().set_text_run_selection(selection)
1229        {
1230            self.owner_window().layout().set_needs_new_display_list();
1231        }
1232    }
1233
1234    fn is_password_field(&self) -> bool {
1235        matches!(*self.input_type(), InputType::Password(_))
1236    }
1237
1238    fn placeholder_text<'a>(&'a self) -> Ref<'a, TracedDOMString> {
1239        self.placeholder.borrow()
1240    }
1241
1242    fn value_text(&self) -> DOMString {
1243        self.Value()
1244    }
1245
1246    fn is_read_only_or_disabled(&self) -> bool {
1247        self.is_readonly() || self.is_form_element_disabled()
1248    }
1249
1250    fn handle_text_content_changed(&self, cx: &mut JSContext) {
1251        self.update_placeholder_shown_state(cx.no_gc());
1252        self.upcast::<Node>()
1253            .dirty(cx.no_gc(), NodeDamage::ContentOrHeritage);
1254    }
1255
1256    fn handle_key_reaction(&self, cx: &mut JSContext, action: KeyReaction) {
1257        match action {
1258            KeyReaction::TriggerDefaultAction => {
1259                self.implicit_submission(cx);
1260            },
1261            KeyReaction::DispatchInput(text, input_type) => {
1262                self.queue_input_event(text, input_type);
1263                self.value_dirty.set(true);
1264                self.update_placeholder_shown_state(cx.no_gc());
1265                self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
1266                self.maybe_update_shared_selection();
1267            },
1268            KeyReaction::RedrawSelection => {
1269                self.maybe_update_shared_selection();
1270            },
1271            KeyReaction::Nothing => (),
1272        }
1273    }
1274}
1275
1276impl HTMLInputElementMethods<crate::DomTypeHolder> for HTMLInputElement {
1277    // https://html.spec.whatwg.org/multipage/#dom-input-accept
1278    make_getter!(Accept, "accept");
1279
1280    // https://html.spec.whatwg.org/multipage/#dom-input-accept
1281    make_setter!(SetAccept, "accept");
1282
1283    // https://html.spec.whatwg.org/multipage/#dom-input-alpha
1284    make_bool_getter!(Alpha, "alpha");
1285
1286    // https://html.spec.whatwg.org/multipage/#dom-input-alpha
1287    make_bool_setter!(SetAlpha, "alpha");
1288
1289    // https://html.spec.whatwg.org/multipage/#dom-input-alt
1290    make_getter!(Alt, "alt");
1291
1292    // https://html.spec.whatwg.org/multipage/#dom-input-alt
1293    make_setter!(SetAlt, "alt");
1294
1295    // https://html.spec.whatwg.org/multipage/#dom-input-dirName
1296    make_getter!(DirName, "dirname");
1297
1298    // https://html.spec.whatwg.org/multipage/#dom-input-dirName
1299    make_setter!(SetDirName, "dirname");
1300
1301    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
1302    make_bool_getter!(Disabled, "disabled");
1303
1304    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
1305    make_bool_setter!(SetDisabled, "disabled");
1306
1307    /// <https://html.spec.whatwg.org/multipage/#dom-input-width>
1308    fn Width(&self, cx: &mut JSContext) -> u32 {
1309        // > The width and height getter steps are to return the
1310        // > respective component of the result of determining the dimensions of this.
1311        self.dimensions(cx).0
1312    }
1313
1314    // <https://html.spec.whatwg.org/multipage/#dom-input-width>
1315    make_dimension_uint_setter!(SetWidth, "width");
1316
1317    // <https://html.spec.whatwg.org/multipage/#dom-input-height>
1318    fn Height(&self, cx: &mut JSContext) -> u32 {
1319        // > The width and height getter steps are to return the
1320        // > respective component of the result of determining the dimensions of this.
1321        self.dimensions(cx).1
1322    }
1323    // <https://html.spec.whatwg.org/multipage/#dom-input-height>
1324    make_dimension_uint_setter!(SetHeight, "height");
1325
1326    // https://html.spec.whatwg.org/multipage/#dom-input-hspace
1327    make_dimension_uint_getter!(Hspace, "hspace");
1328    // https://html.spec.whatwg.org/multipage/#dom-input-hspace
1329    make_dimension_uint_setter!(SetHspace, "hspace");
1330
1331    // https://html.spec.whatwg.org/multipage/#dom-input-vspace
1332    make_dimension_uint_getter!(Vspace, "vspace");
1333    // https://html.spec.whatwg.org/multipage/#dom-input-vspace
1334    make_dimension_uint_setter!(SetVspace, "vspace");
1335
1336    /// <https://html.spec.whatwg.org/multipage/#dom-fae-form>
1337    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
1338        self.form_owner()
1339    }
1340
1341    /// <https://html.spec.whatwg.org/multipage/#dom-input-files>
1342    fn GetFiles(&self) -> Option<DomRoot<FileList>> {
1343        self.input_type()
1344            .as_specific()
1345            .get_files()
1346            .as_ref()
1347            .cloned()
1348    }
1349
1350    /// <https://html.spec.whatwg.org/multipage/#dom-input-files>
1351    fn SetFiles(&self, _cx: &mut JSContext, files: Option<&FileList>) {
1352        if let Some(files) = files {
1353            self.input_type().as_specific().set_files(files)
1354        }
1355    }
1356
1357    // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
1358    make_bool_getter!(DefaultChecked, "checked");
1359
1360    // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
1361    make_bool_setter!(SetDefaultChecked, "checked");
1362
1363    /// <https://html.spec.whatwg.org/multipage/#dom-input-checked>
1364    fn Checked(&self) -> bool {
1365        self.checkedness.get()
1366    }
1367
1368    /// <https://html.spec.whatwg.org/multipage/#dom-input-checked>
1369    fn SetChecked(&self, cx: &mut JSContext, checked: bool) {
1370        self.set_checked(cx, checked, false);
1371    }
1372
1373    // https://html.spec.whatwg.org/multipage/#attr-input-colorspace
1374    make_enumerated_getter!(
1375        ColorSpace,
1376        "colorspace",
1377        "limited-srgb" | "display-p3",
1378        missing => "limited-srgb",
1379        invalid => "limited-srgb"
1380    );
1381
1382    // https://html.spec.whatwg.org/multipage/#attr-input-colorspace
1383    make_setter!(SetColorSpace, "colorspace");
1384
1385    // https://html.spec.whatwg.org/multipage/#dom-input-readonly
1386    make_bool_getter!(ReadOnly, "readonly");
1387
1388    // https://html.spec.whatwg.org/multipage/#dom-input-readonly
1389    make_bool_setter!(SetReadOnly, "readonly");
1390
1391    // https://html.spec.whatwg.org/multipage/#dom-input-size
1392    make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE);
1393
1394    // https://html.spec.whatwg.org/multipage/#dom-input-size
1395    make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE);
1396
1397    /// <https://html.spec.whatwg.org/multipage/#dom-input-type>
1398    fn Type(&self) -> DOMString {
1399        DOMString::from(self.input_type().as_str())
1400    }
1401
1402    // https://html.spec.whatwg.org/multipage/#dom-input-type
1403    make_atomic_setter!(SetType, "type");
1404
1405    /// <https://html.spec.whatwg.org/multipage/#dom-input-value>
1406    fn Value(&self) -> DOMString {
1407        match self.value_mode() {
1408            ValueMode::Value => self.text_input.borrow().get_content(),
1409            ValueMode::Default => self
1410                .upcast::<Element>()
1411                .get_attribute_string_value(&local_name!("value"))
1412                .map(|value| value.into())
1413                .unwrap_or_default(),
1414            ValueMode::DefaultOn => self
1415                .upcast::<Element>()
1416                .get_attribute_string_value(&local_name!("value"))
1417                .map(|value| value.into())
1418                .unwrap_or(DOMString::from_static("on")),
1419            ValueMode::Filename => {
1420                let mut path = DOMString::new();
1421                match self.input_type().as_specific().get_files() {
1422                    Some(ref fl) => match fl.Item(0) {
1423                        Some(ref f) => {
1424                            path.push_str("C:\\fakepath\\");
1425                            path.push_str(&f.name().str());
1426                            path
1427                        },
1428                        None => path,
1429                    },
1430                    None => path,
1431                }
1432            },
1433        }
1434    }
1435
1436    /// <https://html.spec.whatwg.org/multipage/#dom-input-value>
1437    fn SetValue(&self, cx: &mut JSContext, value: DOMString) -> ErrorResult {
1438        self.set_value(cx, value, false)
1439    }
1440
1441    // https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
1442    make_getter!(DefaultValue, "value");
1443
1444    // https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
1445    make_setter!(SetDefaultValue, "value");
1446
1447    // https://html.spec.whatwg.org/multipage/#dom-input-min
1448    make_getter!(Min, "min");
1449
1450    // https://html.spec.whatwg.org/multipage/#dom-input-min
1451    make_setter!(SetMin, "min");
1452
1453    /// <https://html.spec.whatwg.org/multipage/#dom-input-list>
1454    fn GetList(&self) -> Option<DomRoot<HTMLDataListElement>> {
1455        self.suggestions_source_element()
1456    }
1457
1458    /// <https://html.spec.whatwg.org/multipage/#dom-input-valueasdate>
1459    #[expect(unsafe_code)]
1460    fn GetValueAsDate(&self, cx: &mut JSContext, mut return_value: MutableHandleObject) {
1461        if let Some(date_time) = self
1462            .input_type()
1463            .as_specific()
1464            .convert_string_to_naive_datetime(self.Value())
1465        {
1466            let time = ClippedTime {
1467                t: (date_time - OffsetDateTime::UNIX_EPOCH).whole_milliseconds() as f64,
1468            };
1469            return_value.set(unsafe { NewDateObject(cx, time) });
1470        }
1471    }
1472
1473    /// <https://html.spec.whatwg.org/multipage/#dom-input-valueasdate>
1474    #[expect(unsafe_code)]
1475    fn SetValueAsDate(&self, cx: &mut JSContext, value: *mut JSObject) -> ErrorResult {
1476        rooted!(&in(cx) let value = value);
1477        if !self.does_value_as_date_apply() {
1478            return Err(Error::InvalidState(Some(
1479                "Input element cannot be treated as a date".into(),
1480            )));
1481        }
1482        if value.is_null() {
1483            return self.SetValue(cx, DOMString::new());
1484        }
1485        let mut msecs: f64 = 0.0;
1486        // We need to go through unsafe code to interrogate jsapi about a Date.
1487        // To minimize the amount of unsafe code to maintain, this just gets the milliseconds,
1488        // which we then reinflate into a NaiveDate for use in safe code.
1489        unsafe {
1490            let mut is_date = false;
1491            if !ObjectIsDate(cx, value.handle(), &mut is_date) {
1492                return Err(Error::JSFailed);
1493            }
1494            if !is_date {
1495                return Err(Error::Type(c"Value was not a date".to_owned()));
1496            }
1497            if !DateGetMsecSinceEpoch(cx, value.handle(), &mut msecs) {
1498                return Err(Error::JSFailed);
1499            }
1500            if !msecs.is_finite() {
1501                return self.SetValue(cx, DOMString::new());
1502            }
1503        }
1504
1505        let Ok(date_time) = OffsetDateTime::from_unix_timestamp_nanos((msecs * 1e6) as i128) else {
1506            return self.SetValue(cx, DOMString::new());
1507        };
1508        self.SetValue(
1509            cx,
1510            self.input_type()
1511                .as_specific()
1512                .convert_datetime_to_dom_string(date_time),
1513        )
1514    }
1515
1516    /// <https://html.spec.whatwg.org/multipage/#dom-input-valueasnumber>
1517    fn ValueAsNumber(&self) -> f64 {
1518        self.convert_string_to_number(&self.Value().str())
1519            .unwrap_or(f64::NAN)
1520    }
1521
1522    /// <https://html.spec.whatwg.org/multipage/#dom-input-valueasnumber>
1523    fn SetValueAsNumber(&self, cx: &mut JSContext, value: f64) -> ErrorResult {
1524        if value.is_infinite() {
1525            Err(Error::Type(c"value is not finite".to_owned()))
1526        } else if !self.does_value_as_number_apply() {
1527            Err(Error::InvalidState(Some(
1528                "Input element value cannot be treated as a number".into(),
1529            )))
1530        } else if value.is_nan() {
1531            self.SetValue(cx, DOMString::new())
1532        } else if let Some(converted) = self.convert_number_to_string(value) {
1533            self.SetValue(cx, converted)
1534        } else {
1535            // The most literal spec-compliant implementation would use bignum types so
1536            // overflow is impossible, but just setting an overflow to the empty string
1537            // matches Firefox's behavior. For example, try input.valueAsNumber=1e30 on
1538            // a type="date" input.
1539            self.SetValue(cx, DOMString::new())
1540        }
1541    }
1542
1543    // https://html.spec.whatwg.org/multipage/#attr-fe-name
1544    make_getter!(Name, "name");
1545
1546    // https://html.spec.whatwg.org/multipage/#attr-fe-name
1547    make_atomic_setter!(SetName, "name");
1548
1549    // https://html.spec.whatwg.org/multipage/#dom-input-placeholder
1550    make_getter!(Placeholder, "placeholder");
1551
1552    // https://html.spec.whatwg.org/multipage/#dom-input-placeholder
1553    make_setter!(SetPlaceholder, "placeholder");
1554
1555    // https://html.spec.whatwg.org/multipage/#dom-input-formaction
1556    make_form_action_getter!(FormAction, "formaction");
1557
1558    // https://html.spec.whatwg.org/multipage/#dom-input-formaction
1559    make_setter!(SetFormAction, "formaction");
1560
1561    // https://html.spec.whatwg.org/multipage/#dom-fs-formenctype
1562    make_enumerated_getter!(
1563        FormEnctype,
1564        "formenctype",
1565        "application/x-www-form-urlencoded" | "text/plain" | "multipart/form-data",
1566        invalid => "application/x-www-form-urlencoded"
1567    );
1568
1569    // https://html.spec.whatwg.org/multipage/#dom-input-formenctype
1570    make_setter!(SetFormEnctype, "formenctype");
1571
1572    // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod
1573    make_enumerated_getter!(
1574        FormMethod,
1575        "formmethod",
1576        "get" | "post" | "dialog",
1577        invalid => "get"
1578    );
1579
1580    // https://html.spec.whatwg.org/multipage/#dom-fs-formmethod
1581    make_setter!(SetFormMethod, "formmethod");
1582
1583    // https://html.spec.whatwg.org/multipage/#dom-input-formtarget
1584    make_getter!(FormTarget, "formtarget");
1585
1586    // https://html.spec.whatwg.org/multipage/#dom-input-formtarget
1587    make_setter!(SetFormTarget, "formtarget");
1588
1589    // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
1590    make_bool_getter!(FormNoValidate, "formnovalidate");
1591
1592    // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
1593    make_bool_setter!(SetFormNoValidate, "formnovalidate");
1594
1595    // https://html.spec.whatwg.org/multipage/#dom-input-max
1596    make_getter!(Max, "max");
1597
1598    // https://html.spec.whatwg.org/multipage/#dom-input-max
1599    make_setter!(SetMax, "max");
1600
1601    // https://html.spec.whatwg.org/multipage/#dom-input-maxlength
1602    make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
1603
1604    // https://html.spec.whatwg.org/multipage/#dom-input-maxlength
1605    make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
1606
1607    // https://html.spec.whatwg.org/multipage/#dom-input-minlength
1608    make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
1609
1610    // https://html.spec.whatwg.org/multipage/#dom-input-minlength
1611    make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
1612
1613    // https://html.spec.whatwg.org/multipage/#dom-input-multiple
1614    make_bool_getter!(Multiple, "multiple");
1615
1616    // https://html.spec.whatwg.org/multipage/#dom-input-multiple
1617    make_bool_setter!(SetMultiple, "multiple");
1618
1619    // https://html.spec.whatwg.org/multipage/#dom-input-pattern
1620    make_getter!(Pattern, "pattern");
1621
1622    // https://html.spec.whatwg.org/multipage/#dom-input-pattern
1623    make_setter!(SetPattern, "pattern");
1624
1625    // https://html.spec.whatwg.org/multipage/#dom-input-required
1626    make_bool_getter!(Required, "required");
1627
1628    // https://html.spec.whatwg.org/multipage/#dom-input-required
1629    make_bool_setter!(SetRequired, "required");
1630
1631    // https://html.spec.whatwg.org/multipage/#dom-input-src
1632    make_url_getter!(Src, "src");
1633
1634    // https://html.spec.whatwg.org/multipage/#dom-input-src
1635    make_url_setter!(SetSrc, "src");
1636
1637    // https://html.spec.whatwg.org/multipage/#dom-input-step
1638    make_getter!(Step, "step");
1639
1640    // https://html.spec.whatwg.org/multipage/#dom-input-step
1641    make_setter!(SetStep, "step");
1642
1643    // https://html.spec.whatwg.org/multipage/#dom-input-usemap
1644    make_getter!(UseMap, "usemap");
1645
1646    // https://html.spec.whatwg.org/multipage/#dom-input-usemap
1647    make_setter!(SetUseMap, "usemap");
1648
1649    // https://html.spec.whatwg.org/multipage/#dom-popovertargetaction
1650    make_enumerated_getter!(
1651        PopoverTargetAction,
1652        "popovertargetaction",
1653        "toggle" | "show" | "hide",
1654        missing => "toggle",
1655        invalid => "toggle"
1656    );
1657
1658    // https://html.spec.whatwg.org/multipage/#dom-popovertargetaction
1659    make_setter!(SetPopoverTargetAction, "popovertargetaction");
1660
1661    /// <https://html.spec.whatwg.org/multipage/#dom-popovertargetelement>
1662    fn GetPopoverTargetElement(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1663        self.upcast::<Element>()
1664            .get_attr_associated_element(cx, &local_name!("popovertarget"))
1665    }
1666
1667    /// <https://html.spec.whatwg.org/multipage/#dom-popovertargetelement>
1668    fn SetPopoverTargetElement(&self, cx: &mut JSContext, value: Option<&Element>) {
1669        self.upcast::<Element>().set_attr_associated_element(
1670            cx,
1671            &local_name!("popovertarget"),
1672            value,
1673        )
1674    }
1675
1676    /// <https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory>
1677    fn Webkitdirectory(&self) -> bool {
1678        self.upcast::<Element>()
1679            .has_attribute(&LocalName::from("webkitdirectory"))
1680    }
1681
1682    /// <https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory>
1683    fn SetWebkitdirectory(&self, cx: &mut JSContext, value: bool) {
1684        self.upcast::<Element>()
1685            .set_bool_attribute(cx, &LocalName::from("webkitdirectory"), value)
1686    }
1687
1688    /// <https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitentries>
1689    fn WebkitEntries(&self, cx: &mut JSContext, retval: MutableHandleValue) {
1690        // Browsers only populate this from a drag-and-drop operation, and leave
1691        // it empty when `webkitdirectory` is set.
1692        // Right now we don't have DnD yet.
1693        // Above behaviour is now the Baseline 2025, tested with Firefox/Chrome.
1694        // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitEntries
1695        // https://wicg.github.io/entries-api/#issue-452f97f6
1696        // https://wicg.github.io/entries-api/#issue-4cc238bb
1697        let entries: Vec<DomRoot<FileSystemEntry>> = Vec::new();
1698        to_frozen_array(cx, &entries, retval);
1699    }
1700
1701    /// <https://html.spec.whatwg.org/multipage/#dom-input-indeterminate>
1702    fn Indeterminate(&self) -> bool {
1703        self.indeterminateness.get()
1704    }
1705
1706    /// <https://html.spec.whatwg.org/multipage/#dom-input-indeterminate>
1707    fn SetIndeterminate(&self, cx: &mut JSContext, val: bool) {
1708        self.indeterminateness.set(val);
1709        self.update_indeterminate_state(cx.no_gc());
1710    }
1711
1712    /// <https://html.spec.whatwg.org/multipage/#dom-lfe-labels>
1713    /// Different from make_labels_getter because this one
1714    /// conditionally returns null.
1715    fn GetLabels(&self, cx: &mut JSContext) -> Option<DomRoot<NodeList>> {
1716        if matches!(*self.input_type(), InputType::Hidden(_)) {
1717            None
1718        } else {
1719            Some(self.labels_node_list.or_init(|| {
1720                NodeList::new_labels_list(
1721                    cx,
1722                    self.upcast::<Node>().owner_doc().window(),
1723                    self.upcast::<HTMLElement>(),
1724                )
1725            }))
1726        }
1727    }
1728
1729    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-select>
1730    fn Select(&self, cx: &mut JSContext) {
1731        self.dom_select(cx);
1732    }
1733
1734    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart>
1735    fn GetSelectionStart(&self) -> Option<u32> {
1736        self.dom_start().map(|start| start.0)
1737    }
1738
1739    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart>
1740    fn SetSelectionStart(&self, _cx: &mut JSContext, start: Option<u32>) -> ErrorResult {
1741        self.set_dom_start(start.map(Utf16CodeUnits::from))
1742    }
1743
1744    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend>
1745    fn GetSelectionEnd(&self) -> Option<u32> {
1746        self.dom_end().map(|end| end.0)
1747    }
1748
1749    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend>
1750    fn SetSelectionEnd(&self, _cx: &mut JSContext, end: Option<u32>) -> ErrorResult {
1751        self.set_dom_end(end.map(Utf16CodeUnits::from))
1752    }
1753
1754    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection>
1755    fn GetSelectionDirection(&self) -> Option<DOMString> {
1756        self.dom_direction()
1757    }
1758
1759    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection>
1760    fn SetSelectionDirection(
1761        &self,
1762        _cx: &mut JSContext,
1763        direction: Option<DOMString>,
1764    ) -> ErrorResult {
1765        self.set_dom_direction(direction)
1766    }
1767
1768    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setselectionrange>
1769    fn SetSelectionRange(&self, start: u32, end: u32, direction: Option<DOMString>) -> ErrorResult {
1770        self.set_dom_range(
1771            Utf16CodeUnits::from(start),
1772            Utf16CodeUnits::from(end),
1773            direction,
1774        )
1775    }
1776
1777    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext>
1778    fn SetRangeText(&self, cx: &mut JSContext, replacement: DOMString) -> ErrorResult {
1779        self.set_dom_range_text(cx, replacement, None, None, Default::default())?;
1780        self.value_changed(cx, false);
1781        Ok(())
1782    }
1783
1784    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext>
1785    fn SetRangeText_(
1786        &self,
1787        cx: &mut JSContext,
1788        replacement: DOMString,
1789        start: u32,
1790        end: u32,
1791        selection_mode: SelectionMode,
1792    ) -> ErrorResult {
1793        self.set_dom_range_text(
1794            cx,
1795            replacement,
1796            Some(Utf16CodeUnits::from(start)),
1797            Some(Utf16CodeUnits::from(end)),
1798            selection_mode,
1799        )?;
1800        self.value_changed(cx, false);
1801        Ok(())
1802    }
1803
1804    /// Select the files based on filepaths passed in, enabled by
1805    /// `dom_testing_html_input_element_select_files_enabled`, used for test purpose.
1806    fn SelectFiles(&self, cx: &mut JSContext, paths: Vec<DOMString>) {
1807        self.input_type()
1808            .as_specific()
1809            .select_files(cx, self, Some(paths));
1810    }
1811
1812    /// <https://html.spec.whatwg.org/multipage/#dom-input-stepup>
1813    fn StepUp(&self, cx: &mut JSContext, n: i32) -> ErrorResult {
1814        self.step_up_or_down(cx, n, StepDirection::Up)
1815    }
1816
1817    /// <https://html.spec.whatwg.org/multipage/#dom-input-stepdown>
1818    fn StepDown(&self, cx: &mut JSContext, n: i32) -> ErrorResult {
1819        self.step_up_or_down(cx, n, StepDirection::Down)
1820    }
1821
1822    /// <https://html.spec.whatwg.org/multipage/#dom-cva-willvalidate>
1823    fn WillValidate(&self, no_gc: &NoGC) -> bool {
1824        self.is_instance_validatable(no_gc)
1825    }
1826
1827    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
1828    fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
1829        self.validity_state(cx)
1830    }
1831
1832    /// <https://html.spec.whatwg.org/multipage/#dom-cva-checkvalidity>
1833    fn CheckValidity(&self, cx: &mut JSContext) -> bool {
1834        self.check_validity(cx)
1835    }
1836
1837    /// <https://html.spec.whatwg.org/multipage/#dom-cva-reportvalidity>
1838    fn ReportValidity(&self, cx: &mut JSContext) -> bool {
1839        self.report_validity(cx)
1840    }
1841
1842    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
1843    fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
1844        self.validation_message(cx)
1845    }
1846
1847    /// <https://html.spec.whatwg.org/multipage/#dom-cva-setcustomvalidity>
1848    fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
1849        self.validity_state(cx).set_custom_error_message(cx, error);
1850    }
1851
1852    /// <https://html.spec.whatwg.org/multipage/#dom-input-showpicker>
1853    fn ShowPicker(&self, cx: &mut JSContext) -> ErrorResult {
1854        // Step 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
1855        if !self.is_mutable() {
1856            return Err(Error::InvalidState(Some(
1857                "Input element is not mutable to show picker".into(),
1858            )));
1859        }
1860
1861        // Step 2. If this's relevant settings object's origin is not same origin with
1862        // this's relevant settings object's top-level origin,
1863        // and this is a select element, or this's type attribute is not in
1864        // the File Upload state or Color state, then throw a "SecurityError" DOMException.
1865        let document = self.owner_document();
1866        if Some(document.origin().immutable()) != document.top_level_origin().as_ref() &&
1867            !matches!(*self.input_type(), InputType::File(_) | InputType::Color(_))
1868        {
1869            return Err(Error::Security(Some(
1870                "Input element cannot show picker for cross-origin iframe".into(),
1871            )));
1872        }
1873
1874        // Step 3. If this's relevant global object does not have transient activation,
1875        // then throw a "NotAllowedError" DOMException.
1876        if !self.owner_window().has_transient_activation() {
1877            return Err(Error::NotAllowed(Some(
1878                "Window does not have transient activation".into(),
1879            )));
1880        }
1881
1882        // Step 4. If this is a select element, and this is not being rendered,
1883        // then throw a "NotSupportedError" DOMException.
1884        //
1885        // n/a, only applies to select element
1886
1887        // Step 5. Show the picker, if applicable, for this.
1888        self.show_the_picker_if_applicable(cx);
1889        Ok(())
1890    }
1891}
1892
1893impl HTMLInputElement {
1894    /// <https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set>
1895    /// Steps range from 5.1 to 5.10 (specific to HTMLInputElement)
1896    pub(crate) fn form_datums(
1897        &self,
1898        submitter: Option<FormSubmitterElement>,
1899        encoding: Option<&'static Encoding>,
1900    ) -> (Vec<FormDatum>, bool) {
1901        let ty = self.Type();
1902        let name = self.Name();
1903        let is_submitter = match submitter {
1904            Some(FormSubmitterElement::Input(s)) => self == s,
1905            _ => false,
1906        };
1907
1908        // 5.1: disabled state check is in get_unclean_dataset
1909        match *self.input_type() {
1910            // Step 5.1: it's a button but it is not submitter.
1911            InputType::Submit(_) | InputType::Button(_) | InputType::Reset(_) if !is_submitter => {
1912                return (vec![], true);
1913            },
1914
1915            // Step 5.1: it's the "Checkbox" or "Radio Button" and whose checkedness is false.
1916            InputType::Radio(_) | InputType::Checkbox(_) if !self.Checked() => {
1917                return (vec![], true);
1918            },
1919            InputType::Image(_) => {
1920                // Step 5.2.1 If the field element is not submitter, then continue.
1921                if !is_submitter {
1922                    return (vec![], true);
1923                }
1924            },
1925            // Step 5.4: If either the field element does not have a name attribute specified, or its name attribute's value is the empty string, then continue.
1926            _ => {
1927                if name.is_empty() {
1928                    return (vec![], true);
1929                }
1930            },
1931        }
1932
1933        let datums = match *self.input_type() {
1934            // Step 5.2: If the field element is an input element whose type attribute is in the Image Button state:
1935            InputType::Image(ref image_input_type) => {
1936                // Step 5.2.2: If the field element has a name attribute specified and its value is not
1937                // the empty string, let name be that value followed by U+002E (.); otherwise, let name
1938                // be the empty string.
1939                // Note: step 5.2.1 is handled above.
1940                let prefix = if name.is_empty() {
1941                    String::new()
1942                } else {
1943                    format!("{name}.")
1944                };
1945
1946                // Step 5.2.3: Let namex be the concatenation of name and "x", and let namey be the
1947                // concatenation of name and "y".
1948                let name_x: DOMString = format!("{prefix}x").into();
1949                let name_y: DOMString = format!("{prefix}y").into();
1950
1951                // Step 5.2.4: The field element's selected coordinate consists of an x-component and a
1952                // y-component. Create an entry with namex and the x-component, and an entry with namey
1953                // and the y-component, and append them to entry list.
1954                let coordinate = image_input_type.selected_coordinate();
1955
1956                vec![
1957                    FormDatum {
1958                        name: name_x,
1959                        ty: ty.clone(),
1960                        value: FormDatumValue::String(coordinate.x.to_string().into()),
1961                    },
1962                    FormDatum {
1963                        name: name_y,
1964                        ty,
1965                        value: FormDatumValue::String(coordinate.y.to_string().into()),
1966                    },
1967                ]
1968            },
1969            // Step 5.7: Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state:
1970            InputType::Checkbox(_) | InputType::Radio(_) => {
1971                // Step 5.7.1: If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".
1972                let field_value = self.Value();
1973                let value = if field_value.is_empty() {
1974                    DOMString::from_static("on")
1975                } else {
1976                    field_value
1977                };
1978                // Step 5.7.2: Create an entry with name and value, and append it to entry list.
1979                vec![FormDatum {
1980                    ty,
1981                    name,
1982                    value: FormDatumValue::String(value),
1983                }]
1984            },
1985
1986            // Step 5.8: Otherwise, if the field element is an input element whose type attribute is in the File Upload state:
1987            InputType::File(_) => {
1988                let mut datums = vec![];
1989
1990                // Step 5.2-5.7
1991                let name = self.Name();
1992
1993                match self.GetFiles() {
1994                    // Step 5.8.1: If there are no selected files, then create an entry with name and a new File object with an empty name, application/octet-stream as type, and an empty body, and append it to entry list.
1995                    None => {
1996                        datums.push(FormDatum {
1997                            // XXX(izgzhen): Spec says 'application/octet-stream' as the type,
1998                            // but this is _type_ of element rather than content right?
1999                            ty,
2000                            name,
2001                            value: FormDatumValue::String(DOMString::new()),
2002                        })
2003                    },
2004                    // Step 5.8.2: Otherwise, for each file in selected files, create an entry with name and a File object representing the file, and append it to entry list.
2005                    Some(fl) => {
2006                        for f in fl.iter_files() {
2007                            datums.push(FormDatum {
2008                                ty: ty.clone(),
2009                                name: name.clone(),
2010                                value: FormDatumValue::File(DomRoot::from_ref(f)),
2011                            });
2012                        }
2013                    },
2014                }
2015
2016                datums
2017            },
2018
2019            // Step 5.9: Otherwise, if the field element is an input element whose type attribute is in the Hidden state and name is an ASCII case-insensitive match for "_charset_":
2020            InputType::Hidden(_) if name.eq_ignore_ascii_case("_charset_") => {
2021                // Step 5.9.1: Let charset be the name of encoding.
2022                let charset = match encoding {
2023                    None => DOMString::from_static("UTF-8"),
2024                    Some(enc) => DOMString::from(enc.name()),
2025                };
2026                // Step 5.9.2: Create an entry with name and charset, and append it to entry list.
2027                vec![FormDatum {
2028                    ty,
2029                    name,
2030                    value: FormDatumValue::String(charset),
2031                }]
2032            },
2033
2034            // Step 5.10: Otherwise, create an entry with name and the value of the field element, and append it to entry list.
2035            _ => vec![FormDatum {
2036                ty,
2037                name,
2038                value: FormDatumValue::String(self.Value()),
2039            }],
2040        };
2041        (datums, false)
2042    }
2043
2044    /// <https://html.spec.whatwg.org/multipage/#radio-button-group>
2045    pub(crate) fn radio_group_name(&self) -> Option<Atom> {
2046        self.upcast::<Element>()
2047            .get_name()
2048            .filter(|name| !name.is_empty())
2049    }
2050
2051    fn update_checkedness(&self, cx: &mut JSContext, checked: bool, dirty: bool) {
2052        let previously_checked = self.checkedness.replace(checked);
2053        self.update_checked_state(cx.no_gc());
2054
2055        if dirty {
2056            self.checked_changed.set(true);
2057        }
2058
2059        self.input_type()
2060            .as_specific()
2061            .update_checkedness(cx, self, checked, previously_checked);
2062
2063        // This explicitly restyles instead of calling `dirty()`. `dirty()` bumps the tree version
2064        // which invalidates live collections. Live collections never depend on checkedness,
2065        // so this is safe and is very important for performance.
2066        if self.upcast::<Node>().is_connected() {
2067            self.upcast::<Element>()
2068                .restyle(cx.no_gc(), NodeDamage::Other);
2069        }
2070    }
2071
2072    /// <https://html.spec.whatwg.org/multipage/#selector-checked>
2073    fn update_checked_state(&self, no_gc: &NoGC) {
2074        // input elements whose type attribute is in the Checkbox state and whose checkedness state is true
2075        // input elements whose type attribute is in the Radio Button state and whose checkedness state is true
2076        let should_checked_state_apply = matches!(
2077            *self.input_type(),
2078            InputType::Checkbox(_) | InputType::Radio(_)
2079        ) && self.Checked();
2080        self.upcast::<Element>().set_state(
2081            no_gc,
2082            ElementState::CHECKED,
2083            should_checked_state_apply,
2084        );
2085    }
2086
2087    /// <https://html.spec.whatwg.org/multipage/#selector-default>
2088    pub(crate) fn update_default_state(&self, is_default_button: bool, no_gc: &NoGC) {
2089        // > The :default pseudo-class must match any element falling into one of the following categories:
2090        // > - Submit buttons that are default buttons of their form owner.
2091        // > - input elements to which the checked attribute applies and that have a checked attribute
2092        let is_default = self.is_submit_button() && is_default_button;
2093        let checked_attribute = matches!(
2094            *self.input_type(),
2095            InputType::Checkbox(_) | InputType::Radio(_)
2096        ) && self
2097            .upcast::<Element>()
2098            .has_attribute(&local_name!("checked"));
2099        self.upcast::<Element>().set_state(
2100            no_gc,
2101            ElementState::DEFAULT,
2102            is_default || checked_attribute,
2103        );
2104    }
2105
2106    /// This updates the default state via the form owner in order to determine if this is the default button.
2107    fn update_default_state_indirectly(&self, no_gc: &NoGC) {
2108        match self.form_owner() {
2109            Some(form) => form.invalidate_default_button(no_gc),
2110            None => self.update_default_state(false, no_gc),
2111        }
2112    }
2113
2114    /// <https://html.spec.whatwg.org/multipage/#selector-indeterminate>
2115    pub(crate) fn update_indeterminate_state(&self, no_gc: &NoGC) {
2116        // > The :indeterminate pseudo-class must match any element falling into one of the following categories:
2117        // > - input elements whose type attribute is in the Checkbox state and whose indeterminateness is true
2118        // > - input elements whose type attribute is in the Radio Button state and whose radio button
2119        // >   group contains no input elements whose checkedness state is true.
2120        let should_indeterminate_state_apply = match *self.input_type() {
2121            InputType::Checkbox(_) => self.Indeterminate(),
2122            InputType::Radio(_) => {
2123                let group = self.radio_group_name();
2124                let form = self.form_owner();
2125                let root = self
2126                    .upcast::<Node>()
2127                    .GetRootNode(&GetRootNodeOptions::empty());
2128                radio_group_iter_unrooted(no_gc, self, group.as_ref(), form.as_deref(), &root)
2129                    .all(|elem| !elem.Checked())
2130            },
2131            _ => false,
2132        };
2133        self.upcast::<Element>().set_state(
2134            no_gc,
2135            ElementState::INDETERMINATE,
2136            should_indeterminate_state_apply,
2137        );
2138    }
2139
2140    /// <https://html.spec.whatwg.org/multipage/#selector-user-valid>
2141    /// <https://html.spec.whatwg.org/multipage/#selector-user-invalid>
2142    pub(crate) fn update_user_valid_state(&self, no_gc: &NoGC) {
2143        if self.user_validity.get() {
2144            let satisfies_constraints =
2145                self.is_instance_validatable(no_gc) && self.satisfies_constraints();
2146            let element = self.upcast::<Element>();
2147            element.set_state(no_gc, ElementState::USER_VALID, satisfies_constraints);
2148            element.set_state(no_gc, ElementState::USER_INVALID, !satisfies_constraints);
2149        } else {
2150            // Avoid computing constraint validation if user validity is false
2151            let element = self.upcast::<Element>();
2152            element.set_state(no_gc, ElementState::USER_VALID, false);
2153            element.set_state(no_gc, ElementState::USER_INVALID, false);
2154        }
2155    }
2156
2157    /// <https://html.spec.whatwg.org/multipage/#concept-fe-mutable>
2158    pub(crate) fn is_mutable(&self) -> bool {
2159        // https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable
2160        // https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable
2161        !self.is_read_only_or_disabled()
2162    }
2163
2164    /// <https://html.spec.whatwg.org/multipage/#concept-input-apply>
2165    /// readonly should only apply to specific input types.
2166    fn is_readonly(&self) -> bool {
2167        self.does_readonly_apply() && self.ReadOnly()
2168    }
2169
2170    /// <https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control>:
2171    ///
2172    /// > The reset algorithm for input elements is to set its user validity, dirty value
2173    /// > flag, and dirty checkedness flag back to false, set the value of the element to
2174    /// > the value of the value content attribute, if there is one, or the empty string
2175    /// > otherwise, set the checkedness of the element to true if the element has a checked
2176    /// > content attribute and false if it does not, empty the list of selected files, and
2177    /// > then invoke the value sanitization algorithm, if the type attribute's current
2178    /// > state defines one.
2179    pub(crate) fn reset(&self, cx: &mut JSContext) {
2180        self.set_user_validity(cx.no_gc(), false);
2181        self.value_dirty.set(false);
2182
2183        // We set the value and sanitize all in one go.
2184        let mut value = self.DefaultValue();
2185        self.sanitize_value(&mut value);
2186        self.text_input
2187            .safe_borrow_mut(cx.no_gc())
2188            .set_content(value);
2189
2190        let input_type = &*self.input_type();
2191        if matches!(input_type, InputType::Radio(_) | InputType::Checkbox(_)) {
2192            self.update_checkedness(cx, self.DefaultChecked(), false);
2193            self.checked_changed.set(false);
2194        }
2195
2196        if matches!(input_type, InputType::File(_)) {
2197            input_type
2198                .as_specific()
2199                .set_files(&FileList::new(cx, &self.owner_window(), vec![]));
2200        }
2201
2202        self.value_changed(cx, false);
2203    }
2204
2205    /// <https://w3c.github.io/webdriver/#ref-for-dfn-clear-algorithm-3>
2206    /// Used by WebDriver to clear the input element.
2207    pub(crate) fn clear(&self, cx: &mut JSContext) {
2208        // Step 1. Reset dirty value and dirty checkedness flags.
2209        self.value_dirty.set(false);
2210        self.checked_changed.set(false);
2211        // Step 2. Set value to empty string.
2212        self.text_input
2213            .safe_borrow_mut(cx.no_gc())
2214            .set_content(DOMString::new());
2215        // Step 3. Set checkedness based on presence of content attribute.
2216        self.update_checkedness(cx, self.DefaultChecked(), false);
2217        // Step 4. Empty selected files
2218        if self.input_type().as_specific().get_files().is_some() {
2219            let window = self.owner_window();
2220            let filelist = FileList::new(cx, &window, vec![]);
2221            self.input_type().as_specific().set_files(&filelist);
2222        }
2223
2224        // Step 5. Invoke the value sanitization algorithm iff the type attribute's
2225        // current state defines one.
2226        {
2227            let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
2228            let mut value = text_input.get_content();
2229            self.sanitize_value(&mut value);
2230            text_input.set_content(value);
2231        }
2232
2233        self.value_changed(cx, false);
2234    }
2235
2236    fn update_placeholder_shown_state(&self, no_gc: &NoGC) {
2237        if !self.input_type().is_textual_or_password() {
2238            self.upcast::<Element>()
2239                .set_placeholder_shown_state(no_gc, false);
2240        } else {
2241            let has_placeholder = !self.placeholder.borrow().is_empty();
2242            let has_value = !self.text_input.borrow().is_empty();
2243            self.upcast::<Element>()
2244                .set_placeholder_shown_state(no_gc, has_placeholder && !has_value);
2245        }
2246    }
2247
2248    pub(crate) fn select_files_for_webdriver(
2249        &self,
2250        cx: &mut JSContext,
2251        test_paths: Vec<DOMString>,
2252        response_sender: GenericSender<Result<bool, ErrorStatus>>,
2253    ) {
2254        let mut stored_sender = self.pending_webdriver_response.borrow_mut();
2255        assert!(stored_sender.is_none());
2256
2257        *stored_sender = Some(Box::new(PendingWebDriverResponse {
2258            response_sender,
2259            expected_file_count: test_paths.len(),
2260        }));
2261
2262        self.input_type()
2263            .as_specific()
2264            .select_files(cx, self, Some(test_paths));
2265    }
2266
2267    pub(crate) fn take_pending_webdriver_response(&self) -> Option<Box<PendingWebDriverResponse>> {
2268        self.pending_webdriver_response.borrow_mut().take()
2269    }
2270
2271    /// <https://html.spec.whatwg.org/multipage/#value-sanitization-algorithm>
2272    fn sanitize_value(&self, value: &mut DOMString) {
2273        self.input_type().as_specific().sanitize_value(self, value);
2274    }
2275
2276    /// <https://html.spec.whatwg.org/multipage/#implicit-submission>
2277    fn implicit_submission(&self, cx: &mut JSContext) {
2278        let doc = self.owner_document();
2279        let node = doc.upcast::<Node>();
2280        let owner = self.form_owner();
2281        let form = match owner {
2282            None => return,
2283            Some(ref f) => f,
2284        };
2285
2286        if self.upcast::<Element>().click_in_progress() {
2287            return;
2288        }
2289        match form.default_button() {
2290            Some(ref button) => {
2291                if button
2292                    .as_maybe_activatable()
2293                    .is_some_and(|button| button.is_instance_activatable())
2294                {
2295                    // spec does not actually say to set the not trusted flag,
2296                    // but we can get here from synthetic keydown events
2297                    button
2298                        .upcast::<Node>()
2299                        .fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
2300                }
2301            },
2302            None => {
2303                let mut inputs = node
2304                    .traverse_preorder(ShadowIncluding::No)
2305                    .filter_map(DomRoot::downcast::<HTMLInputElement>)
2306                    .filter(|input| {
2307                        input.form_owner() == owner &&
2308                            matches!(
2309                                *input.input_type(),
2310                                InputType::Text(_) |
2311                                    InputType::Search(_) |
2312                                    InputType::Url(_) |
2313                                    InputType::Tel(_) |
2314                                    InputType::Email(_) |
2315                                    InputType::Password(_) |
2316                                    InputType::Date(_) |
2317                                    InputType::Month(_) |
2318                                    InputType::Week(_) |
2319                                    InputType::Time(_) |
2320                                    InputType::DatetimeLocal(_) |
2321                                    InputType::Number(_)
2322                            )
2323                    });
2324
2325                if inputs.nth(1).is_some() {
2326                    // lazily test for > 1 submission-blocking inputs
2327                    return;
2328                }
2329
2330                form.submit(
2331                    cx,
2332                    SubmittedFrom::NotFromForm,
2333                    FormSubmitterElement::Form(form),
2334                );
2335            },
2336        }
2337    }
2338
2339    /// <https://html.spec.whatwg.org/multipage/#concept-input-value-string-number>
2340    pub(crate) fn convert_string_to_number(&self, value: &str) -> Option<f64> {
2341        self.input_type()
2342            .as_specific()
2343            .convert_string_to_number(value)
2344    }
2345
2346    /// <https://html.spec.whatwg.org/multipage/#concept-input-value-string-number>
2347    fn convert_number_to_string(&self, value: f64) -> Option<DOMString> {
2348        self.input_type()
2349            .as_specific()
2350            .convert_number_to_string(value)
2351    }
2352
2353    fn update_related_validity_states(&self, cx: &mut JSContext) {
2354        match *self.input_type() {
2355            InputType::Radio(_) => {
2356                perform_radio_group_validation(cx, self, self.radio_group_name().as_ref())
2357            },
2358            _ => {
2359                self.validity_state(cx)
2360                    .perform_validation_and_update(cx, ValidationFlags::all());
2361            },
2362        }
2363        self.update_user_valid_state(cx.no_gc());
2364    }
2365
2366    fn value_changed(&self, cx: &mut JSContext, changed_by_user: bool) {
2367        self.changed_by_user_while_focused
2368            .set(changed_by_user && self.upcast::<Element>().focus_state());
2369        self.maybe_update_shared_selection();
2370        self.update_related_validity_states(cx);
2371        if self.upcast::<Node>().is_connected() {
2372            self.input_type().as_specific().update_shadow_tree(cx, self);
2373        }
2374    }
2375
2376    /// Fire the events a value change asks for, in spec order.
2377    ///
2378    /// Shared function for the "fire `input`, then fire `change`" pair that several input
2379    /// types need after a user interaction changed this element's value.
2380    pub(crate) fn fire_value_change_events(&self, cx: &mut JSContext, events: ValueChangeEvents) {
2381        let target = self.upcast::<EventTarget>();
2382
2383        // Fire an event named input at the element with the bubbles and composed attributes
2384        // initialized to true.
2385        if events.contains(ValueChangeEvents::Input) {
2386            target.fire_event_with_params(
2387                cx,
2388                atom!("input"),
2389                EventBubbles::Bubbles,
2390                EventCancelable::NotCancelable,
2391                EventComposed::Composed,
2392            );
2393        }
2394
2395        // Fire an event named change at the element with the bubbles attribute initialized
2396        // to true.
2397        if events.contains(ValueChangeEvents::Change) {
2398            target.fire_bubbling_event(cx, atom!("change"));
2399        }
2400    }
2401
2402    /// <https://html.spec.whatwg.org/multipage/#show-the-picker,-if-applicable>
2403    pub(crate) fn show_the_picker_if_applicable(&self, cx: &mut JSContext) {
2404        // Step 1. If element's relevant global object does not have transient activation,
2405        // then return.
2406        let window = self.owner_window();
2407        if !window.has_transient_activation() {
2408            return;
2409        }
2410
2411        // Step 2. If element is not mutable, then return.
2412        if !self.is_mutable() {
2413            return;
2414        }
2415
2416        // Step 3. Consume user activation given element's relevant global object.
2417        window.consume_user_activation();
2418
2419        // Step 4. If element does not support a picker, then return.
2420        //
2421        // Not applicable, that's handled by `self.input_type().as_specific()`
2422
2423        // Step 5. If element is an input element and element's type attribute is in the File Upload state,
2424        // then run these steps in parallel:
2425        // TODO: Implement steps regarding asking for permission
2426
2427        // Step 6. Otherwise, the user agent should show the relevant
2428        // user interface for selecting a value for element,
2429        // in the way it normally would when the user interacts with the control.
2430        self.input_type()
2431            .as_specific()
2432            .show_the_picker_if_applicable(cx, self);
2433    }
2434
2435    pub(crate) fn handle_color_picker_response(
2436        &self,
2437        cx: &mut JSContext,
2438        response: Option<RgbColor>,
2439    ) {
2440        if let InputType::Color(ref color_input_type) = *self.input_type() {
2441            color_input_type.handle_color_picker_response(cx, self, response)
2442        }
2443    }
2444
2445    pub(crate) fn handle_file_picker_response(
2446        &self,
2447        cx: &mut JSContext,
2448        response: Option<Vec<SelectedFile>>,
2449    ) {
2450        if let InputType::File(ref file_input_type) = *self.input_type() {
2451            file_input_type.handle_file_picker_response(cx, self, response)
2452        }
2453    }
2454
2455    fn handle_focus_event(&self, cx: &mut JSContext, event: &FocusEvent) {
2456        let event_type = event.upcast::<Event>().type_();
2457        let document = self.owner_document();
2458
2459        // This hides the control if the input element has lost focus, but doesn't do this for
2460        // file selection dialogs, which are often modal dialogs that may be represented as
2461        // separate windows.
2462        if *event_type == *"blur" && !matches!(&*self.input_type(), InputType::File(..)) {
2463            document
2464                .embedder_controls()
2465                .hide_embedder_control_for_element(self.upcast());
2466        } else if *event_type == *"focus" {
2467            let input_type = &*self.input_type();
2468            let Ok(input_method_type) = input_type.try_into() else {
2469                return;
2470            };
2471
2472            // If there is a Document selection collapse it. This isn't really specified
2473            // and there are quite a few open specification issues about the interaction
2474            // of input and Document selection:
2475            // See <https://github.com/w3c/selection-api/issues/83>.
2476            if self.is_textual_or_password() &&
2477                let Some(selection) = document.selection()
2478            {
2479                let _ = selection.Collapse(cx, None, 0);
2480            }
2481
2482            document.embedder_controls().show_embedder_control(
2483                cx,
2484                ControlElement::Ime(Dom::from_ref(self.upcast())),
2485                EmbedderControlRequest::InputMethod(InputMethodRequest {
2486                    input_method_type,
2487                    text: String::from(self.Value()),
2488                    insertion_point: self.GetSelectionEnd(),
2489                    multiline: false,
2490                    // We follow chromium's heuristic to show the virtual keyboard only if user had interacted before.
2491                    allow_virtual_keyboard: self.owner_window().has_sticky_activation(),
2492                }),
2493                None,
2494            );
2495        }
2496    }
2497
2498    /// <https://html.spec.whatwg.org/multipage/#concept-fe-disabled>
2499    /// <https://html.spec.whatwg.org/multipage/#concept-element-disabled>
2500    pub(crate) fn is_form_element_disabled(&self) -> bool {
2501        // For input elements, the form element disabled concept is aligned with the disabled state.
2502        self.upcast::<Element>()
2503            .state()
2504            .contains(ElementState::DISABLED)
2505    }
2506
2507    pub(crate) fn disabled_state_changed(&self, cx: &mut JSContext) {
2508        if self.input_type().is_textual() {
2509            let read_write = !self.is_read_only_or_disabled();
2510            self.upcast::<Element>()
2511                .set_read_write_state(cx.no_gc(), read_write);
2512        }
2513
2514        if matches!(*self.input_type(), InputType::File(_)) && self.upcast::<Node>().is_connected()
2515        {
2516            self.input_type().as_specific().update_shadow_tree(cx, self);
2517        }
2518    }
2519}
2520
2521impl VirtualMethods for HTMLInputElement {
2522    fn super_type(&self) -> Option<&dyn VirtualMethods> {
2523        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
2524    }
2525
2526    fn attribute_mutated(
2527        &self,
2528        cx: &mut JSContext,
2529        attr: AttrRef<'_>,
2530        mutation: AttributeMutation,
2531    ) {
2532        let could_have_had_embedder_control = self.may_have_embedder_control();
2533
2534        self.super_type()
2535            .unwrap()
2536            .attribute_mutated(cx, attr, mutation);
2537
2538        match *attr.local_name() {
2539            local_name!("checked") => {
2540                if !self.checked_changed.get() {
2541                    let checked_state = match mutation {
2542                        AttributeMutation::Set(None) => true,
2543                        AttributeMutation::Set(Some(_)) => {
2544                            // Input was already checked before.
2545                            return;
2546                        },
2547                        AttributeMutation::Removed => false,
2548                    };
2549                    self.update_checkedness(cx, checked_state, false);
2550                }
2551                self.update_default_state_indirectly(cx.no_gc());
2552            },
2553            local_name!("min") | local_name!("max") => {
2554                self.validity_state(cx)
2555                    .perform_validation_and_update(cx, ValidationFlags::all());
2556            },
2557            local_name!("size") => {
2558                let size = mutation.new_value(attr).map(|value| value.as_uint());
2559                self.size.set(size.unwrap_or(DEFAULT_INPUT_SIZE));
2560            },
2561            local_name!("type") => {
2562                let element = self.upcast::<Element>();
2563
2564                match mutation {
2565                    AttributeMutation::Set(previous_value) => {
2566                        // https://html.spec.whatwg.org/multipage/#input-type-change
2567
2568                        // Ensure there was actually a change in type
2569                        if previous_value
2570                            .is_some_and(|previous_value| **previous_value == **attr.value())
2571                        {
2572                            return;
2573                        }
2574
2575                        let (old_value_mode, old_idl_value) = (self.value_mode(), self.Value());
2576                        let previously_selectable = self.selection_api_applies();
2577
2578                        *self.input_type.safe_borrow_mut(cx.no_gc()) =
2579                            InputType::new_from_atom(attr.value().as_atom());
2580                        self.is_textual_or_password
2581                            .set(self.input_type().is_textual_or_password());
2582
2583                        if self.input_type().is_textual() {
2584                            let read_write = !self.is_read_only_or_disabled();
2585                            element.set_read_write_state(cx.no_gc(), read_write);
2586                        } else {
2587                            element.set_read_write_state(cx.no_gc(), false);
2588                        }
2589
2590                        let new_value_mode = self.value_mode();
2591                        match (&old_value_mode, old_idl_value.is_empty(), new_value_mode) {
2592                            // Step 1
2593                            (&ValueMode::Value, false, ValueMode::Default) |
2594                            (&ValueMode::Value, false, ValueMode::DefaultOn) => {
2595                                self.SetValue(cx, old_idl_value)
2596                                    .expect("Failed to set input value on type change to a default ValueMode.");
2597                            },
2598
2599                            // Step 2
2600                            (_, _, ValueMode::Value) if old_value_mode != ValueMode::Value => {
2601                                self.SetValue(
2602                                    cx,
2603                                    self.upcast::<Element>()
2604                                        .get_attribute_string_value(&local_name!("value"))
2605                                        .unwrap_or_default()
2606                                        .into(),
2607                                )
2608                                .expect(
2609                                    "Failed to set input value on type change to ValueMode::Value.",
2610                                );
2611                                self.value_dirty.set(false);
2612                            },
2613
2614                            // Step 3
2615                            (_, _, ValueMode::Filename)
2616                                if old_value_mode != ValueMode::Filename =>
2617                            {
2618                                self.SetValue(cx, DOMString::new())
2619                                    .expect("Failed to set input value on type change to ValueMode::Filename.");
2620                            },
2621                            _ => {},
2622                        }
2623
2624                        // Step 5
2625                        self.input_type().as_specific().signal_type_change(cx, self);
2626
2627                        // Step 6
2628                        let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
2629                        let mut value = text_input.get_content();
2630                        self.sanitize_value(&mut value);
2631                        text_input.set_content(value);
2632                        self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
2633
2634                        // Set or remove the length restrictions depending on whether they apply
2635                        if self.does_minmaxlength_apply() {
2636                            text_input
2637                                .set_min_length(self.MinLength().to_u32().map(Utf16CodeUnits));
2638                            text_input
2639                                .set_max_length(self.MaxLength().to_u32().map(Utf16CodeUnits));
2640                        } else {
2641                            text_input.set_min_length(None);
2642                            text_input.set_max_length(None);
2643                        }
2644
2645                        // Steps 7-9
2646                        if !previously_selectable && self.selection_api_applies() {
2647                            text_input.clear_selection_to_start();
2648                        }
2649                    },
2650                    AttributeMutation::Removed => {
2651                        self.input_type().as_specific().signal_type_change(cx, self);
2652                        *self.input_type.safe_borrow_mut(cx.no_gc()) = InputType::new_text();
2653                        self.is_textual_or_password
2654                            .set(self.input_type().is_textual_or_password());
2655
2656                        let element = self.upcast::<Element>();
2657                        let read_write = !self.is_read_only_or_disabled();
2658                        element.set_read_write_state(cx.no_gc(), read_write);
2659                    },
2660                }
2661
2662                self.update_placeholder_shown_state(cx.no_gc());
2663                self.input_type()
2664                    .as_specific()
2665                    .update_placeholder_contents(cx, self);
2666
2667                self.validity_state(cx)
2668                    .perform_validation_and_update(cx, ValidationFlags::all());
2669                self.update_checked_state(cx.no_gc());
2670                self.update_indeterminate_state(cx.no_gc());
2671                self.update_default_state_indirectly(cx.no_gc());
2672                element.set_focusring_state(cx.no_gc(), element.focus_state());
2673                self.update_required_and_optional_state(cx.no_gc());
2674            },
2675            local_name!("value") if !self.value_dirty.get() => {
2676                // This is only run when the `value` or `defaultValue` attribute is set. It
2677                // has a different behavior than `SetValue` which is triggered by setting the
2678                // value property in script.
2679                let value = mutation.new_value(attr).map(|value| (**value).to_owned());
2680                let mut value = value.map_or(DOMString::new(), DOMString::from);
2681
2682                self.sanitize_value(&mut value);
2683                self.text_input
2684                    .safe_borrow_mut(cx.no_gc())
2685                    .set_content(value);
2686                self.update_placeholder_shown_state(cx.no_gc());
2687            },
2688            local_name!("maxlength") if self.does_minmaxlength_apply() => match *attr.value() {
2689                AttrValue::Int(_, value) => {
2690                    let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
2691
2692                    if value < 0 {
2693                        text_input.set_max_length(None);
2694                    } else {
2695                        text_input.set_max_length(Some(Utf16CodeUnits(value as u32)))
2696                    }
2697                },
2698                _ => panic!("Expected an AttrValue::Int"),
2699            },
2700            local_name!("minlength") if self.does_minmaxlength_apply() => match *attr.value() {
2701                AttrValue::Int(_, value) => {
2702                    let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
2703
2704                    if value < 0 {
2705                        text_input.set_min_length(None);
2706                    } else {
2707                        text_input.set_min_length(Some(Utf16CodeUnits(value as u32)))
2708                    }
2709                },
2710                _ => panic!("Expected an AttrValue::Int"),
2711            },
2712            local_name!("placeholder") => {
2713                {
2714                    let mut placeholder = self.placeholder.safe_borrow_mut(cx.no_gc());
2715                    placeholder.clear();
2716                    if let AttributeMutation::Set(_) = mutation {
2717                        placeholder
2718                            .extend(attr.value().chars().filter(|&c| c != '\n' && c != '\r'));
2719                    }
2720                }
2721                self.update_placeholder_shown_state(cx.no_gc());
2722                self.input_type()
2723                    .as_specific()
2724                    .update_placeholder_contents(cx, self);
2725            },
2726            local_name!("readonly") => {
2727                if self.input_type().is_textual() {
2728                    let el = self.upcast::<Element>();
2729                    match mutation {
2730                        AttributeMutation::Set(_) => {
2731                            el.set_read_write_state(cx.no_gc(), false);
2732                        },
2733                        AttributeMutation::Removed => {
2734                            el.set_read_write_state(cx.no_gc(), !self.is_form_element_disabled());
2735                        },
2736                    }
2737                }
2738            },
2739            local_name!("form") => {
2740                self.form_attribute_mutated(cx, mutation);
2741            },
2742            local_name!("required") => {
2743                self.update_required_and_optional_state(cx.no_gc());
2744            },
2745            _ => {
2746                self.input_type()
2747                    .as_specific()
2748                    .attribute_mutated(cx, self, attr, mutation);
2749            },
2750        }
2751
2752        self.value_changed(cx, false);
2753
2754        if could_have_had_embedder_control && !self.may_have_embedder_control() {
2755            self.owner_document()
2756                .embedder_controls()
2757                .hide_embedder_control_for_element(self.upcast());
2758        }
2759    }
2760
2761    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
2762        match *name {
2763            local_name!("accept") => AttrValue::from_comma_separated_tokenlist(value.into()),
2764            local_name!("size") => AttrValue::from_limited_u32(value.into(), DEFAULT_INPUT_SIZE),
2765            local_name!("type") => AttrValue::from_atomic(value.into()),
2766            local_name!("maxlength") => {
2767                AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH)
2768            },
2769            local_name!("minlength") => {
2770                AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH)
2771            },
2772            local_name!("width") |
2773            local_name!("height") |
2774            local_name!("hspace") |
2775            local_name!("vspace") => AttrValue::from_dimension(value.into()),
2776            _ => self
2777                .super_type()
2778                .unwrap()
2779                .parse_plain_attribute(name, value),
2780        }
2781    }
2782
2783    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
2784        if let Some(super_type) = self.super_type() {
2785            super_type.bind_to_tree(cx, context);
2786        }
2787        self.input_type()
2788            .as_specific()
2789            .run_shared_bind_to_tree_or_moving_steps(cx, self);
2790        self.value_changed(cx, false);
2791    }
2792
2793    fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
2794        if let Some(super_type) = self.super_type() {
2795            super_type.moving_steps(cx, context);
2796        }
2797        self.input_type()
2798            .as_specific()
2799            .run_shared_bind_to_tree_or_moving_steps(cx, self);
2800    }
2801
2802    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
2803        // Always attempt to hide IME when unbinding input elements from the tree.
2804        self.owner_document_unrooted(cx.no_gc())
2805            .embedder_controls()
2806            .hide_embedder_control_for_element(self.upcast());
2807
2808        let form_owner = self.form_owner();
2809        self.super_type().unwrap().unbind_from_tree(cx, context);
2810
2811        self.input_type()
2812            .as_specific()
2813            .unbind_from_tree(cx, self, form_owner, context);
2814
2815        self.validity_state(cx)
2816            .perform_validation_and_update(cx, ValidationFlags::all());
2817    }
2818
2819    // This represents behavior for which the UIEvents spec and the
2820    // DOM/HTML specs are out of sync.
2821    // Compare:
2822    // https://w3c.github.io/uievents/#default-action
2823    /// <https://dom.spec.whatwg.org/#action-versus-occurance>
2824    fn handle_event(&self, cx: &mut JSContext, event: &Event) {
2825        if let Some(event) = event.downcast::<FocusEvent>() {
2826            self.handle_focus_event(cx, event);
2827            self.maybe_update_shared_selection();
2828        }
2829
2830        let value_change_events = self
2831            .input_type()
2832            .as_specific()
2833            .handle_event(cx, self, event);
2834
2835        if event.is::<InputEvent>() {
2836            self.value_changed(cx, event.IsTrusted());
2837        }
2838
2839        self.fire_value_change_events(cx, value_change_events);
2840
2841        if let Some(super_type) = self.super_type() {
2842            super_type.handle_event(cx, event);
2843        }
2844    }
2845
2846    /// <https://html.spec.whatwg.org/multipage/#the-input-element%3Aconcept-node-clone-ext>
2847    fn cloning_steps(
2848        &self,
2849        cx: &mut JSContext,
2850        copy: &Node,
2851        maybe_doc: Option<&Document>,
2852        clone_children: CloneChildrenFlag,
2853    ) {
2854        if let Some(s) = self.super_type() {
2855            s.cloning_steps(cx, copy, maybe_doc, clone_children);
2856        }
2857        let elem = copy.downcast::<HTMLInputElement>().unwrap();
2858        elem.value_dirty.set(self.value_dirty.get());
2859        elem.update_checkedness(cx, self.Checked(), false);
2860        elem.checked_changed.set(self.checked_changed.get());
2861        // The spec does not mention cloning the indeterminate state, but other browsers
2862        // do it and there are WPT tests expecting cloned nodes to preserve this attribute.
2863        elem.SetIndeterminate(cx, self.Indeterminate());
2864        elem.text_input
2865            .safe_borrow_mut(cx.no_gc())
2866            .clone_content_from(&self.text_input.borrow());
2867        elem.value_changed(cx, false);
2868    }
2869
2870    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
2871        match attr.local_name() {
2872            &local_name!("type") => true,
2873            &local_name!("width") |
2874            &local_name!("height") |
2875            &local_name!("hspace") |
2876            &local_name!("vspace") => {
2877                matches!(*self.input_type(), InputType::Image(_))
2878            },
2879            _ => self
2880                .super_type()
2881                .unwrap()
2882                .attribute_affects_presentational_hints(attr),
2883        }
2884    }
2885}
2886
2887impl FormControl for HTMLInputElement {
2888    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
2889        self.form_owner.get()
2890    }
2891
2892    fn set_form_owner(&self, cx: &mut JSContext, form: Option<&HTMLFormElement>) {
2893        self.form_owner.set(form);
2894        self.input_type().as_specific().form_owner_changed(cx, self);
2895    }
2896
2897    fn to_html_element(&self) -> &HTMLElement {
2898        self.upcast::<HTMLElement>()
2899    }
2900}
2901
2902impl Validatable for HTMLInputElement {
2903    fn as_element(&self) -> &Element {
2904        self.upcast()
2905    }
2906
2907    /// <https://html.spec.whatwg.org/multipage/#have-range-limitations>
2908    fn has_range_limitations(&self) -> bool {
2909        self.does_value_as_number_apply() && (self.minimum().is_some() || self.maximum().is_some())
2910    }
2911
2912    fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
2913        self.validity_state
2914            .or_init(|| ValidityState::new(cx, &self.owner_window(), self.upcast()))
2915    }
2916
2917    fn satisfies_constraints(&self) -> bool {
2918        let Some(validity_state) = self.validity_state.get() else {
2919            return true;
2920        };
2921        validity_state.invalid_flags().is_empty()
2922    }
2923
2924    fn is_instance_validatable(&self, no_gc: &NoGC) -> bool {
2925        // https://html.spec.whatwg.org/multipage/#hidden-state-(type%3Dhidden)%3Abarred-from-constraint-validation
2926        // https://html.spec.whatwg.org/multipage/#button-state-(type%3Dbutton)%3Abarred-from-constraint-validation
2927        // https://html.spec.whatwg.org/multipage/#reset-button-state-(type%3Dreset)%3Abarred-from-constraint-validation
2928        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls%3A-the-disabled-attribute%3Abarred-from-constraint-validation
2929        // https://html.spec.whatwg.org/multipage/#the-readonly-attribute%3Abarred-from-constraint-validation
2930        // https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation
2931        match *self.input_type() {
2932            InputType::Hidden(_) | InputType::Button(_) | InputType::Reset(_) => false,
2933            _ => {
2934                // See https://github.com/whatwg/html/issues/8133 why we should
2935                // not check whether readonly applies
2936                !(self.ReadOnly() ||
2937                    self.is_form_element_disabled() ||
2938                    is_barred_by_datalist_ancestor(no_gc, self.upcast()))
2939            },
2940        }
2941    }
2942
2943    fn perform_validation(
2944        &self,
2945        cx: &mut JSContext,
2946        validate_flags: ValidationFlags,
2947    ) -> ValidationFlags {
2948        let mut failed_flags = ValidationFlags::empty();
2949        let value = self.Value();
2950
2951        if validate_flags.contains(ValidationFlags::VALUE_MISSING) &&
2952            self.suffers_from_being_missing(cx.no_gc(), &value)
2953        {
2954            failed_flags.insert(ValidationFlags::VALUE_MISSING);
2955        }
2956
2957        if validate_flags.contains(ValidationFlags::TYPE_MISMATCH) &&
2958            self.suffers_from_type_mismatch(&value)
2959        {
2960            failed_flags.insert(ValidationFlags::TYPE_MISMATCH);
2961        }
2962
2963        if validate_flags.contains(ValidationFlags::PATTERN_MISMATCH) &&
2964            self.suffers_from_pattern_mismatch(cx, &value)
2965        {
2966            failed_flags.insert(ValidationFlags::PATTERN_MISMATCH);
2967        }
2968
2969        if validate_flags.contains(ValidationFlags::BAD_INPUT) &&
2970            self.suffers_from_bad_input(&value)
2971        {
2972            failed_flags.insert(ValidationFlags::BAD_INPUT);
2973        }
2974
2975        if validate_flags.intersects(ValidationFlags::TOO_LONG | ValidationFlags::TOO_SHORT) {
2976            failed_flags |= self.suffers_from_length_issues(&value);
2977        }
2978
2979        if validate_flags.intersects(
2980            ValidationFlags::RANGE_UNDERFLOW |
2981                ValidationFlags::RANGE_OVERFLOW |
2982                ValidationFlags::STEP_MISMATCH,
2983        ) {
2984            failed_flags |= self.suffers_from_range_issues(&value);
2985        }
2986
2987        failed_flags & validate_flags
2988    }
2989}
2990
2991impl Activatable for HTMLInputElement {
2992    fn as_element(&self) -> &Element {
2993        self.upcast()
2994    }
2995
2996    /// <https://html.spec.whatwg.org/multipage/#the-input-element:activation-behaviour>
2997    fn is_instance_activatable(&self) -> bool {
2998        // Step 1. If element is not mutable, and element's type attribute is
2999        // neither in the Checkbox nor in the Radio state, then return.
3000        match *self.input_type() {
3001            InputType::Checkbox(_) | InputType::Radio(_) => true,
3002            // https://html.spec.whatwg.org/multipage/#hidden-state-(type=hidden)
3003            // > The input element represents a value that is not intended
3004            // > to be examined or manipulated by the user.
3005            InputType::Hidden(_) => false,
3006            _ => self.is_mutable(),
3007        }
3008    }
3009
3010    /// <https://dom.spec.whatwg.org/#eventtarget-legacy-pre-activation-behavior>
3011    fn legacy_pre_activation_behavior(&self, cx: &mut JSContext) -> Option<InputActivationState> {
3012        let activation_state = self
3013            .input_type()
3014            .as_specific()
3015            .legacy_pre_activation_behavior(cx, self);
3016
3017        if activation_state.is_some() {
3018            self.value_changed(cx, false);
3019        }
3020
3021        activation_state
3022    }
3023
3024    /// <https://dom.spec.whatwg.org/#eventtarget-legacy-canceled-activation-behavior>
3025    fn legacy_canceled_activation_behavior(
3026        &self,
3027        cx: &mut JSContext,
3028        cache: Option<InputActivationState>,
3029    ) {
3030        // Step 1
3031        let ty = self.input_type();
3032        let cache = match cache {
3033            Some(cache) => {
3034                if (cache.was_radio && !matches!(*ty, InputType::Radio(_))) ||
3035                    (cache.was_checkbox && !matches!(*ty, InputType::Checkbox(_)))
3036                {
3037                    // Type changed, abandon ship
3038                    // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414
3039                    return;
3040                }
3041                cache
3042            },
3043            None => {
3044                return;
3045            },
3046        };
3047
3048        // Step 2 and 3
3049        ty.as_specific()
3050            .legacy_canceled_activation_behavior(cx, self, cache);
3051
3052        self.value_changed(cx, false);
3053    }
3054
3055    /// <https://html.spec.whatwg.org/multipage/#the-input-element:activation-behaviour>
3056    fn activation_behavior(&self, cx: &mut JSContext, event: &Event, target: &EventTarget) {
3057        // Step 1. If element is not mutable, and element's type attribute is
3058        // neither in the Checkbox nor in the Radio state, then return.
3059        if !self.is_instance_activatable() {
3060            return;
3061        }
3062
3063        // Step 2. Run element's input activation behavior, if any, and do nothing otherwise.
3064        let input_activation_type = {
3065            let input_type = self.input_type();
3066            InputActivationType::new_from_input_type(&input_type)
3067        };
3068
3069        if let Some(input_activation_type) = input_activation_type {
3070            input_activation_type
3071                .as_specific()
3072                .activation_behavior(cx, self, event, target);
3073        }
3074
3075        // Step 3. If element has a form owner and element's type attribute
3076        // is not in the Button state, then return.
3077        if self.form_owner().is_some() && !matches!(*self.input_type(), InputType::Button(_)) {
3078            return;
3079        }
3080
3081        // Step 4. Run the popover target attribute activation behavior
3082        // given element and event's target.
3083        if let Some(target) = target.downcast::<Node>() {
3084            self.upcast::<HTMLElement>()
3085                .popover_target_attribute_activation_behavior(cx, target);
3086        }
3087    }
3088}
3089
3090/// This is used to compile JS-compatible regex provided in pattern attribute
3091/// that matches only the entirety of string.
3092/// <https://html.spec.whatwg.org/multipage/#compiled-pattern-regular-expression>
3093fn compile_pattern(cx: &mut JSContext, pattern_str: &str, out_regex: MutableHandleObject) -> bool {
3094    // First check if pattern compiles...
3095    if check_js_regex_syntax(cx, pattern_str) {
3096        // ...and if it does make pattern that matches only the entirety of string
3097        let pattern_str = format!("^(?:{})$", pattern_str);
3098        let flags = RegExpFlags {
3099            flags_: RegExpFlag_UnicodeSets,
3100        };
3101        new_js_regex(cx, &pattern_str, flags, out_regex)
3102    } else {
3103        false
3104    }
3105}
3106
3107#[expect(unsafe_code)]
3108/// Check if the pattern by itself is valid first, and not that it only becomes
3109/// valid once we add ^(?: and )$.
3110fn check_js_regex_syntax(cx: &mut JSContext, pattern: &str) -> bool {
3111    let pattern: Vec<u16> = pattern.encode_utf16().collect();
3112    rooted!(&in(cx) let mut exception = UndefinedValue());
3113
3114    let valid = unsafe {
3115        CheckRegExpSyntax(
3116            cx,
3117            pattern.as_ptr(),
3118            pattern.len(),
3119            RegExpFlags {
3120                flags_: RegExpFlag_UnicodeSets,
3121            },
3122            exception.handle_mut(),
3123        )
3124    };
3125
3126    if !valid {
3127        unsafe { JS_ClearPendingException(cx) };
3128        return false;
3129    }
3130
3131    // TODO(cybai): report `exception` to devtools
3132    // exception will be `undefined` if the regex is valid
3133    exception.is_undefined()
3134}
3135
3136#[expect(unsafe_code)]
3137fn new_js_regex(
3138    cx: &mut JSContext,
3139    pattern: &str,
3140    flags: RegExpFlags,
3141    mut out_regex: MutableHandleObject,
3142) -> bool {
3143    let pattern: Vec<u16> = pattern.encode_utf16().collect();
3144    out_regex.set(unsafe { NewUCRegExpObject(cx, pattern.as_ptr(), pattern.len(), flags) });
3145
3146    if out_regex.is_null() {
3147        unsafe { JS_ClearPendingException(cx) };
3148        return false;
3149    }
3150    true
3151}
3152
3153#[expect(unsafe_code)]
3154fn matches_js_regex(cx: &mut JSContext, regex_obj: HandleObject, value: &str) -> Result<bool, ()> {
3155    let mut value: Vec<u16> = value.encode_utf16().collect();
3156
3157    let mut is_regex = false;
3158    assert!(unsafe { ObjectIsRegExp(cx, regex_obj, &mut is_regex) });
3159    assert!(is_regex);
3160
3161    rooted!(&in(cx) let mut rval = UndefinedValue());
3162    let mut index = 0;
3163
3164    let ok = unsafe {
3165        ExecuteRegExpNoStatics(
3166            cx,
3167            regex_obj,
3168            value.as_mut_ptr(),
3169            value.len(),
3170            &mut index,
3171            true,
3172            rval.handle_mut(),
3173        )
3174    };
3175
3176    if ok {
3177        Ok(!rval.is_null())
3178    } else {
3179        unsafe { JS_ClearPendingException(cx) };
3180        Err(())
3181    }
3182}
3183
3184/// When WebDriver asks the [`HTMLInputElement`] to do some asynchronous actions, such
3185/// as selecting files, this stores the details necessary to complete the response when
3186/// the action is complete.
3187#[derive(MallocSizeOf)]
3188pub(crate) struct PendingWebDriverResponse {
3189    /// An [`IpcSender`] to use to send the reply when the response is ready.
3190    response_sender: GenericSender<Result<bool, ErrorStatus>>,
3191    /// The number of files expected to be selected when the selection process is done.
3192    expected_file_count: usize,
3193}
3194
3195impl PendingWebDriverResponse {
3196    pub(crate) fn finish(self, number_files_selected: usize) {
3197        if number_files_selected == self.expected_file_count {
3198            let _ = self.response_sender.send(Ok(false));
3199        } else {
3200            // If not all files are found the WebDriver specification says to return
3201            // the InvalidArgument error.
3202            let _ = self.response_sender.send(Err(ErrorStatus::InvalidArgument));
3203        }
3204    }
3205}