1use std::cell::{Cell, RefCell};
6use std::default::Default;
7
8use base::text::Utf16CodeUnitLength;
9use dom_struct::dom_struct;
10use embedder_traits::{EmbedderControlRequest, InputMethodRequest, InputMethodType};
11use fonts::{ByteIndex, TextByteRange};
12use html5ever::{LocalName, Prefix, local_name, ns};
13use js::rust::HandleObject;
14use layout_api::wrapper_traits::{ScriptSelection, SharedSelection};
15use script_bindings::codegen::GenericBindings::CharacterDataBinding::CharacterDataMethods;
16use script_bindings::root::Dom;
17use style::attr::AttrValue;
18use stylo_dom::ElementState;
19
20use crate::clipboard_provider::EmbedderClipboardProvider;
21use crate::dom::attr::Attr;
22use crate::dom::bindings::cell::DomRefCell;
23use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
24use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding::SelectionMode;
25use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
26use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
27use crate::dom::bindings::error::ErrorResult;
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
30use crate::dom::bindings::str::DOMString;
31use crate::dom::clipboardevent::{ClipboardEvent, ClipboardEventType};
32use crate::dom::compositionevent::CompositionEvent;
33use crate::dom::document::Document;
34use crate::dom::document_embedder_controls::ControlElement;
35use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers};
36use crate::dom::event::Event;
37use crate::dom::html::htmlelement::HTMLElement;
38use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
39use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
40use crate::dom::html::htmlinputelement::HTMLInputElement;
41use crate::dom::keyboardevent::KeyboardEvent;
42use crate::dom::node::{
43 BindContext, ChildrenMutation, CloneChildrenFlag, Node, NodeDamage, NodeTraits, UnbindContext,
44};
45use crate::dom::nodelist::NodeList;
46use crate::dom::text::Text;
47use crate::dom::textcontrol::{TextControlElement, TextControlSelection};
48use crate::dom::types::{CharacterData, FocusEvent, MouseEvent};
49use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
50use crate::dom::validitystate::{ValidationFlags, ValidityState};
51use crate::dom::virtualmethods::VirtualMethods;
52use crate::script_runtime::CanGc;
53use crate::textinput::{ClipboardEventFlags, IsComposing, KeyReaction, Lines, TextInput};
54
55#[dom_struct]
56pub(crate) struct HTMLTextAreaElement {
57 htmlelement: HTMLElement,
58 #[no_trace]
59 textinput: DomRefCell<TextInput<EmbedderClipboardProvider>>,
60 placeholder: RefCell<String>,
61 value_dirty: Cell<bool>,
63 form_owner: MutNullableDom<HTMLFormElement>,
64 labels_node_list: MutNullableDom<NodeList>,
65 validity_state: MutNullableDom<ValidityState>,
66 shadow_node: DomRefCell<Option<Dom<Text>>>,
69 #[no_trace]
72 #[conditional_malloc_size_of]
73 shared_selection: SharedSelection,
74}
75
76pub(crate) trait LayoutHTMLTextAreaElementHelpers {
77 fn selection_for_layout(self) -> SharedSelection;
78 fn get_cols(self) -> u32;
79 fn get_rows(self) -> u32;
80}
81
82impl LayoutHTMLTextAreaElementHelpers for LayoutDom<'_, HTMLTextAreaElement> {
83 fn selection_for_layout(self) -> SharedSelection {
84 self.unsafe_get().shared_selection.clone()
85 }
86
87 fn get_cols(self) -> u32 {
88 self.upcast::<Element>()
89 .get_attr_for_layout(&ns!(), &local_name!("cols"))
90 .map_or(DEFAULT_COLS, AttrValue::as_uint)
91 }
92
93 fn get_rows(self) -> u32 {
94 self.upcast::<Element>()
95 .get_attr_for_layout(&ns!(), &local_name!("rows"))
96 .map_or(DEFAULT_ROWS, AttrValue::as_uint)
97 }
98}
99
100const DEFAULT_COLS: u32 = 20;
102
103const DEFAULT_ROWS: u32 = 2;
105
106const DEFAULT_MAX_LENGTH: i32 = -1;
107const DEFAULT_MIN_LENGTH: i32 = -1;
108
109impl HTMLTextAreaElement {
110 fn new_inherited(
111 local_name: LocalName,
112 prefix: Option<Prefix>,
113 document: &Document,
114 ) -> HTMLTextAreaElement {
115 let embedder_sender = document
116 .window()
117 .as_global_scope()
118 .script_to_embedder_chan()
119 .clone();
120 HTMLTextAreaElement {
121 htmlelement: HTMLElement::new_inherited_with_state(
122 ElementState::ENABLED | ElementState::READWRITE,
123 local_name,
124 prefix,
125 document,
126 ),
127 placeholder: Default::default(),
128 textinput: DomRefCell::new(TextInput::new(
129 Lines::Multiple,
130 DOMString::new(),
131 EmbedderClipboardProvider {
132 embedder_sender,
133 webview_id: document.webview_id(),
134 },
135 )),
136 value_dirty: Cell::new(false),
137 form_owner: Default::default(),
138 labels_node_list: Default::default(),
139 validity_state: Default::default(),
140 shadow_node: Default::default(),
141 shared_selection: Default::default(),
142 }
143 }
144
145 pub(crate) fn new(
146 local_name: LocalName,
147 prefix: Option<Prefix>,
148 document: &Document,
149 proto: Option<HandleObject>,
150 can_gc: CanGc,
151 ) -> DomRoot<HTMLTextAreaElement> {
152 Node::reflect_node_with_proto(
153 Box::new(HTMLTextAreaElement::new_inherited(
154 local_name, prefix, document,
155 )),
156 document,
157 proto,
158 can_gc,
159 )
160 }
161
162 pub(crate) fn auto_directionality(&self) -> String {
163 let value: String = self.Value().to_string();
164 HTMLInputElement::directionality_from_value(&value)
165 }
166
167 pub(crate) fn is_mutable(&self) -> bool {
169 !(self.upcast::<Element>().disabled_state() || self.ReadOnly())
172 }
173
174 fn handle_focus_event(&self, event: &FocusEvent) {
175 let event_type = event.upcast::<Event>().type_();
176 if *event_type == *"blur" {
177 self.owner_document()
178 .embedder_controls()
179 .hide_embedder_control(self.upcast());
180 } else if *event_type == *"focus" {
181 self.owner_document()
182 .embedder_controls()
183 .show_embedder_control(
184 ControlElement::Ime(DomRoot::from_ref(self.upcast())),
185 EmbedderControlRequest::InputMethod(InputMethodRequest {
186 input_method_type: InputMethodType::Text,
187 text: self.Value().to_string(),
188 insertion_point: self.GetSelectionEnd(),
189 multiline: false,
190 }),
191 None,
192 );
193 } else {
194 unreachable!("Got unexpected FocusEvent {event_type:?}");
195 }
196
197 self.maybe_update_shared_selection();
199 }
200
201 fn handle_text_content_changed(&self, can_gc: CanGc) {
202 self.validity_state(can_gc)
203 .perform_validation_and_update(ValidationFlags::all(), can_gc);
204
205 let textinput_content = self.textinput.borrow().get_content();
206 let element = self.upcast::<Element>();
207 let placeholder_shown =
208 textinput_content.is_empty() && !self.placeholder.borrow().is_empty();
209 element.set_placeholder_shown_state(placeholder_shown);
210
211 let shadow_root = element
212 .shadow_root()
213 .unwrap_or_else(|| element.attach_ua_shadow_root(true, can_gc));
214 if self.shadow_node.borrow().is_none() {
215 let shadow_node = Text::new(Default::default(), &shadow_root.owner_document(), can_gc);
216 Node::replace_all(Some(shadow_node.upcast()), shadow_root.upcast(), can_gc);
217 self.shadow_node
218 .borrow_mut()
219 .replace(shadow_node.as_traced());
220 }
221
222 let content = if placeholder_shown {
223 self.placeholder
226 .borrow()
227 .replace("\r\n", "\n")
228 .replace('\r', "\n")
229 .into()
230 } else if textinput_content.is_empty() {
231 "\u{200B}".into()
236 } else {
237 textinput_content
238 };
239
240 let shadow_node = self.shadow_node.borrow_mut();
241 let character_data = shadow_node
242 .as_ref()
243 .expect("Should have always created a node at this point.")
244 .upcast::<CharacterData>();
245 if character_data.Data() != content {
246 character_data.SetData(content);
247 self.maybe_update_shared_selection();
248 }
249 }
250
251 fn handle_mouse_event(&self, mouse_event: &MouseEvent) {
252 if mouse_event.upcast::<Event>().DefaultPrevented() {
253 return;
254 }
255
256 if self.textinput.borrow().is_empty() {
259 return;
260 }
261 let node = self.upcast();
262 if self
263 .textinput
264 .borrow_mut()
265 .handle_mouse_event(node, mouse_event)
266 {
267 self.maybe_update_shared_selection();
268 }
269 }
270}
271
272impl TextControlElement for HTMLTextAreaElement {
273 fn selection_api_applies(&self) -> bool {
274 true
275 }
276
277 fn has_selectable_text(&self) -> bool {
278 !self.textinput.borrow().get_content().is_empty()
279 }
280
281 fn has_uncollapsed_selection(&self) -> bool {
282 self.textinput.borrow().has_uncollapsed_selection()
283 }
284
285 fn set_dirty_value_flag(&self, value: bool) {
286 self.value_dirty.set(value)
287 }
288
289 fn select_all(&self) {
290 self.textinput.borrow_mut().select_all();
291 self.maybe_update_shared_selection();
292 }
293
294 fn maybe_update_shared_selection(&self) {
295 let offsets = self.textinput.borrow().sorted_selection_offsets_range();
296 let (start, end) = (offsets.start.0, offsets.end.0);
297 let shared_selection = ScriptSelection {
298 range: TextByteRange::new(ByteIndex(start), ByteIndex(end)),
299 enabled: self.upcast::<Element>().focus_state(),
300 };
301 if shared_selection == *self.shared_selection.borrow() {
302 return;
303 }
304 *self.shared_selection.borrow_mut() = shared_selection;
305 self.owner_window().layout().set_needs_new_display_list();
306 }
307}
308
309impl HTMLTextAreaElementMethods<crate::DomTypeHolder> for HTMLTextAreaElement {
310 make_uint_getter!(Cols, "cols", DEFAULT_COLS);
315
316 make_limited_uint_setter!(SetCols, "cols", DEFAULT_COLS);
318
319 make_getter!(DirName, "dirname");
321
322 make_setter!(SetDirName, "dirname");
324
325 make_bool_getter!(Disabled, "disabled");
327
328 make_bool_setter!(SetDisabled, "disabled");
330
331 fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
333 self.form_owner()
334 }
335
336 make_getter!(Name, "name");
338
339 make_atomic_setter!(SetName, "name");
341
342 make_getter!(Placeholder, "placeholder");
344
345 make_setter!(SetPlaceholder, "placeholder");
347
348 make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
350
351 make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
353
354 make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
356
357 make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
359
360 make_bool_getter!(ReadOnly, "readonly");
362
363 make_bool_setter!(SetReadOnly, "readonly");
365
366 make_bool_getter!(Required, "required");
368
369 make_bool_setter!(SetRequired, "required");
371
372 make_uint_getter!(Rows, "rows", DEFAULT_ROWS);
374
375 make_limited_uint_setter!(SetRows, "rows", DEFAULT_ROWS);
377
378 make_getter!(Wrap, "wrap");
380
381 make_setter!(SetWrap, "wrap");
383
384 fn Type(&self) -> DOMString {
386 DOMString::from("textarea")
387 }
388
389 fn DefaultValue(&self) -> DOMString {
391 self.upcast::<Node>().GetTextContent().unwrap()
392 }
393
394 fn SetDefaultValue(&self, value: DOMString, can_gc: CanGc) {
396 self.upcast::<Node>()
397 .set_text_content_for_element(Some(value), can_gc);
398
399 if !self.value_dirty.get() {
402 self.reset(can_gc);
403 }
404 }
405
406 fn Value(&self) -> DOMString {
408 self.textinput.borrow().get_content()
409 }
410
411 fn SetValue(&self, value: DOMString, can_gc: CanGc) {
413 let old_api_value = self.Value();
415
416 self.textinput.borrow_mut().set_content(value);
418
419 self.value_dirty.set(true);
421
422 if old_api_value != self.Value() {
427 self.textinput.borrow_mut().clear_selection_to_end();
428 self.handle_text_content_changed(can_gc);
429 }
430 }
431
432 fn TextLength(&self) -> u32 {
434 self.textinput.borrow().len_utf16().0 as u32
435 }
436
437 make_labels_getter!(Labels, labels_node_list);
439
440 fn Select(&self) {
442 self.selection().dom_select();
443 }
444
445 fn GetSelectionStart(&self) -> Option<u32> {
447 self.selection().dom_start().map(|start| start.0 as u32)
448 }
449
450 fn SetSelectionStart(&self, start: Option<u32>) -> ErrorResult {
452 self.selection()
453 .set_dom_start(start.map(Utf16CodeUnitLength::from))
454 }
455
456 fn GetSelectionEnd(&self) -> Option<u32> {
458 self.selection().dom_end().map(|end| end.0 as u32)
459 }
460
461 fn SetSelectionEnd(&self, end: Option<u32>) -> ErrorResult {
463 self.selection()
464 .set_dom_end(end.map(Utf16CodeUnitLength::from))
465 }
466
467 fn GetSelectionDirection(&self) -> Option<DOMString> {
469 self.selection().dom_direction()
470 }
471
472 fn SetSelectionDirection(&self, direction: Option<DOMString>) -> ErrorResult {
474 self.selection().set_dom_direction(direction)
475 }
476
477 fn SetSelectionRange(&self, start: u32, end: u32, direction: Option<DOMString>) -> ErrorResult {
479 self.selection().set_dom_range(
480 Utf16CodeUnitLength::from(start),
481 Utf16CodeUnitLength::from(end),
482 direction,
483 )
484 }
485
486 fn SetRangeText(&self, replacement: DOMString) -> ErrorResult {
488 self.selection()
489 .set_dom_range_text(replacement, None, None, Default::default())
490 }
491
492 fn SetRangeText_(
494 &self,
495 replacement: DOMString,
496 start: u32,
497 end: u32,
498 selection_mode: SelectionMode,
499 ) -> ErrorResult {
500 self.selection().set_dom_range_text(
501 replacement,
502 Some(Utf16CodeUnitLength::from(start)),
503 Some(Utf16CodeUnitLength::from(end)),
504 selection_mode,
505 )
506 }
507
508 fn WillValidate(&self) -> bool {
510 self.is_instance_validatable()
511 }
512
513 fn Validity(&self, can_gc: CanGc) -> DomRoot<ValidityState> {
515 self.validity_state(can_gc)
516 }
517
518 fn CheckValidity(&self, can_gc: CanGc) -> bool {
520 self.check_validity(can_gc)
521 }
522
523 fn ReportValidity(&self, can_gc: CanGc) -> bool {
525 self.report_validity(can_gc)
526 }
527
528 fn ValidationMessage(&self) -> DOMString {
530 self.validation_message()
531 }
532
533 fn SetCustomValidity(&self, error: DOMString, can_gc: CanGc) {
535 self.validity_state(can_gc).set_custom_error_message(error);
536 }
537}
538
539impl HTMLTextAreaElement {
540 pub(crate) fn clear(&self) {
543 self.value_dirty.set(false);
544 self.textinput.borrow_mut().set_content(DOMString::from(""));
545 }
546
547 pub(crate) fn reset(&self, can_gc: CanGc) {
548 self.value_dirty.set(false);
550 self.textinput.borrow_mut().set_content(self.DefaultValue());
551 self.handle_text_content_changed(can_gc);
552 }
553
554 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
555 fn selection(&self) -> TextControlSelection<'_, Self> {
556 TextControlSelection::new(self, &self.textinput)
557 }
558
559 fn handle_key_reaction(&self, action: KeyReaction, event: &Event, can_gc: CanGc) {
560 match action {
561 KeyReaction::TriggerDefaultAction => (),
562 KeyReaction::DispatchInput(text, is_composing, input_type) => {
563 if event.IsTrusted() {
564 self.textinput.borrow().queue_input_event(
565 self.upcast(),
566 text,
567 is_composing,
568 input_type,
569 );
570 }
571 self.value_dirty.set(true);
572 self.handle_text_content_changed(can_gc);
573 event.mark_as_handled();
574 },
575 KeyReaction::RedrawSelection => {
576 self.maybe_update_shared_selection();
577 event.mark_as_handled();
578 },
579 KeyReaction::Nothing => (),
580 }
581 }
582}
583
584impl VirtualMethods for HTMLTextAreaElement {
585 fn super_type(&self) -> Option<&dyn VirtualMethods> {
586 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
587 }
588
589 fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
590 self.super_type()
591 .unwrap()
592 .attribute_mutated(attr, mutation, can_gc);
593 match *attr.local_name() {
594 local_name!("disabled") => {
595 let el = self.upcast::<Element>();
596 match mutation {
597 AttributeMutation::Set(..) => {
598 el.set_disabled_state(true);
599 el.set_enabled_state(false);
600
601 el.set_read_write_state(false);
602 },
603 AttributeMutation::Removed => {
604 el.set_disabled_state(false);
605 el.set_enabled_state(true);
606 el.check_ancestors_disabled_state_for_form_control();
607
608 if !el.disabled_state() && !el.read_write_state() {
609 el.set_read_write_state(true);
610 }
611 },
612 }
613 el.update_sequentially_focusable_status(CanGc::note());
614 },
615 local_name!("maxlength") => match *attr.value() {
616 AttrValue::Int(_, value) => {
617 let mut textinput = self.textinput.borrow_mut();
618
619 if value < 0 {
620 textinput.set_max_length(None);
621 } else {
622 textinput.set_max_length(Some(Utf16CodeUnitLength(value as usize)))
623 }
624 },
625 _ => panic!("Expected an AttrValue::Int"),
626 },
627 local_name!("minlength") => match *attr.value() {
628 AttrValue::Int(_, value) => {
629 let mut textinput = self.textinput.borrow_mut();
630
631 if value < 0 {
632 textinput.set_min_length(None);
633 } else {
634 textinput.set_min_length(Some(Utf16CodeUnitLength(value as usize)))
635 }
636 },
637 _ => panic!("Expected an AttrValue::Int"),
638 },
639 local_name!("placeholder") => {
640 {
641 let mut placeholder = self.placeholder.borrow_mut();
642 placeholder.clear();
643 if let AttributeMutation::Set(..) = mutation {
644 placeholder.push_str(attr.value().as_ref());
645 }
646 }
647 self.handle_text_content_changed(can_gc);
648 },
649 local_name!("readonly") => {
650 let el = self.upcast::<Element>();
651 match mutation {
652 AttributeMutation::Set(..) => {
653 el.set_read_write_state(false);
654 },
655 AttributeMutation::Removed => {
656 el.set_read_write_state(!el.disabled_state());
657 },
658 }
659 },
660 local_name!("form") => {
661 self.form_attribute_mutated(mutation, can_gc);
662 },
663 _ => {},
664 }
665
666 self.validity_state(can_gc)
667 .perform_validation_and_update(ValidationFlags::all(), can_gc);
668 }
669
670 fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
671 if let Some(s) = self.super_type() {
672 s.bind_to_tree(context, can_gc);
673 }
674
675 self.upcast::<Element>()
676 .check_ancestors_disabled_state_for_form_control();
677
678 self.validity_state(can_gc)
679 .perform_validation_and_update(ValidationFlags::all(), can_gc);
680 }
681
682 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
683 match *name {
684 local_name!("cols") => AttrValue::from_limited_u32(value.into(), DEFAULT_COLS),
685 local_name!("rows") => AttrValue::from_limited_u32(value.into(), DEFAULT_ROWS),
686 local_name!("maxlength") => {
687 AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH)
688 },
689 local_name!("minlength") => {
690 AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH)
691 },
692 _ => self
693 .super_type()
694 .unwrap()
695 .parse_plain_attribute(name, value),
696 }
697 }
698
699 fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
700 self.super_type().unwrap().unbind_from_tree(context, can_gc);
701
702 let node = self.upcast::<Node>();
703 let el = self.upcast::<Element>();
704 if node
705 .ancestors()
706 .any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
707 {
708 el.check_ancestors_disabled_state_for_form_control();
709 } else {
710 el.check_disabled_attribute();
711 }
712
713 self.validity_state(can_gc)
714 .perform_validation_and_update(ValidationFlags::all(), can_gc);
715 }
716
717 fn cloning_steps(
720 &self,
721 copy: &Node,
722 maybe_doc: Option<&Document>,
723 clone_children: CloneChildrenFlag,
724 can_gc: CanGc,
725 ) {
726 if let Some(s) = self.super_type() {
727 s.cloning_steps(copy, maybe_doc, clone_children, can_gc);
728 }
729 let el = copy.downcast::<HTMLTextAreaElement>().unwrap();
730 el.value_dirty.set(self.value_dirty.get());
731 {
732 let mut textinput = el.textinput.borrow_mut();
733 textinput.set_content(self.textinput.borrow().get_content());
734 }
735 el.validity_state(can_gc)
736 .perform_validation_and_update(ValidationFlags::all(), can_gc);
737 }
738
739 fn children_changed(&self, mutation: &ChildrenMutation, can_gc: CanGc) {
740 if let Some(s) = self.super_type() {
741 s.children_changed(mutation, can_gc);
742 }
743 if !self.value_dirty.get() {
744 self.reset(can_gc);
745 }
746 }
747
748 fn handle_event(&self, event: &Event, can_gc: CanGc) {
750 if let Some(s) = self.super_type() {
751 s.handle_event(event, can_gc);
752 }
753
754 if let Some(mouse_event) = event.downcast::<MouseEvent>() {
755 self.handle_mouse_event(mouse_event);
756 } else if event.type_() == atom!("keydown") && !event.DefaultPrevented() {
757 if let Some(kevent) = event.downcast::<KeyboardEvent>() {
758 let action = self.textinput.borrow_mut().handle_keydown(kevent);
761 self.handle_key_reaction(action, event, can_gc);
762 }
763 } else if event.type_() == atom!("keypress") && !event.DefaultPrevented() {
764 } else if event.type_() == atom!("compositionstart") ||
768 event.type_() == atom!("compositionupdate") ||
769 event.type_() == atom!("compositionend")
770 {
771 if let Some(compositionevent) = event.downcast::<CompositionEvent>() {
772 if event.type_() == atom!("compositionend") {
773 let action = self
774 .textinput
775 .borrow_mut()
776 .handle_compositionend(compositionevent);
777 self.handle_key_reaction(action, event, can_gc);
778 self.upcast::<Node>().dirty(NodeDamage::Other);
779 } else if event.type_() == atom!("compositionupdate") {
780 let action = self
781 .textinput
782 .borrow_mut()
783 .handle_compositionupdate(compositionevent);
784 self.handle_key_reaction(action, event, can_gc);
785 self.upcast::<Node>().dirty(NodeDamage::Other);
786 }
787 self.maybe_update_shared_selection();
788 event.mark_as_handled();
789 }
790 } else if let Some(clipboard_event) = event.downcast::<ClipboardEvent>() {
791 let reaction = self
792 .textinput
793 .borrow_mut()
794 .handle_clipboard_event(clipboard_event);
795
796 let flags = reaction.flags;
797 if flags.contains(ClipboardEventFlags::FireClipboardChangedEvent) {
798 self.owner_document().event_handler().fire_clipboard_event(
799 None,
800 ClipboardEventType::Change,
801 can_gc,
802 );
803 }
804 if flags.contains(ClipboardEventFlags::QueueInputEvent) {
805 self.textinput.borrow().queue_input_event(
806 self.upcast(),
807 reaction.text,
808 IsComposing::NotComposing,
809 reaction.input_type,
810 );
811 }
812 if !flags.is_empty() {
813 self.handle_text_content_changed(can_gc);
814 }
815 } else if let Some(event) = event.downcast::<FocusEvent>() {
816 self.handle_focus_event(event);
817 }
818
819 self.validity_state(can_gc)
820 .perform_validation_and_update(ValidationFlags::all(), can_gc);
821 }
822
823 fn pop(&self) {
824 self.super_type().unwrap().pop();
825
826 self.reset(CanGc::note());
828 }
829}
830
831impl FormControl for HTMLTextAreaElement {
832 fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
833 self.form_owner.get()
834 }
835
836 fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
837 self.form_owner.set(form);
838 }
839
840 fn to_element(&self) -> &Element {
841 self.upcast::<Element>()
842 }
843}
844
845impl Validatable for HTMLTextAreaElement {
846 fn as_element(&self) -> &Element {
847 self.upcast()
848 }
849
850 fn validity_state(&self, can_gc: CanGc) -> DomRoot<ValidityState> {
851 self.validity_state
852 .or_init(|| ValidityState::new(&self.owner_window(), self.upcast(), can_gc))
853 }
854
855 fn is_instance_validatable(&self) -> bool {
856 !self.upcast::<Element>().disabled_state() &&
860 !self.ReadOnly() &&
861 !is_barred_by_datalist_ancestor(self.upcast())
862 }
863
864 fn perform_validation(
865 &self,
866 validate_flags: ValidationFlags,
867 _can_gc: CanGc,
868 ) -> ValidationFlags {
869 let mut failed_flags = ValidationFlags::empty();
870
871 let textinput = self.textinput.borrow();
872 let Utf16CodeUnitLength(value_len) = textinput.len_utf16();
873 let last_edit_by_user = !textinput.was_last_change_by_set_content();
874 let value_dirty = self.value_dirty.get();
875
876 if validate_flags.contains(ValidationFlags::VALUE_MISSING) &&
879 self.Required() &&
880 self.is_mutable() &&
881 value_len == 0
882 {
883 failed_flags.insert(ValidationFlags::VALUE_MISSING);
884 }
885
886 if value_dirty && last_edit_by_user && value_len > 0 {
887 if validate_flags.contains(ValidationFlags::TOO_LONG) {
890 let max_length = self.MaxLength();
891 if max_length != DEFAULT_MAX_LENGTH && value_len > (max_length as usize) {
892 failed_flags.insert(ValidationFlags::TOO_LONG);
893 }
894 }
895
896 if validate_flags.contains(ValidationFlags::TOO_SHORT) {
899 let min_length = self.MinLength();
900 if min_length != DEFAULT_MIN_LENGTH && value_len < (min_length as usize) {
901 failed_flags.insert(ValidationFlags::TOO_SHORT);
902 }
903 }
904 }
905
906 failed_flags
907 }
908}