picker.rs

  1use anyhow::Result;
  2use editor::{
  3    Editor,
  4    actions::{MoveDown, MoveUp},
  5    scroll::Autoscroll,
  6};
  7use gpui::{
  8    AnyElement, App, ClickEvent, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
  9    Focusable, Length, ListSizingBehavior, ListState, MouseButton, MouseUpEvent, Render,
 10    ScrollStrategy, Stateful, Task, UniformListScrollHandle, Window, actions, div, impl_actions,
 11    list, prelude::*, uniform_list,
 12};
 13use head::Head;
 14use schemars::JsonSchema;
 15use serde::Deserialize;
 16use std::{sync::Arc, time::Duration};
 17use ui::{
 18    Color, Divider, Label, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, prelude::*, v_flex,
 19};
 20use util::ResultExt;
 21use workspace::ModalView;
 22
 23mod head;
 24pub mod highlighted_match_with_paths;
 25
 26enum ElementContainer {
 27    List(ListState),
 28    UniformList(UniformListScrollHandle),
 29}
 30
 31pub enum Direction {
 32    Up,
 33    Down,
 34}
 35
 36actions!(picker, [ConfirmCompletion]);
 37
 38/// ConfirmInput is an alternative editor action which - instead of selecting active picker entry - treats pickers editor input literally,
 39/// performing some kind of action on it.
 40#[derive(Clone, PartialEq, Deserialize, JsonSchema, Default)]
 41#[serde(deny_unknown_fields)]
 42pub struct ConfirmInput {
 43    pub secondary: bool,
 44}
 45
 46impl_actions!(picker, [ConfirmInput]);
 47
 48struct PendingUpdateMatches {
 49    delegate_update_matches: Option<Task<()>>,
 50    _task: Task<Result<()>>,
 51}
 52
 53pub struct Picker<D: PickerDelegate> {
 54    pub delegate: D,
 55    element_container: ElementContainer,
 56    head: Head,
 57    pending_update_matches: Option<PendingUpdateMatches>,
 58    confirm_on_update: Option<bool>,
 59    width: Option<Length>,
 60    widest_item: Option<usize>,
 61    max_height: Option<Length>,
 62    focus_handle: FocusHandle,
 63    /// An external control to display a scrollbar in the `Picker`.
 64    show_scrollbar: bool,
 65    /// An internal state that controls whether to show the scrollbar based on the user's focus.
 66    scrollbar_visibility: bool,
 67    scrollbar_state: ScrollbarState,
 68    hide_scrollbar_task: Option<Task<()>>,
 69    /// Whether the `Picker` is rendered as a self-contained modal.
 70    ///
 71    /// Set this to `false` when rendering the `Picker` as part of a larger modal.
 72    is_modal: bool,
 73}
 74
 75#[derive(Debug, Default, Clone, Copy, PartialEq)]
 76pub enum PickerEditorPosition {
 77    #[default]
 78    /// Render the editor at the start of the picker. Usually the top
 79    Start,
 80    /// Render the editor at the end of the picker. Usually the bottom
 81    End,
 82}
 83
 84pub trait PickerDelegate: Sized + 'static {
 85    type ListItem: IntoElement;
 86
 87    fn match_count(&self) -> usize;
 88    fn selected_index(&self) -> usize;
 89    fn separators_after_indices(&self) -> Vec<usize> {
 90        Vec::new()
 91    }
 92    fn set_selected_index(
 93        &mut self,
 94        ix: usize,
 95        window: &mut Window,
 96        cx: &mut Context<Picker<Self>>,
 97    );
 98    fn can_select(
 99        &mut self,
100        _ix: usize,
101        _window: &mut Window,
102        _cx: &mut Context<Picker<Self>>,
103    ) -> bool {
104        true
105    }
106
107    // Allows binding some optional effect to when the selection changes.
108    fn selected_index_changed(
109        &self,
110        _ix: usize,
111        _window: &mut Window,
112        _cx: &mut Context<Picker<Self>>,
113    ) -> Option<Box<dyn Fn(&mut Window, &mut App) + 'static>> {
114        None
115    }
116    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str>;
117    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
118        Some("No matches".into())
119    }
120    fn update_matches(
121        &mut self,
122        query: String,
123        window: &mut Window,
124        cx: &mut Context<Picker<Self>>,
125    ) -> Task<()>;
126
127    // Delegates that support this method (e.g. the CommandPalette) can chose to block on any background
128    // work for up to `duration` to try and get a result synchronously.
129    // This avoids a flash of an empty command-palette on cmd-shift-p, and lets workspace::SendKeystrokes
130    // mostly work when dismissing a palette.
131    fn finalize_update_matches(
132        &mut self,
133        _query: String,
134        _duration: Duration,
135        _window: &mut Window,
136        _cx: &mut Context<Picker<Self>>,
137    ) -> bool {
138        false
139    }
140
141    /// Override if you want to have <enter> update the query instead of confirming.
142    fn confirm_update_query(
143        &mut self,
144        _window: &mut Window,
145        _cx: &mut Context<Picker<Self>>,
146    ) -> Option<String> {
147        None
148    }
149    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>);
150    /// Instead of interacting with currently selected entry, treats editor input literally,
151    /// performing some kind of action on it.
152    fn confirm_input(
153        &mut self,
154        _secondary: bool,
155        _window: &mut Window,
156        _: &mut Context<Picker<Self>>,
157    ) {
158    }
159    fn dismissed(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>);
160    fn should_dismiss(&self) -> bool {
161        true
162    }
163    fn confirm_completion(
164        &mut self,
165        _query: String,
166        _window: &mut Window,
167        _: &mut Context<Picker<Self>>,
168    ) -> Option<String> {
169        None
170    }
171
172    fn editor_position(&self) -> PickerEditorPosition {
173        PickerEditorPosition::default()
174    }
175
176    fn render_editor(
177        &self,
178        editor: &Entity<Editor>,
179        _window: &mut Window,
180        _cx: &mut Context<Picker<Self>>,
181    ) -> Div {
182        v_flex()
183            .when(
184                self.editor_position() == PickerEditorPosition::End,
185                |this| this.child(Divider::horizontal()),
186            )
187            .child(
188                h_flex()
189                    .overflow_hidden()
190                    .flex_none()
191                    .h_9()
192                    .px_2p5()
193                    .child(editor.clone()),
194            )
195            .when(
196                self.editor_position() == PickerEditorPosition::Start,
197                |this| this.child(Divider::horizontal()),
198            )
199    }
200
201    fn render_match(
202        &self,
203        ix: usize,
204        selected: bool,
205        window: &mut Window,
206        cx: &mut Context<Picker<Self>>,
207    ) -> Option<Self::ListItem>;
208    fn render_header(
209        &self,
210        _window: &mut Window,
211        _: &mut Context<Picker<Self>>,
212    ) -> Option<AnyElement> {
213        None
214    }
215    fn render_footer(
216        &self,
217        _window: &mut Window,
218        _: &mut Context<Picker<Self>>,
219    ) -> Option<AnyElement> {
220        None
221    }
222}
223
224impl<D: PickerDelegate> Focusable for Picker<D> {
225    fn focus_handle(&self, cx: &App) -> FocusHandle {
226        match &self.head {
227            Head::Editor(editor) => editor.focus_handle(cx),
228            Head::Empty(head) => head.focus_handle(cx),
229        }
230    }
231}
232
233#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
234enum ContainerKind {
235    List,
236    UniformList,
237}
238
239impl<D: PickerDelegate> Picker<D> {
240    /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
241    /// The picker allows the user to perform search items by text.
242    /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
243    pub fn uniform_list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
244        let head = Head::editor(
245            delegate.placeholder_text(window, cx),
246            Self::on_input_editor_event,
247            window,
248            cx,
249        );
250
251        Self::new(delegate, ContainerKind::UniformList, head, window, cx)
252    }
253
254    /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
255    /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
256    pub fn nonsearchable_uniform_list(
257        delegate: D,
258        window: &mut Window,
259        cx: &mut Context<Self>,
260    ) -> Self {
261        let head = Head::empty(Self::on_empty_head_blur, window, cx);
262
263        Self::new(delegate, ContainerKind::UniformList, head, window, cx)
264    }
265
266    /// A picker, which displays its matches using `gpui::list`, matches can have different heights.
267    /// The picker allows the user to perform search items by text.
268    /// If `PickerDelegate::render_match` only returns items with the same height, use `Picker::uniform_list` as its implementation is optimized for that.
269    pub fn list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
270        let head = Head::editor(
271            delegate.placeholder_text(window, cx),
272            Self::on_input_editor_event,
273            window,
274            cx,
275        );
276
277        Self::new(delegate, ContainerKind::List, head, window, cx)
278    }
279
280    fn new(
281        delegate: D,
282        container: ContainerKind,
283        head: Head,
284        window: &mut Window,
285        cx: &mut Context<Self>,
286    ) -> Self {
287        let element_container = Self::create_element_container(container, cx);
288        let scrollbar_state = match &element_container {
289            ElementContainer::UniformList(scroll_handle) => {
290                ScrollbarState::new(scroll_handle.clone())
291            }
292            ElementContainer::List(state) => ScrollbarState::new(state.clone()),
293        };
294        let focus_handle = cx.focus_handle();
295        let mut this = Self {
296            delegate,
297            head,
298            element_container,
299            pending_update_matches: None,
300            confirm_on_update: None,
301            width: None,
302            widest_item: None,
303            max_height: Some(rems(18.).into()),
304            focus_handle,
305            show_scrollbar: false,
306            scrollbar_visibility: true,
307            scrollbar_state,
308            is_modal: true,
309            hide_scrollbar_task: None,
310        };
311        this.update_matches("".to_string(), window, cx);
312        // give the delegate 4ms to render the first set of suggestions.
313        this.delegate
314            .finalize_update_matches("".to_string(), Duration::from_millis(4), window, cx);
315        this
316    }
317
318    fn create_element_container(
319        container: ContainerKind,
320        cx: &mut Context<Self>,
321    ) -> ElementContainer {
322        match container {
323            ContainerKind::UniformList => {
324                ElementContainer::UniformList(UniformListScrollHandle::new())
325            }
326            ContainerKind::List => {
327                let entity = cx.entity().downgrade();
328                ElementContainer::List(ListState::new(
329                    0,
330                    gpui::ListAlignment::Top,
331                    px(1000.),
332                    move |ix, window, cx| {
333                        entity
334                            .upgrade()
335                            .map(|entity| {
336                                entity.update(cx, |this, cx| {
337                                    this.render_element(window, cx, ix).into_any_element()
338                                })
339                            })
340                            .unwrap_or_else(|| div().into_any_element())
341                    },
342                ))
343            }
344        }
345    }
346
347    pub fn width(mut self, width: impl Into<gpui::Length>) -> Self {
348        self.width = Some(width.into());
349        self
350    }
351
352    pub fn widest_item(mut self, ix: Option<usize>) -> Self {
353        self.widest_item = ix;
354        self
355    }
356
357    pub fn max_height(mut self, max_height: Option<gpui::Length>) -> Self {
358        self.max_height = max_height;
359        self
360    }
361
362    pub fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
363        self.show_scrollbar = show_scrollbar;
364        self
365    }
366
367    pub fn modal(mut self, modal: bool) -> Self {
368        self.is_modal = modal;
369        self
370    }
371
372    pub fn focus(&self, window: &mut Window, cx: &mut App) {
373        self.focus_handle(cx).focus(window);
374    }
375
376    /// Handles the selecting an index, and passing the change to the delegate.
377    /// If `fallback_direction` is set to `None`, the index will not be selected
378    /// if the element at that index cannot be selected.
379    /// If `fallback_direction` is set to
380    /// `Some(..)`, the next selectable element will be selected in the
381    /// specified direction (Down or Up), cycling through all elements until
382    /// finding one that can be selected or returning if there are no selectable elements.
383    /// If `scroll_to_index` is true, the new selected index will be scrolled into
384    /// view.
385    ///
386    /// If some effect is bound to `selected_index_changed`, it will be executed.
387    pub fn set_selected_index(
388        &mut self,
389        mut ix: usize,
390        fallback_direction: Option<Direction>,
391        scroll_to_index: bool,
392        window: &mut Window,
393        cx: &mut Context<Self>,
394    ) {
395        let match_count = self.delegate.match_count();
396        if match_count == 0 {
397            return;
398        }
399
400        if let Some(bias) = fallback_direction {
401            let mut curr_ix = ix;
402            while !self.delegate.can_select(curr_ix, window, cx) {
403                curr_ix = match bias {
404                    Direction::Down => {
405                        if curr_ix == match_count - 1 {
406                            0
407                        } else {
408                            curr_ix + 1
409                        }
410                    }
411                    Direction::Up => {
412                        if curr_ix == 0 {
413                            match_count - 1
414                        } else {
415                            curr_ix - 1
416                        }
417                    }
418                };
419                // There is no item that can be selected
420                if ix == curr_ix {
421                    return;
422                }
423            }
424            ix = curr_ix;
425        } else if !self.delegate.can_select(ix, window, cx) {
426            return;
427        }
428
429        let previous_index = self.delegate.selected_index();
430        self.delegate.set_selected_index(ix, window, cx);
431        let current_index = self.delegate.selected_index();
432
433        if previous_index != current_index {
434            if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) {
435                action(window, cx);
436            }
437            if scroll_to_index {
438                self.scroll_to_item_index(ix);
439            }
440        }
441    }
442
443    pub fn select_next(
444        &mut self,
445        _: &menu::SelectNext,
446        window: &mut Window,
447        cx: &mut Context<Self>,
448    ) {
449        let count = self.delegate.match_count();
450        if count > 0 {
451            let index = self.delegate.selected_index();
452            let ix = if index == count - 1 { 0 } else { index + 1 };
453            self.set_selected_index(ix, Some(Direction::Down), true, window, cx);
454            cx.notify();
455        }
456    }
457
458    pub fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
459        self.select_previous(&Default::default(), window, cx);
460    }
461
462    fn select_previous(
463        &mut self,
464        _: &menu::SelectPrevious,
465        window: &mut Window,
466        cx: &mut Context<Self>,
467    ) {
468        let count = self.delegate.match_count();
469        if count > 0 {
470            let index = self.delegate.selected_index();
471            let ix = if index == 0 { count - 1 } else { index - 1 };
472            self.set_selected_index(ix, Some(Direction::Up), true, window, cx);
473            cx.notify();
474        }
475    }
476
477    pub fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
478        self.select_next(&Default::default(), window, cx);
479    }
480
481    pub fn select_first(
482        &mut self,
483        _: &menu::SelectFirst,
484        window: &mut Window,
485        cx: &mut Context<Self>,
486    ) {
487        let count = self.delegate.match_count();
488        if count > 0 {
489            self.set_selected_index(0, Some(Direction::Down), true, window, cx);
490            cx.notify();
491        }
492    }
493
494    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
495        let count = self.delegate.match_count();
496        if count > 0 {
497            self.set_selected_index(count - 1, Some(Direction::Up), true, window, cx);
498            cx.notify();
499        }
500    }
501
502    pub fn cycle_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
503        let count = self.delegate.match_count();
504        let index = self.delegate.selected_index();
505        let new_index = if index + 1 == count { 0 } else { index + 1 };
506        self.set_selected_index(new_index, Some(Direction::Down), true, window, cx);
507        cx.notify();
508    }
509
510    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
511        if self.delegate.should_dismiss() {
512            self.delegate.dismissed(window, cx);
513            cx.emit(DismissEvent);
514        }
515    }
516
517    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
518        if self.pending_update_matches.is_some()
519            && !self.delegate.finalize_update_matches(
520                self.query(cx),
521                Duration::from_millis(16),
522                window,
523                cx,
524            )
525        {
526            self.confirm_on_update = Some(false)
527        } else {
528            self.pending_update_matches.take();
529            self.do_confirm(false, window, cx);
530        }
531    }
532
533    fn secondary_confirm(
534        &mut self,
535        _: &menu::SecondaryConfirm,
536        window: &mut Window,
537        cx: &mut Context<Self>,
538    ) {
539        if self.pending_update_matches.is_some()
540            && !self.delegate.finalize_update_matches(
541                self.query(cx),
542                Duration::from_millis(16),
543                window,
544                cx,
545            )
546        {
547            self.confirm_on_update = Some(true)
548        } else {
549            self.do_confirm(true, window, cx);
550        }
551    }
552
553    fn confirm_input(&mut self, input: &ConfirmInput, window: &mut Window, cx: &mut Context<Self>) {
554        self.delegate.confirm_input(input.secondary, window, cx);
555    }
556
557    fn confirm_completion(
558        &mut self,
559        _: &ConfirmCompletion,
560        window: &mut Window,
561        cx: &mut Context<Self>,
562    ) {
563        if let Some(new_query) = self.delegate.confirm_completion(self.query(cx), window, cx) {
564            self.set_query(new_query, window, cx);
565        } else {
566            cx.propagate()
567        }
568    }
569
570    fn handle_click(
571        &mut self,
572        ix: usize,
573        secondary: bool,
574        window: &mut Window,
575        cx: &mut Context<Self>,
576    ) {
577        cx.stop_propagation();
578        window.prevent_default();
579        self.set_selected_index(ix, None, false, window, cx);
580        self.do_confirm(secondary, window, cx)
581    }
582
583    fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {
584        if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {
585            self.set_query(update_query, window, cx);
586            self.set_selected_index(0, Some(Direction::Down), false, window, cx);
587        } else {
588            self.delegate.confirm(secondary, window, cx)
589        }
590    }
591
592    fn on_input_editor_event(
593        &mut self,
594        _: &Entity<Editor>,
595        event: &editor::EditorEvent,
596        window: &mut Window,
597        cx: &mut Context<Self>,
598    ) {
599        let Head::Editor(editor) = &self.head else {
600            panic!("unexpected call");
601        };
602        match event {
603            editor::EditorEvent::BufferEdited => {
604                let query = editor.read(cx).text(cx);
605                self.update_matches(query, window, cx);
606            }
607            editor::EditorEvent::Blurred => {
608                if self.is_modal {
609                    self.cancel(&menu::Cancel, window, cx);
610                }
611            }
612            _ => {}
613        }
614    }
615
616    fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
617        let Head::Empty(_) = &self.head else {
618            panic!("unexpected call");
619        };
620        self.cancel(&menu::Cancel, window, cx);
621    }
622
623    pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
624        match &self.head {
625            Head::Editor(editor) => {
626                let placeholder = self.delegate.placeholder_text(window, cx);
627                editor.update(cx, |editor, cx| {
628                    editor.set_placeholder_text(placeholder, cx);
629                    cx.notify();
630                });
631            }
632            Head::Empty(_) => {}
633        }
634    }
635
636    pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
637        let query = self.query(cx);
638        self.update_matches(query, window, cx);
639    }
640
641    pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
642        let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
643
644        self.matches_updated(window, cx);
645        // This struct ensures that we can synchronously drop the task returned by the
646        // delegate's `update_matches` method and the task that the picker is spawning.
647        // If we simply capture the delegate's task into the picker's task, when the picker's
648        // task gets synchronously dropped, the delegate's task would keep running until
649        // the picker's task has a chance of being scheduled, because dropping a task happens
650        // asynchronously.
651        self.pending_update_matches = Some(PendingUpdateMatches {
652            delegate_update_matches: Some(delegate_pending_update_matches),
653            _task: cx.spawn_in(window, async move |this, cx| {
654                let delegate_pending_update_matches = this.update(cx, |this, _| {
655                    this.pending_update_matches
656                        .as_mut()
657                        .unwrap()
658                        .delegate_update_matches
659                        .take()
660                        .unwrap()
661                })?;
662                delegate_pending_update_matches.await;
663                this.update_in(cx, |this, window, cx| {
664                    this.matches_updated(window, cx);
665                })
666            }),
667        });
668    }
669
670    fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
671        if let ElementContainer::List(state) = &mut self.element_container {
672            state.reset(self.delegate.match_count());
673        }
674
675        let index = self.delegate.selected_index();
676        self.scroll_to_item_index(index);
677        self.pending_update_matches = None;
678        if let Some(secondary) = self.confirm_on_update.take() {
679            self.do_confirm(secondary, window, cx);
680        }
681        cx.notify();
682    }
683
684    pub fn query(&self, cx: &App) -> String {
685        match &self.head {
686            Head::Editor(editor) => editor.read(cx).text(cx),
687            Head::Empty(_) => "".to_string(),
688        }
689    }
690
691    pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
692        if let Head::Editor(editor) = &self.head {
693            editor.update(cx, |editor, cx| {
694                editor.set_text(query, window, cx);
695                let editor_offset = editor.buffer().read(cx).len(cx);
696                editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
697                    s.select_ranges(Some(editor_offset..editor_offset))
698                });
699            });
700        }
701    }
702
703    fn scroll_to_item_index(&mut self, ix: usize) {
704        match &mut self.element_container {
705            ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
706            ElementContainer::UniformList(scroll_handle) => {
707                scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
708            }
709        }
710    }
711
712    fn render_element(
713        &self,
714        window: &mut Window,
715        cx: &mut Context<Self>,
716        ix: usize,
717    ) -> impl IntoElement + use<D> {
718        div()
719            .id(("item", ix))
720            .cursor_pointer()
721            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
722                this.handle_click(ix, event.modifiers().secondary(), window, cx)
723            }))
724            // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
725            // and produces right mouse button events. This matches platforms norms
726            // but means that UIs which depend on holding ctrl down (such as the tab
727            // switcher) can't be clicked on. Hence, this handler.
728            .on_mouse_up(
729                MouseButton::Right,
730                cx.listener(move |this, event: &MouseUpEvent, window, cx| {
731                    // We specifically want to use the platform key here, as
732                    // ctrl will already be held down for the tab switcher.
733                    this.handle_click(ix, event.modifiers.platform, window, cx)
734                }),
735            )
736            .children(self.delegate.render_match(
737                ix,
738                ix == self.delegate.selected_index(),
739                window,
740                cx,
741            ))
742            .when(
743                self.delegate.separators_after_indices().contains(&ix),
744                |picker| {
745                    picker
746                        .border_color(cx.theme().colors().border_variant)
747                        .border_b_1()
748                        .py(px(-1.0))
749                },
750            )
751    }
752
753    fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
754        let sizing_behavior = if self.max_height.is_some() {
755            ListSizingBehavior::Infer
756        } else {
757            ListSizingBehavior::Auto
758        };
759
760        match &self.element_container {
761            ElementContainer::UniformList(scroll_handle) => uniform_list(
762                cx.entity().clone(),
763                "candidates",
764                self.delegate.match_count(),
765                move |picker, visible_range, window, cx| {
766                    visible_range
767                        .map(|ix| picker.render_element(window, cx, ix))
768                        .collect()
769                },
770            )
771            .with_sizing_behavior(sizing_behavior)
772            .when_some(self.widest_item, |el, widest_item| {
773                el.with_width_from_item(Some(widest_item))
774            })
775            .flex_grow()
776            .py_1()
777            .track_scroll(scroll_handle.clone())
778            .into_any_element(),
779            ElementContainer::List(state) => list(state.clone())
780                .with_sizing_behavior(sizing_behavior)
781                .flex_grow()
782                .py_2()
783                .into_any_element(),
784        }
785    }
786
787    #[cfg(any(test, feature = "test-support"))]
788    pub fn logical_scroll_top_index(&self) -> usize {
789        match &self.element_container {
790            ElementContainer::List(state) => state.logical_scroll_top().item_ix,
791            ElementContainer::UniformList(scroll_handle) => {
792                scroll_handle.logical_scroll_top_index()
793            }
794        }
795    }
796
797    fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
798        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
799        self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
800            cx.background_executor()
801                .timer(SCROLLBAR_SHOW_INTERVAL)
802                .await;
803            panel
804                .update(cx, |panel, cx| {
805                    panel.scrollbar_visibility = false;
806                    cx.notify();
807                })
808                .log_err();
809        }))
810    }
811
812    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
813        if !self.show_scrollbar
814            || !(self.scrollbar_visibility || self.scrollbar_state.is_dragging())
815        {
816            return None;
817        }
818        Some(
819            div()
820                .occlude()
821                .id("picker-scroll")
822                .h_full()
823                .absolute()
824                .right_1()
825                .top_1()
826                .bottom_0()
827                .w(px(12.))
828                .cursor_default()
829                .on_mouse_move(cx.listener(|_, _, _window, cx| {
830                    cx.notify();
831                    cx.stop_propagation()
832                }))
833                .on_hover(|_, _window, cx| {
834                    cx.stop_propagation();
835                })
836                .on_any_mouse_down(|_, _window, cx| {
837                    cx.stop_propagation();
838                })
839                .on_mouse_up(
840                    MouseButton::Left,
841                    cx.listener(|picker, _, window, cx| {
842                        if !picker.scrollbar_state.is_dragging()
843                            && !picker.focus_handle.contains_focused(window, cx)
844                        {
845                            picker.hide_scrollbar(cx);
846                            cx.notify();
847                        }
848                        cx.stop_propagation();
849                    }),
850                )
851                .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
852                    cx.notify();
853                }))
854                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
855        )
856    }
857}
858
859impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
860impl<D: PickerDelegate> ModalView for Picker<D> {}
861
862impl<D: PickerDelegate> Render for Picker<D> {
863    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
864        let editor_position = self.delegate.editor_position();
865        v_flex()
866            .key_context("Picker")
867            .size_full()
868            .when_some(self.width, |el, width| el.w(width))
869            .overflow_hidden()
870            // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
871            // as a part of a modal rather than the entire modal.
872            //
873            // We should revisit how the `Picker` is styled to make it more composable.
874            .when(self.is_modal, |this| this.elevation_3(cx))
875            .on_action(cx.listener(Self::select_next))
876            .on_action(cx.listener(Self::select_previous))
877            .on_action(cx.listener(Self::editor_move_down))
878            .on_action(cx.listener(Self::editor_move_up))
879            .on_action(cx.listener(Self::select_first))
880            .on_action(cx.listener(Self::select_last))
881            .on_action(cx.listener(Self::cancel))
882            .on_action(cx.listener(Self::confirm))
883            .on_action(cx.listener(Self::secondary_confirm))
884            .on_action(cx.listener(Self::confirm_completion))
885            .on_action(cx.listener(Self::confirm_input))
886            .children(match &self.head {
887                Head::Editor(editor) => {
888                    if editor_position == PickerEditorPosition::Start {
889                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
890                    } else {
891                        None
892                    }
893                }
894                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
895            })
896            .when(self.delegate.match_count() > 0, |el| {
897                el.child(
898                    v_flex()
899                        .id("element-container")
900                        .relative()
901                        .flex_grow()
902                        .when_some(self.max_height, |div, max_h| div.max_h(max_h))
903                        .overflow_hidden()
904                        .children(self.delegate.render_header(window, cx))
905                        .child(self.render_element_container(cx))
906                        .on_hover(cx.listener(|this, hovered, window, cx| {
907                            if *hovered {
908                                this.scrollbar_visibility = true;
909                                this.hide_scrollbar_task.take();
910                                cx.notify();
911                            } else if !this.focus_handle.contains_focused(window, cx) {
912                                this.hide_scrollbar(cx);
913                            }
914                        }))
915                        .when_some(self.render_scrollbar(cx), |div, scrollbar| {
916                            div.child(scrollbar)
917                        }),
918                )
919            })
920            .when(self.delegate.match_count() == 0, |el| {
921                el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
922                    el.child(
923                        v_flex().flex_grow().py_2().child(
924                            ListItem::new("empty_state")
925                                .inset(true)
926                                .spacing(ListItemSpacing::Sparse)
927                                .disabled(true)
928                                .child(Label::new(text).color(Color::Muted)),
929                        ),
930                    )
931                })
932            })
933            .children(self.delegate.render_footer(window, cx))
934            .children(match &self.head {
935                Head::Editor(editor) => {
936                    if editor_position == PickerEditorPosition::End {
937                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
938                    } else {
939                        None
940                    }
941                }
942                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
943            })
944    }
945}