picker.rs

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