picker_prompt.rs

  1use anyhow::{anyhow, Result};
  2use futures::channel::oneshot;
  3use fuzzy::{StringMatch, StringMatchCandidate};
  4
  5use core::cmp;
  6use gpui::{
  7    rems, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  8    InteractiveElement, IntoElement, ParentElement, Render, SharedString, Styled, Subscription,
  9    Task, WeakEntity, Window,
 10};
 11use picker::{Picker, PickerDelegate};
 12use std::sync::Arc;
 13use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
 14use util::ResultExt;
 15use workspace::{ModalView, Workspace};
 16
 17pub struct PickerPrompt {
 18    pub picker: Entity<Picker<PickerPromptDelegate>>,
 19    rem_width: f32,
 20    _subscription: Subscription,
 21}
 22
 23pub fn prompt(
 24    prompt: &str,
 25    options: Vec<SharedString>,
 26    workspace: WeakEntity<Workspace>,
 27    window: &mut Window,
 28    cx: &mut App,
 29) -> Task<Result<Option<usize>>> {
 30    if options.is_empty() {
 31        return Task::ready(Err(anyhow!("No options")));
 32    }
 33    let prompt = prompt.to_string().into();
 34
 35    window.spawn(cx, |mut cx| async move {
 36        // Modal branch picker has a longer trailoff than a popover one.
 37        let (tx, rx) = oneshot::channel();
 38        let delegate = PickerPromptDelegate::new(prompt, options, tx, 70);
 39
 40        workspace.update_in(&mut cx, |workspace, window, cx| {
 41            workspace.toggle_modal(window, cx, |window, cx| {
 42                PickerPrompt::new(delegate, 34., window, cx)
 43            })
 44        })?;
 45
 46        match rx.await {
 47            Ok(selection) => Some(selection).transpose(),
 48            Err(_) => anyhow::Ok(None), // User cancelled
 49        }
 50    })
 51}
 52
 53impl PickerPrompt {
 54    fn new(
 55        delegate: PickerPromptDelegate,
 56        rem_width: f32,
 57        window: &mut Window,
 58        cx: &mut Context<Self>,
 59    ) -> Self {
 60        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
 61        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
 62        Self {
 63            picker,
 64            rem_width,
 65            _subscription,
 66        }
 67    }
 68}
 69impl ModalView for PickerPrompt {}
 70impl EventEmitter<DismissEvent> for PickerPrompt {}
 71
 72impl Focusable for PickerPrompt {
 73    fn focus_handle(&self, cx: &App) -> FocusHandle {
 74        self.picker.focus_handle(cx)
 75    }
 76}
 77
 78impl Render for PickerPrompt {
 79    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 80        v_flex()
 81            .w(rems(self.rem_width))
 82            .child(self.picker.clone())
 83            .on_mouse_down_out(cx.listener(|this, _, window, cx| {
 84                this.picker.update(cx, |this, cx| {
 85                    this.cancel(&Default::default(), window, cx);
 86                })
 87            }))
 88    }
 89}
 90
 91pub struct PickerPromptDelegate {
 92    prompt: Arc<str>,
 93    matches: Vec<StringMatch>,
 94    all_options: Vec<SharedString>,
 95    selected_index: usize,
 96    max_match_length: usize,
 97    tx: Option<oneshot::Sender<Result<usize>>>,
 98}
 99
100impl PickerPromptDelegate {
101    pub fn new(
102        prompt: Arc<str>,
103        options: Vec<SharedString>,
104        tx: oneshot::Sender<Result<usize>>,
105        max_chars: usize,
106    ) -> Self {
107        Self {
108            prompt,
109            all_options: options,
110            matches: vec![],
111            selected_index: 0,
112            max_match_length: max_chars,
113            tx: Some(tx),
114        }
115    }
116}
117
118impl PickerDelegate for PickerPromptDelegate {
119    type ListItem = ListItem;
120
121    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
122        self.prompt.clone()
123    }
124
125    fn match_count(&self) -> usize {
126        self.matches.len()
127    }
128
129    fn selected_index(&self) -> usize {
130        self.selected_index
131    }
132
133    fn set_selected_index(
134        &mut self,
135        ix: usize,
136        _window: &mut Window,
137        _: &mut Context<Picker<Self>>,
138    ) {
139        self.selected_index = ix;
140    }
141
142    fn update_matches(
143        &mut self,
144        query: String,
145        window: &mut Window,
146        cx: &mut Context<Picker<Self>>,
147    ) -> Task<()> {
148        cx.spawn_in(window, move |picker, mut cx| async move {
149            let candidates = picker.update(&mut cx, |picker, _| {
150                picker
151                    .delegate
152                    .all_options
153                    .iter()
154                    .enumerate()
155                    .map(|(ix, option)| StringMatchCandidate::new(ix, &option))
156                    .collect::<Vec<StringMatchCandidate>>()
157            });
158            let Some(candidates) = candidates.log_err() else {
159                return;
160            };
161            let matches: Vec<StringMatch> = if query.is_empty() {
162                candidates
163                    .into_iter()
164                    .enumerate()
165                    .map(|(index, candidate)| StringMatch {
166                        candidate_id: index,
167                        string: candidate.string,
168                        positions: Vec::new(),
169                        score: 0.0,
170                    })
171                    .collect()
172            } else {
173                fuzzy::match_strings(
174                    &candidates,
175                    &query,
176                    true,
177                    10000,
178                    &Default::default(),
179                    cx.background_executor().clone(),
180                )
181                .await
182            };
183            picker
184                .update(&mut cx, |picker, _| {
185                    let delegate = &mut picker.delegate;
186                    delegate.matches = matches;
187                    if delegate.matches.is_empty() {
188                        delegate.selected_index = 0;
189                    } else {
190                        delegate.selected_index =
191                            cmp::min(delegate.selected_index, delegate.matches.len() - 1);
192                    }
193                })
194                .log_err();
195        })
196    }
197
198    fn confirm(&mut self, _: bool, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
199        let Some(option) = self.matches.get(self.selected_index()) else {
200            return;
201        };
202
203        self.tx.take().map(|tx| tx.send(Ok(option.candidate_id)));
204        cx.emit(DismissEvent);
205    }
206
207    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
208        cx.emit(DismissEvent);
209    }
210
211    fn render_match(
212        &self,
213        ix: usize,
214        selected: bool,
215        _window: &mut Window,
216        _cx: &mut Context<Picker<Self>>,
217    ) -> Option<Self::ListItem> {
218        let hit = &self.matches[ix];
219        let shortened_option = util::truncate_and_trailoff(&hit.string, self.max_match_length);
220
221        Some(
222            ListItem::new(SharedString::from(format!("picker-prompt-menu-{ix}")))
223                .inset(true)
224                .spacing(ListItemSpacing::Sparse)
225                .toggle_state(selected)
226                .map(|el| {
227                    let highlights: Vec<_> = hit
228                        .positions
229                        .iter()
230                        .filter(|index| index < &&self.max_match_length)
231                        .copied()
232                        .collect();
233
234                    el.child(HighlightedLabel::new(shortened_option, highlights))
235                }),
236        )
237    }
238}