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    #[allow(clippy::arc_with_non_send_sync)]
243    fn validation_rules_for_state(&self) -> Option<ValidationRules> {
244        let mut rules = self.validation_rules.clone().or_else(|| {
245            self.custom_validator
246                .is_some()
247                .then(ValidationRules::default)
248        })?;
249
250        if let Some(custom_validator) = self.custom_validator.as_ref() {
251            let validator = custom_validator.clone();
252            rules.custom_validator = Some(Arc::new(move |value| match validator(value) {
253                Ok(()) => Ok(()),
254                Err(message) => Err(ValidationError {
255                    message: message.into(),
256                    field_name: None,
257                }),
258            }));
259        }
260
261        Some(rules)
262    }
263
264    fn install_event_subscription(&self, cx: &mut App) {
265        let on_change = self.on_change.clone();
266        let on_enter = self.on_enter.clone();
267        let on_shift_enter = self.on_shift_enter.clone();
268        let on_focus = self.on_focus.clone();
269        let on_blur = self.on_blur.clone();
270        let on_validate = self.on_validate.clone();
271
272        let has_callbacks = on_change.is_some()
273            || on_enter.is_some()
274            || on_shift_enter.is_some()
275            || on_focus.is_some()
276            || on_blur.is_some()
277            || on_validate.is_some();
278        let subscription = has_callbacks.then(|| {
279            cx.subscribe(
280                &self.state,
281                move |emitter, event: &TextareaEvent, cx| match event {
282                    TextareaEvent::Change => {
283                        if let Some(callback) = on_change.as_ref() {
284                            callback(emitter.read(cx).content.clone(), cx);
285                        }
286                    }
287                    TextareaEvent::Enter => {
288                        if let Some(callback) = on_enter.as_ref() {
289                            callback(emitter.read(cx).content.clone(), cx);
290                        }
291                    }
292                    TextareaEvent::ShiftEnter => {
293                        if let Some(callback) = on_shift_enter.as_ref() {
294                            callback(emitter.read(cx).content.clone(), cx);
295                        }
296                    }
297                    TextareaEvent::Focus => {
298                        if let Some(callback) = on_focus.as_ref() {
299                            callback(emitter.read(cx).content.clone(), cx);
300                        }
301                    }
302                    TextareaEvent::Blur => {
303                        if let Some(callback) = on_blur.as_ref() {
304                            callback(emitter.read(cx).content.clone(), cx);
305                        }
306                    }
307                    TextareaEvent::Validate(result) => {
308                        if let Some(callback) = on_validate.as_ref() {
309                            callback(result.clone(), cx);
310                        }
311                    }
312                    TextareaEvent::Tab | TextareaEvent::ShiftTab => {}
313                },
314            )
315        });
316
317        self.state.update(cx, |state, _| {
318            state.replace_event_subscription(subscription);
319        });
320    }
321
322    fn calculate_height(&self, window: &Window, cx: &App) -> Pixels {
323        let line_height = window.line_height().to_f64() as f32;
324        let padding_y = 8.0;
325        let base_height = self.rows as f32 * line_height + padding_y * 2.0;
326
327        if self.auto_grow {
328            let visual_lines = self.state.read(cx).visual_line_count_for_layout().max(1);
329            let content_height = visual_lines as f32 * line_height + padding_y * 2.0;
330
331            let final_height = if let Some(min_rows) = self.min_rows {
332                let min_height = min_rows as f32 * line_height + padding_y * 2.0;
333                content_height.max(min_height)
334            } else {
335                content_height.max(base_height)
336            };
337
338            if let Some(max_rows) = self.max_rows {
339                let max_height = max_rows as f32 * line_height + padding_y * 2.0;
340                px(final_height.min(max_height))
341            } else {
342                px(final_height)
343            }
344        } else {
345            px(base_height)
346        }
347    }
348}
349
350impl Styled for Textarea {
351    fn style(&mut self) -> &mut StyleRefinement {
352        &mut self.style
353    }
354}
355
356impl RenderOnce for Textarea {
357    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
358        let theme = use_theme(cx);
359        let height = self.calculate_height(window, cx);
360
361        // Update state with properties
362        self.state.update(cx, |state, cx| {
363            state.disabled = self.disabled;
364            state.placeholder = self.placeholder.clone();
365
366            // Apply rules before the initial value so `set_value` truncates
367            // against `max_length` on first render too.
368            if let Some(rules) = self.validation_rules_for_state() {
369                state.validation_rules = rules;
370            }
371
372            if !state.initialized {
373                state.initialized = true;
374                if let Some(value) = self.initial_value.clone() {
375                    state.set_value(value, window, cx);
376                }
377            }
378        });
379
380        self.install_event_subscription(cx);
381
382        let (validation_error, success_message, content_length, max_length, has_value, composing) = {
383            let state = self.state.read(cx);
384            let composing = state.composition_char_count();
385            (
386                state.validation_error.clone(),
387                state.success_message.clone(),
388                // Exclude the in-flight IME composition from the committed
389                // count; the footer shows it separately.
390                state.content.chars().count() - composing,
391                state.validation_rules.max_length,
392                !state.content.is_empty(),
393                composing,
394            )
395        };
396
397        // A failed validation (e.g. on blur) shows the destructive border just
398        // like an explicit `.error(true)`.
399        let has_error = self.error || validation_error.is_some();
400
401        let (bg_color, border_color, text_color) = if self.disabled {
402            (
403                theme.tokens.muted.opacity(0.5),
404                theme.tokens.border,
405                theme.tokens.muted_foreground,
406            )
407        } else if has_error {
408            match self.variant {
409                InputVariant::Default => (
410                    theme.tokens.background,
411                    theme.tokens.destructive,
412                    theme.tokens.foreground,
413                ),
414                InputVariant::Outline => (
415                    theme.tokens.background,
416                    theme.tokens.destructive,
417                    theme.tokens.foreground,
418                ),
419                InputVariant::Ghost => (
420                    gpui::transparent_black(),
421                    theme.tokens.destructive.opacity(0.3),
422                    theme.tokens.foreground,
423                ),
424            }
425        } else {
426            match self.variant {
427                InputVariant::Default => (
428                    theme.tokens.background,
429                    theme.tokens.input,
430                    theme.tokens.foreground,
431                ),
432                InputVariant::Outline => (
433                    theme.tokens.background,
434                    theme.tokens.border,
435                    theme.tokens.foreground,
436                ),
437                InputVariant::Ghost => (
438                    gpui::transparent_black(),
439                    theme.tokens.border.opacity(0.3),
440                    theme.tokens.foreground,
441                ),
442            }
443        };
444
445        let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
446        let user_style = self.style;
447
448        let has_footer = self.helper_text.is_some()
449            || validation_error.is_some()
450            || success_message.is_some()
451            || self.show_character_count;
452        let footer_message = if let Some(error) = validation_error.as_ref() {
453            FooterMessage::Error(error)
454        } else if let Some(success) = success_message.as_ref() {
455            if has_value {
456                FooterMessage::Success(success)
457            } else {
458                FooterMessage::Blank
459            }
460        } else if let Some(helper) = self.helper_text.as_ref() {
461            FooterMessage::Helper(helper)
462        } else {
463            FooterMessage::Blank
464        };
465        let character_count = self.show_character_count.then_some(CharacterCount {
466            committed: content_length,
467            composing,
468            max: max_length,
469        });
470
471        let field = wire_actions(&self.state, window, cx)
472            .debug_selector(|| "textarea-field".into())
473            .role(Role::MultilineTextInput)
474            .when_some(self.aria_label.clone(), |this, label| {
475                this.aria_label(label)
476            })
477            .when_some(self.aria_description.clone(), |this, description| {
478                this.aria_description(description)
479            })
480            .aria_value(self.state.read(cx).content.clone())
481            .aria_placeholder(self.placeholder.clone())
482            .aria_disabled(self.disabled)
483            .aria_required(self.state.read(cx).validation_rules.required)
484            .when(has_error, |this| {
485                this.aria_invalid(gpui::accesskit::Invalid::True)
486            })
487            .w_full()
488            .h(height)
489            .flex_shrink_0()
490            .when(self.auto_grow, |this| this.min_h(height))
491            .px(px(12.0))
492            .py(px(8.0))
493            .bg(bg_color)
494            .border_1()
495            .border_color(border_color)
496            .rounded(theme.tokens.radius_md)
497            .text_size(px(14.0))
498            .font_family(theme.tokens.font_mono.clone())
499            .text_color(text_color)
500            .when(!self.disabled, |this| {
501                this.hover(|style| {
502                    style.border_color(if has_error {
503                        theme.tokens.destructive
504                    } else {
505                        theme.tokens.ring
506                    })
507                })
508            })
509            .when(is_focused && !self.disabled, |this| {
510                this.border_color(if has_error {
511                    theme.tokens.destructive
512                } else {
513                    theme.tokens.ring
514                })
515            })
516            .when(!self.disabled, |this| this.cursor(gpui::CursorStyle::IBeam))
517            .child(self.state.clone());
518
519        if has_footer {
520            VStack::new()
521                .debug_selector(|| "textarea-root".into())
522                .w_full()
523                .gap(px(4.0))
524                .child(field)
525                .child(validation_footer(
526                    &theme.tokens,
527                    footer_message,
528                    character_count,
529                ))
530                .map(|this| {
531                    let mut vstack = this;
532                    vstack.style().refine(&user_style);
533                    vstack
534                })
535                .into_any_element()
536        } else {
537            field
538                .map(|this| {
539                    let mut div = this;
540                    div.style().refine(&user_style);
541                    div
542                })
543                .into_any_element()
544        }
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551    use crate::capabilities::foundation::theme::{install_theme, Theme};
552    use std::{cell::Cell, rc::Rc};
553
554    struct TextareaRenderTestView {
555        state: Entity<TextareaState>,
556        callback_calls: Option<Rc<Cell<usize>>>,
557    }
558
559    impl Render for TextareaRenderTestView {
560        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
561            Textarea::new(&self.state).when_some(self.callback_calls.clone(), |textarea, calls| {
562                textarea.on_change(move |_, _| calls.set(calls.get() + 1))
563            })
564        }
565    }
566
567    #[gpui::test]
568    fn repeated_render_replaces_textarea_event_subscription() {
569        let mut app = TestApp::new();
570        app.update(|cx| install_theme(cx, Theme::light()));
571        let stale_calls = Rc::new(Cell::new(0));
572        let current_calls = Rc::new(Cell::new(0));
573        let mut window = app.open_window(|_, cx| TextareaRenderTestView {
574            state: cx.new(TextareaState::new),
575            callback_calls: Some(stale_calls.clone()),
576        });
577
578        window.draw();
579        window.update(|view, _, cx| {
580            view.callback_calls = Some(current_calls.clone());
581            cx.notify();
582        });
583        window.draw();
584        window.update(|view, _, cx| {
585            view.state
586                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
587        });
588        assert_eq!(stale_calls.get(), 0);
589        assert_eq!(current_calls.get(), 1);
590
591        window.update(|view, _, cx| {
592            view.callback_calls = None;
593            cx.notify();
594        });
595        window.draw();
596        window.update(|view, _, cx| {
597            view.state
598                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
599        });
600        assert_eq!(current_calls.get(), 1);
601    }
602
603    struct BareTextareaTestView {
604        state: Entity<TextareaState>,
605    }
606
607    impl Render for BareTextareaTestView {
608        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
609            wire_actions(&self.state, window, cx)
610                .h(px(96.0))
611                .px(px(12.0))
612                .rounded(px(8.0))
613                .child(self.state.clone())
614        }
615    }
616
617    #[gpui::test]
618    fn wire_actions_gives_custom_textarea_containers_full_keyboard_editing() {
619        let mut app = TestApp::new();
620        app.update(|cx| {
621            install_theme(cx, Theme::light());
622            crate::capabilities::controls::textarea_state::init(cx);
623        });
624        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
625        let mut window = app.open_window(|_, _| BareTextareaTestView {
626            state: state.clone(),
627        });
628
629        window.draw();
630        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
631        window.draw();
632        let handle: AnyWindowHandle = window.handle().into();
633        app.raw_context_mut()
634            .simulate_keystrokes(handle, "backspace");
635        app.flush();
636
637        app.update(|cx| {
638            assert_eq!(state.read(cx).content(), "hell");
639        });
640    }
641    struct FooterTextareaTestView {
642        state: Entity<TextareaState>,
643        validate_errors: Rc<Cell<usize>>,
644    }
645
646    impl Render for FooterTextareaTestView {
647        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
648            let validate_errors = self.validate_errors.clone();
649            Textarea::new(&self.state)
650                .required(true)
651                .max_length(3)
652                .helper_text("hint")
653                .show_character_count(true)
654                .on_validate(move |result, _| {
655                    if result.is_err() {
656                        validate_errors.set(validate_errors.get() + 1);
657                    }
658                })
659        }
660    }
661
662    #[gpui::test]
663    fn footer_renders_and_blur_validation_reaches_on_validate() {
664        let mut app = TestApp::new();
665        app.update(|cx| {
666            install_theme(cx, Theme::light());
667            crate::capabilities::controls::textarea_state::init(cx);
668        });
669        let validate_errors = Rc::new(Cell::new(0));
670        let state = app.update(|cx| cx.new(TextareaState::new));
671        let mut window = app.open_window(|_, _| FooterTextareaTestView {
672            state: state.clone(),
673            validate_errors: validate_errors.clone(),
674        });
675        window.draw();
676        window.draw();
677        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
678        window.draw();
679        // Moving focus elsewhere drives the blur -> validate_on_blur path.
680        window.update(|_, window, cx| cx.focus_handle().focus(window));
681        window.draw();
682
683        assert_eq!(validate_errors.get(), 1);
684        app.update(|cx| assert!(state.read(cx).validation_error.is_some()));
685    }
686
687    #[gpui::test]
688    fn max_length_truncates_typed_input() {
689        let mut app = TestApp::new();
690        app.update(|cx| {
691            install_theme(cx, Theme::light());
692            crate::capabilities::controls::textarea_state::init(cx);
693        });
694        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
695        let mut window = app.open_window(|_, _| BareTextareaTestView {
696            state: state.clone(),
697        });
698        window.draw();
699        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
700        window.draw();
701        let handle: AnyWindowHandle = window.handle().into();
702        app.raw_context_mut().simulate_keystrokes(handle, "abcde");
703        app.flush();
704
705        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
706    }
707
708    #[gpui::test]
709    fn set_value_truncates_to_max_length() {
710        let mut app = TestApp::new();
711        app.update(|cx| {
712            install_theme(cx, Theme::light());
713            crate::capabilities::controls::textarea_state::init(cx);
714        });
715        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
716        let mut window = app.open_window(|_, _| BareTextareaTestView {
717            state: state.clone(),
718        });
719        window.draw();
720        window.update(|_, window, cx| {
721            state.update(cx, |state, cx| state.set_value("abcdef", window, cx));
722        });
723
724        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
725    }
726
727    #[gpui::test]
728    fn rejected_max_length_input_does_not_emit_change() {
729        let mut app = TestApp::new();
730        app.update(|cx| {
731            install_theme(cx, Theme::light());
732            crate::capabilities::controls::textarea_state::init(cx);
733        });
734        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abc")));
735        let changes = Rc::new(Cell::new(0));
736        let changes_for_subscription = changes.clone();
737        app.update(|cx| {
738            cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
739                if matches!(event, TextareaEvent::Change) {
740                    changes_for_subscription.set(changes_for_subscription.get() + 1);
741                }
742            })
743            .detach();
744        });
745
746        let mut window = app.open_window(|_, _| BareTextareaTestView {
747            state: state.clone(),
748        });
749        window.draw();
750        window.update(|_, window, cx| {
751            state.update(cx, |state, cx| {
752                state.replace_text_in_range(None, "d", window, cx)
753            });
754        });
755
756        app.update(|cx| {
757            assert_eq!(state.read(cx).content(), "abc");
758            assert_eq!(changes.get(), 0);
759        });
760    }
761
762    #[gpui::test]
763    fn validate_on_change_runs_after_set_value() {
764        let mut app = TestApp::new();
765        app.update(|cx| {
766            install_theme(cx, Theme::light());
767            crate::capabilities::controls::textarea_state::init(cx);
768        });
769        let state = app.update(|cx| {
770            cx.new(|cx| {
771                let mut state = TextareaState::new(cx).required(true).value("x");
772                state.validate_on_change = true;
773                state
774            })
775        });
776        let mut window = app.open_window(|_, _| BareTextareaTestView {
777            state: state.clone(),
778        });
779        window.draw();
780        window.update(|_, window, cx| {
781            state.update(cx, |state, cx| state.set_value("", window, cx));
782        });
783
784        app.update(|cx| {
785            assert_eq!(
786                state
787                    .read(cx)
788                    .validation_error
789                    .as_ref()
790                    .unwrap()
791                    .message
792                    .as_ref(),
793                "This field is required"
794            );
795        });
796    }
797
798    #[gpui::test]
799    fn auto_validation_stays_silent_without_rules() {
800        let mut app = TestApp::new();
801        app.update(|cx| {
802            install_theme(cx, Theme::light());
803            crate::capabilities::controls::textarea_state::init(cx);
804        });
805        // No rules configured: blur and change must not produce validation
806        // messages, so existing plain textareas render exactly as before.
807        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
808        let mut window = app.open_window(|_, _| BareTextareaTestView {
809            state: state.clone(),
810        });
811        window.draw();
812        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
813        window.draw();
814        window.update(|_, window, cx| cx.focus_handle().focus(window));
815        window.draw();
816        window.update(|_, window, cx| {
817            state.update(cx, |state, cx| state.set_value("changed", window, cx));
818        });
819
820        app.update(|cx| {
821            let state = state.read(cx);
822            assert!(state.validation_error.is_none());
823            assert!(state.success_message.is_none());
824        });
825    }
826}