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