picker.rs

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