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