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