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    // Allow intercepting up and down for history navigation in the command palette.
148    fn handle_history(
149        &mut self,
150        _direction: Direction,
151        _window: &mut Window,
152        _cx: &mut Context<Picker<Self>>,
153    ) -> Option<String> {
154        None
155    }
156
157    /// Override if you want to have <enter> update the query instead of confirming.
158    fn confirm_update_query(
159        &mut self,
160        _window: &mut Window,
161        _cx: &mut Context<Picker<Self>>,
162    ) -> Option<String> {
163        None
164    }
165    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>);
166    /// Instead of interacting with currently selected entry, treats editor input literally,
167    /// performing some kind of action on it.
168    fn confirm_input(
169        &mut self,
170        _secondary: bool,
171        _window: &mut Window,
172        _: &mut Context<Picker<Self>>,
173    ) {
174    }
175    fn dismissed(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>);
176    fn should_dismiss(&self) -> bool {
177        true
178    }
179    fn confirm_completion(
180        &mut self,
181        _query: String,
182        _window: &mut Window,
183        _: &mut Context<Picker<Self>>,
184    ) -> Option<String> {
185        None
186    }
187
188    fn editor_position(&self) -> PickerEditorPosition {
189        PickerEditorPosition::default()
190    }
191
192    fn render_editor(
193        &self,
194        editor: &Entity<Editor>,
195        _window: &mut Window,
196        _cx: &mut Context<Picker<Self>>,
197    ) -> Div {
198        v_flex()
199            .when(
200                self.editor_position() == PickerEditorPosition::End,
201                |this| this.child(Divider::horizontal()),
202            )
203            .child(
204                h_flex()
205                    .overflow_hidden()
206                    .flex_none()
207                    .h_9()
208                    .px_2p5()
209                    .child(editor.clone()),
210            )
211            .when(
212                self.editor_position() == PickerEditorPosition::Start,
213                |this| this.child(Divider::horizontal()),
214            )
215    }
216
217    fn render_match(
218        &self,
219        ix: usize,
220        selected: bool,
221        window: &mut Window,
222        cx: &mut Context<Picker<Self>>,
223    ) -> Option<Self::ListItem>;
224
225    fn render_header(
226        &self,
227        _window: &mut Window,
228        _: &mut Context<Picker<Self>>,
229    ) -> Option<AnyElement> {
230        None
231    }
232
233    fn render_footer(
234        &self,
235        _window: &mut Window,
236        _: &mut Context<Picker<Self>>,
237    ) -> Option<AnyElement> {
238        None
239    }
240}
241
242impl<D: PickerDelegate> Focusable for Picker<D> {
243    fn focus_handle(&self, cx: &App) -> FocusHandle {
244        match &self.head {
245            Head::Editor(editor) => editor.focus_handle(cx),
246            Head::Empty(head) => head.focus_handle(cx),
247        }
248    }
249}
250
251#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
252enum ContainerKind {
253    List,
254    UniformList,
255}
256
257impl<D: PickerDelegate> Picker<D> {
258    /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
259    /// The picker allows the user to perform search items by text.
260    /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
261    pub fn uniform_list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
262        let head = Head::editor(
263            delegate.placeholder_text(window, cx),
264            Self::on_input_editor_event,
265            window,
266            cx,
267        );
268
269        Self::new(delegate, ContainerKind::UniformList, head, window, cx)
270    }
271
272    /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
273    /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
274    pub fn nonsearchable_uniform_list(
275        delegate: D,
276        window: &mut Window,
277        cx: &mut Context<Self>,
278    ) -> Self {
279        let head = Head::empty(Self::on_empty_head_blur, window, cx);
280
281        Self::new(delegate, ContainerKind::UniformList, head, window, cx)
282    }
283
284    /// A picker, which displays its matches using `gpui::list`, matches can have different heights.
285    /// The picker allows the user to perform search items by text.
286    /// If `PickerDelegate::render_match` only returns items with the same height, use `Picker::uniform_list` as its implementation is optimized for that.
287    pub fn list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
288        let head = Head::editor(
289            delegate.placeholder_text(window, cx),
290            Self::on_input_editor_event,
291            window,
292            cx,
293        );
294
295        Self::new(delegate, ContainerKind::List, head, window, cx)
296    }
297
298    fn new(
299        delegate: D,
300        container: ContainerKind,
301        head: Head,
302        window: &mut Window,
303        cx: &mut Context<Self>,
304    ) -> Self {
305        let element_container = Self::create_element_container(container);
306        let scrollbar_state = match &element_container {
307            ElementContainer::UniformList(scroll_handle) => {
308                ScrollbarState::new(scroll_handle.clone())
309            }
310            ElementContainer::List(state) => ScrollbarState::new(state.clone()),
311        };
312        let focus_handle = cx.focus_handle();
313        let mut this = Self {
314            delegate,
315            head,
316            element_container,
317            pending_update_matches: None,
318            confirm_on_update: None,
319            width: None,
320            widest_item: None,
321            max_height: Some(rems(18.).into()),
322            focus_handle,
323            show_scrollbar: false,
324            scrollbar_visibility: true,
325            scrollbar_state,
326            is_modal: true,
327            hide_scrollbar_task: None,
328        };
329        this.update_matches("".to_string(), window, cx);
330        // give the delegate 4ms to render the first set of suggestions.
331        this.delegate
332            .finalize_update_matches("".to_string(), Duration::from_millis(4), window, cx);
333        this
334    }
335
336    fn create_element_container(container: ContainerKind) -> ElementContainer {
337        match container {
338            ContainerKind::UniformList => {
339                ElementContainer::UniformList(UniformListScrollHandle::new())
340            }
341            ContainerKind::List => {
342                ElementContainer::List(ListState::new(0, gpui::ListAlignment::Top, px(1000.)))
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        if let Some(query) = self.delegate.handle_history(Direction::Down, window, cx) {
450            self.set_query(query, window, cx);
451            return;
452        }
453        let count = self.delegate.match_count();
454        if count > 0 {
455            let index = self.delegate.selected_index();
456            let ix = if index == count - 1 { 0 } else { index + 1 };
457            self.set_selected_index(ix, Some(Direction::Down), true, window, cx);
458            cx.notify();
459        }
460    }
461
462    pub fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
463        self.select_previous(&Default::default(), window, cx);
464    }
465
466    fn select_previous(
467        &mut self,
468        _: &menu::SelectPrevious,
469        window: &mut Window,
470        cx: &mut Context<Self>,
471    ) {
472        if let Some(query) = self.delegate.handle_history(Direction::Down, window, cx) {
473            self.set_query(query, window, cx);
474            return;
475        }
476        let count = self.delegate.match_count();
477        if count > 0 {
478            let index = self.delegate.selected_index();
479            let ix = if index == 0 { count - 1 } else { index - 1 };
480            self.set_selected_index(ix, Some(Direction::Up), true, window, cx);
481            cx.notify();
482        }
483    }
484
485    pub fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
486        self.select_next(&Default::default(), window, cx);
487    }
488
489    pub fn select_first(
490        &mut self,
491        _: &menu::SelectFirst,
492        window: &mut Window,
493        cx: &mut Context<Self>,
494    ) {
495        let count = self.delegate.match_count();
496        if count > 0 {
497            self.set_selected_index(0, Some(Direction::Down), true, window, cx);
498            cx.notify();
499        }
500    }
501
502    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
503        let count = self.delegate.match_count();
504        if count > 0 {
505            self.set_selected_index(count - 1, Some(Direction::Up), true, window, cx);
506            cx.notify();
507        }
508    }
509
510    pub fn cycle_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
511        let count = self.delegate.match_count();
512        let index = self.delegate.selected_index();
513        let new_index = if index + 1 == count { 0 } else { index + 1 };
514        self.set_selected_index(new_index, Some(Direction::Down), true, window, cx);
515        cx.notify();
516    }
517
518    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
519        if self.delegate.should_dismiss() {
520            self.delegate.dismissed(window, cx);
521            cx.emit(DismissEvent);
522        }
523    }
524
525    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
526        if self.pending_update_matches.is_some()
527            && !self.delegate.finalize_update_matches(
528                self.query(cx),
529                Duration::from_millis(16),
530                window,
531                cx,
532            )
533        {
534            self.confirm_on_update = Some(false)
535        } else {
536            self.pending_update_matches.take();
537            self.do_confirm(false, window, cx);
538        }
539    }
540
541    fn secondary_confirm(
542        &mut self,
543        _: &menu::SecondaryConfirm,
544        window: &mut Window,
545        cx: &mut Context<Self>,
546    ) {
547        if self.pending_update_matches.is_some()
548            && !self.delegate.finalize_update_matches(
549                self.query(cx),
550                Duration::from_millis(16),
551                window,
552                cx,
553            )
554        {
555            self.confirm_on_update = Some(true)
556        } else {
557            self.do_confirm(true, window, cx);
558        }
559    }
560
561    fn confirm_input(&mut self, input: &ConfirmInput, window: &mut Window, cx: &mut Context<Self>) {
562        self.delegate.confirm_input(input.secondary, window, cx);
563    }
564
565    fn confirm_completion(
566        &mut self,
567        _: &ConfirmCompletion,
568        window: &mut Window,
569        cx: &mut Context<Self>,
570    ) {
571        if let Some(new_query) = self.delegate.confirm_completion(self.query(cx), window, cx) {
572            self.set_query(new_query, window, cx);
573        } else {
574            cx.propagate()
575        }
576    }
577
578    fn handle_click(
579        &mut self,
580        ix: usize,
581        secondary: bool,
582        window: &mut Window,
583        cx: &mut Context<Self>,
584    ) {
585        cx.stop_propagation();
586        window.prevent_default();
587        self.set_selected_index(ix, None, false, window, cx);
588        self.do_confirm(secondary, window, cx)
589    }
590
591    fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {
592        if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {
593            self.set_query(update_query, window, cx);
594            self.set_selected_index(0, Some(Direction::Down), false, window, cx);
595        } else {
596            self.delegate.confirm(secondary, window, cx)
597        }
598    }
599
600    fn on_input_editor_event(
601        &mut self,
602        _: &Entity<Editor>,
603        event: &editor::EditorEvent,
604        window: &mut Window,
605        cx: &mut Context<Self>,
606    ) {
607        let Head::Editor(editor) = &self.head else {
608            panic!("unexpected call");
609        };
610        match event {
611            editor::EditorEvent::BufferEdited => {
612                let query = editor.read(cx).text(cx);
613                self.update_matches(query, window, cx);
614            }
615            editor::EditorEvent::Blurred => {
616                if self.is_modal {
617                    self.cancel(&menu::Cancel, window, cx);
618                }
619            }
620            _ => {}
621        }
622    }
623
624    fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
625        let Head::Empty(_) = &self.head else {
626            panic!("unexpected call");
627        };
628        self.cancel(&menu::Cancel, window, cx);
629    }
630
631    pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
632        match &self.head {
633            Head::Editor(editor) => {
634                let placeholder = self.delegate.placeholder_text(window, cx);
635                editor.update(cx, |editor, cx| {
636                    editor.set_placeholder_text(placeholder, cx);
637                    cx.notify();
638                });
639            }
640            Head::Empty(_) => {}
641        }
642    }
643
644    pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
645        let query = self.query(cx);
646        self.update_matches(query, window, cx);
647    }
648
649    pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
650        let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
651
652        self.matches_updated(window, cx);
653        // This struct ensures that we can synchronously drop the task returned by the
654        // delegate's `update_matches` method and the task that the picker is spawning.
655        // If we simply capture the delegate's task into the picker's task, when the picker's
656        // task gets synchronously dropped, the delegate's task would keep running until
657        // the picker's task has a chance of being scheduled, because dropping a task happens
658        // asynchronously.
659        self.pending_update_matches = Some(PendingUpdateMatches {
660            delegate_update_matches: Some(delegate_pending_update_matches),
661            _task: cx.spawn_in(window, async move |this, cx| {
662                let delegate_pending_update_matches = this.update(cx, |this, _| {
663                    this.pending_update_matches
664                        .as_mut()
665                        .unwrap()
666                        .delegate_update_matches
667                        .take()
668                        .unwrap()
669                })?;
670                delegate_pending_update_matches.await;
671                this.update_in(cx, |this, window, cx| {
672                    this.matches_updated(window, cx);
673                })
674            }),
675        });
676    }
677
678    fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
679        if let ElementContainer::List(state) = &mut self.element_container {
680            state.reset(self.delegate.match_count());
681        }
682
683        let index = self.delegate.selected_index();
684        self.scroll_to_item_index(index);
685        self.pending_update_matches = None;
686        if let Some(secondary) = self.confirm_on_update.take() {
687            self.do_confirm(secondary, window, cx);
688        }
689        cx.notify();
690    }
691
692    pub fn query(&self, cx: &App) -> String {
693        match &self.head {
694            Head::Editor(editor) => editor.read(cx).text(cx),
695            Head::Empty(_) => "".to_string(),
696        }
697    }
698
699    pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
700        if let Head::Editor(editor) = &self.head {
701            editor.update(cx, |editor, cx| {
702                editor.set_text(query, window, cx);
703                let editor_offset = editor.buffer().read(cx).len(cx);
704                editor.change_selections(
705                    SelectionEffects::scroll(Autoscroll::Next),
706                    window,
707                    cx,
708                    |s| s.select_ranges(Some(editor_offset..editor_offset)),
709                );
710            });
711        }
712    }
713
714    fn scroll_to_item_index(&mut self, ix: usize) {
715        match &mut self.element_container {
716            ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
717            ElementContainer::UniformList(scroll_handle) => {
718                scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
719            }
720        }
721    }
722
723    fn render_element(
724        &self,
725        window: &mut Window,
726        cx: &mut Context<Self>,
727        ix: usize,
728    ) -> impl IntoElement + use<D> {
729        div()
730            .id(("item", ix))
731            .cursor_pointer()
732            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
733                this.handle_click(ix, event.modifiers().secondary(), window, cx)
734            }))
735            // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
736            // and produces right mouse button events. This matches platforms norms
737            // but means that UIs which depend on holding ctrl down (such as the tab
738            // switcher) can't be clicked on. Hence, this handler.
739            .on_mouse_up(
740                MouseButton::Right,
741                cx.listener(move |this, event: &MouseUpEvent, window, cx| {
742                    // We specifically want to use the platform key here, as
743                    // ctrl will already be held down for the tab switcher.
744                    this.handle_click(ix, event.modifiers.platform, window, cx)
745                }),
746            )
747            .children(self.delegate.render_match(
748                ix,
749                ix == self.delegate.selected_index(),
750                window,
751                cx,
752            ))
753            .when(
754                self.delegate.separators_after_indices().contains(&ix),
755                |picker| {
756                    picker
757                        .border_color(cx.theme().colors().border_variant)
758                        .border_b_1()
759                        .py(px(-1.0))
760                },
761            )
762    }
763
764    fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
765        let sizing_behavior = if self.max_height.is_some() {
766            ListSizingBehavior::Infer
767        } else {
768            ListSizingBehavior::Auto
769        };
770
771        match &self.element_container {
772            ElementContainer::UniformList(scroll_handle) => uniform_list(
773                "candidates",
774                self.delegate.match_count(),
775                cx.processor(move |picker, visible_range: Range<usize>, window, cx| {
776                    visible_range
777                        .map(|ix| picker.render_element(window, cx, ix))
778                        .collect()
779                }),
780            )
781            .with_sizing_behavior(sizing_behavior)
782            .when_some(self.widest_item, |el, widest_item| {
783                el.with_width_from_item(Some(widest_item))
784            })
785            .flex_grow()
786            .py_1()
787            .track_scroll(scroll_handle.clone())
788            .into_any_element(),
789            ElementContainer::List(state) => list(
790                state.clone(),
791                cx.processor(|this, ix, window, cx| {
792                    this.render_element(window, cx, ix).into_any_element()
793                }),
794            )
795            .with_sizing_behavior(sizing_behavior)
796            .flex_grow()
797            .py_2()
798            .into_any_element(),
799        }
800    }
801
802    #[cfg(any(test, feature = "test-support"))]
803    pub fn logical_scroll_top_index(&self) -> usize {
804        match &self.element_container {
805            ElementContainer::List(state) => state.logical_scroll_top().item_ix,
806            ElementContainer::UniformList(scroll_handle) => {
807                scroll_handle.logical_scroll_top_index()
808            }
809        }
810    }
811
812    fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
813        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
814        self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
815            cx.background_executor()
816                .timer(SCROLLBAR_SHOW_INTERVAL)
817                .await;
818            panel
819                .update(cx, |panel, cx| {
820                    panel.scrollbar_visibility = false;
821                    cx.notify();
822                })
823                .log_err();
824        }))
825    }
826
827    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
828        if !self.show_scrollbar
829            || !(self.scrollbar_visibility || self.scrollbar_state.is_dragging())
830        {
831            return None;
832        }
833        Some(
834            div()
835                .occlude()
836                .id("picker-scroll")
837                .h_full()
838                .absolute()
839                .right_1()
840                .top_1()
841                .bottom_0()
842                .w(px(12.))
843                .cursor_default()
844                .on_mouse_move(cx.listener(|_, _, _window, cx| {
845                    cx.notify();
846                    cx.stop_propagation()
847                }))
848                .on_hover(|_, _window, cx| {
849                    cx.stop_propagation();
850                })
851                .on_any_mouse_down(|_, _window, cx| {
852                    cx.stop_propagation();
853                })
854                .on_mouse_up(
855                    MouseButton::Left,
856                    cx.listener(|picker, _, window, cx| {
857                        if !picker.scrollbar_state.is_dragging()
858                            && !picker.focus_handle.contains_focused(window, cx)
859                        {
860                            picker.hide_scrollbar(cx);
861                            cx.notify();
862                        }
863                        cx.stop_propagation();
864                    }),
865                )
866                .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
867                    cx.notify();
868                }))
869                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
870        )
871    }
872}
873
874impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
875impl<D: PickerDelegate> ModalView for Picker<D> {}
876
877impl<D: PickerDelegate> Render for Picker<D> {
878    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
879        let editor_position = self.delegate.editor_position();
880        v_flex()
881            .key_context("Picker")
882            .size_full()
883            .when_some(self.width, |el, width| el.w(width))
884            .overflow_hidden()
885            // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
886            // as a part of a modal rather than the entire modal.
887            //
888            // We should revisit how the `Picker` is styled to make it more composable.
889            .when(self.is_modal, |this| this.elevation_3(cx))
890            .on_action(cx.listener(Self::select_next))
891            .on_action(cx.listener(Self::select_previous))
892            .on_action(cx.listener(Self::editor_move_down))
893            .on_action(cx.listener(Self::editor_move_up))
894            .on_action(cx.listener(Self::select_first))
895            .on_action(cx.listener(Self::select_last))
896            .on_action(cx.listener(Self::cancel))
897            .on_action(cx.listener(Self::confirm))
898            .on_action(cx.listener(Self::secondary_confirm))
899            .on_action(cx.listener(Self::confirm_completion))
900            .on_action(cx.listener(Self::confirm_input))
901            .children(match &self.head {
902                Head::Editor(editor) => {
903                    if editor_position == PickerEditorPosition::Start {
904                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
905                    } else {
906                        None
907                    }
908                }
909                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
910            })
911            .when(self.delegate.match_count() > 0, |el| {
912                el.child(
913                    v_flex()
914                        .id("element-container")
915                        .relative()
916                        .flex_grow()
917                        .when_some(self.max_height, |div, max_h| div.max_h(max_h))
918                        .overflow_hidden()
919                        .children(self.delegate.render_header(window, cx))
920                        .child(self.render_element_container(cx))
921                        .on_hover(cx.listener(|this, hovered, window, cx| {
922                            if *hovered {
923                                this.scrollbar_visibility = true;
924                                this.hide_scrollbar_task.take();
925                                cx.notify();
926                            } else if !this.focus_handle.contains_focused(window, cx) {
927                                this.hide_scrollbar(cx);
928                            }
929                        }))
930                        .when_some(self.render_scrollbar(cx), |div, scrollbar| {
931                            div.child(scrollbar)
932                        }),
933                )
934            })
935            .when(self.delegate.match_count() == 0, |el| {
936                el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
937                    el.child(
938                        v_flex().flex_grow().py_2().child(
939                            ListItem::new("empty_state")
940                                .inset(true)
941                                .spacing(ListItemSpacing::Sparse)
942                                .disabled(true)
943                                .child(Label::new(text).color(Color::Muted)),
944                        ),
945                    )
946                })
947            })
948            .children(self.delegate.render_footer(window, cx))
949            .children(match &self.head {
950                Head::Editor(editor) => {
951                    if editor_position == PickerEditorPosition::End {
952                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
953                    } else {
954                        None
955                    }
956                }
957                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
958            })
959    }
960}