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) =
657 crate::capabilities::controls::input_shell_colors(
658 self.variant,
659 self.disabled,
660 has_error,
661 &theme.tokens,
662 );
663
664 let has_value = !self.state.read(cx).content.is_empty();
665 let show_clear = self.clearable && has_value && !self.disabled;
666 let state_for_clear = self.state.clone();
667 let state_for_password = self.state.clone();
668
669 let input_state = self.state.read(cx);
670 let validation_error = input_state.validation_error.clone();
671 let success_message = input_state.success_message.clone();
672 let composing = input_state.composition_char_count();
673 let content_length = input_state.content.chars().count() - composing;
674 let max_length = input_state.validation_rules.max_length;
675 let is_focused = input_state.focus_handle(cx).is_focused(window);
676 let is_masked = input_state.masked;
677 let aria_role = if input_state.input_type == InputType::Password {
678 Role::PasswordInput
679 } else {
680 Role::TextInput
681 };
682 let aria_label = input_state.aria_label.clone();
683 let aria_description = input_state.aria_description.clone();
684 let aria_placeholder = input_state.placeholder.clone();
685 let aria_value: SharedString = if is_masked {
686 "•".repeat(input_state.content.chars().count()).into()
687 } else {
688 input_state.content.clone()
689 };
690 let aria_required = input_state.validation_rules.required;
691 let aria_invalid = has_error;
692 let shake_triggered = input_state.shake_triggered;
693
694 if shake_triggered {
695 self.state.update(cx, |state, _cx| {
696 state.shake_triggered = false;
697 state.shake_count = state.shake_count.wrapping_add(1);
698 });
699 }
700 let shake_count = self.state.read(cx).shake_count;
701
702 let shadow_xs = BoxShadow {
703 offset: theme.tokens.shadow_xs.offset,
704 blur_radius: theme.tokens.shadow_xs.blur_radius,
705 spread_radius: theme.tokens.shadow_xs.spread_radius,
706 inset: false,
707 color: theme.tokens.shadow_xs.color,
708 };
709 let focus_ring = theme.tokens.focus_ring_light();
710 let error_ring_focused = theme.tokens.error_ring();
711 let error_ring_unfocused = theme.tokens.error_ring();
712 let ring_color = theme.tokens.ring;
713 let destructive_color = theme.tokens.destructive;
714
715 let user_style = self.style;
716
717 VStack::new()
718 .w_full()
719 .gap(px(4.0))
720 .child({
721 let input_container = wire_actions(&self.state, window, cx)
722 .role(aria_role)
723 .when_some(aria_label, |this, label| this.aria_label(label))
724 .when_some(aria_description, |this, description| {
725 this.aria_description(description)
726 })
727 .aria_value(aria_value)
728 .aria_placeholder(aria_placeholder)
729 .aria_disabled(self.disabled)
730 .aria_required(aria_required)
731 .when(aria_invalid, |this| {
732 this.aria_invalid(gpui::accesskit::Invalid::True)
733 })
734 .child(
735 HStack::new()
736 .h(height)
737 .w_full()
738 .px(padding_x)
739 .gap(gap)
740 .bg(bg_color)
741 .border_1()
742 .border_color(border_color)
743 .rounded(theme.tokens.radius_md)
744 .items_center()
745 .text_size(font_size)
746 .font_family(theme.tokens.font_mono.clone())
747 .text_color(text_color)
748 .shadow(smallvec::smallvec![shadow_xs])
749 .when(!self.disabled, |h| h.cursor(gpui::CursorStyle::IBeam))
750 .when(!self.disabled, |h| {
751 h.hover(move |style| {
752 style.border_color(if has_error {
753 destructive_color
754 } else {
755 ring_color
756 })
757 })
758 })
759 .when(is_focused && !self.disabled, |h| {
760 if has_error {
761 h.border_color(destructive_color)
762 .shadow(smallvec::smallvec![error_ring_focused])
763 } else {
764 h.border_color(ring_color)
765 .shadow(smallvec::smallvec![focus_ring])
766 }
767 })
768 .when(has_error && !is_focused, |h| {
769 h.shadow(smallvec::smallvec![error_ring_unfocused])
770 })
771 .children(self.prefix)
772 .child(div().flex_1().overflow_hidden().child(self.state.clone()))
773 .when(show_clear, |h| {
774 h.child(
775 div()
776 .px(px(4.0))
777 .py(px(4.0))
778 .rounded(px(4.0))
779 .cursor_pointer()
780 .hover(|style| style.bg(theme.tokens.muted))
781 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
782 state_for_clear.update(cx, |state, cx| {
783 state.set_value("", window, cx);
784 })
785 })
786 .child("×")
787 .text_color(theme.tokens.muted_foreground),
788 )
789 })
790 .when(self.password, |h| {
791 h.child(
792 div()
793 .px(px(4.0))
794 .py(px(4.0))
795 .rounded(px(4.0))
796 .cursor_pointer()
797 .hover(|style| style.bg(theme.tokens.muted))
798 .on_mouse_down(MouseButton::Left, {
799 let state = state_for_password.clone();
800 move |_, window, cx| {
801 state.update(cx, |state, cx| {
802 state.set_masked(!state.masked, cx);
803 });
804 window.refresh();
805 }
806 })
807 .child(
808 Icon::new(if is_masked { "eye" } else { "eye-off" })
809 .size(px(16.0))
810 .color(theme.tokens.muted_foreground),
811 ),
812 )
813 })
814 .children(self.suffix),
815 );
816
817 if shake_count > 0 {
818 input_container
819 .with_animation(
820 ElementId::Name(format!("input-shake-{}", shake_count).into()),
821 Animation::new(Duration::from_millis(300))
822 .with_easing(easings::ease_out_quad),
823 move |el, delta| el.ml(px(shake_offset(delta, 6.0))),
824 )
825 .into_any_element()
826 } else {
827 input_container.into_any_element()
828 }
829 })
830 .when(
831 self.helper_text.is_some()
832 || validation_error.is_some()
833 || success_message.is_some()
834 || self.show_character_count,
835 |v| {
836 let message = if let Some(error) = validation_error.as_ref() {
837 FooterMessage::Error(error)
838 } else if let Some(success) = success_message.as_ref() {
839 if has_value {
840 FooterMessage::Success(success)
841 } else {
842 FooterMessage::Blank
843 }
844 } else if let Some(helper) = self.helper_text.as_ref() {
845 FooterMessage::Helper(helper)
846 } else {
847 FooterMessage::Blank
848 };
849 let character_count = self.show_character_count.then_some(CharacterCount {
850 committed: content_length,
851 composing,
852 max: max_length,
853 });
854 v.child(validation_footer(&theme.tokens, message, character_count))
855 },
856 )
857 .map(|this| {
858 let mut vstack = this;
859 vstack.style().refine(&user_style);
860 vstack
861 })
862 }
863}
864
865#[cfg(test)]
866mod tests {
867 use super::*;
868 use crate::capabilities::foundation::theme::{install_theme, Theme};
869 use std::{
870 cell::{Cell, RefCell},
871 rc::Rc,
872 };
873
874 struct InputRenderTestView {
875 state: Entity<InputState>,
876 callback_calls: Option<Rc<Cell<usize>>>,
877 initial_value: Option<SharedString>,
878 value: Option<SharedString>,
879 }
880
881 struct FormattedInputRenderTestView {
882 state: Entity<InputState>,
883 value: SharedString,
884 callback_calls: Rc<Cell<usize>>,
885 suffix: bool,
886 }
887
888 struct FormattedCallbackTestView {
889 state: Entity<InputState>,
890 values: Rc<RefCell<Vec<SharedString>>>,
891 }
892
893 struct ToggleFormatterRenderTestView {
894 state: Entity<InputState>,
895 formatter_enabled: bool,
896 }
897
898 impl Render for FormattedCallbackTestView {
899 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
900 let values = self.values.clone();
901 Input::new(&self.state)
902 .custom_formatter(|input| format!("${:.2}", input.parse::<f64>().unwrap_or(0.0)))
903 .on_change(move |value, _| values.borrow_mut().push(value))
904 }
905 }
906
907 impl Render for FormattedInputRenderTestView {
908 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
909 let callback_calls = self.callback_calls.clone();
910 let suffix = self.suffix;
911 Input::new(&self.state)
912 .value(self.value.clone())
913 .custom_formatter(move |input| {
914 if suffix {
915 format!("{input} USD")
916 } else {
917 format!("${:.2}", input.parse::<f64>().unwrap_or(0.0))
918 }
919 })
920 .on_change(move |_, _| callback_calls.set(callback_calls.get() + 1))
921 }
922 }
923
924 impl Render for ToggleFormatterRenderTestView {
925 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
926 let input = Input::new(&self.state).value("12");
927 if self.formatter_enabled {
928 input.custom_formatter(|value| {
929 format!("${:.2}", value.parse::<f64>().unwrap_or(0.0))
930 })
931 } else {
932 input
933 }
934 }
935 }
936
937 impl Render for InputRenderTestView {
938 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
939 Input::new(&self.state)
940 .when_some(self.initial_value.clone(), Input::initial_value)
941 .when_some(self.value.clone(), Input::value)
942 .when_some(self.callback_calls.clone(), |input, calls| {
943 input.on_change(move |_, _| calls.set(calls.get() + 1))
944 })
945 }
946 }
947
948 #[gpui::test]
949 fn controlled_value_changes_replace_existing_content() {
950 let mut app = TestApp::new();
951 app.update(|cx| install_theme(cx, Theme::light()));
952 let mut window = app.open_window(|_, cx| InputRenderTestView {
953 state: cx.new(InputState::new),
954 callback_calls: None,
955 initial_value: None,
956 value: Some("first".into()),
957 });
958
959 window.draw();
960 window.update(|view, _, cx| {
961 view.value = Some("replacement".into());
962 cx.notify();
963 });
964 window.draw();
965
966 assert_eq!(
967 window.read(|view, cx| view.state.read(cx).content().to_string()),
968 "replacement"
969 );
970 }
971
972 #[gpui::test]
973 fn unchanged_controlled_value_does_not_emit_change_on_rerender() {
974 let mut app = TestApp::new();
975 app.update(|cx| install_theme(cx, Theme::light()));
976 let calls = Rc::new(Cell::new(0));
977 let mut window = app.open_window(|_, cx| InputRenderTestView {
978 state: cx.new(|cx| {
979 let mut state = InputState::new(cx);
980 state.content = "first".into();
981 state
982 }),
983 callback_calls: Some(calls.clone()),
984 initial_value: None,
985 value: Some("first".into()),
986 });
987
988 window.draw();
989 window.update(|_, _, cx| cx.notify());
990 window.draw();
991
992 assert_eq!(calls.get(), 0);
993 }
994
995 #[gpui::test]
996 fn formatted_controlled_value_does_not_emit_on_unchanged_rerender() {
997 let mut app = TestApp::new();
998 app.update(|cx| install_theme(cx, Theme::light()));
999 let calls = Rc::new(Cell::new(0));
1000 let mut window = app.open_window(|_, cx| FormattedInputRenderTestView {
1001 state: cx.new(InputState::new),
1002 value: "12".into(),
1003 callback_calls: calls.clone(),
1004 suffix: false,
1005 });
1006
1007 window.draw();
1008 let calls_after_initial_render = calls.get();
1009 assert_eq!(
1010 window.read(|view, cx| view.state.read(cx).content().to_string()),
1011 "$12.00"
1012 );
1013
1014 window.update(|_, _, cx| cx.notify());
1015 window.draw();
1016
1017 assert_eq!(calls.get(), calls_after_initial_render);
1018 }
1019
1020 #[gpui::test]
1021 fn changing_formatter_reformats_the_controlled_value() {
1022 let mut app = TestApp::new();
1023 app.update(|cx| install_theme(cx, Theme::light()));
1024 let calls = Rc::new(Cell::new(0));
1025 let mut window = app.open_window(|_, cx| FormattedInputRenderTestView {
1026 state: cx.new(InputState::new),
1027 value: "12".into(),
1028 callback_calls: calls.clone(),
1029 suffix: false,
1030 });
1031
1032 window.draw();
1033 assert_eq!(
1034 window.read(|view, cx| view.state.read(cx).content().to_string()),
1035 "$12.00"
1036 );
1037
1038 window.update(|view, _, cx| {
1039 view.suffix = true;
1040 cx.notify();
1041 });
1042 window.draw();
1043
1044 assert_eq!(
1045 window.read(|view, cx| view.state.read(cx).content().to_string()),
1046 "12 USD"
1047 );
1048 }
1049
1050 #[gpui::test]
1051 fn removing_builder_formatter_restores_raw_display_value() {
1052 let mut app = TestApp::new();
1053 app.update(|cx| install_theme(cx, Theme::light()));
1054 let mut window = app.open_window(|_, cx| ToggleFormatterRenderTestView {
1055 state: cx.new(InputState::new),
1056 formatter_enabled: true,
1057 });
1058
1059 window.draw();
1060 assert_eq!(
1061 window.read(|view, cx| view.state.read(cx).content().to_string()),
1062 "$12.00"
1063 );
1064
1065 window.update(|view, _, cx| {
1066 view.formatter_enabled = false;
1067 cx.notify();
1068 });
1069 window.draw();
1070
1071 assert_eq!(
1072 window.read(|view, cx| view.state.read(cx).content().to_string()),
1073 "12"
1074 );
1075 }
1076
1077 #[gpui::test]
1078 fn formatted_input_change_callback_reports_raw_value() {
1079 let mut app = TestApp::new();
1080 app.update(|cx| install_theme(cx, Theme::light()));
1081 let state = app.update(|cx| cx.new(InputState::new));
1082 let values = Rc::new(RefCell::new(Vec::new()));
1083 let values_for_view = values.clone();
1084 let mut window = app.open_window(|_, _| FormattedCallbackTestView {
1085 state: state.clone(),
1086 values: values_for_view,
1087 });
1088
1089 window.draw();
1090 window.update(|view, window, cx| {
1091 view.state.update(cx, |state, cx| {
1092 state.set_value("123", window, cx);
1093 });
1094 });
1095
1096 assert_eq!(
1097 values.borrow().last().map(SharedString::as_ref),
1098 Some("123")
1099 );
1100 }
1101
1102 #[gpui::test]
1103 fn clearable_builder_enables_clear_button() {
1104 let mut app = TestApp::new();
1105 app.update(|cx| install_theme(cx, Theme::light()));
1106 let state = app.update(|cx| cx.new(InputState::new));
1107
1108 let input = Input::new(&state).clearable(true);
1109
1110 assert!(input.clearable);
1111 }
1112
1113 #[gpui::test]
1114 fn repeated_render_replaces_input_event_subscription() {
1115 let mut app = TestApp::new();
1116 app.update(|cx| install_theme(cx, Theme::light()));
1117 let stale_calls = Rc::new(Cell::new(0));
1118 let current_calls = Rc::new(Cell::new(0));
1119 let mut window = app.open_window(|_, cx| InputRenderTestView {
1120 state: cx.new(InputState::new),
1121 callback_calls: Some(stale_calls.clone()),
1122 initial_value: None,
1123 value: None,
1124 });
1125
1126 window.draw();
1127 window.update(|view, _, cx| {
1128 view.callback_calls = Some(current_calls.clone());
1129 cx.notify();
1130 });
1131 window.draw();
1132 window.update(|view, _, cx| {
1133 view.state.update(cx, |_, cx| cx.emit(InputEvent::Change));
1134 });
1135 assert_eq!(stale_calls.get(), 0);
1136 assert_eq!(current_calls.get(), 1);
1137
1138 window.update(|view, _, cx| {
1139 view.callback_calls = None;
1140 cx.notify();
1141 });
1142 window.draw();
1143 window.update(|view, _, cx| {
1144 view.state.update(cx, |_, cx| cx.emit(InputEvent::Change));
1145 });
1146 assert_eq!(current_calls.get(), 1);
1147 }
1148
1149 #[gpui::test]
1150 fn initial_value_does_not_overwrite_user_edits_on_rerender() {
1151 let mut app = TestApp::new();
1152 app.update(|cx| install_theme(cx, Theme::light()));
1153 let mut window = app.open_window(|_, cx| InputRenderTestView {
1154 state: cx.new(InputState::new),
1155 callback_calls: None,
1156 initial_value: Some("initial".into()),
1157 value: None,
1158 });
1159
1160 window.draw();
1161 window.update(|view, _, cx| {
1162 view.state.update(cx, |state, cx| {
1163 state.content = "edited".into();
1164 cx.notify();
1165 });
1166 cx.notify();
1167 });
1168 window.draw();
1169
1170 assert_eq!(
1171 window.read(|view, cx| view.state.read(cx).content().to_string()),
1172 "edited"
1173 );
1174 }
1175
1176 #[gpui::test]
1177 fn builder_initial_value_changes_are_ignored_after_first_render() {
1178 let mut app = TestApp::new();
1179 app.update(|cx| install_theme(cx, Theme::light()));
1180 let mut window = app.open_window(|_, cx| InputRenderTestView {
1181 state: cx.new(InputState::new),
1182 callback_calls: None,
1183 initial_value: Some("initial".into()),
1184 value: None,
1185 });
1186
1187 window.draw();
1188 window.update(|view, _, cx| {
1189 view.initial_value = Some("replacement".into());
1190 cx.notify();
1191 });
1192 window.draw();
1193
1194 assert_eq!(
1195 window.read(|view, cx| view.state.read(cx).content().to_string()),
1196 "initial"
1197 );
1198 }
1199
1200 #[gpui::test]
1201 fn set_value_emits_one_change_event() {
1202 let mut app = TestApp::new();
1203 app.update(|cx| install_theme(cx, Theme::light()));
1204 let calls = Rc::new(Cell::new(0));
1205 let mut window = app.open_window(|_, cx| InputRenderTestView {
1206 state: cx.new(InputState::new),
1207 callback_calls: Some(calls.clone()),
1208 initial_value: None,
1209 value: None,
1210 });
1211
1212 window.draw();
1213 window.update(|view, window, cx| {
1214 view.state
1215 .update(cx, |state, cx| state.set_value("edited", window, cx));
1216 });
1217
1218 assert_eq!(calls.get(), 1);
1219 }
1220
1221 #[gpui::test]
1222 fn set_value_replaces_existing_content() {
1223 let mut app = TestApp::new();
1224 app.update(|cx| install_theme(cx, Theme::light()));
1225 let mut window = app.open_window(|_, cx| InputRenderTestView {
1226 state: cx.new(InputState::new),
1227 callback_calls: None,
1228 initial_value: Some("initial".into()),
1229 value: None,
1230 });
1231
1232 window.draw();
1233 window.update(|view, window, cx| {
1234 view.state
1235 .update(cx, |state, cx| state.set_value("edited", window, cx));
1236 });
1237
1238 assert_eq!(
1239 window.read(|view, cx| view.state.read(cx).content().to_string()),
1240 "edited"
1241 );
1242 }
1243
1244 struct BareInputTestView {
1245 state: Entity<InputState>,
1246 }
1247
1248 impl Render for BareInputTestView {
1249 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1250 wire_actions(&self.state, window, cx)
1251 .h(px(36.0))
1252 .px(px(12.0))
1253 .rounded(px(8.0))
1254 .child(self.state.clone())
1255 }
1256 }
1257
1258 #[gpui::test]
1259 fn wire_actions_gives_custom_input_containers_full_keyboard_editing() {
1260 let mut app = TestApp::new();
1261 app.update(|cx| {
1262 install_theme(cx, Theme::light());
1263 crate::capabilities::controls::input::init(cx);
1264 });
1265 let state = app.update(|cx| cx.new(|cx| InputState::new(cx).value("hello")));
1266 let mut window = app.open_window(|_, _| BareInputTestView {
1267 state: state.clone(),
1268 });
1269
1270 window.draw();
1271 window.update(|_, window, cx| state.read(cx).focus_handle(cx).focus(window));
1272 window.draw();
1273 let handle: AnyWindowHandle = window.handle().into();
1274 app.raw_context_mut()
1275 .simulate_keystrokes(handle, "backspace");
1276 app.flush();
1277
1278 app.update(|cx| {
1279 assert_eq!(state.read(cx).content(), "hell");
1280 });
1281 }
1282}