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_material_components::{IconName, TextFieldEvent, TextFieldState};
8use gpui_material_foundation::RetargetTransition;
9use gpui_material_theme::CubicBezier;
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    last_sampled: Option<gpui_material_foundation::Instant>,
198    _input: Subscription,
199}
200
201impl EventEmitter<SearchEvent> for SearchState {}
202
203impl SearchState {
204    /// Creates a collapsed search state with an owned [`TextFieldState`] editor.
205    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
206        let input = cx.new(|cx| TextFieldState::new(window, cx));
207        Self::with_editor(&input, window, cx)
208    }
209
210    /// Uses an editor created for this window while retaining the search provider contract.
211    pub fn with_editor(
212        input: &Entity<TextFieldState>,
213        window: &mut Window,
214        cx: &mut Context<Self>,
215    ) -> Self {
216        let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
217            if !state.is_open()
218                || !matches!(
219                    event,
220                    TextFieldEvent::Change
221                        | TextFieldEvent::PressEnter {
222                            secondary: false,
223                            shift: false
224                        }
225                )
226            {
227                return;
228            }
229            if input.update(cx, |input, cx| {
230                input.marked_text_range(window, cx).is_some()
231            }) {
232                return;
233            }
234            let query = input.read(cx).value();
235            state.update_query(query.clone(), cx);
236            if matches!(event, TextFieldEvent::PressEnter { .. }) && !query.trim().is_empty() {
237                cx.emit(SearchEvent::Submit(query));
238            }
239        });
240        Self {
241            input: input.clone(),
242            trigger: cx.focus_handle(),
243            scope: cx.focus_handle(),
244            results_scope: cx.focus_handle().tab_stop(false),
245            restore: None,
246            scroll: ListState::new(0, ListAlignment::Top, px(100.)),
247            result_focus: HashMap::new(),
248            active_result: None,
249            result_layout: None,
250            query: "".into(),
251            response: SearchResponse::default(),
252            target: SearchValue::Collapsed,
253            progress: 0.,
254            animation: RetargetTransition::settled(0.),
255            last_sampled: None,
256            _input: subscription,
257        }
258    }
259
260    /// Returns the latest committed query text.
261    pub fn query(&self) -> &SharedString {
262        &self.query
263    }
264
265    /// Returns `true` when the target state is [`SearchValue::Expanded`].
266    pub fn is_open(&self) -> bool {
267        self.target == SearchValue::Expanded
268    }
269
270    /// Returns the currently displayed state derived from [`Self::progress`].
271    pub fn current_value(&self) -> SearchValue {
272        if self.progress <= 0.02 {
273            SearchValue::Collapsed
274        } else {
275            SearchValue::Expanded
276        }
277    }
278
279    /// Returns the target endpoint ([`SearchValue::Collapsed`] or [`SearchValue::Expanded`]).
280    pub fn target_value(&self) -> SearchValue {
281        self.target
282    }
283
284    /// Returns the current expansion fraction in `0.0..=1.0`.
285    pub fn progress(&self) -> f32 {
286        self.progress
287    }
288
289    /// Returns whether an expand or collapse transition is currently animating.
290    pub fn is_animating(&self) -> bool {
291        self.animation.is_animating()
292    }
293
294    /// Returns the retained [`TextFieldState`] backing the search input.
295    pub fn editor(&self) -> &Entity<TextFieldState> {
296        &self.input
297    }
298
299    /// Returns the stable focus handle of the expanded editor.
300    pub fn input_focus(&self, cx: &App) -> FocusHandle {
301        self.input.read(cx).focus_handle(cx)
302    }
303
304    /// Returns the retained default focus handle of the search trigger.
305    pub fn trigger_focus(&self) -> &FocusHandle {
306        &self.trigger
307    }
308
309    /// Opens the view and focuses its editor immediately.
310    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
311        self.snap_to(1., window, cx);
312    }
313
314    /// Dismisses the view and restores its entry focus immediately.
315    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316        self.snap_to(0., window, cx);
317    }
318
319    /// Positions the presentation at a fraction from collapsed to expanded.
320    pub fn snap_to(&mut self, fraction: f32, window: &mut Window, cx: &mut Context<Self>) {
321        if !fraction.is_finite() {
322            return;
323        }
324        let fraction = fraction.clamp(0., 1.);
325        if fraction == self.progress && !self.animation.is_animating() {
326            return;
327        }
328        if fraction > 0. {
329            self.prepare_open(window, cx);
330        } else {
331            self.target = SearchValue::Collapsed;
332            self.restore_focus(window, cx);
333        }
334        self.animation.snap_to(fraction);
335        self.progress = fraction;
336        self.last_sampled = None;
337        cx.notify();
338    }
339
340    /// Animates to an endpoint. Retargeting uses the currently displayed fraction.
341    pub fn animate_to(
342        &mut self,
343        target: SearchValue,
344        duration: Duration,
345        window: &mut Window,
346        cx: &mut Context<Self>,
347    ) {
348        if duration.is_zero() || cx.reduce_motion() {
349            self.snap_to(target.progress(), window, cx);
350            return;
351        }
352        self.sample_animation(window, cx);
353        if target == self.target
354            && (self.animation.is_animating() || self.progress == target.progress())
355        {
356            return;
357        }
358        if target == SearchValue::Expanded {
359            self.prepare_open(window, cx);
360        }
361        self.target = target;
362        let now = cx.background_executor().now();
363        self.animation.animate_to(
364            target.progress(),
365            duration,
366            CubicBezier::EASE_IN_OUT,
367            now,
368            false,
369        );
370        self.progress = self.animation.value();
371        self.last_sampled = None;
372        if !self.animation.is_animating() && target == SearchValue::Collapsed {
373            self.restore_focus(window, cx);
374        }
375        cx.notify();
376    }
377
378    /// Returns the latest completed [`SearchOutcome`], or `None` while idle or loading.
379    pub fn results(&self) -> Option<&SearchOutcome> {
380        match &self.response.results {
381            Results::Ready(outcome) => Some(outcome),
382            _ => None,
383        }
384    }
385
386    /// Selects a caller-rendered result and dismisses using the retained focus path.
387    pub fn select_result(
388        &mut self,
389        result: SearchResult,
390        window: &mut Window,
391        cx: &mut Context<Self>,
392    ) {
393        self.select_with_motion(result, Duration::ZERO, window, cx);
394    }
395
396    fn select_with_motion(
397        &mut self,
398        result: SearchResult,
399        duration: Duration,
400        window: &mut Window,
401        cx: &mut Context<Self>,
402    ) {
403        self.animate_to(SearchValue::Collapsed, duration, window, cx);
404        cx.emit(SearchEvent::Select(result));
405    }
406
407    /// Returns the virtualized [`ListState`] used to scroll search results.
408    pub fn scroll_state(&self) -> &ListState {
409        &self.scroll
410    }
411
412    /// Uses a caller-owned virtual result viewport.
413    pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
414        self.scroll = scroll.clone();
415        self.invalidate_result_measurements();
416        cx.notify();
417    }
418
419    fn presented(&self) -> bool {
420        self.is_open() || self.animation.is_animating()
421    }
422
423    fn prepare_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
424        if self.is_open() {
425            return;
426        }
427        if self.restore.is_none() {
428            self.restore = window.focused(cx).or_else(|| Some(self.trigger.clone()));
429        }
430        self.target = SearchValue::Expanded;
431        self.input_focus(cx).focus(window, cx);
432        if self.input.update(cx, |input, cx| {
433            input.marked_text_range(window, cx).is_none()
434        }) {
435            let query = self.input.read(cx).value();
436            self.update_query(query, cx);
437        }
438    }
439
440    fn restore_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
441        if let Some(focus) = self.restore.take() {
442            focus.focus(window, cx);
443        }
444    }
445
446    fn sample_animation(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
447        if !self.animation.is_animating() {
448            return false;
449        }
450        let now = cx.background_executor().now();
451        if self.last_sampled == Some(now) {
452            return false;
453        }
454        self.last_sampled = Some(now);
455        let old = self.progress;
456        let (value, running) = self.animation.sample(now, cx.reduce_motion());
457        self.progress = value;
458        if !running {
459            if self.target == SearchValue::Collapsed {
460                self.restore_focus(window, cx);
461            }
462            cx.notify();
463            false
464        } else {
465            if old != self.progress {
466                cx.notify();
467            }
468            true
469        }
470    }
471
472    /// Synchronizes the query from the application. Query changes issue a
473    /// request, followed by the normal completion path.
474    pub fn set_query(
475        &mut self,
476        query: impl Into<SharedString>,
477        window: &mut Window,
478        cx: &mut Context<Self>,
479    ) {
480        let query = query.into();
481        self.input.update(cx, |input, cx| {
482            if input.value() != query {
483                input.set_value(query.clone(), window, cx);
484            }
485        });
486        self.update_query(query, cx);
487    }
488
489    /// Accepts only the latest pending request. Returns false for superseded
490    /// requests and duplicate completions.
491    pub fn complete(
492        &mut self,
493        request: &SearchRequest,
494        outcome: SearchOutcome,
495        cx: &mut Context<Self>,
496    ) -> bool {
497        let accepted = self.response.finish(request, outcome);
498        if accepted {
499            self.sync_result_focus(cx);
500            cx.notify();
501        }
502        accepted
503    }
504
505    fn update_query(&mut self, query: SharedString, cx: &mut Context<Self>) {
506        if query == self.query {
507            return;
508        }
509        self.query = query.clone();
510        if let Some(request) = self.response.begin(query) {
511            cx.emit(SearchEvent::Request(request));
512        } else {
513            self.result_focus.clear();
514            self.active_result = None;
515            self.scroll
516                .splice_focusable(0..self.scroll.item_count(), std::iter::empty());
517        }
518        self.scroll.reset(0);
519        cx.notify();
520    }
521
522    fn rows(&self) -> &[SearchResult] {
523        match &self.response.results {
524            Results::Ready(SearchOutcome::Results(rows)) => rows,
525            _ => &[],
526        }
527    }
528
529    fn sync_result_focus(&mut self, cx: &App) {
530        let mut previous = std::mem::take(&mut self.result_focus);
531        self.result_focus = self
532            .rows()
533            .iter()
534            .map(|row| {
535                let focus = previous
536                    .remove(&row.id)
537                    .unwrap_or_else(|| cx.focus_handle());
538                (row.id.clone(), focus)
539            })
540            .collect();
541        if self
542            .active_result
543            .as_ref()
544            .is_some_and(|id| !self.result_focus.contains_key(id))
545        {
546            self.active_result = None;
547        }
548        self.invalidate_result_measurements();
549    }
550
551    fn invalidate_result_measurements(&self) {
552        let mut anchor = self.scroll.logical_scroll_top();
553        anchor.item_ix = anchor.item_ix.min(self.rows().len().saturating_sub(1));
554        // Focus metadata keeps the focused row mounted when it scrolls out of
555        // view; keyboard navigation still addresses the complete result model.
556        self.scroll.splice_focusable(
557            0..self.scroll.item_count(),
558            self.rows()
559                .iter()
560                .map(|row| self.result_focus.get(&row.id).cloned()),
561        );
562        self.scroll.scroll_to(anchor);
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    #[test]
571    fn query_revision_rejects_stale_duplicate_and_cleared_results() {
572        let mut state = SearchResponse::default();
573        let first = state.begin("alpha".into()).unwrap();
574        let second = state.begin("beta".into()).unwrap();
575        assert_eq!(second.query(), "beta");
576        assert!(!state.finish(&first, SearchOutcome::Error("stale".into())));
577        assert!(state.finish(&second, SearchOutcome::Results(vec![])));
578        assert!(!state.finish(&second, SearchOutcome::Error("duplicate".into())));
579        let third = state.begin("alpha".into()).unwrap();
580        assert!(state.begin(" ".into()).is_none());
581        assert!(!state.finish(&third, SearchOutcome::Error("cleared".into())));
582        assert!(matches!(state.results, Results::Idle));
583    }
584
585    #[cfg(feature = "test-support")]
586    #[gpui::test]
587    fn clearing_query_to_idle_releases_result_focus_handles(cx: &mut gpui::TestAppContext) {
588        use std::{cell::RefCell, rc::Rc};
589
590        use gpui::{IntoElement, Render, WindowOptions, div};
591        use gpui_material_foundation::MaterialRoot;
592        use gpui_material_theme::MaterialTheme;
593
594        struct Empty;
595        impl Render for Empty {
596            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
597                div()
598            }
599        }
600
601        let latest = Rc::new(RefCell::new(None::<SearchRequest>));
602        let mut search_state = None;
603        let window = cx
604            .update(|cx| {
605                MaterialRoot::init(MaterialTheme::default(), cx);
606                gpui_material_components::init_components(cx);
607                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
608                    let state = cx.new(|cx| SearchState::new(window, cx));
609                    let capture = latest.clone();
610                    cx.subscribe(&state, move |_, event, _| {
611                        if let SearchEvent::Request(request) = event {
612                            capture.replace(Some(request.clone()));
613                        }
614                    })
615                    .detach();
616                    search_state = Some(state);
617                    cx.new(|_| Empty)
618                })
619                .unwrap()
620            })
621            .into();
622        let state = search_state.unwrap();
623        cx.update_window(window, |_, window, cx| {
624            state.update(cx, |state, cx| {
625                state.set_query("design", window, cx);
626            });
627        })
628        .unwrap();
629        let request = latest.borrow().clone().unwrap();
630        cx.update(|cx| {
631            state.update(cx, |state, cx| {
632                let rows = vec![
633                    SearchResult::new("row-1", "Row 1"),
634                    SearchResult::new("row-2", "Row 2"),
635                ];
636                assert!(state.complete(&request, SearchOutcome::Results(rows), cx));
637                assert_eq!(state.result_focus.len(), 2);
638                assert_eq!(state.scroll.item_count(), 2);
639            });
640        });
641        cx.update_window(window, |_, window, cx| {
642            state.update(cx, |state, cx| {
643                state.set_query("", window, cx);
644                assert!(matches!(state.response.results, Results::Idle));
645                assert!(state.result_focus.is_empty());
646                assert!(state.active_result.is_none());
647                assert_eq!(state.scroll.item_count(), 0);
648            });
649        })
650        .unwrap();
651    }
652}