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 list(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
282 let head = Head::editor(
283 delegate.placeholder_text(window, cx),
284 Self::on_input_editor_event,
285 window,
286 cx,
287 );
288
289 Self::new(delegate, ContainerKind::List, head, window, cx)
290 }
291
292 fn new(
293 delegate: D,
294 container: ContainerKind,
295 head: Head,
296 window: &mut Window,
297 cx: &mut Context<Self>,
298 ) -> Self {
299 let element_container = Self::create_element_container(container);
300 let mut this = Self {
301 delegate,
302 head,
303 element_container,
304 pending_update_matches: None,
305 confirm_on_update: None,
306 width: None,
307 widest_item: None,
308 max_height: Some(rems(18.).into()),
309 show_scrollbar: false,
310 is_modal: true,
311 };
312 this.update_matches("".to_string(), window, cx);
313 // give the delegate 4ms to render the first set of suggestions.
314 this.delegate
315 .finalize_update_matches("".to_string(), Duration::from_millis(4), window, cx);
316 this
317 }
318
319 fn create_element_container(container: ContainerKind) -> ElementContainer {
320 match container {
321 ContainerKind::UniformList => {
322 ElementContainer::UniformList(UniformListScrollHandle::new())
323 }
324 ContainerKind::List => {
325 ElementContainer::List(ListState::new(0, gpui::ListAlignment::Top, px(1000.)))
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 widest_item(mut self, ix: Option<usize>) -> Self {
336 self.widest_item = ix;
337 self
338 }
339
340 pub fn max_height(mut self, max_height: Option<gpui::Length>) -> Self {
341 self.max_height = max_height;
342 self
343 }
344
345 pub fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
346 self.show_scrollbar = show_scrollbar;
347 self
348 }
349
350 pub fn modal(mut self, modal: bool) -> Self {
351 self.is_modal = modal;
352 self
353 }
354
355 pub fn list_measure_all(mut self) -> Self {
356 match self.element_container {
357 ElementContainer::List(state) => {
358 self.element_container = ElementContainer::List(state.measure_all());
359 }
360 _ => {}
361 }
362 self
363 }
364
365 pub fn focus(&self, window: &mut Window, cx: &mut App) {
366 self.focus_handle(cx).focus(window);
367 }
368
369 /// Handles the selecting an index, and passing the change to the delegate.
370 /// If `fallback_direction` is set to `None`, the index will not be selected
371 /// if the element at that index cannot be selected.
372 /// If `fallback_direction` is set to
373 /// `Some(..)`, the next selectable element will be selected in the
374 /// specified direction (Down or Up), cycling through all elements until
375 /// finding one that can be selected or returning if there are no selectable elements.
376 /// If `scroll_to_index` is true, the new selected index will be scrolled into
377 /// view.
378 ///
379 /// If some effect is bound to `selected_index_changed`, it will be executed.
380 pub fn set_selected_index(
381 &mut self,
382 mut ix: usize,
383 fallback_direction: Option<Direction>,
384 scroll_to_index: bool,
385 window: &mut Window,
386 cx: &mut Context<Self>,
387 ) {
388 let match_count = self.delegate.match_count();
389 if match_count == 0 {
390 return;
391 }
392
393 if let Some(bias) = fallback_direction {
394 let mut curr_ix = ix;
395 while !self.delegate.can_select(curr_ix, window, cx) {
396 curr_ix = match bias {
397 Direction::Down => {
398 if curr_ix == match_count - 1 {
399 0
400 } else {
401 curr_ix + 1
402 }
403 }
404 Direction::Up => {
405 if curr_ix == 0 {
406 match_count - 1
407 } else {
408 curr_ix - 1
409 }
410 }
411 };
412 // There is no item that can be selected
413 if ix == curr_ix {
414 return;
415 }
416 }
417 ix = curr_ix;
418 } else if !self.delegate.can_select(ix, window, cx) {
419 return;
420 }
421
422 let previous_index = self.delegate.selected_index();
423 self.delegate.set_selected_index(ix, window, cx);
424 let current_index = self.delegate.selected_index();
425
426 if previous_index != current_index {
427 if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) {
428 action(window, cx);
429 }
430 if scroll_to_index {
431 self.scroll_to_item_index(ix);
432 }
433 }
434 }
435
436 pub fn select_next(
437 &mut self,
438 _: &menu::SelectNext,
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 == count - 1 { 0 } else { index + 1 };
446 self.set_selected_index(ix, Some(Direction::Down), true, window, cx);
447 cx.notify();
448 }
449 }
450
451 pub fn editor_move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
452 self.select_previous(&Default::default(), window, cx);
453 }
454
455 fn select_previous(
456 &mut self,
457 _: &menu::SelectPrevious,
458 window: &mut Window,
459 cx: &mut Context<Self>,
460 ) {
461 let count = self.delegate.match_count();
462 if count > 0 {
463 let index = self.delegate.selected_index();
464 let ix = if index == 0 { count - 1 } else { index - 1 };
465 self.set_selected_index(ix, Some(Direction::Up), true, window, cx);
466 cx.notify();
467 }
468 }
469
470 pub fn editor_move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
471 self.select_next(&Default::default(), window, cx);
472 }
473
474 pub fn select_first(
475 &mut self,
476 _: &menu::SelectFirst,
477 window: &mut Window,
478 cx: &mut Context<Self>,
479 ) {
480 let count = self.delegate.match_count();
481 if count > 0 {
482 self.set_selected_index(0, Some(Direction::Down), true, window, cx);
483 cx.notify();
484 }
485 }
486
487 fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
488 let count = self.delegate.match_count();
489 if count > 0 {
490 self.set_selected_index(count - 1, Some(Direction::Up), true, window, cx);
491 cx.notify();
492 }
493 }
494
495 pub fn cycle_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
496 let count = self.delegate.match_count();
497 let index = self.delegate.selected_index();
498 let new_index = if index + 1 == count { 0 } else { index + 1 };
499 self.set_selected_index(new_index, Some(Direction::Down), true, window, cx);
500 cx.notify();
501 }
502
503 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
504 if self.delegate.should_dismiss() {
505 self.delegate.dismissed(window, cx);
506 cx.emit(DismissEvent);
507 }
508 }
509
510 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
511 if self.pending_update_matches.is_some()
512 && !self.delegate.finalize_update_matches(
513 self.query(cx),
514 Duration::from_millis(16),
515 window,
516 cx,
517 )
518 {
519 self.confirm_on_update = Some(false)
520 } else {
521 self.pending_update_matches.take();
522 self.do_confirm(false, window, cx);
523 }
524 }
525
526 fn secondary_confirm(
527 &mut self,
528 _: &menu::SecondaryConfirm,
529 window: &mut Window,
530 cx: &mut Context<Self>,
531 ) {
532 if self.pending_update_matches.is_some()
533 && !self.delegate.finalize_update_matches(
534 self.query(cx),
535 Duration::from_millis(16),
536 window,
537 cx,
538 )
539 {
540 self.confirm_on_update = Some(true)
541 } else {
542 self.do_confirm(true, window, cx);
543 }
544 }
545
546 fn confirm_input(&mut self, input: &ConfirmInput, window: &mut Window, cx: &mut Context<Self>) {
547 self.delegate.confirm_input(input.secondary, window, cx);
548 }
549
550 fn confirm_completion(
551 &mut self,
552 _: &ConfirmCompletion,
553 window: &mut Window,
554 cx: &mut Context<Self>,
555 ) {
556 if let Some(new_query) = self.delegate.confirm_completion(self.query(cx), window, cx) {
557 self.set_query(new_query, window, cx);
558 } else {
559 cx.propagate()
560 }
561 }
562
563 fn handle_click(
564 &mut self,
565 ix: usize,
566 secondary: bool,
567 window: &mut Window,
568 cx: &mut Context<Self>,
569 ) {
570 cx.stop_propagation();
571 window.prevent_default();
572 self.set_selected_index(ix, None, false, window, cx);
573 self.do_confirm(secondary, window, cx)
574 }
575
576 fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {
577 if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {
578 self.set_query(update_query, window, cx);
579 self.set_selected_index(0, Some(Direction::Down), false, window, cx);
580 } else {
581 self.delegate.confirm(secondary, window, cx)
582 }
583 }
584
585 fn on_input_editor_event(
586 &mut self,
587 _: &Entity<Editor>,
588 event: &editor::EditorEvent,
589 window: &mut Window,
590 cx: &mut Context<Self>,
591 ) {
592 let Head::Editor(editor) = &self.head else {
593 panic!("unexpected call");
594 };
595 match event {
596 editor::EditorEvent::BufferEdited => {
597 let query = editor.read(cx).text(cx);
598 self.update_matches(query, window, cx);
599 }
600 editor::EditorEvent::Blurred => {
601 if self.is_modal {
602 self.cancel(&menu::Cancel, window, cx);
603 }
604 }
605 _ => {}
606 }
607 }
608
609 fn on_empty_head_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
610 let Head::Empty(_) = &self.head else {
611 panic!("unexpected call");
612 };
613 self.cancel(&menu::Cancel, window, cx);
614 }
615
616 pub fn refresh_placeholder(&mut self, window: &mut Window, cx: &mut App) {
617 match &self.head {
618 Head::Editor(editor) => {
619 let placeholder = self.delegate.placeholder_text(window, cx);
620 editor.update(cx, |editor, cx| {
621 editor.set_placeholder_text(placeholder.as_ref(), window, cx);
622 cx.notify();
623 });
624 }
625 Head::Empty(_) => {}
626 }
627 }
628
629 pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
630 let query = self.query(cx);
631 self.update_matches(query, window, cx);
632 }
633
634 pub fn update_matches(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
635 let delegate_pending_update_matches = self.delegate.update_matches(query, window, cx);
636
637 self.matches_updated(window, cx);
638 // This struct ensures that we can synchronously drop the task returned by the
639 // delegate's `update_matches` method and the task that the picker is spawning.
640 // If we simply capture the delegate's task into the picker's task, when the picker's
641 // task gets synchronously dropped, the delegate's task would keep running until
642 // the picker's task has a chance of being scheduled, because dropping a task happens
643 // asynchronously.
644 self.pending_update_matches = Some(PendingUpdateMatches {
645 delegate_update_matches: Some(delegate_pending_update_matches),
646 _task: cx.spawn_in(window, async move |this, cx| {
647 let delegate_pending_update_matches = this.update(cx, |this, _| {
648 this.pending_update_matches
649 .as_mut()
650 .unwrap()
651 .delegate_update_matches
652 .take()
653 .unwrap()
654 })?;
655 delegate_pending_update_matches.await;
656 this.update_in(cx, |this, window, cx| {
657 this.matches_updated(window, cx);
658 })
659 }),
660 });
661 }
662
663 fn matches_updated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
664 if let ElementContainer::List(state) = &mut self.element_container {
665 state.reset(self.delegate.match_count());
666 }
667
668 let index = self.delegate.selected_index();
669 self.scroll_to_item_index(index);
670 self.pending_update_matches = None;
671 if let Some(secondary) = self.confirm_on_update.take() {
672 self.do_confirm(secondary, window, cx);
673 }
674 cx.notify();
675 }
676
677 pub fn query(&self, cx: &App) -> String {
678 match &self.head {
679 Head::Editor(editor) => editor.read(cx).text(cx),
680 Head::Empty(_) => "".to_string(),
681 }
682 }
683
684 pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
685 if let Head::Editor(editor) = &self.head {
686 editor.update(cx, |editor, cx| {
687 editor.set_text(query, window, cx);
688 let editor_offset = editor.buffer().read(cx).len(cx);
689 editor.change_selections(
690 SelectionEffects::scroll(Autoscroll::Next),
691 window,
692 cx,
693 |s| s.select_ranges(Some(editor_offset..editor_offset)),
694 );
695 });
696 }
697 }
698
699 fn scroll_to_item_index(&mut self, ix: usize) {
700 match &mut self.element_container {
701 ElementContainer::List(state) => state.scroll_to_reveal_item(ix),
702 ElementContainer::UniformList(scroll_handle) => {
703 scroll_handle.scroll_to_item(ix, ScrollStrategy::Top)
704 }
705 }
706 }
707
708 fn render_element(
709 &self,
710 window: &mut Window,
711 cx: &mut Context<Self>,
712 ix: usize,
713 ) -> impl IntoElement + use<D> {
714 div()
715 .id(("item", ix))
716 .cursor_pointer()
717 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
718 this.handle_click(ix, event.modifiers().secondary(), window, cx)
719 }))
720 // As of this writing, GPUI intercepts `ctrl-[mouse-event]`s on macOS
721 // and produces right mouse button events. This matches platforms norms
722 // but means that UIs which depend on holding ctrl down (such as the tab
723 // switcher) can't be clicked on. Hence, this handler.
724 .on_mouse_up(
725 MouseButton::Right,
726 cx.listener(move |this, event: &MouseUpEvent, window, cx| {
727 // We specifically want to use the platform key here, as
728 // ctrl will already be held down for the tab switcher.
729 this.handle_click(ix, event.modifiers.platform, window, cx)
730 }),
731 )
732 .children(self.delegate.render_match(
733 ix,
734 ix == self.delegate.selected_index(),
735 window,
736 cx,
737 ))
738 .when(
739 self.delegate.separators_after_indices().contains(&ix),
740 |picker| {
741 picker
742 .border_color(cx.theme().colors().border_variant)
743 .border_b_1()
744 .py(px(-1.0))
745 },
746 )
747 }
748
749 fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {
750 let sizing_behavior = if self.max_height.is_some() {
751 ListSizingBehavior::Infer
752 } else {
753 ListSizingBehavior::Auto
754 };
755
756 match &self.element_container {
757 ElementContainer::UniformList(scroll_handle) => uniform_list(
758 "candidates",
759 self.delegate.match_count(),
760 cx.processor(move |picker, visible_range: Range<usize>, window, cx| {
761 visible_range
762 .map(|ix| picker.render_element(window, cx, ix))
763 .collect()
764 }),
765 )
766 .with_sizing_behavior(sizing_behavior)
767 .when_some(self.widest_item, |el, widest_item| {
768 el.with_width_from_item(Some(widest_item))
769 })
770 .flex_grow()
771 .py_1()
772 .track_scroll(scroll_handle.clone())
773 .into_any_element(),
774 ElementContainer::List(state) => list(
775 state.clone(),
776 cx.processor(|this, ix, window, cx| {
777 this.render_element(window, cx, ix).into_any_element()
778 }),
779 )
780 .with_sizing_behavior(sizing_behavior)
781 .flex_grow()
782 .py_2()
783 .into_any_element(),
784 }
785 }
786
787 #[cfg(any(test, feature = "test-support"))]
788 pub fn logical_scroll_top_index(&self) -> usize {
789 match &self.element_container {
790 ElementContainer::List(state) => state.logical_scroll_top().item_ix,
791 ElementContainer::UniformList(scroll_handle) => {
792 scroll_handle.logical_scroll_top_index()
793 }
794 }
795 }
796}
797
798impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
799impl<D: PickerDelegate> ModalView for Picker<D> {}
800
801impl<D: PickerDelegate> Render for Picker<D> {
802 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
803 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
804 let window_size = window.viewport_size();
805 let rem_size = window.rem_size();
806 let is_wide_window = window_size.width / rem_size > rems_from_px(800.).0;
807
808 let aside = self.delegate.documentation_aside(window, cx);
809
810 let editor_position = self.delegate.editor_position();
811 let menu = v_flex()
812 .key_context("Picker")
813 .size_full()
814 .when_some(self.width, |el, width| el.w(width))
815 .overflow_hidden()
816 // This is a bit of a hack to remove the modal styling when we're rendering the `Picker`
817 // as a part of a modal rather than the entire modal.
818 //
819 // We should revisit how the `Picker` is styled to make it more composable.
820 .when(self.is_modal, |this| this.elevation_3(cx))
821 .on_action(cx.listener(Self::select_next))
822 .on_action(cx.listener(Self::select_previous))
823 .on_action(cx.listener(Self::editor_move_down))
824 .on_action(cx.listener(Self::editor_move_up))
825 .on_action(cx.listener(Self::select_first))
826 .on_action(cx.listener(Self::select_last))
827 .on_action(cx.listener(Self::cancel))
828 .on_action(cx.listener(Self::confirm))
829 .on_action(cx.listener(Self::secondary_confirm))
830 .on_action(cx.listener(Self::confirm_completion))
831 .on_action(cx.listener(Self::confirm_input))
832 .children(match &self.head {
833 Head::Editor(editor) => {
834 if editor_position == PickerEditorPosition::Start {
835 Some(self.delegate.render_editor(&editor.clone(), window, cx))
836 } else {
837 None
838 }
839 }
840 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
841 })
842 .when(self.delegate.match_count() > 0, |el| {
843 el.child(
844 v_flex()
845 .id("element-container")
846 .relative()
847 .flex_grow()
848 .when_some(self.max_height, |div, max_h| div.max_h(max_h))
849 .overflow_hidden()
850 .children(self.delegate.render_header(window, cx))
851 .child(self.render_element_container(cx))
852 .when(self.show_scrollbar, |this| {
853 let base_scrollbar_config =
854 Scrollbars::new(ScrollAxes::Vertical).width_sm();
855
856 this.map(|this| match &self.element_container {
857 ElementContainer::List(state) => this.custom_scrollbars(
858 base_scrollbar_config.tracked_scroll_handle(state.clone()),
859 window,
860 cx,
861 ),
862 ElementContainer::UniformList(state) => this.custom_scrollbars(
863 base_scrollbar_config.tracked_scroll_handle(state.clone()),
864 window,
865 cx,
866 ),
867 })
868 }),
869 )
870 })
871 .when(self.delegate.match_count() == 0, |el| {
872 el.when_some(self.delegate.no_matches_text(window, cx), |el, text| {
873 el.child(
874 v_flex().flex_grow().py_2().child(
875 ListItem::new("empty_state")
876 .inset(true)
877 .spacing(ListItemSpacing::Sparse)
878 .disabled(true)
879 .child(Label::new(text).color(Color::Muted)),
880 ),
881 )
882 })
883 })
884 .children(self.delegate.render_footer(window, cx))
885 .children(match &self.head {
886 Head::Editor(editor) => {
887 if editor_position == PickerEditorPosition::End {
888 Some(self.delegate.render_editor(&editor.clone(), window, cx))
889 } else {
890 None
891 }
892 }
893 Head::Empty(empty_head) => Some(div().child(empty_head.clone())),
894 });
895
896 let Some(aside) = aside else {
897 return menu;
898 };
899
900 let render_aside = |aside: DocumentationAside, cx: &mut Context<Self>| {
901 WithRemSize::new(ui_font_size)
902 .occlude()
903 .elevation_2(cx)
904 .w_full()
905 .p_2()
906 .overflow_hidden()
907 .when(is_wide_window, |this| this.max_w_96())
908 .when(!is_wide_window, |this| this.max_w_48())
909 .child((aside.render)(cx))
910 };
911
912 if is_wide_window {
913 div().relative().child(menu).child(
914 h_flex()
915 .absolute()
916 .when(aside.side == DocumentationSide::Left, |this| {
917 this.right_full().mr_1()
918 })
919 .when(aside.side == DocumentationSide::Right, |this| {
920 this.left_full().ml_1()
921 })
922 .when(aside.edge == DocumentationEdge::Top, |this| this.top_0())
923 .when(aside.edge == DocumentationEdge::Bottom, |this| {
924 this.bottom_0()
925 })
926 .child(render_aside(aside, cx)),
927 )
928 } else {
929 v_flex()
930 .w_full()
931 .gap_1()
932 .justify_end()
933 .child(render_aside(aside, cx))
934 .child(menu)
935 }
936 }
937}