1mod head;
2pub mod highlighted_match_with_paths;
3pub mod popover_menu;
4
5use anyhow::Result;
6use editor::{
7 Editor,
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 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 if self.is_modal {
609 self.cancel(&menu::Cancel, window, cx);
610 }
611 }
612 _ => {}
613 }
614 }
615
616 fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
617 let Head::Empty(_) = &self.head else {
618 panic!("unexpected call");
619 };
620 self.cancel(&menu::Cancel, window, cx);
621 }
622
623 pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
624 match &self.head {
625 Head::Editor(editor) => {
626 let placeholder = self.delegate.placeholder_text(window, cx);
627 editor.update(cx, |editor, cx| {
628 editor.set_placeholder_text(placeholder, cx);
629 cx.notify();
630 });
631 }
632 Head::Empty(_) => {}
633 }
634 }
635
636 pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
637 let query = self.query(cx);
638 self.update_matches(query, window, cx);
639 }
640
641 pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
642 let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
643
644 self.matches_updated(window, cx);
645 // This struct ensures that we can synchronously drop the task returned by the
646 // delegate's `update_matches` method and the task that the picker is spawning.
647 // If we simply capture the delegate's task into the picker's task, when the picker's
648 // task gets synchronously dropped, the delegate's task would keep running until
649 // the picker's task has a chance of being scheduled, because dropping a task happens
650 // asynchronously.
651 self.pending_update_matches = Some(PendingUpdateMatches {
652 delegate_update_matches: Some(delegate_pending_update_matches),
653 _task: cx.spawn_in(window, async move |this, cx| {
654 let delegate_pending_update_matches = this.update(cx, |this, _| {
655 this.pending_update_matches
656 .as_mut()
657 .unwrap()
658 .delegate_update_matches
659 .take()
660 .unwrap()
661 })?;
662 delegate_pending_update_matches.await;
663 this.update_in(cx, |this, window, cx| {
664 this.matches_updated(window, cx);
665 })
666 }),
667 });
668 }
669
670 fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
671 if let ElementContainer::List(state) = &mut self.element_container {
672 state.reset(self.delegate.match_count());
673 }
674
675 let index = self.delegate.selected_index();
676 self.scroll_to_item_index(index);
677 self.pending_update_matches = None;
678 if let Some(secondary) = self.confirm_on_update.take() {
679 self.do_confirm(secondary, window, cx);
680 }
681 cx.notify();
682 }
683
684 pub fn query(&self, cx: &App) -> String {
685 match &self.head {
686 Head::Editor(editor) => editor.read(cx).text(cx),
687 Head::Empty(_) => "".to_string(),
688 }
689 }
690
691 pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
692 if let Head::Editor(editor) = &self.head {
693 editor.update(cx, |editor, cx| {
694 editor.set_text(query, window, cx);
695 let editor_offset = editor.buffer().read(cx).len(cx);
696 editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
697 s.select_ranges(Some(editor_offset..editor_offset))
698 });
699 });
700 }
701 }
702
703 fn scroll_to_item_index(&mut self, ix: usize) {
704 match &mut self.element_container {
705 ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
706 ElementContainer::UniformList(scroll_handle) => {
707 scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
708 }
709 }
710 }
711
712 fn render_element(
713 &self,
714 window: &mut Window,
715 cx: &mut Context<Self>,
716 ix: usize,
717 ) -> impl IntoElement + use<D> {
718 div()
719 .id(("item", ix))
720 .cursor_pointer()
721 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
722 this.handle_click(ix, event.modifiers().secondary(), window, cx)
723 }))
724 // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
725 // and produces right mouse button events. This matches platforms norms
726 // but means that UIs which depend on holding ctrl down (such as the tab
727 // switcher) can't be clicked on. Hence, this handler.
728 .on_mouse_up(
729 MouseButton::Right,
730 cx.listener(move |this, event: &MouseUpEvent, window, cx| {
731 // We specifically want to use the platform key here, as
732 // ctrl will already be held down for the tab switcher.
733 this.handle_click(ix, event.modifiers.platform, window, cx)
734 }),
735 )
736 .children(self.delegate.render_match(
737 ix,
738 ix == self.delegate.selected_index(),
739 window,
740 cx,
741 ))
742 .when(
743 self.delegate.separators_after_indices().contains(&ix),
744 |picker| {
745 picker
746 .border_color(cx.theme().colors().border_variant)
747 .border_b_1()
748 .py(px(-1.0))
749 },
750 )
751 }
752
753 fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
754 let sizing_behavior = if self.max_height.is_some() {
755 ListSizingBehavior::Infer
756 } else {
757 ListSizingBehavior::Auto
758 };
759
760 match &self.element_container {
761 ElementContainer::UniformList(scroll_handle) => uniform_list(
762 "candidates",
763 self.delegate.match_count(),
764 cx.processor(move |picker, visible_range: Range<usize>, window, cx| {
765 visible_range
766 .map(|ix| picker.render_element(window, cx, ix))
767 .collect()
768 }),
769 )
770 .with_sizing_behavior(sizing_behavior)
771 .when_some(self.widest_item, |el, widest_item| {
772 el.with_width_from_item(Some(widest_item))
773 })
774 .flex_grow()
775 .py_1()
776 .track_scroll(scroll_handle.clone())
777 .into_any_element(),
778 ElementContainer::List(state) => list(state.clone())
779 .with_sizing_behavior(sizing_behavior)
780 .flex_grow()
781 .py_2()
782 .into_any_element(),
783 }
784 }
785
786 #[cfg(any(test, feature = "test-support"))]
787 pub fn logical_scroll_top_index(&self) -> usize {
788 match &self.element_container {
789 ElementContainer::List(state) => state.logical_scroll_top().item_ix,
790 ElementContainer::UniformList(scroll_handle) => {
791 scroll_handle.logical_scroll_top_index()
792 }
793 }
794 }
795
796 fn hide_scrollbar(&mut self, cx: &mut Context<Self>) {
797 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
798 self.hide_scrollbar_task = Some(cx.spawn(async move |panel, cx| {
799 cx.background_executor()
800 .timer(SCROLLBAR_SHOW_INTERVAL)
801 .await;
802 panel
803 .update(cx, |panel, cx| {
804 panel.scrollbar_visibility = false;
805 cx.notify();
806 })
807 .log_err();
808 }))
809 }
810
811 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
812 if !self.show_scrollbar
813 || !(self.scrollbar_visibility || self.scrollbar_state.is_dragging())
814 {
815 return None;
816 }
817 Some(
818 div()
819 .occlude()
820 .id("picker-scroll")
821 .h_full()
822 .absolute()
823 .right_1()
824 .top_1()
825 .bottom_0()
826 .w(px(12.))
827 .cursor_default()
828 .on_mouse_move(cx.listener(|_, _, _window, cx| {
829 cx.notify();
830 cx.stop_propagation()
831 }))
832 .on_hover(|_, _window, cx| {
833 cx.stop_propagation();
834 })
835 .on_any_mouse_down(|_, _window, cx| {
836 cx.stop_propagation();
837 })
838 .on_mouse_up(
839 MouseButton::Left,
840 cx.listener(|picker, _, window, cx| {
841 if !picker.scrollbar_state.is_dragging()
842 && !picker.focus_handle.contains_focused(window, cx)
843 {
844 picker.hide_scrollbar(cx);
845 cx.notify();
846 }
847 cx.stop_propagation();
848 }),
849 )
850 .on_scroll_wheel(cx.listener(|_, _, _window, cx| {
851 cx.notify();
852 }))
853 .children(Scrollbar::vertical(self.scrollbar_state.clone())),
854 )
855 }
856}
857
858impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
859impl<D: PickerDelegate> ModalView for Picker<D> {}
860
861impl<D: PickerDelegate> Render for Picker<D> {
862 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
863 let editor_position = self.delegate.editor_position();
864 v_flex()
865 .key_context("Picker")
866 .size_full()
867 .when_some(self.width, |el, width| el.w(width))
868 .overflow_hidden()
869 // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
870 // as a part of a modal rather than the entire modal.
871 //
872 // We should revisit how the `Picker` is styled to make it more composable.
873 .when(self.is_modal, |this| this.elevation_3(cx))
874 .on_action(cx.listener(Self::select_next))
875 .on_action(cx.listener(Self::select_previous))
876 .on_action(cx.listener(Self::editor_move_down))
877 .on_action(cx.listener(Self::editor_move_up))
878 .on_action(cx.listener(Self::select_first))
879 .on_action(cx.listener(Self::select_last))
880 .on_action(cx.listener(Self::cancel))
881 .on_action(cx.listener(Self::confirm))
882 .on_action(cx.listener(Self::secondary_confirm))
883 .on_action(cx.listener(Self::confirm_completion))
884 .on_action(cx.listener(Self::confirm_input))
885 .children(match &self.head {
886 Head::Editor(editor) => {
887 if editor_position == PickerEditorPosition::Start {
888 Some(self.delegate.render_editor(&editor.clone(), window, cx))
889 } else {
890 None
891 }
892 }
893 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
894 })
895 .when(self.delegate.match_count() > 0, |el| {
896 el.child(
897 v_flex()
898 .id("element-container")
899 .relative()
900 .flex_grow()
901 .when_some(self.max_height, |div, max_h| div.max_h(max_h))
902 .overflow_hidden()
903 .children(self.delegate.render_header(window, cx))
904 .child(self.render_element_container(cx))
905 .on_hover(cx.listener(|this, hovered, window, cx| {
906 if *hovered {
907 this.scrollbar_visibility = true;
908 this.hide_scrollbar_task.take();
909 cx.notify();
910 } else if !this.focus_handle.contains_focused(window, cx) {
911 this.hide_scrollbar(cx);
912 }
913 }))
914 .when_some(self.render_scrollbar(cx), |div, scrollbar| {
915 div.child(scrollbar)
916 }),
917 )
918 })
919 .when(self.delegate.match_count() == 0, |el| {
920 el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
921 el.child(
922 v_flex().flex_grow().py_2().child(
923 ListItem::new("empty_state")
924 .inset(true)
925 .spacing(ListItemSpacing::Sparse)
926 .disabled(true)
927 .child(Label::new(text).color(Color::Muted)),
928 ),
929 )
930 })
931 })
932 .children(self.delegate.render_footer(window, cx))
933 .children(match &self.head {
934 Head::Editor(editor) => {
935 if editor_position == PickerEditorPosition::End {
936 Some(self.delegate.render_editor(&editor.clone(), window, cx))
937 } else {
938 None
939 }
940 }
941 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
942 })
943 }
944}