Skip to main content

script/dom/html/form_controls/
htmltextareaelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, 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    // https://html.spec.whatwg.org/multipage/#concept-textarea-dirty
60    value_dirty: Cell<bool>,
61    form_owner: MutNullableDom<HTMLFormElement>,
62    labels_node_list: MutNullableDom<NodeList>,
63    validity_state: MutNullableDom<ValidityState>,
64    /// A [`TextInputWidget`] that manages the shadow DOM for this `<textarea>`.
65    text_input_widget: DomRefCell<TextInputWidget>,
66
67    /// <https://w3c.github.io/selection-api/#dfn-has-scheduled-selectionchange-event>
68    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
91// https://html.spec.whatwg.org/multipage/#attr-textarea-cols-value
92const DEFAULT_COLS: u32 = 20;
93
94// https://html.spec.whatwg.org/multipage/#attr-textarea-rows-value
95const 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    /// <https://html.spec.whatwg.org/multipage/#concept-fe-mutable>
159    pub(crate) fn is_mutable(&self) -> bool {
160        // https://html.spec.whatwg.org/multipage/#the-textarea-element%3Aconcept-fe-mutable
161        // https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable
162        !(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 there is a Document selection collapse it. This isn't really specified
174            // and there are quite a few open specification issues about the interaction
175            // of input and Document selection:
176            // See <https://github.com/w3c/selection-api/issues/83>.
177            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                    // We follow chromium's heuristic to show the virtual keyboard only if user had interacted before.
190                    allow_virtual_keyboard: self.owner_window().has_sticky_activation(),
191                }),
192                None,
193            );
194        }
195
196        // Focus changes can activate or deactivate a selection.
197        self.maybe_update_shared_selection();
198    }
199
200    /// <https://w3c.github.io/selection-api/#dfn-schedule-a-selectionchange-event>
201    fn schedule_a_selection_change_event(&self) {
202        // Step 1. If target's has scheduled selectionchange event is true, abort these steps.
203        if self.has_scheduled_selectionchange_event.get() {
204            return;
205        }
206        // Step 2. Set target's has scheduled selectionchange event to true.
207        self.has_scheduled_selectionchange_event.set(true);
208        // Step 3. Queue a task on the user interaction task source to fire a selectionchange event on target.
209        let this = Trusted::new(self);
210        self.owner_global()
211            .task_manager()
212            .user_interaction_task_source()
213            .queue(
214                // https://w3c.github.io/selection-api/#firing-selectionchange-event
215                task!(selectionchange_task_steps: move |cx| {
216                    let this = this.root();
217                    // Step 1. Set target's has scheduled selectionchange event to false.
218                    this.has_scheduled_selectionchange_event.set(false);
219                    // Step 2. If target is an element, fire an event named selectionchange, which bubbles and not cancelable, at target.
220                    this.upcast::<EventTarget>().fire_event_with_params(
221                        cx,
222                        atom!("selectionchange"),
223                        EventBubbles::Bubbles,
224                        EventCancelable::NotCancelable,
225                        EventComposed::Composed,
226                    );
227                    // Step 3. Otherwise, if target is a document, fire an event named selectionchange,
228                    // which does not bubble and not cancelable, at target.
229                    //
230                    // n/a
231                }),
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                // https://w3c.github.io/selection-api/#selectionchange-event
283                // > When an input or textarea element provide a text selection and its selection changes
284                // > (in either extent or direction),
285                // > the user agent must schedule a selectionchange event on the element.
286                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            // Found an already laid out text run to update, so we only need to repaint:
301            self.owner_window().layout().set_needs_new_display_list();
302        } else {
303            // If there isn’t a text run, layout is pending to create it anyway
304        }
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    // TODO A few of these attributes have default values and additional
354    // constraints
355
356    // https://html.spec.whatwg.org/multipage/#dom-textarea-cols
357    make_uint_getter!(Cols, "cols", DEFAULT_COLS);
358
359    // https://html.spec.whatwg.org/multipage/#dom-textarea-cols
360    make_limited_uint_setter!(SetCols, "cols", DEFAULT_COLS);
361
362    // https://html.spec.whatwg.org/multipage/#dom-input-dirName
363    make_getter!(DirName, "dirname");
364
365    // https://html.spec.whatwg.org/multipage/#dom-input-dirName
366    make_setter!(SetDirName, "dirname");
367
368    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
369    make_bool_getter!(Disabled, "disabled");
370
371    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
372    make_bool_setter!(SetDisabled, "disabled");
373
374    /// <https://html.spec.whatwg.org/multipage/#dom-fae-form>
375    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
376        self.form_owner()
377    }
378
379    // https://html.spec.whatwg.org/multipage/#attr-fe-name
380    make_getter!(Name, "name");
381
382    // https://html.spec.whatwg.org/multipage/#attr-fe-name
383    make_atomic_setter!(SetName, "name");
384
385    // https://html.spec.whatwg.org/multipage/#dom-textarea-placeholder
386    make_getter!(Placeholder, "placeholder");
387
388    // https://html.spec.whatwg.org/multipage/#dom-textarea-placeholder
389    make_setter!(SetPlaceholder, "placeholder");
390
391    // https://html.spec.whatwg.org/multipage/#attr-textarea-maxlength
392    make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
393
394    // https://html.spec.whatwg.org/multipage/#attr-textarea-maxlength
395    make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
396
397    // https://html.spec.whatwg.org/multipage/#attr-textarea-minlength
398    make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
399
400    // https://html.spec.whatwg.org/multipage/#attr-textarea-minlength
401    make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
402
403    // https://html.spec.whatwg.org/multipage/#attr-textarea-readonly
404    make_bool_getter!(ReadOnly, "readonly");
405
406    // https://html.spec.whatwg.org/multipage/#attr-textarea-readonly
407    make_bool_setter!(SetReadOnly, "readonly");
408
409    // https://html.spec.whatwg.org/multipage/#dom-textarea-required
410    make_bool_getter!(Required, "required");
411
412    // https://html.spec.whatwg.org/multipage/#dom-textarea-required
413    make_bool_setter!(SetRequired, "required");
414
415    // https://html.spec.whatwg.org/multipage/#dom-textarea-rows
416    make_uint_getter!(Rows, "rows", DEFAULT_ROWS);
417
418    // https://html.spec.whatwg.org/multipage/#dom-textarea-rows
419    make_limited_uint_setter!(SetRows, "rows", DEFAULT_ROWS);
420
421    // https://html.spec.whatwg.org/multipage/#dom-textarea-wrap
422    make_getter!(Wrap, "wrap");
423
424    // https://html.spec.whatwg.org/multipage/#dom-textarea-wrap
425    make_setter!(SetWrap, "wrap");
426
427    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-type>
428    fn Type(&self) -> DOMString {
429        DOMString::from_static("textarea")
430    }
431
432    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue>
433    fn DefaultValue(&self) -> DOMString {
434        self.upcast::<Node>().GetTextContent().unwrap()
435    }
436
437    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue>
438    fn SetDefaultValue(&self, cx: &mut JSContext, value: DOMString) {
439        self.upcast::<Node>()
440            .set_text_content_for_element(cx, Some(value));
441
442        // if the element's dirty value flag is false, then the element's
443        // raw value must be set to the value of the element's textContent IDL attribute
444        if !self.value_dirty.get() {
445            self.reset(cx);
446        }
447    }
448
449    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-value>
450    fn Value(&self) -> DOMString {
451        self.text_input.borrow().get_content()
452    }
453
454    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-value>
455    fn SetValue(&self, cx: &mut JSContext, value: DOMString) {
456        // Step 1: Let oldAPIValue be this element's API value.
457        let old_api_value = self.Value();
458
459        // Step 2:  Set this element's raw value to the new value.
460        self.text_input
461            .safe_borrow_mut(cx.no_gc())
462            .set_content(value);
463
464        // Step 3: Set this element's dirty value flag to true.
465        self.value_dirty.set(true);
466
467        // Step 4: If the new API value is different from oldAPIValue, then move
468        // the text entry cursor position to the end of the text control,
469        // unselecting any selected text and resetting the selection direction to
470        // "none".
471        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    /// <https://html.spec.whatwg.org/multipage/#dom-textarea-textlength>
480    fn TextLength(&self) -> u32 {
481        self.text_input.borrow().len_utf16().0
482    }
483
484    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
485    make_labels_getter!(Labels, labels_node_list);
486
487    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-select>
488    fn Select(&self, cx: &mut JSContext) {
489        self.dom_select(cx);
490    }
491
492    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart>
493    fn GetSelectionStart(&self) -> Option<u32> {
494        self.dom_start().map(|start| start.0)
495    }
496
497    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart>
498    fn SetSelectionStart(&self, _cx: &mut JSContext, start: Option<u32>) -> ErrorResult {
499        self.set_dom_start(start.map(Utf16CodeUnits::from))
500    }
501
502    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend>
503    fn GetSelectionEnd(&self) -> Option<u32> {
504        self.dom_end().map(|end| end.0)
505    }
506
507    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend>
508    fn SetSelectionEnd(&self, _cx: &mut JSContext, end: Option<u32>) -> ErrorResult {
509        self.set_dom_end(end.map(Utf16CodeUnits::from))
510    }
511
512    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection>
513    fn GetSelectionDirection(&self) -> Option<DOMString> {
514        self.dom_direction()
515    }
516
517    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection>
518    fn SetSelectionDirection(
519        &self,
520        _cx: &mut JSContext,
521        direction: Option<DOMString>,
522    ) -> ErrorResult {
523        self.set_dom_direction(direction)
524    }
525
526    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setselectionrange>
527    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    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext>
536    fn SetRangeText(&self, cx: &mut JSContext, replacement: DOMString) -> ErrorResult {
537        self.set_dom_range_text(cx, replacement, None, None, Default::default())
538    }
539
540    /// <https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext>
541    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    /// <https://html.spec.whatwg.org/multipage/#dom-cva-willvalidate>
559    fn WillValidate(&self, no_gc: &NoGC) -> bool {
560        self.is_instance_validatable(no_gc)
561    }
562
563    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
564    fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
565        self.validity_state(cx)
566    }
567
568    /// <https://html.spec.whatwg.org/multipage/#dom-cva-checkvalidity>
569    fn CheckValidity(&self, cx: &mut JSContext) -> bool {
570        self.check_validity(cx)
571    }
572
573    /// <https://html.spec.whatwg.org/multipage/#dom-cva-reportvalidity>
574    fn ReportValidity(&self, cx: &mut JSContext) -> bool {
575        self.report_validity(cx)
576    }
577
578    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
579    fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
580        self.validation_message(cx)
581    }
582
583    /// <https://html.spec.whatwg.org/multipage/#dom-cva-setcustomvalidity>
584    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    /// <https://w3c.github.io/webdriver/#ref-for-dfn-clear-algorithm-4>
591    /// Used by WebDriver to clear the textarea element.
592    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        // https://html.spec.whatwg.org/multipage/#the-textarea-element:concept-form-reset-control
599        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                // https://html.spec.whatwg.org/multipage/#selector-required
690                // > The :required pseudo-class must match any element falling into one of the following categories:
691                // > - textarea elements that have a required attribute
692                let element = self.upcast::<Element>();
693                let required = matches!(mutation, AttributeMutation::Set(_));
694                element.set_state(cx.no_gc(), ElementState::REQUIRED, required);
695
696                // https://html.spec.whatwg.org/multipage/#selector-optional
697                // > The :optional pseudo-class must match any element falling into one of the following categories:
698                // > - textarea elements that do not have a required attribute
699                element.set_state(cx.no_gc(), ElementState::OPTIONAL_, !required);
700            },
701            local_name!("rows") => {
702                // So we can recalculate the effective height based on rows.
703                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        // Always attempt to hide IME when unbinding input elements from the tree.
738        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    // The cloning steps for textarea elements must propagate the raw value
748    // and dirty value flag from the node being cloned to the copy.
749    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    // copied and modified from htmlinputelement.rs
778    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        // https://html.spec.whatwg.org/multipage/#the-textarea-element:stack-of-open-elements
795        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        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls%3A-the-disabled-attribute%3Abarred-from-constraint-validation
832        // https://html.spec.whatwg.org/multipage/#the-textarea-element%3Abarred-from-constraint-validation
833        // https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation
834        !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        // https://html.spec.whatwg.org/multipage/#suffering-from-being-missing
852        // https://html.spec.whatwg.org/multipage/#the-textarea-element%3Asuffering-from-being-missing
853        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            // https://html.spec.whatwg.org/multipage/#suffering-from-being-too-long
863            // https://html.spec.whatwg.org/multipage/#limiting-user-input-length%3A-the-maxlength-attribute%3Asuffering-from-being-too-long
864            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            // https://html.spec.whatwg.org/multipage/#suffering-from-being-too-short
872            // https://html.spec.whatwg.org/multipage/#setting-minimum-input-length-requirements%3A-the-minlength-attribute%3Asuffering-from-being-too-short
873            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}