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