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