1use 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
18pub 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 pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
173 self.aria_label = Some(label.into());
174 self
175 }
176
177 pub fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
179 self.aria_description = Some(description.into());
180 self
181 }
182
183 pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
185 self.validation_rules = Some(rules);
186 self
187 }
188
189 pub fn min_length(mut self, min: usize) -> Self {
191 self.rules_mut().min_length = Some(min);
192 self
193 }
194
195 pub fn max_length(mut self, max: usize) -> Self {
197 self.rules_mut().max_length = Some(max);
198 self
199 }
200
201 pub fn required(mut self, required: bool) -> Self {
203 self.rules_mut().required = required;
204 self
205 }
206
207 pub fn helper_text(mut self, text: impl Into<SharedString>) -> Self {
209 self.helper_text = Some(text.into());
210 self
211 }
212
213 pub fn show_character_count(mut self, show: bool) -> Self {
215 self.show_character_count = show;
216 self
217 }
218
219 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 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 self.state.update(cx, |state, cx| {
363 state.disabled = self.disabled;
364 state.placeholder = self.placeholder.clone();
365
366 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 state.content.chars().count() - composing,
391 state.validation_rules.max_length,
392 !state.content.is_empty(),
393 composing,
394 )
395 };
396
397 let has_error = self.error || validation_error.is_some();
400
401 let (bg_color, border_color, text_color) =
402 crate::capabilities::controls::input_shell_colors(
403 self.variant,
404 self.disabled,
405 has_error,
406 &theme.tokens,
407 );
408
409 let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
410 let user_style = self.style;
411
412 let has_footer = self.helper_text.is_some()
413 || validation_error.is_some()
414 || success_message.is_some()
415 || self.show_character_count;
416 let footer_message = if let Some(error) = validation_error.as_ref() {
417 FooterMessage::Error(error)
418 } else if let Some(success) = success_message.as_ref() {
419 if has_value {
420 FooterMessage::Success(success)
421 } else {
422 FooterMessage::Blank
423 }
424 } else if let Some(helper) = self.helper_text.as_ref() {
425 FooterMessage::Helper(helper)
426 } else {
427 FooterMessage::Blank
428 };
429 let character_count = self.show_character_count.then_some(CharacterCount {
430 committed: content_length,
431 composing,
432 max: max_length,
433 });
434
435 let field = wire_actions(&self.state, window, cx)
436 .debug_selector(|| "textarea-field".into())
437 .role(Role::MultilineTextInput)
438 .when_some(self.aria_label.clone(), |this, label| {
439 this.aria_label(label)
440 })
441 .when_some(self.aria_description.clone(), |this, description| {
442 this.aria_description(description)
443 })
444 .aria_value(self.state.read(cx).content.clone())
445 .aria_placeholder(self.placeholder.clone())
446 .aria_disabled(self.disabled)
447 .aria_required(self.state.read(cx).validation_rules.required)
448 .when(has_error, |this| {
449 this.aria_invalid(gpui::accesskit::Invalid::True)
450 })
451 .w_full()
452 .h(height)
453 .flex_shrink_0()
454 .when(self.auto_grow, |this| this.min_h(height))
455 .px(px(12.0))
456 .py(px(8.0))
457 .bg(bg_color)
458 .border_1()
459 .border_color(border_color)
460 .rounded(theme.tokens.radius_md)
461 .text_size(px(14.0))
462 .font_family(theme.tokens.font_mono.clone())
463 .text_color(text_color)
464 .when(!self.disabled, |this| {
465 this.hover(|style| {
466 style.border_color(if has_error {
467 theme.tokens.destructive
468 } else {
469 theme.tokens.ring
470 })
471 })
472 })
473 .when(is_focused && !self.disabled, |this| {
474 this.border_color(if has_error {
475 theme.tokens.destructive
476 } else {
477 theme.tokens.ring
478 })
479 })
480 .when(!self.disabled, |this| this.cursor(gpui::CursorStyle::IBeam))
481 .child(self.state.clone());
482
483 if has_footer {
484 VStack::new()
485 .debug_selector(|| "textarea-root".into())
486 .w_full()
487 .gap(px(4.0))
488 .child(field)
489 .child(validation_footer(
490 &theme.tokens,
491 footer_message,
492 character_count,
493 ))
494 .map(|this| {
495 let mut vstack = this;
496 vstack.style().refine(&user_style);
497 vstack
498 })
499 .into_any_element()
500 } else {
501 field
502 .map(|this| {
503 let mut div = this;
504 div.style().refine(&user_style);
505 div
506 })
507 .into_any_element()
508 }
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515 use crate::capabilities::foundation::theme::{install_theme, Theme};
516 use std::{cell::Cell, rc::Rc};
517
518 struct TextareaRenderTestView {
519 state: Entity<TextareaState>,
520 callback_calls: Option<Rc<Cell<usize>>>,
521 }
522
523 impl Render for TextareaRenderTestView {
524 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
525 Textarea::new(&self.state).when_some(self.callback_calls.clone(), |textarea, calls| {
526 textarea.on_change(move |_, _| calls.set(calls.get() + 1))
527 })
528 }
529 }
530
531 #[gpui::test]
532 fn repeated_render_replaces_textarea_event_subscription() {
533 let mut app = TestApp::new();
534 app.update(|cx| install_theme(cx, Theme::light()));
535 let stale_calls = Rc::new(Cell::new(0));
536 let current_calls = Rc::new(Cell::new(0));
537 let mut window = app.open_window(|_, cx| TextareaRenderTestView {
538 state: cx.new(TextareaState::new),
539 callback_calls: Some(stale_calls.clone()),
540 });
541
542 window.draw();
543 window.update(|view, _, cx| {
544 view.callback_calls = Some(current_calls.clone());
545 cx.notify();
546 });
547 window.draw();
548 window.update(|view, _, cx| {
549 view.state
550 .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
551 });
552 assert_eq!(stale_calls.get(), 0);
553 assert_eq!(current_calls.get(), 1);
554
555 window.update(|view, _, cx| {
556 view.callback_calls = None;
557 cx.notify();
558 });
559 window.draw();
560 window.update(|view, _, cx| {
561 view.state
562 .update(cx, |_, cx| cx.emit(TextareaEvent::Change));
563 });
564 assert_eq!(current_calls.get(), 1);
565 }
566
567 struct BareTextareaTestView {
568 state: Entity<TextareaState>,
569 }
570
571 impl Render for BareTextareaTestView {
572 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
573 wire_actions(&self.state, window, cx)
574 .h(px(96.0))
575 .px(px(12.0))
576 .rounded(px(8.0))
577 .child(self.state.clone())
578 }
579 }
580
581 #[gpui::test]
582 fn wire_actions_gives_custom_textarea_containers_full_keyboard_editing() {
583 let mut app = TestApp::new();
584 app.update(|cx| {
585 install_theme(cx, Theme::light());
586 crate::capabilities::controls::textarea_state::init(cx);
587 });
588 let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).value("hello")));
589 let mut window = app.open_window(|_, _| BareTextareaTestView {
590 state: state.clone(),
591 });
592
593 window.draw();
594 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
595 window.draw();
596 let handle: AnyWindowHandle = window.handle().into();
597 app.raw_context_mut()
598 .simulate_keystrokes(handle, "backspace");
599 app.flush();
600
601 app.update(|cx| {
602 assert_eq!(state.read(cx).content(), "hell");
603 });
604 }
605 struct FooterTextareaTestView {
606 state: Entity<TextareaState>,
607 validate_errors: Rc<Cell<usize>>,
608 }
609
610 impl Render for FooterTextareaTestView {
611 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
612 let validate_errors = self.validate_errors.clone();
613 Textarea::new(&self.state)
614 .required(true)
615 .max_length(3)
616 .helper_text("hint")
617 .show_character_count(true)
618 .on_validate(move |result, _| {
619 if result.is_err() {
620 validate_errors.set(validate_errors.get() + 1);
621 }
622 })
623 }
624 }
625
626 #[gpui::test]
627 fn footer_renders_and_blur_validation_reaches_on_validate() {
628 let mut app = TestApp::new();
629 app.update(|cx| {
630 install_theme(cx, Theme::light());
631 crate::capabilities::controls::textarea_state::init(cx);
632 });
633 let validate_errors = Rc::new(Cell::new(0));
634 let state = app.update(|cx| cx.new(TextareaState::new));
635 let mut window = app.open_window(|_, _| FooterTextareaTestView {
636 state: state.clone(),
637 validate_errors: validate_errors.clone(),
638 });
639 window.draw();
640 window.draw();
641 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
642 window.draw();
643 window.update(|_, window, cx| cx.focus_handle().focus(window));
645 window.draw();
646
647 assert_eq!(validate_errors.get(), 1);
648 app.update(|cx| assert!(state.read(cx).validation_error.is_some()));
649 }
650
651 #[gpui::test]
652 fn max_length_truncates_typed_input() {
653 let mut app = TestApp::new();
654 app.update(|cx| {
655 install_theme(cx, Theme::light());
656 crate::capabilities::controls::textarea_state::init(cx);
657 });
658 let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
659 let mut window = app.open_window(|_, _| BareTextareaTestView {
660 state: state.clone(),
661 });
662 window.draw();
663 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
664 window.draw();
665 let handle: AnyWindowHandle = window.handle().into();
666 app.raw_context_mut().simulate_keystrokes(handle, "abcde");
667 app.flush();
668
669 app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
670 }
671
672 #[gpui::test]
673 fn set_value_truncates_to_max_length() {
674 let mut app = TestApp::new();
675 app.update(|cx| {
676 install_theme(cx, Theme::light());
677 crate::capabilities::controls::textarea_state::init(cx);
678 });
679 let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3)));
680 let mut window = app.open_window(|_, _| BareTextareaTestView {
681 state: state.clone(),
682 });
683 window.draw();
684 window.update(|_, window, cx| {
685 state.update(cx, |state, cx| state.set_value("abcdef", window, cx));
686 });
687
688 app.update(|cx| assert_eq!(state.read(cx).content(), "abc"));
689 }
690
691 #[gpui::test]
692 fn rejected_max_length_input_does_not_emit_change() {
693 let mut app = TestApp::new();
694 app.update(|cx| {
695 install_theme(cx, Theme::light());
696 crate::capabilities::controls::textarea_state::init(cx);
697 });
698 let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abc")));
699 let changes = Rc::new(Cell::new(0));
700 let changes_for_subscription = changes.clone();
701 app.update(|cx| {
702 cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
703 if matches!(event, TextareaEvent::Change) {
704 changes_for_subscription.set(changes_for_subscription.get() + 1);
705 }
706 })
707 .detach();
708 });
709
710 let mut window = app.open_window(|_, _| BareTextareaTestView {
711 state: state.clone(),
712 });
713 window.draw();
714 window.update(|_, window, cx| {
715 state.update(cx, |state, cx| {
716 state.replace_text_in_range(None, "d", window, cx)
717 });
718 });
719
720 app.update(|cx| {
721 assert_eq!(state.read(cx).content(), "abc");
722 assert_eq!(changes.get(), 0);
723 });
724 }
725
726 #[gpui::test]
727 fn validate_on_change_runs_after_set_value() {
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| {
734 cx.new(|cx| {
735 let mut state = TextareaState::new(cx).required(true).value("x");
736 state.validate_on_change = true;
737 state
738 })
739 });
740 let mut window = app.open_window(|_, _| BareTextareaTestView {
741 state: state.clone(),
742 });
743 window.draw();
744 window.update(|_, window, cx| {
745 state.update(cx, |state, cx| state.set_value("", window, cx));
746 });
747
748 app.update(|cx| {
749 assert_eq!(
750 state
751 .read(cx)
752 .validation_error
753 .as_ref()
754 .unwrap()
755 .message
756 .as_ref(),
757 "This field is required"
758 );
759 });
760 }
761
762 #[gpui::test]
763 fn auto_validation_stays_silent_without_rules() {
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| cx.new(|cx| TextareaState::new(cx).value("hello")));
772 let mut window = app.open_window(|_, _| BareTextareaTestView {
773 state: state.clone(),
774 });
775 window.draw();
776 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
777 window.draw();
778 window.update(|_, window, cx| cx.focus_handle().focus(window));
779 window.draw();
780 window.update(|_, window, cx| {
781 state.update(cx, |state, cx| state.set_value("changed", window, cx));
782 });
783
784 app.update(|cx| {
785 let state = state.read(cx);
786 assert!(state.validation_error.is_none());
787 assert!(state.success_message.is_none());
788 });
789 }
790}