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            .role(Role::MultilineTextInput)
472            .when_some(self.aria_label.clone(), |this, label| {
473                this.aria_label(label)
474            })
475            .when_some(self.aria_description.clone(), |this, description| {
476                this.aria_description(description)
477            })
478            .aria_value(self.state.read(cx).content.clone())
479            .aria_placeholder(self.placeholder.clone())
480            .aria_disabled(self.disabled)
481            .aria_required(self.state.read(cx).validation_rules.required)
482            .when(has_error, |this| {
483                this.aria_invalid(gpui::accesskit::Invalid::True)
484            })
485            .w_full()
486            .h(height)
487            .flex_shrink_0()
488            .when(self.auto_grow, |this| this.min_h(height))
489            .px(px(12.0))
490            .py(px(8.0))
491            .bg(bg_color)
492            .border_1()
493            .border_color(border_color)
494            .rounded(theme.tokens.radius_md)
495            .text_size(px(14.0))
496            .font_family(theme.tokens.font_mono.clone())
497            .text_color(text_color)
498            .when(!self.disabled, |this| {
499                this.hover(|style| {
500                    style.border_color(if has_error {
501                        theme.tokens.destructive
502                    } else {
503                        theme.tokens.ring
504                    })
505                })
506            })
507            .when(is_focused && !self.disabled, |this| {
508                this.border_color(if has_error {
509                    theme.tokens.destructive
510                } else {
511                    theme.tokens.ring
512                })
513            })
514            .when(!self.disabled, |this| this.cursor(gpui::CursorStyle::IBeam))
515            .child(self.state.clone());
516
517        if has_footer {
518            VStack::new()
519                .w_full()
520                .gap(px(4.0))
521                .child(field)
522                .child(validation_footer(
523                    &theme.tokens,
524                    footer_message,
525                    character_count,
526                ))
527                .map(|this| {
528                    let mut vstack = this;
529                    vstack.style().refine(&user_style);
530                    vstack
531                })
532                .into_any_element()
533        } else {
534            field
535                .map(|this| {
536                    let mut div = this;
537                    div.style().refine(&user_style);
538                    div
539                })
540                .into_any_element()
541        }
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use crate::capabilities::foundation::theme::{install_theme, Theme};
549    use std::{cell::Cell, rc::Rc};
550
551    struct TextareaRenderTestView {
552        state: Entity<TextareaState>,
553        callback_calls: Option<Rc<Cell<usize>>>,
554    }
555
556    impl Render for TextareaRenderTestView {
557        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
558            Textarea::new(&self.state).when_some(self.callback_calls.clone(), |textarea, calls| {
559                textarea.on_change(move |_, _| calls.set(calls.get() + 1))
560            })
561        }
562    }
563
564    #[gpui::test]
565    fn repeated_render_replaces_textarea_event_subscription() {
566        let mut app = TestApp::new();
567        app.update(|cx| install_theme(cx, Theme::light()));
568        let stale_calls = Rc::new(Cell::new(0));
569        let current_calls = Rc::new(Cell::new(0));
570        let mut window = app.open_window(|_, cx| TextareaRenderTestView {
571            state: cx.new(TextareaState::new),
572            callback_calls: Some(stale_calls.clone()),
573        });
574
575        window.draw();
576        window.update(|view, _, cx| {
577            view.callback_calls = Some(current_calls.clone());
578            cx.notify();
579        });
580        window.draw();
581        window.update(|view, _, cx| {
582            view.state
583                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
584        });
585        assert_eq!(stale_calls.get(), 0);
586        assert_eq!(current_calls.get(), 1);
587
588        window.update(|view, _, cx| {
589            view.callback_calls = None;
590            cx.notify();
591        });
592        window.draw();
593        window.update(|view, _, cx| {
594            view.state
595                .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
596        });
597        assert_eq!(current_calls.get(), 1);
598    }
599
600    struct BareTextareaTestView {
601        state: Entity<TextareaState>,
602    }
603
604    impl Render for BareTextareaTestView {
605        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
606            wire_actions(&self.state, window, cx)
607                .h(px(96.0))
608                .px(px(12.0))
609                .rounded(px(8.0))
610                .child(self.state.clone())
611        }
612    }
613
614    #[gpui::test]
615    fn wire_actions_gives_custom_textarea_containers_full_keyboard_editing() {
616        let mut app = TestApp::new();
617        app.update(|cx| {
618            install_theme(cx, Theme::light());
619            crate::capabilities::controls::textarea_state::init(cx);
620        });
621        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
622        let mut window = app.open_window(|_, _| BareTextareaTestView {
623            state: state.clone(),
624        });
625
626        window.draw();
627        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
628        window.draw();
629        let handle: AnyWindowHandle = window.handle().into();
630        app.raw_context_mut()
631            .simulate_keystrokes(handle, "backspace");
632        app.flush();
633
634        app.update(|cx| {
635            assert_eq!(state.read(cx).content(), "hell");
636        });
637    }
638    struct FooterTextareaTestView {
639        state: Entity<TextareaState>,
640        validate_errors: Rc<Cell<usize>>,
641    }
642
643    impl Render for FooterTextareaTestView {
644        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
645            let validate_errors = self.validate_errors.clone();
646            Textarea::new(&self.state)
647                .required(true)
648                .max_length(3)
649                .helper_text("hint")
650                .show_character_count(true)
651                .on_validate(move |result, _| {
652                    if result.is_err() {
653                        validate_errors.set(validate_errors.get() + 1);
654                    }
655                })
656        }
657    }
658
659    #[gpui::test]
660    fn footer_renders_and_blur_validation_reaches_on_validate() {
661        let mut app = TestApp::new();
662        app.update(|cx| {
663            install_theme(cx, Theme::light());
664            crate::capabilities::controls::textarea_state::init(cx);
665        });
666        let validate_errors = Rc::new(Cell::new(0));
667        let state = app.update(|cx| cx.new(TextareaState::new));
668        let mut window = app.open_window(|_, _| FooterTextareaTestView {
669            state: state.clone(),
670            validate_errors: validate_errors.clone(),
671        });
672        window.draw();
673        window.draw();
674        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
675        window.draw();
676        // Moving focus elsewhere drives the blur -> validate_on_blur path.
677        window.update(|_, window, cx| cx.focus_handle().focus(window));
678        window.draw();
679
680        assert_eq!(validate_errors.get(), 1);
681        app.update(|cx| assert!(state.read(cx).validation_error.is_some()));
682    }
683
684    #[gpui::test]
685    fn max_length_truncates_typed_input() {
686        let mut app = TestApp::new();
687        app.update(|cx| {
688            install_theme(cx, Theme::light());
689            crate::capabilities::controls::textarea_state::init(cx);
690        });
691        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
692        let mut window = app.open_window(|_, _| BareTextareaTestView {
693            state: state.clone(),
694        });
695        window.draw();
696        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
697        window.draw();
698        let handle: AnyWindowHandle = window.handle().into();
699        app.raw_context_mut().simulate_keystrokes(handle, "abcde");
700        app.flush();
701
702        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
703    }
704
705    #[gpui::test]
706    fn set_value_truncates_to_max_length() {
707        let mut app = TestApp::new();
708        app.update(|cx| {
709            install_theme(cx, Theme::light());
710            crate::capabilities::controls::textarea_state::init(cx);
711        });
712        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
713        let mut window = app.open_window(|_, _| BareTextareaTestView {
714            state: state.clone(),
715        });
716        window.draw();
717        window.update(|_, window, cx| {
718            state.update(cx, |state, cx| state.set_value("abcdef", window, cx));
719        });
720
721        app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
722    }
723
724    #[gpui::test]
725    fn rejected_max_length_input_does_not_emit_change() {
726        let mut app = TestApp::new();
727        app.update(|cx| {
728            install_theme(cx, Theme::light());
729            crate::capabilities::controls::textarea_state::init(cx);
730        });
731        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abc")));
732        let changes = Rc::new(Cell::new(0));
733        let changes_for_subscription = changes.clone();
734        app.update(|cx| {
735            cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
736                if matches!(event, TextareaEvent::Change) {
737                    changes_for_subscription.set(changes_for_subscription.get() + 1);
738                }
739            })
740            .detach();
741        });
742
743        let mut window = app.open_window(|_, _| BareTextareaTestView {
744            state: state.clone(),
745        });
746        window.draw();
747        window.update(|_, window, cx| {
748            state.update(cx, |state, cx| {
749                state.replace_text_in_range(None, "d", window, cx)
750            });
751        });
752
753        app.update(|cx| {
754            assert_eq!(state.read(cx).content(), "abc");
755            assert_eq!(changes.get(), 0);
756        });
757    }
758
759    #[gpui::test]
760    fn validate_on_change_runs_after_set_value() {
761        let mut app = TestApp::new();
762        app.update(|cx| {
763            install_theme(cx, Theme::light());
764            crate::capabilities::controls::textarea_state::init(cx);
765        });
766        let state = app.update(|cx| {
767            cx.new(|cx| {
768                let mut state = TextareaState::new(cx).required(true).value("x");
769                state.validate_on_change = true;
770                state
771            })
772        });
773        let mut window = app.open_window(|_, _| BareTextareaTestView {
774            state: state.clone(),
775        });
776        window.draw();
777        window.update(|_, window, cx| {
778            state.update(cx, |state, cx| state.set_value("", window, cx));
779        });
780
781        app.update(|cx| {
782            assert_eq!(
783                state
784                    .read(cx)
785                    .validation_error
786                    .as_ref()
787                    .unwrap()
788                    .message
789                    .as_ref(),
790                "This field is required"
791            );
792        });
793    }
794
795    #[gpui::test]
796    fn auto_validation_stays_silent_without_rules() {
797        let mut app = TestApp::new();
798        app.update(|cx| {
799            install_theme(cx, Theme::light());
800            crate::capabilities::controls::textarea_state::init(cx);
801        });
802        // No rules configured: blur and change must not produce validation
803        // messages, so existing plain textareas render exactly as before.
804        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
805        let mut window = app.open_window(|_, _| BareTextareaTestView {
806            state: state.clone(),
807        });
808        window.draw();
809        window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
810        window.draw();
811        window.update(|_, window, cx| cx.focus_handle().focus(window));
812        window.draw();
813        window.update(|_, window, cx| {
814            state.update(cx, |state, cx| state.set_value("changed", window, cx));
815        });
816
817        app.update(|cx| {
818            let state = state.read(cx);
819            assert!(state.validation_error.is_none());
820            assert!(state.success_message.is_none());
821        });
822    }
823}