picker.rs

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