picker.rs

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