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(&mut self, cx: &mut ViewContext<Self>) {
429        let query = self.query(cx);
430        self.update_matches(query, cx);
431    }
432
433    pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
434        let delegate_pending_update_matches = self.delegate.update_matches(query, cx);
435
436        self.matches_updated(cx);
437        // This struct ensures that we can synchronously drop the task returned by the
438        // delegate's `update_matches` method and the task that the picker is spawning.
439        // If we simply capture the delegate's task into the picker's task, when the picker's
440        // task gets synchronously dropped, the delegate's task would keep running until
441        // the picker's task has a chance of being scheduled, because dropping a task happens
442        // asynchronously.
443        self.pending_update_matches = Some(PendingUpdateMatches {
444            delegate_update_matches: Some(delegate_pending_update_matches),
445            _task: cx.spawn(|this, mut cx| async move {
446                let delegate_pending_update_matches = this.update(&mut cx, |this, _| {
447                    this.pending_update_matches
448                        .as_mut()
449                        .unwrap()
450                        .delegate_update_matches
451                        .take()
452                        .unwrap()
453                })?;
454                delegate_pending_update_matches.await;
455                this.update(&mut cx, |this, cx| {
456                    this.matches_updated(cx);
457                })
458            }),
459        });
460    }
461
462    fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
463        if let ElementContainer::List(state) = &mut self.element_container {
464            state.reset(self.delegate.match_count());
465        }
466
467        let index = self.delegate.selected_index();
468        self.scroll_to_item_index(index);
469        self.pending_update_matches = None;
470        if let Some(secondary) = self.confirm_on_update.take() {
471            self.do_confirm(secondary, cx);
472        }
473        cx.notify();
474    }
475
476    pub fn query(&self, cx: &AppContext) -> String {
477        match &self.head {
478            Head::Editor(editor) => editor.read(cx).text(cx),
479            Head::Empty(_) => "".to_string(),
480        }
481    }
482
483    pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut WindowContext<'_>) {
484        if let Head::Editor(ref editor) = &self.head {
485            editor.update(cx, |editor, cx| {
486                editor.set_text(query, cx);
487                let editor_offset = editor.buffer().read(cx).len(cx);
488                editor.change_selections(Some(Autoscroll::Next), cx, |s| {
489                    s.select_ranges(Some(editor_offset..editor_offset))
490                });
491            });
492        }
493    }
494
495    fn scroll_to_item_index(&mut self, ix: usize) {
496        match &mut self.element_container {
497            ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
498            ElementContainer::UniformList(scroll_handle) => {
499                scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
500            }
501        }
502    }
503
504    fn render_element(&self, cx: &mut ViewContext<Self>, ix: usize) -> impl IntoElement {
505        div()
506            .id(("item", ix))
507            .cursor_pointer()
508            .on_click(cx.listener(move |this, event: &ClickEvent, cx| {
509                this.handle_click(ix, event.down.modifiers.secondary(), cx)
510            }))
511            // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
512            // and produces right mouse button events. This matches platforms norms
513            // but means that UIs which depend on holding ctrl down (such as the tab
514            // switcher) can't be clicked on. Hence, this handler.
515            .on_mouse_up(
516                MouseButton::Right,
517                cx.listener(move |this, event: &MouseUpEvent, cx| {
518                    // We specifically want to use the platform key here, as
519                    // ctrl will already be held down for the tab switcher.
520                    this.handle_click(ix, event.modifiers.platform, cx)
521                }),
522            )
523            .children(
524                self.delegate
525                    .render_match(ix, ix == self.delegate.selected_index(), cx),
526            )
527            .when(
528                self.delegate.separators_after_indices().contains(&ix),
529                |picker| {
530                    picker
531                        .border_color(cx.theme().colors().border_variant)
532                        .border_b_1()
533                        .py(px(-1.0))
534                },
535            )
536    }
537
538    fn render_element_container(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
539        let sizing_behavior = if self.max_height.is_some() {
540            ListSizingBehavior::Infer
541        } else {
542            ListSizingBehavior::Auto
543        };
544        match &self.element_container {
545            ElementContainer::UniformList(scroll_handle) => uniform_list(
546                cx.view().clone(),
547                "candidates",
548                self.delegate.match_count(),
549                move |picker, visible_range, cx| {
550                    visible_range
551                        .map(|ix| picker.render_element(cx, ix))
552                        .collect()
553                },
554            )
555            .with_sizing_behavior(sizing_behavior)
556            .flex_grow()
557            .py_1()
558            .track_scroll(scroll_handle.clone())
559            .into_any_element(),
560            ElementContainer::List(state) => list(state.clone())
561                .with_sizing_behavior(sizing_behavior)
562                .flex_grow()
563                .py_2()
564                .into_any_element(),
565        }
566    }
567
568    #[cfg(any(test, feature = "test-support"))]
569    pub fn logical_scroll_top_index(&self) -> usize {
570        match &self.element_container {
571            ElementContainer::List(state) => state.logical_scroll_top().item_ix,
572            ElementContainer::UniformList(scroll_handle) => {
573                scroll_handle.logical_scroll_top_index()
574            }
575        }
576    }
577}
578
579impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
580impl<D: PickerDelegate> ModalView for Picker<D> {}
581
582impl<D: PickerDelegate> Render for Picker<D> {
583    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
584        let editor_position = self.delegate.editor_position();
585
586        v_flex()
587            .key_context("Picker")
588            .size_full()
589            .when_some(self.width, |el, width| el.w(width))
590            .overflow_hidden()
591            // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
592            // as a part of a modal rather than the entire modal.
593            //
594            // We should revisit how the `Picker` is styled to make it more composable.
595            .when(self.is_modal, |this| this.elevation_3(cx))
596            .on_action(cx.listener(Self::select_next))
597            .on_action(cx.listener(Self::select_prev))
598            .on_action(cx.listener(Self::select_first))
599            .on_action(cx.listener(Self::select_last))
600            .on_action(cx.listener(Self::cancel))
601            .on_action(cx.listener(Self::confirm))
602            .on_action(cx.listener(Self::secondary_confirm))
603            .on_action(cx.listener(Self::confirm_completion))
604            .on_action(cx.listener(Self::confirm_input))
605            .children(match &self.head {
606                Head::Editor(editor) => {
607                    if editor_position == PickerEditorPosition::Start {
608                        Some(self.delegate.render_editor(&editor.clone(), cx))
609                    } else {
610                        None
611                    }
612                }
613                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
614            })
615            .when(self.delegate.match_count() > 0, |el| {
616                el.child(
617                    v_flex()
618                        .flex_grow()
619                        .when_some(self.max_height, |div, max_h| div.max_h(max_h))
620                        .overflow_hidden()
621                        .children(self.delegate.render_header(cx))
622                        .child(self.render_element_container(cx)),
623                )
624            })
625            .when(self.delegate.match_count() == 0, |el| {
626                el.child(
627                    v_flex().flex_grow().py_2().child(
628                        ListItem::new("empty_state")
629                            .inset(true)
630                            .spacing(ListItemSpacing::Sparse)
631                            .disabled(true)
632                            .child(
633                                Label::new(self.delegate.no_matches_text(cx)).color(Color::Muted),
634                            ),
635                    ),
636                )
637            })
638            .children(self.delegate.render_footer(cx))
639            .children(match &self.head {
640                Head::Editor(editor) => {
641                    if editor_position == PickerEditorPosition::End {
642                        Some(self.delegate.render_editor(&editor.clone(), cx))
643                    } else {
644                        None
645                    }
646                }
647                Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
648            })
649    }
650}