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 list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
282        let head = Head::editor(
283            delegate.placeholder_text(window, cx),
284            Self::on_input_editor_event,
285            window,
286            cx,
287        );
288
289        Self::new(delegate, ContainerKind::List, head, window, cx)
290    }
291
292    fn new(
293        delegate: D,
294        container: ContainerKind,
295        head: Head,
296        window: &mut Window,
297        cx: &mut Context<Self>,
298    ) -> Self {
299        let element_container = Self::create_element_container(container);
300        let mut this = Self {
301            delegate,
302            head,
303            element_container,
304            pending_update_matches: None,
305            confirm_on_update: None,
306            width: None,
307            widest_item: None,
308            max_height: Some(rems(18.).into()),
309            show_scrollbar: false,
310            is_modal: true,
311        };
312        this.update_matches("".to_string(), window, cx);
313        // give the delegate 4ms to render the first set of suggestions.
314        this.delegate
315            .finalize_update_matches("".to_string(), Duration::from_millis(4), window, cx);
316        this
317    }
318
319    fn create_element_container(container: ContainerKind) -> ElementContainer {
320        match container {
321            ContainerKind::UniformList => {
322                ElementContainer::UniformList(UniformListScrollHandle::new())
323            }
324            ContainerKind::List => {
325                ElementContainer::List(ListState::new(0, gpui::ListAlignment::Top, px(1000.)))
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 const fn widest_item(mut self, ix: Option<usize>) -> Self {
336        self.widest_item = ix;
337        self
338    }
339
340    pub const fn max_height(mut self, max_height: Option<gpui::Length>) -> Self {
341        self.max_height = max_height;
342        self
343    }
344
345    pub const fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
346        self.show_scrollbar = show_scrollbar;
347        self
348    }
349
350    pub const fn modal(mut self, modal: bool) -> Self {
351        self.is_modal = modal;
352        self
353    }
354
355    pub fn focus(&self, window: &mut Window, cx: &mut App) {
356        self.focus_handle(cx).focus(window);
357    }
358
359    /// Handles the selecting an index, and passing the change to the delegate.
360    /// If `fallback_direction` is set to `None`, the index will not be selected
361    /// if the element at that index cannot be selected.
362    /// If `fallback_direction` is set to
363    /// `Some(..)`, the next selectable element will be selected in the
364    /// specified direction (Down or Up), cycling through all elements until
365    /// finding one that can be selected or returning if there are no selectable elements.
366    /// If `scroll_to_index` is true, the new selected index will be scrolled into
367    /// view.
368    ///
369    /// If some effect is bound to `selected_index_changed`, it will be executed.
370    pub fn set_selected_index(
371        &mut self,
372        mut ix: usize,
373        fallback_direction: Option<Direction>,
374        scroll_to_index: bool,
375        window: &mut Window,
376        cx: &mut Context<Self>,
377    ) {
378        let match_count = self.delegate.match_count();
379        if match_count == 0 {
380            return;
381        }
382
383        if let Some(bias) = fallback_direction {
384            let mut curr_ix = ix;
385            while !self.delegate.can_select(curr_ix, window, cx) {
386                curr_ix = match bias {
387                    Direction::Down => {
388                        if curr_ix == match_count - 1 {
389                            0
390                        } else {
391                            curr_ix + 1
392                        }
393                    }
394                    Direction::Up => {
395                        if curr_ix == 0 {
396                            match_count - 1
397                        } else {
398                            curr_ix - 1
399                        }
400                    }
401                };
402                // There is no item that can be selected
403                if ix == curr_ix {
404                    return;
405                }
406            }
407            ix = curr_ix;
408        } else if !self.delegate.can_select(ix, window, cx) {
409            return;
410        }
411
412        let previous_index = self.delegate.selected_index();
413        self.delegate.set_selected_index(ix, window, cx);
414        let current_index = self.delegate.selected_index();
415
416        if previous_index != current_index {
417            if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) {
418                action(window, cx);
419            }
420            if scroll_to_index {
421                self.scroll_to_item_index(ix);
422            }
423        }
424    }
425
426    pub fn select_next(
427        &mut self,
428        _: &menu::SelectNext,
429        window: &mut Window,
430        cx: &mut Context<Self>,
431    ) {
432        let count = self.delegate.match_count();
433        if count > 0 {
434            let index = self.delegate.selected_index();
435            let ix = if index == count - 1 { 0 } else { index + 1 };
436            self.set_selected_index(ix, Some(Direction::Down), true, window, cx);
437            cx.notify();
438        }
439    }
440
441    pub fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
442        self.select_previous(&Default::default(), window, cx);
443    }
444
445    fn select_previous(
446        &mut self,
447        _: &menu::SelectPrevious,
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 == 0 { count - 1 } else { index - 1 };
455            self.set_selected_index(ix, Some(Direction::Up), true, window, cx);
456            cx.notify();
457        }
458    }
459
460    pub fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
461        self.select_next(&Default::default(), window, cx);
462    }
463
464    pub fn select_first(
465        &mut self,
466        _: &menu::SelectFirst,
467        window: &mut Window,
468        cx: &mut Context<Self>,
469    ) {
470        let count = self.delegate.match_count();
471        if count > 0 {
472            self.set_selected_index(0, Some(Direction::Down), true, window, cx);
473            cx.notify();
474        }
475    }
476
477    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
478        let count = self.delegate.match_count();
479        if count > 0 {
480            self.set_selected_index(count - 1, Some(Direction::Up), true, window, cx);
481            cx.notify();
482        }
483    }
484
485    pub fn cycle_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
486        let count = self.delegate.match_count();
487        let index = self.delegate.selected_index();
488        let new_index = if index + 1 == count { 0 } else { index + 1 };
489        self.set_selected_index(new_index, Some(Direction::Down), true, window, cx);
490        cx.notify();
491    }
492
493    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
494        if self.delegate.should_dismiss() {
495            self.delegate.dismissed(window, cx);
496            cx.emit(DismissEvent);
497        }
498    }
499
500    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
501        if self.pending_update_matches.is_some()
502            && !self.delegate.finalize_update_matches(
503                self.query(cx),
504                Duration::from_millis(16),
505                window,
506                cx,
507            )
508        {
509            self.confirm_on_update = Some(false)
510        } else {
511            self.pending_update_matches.take();
512            self.do_confirm(false, window, cx);
513        }
514    }
515
516    fn secondary_confirm(
517        &mut self,
518        _: &menu::SecondaryConfirm,
519        window: &mut Window,
520        cx: &mut Context<Self>,
521    ) {
522        if self.pending_update_matches.is_some()
523            && !self.delegate.finalize_update_matches(
524                self.query(cx),
525                Duration::from_millis(16),
526                window,
527                cx,
528            )
529        {
530            self.confirm_on_update = Some(true)
531        } else {
532            self.do_confirm(true, window, cx);
533        }
534    }
535
536    fn confirm_input(&mut self, input: &ConfirmInput, window: &mut Window, cx: &mut Context<Self>) {
537        self.delegate.confirm_input(input.secondary, window, cx);
538    }
539
540    fn confirm_completion(
541        &mut self,
542        _: &ConfirmCompletion,
543        window: &mut Window,
544        cx: &mut Context<Self>,
545    ) {
546        if let Some(new_query) = self.delegate.confirm_completion(self.query(cx), window, cx) {
547            self.set_query(new_query, window, cx);
548        } else {
549            cx.propagate()
550        }
551    }
552
553    fn handle_click(
554        &mut self,
555        ix: usize,
556        secondary: bool,
557        window: &mut Window,
558        cx: &mut Context<Self>,
559    ) {
560        cx.stop_propagation();
561        window.prevent_default();
562        self.set_selected_index(ix, None, false, window, cx);
563        self.do_confirm(secondary, window, cx)
564    }
565
566    fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {
567        if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {
568            self.set_query(update_query, window, cx);
569            self.set_selected_index(0, Some(Direction::Down), false, window, cx);
570        } else {
571            self.delegate.confirm(secondary, window, cx)
572        }
573    }
574
575    fn on_input_editor_event(
576        &mut self,
577        _: &Entity<Editor>,
578        event: &editor::EditorEvent,
579        window: &mut Window,
580        cx: &mut Context<Self>,
581    ) {
582        let Head::Editor(editor) = &self.head else {
583            panic!("unexpected call");
584        };
585        match event {
586            editor::EditorEvent::BufferEdited => {
587                let query = editor.read(cx).text(cx);
588                self.update_matches(query, window, cx);
589            }
590            editor::EditorEvent::Blurred => {
591                if self.is_modal {
592                    self.cancel(&menu::Cancel, window, cx);
593                }
594            }
595            _ => {}
596        }
597    }
598
599    fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
600        let Head::Empty(_) = &self.head else {
601            panic!("unexpected call");
602        };
603        self.cancel(&menu::Cancel, window, cx);
604    }
605
606    pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
607        match &self.head {
608            Head::Editor(editor) => {
609                let placeholder = self.delegate.placeholder_text(window, cx);
610                editor.update(cx, |editor, cx| {
611                    editor.set_placeholder_text(placeholder.as_ref(), window, cx);
612                    cx.notify();
613                });
614            }
615            Head::Empty(_) => {}
616        }
617    }
618
619    pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
620        let query = self.query(cx);
621        self.update_matches(query, window, cx);
622    }
623
624    pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
625        let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
626
627        self.matches_updated(window, cx);
628        // This struct ensures that we can synchronously drop the task returned by the
629        // delegate's `update_matches` method and the task that the picker is spawning.
630        // If we simply capture the delegate's task into the picker's task, when the picker's
631        // task gets synchronously dropped, the delegate's task would keep running until
632        // the picker's task has a chance of being scheduled, because dropping a task happens
633        // asynchronously.
634        self.pending_update_matches = Some(PendingUpdateMatches {
635            delegate_update_matches: Some(delegate_pending_update_matches),
636            _task: cx.spawn_in(window, async move |this, cx| {
637                let delegate_pending_update_matches = this.update(cx, |this, _| {
638                    this.pending_update_matches
639                        .as_mut()
640                        .unwrap()
641                        .delegate_update_matches
642                        .take()
643                        .unwrap()
644                })?;
645                delegate_pending_update_matches.await;
646                this.update_in(cx, |this, window, cx| {
647                    this.matches_updated(window, cx);
648                })
649            }),
650        });
651    }
652
653    fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
654        if let ElementContainer::List(state) = &mut self.element_container {
655            state.reset(self.delegate.match_count());
656        }
657
658        let index = self.delegate.selected_index();
659        self.scroll_to_item_index(index);
660        self.pending_update_matches = None;
661        if let Some(secondary) = self.confirm_on_update.take() {
662            self.do_confirm(secondary, window, cx);
663        }
664        cx.notify();
665    }
666
667    pub fn query(&self, cx: &App) -> String {
668        match &self.head {
669            Head::Editor(editor) => editor.read(cx).text(cx),
670            Head::Empty(_) => "".to_string(),
671        }
672    }
673
674    pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
675        if let Head::Editor(editor) = &self.head {
676            editor.update(cx, |editor, cx| {
677                editor.set_text(query, window, cx);
678                let editor_offset = editor.buffer().read(cx).len(cx);
679                editor.change_selections(
680                    SelectionEffects::scroll(Autoscroll::Next),
681                    window,
682                    cx,
683                    |s| s.select_ranges(Some(editor_offset..editor_offset)),
684                );
685            });
686        }
687    }
688
689    fn scroll_to_item_index(&mut self, ix: usize) {
690        match &mut self.element_container {
691            ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
692            ElementContainer::UniformList(scroll_handle) => {
693                scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
694            }
695        }
696    }
697
698    fn render_element(
699        &self,
700        window: &mut Window,
701        cx: &mut Context<Self>,
702        ix: usize,
703    ) -> impl IntoElement + use<D> {
704        div()
705            .id(("item", ix))
706            .cursor_pointer()
707            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
708                this.handle_click(ix, event.modifiers().secondary(), window, cx)
709            }))
710            // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
711            // and produces right mouse button events. This matches platforms norms
712            // but means that UIs which depend on holding ctrl down (such as the tab
713            // switcher) can't be clicked on. Hence, this handler.
714            .on_mouse_up(
715                MouseButton::Right,
716                cx.listener(move |this, event: &MouseUpEvent, window, cx| {
717                    // We specifically want to use the platform key here, as
718                    // ctrl will already be held down for the tab switcher.
719                    this.handle_click(ix, event.modifiers.platform, window, cx)
720                }),
721            )
722            .children(self.delegate.render_match(
723                ix,
724                ix == self.delegate.selected_index(),
725                window,
726                cx,
727            ))
728            .when(
729                self.delegate.separators_after_indices().contains(&ix),
730                |picker| {
731                    picker
732                        .border_color(cx.theme().colors().border_variant)
733                        .border_b_1()
734                        .py(px(-1.0))
735                },
736            )
737    }
738
739    fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
740        let sizing_behavior = if self.max_height.is_some() {
741            ListSizingBehavior::Infer
742        } else {
743            ListSizingBehavior::Auto
744        };
745
746        match &self.element_container {
747            ElementContainer::UniformList(scroll_handle) => uniform_list(
748                "candidates",
749                self.delegate.match_count(),
750                cx.processor(move |picker, visible_range: Range<usize>, window, cx| {
751                    visible_range
752                        .map(|ix| picker.render_element(window, cx, ix))
753                        .collect()
754                }),
755            )
756            .with_sizing_behavior(sizing_behavior)
757            .when_some(self.widest_item, |el, widest_item| {
758                el.with_width_from_item(Some(widest_item))
759            })
760            .flex_grow()
761            .py_1()
762            .track_scroll(scroll_handle.clone())
763            .into_any_element(),
764            ElementContainer::List(state) => list(
765                state.clone(),
766                cx.processor(|this, ix, window, cx| {
767                    this.render_element(window, cx, ix).into_any_element()
768                }),
769            )
770            .with_sizing_behavior(sizing_behavior)
771            .flex_grow()
772            .py_2()
773            .into_any_element(),
774        }
775    }
776
777    #[cfg(any(test, feature = "test-support"))]
778    pub fn logical_scroll_top_index(&self) -> usize {
779        match &self.element_container {
780            ElementContainer::List(state) => state.logical_scroll_top().item_ix,
781            ElementContainer::UniformList(scroll_handle) => {
782                scroll_handle.logical_scroll_top_index()
783            }
784        }
785    }
786}
787
788impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
789impl<D: PickerDelegate> ModalView for Picker<D> {}
790
791impl<D: PickerDelegate> Render for Picker<D> {
792    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
793        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
794        let window_size = window.viewport_size();
795        let rem_size = window.rem_size();
796        let is_wide_window = window_size.width / rem_size > rems_from_px(800.).0;
797
798        let aside = self.delegate.documentation_aside(window, cx);
799
800        let editor_position = self.delegate.editor_position();
801        let menu = v_flex()
802            .key_context("Picker")
803            .size_full()
804            .when_some(self.width, |el, width| el.w(width))
805            .overflow_hidden()
806            // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
807            // as a part of a modal rather than the entire modal.
808            //
809            // We should revisit how the `Picker` is styled to make it more composable.
810            .when(self.is_modal, |this| this.elevation_3(cx))
811            .on_action(cx.listener(Self::select_next))
812            .on_action(cx.listener(Self::select_previous))
813            .on_action(cx.listener(Self::editor_move_down))
814            .on_action(cx.listener(Self::editor_move_up))
815            .on_action(cx.listener(Self::select_first))
816            .on_action(cx.listener(Self::select_last))
817            .on_action(cx.listener(Self::cancel))
818            .on_action(cx.listener(Self::confirm))
819            .on_action(cx.listener(Self::secondary_confirm))
820            .on_action(cx.listener(Self::confirm_completion))
821            .on_action(cx.listener(Self::confirm_input))
822            .children(match &self.head {
823                Head::Editor(editor) => {
824                    if editor_position == PickerEditorPosition::Start {
825                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
826                    } else {
827                        None
828                    }
829                }
830                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
831            })
832            .when(self.delegate.match_count() > 0, |el| {
833                el.child(
834                    v_flex()
835                        .id("element-container")
836                        .relative()
837                        .flex_grow()
838                        .when_some(self.max_height, |div, max_h| div.max_h(max_h))
839                        .overflow_hidden()
840                        .children(self.delegate.render_header(window, cx))
841                        .child(self.render_element_container(cx))
842                        .when(self.show_scrollbar, |this| {
843                            let base_scrollbar_config =
844                                Scrollbars::new(ScrollAxes::Vertical).width_sm();
845
846                            this.map(|this| match &self.element_container {
847                                ElementContainer::List(state) => this.custom_scrollbars(
848                                    base_scrollbar_config.tracked_scroll_handle(state.clone()),
849                                    window,
850                                    cx,
851                                ),
852                                ElementContainer::UniformList(state) => this.custom_scrollbars(
853                                    base_scrollbar_config.tracked_scroll_handle(state.clone()),
854                                    window,
855                                    cx,
856                                ),
857                            })
858                        }),
859                )
860            })
861            .when(self.delegate.match_count() == 0, |el| {
862                el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
863                    el.child(
864                        v_flex().flex_grow().py_2().child(
865                            ListItem::new("empty_state")
866                                .inset(true)
867                                .spacing(ListItemSpacing::Sparse)
868                                .disabled(true)
869                                .child(Label::new(text).color(Color::Muted)),
870                        ),
871                    )
872                })
873            })
874            .children(self.delegate.render_footer(window, cx))
875            .children(match &self.head {
876                Head::Editor(editor) => {
877                    if editor_position == PickerEditorPosition::End {
878                        Some(self.delegate.render_editor(&editor.clone(), window, cx))
879                    } else {
880                        None
881                    }
882                }
883                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
884            });
885
886        let Some(aside) = aside else {
887            return menu;
888        };
889
890        let render_aside = |aside: DocumentationAside, cx: &mut Context<Self>| {
891            WithRemSize::new(ui_font_size)
892                .occlude()
893                .elevation_2(cx)
894                .w_full()
895                .p_2()
896                .overflow_hidden()
897                .when(is_wide_window, |this| this.max_w_96())
898                .when(!is_wide_window, |this| this.max_w_48())
899                .child((aside.render)(cx))
900        };
901
902        if is_wide_window {
903            div().relative().child(menu).child(
904                h_flex()
905                    .absolute()
906                    .when(aside.side == DocumentationSide::Left, |this| {
907                        this.right_full().mr_1()
908                    })
909                    .when(aside.side == DocumentationSide::Right, |this| {
910                        this.left_full().ml_1()
911                    })
912                    .when(aside.edge == DocumentationEdge::Top, |this| this.top_0())
913                    .when(aside.edge == DocumentationEdge::Bottom, |this| {
914                        this.bottom_0()
915                    })
916                    .child(render_aside(aside, cx)),
917            )
918        } else {
919            v_flex()
920                .w_full()
921                .gap_1()
922                .justify_end()
923                .child(render_aside(aside, cx))
924                .child(menu)
925        }
926    }
927}