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