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