1use std::rc::Rc;
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
5 AnyElement, App, DefiniteLength, Edges, ElementId, Entity, Global, Hsla,
6 InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Rems, RenderOnce, Role,
7 SharedString, StyleRefinement, Styled, TextAlign, TouchPhase, Window, div, px, relative,
8};
9
10use crate::button::{Button, ButtonRounded, ButtonVariants as _};
11use crate::input::clear_button;
12use crate::list::{ListDelegate, ListState};
13use crate::native_menu::NativeMenu;
14use crate::spinner::Spinner;
15use crate::touch_selection::{EditMenuItem, TouchSelectionOverlay};
16use crate::{ActiveTheme, Colorize, v_flex};
17use crate::{IconName, Size};
18use crate::{RoleOverride, Selectable, StyledExt, h_flex};
19use crate::{Sizable, StyleSized};
20use gpui_base::InputBase as BaseInput;
21use gpui_base::input::Editor as BaseEditor;
22use gpui_base::{LayoutDirection, LogicalStyledExt as _};
23use rust_i18n::t;
24
25use super::state::{TextInputState, sync_focused_input_registry};
26use super::{GutterStyle, InputContentType, InputState, sync_native_content_type};
27use crate::ThemeStyled as _;
28
29#[derive(Default)]
31struct NativeTouchSelection(bool);
32impl Global for NativeTouchSelection {}
33
34pub fn set_native_touch_selection(enabled: bool, cx: &mut App) {
43 cx.set_global(NativeTouchSelection(enabled));
44 cx.refresh_windows();
45}
46
47fn is_native_touch_selection(cx: &App) -> bool {
48 cx.try_global::<NativeTouchSelection>()
49 .is_some_and(|native| native.0)
50}
51
52fn accessibility_role(
53 is_multi_line: bool,
54 content_type: Option<InputContentType>,
55 role: RoleOverride,
56) -> Option<Role> {
57 role.resolve(|| {
58 if is_multi_line {
59 return Role::MultilineTextInput;
60 }
61
62 match content_type {
63 None => Role::TextInput,
64 Some(InputContentType::TelephoneNumber) => Role::PhoneNumberInput,
65 Some(InputContentType::EmailAddress) => Role::EmailInput,
66 Some(InputContentType::Url) => Role::UrlInput,
67 Some(InputContentType::Password | InputContentType::NewPassword) => Role::PasswordInput,
68 Some(InputContentType::DateTime) => Role::DateTimeInput,
69 Some(InputContentType::Birthdate) => Role::DateInput,
70 Some(
71 InputContentType::Name
72 | InputContentType::NamePrefix
73 | InputContentType::GivenName
74 | InputContentType::MiddleName
75 | InputContentType::FamilyName
76 | InputContentType::NameSuffix
77 | InputContentType::Nickname
78 | InputContentType::JobTitle
79 | InputContentType::OrganizationName
80 | InputContentType::Location
81 | InputContentType::FullStreetAddress
82 | InputContentType::StreetAddressLine1
83 | InputContentType::StreetAddressLine2
84 | InputContentType::AddressCity
85 | InputContentType::AddressState
86 | InputContentType::AddressCityAndState
87 | InputContentType::Sublocality
88 | InputContentType::CountryName
89 | InputContentType::PostalCode
90 | InputContentType::CreditCardNumber
91 | InputContentType::CreditCardName
92 | InputContentType::CreditCardGivenName
93 | InputContentType::CreditCardMiddleName
94 | InputContentType::CreditCardFamilyName
95 | InputContentType::CreditCardSecurityCode
96 | InputContentType::CreditCardExpiration
97 | InputContentType::CreditCardExpirationMonth
98 | InputContentType::CreditCardExpirationYear
99 | InputContentType::CreditCardType
100 | InputContentType::Username
101 | InputContentType::OneTimeCode
102 | InputContentType::ShipmentTrackingNumber
103 | InputContentType::FlightNumber
104 | InputContentType::BirthdateDay
105 | InputContentType::BirthdateMonth
106 | InputContentType::BirthdateYear
107 | InputContentType::CellularEid
108 | InputContentType::CellularImei,
109 ) => Role::TextInput,
110 }
111 })
112}
113
114fn exposes_accessibility_value(content_type: Option<InputContentType>) -> bool {
115 !matches!(
116 content_type,
117 Some(InputContentType::Password | InputContentType::NewPassword)
118 )
119}
120
121pub(crate) fn input_style(disabled: bool, cx: &App) -> (Hsla, Hsla) {
123 if disabled {
124 (
125 cx.theme().input.mix_oklab(cx.theme().transparent, 0.8),
126 cx.theme().muted_foreground,
127 )
128 } else {
129 (cx.theme().input_background(), cx.theme().foreground)
130 }
131}
132
133#[derive(IntoElement)]
135pub struct Input {
136 gutter_style: GutterStyle,
137 token_renderer: Option<gpui_base::input::InlineTokenRenderer>,
138 token_click_listener: Option<gpui_base::input::InlineTokenClickListener>,
139 token_hover_listener: Option<gpui_base::input::InlineTokenHoverListener>,
140 id: Option<ElementId>,
141 state: TextInputState,
142 style: StyleRefinement,
143 size: Size,
144 prefix: Option<AnyElement>,
145 suffix: Option<AnyElement>,
146 height: Option<DefiniteLength>,
147 appearance: bool,
148 cleanable: bool,
149 mask_toggle: bool,
150 disabled: bool,
151 readonly: bool,
152 bordered: bool,
153 focus_bordered: bool,
154 tab_index: isize,
155 selected: bool,
156 content_type: Option<InputContentType>,
157 role: RoleOverride,
158 accessibility_id: Option<SharedString>,
159 aria_label: Option<SharedString>,
160
161 context_menu_builder: Option<Rc<dyn Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu>>,
165
166 paste_handler: Option<Rc<dyn Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool>>,
169
170 list: Option<Rc<dyn super::list_popup::InputList>>,
172}
173
174impl Sizable for Input {
175 fn with_size(mut self, size: impl Into<Size>) -> Self {
176 self.size = size.into();
177 self
178 }
179}
180
181impl Selectable for Input {
182 fn selected(mut self, selected: bool) -> Self {
183 self.selected = selected;
184 self
185 }
186
187 fn is_selected(&self) -> bool {
188 self.selected
189 }
190}
191
192impl crate::FocusableExt for Input {
193 fn focus_ring(mut self, enabled: bool) -> Self {
194 self.focus_bordered = enabled;
195 self
196 }
197
198 fn is_focus_ring_enabled(&self) -> bool {
199 self.focus_bordered
200 }
201}
202
203impl Input {
204 pub fn token<R: IntoElement>(
208 mut self,
209 render: impl Fn(&super::InlineTokenContext, &mut Window, &mut App) -> R + 'static,
210 ) -> Self {
211 self.token_renderer = Some(Rc::new(move |token, window, cx| {
212 render(token, window, cx).into_any_element()
213 }));
214 self
215 }
216 pub fn on_token_click(
218 mut self,
219 listener: impl Fn(&super::InlineTokenClickEvent, &mut Window, &mut App) + 'static,
220 ) -> Self {
221 self.token_click_listener = Some(Rc::new(listener));
222 self
223 }
224 pub fn on_token_hover(
227 mut self,
228 listener: impl Fn(&super::InlineTokenHoverEvent, &mut Window, &mut App) + 'static,
229 ) -> Self {
230 self.token_hover_listener = Some(Rc::new(listener));
231 self
232 }
233
234 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
236 self.id = Some(id.into());
237 self
238 }
239
240 pub fn new(state: &Entity<InputState>) -> Self {
242 Self::with_state(state.clone().into())
243 }
244
245 pub(crate) fn from_state(state: impl Into<TextInputState>) -> Self {
250 Self::with_state(state.into())
251 }
252
253 fn with_state(state: TextInputState) -> Self {
254 Self {
255 gutter_style: GutterStyle::default(),
256 id: None,
257 state,
258 size: Size::default(),
259 style: StyleRefinement::default(),
260 prefix: None,
261 suffix: None,
262 height: None,
263 appearance: true,
264 cleanable: false,
265 mask_toggle: false,
266 disabled: false,
267 readonly: false,
268 bordered: true,
269 focus_bordered: true,
270 tab_index: 0,
271 selected: false,
272 content_type: None,
273 role: RoleOverride::default(),
274 accessibility_id: None,
275 aria_label: None,
276 context_menu_builder: None,
277 paste_handler: None,
278 token_renderer: None,
279 token_click_listener: None,
280 token_hover_listener: None,
281 list: None,
282 }
283 }
284
285 pub(crate) fn gutter_style(mut self, style: GutterStyle) -> Self {
286 self.gutter_style = style;
287 self
288 }
289
290 pub(crate) fn state(&self) -> &TextInputState {
294 &self.state
295 }
296
297 pub(crate) fn is_disabled(&self) -> bool {
298 self.disabled
299 }
300
301 pub fn list<D: ListDelegate>(mut self, list: &Entity<ListState<D>>) -> Self {
320 self.list = Some(Rc::new(list.clone()));
321 self
322 }
323
324 pub fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
325 self.accessibility_id = Some(id.into());
326 self
327 }
328
329 pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
330 self.aria_label = Some(label.into());
331 self
332 }
333
334 pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
335 self.prefix = Some(prefix.into_any_element());
336 self
337 }
338
339 pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
340 self.suffix = Some(suffix.into_any_element());
341 self
342 }
343
344 pub fn h_full(mut self) -> Self {
346 self.height = Some(relative(1.));
347 self
348 }
349
350 pub fn h(mut self, height: impl Into<DefiniteLength>) -> Self {
352 self.height = Some(height.into());
353 self
354 }
355
356 pub fn appearance(mut self, appearance: bool) -> Self {
358 self.appearance = appearance;
359 self
360 }
361
362 pub fn bordered(mut self, bordered: bool) -> Self {
364 self.bordered = bordered;
365 self
366 }
367
368 pub fn focus_bordered(mut self, bordered: bool) -> Self {
370 self.focus_bordered = bordered;
371 self
372 }
373
374 pub fn cleanable(mut self, cleanable: bool) -> Self {
376 self.cleanable = cleanable;
377 self
378 }
379
380 pub fn mask_toggle(mut self) -> Self {
382 self.mask_toggle = true;
383 self
384 }
385
386 pub fn content_type(mut self, content_type: InputContentType) -> Self {
391 self.content_type = Some(content_type);
392 self
393 }
394
395 pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
399 self.role = role.into();
400 self
401 }
402
403 pub fn disabled(mut self, disabled: bool) -> Self {
405 self.disabled = disabled;
406 self
407 }
408
409 pub fn readonly(mut self, readonly: bool) -> Self {
415 self.readonly = readonly;
416 self
417 }
418
419 pub fn tab_index(mut self, index: isize) -> Self {
421 self.tab_index = index;
422 self
423 }
424
425 pub fn context_menu(
430 mut self,
431 f: impl Fn(NativeMenu, &mut Window, &mut App) -> NativeMenu + 'static,
432 ) -> Self {
433 self.context_menu_builder = Some(Rc::new(f));
434 self
435 }
436
437 pub fn on_paste(
453 mut self,
454 handler: impl Fn(&gpui::ClipboardItem, &mut Window, &mut App) -> bool + 'static,
455 ) -> Self {
456 self.paste_handler = Some(Rc::new(handler));
457 self
458 }
459
460 fn render_touch_selection(
468 state: &TextInputState,
469 window: &Window,
470 cx: &App,
471 ) -> Vec<AnyElement> {
472 if is_native_touch_selection(cx) || state.touch_selection(cx).is_none() {
473 return Vec::new();
474 }
475 let capabilities = state.context_menu_capabilities(cx);
476 let editable = capabilities.is_editable();
477 let copyable = capabilities.is_copyable();
478 let pasteable = editable;
482 let selectable = state.text(cx).len() > 0 && !state.is_all_selected(cx);
483 let focus_handle = state.presentation(cx).focus_handle().clone();
484
485 let dispatch = {
486 move |action: &dyn gpui::Action, window: &mut Window, cx: &mut App| {
487 focus_handle.dispatch_action(action, window, cx);
488 }
489 };
490 let mut items = Vec::with_capacity(4);
491 if editable && copyable {
492 let dispatch = dispatch.clone();
493 items.push(EditMenuItem::new(t!("Input.Cut"), move |window, cx| {
494 dispatch(&gpui_base::input::Cut, window, cx);
495 }));
496 }
497 if copyable {
498 let dispatch = dispatch.clone();
499 let state = state.clone();
500 items.push(EditMenuItem::new(t!("Input.Copy"), move |window, cx| {
501 dispatch(&gpui_base::input::Copy, window, cx);
502 state.close_edit_menu(cx);
503 }));
504 }
505 if pasteable {
506 let dispatch = dispatch.clone();
507 items.push(EditMenuItem::new(t!("Input.Paste"), move |window, cx| {
508 dispatch(&gpui_base::input::Paste, window, cx);
509 }));
510 }
511 if selectable {
512 let state = state.clone();
513 items.push(EditMenuItem::new(
514 t!("Input.Select All"),
515 move |window, cx| state.select_all_from_edit_menu(window, cx),
516 ));
517 }
518
519 let drag_state = state.clone();
520 let source_state = state.clone();
521 TouchSelectionOverlay::new(
522 ("input-touch-selection", state.entity_id()),
523 move |_, cx| source_state.touch_selection(cx),
524 )
525 .handles(move |edge, phase, position, _, cx| match phase {
526 TouchPhase::Started => drag_state.begin_edge_drag(edge, position, cx),
527 TouchPhase::Moved => drag_state.update_edge_drag(position, cx),
528 TouchPhase::Ended | TouchPhase::Cancelled => drag_state.end_edge_drag(cx),
529 })
530 .items(items)
531 .into_elements(window, cx)
532 }
533
534 fn render_toggle_mask_button(state: &TextInputState, cx: &App) -> impl IntoElement {
535 let masked = state.presentation(cx).is_masked();
536 Button::new("toggle-mask")
537 .icon(if masked {
538 IconName::Eye
539 } else {
540 IconName::EyeOff
541 })
542 .accessibility_label(if masked {
543 t!("Input.Show Password")
544 } else {
545 t!("Input.Hide Password")
546 })
547 .xsmall()
548 .text()
549 .tab_stop(false)
550 .on_click({
551 let state = state.clone();
552 move |_, window, cx| state.toggle_masked(window, cx)
553 })
554 }
555
556 fn render_editor(
558 input_state: TextInputState,
559 gutter_style: GutterStyle,
560 search_panel: Option<AnyElement>,
561 _: &Window,
562 ) -> impl IntoElement {
563 v_flex().size_full().children(search_panel).child(
564 div().relative().flex_1().child(match input_state {
565 TextInputState::Editor(state) => BaseEditor::new(&state)
566 .with_line_number_renderer(gutter_style)
567 .into_any_element(),
568 state => state.into_any_element(),
569 }),
570 )
571 }
572}
573
574impl Styled for Input {
575 fn style(&mut self) -> &mut StyleRefinement {
576 &mut self.style
577 }
578}
579
580fn start_text_align(cx: &App) -> TextAlign {
582 if LayoutDirection::global(cx).is_rtl() {
583 TextAlign::Right
584 } else {
585 TextAlign::Left
586 }
587}
588
589impl RenderOnce for Input {
590 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
591 const LINE_HEIGHT: Rems = Rems(1.25);
592 let text_align = self
594 .style
595 .text
596 .text_align
597 .unwrap_or_else(|| start_text_align(cx));
598 let state = self.state.clone();
599 state.install_token_presentation(
600 Some(self.token_renderer.unwrap_or_else(|| {
601 Rc::new(|token, _, _| super::InputToken::new(token).into_any_element())
602 })),
603 self.token_click_listener,
604 matches!(
605 self.content_type,
606 Some(InputContentType::Password | InputContentType::NewPassword)
607 ),
608 cx,
609 );
610 state.install_token_hover_presentation(self.token_hover_listener, cx);
611 sync_focused_input_registry(&state, window, cx);
613
614 state.ensure_highlighter_factory(crate::highlighter::input_highlighter_factory(), cx);
615 state.set_editor_style(
616 gpui_base::input::InputEditorStyle {
617 foreground: cx.theme().foreground,
618 muted_foreground: cx.theme().muted_foreground,
619 background: cx.theme().editor_background(),
620 border: cx.theme().border,
621 selection: cx.theme().selection,
622 caret: cx.theme().caret,
623 diagnostics: gpui_base::input::DiagnosticColors {
624 error: cx.theme().highlight_theme.style.status.error(cx),
625 warning: cx.theme().highlight_theme.style.status.warning(cx),
626 info: cx.theme().highlight_theme.style.status.info(cx),
627 hint: cx.theme().highlight_theme.style.status.hint(cx),
628 },
629 highlight_styles: cx.theme().highlight_theme.clone(),
630 editor_invisible: cx.theme().highlight_theme.style.editor_invisible,
631 editor_active_line: cx.theme().highlight_theme.style.editor_active_line,
632 editor_gutter_background: cx.theme().highlight_theme.style.editor_gutter_background,
633 fold_icon_renderer: Some(Rc::new(|ix, is_folded| {
634 Button::new(("fold-icon", ix))
635 .ghost()
636 .icon(if is_folded {
637 IconName::ChevronRight
638 } else {
639 IconName::ChevronDown
640 })
641 .xsmall()
642 .rounded(ButtonRounded::Small)
643 .size(px(14.))
644 .selected(is_folded)
645 .into_any_element()
646 })),
647 },
648 cx,
649 );
650 state.set_editor_paddings(
651 if state.presentation(cx).is_multi_line() {
652 Edges {
653 top: self.size.input_py(),
654 right: self.size.input_px(),
655 bottom: self.size.input_py(),
656 left: if state.presentation(cx).is_code_editor() {
657 self.size.input_px().min(px(6.))
658 } else {
659 self.size.input_px()
660 },
661 }
662 } else {
663 Edges::default()
664 },
665 cx,
666 );
667 state.set_disabled(self.disabled, cx);
668 state.set_readonly(self.readonly, cx);
669 state.set_text_align(text_align, cx);
670 let custom = self.context_menu_builder.clone();
671 state.on_context_menu(
672 Rc::new(move |_, capabilities, position, window, cx| {
673 let menu = if let Some(custom) = custom.as_ref() {
674 custom(NativeMenu::new(), window, cx)
675 } else {
676 let enabled = !capabilities.is_disabled();
677 let editable = enabled && !capabilities.is_readonly();
680 let mut menu = NativeMenu::new();
681 if capabilities.is_code_editor() {
682 menu = menu
683 .menu_with_disabled(
684 t!("Input.Go to Definition"),
685 !(enabled && capabilities.has_definition()),
686 Box::new(gpui_base::input::GoToDefinition),
687 )
688 .menu_with_disabled(
689 t!("Input.Show Code Actions"),
690 !(editable && capabilities.has_code_actions()),
691 Box::new(gpui_base::input::ToggleCodeActions),
692 )
693 .separator();
694 }
695 menu.menu_with_disabled(
696 t!("Input.Cut"),
697 !(editable && capabilities.is_copyable()),
698 Box::new(gpui_base::input::Cut),
699 )
700 .menu_with_disabled(
701 t!("Input.Copy"),
702 !capabilities.is_copyable(),
703 Box::new(gpui_base::input::Copy),
704 )
705 .menu_with_disabled(
709 t!("Input.Paste"),
710 !editable,
711 Box::new(gpui_base::input::Paste),
712 )
713 .separator()
714 .menu(
715 t!("Input.Select All"),
716 Box::new(gpui_base::input::SelectAll),
717 )
718 };
719 menu.show(position, window, cx);
720 }),
721 cx,
722 );
723 let paste_handler = self
726 .paste_handler
727 .clone()
728 .filter(|_| state.presentation(cx).is_editable());
729 let mut overlays = state.render_overlays(window, cx);
730 overlays
731 .floating
732 .extend(Self::render_touch_selection(&state, window, cx));
733
734 let presentation = state.presentation(cx);
735 let content_type = self.content_type;
736 let disabled = self.disabled;
737 let list_popup = match (&state, self.list.take()) {
739 (TextInputState::Input(input), Some(list)) => Some(super::list_popup::ListPopup::new(
740 input,
741 list,
742 !self.disabled && !self.readonly,
743 self.size,
744 window,
745 cx,
746 )),
747 _ => None,
748 };
749 let is_multi_line = presentation.is_multi_line();
750 let accessibility_role = accessibility_role(
753 is_multi_line,
754 content_type.or(presentation
755 .is_masked()
756 .then_some(InputContentType::Password)),
757 self.role,
758 );
759 let input_focused =
760 presentation.focus_handle().is_focused(window) && !presentation.is_disabled();
761 if input_focused {
762 sync_native_content_type(window, content_type, presentation.is_editable());
763 }
764 let frame_focus_handle = window
765 .use_keyed_state(("input-frame-focus", state.entity_id()), cx, |_, cx| {
766 cx.focus_handle()
767 })
768 .read(cx)
769 .clone();
770 let focused = !presentation.is_disabled()
771 && (state.has_selection_focus(window, cx)
772 || frame_focus_handle.contains_focused(window, cx));
773
774 let gap_x = match self.size {
775 Size::Small => px(4.),
776 Size::Large => px(8.),
777 _ => px(6.),
778 };
779
780 let (bg, _) = input_style(presentation.is_disabled(), cx);
781 let bg = if presentation.is_code_editor() {
782 cx.theme().editor_background()
783 } else {
784 bg
785 };
786 let bg = if presentation.is_disabled() {
787 bg.opacity(0.5)
788 } else {
789 bg
790 };
791 let prefix = self.prefix;
792 let suffix = self.suffix;
793 let show_clear_button = self.cleanable
794 && presentation.is_editable()
795 && !presentation.is_loading()
796 && state.text(cx).len() > 0
797 && !presentation.is_multi_line();
798 let has_suffix =
799 suffix.is_some() || presentation.is_loading() || self.mask_toggle || show_clear_button;
800
801 let placeholder = Some(presentation.placeholder().clone()).filter(|p| !p.is_empty());
802
803 let placeholder_is_mask = presentation.mask_placeholder() == placeholder.as_deref();
805
806 let aria_label = match self.aria_label {
807 Some(label) => Some(label),
808 None if placeholder_is_mask => None,
809 None => placeholder.clone(),
810 };
811 state.set_accessibility(
812 gpui_base::input::InputAccessibility::new(accessibility_role)
813 .with_label(aria_label)
814 .with_placeholder(placeholder)
815 .with_accessibility_id(self.accessibility_id)
816 .with_value_exposed(exposes_accessibility_value(content_type)),
817 cx,
818 );
819 let id = self
820 .id
821 .unwrap_or_else(|| ("input", state.entity_id()).into());
822 BaseInput::new(id)
823 .semantic_owner(state.entity_id())
824 .focused(focused)
825 .disabled(disabled)
826 .track_focus(&frame_focus_handle)
827 .on_mouse_down(MouseButton::Right, {
828 let state = state.clone();
829 move |_, window, cx| {
830 sync_focused_input_registry(&state, window, cx);
834 }
835 })
836 .when(disabled, |this| {
837 this.capture_any_mouse_down(|_, _, cx| cx.stop_propagation())
838 })
839 .styles(|styles| {
840 styles.focused(|style| {
841 style.when(
842 self.appearance && self.bordered && self.focus_bordered,
843 |style| style.border_1().border_color(cx.theme().ring),
844 )
845 })
846 })
847 .role(RoleOverride::Presentational)
851 .flex_row_dir(cx)
852 .size_full()
853 .line_height(LINE_HEIGHT)
854 .when(!is_multi_line, |this| {
855 this.input_px(self.size).input_py(self.size)
856 })
857 .input_h(self.size)
858 .input_text_size(self.size)
859 .items_center()
860 .when(presentation.is_multi_line(), |this| {
861 this.h_auto()
862 .when_some(self.height, |this, height| this.h(height))
863 })
864 .when(self.appearance, |this| {
865 this.bg(bg)
866 .rounded(cx.theme().radius)
867 .when(self.bordered, |this| {
868 this.border_1().border_color(cx.theme().input)
869 })
870 })
871 .items_center()
872 .gap(gap_x)
873 .text_color(cx.theme().foreground)
876 .refine_style(&self.style)
877 .when(
878 focused && self.appearance && self.bordered && self.focus_bordered,
879 |this| this.focus_ring_style(window, cx),
880 )
881 .children(prefix.map(|p| {
882 div()
883 .when(presentation.is_disabled(), |this| this.opacity(0.5))
884 .child(p)
885 }))
886 .when(presentation.is_multi_line(), |this| {
887 this.child(Self::render_editor(
888 state.clone(),
889 self.gutter_style,
890 overlays.search,
891 window,
892 ))
893 })
894 .when(!presentation.is_multi_line(), |this| {
895 this.child(state.clone().into_any_element())
896 })
897 .when(has_suffix, |this| {
898 this.pe(self.size.input_px(), cx).child(
899 h_flex()
900 .flex_row_dir(cx)
901 .id("suffix")
902 .gap(gap_x)
903 .items_center()
904 .cursor_default()
905 .when(presentation.is_disabled(), |this| this.opacity(0.5))
906 .when(presentation.is_loading(), |this| {
907 this.child(Spinner::new().color(cx.theme().muted_foreground))
908 })
909 .when(self.mask_toggle, |this| {
910 this.child(Self::render_toggle_mask_button(&state, cx))
911 })
912 .when(show_clear_button, |this| {
913 this.child(clear_button(cx).on_click({
914 let state = state.clone();
915 move |_, window, cx| {
916 state.clean(window, cx);
917 state.focus(window, cx);
918 }
919 }))
920 })
921 .children(suffix),
922 )
923 })
924 .relative()
925 .children(overlays.floating)
926 .when_some(list_popup, |this, popup| popup.attach(this, cx))
927 .when_some(paste_handler, |this, handler| {
928 this.capture_action(move |_: &gpui_base::input::Paste, window, cx| {
929 if let Some(clipboard) = cx.read_from_clipboard() {
930 if handler(&clipboard, window, cx) {
931 cx.stop_propagation();
932 }
933 }
934 })
935 })
936 .render(window, cx)
937 }
938}
939
940#[cfg(test)]
941mod tests {
942 use super::*;
943 use crate::ElementExt as _;
944 use crate::input::AnyInputState;
945
946 #[test]
947 fn content_types_map_to_accessibility_roles() {
948 let cases = [
949 (None, Role::TextInput),
950 (Some(InputContentType::Name), Role::TextInput),
951 (Some(InputContentType::NamePrefix), Role::TextInput),
952 (Some(InputContentType::GivenName), Role::TextInput),
953 (Some(InputContentType::MiddleName), Role::TextInput),
954 (Some(InputContentType::FamilyName), Role::TextInput),
955 (Some(InputContentType::NameSuffix), Role::TextInput),
956 (Some(InputContentType::Nickname), Role::TextInput),
957 (Some(InputContentType::JobTitle), Role::TextInput),
958 (Some(InputContentType::OrganizationName), Role::TextInput),
959 (Some(InputContentType::Location), Role::TextInput),
960 (Some(InputContentType::FullStreetAddress), Role::TextInput),
961 (Some(InputContentType::StreetAddressLine1), Role::TextInput),
962 (Some(InputContentType::StreetAddressLine2), Role::TextInput),
963 (Some(InputContentType::AddressCity), Role::TextInput),
964 (Some(InputContentType::AddressState), Role::TextInput),
965 (Some(InputContentType::AddressCityAndState), Role::TextInput),
966 (Some(InputContentType::Sublocality), Role::TextInput),
967 (Some(InputContentType::CountryName), Role::TextInput),
968 (Some(InputContentType::PostalCode), Role::TextInput),
969 (
970 Some(InputContentType::TelephoneNumber),
971 Role::PhoneNumberInput,
972 ),
973 (Some(InputContentType::EmailAddress), Role::EmailInput),
974 (Some(InputContentType::Url), Role::UrlInput),
975 (Some(InputContentType::CreditCardNumber), Role::TextInput),
976 (Some(InputContentType::CreditCardName), Role::TextInput),
977 (Some(InputContentType::CreditCardGivenName), Role::TextInput),
978 (
979 Some(InputContentType::CreditCardMiddleName),
980 Role::TextInput,
981 ),
982 (
983 Some(InputContentType::CreditCardFamilyName),
984 Role::TextInput,
985 ),
986 (
987 Some(InputContentType::CreditCardSecurityCode),
988 Role::TextInput,
989 ),
990 (
991 Some(InputContentType::CreditCardExpiration),
992 Role::TextInput,
993 ),
994 (
995 Some(InputContentType::CreditCardExpirationMonth),
996 Role::TextInput,
997 ),
998 (
999 Some(InputContentType::CreditCardExpirationYear),
1000 Role::TextInput,
1001 ),
1002 (Some(InputContentType::CreditCardType), Role::TextInput),
1003 (Some(InputContentType::Username), Role::TextInput),
1004 (Some(InputContentType::Password), Role::PasswordInput),
1005 (Some(InputContentType::NewPassword), Role::PasswordInput),
1006 (Some(InputContentType::OneTimeCode), Role::TextInput),
1007 (
1008 Some(InputContentType::ShipmentTrackingNumber),
1009 Role::TextInput,
1010 ),
1011 (Some(InputContentType::FlightNumber), Role::TextInput),
1012 (Some(InputContentType::DateTime), Role::DateTimeInput),
1013 (Some(InputContentType::Birthdate), Role::DateInput),
1014 (Some(InputContentType::BirthdateDay), Role::TextInput),
1015 (Some(InputContentType::BirthdateMonth), Role::TextInput),
1016 (Some(InputContentType::BirthdateYear), Role::TextInput),
1017 (Some(InputContentType::CellularEid), Role::TextInput),
1018 (Some(InputContentType::CellularImei), Role::TextInput),
1019 ];
1020
1021 for (content_type, role) in cases {
1022 assert_eq!(
1023 accessibility_role(false, content_type, RoleOverride::Implicit),
1024 Some(role)
1025 );
1026 }
1027 }
1028
1029 #[test]
1030 fn multiline_inputs_keep_multiline_accessibility_role() {
1031 assert_eq!(
1032 accessibility_role(
1033 true,
1034 Some(InputContentType::Password),
1035 RoleOverride::Implicit
1036 ),
1037 Some(Role::MultilineTextInput)
1038 );
1039 }
1040
1041 #[test]
1042 fn explicit_accessibility_role_overrides_defaults() {
1043 assert_eq!(
1044 accessibility_role(
1045 false,
1046 Some(InputContentType::Password),
1047 Role::TextInput.into()
1048 ),
1049 Some(Role::TextInput)
1050 );
1051 assert_eq!(
1052 accessibility_role(
1053 true,
1054 Some(InputContentType::Password),
1055 Role::TextInput.into()
1056 ),
1057 Some(Role::TextInput)
1058 );
1059 }
1060
1061 #[test]
1062 fn presentational_role_emits_no_accessibility_node() {
1063 assert_eq!(
1064 accessibility_role(
1065 false,
1066 Some(InputContentType::Password),
1067 RoleOverride::Presentational
1068 ),
1069 None
1070 );
1071 assert_eq!(
1072 accessibility_role(true, None, RoleOverride::Presentational),
1073 None
1074 );
1075 }
1076
1077 #[test]
1078 fn role_option_converts_to_the_matching_override() {
1079 assert_eq!(
1080 RoleOverride::from(Some(Role::Button)),
1081 RoleOverride::Role(Role::Button)
1082 );
1083 assert_eq!(RoleOverride::from(None), RoleOverride::Presentational);
1084 }
1085
1086 #[gpui::test]
1087 fn default_text_align_follows_layout_direction(cx: &mut gpui::TestAppContext) {
1088 cx.update(|cx| {
1089 crate::init(cx);
1090 assert_eq!(start_text_align(cx), TextAlign::Left);
1091 LayoutDirection::Rtl.set_global(cx);
1092 assert_eq!(start_text_align(cx), TextAlign::Right);
1093 });
1094 }
1095
1096 #[gpui::test]
1097 fn test_on_paste_builder(cx: &mut gpui::TestAppContext) {
1098 use gpui::{AppContext as _, Render};
1099
1100 struct Probe;
1101 impl Render for Probe {
1102 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1103 div()
1104 }
1105 }
1106
1107 cx.update(crate::init);
1108 let _ = cx.add_window_view(|window, cx| {
1109 let state = cx.new(|cx| InputState::new(window, cx));
1110
1111 assert!(Input::new(&state).paste_handler.is_none());
1112 let input = Input::new(&state).on_paste(|_, _, _| true);
1113 assert!(input.paste_handler.is_some());
1114 Probe
1115 });
1116 }
1117
1118 #[gpui::test]
1119 fn test_on_token_hover_builder(cx: &mut gpui::TestAppContext) {
1120 use gpui::{AppContext as _, Render};
1121
1122 struct Probe;
1123 impl Render for Probe {
1124 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1125 div()
1126 }
1127 }
1128
1129 cx.update(crate::init);
1130 let _ = cx.add_window_view(|window, cx| {
1131 let state = cx.new(|cx| InputState::new(window, cx));
1132
1133 assert!(Input::new(&state).token_hover_listener.is_none());
1134 let input = Input::new(&state).on_token_hover(|_, _, _| {});
1135 assert!(input.token_hover_listener.is_some());
1136 Probe
1137 });
1138 }
1139
1140 #[gpui::test]
1141 fn editable_input_offers_accessibility_write_action(cx: &mut gpui::TestAppContext) {
1142 use gpui::{AccessibleAction, AppContext as _, Element as _, IntoElement as _, Render};
1143 use std::cell::RefCell;
1144
1145 type EmittedState = Option<(Option<String>, bool)>;
1146
1147 struct InputA11yProbe {
1148 state: Entity<InputState>,
1149 emitted: Rc<RefCell<EmittedState>>,
1150 disabled: bool,
1151 readonly: bool,
1152 }
1153
1154 impl Render for InputA11yProbe {
1155 fn render(
1156 &mut self,
1157 _window: &mut Window,
1158 _cx: &mut gpui::Context<Self>,
1159 ) -> impl IntoElement {
1160 let state = self.state.clone();
1161 let emitted = self.emitted.clone();
1162 div()
1163 .child(
1164 Input::new(&state)
1165 .disabled(self.disabled)
1166 .readonly(self.readonly),
1167 )
1168 .on_prepaint(move |_, window, cx| {
1169 state.update(cx, |state, cx| {
1170 let input = state.render(window, cx).into_element();
1171 let mut node = gpui::accesskit::Node::new(Role::Unknown);
1172 input.write_a11y_info(&mut node);
1173 *emitted.borrow_mut() = Some((
1174 node.value().map(ToOwned::to_owned),
1175 node.supports_action(AccessibleAction::SetValue),
1176 ));
1177 });
1178 })
1179 }
1180 }
1181
1182 cx.update(crate::init);
1183 let emitted = Rc::new(RefCell::new(None));
1184 let captured = emitted.clone();
1185 let (probe, cx) = cx.add_window_view(move |window, cx| InputA11yProbe {
1186 state: cx.new(|cx| InputState::new(window, cx).default_value("initial")),
1187 emitted,
1188 disabled: false,
1189 readonly: false,
1190 });
1191 cx.update(|window, cx| {
1192 let _ = window.draw(cx);
1193 });
1194 let expected_value = cfg!(feature = "test-support").then(|| "initial".to_owned());
1197 assert_eq!(*captured.borrow(), Some((expected_value.clone(), true)));
1198
1199 let state = probe.read_with(cx, |probe, _| probe.state.clone());
1200 for disabled in [false, true] {
1201 probe.update(cx, |probe, cx| {
1202 probe.disabled = disabled;
1203 probe.readonly = !disabled;
1204 cx.notify();
1205 });
1206 cx.update(|window, cx| window.draw(cx).clear(cx));
1207 assert_eq!(*captured.borrow(), Some((expected_value.clone(), false)));
1208 }
1209 probe.update(cx, |probe, cx| {
1210 probe.disabled = false;
1211 probe.readonly = false;
1212 cx.notify();
1213 });
1214 cx.update(|window, cx| {
1215 state.update(cx, |state, cx| state.set_masked(true, window, cx));
1216 window.draw(cx).clear(cx);
1217 });
1218 assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
1219 assert_eq!(*captured.borrow(), Some((None, true)));
1220 }
1221
1222 #[gpui::test]
1223 fn input_emits_accessibility_id(cx: &mut gpui::TestAppContext) {
1224 use gpui::{AppContext as _, Element as _, IntoElement as _, Render};
1225 use std::cell::RefCell;
1226
1227 type EmittedIds = Vec<Option<String>>;
1228
1229 struct InputA11yProbe {
1230 states: [Entity<InputState>; 2],
1231 emitted: Rc<RefCell<EmittedIds>>,
1232 }
1233
1234 impl Render for InputA11yProbe {
1235 fn render(
1236 &mut self,
1237 _window: &mut Window,
1238 _cx: &mut gpui::Context<Self>,
1239 ) -> impl IntoElement {
1240 let states = self.states.clone();
1241 let emitted = self.emitted.clone();
1242 div()
1243 .child(Input::new(&states[0]))
1244 .child(Input::new(&states[1]).accessibility_id("search.query"))
1245 .on_prepaint(move |_, window, cx| {
1246 *emitted.borrow_mut() = states
1247 .iter()
1248 .map(|state| {
1249 state.update(cx, |state, cx| {
1250 let input = state.render(window, cx).into_element();
1251 let mut node = gpui::accesskit::Node::new(Role::Unknown);
1252 input.write_a11y_info(&mut node);
1253 node.author_id().map(ToOwned::to_owned)
1254 })
1255 })
1256 .collect();
1257 })
1258 }
1259 }
1260
1261 cx.update(crate::init);
1262 let emitted = Rc::new(RefCell::new(Vec::new()));
1263 let captured = emitted.clone();
1264 let (_, cx) = cx.add_window_view(move |window, cx| InputA11yProbe {
1265 states: std::array::from_fn(|_| cx.new(|cx| InputState::new(window, cx))),
1266 emitted,
1267 });
1268 cx.update(|window, cx| {
1269 let _ = window.draw(cx);
1270 });
1271
1272 assert_eq!(*captured.borrow(), vec![None, Some("search.query".into())]);
1273 }
1274
1275 #[test]
1276 fn password_content_types_keep_accessibility_values_private() {
1277 assert!(exposes_accessibility_value(None));
1278 assert!(!exposes_accessibility_value(Some(
1279 InputContentType::Password
1280 )));
1281 assert!(!exposes_accessibility_value(Some(
1282 InputContentType::NewPassword
1283 )));
1284 }
1285
1286 #[gpui::test]
1287 fn focused_input_registry_tracks_focus_and_blur(cx: &mut gpui::TestAppContext) {
1288 use crate::{Root, WindowExt as _};
1289 use gpui::{AppContext as _, Render};
1290
1291 struct Probe {
1292 input: Entity<InputState>,
1293 textarea: Entity<crate::input::TextareaState>,
1294 editor: Entity<crate::input::EditorState>,
1295 otp: Entity<gpui_base::OtpState>,
1296 other: gpui::FocusHandle,
1297 }
1298 impl Render for Probe {
1299 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1300 div()
1301 .child(div().track_focus(&self.other))
1302 .child(Input::new(&self.input))
1303 .child(crate::input::Textarea::new(&self.textarea))
1304 .child(crate::input::Editor::new(&self.editor))
1305 .child(crate::input::OtpInput::new(&self.otp))
1306 }
1307 }
1308
1309 cx.update(crate::init);
1310 let mut input = None;
1311 let mut textarea = None;
1312 let mut editor = None;
1313 let mut other_focus = None;
1314 let mut otp = None;
1315 let window = cx.update(|cx| {
1316 cx.open_window(Default::default(), |window, cx| {
1317 let state = cx.new(|cx| InputState::new(window, cx));
1318 let textarea_state = cx.new(|cx| crate::input::TextareaState::new(window, cx));
1319 let editor_state =
1320 cx.new(|cx| crate::input::EditorState::new(window, cx).language("rust"));
1321 let otp_state = cx.new(|cx| gpui_base::OtpState::new(6, window, cx));
1322 input = Some(state.clone());
1323 textarea = Some(textarea_state.clone());
1324 editor = Some(editor_state.clone());
1325 otp = Some(otp_state.clone());
1326 let other = cx.focus_handle();
1327 other_focus = Some(other.clone());
1328 let probe = cx.new(|_| Probe {
1329 input: state,
1330 textarea: textarea_state,
1331 editor: editor_state,
1332 otp: otp_state,
1333 other,
1334 });
1335 cx.new(|cx| Root::new(probe, window, cx))
1336 })
1337 .unwrap()
1338 });
1339 let input = input.unwrap();
1340 let textarea = textarea.unwrap();
1341 let editor = editor.unwrap();
1342 let otp = otp.unwrap();
1343 let other_focus = other_focus.unwrap();
1344 let mut cx = gpui::VisualTestContext::from_window(window.into(), cx);
1345
1346 let cases: Vec<AnyInputState> =
1348 vec![input.into(), textarea.into(), editor.into(), otp.into()];
1349 for expected in cases {
1350 cx.update(|window, cx| {
1351 let _ = window.draw(cx);
1352 });
1353 cx.update(|window, cx| expected.focus_handle(cx).focus(window, cx));
1354 cx.run_until_parked();
1355 cx.update(|window, cx| {
1356 let _ = window.draw(cx);
1357 });
1358 assert_eq!(
1359 cx.update(|window, cx| window.focused_input(cx)),
1360 Some(expected)
1361 );
1362
1363 cx.update(|window, cx| other_focus.clone().focus(window, cx));
1364 cx.run_until_parked();
1365 cx.update(|window, cx| {
1366 let _ = window.draw(cx);
1367 });
1368 assert_eq!(cx.update(|window, cx| window.focused_input(cx)), None);
1369 }
1370 }
1371
1372 #[gpui::test]
1373 fn focused_input_registry_ignores_input_removed_while_focused(cx: &mut gpui::TestAppContext) {
1374 use crate::{Root, WindowExt as _};
1375 use gpui::{AppContext as _, Render};
1376
1377 struct Probe {
1378 input: Entity<InputState>,
1379 show_input: bool,
1380 other: gpui::FocusHandle,
1381 }
1382 impl Render for Probe {
1383 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1384 let base = div().child(div().track_focus(&self.other));
1385 if self.show_input {
1386 base.child(Input::new(&self.input))
1387 } else {
1388 base
1389 }
1390 }
1391 }
1392
1393 cx.update(crate::init);
1394 let mut input = None;
1395 let mut other_focus = None;
1396 let mut probe_entity = None;
1397 let window = cx.update(|cx| {
1398 cx.open_window(Default::default(), |window, cx| {
1399 let state = cx.new(|cx| InputState::new(window, cx));
1400 input = Some(state.clone());
1401 let other = cx.focus_handle();
1402 other_focus = Some(other.clone());
1403 let probe = cx.new(|_| Probe {
1404 input: state,
1405 show_input: true,
1406 other,
1407 });
1408 probe_entity = Some(probe.clone());
1409 cx.new(|cx| Root::new(probe, window, cx))
1410 })
1411 .unwrap()
1412 });
1413 let input: AnyInputState = input.unwrap().into();
1414 let other_focus = other_focus.unwrap();
1415 let probe = probe_entity.unwrap();
1416 let mut cx = gpui::VisualTestContext::from_window(window.into(), cx);
1417
1418 cx.update(|window, cx| {
1419 let _ = window.draw(cx);
1420 });
1421 cx.update(|window, cx| input.focus_handle(cx).focus(window, cx));
1422 cx.run_until_parked();
1423 cx.update(|window, cx| {
1424 let _ = window.draw(cx);
1425 });
1426 assert_eq!(
1427 cx.update(|window, cx| window.focused_input(cx)),
1428 Some(input.clone())
1429 );
1430
1431 cx.update(|window, cx| {
1435 probe.update(cx, |probe, cx| {
1436 probe.show_input = false;
1437 cx.notify();
1438 });
1439 other_focus.focus(window, cx);
1440 });
1441 cx.run_until_parked();
1442 cx.update(|window, cx| {
1443 let _ = window.draw(cx);
1444 });
1445 assert!(!cx.update(|window, cx| window.has_focused_input(cx)));
1446 assert_eq!(cx.update(|window, cx| window.focused_input(cx)), None);
1447 }
1448
1449 #[gpui::test]
1450 fn native_touch_selection_leaves_the_handles_and_menu_to_the_platform(
1451 cx: &mut gpui::TestAppContext,
1452 ) {
1453 use gpui::{AppContext as _, LongPressEvent, Render, point};
1454
1455 struct Probe(Entity<InputState>);
1456 impl Render for Probe {
1457 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1458 div().w(px(300.)).child(Input::new(&self.0))
1459 }
1460 }
1461
1462 cx.update(crate::init);
1463 let (probe, cx) = cx.add_window_view(|window, cx| {
1464 Probe(cx.new(|cx| InputState::new(window, cx).default_value("quick select value")))
1465 });
1466 cx.update(|window, cx| {
1467 let _ = window.draw(cx);
1468 });
1469 let position = point(px(40.), px(16.));
1470 for phase in [TouchPhase::Started, TouchPhase::Ended] {
1471 cx.simulate_event(LongPressEvent {
1472 phase,
1473 start_position: position,
1474 position,
1475 });
1476 }
1477 let state = TextInputState::from(probe.read_with(cx, |probe, _| probe.0.clone()));
1478 let overlay = |cx: &mut gpui::VisualTestContext| {
1479 cx.update(|window, cx| Input::render_touch_selection(&state, window, cx).len())
1480 };
1481 assert!(cx.update(|_, cx| state.touch_selection(cx).is_some()));
1482 assert!(overlay(cx) > 0);
1483
1484 cx.update(|_, cx| set_native_touch_selection(true, cx));
1485 assert!(cx.update(|_, cx| state.touch_selection(cx).is_some()));
1486 assert_eq!(overlay(cx), 0);
1487
1488 cx.update(|_, cx| set_native_touch_selection(false, cx));
1489 assert!(overlay(cx) > 0);
1490 }
1491
1492 #[derive(IntoElement)]
1494 struct InheritedColor(Rc<std::cell::Cell<Option<Hsla>>>);
1495
1496 impl RenderOnce for InheritedColor {
1497 fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
1498 self.0.set(Some(window.text_style().color));
1499 div().w(px(8.)).h(px(8.))
1500 }
1501 }
1502
1503 struct BareInput {
1506 state: Entity<InputState>,
1507 color: Rc<std::cell::Cell<Option<Hsla>>>,
1508 text_color: Option<Hsla>,
1509 }
1510
1511 impl gpui::Render for BareInput {
1512 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1513 Input::new(&self.state)
1514 .prefix(InheritedColor(self.color.clone()))
1515 .when_some(self.text_color, |this, color| this.text_color(color))
1516 }
1517 }
1518
1519 #[gpui::test]
1520 fn input_text_takes_the_theme_foreground_without_root(cx: &mut gpui::TestAppContext) {
1521 use gpui::AppContext as _;
1522
1523 let foreground = cx.update(|cx| {
1524 crate::init(cx);
1525 let theme = crate::Theme::global_mut(cx);
1526 theme.foreground = gpui::white();
1527 theme.foreground
1528 });
1529 for (text_color, expected) in [(None, foreground), (Some(gpui::red()), gpui::red())] {
1530 let color = Rc::new(std::cell::Cell::new(None));
1531 let (_, cx) = cx.add_window_view({
1532 let color = color.clone();
1533 move |window, cx| BareInput {
1534 state: cx.new(|cx| InputState::new(window, cx)),
1535 color,
1536 text_color,
1537 }
1538 });
1539 cx.run_until_parked();
1540 cx.update(|window, cx| window.draw(cx).clear(cx));
1541 assert_eq!(color.get(), Some(expected));
1542 }
1543 }
1544}