1use gpui::ColorExt as _;
2use gpui::{
3 AnyElement, App, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity, EventEmitter,
4 FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length, ParentElement, Render,
5 RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window,
6 deferred, div, prelude::FluentBuilder, px, rems,
7};
8use gpui_base::TestSupportExt as _;
9use rust_i18n::t;
10
11use crate::ThemeStyled as _;
12use crate::{
13 ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size,
14 StyleSized, StyledExt,
15 actions::Cancel,
16 h_flex,
17 input::{clear_button, input_style},
18 list::List,
19 searchable_list::{
20 SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState,
21 },
22 sizing::DROPDOWN_LIST_PADDING,
23 v_flex,
24};
25use gpui_base::{GlobalState, Select as BaseSelect};
26
27pub use crate::searchable_list::SearchableGroup as SelectGroup;
31pub use crate::searchable_list::SearchableListDelegate as SelectDelegate;
33pub use crate::searchable_list::SearchableListItem as SelectItem;
35pub use crate::searchable_list::SearchableListItemElement as SelectListItem;
37pub use crate::searchable_list::SearchableVec;
39
40#[derive(IntoElement)]
41pub struct Caret {
42 size: Size,
43 color: Option<Hsla>,
44}
45
46impl Caret {
47 pub fn new(size: Size) -> Self {
49 Self { size, color: None }
50 }
51
52 pub fn text_color(mut self, color: Hsla) -> Self {
54 self.color = Some(color);
55 self
56 }
57}
58
59impl RenderOnce for Caret {
60 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
61 Icon::new(IconName::ChevronDown)
62 .with_size(match self.size {
63 Size::XSmall => Size::XSmall,
64 Size::Small => Size::Small,
65 _ => Size::Medium,
66 })
67 .when_some(self.color, |this, color| this.text_color(color))
68 }
69}
70
71pub enum SelectEvent<D: SearchableListDelegate + 'static>
73where
74 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
75{
76 Confirm(Option<<D::Item as SearchableListItem>::Value>),
77}
78
79struct SelectOptions {
82 style: StyleRefinement,
83 size: Size,
84 icon: Option<Icon>,
85 cleanable: bool,
86 placeholder: Option<SharedString>,
87 accessibility_label: Option<SharedString>,
88 title_prefix: Option<SharedString>,
89 search_placeholder: Option<SharedString>,
90 menu_width: Length,
91 menu_max_h: Length,
92 disabled: bool,
93 appearance: bool,
94 focus_ring_enabled: bool,
95}
96
97impl Default for SelectOptions {
98 fn default() -> Self {
99 Self {
100 style: StyleRefinement::default(),
101 size: Size::default(),
102 icon: None,
103 cleanable: false,
104 placeholder: None,
105 accessibility_label: None,
106 title_prefix: None,
107 menu_width: Length::Auto,
108 menu_max_h: rems(20.).into(),
109 disabled: false,
110 appearance: true,
111 focus_ring_enabled: true,
112 search_placeholder: None,
113 }
114 }
115}
116
117pub struct SelectState<D: SearchableListDelegate + 'static>
123where
124 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
125{
126 pub(crate) state: SearchableListState<D>,
127
128 searchable: bool,
130 icon: Option<Icon>,
131 title_prefix: Option<SharedString>,
132 focus_ring_enabled: bool,
133}
134
135#[derive(IntoElement)]
137pub struct Select<D: SearchableListDelegate + 'static>
138where
139 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
140{
141 id: ElementId,
142 state: Entity<SelectState<D>>,
143 options: SelectOptions,
144 empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
145}
146
147impl<D> SelectState<D>
148where
149 D: SearchableListDelegate + 'static,
150 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
151{
152 pub fn new(
154 delegate: D,
155 selected_index: Option<IndexPath>,
156 window: &mut Window,
157 cx: &mut Context<Self>,
158 ) -> Self {
159 let weak = cx.entity().downgrade();
160 let weak_confirm = weak.clone();
161 let weak_cancel = weak.clone();
162 let weak_empty = weak;
163
164 let selected_indices = selected_index.into_iter().collect::<Vec<_>>();
165
166 let state = SearchableListState::new(
167 delegate,
168 selected_indices,
169 move |selected_index, _secondary, window, cx| {
171 cx.defer_in(window, {
172 let weak_confirm = weak_confirm.clone();
173 move |list_state, window, cx| {
174 let mut selection = weak_confirm
175 .upgrade()
176 .map(|e| e.read(cx).state.selection.clone())
177 .unwrap_or_default();
178
179 let changes = {
180 let mut changes: Vec<SearchableListChange> = selection
181 .iter()
182 .map(|(ix, _)| SearchableListChange::Deselect { index: *ix })
183 .collect();
184
185 if let Some(ix) = selected_index {
186 changes.push(SearchableListChange::Select { index: ix });
187 }
188
189 changes
190 };
191
192 list_state
195 .delegate_mut()
196 .delegate
197 .on_will_change(&mut selection, &changes);
198
199 let confirmed = weak_confirm.update(cx, |this, cx| {
200 this.state.selection = selection;
201
202 let final_value =
203 this.state.selection.first().map(|(_, i)| i.value().clone());
204
205 cx.emit(SelectEvent::Confirm(final_value.clone()));
206 cx.notify();
207 this.set_open(false, cx);
208 this.focus(window, cx);
209
210 (this.state.selection.clone(), final_value)
211 });
212
213 if let Ok((mut new_selection, final_value)) = confirmed {
219 if !list_state.query_input.read(cx).value().is_empty() {
220 list_state.set_query("", window, cx);
221 }
222
223 if let Some(ix) = final_value
224 .as_ref()
225 .and_then(|value| list_state.delegate().delegate.position(value))
226 {
227 list_state.set_selected_index(Some(ix), window, cx);
228 if let Some((slot, _)) = new_selection.first_mut() {
229 *slot = ix;
230 }
231 _ = weak_confirm.update(cx, |this, cx| {
232 if let Some((slot, _)) = this.state.selection.first_mut() {
233 *slot = ix;
234 }
235 cx.notify();
236 });
237 }
238
239 list_state
240 .delegate_mut()
241 .update_selection_snapshot(new_selection.clone());
242 list_state
243 .delegate_mut()
244 .delegate
245 .on_confirm(&new_selection);
246 }
247 }
248 });
249 },
250 move |_final_selected_index, window, cx| {
252 cx.defer_in(window, {
253 let weak_cancel = weak_cancel.clone();
254 move |list_state, window, cx| {
255 let committed_ix = weak_cancel
256 .upgrade()
257 .and_then(|e| e.read(cx).state.selection.first().map(|(ix, _)| *ix));
258
259 if !list_state.query_input.read(cx).value().is_empty() {
260 list_state.set_query("", window, cx);
261 }
262 list_state.set_selected_index(committed_ix, window, cx);
263
264 _ = weak_cancel.update(cx, |this, cx| {
265 this.set_open(false, cx);
266 this.focus(window, cx);
267 });
268 }
269 });
270 },
271 move |window, cx| {
273 if let Some(empty) = weak_empty
274 .upgrade()
275 .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx)))
276 {
277 empty
278 } else {
279 h_flex()
280 .justify_center()
281 .py_6()
282 .text_color(cx.theme().muted_foreground.opacity(0.6))
283 .child(Icon::new(IconName::Inbox).size(px(28.)))
284 .into_any_element()
285 }
286 },
287 Self::on_blur,
288 window,
289 cx,
290 );
291
292 Self {
293 state,
294 searchable: false,
295 icon: None,
296 title_prefix: None,
297 focus_ring_enabled: true,
298 }
299 }
300
301 pub fn searchable(mut self, searchable: bool) -> Self {
305 self.searchable = searchable;
306 self
307 }
308
309 pub fn set_selected_index(
311 &mut self,
312 selected_index: Option<IndexPath>,
313 window: &mut Window,
314 cx: &mut Context<Self>,
315 ) {
316 self.state.list.update(cx, |list, cx| {
317 list._set_selected_index(selected_index, window, cx);
318 });
319
320 let item = selected_index
321 .and_then(|ix| self.state.list.read(cx).delegate().delegate.item(ix))
322 .map(|i| i.clone());
323
324 self.state.selection = match (selected_index, item) {
325 (Some(ix), Some(item)) => vec![(ix, item)],
326 _ => vec![],
327 };
328 self.state.sync_snapshot(cx);
329 }
330
331 pub fn set_selected_value(
339 &mut self,
340 selected_value: &<D::Item as SearchableListItem>::Value,
341 window: &mut Window,
342 cx: &mut Context<Self>,
343 ) {
344 self.state.clear_query(window, cx);
345
346 let selected_index = self
347 .state
348 .list
349 .read(cx)
350 .delegate()
351 .delegate
352 .position(selected_value);
353
354 self.set_selected_index(selected_index, window, cx);
355 }
356
357 pub fn set_items(&mut self, items: D, _: &mut Window, cx: &mut Context<Self>)
359 where
360 D: SearchableListDelegate + 'static,
361 {
362 self.state.list.update(cx, |list, _| {
363 list.delegate_mut().delegate = items;
364 });
365 }
366
367 pub fn selected_index(&self, cx: &App) -> Option<IndexPath> {
369 self.state.list.read(cx).selected_index()
370 }
371
372 pub fn selected_value(&self) -> Option<&<D::Item as SearchableListItem>::Value> {
374 self.state.selection.first().map(|(_, i)| i.value())
375 }
376
377 pub fn focus(&self, window: &mut Window, cx: &mut App) {
379 self.state.focus_handle.focus(window, cx);
380 }
381
382 fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
383 if self.state.list.read(cx).is_focused(window, cx)
384 || self.state.focus_handle.is_focused(window)
385 {
386 return;
387 }
388
389 self.clear_query_and_restore_cursor(window, cx);
390 self.set_open(false, cx);
391 cx.notify();
392 }
393
394 fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
395 cx.stop_propagation();
396
397 self.set_open(!self.state.open, cx);
398
399 if self.state.open {
400 self.state.list.focus_handle(cx).focus(window, cx);
401 } else {
402 self.clear_query_and_restore_cursor(window, cx);
403 }
404
405 cx.notify();
406 }
407
408 fn escape(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
409 if !self.state.open {
410 cx.propagate();
411 return;
412 }
413
414 cx.stop_propagation();
415 self.clear_query_and_restore_cursor(window, cx);
416 self.set_open(false, cx);
417 self.focus(window, cx);
418 cx.notify();
419 }
420
421 fn clear_query_and_restore_cursor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
425 self.state.clear_query(window, cx);
426
427 let committed_ix = self.state.selection.first().map(|(ix, _)| *ix);
428 self.state.list.update(cx, |list, cx| {
429 if list.selected_index() != committed_ix {
430 list.set_selected_index(committed_ix, window, cx);
431 }
432 });
433 }
434
435 fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
436 let dismissed = self.state.open && !open;
437 self.state.open = open;
438 self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
439
440 if dismissed {
441 cx.emit(DismissEvent);
442 }
443 cx.notify();
444 }
445
446 fn clean(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
447 cx.stop_propagation();
448 self.set_selected_index(None, window, cx);
449 cx.emit(SelectEvent::Confirm(None));
450 }
451
452 fn display_title(&mut self, _: &Window, cx: &mut Context<Self>) -> impl IntoElement {
453 let default_title = div().text_color(cx.theme().muted_foreground).child(
454 self.state
455 .placeholder
456 .clone()
457 .unwrap_or_else(|| t!("Select.placeholder").into()),
458 );
459
460 let Some(selected_index) = self.selected_index(cx) else {
461 return default_title;
462 };
463
464 let Some(title) = self
465 .state
466 .list
467 .read(cx)
468 .delegate()
469 .delegate
470 .item(selected_index)
471 .map(|item| {
472 if let Some(el) = item.display_title() {
473 el
474 } else if let Some(prefix) = self.title_prefix.as_ref() {
475 format!("{}{}", prefix, item.title()).into_any_element()
476 } else {
477 item.title().into_any_element()
478 }
479 })
480 else {
481 return default_title;
482 };
483
484 div()
485 .when(self.state.disabled, |this| {
486 this.text_color(cx.theme().muted_foreground)
487 })
488 .child(title)
489 }
490
491 fn accessibility_value(&self) -> SharedString {
492 let Some((_, item)) = self.state.selection.first() else {
493 return self
494 .state
495 .placeholder
496 .clone()
497 .unwrap_or_else(|| t!("Select.placeholder").into());
498 };
499
500 if let Some(prefix) = self.title_prefix.as_ref() {
501 format!("{}{}", prefix, item.title()).into()
502 } else {
503 item.title()
504 }
505 }
506}
507
508impl<D> Render for SelectState<D>
509where
510 D: SearchableListDelegate + 'static,
511 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
512{
513 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
514 let searchable = self.searchable;
515 let is_focused = self.state.focus_handle.is_focused(window);
516 let show_clean = self.state.cleanable && self.selected_index(cx).is_some();
517 let bounds = self.state.bounds;
518 let allow_open = !(self.state.open || self.state.disabled);
519 let outline_visible = self.state.open || (is_focused && !self.state.disabled);
520
521 let (bg, fg) = input_style(self.state.disabled, cx);
522
523 self.state.list.update(cx, |list, cx| {
524 list.set_searchable(searchable, cx);
525 list.delegate_mut().size = self.state.size;
526 });
527
528 div().size_full().relative().child(
529 div()
530 .relative()
531 .on_prepaint({
532 let state = cx.entity();
533 move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds)
534 })
535 .child(
536 div()
537 .id("input")
538 .test_support()
539 .relative()
540 .flex()
541 .items_center()
542 .justify_between()
543 .border_1()
544 .border_color(cx.theme().transparent)
545 .when(self.state.appearance, |this| {
546 this.bg(bg)
547 .text_color(fg)
548 .when(self.state.disabled, |this| this.opacity(0.5))
549 .border_color(cx.theme().input)
550 .rounded(cx.theme().radius)
551 })
552 .input_size(self.state.size)
553 .input_text_size(self.state.size)
554 .refine_style(&self.state.style)
555 .when(outline_visible && self.state.appearance, |this| {
556 this.border_1().border_color(cx.theme().ring)
557 })
558 .when(
559 outline_visible && self.state.appearance && self.focus_ring_enabled,
560 |this| this.focus_ring_style(window, cx),
561 )
562 .when(allow_open, |this| {
563 this.on_click(cx.listener(Self::toggle_menu))
564 })
565 .child(
566 h_flex()
567 .id("inner")
568 .w_full()
569 .min_w_0()
570 .overflow_hidden()
571 .whitespace_nowrap()
572 .items_center()
573 .justify_between()
574 .gap_1()
575 .child(
576 div()
577 .id("title")
578 .flex_1()
579 .min_w_0()
580 .overflow_hidden()
581 .whitespace_nowrap()
582 .truncate()
583 .child(self.display_title(window, cx)),
584 )
585 .when(show_clean, |this| {
586 this.child(clear_button(cx).map(|this| {
587 if self.state.disabled {
588 this.disabled(true)
589 } else {
590 this.on_click(cx.listener(Self::clean))
591 }
592 }))
593 })
594 .when(!show_clean, |this| {
595 let icon = match self.icon.clone() {
596 Some(icon) => icon
597 .xsmall()
598 .text_color(cx.theme().muted_foreground)
599 .into_any_element(),
600 None => Caret::new(self.state.size)
601 .text_color(cx.theme().muted_foreground)
602 .into_any_element(),
603 };
604
605 this.child(icon)
606 }),
607 ),
608 )
609 .when(self.state.open, |this| {
610 this.child(
611 deferred(crate::popover::dropdown_popup(
612 ("select-popup", cx.entity_id()),
613 bounds,
614 v_flex()
615 .occlude()
616 .map(|this| match self.state.menu_width {
617 Length::Auto => this.w(bounds.size.width),
618 Length::Definite(w) => this.w(w),
619 })
620 .popover_style(cx)
621 .child(
622 List::new(&self.state.list)
623 .when_some(
624 self.state.search_placeholder.clone(),
625 |this, placeholder| {
626 this.search_placeholder(placeholder)
627 },
628 )
629 .with_size(self.state.size)
630 .max_h(self.state.menu_max_h)
631 .paddings(Edges::all(DROPDOWN_LIST_PADDING)),
632 )
633 .on_mouse_down_out(cx.listener(|this, _, window, cx| {
634 this.escape(&Cancel, window, cx);
635 })),
636 cx,
637 ))
638 .priority(gpui_base::POPUP_PRIORITY),
639 )
640 }),
641 )
642 }
643}
644
645impl<D> Select<D>
646where
647 D: SearchableListDelegate + 'static,
648 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
649{
650 pub fn new(state: &Entity<SelectState<D>>) -> Self {
651 Self {
652 id: ("select", state.entity_id()).into(),
653 state: state.clone(),
654 options: SelectOptions::default(),
655 empty: None,
656 }
657 }
658
659 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
661 self.id = id.into();
662 self
663 }
664
665 pub fn menu_width(mut self, width: impl Into<Length>) -> Self {
667 self.options.menu_width = width.into();
668 self
669 }
670
671 pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self {
673 self.options.menu_max_h = max_h.into();
674 self
675 }
676
677 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
679 self.options.placeholder = Some(placeholder.into());
680 self
681 }
682
683 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
688 self.options.accessibility_label = Some(label.into());
689 self
690 }
691
692 pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
694 self.options.icon = Some(icon.into());
695 self
696 }
697
698 pub fn title_prefix(mut self, prefix: impl Into<SharedString>) -> Self {
702 self.options.title_prefix = Some(prefix.into());
703 self
704 }
705
706 pub fn cleanable(mut self, cleanable: bool) -> Self {
708 self.options.cleanable = cleanable;
709 self
710 }
711
712 pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
714 self.options.search_placeholder = Some(placeholder.into());
715 self
716 }
717
718 pub fn disabled(mut self, disabled: bool) -> Self {
720 self.options.disabled = disabled;
721 self
722 }
723
724 pub fn empty<E: IntoElement + 'static>(
726 mut self,
727 builder: impl Fn(&mut Window, &App) -> E + 'static,
728 ) -> Self {
729 self.empty = Some(Box::new(move |window, cx| {
730 builder(window, cx).into_any_element()
731 }));
732 self
733 }
734
735 pub fn appearance(mut self, appearance: bool) -> Self {
737 self.options.appearance = appearance;
738 self
739 }
740}
741
742impl<D> Sizable for Select<D>
743where
744 D: SearchableListDelegate + 'static,
745 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
746{
747 fn with_size(mut self, size: impl Into<Size>) -> Self {
748 self.options.size = size.into();
749 self
750 }
751}
752
753impl<D> crate::FocusableExt for Select<D>
754where
755 D: SearchableListDelegate + 'static,
756 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
757{
758 fn focus_ring(mut self, enabled: bool) -> Self {
759 self.options.focus_ring_enabled = enabled;
760 self
761 }
762
763 fn is_focus_ring_enabled(&self) -> bool {
764 self.options.focus_ring_enabled
765 }
766}
767
768impl<D> EventEmitter<SelectEvent<D>> for SelectState<D>
769where
770 D: SearchableListDelegate + 'static,
771 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
772{
773}
774
775impl<D> EventEmitter<DismissEvent> for SelectState<D>
776where
777 D: SearchableListDelegate + 'static,
778 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
779{
780}
781
782impl<D> Focusable for SelectState<D>
783where
784 D: SearchableListDelegate + 'static,
785 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
786{
787 fn focus_handle(&self, cx: &App) -> FocusHandle {
788 if self.state.open {
789 self.state.list.focus_handle(cx)
790 } else {
791 self.state.focus_handle.clone()
792 }
793 }
794}
795
796impl<D> Styled for Select<D>
797where
798 D: SearchableListDelegate + 'static,
799 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
800{
801 fn style(&mut self) -> &mut StyleRefinement {
802 &mut self.options.style
803 }
804}
805
806impl<D> RenderOnce for Select<D>
807where
808 D: SearchableListDelegate + 'static,
809 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
810{
811 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
812 let disabled = self.options.disabled;
813 let accessibility_label = self.options.accessibility_label.clone();
814 let focus_handle = self.state.read(cx).state.focus_handle.clone();
815 let empty = self.empty;
816 let opts = self.options;
817
818 self.state.update(cx, |this, _| {
819 this.state.style = opts.style;
820 this.state.size = opts.size;
821 this.state.cleanable = opts.cleanable;
822 this.state.placeholder = opts.placeholder;
823 this.state.search_placeholder = opts.search_placeholder;
824 this.state.menu_width = opts.menu_width;
825 this.state.menu_max_h = opts.menu_max_h;
826 this.state.disabled = opts.disabled;
827 this.state.appearance = opts.appearance;
828 this.focus_ring_enabled = opts.focus_ring_enabled;
829 this.icon = opts.icon;
830 this.title_prefix = opts.title_prefix;
831
832 if let Some(empty) = empty {
833 this.state.empty = Some(empty);
834 }
835 });
836
837 let is_open = self.state.read(cx).state.open;
838 let accessibility_value = self.state.read(cx).accessibility_value();
839 let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx);
840 let open_state = self.state.clone();
841
842 BaseSelect::new(self.id)
843 .open(is_open)
844 .disabled(disabled)
845 .when_some(accessibility_label, |this, label| {
846 this.accessibility_label(label)
847 })
848 .focus_handle(&focus_handle)
849 .content_focus_handle(&content_focus_handle)
850 .accessibility_value(accessibility_value)
851 .on_open_change(move |open, window, cx| {
852 open_state.update(cx, |state, cx| {
853 if !open {
854 state.clear_query_and_restore_cursor(window, cx);
855 }
856 state.set_open(open, cx);
857 });
858 })
859 .size_full()
860 .child(self.state)
861 }
862}
863
864#[cfg(test)]
867mod tests {
868 use gpui::{AppContext as _, RenderOnce as _, TestAppContext};
869
870 use crate::{
871 IndexPath,
872 searchable_list::{SearchableListDelegate as _, SearchableVec},
873 select::{Select, SelectGroup, SelectState},
874 };
875
876 #[gpui::test]
877 fn an_explicit_accessibility_label_does_not_replace_the_placeholder(cx: &mut TestAppContext) {
878 cx.update(crate::init);
879 let cx = cx.add_empty_window();
880 cx.update(|window, cx| {
881 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
882 let state = cx.new(|cx| SelectState::new(items, None, window, cx));
883
884 let plain = Select::new(&state).placeholder("Choose a language");
885 assert_eq!(plain.options.accessibility_label, None);
886 assert_eq!(
887 plain.options.placeholder.as_deref(),
888 Some("Choose a language")
889 );
890
891 let named = Select::new(&state)
892 .placeholder("Choose a language")
893 .accessibility_label("Programming language");
894 assert_eq!(
895 named.options.accessibility_label.as_deref(),
896 Some("Programming language")
897 );
898 assert_eq!(
899 named.options.placeholder.as_deref(),
900 Some("Choose a language"),
901 "an accessible name must not change what is drawn"
902 );
903 });
904 }
905
906 #[gpui::test]
907 fn test_select_initial_selection_seeds_cursor(cx: &mut TestAppContext) {
908 cx.update(crate::init);
909 let cx = cx.add_empty_window();
910 cx.update(|window, cx| {
911 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
912 let state = cx.new(|cx| SelectState::new(items, Some(IndexPath::new(1)), window, cx));
913
914 assert_eq!(
915 state.read(cx).selected_index(cx),
916 Some(IndexPath::new(1)),
917 "initial cursor should be seeded on ListState so display_title can read it",
918 );
919 assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
920 });
921 }
922
923 #[gpui::test]
924 fn test_select_initial_grouped_selection_seeds_cursor(cx: &mut TestAppContext) {
925 cx.update(crate::init);
926 let cx = cx.add_empty_window();
927 cx.update(|window, cx| {
928 let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
929 groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
930 groups.push(SelectGroup::new("B").items(["Banana", "Blueberry", "Blackberry"]));
931
932 let initial = IndexPath::new(1).section(1);
933 let state = cx.new(|cx| SelectState::new(groups, Some(initial), window, cx));
934
935 assert_eq!(state.read(cx).selected_index(cx), Some(initial));
936 assert_eq!(state.read(cx).selected_value(), Some(&"Blueberry"));
937 });
938 }
939
940 #[gpui::test]
941 fn test_select_set_selected_value_clears_search_query(cx: &mut TestAppContext) {
942 cx.update(crate::init);
943 let cx = cx.add_empty_window();
944 cx.update(|window, cx| {
945 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
946 let state = cx.new(|cx| SelectState::new(items, None, window, cx).searchable(true));
947 let list = state.read(cx).state.list.clone();
948
949 list.update(cx, |list, cx| list.set_query("Rust", window, cx));
950 assert_eq!(list.read(cx).delegate().delegate.items_count(0), 1);
951
952 state.update(cx, |state, cx| {
953 state.set_selected_value(&"Go", window, cx);
954 });
955
956 assert_eq!(state.read(cx).selected_value(), Some(&"Go"));
957 assert_eq!(state.read(cx).selected_index(cx), Some(IndexPath::new(1)));
958 assert_eq!(list.read(cx).query_input.read(cx).value(), "");
959 });
960 }
961
962 #[gpui::test]
963 fn test_select_set_selected_value_clears_grouped_search_query(cx: &mut TestAppContext) {
964 cx.update(crate::init);
965 let cx = cx.add_empty_window();
966 cx.update(|window, cx| {
967 let mut groups: SearchableVec<SelectGroup<&'static str>> = SearchableVec::new(vec![]);
968 groups.push(SelectGroup::new("A").items(["Apple", "Avocado"]));
969 groups.push(SelectGroup::new("B").items(["Banana", "Blueberry"]));
970
971 let state = cx.new(|cx| SelectState::new(groups, None, window, cx).searchable(true));
972 let list = state.read(cx).state.list.clone();
973
974 list.update(cx, |list, cx| list.set_query("Blue", window, cx));
975 state.update(cx, |state, cx| {
976 state.set_selected_value(&"Banana", window, cx);
977 });
978
979 assert_eq!(state.read(cx).selected_value(), Some(&"Banana"));
980 assert_eq!(
981 state.read(cx).selected_index(cx),
982 Some(IndexPath::new(0).section(1)),
983 );
984 });
985 }
986
987 #[gpui::test]
988 fn test_select_accessibility_value_tracks_placeholder_and_selection(cx: &mut TestAppContext) {
989 cx.update(crate::init);
990 let window = cx.add_empty_window();
991 window.update(|window, cx| {
992 let items = SearchableVec::new(vec!["Rust", "Go"]);
993 let state = cx.new(|cx| SelectState::new(items, None, window, cx).searchable(true));
994
995 _ = Select::new(&state)
996 .placeholder("Choose a language")
997 .accessibility_label("Programming language")
998 .render(window, cx);
999 assert_eq!(state.read(cx).accessibility_value(), "Choose a language");
1000
1001 state.update(cx, |state, cx| {
1002 state.set_selected_value(&"Rust", window, cx);
1003 });
1004 assert_eq!(state.read(cx).accessibility_value(), "Rust");
1005
1006 let list = state.read(cx).state.list.clone();
1007 list.update(cx, |list, cx| list.set_query("Go", window, cx));
1008 assert_eq!(list.read(cx).delegate().delegate.items_count(0), 1);
1009 assert_eq!(state.read(cx).accessibility_value(), "Rust");
1011
1012 _ = Select::new(&state)
1013 .placeholder("Choose a language")
1014 .title_prefix("Language: ")
1015 .render(window, cx);
1016 assert_eq!(state.read(cx).accessibility_value(), "Language: Rust");
1017
1018 state.update(cx, |state, cx| state.set_selected_index(None, window, cx));
1019 assert_eq!(state.read(cx).accessibility_value(), "Choose a language");
1020
1021 _ = Select::new(&state).render(window, cx);
1022 assert_eq!(
1023 state.read(cx).accessibility_value(),
1024 rust_i18n::t!("Select.placeholder").to_string(),
1025 );
1026 });
1027 }
1028}