1pub use crate::capabilities::controls::input_state::{
4 wire_actions, Backspace, Copy, Cut, Delete, End, Enter, Escape, Home, InputEvent, InputMask,
5 InputState, InputType, Left, Paste, Right, SelectAll, SelectLeft, SelectRight, SelectWordLeft,
6 SelectWordRight, ShiftTab, Tab, ValidationError, ValidationRules, WordLeft, WordRight,
7};
8use crate::capabilities::controls::validation::{validation_footer, CharacterCount, FooterMessage};
9use crate::capabilities::foundation::theme::use_theme;
10use crate::capabilities::layout::{HStack, VStack};
11use crate::capabilities::motion::animations::{easings, shake_offset};
12use crate::capabilities::primitives::icon::Icon;
13use gpui::{prelude::FluentBuilder as _, *};
14use std::rc::Rc;
15use std::sync::Arc;
16use std::time::Duration;
17
18type InputValidator = Rc<dyn Fn(&str) -> Result<(), String>>;
19type InputTransformer = Rc<dyn Fn(&str) -> String>;
20type InputValueCallback = Rc<dyn Fn(SharedString, &mut App)>;
21type InputValidationCallback = Rc<dyn Fn(Result<(), ValidationError>, &mut App)>;
22
23pub fn init(cx: &mut App) {
24 if !crate::capabilities::foundation::initialization::begin(cx, "input") {
25 return;
26 }
27 cx.bind_keys([
28 KeyBinding::new("backspace", Backspace, Some("Input")),
29 KeyBinding::new("delete", Delete, Some("Input")),
30 KeyBinding::new("left", Left, Some("Input")),
31 KeyBinding::new("right", Right, Some("Input")),
32 KeyBinding::new("shift-left", SelectLeft, Some("Input")),
33 KeyBinding::new("shift-right", SelectRight, Some("Input")),
34 KeyBinding::new("home", Home, Some("Input")),
35 KeyBinding::new("end", End, Some("Input")),
36 KeyBinding::new("enter", Enter, Some("Input")),
37 KeyBinding::new("tab", Tab, Some("Input")),
38 KeyBinding::new("shift-tab", ShiftTab, Some("Input")),
39 #[cfg(target_os = "macos")]
40 KeyBinding::new("cmd-a", SelectAll, Some("Input")),
41 #[cfg(not(target_os = "macos"))]
42 KeyBinding::new("ctrl-a", SelectAll, Some("Input")),
43 #[cfg(target_os = "macos")]
44 KeyBinding::new("cmd-c", Copy, Some("Input")),
45 #[cfg(not(target_os = "macos"))]
46 KeyBinding::new("ctrl-c", Copy, Some("Input")),
47 #[cfg(target_os = "macos")]
48 KeyBinding::new("cmd-x", Cut, Some("Input")),
49 #[cfg(not(target_os = "macos"))]
50 KeyBinding::new("ctrl-x", Cut, Some("Input")),
51 #[cfg(target_os = "macos")]
52 KeyBinding::new("cmd-v", Paste, Some("Input")),
53 #[cfg(not(target_os = "macos"))]
54 KeyBinding::new("ctrl-v", Paste, Some("Input")),
55 KeyBinding::new("escape", Escape, Some("Input")),
56 #[cfg(target_os = "macos")]
58 KeyBinding::new("alt-left", WordLeft, Some("Input")),
59 #[cfg(target_os = "macos")]
60 KeyBinding::new("alt-right", WordRight, Some("Input")),
61 #[cfg(not(target_os = "macos"))]
62 KeyBinding::new("ctrl-left", WordLeft, Some("Input")),
63 #[cfg(not(target_os = "macos"))]
64 KeyBinding::new("ctrl-right", WordRight, Some("Input")),
65 #[cfg(target_os = "macos")]
66 KeyBinding::new("alt-shift-left", SelectWordLeft, Some("Input")),
67 #[cfg(target_os = "macos")]
68 KeyBinding::new("alt-shift-right", SelectWordRight, Some("Input")),
69 #[cfg(not(target_os = "macos"))]
70 KeyBinding::new("ctrl-shift-left", SelectWordLeft, Some("Input")),
71 #[cfg(not(target_os = "macos"))]
72 KeyBinding::new("ctrl-shift-right", SelectWordRight, Some("Input")),
73 ]);
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum InputVariant {
78 Default,
79 Outline,
80 Ghost,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum InputSize {
85 Sm,
86 #[default]
87 Md,
88 Lg,
89}
90
91#[derive(IntoElement)]
92pub struct Input {
93 state: Entity<InputState>,
94 placeholder: Option<SharedString>,
95 variant: InputVariant,
96 size: InputSize,
97 disabled: bool,
98 error: bool,
99 password: bool,
100 clearable: bool,
101 prefix: Option<AnyElement>,
102 suffix: Option<AnyElement>,
103 initial_value: Option<SharedString>,
104 value: Option<SharedString>,
105
106 input_type: Option<InputType>,
108 validation_rules: Option<ValidationRules>,
109 helper_text: Option<SharedString>,
110 show_character_count: bool,
111 aria_label: Option<SharedString>,
112 aria_description: Option<SharedString>,
113 autocomplete: Option<SharedString>,
114 required: bool,
115
116 custom_validator: Option<InputValidator>,
118 custom_filter: Option<InputTransformer>,
119 custom_formatter: Option<InputTransformer>,
120
121 on_change: Option<InputValueCallback>,
123 on_enter: Option<InputValueCallback>,
124 on_focus: Option<InputValueCallback>,
125 on_blur: Option<InputValueCallback>,
126 on_validate: Option<InputValidationCallback>,
127
128 style: StyleRefinement,
130}
131
132impl Input {
133 pub fn new(state: &Entity<InputState>) -> Self {
135 Self {
136 state: state.clone(),
137 placeholder: None,
138 variant: InputVariant::Default,
139 size: InputSize::default(),
140 disabled: false,
141 error: false,
142 password: false,
143 clearable: false,
144 prefix: None,
145 suffix: None,
146 initial_value: None,
147 value: None,
148
149 input_type: None,
151 validation_rules: None,
152 helper_text: None,
153 show_character_count: false,
154 aria_label: None,
155 aria_description: None,
156 autocomplete: None,
157 required: false,
158
159 custom_validator: None,
161 custom_filter: None,
162 custom_formatter: None,
163
164 on_change: None,
166 on_enter: None,
167 on_focus: None,
168 on_blur: None,
169 on_validate: None,
170
171 style: StyleRefinement::default(),
173 }
174 }
175
176 pub fn initial_value(mut self, value: impl Into<SharedString>) -> Self {
181 self.initial_value = Some(value.into());
182 self.value = None;
183 self
184 }
185
186 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
191 self.value = Some(value.into());
192 self.initial_value = None;
193 self
194 }
195
196 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
198 self.placeholder = Some(placeholder.into());
199 self
200 }
201
202 #[deprecated(note = "use clearable instead")]
206 pub fn cleanable(self) -> Self {
207 self.clearable(true)
208 }
209
210 pub fn variant(mut self, variant: InputVariant) -> Self {
212 self.variant = variant;
213 self
214 }
215
216 pub fn size(mut self, size: InputSize) -> Self {
218 self.size = size;
219 self
220 }
221
222 pub fn disabled(mut self, disabled: bool) -> Self {
224 self.disabled = disabled;
225 self
226 }
227
228 pub fn error(mut self, error: bool) -> Self {
230 self.error = error;
231 self
232 }
233
234 pub fn password(mut self, password: bool) -> Self {
236 self.password = password;
237 self
238 }
239
240 pub fn clearable(mut self, clearable: bool) -> Self {
242 self.clearable = clearable;
243 self
244 }
245
246 pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
248 self.prefix = Some(prefix.into_any_element());
249 self
250 }
251
252 pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
254 self.suffix = Some(suffix.into_any_element());
255 self
256 }
257
258 pub fn on_change<F>(mut self, callback: F) -> Self
263 where
264 F: Fn(SharedString, &mut App) + 'static,
265 {
266 self.on_change = Some(Rc::new(callback));
267 self
268 }
269
270 pub fn on_enter<F>(mut self, callback: F) -> Self
272 where
273 F: Fn(SharedString, &mut App) + 'static,
274 {
275 self.on_enter = Some(Rc::new(callback));
276 self
277 }
278
279 pub fn on_focus<F>(mut self, callback: F) -> Self
281 where
282 F: Fn(SharedString, &mut App) + 'static,
283 {
284 self.on_focus = Some(Rc::new(callback));
285 self
286 }
287
288 pub fn on_blur<F>(mut self, callback: F) -> Self
290 where
291 F: Fn(SharedString, &mut App) + 'static,
292 {
293 self.on_blur = Some(Rc::new(callback));
294 self
295 }
296
297 pub fn input_type(mut self, input_type: InputType) -> Self {
299 self.input_type = Some(input_type);
300 self
301 }
302
303 pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
305 self.validation_rules = Some(rules);
306 self
307 }
308
309 pub fn min_length(mut self, min: usize) -> Self {
311 if self.validation_rules.is_none() {
312 self.validation_rules = Some(ValidationRules::default());
313 }
314 if let Some(ref mut rules) = self.validation_rules {
315 rules.min_length = Some(min);
316 }
317 self
318 }
319
320 pub fn max_length(mut self, max: usize) -> Self {
322 if self.validation_rules.is_none() {
323 self.validation_rules = Some(ValidationRules::default());
324 }
325 if let Some(ref mut rules) = self.validation_rules {
326 rules.max_length = Some(max);
327 }
328 self
329 }
330
331 pub fn required(mut self, required: bool) -> Self {
333 self.required = required;
334 if self.validation_rules.is_none() {
335 self.validation_rules = Some(ValidationRules::default());
336 }
337 if let Some(ref mut rules) = self.validation_rules {
338 rules.required = required;
339 }
340 self
341 }
342
343 pub fn helper_text(mut self, text: impl Into<SharedString>) -> Self {
345 self.helper_text = Some(text.into());
346 self
347 }
348
349 pub fn show_character_count(mut self, show: bool) -> Self {
351 self.show_character_count = show;
352 self
353 }
354
355 pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
357 self.aria_label = Some(label.into());
358 self
359 }
360
361 pub fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
363 self.aria_description = Some(description.into());
364 self
365 }
366
367 pub fn autocomplete(mut self, autocomplete: impl Into<SharedString>) -> Self {
369 self.autocomplete = Some(autocomplete.into());
370 self
371 }
372
373 pub fn on_validate<F>(mut self, callback: F) -> Self
375 where
376 F: Fn(Result<(), ValidationError>, &mut App) + 'static,
377 {
378 self.on_validate = Some(Rc::new(callback));
379 self
380 }
381
382 pub fn custom_validator<F>(mut self, validator: F) -> Self
396 where
397 F: Fn(&str) -> Result<(), String> + 'static,
398 {
399 self.custom_validator = Some(Rc::new(validator));
400 self
401 }
402
403 pub fn custom_filter<F>(mut self, filter: F) -> Self
416 where
417 F: Fn(&str) -> String + 'static,
418 {
419 self.custom_filter = Some(Rc::new(filter));
420 self
421 }
422
423 pub fn custom_formatter<F>(mut self, formatter: F) -> Self
434 where
435 F: Fn(&str) -> String + 'static,
436 {
437 self.custom_formatter = Some(Rc::new(formatter));
438 self
439 }
440
441 fn install_event_subscription(&self, cx: &mut App) {
442 let on_change = self.on_change.clone();
443 let on_enter = self.on_enter.clone();
444 let on_focus = self.on_focus.clone();
445 let on_blur = self.on_blur.clone();
446 let on_validate = self.on_validate.clone();
447
448 let has_callbacks = on_change.is_some()
449 || on_enter.is_some()
450 || on_focus.is_some()
451 || on_blur.is_some()
452 || on_validate.is_some();
453 let subscription = has_callbacks.then(|| {
454 cx.subscribe(&self.state, move |emitter, event: &InputEvent, cx| {
455 let callback_value = || emitter.read(cx).raw_value().into();
459 match event {
460 InputEvent::Change => {
461 if let Some(callback) = on_change.as_ref() {
462 callback(callback_value(), cx);
463 }
464 }
465 InputEvent::Enter => {
466 if let Some(callback) = on_enter.as_ref() {
467 callback(callback_value(), cx);
468 }
469 }
470 InputEvent::Focus => {
471 if let Some(callback) = on_focus.as_ref() {
472 callback(callback_value(), cx);
473 }
474 }
475 InputEvent::Blur => {
476 if let Some(callback) = on_blur.as_ref() {
477 callback(callback_value(), cx);
478 }
479 }
480 InputEvent::Validate(result) => {
481 if let Some(callback) = on_validate.as_ref() {
482 callback(result.clone(), cx);
483 }
484 }
485 InputEvent::Tab | InputEvent::ShiftTab => {}
486 }
487 })
488 });
489
490 self.state.update(cx, |state, _| {
491 state.replace_event_subscription(subscription);
492 });
493 }
494
495 fn height(&self) -> Pixels {
497 match self.size {
498 InputSize::Sm => px(32.0),
499 InputSize::Md => px(40.0),
500 InputSize::Lg => px(48.0),
501 }
502 }
503
504 fn padding_x(&self) -> Pixels {
506 match self.size {
507 InputSize::Sm => px(8.0),
508 InputSize::Md => px(12.0),
509 InputSize::Lg => px(16.0),
510 }
511 }
512
513 fn font_size(&self) -> Pixels {
515 match self.size {
516 InputSize::Sm => px(13.0),
517 InputSize::Md => px(14.0),
518 InputSize::Lg => px(16.0),
519 }
520 }
521
522 fn element_gap(&self) -> Pixels {
524 match self.size {
525 InputSize::Sm => px(6.0),
526 InputSize::Md => px(8.0),
527 InputSize::Lg => px(10.0),
528 }
529 }
530
531 #[allow(clippy::arc_with_non_send_sync)]
538 fn validation_rules_for_state(&self) -> Option<ValidationRules> {
539 let has_builder_callbacks = self.custom_validator.is_some()
540 || self.custom_filter.is_some()
541 || self.custom_formatter.is_some();
542 let mut rules = self
543 .validation_rules
544 .clone()
545 .or_else(|| has_builder_callbacks.then(ValidationRules::default))?;
546
547 if let Some(custom_validator) = self.custom_validator.as_ref() {
548 let validator = custom_validator.clone();
549 rules.custom_validator = Some(Arc::new(move |value| match validator(value) {
550 Ok(()) => Ok(()),
551 Err(message) => Err(ValidationError {
552 message: message.into(),
553 field_name: None,
554 }),
555 }));
556 }
557
558 if let Some(custom_filter) = self.custom_filter.as_ref() {
559 let filter = custom_filter.clone();
560 rules.custom_filter = Some(Arc::new(move |input| filter(input)));
561 }
562
563 if let Some(custom_formatter) = self.custom_formatter.as_ref() {
564 let formatter = custom_formatter.clone();
565 rules.custom_formatter = Some(Arc::new(move |input| formatter(input)));
566 }
567
568 Some(rules)
569 }
570}
571
572impl Styled for Input {
573 fn style(&mut self) -> &mut StyleRefinement {
574 &mut self.style
575 }
576}
577
578impl RenderOnce for Input {
579 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
580 let theme = use_theme(cx);
581 let height = self.height();
582 let padding_x = self.padding_x();
583 let font_size = self.font_size();
584 let gap = self.element_gap();
585
586 self.state.update(cx, |state, cx| {
587 state.disabled = self.disabled;
588 if let Some(placeholder) = self.placeholder.clone() {
589 if state.placeholder != placeholder {
590 state.placeholder = placeholder;
591 if state.content().is_empty() {
592 state.invalidate_layout_cache();
593 }
594 }
595 }
596
597 if self.password && state.input_type != InputType::Password {
600 state.input_type = InputType::Password;
601 state.masked = true;
602 }
603
604 if let Some(input_type) = self.input_type {
605 let input_type_changed = state.input_type != input_type;
606 state.input_type = input_type;
607 if input_type_changed && input_type == InputType::Password {
608 state.masked = true;
609 }
610 match input_type {
611 InputType::Tel => state.input_mask = InputMask::Phone,
612 InputType::CreditCard => state.input_mask = InputMask::CreditCard,
613 InputType::Date => state.input_mask = InputMask::Date,
614 InputType::Time => state.input_mask = InputMask::Time,
615 _ => {}
616 }
617 }
618
619 let builder_formatter_active = self.custom_formatter.is_some()
620 || self
621 .validation_rules
622 .as_ref()
623 .is_some_and(|rules| rules.custom_formatter.is_some());
624
625 if let Some(rules) = self.validation_rules_for_state() {
626 state.validation_rules = rules;
627 }
628 state.sync_builder_formatter(builder_formatter_active);
629
630 state.refresh_formatted_content();
634
635 state.aria_label = self.aria_label.clone();
636 state.aria_description = self.aria_description.clone();
637 state.autocomplete = self.autocomplete.clone();
638 state.helper_text = self.helper_text.clone();
639
640 if let Some(value) = self.value.clone() {
641 if !state.value_matches(value.as_ref()) {
642 state.set_value(value, window, cx);
643 }
644 } else if let Some(value) = self.initial_value.clone() {
645 state.apply_initial_value(value, window, cx);
646 }
647 });
648
649 self.install_event_subscription(cx);
650
651 let has_error = self.error || self.state.read(cx).validation_error.is_some();
655
656 let (bg_color, border_color, text_color) = if self.disabled {
657 (
658 theme.tokens.muted.opacity(0.5),
659 theme.tokens.border,
660 theme.tokens.muted_foreground,
661 )
662 } else if has_error {
663 match self.variant {
664 InputVariant::Default => (
665 theme.tokens.background,
666 theme.tokens.destructive,
667 theme.tokens.foreground,
668 ),
669 InputVariant::Outline => (
670 theme.tokens.background,
671 theme.tokens.destructive,
672 theme.tokens.foreground,
673 ),
674 InputVariant::Ghost => (
675 gpui::transparent_black(),
676 theme.tokens.destructive.opacity(0.3),
677 theme.tokens.foreground,
678 ),
679 }
680 } else {
681 match self.variant {
682 InputVariant::Default => (
683 theme.tokens.background,
684 theme.tokens.input,
685 theme.tokens.foreground,
686 ),
687 InputVariant::Outline => (
688 theme.tokens.background,
689 theme.tokens.border,
690 theme.tokens.foreground,
691 ),
692 InputVariant::Ghost => (
693 gpui::transparent_black(),
694 theme.tokens.border.opacity(0.3),
695 theme.tokens.foreground,
696 ),
697 }
698 };
699
700 let has_value = !self.state.read(cx).content.is_empty();
701 let show_clear = self.clearable && has_value && !self.disabled;
702 let state_for_clear = self.state.clone();
703 let state_for_password = self.state.clone();
704
705 let input_state = self.state.read(cx);
706 let validation_error = input_state.validation_error.clone();
707 let success_message = input_state.success_message.clone();
708 let composing = input_state.composition_char_count();
709 let content_length = input_state.content.chars().count() - composing;
710 let max_length = input_state.validation_rules.max_length;
711 let is_focused = input_state.focus_handle(cx).is_focused(window);
712 let is_masked = input_state.masked;
713 let aria_role = if input_state.input_type == InputType::Password {
714 Role::PasswordInput
715 } else {
716 Role::TextInput
717 };
718 let aria_label = input_state.aria_label.clone();
719 let aria_description = input_state.aria_description.clone();
720 let aria_placeholder = input_state.placeholder.clone();
721 let aria_value: SharedString = if is_masked {
722 "•".repeat(input_state.content.chars().count()).into()
723 } else {
724 input_state.content.clone()
725 };
726 let aria_required = input_state.validation_rules.required;
727 let aria_invalid = has_error;
728 let shake_triggered = input_state.shake_triggered;
729
730 if shake_triggered {
731 self.state.update(cx, |state, _cx| {
732 state.shake_triggered = false;
733 state.shake_count = state.shake_count.wrapping_add(1);
734 });
735 }
736 let shake_count = self.state.read(cx).shake_count;
737
738 let shadow_xs = BoxShadow {
739 offset: theme.tokens.shadow_xs.offset,
740 blur_radius: theme.tokens.shadow_xs.blur_radius,
741 spread_radius: theme.tokens.shadow_xs.spread_radius,
742 inset: false,
743 color: theme.tokens.shadow_xs.color,
744 };
745 let focus_ring = theme.tokens.focus_ring_light();
746 let error_ring_focused = theme.tokens.error_ring();
747 let error_ring_unfocused = theme.tokens.error_ring();
748 let ring_color = theme.tokens.ring;
749 let destructive_color = theme.tokens.destructive;
750
751 let user_style = self.style;
752
753 VStack::new()
754 .w_full()
755 .gap(px(4.0))
756 .child({
757 let input_container = wire_actions(&self.state, window, cx)
758 .role(aria_role)
759 .when_some(aria_label, |this, label| this.aria_label(label))
760 .when_some(aria_description, |this, description| {
761 this.aria_description(description)
762 })
763 .aria_value(aria_value)
764 .aria_placeholder(aria_placeholder)
765 .aria_disabled(self.disabled)
766 .aria_required(aria_required)
767 .when(aria_invalid, |this| {
768 this.aria_invalid(gpui::accesskit::Invalid::True)
769 })
770 .child(
771 HStack::new()
772 .h(height)
773 .w_full()
774 .px(padding_x)
775 .gap(gap)
776 .bg(bg_color)
777 .border_1()
778 .border_color(border_color)
779 .rounded(theme.tokens.radius_md)
780 .items_center()
781 .text_size(font_size)
782 .font_family(theme.tokens.font_mono.clone())
783 .text_color(text_color)
784 .shadow(smallvec::smallvec![shadow_xs])
785 .when(!self.disabled, |h| h.cursor(gpui::CursorStyle::IBeam))
786 .when(!self.disabled, |h| {
787 h.hover(move |style| {
788 style.border_color(if has_error {
789 destructive_color
790 } else {
791 ring_color
792 })
793 })
794 })
795 .when(is_focused && !self.disabled, |h| {
796 if has_error {
797 h.border_color(destructive_color)
798 .shadow(smallvec::smallvec![error_ring_focused])
799 } else {
800 h.border_color(ring_color)
801 .shadow(smallvec::smallvec![focus_ring])
802 }
803 })
804 .when(has_error && !is_focused, |h| {
805 h.shadow(smallvec::smallvec![error_ring_unfocused])
806 })
807 .children(self.prefix)
808 .child(div().flex_1().overflow_hidden().child(self.state.clone()))
809 .when(show_clear, |h| {
810 h.child(
811 div()
812 .px(px(4.0))
813 .py(px(4.0))
814 .rounded(px(4.0))
815 .cursor_pointer()
816 .hover(|style| style.bg(theme.tokens.muted))
817 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
818 state_for_clear.update(cx, |state, cx| {
819 state.set_value("", window, cx);
820 })
821 })
822 .child("×")
823 .text_color(theme.tokens.muted_foreground),
824 )
825 })
826 .when(self.password, |h| {
827 h.child(
828 div()
829 .px(px(4.0))
830 .py(px(4.0))
831 .rounded(px(4.0))
832 .cursor_pointer()
833 .hover(|style| style.bg(theme.tokens.muted))
834 .on_mouse_down(MouseButton::Left, {
835 let state = state_for_password.clone();
836 move |_, window, cx| {
837 state.update(cx, |state, cx| {
838 state.set_masked(!state.masked, cx);
839 });
840 window.refresh();
841 }
842 })
843 .child(
844 Icon::new(if is_masked { "eye" } else { "eye-off" })
845 .size(px(16.0))
846 .color(theme.tokens.muted_foreground),
847 ),
848 )
849 })
850 .children(self.suffix),
851 );
852
853 if shake_count > 0 {
854 input_container
855 .with_animation(
856 ElementId::Name(format!("input-shake-{}", shake_count).into()),
857 Animation::new(Duration::from_millis(300))
858 .with_easing(easings::ease_out_quad),
859 move |el, delta| el.ml(px(shake_offset(delta, 6.0))),
860 )
861 .into_any_element()
862 } else {
863 input_container.into_any_element()
864 }
865 })
866 .when(
867 self.helper_text.is_some()
868 || validation_error.is_some()
869 || success_message.is_some()
870 || self.show_character_count,
871 |v| {
872 let message = if let Some(error) = validation_error.as_ref() {
873 FooterMessage::Error(error)
874 } else if let Some(success) = success_message.as_ref() {
875 if has_value {
876 FooterMessage::Success(success)
877 } else {
878 FooterMessage::Blank
879 }
880 } else if let Some(helper) = self.helper_text.as_ref() {
881 FooterMessage::Helper(helper)
882 } else {
883 FooterMessage::Blank
884 };
885 let character_count = self.show_character_count.then_some(CharacterCount {
886 committed: content_length,
887 composing,
888 max: max_length,
889 });
890 v.child(validation_footer(&theme.tokens, message, character_count))
891 },
892 )
893 .map(|this| {
894 let mut vstack = this;
895 vstack.style().refine(&user_style);
896 vstack
897 })
898 }
899}
900
901#[cfg(test)]
902mod tests {
903 use super::*;
904 use crate::capabilities::foundation::theme::{install_theme, Theme};
905 use std::{
906 cell::{Cell, RefCell},
907 rc::Rc,
908 };
909
910 struct InputRenderTestView {
911 state: Entity<InputState>,
912 callback_calls: Option<Rc<Cell<usize>>>,
913 initial_value: Option<SharedString>,
914 value: Option<SharedString>,
915 }
916
917 struct FormattedInputRenderTestView {
918 state: Entity<InputState>,
919 value: SharedString,
920 callback_calls: Rc<Cell<usize>>,
921 suffix: bool,
922 }
923
924 struct FormattedCallbackTestView {
925 state: Entity<InputState>,
926 values: Rc<RefCell<Vec<SharedString>>>,
927 }
928
929 struct ToggleFormatterRenderTestView {
930 state: Entity<InputState>,
931 formatter_enabled: bool,
932 }
933
934 impl Render for FormattedCallbackTestView {
935 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
936 let values = self.values.clone();
937 Input::new(&self.state)
938 .custom_formatter(|input| format!("${:.2}", input.parse::<f64>().unwrap_or(0.0)))
939 .on_change(move |value, _| values.borrow_mut().push(value))
940 }
941 }
942
943 impl Render for FormattedInputRenderTestView {
944 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
945 let callback_calls = self.callback_calls.clone();
946 let suffix = self.suffix;
947 Input::new(&self.state)
948 .value(self.value.clone())
949 .custom_formatter(move |input| {
950 if suffix {
951 format!("{input} USD")
952 } else {
953 format!("${:.2}", input.parse::<f64>().unwrap_or(0.0))
954 }
955 })
956 .on_change(move |_, _| callback_calls.set(callback_calls.get() + 1))
957 }
958 }
959
960 impl Render for ToggleFormatterRenderTestView {
961 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
962 let input = Input::new(&self.state).value("12");
963 if self.formatter_enabled {
964 input.custom_formatter(|value| {
965 format!("${:.2}", value.parse::<f64>().unwrap_or(0.0))
966 })
967 } else {
968 input
969 }
970 }
971 }
972
973 impl Render for InputRenderTestView {
974 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
975 Input::new(&self.state)
976 .when_some(self.initial_value.clone(), Input::initial_value)
977 .when_some(self.value.clone(), Input::value)
978 .when_some(self.callback_calls.clone(), |input, calls| {
979 input.on_change(move |_, _| calls.set(calls.get() + 1))
980 })
981 }
982 }
983
984 #[gpui::test]
985 fn controlled_value_changes_replace_existing_content() {
986 let mut app = TestApp::new();
987 app.update(|cx| install_theme(cx, Theme::light()));
988 let mut window = app.open_window(|_, cx| InputRenderTestView {
989 state: cx.new(InputState::new),
990 callback_calls: None,
991 initial_value: None,
992 value: Some("first".into()),
993 });
994
995 window.draw();
996 window.update(|view, _, cx| {
997 view.value = Some("replacement".into());
998 cx.notify();
999 });
1000 window.draw();
1001
1002 assert_eq!(
1003 window.read(|view, cx| view.state.read(cx).content().to_string()),
1004 "replacement"
1005 );
1006 }
1007
1008 #[gpui::test]
1009 fn unchanged_controlled_value_does_not_emit_change_on_rerender() {
1010 let mut app = TestApp::new();
1011 app.update(|cx| install_theme(cx, Theme::light()));
1012 let calls = Rc::new(Cell::new(0));
1013 let mut window = app.open_window(|_, cx| InputRenderTestView {
1014 state: cx.new(|cx| {
1015 let mut state = InputState::new(cx);
1016 state.content = "first".into();
1017 state
1018 }),
1019 callback_calls: Some(calls.clone()),
1020 initial_value: None,
1021 value: Some("first".into()),
1022 });
1023
1024 window.draw();
1025 window.update(|_, _, cx| cx.notify());
1026 window.draw();
1027
1028 assert_eq!(calls.get(), 0);
1029 }
1030
1031 #[gpui::test]
1032 fn formatted_controlled_value_does_not_emit_on_unchanged_rerender() {
1033 let mut app = TestApp::new();
1034 app.update(|cx| install_theme(cx, Theme::light()));
1035 let calls = Rc::new(Cell::new(0));
1036 let mut window = app.open_window(|_, cx| FormattedInputRenderTestView {
1037 state: cx.new(InputState::new),
1038 value: "12".into(),
1039 callback_calls: calls.clone(),
1040 suffix: false,
1041 });
1042
1043 window.draw();
1044 let calls_after_initial_render = calls.get();
1045 assert_eq!(
1046 window.read(|view, cx| view.state.read(cx).content().to_string()),
1047 "$12.00"
1048 );
1049
1050 window.update(|_, _, cx| cx.notify());
1051 window.draw();
1052
1053 assert_eq!(calls.get(), calls_after_initial_render);
1054 }
1055
1056 #[gpui::test]
1057 fn changing_formatter_reformats_the_controlled_value() {
1058 let mut app = TestApp::new();
1059 app.update(|cx| install_theme(cx, Theme::light()));
1060 let calls = Rc::new(Cell::new(0));
1061 let mut window = app.open_window(|_, cx| FormattedInputRenderTestView {
1062 state: cx.new(InputState::new),
1063 value: "12".into(),
1064 callback_calls: calls.clone(),
1065 suffix: false,
1066 });
1067
1068 window.draw();
1069 assert_eq!(
1070 window.read(|view, cx| view.state.read(cx).content().to_string()),
1071 "$12.00"
1072 );
1073
1074 window.update(|view, _, cx| {
1075 view.suffix = true;
1076 cx.notify();
1077 });
1078 window.draw();
1079
1080 assert_eq!(
1081 window.read(|view, cx| view.state.read(cx).content().to_string()),
1082 "12 USD"
1083 );
1084 }
1085
1086 #[gpui::test]
1087 fn removing_builder_formatter_restores_raw_display_value() {
1088 let mut app = TestApp::new();
1089 app.update(|cx| install_theme(cx, Theme::light()));
1090 let mut window = app.open_window(|_, cx| ToggleFormatterRenderTestView {
1091 state: cx.new(InputState::new),
1092 formatter_enabled: true,
1093 });
1094
1095 window.draw();
1096 assert_eq!(
1097 window.read(|view, cx| view.state.read(cx).content().to_string()),
1098 "$12.00"
1099 );
1100
1101 window.update(|view, _, cx| {
1102 view.formatter_enabled = false;
1103 cx.notify();
1104 });
1105 window.draw();
1106
1107 assert_eq!(
1108 window.read(|view, cx| view.state.read(cx).content().to_string()),
1109 "12"
1110 );
1111 }
1112
1113 #[gpui::test]
1114 fn formatted_input_change_callback_reports_raw_value() {
1115 let mut app = TestApp::new();
1116 app.update(|cx| install_theme(cx, Theme::light()));
1117 let state = app.update(|cx| cx.new(InputState::new));
1118 let values = Rc::new(RefCell::new(Vec::new()));
1119 let values_for_view = values.clone();
1120 let mut window = app.open_window(|_, _| FormattedCallbackTestView {
1121 state: state.clone(),
1122 values: values_for_view,
1123 });
1124
1125 window.draw();
1126 window.update(|view, window, cx| {
1127 view.state.update(cx, |state, cx| {
1128 state.set_value("123", window, cx);
1129 });
1130 });
1131
1132 assert_eq!(
1133 values.borrow().last().map(SharedString::as_ref),
1134 Some("123")
1135 );
1136 }
1137
1138 #[gpui::test]
1139 fn clearable_builder_enables_clear_button() {
1140 let mut app = TestApp::new();
1141 app.update(|cx| install_theme(cx, Theme::light()));
1142 let state = app.update(|cx| cx.new(InputState::new));
1143
1144 let input = Input::new(&state).clearable(true);
1145
1146 assert!(input.clearable);
1147 }
1148
1149 #[gpui::test]
1150 fn repeated_render_replaces_input_event_subscription() {
1151 let mut app = TestApp::new();
1152 app.update(|cx| install_theme(cx, Theme::light()));
1153 let stale_calls = Rc::new(Cell::new(0));
1154 let current_calls = Rc::new(Cell::new(0));
1155 let mut window = app.open_window(|_, cx| InputRenderTestView {
1156 state: cx.new(InputState::new),
1157 callback_calls: Some(stale_calls.clone()),
1158 initial_value: None,
1159 value: None,
1160 });
1161
1162 window.draw();
1163 window.update(|view, _, cx| {
1164 view.callback_calls = Some(current_calls.clone());
1165 cx.notify();
1166 });
1167 window.draw();
1168 window.update(|view, _, cx| {
1169 view.state.update(cx, |_, cx| cx.emit(InputEvent::Change));
1170 });
1171 assert_eq!(stale_calls.get(), 0);
1172 assert_eq!(current_calls.get(), 1);
1173
1174 window.update(|view, _, cx| {
1175 view.callback_calls = None;
1176 cx.notify();
1177 });
1178 window.draw();
1179 window.update(|view, _, cx| {
1180 view.state.update(cx, |_, cx| cx.emit(InputEvent::Change));
1181 });
1182 assert_eq!(current_calls.get(), 1);
1183 }
1184
1185 #[gpui::test]
1186 fn initial_value_does_not_overwrite_user_edits_on_rerender() {
1187 let mut app = TestApp::new();
1188 app.update(|cx| install_theme(cx, Theme::light()));
1189 let mut window = app.open_window(|_, cx| InputRenderTestView {
1190 state: cx.new(InputState::new),
1191 callback_calls: None,
1192 initial_value: Some("initial".into()),
1193 value: None,
1194 });
1195
1196 window.draw();
1197 window.update(|view, _, cx| {
1198 view.state.update(cx, |state, cx| {
1199 state.content = "edited".into();
1200 cx.notify();
1201 });
1202 cx.notify();
1203 });
1204 window.draw();
1205
1206 assert_eq!(
1207 window.read(|view, cx| view.state.read(cx).content().to_string()),
1208 "edited"
1209 );
1210 }
1211
1212 #[gpui::test]
1213 fn builder_initial_value_changes_are_ignored_after_first_render() {
1214 let mut app = TestApp::new();
1215 app.update(|cx| install_theme(cx, Theme::light()));
1216 let mut window = app.open_window(|_, cx| InputRenderTestView {
1217 state: cx.new(InputState::new),
1218 callback_calls: None,
1219 initial_value: Some("initial".into()),
1220 value: None,
1221 });
1222
1223 window.draw();
1224 window.update(|view, _, cx| {
1225 view.initial_value = Some("replacement".into());
1226 cx.notify();
1227 });
1228 window.draw();
1229
1230 assert_eq!(
1231 window.read(|view, cx| view.state.read(cx).content().to_string()),
1232 "initial"
1233 );
1234 }
1235
1236 #[gpui::test]
1237 fn set_value_emits_one_change_event() {
1238 let mut app = TestApp::new();
1239 app.update(|cx| install_theme(cx, Theme::light()));
1240 let calls = Rc::new(Cell::new(0));
1241 let mut window = app.open_window(|_, cx| InputRenderTestView {
1242 state: cx.new(InputState::new),
1243 callback_calls: Some(calls.clone()),
1244 initial_value: None,
1245 value: None,
1246 });
1247
1248 window.draw();
1249 window.update(|view, window, cx| {
1250 view.state
1251 .update(cx, |state, cx| state.set_value("edited", window, cx));
1252 });
1253
1254 assert_eq!(calls.get(), 1);
1255 }
1256
1257 #[gpui::test]
1258 fn set_value_replaces_existing_content() {
1259 let mut app = TestApp::new();
1260 app.update(|cx| install_theme(cx, Theme::light()));
1261 let mut window = app.open_window(|_, cx| InputRenderTestView {
1262 state: cx.new(InputState::new),
1263 callback_calls: None,
1264 initial_value: Some("initial".into()),
1265 value: None,
1266 });
1267
1268 window.draw();
1269 window.update(|view, window, cx| {
1270 view.state
1271 .update(cx, |state, cx| state.set_value("edited", window, cx));
1272 });
1273
1274 assert_eq!(
1275 window.read(|view, cx| view.state.read(cx).content().to_string()),
1276 "edited"
1277 );
1278 }
1279
1280 struct BareInputTestView {
1281 state: Entity<InputState>,
1282 }
1283
1284 impl Render for BareInputTestView {
1285 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1286 wire_actions(&self.state, window, cx)
1287 .h(px(36.0))
1288 .px(px(12.0))
1289 .rounded(px(8.0))
1290 .child(self.state.clone())
1291 }
1292 }
1293
1294 #[gpui::test]
1295 fn wire_actions_gives_custom_input_containers_full_keyboard_editing() {
1296 let mut app = TestApp::new();
1297 app.update(|cx| {
1298 install_theme(cx, Theme::light());
1299 crate::capabilities::controls::input::init(cx);
1300 });
1301 let state = app.update(|cx| cx.new(|cx| InputState::new(cx).value("hello")));
1302 let mut window = app.open_window(|_, _| BareInputTestView {
1303 state: state.clone(),
1304 });
1305
1306 window.draw();
1307 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
1308 window.draw();
1309 let handle: AnyWindowHandle = window.handle().into();
1310 app.raw_context_mut()
1311 .simulate_keystrokes(handle, "backspace");
1312 app.flush();
1313
1314 app.update(|cx| {
1315 assert_eq!(state.read(cx).content(), "hell");
1316 });
1317 }
1318}