1use gpui_base::LogicalStyledExt as _;
2use gpui_base::TestSupportExt as _;
3use std::rc::Rc;
4
5use gpui::{
6 AbsoluteLength, AnyElement, App, AppContext as _, AvailableSpace, Context, Entity, FocusHandle,
7 Focusable, FontFallbacks, FontFeatures, FontStyle, FontWeight, InteractiveElement, IntoElement,
8 KeyBinding, Keystroke, ListSizingBehavior, ParentElement, Pixels, Render, Role, ScrollStrategy,
9 SharedString, Size, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription,
10 TextOverflow, WhiteSpace, Window, div, prelude::FluentBuilder as _, px, size,
11};
12use rust_i18n::t;
13
14use crate::{
15 ActiveTheme as _, ElementExt as _, Icon, IconName, IndexPath, StyledExt as _,
16 VirtualListScrollHandle,
17 actions::{Cancel, Confirm, SelectDown, SelectUp},
18 command::{
19 command::CommandOptions,
20 item::{CommandEntry, CommandItem},
21 },
22 h_flex,
23 input::{Input, InputEvent, InputState},
24 kbd::Kbd,
25 scroll::Scrollbar,
26 v_flex, v_virtual_list,
27};
28
29pub(crate) const CONTEXT: &str = "Command";
30
31const SEPARATOR_ROW_HEIGHT: f32 = 9.;
34
35pub(crate) type OnQuery = dyn Fn(&str, &mut Window, &mut App);
36pub(crate) type OnIndex = dyn Fn(IndexPath, &mut Window, &mut App);
37pub(crate) type OnCancel = dyn Fn(&mut Window, &mut App);
38
39pub(crate) struct CommandModel {
40 pub(crate) entries: Vec<CommandEntry>,
41 pub(crate) searchable: bool,
42 pub(crate) filterable: bool,
43 pub(crate) highlight_matches: bool,
44 pub(crate) on_query: Option<Rc<OnQuery>>,
45 pub(crate) on_select: Option<Rc<OnIndex>>,
46 pub(crate) on_confirm: Option<Rc<OnIndex>>,
47 pub(crate) on_cancel: Option<Rc<OnCancel>>,
48}
49
50impl Default for CommandModel {
51 fn default() -> Self {
52 Self {
53 entries: Vec::new(),
54 searchable: true,
55 filterable: true,
56 highlight_matches: false,
57 on_query: None,
58 on_select: None,
59 on_confirm: None,
60 on_cancel: None,
61 }
62 }
63}
64
65pub(crate) fn init(cx: &mut App) {
66 let context: Option<&str> = Some(CONTEXT);
67 cx.bind_keys([
68 KeyBinding::new("escape", Cancel, context),
69 KeyBinding::new("enter", Confirm { secondary: false }, context),
70 KeyBinding::new("up", SelectUp, context),
71 KeyBinding::new("down", SelectDown, context),
72 ]);
73}
74
75#[derive(Clone, PartialEq)]
80enum CommandRow {
81 Heading(SharedString),
82 Item(usize),
84 Separator,
85}
86
87#[derive(Clone, PartialEq)]
88struct TextShapeKey {
89 font_family: SharedString,
90 font_features: FontFeatures,
91 font_fallbacks: Option<FontFallbacks>,
92 font_size: AbsoluteLength,
93 font_weight: FontWeight,
94 font_style: FontStyle,
95 white_space: WhiteSpace,
96 text_overflow: Option<TextOverflow>,
97 line_clamp: Option<usize>,
98}
99
100#[derive(Clone, PartialEq)]
101struct ListMeasurementKey {
102 content_width: Pixels,
103 rem_size: Pixels,
104 line_height: Pixels,
105 text_shape: TextShapeKey,
106}
107
108#[derive(Clone)]
110struct MatchedItem {
111 entry_ix: usize,
112 item_ix: usize,
113 index_path: IndexPath,
114 row_ix: usize,
115 disabled: bool,
116}
117
118pub struct CommandState {
121 focus_handle: FocusHandle,
122 query_input: Entity<InputState>,
123 scroll_handle: VirtualListScrollHandle,
124 model: CommandModel,
125 rows: Vec<CommandRow>,
126 row_sizes: Rc<Vec<Size<Pixels>>>,
127 list_measurement_key: Option<ListMeasurementKey>,
128 needs_measure: bool,
129 measured_bindings: Vec<Option<Keystroke>>,
133 matched: Vec<MatchedItem>,
134 selected_index: Option<usize>,
135 preserve_no_selection: bool,
136 loading: bool,
137 pending_scroll: Option<usize>,
138 applied_placeholder: SharedString,
142 applied_query: SharedString,
143 pub(crate) options: CommandOptions,
144 _subscriptions: Vec<Subscription>,
145}
146
147impl CommandState {
148 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
150 let query_input = cx.new(|cx| InputState::new(window, cx));
151
152 let _subscriptions =
153 vec![cx.subscribe_in(&query_input, window, Self::on_query_input_event)];
154
155 Self {
156 focus_handle: cx.focus_handle(),
157 query_input,
158 scroll_handle: VirtualListScrollHandle::new(),
159 model: CommandModel::default(),
160 rows: Vec::new(),
161 row_sizes: Rc::new(Vec::new()),
162 list_measurement_key: None,
163 needs_measure: true,
164 measured_bindings: Vec::new(),
165 matched: Vec::new(),
166 selected_index: None,
167 preserve_no_selection: false,
168 loading: false,
169 pending_scroll: None,
170 applied_placeholder: SharedString::default(),
171 applied_query: SharedString::default(),
172 options: CommandOptions::default(),
173 _subscriptions,
174 }
175 }
176
177 pub(crate) fn set_options(&mut self, options: CommandOptions) {
179 if self.options.style.text != options.style.text {
180 self.needs_measure = true;
181 }
182 self.options = options;
183 }
184
185 pub(crate) fn install_model(&mut self, model: CommandModel, cx: &mut Context<Self>) {
186 let selected_index_path = self.selected_index();
187 let same_layout = self.model.searchable == model.searchable
191 && self.model.filterable == model.filterable
192 && self.model.entries.len() == model.entries.len()
193 && self
194 .model
195 .entries
196 .iter()
197 .zip(&model.entries)
198 .all(|(entry, other)| entry.same_layout(other));
199 self.model = model;
200 if !same_layout {
201 self.update_matches(cx);
202 }
203
204 let preserved_selection = selected_index_path.and_then(|selected_index_path| {
205 self.matched
206 .iter()
207 .enumerate()
208 .find_map(|(matched_ix, matched)| {
209 (!matched.disabled && matched.index_path == selected_index_path)
210 .then_some(matched_ix)
211 })
212 });
213
214 if let Some(matched_ix) = preserved_selection {
215 self.selected_index = Some(matched_ix);
219 self.preserve_no_selection = false;
220 } else if self.preserve_no_selection {
221 self.selected_index = None;
222 self.pending_scroll = None;
223 } else {
224 self.reset_selection();
225 }
226 }
227
228 pub fn query(&self, cx: &App) -> SharedString {
230 self.query_input.read(cx).value()
231 }
232
233 pub fn set_query(
238 &mut self,
239 query: impl Into<SharedString>,
240 window: &mut Window,
241 cx: &mut Context<Self>,
242 ) {
243 let query = query.into();
244 if self.query(cx) == query {
245 return;
246 }
247
248 self.query_input
249 .update(cx, |input, cx| input.set_value(query, window, cx));
250 self.on_query_changed(window, cx);
251 }
252
253 pub fn selected_index(&self) -> Option<IndexPath> {
260 self.selected_index
261 .and_then(|selected_index| self.matched.get(selected_index))
262 .filter(|matched| !matched.disabled)
263 .map(|matched| matched.index_path)
264 }
265
266 pub fn set_selected_index(
272 &mut self,
273 index: Option<IndexPath>,
274 window: &mut Window,
275 cx: &mut Context<Self>,
276 ) {
277 let matched_ix = index.and_then(|index| {
278 self.matched
279 .iter()
280 .position(|matched| matched.index_path == index && !matched.disabled)
281 });
282
283 let preserve_no_selection = matched_ix.is_none();
284 if self.selected_index == matched_ix {
285 self.preserve_no_selection = preserve_no_selection;
286 return;
287 }
288
289 let previous_index = self.selected_index();
290 self.selected_index = matched_ix;
291 self.preserve_no_selection = preserve_no_selection;
292 self.pending_scroll = matched_ix
293 .and_then(|matched_ix| self.matched.get(matched_ix))
294 .map(|matched| matched.row_ix);
295
296 if let Some((on_select, index)) = self.on_select_if_changed(previous_index) {
297 window.defer(cx, move |window, cx| on_select(index, window, cx));
298 }
299
300 cx.notify();
301 }
302
303 pub fn matched_count(&self) -> usize {
305 self.matched.len()
306 }
307
308 pub fn focus(&self, window: &mut Window, cx: &mut App) {
310 if self.model.searchable {
311 self.query_input.focus_handle(cx).focus(window, cx);
312 } else {
313 self.focus_handle.focus(window, cx);
314 }
315 }
316
317 pub fn set_loading(&mut self, loading: bool, window: &mut Window, cx: &mut Context<Self>) {
322 self.loading = loading;
323 self.query_input
324 .update(cx, |input, cx| input.set_loading(loading, window, cx));
325 cx.notify();
326 }
327
328 pub fn is_loading(&self) -> bool {
330 self.loading
331 }
332
333 fn item_matches(&self, item: &CommandItem, query: &str) -> bool {
336 if !self.model.searchable || !self.model.filterable || query.is_empty() {
337 true
338 } else {
339 item.matches(query)
340 }
341 }
342
343 fn highlighted_query(&self) -> &str {
346 if self.model.highlight_matches && self.model.searchable && self.model.filterable {
347 self.applied_query.trim()
348 } else {
349 ""
350 }
351 }
352
353 fn item_at(&self, matched_ix: usize) -> Option<&CommandItem> {
354 let matched = self.matched.get(matched_ix)?;
355
356 match self.model.entries.get(matched.entry_ix)? {
357 CommandEntry::Item(item) => Some(item),
358 CommandEntry::Group(group) => group.items.get(matched.item_ix),
359 CommandEntry::Separator => None,
360 }
361 }
362
363 fn update_matches(&mut self, cx: &App) {
366 let query = self.query(cx);
367 let query = query.trim();
368
369 let mut rows: Vec<CommandRow> = Vec::new();
370 let mut matched: Vec<MatchedItem> = Vec::new();
371 let has_ungrouped_items = self
372 .model
373 .entries
374 .iter()
375 .any(|entry| matches!(entry, CommandEntry::Item(_)));
376 let mut ungrouped_item_ix = 0;
377 let mut group_ix = 0;
378 let mut pending_separator = false;
381
382 for (entry_ix, entry) in self.model.entries.iter().enumerate() {
383 match entry {
384 CommandEntry::Separator => pending_separator = !rows.is_empty(),
385 CommandEntry::Item(item) => {
386 let item_ix = ungrouped_item_ix;
387 ungrouped_item_ix += 1;
388 if !self.item_matches(item, query) {
389 continue;
390 }
391
392 if pending_separator {
393 rows.push(CommandRow::Separator);
394 pending_separator = false;
395 }
396
397 let index_path = IndexPath::new(item_ix).section(0);
398 matched.push(MatchedItem {
399 entry_ix,
400 item_ix: 0,
401 index_path,
402 row_ix: rows.len(),
403 disabled: item.is_disabled(),
404 });
405 rows.push(CommandRow::Item(matched.len() - 1));
406 }
407 CommandEntry::Group(group) => {
408 let section_ix = group_ix + usize::from(has_ungrouped_items);
409 group_ix += 1;
410 let visible = group
411 .items
412 .iter()
413 .enumerate()
414 .filter(|(_, item)| self.item_matches(item, query))
415 .map(|(item_ix, item)| (item_ix, item.is_disabled()))
416 .collect::<Vec<_>>();
417
418 if visible.is_empty() {
419 continue;
420 }
421
422 if pending_separator {
423 rows.push(CommandRow::Separator);
424 pending_separator = false;
425 }
426
427 if let Some(heading) = group.heading() {
428 rows.push(CommandRow::Heading(heading.clone()));
429 }
430
431 for (item_ix, disabled) in visible {
432 let index_path = IndexPath::new(item_ix).section(section_ix);
433 matched.push(MatchedItem {
434 entry_ix,
435 item_ix,
436 index_path,
437 row_ix: rows.len(),
438 disabled,
439 });
440 rows.push(CommandRow::Item(matched.len() - 1));
441 }
442 }
443 }
444 }
445
446 self.rows = rows;
447 self.matched = matched;
448 self.needs_measure = true;
449 self.selected_index = self.selected_index.and_then(|selected_index| {
450 (selected_index < self.matched.len()).then_some(selected_index)
451 });
452 }
453
454 fn reset_selection(&mut self) {
456 self.selected_index = self.matched.iter().position(|matched| !matched.disabled);
457 self.preserve_no_selection = false;
458 self.pending_scroll = self
459 .selected_index
460 .and_then(|selected_index| self.matched.get(selected_index))
461 .map(|matched| matched.row_ix)
462 .or(Some(0));
463 }
464
465 fn on_query_input_event(
466 &mut self,
467 _: &Entity<InputState>,
468 event: &InputEvent,
469 window: &mut Window,
470 cx: &mut Context<Self>,
471 ) {
472 if !matches!(event, InputEvent::Change) {
473 return;
474 }
475
476 self.on_query_changed(window, cx);
477 }
478
479 fn on_query_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
481 let query = self.query(cx);
482 if query == self.applied_query {
483 return;
484 }
485
486 let previous_selection = self.selected_index();
487 self.applied_query = query.clone();
488 self.update_matches(cx);
489 self.reset_selection();
490 let selection_callback = self.on_select_if_changed(previous_selection);
491 let query_callback = self
492 .model
493 .searchable
494 .then(|| self.model.on_query.clone())
495 .flatten();
496
497 if selection_callback.is_some() || query_callback.is_some() {
498 window.defer(cx, move |window, cx| {
499 if let Some((on_select, index)) = selection_callback {
500 on_select(index, window, cx);
501 }
502 if let Some(on_query) = query_callback {
503 on_query(query.as_ref(), window, cx);
504 }
505 });
506 }
507
508 cx.notify();
509 }
510
511 fn set_list_measurement_key(
512 &mut self,
513 measurement_key: ListMeasurementKey,
514 window: &mut Window,
515 cx: &mut Context<Self>,
516 ) {
517 if self.list_measurement_key.as_ref() == Some(&measurement_key) {
518 return;
519 }
520
521 self.list_measurement_key = Some(measurement_key);
522 self.measure_on_next_frame(window, cx);
523 }
524
525 fn measure_on_next_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
528 self.needs_measure = true;
529 let entity_id = cx.entity_id();
530 window.on_next_frame(move |_, cx| cx.notify(entity_id));
531 }
532
533 fn on_select_if_changed(
536 &self,
537 previous_index: Option<IndexPath>,
538 ) -> Option<(Rc<OnIndex>, IndexPath)> {
539 let index = self.selected_index();
540 if index == previous_index {
541 return None;
542 }
543
544 self.model.on_select.clone().zip(index)
545 }
546
547 fn select(&mut self, matched_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
551 if self.selected_index == Some(matched_ix) {
552 return;
553 }
554
555 let previous_index = self.selected_index();
556 self.selected_index = Some(matched_ix);
557 self.preserve_no_selection = false;
558
559 if let Some((on_select, index)) = self.on_select_if_changed(previous_index) {
560 window.defer(cx, move |window, cx| on_select(index, window, cx));
561 }
562
563 cx.notify();
564 }
565
566 fn select_by(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
569 let len = self.matched.len();
570 if len == 0 {
571 return;
572 }
573
574 let mut next = self
575 .selected_index
576 .unwrap_or_else(|| if step >= 0 { len.saturating_sub(1) } else { 0 });
577 let mut enabled = None;
578 for _ in 0..len {
579 next = (next as isize + step).rem_euclid(len as isize) as usize;
580 if !self.matched[next].disabled {
581 enabled = Some(next);
582 break;
583 }
584 }
585
586 if let Some(next) = enabled
587 && self.selected_index != Some(next)
588 {
589 self.pending_scroll = self.matched.get(next).map(|matched| matched.row_ix);
590 self.select(next, window, cx);
591 }
592 }
593
594 fn on_action_select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
595 self.select_by(-1, window, cx);
596 }
597
598 fn on_action_select_down(
599 &mut self,
600 _: &SelectDown,
601 window: &mut Window,
602 cx: &mut Context<Self>,
603 ) {
604 self.select_by(1, window, cx);
605 }
606
607 fn on_action_confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
608 if let Some(selected_index) = self.selected_index {
609 self.confirm(selected_index, window, cx);
610 }
611 }
612
613 fn on_action_cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
616 if self.model.searchable && !self.query(cx).is_empty() {
617 self.set_query("", window, cx);
618 return;
619 }
620
621 if let Some(on_cancel) = self.model.on_cancel.clone() {
624 on_cancel(window, cx);
625 }
626
627 cx.propagate();
628 }
629
630 fn confirm(&mut self, matched_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
631 let Some(item) = self.item_at(matched_ix) else {
632 return;
633 };
634 if item.is_disabled() {
635 return;
636 }
637
638 let index_path = self.matched[matched_ix].index_path;
639 let action = item.action.as_ref().map(|action| action.boxed_clone());
640 let on_confirm = self.model.on_confirm.clone();
641
642 if let Some(action) = action {
643 window.dispatch_action(action, cx);
644 }
645 if let Some(on_confirm) = on_confirm {
646 window.defer(cx, move |window, cx| {
647 on_confirm(index_path, window, cx);
648 });
649 }
650 }
651
652 fn measure_rows(&mut self, window: &mut Window, cx: &mut Context<Self>) {
657 let available = size(
658 self.list_measurement_key
659 .as_ref()
660 .map_or(AvailableSpace::MinContent, |key| {
661 AvailableSpace::Definite(key.content_width)
662 }),
663 AvailableSpace::MinContent,
664 );
665 let mut text_style = StyleRefinement::default();
666 text_style.text = self.options.style.text.clone();
667 let mut bindings = vec![None; self.matched.len()];
668
669 let row_sizes = self
670 .rows
671 .iter()
672 .enumerate()
673 .map(|(row_ix, row)| {
674 let row = match row {
675 CommandRow::Separator => return size(px(0.), px(SEPARATOR_ROW_HEIGHT)),
676 CommandRow::Heading(_) => self.render_row(row_ix, window, cx),
677 CommandRow::Item(matched_ix) => {
678 let binding = self.item_binding(*matched_ix, window, cx);
679 bindings[*matched_ix] = binding.as_ref().map(|kbd| kbd.keystroke().clone());
680 self.render_item_with_binding(*matched_ix, binding, window, cx)
681 }
682 };
683 let row_size = div()
684 .refine_style(&text_style)
685 .child(row)
686 .into_any_element()
687 .layout_as_root(available, window, cx);
688 size(px(0.), row_size.height)
689 })
690 .collect::<Vec<_>>();
691
692 self.row_sizes = Rc::new(row_sizes);
693 self.measured_bindings = bindings;
694 }
695
696 fn sync_placeholder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
699 let placeholder = self
700 .options
701 .placeholder
702 .as_ref()
703 .cloned()
704 .unwrap_or_else(|| t!("Command.placeholder").to_string().into());
705
706 if self.applied_placeholder == placeholder {
707 return;
708 }
709
710 self.applied_placeholder = placeholder.clone();
711 self.query_input.update(cx, |input, cx| {
712 input.set_placeholder(placeholder, window, cx)
713 });
714 }
715
716 fn item_radius(&self, window: &Window, cx: &App) -> Pixels {
721 let theme = cx.theme();
722 let rem_size = window.rem_size();
723 let own_radius = self.options.style.corner_radii.top_left;
724 let (outer, border) = match (self.options.bordered, own_radius) {
725 (true, radius) => (
726 radius.map_or(theme.radius_lg, |r| r.to_pixels(rem_size)),
727 px(1.),
728 ),
729 (false, Some(radius)) => (radius.to_pixels(rem_size), px(0.)),
730 (false, None) => return theme.radius,
731 };
732 (outer - rem_size * 0.25 - border).max(px(0.))
733 }
734
735 fn item_row(&self, selected: bool, window: &Window, cx: &App) -> gpui::Div {
738 div()
739 .flex()
740 .flex_row()
741 .items_center()
742 .w_full()
743 .gap_2()
744 .px_2()
745 .py_1p5()
746 .text_sm()
747 .rounded(self.item_radius(window, cx))
748 .when(selected, |this| {
749 this.bg(cx.theme().accent)
750 .text_color(cx.theme().accent_foreground)
751 })
752 }
753
754 fn heading_row(&self, heading: SharedString, cx: &App) -> gpui::Div {
755 div()
756 .w_full()
757 .px_2()
758 .py_1p5()
759 .text_xs()
760 .font_medium()
761 .text_color(cx.theme().muted_foreground)
762 .child(heading)
763 }
764
765 fn render_row(&self, row_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
766 match self.rows.get(row_ix) {
767 None => div().into_any_element(),
768 Some(CommandRow::Separator) => div()
769 .w_full()
770 .py(px(4.))
771 .child(div().h(px(1.)).w_full().bg(cx.theme().border))
772 .into_any_element(),
773 Some(CommandRow::Heading(heading)) => {
774 self.heading_row(heading.clone(), cx).into_any_element()
775 }
776 Some(CommandRow::Item(matched_ix)) => self.render_item(*matched_ix, window, cx),
777 }
778 }
779
780 fn render_visible_row(
783 &mut self,
784 row_ix: usize,
785 window: &mut Window,
786 cx: &mut Context<Self>,
787 ) -> AnyElement {
788 let Some(&CommandRow::Item(matched_ix)) = self.rows.get(row_ix) else {
789 return self.render_row(row_ix, window, cx);
790 };
791
792 let binding = self.item_binding(matched_ix, window, cx);
793 let measured = self
794 .measured_bindings
795 .get(matched_ix)
796 .and_then(Option::as_ref);
797 if !self.needs_measure && measured != binding.as_ref().map(Kbd::keystroke) {
798 self.measure_on_next_frame(window, cx);
799 }
800
801 self.render_item_with_binding(matched_ix, binding, window, cx)
802 }
803
804 fn item_binding(&self, matched_ix: usize, window: &Window, cx: &App) -> Option<Kbd> {
807 let item = self.item_at(matched_ix)?;
808 if item.content.is_some() {
809 return None;
810 }
811
812 let action = item.action.as_ref()?;
813 Kbd::binding_for_action_in(action.as_ref(), &self.focus_handle(cx), window)
814 .or_else(|| Kbd::binding_for_action(action.as_ref(), None, window))
815 }
816
817 fn render_item(
818 &self,
819 matched_ix: usize,
820 window: &mut Window,
821 cx: &mut Context<Self>,
822 ) -> AnyElement {
823 let binding = self.item_binding(matched_ix, window, cx);
824 self.render_item_with_binding(matched_ix, binding, window, cx)
825 }
826
827 fn render_item_with_binding(
828 &self,
829 matched_ix: usize,
830 binding: Option<Kbd>,
831 window: &mut Window,
832 cx: &mut Context<Self>,
833 ) -> AnyElement {
834 let Some(item) = self.item_at(matched_ix) else {
835 return div().into_any_element();
836 };
837
838 let disabled = item.is_disabled();
839 let selected = self.selected_index == Some(matched_ix) && !disabled;
840 let muted_foreground = cx.theme().muted_foreground;
841 let icon_color = if selected {
842 cx.theme().accent_foreground
843 } else {
844 muted_foreground
845 };
846 let content = match &item.content {
847 Some(render) => render(window, cx),
848 None => h_flex()
849 .flex_row_dir(cx)
850 .flex_1()
851 .gap_2()
852 .items_center()
853 .when_some(item.icon.clone(), |this, icon| {
854 this.child(icon.size_4().text_color(icon_color))
855 })
856 .when_some(item.label_text().cloned(), |this, label| {
857 this.child(crate::label::highlight_matches(
858 label,
859 self.highlighted_query(),
860 cx,
861 ))
862 })
863 .into_any_element(),
864 };
865
866 self.item_row(selected, window, cx)
867 .id(self.matched[matched_ix].index_path)
868 .test_support()
869 .role(Role::ListBoxOption)
870 .when_some(item.label_text().cloned(), |this, label| {
873 this.aria_label(label)
874 })
875 .aria_selected(selected)
876 .when(disabled, |this| this.text_color(muted_foreground))
877 .when(!disabled, |this| {
878 this.cursor_default()
879 .on_hover(cx.listener(move |this, hovered: &bool, window, cx| {
880 if *hovered {
881 this.select(matched_ix, window, cx);
882 }
883 }))
884 .on_click(cx.listener(move |this, _, window, cx| {
885 this.confirm(matched_ix, window, cx);
886 }))
887 })
888 .child(content)
889 .map(|this| match binding {
890 Some(binding) => this.child(binding.ms(gpui::Length::Auto, cx)),
891 None => this.when(item.checked, |this| {
894 this.child(crate::Sizable::xsmall(
895 Icon::new(IconName::Check).ms(gpui::Length::Auto, cx),
896 ))
897 }),
898 })
899 .into_any_element()
900 }
901
902 fn render_empty(&self, window: &mut Window, cx: &mut App) -> AnyElement {
903 if let Some(empty) = self.options.empty.as_ref() {
904 return empty(self, window, cx);
905 }
906
907 let message: SharedString = t!("Command.empty").to_string().into();
908
909 div()
910 .py_6()
911 .w_full()
912 .text_center()
913 .text_sm()
914 .text_color(cx.theme().muted_foreground)
915 .child(message)
916 .into_any_element()
917 }
918}
919
920impl Focusable for CommandState {
921 fn focus_handle(&self, cx: &App) -> FocusHandle {
922 if self.model.searchable {
923 self.query_input.focus_handle(cx)
924 } else {
925 self.focus_handle.clone()
926 }
927 }
928}
929
930impl Render for CommandState {
931 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
932 self.sync_placeholder(window, cx);
933
934 if self.needs_measure {
935 self.needs_measure = false;
936 self.measure_rows(window, cx);
937 }
938
939 if let Some(row_ix) = self.pending_scroll.take() {
940 self.scroll_handle
941 .scroll_to_item(row_ix, ScrollStrategy::Nearest);
942 }
943
944 let rows_count = self.rows.len();
945 let row_sizes = self.row_sizes.clone();
946 let command_state = cx.entity();
947
948 v_flex()
949 .id("command")
950 .test_support()
951 .key_context(CONTEXT)
952 .track_focus(&self.focus_handle)
953 .on_action(cx.listener(Self::on_action_select_up))
954 .on_action(cx.listener(Self::on_action_select_down))
955 .on_action(cx.listener(Self::on_action_confirm))
956 .on_action(cx.listener(Self::on_action_cancel))
957 .w_full()
958 .overflow_hidden()
959 .bg(cx.theme().popover)
960 .text_color(cx.theme().popover_foreground)
961 .when(self.options.bordered, |this| {
962 this.rounded(cx.theme().radius_lg)
963 .border_1()
964 .border_color(cx.theme().border)
965 })
966 .refine_style(&self.options.style)
967 .when_some(self.options.header.as_ref(), |this, header| {
968 this.child(header(self, window, cx))
969 })
970 .when(self.model.searchable, |this| {
971 this.child(
972 div()
973 .flex_none()
974 .px_3()
975 .border_b_1()
976 .border_color(cx.theme().border)
977 .child(
978 Input::new(&self.query_input)
979 .prefix(
980 Icon::new(IconName::Search)
981 .text_color(cx.theme().muted_foreground),
982 )
983 .appearance(false)
984 .p_0(),
985 ),
986 )
987 })
988 .child(
989 v_flex()
990 .id("command-list-container")
991 .role(Role::ListBox)
992 .relative()
993 .flex_1()
994 .when(rows_count == 0 && !self.loading, |this| this.p_1())
1000 .on_prepaint({
1001 let measure_state = command_state.clone();
1002 move |bounds, window, cx| {
1003 measure_state.update(cx, |state, cx| {
1004 let text_style = window.text_style();
1009 state.set_list_measurement_key(
1010 ListMeasurementKey {
1011 content_width: (bounds.size.width
1012 - window.rem_size() * 0.5)
1013 .max(px(0.)),
1014 rem_size: window.rem_size(),
1015 line_height: window.line_height(),
1016 text_shape: TextShapeKey {
1017 font_family: text_style.font_family,
1018 font_features: text_style.font_features,
1019 font_fallbacks: text_style.font_fallbacks,
1020 font_size: text_style.font_size,
1021 font_weight: text_style.font_weight,
1022 font_style: text_style.font_style,
1023 white_space: text_style.white_space,
1024 text_overflow: text_style.text_overflow,
1025 line_clamp: text_style.line_clamp,
1026 },
1027 },
1028 window,
1029 cx,
1030 )
1031 })
1032 }
1033 })
1034 .max_h(self.options.max_h)
1035 .overflow_hidden()
1036 .when(rows_count == 0 && !self.loading, |this| {
1039 this.child(self.render_empty(window, cx))
1040 })
1041 .when(rows_count > 0, |this| {
1042 this.child(
1043 v_virtual_list(
1044 command_state.clone(),
1045 "command-list",
1046 row_sizes,
1047 move |this, visible_range, window, cx| {
1048 visible_range
1049 .map(|row_ix| this.render_visible_row(row_ix, window, cx))
1050 .collect::<Vec<_>>()
1051 },
1052 )
1053 .p_1()
1058 .with_sizing_behavior(ListSizingBehavior::Infer)
1059 .track_scroll(&self.scroll_handle)
1060 .map(|list| {
1061 gpui_base::ScrollBounce::new(
1062 "command-scroll-bounce",
1063 &self.scroll_handle,
1064 list,
1065 )
1066 .when_some(self.options.scroll_bounce, |bounce, on| {
1067 bounce.enabled(on)
1068 })
1069 }),
1070 )
1071 .child(Scrollbar::vertical(&self.scroll_handle))
1072 }),
1073 )
1074 .when_some(self.options.footer.as_ref(), |this, footer| {
1075 this.child(footer(self, window, cx))
1076 })
1077 }
1078}
1079
1080#[cfg(test)]
1083mod tests {
1084 use std::{
1085 cell::{Cell, RefCell},
1086 rc::Rc,
1087 };
1088
1089 use gpui::{
1090 AppContext as _, AvailableSpace, Entity, InteractiveElement as _, IntoElement, KeyBinding,
1091 Modifiers, ParentElement as _, Pixels, Render, Styled as _, TestAppContext, Window,
1092 actions, div, point, prelude::FluentBuilder as _, px,
1093 };
1094
1095 use super::{CONTEXT, CommandModel, CommandRow, CommandState, SEPARATOR_ROW_HEIGHT};
1096 use crate::{
1097 Disableable as _, Icon, IconName, IndexPath,
1098 actions::{Cancel, Confirm, SelectDown},
1099 command::{Command, CommandEntry, CommandGroup, CommandItem},
1100 };
1101
1102 actions!(
1103 command_test,
1104 [GlobalTestItem, OpenTestItem, RemovePaletteTestItem]
1105 );
1106
1107 struct CommandActionsHarness {
1108 state: Entity<CommandState>,
1109 events: Rc<RefCell<Vec<String>>>,
1110 }
1111
1112 impl Render for CommandActionsHarness {
1113 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1114 let action_events = self.events.clone();
1115 let propagated_cancel_events = self.events.clone();
1116 let query_events = self.events.clone();
1117 let select_events = self.events.clone();
1118 let confirm_events = self.events.clone();
1119 let cancel_events = self.events.clone();
1120
1121 div()
1122 .size_full()
1123 .on_action(move |_: &OpenTestItem, _, _| {
1124 action_events.borrow_mut().push("action".into());
1125 })
1126 .on_action(move |_: &Cancel, _, _| {
1127 propagated_cancel_events
1128 .borrow_mut()
1129 .push("propagated_cancel".into());
1130 })
1131 .child(
1132 Command::new(&self.state)
1133 .item(
1134 CommandItem::new()
1135 .label("Item")
1136 .keywords(["needle"])
1137 .action(Box::new(OpenTestItem)),
1138 )
1139 .item(CommandItem::new().label("Item"))
1140 .item(
1141 CommandItem::new()
1142 .label("Item")
1143 .action(Box::new(GlobalTestItem)),
1144 )
1145 .on_query(move |query, _, _| {
1146 query_events.borrow_mut().push(format!("query:{query}"));
1147 })
1148 .on_select(move |index, _, _| {
1149 select_events
1150 .borrow_mut()
1151 .push(format!("select:{}:{}", index.section, index.row));
1152 })
1153 .on_confirm(move |index, _, _| {
1154 confirm_events
1155 .borrow_mut()
1156 .push(format!("confirm:{}:{}", index.section, index.row));
1157 })
1158 .on_cancel(move |_, _| {
1159 cancel_events.borrow_mut().push("cancel".into());
1160 }),
1161 )
1162 }
1163 }
1164
1165 struct ReentrantCallbackHarness {
1166 state: Entity<CommandState>,
1167 events: Vec<String>,
1168 }
1169
1170 impl Render for ReentrantCallbackHarness {
1171 fn render(&mut self, _: &mut Window, cx: &mut gpui::Context<Self>) -> impl IntoElement {
1172 let select_owner = cx.weak_entity();
1173 let query_owner = cx.weak_entity();
1174 let confirm_owner = cx.weak_entity();
1175
1176 Command::new(&self.state)
1177 .item(CommandItem::new().label("alpha"))
1178 .item(CommandItem::new().label("beta"))
1179 .on_select(move |index, _, cx| {
1180 _ = select_owner.update(cx, |harness, cx| {
1181 assert_eq!(harness.state.read(cx).selected_index(), Some(index));
1182 harness
1183 .events
1184 .push(format!("select:{}:{}", index.section, index.row));
1185 });
1186 })
1187 .on_query(move |query, _, cx| {
1188 _ = query_owner.update(cx, |harness, cx| {
1189 assert_eq!(harness.state.read(cx).query(cx).as_ref(), query);
1190 harness.events.push(format!("query:{query}"));
1191 });
1192 })
1193 .on_confirm(move |index, _, cx| {
1194 _ = confirm_owner.update(cx, |harness, cx| {
1195 assert_eq!(harness.state.read(cx).selected_index(), Some(index));
1196 harness
1197 .events
1198 .push(format!("confirm:{}:{}", index.section, index.row));
1199 });
1200 })
1201 }
1202 }
1203
1204 #[gpui::test]
1205 fn query_and_selection_callbacks_run_after_the_state_lease_in_defined_order(
1206 cx: &mut TestAppContext,
1207 ) {
1208 cx.update(crate::init);
1209 let (harness, cx) = cx.add_window_view(|window, cx| ReentrantCallbackHarness {
1210 state: cx.new(|cx| CommandState::new(window, cx)),
1211 events: Vec::new(),
1212 });
1213 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1214
1215 cx.run_until_parked();
1216 cx.update(|window, cx| {
1217 _ = window.draw(cx);
1218 state.update(cx, |state, cx| {
1219 state.selected_index = Some(1);
1220 state.set_query("alpha", window, cx);
1221 });
1222 });
1223
1224 assert_eq!(
1225 harness.read_with(cx, |harness, _| harness.events.clone()),
1226 ["select:0:0", "query:alpha"]
1227 );
1228 }
1229
1230 #[gpui::test]
1231 fn actionless_confirm_callback_runs_after_the_state_lease(cx: &mut TestAppContext) {
1232 cx.update(crate::init);
1233 let (harness, cx) = cx.add_window_view(|window, cx| ReentrantCallbackHarness {
1234 state: cx.new(|cx| CommandState::new(window, cx)),
1235 events: Vec::new(),
1236 });
1237 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1238
1239 cx.run_until_parked();
1240 cx.update(|window, cx| {
1241 _ = window.draw(cx);
1242 state.update(cx, |state, cx| state.confirm(0, window, cx));
1243 });
1244
1245 assert_eq!(
1246 harness.read_with(cx, |harness, _| harness.events.clone()),
1247 ["confirm:0:0"]
1248 );
1249 }
1250
1251 struct CommandItemWidthHarness {
1252 state: Entity<CommandState>,
1253 matched_ix: usize,
1254 width: Rc<Cell<Option<Pixels>>>,
1255 }
1256
1257 impl Render for CommandItemWidthHarness {
1258 fn render(
1259 &mut self,
1260 window: &mut Window,
1261 cx: &mut gpui::Context<Self>,
1262 ) -> impl IntoElement {
1263 let width = self.width.clone();
1264 let item = self.state.update(cx, |state, cx| {
1265 state.render_item(self.matched_ix, window, cx)
1266 });
1267
1268 div()
1269 .on_children_prepainted(move |bounds, _, _| width.set(Some(bounds[0].size.width)))
1270 .child(item)
1271 }
1272 }
1273
1274 #[gpui::test]
1275 fn action_that_removes_command_state_still_confirms_after_dispatch(cx: &mut TestAppContext) {
1276 cx.update(crate::init);
1277 let events = Rc::new(RefCell::new(Vec::new()));
1278 let state_owner: Rc<RefCell<Option<Entity<CommandState>>>> = Rc::new(RefCell::new(None));
1279 let action_events = events.clone();
1280 let action_state_owner = state_owner.clone();
1281 cx.update(|cx| {
1282 cx.on_action(move |_: &RemovePaletteTestItem, _| {
1283 action_events.borrow_mut().push("action".into());
1284 action_state_owner.borrow_mut().take();
1285 });
1286 });
1287 let cx = cx.add_empty_window();
1288 cx.update(|window, cx| {
1289 let confirm_events = events.clone();
1290 let state = cx.new(|cx| {
1291 let mut state = CommandState::new(window, cx);
1292 state.install_model(
1293 CommandModel {
1294 entries: vec![CommandEntry::Item(
1295 CommandItem::new()
1296 .label("removed")
1297 .action(Box::new(RemovePaletteTestItem)),
1298 )],
1299 searchable: false,
1300 on_confirm: Some(Rc::new(move |index, _, _| {
1301 confirm_events
1302 .borrow_mut()
1303 .push(format!("confirm:{}:{}", index.section, index.row));
1304 })),
1305 ..CommandModel::default()
1306 },
1307 cx,
1308 );
1309 state
1310 });
1311 *state_owner.borrow_mut() = Some(state.clone());
1312 state.update(cx, |state, cx| state.confirm(0, window, cx));
1313 });
1314 cx.run_until_parked();
1315
1316 assert!(state_owner.borrow().is_none());
1317 assert_eq!(events.borrow().as_slice(), ["action", "confirm:0:0"]);
1318 }
1319
1320 #[gpui::test]
1321 fn command_actions_and_callbacks_follow_defined_order(cx: &mut TestAppContext) {
1322 cx.update(|cx| {
1323 crate::init(cx);
1324 cx.bind_keys([
1325 KeyBinding::new("ctrl-o", OpenTestItem, Some(CONTEXT)),
1326 KeyBinding::new("ctrl-g", GlobalTestItem, None),
1327 ]);
1328 });
1329 let events = Rc::new(RefCell::new(Vec::new()));
1330 let (harness, cx) = cx.add_window_view(|window, cx| CommandActionsHarness {
1331 state: cx.new(|cx| CommandState::new(window, cx)),
1332 events: events.clone(),
1333 });
1334 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1335
1336 cx.run_until_parked();
1337 cx.update(|window, cx| {
1338 _ = window.draw(cx);
1339 state.update(cx, |state, cx| state.focus(window, cx));
1340 _ = window.draw(cx);
1341 });
1342
1343 let action_width = Rc::new(Cell::new(None));
1344 let plain_width = Rc::new(Cell::new(None));
1345 let global_width = Rc::new(Cell::new(None));
1346 let (action_probe, plain_probe, global_probe) = cx.update(|_, cx| {
1347 (
1348 cx.new(|_| CommandItemWidthHarness {
1349 state: state.clone(),
1350 matched_ix: 0,
1351 width: action_width.clone(),
1352 }),
1353 cx.new(|_| CommandItemWidthHarness {
1354 state: state.clone(),
1355 matched_ix: 1,
1356 width: plain_width.clone(),
1357 }),
1358 cx.new(|_| CommandItemWidthHarness {
1359 state: state.clone(),
1360 matched_ix: 2,
1361 width: global_width.clone(),
1362 }),
1363 )
1364 });
1365 cx.draw(
1366 point(px(0.), px(0.)),
1367 AvailableSpace::min_size(),
1368 move |_, _| action_probe.into_any_element(),
1369 );
1370 cx.draw(
1371 point(px(0.), px(0.)),
1372 AvailableSpace::min_size(),
1373 move |_, _| plain_probe.into_any_element(),
1374 );
1375 cx.draw(
1376 point(px(0.), px(0.)),
1377 AvailableSpace::min_size(),
1378 move |_, _| global_probe.into_any_element(),
1379 );
1380 let action_width = action_width.get().unwrap();
1381 let plain_width = plain_width.get().unwrap();
1382 let global_width = global_width.get().unwrap();
1383 assert!(
1384 action_width > plain_width,
1385 "the scoped Action binding should add a visible Kbd ({action_width:?} vs {plain_width:?})",
1386 );
1387 assert!(
1388 global_width > plain_width,
1389 "the app-level fallback binding should add a visible Kbd ({global_width:?} vs {plain_width:?})",
1390 );
1391
1392 cx.update(|window, cx| {
1393 state.update(cx, |state, cx| {
1394 state.set_query("needle", window, cx);
1395 state.set_query("needle", window, cx);
1396 state.set_query("", window, cx);
1397 });
1398 window.dispatch_action(Box::new(SelectDown), cx);
1399 window.dispatch_action(Box::new(crate::actions::SelectUp), cx);
1400 window.dispatch_action(Box::new(Confirm { secondary: false }), cx);
1401 });
1402 cx.run_until_parked();
1403
1404 assert_eq!(
1405 events.borrow().as_slice(),
1406 [
1407 "query:needle",
1408 "query:",
1409 "select:0:1",
1410 "select:0:0",
1411 "action",
1412 "confirm:0:0",
1413 ]
1414 );
1415
1416 cx.simulate_click(point(px(20.), px(52.)), Modifiers::default());
1417 cx.run_until_parked();
1418 cx.update(|window, cx| window.dispatch_action(Box::new(Cancel), cx));
1419 cx.run_until_parked();
1420
1421 assert_eq!(
1422 events.borrow().as_slice(),
1423 [
1424 "query:needle",
1425 "query:",
1426 "select:0:1",
1427 "select:0:0",
1428 "action",
1429 "confirm:0:0",
1430 "action",
1431 "confirm:0:0",
1432 "cancel",
1433 "propagated_cancel",
1434 ]
1435 );
1436 }
1437
1438 struct CommandOwnedEntriesHarness {
1439 state: Entity<CommandState>,
1440 }
1441
1442 impl Render for CommandOwnedEntriesHarness {
1443 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
1444 Command::new(&self.state)
1445 .searchable(false)
1446 .item(CommandItem::new().label("alpha"))
1447 .group(
1448 CommandGroup::new()
1449 .label("Settings")
1450 .item(CommandItem::new().label("beta")),
1451 )
1452 .separator()
1453 .item(
1454 CommandItem::new()
1455 .label("custom")
1456 .child(|_, _| div().h(px(72.)).child("Custom")),
1457 )
1458 }
1459 }
1460
1461 #[gpui::test]
1462 fn command_owns_entries_and_lazy_item_content(cx: &mut TestAppContext) {
1463 cx.update(crate::init);
1464 let (harness, cx) = cx.add_window_view(|window, cx| CommandOwnedEntriesHarness {
1465 state: cx.new(|cx| CommandState::new(window, cx)),
1466 });
1467
1468 cx.run_until_parked();
1469 cx.update(|window, cx| _ = window.draw(cx));
1470
1471 let (labels, rows, row_sizes) = cx.update(|_, cx| {
1472 let state = harness.read(cx).state.read(cx);
1473 (
1474 (0..state.matched_count())
1475 .map(|matched_ix| {
1476 state
1477 .item_at(matched_ix)
1478 .unwrap()
1479 .label_text()
1480 .unwrap()
1481 .clone()
1482 })
1483 .collect::<Vec<_>>(),
1484 state.rows.clone(),
1485 state.row_sizes.clone(),
1486 )
1487 });
1488
1489 assert_eq!(labels, ["alpha", "beta", "custom"]);
1490 assert!(matches!(
1491 rows.as_slice(),
1492 [
1493 CommandRow::Item(_),
1494 CommandRow::Heading(heading),
1495 CommandRow::Item(_),
1496 CommandRow::Separator,
1497 CommandRow::Item(_),
1498 ] if heading == "Settings"
1499 ));
1500 assert_eq!(row_sizes[4].height, px(84.));
1501 }
1502
1503 fn command_with_entries(
1504 state: &Entity<CommandState>,
1505 entries: impl IntoIterator<Item = CommandEntry>,
1506 ) -> Command {
1507 entries
1508 .into_iter()
1509 .fold(Command::new(state), |command, entry| match entry {
1510 CommandEntry::Item(item) => command.item(item),
1511 CommandEntry::Group(group) => command.group(group),
1512 CommandEntry::Separator => command.separator(),
1513 })
1514 }
1515
1516 fn command_state(
1517 window: &mut Window,
1518 cx: &mut gpui::Context<CommandState>,
1519 entries: impl IntoIterator<Item = CommandEntry>,
1520 ) -> CommandState {
1521 let mut state = CommandState::new(window, cx);
1522 state.install_model(
1523 CommandModel {
1524 entries: entries.into_iter().collect(),
1525 ..CommandModel::default()
1526 },
1527 cx,
1528 );
1529 state
1530 }
1531
1532 fn command_state_with_options(
1533 window: &mut Window,
1534 cx: &mut gpui::Context<CommandState>,
1535 entries: impl IntoIterator<Item = CommandEntry>,
1536 searchable: bool,
1537 ) -> CommandState {
1538 let mut state = CommandState::new(window, cx);
1539 state.install_model(
1540 CommandModel {
1541 entries: entries.into_iter().collect(),
1542 searchable,
1543 ..CommandModel::default()
1544 },
1545 cx,
1546 );
1547 state
1548 }
1549
1550 fn suggestion_entries() -> Vec<CommandEntry> {
1551 vec![
1552 CommandGroup::new()
1553 .label("Suggestions")
1554 .item(CommandItem::new().label("Calendar"))
1555 .item(CommandItem::new().label("Search Emoji"))
1556 .item(CommandItem::new().label("Calculator").disabled(true))
1557 .into(),
1558 CommandEntry::Separator,
1559 CommandGroup::new()
1560 .label("Settings")
1561 .item(CommandItem::new().label("Profile"))
1562 .item(CommandItem::new().label("Billing"))
1563 .into(),
1564 ]
1565 }
1566
1567 #[gpui::test]
1568 fn query_hides_the_groups_that_have_no_match(cx: &mut TestAppContext) {
1569 cx.update(crate::init);
1570 let cx = cx.add_empty_window();
1571
1572 cx.update(|window, cx| {
1573 let state = cx.new(|cx| command_state(window, cx, suggestion_entries()));
1574
1575 state.update(cx, |state, cx| {
1576 state.update_matches(cx);
1577 assert_eq!(state.matched_count(), 5);
1578 assert_eq!(
1579 state
1580 .rows
1581 .iter()
1582 .filter(|row| matches!(row, CommandRow::Heading(_)))
1583 .count(),
1584 2,
1585 );
1586 assert_eq!(
1587 state
1588 .rows
1589 .iter()
1590 .filter(|row| matches!(row, CommandRow::Separator))
1591 .count(),
1592 1,
1593 );
1594
1595 state.set_query("Bil", window, cx);
1598 state.update_matches(cx);
1599
1600 assert_eq!(state.matched_count(), 1);
1601 assert_eq!(state.selected_index(), Some(IndexPath::new(1).section(1)));
1602 assert_eq!(
1603 state
1604 .rows
1605 .iter()
1606 .filter(|row| matches!(row, CommandRow::Separator))
1607 .count(),
1608 0,
1609 );
1610 assert!(matches!(state.rows.first(), Some(CommandRow::Heading(_))));
1611 });
1612 });
1613 }
1614
1615 #[gpui::test]
1616 fn rows_highlight_the_query_the_palette_filtered_by(cx: &mut TestAppContext) {
1617 cx.update(crate::init);
1618 let cx = cx.add_empty_window();
1619
1620 cx.update(|window, cx| {
1621 let plain = cx.new(|cx| command_state(window, cx, suggestion_entries()));
1622 plain.update(cx, |state, cx| {
1623 state.set_query("cal", window, cx);
1624 assert_eq!(state.highlighted_query(), "");
1625 });
1626
1627 let state = cx.new(|cx| {
1628 let mut state = CommandState::new(window, cx);
1629 state.install_model(
1630 CommandModel {
1631 entries: suggestion_entries(),
1632 highlight_matches: true,
1633 ..CommandModel::default()
1634 },
1635 cx,
1636 );
1637 state
1638 });
1639 state.update(cx, |state, cx| {
1640 assert_eq!(state.highlighted_query(), "");
1641 state.set_query(" cal ", window, cx);
1642 assert_eq!(state.highlighted_query(), "cal");
1643 });
1644
1645 let host_filtered = cx.new(|cx| {
1646 let mut state = CommandState::new(window, cx);
1647 state.install_model(
1648 CommandModel {
1649 entries: suggestion_entries(),
1650 filterable: false,
1651 highlight_matches: true,
1652 ..CommandModel::default()
1653 },
1654 cx,
1655 );
1656 state
1657 });
1658 host_filtered.update(cx, |state, cx| {
1659 state.set_query("cal", window, cx);
1660 assert_eq!(state.highlighted_query(), "");
1661 });
1662 });
1663 }
1664
1665 fn custom_entries() -> Vec<CommandEntry> {
1666 vec![CommandEntry::Item(
1667 CommandItem::new().label("Custom").child(|_, _| div()),
1668 )]
1669 }
1670
1671 #[gpui::test]
1672 fn reinstalling_an_unchanged_model_keeps_the_measured_rows(cx: &mut TestAppContext) {
1673 cx.update(crate::init);
1674 let cx = cx.add_empty_window();
1675
1676 cx.update(|window, cx| {
1677 let state = cx.new(|cx| command_state(window, cx, suggestion_entries()));
1678
1679 state.update(cx, |state, cx| {
1680 state.needs_measure = false;
1682 state.install_model(
1683 CommandModel {
1684 entries: suggestion_entries(),
1685 ..CommandModel::default()
1686 },
1687 cx,
1688 );
1689 assert!(!state.needs_measure);
1690 assert_eq!(state.matched_count(), 5);
1691
1692 state.install_model(
1695 CommandModel {
1696 entries: custom_entries(),
1697 ..CommandModel::default()
1698 },
1699 cx,
1700 );
1701 assert!(state.needs_measure);
1702 assert_eq!(state.matched_count(), 1);
1703
1704 state.needs_measure = false;
1707 let entries = state.model.entries.clone();
1708 state.install_model(
1709 CommandModel {
1710 entries,
1711 ..CommandModel::default()
1712 },
1713 cx,
1714 );
1715 assert!(state.needs_measure);
1716
1717 let item = || CommandItem::new().label("Renamed");
1720 let icon = || Icon::new(IconName::Check);
1721 for entries in [
1722 vec![CommandEntry::Item(item())],
1723 vec![CommandEntry::Item(item().icon(icon()))],
1724 vec![CommandEntry::Item(item().icon(icon().ml_2()))],
1725 vec![CommandEntry::Item(
1726 item().icon(icon().ml_2()).disabled(true),
1727 )],
1728 ] {
1729 state.needs_measure = false;
1730 state.install_model(
1731 CommandModel {
1732 entries,
1733 ..CommandModel::default()
1734 },
1735 cx,
1736 );
1737 assert!(state.needs_measure);
1738 }
1739 assert_eq!(state.selected_index(), None);
1740 });
1741 });
1742 }
1743
1744 #[gpui::test]
1745 fn a_query_that_matches_nothing_leaves_no_rows(cx: &mut TestAppContext) {
1746 cx.update(crate::init);
1747 let cx = cx.add_empty_window();
1748
1749 cx.update(|window, cx| {
1750 let state = cx.new(|cx| command_state(window, cx, suggestion_entries()));
1751
1752 state.update(cx, |state, cx| {
1753 state.set_query("zzz", window, cx);
1754 state.update_matches(cx);
1755
1756 assert_eq!(state.matched_count(), 0);
1757 assert!(state.rows.is_empty());
1758 assert_eq!(state.selected_index(), None);
1759 });
1760 });
1761 }
1762
1763 #[gpui::test]
1764 fn filterable_off_keeps_every_item_and_resets_the_highlight(cx: &mut TestAppContext) {
1765 cx.update(crate::init);
1766 let cx = cx.add_empty_window();
1767
1768 cx.update(|window, cx| {
1769 let state = cx.new(|cx| {
1770 let mut state = CommandState::new(window, cx);
1771 state.install_model(
1772 CommandModel {
1773 entries: suggestion_entries(),
1774 filterable: false,
1775 ..CommandModel::default()
1776 },
1777 cx,
1778 );
1779 state
1780 });
1781
1782 state.update(cx, |state, cx| {
1783 state.set_selected_index(Some(IndexPath::new(1).section(1)), window, cx);
1784
1785 state.set_query("Bil", window, cx);
1789
1790 assert_eq!(state.matched_count(), 5);
1791 assert_eq!(state.selected_index(), Some(IndexPath::new(0).section(0)));
1792 });
1793 });
1794 }
1795
1796 #[gpui::test]
1797 fn keywords_match_when_the_label_does_not(cx: &mut TestAppContext) {
1798 cx.update(crate::init);
1799 let cx = cx.add_empty_window();
1800
1801 cx.update(|window, cx| {
1802 let state = cx.new(|cx| {
1803 command_state(
1804 window,
1805 cx,
1806 [CommandEntry::Item(
1807 CommandItem::new().label("Profile").keywords(["account"]),
1808 )],
1809 )
1810 });
1811
1812 state.update(cx, |state, cx| {
1813 state.set_query("account", window, cx);
1814 state.update_matches(cx);
1815
1816 assert_eq!(state.matched_count(), 1);
1817 });
1818 });
1819 }
1820
1821 #[gpui::test]
1822 fn non_searchable_command_keeps_every_item(cx: &mut TestAppContext) {
1823 cx.update(crate::init);
1824 let cx = cx.add_empty_window();
1825 cx.update(|window, cx| {
1826 let state = cx.new(|cx| {
1827 command_state_with_options(
1828 window,
1829 cx,
1830 [
1831 CommandEntry::Item(CommandItem::new().label("alpha")),
1832 CommandEntry::Item(CommandItem::new().label("beta")),
1833 ],
1834 false,
1835 )
1836 });
1837 state.update(cx, |state, cx| {
1838 state.set_query("missing", window, cx);
1839 assert_eq!(state.matched_count(), 2);
1840 });
1841 });
1842 }
1843
1844 #[gpui::test]
1845 fn non_searchable_command_uses_frame_focus(cx: &mut TestAppContext) {
1846 cx.update(crate::init);
1847 let confirmed = Rc::new(RefCell::new(None));
1848 let confirmed_for_render = confirmed.clone();
1849 let (harness, cx) = cx.add_window_view(move |window, cx| Harness {
1850 state: cx.new(|cx| CommandState::new(window, cx)),
1851 command: Rc::new(move |state| {
1852 let confirmed = confirmed_for_render.clone();
1853 Command::new(state)
1854 .searchable(false)
1855 .item(CommandItem::new().label("alpha"))
1856 .item(CommandItem::new().label("beta"))
1857 .on_confirm(move |index_path, _, _| {
1858 *confirmed.borrow_mut() = Some(index_path);
1859 })
1860 }),
1861 });
1862 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1863
1864 cx.run_until_parked();
1865 cx.update(|window, cx| _ = window.draw(cx));
1866 cx.update(|window, cx| {
1867 state.update(cx, |state, cx| state.focus(window, cx));
1868 assert!(state.read(cx).focus_handle.is_focused(window));
1869 window.dispatch_action(Box::new(SelectDown), cx);
1870 window.dispatch_action(Box::new(Confirm { secondary: false }), cx);
1871 });
1872
1873 assert_eq!(*confirmed.borrow(), Some(IndexPath::new(1).section(0)));
1874 }
1875
1876 #[gpui::test]
1877 fn filtered_ungrouped_item_keeps_its_input_row(cx: &mut TestAppContext) {
1878 cx.update(crate::init);
1879 let confirmed = Rc::new(RefCell::new(None));
1880 let confirmed_for_render = confirmed.clone();
1881 let (harness, cx) = cx.add_window_view(move |window, cx| Harness {
1882 state: cx.new(|cx| CommandState::new(window, cx)),
1883 command: Rc::new(move |state| {
1884 let confirmed = confirmed_for_render.clone();
1885 Command::new(state)
1886 .items([
1887 CommandItem::new().label("alpha"),
1888 CommandItem::new().label("beta"),
1889 CommandItem::new().label("gamma"),
1890 ])
1891 .on_confirm(move |index_path, _, _| {
1892 *confirmed.borrow_mut() = Some(index_path);
1893 })
1894 }),
1895 });
1896 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1897
1898 cx.run_until_parked();
1899 cx.update(|window, cx| {
1900 state.update(cx, |state, cx| {
1901 state.set_query("gamma", window, cx);
1902 state.focus(window, cx);
1903 });
1904 window.dispatch_action(Box::new(Confirm { secondary: false }), cx);
1905 });
1906
1907 assert_eq!(*confirmed.borrow(), Some(IndexPath::new(2).section(0)));
1908 }
1909
1910 #[gpui::test]
1911 fn initially_rendered_disabled_first_item_selects_and_confirms_the_first_enabled_item(
1912 cx: &mut TestAppContext,
1913 ) {
1914 cx.update(crate::init);
1915 let confirmed = Rc::new(RefCell::new(None));
1916 let confirmed_for_render = confirmed.clone();
1917 let (harness, cx) = cx.add_window_view(move |window, cx| Harness {
1918 state: cx.new(|cx| CommandState::new(window, cx)),
1919 command: Rc::new(move |state| {
1920 let confirmed = confirmed_for_render.clone();
1921 Command::new(state)
1922 .item(CommandItem::new().label("disabled").disabled(true))
1923 .item(CommandItem::new().label("enabled"))
1924 .on_confirm(move |index_path, _, _| {
1925 *confirmed.borrow_mut() = Some(index_path);
1926 })
1927 }),
1928 });
1929 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1930
1931 cx.run_until_parked();
1932 cx.update(|window, cx| _ = window.draw(cx));
1933 cx.update(|window, cx| {
1934 state.update(cx, |state, cx| state.focus(window, cx));
1935 window.dispatch_action(Box::new(Confirm { secondary: false }), cx);
1936 });
1937
1938 assert_eq!(
1939 state.read_with(cx, |state, _| state.selected_index()),
1940 Some(IndexPath::new(1).section(0))
1941 );
1942 assert_eq!(*confirmed.borrow(), Some(IndexPath::new(1).section(0)));
1943 }
1944
1945 #[gpui::test]
1946 fn initially_rendered_all_disabled_items_have_no_selected_index_and_ignore_enter(
1947 cx: &mut TestAppContext,
1948 ) {
1949 cx.update(crate::init);
1950 let confirmed = Rc::new(RefCell::new(None));
1951 let confirmed_for_render = confirmed.clone();
1952 let (harness, cx) = cx.add_window_view(move |window, cx| Harness {
1953 state: cx.new(|cx| CommandState::new(window, cx)),
1954 command: Rc::new(move |state| {
1955 let confirmed = confirmed_for_render.clone();
1956 Command::new(state)
1957 .item(CommandItem::new().label("one").disabled(true))
1958 .item(CommandItem::new().label("two").disabled(true))
1959 .on_confirm(move |index_path, _, _| {
1960 *confirmed.borrow_mut() = Some(index_path);
1961 })
1962 }),
1963 });
1964 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1965
1966 cx.run_until_parked();
1967 cx.update(|window, cx| _ = window.draw(cx));
1968 cx.update(|window, cx| {
1969 state.update(cx, |state, cx| state.focus(window, cx));
1970 window.dispatch_action(Box::new(Confirm { secondary: false }), cx);
1971 });
1972
1973 assert_eq!(state.read_with(cx, |state, _| state.selected_index()), None);
1974 assert_eq!(*confirmed.borrow(), None);
1975 }
1976
1977 #[gpui::test]
1978 fn non_searchable_command_cancels_without_clearing_a_hidden_query(cx: &mut TestAppContext) {
1979 cx.update(crate::init);
1980 let cancelled = Rc::new(Cell::new(false));
1981 let cancelled_for_render = cancelled.clone();
1982 let query_calls = Rc::new(Cell::new(0));
1983 let query_calls_for_render = query_calls.clone();
1984 let (harness, cx) = cx.add_window_view(move |window, cx| Harness {
1985 state: cx.new(|cx| CommandState::new(window, cx)),
1986 command: Rc::new(move |state| {
1987 let cancelled = cancelled_for_render.clone();
1988 let query_calls = query_calls_for_render.clone();
1989 Command::new(state)
1990 .searchable(false)
1991 .item(CommandItem::new().label("alpha"))
1992 .on_query(move |_, _, _| query_calls.set(query_calls.get() + 1))
1993 .on_cancel(move |_, _| cancelled.set(true))
1994 }),
1995 });
1996 let state = cx.update(|_, cx| harness.read(cx).state.clone());
1997
1998 cx.run_until_parked();
1999 cx.update(|window, cx| _ = window.draw(cx));
2000 cx.update(|window, cx| {
2001 state.update(cx, |state, cx| {
2002 state.set_query("hidden query", window, cx);
2003 state.focus(window, cx);
2004 });
2005 window.dispatch_action(Box::new(Cancel), cx);
2006 });
2007
2008 assert!(cancelled.get());
2009 assert_eq!(query_calls.get(), 0);
2010 assert_eq!(
2011 state.read_with(cx, |state, cx| state.query(cx)),
2012 "hidden query"
2013 );
2014 }
2015
2016 #[gpui::test]
2017 fn moving_the_highlight_skips_disabled_items_and_wraps(cx: &mut TestAppContext) {
2018 cx.update(crate::init);
2019 let cx = cx.add_empty_window();
2020
2021 cx.update(|window, cx| {
2022 let state = cx.new(|cx| command_state(window, cx, suggestion_entries()));
2023
2024 state.update(cx, |state, cx| {
2025 state.update_matches(cx);
2026 state.reset_selection();
2027 assert_eq!(state.selected_index(), Some(IndexPath::new(0).section(0)));
2028
2029 state.select_by(1, window, cx);
2030 assert_eq!(state.selected_index(), Some(IndexPath::new(1).section(0)));
2031
2032 state.select_by(1, window, cx);
2034 assert_eq!(state.selected_index(), Some(IndexPath::new(0).section(1)));
2035
2036 state.select_by(-1, window, cx);
2037 assert_eq!(state.selected_index(), Some(IndexPath::new(1).section(0)));
2038
2039 state.select_by(-1, window, cx);
2041 assert_eq!(state.selected_index(), Some(IndexPath::new(0).section(0)));
2042 state.select_by(-1, window, cx);
2043 assert_eq!(state.selected_index(), Some(IndexPath::new(1).section(1)));
2044 });
2045 });
2046 }
2047
2048 #[gpui::test]
2049 fn owner_can_set_and_clear_selection_by_original_index_path(cx: &mut TestAppContext) {
2050 cx.update(crate::init);
2051 let cx = cx.add_empty_window();
2052
2053 cx.update(|window, cx| {
2054 let initially_empty = cx.new(|cx| CommandState::new(window, cx));
2055 initially_empty.update(cx, |state, cx| {
2056 state.set_selected_index(None, window, cx);
2057 state.install_model(
2058 CommandModel {
2059 entries: suggestion_entries().into_iter().collect(),
2060 ..CommandModel::default()
2061 },
2062 cx,
2063 );
2064 assert_eq!(state.selected_index(), None);
2065 });
2066
2067 let state = cx.new(|cx| command_state(window, cx, suggestion_entries()));
2068
2069 state.update(cx, |state, cx| {
2070 let target = IndexPath::new(1).section(1);
2071 state.set_selected_index(Some(target), window, cx);
2072 assert_eq!(state.selected_index(), Some(target));
2073
2074 state.set_selected_index(None, window, cx);
2075 assert_eq!(state.selected_index(), None);
2076
2077 state.install_model(
2078 CommandModel {
2079 entries: suggestion_entries().into_iter().collect(),
2080 ..CommandModel::default()
2081 },
2082 cx,
2083 );
2084 assert_eq!(state.selected_index(), None);
2085
2086 state.set_query("calendar", window, cx);
2087 state.set_selected_index(Some(target), window, cx);
2088 assert_eq!(state.selected_index(), None);
2089 });
2090 });
2091 }
2092
2093 #[gpui::test]
2094 fn confirming_a_disabled_item_does_nothing(cx: &mut TestAppContext) {
2095 cx.update(crate::init);
2096 let cx = cx.add_empty_window();
2097
2098 cx.update(|window, cx| {
2099 let state = cx.new(|cx| {
2100 command_state(
2101 window,
2102 cx,
2103 [
2104 CommandEntry::Item(CommandItem::new().label("enabled")),
2105 CommandEntry::Item(CommandItem::new().label("disabled").disabled(true)),
2106 ],
2107 )
2108 });
2109
2110 state.update(cx, |state, cx| {
2111 state.update_matches(cx);
2112
2113 assert_eq!(state.matched_count(), 2);
2114 state.confirm(1, window, cx);
2117 assert_eq!(state.selected_index, Some(0));
2118 });
2119 });
2120 }
2121
2122 #[gpui::test]
2123 fn a_checked_item_uses_an_xsmall_trailing_check_icon(cx: &mut TestAppContext) {
2124 cx.update(crate::init);
2125 let cx = cx.add_empty_window();
2126 let unchecked_width = Rc::new(Cell::new(None));
2127 let checked_width = Rc::new(Cell::new(None));
2128 let (unchecked, checked) = cx.update(|window, cx| {
2129 let unchecked_state = cx.new(|cx| {
2130 command_state(
2131 window,
2132 cx,
2133 [CommandEntry::Item(CommandItem::new().label("theme"))],
2134 )
2135 });
2136 let checked_state = cx.new(|cx| {
2137 command_state(
2138 window,
2139 cx,
2140 [CommandEntry::Item(
2141 CommandItem::new().label("theme").checked(true),
2142 )],
2143 )
2144 });
2145 let unchecked_width = unchecked_width.clone();
2146 let checked_width = checked_width.clone();
2147 (
2148 cx.new(|_| CheckIconWidthHarness {
2149 state: unchecked_state,
2150 width: unchecked_width,
2151 }),
2152 cx.new(|_| CheckIconWidthHarness {
2153 state: checked_state,
2154 width: checked_width,
2155 }),
2156 )
2157 });
2158
2159 cx.draw(
2160 gpui::point(px(0.), px(0.)),
2161 gpui::AvailableSpace::min_size(),
2162 move |_, _| unchecked.into_any_element(),
2163 );
2164
2165 cx.draw(
2166 gpui::point(px(0.), px(0.)),
2167 gpui::AvailableSpace::min_size(),
2168 move |_, _| checked.into_any_element(),
2169 );
2170
2171 assert_eq!(
2172 checked_width.get().unwrap() - unchecked_width.get().unwrap(),
2173 px(20.)
2174 );
2175 }
2176
2177 struct CheckIconWidthHarness {
2178 state: Entity<CommandState>,
2179 width: Rc<Cell<Option<gpui::Pixels>>>,
2180 }
2181
2182 impl Render for CheckIconWidthHarness {
2183 fn render(
2184 &mut self,
2185 window: &mut Window,
2186 cx: &mut gpui::Context<Self>,
2187 ) -> impl IntoElement {
2188 let width = self.width.clone();
2189 let item = self.state.update(cx, |state, cx| {
2190 state.update_matches(cx);
2191 state.render_item(0, window, cx)
2192 });
2193
2194 div()
2195 .on_children_prepainted(move |bounds, _, _| width.set(Some(bounds[0].size.width)))
2196 .child(item)
2197 }
2198 }
2199
2200 struct Harness {
2201 state: Entity<CommandState>,
2202 command: Rc<dyn Fn(&Entity<CommandState>) -> Command>,
2203 }
2204
2205 impl Render for Harness {
2206 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
2207 div()
2208 .size_full()
2209 .child((self.command)(&self.state).max_h(px(200.)))
2210 }
2211 }
2212
2213 #[gpui::test]
2214 fn header_and_footer_render_with_current_state(cx: &mut TestAppContext) {
2215 cx.update(crate::init);
2216 let header_calls = Rc::new(Cell::new(0));
2217 let footer_calls = Rc::new(Cell::new(0));
2218 let header_matched_count = Rc::new(Cell::new(None));
2219 let footer_matched_count = Rc::new(Cell::new(None));
2220
2221 let (harness, cx) = cx.add_window_view(|window, cx| HeaderFooterHarness {
2222 state: cx.new(|cx| CommandState::new(window, cx)),
2223 header_calls,
2224 footer_calls,
2225 header_matched_count,
2226 footer_matched_count,
2227 });
2228
2229 cx.run_until_parked();
2230 cx.update(|window, cx| _ = window.draw(cx));
2231
2232 let (header_calls, footer_calls, header_matched_count, footer_matched_count) =
2233 cx.update(|_, cx| {
2234 let harness = harness.read(cx);
2235 (
2236 harness.header_calls.get(),
2237 harness.footer_calls.get(),
2238 harness.header_matched_count.get(),
2239 harness.footer_matched_count.get(),
2240 )
2241 });
2242 assert!(header_calls > 0);
2243 assert!(footer_calls > 0);
2244 assert_eq!(header_matched_count, Some(2));
2245 assert_eq!(footer_matched_count, Some(2));
2246 }
2247
2248 #[gpui::test]
2249 fn custom_empty_slot_renders_with_current_state(cx: &mut TestAppContext) {
2250 cx.update(crate::init);
2251 let empty_calls = Rc::new(Cell::new(0));
2252 let empty_matched_count = Rc::new(Cell::new(None));
2253 let calls = empty_calls.clone();
2254 let matched_count = empty_matched_count.clone();
2255 let (_harness, cx) = cx.add_window_view(move |window, cx| Harness {
2256 state: cx.new(|cx| CommandState::new(window, cx)),
2257 command: Rc::new(move |state| {
2258 let calls = calls.clone();
2259 let matched_count = matched_count.clone();
2260 Command::new(state).empty(
2261 move |state: &CommandState, _: &mut Window, _: &mut gpui::App| {
2262 calls.set(calls.get() + 1);
2263 matched_count.set(Some(state.matched_count()));
2264 div().child("Custom empty")
2265 },
2266 )
2267 }),
2268 });
2269
2270 cx.run_until_parked();
2271 cx.update(|window, cx| _ = window.draw(cx));
2272
2273 assert!(empty_calls.get() > 0);
2274 assert_eq!(empty_matched_count.get(), Some(0));
2275 }
2276
2277 fn entries_with_late_first_enabled_item() -> Vec<CommandEntry> {
2278 vec![
2279 CommandGroup::new()
2280 .label("Disabled")
2281 .items((0..30).map(|ix| {
2282 CommandItem::new()
2283 .label(format!("disabled-{ix}"))
2284 .keywords(["match"])
2285 .disabled(true)
2286 }))
2287 .into(),
2288 CommandEntry::Separator,
2289 CommandGroup::new()
2290 .label("Enabled")
2291 .item(CommandItem::new().label("enabled").keywords(["match"]))
2292 .into(),
2293 ]
2294 }
2295
2296 fn assert_first_enabled_row_is_scrolled_into_view(
2297 state: &Entity<CommandState>,
2298 cx: &mut TestAppContext,
2299 ) {
2300 let (selected_row, offset) = state.read_with(cx, |state, _| {
2301 (
2302 state.matched[state.selected_index.unwrap()].row_ix,
2303 state.scroll_handle.base_handle().offset().y,
2304 )
2305 });
2306
2307 assert!(selected_row > 30);
2308 assert!(
2309 offset < px(-900.),
2310 "the list should scroll to the selected row, not row zero ({offset:?})",
2311 );
2312 }
2313
2314 #[gpui::test]
2315 fn first_enabled_selection_resets_scroll_to_its_late_row(cx: &mut TestAppContext) {
2316 cx.update(crate::init);
2317 let (harness, cx) = cx.add_window_view(|window, cx| Harness {
2318 state: cx.new(|cx| CommandState::new(window, cx)),
2319 command: Rc::new(|state| {
2320 command_with_entries(state, entries_with_late_first_enabled_item())
2321 }),
2322 });
2323 let state = cx.update(|_, cx| harness.read(cx).state.clone());
2324
2325 cx.run_until_parked();
2326 cx.update(|window, cx| _ = window.draw(cx));
2327 assert_first_enabled_row_is_scrolled_into_view(&state, cx);
2328
2329 cx.update(|window, cx| {
2330 state.update(cx, |state, cx| state.set_query("match", window, cx));
2331 _ = window.draw(cx);
2332 });
2333 assert_first_enabled_row_is_scrolled_into_view(&state, cx);
2334
2335 cx.update(|window, cx| {
2336 harness.update(cx, |_, cx| {
2337 cx.notify();
2338 });
2339 _ = window.draw(cx);
2340 });
2341 assert_first_enabled_row_is_scrolled_into_view(&state, cx);
2342 }
2343
2344 struct HeaderFooterHarness {
2345 state: Entity<CommandState>,
2346 header_calls: Rc<Cell<usize>>,
2347 footer_calls: Rc<Cell<usize>>,
2348 header_matched_count: Rc<Cell<Option<usize>>>,
2349 footer_matched_count: Rc<Cell<Option<usize>>>,
2350 }
2351
2352 impl Render for HeaderFooterHarness {
2353 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
2354 let header_calls = self.header_calls.clone();
2355 let header_matched_count = self.header_matched_count.clone();
2356 let footer_calls = self.footer_calls.clone();
2357 let footer_matched_count = self.footer_matched_count.clone();
2358
2359 div().size_full().child(
2360 Command::new(&self.state)
2361 .items([
2362 CommandItem::new().label("Calendar"),
2363 CommandItem::new().label("Calculator"),
2364 ])
2365 .max_h(px(200.))
2366 .header(move |state, _, _| {
2367 header_calls.set(header_calls.get() + 1);
2368 header_matched_count.set(Some(state.matched_count()));
2369 div()
2370 })
2371 .footer(move |state, _, _| {
2372 footer_calls.set(footer_calls.get() + 1);
2373 footer_matched_count.set(Some(state.matched_count()));
2374 div()
2375 }),
2376 )
2377 }
2378 }
2379
2380 struct PaddedHarness {
2381 state: Entity<CommandState>,
2382 }
2383
2384 impl Render for PaddedHarness {
2385 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
2386 div().size_full().child(
2387 Command::new(&self.state)
2388 .item(
2389 CommandItem::new()
2390 .label("fixed")
2391 .child(|_, _| div().h(px(32.))),
2392 )
2393 .max_h(px(200.))
2394 .p_4(),
2395 )
2396 }
2397 }
2398
2399 struct WrappingHarness {
2400 state: Entity<CommandState>,
2401 width: Pixels,
2402 no_wrap: bool,
2403 }
2404
2405 impl Render for WrappingHarness {
2406 fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
2407 div().size_full().child(
2408 div().w(self.width).child(
2409 Command::new(&self.state)
2410 .item(CommandItem::new().label("wrapped").child(|_, _| {
2411 div()
2412 .w_full()
2413 .child("A command row whose content wraps at narrow list widths")
2414 }))
2415 .max_h(px(200.))
2416 .when(self.no_wrap, |this| this.whitespace_nowrap()),
2417 ),
2418 )
2419 }
2420 }
2421
2422 #[gpui::test]
2423 fn wrapping_rows_remeasure_for_the_list_content_width(cx: &mut TestAppContext) {
2424 cx.update(crate::init);
2425
2426 let (harness, cx) = cx.add_window_view(|window, cx| WrappingHarness {
2427 state: cx.new(|cx| CommandState::new(window, cx)),
2428 width: px(360.),
2429 no_wrap: false,
2430 });
2431
2432 cx.run_until_parked();
2433 cx.update(|window, cx| _ = window.draw(cx));
2434 cx.run_until_parked();
2435 cx.update(|window, cx| _ = window.draw(cx));
2436
2437 let wide = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2438
2439 cx.update(|_, cx| {
2440 harness.update(cx, |harness, cx| {
2441 harness.width = px(120.);
2442 cx.notify();
2443 })
2444 });
2445 cx.run_until_parked();
2446 cx.update(|window, cx| _ = window.draw(cx));
2447 cx.run_until_parked();
2448 cx.update(|window, cx| _ = window.draw(cx));
2449 let narrow = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2450
2451 assert!(
2452 narrow > wide,
2453 "the narrow list should cache a taller wrapped row ({narrow:?} vs {wide:?})",
2454 );
2455 }
2456
2457 #[gpui::test]
2458 fn wrapping_rows_remeasure_when_rem_size_changes(cx: &mut TestAppContext) {
2459 cx.update(crate::init);
2460
2461 let (harness, cx) = cx.add_window_view(|window, cx| {
2462 window.set_rem_size(px(20.));
2463 WrappingHarness {
2464 state: cx.new(|cx| CommandState::new(window, cx)),
2465 width: px(160.),
2466 no_wrap: false,
2467 }
2468 });
2469
2470 cx.run_until_parked();
2471 cx.update(|window, cx| _ = window.draw(cx));
2472 cx.run_until_parked();
2473 cx.update(|window, cx| _ = window.draw(cx));
2474 let smaller_rem = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2475
2476 cx.update(|window, cx| {
2477 window.set_rem_size(px(28.));
2478 _ = window.draw(cx);
2479 });
2480 cx.run_until_parked();
2481 cx.update(|window, cx| _ = window.draw(cx));
2482 let larger_rem = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2483
2484 assert!(
2485 larger_rem > smaller_rem,
2486 "a larger rem should remeasure the fixed-width wrapped row ({larger_rem:?} vs {smaller_rem:?})",
2487 );
2488 }
2489
2490 #[gpui::test]
2491 fn wrapping_rows_remeasure_when_inherited_typography_changes(cx: &mut TestAppContext) {
2492 cx.update(crate::init);
2493
2494 let (harness, cx) = cx.add_window_view(|window, cx| WrappingHarness {
2495 state: cx.new(|cx| CommandState::new(window, cx)),
2496 width: px(160.),
2497 no_wrap: false,
2498 });
2499
2500 cx.run_until_parked();
2501 cx.update(|window, cx| _ = window.draw(cx));
2502 cx.run_until_parked();
2503 cx.update(|window, cx| _ = window.draw(cx));
2504 let wrapped_height = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2505
2506 cx.update(|window, cx| {
2507 harness.update(cx, |harness, cx| {
2508 harness.no_wrap = true;
2509 cx.notify();
2510 });
2511 _ = window.draw(cx);
2512 });
2513 cx.run_until_parked();
2514 cx.update(|window, cx| _ = window.draw(cx));
2515 let no_wrap_height = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2516 assert!(
2517 no_wrap_height < wrapped_height,
2518 "a changed inherited typography should remeasure the fixed-width row ({no_wrap_height:?} vs {wrapped_height:?})",
2519 );
2520 }
2521
2522 #[gpui::test]
2523 fn outer_command_padding_does_not_inflate_measured_row_heights(cx: &mut TestAppContext) {
2524 cx.update(crate::init);
2525
2526 let (harness, cx) = cx.add_window_view(|window, cx| PaddedHarness {
2527 state: cx.new(|cx| CommandState::new(window, cx)),
2528 });
2529
2530 cx.run_until_parked();
2531 cx.update(|window, cx| _ = window.draw(cx));
2532 cx.run_until_parked();
2533 cx.update(|window, cx| _ = window.draw(cx));
2534 let height = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes[0].height);
2535
2536 assert_eq!(height, px(44.));
2537 }
2538
2539 #[gpui::test]
2540 fn custom_rows_keep_independent_heights(cx: &mut TestAppContext) {
2541 cx.update(crate::init);
2542
2543 let (harness, cx) = cx.add_window_view(|window, cx| Harness {
2544 state: cx.new(|cx| CommandState::new(window, cx)),
2545 command: Rc::new(|state| {
2546 Command::new(state)
2547 .group(
2548 CommandGroup::new().label("Short").item(
2549 CommandItem::new()
2550 .label("short")
2551 .child(|_, _| div().h(px(32.))),
2552 ),
2553 )
2554 .separator()
2555 .group(
2556 CommandGroup::new().label("Tall").item(
2557 CommandItem::new()
2558 .label("tall")
2559 .child(|_, _| div().h(px(72.))),
2560 ),
2561 )
2562 }),
2563 });
2564
2565 cx.run_until_parked();
2566 cx.update(|window, cx| _ = window.draw(cx));
2567 let row_sizes = cx.update(|_, cx| harness.read(cx).state.read(cx).row_sizes.clone());
2568
2569 assert_eq!(row_sizes.len(), 5);
2570 assert!(row_sizes[0].height > px(0.));
2571 assert_eq!(row_sizes[1].height, px(44.));
2572 assert_eq!(row_sizes[2].height, px(SEPARATOR_ROW_HEIGHT));
2573 assert!(row_sizes[3].height > px(0.));
2574 assert_eq!(row_sizes[4].height, px(84.));
2575 }
2576
2577 #[gpui::test]
2578 fn reinstalling_a_model_preserves_selection_by_index_path_and_remeasures_rows(
2579 cx: &mut TestAppContext,
2580 ) {
2581 cx.update(crate::init);
2582 let reversed = Rc::new(Cell::new(false));
2583 let reversed_for_render = reversed.clone();
2584 let (harness, cx) = cx.add_window_view(|window, cx| Harness {
2585 state: cx.new(|cx| CommandState::new(window, cx)),
2586 command: Rc::new(move |state| {
2587 if reversed_for_render.get() {
2588 Command::new(state)
2589 .item(
2590 CommandItem::new()
2591 .label("beta")
2592 .child(|_, _| div().h(px(72.))),
2593 )
2594 .item(
2595 CommandItem::new()
2596 .label("alpha")
2597 .child(|_, _| div().h(px(32.))),
2598 )
2599 } else {
2600 Command::new(state)
2601 .item(
2602 CommandItem::new()
2603 .label("alpha")
2604 .child(|_, _| div().h(px(32.))),
2605 )
2606 .item(
2607 CommandItem::new()
2608 .label("beta")
2609 .child(|_, _| div().h(px(72.))),
2610 )
2611 }
2612 }),
2613 });
2614 let state = cx.update(|_, cx| harness.read(cx).state.clone());
2615
2616 cx.run_until_parked();
2617 cx.update(|window, cx| _ = window.draw(cx));
2618 cx.update(|window, cx| {
2619 state.update(cx, |state, cx| state.select_by(1, window, cx));
2620 });
2621 assert_eq!(
2622 state.read_with(cx, |state, _| state.selected_index()),
2623 Some(IndexPath::new(1).section(0)),
2624 );
2625
2626 reversed.set(true);
2627 cx.update(|window, cx| {
2628 harness.update(cx, |_, cx| cx.notify());
2629 _ = window.draw(cx);
2630 });
2631
2632 let (selected_matched_index, selected_index, row_sizes) =
2633 state.read_with(cx, |state, _| {
2634 (
2635 state.selected_index,
2636 state.selected_index(),
2637 state.row_sizes.clone(),
2638 )
2639 });
2640 assert_eq!(selected_matched_index, Some(1));
2641 assert_eq!(selected_index, Some(IndexPath::new(1).section(0)));
2642 assert_eq!(row_sizes[0].height, px(84.));
2643 assert_eq!(row_sizes[1].height, px(44.));
2644 }
2645
2646 #[gpui::test]
2647 fn a_state_redraw_reuses_the_installed_custom_row_measurement(cx: &mut TestAppContext) {
2648 cx.update(crate::init);
2649 let renders = Rc::new(Cell::new(0));
2650 let count = renders.clone();
2651 let cx = cx.add_empty_window();
2652 let state = cx.update(|window, cx| {
2653 cx.new(|cx| {
2654 command_state(
2655 window,
2656 cx,
2657 [CommandEntry::Item(
2658 CommandItem::new().label("custom").child(move |_, _| {
2659 count.set(count.get() + 1);
2660 div().child("Custom")
2661 }),
2662 )],
2663 )
2664 })
2665 });
2666
2667 let first_state = state.clone();
2668 cx.draw(
2669 gpui::point(px(0.), px(0.)),
2670 gpui::AvailableSpace::min_size(),
2671 move |_, _| first_state.into_any_element(),
2672 );
2673 let settled_state = state.clone();
2674 cx.draw(
2675 gpui::point(px(0.), px(0.)),
2676 gpui::AvailableSpace::min_size(),
2677 move |_, _| settled_state.into_any_element(),
2678 );
2679 let after_first_draw = renders.get();
2680 cx.draw(
2681 gpui::point(px(0.), px(0.)),
2682 gpui::AvailableSpace::min_size(),
2683 move |_, _| state.into_any_element(),
2684 );
2685
2686 assert_eq!(renders.get() - after_first_draw, 2);
2687 }
2688
2689 #[gpui::test]
2690 fn moving_past_the_visible_rows_scrolls_the_list(cx: &mut TestAppContext) {
2691 cx.update(crate::init);
2692
2693 let (harness, cx) = cx.add_window_view(|window, cx| Harness {
2694 state: cx.new(|cx| CommandState::new(window, cx)),
2695 command: Rc::new(|state| {
2696 Command::new(state)
2697 .items((0..50).map(|ix| CommandItem::new().label(format!("Item {ix}"))))
2698 }),
2699 });
2700
2701 cx.run_until_parked();
2702 cx.update(|window, cx| _ = window.draw(cx));
2703
2704 let state = cx.update(|_, cx| harness.read(cx).state.clone());
2705 assert_eq!(
2706 state.read_with(cx, |state, _| state.scroll_handle.base_handle().offset().y),
2707 px(0.),
2708 );
2709
2710 cx.update(|window, cx| {
2713 state.update(cx, |state, cx| {
2714 for _ in 0..49 {
2715 state.select_by(1, window, cx);
2716 }
2717 })
2718 });
2719 cx.update(|window, cx| _ = window.draw(cx));
2720
2721 assert_eq!(
2722 state.read_with(cx, |state, _| state.selected_index()),
2723 Some(IndexPath::new(49).section(0))
2724 );
2725 assert!(
2726 state.read_with(cx, |state, _| state.scroll_handle.base_handle().offset().y) < px(0.),
2727 "selecting the last row should have scrolled the list",
2728 );
2729 }
2730
2731 #[gpui::test]
2732 fn a_reinstalled_model_does_not_scroll_a_preserved_selection(cx: &mut TestAppContext) {
2733 cx.update(crate::init);
2734
2735 let (harness, cx) = cx.add_window_view(|window, cx| Harness {
2736 state: cx.new(|cx| CommandState::new(window, cx)),
2737 command: Rc::new(|state| {
2738 Command::new(state)
2739 .items((0..50).map(|ix| CommandItem::new().label(format!("Item {ix}"))))
2740 }),
2741 });
2742
2743 cx.run_until_parked();
2744 cx.update(|window, cx| _ = window.draw(cx));
2745
2746 let state = cx.update(|_, cx| harness.read(cx).state.clone());
2747
2748 cx.update(|window, cx| {
2753 state.update(cx, |state, cx| state.select(10, window, cx));
2754 });
2755 cx.update(|window, cx| _ = window.draw(cx));
2756
2757 assert_eq!(
2758 state.read_with(cx, |state, _| state.scroll_handle.base_handle().offset().y),
2759 px(0.),
2760 "reinstalling the model must keep the scroll position",
2761 );
2762 }
2763}