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