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