1use 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 Value,
88
89 Default,
91
92 DefaultOn,
94
95 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 is_textual_or_password: Cell<bool>,
113
114 placeholder: DomRefCell<TracedDOMString>,
115 size: Cell<u32>,
116 maxlength: Cell<i32>,
117 minlength: Cell<i32>,
118 checkedness: Cell<bool>,
122 checked_changed: Cell<bool>,
124 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 value_dirty: Cell<bool>,
139 user_validity: Cell<bool>,
141 changed_by_user_while_focused: Cell<bool>,
142
143 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 }
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 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 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 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 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 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 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 element.set_state(no_gc, ElementState::REQUIRED, required_applies && required);
453
454 element.set_state(
458 no_gc,
459 ElementState::OPTIONAL_,
460 required_applies && !required,
461 );
462 }
463
464 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 pub(crate) fn allowed_value_step(&self) -> Option<f64> {
488 let default_step = self.default_step()?;
491
492 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 if step_value.eq_ignore_ascii_case("any") {
504 return None;
505 }
506
507 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 Some(parsed_value * self.step_scale_factor())
520 }
521
522 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 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 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 let nsteps = (min - step_base) / allowed_step;
546 Some(step_base + (allowed_step * nsteps.ceil()))
548 },
549 (_, _) => None,
550 }
551 }
552
553 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 let nsteps = (max - step_base) / allowed_step;
561 Some(step_base + (allowed_step * nsteps.floor()))
563 },
564 (_, _) => None,
565 }
566 }
567
568 fn default_minimum(&self) -> Option<f64> {
570 match *self.input_type() {
571 InputType::Range(_) => Some(0.0),
572 _ => None,
573 }
574 }
575
576 fn default_maximum(&self) -> Option<f64> {
578 match *self.input_type() {
579 InputType::Range(_) => Some(100.0),
580 _ => None,
581 }
582 }
583
584 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 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 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 pub(crate) fn step_base(&self) -> f64 {
625 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 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 if let Some(default_step_base) = self.default_step_base() {
649 return default_step_base;
650 }
651
652 0.0
654 }
655
656 fn default_step_base(&self) -> Option<f64> {
658 match *self.input_type() {
659 InputType::Week(_) => Some(-259200000.0),
660 _ => None,
661 }
662 }
663
664 fn step_up_or_down(&self, cx: &mut JSContext, n: i32, dir: StepDirection) -> ErrorResult {
668 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 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 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 if let Some(stepped_minimum) = self.stepped_minimum() &&
697 stepped_minimum > max
698 {
699 return Ok(());
700 }
701 }
702
703 let mut value: f64 = self
707 .convert_string_to_number(&self.Value().str())
708 .unwrap_or(0.0);
709
710 let valueBeforeStepping = value;
712
713 if (value - step_base) % allowed_value_step != 0.0 {
718 value = match dir {
719 StepDirection::Down =>
720 {
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 {
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 else {
735 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 if let Some(min) = minimum &&
749 value < min
750 {
751 value = self.stepped_minimum().unwrap_or(value);
752 }
753
754 if let Some(max) = maximum &&
758 value > max
759 {
760 value = self.stepped_maximum().unwrap_or(value);
761 }
762
763 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 self.SetValueAsNumber(cx, value)
783 }
784
785 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 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 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 fn suffers_from_pattern_mismatch(&self, cx: &mut JSContext, value: &DOMString) -> bool {
828 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 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 false
850 }
851 }
852
853 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 fn suffers_from_length_issues(&self, value: &DOMString) -> ValidationFlags {
867 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 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 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 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 if let Some(min_value) = min_value &&
924 value_as_number < min_value
925 {
926 failed_flags.insert(ValidationFlags::RANGE_UNDERFLOW);
927 }
928 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 if let Some(step) = self.allowed_value_step() {
938 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 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 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 fn schedule_a_selection_change_event(&self) {
982 if self.has_scheduled_selectionchange_event.get() {
984 return;
985 }
986 self.has_scheduled_selectionchange_event.set(true);
988 let this = Trusted::new(self);
990 self.owner_global()
991 .task_manager()
992 .user_interaction_task_source()
993 .queue(
994 task!(selectionchange_task_steps: move |cx| {
996 let this = this.root();
997 this.has_scheduled_selectionchange_event.set(false);
999 this.upcast::<EventTarget>().fire_event_with_params(
1001 cx,
1002 atom!("selectionchange"),
1003 EventBubbles::Bubbles,
1004 EventCancelable::NotCancelable,
1005 EventComposed::Composed,
1006 );
1007 }),
1012 );
1013 }
1014
1015 fn dimensions(&self, cx: &mut JSContext) -> (u32, u32) {
1017 let InputType::Image(ref image_input_type) = *self.input_type() else {
1020 return Default::default();
1021 };
1022 image_input_type.dimensions(cx, self)
1024 }
1025
1026 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 self.value_dirty.set(true);
1038
1039 self.sanitize_value(&mut value);
1042
1043 let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
1044
1045 if text_input.get_content() != value {
1050 text_input.set_content(value);
1052
1053 text_input.clear_selection_to_end();
1054 }
1055 }
1056
1057 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 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 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 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 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 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 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 make_getter!(Accept, "accept");
1279
1280 make_setter!(SetAccept, "accept");
1282
1283 make_bool_getter!(Alpha, "alpha");
1285
1286 make_bool_setter!(SetAlpha, "alpha");
1288
1289 make_getter!(Alt, "alt");
1291
1292 make_setter!(SetAlt, "alt");
1294
1295 make_getter!(DirName, "dirname");
1297
1298 make_setter!(SetDirName, "dirname");
1300
1301 make_bool_getter!(Disabled, "disabled");
1303
1304 make_bool_setter!(SetDisabled, "disabled");
1306
1307 fn Width(&self, cx: &mut JSContext) -> u32 {
1309 self.dimensions(cx).0
1312 }
1313
1314 make_dimension_uint_setter!(SetWidth, "width");
1316
1317 fn Height(&self, cx: &mut JSContext) -> u32 {
1319 self.dimensions(cx).1
1322 }
1323 make_dimension_uint_setter!(SetHeight, "height");
1325
1326 make_dimension_uint_getter!(Hspace, "hspace");
1328 make_dimension_uint_setter!(SetHspace, "hspace");
1330
1331 make_dimension_uint_getter!(Vspace, "vspace");
1333 make_dimension_uint_setter!(SetVspace, "vspace");
1335
1336 fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
1338 self.form_owner()
1339 }
1340
1341 fn GetFiles(&self) -> Option<DomRoot<FileList>> {
1343 self.input_type()
1344 .as_specific()
1345 .get_files()
1346 .as_ref()
1347 .cloned()
1348 }
1349
1350 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 make_bool_getter!(DefaultChecked, "checked");
1359
1360 make_bool_setter!(SetDefaultChecked, "checked");
1362
1363 fn Checked(&self) -> bool {
1365 self.checkedness.get()
1366 }
1367
1368 fn SetChecked(&self, cx: &mut JSContext, checked: bool) {
1370 self.set_checked(cx, checked, false);
1371 }
1372
1373 make_enumerated_getter!(
1375 ColorSpace,
1376 "colorspace",
1377 "limited-srgb" | "display-p3",
1378 missing => "limited-srgb",
1379 invalid => "limited-srgb"
1380 );
1381
1382 make_setter!(SetColorSpace, "colorspace");
1384
1385 make_bool_getter!(ReadOnly, "readonly");
1387
1388 make_bool_setter!(SetReadOnly, "readonly");
1390
1391 make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE);
1393
1394 make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE);
1396
1397 fn Type(&self) -> DOMString {
1399 DOMString::from(self.input_type().as_str())
1400 }
1401
1402 make_atomic_setter!(SetType, "type");
1404
1405 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 fn SetValue(&self, cx: &mut JSContext, value: DOMString) -> ErrorResult {
1438 self.set_value(cx, value, false)
1439 }
1440
1441 make_getter!(DefaultValue, "value");
1443
1444 make_setter!(SetDefaultValue, "value");
1446
1447 make_getter!(Min, "min");
1449
1450 make_setter!(SetMin, "min");
1452
1453 fn GetList(&self) -> Option<DomRoot<HTMLDataListElement>> {
1455 self.suggestions_source_element()
1456 }
1457
1458 #[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 #[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 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 fn ValueAsNumber(&self) -> f64 {
1518 self.convert_string_to_number(&self.Value().str())
1519 .unwrap_or(f64::NAN)
1520 }
1521
1522 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 self.SetValue(cx, DOMString::new())
1540 }
1541 }
1542
1543 make_getter!(Name, "name");
1545
1546 make_atomic_setter!(SetName, "name");
1548
1549 make_getter!(Placeholder, "placeholder");
1551
1552 make_setter!(SetPlaceholder, "placeholder");
1554
1555 make_form_action_getter!(FormAction, "formaction");
1557
1558 make_setter!(SetFormAction, "formaction");
1560
1561 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 make_setter!(SetFormEnctype, "formenctype");
1571
1572 make_enumerated_getter!(
1574 FormMethod,
1575 "formmethod",
1576 "get" | "post" | "dialog",
1577 invalid => "get"
1578 );
1579
1580 make_setter!(SetFormMethod, "formmethod");
1582
1583 make_getter!(FormTarget, "formtarget");
1585
1586 make_setter!(SetFormTarget, "formtarget");
1588
1589 make_bool_getter!(FormNoValidate, "formnovalidate");
1591
1592 make_bool_setter!(SetFormNoValidate, "formnovalidate");
1594
1595 make_getter!(Max, "max");
1597
1598 make_setter!(SetMax, "max");
1600
1601 make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
1603
1604 make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
1606
1607 make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
1609
1610 make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
1612
1613 make_bool_getter!(Multiple, "multiple");
1615
1616 make_bool_setter!(SetMultiple, "multiple");
1618
1619 make_getter!(Pattern, "pattern");
1621
1622 make_setter!(SetPattern, "pattern");
1624
1625 make_bool_getter!(Required, "required");
1627
1628 make_bool_setter!(SetRequired, "required");
1630
1631 make_url_getter!(Src, "src");
1633
1634 make_url_setter!(SetSrc, "src");
1636
1637 make_getter!(Step, "step");
1639
1640 make_setter!(SetStep, "step");
1642
1643 make_getter!(UseMap, "usemap");
1645
1646 make_setter!(SetUseMap, "usemap");
1648
1649 make_enumerated_getter!(
1651 PopoverTargetAction,
1652 "popovertargetaction",
1653 "toggle" | "show" | "hide",
1654 missing => "toggle",
1655 invalid => "toggle"
1656 );
1657
1658 make_setter!(SetPopoverTargetAction, "popovertargetaction");
1660
1661 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 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 fn Webkitdirectory(&self) -> bool {
1678 self.upcast::<Element>()
1679 .has_attribute(&LocalName::from("webkitdirectory"))
1680 }
1681
1682 fn SetWebkitdirectory(&self, cx: &mut JSContext, value: bool) {
1684 self.upcast::<Element>()
1685 .set_bool_attribute(cx, &LocalName::from("webkitdirectory"), value)
1686 }
1687
1688 fn WebkitEntries(&self, cx: &mut JSContext, retval: MutableHandleValue) {
1690 let entries: Vec<DomRoot<FileSystemEntry>> = Vec::new();
1698 to_frozen_array(cx, &entries, retval);
1699 }
1700
1701 fn Indeterminate(&self) -> bool {
1703 self.indeterminateness.get()
1704 }
1705
1706 fn SetIndeterminate(&self, cx: &mut JSContext, val: bool) {
1708 self.indeterminateness.set(val);
1709 self.update_indeterminate_state(cx.no_gc());
1710 }
1711
1712 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 fn Select(&self, cx: &mut JSContext) {
1731 self.dom_select(cx);
1732 }
1733
1734 fn GetSelectionStart(&self) -> Option<u32> {
1736 self.dom_start().map(|start| start.0)
1737 }
1738
1739 fn SetSelectionStart(&self, _cx: &mut JSContext, start: Option<u32>) -> ErrorResult {
1741 self.set_dom_start(start.map(Utf16CodeUnits::from))
1742 }
1743
1744 fn GetSelectionEnd(&self) -> Option<u32> {
1746 self.dom_end().map(|end| end.0)
1747 }
1748
1749 fn SetSelectionEnd(&self, _cx: &mut JSContext, end: Option<u32>) -> ErrorResult {
1751 self.set_dom_end(end.map(Utf16CodeUnits::from))
1752 }
1753
1754 fn GetSelectionDirection(&self) -> Option<DOMString> {
1756 self.dom_direction()
1757 }
1758
1759 fn SetSelectionDirection(
1761 &self,
1762 _cx: &mut JSContext,
1763 direction: Option<DOMString>,
1764 ) -> ErrorResult {
1765 self.set_dom_direction(direction)
1766 }
1767
1768 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 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 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 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 fn StepUp(&self, cx: &mut JSContext, n: i32) -> ErrorResult {
1814 self.step_up_or_down(cx, n, StepDirection::Up)
1815 }
1816
1817 fn StepDown(&self, cx: &mut JSContext, n: i32) -> ErrorResult {
1819 self.step_up_or_down(cx, n, StepDirection::Down)
1820 }
1821
1822 fn WillValidate(&self, no_gc: &NoGC) -> bool {
1824 self.is_instance_validatable(no_gc)
1825 }
1826
1827 fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
1829 self.validity_state(cx)
1830 }
1831
1832 fn CheckValidity(&self, cx: &mut JSContext) -> bool {
1834 self.check_validity(cx)
1835 }
1836
1837 fn ReportValidity(&self, cx: &mut JSContext) -> bool {
1839 self.report_validity(cx)
1840 }
1841
1842 fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
1844 self.validation_message(cx)
1845 }
1846
1847 fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
1849 self.validity_state(cx).set_custom_error_message(cx, error);
1850 }
1851
1852 fn ShowPicker(&self, cx: &mut JSContext) -> ErrorResult {
1854 if !self.is_mutable() {
1856 return Err(Error::InvalidState(Some(
1857 "Input element is not mutable to show picker".into(),
1858 )));
1859 }
1860
1861 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 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 self.show_the_picker_if_applicable(cx);
1889 Ok(())
1890 }
1891}
1892
1893impl HTMLInputElement {
1894 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 match *self.input_type() {
1910 InputType::Submit(_) | InputType::Button(_) | InputType::Reset(_) if !is_submitter => {
1912 return (vec![], true);
1913 },
1914
1915 InputType::Radio(_) | InputType::Checkbox(_) if !self.Checked() => {
1917 return (vec![], true);
1918 },
1919 InputType::Image(_) => {
1920 if !is_submitter {
1922 return (vec![], true);
1923 }
1924 },
1925 _ => {
1927 if name.is_empty() {
1928 return (vec![], true);
1929 }
1930 },
1931 }
1932
1933 let datums = match *self.input_type() {
1934 InputType::Image(ref image_input_type) => {
1936 let prefix = if name.is_empty() {
1941 String::new()
1942 } else {
1943 format!("{name}.")
1944 };
1945
1946 let name_x: DOMString = format!("{prefix}x").into();
1949 let name_y: DOMString = format!("{prefix}y").into();
1950
1951 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 InputType::Checkbox(_) | InputType::Radio(_) => {
1971 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 vec![FormDatum {
1980 ty,
1981 name,
1982 value: FormDatumValue::String(value),
1983 }]
1984 },
1985
1986 InputType::File(_) => {
1988 let mut datums = vec![];
1989
1990 let name = self.Name();
1992
1993 match self.GetFiles() {
1994 None => {
1996 datums.push(FormDatum {
1997 ty,
2000 name,
2001 value: FormDatumValue::String(DOMString::new()),
2002 })
2003 },
2004 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 InputType::Hidden(_) if name.eq_ignore_ascii_case("_charset_") => {
2021 let charset = match encoding {
2023 None => DOMString::from_static("UTF-8"),
2024 Some(enc) => DOMString::from(enc.name()),
2025 };
2026 vec![FormDatum {
2028 ty,
2029 name,
2030 value: FormDatumValue::String(charset),
2031 }]
2032 },
2033
2034 _ => vec![FormDatum {
2036 ty,
2037 name,
2038 value: FormDatumValue::String(self.Value()),
2039 }],
2040 };
2041 (datums, false)
2042 }
2043
2044 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 if self.upcast::<Node>().is_connected() {
2067 self.upcast::<Element>()
2068 .restyle(cx.no_gc(), NodeDamage::Other);
2069 }
2070 }
2071
2072 fn update_checked_state(&self, no_gc: &NoGC) {
2074 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 pub(crate) fn update_default_state(&self, is_default_button: bool, no_gc: &NoGC) {
2089 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 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 pub(crate) fn update_indeterminate_state(&self, no_gc: &NoGC) {
2116 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 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 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 pub(crate) fn is_mutable(&self) -> bool {
2159 !self.is_read_only_or_disabled()
2162 }
2163
2164 fn is_readonly(&self) -> bool {
2167 self.does_readonly_apply() && self.ReadOnly()
2168 }
2169
2170 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 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 pub(crate) fn clear(&self, cx: &mut JSContext) {
2208 self.value_dirty.set(false);
2210 self.checked_changed.set(false);
2211 self.text_input
2213 .safe_borrow_mut(cx.no_gc())
2214 .set_content(DOMString::new());
2215 self.update_checkedness(cx, self.DefaultChecked(), false);
2217 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 {
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 fn sanitize_value(&self, value: &mut DOMString) {
2273 self.input_type().as_specific().sanitize_value(self, value);
2274 }
2275
2276 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 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 return;
2328 }
2329
2330 form.submit(
2331 cx,
2332 SubmittedFrom::NotFromForm,
2333 FormSubmitterElement::Form(form),
2334 );
2335 },
2336 }
2337 }
2338
2339 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 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 pub(crate) fn fire_value_change_events(&self, cx: &mut JSContext, events: ValueChangeEvents) {
2381 let target = self.upcast::<EventTarget>();
2382
2383 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 if events.contains(ValueChangeEvents::Change) {
2398 target.fire_bubbling_event(cx, atom!("change"));
2399 }
2400 }
2401
2402 pub(crate) fn show_the_picker_if_applicable(&self, cx: &mut JSContext) {
2404 let window = self.owner_window();
2407 if !window.has_transient_activation() {
2408 return;
2409 }
2410
2411 if !self.is_mutable() {
2413 return;
2414 }
2415
2416 window.consume_user_activation();
2418
2419 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 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 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 allow_virtual_keyboard: self.owner_window().has_sticky_activation(),
2492 }),
2493 None,
2494 );
2495 }
2496 }
2497
2498 pub(crate) fn is_form_element_disabled(&self) -> bool {
2501 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 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 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 (&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 (_, _, 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 (_, _, 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 self.input_type().as_specific().signal_type_change(cx, self);
2626
2627 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 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 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 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 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 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 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 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 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 match *self.input_type() {
2932 InputType::Hidden(_) | InputType::Button(_) | InputType::Reset(_) => false,
2933 _ => {
2934 !(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 fn is_instance_activatable(&self) -> bool {
2998 match *self.input_type() {
3001 InputType::Checkbox(_) | InputType::Radio(_) => true,
3002 InputType::Hidden(_) => false,
3006 _ => self.is_mutable(),
3007 }
3008 }
3009
3010 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 fn legacy_canceled_activation_behavior(
3026 &self,
3027 cx: &mut JSContext,
3028 cache: Option<InputActivationState>,
3029 ) {
3030 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 return;
3040 }
3041 cache
3042 },
3043 None => {
3044 return;
3045 },
3046 };
3047
3048 ty.as_specific()
3050 .legacy_canceled_activation_behavior(cx, self, cache);
3051
3052 self.value_changed(cx, false);
3053 }
3054
3055 fn activation_behavior(&self, cx: &mut JSContext, event: &Event, target: &EventTarget) {
3057 if !self.is_instance_activatable() {
3060 return;
3061 }
3062
3063 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 if self.form_owner().is_some() && !matches!(*self.input_type(), InputType::Button(_)) {
3078 return;
3079 }
3080
3081 if let Some(target) = target.downcast::<Node>() {
3084 self.upcast::<HTMLElement>()
3085 .popover_target_attribute_activation_behavior(cx, target);
3086 }
3087 }
3088}
3089
3090fn compile_pattern(cx: &mut JSContext, pattern_str: &str, out_regex: MutableHandleObject) -> bool {
3094 if check_js_regex_syntax(cx, pattern_str) {
3096 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)]
3108fn 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 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#[derive(MallocSizeOf)]
3188pub(crate) struct PendingWebDriverResponse {
3189 response_sender: GenericSender<Result<bool, ErrorStatus>>,
3191 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 let _ = self.response_sender.send(Err(ErrorStatus::InvalidArgument));
3203 }
3204 }
3205}