1use anyhow::Result;
2use editor::{
3 Editor,
4 actions::{MoveDown, MoveUp},
5 scroll::Autoscroll,
6};
7use gpui::{
8 AnyElement, App, ClickEvent, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
9 Focusable, Length, ListSizingBehavior, ListState, MouseButton, MouseUpEvent, Render,
10 ScrollStrategy, Stateful, Task, UniformListScrollHandle, Window, actions, div, impl_actions,
11 list, prelude::*, uniform_list,
12};
13use head::Head;
14use schemars::JsonSchema;
15use serde::Deserialize;
16use std::{sync::Arc, time::Duration};
17use ui::{
18 Color, Divider, Label, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, prelude::*, v_flex,
19};
20use util::ResultExt;
21use workspace::ModalView;
22
23mod head;
24pub mod highlighted_match_with_paths;
25
26enum ElementContainer {
27 List(ListState),
28 UniformList(UniformListScrollHandle),
29}
30
31pub enum Direction {
32 Up,
33 Down,
34}
35
36actions!(picker, [ConfirmCompletion]);
37
38/// ConfirmInput is an alternative editor action which - instead of selecting active picker entry - treats pickers editor input literally,
39/// performing some kind of action on it.
40#[derive(Clone, PartialEq, Deserialize, JsonSchema, Default)]
41#[serde(deny_unknown_fields)]
42pub struct ConfirmInput {
43 pub secondary: bool,
44}
45
46impl_actions!(picker, [ConfirmInput]);
47
48struct PendingUpdateMatches {
49 delegate_update_matches: Option<Task<()>>,
50 _task: Task<Result<()>>,
51}
52
53pub struct Picker<D: PickerDelegate> {
54 pub delegate: D,
55 element_container: ElementContainer,
56 head: Head,
57 pending_update_matches: Option<PendingUpdateMatches>,
58 confirm_on_update: Option<bool>,
59 width: Option<Length>,
60 widest_item: Option<usize>,
61 max_height: Option<Length>,
62 focus_handle: FocusHandle,
63 /// An external control to display a scrollbar in the `Picker`.
64 show_scrollbar: bool,
65 /// An internal state that controls whether to show the scrollbar based on the user's focus.
66 scrollbar_visibility: bool,
67 scrollbar_state: ScrollbarState,
68 hide_scrollbar_task: Option<Task<()>>,
69 /// Whether the `Picker` is rendered as a self-contained modal.
70 ///
71 /// Set this to `false` when rendering the `Picker` as part of a larger modal.
72 is_modal: bool,
73}
74
75#[derive(Debug, Default, Clone, Copy, PartialEq)]
76pub enum PickerEditorPosition {
77 #[default]
78 /// Render the editor at the start of the picker. Usually the top
79 Start,
80 /// Render the editor at the end of the picker. Usually the bottom
81 End,
82}
83
84pub trait PickerDelegate: Sized + 'static {
85 type ListItem: IntoElement;
86
87 fn match_count(&self) -> usize;
88 fn selected_index(&self) -> usize;
89 fn separators_after_indices(&self) -> Vec<usize> {
90 Vec::new()
91 }
92 fn set_selected_index(
93 &mut self,
94 ix: usize,
95 window: &mut Window,
96 cx: &mut Context<Picker<Self>>,
97 );
98 fn can_select(
99 &mut self,
100 _ix: usize,
101 _window: &mut Window,
102 _cx: &mut Context<Picker<Self>>,
103 ) -> bool {
104 true
105 }
106
107 // Allows binding some optional effect to when the selection changes.
108 fn selected_index_changed(
109 &self,
110 _ix: usize,
111 _window: &mut Window,
112 _cx: &mut Context<Picker<Self>>,
113 ) -> Option<Box<dyn Fn(&mut Window, &mut App) + 'static>> {
114 None
115 }
116 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str>;
117 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
118 Some("No matches".into())
119 }
120 fn update_matches(
121 &mut self,
122 query: String,
123 window: &mut Window,
124 cx: &mut Context<Picker<Self>>,
125 ) -> Task<()>;
126
127 // Delegates that support this method (e.g. the CommandPalette) can chose to block on any background
128 // work for up to `duration` to try and get a result synchronously.
129 // This avoids a flash of an empty command-palette on cmd-shift-p, and lets workspace::SendKeystrokes
130 // mostly work when dismissing a palette.
131 fn finalize_update_matches(
132 &mut self,
133 _query: String,
134 _duration: Duration,
135 _window: &mut Window,
136 _cx: &mut Context<Picker<Self>>,
137 ) -> bool {
138 false
139 }
140
141 /// Override if you want to have <enter> update the query instead of confirming.
142 fn confirm_update_query(
143 &mut self,
144 _window: &mut Window,
145 _cx: &mut Context<Picker<Self>>,
146 ) -> Option<String> {
147 None
148 }
149 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>);
150 /// Instead of interacting with currently selected entry, treats editor input literally,
151 /// performing some kind of action on it.
152 fn confirm_input(
153 &mut self,
154 _secondary: bool,
155 _window: &mut Window,
156 _: &mut Context<Picker<Self>>,
157 ) {
158 }
159 fn dismissed(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>);
160 fn should_dismiss(&self) -> bool {
161 true
162 }
163 fn confirm_completion(
164 &mut self,
165 _query: String,
166 _window: &mut Window,
167 _: &mut Context<Picker<Self>>,
168 ) -> Option<String> {
169 None
170 }
171
172 fn editor_position(&self) -> PickerEditorPosition {
173 PickerEditorPosition::default()
174 }
175
176 fn render_editor(
177 &self,
178 editor: &Entity<Editor>,
179 _window: &mut Window,
180 _cx: &mut Context<Picker<Self>>,
181 ) -> Div {
182 v_flex()
183 .when(
184 self.editor_position() == PickerEditorPosition::End,
185 |this| this.child(Divider::horizontal()),
186 )
187 .child(
188 h_flex()
189 .overflow_hidden()
190 .flex_none()
191 .h_9()
192 .px_3()
193 .child(editor.clone()),
194 )
195 .when(
196 self.editor_position() == PickerEditorPosition::Start,
197 |this| this.child(Divider::horizontal()),
198 )
199 }
200
201 fn render_match(
202 &self,
203 ix: usize,
204 selected: bool,
205 window: &mut Window,
206 cx: &mut Context<Picker<Self>>,
207 ) -> Option<Self::ListItem>;
208 fn render_header(
209 &self,
210 _window: &mut Window,
211 _: &mut Context<Picker<Self>>,
212 ) -> Option<AnyElement> {
213 None
214 }
215 fn render_footer(
216 &self,
217 _window: &mut Window,
218 _: &mut Context<Picker<Self>>,
219 ) -> Option<AnyElement> {
220 None
221 }
222}
223
224impl<D: PickerDelegate> Focusable for Picker<D> {
225 fn focus_handle(&self, cx: &App) -> FocusHandle {
226 match &self.head {
227 Head::Editor(editor) => editor.focus_handle(cx),
228 Head::Empty(head) => head.focus_handle(cx),
229 }
230 }
231}
232
233#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
234enum ContainerKind {
235 List,
236 UniformList,
237}
238
239impl<D: PickerDelegate> Picker<D> {
240 /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
241 /// The picker allows the user to perform search items by text.
242 /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
243 pub fn uniform_list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
244 let head = Head::editor(
245 delegate.placeholder_text(window, cx),
246 Self::on_input_editor_event,
247 window,
248 cx,
249 );
250
251 Self::new(delegate, ContainerKind::UniformList, head, window, cx)
252 }
253
254 /// A picker, which displays its matches using `gpui::uniform_list`, all matches should have the same height.
255 /// If `PickerDelegate::render_match` can return items with different heights, use `Picker::list`.
256 pub fn nonsearchable_uniform_list(
257 delegate: D,
258 window: &mut Window,
259 cx: &mut Context<Self>,
260 ) -> Self {
261 let head = Head::empty(Self::on_empty_head_blur, window, cx);
262
263 Self::new(delegate, ContainerKind::UniformList, head, window, cx)
264 }
265
266 /// A picker, which displays its matches using `gpui::list`, matches can have different heights.
267 /// The picker allows the user to perform search items by text.
268 /// If `PickerDelegate::render_match` only returns items with the same height, use `Picker::uniform_list` as its implementation is optimized for that.
269 pub fn list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
270 let head = Head::editor(
271 delegate.placeholder_text(window, cx),
272 Self::on_input_editor_event,
273 window,
274 cx,
275 );
276
277 Self::new(delegate, ContainerKind::List, head, window, cx)
278 }
279
280 fn new(
281 delegate: D,
282 container: ContainerKind,
283 head: Head,
284 window: &mut Window,
285 cx: &mut Context<Self>,
286 ) -> Self {
287 let element_container = Self::create_element_container(container, cx);
288 let scrollbar_state = match &element_container {
289 ElementContainer::UniformList(scroll_handle) => {
290 ScrollbarState::new(scroll_handle.clone())
291 }
292 ElementContainer::List(state) => ScrollbarState::new(state.clone()),
293 };
294 let focus_handle = cx.focus_handle();
295 let mut this = Self {
296 delegate,
297 head,
298 element_container,
299 pending_update_matches: None,
300 confirm_on_update: None,
301 width: None,
302 widest_item: None,
303 max_height: Some(rems(18.).into()),
304 focus_handle,
305 show_scrollbar: false,
306 scrollbar_visibility: true,
307 scrollbar_state,
308 is_modal: true,
309 hide_scrollbar_task: None,
310 };
311 this.update_matches("".to_string(), window, cx);
312 // give the delegate 4ms to render the first set of suggestions.
313 this.delegate
314 .finalize_update_matches("".to_string(), Duration::from_millis(4), window, cx);
315 this
316 }
317
318 fn create_element_container(
319 container: ContainerKind,
320 cx: &mut Context<Self>,
321 ) -> ElementContainer {
322 match container {
323 ContainerKind::UniformList => {
324 ElementContainer::UniformList(UniformListScrollHandle::new())
325 }
326 ContainerKind::List => {
327 let entity = cx.entity().downgrade();
328 ElementContainer::List(ListState::new(
329 0,
330 gpui::ListAlignment::Top,
331 px(1000.),
332 move |ix, window, cx| {
333 entity
334 .upgrade()
335 .map(|entity| {
336 entity.update(cx, |this, cx| {
337 this.render_element(window, cx, ix).into_any_element()
338 })
339 })
340 .unwrap_or_else(|| div().into_any_element())
341 },
342 ))
343 }
344 }
345 }
346
347 pub fn width(mut self, width: impl Into<gpui::Length>) -> Self {
348 self.width = Some(width.into());
349 self
350 }
351
352 pub fn widest_item(mut self, ix: Option<usize>) -> Self {
353 self.widest_item = ix;
354 self
355 }
356
357 pub fn max_height(mut self, max_height: Option<gpui::Length>) -> Self {
358 self.max_height = max_height;
359 self
360 }
361
362 pub fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
363 self.show_scrollbar = show_scrollbar;
364 self
365 }
366
367 pub fn modal(mut self, modal: bool) -> Self {
368 self.is_modal = modal;
369 self
370 }
371
372 pub fn focus(&self, window: &mut Window, cx: &mut App) {
373 self.focus_handle(cx).focus(window);
374 }
375
376 /// Handles the selecting an index, and passing the change to the delegate.
377 /// If `fallback_direction` is set to `None`, the index will not be selected
378 /// if the element at that index cannot be selected.
379 /// If `fallback_direction` is set to
380 /// `Some(..)`, the next selectable element will be selected in the
381 /// specified direction (Down or Up), cycling through all elements until
382 /// finding one that can be selected or returning if there are no selectable elements.
383 /// If `scroll_to_index` is true, the new selected index will be scrolled into
384 /// view.
385 ///
386 /// If some effect is bound to `selected_index_changed`, it will be executed.
387 pub fn set_selected_index(
388 &mut self,
389 mut ix: usize,
390 fallback_direction: Option<Direction>,
391 scroll_to_index: bool,
392 window: &mut Window,
393 cx: &mut Context<Self>,
394 ) {
395 let match_count = self.delegate.match_count();
396 if match_count == 0 {
397 return;
398 }
399
400 if let Some(bias) = fallback_direction {
401 let mut curr_ix = ix;
402 while !self.delegate.can_select(curr_ix, window, cx) {
403 curr_ix = match bias {
404 Direction::Down => {
405 if curr_ix == match_count - 1 {
406 0
407 } else {
408 curr_ix + 1
409 }
410 }
411 Direction::Up => {
412 if curr_ix == 0 {
413 match_count - 1
414 } else {
415 curr_ix - 1
416 }
417 }
418 };
419 // There is no item that can be selected
420 if ix == curr_ix {
421 return;
422 }
423 }
424 ix = curr_ix;
425 } else if !self.delegate.can_select(ix, window, cx) {
426 return;
427 }
428
429 let previous_index = self.delegate.selected_index();
430 self.delegate.set_selected_index(ix, window, cx);
431 let current_index = self.delegate.selected_index();
432
433 if previous_index != current_index {
434 if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) {
435 action(window, cx);
436 }
437 if scroll_to_index {
438 self.scroll_to_item_index(ix);
439 }
440 }
441 }
442
443 pub fn select_next(
444 &mut self,
445 _: &menu::SelectNext,
446 window: &mut Window,
447 cx: &mut Context<Self>,
448 ) {
449 let count = self.delegate.match_count();
450 if count > 0 {
451 let index = self.delegate.selected_index();
452 let ix = if index == count - 1 { 0 } else { index + 1 };
453 self.set_selected_index(ix, Some(Direction::Down), true, window, cx);
454 cx.notify();
455 }
456 }
457
458 pub fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
459 self.select_previous(&Default::default(), window, cx);
460 }
461
462 fn select_previous(
463 &mut self,
464 _: &menu::SelectPrevious,
465 window: &mut Window,
466 cx: &mut Context<Self>,
467 ) {
468 let count = self.delegate.match_count();
469 if count > 0 {
470 let index = self.delegate.selected_index();
471 let ix = if index == 0 { count - 1 } else { index - 1 };
472 self.set_selected_index(ix, Some(Direction::Up), true, window, cx);
473 cx.notify();
474 }
475 }
476
477 pub fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
478 self.select_next(&Default::default(), window, cx);
479 }
480
481 pub fn select_first(
482 &mut self,
483 _: &menu::SelectFirst,
484 window: &mut Window,
485 cx: &mut Context<Self>,
486 ) {
487 let count = self.delegate.match_count();
488 if count > 0 {
489 self.set_selected_index(0, Some(Direction::Down), true, window, cx);
490 cx.notify();
491 }
492 }
493
494 fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
495 let count = self.delegate.match_count();
496 if count > 0 {
497 self.set_selected_index(count - 1, Some(Direction::Up), true, window, cx);
498 cx.notify();
499 }
500 }
501
502 pub fn cycle_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
503 let count = self.delegate.match_count();
504 let index = self.delegate.selected_index();
505 let new_index = if index + 1 == count { 0 } else { index + 1 };
506 self.set_selected_index(new_index, Some(Direction::Down), true, window, cx);
507 cx.notify();
508 }
509
510 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
511 if self.delegate.should_dismiss() {
512 self.delegate.dismissed(window, cx);
513 cx.emit(DismissEvent);
514 }
515 }
516
517 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
518 if self.pending_update_matches.is_some()
519 && !self.delegate.finalize_update_matches(
520 self.query(cx),
521 Duration::from_millis(16),
522 window,
523 cx,
524 )
525 {
526 self.confirm_on_update = Some(false)
527 } else {
528 self.pending_update_matches.take();
529 self.do_confirm(false, window, cx);
530 }
531 }
532
533 fn secondary_confirm(
534 &mut self,
535 _: &menu::SecondaryConfirm,
536 window: &mut Window,
537 cx: &mut Context<Self>,
538 ) {
539 if self.pending_update_matches.is_some()
540 && !self.delegate.finalize_update_matches(
541 self.query(cx),
542 Duration::from_millis(16),
543 window,
544 cx,
545 )
546 {
547 self.confirm_on_update = Some(true)
548 } else {
549 self.do_confirm(true, window, cx);
550 }
551 }
552
553 fn confirm_input(&mut self, input: &ConfirmInput, window: &mut Window, cx: &mut Context<Self>) {
554 self.delegate.confirm_input(input.secondary, window, cx);
555 }
556
557 fn confirm_completion(
558 &mut self,
559 _: &ConfirmCompletion,
560 window: &mut Window,
561 cx: &mut Context<Self>,
562 ) {
563 if let Some(new_query) = self.delegate.confirm_completion(self.query(cx), window, cx) {
564 self.set_query(new_query, window, cx);
565 } else {
566 cx.propagate()
567 }
568 }
569
570 fn handle_click(
571 &mut self,
572 ix: usize,
573 secondary: bool,
574 window: &mut Window,
575 cx: &mut Context<Self>,
576 ) {
577 cx.stop_propagation();
578 window.prevent_default();
579 self.set_selected_index(ix, None, false, window, cx);
580 self.do_confirm(secondary, window, cx)
581 }
582
583 fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {
584 if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {
585 self.set_query(update_query, window, cx);
586 self.set_selected_index(0, Some(Direction::Down), false, window, cx);
587 } else {
588 self.delegate.confirm(secondary, window, cx)
589 }
590 }
591
592 fn on_input_editor_event(
593 &mut self,
594 _: &Entity<Editor>,
595 event: &editor::EditorEvent,
596 window: &mut Window,
597 cx: &mut Context<Self>,
598 ) {
599 let Head::Editor(editor) = &self.head else {
600 panic!("unexpected call");
601 };
602 match event {
603 editor::EditorEvent::BufferEdited => {
604 let query = editor.read(cx).text(cx);
605 self.update_matches(query, window, cx);
606 }
607 editor::EditorEvent::Blurred => {
608 self.cancel(&menu::Cancel, window, cx);
609 }
610 _ => {}
611 }
612 }
613
614 fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
615 let Head::Empty(_) = &self.head else {
616 panic!("unexpected call");
617 };
618 self.cancel(&menu::Cancel, window, cx);
619 }
620
621 pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
622 match &self.head {
623 Head::Editor(editor) => {
624 let placeholder = self.delegate.placeholder_text(window, cx);
625 editor.update(cx, |editor, cx| {
626 editor.set_placeholder_text(placeholder, cx);
627 cx.notify();
628 });
629 }
630 Head::Empty(_) => {}
631 }
632 }
633
634 pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
635 let query = self.query(cx);
636 self.update_matches(query, window, cx);
637 }
638
639 pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
640 let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
641
642 self.matches_updated(window, cx);
643 // This struct ensures that we can synchronously drop the task returned by the
644 // delegate's `update_matches` method and the task that the picker is spawning.
645 // If we simply capture the delegate's task into the picker's task, when the picker's
646 // task gets synchronously dropped, the delegate's task would keep running until
647 // the picker's task has a chance of being scheduled, because dropping a task happens
648 // asynchronously.
649 self.pending_update_matches = Some(PendingUpdateMatches {
650 delegate_update_matches: Some(delegate_pending_update_matches),
651 _task: cx.spawn_in(window, async move |this, cx| {
652 let delegate_pending_update_matches = this.update(cx, |this, _| {
653 this.pending_update_matches
654 .as_mut()
655 .unwrap()
656 .delegate_update_matches
657 .take()
658 .unwrap()
659 })?;
660 delegate_pending_update_matches.await;
661 this.update_in(cx, |this, window, cx| {
662 this.matches_updated(window, cx);
663 })
664 }),
665 });
666 }
667
668 fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
669 if let ElementContainer::List(state) = &mut self.element_container {
670 state.reset(self.delegate.match_count());
671 }
672
673 let index = self.delegate.selected_index();
674 self.scroll_to_item_index(index);
675 self.pending_update_matches = None;
676 if let Some(secondary) = self.confirm_on_update.take() {
677 self.do_confirm(secondary, window, cx);
678 }
679 cx.notify();
680 }
681
682 pub fn query(&self, cx: &App) -> String {
683 match &self.head {
684 Head::Editor(editor) => editor.read(cx).text(cx),
685 Head::Empty(_) => "".to_string(),
686 }
687 }
688
689 pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
690 if let Head::Editor(editor) = &self.head {
691 editor.update(cx, |editor, cx| {
692 editor.set_text(query, window, cx);
693 let editor_offset = editor.buffer().read(cx).len(cx);
694 editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
695 s.select_ranges(Some(editor_offset..editor_offset))
696 });
697 });
698 }
699 }
700
701 fn scroll_to_item_index(&mut self, ix: usize) {
702 match &mut self.element_container {
703 ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
704 ElementContainer::UniformList(scroll_handle) => {
705 scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
706 }
707 }
708 }
709
710 fn render_element(
711 &self,
712 window: &mut Window,
713 cx: &mut Context<Self>,
714 ix: usize,
715 ) -> impl IntoElement + use<D> {
716 div()
717 .id(("item", ix))
718 .cursor_pointer()
719 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
720 this.handle_click(ix, event.modifiers().secondary(), window, cx)
721 }))
722 // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
723 // and produces right mouse button events. This matches platforms norms
724 // but means that UIs which depend on holding ctrl down (such as the tab
725 // switcher) can't be clicked on. Hence, this handler.
726 .on_mouse_up(
727 MouseButton::Right,
728 cx.listener(move |this, event: &MouseUpEvent, window, cx| {
729 // We specifically want to use the platform key here, as
730 // ctrl will already be held down for the tab switcher.
731 this.handle_click(ix, event.modifiers.platform, window, cx)
732 }),
733 )
734 .children(self.delegate.render_match(
735 ix,
736 ix == self.delegate.selected_index(),
737 window,
738 cx,
739 ))
740 .when(
741 self.delegate.separators_after_indices().contains(&ix),
742 |picker| {
743 picker
744 .border_color(cx.theme().colors().border_variant)
745 .border_b_1()
746 .py(px(-1.0))
747 },
748 )
749 }
750
751 fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
752 let sizing_behavior = if self.max_height.is_some() {
753 ListSizingBehavior::Infer
754 } else {
755 ListSizingBehavior::Auto
756 };
757
758 match &self.element_container {
759 ElementContainer::UniformList(scroll_handle) => uniform_list(
760 cx.entity().clone(),
761 "candidates",
762 self.delegate.match_count(),
763 move |picker, visible_range, window, cx| {
764 visible_range
765 .map(|ix| picker.render_element(window, cx, ix))
766 .collect()
767 },
768 )
769 .with_sizing_behavior(sizing_behavior)
770 .when_some(self.widest_item, |el, widest_item| {
771 el.with_width_from_item(Some(widest_item))
772 })
773 .flex_grow()
774 .py_1()
775 .track_scroll(scroll_handle.clone())
776 .into_any_element(),
777 ElementContainer::List(state) => list(state.clone())
778 .with_sizing_behavior(sizing_behavior)
779 .flex_grow()
780 .py_2()
781 .into_any_element(),
782 }
783 }
784
785 #[cfg(any(test, feature = "test-support"))]
786 pub fn logical_scroll_top_index(&self) -> usize {
787 match &self.element_container {
788 ElementContainer::List(state) => state.logical_scroll_top().item_ix,
789 ElementContainer::UniformList(scroll_handle) => {
790 scroll_handle.logical_scroll_top_index()
791 }
792 }
793 }
794
795 fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
796 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
797 self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
798 cx.background_executor()
799 .timer(SCROLLBAR_SHOW_INTERVAL)
800 .await;
801 panel
802 .update(cx, |panel, cx| {
803 panel.scrollbar_visibility = false;
804 cx.notify();
805 })
806 .log_err();
807 }))
808 }
809
810 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
811 if !self.show_scrollbar
812 || !(self.scrollbar_visibility || self.scrollbar_state.is_dragging())
813 {
814 return None;
815 }
816 Some(
817 div()
818 .occlude()
819 .id("picker-scroll")
820 .h_full()
821 .absolute()
822 .right_1()
823 .top_1()
824 .bottom_0()
825 .w(px(12.))
826 .cursor_default()
827 .on_mouse_move(cx.listener(|_, _, _window, cx| {
828 cx.notify();
829 cx.stop_propagation()
830 }))
831 .on_hover(|_, _window, cx| {
832 cx.stop_propagation();
833 })
834 .on_any_mouse_down(|_, _window, cx| {
835 cx.stop_propagation();
836 })
837 .on_mouse_up(
838 MouseButton::Left,
839 cx.listener(|picker, _, window, cx| {
840 if !picker.scrollbar_state.is_dragging()
841 && !picker.focus_handle.contains_focused(window, cx)
842 {
843 picker.hide_scrollbar(cx);
844 cx.notify();
845 }
846 cx.stop_propagation();
847 }),
848 )
849 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
850 cx.notify();
851 }))
852 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
853 )
854 }
855}
856
857impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
858impl<D: PickerDelegate> ModalView for Picker<D> {}
859
860impl<D: PickerDelegate> Render for Picker<D> {
861 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
862 let editor_position = self.delegate.editor_position();
863 v_flex()
864 .key_context("Picker")
865 .size_full()
866 .when_some(self.width, |el, width| el.w(width))
867 .overflow_hidden()
868 // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
869 // as a part of a modal rather than the entire modal.
870 //
871 // We should revisit how the `Picker` is styled to make it more composable.
872 .when(self.is_modal, |this| this.elevation_3(cx))
873 .on_action(cx.listener(Self::select_next))
874 .on_action(cx.listener(Self::select_previous))
875 .on_action(cx.listener(Self::editor_move_down))
876 .on_action(cx.listener(Self::editor_move_up))
877 .on_action(cx.listener(Self::select_first))
878 .on_action(cx.listener(Self::select_last))
879 .on_action(cx.listener(Self::cancel))
880 .on_action(cx.listener(Self::confirm))
881 .on_action(cx.listener(Self::secondary_confirm))
882 .on_action(cx.listener(Self::confirm_completion))
883 .on_action(cx.listener(Self::confirm_input))
884 .children(match &self.head {
885 Head::Editor(editor) => {
886 if editor_position == PickerEditorPosition::Start {
887 Some(self.delegate.render_editor(&editor.clone(), window, cx))
888 } else {
889 None
890 }
891 }
892 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
893 })
894 .when(self.delegate.match_count() > 0, |el| {
895 el.child(
896 v_flex()
897 .id("element-container")
898 .relative()
899 .flex_grow()
900 .when_some(self.max_height, |div, max_h| div.max_h(max_h))
901 .overflow_hidden()
902 .children(self.delegate.render_header(window, cx))
903 .child(self.render_element_container(cx))
904 .on_hover(cx.listener(|this, hovered, window, cx| {
905 if *hovered {
906 this.scrollbar_visibility = true;
907 this.hide_scrollbar_task.take();
908 cx.notify();
909 } else if !this.focus_handle.contains_focused(window, cx) {
910 this.hide_scrollbar(cx);
911 }
912 }))
913 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
914 div.child(scrollbar)
915 }),
916 )
917 })
918 .when(self.delegate.match_count() == 0, |el| {
919 el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
920 el.child(
921 v_flex().flex_grow().py_2().child(
922 ListItem::new("empty_state")
923 .inset(true)
924 .spacing(ListItemSpacing::Sparse)
925 .disabled(true)
926 .child(Label::new(text).color(Color::Muted)),
927 ),
928 )
929 })
930 })
931 .children(self.delegate.render_footer(window, cx))
932 .children(match &self.head {
933 Head::Editor(editor) => {
934 if editor_position == PickerEditorPosition::End {
935 Some(self.delegate.render_editor(&editor.clone(), window, cx))
936 } else {
937 None
938 }
939 }
940 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
941 })
942 }
943}