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, Render, Task,
6 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(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 pub fn refresh(&mut self, cx: &mut ViewContext<Self>) {
317 let query = self.query(cx);
318 self.update_matches(query, cx);
319 }
320
321 pub fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) {
322 let delegate_pending_update_matches = self.delegate.update_matches(query, cx);
323
324 self.matches_updated(cx);
325 // This struct ensures that we can synchronously drop the task returned by the
326 // delegate's `update_matches` method and the task that the picker is spawning.
327 // If we simply capture the delegate's task into the picker's task, when the picker's
328 // task gets synchronously dropped, the delegate's task would keep running until
329 // the picker's task has a chance of being scheduled, because dropping a task happens
330 // asynchronously.
331 self.pending_update_matches = Some(PendingUpdateMatches {
332 delegate_update_matches: Some(delegate_pending_update_matches),
333 _task: cx.spawn(|this, mut cx| async move {
334 let delegate_pending_update_matches = this.update(&mut cx, |this, _| {
335 this.pending_update_matches
336 .as_mut()
337 .unwrap()
338 .delegate_update_matches
339 .take()
340 .unwrap()
341 })?;
342 delegate_pending_update_matches.await;
343 this.update(&mut cx, |this, cx| {
344 this.matches_updated(cx);
345 })
346 }),
347 });
348 }
349
350 fn matches_updated(&mut self, cx: &mut ViewContext<Self>) {
351 if let ElementContainer::List(state) = &mut self.element_container {
352 state.reset(self.delegate.match_count());
353 }
354
355 let index = self.delegate.selected_index();
356 self.scroll_to_item_index(index);
357 self.pending_update_matches = None;
358 if let Some(secondary) = self.confirm_on_update.take() {
359 self.delegate.confirm(secondary, cx);
360 }
361 cx.notify();
362 }
363
364 pub fn query(&self, cx: &AppContext) -> String {
365 match &self.head {
366 Head::Editor(editor) => editor.read(cx).text(cx),
367 Head::Empty(_) => "".to_string(),
368 }
369 }
370
371 pub fn set_query(&self, query: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
372 if let Head::Editor(ref editor) = &self.head {
373 editor.update(cx, |editor, cx| {
374 editor.set_text(query, cx);
375 let editor_offset = editor.buffer().read(cx).len(cx);
376 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
377 s.select_ranges(Some(editor_offset..editor_offset))
378 });
379 });
380 }
381 }
382
383 fn scroll_to_item_index(&mut self, ix: usize) {
384 match &mut self.element_container {
385 ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
386 ElementContainer::UniformList(scroll_handle) => scroll_handle.scroll_to_item(ix),
387 }
388 }
389
390 fn render_element(&self, cx: &mut ViewContext<Self>, ix: usize) -> impl IntoElement {
391 div()
392 .id(("item", ix))
393 .cursor_pointer()
394 .on_click(cx.listener(move |this, event: &ClickEvent, cx| {
395 this.handle_click(ix, event.down.modifiers.command, cx)
396 }))
397 .children(
398 self.delegate
399 .render_match(ix, ix == self.delegate.selected_index(), cx),
400 )
401 .when(
402 self.delegate.separators_after_indices().contains(&ix),
403 |picker| {
404 picker
405 .border_color(cx.theme().colors().border_variant)
406 .border_b_1()
407 .pb(px(-1.0))
408 },
409 )
410 }
411
412 fn render_element_container(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
413 match &self.element_container {
414 ElementContainer::UniformList(scroll_handle) => uniform_list(
415 cx.view().clone(),
416 "candidates",
417 self.delegate.match_count(),
418 move |picker, visible_range, cx| {
419 visible_range
420 .map(|ix| picker.render_element(cx, ix))
421 .collect()
422 },
423 )
424 .py_2()
425 .track_scroll(scroll_handle.clone())
426 .into_any_element(),
427 ElementContainer::List(state) => list(state.clone())
428 .with_sizing_behavior(gpui::ListSizingBehavior::Infer)
429 .py_2()
430 .into_any_element(),
431 }
432 }
433}
434
435impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
436impl<D: PickerDelegate> ModalView for Picker<D> {}
437
438impl<D: PickerDelegate> Render for Picker<D> {
439 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
440 div()
441 .key_context("Picker")
442 .size_full()
443 .when_some(self.width, |el, width| el.w(width))
444 .overflow_hidden()
445 // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
446 // as a part of a modal rather than the entire modal.
447 //
448 // We should revisit how the `Picker` is styled to make it more composable.
449 .when(self.is_modal, |this| this.elevation_3(cx))
450 .on_action(cx.listener(Self::select_next))
451 .on_action(cx.listener(Self::select_prev))
452 .on_action(cx.listener(Self::select_first))
453 .on_action(cx.listener(Self::select_last))
454 .on_action(cx.listener(Self::cancel))
455 .on_action(cx.listener(Self::confirm))
456 .on_action(cx.listener(Self::secondary_confirm))
457 .on_action(cx.listener(Self::use_selected_query))
458 .child(match &self.head {
459 Head::Editor(editor) => v_flex()
460 .child(
461 h_flex()
462 .overflow_hidden()
463 .flex_none()
464 .h_9()
465 .px_4()
466 .child(editor.clone()),
467 )
468 .child(Divider::horizontal()),
469 Head::Empty(empty_head) => div().child(empty_head.clone()),
470 })
471 .when(self.delegate.match_count() > 0, |el| {
472 el.child(
473 v_flex()
474 .flex_grow()
475 .max_h(self.max_height.unwrap_or(rems(18.).into()))
476 .overflow_hidden()
477 .children(self.delegate.render_header(cx))
478 .child(self.render_element_container(cx)),
479 )
480 })
481 .when(self.delegate.match_count() == 0, |el| {
482 el.child(
483 v_flex().flex_grow().py_2().child(
484 ListItem::new("empty_state")
485 .inset(true)
486 .spacing(ListItemSpacing::Sparse)
487 .disabled(true)
488 .child(Label::new("No matches").color(Color::Muted)),
489 ),
490 )
491 })
492 .children(self.delegate.render_footer(cx))
493 }
494}