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