Skip to main content

gpui_material_extras/
search.rs

1use std::{collections::HashMap, time::Duration};
2
3use gpui::{
4    App, AppContext, Context, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle,
5    Focusable, ListAlignment, ListState, SharedString, Subscription, Window, px,
6};
7use gpui_base::motion::Easing;
8use gpui_material_components::{IconName, TextFieldEvent, TextFieldState};
9use gpui_material_foundation::RetargetTransition;
10
11mod presentation;
12mod scroll;
13
14pub use presentation::{
15    SearchBar, SearchMotion, SearchPopupOptions, SearchScrim, SearchStyle, SearchView,
16    SearchViewVariant, SearchWindowOptions,
17};
18pub use scroll::SearchScrollState;
19
20/// Identifies one committed query. Complete requests through [SearchState::complete].
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct SearchRequest {
23    revision: u64,
24    query: SharedString,
25}
26
27impl SearchRequest {
28    /// Returns the query string associated with this search request.
29    pub fn query(&self) -> &SharedString {
30        &self.query
31    }
32}
33
34/// A result row whose ID remains stable when results reorder.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct SearchResult {
37    id: ElementId,
38    label: SharedString,
39    supporting: Option<SharedString>,
40    group: Option<SharedString>,
41    icon: Option<IconName>,
42}
43
44impl SearchResult {
45    /// Creates a search result with a stable element `id` and primary `label`.
46    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
47        Self {
48            id: id.into(),
49            label: label.into(),
50            supporting: None,
51            group: None,
52            icon: None,
53        }
54    }
55
56    /// Sets secondary supporting text displayed beneath the primary label.
57    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
58        self.supporting = Some(text.into());
59        self
60    }
61
62    /// Groups consecutive rows under this heading.
63    pub fn group(mut self, heading: impl Into<SharedString>) -> Self {
64        self.group = Some(heading.into());
65        self
66    }
67
68    /// Sets an optional leading icon for this result row.
69    pub fn icon(mut self, icon: IconName) -> Self {
70        self.icon = Some(icon);
71        self
72    }
73
74    /// Returns the group heading assigned to this result, if any.
75    pub fn group_label(&self) -> Option<&SharedString> {
76        self.group.as_ref()
77    }
78
79    /// Returns the stable element identifier of this result row.
80    pub fn id(&self) -> &ElementId {
81        &self.id
82    }
83
84    /// Returns the primary display label of this result row.
85    pub fn label(&self) -> &SharedString {
86        &self.label
87    }
88}
89
90/// Result from the application's search provider.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub enum SearchOutcome {
93    /// Search completed with the supplied ordered list of results (possibly empty).
94    Results(Vec<SearchResult>),
95    /// Search failed with a localized error message shown in an alert status region.
96    Error(SharedString),
97}
98
99/// Search providers subscribe to requests. Submissions and result selection
100/// are separate commands and the application owns their consequences.
101#[derive(Clone, Debug)]
102pub enum SearchEvent {
103    /// Emitted when the non-empty query changes and needs asynchronous resolution.
104    Request(SearchRequest),
105    /// Emitted when the user presses Enter with a non-empty query.
106    Submit(SharedString),
107    /// Emitted when the user activates a [`SearchResult`] row.
108    Select(SearchResult),
109}
110
111enum Results {
112    Idle,
113    Loading,
114    Ready(SearchOutcome),
115}
116
117struct SearchResponse {
118    revision: u64,
119    pending: Option<SearchRequest>,
120    results: Results,
121}
122
123impl Default for SearchResponse {
124    fn default() -> Self {
125        Self {
126            revision: 0,
127            pending: None,
128            results: Results::Idle,
129        }
130    }
131}
132
133impl SearchResponse {
134    fn begin(&mut self, query: SharedString) -> Option<SearchRequest> {
135        self.revision = self
136            .revision
137            .checked_add(1)
138            .expect("search revision exhausted");
139        self.pending = (!query.trim().is_empty()).then_some(SearchRequest {
140            revision: self.revision,
141            query,
142        });
143        self.results = if self.pending.is_some() {
144            Results::Loading
145        } else {
146            Results::Idle
147        };
148        self.pending.clone()
149    }
150
151    fn finish(&mut self, request: &SearchRequest, outcome: SearchOutcome) -> bool {
152        if self.pending.as_ref() != Some(request) {
153            return false;
154        }
155        self.pending = None;
156        self.results = Results::Ready(outcome);
157        true
158    }
159}
160
161/// Expansion endpoint of a [`SearchState`] presentation.
162#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
163pub enum SearchValue {
164    /// Search view is dismissed and only the collapsed trigger is visible.
165    #[default]
166    Collapsed,
167    /// Search view is presented and ready for query editing and result selection.
168    Expanded,
169}
170
171impl SearchValue {
172    fn progress(self) -> f32 {
173        match self {
174            Self::Collapsed => 0.,
175            Self::Expanded => 1.,
176        }
177    }
178}
179
180/// Retains editing, IME, result and focus state while the search view expands.
181/// The application performs asynchronous work and owns resulting navigation.
182pub struct SearchState {
183    input: Entity<TextFieldState>,
184    trigger: FocusHandle,
185    scope: FocusHandle,
186    results_scope: FocusHandle,
187    restore: Option<FocusHandle>,
188    scroll: ListState,
189    result_focus: HashMap<ElementId, FocusHandle>,
190    active_result: Option<ElementId>,
191    result_layout: Option<(gpui_material_theme::Typography, gpui::Pixels, u64)>,
192    query: SharedString,
193    response: SearchResponse,
194    target: SearchValue,
195    progress: f32,
196    animation: RetargetTransition,
197    _input: Subscription,
198}
199
200impl EventEmitter<SearchEvent> for SearchState {}
201
202impl SearchState {
203    /// Creates a collapsed search state with an owned [`TextFieldState`] editor.
204    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
205        let input = cx.new(|cx| TextFieldState::new(window, cx));
206        Self::with_editor(&input, window, cx)
207    }
208
209    /// Uses an editor created for this window while retaining the search provider contract.
210    pub fn with_editor(
211        input: &Entity<TextFieldState>,
212        window: &mut Window,
213        cx: &mut Context<Self>,
214    ) -> Self {
215        let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
216            if !state.is_open()
217                || !matches!(
218                    event,
219                    TextFieldEvent::Change
220                        | TextFieldEvent::PressEnter {
221                            secondary: false,
222                            shift: false
223                        }
224                )
225            {
226                return;
227            }
228            if input.update(cx, |input, cx| {
229                input.marked_text_range(window, cx).is_some()
230            }) {
231                return;
232            }
233            let query = input.read(cx).value();
234            state.update_query(query.clone(), cx);
235            if matches!(event, TextFieldEvent::PressEnter { .. }) && !query.trim().is_empty() {
236                cx.emit(SearchEvent::Submit(query));
237            }
238        });
239        Self {
240            input: input.clone(),
241            trigger: cx.focus_handle(),
242            scope: cx.focus_handle(),
243            results_scope: cx.focus_handle().tab_stop(false),
244            restore: None,
245            scroll: ListState::new(0, ListAlignment::Top, px(100.)),
246            result_focus: HashMap::new(),
247            active_result: None,
248            result_layout: None,
249            query: "".into(),
250            response: SearchResponse::default(),
251            target: SearchValue::Collapsed,
252            progress: 0.,
253            animation: RetargetTransition::settled(0.),
254            _input: subscription,
255        }
256    }
257
258    /// Returns the latest committed query text.
259    pub fn query(&self) -> &SharedString {
260        &self.query
261    }
262
263    /// Returns `true` when the target state is [`SearchValue::Expanded`].
264    pub fn is_open(&self) -> bool {
265        self.target == SearchValue::Expanded
266    }
267
268    /// Returns the currently displayed state derived from [`Self::progress`].
269    pub fn current_value(&self) -> SearchValue {
270        if self.progress <= 0.02 {
271            SearchValue::Collapsed
272        } else {
273            SearchValue::Expanded
274        }
275    }
276
277    /// Returns the target endpoint ([`SearchValue::Collapsed`] or [`SearchValue::Expanded`]).
278    pub fn target_value(&self) -> SearchValue {
279        self.target
280    }
281
282    /// Returns the current expansion fraction in `0.0..=1.0`.
283    pub fn progress(&self) -> f32 {
284        self.progress
285    }
286
287    /// Returns whether an expand or collapse transition is currently animating.
288    pub fn is_animating(&self) -> bool {
289        self.animation.is_animating()
290    }
291
292    /// Returns the retained [`TextFieldState`] backing the search input.
293    pub fn editor(&self) -> &Entity<TextFieldState> {
294        &self.input
295    }
296
297    /// Returns the stable focus handle of the expanded editor.
298    pub fn input_focus(&self, cx: &App) -> FocusHandle {
299        self.input.read(cx).focus_handle(cx)
300    }
301
302    /// Returns the retained default focus handle of the search trigger.
303    pub fn trigger_focus(&self) -> &FocusHandle {
304        &self.trigger
305    }
306
307    /// Opens the view and focuses its editor immediately.
308    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
309        self.snap_to(1., window, cx);
310    }
311
312    /// Dismisses the view and restores its entry focus immediately.
313    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
314        self.snap_to(0., window, cx);
315    }
316
317    /// Positions the presentation at a fraction from collapsed to expanded.
318    pub fn snap_to(&mut self, fraction: f32, window: &mut Window, cx: &mut Context<Self>) {
319        if !fraction.is_finite() {
320            return;
321        }
322        let fraction = fraction.clamp(0., 1.);
323        if fraction == self.progress && !self.animation.is_animating() {
324            return;
325        }
326        if fraction > 0. {
327            self.prepare_open(window, cx);
328        } else {
329            self.target = SearchValue::Collapsed;
330            self.restore_focus(window, cx);
331        }
332        self.animation.snap_to(fraction);
333        self.progress = fraction;
334        cx.notify();
335    }
336
337    /// Animates to an endpoint. Retargeting uses the currently displayed fraction.
338    pub fn animate_to(
339        &mut self,
340        target: SearchValue,
341        duration: Duration,
342        window: &mut Window,
343        cx: &mut Context<Self>,
344    ) {
345        if duration.is_zero() || cx.reduce_motion() {
346            self.snap_to(target.progress(), window, cx);
347            return;
348        }
349        self.sample_animation(window, cx);
350        if target == self.target
351            && (self.animation.is_animating() || self.progress == target.progress())
352        {
353            return;
354        }
355        if target == SearchValue::Expanded {
356            self.prepare_open(window, cx);
357        }
358        self.target = target;
359        let now = cx.background_executor().now();
360        self.animation
361            .animate_to(target.progress(), duration, Easing::EaseInOut, now, false);
362        self.progress = self.animation.value();
363        if !self.animation.is_animating() && target == SearchValue::Collapsed {
364            self.restore_focus(window, cx);
365        }
366        cx.notify();
367    }
368
369    /// Returns the latest completed [`SearchOutcome`], or `None` while idle or loading.
370    pub fn results(&self) -> Option<&SearchOutcome> {
371        match &self.response.results {
372            Results::Ready(outcome) => Some(outcome),
373            _ => None,
374        }
375    }
376
377    /// Selects a caller-rendered result and dismisses using the retained focus path.
378    pub fn select_result(
379        &mut self,
380        result: SearchResult,
381        window: &mut Window,
382        cx: &mut Context<Self>,
383    ) {
384        self.select_with_motion(result, Duration::ZERO, window, cx);
385    }
386
387    fn select_with_motion(
388        &mut self,
389        result: SearchResult,
390        duration: Duration,
391        window: &mut Window,
392        cx: &mut Context<Self>,
393    ) {
394        self.animate_to(SearchValue::Collapsed, duration, window, cx);
395        cx.emit(SearchEvent::Select(result));
396    }
397
398    /// Returns the virtualized [`ListState`] used to scroll search results.
399    pub fn scroll_state(&self) -> &ListState {
400        &self.scroll
401    }
402
403    /// Uses a caller-owned virtual result viewport.
404    pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
405        self.scroll = scroll.clone();
406        self.invalidate_result_measurements();
407        cx.notify();
408    }
409
410    fn presented(&self) -> bool {
411        self.is_open() || self.animation.is_animating()
412    }
413
414    fn prepare_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
415        if self.is_open() {
416            return;
417        }
418        if self.restore.is_none() {
419            self.restore = window.focused(cx).or_else(|| Some(self.trigger.clone()));
420        }
421        self.target = SearchValue::Expanded;
422        self.input_focus(cx).focus(window, cx);
423        if self.input.update(cx, |input, cx| {
424            input.marked_text_range(window, cx).is_none()
425        }) {
426            let query = self.input.read(cx).value();
427            self.update_query(query, cx);
428        }
429    }
430
431    fn restore_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
432        if let Some(focus) = self.restore.take() {
433            focus.focus(window, cx);
434        }
435    }
436
437    fn sample_animation(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
438        if !self.animation.is_animating() {
439            return false;
440        }
441        let now = cx.background_executor().now();
442        let old = self.progress;
443        let (value, running) = self.animation.sample(now, cx.reduce_motion());
444        self.progress = value;
445        if !running {
446            if self.target == SearchValue::Collapsed {
447                self.restore_focus(window, cx);
448            }
449            cx.notify();
450            false
451        } else {
452            if old != self.progress {
453                cx.notify();
454            }
455            true
456        }
457    }
458
459    /// Synchronizes the query from the application. Query changes issue a
460    /// request, followed by the normal completion path.
461    pub fn set_query(
462        &mut self,
463        query: impl Into<SharedString>,
464        window: &mut Window,
465        cx: &mut Context<Self>,
466    ) {
467        let query = query.into();
468        self.input.update(cx, |input, cx| {
469            if input.value() != query {
470                input.set_value(query.clone(), window, cx);
471            }
472        });
473        self.update_query(query, cx);
474    }
475
476    /// Accepts only the latest pending request. Returns false for superseded
477    /// requests and duplicate completions.
478    pub fn complete(
479        &mut self,
480        request: &SearchRequest,
481        outcome: SearchOutcome,
482        cx: &mut Context<Self>,
483    ) -> bool {
484        let accepted = self.response.finish(request, outcome);
485        if accepted {
486            self.sync_result_focus(cx);
487            cx.notify();
488        }
489        accepted
490    }
491
492    fn update_query(&mut self, query: SharedString, cx: &mut Context<Self>) {
493        if query == self.query {
494            return;
495        }
496        self.query = query.clone();
497        if let Some(request) = self.response.begin(query) {
498            cx.emit(SearchEvent::Request(request));
499        } else {
500            self.result_focus.clear();
501            self.active_result = None;
502            self.scroll
503                .splice_focusable(0..self.scroll.item_count(), std::iter::empty());
504        }
505        self.scroll.reset(0);
506        cx.notify();
507    }
508
509    fn rows(&self) -> &[SearchResult] {
510        match &self.response.results {
511            Results::Ready(SearchOutcome::Results(rows)) => rows,
512            _ => &[],
513        }
514    }
515
516    fn sync_result_focus(&mut self, cx: &App) {
517        let mut previous = std::mem::take(&mut self.result_focus);
518        self.result_focus = self
519            .rows()
520            .iter()
521            .map(|row| {
522                let focus = previous
523                    .remove(&row.id)
524                    .unwrap_or_else(|| cx.focus_handle());
525                (row.id.clone(), focus)
526            })
527            .collect();
528        if self
529            .active_result
530            .as_ref()
531            .is_some_and(|id| !self.result_focus.contains_key(id))
532        {
533            self.active_result = None;
534        }
535        self.invalidate_result_measurements();
536    }
537
538    fn invalidate_result_measurements(&self) {
539        let mut anchor = self.scroll.logical_scroll_top();
540        anchor.item_ix = anchor.item_ix.min(self.rows().len().saturating_sub(1));
541        // Focus metadata keeps the focused row mounted when it scrolls out of
542        // view; keyboard navigation still addresses the complete result model.
543        self.scroll.splice_focusable(
544            0..self.scroll.item_count(),
545            self.rows()
546                .iter()
547                .map(|row| self.result_focus.get(&row.id).cloned()),
548        );
549        self.scroll.scroll_to(anchor);
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    #[test]
558    fn query_revision_rejects_stale_duplicate_and_cleared_results() {
559        let mut state = SearchResponse::default();
560        let first = state.begin("alpha".into()).unwrap();
561        let second = state.begin("beta".into()).unwrap();
562        assert_eq!(second.query(), "beta");
563        assert!(!state.finish(&first, SearchOutcome::Error("stale".into())));
564        assert!(state.finish(&second, SearchOutcome::Results(vec![])));
565        assert!(!state.finish(&second, SearchOutcome::Error("duplicate".into())));
566        let third = state.begin("alpha".into()).unwrap();
567        assert!(state.begin(" ".into()).is_none());
568        assert!(!state.finish(&third, SearchOutcome::Error("cleared".into())));
569        assert!(matches!(state.results, Results::Idle));
570    }
571
572    #[cfg(feature = "test-support")]
573    #[gpui::test]
574    fn clearing_query_to_idle_releases_result_focus_handles(cx: &mut gpui::TestAppContext) {
575        use std::{cell::RefCell, rc::Rc};
576
577        use gpui::{IntoElement, Render, WindowOptions, div};
578        use gpui_material_foundation::MaterialRoot;
579        use gpui_material_theme::MaterialTheme;
580
581        struct Empty;
582        impl Render for Empty {
583            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
584                div()
585            }
586        }
587
588        let latest = Rc::new(RefCell::new(None::<SearchRequest>));
589        let mut search_state = None;
590        let window = cx
591            .update(|cx| {
592                MaterialRoot::init(MaterialTheme::default(), cx);
593                gpui_material_components::init_components(cx);
594                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
595                    let state = cx.new(|cx| SearchState::new(window, cx));
596                    let capture = latest.clone();
597                    cx.subscribe(&state, move |_, event, _| {
598                        if let SearchEvent::Request(request) = event {
599                            capture.replace(Some(request.clone()));
600                        }
601                    })
602                    .detach();
603                    search_state = Some(state);
604                    cx.new(|_| Empty)
605                })
606                .unwrap()
607            })
608            .into();
609        let state = search_state.unwrap();
610        cx.update_window(window, |_, window, cx| {
611            state.update(cx, |state, cx| {
612                state.set_query("design", window, cx);
613            });
614        })
615        .unwrap();
616        let request = latest.borrow().clone().unwrap();
617        cx.update(|cx| {
618            state.update(cx, |state, cx| {
619                let rows = vec![
620                    SearchResult::new("row-1", "Row 1"),
621                    SearchResult::new("row-2", "Row 2"),
622                ];
623                assert!(state.complete(&request, SearchOutcome::Results(rows), cx));
624                assert_eq!(state.result_focus.len(), 2);
625                assert_eq!(state.scroll.item_count(), 2);
626            });
627        });
628        cx.update_window(window, |_, window, cx| {
629            state.update(cx, |state, cx| {
630                state.set_query("", window, cx);
631                assert!(matches!(state.response.results, Results::Idle));
632                assert!(state.result_focus.is_empty());
633                assert!(state.active_result.is_none());
634                assert_eq!(state.scroll.item_count(), 0);
635            });
636        })
637        .unwrap();
638    }
639}