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