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