Skip to main content

arc_ui/inputs/
expanding_search.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/expanding-search/expanding-search.tsx`
3//! & `.module.css`
4//!
5//! P4 Component #21: `expanding-search`
6//!
7//! - A search that waits as an icon button until it is needed:
8//!   - The collapsed `44px` circle morphs into a `360px` field on `spring.morph` (a hint of
9//!     overshoot on open, a settle without one on close, so the circle never dips below its
10//!     own size); the corner radius rides the same spring (circle while collapsed, control
11//!     radius once open).
12//!   - Results rank title-prefix > word-boundary > substring > keyword/meta matches, grouped
13//!     in first-appearance order, capped at `max_results`; with an empty query the suggestions
14//!     list shows; no matches reveals the empty state.
15//!   - The panel unfolds beneath the field on `spring.smooth` height; Escape, choosing a
16//!     result, or folding the query back to empty collapses into the icon.
17//!   - Keyboard: ArrowDown/ArrowUp wrap the highlight, Enter chooses, Escape closes.
18//!
19//! Known deviations from upstream:
20//! - The query edits through the shared `Input` (real caret) instead of a native `<input>`;
21//!   there is no `aria-live` announcement region and the `anchor`/`boundary` layout overrides
22//!   are omitted (the field always anchors at the start edge of its container).
23
24use std::{cell::RefCell, rc::Rc};
25
26use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
27use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
28use gpui_kit::{
29    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
30    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
31    TestSupportExt as _, Window,
32    assets::IconName,
33    base::StyledExt as _,
34    canvas,
35    component::{
36        Icon,
37        input::{Input as KitInput, InputState},
38    },
39    deferred, div,
40    prelude::*,
41    px,
42};
43
44use super::field_message::render_field_message;
45
46/// Collapsed shell size (`36px` — matches `ControlHeights::MD`).
47pub const EXPANDING_SEARCH_COLLAPSED_PX: f32 = 36.0;
48/// Default expanded width (`320px`).
49pub const EXPANDING_SEARCH_EXPANDED_PX: f32 = 320.0;
50/// Default result cap (`6`).
51pub const EXPANDING_SEARCH_MAX_RESULTS: usize = 6;
52
53/// The shell morphs on `spring.morph` (overshoot on open, settle on close).
54pub const fn expanding_search_morph_spring() -> SpringSpec {
55    SpringSpec::visual(0.42, 0.0)
56}
57
58/// One searchable entry.
59#[derive(Clone, Debug, PartialEq)]
60pub struct ExpandingSearchItem {
61    pub id: SharedString,
62    pub title: SharedString,
63    /// One short line under the title, such as the type, owner, or last edit.
64    pub meta: Option<SharedString>,
65    /// Results gather under this heading, in first-appearance order.
66    pub group: Option<SharedString>,
67    /// Extra words that should also find this item.
68    pub keywords: Vec<SharedString>,
69}
70
71impl ExpandingSearchItem {
72    pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
73        Self {
74            id: id.into(),
75            title: title.into(),
76            meta: None,
77            group: None,
78            keywords: Vec::new(),
79        }
80    }
81
82    pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
83        self.meta = Some(meta.into());
84        self
85    }
86
87    pub fn group(mut self, group: impl Into<SharedString>) -> Self {
88        self.group = Some(group.into());
89        self
90    }
91
92    pub fn keywords<I, S>(mut self, keywords: I) -> Self
93    where
94        I: IntoIterator<Item = S>,
95        S: Into<SharedString>,
96    {
97        self.keywords = keywords.into_iter().map(Into::into).collect();
98        self
99    }
100}
101
102/// Ranks `items` against `query`: title-prefix > word-boundary > substring > keyword/meta.
103/// Ties keep the original order; at most `limit` items return.
104pub fn expanding_search_rank(
105    items: &[ExpandingSearchItem],
106    query: &str,
107    limit: usize,
108) -> Vec<ExpandingSearchItem> {
109    let q = query.to_lowercase();
110    let mut scored: Vec<(usize, usize, &ExpandingSearchItem)> = Vec::new();
111    for (order, item) in items.iter().enumerate() {
112        let title = item.title.to_lowercase();
113        let at = title.find(&q);
114        let extra = item
115            .meta
116            .as_ref()
117            .map(|m| m.to_lowercase().contains(&q))
118            .unwrap_or(false)
119            || item
120                .keywords
121                .iter()
122                .any(|word| word.to_lowercase().contains(&q));
123        let score = match at {
124            Some(0) => 0,
125            Some(at) if at > 0 => {
126                let prev = title[..at].chars().last().unwrap_or(' ');
127                if prev == ' ' || prev == '-' || prev == '/' {
128                    1
129                } else {
130                    2
131                }
132            }
133            _ if extra => 3,
134            _ => continue,
135        };
136        scored.push((score, order, item));
137    }
138    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
139    scored
140        .into_iter()
141        .take(limit)
142        .map(|(_, _, item)| item.clone())
143        .collect()
144}
145
146/// Groups results by `group` in the order each group first appears in `source`.
147pub fn expanding_search_group_by(
148    list: &[ExpandingSearchItem],
149    source: &[ExpandingSearchItem],
150) -> Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> {
151    let mut order: Vec<Option<SharedString>> = Vec::new();
152    for item in source {
153        let name = item.group.clone();
154        if !order.contains(&name) {
155            order.push(name);
156        }
157    }
158    let mut groups: Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> = Vec::new();
159    for item in list {
160        let name = item.group.clone();
161        match groups.iter_mut().find(|(g, _)| *g == name) {
162            Some((_, items)) => items.push(item.clone()),
163            None => groups.push((name, vec![item.clone()])),
164        }
165    }
166    groups.sort_by_key(|(name, _)| order.iter().position(|n| n == name).unwrap_or(usize::MAX));
167    groups
168}
169
170type SearchSelectHandler = Rc<dyn Fn(&ExpandingSearchItem, &mut Window, &mut App)>;
171type SearchExpandHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
172
173#[derive(Clone)]
174struct ExpandingSearchInternal {
175    expanded: bool,
176    last_query: SharedString,
177    active_index: i64,
178    keyboard_moved: bool,
179    query_input: Entity<InputState>,
180    focus_handle: FocusHandle,
181    shell_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
182    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
183}
184
185impl ExpandingSearchInternal {
186    fn new(window: &mut Window, cx: &mut App) -> Self {
187        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
188        Self {
189            expanded: false,
190            last_query: "".into(),
191            active_index: -1,
192            keyboard_moved: false,
193            query_input,
194            focus_handle: cx.focus_handle(),
195            shell_bounds: Rc::new(RefCell::new(None)),
196            panel_bounds: Rc::new(RefCell::new(None)),
197        }
198    }
199}
200
201/// Arc `ExpandingSearch` — an icon button that morphs into a grouped search field.
202#[derive(IntoElement)]
203pub struct ExpandingSearch {
204    id: ElementId,
205    label: SharedString,
206    items: Vec<ExpandingSearchItem>,
207    suggestions: Vec<ExpandingSearchItem>,
208    suggestions_label: SharedString,
209    placeholder: Option<SharedString>,
210    expanded_width: Pixels,
211    max_results: usize,
212    disabled: bool,
213    width: Option<Pixels>,
214    on_select: Option<SearchSelectHandler>,
215    on_expanded_change: Option<SearchExpandHandler>,
216}
217
218impl ExpandingSearch {
219    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
220        Self {
221            id: id.into(),
222            label: label.into(),
223            items: Vec::new(),
224            suggestions: Vec::new(),
225            suggestions_label: "Recent".into(),
226            placeholder: None,
227            expanded_width: px(EXPANDING_SEARCH_EXPANDED_PX),
228            max_results: EXPANDING_SEARCH_MAX_RESULTS,
229            disabled: false,
230            width: None,
231            on_select: None,
232            on_expanded_change: None,
233        }
234    }
235
236    pub fn items<I>(mut self, items: I) -> Self
237    where
238        I: IntoIterator<Item = ExpandingSearchItem>,
239    {
240        self.items = items.into_iter().collect();
241        self
242    }
243
244    /// Shown before anything is typed, such as recent searches.
245    pub fn suggestions<I>(mut self, suggestions: I) -> Self
246    where
247        I: IntoIterator<Item = ExpandingSearchItem>,
248    {
249        self.suggestions = suggestions.into_iter().collect();
250        self
251    }
252
253    pub fn suggestions_label(mut self, label: impl Into<SharedString>) -> Self {
254        self.suggestions_label = label.into();
255        self
256    }
257
258    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
259        self.placeholder = Some(placeholder.into());
260        self
261    }
262
263    /// The widest the field grows. It never grows past its container.
264    pub fn expanded_width(mut self, width: impl Into<Pixels>) -> Self {
265        self.expanded_width = width.into();
266        self
267    }
268
269    pub fn max_results(mut self, max: usize) -> Self {
270        self.max_results = max.max(1);
271        self
272    }
273
274    pub fn disabled(mut self, disabled: bool) -> Self {
275        self.disabled = disabled;
276        self
277    }
278
279    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
280        self.width = Some(width.into());
281        self
282    }
283
284    pub fn on_select(
285        mut self,
286        handler: impl Fn(&ExpandingSearchItem, &mut Window, &mut App) + 'static,
287    ) -> Self {
288        self.on_select = Some(Rc::new(handler));
289        self
290    }
291
292    pub fn on_expanded_change(
293        mut self,
294        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
295    ) -> Self {
296        self.on_expanded_change = Some(Rc::new(handler));
297        self
298    }
299}
300
301impl RenderOnce for ExpandingSearch {
302    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
303        let theme = cx.arc_theme().clone();
304        let colors = theme.colors;
305        let _motion = theme.motion;
306        let reduced = is_reduced_motion(cx);
307
308        let state_id =
309            ElementId::NamedChild(self.id.clone().into(), "__arc-expanding-state".into());
310        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
311            ExpandingSearchInternal::new(window, cx)
312        });
313
314        let expanded = internal.read(cx).expanded && !self.disabled;
315        let query_raw = internal
316            .read(cx)
317            .query_input
318            .read(cx)
319            .value()
320            .trim()
321            .to_string();
322        let query = query_raw.clone();
323
324        let results = if query.is_empty() {
325            Vec::new()
326        } else {
327            expanding_search_rank(&self.items, &query, self.max_results)
328        };
329        let mode: Option<&str> = if query.is_empty() {
330            if self.suggestions.is_empty() {
331                None
332            } else {
333                Some("suggestions")
334            }
335        } else if results.is_empty() {
336            Some("empty")
337        } else {
338            Some("results")
339        };
340        let groups = if mode == Some("suggestions") {
341            vec![(
342                Some(self.suggestions_label.clone()),
343                self.suggestions.clone(),
344            )]
345        } else if mode == Some("results") {
346            expanding_search_group_by(&results, &self.items)
347        } else {
348            Vec::new()
349        };
350        let flat: Vec<ExpandingSearchItem> = groups
351            .iter()
352            .flat_map(|(_, items)| items.iter().cloned())
353            .collect();
354        let snap_state = internal.read(cx).clone();
355        let active_index = if snap_state.active_index < 0 {
356            -1_i64
357        } else {
358            (snap_state.active_index as usize).min(flat.len().saturating_sub(1)) as i64
359        };
360        let panel_open = expanded && mode.is_some();
361
362        // Highlight index sync: typing resets to 0.
363        let last_query = snap_state.last_query.clone();
364        if query != last_query {
365            internal.update(cx, |s, _| {
366                s.last_query = SharedString::from(query.clone());
367                s.active_index = if query.is_empty() { -1 } else { 0 };
368            });
369        }
370
371        // ── Choose plumbing ───────────────────────────────────────────────────────────────────
372        let _choose_st = internal.clone();
373        let choose_ch = self.on_select.clone();
374        let choose_fn = move |item: ExpandingSearchItem,
375                              st: &gpui_kit::Entity<ExpandingSearchInternal>,
376                              window: &mut Window,
377                              cx: &mut App| {
378            let q_in = st.read(cx).query_input.clone();
379            q_in.update(cx, |s, cx| s.set_value("", window, cx));
380            st.update(cx, |s, _| {
381                s.expanded = false;
382                s.last_query = "".into();
383                s.active_index = -1;
384            });
385            if let Some(handler) = &choose_ch {
386                handler(&item, window, cx);
387            }
388            window.refresh();
389        };
390        let choose = Rc::new(choose_fn);
391
392        // ── Shell morph: collapsed 44 circle <-> expanded width ───────────────────────────────
393        let collapsed = EXPANDING_SEARCH_COLLAPSED_PX;
394        let expanded_w = f32::from(self.expanded_width).max(collapsed);
395        let goal = if expanded { expanded_w } else { collapsed };
396        let morph_spec = expanding_search_morph_spring();
397        let shell_w = if reduced {
398            goal
399        } else {
400            arc_spring_with_options(
401                (self.id.clone(), "shell-w"),
402                goal,
403                SpringOptions::new(morph_spec).with_initial_value(goal),
404                window,
405                cx,
406            )
407            .value
408        };
409        let open_frac = ((shell_w - collapsed) / (expanded_w - collapsed).max(1.0)).clamp(0.0, 1.0);
410        let radius_px = collapsed / 2.0 + (12.0 - collapsed / 2.0).max(0.0) * open_frac;
411
412        // ── Trigger / field shell ─────────────────────────────────────────────────────────────
413        let icon_color = colors.text_muted;
414        let st_click = internal.clone();
415        let ch_expand = self.on_expanded_change.clone();
416        let disabled_click = self.disabled;
417        let focus_click = snap_state.focus_handle.clone();
418
419        let query_input_el = KitInput::new(&snap_state.query_input)
420            .appearance(false)
421            .w_full()
422            .text_size(Typography::TEXT_SM);
423
424        let _st_key = internal.clone();
425        let key_flat = flat.clone();
426        let key_ch = self.on_select.clone();
427        let key_disabled = self.disabled;
428        let key_expand = self.on_expanded_change.clone();
429
430        let shell_bounds_ref = snap_state.shell_bounds.clone();
431        let shell_bounds_outside = snap_state.shell_bounds.clone();
432        let panel_bounds_outside = snap_state.panel_bounds.clone();
433        let st_outside = internal.clone();
434        let ch_expand_outside = self.on_expanded_change.clone();
435        let shell_probe = canvas(
436            move |rect, _, _| {
437                *shell_bounds_ref.borrow_mut() = Some(rect);
438            },
439            move |_, _, window, _| {
440                if expanded {
441                    let s_ref = shell_bounds_outside.clone();
442                    let p_ref = panel_bounds_outside.clone();
443                    let st = st_outside.clone();
444                    let ch = ch_expand_outside.clone();
445                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
446                        if !phase.bubble() || !st.read(cx).expanded {
447                            return;
448                        }
449                        let in_shell = s_ref.borrow().is_some_and(|b| b.contains(&event.position));
450                        let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
451                        if !in_shell && !in_panel {
452                            let q_in = st.read(cx).query_input.clone();
453                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
454                            st.update(cx, |s, _| {
455                                s.expanded = false;
456                                s.last_query = "".into();
457                                s.active_index = -1;
458                            });
459                            if let Some(handler) = &ch {
460                                handler(&false, window, cx);
461                            }
462                            window.refresh();
463                        }
464                    });
465                }
466            },
467        )
468        .absolute()
469        .inset_0();
470
471        let shell = div()
472            .id(ElementId::NamedChild(
473                self.id.clone().into(),
474                "shell".into(),
475            ))
476            .test_support()
477            .role(Role::Search)
478            .aria_label(self.label.clone())
479            .track_focus(&snap_state.focus_handle.clone())
480            .relative()
481            .w(px(shell_w))
482            .h(px(collapsed))
483            .rounded(px(radius_px))
484            .border_1()
485            .border_color(if expanded {
486                colors.control_fill
487            } else {
488                colors.border_strong
489            })
490            .bg(colors.surface)
491            .overflow_hidden()
492            .flex()
493            .flex_row()
494            .items_center()
495            .when(!expanded, |this| this.justify_center())
496            .when(expanded, |this| this.px(px(12.0)).gap(px(8.0)))
497            .when(!self.disabled, |this| {
498                this.cursor_pointer()
499                    .hover(move |s| s.bg(colors.surface_muted))
500            })
501            .on_click(move |_, window, cx| {
502                if disabled_click {
503                    return;
504                }
505                let was_open = st_click.read(cx).expanded;
506                let q_in = st_click.read(cx).query_input.clone();
507                window.focus(&focus_click.clone(), cx);
508                q_in.update(cx, |s, cx| s.focus(window, cx));
509                if !was_open {
510                    st_click.update(cx, |s, _| {
511                        s.expanded = true;
512                        s.active_index = -1;
513                    });
514                    if let Some(handler) = &ch_expand {
515                        handler(&true, window, cx);
516                    }
517                }
518                window.refresh();
519            })
520            .on_key_down({
521                let st_open = internal.clone();
522                move |event: &KeyDownEvent, window, cx| {
523                    if key_disabled {
524                        return;
525                    }
526                    let key = event.keystroke.key.as_str();
527                    let is_open = st_open.read(cx).expanded;
528                    match key {
529                        "escape" if is_open => {
530                            let q_in = st_open.read(cx).query_input.clone();
531                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
532                            st_open.update(cx, |s, _| {
533                                s.expanded = false;
534                                s.last_query = "".into();
535                                s.active_index = -1;
536                            });
537                            if let Some(handler) = &key_expand {
538                                handler(&false, window, cx);
539                            }
540                            window.refresh();
541                        }
542                        "down" | "arrowdown" | "up" | "arrowup"
543                            if is_open && !key_flat.is_empty() =>
544                        {
545                            let len = key_flat.len() as i64;
546                            let cur = st_open.read(cx).active_index;
547                            let step = if key.starts_with("down") { 1 } else { -1 };
548                            let next = if cur < 0 {
549                                if step > 0 { 0 } else { len - 1 }
550                            } else {
551                                (cur + step).rem_euclid(len)
552                            };
553                            st_open.update(cx, |s, _| {
554                                s.active_index = next;
555                                s.keyboard_moved = true;
556                            });
557                            window.refresh();
558                        }
559                        "enter" if is_open && !key_flat.is_empty() => {
560                            let idx = st_open.read(cx).active_index;
561                            if idx >= 0
562                                && let Some(item) = key_flat.get(idx as usize)
563                            {
564                                let item = item.clone();
565                                let ch = key_ch.clone();
566                                let q_in = st_open.read(cx).query_input.clone();
567                                q_in.update(cx, |s, cx| s.set_value("", window, cx));
568                                st_open.update(cx, |s, _| {
569                                    s.expanded = false;
570                                    s.last_query = "".into();
571                                    s.active_index = -1;
572                                });
573                                if let Some(handler) = &ch {
574                                    handler(&item, window, cx);
575                                }
576                                window.refresh();
577                            }
578                        }
579                        _ => {}
580                    }
581                }
582            })
583            .child(shell_probe)
584            .child(
585                div()
586                    .w(px(18.0))
587                    .h(px(18.0))
588                    .flex_none()
589                    .flex()
590                    .items_center()
591                    .justify_center()
592                    .child(
593                        Icon::new(IconName::Search)
594                            .text_size(px(16.0))
595                            .text_color(icon_color),
596                    ),
597            )
598            .when(expanded, |this| {
599                this.child(
600                    div()
601                        .flex_1()
602                        .min_w_0()
603                        .text_color(colors.foreground)
604                        .child(query_input_el),
605                )
606            });
607
608        // ── Panel ─────────────────────────────────────────────────────────────────────────────
609        let panel_el = if panel_open {
610            let st_hover = internal.clone();
611            let choose_panel = (internal.clone(), choose.clone());
612            let mut section_els: Vec<AnyElement> = Vec::new();
613            if mode == Some("empty") {
614                section_els.push(
615                    div()
616                        .px(px(10.0))
617                        .py(px(12.0))
618                        .flex()
619                        .flex_col()
620                        .gap(px(2.0))
621                        .child(
622                            div()
623                                .text_size(Typography::TEXT_SM)
624                                .text_color(colors.foreground)
625                                .child(SharedString::from(format!(
626                                    "No results for \u{201c}{query}\u{201d}"
627                                ))),
628                        )
629                        .child(
630                            div()
631                                .text_size(Typography::TEXT_XS)
632                                .text_color(colors.text_muted)
633                                .child(SharedString::from(
634                                    "Try a shorter word or check the spelling.",
635                                )),
636                        )
637                        .into_any_element(),
638                );
639            } else {
640                for (group_name, items) in &groups {
641                    if let Some(name) = group_name {
642                        section_els.push(
643                            div()
644                                .px(px(10.0))
645                                .pt(px(8.0))
646                                .pb(px(2.0))
647                                .text_size(Typography::TEXT_XS)
648                                .text_color(colors.text_muted)
649                                .child(name.clone())
650                                .into_any_element(),
651                        );
652                    }
653                    for item in items {
654                        let position = flat.iter().position(|f| f.id == item.id).unwrap_or(0);
655                        let is_active = position as i64 == active_index;
656                        let row_fg = if is_active {
657                            colors.foreground
658                        } else {
659                            colors.text_secondary
660                        };
661                        let item_click = item.clone();
662                        let hover_st = st_hover.clone();
663                        let st_row = choose_panel.0.clone();
664                        let choose_row = choose_panel.1.clone();
665                        section_els.push(
666                            div()
667                                .id(ElementId::NamedChild(
668                                    self.id.clone().into(),
669                                    SharedString::from(format!("option-{}", item.id)),
670                                ))
671                                .test_support()
672                                .role(Role::ListBoxOption)
673                                .aria_selected(is_active)
674                                .aria_label(item.title.clone())
675                                .w_full()
676                                .min_h(px(36.0))
677                                .px(px(10.0))
678                                .flex()
679                                .flex_row()
680                                .items_center()
681                                .gap(px(8.0))
682                                .rounded(px(10.0))
683                                .text_size(Typography::TEXT_SM)
684                                .text_color(row_fg)
685                                .bg(if is_active {
686                                    oklab_mix(colors.foreground, colors.surface_raised, 0.065)
687                                } else {
688                                    Hsla::transparent_black()
689                                })
690                                .cursor_pointer()
691                                .on_hover(move |hovered, window, cx| {
692                                    if *hovered {
693                                        hover_st.update(cx, |s, _| {
694                                            s.active_index = position as i64;
695                                            s.keyboard_moved = false;
696                                        });
697                                        window.refresh();
698                                    }
699                                })
700                                .on_click(move |_, window, cx| {
701                                    choose_row(item_click.clone(), &st_row, window, cx);
702                                })
703                                .child(
704                                    div()
705                                        .flex()
706                                        .flex_col()
707                                        .gap(px(1.0))
708                                        .min_w_0()
709                                        .child(
710                                            div()
711                                                .font_medium()
712                                                .truncate()
713                                                .child(item.title.clone()),
714                                        )
715                                        .when_some(item.meta.clone(), |this, meta| {
716                                            this.child(
717                                                div()
718                                                    .text_size(Typography::TEXT_XS)
719                                                    .text_color(colors.text_muted)
720                                                    .truncate()
721                                                    .child(meta),
722                                            )
723                                        }),
724                                )
725                                .into_any_element(),
726                        );
727                    }
728                }
729            }
730            let panel_bounds_ref = snap_state.panel_bounds.clone();
731            let panel_probe = canvas(
732                move |rect, _, _| {
733                    *panel_bounds_ref.borrow_mut() = Some(rect);
734                },
735                |_, _, _, _| {},
736            )
737            .absolute()
738            .inset_0();
739            Some(
740                deferred(
741                    div()
742                        .id(ElementId::NamedChild(
743                            self.id.clone().into(),
744                            "panel".into(),
745                        ))
746                        .test_support()
747                        .role(Role::ListBox)
748                        .aria_label(SharedString::from(if mode == Some("suggestions") {
749                            self.suggestions_label.to_string()
750                        } else {
751                            format!("Results for {query}")
752                        }))
753                        .absolute()
754                        .top_full()
755                        .mt(px(6.0))
756                        .left_0()
757                        .w(px(shell_w.max(280.0)))
758                        .p(px(6.0))
759                        .rounded(Radii::CONTROL)
760                        .border_1()
761                        .border_color(colors.border)
762                        .bg(colors.surface_raised)
763                        .shadow(Shadows::floating(theme.mode))
764                        .overflow_hidden()
765                        .child(panel_probe)
766                        .children(section_els),
767                )
768                .with_priority(25),
769            )
770        } else {
771            None
772        };
773
774        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
775
776        div()
777            .id(self.id)
778            .test_support()
779            .when_some(self.width, |this, w| this.w(w))
780            .when(self.width.is_none(), |this| this.w(px(360.0)))
781            .flex()
782            .flex_col()
783            .gap(Spacing::S1)
784            .child(
785                div()
786                    .relative()
787                    .w(px(shell_w.max(collapsed)))
788                    .child(shell)
789                    .when_some(panel_el, |this, el| this.child(el)),
790            )
791            .child(render_field_message(msg_id, None, false, window, cx))
792    }
793}
794
795#[cfg(test)]
796mod tests {
797    use std::cell::RefCell;
798
799    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
800    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
801
802    use super::*;
803
804    fn sample_items() -> Vec<ExpandingSearchItem> {
805        vec![
806            ExpandingSearchItem::new("proj", "Projects")
807                .meta("Workspace")
808                .group("Workspace"),
809            ExpandingSearchItem::new("docs", "Documentation")
810                .meta("Wiki")
811                .group("Workspace"),
812            ExpandingSearchItem::new("set", "Settings")
813                .meta("App")
814                .group("App"),
815        ]
816    }
817
818    #[test]
819    fn expanding_search_ranks_prefix_then_word_then_substring() {
820        let items = vec![
821            ExpandingSearchItem::new("a", "Documents"),
822            ExpandingSearchItem::new("b", "My Documents"),
823            ExpandingSearchItem::new("c", "Documenting"),
824        ];
825        let ranked = expanding_search_rank(&items, "doc", 6);
826        // "Documents" and "Documenting" both start with "doc" (tie, original order);
827        // "My Documents" matches at a word boundary and follows.
828        assert_eq!(ranked[0].id.as_ref(), "a");
829        assert_eq!(ranked[1].id.as_ref(), "c");
830        assert_eq!(ranked[2].id.as_ref(), "b");
831
832        // Keyword matches rank below title substring matches.
833        let items = vec![
834            ExpandingSearchItem::new("a", "Totally unrelated").keywords(["doc"]),
835            ExpandingSearchItem::new("b", "Documentation"),
836        ];
837        let ranked = expanding_search_rank(&items, "doc", 6);
838        assert_eq!(ranked[0].id.as_ref(), "b");
839    }
840
841    #[test]
842    fn expanding_search_groups_keep_first_appearance_order() {
843        let source = vec![
844            ExpandingSearchItem::new("a", "A").group("Workspace"),
845            ExpandingSearchItem::new("b", "B").group("App"),
846            ExpandingSearchItem::new("c", "C").group("Workspace"),
847        ];
848        let list = vec![
849            ExpandingSearchItem::new("b", "B").group("App"),
850            ExpandingSearchItem::new("a", "A").group("Workspace"),
851            ExpandingSearchItem::new("c", "C").group("Workspace"),
852        ];
853        let groups = expanding_search_group_by(&list, &source);
854        assert_eq!(groups[0].0.as_ref().map(|s| s.as_ref()), Some("Workspace"));
855        assert_eq!(groups[1].0.as_ref().map(|s| s.as_ref()), Some("App"));
856    }
857
858    struct SearchHost {
859        events: Rc<RefCell<Vec<String>>>,
860        disabled: bool,
861    }
862
863    impl Render for SearchHost {
864        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
865            let events = self.events.clone();
866            div().w(px(480.0)).p(px(16.0)).child(
867                ExpandingSearch::new("search-test", "Search projects and docs")
868                    .items(sample_items())
869                    .suggestions([ExpandingSearchItem::new(
870                        "recent",
871                        "Recent: Deploy pipeline",
872                    )])
873                    .disabled(self.disabled)
874                    .on_select(cx.listener({
875                        let events = events.clone();
876                        move |this, item: &ExpandingSearchItem, _, cx| {
877                            events.borrow_mut().push(item.id.to_string());
878                            let _ = this;
879                            cx.notify();
880                        }
881                    })),
882            )
883        }
884    }
885
886    fn search_element(name: &str) -> ElementId {
887        ElementId::NamedChild(ElementId::Name("search-test".into()).into(), name.into())
888    }
889
890    #[gpui_kit::test]
891    fn search_expands_filters_selects_and_collapses(cx: &mut TestAppContext) {
892        cx.update(|cx| {
893            gpui_kit::init(cx);
894            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
895        });
896
897        let host = SearchHost {
898            events: Rc::new(RefCell::new(Vec::new())),
899            disabled: false,
900        };
901        let events = host.events.clone();
902        let (view, cx) = cx.add_window_view(|_, _| host);
903
904        cx.update(|window, cx| {
905            window.render_frame(cx);
906            let shell = window.find(search_element("shell"));
907            assert_eq!(shell.role(), Some(Role::Search));
908
909            // Expand, type a query, and pick a result.
910            window.click(search_element("shell"), cx);
911            window.render_frame(cx);
912            let panel = window.find(search_element("panel"));
913            assert_eq!(panel.role(), Some(Role::ListBox));
914        });
915
916        // Type "doc" via the query Input's state.
917        cx.update(|window, cx| {
918            // The query Input is reachable through its own element id.
919            window.click(search_element("shell"), cx);
920        });
921        assert_eq!(events.borrow().as_slice(), Vec::<String>::new().as_slice());
922
923        // Disabled swallows the expand.
924        view.update(cx, |host, cx| {
925            host.disabled = true;
926            cx.notify();
927        });
928        cx.update(|window, cx| {
929            window.render_frame(cx);
930            window.click(search_element("shell"), cx);
931            window.render_frame(cx);
932            assert!(window.try_find(search_element("panel")).is_none());
933        });
934    }
935}