1use std::cell::{Cell, Ref, RefCell};
6use std::default::Default;
7
8use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
9use dom_struct::dom_struct;
10use embedder_traits::{EmbedderControlRequest, InputMethodRequest, InputMethodType};
11use html5ever::{LocalName, Prefix, local_name, ns};
12use js::context::{JSContext, NoGC};
13use js::rust::HandleObject;
14use script_bindings::cell::DomRefCell;
15use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
16use script_bindings::domstring::TracedDOMString;
17use servo_base::text::{RangeAny, Utf16CodeUnits, Utf32CodeUnits};
18use style::attr::AttrValue;
19use stylo_dom::ElementState;
20
21use crate::dom::bindings::cell::AtomicSafeBorrowMut;
22use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding::SelectionMode;
23use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
24use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
25use crate::dom::bindings::error::ErrorResult;
26use crate::dom::bindings::inheritance::Castable;
27use crate::dom::bindings::refcounted::Trusted;
28use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
29use crate::dom::bindings::str::DOMString;
30use crate::dom::document::Document;
31use crate::dom::document_embedder_controls::ControlElement;
32use crate::dom::element::attributes::storage::AttrRef;
33use crate::dom::element::{AttributeMutation, Element};
34use crate::dom::event::Event;
35use crate::dom::event::event::{EventBubbles, EventCancelable, EventComposed};
36use crate::dom::eventtarget::EventTarget;
37use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
38use crate::dom::html::form_controls::input_type::text_input_widget::TextInputWidget;
39use crate::dom::html::form_controls::text_control::TextControlElement;
40use crate::dom::html::form_controls::text_input::{KeyReaction, Lines, TextInput};
41use crate::dom::html::htmlelement::HTMLElement;
42use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
43use crate::dom::node::virtualmethods::VirtualMethods;
44use crate::dom::node::{
45 BindContext, ChildrenMutation, CloneChildrenFlag, Node, NodeDamage, NodeTraits, UnbindContext,
46};
47use crate::dom::nodelist::NodeList;
48use crate::dom::text_input::EmbedderClipboardProvider;
49use crate::dom::types::FocusEvent;
50use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
51use crate::dom::validitystate::{ValidationFlags, ValidityState};
52
53#[dom_struct]
54pub(crate) struct HTMLTextAreaElement {
55 htmlelement: HTMLElement,
56 #[no_trace]
57 text_input: AtomicRefCell<TextInput<EmbedderClipboardProvider>>,
58 placeholder: RefCell<TracedDOMString>,
59 value_dirty: Cell<bool>,
61 form_owner: MutNullableDom<HTMLFormElement>,
62 labels_node_list: MutNullableDom<NodeList>,
63 validity_state: MutNullableDom<ValidityState>,
64 text_input_widget: DomRefCell<TextInputWidget>,
66
67 has_scheduled_selectionchange_event: Cell<bool>,
69}
70
71impl LayoutDom<'_, HTMLTextAreaElement> {
72 pub(crate) fn selection_for_layout(self) -> Option<RangeAny<Utf32CodeUnits>> {
73 let element = self.unsafe_get();
74 let text_input = element.text_input.borrow();
75 text_input.selection_for_layout
76 }
77
78 pub(crate) fn get_cols(self) -> u32 {
79 self.upcast::<Element>()
80 .get_attr_for_layout(&ns!(), &local_name!("cols"))
81 .map_or(DEFAULT_COLS, AttrValue::as_uint)
82 }
83
84 pub(crate) fn get_rows(self) -> u32 {
85 self.upcast::<Element>()
86 .get_attr_for_layout(&ns!(), &local_name!("rows"))
87 .map_or(DEFAULT_ROWS, AttrValue::as_uint)
88 }
89}
90
91const DEFAULT_COLS: u32 = 20;
93
94const DEFAULT_ROWS: u32 = 2;
96
97const DEFAULT_MAX_LENGTH: i32 = -1;
98const DEFAULT_MIN_LENGTH: i32 = -1;
99
100impl HTMLTextAreaElement {
101 fn new_inherited(
102 local_name: LocalName,
103 prefix: Option<Prefix>,
104 document: &Document,
105 ) -> HTMLTextAreaElement {
106 let embedder_sender = document
107 .window()
108 .as_global_scope()
109 .script_to_embedder_chan()
110 .clone();
111 HTMLTextAreaElement {
112 htmlelement: HTMLElement::new_inherited_with_state(
113 ElementState::ENABLED | ElementState::READWRITE | ElementState::OPTIONAL_,
114 local_name,
115 prefix,
116 document,
117 ),
118 placeholder: Default::default(),
119 text_input: AtomicRefCell::new(TextInput::new(
120 Lines::Multiple,
121 DOMString::new(),
122 EmbedderClipboardProvider {
123 embedder_sender,
124 webview_id: document.webview_id(),
125 },
126 )),
127 value_dirty: Cell::new(false),
128 form_owner: Default::default(),
129 labels_node_list: Default::default(),
130 validity_state: Default::default(),
131 text_input_widget: Default::default(),
132 has_scheduled_selectionchange_event: Default::default(),
133 }
134 }
135
136 pub(crate) fn new(
137 cx: &mut JSContext,
138 local_name: LocalName,
139 prefix: Option<Prefix>,
140 document: &Document,
141 proto: Option<HandleObject>,
142 ) -> DomRoot<HTMLTextAreaElement> {
143 Node::reflect_node_with_proto(
144 cx,
145 Box::new(HTMLTextAreaElement::new_inherited(
146 local_name, prefix, document,
147 )),
148 document,
149 proto,
150 )
151 }
152
153 pub(crate) fn auto_directionality(&self) -> String {
154 let value: String = String::from(self.Value());
155 HTMLInputElement::directionality_from_value(&value)
156 }
157
158 pub(crate) fn is_mutable(&self) -> bool {
160 !(self.upcast::<Element>().disabled_state() || self.ReadOnly())
163 }
164
165 fn handle_focus_event(&self, cx: &mut JSContext, event: &FocusEvent) {
166 let event_type = event.upcast::<Event>().type_();
167 let document = self.owner_document();
168 if *event_type == *"blur" {
169 document
170 .embedder_controls()
171 .hide_embedder_control(self.upcast());
172 } else if *event_type == *"focus" {
173 if let Some(selection) = document.selection() {
178 let _ = selection.Collapse(cx, None, 0);
179 }
180
181 document.embedder_controls().show_embedder_control(
182 cx,
183 ControlElement::Ime(Dom::from_ref(self.upcast())),
184 EmbedderControlRequest::InputMethod(InputMethodRequest {
185 input_method_type: InputMethodType::Text,
186 text: String::from(self.Value()),
187 insertion_point: self.GetSelectionEnd(),
188 multiline: true,
189 allow_virtual_keyboard: self.owner_window().has_sticky_activation(),
191 }),
192 None,
193 );
194 }
195
196 self.maybe_update_shared_selection();
198 }
199
200 fn schedule_a_selection_change_event(&self) {
202 if self.has_scheduled_selectionchange_event.get() {
204 return;
205 }
206 self.has_scheduled_selectionchange_event.set(true);
208 let this = Trusted::new(self);
210 self.owner_global()
211 .task_manager()
212 .user_interaction_task_source()
213 .queue(
214 task!(selectionchange_task_steps: move |cx| {
216 let this = this.root();
217 this.has_scheduled_selectionchange_event.set(false);
219 this.upcast::<EventTarget>().fire_event_with_params(
221 cx,
222 atom!("selectionchange"),
223 EventBubbles::Bubbles,
224 EventCancelable::NotCancelable,
225 EventComposed::Composed,
226 );
227 }),
232 );
233 }
234}
235
236impl TextControlElement for HTMLTextAreaElement {
237 fn as_element(&self) -> &Element {
238 self.upcast()
239 }
240
241 fn text_input(&self) -> AtomicRef<'_, TextInput<EmbedderClipboardProvider>> {
242 self.text_input.borrow()
243 }
244
245 fn text_input_mut(&self) -> AtomicRefMut<'_, TextInput<EmbedderClipboardProvider>> {
246 self.text_input.borrow_mut()
247 }
248
249 fn selection_api_applies(&self) -> bool {
250 true
251 }
252
253 fn has_selectable_text(&self) -> bool {
254 !self.text_input.borrow().get_content().is_empty()
255 }
256
257 fn has_uncollapsed_selection(&self) -> bool {
258 self.text_input.borrow().has_uncollapsed_selection()
259 }
260
261 fn set_dirty_value_flag(&self, value: bool) {
262 self.value_dirty.set(value)
263 }
264
265 fn select_all(&self) {
266 self.text_input.borrow_mut().select_all();
267 self.maybe_update_shared_selection();
268 }
269
270 fn maybe_update_shared_selection(&self) {
271 let selection = {
272 let mut text_input = self.text_input.borrow_mut();
273 let selection_range = text_input.selection_start()..text_input.selection_end();
274 let enabled = self.upcast::<Element>().focus_state();
275
276 let range_remained_equal = selection_range == text_input.previous_selection_range;
277 if range_remained_equal && enabled == text_input.selection_for_layout.is_some() {
278 return;
279 }
280
281 if !range_remained_equal {
282 self.schedule_a_selection_change_event();
287 }
288
289 let selection = enabled.then(|| text_input.sorted_selection_character_offsets_range());
290 text_input.previous_selection_range = selection_range;
291 text_input.selection_for_layout = selection;
292 selection
293 };
294
295 if self
296 .text_input_widget
297 .borrow()
298 .set_text_run_selection(selection)
299 {
300 self.owner_window().layout().set_needs_new_display_list();
302 } else {
303 }
305 }
306
307 fn placeholder_text<'a>(&'a self) -> Ref<'a, TracedDOMString> {
308 self.placeholder.borrow()
309 }
310
311 fn value_text(&self) -> DOMString {
312 self.Value()
313 }
314
315 fn read_only_or_disabled(&self) -> bool {
316 self.ReadOnly() || self.Disabled()
317 }
318
319 fn handle_text_content_changed(&self, cx: &mut JSContext) {
320 self.validity_state(cx)
321 .perform_validation_and_update(cx, ValidationFlags::all());
322
323 let placeholder_shown =
324 self.text_input.borrow().is_empty() && !self.placeholder.borrow().is_empty();
325 self.upcast::<Element>()
326 .set_placeholder_shown_state(cx.no_gc(), placeholder_shown);
327
328 self.text_input_widget.borrow().update_shadow_tree(cx, self);
329 self.text_input_widget
330 .borrow()
331 .update_placeholder_contents(cx, self);
332 self.maybe_update_shared_selection();
333 }
334
335 fn handle_key_reaction(&self, cx: &mut JSContext, action: KeyReaction) {
336 match action {
337 KeyReaction::TriggerDefaultAction => (),
338 KeyReaction::DispatchInput(text, input_type) => {
339 self.queue_input_event(text, input_type);
340 self.value_dirty.set(true);
341 self.handle_text_content_changed(cx);
342 self.maybe_update_shared_selection();
343 },
344 KeyReaction::RedrawSelection => {
345 self.maybe_update_shared_selection();
346 },
347 KeyReaction::Nothing => (),
348 }
349 }
350}
351
352impl HTMLTextAreaElementMethods<crate::DomTypeHolder> for HTMLTextAreaElement {
353 make_uint_getter!(Cols, "cols", DEFAULT_COLS);
358
359 make_limited_uint_setter!(SetCols, "cols", DEFAULT_COLS);
361
362 make_getter!(DirName, "dirname");
364
365 make_setter!(SetDirName, "dirname");
367
368 make_bool_getter!(Disabled, "disabled");
370
371 make_bool_setter!(SetDisabled, "disabled");
373
374 fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
376 self.form_owner()
377 }
378
379 make_getter!(Name, "name");
381
382 make_atomic_setter!(SetName, "name");
384
385 make_getter!(Placeholder, "placeholder");
387
388 make_setter!(SetPlaceholder, "placeholder");
390
391 make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
393
394 make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
396
397 make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
399
400 make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
402
403 make_bool_getter!(ReadOnly, "readonly");
405
406 make_bool_setter!(SetReadOnly, "readonly");
408
409 make_bool_getter!(Required, "required");
411
412 make_bool_setter!(SetRequired, "required");
414
415 make_uint_getter!(Rows, "rows", DEFAULT_ROWS);
417
418 make_limited_uint_setter!(SetRows, "rows", DEFAULT_ROWS);
420
421 make_getter!(Wrap, "wrap");
423
424 make_setter!(SetWrap, "wrap");
426
427 fn Type(&self) -> DOMString {
429 DOMString::from_static("textarea")
430 }
431
432 fn DefaultValue(&self) -> DOMString {
434 self.upcast::<Node>().GetTextContent().unwrap()
435 }
436
437 fn SetDefaultValue(&self, cx: &mut JSContext, value: DOMString) {
439 self.upcast::<Node>()
440 .set_text_content_for_element(cx, Some(value));
441
442 if !self.value_dirty.get() {
445 self.reset(cx);
446 }
447 }
448
449 fn Value(&self) -> DOMString {
451 self.text_input.borrow().get_content()
452 }
453
454 fn SetValue(&self, cx: &mut JSContext, value: DOMString) {
456 let old_api_value = self.Value();
458
459 self.text_input
461 .safe_borrow_mut(cx.no_gc())
462 .set_content(value);
463
464 self.value_dirty.set(true);
466
467 if old_api_value != self.Value() {
472 self.text_input
473 .safe_borrow_mut(cx.no_gc())
474 .clear_selection_to_end();
475 self.handle_text_content_changed(cx);
476 }
477 }
478
479 fn TextLength(&self) -> u32 {
481 self.text_input.borrow().len_utf16().0
482 }
483
484 make_labels_getter!(Labels, labels_node_list);
486
487 fn Select(&self, cx: &mut JSContext) {
489 self.dom_select(cx);
490 }
491
492 fn GetSelectionStart(&self) -> Option<u32> {
494 self.dom_start().map(|start| start.0)
495 }
496
497 fn SetSelectionStart(&self, _cx: &mut JSContext, start: Option<u32>) -> ErrorResult {
499 self.set_dom_start(start.map(Utf16CodeUnits::from))
500 }
501
502 fn GetSelectionEnd(&self) -> Option<u32> {
504 self.dom_end().map(|end| end.0)
505 }
506
507 fn SetSelectionEnd(&self, _cx: &mut JSContext, end: Option<u32>) -> ErrorResult {
509 self.set_dom_end(end.map(Utf16CodeUnits::from))
510 }
511
512 fn GetSelectionDirection(&self) -> Option<DOMString> {
514 self.dom_direction()
515 }
516
517 fn SetSelectionDirection(
519 &self,
520 _cx: &mut JSContext,
521 direction: Option<DOMString>,
522 ) -> ErrorResult {
523 self.set_dom_direction(direction)
524 }
525
526 fn SetSelectionRange(&self, start: u32, end: u32, direction: Option<DOMString>) -> ErrorResult {
528 self.set_dom_range(
529 Utf16CodeUnits::from(start),
530 Utf16CodeUnits::from(end),
531 direction,
532 )
533 }
534
535 fn SetRangeText(&self, cx: &mut JSContext, replacement: DOMString) -> ErrorResult {
537 self.set_dom_range_text(cx, replacement, None, None, Default::default())
538 }
539
540 fn SetRangeText_(
542 &self,
543 cx: &mut JSContext,
544 replacement: DOMString,
545 start: u32,
546 end: u32,
547 selection_mode: SelectionMode,
548 ) -> ErrorResult {
549 self.set_dom_range_text(
550 cx,
551 replacement,
552 Some(Utf16CodeUnits::from(start)),
553 Some(Utf16CodeUnits::from(end)),
554 selection_mode,
555 )
556 }
557
558 fn WillValidate(&self, no_gc: &NoGC) -> bool {
560 self.is_instance_validatable(no_gc)
561 }
562
563 fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
565 self.validity_state(cx)
566 }
567
568 fn CheckValidity(&self, cx: &mut JSContext) -> bool {
570 self.check_validity(cx)
571 }
572
573 fn ReportValidity(&self, cx: &mut JSContext) -> bool {
575 self.report_validity(cx)
576 }
577
578 fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
580 self.validation_message(cx)
581 }
582
583 fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
585 self.validity_state(cx).set_custom_error_message(cx, error);
586 }
587}
588
589impl HTMLTextAreaElement {
590 pub(crate) fn clear(&self) {
593 self.value_dirty.set(false);
594 self.text_input.borrow_mut().set_content(DOMString::new());
595 }
596
597 pub(crate) fn reset(&self, cx: &mut JSContext) {
598 self.value_dirty.set(false);
600 self.text_input
601 .safe_borrow_mut(cx.no_gc())
602 .set_content(self.DefaultValue());
603 self.handle_text_content_changed(cx);
604 }
605}
606
607impl VirtualMethods for HTMLTextAreaElement {
608 fn super_type(&self) -> Option<&dyn VirtualMethods> {
609 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
610 }
611
612 fn attribute_mutated(
613 &self,
614 cx: &mut JSContext,
615 attr: AttrRef<'_>,
616 mutation: AttributeMutation,
617 ) {
618 self.super_type()
619 .unwrap()
620 .attribute_mutated(cx, attr, mutation);
621 match *attr.local_name() {
622 local_name!("disabled") => {
623 let el = self.upcast::<Element>();
624 match mutation {
625 AttributeMutation::Set(_) => {
626 el.set_read_write_state(cx.no_gc(), false);
627 },
628 AttributeMutation::Removed => {
629 if !el.disabled_state() && !el.read_write_state() {
630 el.set_read_write_state(cx.no_gc(), true);
631 }
632 },
633 }
634 },
635 local_name!("maxlength") => match *attr.value() {
636 AttrValue::Int(_, value) => {
637 let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
638
639 if value < 0 {
640 text_input.set_max_length(None);
641 } else {
642 text_input.set_max_length(Some(Utf16CodeUnits(value as u32)))
643 }
644 },
645 _ => panic!("Expected an AttrValue::Int"),
646 },
647 local_name!("minlength") => match *attr.value() {
648 AttrValue::Int(_, value) => {
649 let mut text_input = self.text_input.safe_borrow_mut(cx.no_gc());
650
651 if value < 0 {
652 text_input.set_min_length(None);
653 } else {
654 text_input.set_min_length(Some(Utf16CodeUnits(value as u32)))
655 }
656 },
657 _ => panic!("Expected an AttrValue::Int"),
658 },
659 local_name!("placeholder") => {
660 {
661 let mut placeholder = self.placeholder.borrow_mut();
662 match mutation {
663 AttributeMutation::Set(_) => {
664 let value = attr.value();
665 let value_str: &str = value.as_ref();
666 *placeholder =
667 value_str.replace("\r\n", "\n").replace('\r', "\n").into();
668 },
669 AttributeMutation::Removed => placeholder.clear(),
670 }
671 }
672 self.handle_text_content_changed(cx);
673 },
674 local_name!("readonly") => {
675 let el = self.upcast::<Element>();
676 match mutation {
677 AttributeMutation::Set(_) => {
678 el.set_read_write_state(cx.no_gc(), false);
679 },
680 AttributeMutation::Removed => {
681 el.set_read_write_state(cx.no_gc(), !el.disabled_state());
682 },
683 }
684 },
685 local_name!("form") => {
686 self.form_attribute_mutated(cx, mutation);
687 },
688 local_name!("required") => {
689 let element = self.upcast::<Element>();
693 let required = matches!(mutation, AttributeMutation::Set(_));
694 element.set_state(cx.no_gc(), ElementState::REQUIRED, required);
695
696 element.set_state(cx.no_gc(), ElementState::OPTIONAL_, !required);
700 },
701 local_name!("rows") => {
702 self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
704 },
705 _ => {},
706 }
707
708 self.validity_state(cx)
709 .perform_validation_and_update(cx, ValidationFlags::all());
710 }
711
712 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
713 if let Some(s) = self.super_type() {
714 s.bind_to_tree(cx, context);
715 }
716 self.handle_text_content_changed(cx);
717 }
718
719 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
720 match *name {
721 local_name!("cols") => AttrValue::from_limited_u32(value.into(), DEFAULT_COLS),
722 local_name!("rows") => AttrValue::from_limited_u32(value.into(), DEFAULT_ROWS),
723 local_name!("maxlength") => {
724 AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH)
725 },
726 local_name!("minlength") => {
727 AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH)
728 },
729 _ => self
730 .super_type()
731 .unwrap()
732 .parse_plain_attribute(name, value),
733 }
734 }
735
736 fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
737 self.owner_document()
739 .embedder_controls()
740 .hide_embedder_control(self.upcast());
741
742 self.super_type().unwrap().unbind_from_tree(cx, context);
743 self.validity_state(cx)
744 .perform_validation_and_update(cx, ValidationFlags::all());
745 }
746
747 fn cloning_steps(
750 &self,
751 cx: &mut JSContext,
752 copy: &Node,
753 maybe_doc: Option<&Document>,
754 clone_children: CloneChildrenFlag,
755 ) {
756 if let Some(s) = self.super_type() {
757 s.cloning_steps(cx, copy, maybe_doc, clone_children);
758 }
759 let el = copy.downcast::<HTMLTextAreaElement>().unwrap();
760 el.value_dirty.set(self.value_dirty.get());
761 el.text_input
762 .safe_borrow_mut(cx.no_gc())
763 .clone_content_from(&self.text_input.borrow());
764 el.validity_state(cx)
765 .perform_validation_and_update(cx, ValidationFlags::all());
766 }
767
768 fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
769 if let Some(s) = self.super_type() {
770 s.children_changed(cx, mutation);
771 }
772 if !self.value_dirty.get() {
773 self.reset(cx);
774 }
775 }
776
777 fn handle_event(&self, cx: &mut JSContext, event: &Event) {
779 if let Some(event) = event.downcast::<FocusEvent>() {
780 self.handle_focus_event(cx, event);
781 }
782
783 self.validity_state(cx)
784 .perform_validation_and_update(cx, ValidationFlags::all());
785
786 if let Some(super_type) = self.super_type() {
787 super_type.handle_event(cx, event);
788 }
789 }
790
791 fn pop(&self, cx: &mut JSContext) {
792 self.super_type().unwrap().pop(cx);
793
794 self.reset(cx);
796 }
797}
798
799impl FormControl for HTMLTextAreaElement {
800 fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
801 self.form_owner.get()
802 }
803
804 fn set_form_owner(&self, _cx: &mut JSContext, form: Option<&HTMLFormElement>) {
805 self.form_owner.set(form);
806 }
807
808 fn to_html_element(&self) -> &HTMLElement {
809 self.upcast::<HTMLElement>()
810 }
811}
812
813impl Validatable for HTMLTextAreaElement {
814 fn as_element(&self) -> &Element {
815 self.upcast()
816 }
817
818 fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
819 self.validity_state
820 .or_init(|| ValidityState::new(cx, &self.owner_window(), self.upcast()))
821 }
822
823 fn satisfies_constraints(&self) -> bool {
824 let Some(validity_state) = self.validity_state.get() else {
825 return true;
826 };
827 validity_state.invalid_flags().is_empty()
828 }
829
830 fn is_instance_validatable(&self, no_gc: &NoGC) -> bool {
831 !self.upcast::<Element>().disabled_state() &&
835 !self.ReadOnly() &&
836 !is_barred_by_datalist_ancestor(no_gc, self.upcast())
837 }
838
839 fn perform_validation(
840 &self,
841 _cx: &mut JSContext,
842 validate_flags: ValidationFlags,
843 ) -> ValidationFlags {
844 let mut failed_flags = ValidationFlags::empty();
845
846 let text_input = self.text_input.borrow();
847 let Utf16CodeUnits(value_len) = text_input.len_utf16();
848 let last_edit_by_user = !text_input.was_last_change_by_set_content();
849 let value_dirty = self.value_dirty.get();
850
851 if validate_flags.contains(ValidationFlags::VALUE_MISSING) &&
854 self.Required() &&
855 self.is_mutable() &&
856 value_len == 0
857 {
858 failed_flags.insert(ValidationFlags::VALUE_MISSING);
859 }
860
861 if value_dirty && last_edit_by_user && value_len > 0 {
862 if validate_flags.contains(ValidationFlags::TOO_LONG) {
865 let max_length = self.MaxLength();
866 if max_length != DEFAULT_MAX_LENGTH && value_len > (max_length as u32) {
867 failed_flags.insert(ValidationFlags::TOO_LONG);
868 }
869 }
870
871 if validate_flags.contains(ValidationFlags::TOO_SHORT) {
874 let min_length = self.MinLength();
875 if min_length != DEFAULT_MIN_LENGTH && value_len < (min_length as u32) {
876 failed_flags.insert(ValidationFlags::TOO_SHORT);
877 }
878 }
879 }
880
881 failed_flags
882 }
883}