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