picker.rs

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