1use gpui::{
2 AnyElement, App, Bounds, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity,
3 EventEmitter, FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length,
4 MouseDownEvent, ParentElement, Pixels, Render, RenderOnce, SharedString,
5 StatefulInteractiveElement, StyleRefinement, Styled, Window, deferred, div,
6 prelude::FluentBuilder, px, rems,
7};
8
9use gpui_base::LogicalStyledExt as _;
10use rust_i18n::t;
11
12pub use crate::select::Caret;
13
14use crate::ThemeStyled as _;
15use crate::{
16 ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size,
17 StyleSized, StyledExt, h_flex,
18 input::{clear_button, input_style},
19 list::{List, ListState},
20 searchable_list::{
21 SearchableListAdapter, SearchableListChange, SearchableListDelegate, SearchableListItem,
22 SearchableListState,
23 state::{MenuSide, menu_popup},
24 },
25 sizing::DROPDOWN_LIST_PADDING,
26 v_flex,
27};
28use gpui_base::{Combobox as BaseCombobox, GlobalState};
29
30pub struct ComboboxTriggerContext<'a, D: SearchableListDelegate + 'static> {
37 selection: &'a [(IndexPath, D::Item)],
38 placeholder: Option<&'a SharedString>,
39 open: bool,
40 disabled: bool,
41 size: Size,
42}
43
44impl<'a, D: SearchableListDelegate + 'static> ComboboxTriggerContext<'a, D> {
45 pub fn selection(&self) -> &'a [(IndexPath, D::Item)] {
47 self.selection
48 }
49
50 pub fn placeholder(&self) -> Option<&'a SharedString> {
51 self.placeholder
52 }
53
54 pub fn is_open(&self) -> bool {
56 self.open
57 }
58
59 pub fn is_disabled(&self) -> bool {
60 self.disabled
61 }
62
63 pub fn size(&self) -> Size {
64 self.size
65 }
66}
67
68pub type ComboboxChange = SearchableListChange;
72
73struct ComboboxOptions {
76 style: StyleRefinement,
77 size: Size,
78 cleanable: bool,
79 placeholder: Option<SharedString>,
80 search_placeholder: Option<SharedString>,
81 highlight_matches: bool,
82 menu_width: Length,
83 menu_max_h: Length,
84 disabled: bool,
85 appearance: bool,
86 focus_ring_enabled: bool,
87 trigger_icon: Option<Icon>,
88 check_icon: Option<Icon>,
89}
90
91impl Default for ComboboxOptions {
92 fn default() -> Self {
93 Self {
94 style: StyleRefinement::default(),
95 size: Size::default(),
96 cleanable: false,
97 placeholder: None,
98 search_placeholder: None,
99 highlight_matches: false,
100 menu_width: Length::Auto,
101 menu_max_h: rems(20.).into(),
102 disabled: false,
103 appearance: true,
104 focus_ring_enabled: true,
105 trigger_icon: None,
106 check_icon: None,
107 }
108 }
109}
110
111pub struct ComboboxState<D: SearchableListDelegate + 'static>
115where
116 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
117{
118 pub(crate) state: SearchableListState<D>,
119
120 multiple: bool,
122 searchable: bool,
123 trigger_icon: Option<Icon>,
124 check_icon: Option<Icon>,
125 render_trigger: Option<
126 Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>,
127 >,
128 footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
129 focus_ring_enabled: bool,
130}
131
132pub enum ComboboxEvent<D: SearchableListDelegate + 'static>
134where
135 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
136{
137 Change(Vec<<D::Item as SearchableListItem>::Value>),
139 Confirm(Vec<<D::Item as SearchableListItem>::Value>),
141}
142
143impl<D> ComboboxState<D>
144where
145 D: SearchableListDelegate + 'static,
146 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
147{
148 pub fn new(
150 delegate: D,
151 selected_indices: Vec<IndexPath>,
152 window: &mut Window,
153 cx: &mut Context<Self>,
154 ) -> Self {
155 let weak = cx.entity().downgrade();
156 let weak_confirm = weak.clone();
157 let weak_cancel = weak.clone();
158 let weak_empty = weak;
159
160 let state = SearchableListState::new(
161 delegate,
162 selected_indices,
163 move |selected_index, _secondary, window, cx| {
164 cx.defer_in(window, {
165 let weak_confirm = weak_confirm.clone();
166 move |list_state, window, cx| {
167 let Some(index) = selected_index else {
168 return;
169 };
170
171 let Some(item) = list_state.delegate().delegate.item(index).cloned() else {
172 return;
173 };
174
175 let ix = index;
176
177 let Some(weak) = weak_confirm.upgrade() else {
178 return;
179 };
180
181 let (multiple, mut selection) = {
182 let s = weak.read(cx);
183 (s.multiple, s.state.selection.clone())
184 };
185
186 let changes = Self::selection_changes(multiple, &selection, ix, &item);
187
188 let before_values: Vec<_> = selection
189 .iter()
190 .map(|(_, item)| item.value().clone())
191 .collect();
192
193 list_state
196 .delegate_mut()
197 .delegate
198 .on_will_change(&mut selection, &changes);
199
200 let after_values: Vec<_> = selection
201 .iter()
202 .map(|(_, item)| item.value().clone())
203 .collect();
204 let changed = before_values != after_values;
205 let should_close = !multiple
206 && (changed
207 || selection
208 .iter()
209 .any(|(_, selected)| selected.value() == item.value()));
210
211 let new_selection = weak_confirm.update(cx, |this, cx| {
212 this.state.selection = selection;
213
214 if changed {
215 cx.emit(ComboboxEvent::Change(this.selected_values()));
216 cx.notify();
217 }
218
219 if should_close {
220 cx.emit(ComboboxEvent::Confirm(this.selected_values()));
221 this.set_open(false, cx);
222 this.focus(window, cx);
223 }
224
225 this.state.selection.clone()
226 });
227
228 if let Ok(new_selection) = new_selection {
230 list_state
231 .delegate_mut()
232 .update_selection_snapshot(new_selection.clone());
233
234 if should_close {
235 list_state
236 .delegate_mut()
237 .delegate
238 .on_confirm(&new_selection);
239 }
240 }
241 }
242 });
243 },
244 move |_final_selected_index, window, cx| {
246 cx.defer_in(window, {
247 let weak_cancel = weak_cancel.clone();
248 move |_list_state, window, cx| {
249 _ = weak_cancel.update(cx, |this, cx| {
250 if !this.state.open {
253 return;
254 }
255 cx.emit(ComboboxEvent::Confirm(this.selected_values()));
256 this.set_open(false, cx);
257 this.focus(window, cx);
258 });
259 }
260 });
261 },
262 move |window, cx| {
264 if let Some(empty) = weak_empty
265 .upgrade()
266 .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx)))
267 {
268 empty
269 } else {
270 h_flex()
271 .flex_row_dir(cx)
272 .justify_center()
273 .py_6()
274 .text_color(cx.theme().muted_foreground.opacity(0.6))
275 .child(Icon::new(IconName::Inbox).size(px(28.)))
276 .into_any_element()
277 }
278 },
279 Self::on_blur,
280 window,
281 cx,
282 );
283
284 Self {
285 state,
286 multiple: false,
287 searchable: false,
288 trigger_icon: None,
289 check_icon: None,
290 render_trigger: None,
291 footer: None,
292 focus_ring_enabled: true,
293 }
294 }
295
296 pub fn multiple(mut self, multiple: bool) -> Self {
301 self.multiple = multiple;
302 self
303 }
304
305 pub fn searchable(mut self, searchable: bool) -> Self {
307 self.searchable = searchable;
308 self
309 }
310
311 pub fn selected_values(&self) -> Vec<<D::Item as SearchableListItem>::Value> {
313 self.state.selected_values()
314 }
315
316 pub fn selected_value(&self) -> Option<<D::Item as SearchableListItem>::Value> {
320 self.state.selected_values().into_iter().next()
321 }
322
323 pub fn selection(&self) -> &[(IndexPath, D::Item)] {
325 self.state.selection()
326 }
327
328 pub fn set_selected_values(
334 &mut self,
335 values: &[<D::Item as SearchableListItem>::Value],
336 window: &mut Window,
337 cx: &mut Context<Self>,
338 ) {
339 self.state.clear_query(window, cx);
340
341 let selected_indices = {
342 let list = self.state.list.read(cx);
343 let delegate = &list.delegate().delegate;
344
345 values
346 .iter()
347 .filter_map(|value| delegate.position(value))
348 .collect::<Vec<_>>()
349 };
350
351 self.set_selected_indices(selected_indices, window, cx);
352 }
353
354 pub fn set_selected_indices(
356 &mut self,
357 indices: impl IntoIterator<Item = IndexPath>,
358 _window: &mut Window,
359 cx: &mut Context<Self>,
360 ) {
361 self.state.set_selected_indices(indices, cx);
362 self.state.sync_snapshot(cx);
363 cx.notify();
364 }
365
366 pub fn add_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool {
368 let added = self.state.add_selected_index(index, cx);
369
370 if added {
371 self.state.sync_snapshot(cx);
372 cx.notify();
373 }
374
375 added
376 }
377
378 pub fn remove_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool {
380 let removed = self.state.remove_selected_index(index);
381
382 if removed {
383 self.state.sync_snapshot(cx);
384 }
385
386 removed
387 }
388
389 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
391 self.state.selection.clear();
392 self.state.sync_snapshot(cx);
393 cx.emit(ComboboxEvent::Change(self.selected_values()));
394 cx.notify();
395 }
396
397 pub fn set_items(&mut self, items: D, _: &mut Window, cx: &mut Context<Self>) {
399 self.state.list.update(cx, |list, _| {
400 list.delegate_mut().delegate = items;
401 });
402 }
403
404 pub fn focus(&self, window: &mut Window, cx: &mut App) {
406 self.state.focus_handle.focus(window, cx);
407 }
408
409 pub fn query(&self, cx: &App) -> SharedString {
411 self.state.list.read(cx).query_input.read(cx).value()
412 }
413
414 pub fn set_query(&self, query: impl Into<SharedString>, window: &mut Window, cx: &mut App) {
416 let query = query.into();
417 self.state.list.update(cx, |list, cx| {
418 list.set_query(query.as_ref(), window, cx);
419 });
420 }
421
422 fn selection_changes(
423 multiple: bool,
424 selection: &[(IndexPath, D::Item)],
425 ix: IndexPath,
426 item: &D::Item,
427 ) -> Vec<SearchableListChange> {
428 let is_selected = selection
429 .iter()
430 .any(|(_, selected_item)| selected_item.value() == item.value());
431
432 if multiple {
433 if is_selected {
434 vec![SearchableListChange::Deselect { index: ix }]
435 } else {
436 vec![SearchableListChange::Select { index: ix }]
437 }
438 } else {
439 let mut changes: Vec<SearchableListChange> = selection
440 .iter()
441 .map(|(cur_ix, _)| SearchableListChange::Deselect { index: *cur_ix })
442 .collect();
443 changes.push(SearchableListChange::Select { index: ix });
444 changes
445 }
446 }
447
448 #[allow(dead_code)]
452 pub(crate) fn handle_item_select(
453 &mut self,
454 ix: IndexPath,
455 window: &mut Window,
456 cx: &mut Context<Self>,
457 ) {
458 let Some(item) = self
459 .state
460 .list
461 .read(cx)
462 .delegate()
463 .delegate
464 .item(ix)
465 .cloned()
466 else {
467 return;
468 };
469
470 let changes = Self::selection_changes(self.multiple, &self.state.selection, ix, &item);
471
472 let mut selection = self.state.selection.clone();
473 let before_values: Vec<_> = selection
474 .iter()
475 .map(|(_, item)| item.value().clone())
476 .collect();
477
478 self.state.list.update(cx, |list, _cx| {
479 list.delegate_mut()
480 .delegate
481 .on_will_change(&mut selection, &changes);
482 });
483
484 let after_values: Vec<_> = selection
485 .iter()
486 .map(|(_, item)| item.value().clone())
487 .collect();
488 let changed = before_values != after_values;
489 let should_close = !self.multiple
490 && (changed
491 || selection
492 .iter()
493 .any(|(_, selected)| selected.value() == item.value()));
494
495 self.state.selection = selection;
496 self.state.sync_snapshot(cx);
497
498 if changed {
499 cx.emit(ComboboxEvent::Change(self.selected_values()));
500 cx.notify();
501 }
502
503 if should_close {
504 let final_selection = self.state.selection.clone();
505 self.state.list.update(cx, |list, _cx| {
506 list.delegate_mut().delegate.on_confirm(&final_selection);
507 });
508
509 cx.emit(ComboboxEvent::Confirm(self.selected_values()));
510 self.set_open(false, cx);
511 self.focus(window, cx);
512 }
513 }
514
515 fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
516 if self.state.list.read(cx).is_focused(window, cx)
517 || self.state.focus_handle.is_focused(window)
518 {
519 return;
520 }
521
522 self.set_open(false, cx);
523 cx.notify();
524 }
525
526 fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
527 cx.stop_propagation();
528
529 self.set_open(!self.state.open, cx);
530
531 if self.state.open {
532 self.state.list.focus_handle(cx).focus(window, cx);
533 } else {
534 cx.emit(ComboboxEvent::Confirm(self.selected_values()));
535 self.focus(window, cx);
536 }
537
538 cx.notify();
539 }
540
541 fn dismiss(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
547 if !self.state.open || self.state.bounds.contains(&event.position) {
548 return;
549 }
550
551 cx.stop_propagation();
552 cx.emit(ComboboxEvent::Confirm(self.selected_values()));
553
554 self.set_open(false, cx);
555 self.focus(window, cx);
556 cx.notify();
557 }
558
559 fn set_open(&mut self, open: bool, cx: &mut Context<Self>) {
560 if self.state.open && !open {
561 self.state.menu_side.reset();
562 let list = self.state.list.downgrade();
564 cx.defer(move |cx| {
565 _ = list.update(cx, |list, _| list.reset_held_items_height());
566 });
567 }
568 self.state.open = open;
569 self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx));
570
571 cx.notify();
572 }
573
574 fn clean(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) {
575 cx.stop_propagation();
576 self.clear_selection(cx);
577 }
578
579 fn default_trigger_body(&self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
580 let placeholder_text = self
581 .state
582 .placeholder
583 .clone()
584 .unwrap_or_else(|| t!("Combobox.placeholder").into());
585
586 if self.state.selection.is_empty() {
587 return div()
588 .text_color(cx.theme().muted_foreground)
589 .child(placeholder_text)
590 .into_any_element();
591 }
592
593 if self.multiple {
594 let items: Vec<SharedString> = self
595 .state
596 .selection
597 .iter()
598 .map(|(_, i)| i.title())
599 .collect();
600
601 div()
602 .w_full()
603 .overflow_hidden()
604 .whitespace_nowrap()
605 .truncate()
606 .child(items.join(", "))
607 .into_any_element()
608 } else {
609 let title = self
610 .state
611 .selection
612 .first()
613 .map(|(_, i)| i.title())
614 .unwrap_or_default();
615
616 div()
617 .w_full()
618 .overflow_hidden()
619 .whitespace_nowrap()
620 .truncate()
621 .child(title)
622 .into_any_element()
623 }
624 }
625}
626
627impl<D> Render for ComboboxState<D>
628where
629 D: SearchableListDelegate + 'static,
630 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
631{
632 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
633 let searchable = self.searchable;
634 let is_focused = self.state.focus_handle.is_focused(window);
635 let show_clean = self.state.cleanable && !self.state.selection.is_empty();
636 let bounds = self.state.bounds;
637 let allow_open = !self.state.disabled;
638 let outline_visible = self.state.open || (is_focused && !self.state.disabled);
639 let disabled = self.state.disabled;
640
641 let (bg, fg) = input_style(disabled, cx);
642
643 self.state.list.update(cx, |list, cx| {
644 list.set_searchable(searchable, cx);
645 list.delegate_mut().size = self.state.size;
646 list.delegate_mut().highlight_matches = self.state.highlight_matches;
647 list.delegate_mut().check_icon = self.check_icon.clone();
648 });
649
650 let selection = &self.state.selection;
651 let placeholder = self.state.placeholder.as_ref();
652 let open = self.state.open;
653 let size = self.state.size;
654 let has_custom_trigger = self.render_trigger.is_some();
655
656 let trigger_body = if let Some(render_trigger) = &self.render_trigger {
657 let trigger = ComboboxTriggerContext {
658 selection,
659 placeholder,
660 open,
661 disabled,
662 size,
663 };
664
665 render_trigger(&trigger, window, cx)
666 } else {
667 self.default_trigger_body(window, cx)
668 };
669
670 let trailing: AnyElement = if has_custom_trigger {
671 div().into_any_element()
672 } else if show_clean {
673 clear_button(cx)
674 .map(|this| {
675 if disabled {
676 this.disabled(true)
677 } else {
678 this.on_click(cx.listener(Self::clean))
679 }
680 })
681 .into_any_element()
682 } else if let Some(icon) = self.trigger_icon.clone() {
683 icon.xsmall()
684 .text_color(cx.theme().muted_foreground)
685 .into_any_element()
686 } else {
687 Caret::new(size)
688 .text_color(cx.theme().muted_foreground)
689 .into_any_element()
690 };
691
692 let toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>> =
693 if allow_open {
694 Some(Box::new(cx.listener(Self::toggle_menu)))
695 } else {
696 None
697 };
698
699 let footer_el = self.footer.as_ref().map(|f| f(window, cx));
700
701 let dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static> =
702 Box::new(cx.listener(Self::dismiss));
703
704 div().size_full().relative().child(
705 div()
706 .relative()
707 .on_prepaint({
708 let state = cx.entity();
709 move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds)
710 })
711 .child(render_trigger_container(
712 disabled,
713 self.state.appearance,
714 self.focus_ring_enabled,
715 self.state.size,
716 &self.state.style,
717 bg,
718 fg,
719 outline_visible,
720 allow_open,
721 trigger_body,
722 trailing,
723 toggle_handler,
724 window,
725 cx,
726 ))
727 .when(self.state.open, |this| {
728 this.child(
729 deferred(render_popup_shell(
730 ("combobox-popup", cx.entity_id()),
731 &self.state.list,
732 self.state.menu_width,
733 self.state.search_placeholder.clone(),
734 self.state.size,
735 self.state.menu_max_h,
736 &self.state.menu_side,
737 bounds,
738 footer_el,
739 dismiss_handler,
740 cx,
741 ))
742 .with_priority(gpui_base::POPUP_PRIORITY),
743 )
744 }),
745 )
746 }
747}
748
749impl<D> EventEmitter<ComboboxEvent<D>> for ComboboxState<D>
750where
751 D: SearchableListDelegate + 'static,
752 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
753{
754}
755impl<D> EventEmitter<DismissEvent> for ComboboxState<D>
756where
757 D: SearchableListDelegate + 'static,
758 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
759{
760}
761
762impl<D> Focusable for ComboboxState<D>
763where
764 D: SearchableListDelegate + 'static,
765 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
766{
767 fn focus_handle(&self, cx: &App) -> FocusHandle {
768 if self.state.open {
769 self.state.list.focus_handle(cx)
770 } else {
771 self.state.focus_handle.clone()
772 }
773 }
774}
775
776#[derive(IntoElement)]
783pub struct Combobox<D: SearchableListDelegate + 'static>
784where
785 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
786{
787 id: ElementId,
788 state: Entity<ComboboxState<D>>,
789 options: ComboboxOptions,
790 render_trigger: Option<
791 Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>,
792 >,
793 footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
794 empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
795}
796
797impl<D> Combobox<D>
798where
799 D: SearchableListDelegate + 'static,
800 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
801{
802 pub fn new(state: &Entity<ComboboxState<D>>) -> Self {
803 Self {
804 id: ("multi-combo-box", state.entity_id()).into(),
805 state: state.clone(),
806 options: ComboboxOptions::default(),
807 render_trigger: None,
808 footer: None,
809 empty: None,
810 }
811 }
812
813 pub fn menu_width(mut self, width: impl Into<Length>) -> Self {
815 self.options.menu_width = width.into();
816 self
817 }
818
819 pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self {
821 self.options.menu_max_h = max_h.into();
822 self
823 }
824
825 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
827 self.options.placeholder = Some(placeholder.into());
828 self
829 }
830
831 pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
833 self.options.trigger_icon = Some(icon.into());
834 self
835 }
836
837 pub fn check_icon(mut self, icon: impl Into<Icon>) -> Self {
839 self.options.check_icon = Some(icon.into());
840 self
841 }
842
843 pub fn highlight_matches(mut self, highlight: bool) -> Self {
849 self.options.highlight_matches = highlight;
850 self
851 }
852
853 pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
855 self.options.search_placeholder = Some(placeholder.into());
856 self
857 }
858
859 pub fn cleanable(mut self, cleanable: bool) -> Self {
861 self.options.cleanable = cleanable;
862 self
863 }
864
865 pub fn disabled(mut self, disabled: bool) -> Self {
867 self.options.disabled = disabled;
868 self
869 }
870
871 pub fn empty<E: IntoElement + 'static>(
873 mut self,
874 builder: impl Fn(&mut Window, &App) -> E + 'static,
875 ) -> Self {
876 self.empty = Some(Box::new(move |window, cx| {
877 builder(window, cx).into_any_element()
878 }));
879 self
880 }
881
882 pub fn appearance(mut self, appearance: bool) -> Self {
884 self.options.appearance = appearance;
885 self
886 }
887
888 pub fn render_trigger<E: IntoElement + 'static>(
890 mut self,
891 f: impl Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> E + 'static,
892 ) -> Self {
893 self.render_trigger = Some(Box::new(move |trigger, window, cx| {
894 f(trigger, window, cx).into_any_element()
895 }));
896 self
897 }
898
899 pub fn footer<E: IntoElement + 'static>(
901 mut self,
902 f: impl Fn(&mut Window, &mut App) -> E + 'static,
903 ) -> Self {
904 self.footer = Some(Box::new(move |window, cx| f(window, cx).into_any_element()));
905 self
906 }
907}
908
909impl<D> Sizable for Combobox<D>
910where
911 D: SearchableListDelegate + 'static,
912 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
913{
914 fn with_size(mut self, size: impl Into<Size>) -> Self {
915 self.options.size = size.into();
916 self
917 }
918}
919
920impl<D> crate::FocusableExt for Combobox<D>
921where
922 D: SearchableListDelegate + 'static,
923 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
924{
925 fn focus_ring(mut self, enabled: bool) -> Self {
926 self.options.focus_ring_enabled = enabled;
927 self
928 }
929
930 fn is_focus_ring_enabled(&self) -> bool {
931 self.options.focus_ring_enabled
932 }
933}
934
935impl<D> Styled for Combobox<D>
936where
937 D: SearchableListDelegate + 'static,
938 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
939{
940 fn style(&mut self) -> &mut StyleRefinement {
941 &mut self.options.style
942 }
943}
944
945impl<D> RenderOnce for Combobox<D>
946where
947 D: SearchableListDelegate + 'static,
948 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
949{
950 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
951 let disabled = self.options.disabled;
952 let focus_handle = self.state.read(cx).state.focus_handle.clone();
953 let render_trigger = self.render_trigger;
954 let footer = self.footer;
955 let empty = self.empty;
956 let opts = self.options;
957
958 self.state.update(cx, |this, _| {
959 this.state.style = opts.style;
960 this.state.size = opts.size;
961 this.state.cleanable = opts.cleanable;
962 this.state.placeholder = opts.placeholder;
963 this.state.search_placeholder = opts.search_placeholder;
964 this.state.highlight_matches = opts.highlight_matches;
965 this.state.menu_width = opts.menu_width;
966 this.state.menu_max_h = opts.menu_max_h;
967 this.state.disabled = opts.disabled;
968 this.state.appearance = opts.appearance;
969 this.focus_ring_enabled = opts.focus_ring_enabled;
970 this.trigger_icon = opts.trigger_icon;
971 this.check_icon = opts.check_icon;
972 this.render_trigger = render_trigger;
973 this.footer = footer;
974
975 if let Some(empty) = empty {
976 this.state.empty = Some(empty);
977 }
978 });
979
980 let is_open = self.state.read(cx).state.open;
981 let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx);
982 let open_state = self.state.clone();
983 let confirm_state = self.state.clone();
984
985 BaseCombobox::new(self.id)
986 .open(is_open)
987 .disabled(disabled)
988 .focus_handle(&focus_handle)
989 .content_focus_handle(&content_focus_handle)
990 .on_open_change(move |open, _, cx| {
991 open_state.update(cx, |state, cx| state.set_open(open, cx));
992 })
993 .on_dismiss(move |_, cx| {
996 confirm_state.update(cx, |state, cx| {
997 cx.emit(ComboboxEvent::Confirm(state.selected_values()));
998 });
999 })
1000 .size_full()
1001 .child(self.state)
1002 }
1003}
1004
1005#[allow(clippy::too_many_arguments)]
1009fn render_trigger_container(
1010 disabled: bool,
1011 appearance: bool,
1012 focus_ring_enabled: bool,
1013 size: Size,
1014 style: &StyleRefinement,
1015 bg: Hsla,
1016 fg: Hsla,
1017 outline_visible: bool,
1018 allow_open: bool,
1019 trigger_body: AnyElement,
1020 trailing: AnyElement,
1021 toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
1022 window: &Window,
1023 cx: &mut App,
1024) -> impl IntoElement {
1025 div()
1026 .id("input")
1027 .relative()
1028 .flex()
1029 .items_center()
1030 .justify_between()
1031 .border_1()
1032 .border_color(cx.theme().transparent)
1033 .when(appearance, |this| {
1034 this.bg(bg)
1035 .text_color(fg)
1036 .when(disabled, |this| this.opacity(0.5))
1037 .border_color(cx.theme().input)
1038 .rounded(cx.theme().radius)
1039 })
1040 .input_size(size)
1041 .input_text_size(size)
1042 .refine_style(style)
1043 .when(outline_visible && appearance, |this| {
1044 this.border_1().border_color(cx.theme().ring)
1045 })
1046 .when(
1047 outline_visible && appearance && focus_ring_enabled,
1048 |this| this.focus_ring_style(window, cx),
1049 )
1050 .when(allow_open, |this| {
1051 this.when_some(toggle_handler, |this, handler| this.on_click(handler))
1052 })
1053 .child(
1054 h_flex()
1055 .flex_row_dir(cx)
1056 .id("inner")
1057 .w_full()
1058 .min_w_0()
1059 .overflow_hidden()
1060 .whitespace_nowrap()
1061 .items_center()
1062 .justify_between()
1063 .gap_1()
1064 .child(
1065 div()
1066 .flex_1()
1067 .min_w_0()
1068 .overflow_hidden()
1069 .whitespace_nowrap()
1070 .child(trigger_body),
1071 )
1072 .child(trailing),
1073 )
1074}
1075
1076#[allow(clippy::too_many_arguments)]
1078fn render_popup_shell<D: SearchableListDelegate + 'static>(
1079 id: impl Into<ElementId>,
1080 list: &Entity<ListState<SearchableListAdapter<D>>>,
1081 menu_width: Length,
1082 search_placeholder: Option<SharedString>,
1083 size: Size,
1084 menu_max_h: Length,
1085 menu_side: &MenuSide,
1086 bounds: Bounds<Pixels>,
1087 footer_el: Option<AnyElement>,
1088 dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static>,
1089 cx: &mut App,
1090) -> AnyElement {
1091 let has_footer = footer_el.is_some();
1092
1093 menu_popup(
1094 menu_side,
1095 id,
1096 bounds,
1097 v_flex()
1098 .occlude()
1099 .map(|this| match menu_width {
1100 Length::Auto => this.w(bounds.size.width),
1101 Length::Definite(w) => this.w(w),
1102 })
1103 .popover_style(cx)
1104 .child(
1105 List::new(list)
1106 .when_some(search_placeholder, |this, placeholder| {
1107 this.search_placeholder(placeholder)
1108 })
1109 .with_size(size)
1110 .max_h(menu_max_h)
1111 .hold_items_height(menu_side.is_above())
1112 .paddings(Edges::all(DROPDOWN_LIST_PADDING)),
1113 )
1114 .when(has_footer, |this| {
1115 this.child(
1116 div()
1117 .border_t_1()
1118 .border_color(cx.theme().border)
1119 .p_1()
1120 .when_some(footer_el, |this, el| this.child(el)),
1121 )
1122 })
1123 .on_mouse_down_out(dismiss_handler),
1124 cx,
1125 )
1126 .into_any_element()
1127}
1128
1129#[cfg(test)]
1132mod tests {
1133 use std::{cell::Cell, rc::Rc};
1134
1135 use gpui::{
1136 AppContext as _, Bounds, Context, Entity, Modifiers, MouseButton, MouseDownEvent, Pixels,
1137 Point, Subscription, TestAppContext, point, px, size,
1138 };
1139
1140 use crate::{
1141 IndexPath,
1142 combobox::{Combobox, ComboboxEvent, ComboboxState},
1143 searchable_list::{
1144 SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState,
1145 SearchableVec,
1146 },
1147 };
1148
1149 struct TestComboboxEventCollector {
1150 event_count: Rc<Cell<usize>>,
1151 _subscription: Subscription,
1152 }
1153
1154 impl TestComboboxEventCollector {
1155 fn new(
1156 state: &Entity<ComboboxState<SearchableVec<&'static str>>>,
1157 cx: &mut Context<Self>,
1158 ) -> Self {
1159 let event_count = Rc::new(Cell::new(0));
1160 let event_count_for_subscription = event_count.clone();
1161 let _subscription = cx.subscribe(
1162 state,
1163 move |_, _, _: &ComboboxEvent<SearchableVec<&'static str>>, _| {
1164 event_count_for_subscription.set(event_count_for_subscription.get() + 1);
1165 },
1166 );
1167
1168 Self {
1169 event_count,
1170 _subscription,
1171 }
1172 }
1173 }
1174
1175 #[gpui::test]
1176 fn test_combo_box_builder(cx: &mut TestAppContext) {
1177 cx.update(crate::init);
1178 let cx = cx.add_empty_window();
1179 cx.update(|window, cx| {
1180 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1181 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1182
1183 let _cb = Combobox::new(&state)
1184 .placeholder("Select language")
1185 .search_placeholder("Search...")
1186 .menu_width(gpui::px(300.))
1187 .menu_max_h(gpui::rems(15.))
1188 .cleanable(true)
1189 .disabled(false)
1190 .appearance(true);
1191 });
1192 }
1193
1194 #[gpui::test]
1195 fn test_combo_box_search_filters_items(cx: &mut TestAppContext) {
1196 cx.update(crate::init);
1197 let cx = cx.add_empty_window();
1198 cx.update(|window, cx| {
1199 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1200 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1201
1202 let count_before = state
1203 .read(cx)
1204 .state
1205 .list
1206 .read(cx)
1207 .delegate()
1208 .delegate
1209 .items_count(0);
1210 assert_eq!(count_before, 3);
1211
1212 state.update(cx, |s, cx| {
1213 s.state.list.update(cx, |list, cx| {
1214 let _ = list
1215 .delegate_mut()
1216 .delegate
1217 .perform_search("Rust", window, cx);
1218 });
1219 });
1220
1221 let count_after = state
1222 .read(cx)
1223 .state
1224 .list
1225 .read(cx)
1226 .delegate()
1227 .delegate
1228 .items_count(0);
1229 assert_eq!(count_after, 1);
1230 });
1231 }
1232
1233 #[gpui::test]
1234 fn test_combo_box_set_query_updates_text_and_filters_items(cx: &mut TestAppContext) {
1235 cx.update(crate::init);
1236 let cx = cx.add_empty_window();
1237 cx.update(|window, cx| {
1238 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1239 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true));
1240
1241 state.update(cx, |state, cx| state.set_query(" Rust ", window, cx));
1242
1243 assert_eq!(state.read(cx).query(cx).as_ref(), " Rust ");
1244 assert_eq!(
1245 state
1246 .read(cx)
1247 .state
1248 .list
1249 .read(cx)
1250 .delegate()
1251 .delegate
1252 .items_count(0),
1253 1,
1254 );
1255 });
1256 }
1257
1258 #[gpui::test]
1259 fn test_multi_combo_box_builder(cx: &mut TestAppContext) {
1260 cx.update(crate::init);
1261 let cx = cx.add_empty_window();
1262 cx.update(|window, cx| {
1263 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1264 let state = cx.new(|cx| {
1265 ComboboxState::new(items, vec![IndexPath::new(0)], window, cx)
1266 .multiple(true)
1267 .searchable(true)
1268 });
1269
1270 let _cb = Combobox::new(&state)
1271 .placeholder("Select frameworks")
1272 .search_placeholder("Search...")
1273 .menu_width(gpui::px(300.))
1274 .cleanable(true)
1275 .disabled(false);
1276
1277 assert_eq!(state.read(cx).selected_values(), vec!["React"]);
1278 });
1279 }
1280
1281 #[gpui::test]
1282 fn test_combo_box_set_selected_values_uses_current_delegate(cx: &mut TestAppContext) {
1283 cx.update(crate::init);
1284 let cx = cx.add_empty_window();
1285 cx.update(|window, cx| {
1286 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1287 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1288
1289 state.update(cx, |state, cx| {
1290 state.set_selected_values(&["Vue", "Missing"], window, cx);
1291
1292 assert_eq!(state.selected_values(), vec!["Vue"]);
1293 assert_eq!(
1294 state
1295 .selection()
1296 .iter()
1297 .map(|(index, _)| *index)
1298 .collect::<Vec<_>>(),
1299 vec![IndexPath::new(1)],
1300 );
1301 assert_eq!(
1302 state
1303 .state
1304 .list
1305 .read(cx)
1306 .delegate()
1307 .selection_snapshot
1308 .as_slice(),
1309 state.selection(),
1310 );
1311
1312 state.set_items(SearchableVec::new(vec!["Vue", "Rust", "Go"]), window, cx);
1313 state.set_selected_values(&["Go", "Vue"], window, cx);
1314
1315 assert_eq!(state.selected_values(), vec!["Go", "Vue"]);
1316 assert_eq!(
1317 state
1318 .selection()
1319 .iter()
1320 .map(|(index, _)| *index)
1321 .collect::<Vec<_>>(),
1322 vec![IndexPath::new(2), IndexPath::new(0)],
1323 );
1324 assert_eq!(
1325 state
1326 .state
1327 .list
1328 .read(cx)
1329 .delegate()
1330 .selection_snapshot
1331 .as_slice(),
1332 state.selection(),
1333 );
1334
1335 state.set_selected_values(&[], window, cx);
1336
1337 assert!(state.selection().is_empty());
1338 assert!(
1339 state
1340 .state
1341 .list
1342 .read(cx)
1343 .delegate()
1344 .selection_snapshot
1345 .is_empty()
1346 );
1347 });
1348 });
1349 }
1350
1351 #[gpui::test]
1354 fn test_combo_box_set_selected_values_keeps_values_hidden_by_the_search(
1355 cx: &mut TestAppContext,
1356 ) {
1357 cx.update(crate::init);
1358 let cx = cx.add_empty_window();
1359 cx.update(|window, cx| {
1360 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1361 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1362
1363 state.update(cx, |state, cx| {
1364 state.set_selected_values(&["React", "Vue"], window, cx);
1365 state.state.list.update(cx, |list, cx| {
1366 list.set_query("Angular", window, cx);
1367 });
1368
1369 state.set_selected_values(&["React", "Vue", "Angular"], window, cx);
1370
1371 assert_eq!(
1372 state.selected_values(),
1373 vec!["React", "Vue", "Angular"],
1374 "a value the search had hidden must survive being reapplied"
1375 );
1376 assert_eq!(
1377 state
1378 .selection()
1379 .iter()
1380 .map(|(index, _)| *index)
1381 .collect::<Vec<_>>(),
1382 vec![IndexPath::new(0), IndexPath::new(1), IndexPath::new(2)],
1383 "clearing the query puts every selected item back in view"
1384 );
1385 });
1386 });
1387 }
1388
1389 #[gpui::test]
1390 fn test_combo_box_set_selected_values_does_not_emit_events(cx: &mut TestAppContext) {
1391 cx.update(crate::init);
1392 let cx = cx.add_empty_window();
1393 let state = cx.update(|window, cx| {
1394 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1395 cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true))
1396 });
1397 let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1398
1399 cx.update(|window, cx| {
1400 state.update(cx, |state, cx| {
1401 state.set_selected_values(&["React", "Vue"], window, cx);
1402 });
1403 });
1404
1405 cx.update(|_, cx| {
1406 assert_eq!(collector.read(cx).event_count.get(), 0);
1407 });
1408 }
1409
1410 #[gpui::test]
1411 fn test_combo_box_initial_selection_seeds_cursor(cx: &mut TestAppContext) {
1412 cx.update(crate::init);
1413 let cx = cx.add_empty_window();
1414 cx.update(|window, cx| {
1415 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1416 let state = cx.new(|cx| {
1417 ComboboxState::new(items, vec![IndexPath::new(1)], window, cx).multiple(true)
1418 });
1419
1420 let state_ref = state.read(cx);
1421 assert_eq!(
1422 state_ref.state.list.read(cx).selected_index(),
1423 Some(IndexPath::new(1)),
1424 "initial selected_indices should seed ListState.selected_index, not just the snapshot",
1425 );
1426 assert_eq!(state_ref.selected_values(), vec!["Vue"]);
1427 });
1428 }
1429
1430 #[gpui::test]
1431 fn test_multi_combo_box_toggle(cx: &mut TestAppContext) {
1432 cx.update(crate::init);
1433 let cx = cx.add_empty_window();
1434 cx.update(|window, cx| {
1435 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1436 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1437
1438 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1439 assert_eq!(state.read(cx).selected_values(), &["React"]);
1440
1441 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx));
1442 assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]);
1443
1444 state.update(cx, |s, cx| s.remove_selected_index(IndexPath::new(0), cx));
1445 assert_eq!(state.read(cx).selected_values(), &["Vue"]);
1446 });
1447 }
1448
1449 #[gpui::test]
1450 fn test_multi_combo_box_search_selection_uses_value_identity(cx: &mut TestAppContext) {
1451 cx.update(crate::init);
1452 let cx = cx.add_empty_window();
1453 cx.update(|window, cx| {
1454 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1455 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1456
1457 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1458 assert_eq!(state.read(cx).selected_values(), &["React"]);
1459
1460 state.update(cx, |s, cx| {
1461 s.state.list.update(cx, |list, cx| {
1462 let _ = list
1463 .delegate_mut()
1464 .delegate
1465 .perform_search("Vue", window, cx);
1466 });
1467 });
1468
1469 state.read_with(cx, |s, cx| {
1470 let selection = s.state.selection.clone();
1471 let list = s.state.list.read(cx);
1472 let delegate = &list.delegate().delegate;
1473 let ix = IndexPath::new(0);
1474 let item = delegate.item(ix).expect("filtered item exists");
1475
1476 assert_eq!(item.value(), &"Vue");
1477 assert!(
1478 !delegate.is_item_checked(ix, item, &selection, cx),
1479 "filtered row 0 should not inherit React's checked state",
1480 );
1481 });
1482
1483 state.update(cx, |s, cx| {
1484 s.handle_item_select(IndexPath::new(0), window, cx);
1485 });
1486 assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]);
1487 });
1488 }
1489
1490 #[gpui::test]
1491 fn test_multi_combo_box_search_deselects_by_value(cx: &mut TestAppContext) {
1492 cx.update(crate::init);
1493 let cx = cx.add_empty_window();
1494 cx.update(|window, cx| {
1495 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1496 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true));
1497
1498 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1499
1500 state.update(cx, |s, cx| {
1501 s.state.list.update(cx, |list, cx| {
1502 let _ = list
1503 .delegate_mut()
1504 .delegate
1505 .perform_search("React", window, cx);
1506 });
1507 });
1508
1509 state.update(cx, |s, cx| {
1510 s.handle_item_select(IndexPath::new(0), window, cx);
1511 });
1512 assert!(state.read(cx).selected_values().is_empty());
1513 });
1514 }
1515
1516 #[gpui::test]
1517 fn test_searchable_list_default_change_uses_value_identity(cx: &mut TestAppContext) {
1518 cx.update(crate::init);
1519 let cx = cx.add_empty_window();
1520 cx.update(|window, cx| {
1521 let mut delegate = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1522 let mut selection = vec![(IndexPath::new(1), "Vue")];
1523
1524 let _ = delegate.perform_search("Vue", window, cx);
1525 delegate.on_will_change(
1526 &mut selection,
1527 &[SearchableListChange::Deselect {
1528 index: IndexPath::new(0),
1529 }],
1530 );
1531 assert!(selection.is_empty());
1532
1533 delegate.on_will_change(
1534 &mut selection,
1535 &[SearchableListChange::Select {
1536 index: IndexPath::new(0),
1537 }],
1538 );
1539 assert_eq!(selection, vec![(IndexPath::new(0), "Vue")]);
1540 });
1541 }
1542
1543 #[gpui::test]
1544 fn test_multi_combo_box_clear(cx: &mut TestAppContext) {
1545 cx.update(crate::init);
1546 let cx = cx.add_empty_window();
1547 cx.update(|window, cx| {
1548 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1549 let state = cx.new(|cx| {
1550 ComboboxState::new(
1551 items,
1552 vec![IndexPath::new(0), IndexPath::new(1)],
1553 window,
1554 cx,
1555 )
1556 .multiple(true)
1557 });
1558
1559 assert_eq!(state.read(cx).selected_values().len(), 2);
1560 state.update(cx, |s, cx| s.clear_selection(cx));
1561 assert!(state.read(cx).selected_values().is_empty());
1562 });
1563 }
1564
1565 #[gpui::test]
1566 fn test_single_combo_box_mode(cx: &mut TestAppContext) {
1567 cx.update(crate::init);
1568 let cx = cx.add_empty_window();
1569 cx.update(|window, cx| {
1570 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1571 let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx));
1572
1573 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1575 assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1576
1577 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx));
1578 assert_eq!(state.read(cx).selected_values(), &["Rust", "Go"]);
1579 });
1580 }
1581
1582 struct VetoDelegate(SearchableVec<&'static str>);
1584
1585 impl SearchableListDelegate for VetoDelegate {
1586 type Item = &'static str;
1587
1588 fn items_count(&self, section: usize) -> usize {
1589 self.0.items_count(section)
1590 }
1591
1592 fn item(&self, ix: IndexPath) -> Option<&&'static str> {
1593 self.0.item(ix)
1594 }
1595
1596 fn position<V>(&self, value: &V) -> Option<IndexPath>
1597 where
1598 &'static str: SearchableListItem<Value = V>,
1599 V: PartialEq,
1600 {
1601 self.0.position(value)
1602 }
1603
1604 fn on_will_change(
1605 &mut self,
1606 _selection: &mut Vec<(IndexPath, &'static str)>,
1607 _changes: &[SearchableListChange],
1608 ) {
1609 }
1611 }
1612
1613 #[gpui::test]
1614 fn test_on_will_change_veto(cx: &mut TestAppContext) {
1615 cx.update(crate::init);
1616 let cx = cx.add_empty_window();
1617 cx.update(|window, cx| {
1618 let delegate = VetoDelegate(SearchableVec::new(vec!["Rust", "Go", "C++"]));
1619 let state = cx.new(|cx| ComboboxState::new(delegate, vec![], window, cx));
1620
1621 state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx));
1623 assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1624
1625 state.update(cx, |s, cx| {
1627 s.handle_item_select(IndexPath::new(1), window, cx);
1628 });
1629
1630 assert_eq!(state.read(cx).selected_values(), &["Rust"]);
1632 });
1633 }
1634
1635 struct RedirectDelegate {
1636 items: SearchableVec<&'static str>,
1637 confirmations: Rc<Cell<usize>>,
1638 }
1639
1640 impl SearchableListDelegate for RedirectDelegate {
1641 type Item = &'static str;
1642
1643 fn items_count(&self, section: usize) -> usize {
1644 self.items.items_count(section)
1645 }
1646
1647 fn item(&self, ix: IndexPath) -> Option<&&'static str> {
1648 self.items.item(ix)
1649 }
1650
1651 fn position<V>(&self, value: &V) -> Option<IndexPath>
1652 where
1653 &'static str: SearchableListItem<Value = V>,
1654 V: PartialEq,
1655 {
1656 self.items.position(value)
1657 }
1658
1659 fn on_will_change(
1660 &mut self,
1661 selection: &mut Vec<(IndexPath, &'static str)>,
1662 _: &[SearchableListChange],
1663 ) {
1664 *selection = vec![(IndexPath::new(2), "C++")];
1665 }
1666
1667 fn on_confirm(&mut self, selection: &[(IndexPath, &'static str)]) {
1668 assert_eq!(selection[0].1, "C++");
1669 self.confirmations.set(self.confirmations.get() + 1);
1670 }
1671 }
1672
1673 #[gpui::test]
1674 fn single_select_confirms_delegate_replacement(cx: &mut TestAppContext) {
1675 use crate::list::ListDelegate as _;
1676 cx.update(crate::init);
1677 let cx = cx.add_empty_window();
1678 for through_list in [false, true] {
1679 let confirmations = Rc::new(Cell::new(0));
1680 let state = cx.update(|window, cx| {
1681 cx.new(|cx| {
1682 ComboboxState::new(
1683 RedirectDelegate {
1684 items: SearchableVec::new(vec!["Rust", "Go", "C++"]),
1685 confirmations: confirmations.clone(),
1686 },
1687 vec![IndexPath::new(0)],
1688 window,
1689 cx,
1690 )
1691 })
1692 });
1693 let events = Rc::new(Cell::new(0));
1694 let event_count = events.clone();
1695 let _subscription = cx.update(|_, cx| {
1696 cx.subscribe(&state, move |_, _: &ComboboxEvent<RedirectDelegate>, _| {
1697 event_count.set(event_count.get() + 1);
1698 })
1699 });
1700 cx.update(|window, cx| {
1701 state.update(cx, |state, cx| {
1702 state.set_open(true, cx);
1703 if through_list {
1704 state.state.list.update(cx, |list, cx| {
1705 list.set_selected_index(Some(IndexPath::new(1)), window, cx);
1706 list.delegate_mut().confirm(false, window, cx);
1707 });
1708 } else {
1709 state.handle_item_select(IndexPath::new(1), window, cx);
1710 }
1711 });
1712 });
1713 cx.run_until_parked();
1714 cx.update(|_, cx| {
1715 assert_eq!(state.read(cx).selected_values(), vec!["C++"]);
1716 assert!(!state.read(cx).state.open);
1717 assert_eq!(confirmations.get(), 1);
1718 assert_eq!(events.get(), 2, "one Change and one Confirm");
1719 });
1720 }
1721 }
1722
1723 fn left_press(position: Point<Pixels>) -> MouseDownEvent {
1724 MouseDownEvent {
1725 button: MouseButton::Left,
1726 position,
1727 modifiers: Modifiers::default(),
1728 click_count: 1,
1729 first_mouse: false,
1730 }
1731 }
1732
1733 #[gpui::test]
1734 fn test_combo_box_dismiss_ignores_press_on_trigger(cx: &mut TestAppContext) {
1735 cx.update(crate::init);
1736 let cx = cx.add_empty_window();
1737 let state = cx.update(|window, cx| {
1738 let items = SearchableVec::new(vec!["React", "Vue", "Angular"]);
1739 cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true))
1740 });
1741 let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1742
1743 cx.update(|window, cx| {
1744 state.update(cx, |state, cx| {
1745 state.state.bounds = Bounds {
1746 origin: point(px(10.), px(10.)),
1747 size: size(px(200.), px(32.)),
1748 };
1749 state.set_open(true, cx);
1750 state.dismiss(&left_press(point(px(20.), px(20.))), window, cx);
1751 });
1752 });
1753
1754 cx.update(|_, cx| {
1755 assert!(
1756 state.read(cx).state.open,
1757 "a press on the trigger must reach nested controls, so the menu stays open \
1758 and `toggle_menu` closes it on release instead",
1759 );
1760 assert_eq!(collector.read(cx).event_count.get(), 0);
1761 });
1762
1763 cx.update(|window, cx| {
1764 state.update(cx, |state, cx| {
1765 state.dismiss(&left_press(point(px(20.), px(200.))), window, cx);
1766 });
1767 });
1768
1769 cx.update(|_, cx| {
1770 assert!(!state.read(cx).state.open);
1771 assert_eq!(
1772 collector.read(cx).event_count.get(),
1773 1,
1774 "dismissing from outside the trigger emits Confirm",
1775 );
1776 });
1777 }
1778
1779 #[allow(unused)]
1781 fn _uses_state<D: SearchableListDelegate + 'static>(_: &SearchableListState<D>)
1782 where
1783 <D::Item as SearchableListItem>::Value: PartialEq + Clone,
1784 {
1785 }
1786 fn assert_filtered_row_replacement(cx: &mut TestAppContext, through_list: bool) {
1787 use crate::list::ListDelegate as _;
1788
1789 cx.update(crate::init);
1790 let cx = cx.add_empty_window();
1791 let state = cx.update(|window, cx| {
1792 cx.new(|cx| {
1793 ComboboxState::new(
1794 SearchableVec::new(vec!["React", "Vue"]),
1795 vec![IndexPath::new(0)],
1796 window,
1797 cx,
1798 )
1799 .searchable(true)
1800 })
1801 });
1802 let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1803
1804 cx.update(|window, cx| {
1805 state.update(cx, |state, cx| {
1806 state.set_open(true, cx);
1807 state.state.list.update(cx, |list, cx| {
1808 let _ = list
1809 .delegate_mut()
1810 .delegate
1811 .perform_search("Vue", window, cx);
1812 list.set_selected_index(Some(IndexPath::new(0)), window, cx);
1813 });
1814 assert_eq!(state.selected_values(), vec!["React"]);
1815 assert_eq!(
1816 state
1817 .state
1818 .list
1819 .read(cx)
1820 .delegate()
1821 .delegate
1822 .item(IndexPath::new(0)),
1823 Some(&"Vue"),
1824 );
1825 if through_list {
1826 state.state.list.update(cx, |list, cx| {
1827 list.delegate_mut().confirm(false, window, cx);
1828 });
1829 } else {
1830 state.handle_item_select(IndexPath::new(0), window, cx);
1831 }
1832 });
1833 });
1834
1835 cx.update(|_, cx| {
1836 assert_eq!(state.read(cx).selected_values(), vec!["Vue"]);
1837 assert!(
1838 !state.read(cx).state.open,
1839 "single selection must close the popover"
1840 );
1841 assert_eq!(collector.read(cx).event_count.get(), 2);
1842 });
1843 }
1844
1845 #[gpui::test]
1846 fn test_filtered_row_replacement_direct(cx: &mut TestAppContext) {
1847 assert_filtered_row_replacement(cx, false);
1848 }
1849
1850 #[gpui::test]
1851 fn test_filtered_row_replacement_list_confirm(cx: &mut TestAppContext) {
1852 assert_filtered_row_replacement(cx, true);
1853 }
1854
1855 #[gpui::test]
1856 fn current_item_acceptance_closes_without_change(cx: &mut TestAppContext) {
1857 use crate::list::ListDelegate as _;
1858 cx.update(crate::init);
1859 let cx = cx.add_empty_window();
1860 for through_list in [false, true] {
1861 let state = cx.update(|window, cx| {
1862 cx.new(|cx| {
1863 ComboboxState::new(
1864 SearchableVec::new(vec!["React", "Vue"]),
1865 vec![IndexPath::new(0)],
1866 window,
1867 cx,
1868 )
1869 })
1870 });
1871 let collector =
1872 cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx)));
1873 cx.update(|window, cx| {
1874 state.update(cx, |state, cx| {
1875 state.set_open(true, cx);
1876 if through_list {
1877 state.state.list.update(cx, |list, cx| {
1878 list.delegate_mut().confirm(false, window, cx)
1879 });
1880 } else {
1881 state.handle_item_select(IndexPath::new(0), window, cx);
1882 }
1883 })
1884 });
1885 cx.run_until_parked();
1886 cx.update(|_, cx| {
1887 assert!(!state.read(cx).state.open);
1888 assert_eq!(state.read(cx).selected_values(), vec!["React"]);
1889 assert_eq!(
1890 collector.read(cx).event_count.get(),
1891 1,
1892 "only Confirm, no Change"
1893 );
1894 });
1895 }
1896 }
1897
1898 #[cfg(feature = "gpui-fast")]
1900 mod retained {
1901 use std::{cell::Cell, rc::Rc};
1902
1903 use gpui::{
1904 AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
1905 TestAppContext, Window, div, px,
1906 };
1907
1908 use crate::{
1909 combobox::{Combobox, ComboboxState},
1910 searchable_list::SearchableVec,
1911 };
1912
1913 struct Page {
1916 state: Entity<ComboboxState<SearchableVec<&'static str>>>,
1917 renders: Rc<Cell<usize>>,
1918 }
1919
1920 impl Render for Page {
1921 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1922 self.renders.set(self.renders.get() + 1);
1923 let selected = self.state.read(cx).selected_values();
1924 div()
1925 .w(px(240.))
1926 .child(Combobox::new(&self.state))
1927 .child(format!("{selected:?}"))
1928 }
1929 }
1930
1931 #[gpui::test]
1934 fn drawing_a_combobox_again_leaves_the_page_around_it_retained(cx: &mut TestAppContext) {
1935 cx.update(crate::init);
1936 let renders = Rc::new(Cell::new(0));
1937 let (_, cx) = cx.add_window_view({
1938 let renders = renders.clone();
1939 move |window, cx| {
1940 let items = SearchableVec::new(vec!["Rust", "Go", "C++"]);
1941 Page {
1942 state: cx.new(|cx| ComboboxState::new(items, vec![], window, cx)),
1943 renders,
1944 }
1945 }
1946 });
1947 cx.update(|window, cx| window.draw(cx).clear(cx));
1948 cx.update(|window, cx| window.draw(cx).clear(cx));
1949 let rendered = renders.get();
1950 for _ in 0..3 {
1951 cx.update(|window, cx| window.draw(cx).clear(cx));
1952 }
1953 assert_eq!(renders.get(), rendered, "the page was built again");
1954 }
1955 }
1956}