arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/expanding-search/expanding-search.tsx`
//! & `.module.css`
//!
//! P4 Component #21: `expanding-search`
//!
//! - A search that waits as an icon button until it is needed:
//!   - The collapsed `44px` circle morphs into a `360px` field on `spring.morph` (a hint of
//!     overshoot on open, a settle without one on close, so the circle never dips below its
//!     own size); the corner radius rides the same spring (circle while collapsed, control
//!     radius once open).
//!   - Results rank title-prefix > word-boundary > substring > keyword/meta matches, grouped
//!     in first-appearance order, capped at `max_results`; with an empty query the suggestions
//!     list shows; no matches reveals the empty state.
//!   - The panel unfolds beneath the field on `spring.smooth` height; Escape, choosing a
//!     result, or folding the query back to empty collapses into the icon.
//!   - Keyboard: ArrowDown/ArrowUp wrap the highlight, Enter chooses, Escape closes.
//!
//! Known deviations from upstream:
//! - The query edits through the shared `Input` (real caret) instead of a native `<input>`;
//!   there is no `aria-live` announcement region and the `anchor`/`boundary` layout overrides
//!   are omitted (the field always anchors at the start edge of its container).

use std::{cell::RefCell, rc::Rc};

use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window,
    assets::IconName,
    base::StyledExt as _,
    canvas,
    component::{
        Icon,
        input::{Input as KitInput, InputState},
    },
    deferred, div,
    prelude::*,
    px,
};

use super::field_message::render_field_message;

/// Collapsed shell size (`36px` — matches `ControlHeights::MD`).
pub const EXPANDING_SEARCH_COLLAPSED_PX: f32 = 36.0;
/// Default expanded width (`320px`).
pub const EXPANDING_SEARCH_EXPANDED_PX: f32 = 320.0;
/// Default result cap (`6`).
pub const EXPANDING_SEARCH_MAX_RESULTS: usize = 6;

/// The shell morphs on `spring.morph` (overshoot on open, settle on close).
pub const fn expanding_search_morph_spring() -> SpringSpec {
    SpringSpec::visual(0.42, 0.0)
}

/// One searchable entry.
#[derive(Clone, Debug, PartialEq)]
pub struct ExpandingSearchItem {
    pub id: SharedString,
    pub title: SharedString,
    /// One short line under the title, such as the type, owner, or last edit.
    pub meta: Option<SharedString>,
    /// Results gather under this heading, in first-appearance order.
    pub group: Option<SharedString>,
    /// Extra words that should also find this item.
    pub keywords: Vec<SharedString>,
}

impl ExpandingSearchItem {
    pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            meta: None,
            group: None,
            keywords: Vec::new(),
        }
    }

    pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
        self.meta = Some(meta.into());
        self
    }

    pub fn group(mut self, group: impl Into<SharedString>) -> Self {
        self.group = Some(group.into());
        self
    }

    pub fn keywords<I, S>(mut self, keywords: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.keywords = keywords.into_iter().map(Into::into).collect();
        self
    }
}

/// Ranks `items` against `query`: title-prefix > word-boundary > substring > keyword/meta.
/// Ties keep the original order; at most `limit` items return.
pub fn expanding_search_rank(
    items: &[ExpandingSearchItem],
    query: &str,
    limit: usize,
) -> Vec<ExpandingSearchItem> {
    let q = query.to_lowercase();
    let mut scored: Vec<(usize, usize, &ExpandingSearchItem)> = Vec::new();
    for (order, item) in items.iter().enumerate() {
        let title = item.title.to_lowercase();
        let at = title.find(&q);
        let extra = item
            .meta
            .as_ref()
            .map(|m| m.to_lowercase().contains(&q))
            .unwrap_or(false)
            || item
                .keywords
                .iter()
                .any(|word| word.to_lowercase().contains(&q));
        let score = match at {
            Some(0) => 0,
            Some(at) if at > 0 => {
                let prev = title[..at].chars().last().unwrap_or(' ');
                if prev == ' ' || prev == '-' || prev == '/' {
                    1
                } else {
                    2
                }
            }
            _ if extra => 3,
            _ => continue,
        };
        scored.push((score, order, item));
    }
    scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    scored
        .into_iter()
        .take(limit)
        .map(|(_, _, item)| item.clone())
        .collect()
}

/// Groups results by `group` in the order each group first appears in `source`.
pub fn expanding_search_group_by(
    list: &[ExpandingSearchItem],
    source: &[ExpandingSearchItem],
) -> Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> {
    let mut order: Vec<Option<SharedString>> = Vec::new();
    for item in source {
        let name = item.group.clone();
        if !order.contains(&name) {
            order.push(name);
        }
    }
    let mut groups: Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> = Vec::new();
    for item in list {
        let name = item.group.clone();
        match groups.iter_mut().find(|(g, _)| *g == name) {
            Some((_, items)) => items.push(item.clone()),
            None => groups.push((name, vec![item.clone()])),
        }
    }
    groups.sort_by_key(|(name, _)| order.iter().position(|n| n == name).unwrap_or(usize::MAX));
    groups
}

type SearchSelectHandler = Rc<dyn Fn(&ExpandingSearchItem, &mut Window, &mut App)>;
type SearchExpandHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;

#[derive(Clone)]
struct ExpandingSearchInternal {
    expanded: bool,
    last_query: SharedString,
    active_index: i64,
    keyboard_moved: bool,
    query_input: Entity<InputState>,
    focus_handle: FocusHandle,
    shell_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}

impl ExpandingSearchInternal {
    fn new(window: &mut Window, cx: &mut App) -> Self {
        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
        Self {
            expanded: false,
            last_query: "".into(),
            active_index: -1,
            keyboard_moved: false,
            query_input,
            focus_handle: cx.focus_handle(),
            shell_bounds: Rc::new(RefCell::new(None)),
            panel_bounds: Rc::new(RefCell::new(None)),
        }
    }
}

/// Arc `ExpandingSearch` — an icon button that morphs into a grouped search field.
#[derive(IntoElement)]
pub struct ExpandingSearch {
    id: ElementId,
    label: SharedString,
    items: Vec<ExpandingSearchItem>,
    suggestions: Vec<ExpandingSearchItem>,
    suggestions_label: SharedString,
    placeholder: Option<SharedString>,
    expanded_width: Pixels,
    max_results: usize,
    disabled: bool,
    width: Option<Pixels>,
    on_select: Option<SearchSelectHandler>,
    on_expanded_change: Option<SearchExpandHandler>,
}

impl ExpandingSearch {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            items: Vec::new(),
            suggestions: Vec::new(),
            suggestions_label: "Recent".into(),
            placeholder: None,
            expanded_width: px(EXPANDING_SEARCH_EXPANDED_PX),
            max_results: EXPANDING_SEARCH_MAX_RESULTS,
            disabled: false,
            width: None,
            on_select: None,
            on_expanded_change: None,
        }
    }

    pub fn items<I>(mut self, items: I) -> Self
    where
        I: IntoIterator<Item = ExpandingSearchItem>,
    {
        self.items = items.into_iter().collect();
        self
    }

    /// Shown before anything is typed, such as recent searches.
    pub fn suggestions<I>(mut self, suggestions: I) -> Self
    where
        I: IntoIterator<Item = ExpandingSearchItem>,
    {
        self.suggestions = suggestions.into_iter().collect();
        self
    }

    pub fn suggestions_label(mut self, label: impl Into<SharedString>) -> Self {
        self.suggestions_label = label.into();
        self
    }

    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// The widest the field grows. It never grows past its container.
    pub fn expanded_width(mut self, width: impl Into<Pixels>) -> Self {
        self.expanded_width = width.into();
        self
    }

    pub fn max_results(mut self, max: usize) -> Self {
        self.max_results = max.max(1);
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_select(
        mut self,
        handler: impl Fn(&ExpandingSearchItem, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }

    pub fn on_expanded_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_expanded_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for ExpandingSearch {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let _motion = theme.motion;
        let reduced = is_reduced_motion(cx);

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-expanding-state".into());
        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
            ExpandingSearchInternal::new(window, cx)
        });

        let expanded = internal.read(cx).expanded && !self.disabled;
        let query_raw = internal
            .read(cx)
            .query_input
            .read(cx)
            .value()
            .trim()
            .to_string();
        let query = query_raw.clone();

        let results = if query.is_empty() {
            Vec::new()
        } else {
            expanding_search_rank(&self.items, &query, self.max_results)
        };
        let mode: Option<&str> = if query.is_empty() {
            if self.suggestions.is_empty() {
                None
            } else {
                Some("suggestions")
            }
        } else if results.is_empty() {
            Some("empty")
        } else {
            Some("results")
        };
        let groups = if mode == Some("suggestions") {
            vec![(
                Some(self.suggestions_label.clone()),
                self.suggestions.clone(),
            )]
        } else if mode == Some("results") {
            expanding_search_group_by(&results, &self.items)
        } else {
            Vec::new()
        };
        let flat: Vec<ExpandingSearchItem> = groups
            .iter()
            .flat_map(|(_, items)| items.iter().cloned())
            .collect();
        let snap_state = internal.read(cx).clone();
        let active_index = if snap_state.active_index < 0 {
            -1_i64
        } else {
            (snap_state.active_index as usize).min(flat.len().saturating_sub(1)) as i64
        };
        let panel_open = expanded && mode.is_some();

        // Highlight index sync: typing resets to 0.
        let last_query = snap_state.last_query.clone();
        if query != last_query {
            internal.update(cx, |s, _| {
                s.last_query = SharedString::from(query.clone());
                s.active_index = if query.is_empty() { -1 } else { 0 };
            });
        }

        // ── Choose plumbing ───────────────────────────────────────────────────────────────────
        let _choose_st = internal.clone();
        let choose_ch = self.on_select.clone();
        let choose_fn = move |item: ExpandingSearchItem,
                              st: &gpui_kit::Entity<ExpandingSearchInternal>,
                              window: &mut Window,
                              cx: &mut App| {
            let q_in = st.read(cx).query_input.clone();
            q_in.update(cx, |s, cx| s.set_value("", window, cx));
            st.update(cx, |s, _| {
                s.expanded = false;
                s.last_query = "".into();
                s.active_index = -1;
            });
            if let Some(handler) = &choose_ch {
                handler(&item, window, cx);
            }
            window.refresh();
        };
        let choose = Rc::new(choose_fn);

        // ── Shell morph: collapsed 44 circle <-> expanded width ───────────────────────────────
        let collapsed = EXPANDING_SEARCH_COLLAPSED_PX;
        let expanded_w = f32::from(self.expanded_width).max(collapsed);
        let goal = if expanded { expanded_w } else { collapsed };
        let morph_spec = expanding_search_morph_spring();
        let shell_w = if reduced {
            goal
        } else {
            arc_spring_with_options(
                (self.id.clone(), "shell-w"),
                goal,
                SpringOptions::new(morph_spec).with_initial_value(goal),
                window,
                cx,
            )
            .value
        };
        let open_frac = ((shell_w - collapsed) / (expanded_w - collapsed).max(1.0)).clamp(0.0, 1.0);
        let radius_px = collapsed / 2.0 + (12.0 - collapsed / 2.0).max(0.0) * open_frac;

        // ── Trigger / field shell ─────────────────────────────────────────────────────────────
        let icon_color = colors.text_muted;
        let st_click = internal.clone();
        let ch_expand = self.on_expanded_change.clone();
        let disabled_click = self.disabled;
        let focus_click = snap_state.focus_handle.clone();

        let query_input_el = KitInput::new(&snap_state.query_input)
            .appearance(false)
            .w_full()
            .text_size(Typography::TEXT_SM);

        let _st_key = internal.clone();
        let key_flat = flat.clone();
        let key_ch = self.on_select.clone();
        let key_disabled = self.disabled;
        let key_expand = self.on_expanded_change.clone();

        let shell_bounds_ref = snap_state.shell_bounds.clone();
        let shell_bounds_outside = snap_state.shell_bounds.clone();
        let panel_bounds_outside = snap_state.panel_bounds.clone();
        let st_outside = internal.clone();
        let ch_expand_outside = self.on_expanded_change.clone();
        let shell_probe = canvas(
            move |rect, _, _| {
                *shell_bounds_ref.borrow_mut() = Some(rect);
            },
            move |_, _, window, _| {
                if expanded {
                    let s_ref = shell_bounds_outside.clone();
                    let p_ref = panel_bounds_outside.clone();
                    let st = st_outside.clone();
                    let ch = ch_expand_outside.clone();
                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                        if !phase.bubble() || !st.read(cx).expanded {
                            return;
                        }
                        let in_shell = s_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
                        if !in_shell && !in_panel {
                            let q_in = st.read(cx).query_input.clone();
                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
                            st.update(cx, |s, _| {
                                s.expanded = false;
                                s.last_query = "".into();
                                s.active_index = -1;
                            });
                            if let Some(handler) = &ch {
                                handler(&false, window, cx);
                            }
                            window.refresh();
                        }
                    });
                }
            },
        )
        .absolute()
        .inset_0();

        let shell = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "shell".into(),
            ))
            .test_support()
            .role(Role::Search)
            .aria_label(self.label.clone())
            .track_focus(&snap_state.focus_handle.clone())
            .relative()
            .w(px(shell_w))
            .h(px(collapsed))
            .rounded(px(radius_px))
            .border_1()
            .border_color(if expanded {
                colors.control_fill
            } else {
                colors.border_strong
            })
            .bg(colors.surface)
            .overflow_hidden()
            .flex()
            .flex_row()
            .items_center()
            .when(!expanded, |this| this.justify_center())
            .when(expanded, |this| this.px(px(12.0)).gap(px(8.0)))
            .when(!self.disabled, |this| {
                this.cursor_pointer()
                    .hover(move |s| s.bg(colors.surface_muted))
            })
            .on_click(move |_, window, cx| {
                if disabled_click {
                    return;
                }
                let was_open = st_click.read(cx).expanded;
                let q_in = st_click.read(cx).query_input.clone();
                window.focus(&focus_click.clone(), cx);
                q_in.update(cx, |s, cx| s.focus(window, cx));
                if !was_open {
                    st_click.update(cx, |s, _| {
                        s.expanded = true;
                        s.active_index = -1;
                    });
                    if let Some(handler) = &ch_expand {
                        handler(&true, window, cx);
                    }
                }
                window.refresh();
            })
            .on_key_down({
                let st_open = internal.clone();
                move |event: &KeyDownEvent, window, cx| {
                    if key_disabled {
                        return;
                    }
                    let key = event.keystroke.key.as_str();
                    let is_open = st_open.read(cx).expanded;
                    match key {
                        "escape" if is_open => {
                            let q_in = st_open.read(cx).query_input.clone();
                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
                            st_open.update(cx, |s, _| {
                                s.expanded = false;
                                s.last_query = "".into();
                                s.active_index = -1;
                            });
                            if let Some(handler) = &key_expand {
                                handler(&false, window, cx);
                            }
                            window.refresh();
                        }
                        "down" | "arrowdown" | "up" | "arrowup"
                            if is_open && !key_flat.is_empty() =>
                        {
                            let len = key_flat.len() as i64;
                            let cur = st_open.read(cx).active_index;
                            let step = if key.starts_with("down") { 1 } else { -1 };
                            let next = if cur < 0 {
                                if step > 0 { 0 } else { len - 1 }
                            } else {
                                (cur + step).rem_euclid(len)
                            };
                            st_open.update(cx, |s, _| {
                                s.active_index = next;
                                s.keyboard_moved = true;
                            });
                            window.refresh();
                        }
                        "enter" if is_open && !key_flat.is_empty() => {
                            let idx = st_open.read(cx).active_index;
                            if idx >= 0
                                && let Some(item) = key_flat.get(idx as usize)
                            {
                                let item = item.clone();
                                let ch = key_ch.clone();
                                let q_in = st_open.read(cx).query_input.clone();
                                q_in.update(cx, |s, cx| s.set_value("", window, cx));
                                st_open.update(cx, |s, _| {
                                    s.expanded = false;
                                    s.last_query = "".into();
                                    s.active_index = -1;
                                });
                                if let Some(handler) = &ch {
                                    handler(&item, window, cx);
                                }
                                window.refresh();
                            }
                        }
                        _ => {}
                    }
                }
            })
            .child(shell_probe)
            .child(
                div()
                    .w(px(18.0))
                    .h(px(18.0))
                    .flex_none()
                    .flex()
                    .items_center()
                    .justify_center()
                    .child(
                        Icon::new(IconName::Search)
                            .text_size(px(16.0))
                            .text_color(icon_color),
                    ),
            )
            .when(expanded, |this| {
                this.child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .text_color(colors.foreground)
                        .child(query_input_el),
                )
            });

        // ── Panel ─────────────────────────────────────────────────────────────────────────────
        let panel_el = if panel_open {
            let st_hover = internal.clone();
            let choose_panel = (internal.clone(), choose.clone());
            let mut section_els: Vec<AnyElement> = Vec::new();
            if mode == Some("empty") {
                section_els.push(
                    div()
                        .px(px(10.0))
                        .py(px(12.0))
                        .flex()
                        .flex_col()
                        .gap(px(2.0))
                        .child(
                            div()
                                .text_size(Typography::TEXT_SM)
                                .text_color(colors.foreground)
                                .child(SharedString::from(format!(
                                    "No results for \u{201c}{query}\u{201d}"
                                ))),
                        )
                        .child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .text_color(colors.text_muted)
                                .child(SharedString::from(
                                    "Try a shorter word or check the spelling.",
                                )),
                        )
                        .into_any_element(),
                );
            } else {
                for (group_name, items) in &groups {
                    if let Some(name) = group_name {
                        section_els.push(
                            div()
                                .px(px(10.0))
                                .pt(px(8.0))
                                .pb(px(2.0))
                                .text_size(Typography::TEXT_XS)
                                .text_color(colors.text_muted)
                                .child(name.clone())
                                .into_any_element(),
                        );
                    }
                    for item in items {
                        let position = flat.iter().position(|f| f.id == item.id).unwrap_or(0);
                        let is_active = position as i64 == active_index;
                        let row_fg = if is_active {
                            colors.foreground
                        } else {
                            colors.text_secondary
                        };
                        let item_click = item.clone();
                        let hover_st = st_hover.clone();
                        let st_row = choose_panel.0.clone();
                        let choose_row = choose_panel.1.clone();
                        section_els.push(
                            div()
                                .id(ElementId::NamedChild(
                                    self.id.clone().into(),
                                    SharedString::from(format!("option-{}", item.id)),
                                ))
                                .test_support()
                                .role(Role::ListBoxOption)
                                .aria_selected(is_active)
                                .aria_label(item.title.clone())
                                .w_full()
                                .min_h(px(36.0))
                                .px(px(10.0))
                                .flex()
                                .flex_row()
                                .items_center()
                                .gap(px(8.0))
                                .rounded(px(10.0))
                                .text_size(Typography::TEXT_SM)
                                .text_color(row_fg)
                                .bg(if is_active {
                                    oklab_mix(colors.foreground, colors.surface_raised, 0.065)
                                } else {
                                    Hsla::transparent_black()
                                })
                                .cursor_pointer()
                                .on_hover(move |hovered, window, cx| {
                                    if *hovered {
                                        hover_st.update(cx, |s, _| {
                                            s.active_index = position as i64;
                                            s.keyboard_moved = false;
                                        });
                                        window.refresh();
                                    }
                                })
                                .on_click(move |_, window, cx| {
                                    choose_row(item_click.clone(), &st_row, window, cx);
                                })
                                .child(
                                    div()
                                        .flex()
                                        .flex_col()
                                        .gap(px(1.0))
                                        .min_w_0()
                                        .child(
                                            div()
                                                .font_medium()
                                                .truncate()
                                                .child(item.title.clone()),
                                        )
                                        .when_some(item.meta.clone(), |this, meta| {
                                            this.child(
                                                div()
                                                    .text_size(Typography::TEXT_XS)
                                                    .text_color(colors.text_muted)
                                                    .truncate()
                                                    .child(meta),
                                            )
                                        }),
                                )
                                .into_any_element(),
                        );
                    }
                }
            }
            let panel_bounds_ref = snap_state.panel_bounds.clone();
            let panel_probe = canvas(
                move |rect, _, _| {
                    *panel_bounds_ref.borrow_mut() = Some(rect);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0();
            Some(
                deferred(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            "panel".into(),
                        ))
                        .test_support()
                        .role(Role::ListBox)
                        .aria_label(SharedString::from(if mode == Some("suggestions") {
                            self.suggestions_label.to_string()
                        } else {
                            format!("Results for {query}")
                        }))
                        .absolute()
                        .top_full()
                        .mt(px(6.0))
                        .left_0()
                        .w(px(shell_w.max(280.0)))
                        .p(px(6.0))
                        .rounded(Radii::CONTROL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .overflow_hidden()
                        .child(panel_probe)
                        .children(section_els),
                )
                .with_priority(25),
            )
        } else {
            None
        };

        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w(px(360.0)))
            .flex()
            .flex_col()
            .gap(Spacing::S1)
            .child(
                div()
                    .relative()
                    .w(px(shell_w.max(collapsed)))
                    .child(shell)
                    .when_some(panel_el, |this, el| this.child(el)),
            )
            .child(render_field_message(msg_id, None, false, window, cx))
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    fn sample_items() -> Vec<ExpandingSearchItem> {
        vec![
            ExpandingSearchItem::new("proj", "Projects")
                .meta("Workspace")
                .group("Workspace"),
            ExpandingSearchItem::new("docs", "Documentation")
                .meta("Wiki")
                .group("Workspace"),
            ExpandingSearchItem::new("set", "Settings")
                .meta("App")
                .group("App"),
        ]
    }

    #[test]
    fn expanding_search_ranks_prefix_then_word_then_substring() {
        let items = vec![
            ExpandingSearchItem::new("a", "Documents"),
            ExpandingSearchItem::new("b", "My Documents"),
            ExpandingSearchItem::new("c", "Documenting"),
        ];
        let ranked = expanding_search_rank(&items, "doc", 6);
        // "Documents" and "Documenting" both start with "doc" (tie, original order);
        // "My Documents" matches at a word boundary and follows.
        assert_eq!(ranked[0].id.as_ref(), "a");
        assert_eq!(ranked[1].id.as_ref(), "c");
        assert_eq!(ranked[2].id.as_ref(), "b");

        // Keyword matches rank below title substring matches.
        let items = vec![
            ExpandingSearchItem::new("a", "Totally unrelated").keywords(["doc"]),
            ExpandingSearchItem::new("b", "Documentation"),
        ];
        let ranked = expanding_search_rank(&items, "doc", 6);
        assert_eq!(ranked[0].id.as_ref(), "b");
    }

    #[test]
    fn expanding_search_groups_keep_first_appearance_order() {
        let source = vec![
            ExpandingSearchItem::new("a", "A").group("Workspace"),
            ExpandingSearchItem::new("b", "B").group("App"),
            ExpandingSearchItem::new("c", "C").group("Workspace"),
        ];
        let list = vec![
            ExpandingSearchItem::new("b", "B").group("App"),
            ExpandingSearchItem::new("a", "A").group("Workspace"),
            ExpandingSearchItem::new("c", "C").group("Workspace"),
        ];
        let groups = expanding_search_group_by(&list, &source);
        assert_eq!(groups[0].0.as_ref().map(|s| s.as_ref()), Some("Workspace"));
        assert_eq!(groups[1].0.as_ref().map(|s| s.as_ref()), Some("App"));
    }

    struct SearchHost {
        events: Rc<RefCell<Vec<String>>>,
        disabled: bool,
    }

    impl Render for SearchHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            div().w(px(480.0)).p(px(16.0)).child(
                ExpandingSearch::new("search-test", "Search projects and docs")
                    .items(sample_items())
                    .suggestions([ExpandingSearchItem::new(
                        "recent",
                        "Recent: Deploy pipeline",
                    )])
                    .disabled(self.disabled)
                    .on_select(cx.listener({
                        let events = events.clone();
                        move |this, item: &ExpandingSearchItem, _, cx| {
                            events.borrow_mut().push(item.id.to_string());
                            let _ = this;
                            cx.notify();
                        }
                    })),
            )
        }
    }

    fn search_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("search-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn search_expands_filters_selects_and_collapses(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = SearchHost {
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            let shell = window.find(search_element("shell"));
            assert_eq!(shell.role(), Some(Role::Search));

            // Expand, type a query, and pick a result.
            window.click(search_element("shell"), cx);
            window.render_frame(cx);
            let panel = window.find(search_element("panel"));
            assert_eq!(panel.role(), Some(Role::ListBox));
        });

        // Type "doc" via the query Input's state.
        cx.update(|window, cx| {
            // The query Input is reachable through its own element id.
            window.click(search_element("shell"), cx);
        });
        assert_eq!(events.borrow().as_slice(), Vec::<String>::new().as_slice());

        // Disabled swallows the expand.
        view.update(cx, |host, cx| {
            host.disabled = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(search_element("shell"), cx);
            window.render_frame(cx);
            assert!(window.try_find(search_element("panel")).is_none());
        });
    }
}