Skip to main content

fc_ui/capabilities/controls/
textarea.rs

1//! Textarea component - Multi-line text input component with full editing capabilities.
2
3use crate::capabilities::controls::input::InputVariant;
4pub use crate::capabilities::controls::textarea_state::wire_actions;
5use crate::capabilities::controls::textarea_state::TextareaEvent;
6use crate::capabilities::controls::textarea_state::TextareaState;
7use crate::capabilities::controls::textarea_state::{ValidationError, ValidationRules};
8use crate::capabilities::controls::validation::{validation_footer, CharacterCount, FooterMessage};
9use crate::capabilities::foundation::theme::use_theme;
10use crate::capabilities::layout::VStack;
11use gpui::{prelude::FluentBuilder as _, *};
12use std::rc::Rc;
13use std::sync::Arc;
14
15type TextareaValidator = Rc<dyn Fn(&str) -> Result<(), String>>;
16type TextareaValidationCallback = Rc<dyn Fn(Result<(), ValidationError>, &mut App)>;
17
18/// Initialize textarea component with key bindings
19pub fn init(cx: &mut App) {
20    if !crate::capabilities::foundation::initialization::begin(cx, "textarea") {
21        return;
22    }
23    crate::capabilities::controls::textarea_state::init(cx);
24}
25
26#[derive(IntoElement)]
27pub struct Textarea {
28    state: Entity<TextareaState>,
29    placeholder: SharedString,
30    variant: InputVariant,
31    disabled: bool,
32    error: bool,
33    rows: usize,
34    min_rows: Option<usize>,
35    max_rows: Option<usize>,
36    auto_grow: bool,
37    initial_value: Option<SharedString>,
38
39    aria_label: Option<SharedString>,
40    aria_description: Option<SharedString>,
41
42    on_change: Option<Rc<dyn Fn(SharedString, &mut App)>>,
43    on_enter: Option<Rc<dyn Fn(SharedString, &mut App)>>,
44    on_shift_enter: Option<Rc<dyn Fn(SharedString, &mut App)>>,
45    on_focus: Option<Rc<dyn Fn(SharedString, &mut App)>>,
46    on_blur: Option<Rc<dyn Fn(SharedString, &mut App)>>,
47
48    validation_rules: Option<ValidationRules>,
49    custom_validator: Option<TextareaValidator>,
50    helper_text: Option<SharedString>,
51    show_character_count: bool,
52    on_validate: Option<TextareaValidationCallback>,
53
54    style: StyleRefinement,
55}
56
57impl Textarea {
58    pub fn new(state: &Entity<TextareaState>) -> Self {
59        Self {
60            state: state.clone(),
61            placeholder: "".into(),
62            variant: InputVariant::Default,
63            disabled: false,
64            error: false,
65            rows: 3,
66            min_rows: None,
67            max_rows: None,
68            auto_grow: false,
69            initial_value: None,
70            aria_label: None,
71            aria_description: None,
72            on_change: None,
73            on_enter: None,
74            on_shift_enter: None,
75            on_focus: None,
76            on_blur: None,
77            validation_rules: None,
78            custom_validator: None,
79            helper_text: None,
80            show_character_count: false,
81            on_validate: None,
82            style: StyleRefinement::default(),
83        }
84    }
85
86    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
87        self.initial_value = Some(value.into());
88        self
89    }
90
91    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
92        self.placeholder = placeholder.into();
93        self
94    }
95
96    pub fn variant(mut self, variant: InputVariant) -> Self {
97        self.variant = variant;
98        self
99    }
100
101    pub fn disabled(mut self, disabled: bool) -> Self {
102        self.disabled = disabled;
103        self
104    }
105
106    pub fn error(mut self, error: bool) -> Self {
107        self.error = error;
108        self
109    }
110
111    pub fn rows(mut self, rows: usize) -> Self {
112        self.rows = rows.max(1);
113        self
114    }
115
116    pub fn min_rows(mut self, min_rows: usize) -> Self {
117        self.min_rows = Some(min_rows.max(1));
118        self
119    }
120
121    pub fn max_rows(mut self, max_rows: usize) -> Self {
122        self.max_rows = Some(max_rows.max(1));
123        self
124    }
125
126    pub fn auto_grow(mut self, auto_grow: bool) -> Self {
127        self.auto_grow = auto_grow;
128        self
129    }
130
131    pub fn on_change<F>(mut self, callback: F) -> Self
132    where
133        F: Fn(SharedString, &mut App) + 'static,
134    {
135        self.on_change = Some(Rc::new(callback));
136        self
137    }
138
139    pub fn on_enter<F>(mut self, callback: F) -> Self
140    where
141        F: Fn(SharedString, &mut App) + 'static,
142    {
143        self.on_enter = Some(Rc::new(callback));
144        self
145    }
146
147    pub fn on_shift_enter<F>(mut self, callback: F) -> Self
148    where
149        F: Fn(SharedString, &mut App) + 'static,
150    {
151        self.on_shift_enter = Some(Rc::new(callback));
152        self
153    }
154
155    pub fn on_focus<F>(mut self, callback: F) -> Self
156    where
157        F: Fn(SharedString, &mut App) + 'static,
158    {
159        self.on_focus = Some(Rc::new(callback));
160        self
161    }
162
163    pub fn on_blur<F>(mut self, callback: F) -> Self
164    where
165        F: Fn(SharedString, &mut App) + 'static,
166    {
167        self.on_blur = Some(Rc::new(callback));
168        self
169    }
170
171    /// Set the accessible label for the textarea.
172    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
173        self.aria_label = Some(label.into());
174        self
175    }
176
177    /// Set the accessible description for the textarea.
178    pub fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
179        self.aria_description = Some(description.into());
180        self
181    }
182
183    /// Set validation rules
184    pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
185        self.validation_rules = Some(rules);
186        self
187    }
188
189    /// Set minimum length requirement
190    pub fn min_length(mut self, min: usize) -> Self {
191        self.rules_mut().min_length = Some(min);
192        self
193    }
194
195    /// Set maximum length requirement (also truncates user input)
196    pub fn max_length(mut self, max: usize) -> Self {
197        self.rules_mut().max_length = Some(max);
198        self
199    }
200
201    /// Mark field as required
202    pub fn required(mut self, required: bool) -> Self {
203        self.rules_mut().required = required;
204        self
205    }
206
207    /// Set helper text displayed below the textarea
208    pub fn helper_text(mut self, text: impl Into<SharedString>) -> Self {
209        self.helper_text = Some(text.into());
210        self
211    }
212
213    /// Show character count indicator
214    pub fn show_character_count(mut self, show: bool) -> Self {
215        self.show_character_count = show;
216        self
217    }
218
219    /// Set a custom validation function
220    pub fn custom_validator<F>(mut self, validator: F) -> Self
221    where
222        F: Fn(&str) -> Result<(), String> + 'static,
223    {
224        self.custom_validator = Some(Rc::new(validator));
225        self
226    }
227
228    /// Set callback for validation events
229    pub fn on_validate<F>(mut self, callback: F) -> Self
230    where
231        F: Fn(Result<(), ValidationError>, &mut App) + 'static,
232    {
233        self.on_validate = Some(Rc::new(callback));
234        self
235    }
236
237    fn rules_mut(&mut self) -> &mut ValidationRules {
238        self.validation_rules
239            .get_or_insert_with(ValidationRules::default)
240    }
241
242    fn validation_rules_for_state(&self) -> Option<ValidationRules> {
243        let mut rules = self.validation_rules.clone().or_else(|| {
244            self.custom_validator
245                .is_some()
246                .then(ValidationRules::default)
247        })?;
248
249        if let Some(custom_validator) = self.custom_validator.as_ref() {
250            let validator = custom_validator.clone();
251            rules.custom_validator = Some(Arc::new(move |value| match validator(value) {
252                Ok(()) => Ok(()),
253                Err(message) => Err(ValidationError {
254                    message: message.into(),
255                    field_name: None,
256                }),
257            }));
258        }
259
260        Some(rules)
261    }
262
263    fn install_event_subscription(&self, cx: &mut App) {
264        let on_change = self.on_change.clone();
265        let on_enter = self.on_enter.clone();
266        let on_shift_enter = self.on_shift_enter.clone();
267        let on_focus = self.on_focus.clone();
268        let on_blur = self.on_blur.clone();
269        let on_validate = self.on_validate.clone();
270
271        let has_callbacks = on_change.is_some()
272            || on_enter.is_some()
273            || on_shift_enter.is_some()
274            || on_focus.is_some()
275            || on_blur.is_some()
276            || on_validate.is_some();
277        let subscription = has_callbacks.then(|| {
278            cx.subscribe(
279                &self.state,
280                move |emitter, event: &TextareaEvent, cx| match event {
281                    TextareaEvent::Change => {
282                        if let Some(callback) = on_change.as_ref() {
283                            callback(emitter.read(cx).content.clone(), cx);
284                        }
285                    }
286                    TextareaEvent::Enter => {
287                        if let Some(callback) = on_enter.as_ref() {
288                            callback(emitter.read(cx).content.clone(), cx);
289                        }
290                    }
291                    TextareaEvent::ShiftEnter => {
292                        if let Some(callback) = on_shift_enter.as_ref() {
293                            callback(emitter.read(cx).content.clone(), cx);
294                        }
295                    }
296                    TextareaEvent::Focus => {
297                        if let Some(callback) = on_focus.as_ref() {
298                            callback(emitter.read(cx).content.clone(), cx);
299                        }
300                    }
301                    TextareaEvent::Blur => {
302                        if let Some(callback) = on_blur.as_ref() {
303                            callback(emitter.read(cx).content.clone(), cx);
304                        }
305                    }
306                    TextareaEvent::Validate(result) => {
307                        if let Some(callback) = on_validate.as_ref() {
308                            callback(result.clone(), cx);
309                        }
310                    }
311                    TextareaEvent::Tab | TextareaEvent::ShiftTab => {}
312                },
313            )
314        });
315
316        self.state.update(cx, |state, _| {
317            state.replace_event_subscription(subscription);
318        });
319    }
320
321    fn calculate_height(&self, window: &Window, cx: &App) -> Pixels {
322        let line_height = window.line_height().to_f64() as f32;
323        let padding_y = 8.0;
324        let base_height = self.rows as f32 * line_height + padding_y * 2.0;
325
326        if self.auto_grow {
327            let visual_lines = self.state.read(cx).visual_line_count_for_layout().max(1);
328            let content_height = visual_lines as f32 * line_height + padding_y * 2.0;
329
330            let final_height = if let Some(min_rows) = self.min_rows {
331                let min_height = min_rows as f32 * line_height + padding_y * 2.0;
332                content_height.max(min_height)
333            } else {
334                content_height.max(base_height)
335            };
336
337            if let Some(max_rows) = self.max_rows {
338                let max_height = max_rows as f32 * line_height + padding_y * 2.0;
339                px(final_height.min(max_height))
340            } else {
341                px(final_height)
342            }
343        } else {
344            px(base_height)
345        }
346    }
347}
348
349impl Styled for Textarea {
350    fn style(&mut self) -> &mut StyleRefinement {
351        &mut self.style
352    }
353}
354
355impl RenderOnce for Textarea {
356    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
357        let theme = use_theme(cx);
358        let height = self.calculate_height(window, cx);
359
360        // Update state with properties
361        self.state.update(cx, |state, cx| {
362            state.disabled = self.disabled;
363            state.placeholder = self.placeholder.clone();
364
365            // Apply rules before the initial value so `set_value` truncates
366            // against `max_length` on first render too.
367            if let Some(rules) = self.validation_rules_for_state() {
368                state.validation_rules = rules;
369            }
370
371            if !state.initialized {
372                state.initialized = true;
373                if let Some(value) = self.initial_value.clone() {
374                    state.set_value(value, window, cx);
375                }
376            }
377        });
378
379        self.install_event_subscription(cx);
380
381        let (validation_error, success_message, content_length, max_length, has_value, composing) = {
382            let state = self.state.read(cx);
383            let composing = state.composition_char_count();
384            (
385                state.validation_error.clone(),
386                state.success_message.clone(),
387                // Exclude the in-flight IME composition from the committed
388                // count; the footer shows it separately.
389                state.content.chars().count() - composing,
390                state.validation_rules.max_length,
391                !state.content.is_empty(),
392                composing,
393            )
394        };
395
396        // A failed validation (e.g. on blur) shows the destructive border just
397        // like an explicit `.error(true)`.
398        let has_error = self.error || validation_error.is_some();
399
400        let (bg_color, border_color, text_color) = if self.disabled {
401            (
402                theme.tokens.muted.opacity(0.5),
403                theme.tokens.border,
404                theme.tokens.muted_foreground,
405            )
406        } else if has_error {
407            match self.variant {
408                InputVariant::Default => (
409                    theme.tokens.background,
410                    theme.tokens.destructive,
411                    theme.tokens.foreground,
412                ),
413                InputVariant::Outline => (
414                    theme.tokens.background,
415                    theme.tokens.destructive,
416                    theme.tokens.foreground,
417                ),
418                InputVariant::Ghost => (
419                    gpui::transparent_black(),
420                    theme.tokens.destructive.opacity(0.3),
421                    theme.tokens.foreground,
422                ),
423            }
424        } else {
425            match self.variant {
426                InputVariant::Default => (
427                    theme.tokens.background,
428                    theme.tokens.input,
429                    theme.tokens.foreground,
430                ),
431                InputVariant::Outline => (
432                    theme.tokens.background,
433                    theme.tokens.border,
434                    theme.tokens.foreground,
435                ),
436                InputVariant::Ghost => (
437                    gpui::transparent_black(),
438                    theme.tokens.border.opacity(0.3),
439                    theme.tokens.foreground,
440                ),
441            }
442        };
443
444        let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
445        let user_style = self.style;
446
447        let has_footer = self.helper_text.is_some()
448            || validation_error.is_some()
449            || success_message.is_some()
450            || self.show_character_count;
451        let footer_message = if let Some(error) = validation_error.as_ref() {
452            FooterMessage::Error(error)
453        } else if let Some(success) = success_message.as_ref() {
454            if has_value {
455                FooterMessage::Success(success)
456            } else {
457                FooterMessage::Blank
458            }
459        } else if let Some(helper) = self.helper_text.as_ref() {
460            FooterMessage::Helper(helper)
461        } else {
462            FooterMessage::Blank
463        };
464        let character_count = self.show_character_count.then_some(CharacterCount {
465            committed: content_length,
466            composing,
467            max: max_length,
468        });
469
470        let field = wire_actions(&self.state, window, cx)
471            .debug_selector(|| "textarea-field".into())
472            .role(Role::MultilineTextInput)
473            .when_some(self.aria_label.clone(), |this, label| {
474                this.aria_label(label)
475            })
476            .when_some(self.aria_description.clone(), |this, description| {
477                this.aria_description(description)
478            })
479            .aria_value(self.state.read(cx).content.clone())
480            .aria_placeholder(self.placeholder.clone())
481            .aria_disabled(self.disabled)
482            .aria_required(self.state.read(cx).validation_rules.required)
483            .when(has_error, |this| {
484                this.aria_invalid(gpui::accesskit::Invalid::True)
485            })
486            .w_full()
487            .h(height)
488            .flex_shrink_0()
489            .when(self.auto_grow, |this| this.min_h(height))
490            .px(px(12.0))
491            .py(px(8.0))
492            .bg(bg_color)
493            .border_1()
494            .border_color(border_color)
495            .rounded(theme.tokens.radius_md)
496            .text_size(px(14.0))
497            .font_family(theme.tokens.font_mono.clone())
498            .text_color(text_color)
499            .when(!self.disabled, |this| {
500                this.hover(|style| {
501                    style.border_color(if has_error {
502                        theme.tokens.destructive
503                    } else {
504                        theme.tokens.ring
505                    })
506                })
507            })
508            .when(is_focused && !self.disabled, |this| {
509                this.border_color(if has_error {
510                    theme.tokens.destructive
511                } else {
512                    theme.tokens.ring
513                })
514            })
515            .when(!self.disabled, |this| this.cursor(gpui::CursorStyle::IBeam))
516            .child(self.state.clone());
517
518        if has_footer {
519            VStack::new()
520                .debug_selector(|| "textarea-root".into())
521                .w_full()
522                .gap(px(4.0))
523                .child(field)
524                .child(validation_footer(
525                    &theme.tokens,
526                    footer_message,
527                    character_count,
528                ))
529                .map(|this| {
530                    let mut vstack = this;
531                    vstack.style().refine(&user_style);
532                    vstack
533                })
534                .into_any_element()
535        } else {
536            field
537                .map(|this| {
538                    let mut div = this;
539                    div.style().refine(&user_style);
540                    div
541                })
542                .into_any_element()
543        }
544    }
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use crate::capabilities::foundation::theme::{install_theme, Theme};
551    use std::{cell::Cell, rc::Rc};
552
553    struct TextareaRenderTestView {
554        state: Entity<TextareaState>,
555        callback_calls: Option<Rc<Cell<usize>>>,
556    }
557
558    impl Render for TextareaRenderTestView {
559        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
560            Textarea::new(&self.state).when_some(self.callback_calls.clone(), |textarea, calls| {
561                textarea.on_change(move |_, _| calls.set(calls.get() + 1))
562            })
563        }
564    }
565
566    #[gpui::test]
567    fn repeated_render_replaces_textarea_event_subscription() {
568        let mut app = TestApp::new();
569        app.update(|cx| install_theme(cx, Theme::light()));
570        let stale_calls = Rc::new(Cell::new(0));
571        let current_calls = Rc::new(Cell::new(0));
572        let mut window = app.open_window(|_, cx| TextareaRenderTestView {
573            state: cx.new(TextareaState::new),
574            callback_calls: Some(stale_calls.clone()),
575        });
576
577        window.draw();
578        window.update(|view, _, cx| {
579            view.callback_calls = Some(current_calls.clone());
580            cx.notify();
581        });
582        window.draw();
583        window.update(|view, _, cx| {
584            view.state
585                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
586        });
587        assert_eq!(stale_calls.get(), 0);
588        assert_eq!(current_calls.get(), 1);
589
590        window.update(|view, _, cx| {
591            view.callback_calls = None;
592            cx.notify();
593        });
594        window.draw();
595        window.update(|view, _, cx| {
596            view.state
597                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
598        });
599        assert_eq!(current_calls.get(), 1);
600    }
601
602    struct BareTextareaTestView {
603        state: Entity<TextareaState>,
604    }
605
606    impl Render for BareTextareaTestView {
607        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
608            wire_actions(&self.state, window, cx)
609                .h(px(96.0))
610                .px(px(12.0))
611                .rounded(px(8.0))
612                .child(self.state.clone())
613        }
614    }
615
616    #[gpui::test]
617    fn wire_actions_gives_custom_textarea_containers_full_keyboard_editing() {
618        let mut app = TestApp::new();
619        app.update(|cx| {
620            install_theme(cx, Theme::light());
621            crate::capabilities::controls::textarea_state::init(cx);
622        });
623        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
624        let mut window = app.open_window(|_, _| BareTextareaTestView {
625            state: state.clone(),
626        });
627
628        window.draw();
629        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
630        window.draw();
631        let handle: AnyWindowHandle = window.handle().into();
632        app.raw_context_mut()
633            .simulate_keystrokes(handle, "backspace");
634        app.flush();
635
636        app.update(|cx| {
637            assert_eq!(state.read(cx).content(), "hell");
638        });
639    }
640    struct FooterTextareaTestView {
641        state: Entity<TextareaState>,
642        validate_errors: Rc<Cell<usize>>,
643    }
644
645    impl Render for FooterTextareaTestView {
646        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
647            let validate_errors = self.validate_errors.clone();
648            Textarea::new(&self.state)
649                .required(true)
650                .max_length(3)
651                .helper_text("hint")
652                .show_character_count(true)
653                .on_validate(move |result, _| {
654                    if result.is_err() {
655                        validate_errors.set(validate_errors.get() + 1);
656                    }
657                })
658        }
659    }
660
661    #[gpui::test]
662    fn footer_renders_and_blur_validation_reaches_on_validate() {
663        let mut app = TestApp::new();
664        app.update(|cx| {
665            install_theme(cx, Theme::light());
666            crate::capabilities::controls::textarea_state::init(cx);
667        });
668        let validate_errors = Rc::new(Cell::new(0));
669        let state = app.update(|cx| cx.new(TextareaState::new));
670        let mut window = app.open_window(|_, _| FooterTextareaTestView {
671            state: state.clone(),
672            validate_errors: validate_errors.clone(),
673        });
674        window.draw();
675        window.draw();
676        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
677        window.draw();
678        // Moving focus elsewhere drives the blur -> validate_on_blur path.
679        window.update(|_, window, cx| cx.focus_handle().focus(window));
680        window.draw();
681
682        assert_eq!(validate_errors.get(), 1);
683        app.update(|cx| assert!(state.read(cx).validation_error.is_some()));
684    }
685
686    #[gpui::test]
687    fn max_length_truncates_typed_input() {
688        let mut app = TestApp::new();
689        app.update(|cx| {
690            install_theme(cx, Theme::light());
691            crate::capabilities::controls::textarea_state::init(cx);
692        });
693        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
694        let mut window = app.open_window(|_, _| BareTextareaTestView {
695            state: state.clone(),
696        });
697        window.draw();
698        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
699        window.draw();
700        let handle: AnyWindowHandle = window.handle().into();
701        app.raw_context_mut().simulate_keystrokes(handle, "abcde");
702        app.flush();
703
704        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
705    }
706
707    #[gpui::test]
708    fn set_value_truncates_to_max_length() {
709        let mut app = TestApp::new();
710        app.update(|cx| {
711            install_theme(cx, Theme::light());
712            crate::capabilities::controls::textarea_state::init(cx);
713        });
714        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
715        let mut window = app.open_window(|_, _| BareTextareaTestView {
716            state: state.clone(),
717        });
718        window.draw();
719        window.update(|_, window, cx| {
720            state.update(cx, |state, cx| state.set_value("abcdef", window, cx));
721        });
722
723        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
724    }
725
726    #[gpui::test]
727    fn rejected_max_length_input_does_not_emit_change() {
728        let mut app = TestApp::new();
729        app.update(|cx| {
730            install_theme(cx, Theme::light());
731            crate::capabilities::controls::textarea_state::init(cx);
732        });
733        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abc")));
734        let changes = Rc::new(Cell::new(0));
735        let changes_for_subscription = changes.clone();
736        app.update(|cx| {
737            cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
738                if matches!(event, TextareaEvent::Change) {
739                    changes_for_subscription.set(changes_for_subscription.get() + 1);
740                }
741            })
742            .detach();
743        });
744
745        let mut window = app.open_window(|_, _| BareTextareaTestView {
746            state: state.clone(),
747        });
748        window.draw();
749        window.update(|_, window, cx| {
750            state.update(cx, |state, cx| {
751                state.replace_text_in_range(None, "d", window, cx)
752            });
753        });
754
755        app.update(|cx| {
756            assert_eq!(state.read(cx).content(), "abc");
757            assert_eq!(changes.get(), 0);
758        });
759    }
760
761    #[gpui::test]
762    fn validate_on_change_runs_after_set_value() {
763        let mut app = TestApp::new();
764        app.update(|cx| {
765            install_theme(cx, Theme::light());
766            crate::capabilities::controls::textarea_state::init(cx);
767        });
768        let state = app.update(|cx| {
769            cx.new(|cx| {
770                let mut state = TextareaState::new(cx).required(true).value("x");
771                state.validate_on_change = true;
772                state
773            })
774        });
775        let mut window = app.open_window(|_, _| BareTextareaTestView {
776            state: state.clone(),
777        });
778        window.draw();
779        window.update(|_, window, cx| {
780            state.update(cx, |state, cx| state.set_value("", window, cx));
781        });
782
783        app.update(|cx| {
784            assert_eq!(
785                state
786                    .read(cx)
787                    .validation_error
788                    .as_ref()
789                    .unwrap()
790                    .message
791                    .as_ref(),
792                "This field is required"
793            );
794        });
795    }
796
797    #[gpui::test]
798    fn auto_validation_stays_silent_without_rules() {
799        let mut app = TestApp::new();
800        app.update(|cx| {
801            install_theme(cx, Theme::light());
802            crate::capabilities::controls::textarea_state::init(cx);
803        });
804        // No rules configured: blur and change must not produce validation
805        // messages, so existing plain textareas render exactly as before.
806        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
807        let mut window = app.open_window(|_, _| BareTextareaTestView {
808            state: state.clone(),
809        });
810        window.draw();
811        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
812        window.draw();
813        window.update(|_, window, cx| cx.focus_handle().focus(window));
814        window.draw();
815        window.update(|_, window, cx| {
816            state.update(cx, |state, cx| state.set_value("changed", window, cx));
817        });
818
819        app.update(|cx| {
820            let state = state.read(cx);
821            assert!(state.validation_error.is_none());
822            assert!(state.success_message.is_none());
823        });
824    }
825}