1use std::{cell::RefCell, rc::Rc};
11
12use arc_motion::{
13 ArcPresence, BlurFallback, arc_spring_with_options, is_reduced_motion, spring::SpringOptions,
14};
15use arc_tokens::{
16 ActiveArcTheme as _, CommandPaletteTokens, ControlHeights, Radii, Shadows, Spacing, Typography,
17};
18use gpui_kit::{
19 App, Context, ElementId, Entity, FocusHandle, Focusable as _, IntoElement, KeyDownEvent,
20 MouseMoveEvent, ParentElement, RenderOnce, Role, ScrollHandle, SharedString, Styled,
21 Subscription, TestSupportExt as _, Window,
22 assets::IconName,
23 base::{ElementExt as _, StyledExt as _},
24 canvas,
25 component::{
26 Icon,
27 input::{Input as KitInput, InputState, MoveEnd, MoveHome},
28 },
29 div, point,
30 prelude::*,
31 px,
32};
33
34#[derive(Clone, Debug, PartialEq)]
37pub struct CommandItem {
38 pub id: SharedString,
39 pub label: SharedString,
40 pub description: Option<SharedString>,
41 pub group: Option<SharedString>,
42 pub keywords: Vec<SharedString>,
43 pub icon: Option<IconName>,
44 pub shortcut: Option<SharedString>,
45}
46
47impl CommandItem {
48 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
49 Self {
50 id: id.into(),
51 label: label.into(),
52 description: None,
53 group: None,
54 keywords: Vec::new(),
55 icon: None,
56 shortcut: None,
57 }
58 }
59
60 pub fn description(mut self, value: impl Into<SharedString>) -> Self {
61 self.description = Some(value.into());
62 self
63 }
64
65 pub fn group(mut self, value: impl Into<SharedString>) -> Self {
66 self.group = Some(value.into());
67 self
68 }
69
70 pub fn keywords<I, S>(mut self, values: I) -> Self
71 where
72 I: IntoIterator<Item = S>,
73 S: Into<SharedString>,
74 {
75 self.keywords = values.into_iter().map(Into::into).collect();
76 self
77 }
78
79 pub fn icon(mut self, value: IconName) -> Self {
80 self.icon = Some(value);
81 self
82 }
83
84 pub fn shortcut(mut self, value: impl Into<SharedString>) -> Self {
85 self.shortcut = Some(value.into());
86 self
87 }
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
91struct MatchRange {
92 start: usize,
93 end: usize,
94}
95
96#[derive(Clone, Debug)]
97struct RankedCommand {
98 item: CommandItem,
99 score: usize,
100 ranges: Vec<MatchRange>,
101 order: usize,
102}
103
104fn word_start(text: &str, word: &str) -> Option<usize> {
105 if word.is_empty() {
106 return None;
107 }
108 let mut offset = 0;
109 while let Some(found) = text[offset..].find(word) {
110 let at = offset + found;
111 if at == 0
112 || !text[..at]
113 .chars()
114 .next_back()
115 .is_some_and(|c| c.is_alphanumeric())
116 {
117 return Some(at);
118 }
119 offset = at
120 + text[at..]
121 .chars()
122 .next()
123 .expect("nonempty match")
124 .len_utf8();
125 }
126 None
127}
128
129fn subsequence(text: &str, word: &str) -> Option<Vec<MatchRange>> {
130 let mut chars = word.chars();
131 let first = chars.next()?;
132 if word.chars().count() < 2 {
133 return None;
134 }
135 for (start, _) in text.match_indices(first) {
136 if start > 0
137 && text[..start]
138 .chars()
139 .next_back()
140 .is_some_and(|c| c.is_alphanumeric())
141 {
142 continue;
143 }
144 let mut ranges = vec![MatchRange {
145 start,
146 end: start + first.len_utf8(),
147 }];
148 let mut cursor = start + first.len_utf8();
149 let mut matched = true;
150 for next in chars.clone() {
151 let Some(relative) = text[cursor..].find(next) else {
152 matched = false;
153 break;
154 };
155 let at = cursor + relative;
156 let end = at + next.len_utf8();
157 if ranges.last().is_some_and(|range| range.end == at) {
158 ranges.last_mut().expect("range exists").end = end;
159 } else {
160 ranges.push(MatchRange { start: at, end });
161 }
162 cursor = end;
163 }
164 if matched && text[start..cursor].chars().count() <= word.chars().count() * 3 {
165 return Some(ranges);
166 }
167 }
168 None
169}
170
171fn score_word(item: &CommandItem, label: &str, word: &str) -> Option<(usize, Vec<MatchRange>)> {
172 if let Some(at) = word_start(label, word) {
173 if at == 0 {
174 return Some((
175 100,
176 vec![MatchRange {
177 start: 0,
178 end: word.len(),
179 }],
180 ));
181 }
182 return Some((
183 80,
184 vec![MatchRange {
185 start: at,
186 end: at + word.len(),
187 }],
188 ));
189 }
190 if word.chars().count() >= 3
191 && let Some(at) = label.find(word).filter(|at| *at > 0)
192 {
193 return Some((
194 50,
195 vec![MatchRange {
196 start: at,
197 end: at + word.len(),
198 }],
199 ));
200 }
201 if item
202 .keywords
203 .iter()
204 .any(|keyword| word_start(&keyword.to_lowercase(), word).is_some())
205 {
206 return Some((40, Vec::new()));
207 }
208 if item
209 .description
210 .as_ref()
211 .is_some_and(|description| word_start(&description.to_lowercase(), word).is_some())
212 {
213 return Some((25, Vec::new()));
214 }
215 subsequence(label, word).map(|ranges| (10, ranges))
216}
217
218pub fn command_palette_rank(items: &[CommandItem], query: &str) -> Vec<CommandItem> {
220 command_palette_ranked(items, query)
221 .into_iter()
222 .map(|entry| entry.item)
223 .collect()
224}
225
226fn command_palette_ranked(items: &[CommandItem], query: &str) -> Vec<RankedCommand> {
227 let words: Vec<String> = query
228 .trim()
229 .to_lowercase()
230 .split_whitespace()
231 .map(str::to_owned)
232 .collect();
233 let mut ranked = Vec::new();
234 for (order, item) in items.iter().enumerate() {
235 if words.is_empty() {
236 ranked.push(RankedCommand {
237 item: item.clone(),
238 score: 0,
239 ranges: Vec::new(),
240 order,
241 });
242 continue;
243 }
244 let label = item.label.to_lowercase();
245 let mut score = 0;
246 let mut ranges = Vec::new();
247 let mut matched = true;
248 for word in &words {
249 let Some((word_score, word_ranges)) = score_word(item, &label, word) else {
250 matched = false;
251 break;
252 };
253 score += word_score;
254 ranges.extend(word_ranges);
255 }
256 if matched {
257 ranked.push(RankedCommand {
258 item: item.clone(),
259 score,
260 ranges,
261 order,
262 });
263 }
264 }
265 ranked.sort_by_key(|entry| (std::cmp::Reverse(entry.score), entry.order));
266 ranked
267}
268
269pub fn command_palette_group_by(ranked: &[CommandItem]) -> Vec<(SharedString, Vec<CommandItem>)> {
271 let mut groups: Vec<(SharedString, Vec<CommandItem>)> = Vec::new();
272 for item in ranked {
273 let group = item.group.clone().unwrap_or_else(|| "Actions".into());
274 if let Some((_, entries)) = groups.iter_mut().find(|(name, _)| *name == group) {
275 entries.push(item.clone());
276 } else {
277 groups.push((group, vec![item.clone()]));
278 }
279 }
280 groups
281}
282
283pub fn command_palette_shortcut_keys(shortcut: &str) -> Vec<SharedString> {
284 let mut keys = Vec::new();
285 let mut start = 0;
286 for (at, ch) in shortcut.char_indices() {
287 if ch.is_whitespace() || (ch == '+' && at + 1 < shortcut.len()) {
288 if start < at {
289 keys.push(shortcut[start..at].into());
290 }
291 start = at + ch.len_utf8();
292 }
293 }
294 if start < shortcut.len() {
295 keys.push(shortcut[start..].into());
296 }
297 keys
298}
299
300fn highlight_ranges(label: &str, ranges: &[MatchRange]) -> Vec<std::ops::Range<usize>> {
302 let mut folded_at = 0;
303 let mut result: Vec<std::ops::Range<usize>> = Vec::new();
304 for (at, character) in label.char_indices() {
305 let folded_end = folded_at + character.to_lowercase().map(char::len_utf8).sum::<usize>();
306 if ranges
307 .iter()
308 .any(|range| range.start < folded_end && range.end > folded_at)
309 {
310 let end = at + character.len_utf8();
311 if let Some(last) = result.last_mut().filter(|last| last.end == at) {
312 last.end = end;
313 } else {
314 result.push(at..end);
315 }
316 }
317 folded_at = folded_end;
318 }
319 result
320}
321
322fn label_with_highlight(label: &str, ranges: &[MatchRange]) -> gpui_kit::StyledText {
323 gpui_kit::StyledText::new(label.to_owned()).with_highlights(
324 highlight_ranges(label, ranges).into_iter().map(|range| {
325 (
326 range,
327 gpui_kit::HighlightStyle {
328 font_weight: Some(gpui_kit::FontWeight::MEDIUM),
329 ..Default::default()
330 },
331 )
332 }),
333 )
334}
335
336#[derive(Clone)]
337struct RetainedCommandRow {
338 item: CommandItem,
339 ranges: Vec<MatchRange>,
340 top: f32,
341}
342
343#[derive(Clone)]
344struct RetainedCommandGroup {
345 name: SharedString,
346 top: f32,
347 rows: Vec<RetainedCommandRow>,
348}
349
350fn command_row_content(
352 palette_id: &ElementId,
353 item: &CommandItem,
354 ranges: &[MatchRange],
355 narrow: bool,
356 cx: &App,
357) -> gpui_kit::Div {
358 let colors = cx.arc_theme().colors;
359 let mut copy = div()
360 .flex()
361 .items_center()
362 .gap(Spacing::S2)
363 .min_w_0()
364 .flex_1()
365 .child(
366 div()
367 .min_w_0()
368 .truncate()
369 .text_size(Typography::TEXT_SM)
370 .child(label_with_highlight(item.label.as_ref(), ranges)),
371 );
372 if let Some(description) = &item.description {
373 copy = copy.child(
374 div()
375 .text_size(Typography::TEXT_XS)
376 .text_color(colors.text_muted)
377 .truncate()
378 .child(description.clone()),
379 );
380 }
381 div()
382 .flex()
383 .items_center()
384 .w_full()
385 .gap(Spacing::S2)
386 .child(
387 Icon::new(item.icon.unwrap_or(IconName::Command))
388 .text_size(CommandPaletteTokens::ICON)
389 .text_color(if item.icon.is_some() {
390 colors.text_secondary
391 } else {
392 colors.text_muted
393 }),
394 )
395 .child(copy)
396 .when_some(
397 item.shortcut.as_ref().filter(|_| !narrow),
398 |row, shortcut| {
399 row.child(
400 div()
401 .id(ElementId::NamedChild(
402 palette_id.clone().into(),
403 format!("shortcut-{}", item.id).into(),
404 ))
405 .test_support()
406 .flex()
407 .gap(Spacing::S1)
408 .children(
409 command_palette_shortcut_keys(shortcut)
410 .into_iter()
411 .map(|key| {
412 div()
413 .min_w(CommandPaletteTokens::KEYCAP)
414 .h(CommandPaletteTokens::KEYCAP)
415 .px(Spacing::S1)
416 .rounded(Radii::CONTROL)
417 .bg(colors.surface_muted)
418 .text_size(Typography::TEXT_XS)
419 .text_color(colors.text_secondary)
420 .flex()
421 .items_center()
422 .justify_center()
423 .child(key)
424 }),
425 ),
426 )
427 },
428 )
429}
430
431type CommandSelectHandler = Rc<dyn Fn(&CommandItem, &mut Window, &mut App)>;
432type CommandCloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
433
434#[derive(Clone)]
435struct CommandPaletteInternal {
436 query_input: Entity<InputState>,
437 keyboard_scope: FocusHandle,
439 focus_handle: FocusHandle,
440 last_query: SharedString,
441 placeholder: SharedString,
442 active_index: i64,
444 pointer_item: Option<SharedString>,
445 pointer_navigation: bool,
446 highlight_top: f32,
447 last_pointer: Rc<RefCell<Option<(f32, f32)>>>,
448 scroll: ScrollHandle,
449 width: Rc<RefCell<f32>>,
450 previous_positions: std::collections::HashMap<SharedString, f32>,
451 previous_active: Option<SharedString>,
452 group_positions: std::collections::HashMap<SharedString, f32>,
453 content_origin: Rc<std::cell::Cell<f32>>,
454 displayed_results: Option<bool>,
456 rendered_ranked: Vec<RankedCommand>,
457 retained_rows: Vec<RetainedCommandRow>,
458 retained_groups: Vec<RetainedCommandGroup>,
459 glide: bool,
460 empty_query: SharedString,
461 _subscriptions: Rc<Vec<Subscription>>,
462}
463
464impl CommandPaletteInternal {
465 fn new(
466 placeholder: SharedString,
467 auto_focus: bool,
468 window: &mut Window,
469 cx: &mut Context<Self>,
470 ) -> Self {
471 let query_input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder.clone()));
472 let focus_handle = query_input.read(cx).focus_handle(cx);
473 let observer = cx.observe(&query_input, |_, _, cx| cx.notify());
474 let input = query_input.clone();
475 let window_id = window.window_handle().window_id();
476 let shortcut = cx.intercept_keystrokes(move |event, window, cx| {
478 let stroke = &event.keystroke;
479 if window.window_handle().window_id() == window_id
480 && (stroke.modifiers.control || stroke.modifiers.platform)
481 && stroke.key.eq_ignore_ascii_case("k")
482 {
483 input.update(cx, |input, cx| input.focus(window, cx));
484 cx.stop_propagation();
485 window.refresh();
486 }
487 });
488 if auto_focus {
489 let input = query_input.clone();
490 window.on_next_frame(move |window, cx| {
491 input.update(cx, |input, cx| input.focus(window, cx));
492 });
493 }
494 Self {
495 query_input,
496 keyboard_scope: cx.focus_handle(),
497 focus_handle,
498 last_query: "".into(),
499 placeholder,
500 active_index: 0,
501 pointer_item: None,
502 pointer_navigation: false,
503 highlight_top: 0.0,
504 last_pointer: Rc::new(RefCell::new(None)),
505 scroll: ScrollHandle::new(),
506 width: Rc::new(RefCell::new(f32::from(CommandPaletteTokens::MAX_WIDTH))),
507 previous_positions: Default::default(),
508 previous_active: None,
509 group_positions: Default::default(),
510 content_origin: Rc::new(std::cell::Cell::new(0.0)),
511 displayed_results: None,
512 rendered_ranked: Vec::new(),
513 retained_rows: Vec::new(),
514 retained_groups: Vec::new(),
515 glide: true,
516 empty_query: "".into(),
517 _subscriptions: Rc::new(vec![observer, shortcut]),
518 }
519 }
520}
521
522#[derive(IntoElement)]
524pub struct CommandPalette {
525 id: ElementId,
526 items: Vec<CommandItem>,
527 placeholder: SharedString,
528 label: SharedString,
529 auto_focus: bool,
530 animate_entry: bool,
531 on_select: Option<CommandSelectHandler>,
532 on_close: Option<CommandCloseHandler>,
533}
534
535impl CommandPalette {
536 pub fn new(id: impl Into<ElementId>) -> Self {
537 Self {
538 id: id.into(),
539 items: Vec::new(),
540 placeholder: "Search commands".into(),
541 label: "Command palette".into(),
542 auto_focus: false,
543 animate_entry: true,
544 on_select: None,
545 on_close: None,
546 }
547 }
548
549 pub fn items<I>(mut self, items: I) -> Self
550 where
551 I: IntoIterator<Item = CommandItem>,
552 {
553 self.items = items.into_iter().collect();
554 self
555 }
556
557 pub fn placeholder(mut self, value: impl Into<SharedString>) -> Self {
558 self.placeholder = value.into();
559 self
560 }
561
562 pub fn label(mut self, value: impl Into<SharedString>) -> Self {
563 self.label = value.into();
564 self
565 }
566
567 pub fn auto_focus(mut self, value: bool) -> Self {
568 self.auto_focus = value;
569 self
570 }
571
572 pub fn animate_entry(mut self, value: bool) -> Self {
574 self.animate_entry = value;
575 self
576 }
577
578 pub fn on_select<F>(mut self, callback: F) -> Self
579 where
580 F: Fn(&CommandItem, &mut Window, &mut App) + 'static,
581 {
582 self.on_select = Some(Rc::new(callback));
583 self
584 }
585
586 pub fn on_close<F>(mut self, callback: F) -> Self
587 where
588 F: Fn(&mut Window, &mut App) + 'static,
589 {
590 self.on_close = Some(Rc::new(callback));
591 self
592 }
593}
594
595impl RenderOnce for CommandPalette {
596 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
597 let colors = cx.arc_theme().colors;
598 let reduced = is_reduced_motion(cx);
599 let state_id = ElementId::NamedChild(self.id.clone().into(), "state".into());
600 let internal = window.use_keyed_state(state_id, cx, |window, cx| {
601 CommandPaletteInternal::new(self.placeholder.clone(), self.auto_focus, window, cx)
602 });
603 let snapshot = internal.read(cx).clone();
604 let motion = cx.arc_theme().motion;
605 let raw_query = snapshot.query_input.read(cx).value();
607 let query = raw_query.trim().to_owned();
608 if snapshot.placeholder != self.placeholder {
609 internal.update(cx, |state, _| state.placeholder = self.placeholder.clone());
610 snapshot.query_input.update(cx, |input, cx| {
611 input.set_placeholder(self.placeholder.clone(), window, cx);
612 });
613 }
614 let ranked = command_palette_ranked(&self.items, &query);
615 let ranked_items: Vec<CommandItem> =
616 ranked.iter().map(|entry| entry.item.clone()).collect();
617 let groups = command_palette_group_by(&ranked_items);
618 let visual_items: Vec<CommandItem> = groups
619 .iter()
620 .flat_map(|(_, items)| items.iter().cloned())
621 .collect();
622 let query_changed = raw_query != snapshot.last_query;
623 let active_index = if visual_items.is_empty() {
624 -1
625 } else if query_changed {
626 0
627 } else {
628 snapshot
629 .active_index
630 .clamp(0, visual_items.len() as i64 - 1)
631 };
632 internal.update(cx, |state, _| {
633 state.last_query = raw_query.clone();
634 state.active_index = active_index;
635 if query_changed {
636 state.pointer_navigation = false;
637 state.pointer_item = None;
638 }
639 });
640 let narrow = *snapshot.width.borrow() < f32::from(CommandPaletteTokens::NARROW_WIDTH);
641 let row_h = f32::from(CommandPaletteTokens::ROW);
642 let heading_h = f32::from(CommandPaletteTokens::HEADING);
643 let mut positions = std::collections::HashMap::new();
644 let mut content_height = 0.0;
645 for (_, items) in &groups {
646 content_height += heading_h;
647 for item in items {
648 positions.insert(item.id.clone(), content_height);
649 content_height += row_h;
650 }
651 }
652 let previous_items: Vec<_> = command_palette_group_by(
653 &snapshot
654 .rendered_ranked
655 .iter()
656 .map(|e| e.item.clone())
657 .collect::<Vec<_>>(),
658 )
659 .into_iter()
660 .flat_map(|(_, items)| items)
661 .collect();
662 let list_changed = previous_items != visual_items;
663 let glide = !reduced
665 && if list_changed {
666 visual_items.iter().enumerate().all(|(index, item)| {
667 previous_items
668 .iter()
669 .position(|old| old.id == item.id)
670 .is_none_or(|before| {
671 before.abs_diff(index) <= CommandPaletteTokens::GLIDE_ROWS
672 })
673 })
674 } else {
675 snapshot.glide
676 };
677 internal.update(cx, |state, _| state.glide = glide);
678 let pointer_navigation = snapshot.pointer_navigation && !query_changed;
679 let active_id = if pointer_navigation {
680 snapshot
681 .pointer_item
682 .clone()
683 .filter(|id| positions.contains_key(id))
684 } else {
685 (active_index >= 0).then(|| visual_items[active_index as usize].id.clone())
686 };
687 if !pointer_navigation && (query_changed || active_id != snapshot.previous_active) {
689 let scroll = snapshot.scroll.clone();
690 let target = active_id.as_ref().map(|id| positions[id]);
691 let viewport = content_height.min(f32::from(
692 CommandPaletteTokens::MAX_RESULTS - CommandPaletteTokens::RESULTS_INSET * 2.0,
693 ));
694 window.on_next_frame(move |window, _| {
695 let offset = scroll.offset();
696 let mut y = f32::from(offset.y);
697 if let Some(top) = target {
698 if top + y < 0.0 {
699 y = -top;
700 }
701 if top + row_h + y > viewport {
702 y = viewport - top - row_h;
703 }
704 } else {
705 y = 0.0;
706 }
707 scroll.set_offset(point(offset.x, px(y.min(0.0))));
708 window.refresh();
709 });
710 }
711 internal.update(cx, |state, _| {
712 state.previous_active = active_id.clone();
713 });
714
715 let query_input = KitInput::new(&snapshot.query_input)
716 .id(ElementId::NamedChild(
717 self.id.clone().into(),
718 "input".into(),
719 ))
720 .appearance(false)
721 .h(ControlHeights::MD)
722 .w_full()
723 .text_size(Typography::TEXT_SM)
724 .role(Role::ComboBox)
725 .aria_label(self.label.clone());
726
727 let click_select_handler = self.on_select.clone();
728 let select = self.on_select.clone();
729 let close = self.on_close.clone();
730 let key_state = internal.clone();
731 let key_items = visual_items.clone();
732 let key_input = snapshot.query_input.clone();
733 let key_close = close.clone();
734 let home_state = internal.clone();
735 let end_state = internal.clone();
736 let end_index = key_items.len() as i64 - 1;
737 let home_listener = move |_: &MoveHome, window: &mut Window, cx: &mut App| {
738 home_state.update(cx, |state, _| {
739 state.active_index = 0;
740 state.pointer_navigation = false;
741 state.pointer_item = None;
742 });
743 cx.stop_propagation();
744 window.refresh();
745 };
746 let end_listener = move |_: &MoveEnd, window: &mut Window, cx: &mut App| {
747 end_state.update(cx, |state, _| {
748 state.active_index = end_index;
749 state.pointer_navigation = false;
750 state.pointer_item = None;
751 });
752 cx.stop_propagation();
753 window.refresh();
754 };
755 let key_listener = move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
756 let key = event.keystroke.key.as_str();
757 let modifiers = event.keystroke.modifiers;
758 if (modifiers.control || modifiers.platform) && key.eq_ignore_ascii_case("k") {
759 key_input.update(cx, |state, cx| state.focus(window, cx));
760 window.refresh();
761 return;
762 }
763 let len = key_items.len() as i64;
764 if matches!(
765 key,
766 "down" | "arrowdown" | "up" | "arrowup" | "home" | "end"
767 ) {
768 key_state.update(cx, |state, _| {
769 state.pointer_navigation = false;
770 state.pointer_item = None;
771 });
772 }
773 match key {
774 "down" | "arrowdown" | "up" | "arrowup" | "home" | "end" | "enter" if len == 0 => {}
775 "down" | "arrowdown" if len > 0 => {
776 key_state.update(cx, |state, _| {
777 state.active_index = (state.active_index + 1).min(len - 1);
778 });
779 }
780 "up" | "arrowup" if len > 0 => {
781 key_state.update(cx, |state, _| {
782 state.active_index = (state.active_index - 1).max(0);
783 });
784 }
785 "home" if len > 0 => key_state.update(cx, |state, _| {
786 state.active_index = 0;
787 }),
788 "end" if len > 0 => key_state.update(cx, |state, _| {
789 state.active_index = len - 1;
790 }),
791 "enter" if len > 0 => {
792 let state = key_state.read(cx);
793 let target = if state.pointer_navigation {
794 state
795 .pointer_item
796 .as_ref()
797 .and_then(|id| key_items.iter().find(|item| &item.id == id))
798 } else {
799 key_items.get(state.active_index.clamp(0, len - 1) as usize)
800 };
801 if let Some(item) = target {
802 if let Some(handler) = &select {
803 handler(item, window, cx);
804 }
805 key_input.update(cx, |state, cx| {
806 state.set_value("", window, cx);
807 state.focus(window, cx);
808 });
809 key_state.update(cx, |state, _| {
810 state.last_query = "".into();
811 state.active_index = 0;
812 state.pointer_navigation = false;
813 state.pointer_item = None;
814 });
815 }
816 }
817 "escape" => {
818 if !key_input.read(cx).value().is_empty() {
819 key_input.update(cx, |state, cx| state.set_value("", window, cx));
820 key_state.update(cx, |state, _| {
821 state.last_query = "".into();
822 state.active_index = 0;
823 state.pointer_navigation = false;
824 state.pointer_item = None;
825 });
826 } else if let Some(handler) = &key_close {
827 handler(window, cx);
828 }
829 }
830 _ => return,
831 }
832 cx.stop_propagation();
833 window.refresh();
834 };
835
836 let highlight_target = active_id
838 .as_ref()
839 .map(|id| positions[id])
840 .unwrap_or(snapshot.highlight_top);
841 let highlight_y = arc_spring_with_options(
842 (self.id.clone(), "highlight-y"),
843 highlight_target,
844 SpringOptions::new(motion.spring.snappy)
845 .with_initial_value(highlight_target)
846 .with_travel(!reduced && active_id.is_some() && snapshot.previous_active.is_some()),
847 window,
848 cx,
849 )
850 .value;
851 internal.update(cx, |state, _| state.highlight_top = highlight_y);
852 let highlight_opacity =
853 ArcPresence::new((self.id.clone(), "highlight-opacity"), active_id.is_some())
854 .enter(CommandPaletteTokens::HIGHLIGHT_ENTER, motion.ease.enter)
855 .exit(CommandPaletteTokens::HIGHLIGHT_EXIT, motion.ease.standard)
856 .sample(window, cx)
857 .progress;
858 let wants_results = !visual_items.is_empty();
859 let mut showing_results = snapshot.displayed_results.unwrap_or(wants_results);
860 let mut content_presence = ArcPresence::new(
862 (self.id.clone(), "content-presence"),
863 showing_results == wants_results,
864 )
865 .animate_initial(false)
866 .enter(motion.duration.standard, motion.ease.enter)
867 .exit(motion.duration.instant, motion.ease.standard)
868 .sample(window, cx);
869 if !content_presence.should_render() {
870 showing_results = wants_results;
871 internal.update(cx, |state, _| {
872 state.displayed_results = Some(showing_results)
873 });
874 content_presence = ArcPresence::new((self.id.clone(), "content-presence"), true)
875 .enter(motion.duration.standard, motion.ease.enter)
876 .exit(motion.duration.instant, motion.ease.standard)
877 .sample(window, cx);
878 }
879 let displayed_ranked = if showing_results && wants_results {
880 ranked.clone()
881 } else {
882 snapshot.rendered_ranked.clone()
883 };
884 internal.update(cx, |state, _| {
885 state.displayed_results = Some(showing_results);
886 if showing_results && wants_results {
887 state.rendered_ranked = ranked.clone();
888 }
889 if !showing_results && !wants_results {
890 state.empty_query = query.clone().into();
891 }
892 });
893 let displayed_items: Vec<_> = displayed_ranked.iter().map(|e| e.item.clone()).collect();
894 let displayed_groups = if showing_results {
895 command_palette_group_by(&displayed_items)
896 } else {
897 Vec::new()
898 };
899 let mut displayed_positions = std::collections::HashMap::new();
900 let mut displayed_height = 0.0;
901 for (_, items) in &displayed_groups {
902 displayed_height += heading_h;
903 for item in items {
904 displayed_positions.insert(item.id.clone(), displayed_height);
905 displayed_height += row_h;
906 }
907 }
908 let interactive_results = showing_results && wants_results;
909 let mut retained_groups = snapshot.retained_groups.clone();
911 for (name, entries) in command_palette_group_by(&previous_items) {
912 if interactive_results
913 && !displayed_groups.iter().any(|(next, _)| *next == name)
914 && !retained_groups.iter().any(|group| group.name == name)
915 && let Some(top) = snapshot.group_positions.get(&name)
916 {
917 retained_groups.push(RetainedCommandGroup {
918 name,
919 top: *top,
920 rows: entries
921 .into_iter()
922 .filter_map(|item| {
923 snapshot.previous_positions.get(&item.id).map(|top| {
924 RetainedCommandRow {
925 ranges: snapshot
926 .rendered_ranked
927 .iter()
928 .find(|r| r.item.id == item.id)
929 .map(|r| r.ranges.clone())
930 .unwrap_or_default(),
931 item,
932 top: *top,
933 }
934 })
935 })
936 .collect(),
937 });
938 }
939 }
940 let mut active_groups = Vec::new();
941 let mut exit_groups = Vec::new();
942 for group in retained_groups {
943 if !interactive_results || displayed_groups.iter().any(|(name, _)| *name == group.name)
944 {
945 continue;
946 }
947 let sample = ArcPresence::new(
948 (
949 ElementId::NamedChild(
950 self.id.clone().into(),
951 format!("group-{}", group.name).into(),
952 ),
953 "group-presence",
954 ),
955 false,
956 )
957 .animate_initial(false)
958 .enter(motion.duration.standard, motion.ease.enter)
959 .exit(
960 if glide {
961 motion.duration.instant
962 } else {
963 std::time::Duration::ZERO
964 },
965 motion.ease.standard,
966 )
967 .sample(window, cx);
968 if sample.should_render() {
969 let mut layer = div()
970 .id(ElementId::NamedChild(
971 self.id.clone().into(),
972 format!("exit-group-{}", group.name).into(),
973 ))
974 .test_support()
975 .absolute()
976 .top(px(group.top))
977 .left_0()
978 .right_0()
979 .opacity(sample.progress)
980 .child(
981 div()
982 .h(px(heading_h))
983 .px(Spacing::S3)
984 .flex()
985 .items_center()
986 .text_size(Typography::TEXT_XS)
987 .text_color(colors.text_muted)
988 .font_medium()
989 .child(group.name.clone()),
990 );
991 for row in &group.rows {
992 layer = layer.child(
993 div()
994 .absolute()
995 .top(px(row.top - group.top))
996 .left_0()
997 .right_0()
998 .h(px(row_h))
999 .px(Spacing::S3)
1000 .flex()
1001 .items_center()
1002 .child(command_row_content(
1003 &ElementId::NamedChild(self.id.clone().into(), "exit".into()),
1004 &row.item,
1005 &row.ranges,
1006 narrow,
1007 cx,
1008 )),
1009 );
1010 }
1011 exit_groups.push(layer.into_any_element());
1012 active_groups.push(group);
1013 }
1014 }
1015 internal.update(cx, |state, _| state.retained_groups = active_groups.clone());
1016 let mut retained_rows = snapshot.retained_rows.clone();
1017 for previous in &snapshot.rendered_ranked {
1018 if interactive_results
1019 && !displayed_positions.contains_key(&previous.item.id)
1020 && !retained_rows
1021 .iter()
1022 .any(|row| row.item.id == previous.item.id)
1023 && let Some(top) = snapshot.previous_positions.get(&previous.item.id)
1024 {
1025 retained_rows.push(RetainedCommandRow {
1026 item: previous.item.clone(),
1027 ranges: previous.ranges.clone(),
1028 top: *top,
1029 });
1030 }
1031 }
1032 let mut active_retained = Vec::new();
1033 let mut exit_rows = Vec::new();
1034 for row in retained_rows {
1035 if !interactive_results
1036 || displayed_positions.contains_key(&row.item.id)
1037 || active_groups
1038 .iter()
1039 .any(|group| group.rows.iter().any(|r| r.item.id == row.item.id))
1040 {
1041 continue;
1042 }
1043 let sample = ArcPresence::new(
1044 (
1045 ElementId::NamedChild(self.id.clone().into(), row.item.id.clone()),
1046 "row-presence",
1047 ),
1048 false,
1049 )
1050 .animate_initial(false)
1051 .enter(motion.duration.standard, motion.ease.enter)
1052 .exit(
1053 if glide {
1054 motion.duration.instant
1055 } else {
1056 std::time::Duration::ZERO
1057 },
1058 motion.ease.standard,
1059 )
1060 .sample(window, cx);
1061 if sample.should_render() {
1062 exit_rows.push(
1063 div()
1064 .id(ElementId::NamedChild(
1065 self.id.clone().into(),
1066 format!("exit-{}", row.item.id).into(),
1067 ))
1068 .test_support()
1069 .absolute()
1070 .top(px(row.top))
1071 .left_0()
1072 .right_0()
1073 .h(px(row_h))
1074 .px(Spacing::S3)
1075 .flex()
1076 .items_center()
1077 .opacity(sample.progress)
1078 .child(command_row_content(
1079 &ElementId::NamedChild(self.id.clone().into(), "exit".into()),
1080 &row.item,
1081 &row.ranges,
1082 narrow,
1083 cx,
1084 ))
1085 .into_any_element(),
1086 );
1087 active_retained.push(row);
1088 }
1089 }
1090 internal.update(cx, |state, _| state.retained_rows = active_retained);
1091 let mut result_rows: Vec<gpui_kit::AnyElement> = Vec::new();
1092 let mut flat_index = 0usize;
1093 let mut group_top = 0.0;
1094 for (group_name, entries) in displayed_groups {
1095 let group_id =
1096 ElementId::NamedChild(self.id.clone().into(), format!("group-{group_name}").into());
1097 let group_presence = ArcPresence::new((group_id.clone(), "group-presence"), true)
1098 .animate_initial(snapshot.displayed_results.is_some())
1099 .enter(motion.duration.standard, motion.ease.enter)
1100 .exit(motion.duration.instant, motion.ease.standard)
1101 .sample(window, cx);
1102 let group_y = arc_spring_with_options(
1103 (group_id.clone(), "group-y"),
1104 group_top,
1105 SpringOptions::new(motion.spring.smooth)
1106 .with_initial_value(group_top)
1107 .with_travel(glide),
1108 window,
1109 cx,
1110 )
1111 .value
1112 - group_top;
1113 let group_base = group_top;
1114 group_top += heading_h + entries.len() as f32 * row_h;
1115 let measured_state = internal.clone();
1116 let measured_origin = snapshot.content_origin.clone();
1117 let measured_group = group_name.clone();
1118 let heading = div()
1119 .h(px(heading_h))
1120 .px(Spacing::S3)
1121 .flex()
1122 .items_center()
1123 .text_size(Typography::TEXT_XS)
1124 .text_color(colors.text_muted)
1125 .font_medium()
1126 .child(group_name.clone());
1127 let mut rows = vec![heading.into_any_element()];
1128 for entry in entries {
1129 let row_index = flat_index;
1130 flat_index += 1;
1131 let active = interactive_results && active_id.as_ref() == Some(&entry.id);
1132 let item_id = entry.id.clone();
1133 let pointer_state = internal.clone();
1134 let leave_state = internal.clone();
1135 let pointer_id = entry.id.clone();
1136 let leave_id = entry.id.clone();
1137 let item_for_click = entry.clone();
1138 let click_select = click_select_handler.clone();
1139 let click_state = internal.clone();
1140 let click_input = snapshot.query_input.clone();
1141 let row_target = displayed_positions[&entry.id];
1142 let row_y = arc_spring_with_options(
1143 (
1144 ElementId::NamedChild(self.id.clone().into(), entry.id.clone()),
1145 "row-y",
1146 ),
1147 row_target - group_base,
1148 SpringOptions::new(motion.spring.smooth)
1149 .with_initial_value(row_target - group_base)
1150 .with_travel(glide),
1151 window,
1152 cx,
1153 )
1154 .value
1155 - (row_target - group_base);
1156 let ranges = displayed_ranked
1157 .iter()
1158 .find(|candidate| candidate.item.id == entry.id)
1159 .map(|candidate| candidate.ranges.clone())
1160 .unwrap_or_default();
1161 let row_presence = ArcPresence::new(
1162 (
1163 ElementId::NamedChild(self.id.clone().into(), entry.id.clone()),
1164 "row-presence",
1165 ),
1166 true,
1167 )
1168 .animate_initial(snapshot.displayed_results.is_some())
1169 .enter(motion.duration.standard, motion.ease.enter)
1170 .exit(motion.duration.instant, motion.ease.standard)
1171 .sample(window, cx);
1172 let measured_row_state = internal.clone();
1173 let measured_row_origin = snapshot.content_origin.clone();
1174 let measured_item = entry.id.clone();
1175 let row = div()
1176 .on_prepaint(move |bounds, _, cx| {
1177 measured_row_state.update(cx, |s, _| {
1178 s.previous_positions.insert(
1179 measured_item.clone(),
1180 f32::from(bounds.origin.y) - measured_row_origin.get(),
1181 );
1182 });
1183 })
1184 .opacity(row_presence.progress)
1185 .id(ElementId::NamedChild(
1186 self.id.clone().into(),
1187 format!("item-{item_id}").into(),
1188 ))
1189 .test_support()
1190 .w_full()
1191 .h(px(row_h))
1192 .flex_shrink_0()
1193 .top(px(row_y))
1194 .px(Spacing::S3)
1195 .gap(Spacing::S2)
1196 .rounded(Radii::CONTROL)
1197 .flex()
1198 .flex_row()
1199 .items_center()
1200 .relative()
1201 .cursor_pointer()
1202 .role(Role::ListBoxOption)
1203 .aria_label(entry.label.clone())
1204 .aria_selected(active)
1205 .when(active, |d| d.aria_active_descendant())
1206 .aria_position_in_set(row_index + 1)
1207 .aria_size_of_set(visual_items.len())
1208 .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
1209 if !interactive_results {
1210 return;
1211 }
1212 let point = event.position;
1213 let current = (f32::from(point.x), f32::from(point.y));
1214 let pointer = pointer_state.read(cx).last_pointer.clone();
1215 if *pointer.borrow() == Some(current) {
1216 return;
1217 }
1218 *pointer.borrow_mut() = Some(current);
1219 pointer_state.update(cx, |state, _| {
1220 state.pointer_navigation = true;
1221 state.pointer_item = Some(pointer_id.clone());
1222 });
1223 window.refresh();
1224 })
1225 .on_hover(move |hovered, window, cx| {
1226 if !*hovered {
1227 leave_state.update(cx, |state, _| {
1228 if state.pointer_item.as_ref() == Some(&leave_id) {
1229 state.pointer_item = None;
1230 *state.last_pointer.borrow_mut() = None;
1231 }
1232 });
1233 window.refresh();
1234 }
1235 })
1236 .on_mouse_down(gpui_kit::MouseButton::Left, |_, window, _| {
1237 window.prevent_default()
1238 })
1239 .on_click(move |_, window, cx| {
1240 if !interactive_results {
1241 return;
1242 }
1243 if let Some(handler) = &click_select {
1244 handler(&item_for_click, window, cx);
1245 }
1246 click_input.update(cx, |input, cx| {
1247 input.set_value("", window, cx);
1248 input.focus(window, cx);
1249 });
1250 click_state.update(cx, |state, _| {
1251 state.last_query = "".into();
1252 state.active_index = 0;
1253 state.pointer_navigation = false;
1254 state.pointer_item = None;
1255 });
1256 window.refresh();
1257 });
1258 rows.push(
1259 row.child(command_row_content(&self.id, &entry, &ranges, narrow, cx))
1260 .into_any_element(),
1261 );
1262 }
1263 result_rows.push(
1264 div()
1265 .id(group_id)
1266 .test_support()
1267 .on_prepaint(move |bounds, _, cx| {
1268 measured_state.update(cx, |s, _| {
1269 s.group_positions.insert(
1270 measured_group.clone(),
1271 f32::from(bounds.origin.y) - measured_origin.get(),
1272 );
1273 });
1274 })
1275 .relative()
1276 .top(px(group_y))
1277 .opacity(group_presence.progress)
1278 .role(Role::Group)
1279 .aria_label(group_name)
1280 .flex()
1281 .flex_col()
1282 .children(rows)
1283 .into_any_element(),
1284 );
1285 }
1286
1287 internal.update(cx, |state, _| {
1288 state
1289 .previous_positions
1290 .retain(|id, _| displayed_positions.contains_key(id));
1291 state.group_positions.retain(|name, _| {
1292 displayed_items.iter().any(|item| {
1293 item.group
1294 .as_ref()
1295 .map_or("Actions", |group| group.as_ref())
1296 == name.as_ref()
1297 })
1298 });
1299 });
1300
1301 if !showing_results {
1302 let empty_presence = content_presence;
1303 let blur = BlurFallback::evaluate(
1304 motion.blur.subtle * (1.0 - empty_presence.progress),
1305 reduced,
1306 );
1307 result_rows.push(
1308 div()
1309 .id(ElementId::NamedChild(
1310 self.id.clone().into(),
1311 "empty".into(),
1312 ))
1313 .test_support()
1314 .relative()
1315 .top(if reduced {
1316 px(0.0)
1317 } else {
1318 (if empty_presence.is_exiting() {
1319 CommandPaletteTokens::EXIT_Y
1320 } else {
1321 CommandPaletteTokens::ENTER_Y
1322 }) * (1.0 - empty_presence.progress)
1323 })
1324 .opacity(empty_presence.progress * blur.opacity_multiplier)
1325 .h(CommandPaletteTokens::EMPTY_HEIGHT)
1326 .flex()
1327 .flex_col()
1328 .items_center()
1329 .justify_center()
1330 .gap(Spacing::S1)
1331 .text_color(colors.text_muted)
1332 .child(Icon::new(IconName::Search).text_size(px(18.0)))
1333 .child(if !wants_results && query.is_empty() {
1334 "No commands".to_owned()
1335 } else {
1336 format!(
1337 "No results for “{}”",
1338 if wants_results {
1339 snapshot.empty_query.as_ref()
1340 } else {
1341 &query
1342 }
1343 )
1344 })
1345 .child(
1346 div()
1347 .text_size(Typography::TEXT_XS)
1348 .child(if query.is_empty() {
1349 "Add commands to this palette."
1350 } else {
1351 "Try a different word or clear the search."
1352 }),
1353 )
1354 .into_any_element(),
1355 );
1356 }
1357
1358 let target_height = if showing_results {
1359 displayed_height.min(f32::from(
1360 CommandPaletteTokens::MAX_RESULTS - CommandPaletteTokens::RESULTS_INSET * 2.0,
1361 ))
1362 } else {
1363 f32::from(CommandPaletteTokens::EMPTY_HEIGHT)
1364 };
1365 let list_height = arc_spring_with_options(
1366 (self.id.clone(), "results-height"),
1367 target_height,
1368 SpringOptions::new(motion.spring.smooth)
1369 .with_initial_value(target_height)
1370 .with_travel(!reduced),
1371 window,
1372 cx,
1373 )
1374 .value;
1375 let presence = ArcPresence::new((self.id.clone(), "presence"), true)
1376 .animate_initial(self.animate_entry)
1377 .enter(motion.duration.fast, motion.ease.enter)
1378 .sample(window, cx);
1379 let panel_opacity = presence.progress;
1380 let panel_y = if reduced {
1381 px(0.0)
1382 } else {
1383 CommandPaletteTokens::ENTER_Y * (1.0 - presence.progress)
1384 };
1385 let clear_presence =
1386 ArcPresence::new((self.id.clone(), "clear-presence"), !raw_query.is_empty())
1387 .animate_initial(false)
1388 .enter(motion.duration.instant, motion.ease.enter)
1389 .exit(motion.duration.instant, motion.ease.standard)
1390 .sample(window, cx);
1391 let clear_scale = arc_spring_with_options(
1392 (self.id.clone(), "clear-scale"),
1393 if raw_query.is_empty() {
1394 CommandPaletteTokens::CLEAR_SCALE
1395 } else {
1396 1.0
1397 },
1398 SpringOptions::new(motion.spring.snappy).with_travel(!reduced),
1399 window,
1400 cx,
1401 )
1402 .value;
1403 let clear_blur = BlurFallback::evaluate(
1404 motion.blur.subtle * (1.0 - clear_presence.progress),
1405 reduced,
1406 );
1407 let width_ref = snapshot.width.clone();
1408 let width_probe = canvas(
1409 move |bounds, window, _| {
1410 let measured = f32::from(bounds.size.width);
1411 let was_narrow =
1412 *width_ref.borrow() < f32::from(CommandPaletteTokens::NARROW_WIDTH);
1413 let is_narrow = measured < f32::from(CommandPaletteTokens::NARROW_WIDTH);
1414 *width_ref.borrow_mut() = measured;
1415 if was_narrow != is_narrow {
1417 window.on_next_frame(|window, _| window.refresh());
1418 }
1419 },
1420 |_, _, _, _| {},
1421 )
1422 .absolute()
1423 .inset_0();
1424
1425 let content_origin = snapshot.content_origin.clone();
1426 let clear_state = internal.clone();
1427 let clear_input = snapshot.query_input.clone();
1428 let shell_id = ElementId::NamedChild(self.id.clone().into(), "shell".into());
1429 let list_id = ElementId::NamedChild(self.id.clone().into(), "results".into());
1430 let clear_button = if !clear_presence.should_render() {
1431 None
1432 } else {
1433 Some(
1434 div()
1435 .id(ElementId::NamedChild(
1436 self.id.clone().into(),
1437 "clear".into(),
1438 ))
1439 .test_support()
1440 .size(Spacing::S6)
1441 .flex_shrink_0()
1442 .role(Role::Button)
1443 .opacity(clear_presence.progress * clear_blur.opacity_multiplier)
1444 .rounded(Radii::CONTROL)
1445 .flex()
1446 .items_center()
1447 .justify_center()
1448 .cursor_pointer()
1449 .text_color(colors.text_muted)
1450 .hover(|d| d.bg(colors.surface_muted))
1451 .aria_label("Clear search")
1452 .on_click(move |_, window, cx| {
1453 clear_input.update(cx, |state, cx| {
1454 state.set_value("", window, cx);
1455 state.focus(window, cx);
1456 });
1457 clear_state.update(cx, |state, _| {
1458 state.last_query = "".into();
1459 state.active_index = 0;
1460 state.pointer_navigation = false;
1461 state.pointer_item = None;
1462 });
1463 window.refresh();
1464 })
1465 .child(Icon::new(IconName::X).text_size(Typography::TEXT_SM * clear_scale)),
1466 )
1467 };
1468
1469 let search_focused = snapshot.focus_handle.is_focused(window);
1473 div()
1474 .w_full()
1475 .max_w(CommandPaletteTokens::MAX_WIDTH)
1476 .relative()
1477 .child(
1478 div()
1479 .id(self.id.clone())
1480 .test_support()
1481 .relative()
1482 .w_full()
1483 .top(panel_y)
1484 .rounded(CommandPaletteTokens::PANEL_RADIUS)
1485 .border_1()
1486 .border_color(colors.border)
1487 .bg(colors.surface)
1488 .shadow(Shadows::floating(cx.arc_theme().mode))
1489 .overflow_hidden()
1490 .text_size(Typography::TEXT_SM)
1491 .text_color(colors.foreground)
1492 .flex()
1493 .flex_col()
1494 .track_focus(&snapshot.keyboard_scope)
1495 .capture_action(home_listener)
1496 .capture_action(end_listener)
1497 .capture_key_down(key_listener)
1498 .child(width_probe)
1499 .opacity(panel_opacity)
1500 .role(Role::Group)
1501 .aria_label(self.label)
1502 .child(
1503 div()
1504 .id(shell_id)
1505 .test_support()
1506 .relative()
1507 .h(ControlHeights::MD)
1508 .w_full()
1509 .border_b_1()
1510 .border_color(colors.border_subtle)
1511 .when(search_focused, |row| {
1512 row.rounded_tl(CommandPaletteTokens::PANEL_RADIUS)
1513 .rounded_tr(CommandPaletteTokens::PANEL_RADIUS)
1514 .bg(colors.surface_muted)
1515 })
1516 .flex()
1517 .flex_row()
1518 .items_center()
1519 .gap(Spacing::S2)
1520 .px(Spacing::S3)
1521 .child(
1522 Icon::new(IconName::Search)
1523 .text_size(CommandPaletteTokens::ICON)
1524 .text_color(colors.text_muted),
1525 )
1526 .child(query_input)
1527 .when_some(clear_button, |d, button| d.child(button))
1528 .when_some(close, |d, handler| {
1529 d.child(
1530 div()
1531 .id(ElementId::NamedChild(
1532 self.id.clone().into(),
1533 "close".into(),
1534 ))
1535 .test_support()
1536 .role(Role::Button)
1537 .aria_label("Close command palette")
1538 .h(Spacing::S6)
1539 .px(Spacing::S1)
1540 .rounded(Radii::CONTROL)
1541 .cursor_pointer()
1542 .flex_shrink_0()
1543 .text_size(Typography::TEXT_XS)
1544 .text_color(colors.text_muted)
1545 .on_click(move |_, window, cx| handler(window, cx))
1546 .child("Esc"),
1547 )
1548 })
1549 .when(!narrow, |d| {
1550 d.child(
1551 div()
1552 .flex_shrink_0()
1553 .text_size(Typography::TEXT_XS)
1554 .text_color(colors.text_muted)
1555 .child(if cfg!(target_os = "macos") {
1556 "⌘ K"
1557 } else {
1558 "Ctrl K"
1559 }),
1560 )
1561 }),
1562 )
1563 .child(
1564 div()
1565 .id(ElementId::NamedChild(
1566 self.id.clone().into(),
1567 "results-frame".into(),
1568 ))
1569 .test_support()
1570 .p(CommandPaletteTokens::RESULTS_INSET)
1571 .child(
1572 div()
1573 .id(list_id)
1574 .test_support()
1575 .relative()
1576 .h(px(list_height))
1577 .flex_shrink_0()
1578 .track_scroll(&snapshot.scroll)
1579 .max_h(
1580 CommandPaletteTokens::MAX_RESULTS
1581 - CommandPaletteTokens::RESULTS_INSET * 2.0,
1582 )
1583 .overflow_y_scroll()
1584 .role(Role::ListBox)
1585 .aria_label("Command results")
1586 .child(
1587 div()
1588 .on_prepaint(move |bounds, _, _| {
1589 content_origin.set(f32::from(bounds.origin.y))
1590 })
1591 .relative()
1592 .h(px(if showing_results {
1593 displayed_height
1594 } else {
1595 f32::from(CommandPaletteTokens::EMPTY_HEIGHT)
1596 }))
1597 .opacity(if showing_results {
1598 content_presence.progress
1599 } else {
1600 1.0
1601 })
1602 .when(showing_results && highlight_opacity > 0.0, |d| {
1603 d.child(
1604 div()
1605 .id(ElementId::NamedChild(
1606 self.id.clone().into(),
1607 "highlight".into(),
1608 ))
1609 .test_support()
1610 .absolute()
1611 .left_0()
1612 .right_0()
1613 .top(px(highlight_y))
1614 .h(px(row_h))
1615 .rounded(Radii::CONTROL)
1616 .bg(colors.surface_muted)
1617 .opacity(highlight_opacity),
1618 )
1619 })
1620 .children(result_rows)
1621 .children(exit_rows)
1622 .children(exit_groups),
1623 ),
1624 ),
1625 )
1626 .child(
1627 div()
1628 .id(ElementId::NamedChild(
1629 self.id.clone().into(),
1630 "status".into(),
1631 ))
1632 .role(Role::Status)
1633 .test_support()
1634 .aria_label(if query.is_empty() {
1635 String::new()
1636 } else if visual_items.is_empty() {
1637 "No results".to_owned()
1638 } else if visual_items.len() == 1 {
1639 "1 result".to_owned()
1640 } else {
1641 format!("{} results", visual_items.len())
1642 })
1643 .absolute()
1644 .size(px(1.0))
1645 .overflow_hidden()
1646 .child(" "),
1647 ),
1648 )
1649 }
1650}
1651
1652#[cfg(test)]
1653mod tests {
1654 use super::*;
1655
1656 fn items() -> Vec<CommandItem> {
1657 vec![
1658 CommandItem::new("a", "Open project")
1659 .group("Workspace")
1660 .keywords(["launch"]),
1661 CommandItem::new("b", "Project settings")
1662 .group("Settings")
1663 .description("Configure the workspace"),
1664 CommandItem::new("c", "Duplicate project").group("Workspace"),
1665 ]
1666 }
1667
1668 #[test]
1669 fn ranks_prefix_boundary_substring_keyword_and_description() {
1670 let ranked = command_palette_rank(&items(), "project");
1671 assert_eq!(
1672 ranked
1673 .iter()
1674 .map(|item| item.id.as_ref())
1675 .collect::<Vec<_>>(),
1676 vec!["b", "a", "c"]
1677 );
1678 assert_eq!(command_palette_rank(&items(), "launch")[0].id.as_ref(), "a");
1679 assert_eq!(
1680 command_palette_rank(&items(), "configure")[0].id.as_ref(),
1681 "b"
1682 );
1683 }
1684
1685 #[test]
1686 fn all_words_must_match_and_ties_keep_input_order() {
1687 let ranked = command_palette_rank(&items(), "project settings");
1688 assert_eq!(ranked.len(), 1);
1689 assert_eq!(ranked[0].id.as_ref(), "b");
1690 let tied = vec![
1691 CommandItem::new("a", "Alpha"),
1692 CommandItem::new("b", "Alpha copy"),
1693 ];
1694 assert_eq!(
1695 command_palette_rank(&tied, "alpha")
1696 .iter()
1697 .map(|item| item.id.as_ref())
1698 .collect::<Vec<_>>(),
1699 vec!["a", "b"]
1700 );
1701 }
1702
1703 #[test]
1704 fn groups_default_to_actions_and_follow_rank_order() {
1705 let ranked = command_palette_rank(&items(), "");
1706 let groups = command_palette_group_by(&ranked);
1707 assert_eq!(groups[0].0.as_ref(), "Workspace");
1708 assert_eq!(groups[1].0.as_ref(), "Settings");
1709 let plain = vec![CommandItem::new("x", "Action")];
1710 assert_eq!(command_palette_group_by(&plain)[0].0.as_ref(), "Actions");
1711 }
1712
1713 #[test]
1714 fn shortcut_parser_splits_modifiers_and_spaces() {
1715 assert_eq!(command_palette_shortcut_keys("⌘ K").len(), 2);
1716 assert_eq!(command_palette_shortcut_keys("Shift+N").len(), 2);
1717 assert_eq!(
1718 command_palette_shortcut_keys("Ctrl++"),
1719 vec![SharedString::from("Ctrl"), SharedString::from("+")]
1720 );
1721 }
1722
1723 #[test]
1724 fn score_weights_match_upstream_and_extra_words_are_boundary_only() {
1725 let candidates = [
1726 CommandItem::new("substring", "Latest"),
1727 CommandItem::new("prefix", "Test command"),
1728 CommandItem::new("word", "Run test"),
1729 CommandItem::new("keyword", "Other").keywords(["test"]),
1730 CommandItem::new("description", "More").description("test the system"),
1731 CommandItem::new("not-keyword", "Unrelated").keywords(["latest"]),
1732 CommandItem::new("not-description", "Nothing").description("latest"),
1733 ];
1734 let ranked = command_palette_ranked(&candidates, "test");
1735 assert_eq!(
1736 ranked
1737 .iter()
1738 .map(|entry| (entry.item.id.as_ref(), entry.score))
1739 .collect::<Vec<_>>(),
1740 vec![
1741 ("prefix", 100),
1742 ("word", 80),
1743 ("substring", 50),
1744 ("keyword", 40),
1745 ("description", 25)
1746 ]
1747 );
1748 assert!(command_palette_rank(&candidates, "test absent").is_empty());
1749 }
1750
1751 #[test]
1752 fn subsequences_are_word_anchored_and_span_limited() {
1753 let candidate = CommandItem::new("share", "Share project");
1754 let ranked = command_palette_ranked(&[candidate], "shpr");
1755 assert_eq!(ranked[0].score, 10);
1756 assert!(subsequence("xxshare project", "shpr").is_none());
1757 assert!(subsequence("s...........p", "sp").is_none());
1758 assert_eq!(command_palette_rank(&items(), "dup pr")[0].id.as_ref(), "c");
1759 }
1760
1761 #[test]
1762 fn unicode_highlights_keep_original_utf8_boundaries_and_merge_overlaps() {
1763 let candidates = [
1764 CommandItem::new("cn", "打开项目"),
1765 CommandItem::new("unicode", "İstanbul"),
1766 ];
1767 let ranked = command_palette_ranked(&candidates, "打开");
1768 assert_eq!(highlight_ranges("打开项目", &ranked[0].ranges), vec![0..6]);
1769 let ranked = command_palette_ranked(&candidates, "i");
1770 assert_eq!(highlight_ranges("İstanbul", &ranked[0].ranges), vec![0..2]);
1771 assert_eq!(
1772 highlight_ranges(
1773 "Open",
1774 &[
1775 MatchRange { start: 0, end: 3 },
1776 MatchRange { start: 0, end: 2 }
1777 ]
1778 ),
1779 vec![0..3]
1780 );
1781 assert_eq!(command_palette_rank(&items(), " \t ").len(), 3);
1782 }
1783
1784 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1785 use gpui_kit::{Render, TestAppContext, test::TestWindowExt as _};
1786
1787 struct PaletteHost {
1788 selected: Rc<RefCell<Vec<String>>>,
1789 closed: Rc<RefCell<usize>>,
1790 commands: Vec<CommandItem>,
1791 show: bool,
1792 width: f32,
1793 auto_focus: bool,
1794 }
1795
1796 impl Render for PaletteHost {
1797 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1798 let selected = self.selected.clone();
1799 let closed = self.closed.clone();
1800 div().w(px(self.width)).p(Spacing::S4).when(self.show, |d| {
1801 d.child(
1802 CommandPalette::new("palette-test")
1803 .items(self.commands.clone())
1804 .auto_focus(self.auto_focus)
1805 .on_select(move |item, _, _| {
1806 selected.borrow_mut().push(item.id.to_string())
1807 })
1808 .on_close(move |_, _| *closed.borrow_mut() += 1),
1809 )
1810 })
1811 }
1812 }
1813
1814 fn element(name: &str) -> ElementId {
1815 ElementId::NamedChild(
1816 ElementId::Name("palette-test".into()).into(),
1817 name.to_owned().into(),
1818 )
1819 }
1820
1821 fn setup(cx: &mut TestAppContext, mode: ThemeMode) {
1822 cx.update(|cx| {
1823 gpui_kit::init(cx);
1824 install_arc_theme(mode, Accent::Violet, cx);
1825 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1826 });
1827 }
1828
1829 #[gpui_kit::test]
1830 fn pointer_leave_clears_only_pointer_target_and_keyboard_restores_selection(
1831 cx: &mut TestAppContext,
1832 ) {
1833 use gpui_kit::test::TestEventExt as _;
1834 setup(cx, ThemeMode::Dark);
1835 let events = Rc::new(RefCell::new(Vec::new()));
1836 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
1837 selected: events.clone(),
1838 closed: Rc::new(RefCell::new(0)),
1839 commands: items(),
1840 show: true,
1841 width: 560.0,
1842 auto_focus: false,
1843 });
1844 cx.update(|w, cx| {
1845 w.render_frame(cx);
1846 w.press("ctrl-k", cx);
1847 w.press("down", cx);
1848 assert_eq!(w.find(element("item-c")).selected(), Some(true));
1849 let last = w.find(element("item-b")).bounds().center();
1850 w.pointer_move(last, None, cx);
1851 w.render_frame(cx);
1852 assert_eq!(w.find(element("item-b")).selected(), Some(true));
1853 let panel = w.find("palette-test").bounds();
1854 w.pointer_move(point(panel.center().x, panel.bottom() + px(10.0)), None, cx);
1855 w.render_frame(cx);
1856 for id in ["a", "b", "c"] {
1857 assert_eq!(
1858 w.find(element(&format!("item-{id}"))).selected(),
1859 Some(false)
1860 );
1861 }
1862 assert!(w.try_find(element("highlight")).is_none());
1863 w.press("enter", cx);
1864 assert!(events.borrow().is_empty(), "不得执行已经不可见的鼠标目标");
1865 w.press("down", cx);
1866 assert_eq!(w.find(element("item-b")).selected(), Some(true));
1867 w.pointer_move(point(px(1.0), px(1.0)), None, cx);
1869 w.render_frame(cx);
1870 assert_eq!(w.find(element("item-b")).selected(), Some(true));
1871 w.press("enter", cx);
1872 assert_eq!(events.borrow().as_slice(), &["b"]);
1873 });
1874 }
1875
1876 #[gpui_kit::test]
1877 fn pointer_highlight_fades_in_place_and_reentry_reverses(cx: &mut TestAppContext) {
1878 use gpui_kit::test::TestEventExt as _;
1879 setup(cx, ThemeMode::Dark);
1880 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
1881 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
1882 selected: Rc::new(RefCell::new(Vec::new())),
1883 closed: Rc::new(RefCell::new(0)),
1884 commands: items(),
1885 show: true,
1886 width: 560.0,
1887 auto_focus: false,
1888 });
1889 cx.update(|w, cx| w.render_frame(cx));
1890 cx.executor()
1891 .advance_clock(std::time::Duration::from_millis(500));
1892 cx.update(|w, cx| {
1893 w.render_frame(cx);
1894 let p = w.find(element("item-b")).bounds().center();
1895 w.pointer_move(p, None, cx);
1896 w.render_frame(cx);
1897 });
1898 cx.executor()
1899 .advance_clock(std::time::Duration::from_millis(500));
1900 let before = cx.update(|w, cx| {
1901 w.render_frame(cx);
1902 let before = w.find(element("highlight")).bounds();
1903 let p = w.find("palette-test").bounds();
1904 w.pointer_move(point(p.center().x, p.bottom() + px(10.0)), None, cx);
1905 w.render_frame(cx);
1906 assert_eq!(w.find(element("highlight")).bounds(), before);
1907 before
1908 });
1909 cx.executor()
1910 .advance_clock(std::time::Duration::from_millis(40));
1911 cx.update(|w, cx| {
1912 w.render_frame(cx);
1913 assert_eq!(
1914 w.find(element("highlight")).bounds(),
1915 before,
1916 "淡出中不得回滑"
1917 );
1918 let p = w.find(element("item-b")).bounds().center();
1919 w.pointer_move(p, None, cx);
1920 w.render_frame(cx);
1921 assert_eq!(w.find(element("item-b")).selected(), Some(true));
1922 });
1923 cx.executor()
1924 .advance_clock(std::time::Duration::from_millis(120));
1925 cx.update(|w, cx| {
1926 w.render_frame(cx);
1927 assert!(w.try_find(element("highlight")).is_some());
1928 let p = w.find("palette-test").bounds();
1929 w.pointer_move(point(p.center().x, p.bottom() + px(10.0)), None, cx);
1930 w.render_frame(cx);
1931 });
1932 cx.executor()
1933 .advance_clock(std::time::Duration::from_millis(120));
1934 cx.update(|w, cx| {
1935 w.render_frame(cx);
1936 assert!(w.try_find(element("highlight")).is_none());
1937 });
1938 }
1939
1940 #[gpui_kit::test]
1941 fn results_clip_rectangle_stays_inside_panel_corners_even_when_scrolled(
1942 cx: &mut TestAppContext,
1943 ) {
1944 use gpui_kit::{
1945 InputEvent as _, ScrollDelta, ScrollEvent, TouchPhase, test::TestEventExt as _,
1946 };
1947 setup(cx, ThemeMode::Light);
1948 let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
1949 selected: Rc::new(RefCell::new(Vec::new())),
1950 closed: Rc::new(RefCell::new(0)),
1951 commands: (0..30)
1952 .map(|i| CommandItem::new(format!("r{i}"), format!("Row {i}")))
1953 .collect(),
1954 show: true,
1955 width: 560.0,
1956 auto_focus: false,
1957 });
1958 cx.update(|w, cx| {
1959 for mode in [ThemeMode::Light, ThemeMode::Dark] {
1960 install_arc_theme(mode, Accent::Violet, cx);
1961 for width in [560.0, 360.0] {
1962 view.update(cx, |host, cx| {
1963 host.width = width;
1964 cx.notify();
1965 });
1966 w.render_frame(cx);
1967 let panel = w.find("palette-test").bounds();
1968 let list = w.find(element("results")).bounds();
1969 let radius = f32::from(CommandPaletteTokens::PANEL_RADIUS);
1970 let dx = f32::from(list.left() - panel.left());
1971 let dy = f32::from(panel.bottom() - list.bottom());
1972 assert!(
1973 (radius - dx).powi(2) + (radius - dy).powi(2) <= radius.powi(2),
1974 "矩形裁剪角须位于面板圆角内"
1975 );
1976 assert!(list.right() < panel.right());
1977 assert!(list.size.height <= CommandPaletteTokens::MAX_RESULTS);
1978 w.press("ctrl-k", cx);
1979 w.press("end", cx);
1980 w.simulate_next_frame(cx);
1981 w.render_frame(cx);
1982 let row = w.find(element("item-r29")).bounds();
1983 assert!(row.bottom() <= list.bottom());
1984 let hi = w.find(element("highlight")).bounds();
1985 assert!(hi.left() >= list.left() && hi.right() <= list.right());
1986 w.pointer_move(list.center(), None, cx);
1987 for delta in [60.0, 60.0, -30.0, -2000.0] {
1988 w.dispatch_event(
1989 ScrollEvent {
1990 position: list.center(),
1991 delta: ScrollDelta::Pixels(point(px(0.0), px(delta))),
1992 modifiers: Default::default(),
1993 touch_phase: TouchPhase::Moved,
1994 source: Default::default(),
1995 }
1996 .to_platform_input(),
1997 cx,
1998 );
1999 w.render_frame(cx);
2000 assert_eq!(w.find(element("results")).bounds(), list);
2001 }
2002 }
2003 }
2004 });
2005 }
2006
2007 #[gpui_kit::test]
2008 fn keyboard_scope_does_not_reuse_the_search_input_focus(cx: &mut TestAppContext) {
2009 setup(cx, ThemeMode::Light);
2010 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2011 selected: Rc::new(RefCell::new(Vec::new())),
2012 closed: Rc::new(RefCell::new(0)),
2013 commands: items(),
2014 show: true,
2015 width: 560.0,
2016 auto_focus: false,
2017 });
2018 cx.update(|w, cx| {
2019 w.render_frame(cx);
2020 w.press("ctrl-k", cx);
2021 w.press("down", cx);
2023 assert_eq!(w.find(element("item-c")).selected(), Some(true));
2024 w.input("settings", cx);
2025 w.press("enter", cx);
2026 let state = cx.new(|cx| CommandPaletteInternal::new("Search".into(), false, w, cx));
2028 let state = state.read(cx);
2029 assert_ne!(
2030 state.keyboard_scope, state.focus_handle,
2031 "父级事件作用域不能重复声明输入焦点"
2032 );
2033 assert_eq!(
2034 state.query_input.read(cx).focus_handle(cx),
2035 state.focus_handle
2036 );
2037 });
2038 }
2039
2040 #[gpui_kit::test]
2041 fn filtered_rows_pop_out_without_stale_selection_and_expire(cx: &mut TestAppContext) {
2042 setup(cx, ThemeMode::Light);
2043 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2044 let selected = Rc::new(RefCell::new(Vec::new()));
2045 let events = selected.clone();
2046 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2047 selected,
2048 closed: Rc::new(RefCell::new(0)),
2049 commands: items(),
2050 show: true,
2051 width: 560.0,
2052 auto_focus: false,
2053 });
2054 cx.update(|window, cx| window.render_frame(cx));
2055 cx.executor()
2056 .advance_clock(std::time::Duration::from_millis(500));
2057 cx.update(|window, cx| {
2058 window.render_frame(cx);
2059 window.press("ctrl-k", cx);
2060 window.input("dup", cx);
2061 assert!(window.try_find(element("item-a")).is_none());
2062 assert!(window.try_find(element("exit-a")).is_some());
2063 assert!(window.try_find(element("item-c")).is_some());
2064 assert_eq!(window.find(element("item-c")).selected(), Some(true));
2065 });
2066 cx.executor()
2067 .advance_clock(std::time::Duration::from_millis(180));
2068 cx.update(|window, cx| {
2069 window.render_frame(cx);
2070 assert!(window.try_find(element("exit-a")).is_none());
2071 window.press("enter", cx);
2072 });
2073 assert_eq!(events.borrow().as_slice(), &["c"]);
2074 }
2075
2076 #[gpui_kit::test]
2077 fn whole_group_exit_keeps_heading_copy_and_shortcuts_then_reverses(cx: &mut TestAppContext) {
2078 setup(cx, ThemeMode::Dark);
2079 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2080 let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
2081 selected: Rc::new(RefCell::new(Vec::new())),
2082 closed: Rc::new(RefCell::new(0)),
2083 commands: vec![
2084 CommandItem::new("a", "Alpha").group("First"),
2085 CommandItem::new("b", "Beta")
2086 .group("Second")
2087 .description("Details")
2088 .shortcut("Ctrl+B"),
2089 ],
2090 show: true,
2091 width: 560.0,
2092 auto_focus: false,
2093 });
2094 cx.update(|w, cx| w.render_frame(cx));
2095 cx.executor()
2096 .advance_clock(std::time::Duration::from_millis(700));
2097 cx.update(|w, cx| w.render_frame(cx));
2098 cx.executor()
2100 .advance_clock(std::time::Duration::from_millis(700));
2101 let before = cx.update(|w, cx| {
2102 w.render_frame(cx);
2103 let before = w.find(element("group-Second")).bounds();
2104 w.press("ctrl-k", cx);
2105 w.input("alpha", cx);
2106 let exit = w.find(element("exit-group-Second"));
2107 assert_eq!(exit.bounds().origin.y, before.origin.y);
2108 assert!(w.try_find(element("exit-b")).is_none());
2109 let shortcut = ElementId::NamedChild(element("exit").into(), "shortcut-b".into());
2110 assert!(w.try_find(shortcut).is_some());
2111 assert_eq!(exit.role(), None);
2112 before
2113 });
2114 cx.executor()
2115 .advance_clock(std::time::Duration::from_millis(40));
2116 cx.update(|w, cx| {
2117 w.render_frame(cx);
2118 w.press("escape", cx);
2119 assert!(w.try_find(element("exit-group-Second")).is_none());
2120 assert!(w.try_find(element("group-Second")).is_some());
2121 view.update(cx, |_, cx| cx.notify());
2122 });
2123 cx.executor()
2124 .advance_clock(std::time::Duration::from_millis(700));
2125 cx.update(|w, cx| {
2126 w.render_frame(cx);
2127 assert_eq!(
2128 w.find(element("group-Second")).bounds().origin.y,
2129 before.origin.y
2130 );
2131 w.input("alpha", cx);
2132 });
2133 cx.executor()
2134 .advance_clock(std::time::Duration::from_millis(180));
2135 cx.update(|w, cx| {
2136 w.render_frame(cx);
2137 assert!(w.try_find(element("exit-group-Second")).is_none());
2138 });
2139 }
2140
2141 #[gpui_kit::test]
2142 fn row_exit_retains_shortcut_and_mid_glide_position(cx: &mut TestAppContext) {
2143 setup(cx, ThemeMode::Light);
2144 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2145 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2146 selected: Rc::new(RefCell::new(Vec::new())),
2147 closed: Rc::new(RefCell::new(0)),
2148 commands: vec![
2149 CommandItem::new("a", "Alpha").group("Actions"),
2150 CommandItem::new("b", "Beta")
2151 .group("Actions")
2152 .description("Details")
2153 .shortcut("Ctrl+B"),
2154 CommandItem::new("c", "Gamma").group("Actions"),
2155 ],
2156 show: true,
2157 width: 560.0,
2158 auto_focus: false,
2159 });
2160 cx.update(|w, cx| w.render_frame(cx));
2161 cx.executor()
2162 .advance_clock(std::time::Duration::from_millis(700));
2163 cx.update(|w, cx| {
2164 w.render_frame(cx);
2165 w.press("ctrl-k", cx);
2166 w.input("beta", cx);
2167 });
2168 cx.executor()
2169 .advance_clock(std::time::Duration::from_millis(40));
2170 cx.update(|w, cx| {
2171 w.render_frame(cx);
2172 let before = w.find(element("item-b")).bounds().origin.y;
2173 w.press("escape", cx);
2174 w.input("gamma", cx);
2175 assert!((f32::from(w.find(element("exit-b")).bounds().origin.y - before)).abs() < 0.1);
2176 let shortcut = ElementId::NamedChild(element("exit").into(), "shortcut-b".into());
2177 assert!(w.try_find(shortcut).is_some());
2178 });
2179 }
2180
2181 #[gpui_kit::test]
2182 fn long_reorder_snaps_exits_and_does_not_resume_glide(cx: &mut TestAppContext) {
2183 setup(cx, ThemeMode::Light);
2184 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2185 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2186 selected: Rc::new(RefCell::new(Vec::new())),
2187 closed: Rc::new(RefCell::new(0)),
2188 commands: (0..12)
2189 .map(|i| CommandItem::new(format!("n{i}"), format!("Command {i}")))
2190 .collect(),
2191 show: true,
2192 width: 560.0,
2193 auto_focus: false,
2194 });
2195 cx.update(|w, cx| w.render_frame(cx));
2196 cx.executor()
2197 .advance_clock(std::time::Duration::from_millis(700));
2198 cx.update(|w, cx| {
2199 w.render_frame(cx);
2200 w.press("ctrl-k", cx);
2201 w.input("command 11", cx);
2202 assert!(w.try_find(element("exit-n0")).is_none());
2203 let before = w.find(element("item-n11")).bounds().origin.y;
2204 w.render_frame(cx);
2205 assert_eq!(w.find(element("item-n11")).bounds().origin.y, before);
2206 });
2207 }
2208
2209 #[gpui_kit::test]
2210 fn entry_keeps_final_layout_size_without_trailing_growth(cx: &mut TestAppContext) {
2211 setup(cx, ThemeMode::Light);
2212 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2213 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2214 selected: Rc::new(RefCell::new(Vec::new())),
2215 closed: Rc::new(RefCell::new(0)),
2216 commands: items(),
2217 show: true,
2218 width: 560.0,
2219 auto_focus: false,
2220 });
2221 let first = cx.update(|w, cx| {
2222 w.render_frame(cx);
2223 (
2224 w.find("palette-test").bounds(),
2225 w.find(element("item-a")).bounds(),
2226 )
2227 });
2228 cx.executor()
2229 .advance_clock(std::time::Duration::from_millis(700));
2230 cx.update(|w, cx| {
2231 w.render_frame(cx);
2232 let settled = w.find("palette-test").bounds();
2233 assert_eq!(first.0.size, settled.size, "入场不得改变面板布局尺寸");
2234 assert!((f32::from(first.0.center().x - settled.center().x)).abs() < 0.1);
2235 assert!(
2236 (f32::from(first.0.origin.y - settled.origin.y)
2237 - f32::from(CommandPaletteTokens::ENTER_Y))
2238 .abs()
2239 < 0.1
2240 );
2241 assert_eq!(first.1.size, w.find(element("item-a")).bounds().size);
2242 });
2243 }
2244
2245 #[gpui_kit::test]
2246 fn reduced_motion_skips_group_exits_and_entry_motion(cx: &mut TestAppContext) {
2247 setup(cx, ThemeMode::Dark);
2248 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2249 selected: Rc::new(RefCell::new(Vec::new())),
2250 closed: Rc::new(RefCell::new(0)),
2251 commands: items(),
2252 show: true,
2253 width: 560.0,
2254 auto_focus: false,
2255 });
2256 cx.update(|w, cx| {
2257 w.render_frame(cx);
2258 assert_eq!(
2259 w.find(element("item-a")).bounds().size.height,
2260 CommandPaletteTokens::ROW
2261 );
2262 let width = w.find("palette-test").bounds().size.width;
2263 w.press("ctrl-k", cx);
2264 w.input("dup", cx);
2265 assert!(w.try_find(element("exit-group-Settings")).is_none());
2266 assert!(w.try_find(element("exit-a")).is_none());
2267 assert_eq!(w.find("palette-test").bounds().size.width, width);
2268 });
2269 }
2270
2271 #[gpui_kit::test]
2272 fn result_empty_wait_sequence_preserves_exit_and_reverses(cx: &mut TestAppContext) {
2273 setup(cx, ThemeMode::Dark);
2274 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
2275 let selected = Rc::new(RefCell::new(Vec::new()));
2276 let events = selected.clone();
2277 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2278 selected,
2279 closed: Rc::new(RefCell::new(0)),
2280 commands: items(),
2281 show: true,
2282 width: 560.0,
2283 auto_focus: false,
2284 });
2285 cx.update(|window, cx| window.render_frame(cx));
2286 cx.executor()
2287 .advance_clock(std::time::Duration::from_millis(500));
2288 cx.update(|window, cx| {
2289 window.render_frame(cx);
2290 window.press("ctrl-k", cx);
2291 window.input("zzzz", cx);
2292 assert!(window.try_find(element("item-a")).is_some());
2294 assert!(window.try_find(element("empty")).is_none());
2295 window.click(element("item-a"), cx);
2296 window.press("enter", cx);
2297 });
2298 assert!(events.borrow().is_empty());
2299 cx.executor()
2300 .advance_clock(std::time::Duration::from_millis(180));
2301 cx.update(|window, cx| {
2302 window.render_frame(cx);
2303 assert!(window.try_find(element("empty")).is_some());
2304 assert!(window.try_find(element("item-a")).is_none());
2305 });
2306 cx.executor()
2307 .advance_clock(std::time::Duration::from_millis(300));
2308 cx.update(|window, cx| {
2309 window.render_frame(cx);
2310 window.press("escape", cx);
2311 assert!(window.try_find(element("empty")).is_some());
2313 assert!(window.try_find(element("item-a")).is_none());
2314 });
2315 cx.executor()
2316 .advance_clock(std::time::Duration::from_millis(60));
2317 cx.update(|window, cx| {
2318 window.render_frame(cx);
2319 window.input("zzzz", cx);
2320 assert!(window.try_find(element("empty")).is_some());
2321 });
2322 cx.executor()
2323 .advance_clock(std::time::Duration::from_millis(300));
2324 cx.update(|window, cx| {
2325 window.render_frame(cx);
2326 assert!(window.try_find(element("empty")).is_some());
2327 window.press("escape", cx);
2328 });
2329 cx.executor()
2330 .advance_clock(std::time::Duration::from_millis(180));
2331 cx.update(|window, cx| {
2332 window.render_frame(cx);
2333 assert!(window.try_find(element("item-a")).is_some());
2334 assert!(window.try_find(element("empty")).is_none());
2335 });
2336 }
2337
2338 #[gpui_kit::test]
2339 fn keyboard_walks_visual_groups_without_wrapping_and_selects(cx: &mut TestAppContext) {
2340 setup(cx, ThemeMode::Light);
2341 let selected = Rc::new(RefCell::new(Vec::new()));
2342 let events = selected.clone();
2343 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2344 selected,
2345 closed: Rc::new(RefCell::new(0)),
2346 commands: items(),
2347 show: true,
2348 width: 560.0,
2349 auto_focus: false,
2350 });
2351 cx.update(|window, cx| {
2352 window.render_frame(cx);
2353 assert_eq!(window.find(element("results")).role(), Some(Role::ListBox));
2354 assert_eq!(window.find(element("item-a")).selected(), Some(true));
2355 window.press("ctrl-k", cx);
2356 window.press("up", cx);
2357 assert_eq!(window.find(element("item-a")).selected(), Some(true));
2358 window.press("down", cx);
2360 assert_eq!(window.find(element("item-c")).selected(), Some(true));
2361 window.press("end", cx);
2362 window.press("down", cx);
2363 assert_eq!(window.find(element("item-b")).selected(), Some(true));
2364 window.press("home", cx);
2365 window.press("enter", cx);
2366 });
2367 assert_eq!(events.borrow().as_slice(), &["a"]);
2368 }
2369
2370 #[gpui_kit::test]
2371 fn search_clear_escape_pointer_select_and_close_are_reachable(cx: &mut TestAppContext) {
2372 setup(cx, ThemeMode::Dark);
2373 let selected = Rc::new(RefCell::new(Vec::new()));
2374 let closed = Rc::new(RefCell::new(0));
2375 let selection_events = selected.clone();
2376 let close_events = closed.clone();
2377 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2378 selected,
2379 closed,
2380 commands: items(),
2381 show: true,
2382 width: 560.0,
2383 auto_focus: false,
2384 });
2385 cx.update(|window, cx| {
2386 window.render_frame(cx);
2387 window.press("ctrl-k", cx);
2388 window.input("dup pr", cx);
2389 window.render_frame(cx);
2390 assert!(window.try_find(element("item-a")).is_none());
2391 assert_eq!(window.find(element("item-c")).selected(), Some(true));
2392 window.click(element("item-c"), cx);
2393 assert_eq!(selection_events.borrow().as_slice(), &["c"]);
2394 assert!(window.try_find(element("item-a")).is_some());
2395 window.input("zzzzzz", cx);
2397 window.render_frame(cx);
2398 assert!(window.try_find(element("empty")).is_some());
2399 window.press("enter", cx);
2400 assert_eq!(selection_events.borrow().len(), 1);
2401 window.press("escape", cx);
2402 assert_eq!(*close_events.borrow(), 0);
2403 assert!(window.try_find(element("item-a")).is_some());
2404 window.input("project", cx);
2405 window.render_frame(cx);
2406 window.click(element("clear"), cx);
2407 assert!(window.try_find(element("item-a")).is_some());
2408 window.press("escape", cx);
2409 assert_eq!(*close_events.borrow(), 1);
2410 window.click(element("close"), cx);
2411 assert_eq!(*close_events.borrow(), 2);
2412 });
2413 }
2414
2415 #[gpui_kit::test]
2416 fn whitespace_escape_clears_before_closing(cx: &mut TestAppContext) {
2417 setup(cx, ThemeMode::Light);
2418 let closed = Rc::new(RefCell::new(0));
2419 let events = closed.clone();
2420 let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
2421 selected: Rc::new(RefCell::new(Vec::new())),
2422 closed,
2423 commands: items(),
2424 show: true,
2425 width: 560.0,
2426 auto_focus: false,
2427 });
2428 cx.update(|window, cx| {
2429 window.render_frame(cx);
2430 window.press("ctrl-k", cx);
2431 window.input(" ", cx);
2432 window.press("escape", cx);
2433 assert_eq!(*events.borrow(), 0);
2434 assert!(window.try_find(element("clear")).is_none());
2435 window.press("escape", cx);
2436 assert_eq!(*events.borrow(), 1);
2437 });
2438 }
2439
2440 #[gpui_kit::test]
2441 fn shortcuts_follow_width_breakpoints_and_end_scrolls_into_view(cx: &mut TestAppContext) {
2442 setup(cx, ThemeMode::Dark);
2443 let commands = (0..30)
2444 .map(|index| {
2445 CommandItem::new(format!("row-{index}"), format!("Command {index}"))
2446 .shortcut("Ctrl+K")
2447 })
2448 .collect();
2449 let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
2450 selected: Rc::new(RefCell::new(Vec::new())),
2451 closed: Rc::new(RefCell::new(0)),
2452 commands,
2453 show: true,
2454 width: 560.0,
2455 auto_focus: false,
2456 });
2457 cx.update(|window, cx| {
2458 window.render_frame(cx);
2459 assert!(window.try_find(element("shortcut-row-0")).is_some());
2460 view.update(cx, |host, cx| {
2461 host.width = 360.0;
2462 cx.notify();
2463 });
2464 window.render_frame(cx);
2465 window.render_frame(cx);
2466 assert!(window.try_find(element("shortcut-row-0")).is_none());
2467 view.update(cx, |host, cx| {
2468 host.width = 560.0;
2469 cx.notify();
2470 });
2471 window.render_frame(cx);
2472 window.render_frame(cx);
2473 assert!(window.try_find(element("shortcut-row-0")).is_some());
2474 window.press("ctrl-k", cx);
2475 window.press("end", cx);
2476 window.simulate_next_frame(cx);
2477 window.render_frame(cx);
2478 let row = window.find(element("item-row-29"));
2479 let frame = window.find(element("results")).bounds();
2480 assert_eq!(row.selected(), Some(true));
2481 assert!(row.bounds().origin.y >= frame.origin.y);
2482 assert!(row.bounds().bottom() <= frame.bottom());
2483 window.press("home", cx);
2484 window.simulate_next_frame(cx);
2485 window.render_frame(cx);
2486 assert!(window.find(element("item-row-0")).bounds().origin.y >= frame.origin.y);
2487 });
2488 }
2489
2490 #[gpui_kit::test]
2491 fn autofocus_does_not_steal_focus_on_rerender_and_shortcut_unsubscribes(
2492 cx: &mut TestAppContext,
2493 ) {
2494 setup(cx, ThemeMode::Light);
2495 let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
2496 selected: Rc::new(RefCell::new(Vec::new())),
2497 closed: Rc::new(RefCell::new(0)),
2498 commands: items(),
2499 show: true,
2500 width: 560.0,
2501 auto_focus: true,
2502 });
2503 cx.update(|window, cx| {
2504 window.render_frame(cx);
2505 window.simulate_next_frame(cx);
2507 window.render_frame(cx);
2508 assert!(window.focused(cx).is_some());
2509 window.blur(cx);
2510 view.update(cx, |_, cx| cx.notify());
2511 window.render_frame(cx);
2512 window.render_frame(cx);
2513 assert!(window.focused(cx).is_none());
2514 window.press("ctrl-k", cx);
2515 assert!(window.focused(cx).is_some());
2516 window.blur(cx);
2517 view.update(cx, |host, cx| {
2518 host.show = false;
2519 cx.notify();
2520 });
2521 window.render_frame(cx);
2522 window.render_frame(cx);
2523 });
2524 cx.run_until_parked();
2526 cx.update(|window, cx| {
2527 window.press("ctrl-k", cx);
2528 assert!(window.focused(cx).is_none());
2529 });
2530 }
2531
2532 #[gpui_kit::test]
2533 fn empty_palette_and_dynamic_items_do_not_select_stale_commands(cx: &mut TestAppContext) {
2534 setup(cx, ThemeMode::Light);
2535 let events = Rc::new(RefCell::new(Vec::new()));
2536 let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
2537 selected: events.clone(),
2538 closed: Rc::new(RefCell::new(0)),
2539 commands: Vec::new(),
2540 show: true,
2541 width: 560.0,
2542 auto_focus: false,
2543 });
2544 cx.update(|window, cx| {
2545 window.render_frame(cx);
2546 window.press("ctrl-k", cx);
2547 for key in ["down", "end", "up", "home", "enter"] {
2548 window.press(key, cx);
2549 }
2550 assert!(events.borrow().is_empty());
2551 assert!(window.try_find(element("empty")).is_some());
2552 view.update(cx, |host, cx| {
2553 host.commands = items();
2554 cx.notify();
2555 });
2556 window.render_frame(cx);
2557 window.press("enter", cx);
2558 assert_eq!(events.borrow().as_slice(), &["a"]);
2559 view.update(cx, |host, cx| {
2560 host.show = false;
2561 cx.notify();
2562 });
2563 window.render_frame(cx);
2564 assert!(window.try_find(element("results")).is_none());
2565 });
2566 }
2567}