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, [ConfirmCompletion]);
 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    /// Override if you want to have <enter> update the query instead of confirming.
 91    fn confirm_update_query(&mut self, _cx: &mut ViewContext<Picker<Self>>) -> Option<String> {
 92        None
 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 confirm_completion(&self, _query: String) -> 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_3()
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 confirm_completion(&mut self, _: &ConfirmCompletion, cx: &mut ViewContext<Self>) {
353        if let Some(new_query) = self.delegate.confirm_completion(self.query(cx)) {
354            self.set_query(new_query, cx);
355        } else {
356            cx.propagate()
357        }
358    }
359
360    fn handle_click(&mut self, ix: usize, secondary: bool, cx: &mut ViewContext<Self>) {
361        cx.stop_propagation();
362        cx.prevent_default();
363        self.set_selected_index(ix, false, cx);
364        self.do_confirm(secondary, cx)
365    }
366
367    fn do_confirm(&mut self, secondary: bool, cx: &mut ViewContext<Self>) {
368        if let Some(update_query) = self.delegate.confirm_update_query(cx) {
369            self.set_query(update_query, cx);
370            self.delegate.set_selected_index(0, cx);
371        } else {
372            self.delegate.confirm(secondary, cx)
373        }
374    }
375
376    fn on_input_editor_event(
377        &mut self,
378        _: View<Editor>,
379        event: &editor::EditorEvent,
380        cx: &mut ViewContext<Self>,
381    ) {
382        let Head::Editor(ref editor) = &self.head else {
383            panic!("unexpected call");
384        };
385        match event {
386            editor::EditorEvent::BufferEdited => {
387                let query = editor.read(cx).text(cx);
388                self.update_matches(query, cx);
389            }
390            editor::EditorEvent::Blurred => {
391                self.cancel(&menu::Cancel, cx);
392            }
393            _ => {}
394        }
395    }
396
397    fn on_empty_head_blur(&mut self, cx: &mut ViewContext<Self>) {
398        let Head::Empty(_) = &self.head else {
399            panic!("unexpected call");
400        };
401        self.cancel(&menu::Cancel, cx);
402    }
403
404    pub fn refresh(&mut self, cx: &mut ViewContext<Self>) {
405        let query = self.query(cx);
406        self.update_matches(query, cx);
407    }
408
409    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
410        let delegate_pending_update_matches = self.delegate.update_matches(query, cx);
411
412        self.matches_updated(cx);
413        // This struct ensures that we can synchronously drop the task returned by the
414        // delegate's `update_matches` method and the task that the picker is spawning.
415        // If we simply capture the delegate's task into the picker's task, when the picker's
416        // task gets synchronously dropped, the delegate's task would keep running until
417        // the picker's task has a chance of being scheduled, because dropping a task happens
418        // asynchronously.
419        self.pending_update_matches = Some(PendingUpdateMatches {
420            delegate_update_matches: Some(delegate_pending_update_matches),
421            _task: cx.spawn(|this, mut cx| async move {
422                let delegate_pending_update_matches = this.update(&mut cx, |this, _| {
423                    this.pending_update_matches
424                        .as_mut()
425                        .unwrap()
426                        .delegate_update_matches
427                        .take()
428                        .unwrap()
429                })?;
430                delegate_pending_update_matches.await;
431                this.update(&mut cx, |this, cx| {
432                    this.matches_updated(cx);
433                })
434            }),
435        });
436    }
437
438    fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
439        if let ElementContainer::List(state) = &mut self.element_container {
440            state.reset(self.delegate.match_count());
441        }
442
443        let index = self.delegate.selected_index();
444        self.scroll_to_item_index(index);
445        self.pending_update_matches = None;
446        if let Some(secondary) = self.confirm_on_update.take() {
447            self.do_confirm(secondary, cx);
448        }
449        cx.notify();
450    }
451
452    pub fn query(&self, cx: &AppContext) -> String {
453        match &self.head {
454            Head::Editor(editor) => editor.read(cx).text(cx),
455            Head::Empty(_) => "".to_string(),
456        }
457    }
458
459    pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
460        if let Head::Editor(ref editor) = &self.head {
461            editor.update(cx, |editor, cx| {
462                editor.set_text(query, cx);
463                let editor_offset = editor.buffer().read(cx).len(cx);
464                editor.change_selections(Some(Autoscroll::Next), cx, |s| {
465                    s.select_ranges(Some(editor_offset..editor_offset))
466                });
467            });
468        }
469    }
470
471    fn scroll_to_item_index(&mut self, ix: usize) {
472        match &mut self.element_container {
473            ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
474            ElementContainer::UniformList(scroll_handle) => scroll_handle.scroll_to_item(ix),
475        }
476    }
477
478    fn render_element(&self, cx: &mut ViewContext<Self>, ix: usize) -> impl IntoElement {
479        div()
480            .id(("item", ix))
481            .cursor_pointer()
482            .on_click(cx.listener(move |this, event: &ClickEvent, cx| {
483                this.handle_click(ix, event.down.modifiers.secondary(), cx)
484            }))
485            // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
486            // and produces right mouse button events. This matches platforms norms
487            // but means that UIs which depend on holding ctrl down (such as the tab
488            // switcher) can't be clicked on. Hence, this handler.
489            .on_mouse_up(
490                MouseButton::Right,
491                cx.listener(move |this, event: &MouseUpEvent, cx| {
492                    // We specficially want to use the platform key here, as
493                    // ctrl will already be held down for the tab switcher.
494                    this.handle_click(ix, event.modifiers.platform, cx)
495                }),
496            )
497            .children(
498                self.delegate
499                    .render_match(ix, ix == self.delegate.selected_index(), cx),
500            )
501            .when(
502                self.delegate.separators_after_indices().contains(&ix),
503                |picker| {
504                    picker
505                        .border_color(cx.theme().colors().border_variant)
506                        .border_b_1()
507                        .pb(px(-1.0))
508                },
509            )
510    }
511
512    fn render_element_container(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
513        let sizing_behavior = if self.max_height.is_some() {
514            ListSizingBehavior::Infer
515        } else {
516            ListSizingBehavior::Auto
517        };
518        match &self.element_container {
519            ElementContainer::UniformList(scroll_handle) => uniform_list(
520                cx.view().clone(),
521                "candidates",
522                self.delegate.match_count(),
523                move |picker, visible_range, cx| {
524                    visible_range
525                        .map(|ix| picker.render_element(cx, ix))
526                        .collect()
527                },
528            )
529            .with_sizing_behavior(sizing_behavior)
530            .flex_grow()
531            .py_1()
532            .track_scroll(scroll_handle.clone())
533            .into_any_element(),
534            ElementContainer::List(state) => list(state.clone())
535                .with_sizing_behavior(sizing_behavior)
536                .flex_grow()
537                .py_2()
538                .into_any_element(),
539        }
540    }
541
542    #[cfg(any(test, feature = "test-support"))]
543    pub fn logical_scroll_top_index(&self) -> usize {
544        match &self.element_container {
545            ElementContainer::List(state) => state.logical_scroll_top().item_ix,
546            ElementContainer::UniformList(scroll_handle) => {
547                scroll_handle.logical_scroll_top_index()
548            }
549        }
550    }
551}
552
553impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
554impl<D: PickerDelegate> ModalView for Picker<D> {}
555
556impl<D: PickerDelegate> Render for Picker<D> {
557    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
558        v_flex()
559            .key_context("Picker")
560            .size_full()
561            .when_some(self.width, |el, width| el.w(width))
562            .overflow_hidden()
563            // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
564            // as a part of a modal rather than the entire modal.
565            //
566            // We should revisit how the `Picker` is styled to make it more composable.
567            .when(self.is_modal, |this| this.elevation_3(cx))
568            .on_action(cx.listener(Self::select_next))
569            .on_action(cx.listener(Self::select_prev))
570            .on_action(cx.listener(Self::select_first))
571            .on_action(cx.listener(Self::select_last))
572            .on_action(cx.listener(Self::cancel))
573            .on_action(cx.listener(Self::confirm))
574            .on_action(cx.listener(Self::secondary_confirm))
575            .on_action(cx.listener(Self::confirm_completion))
576            .on_action(cx.listener(Self::confirm_input))
577            .child(match &self.head {
578                Head::Editor(editor) => self.delegate.render_editor(&editor.clone(), cx),
579                Head::Empty(empty_head) => div().child(empty_head.clone()),
580            })
581            .when(self.delegate.match_count() > 0, |el| {
582                el.child(
583                    v_flex()
584                        .flex_grow()
585                        .when_some(self.max_height, |div, max_h| div.max_h(max_h))
586                        .overflow_hidden()
587                        .children(self.delegate.render_header(cx))
588                        .child(self.render_element_container(cx)),
589                )
590            })
591            .when(self.delegate.match_count() == 0, |el| {
592                el.child(
593                    v_flex().flex_grow().py_2().child(
594                        ListItem::new("empty_state")
595                            .inset(true)
596                            .spacing(ListItemSpacing::Sparse)
597                            .disabled(true)
598                            .child(
599                                Label::new(self.delegate.no_matches_text(cx)).color(Color::Muted),
600                            ),
601                    ),
602                )
603            })
604            .children(self.delegate.render_footer(cx))
605    }
606}