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