Skip to main content

arc_ui/inputs/
command_palette.rs

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