Skip to main content

gpui_material_extras/search/presentation/
view.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, EntityInputHandler, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
6    Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_components::{
10    Icon, IconButton, IconName, ListItem, LoadingIndicator, Text, TextField, TextFieldState,
11};
12use gpui_material_foundation::{Surface, current_material_theme};
13use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, TypeRole};
14
15use super::{
16    SearchMotion, SearchPopupOptions, SearchStyle, SearchViewVariant, SearchWindowOptions, length,
17    valid_dimension,
18};
19use crate::search::{Results, SearchOutcome, SearchResult, SearchState, SearchValue};
20
21type InputBuilder = Box<dyn FnOnce(TextField) -> AnyElement>;
22type RowBuilder = Rc<dyn Fn(ListItem, &SearchResult, &mut Window, &mut App) -> ListItem>;
23type ResultBuilder = Box<dyn FnOnce(&Entity<SearchState>, &mut Window, &mut App) -> AnyElement>;
24
25/// Expanded Material search editor and result region, also usable as an independent view.
26#[derive(IntoElement)]
27pub struct SearchView {
28    id: ElementId,
29    pub(super) label: SharedString,
30    pub(super) state: Entity<SearchState>,
31    pub(super) variant: SearchViewVariant,
32    pub(super) close_label: SharedString,
33    loading_label: SharedString,
34    empty_label: SharedString,
35    prompt: SharedString,
36    input: Option<InputBuilder>,
37    filters: Option<AnyElement>,
38    row: Option<RowBuilder>,
39    result_content: Option<ResultBuilder>,
40    pub(super) focused_width: Option<Pixels>,
41    docked_dimensions: (Pixels, Pixels),
42    gap: Pixels,
43    pub(super) style: SearchStyle,
44    pub(super) motion: SearchMotion,
45    pub(super) popup: SearchPopupOptions,
46    pub(super) window: SearchWindowOptions,
47}
48
49impl SearchView {
50    /// Creates an expanded search view bound to `state` with default English status labels.
51    pub fn new(
52        id: impl Into<ElementId>,
53        label: impl Into<SharedString>,
54        state: &Entity<SearchState>,
55    ) -> Self {
56        Self {
57            id: id.into(),
58            label: label.into(),
59            state: state.clone(),
60            variant: SearchViewVariant::default(),
61            close_label: "Close search".into(),
62            loading_label: "Searching".into(),
63            empty_label: "No results".into(),
64            prompt: "Enter a search term".into(),
65            input: None,
66            filters: None,
67            row: None,
68            result_content: None,
69            focused_width: None,
70            docked_dimensions: (px(440.), px(424.)),
71            gap: px(0.),
72            style: SearchStyle::default(),
73            motion: SearchMotion::default(),
74            popup: SearchPopupOptions::default(),
75            window: SearchWindowOptions::default(),
76        }
77    }
78
79    /// Sets the presentation variant (`Docked`, `FullScreen`, or `FullScreenContained`).
80    pub fn variant(mut self, variant: SearchViewVariant) -> Self {
81        self.variant = variant;
82        self
83    }
84
85    /// Overrides the close-button label and the loading, empty-result, and idle prompt messages.
86    pub fn labels(
87        mut self,
88        close: SharedString,
89        loading: SharedString,
90        empty: SharedString,
91        prompt: SharedString,
92    ) -> Self {
93        self.close_label = close;
94        self.loading_label = loading;
95        self.empty_label = empty;
96        self.prompt = prompt;
97        self
98    }
99
100    /// Configures the editor. Keep the provided field in the returned content.
101    pub fn input<E: IntoElement + 'static>(
102        mut self,
103        build: impl FnOnce(TextField) -> E + 'static,
104    ) -> Self {
105        self.input = Some(Box::new(move |field| build(field).into_any_element()));
106        self
107    }
108
109    /// Places a filter bar or chip row directly above the search results list.
110    pub fn filters(mut self, content: impl IntoElement) -> Self {
111        self.filters = Some(content.into_any_element());
112        self
113    }
114
115    /// Decorates a provider row. Search installs the stable ID's focus and selection after this callback.
116    pub fn result_row(
117        mut self,
118        build: impl Fn(ListItem, &SearchResult, &mut Window, &mut App) -> ListItem + 'static,
119    ) -> Self {
120        self.row = Some(Rc::new(build));
121        self
122    }
123
124    /// Takes over the entire result region while still using the SearchState provider.
125    pub fn result_content<E: IntoElement + 'static>(
126        mut self,
127        build: impl FnOnce(&Entity<SearchState>, &mut Window, &mut App) -> E + 'static,
128    ) -> Self {
129        self.result_content = Some(Box::new(move |state, window, cx| {
130            build(state, window, cx).into_any_element()
131        }));
132        self
133    }
134
135    /// Sets the maximum width of the search input editor in logical pixels.
136    pub fn focused_width(mut self, width: Pixels) -> Self {
137        self.focused_width = valid_dimension(width);
138        self
139    }
140
141    /// Sets the preferred width and height of the docked popup panel. Defaults to `440px x 424px`.
142    pub fn docked_size(mut self, width: Pixels, height: Pixels) -> Self {
143        self.docked_dimensions = (
144            valid_dimension(width).unwrap_or(px(440.)),
145            valid_dimension(height).unwrap_or(px(424.)),
146        );
147        self
148    }
149
150    /// Adds a vertical gap between the input header and results surface in [`SearchViewVariant::Docked`].
151    pub fn result_gap(mut self, gap: Pixels) -> Self {
152        self.gap = length(gap);
153        self
154    }
155
156    /// Applies visual style overrides to the search view surfaces and editor.
157    pub fn style(mut self, style: SearchStyle) -> Self {
158        self.style = style;
159        self
160    }
161
162    /// Configures expand and collapse transition durations.
163    pub fn motion(mut self, motion: SearchMotion) -> Self {
164        self.motion = motion;
165        self
166    }
167
168    /// Configures popup anchoring, dismissal, focus trapping, and scrim for [`SearchViewVariant::Docked`].
169    pub fn popup_options(mut self, options: SearchPopupOptions) -> Self {
170        self.popup = options;
171        self
172    }
173
174    /// Configures overlay insets, dismissal, and scrim for full-screen variants.
175    pub fn window_options(mut self, options: SearchWindowOptions) -> Self {
176        self.window = options;
177        self
178    }
179
180    fn render_input_region(
181        &mut self,
182        editor: &Entity<TextFieldState>,
183        editor_width: Option<Pixels>,
184        direction: Direction,
185        duration: Duration,
186    ) -> impl IntoElement + use<> {
187        let close = self.state.clone();
188        let down_state = self.state.clone();
189        let down_editor = editor.clone();
190        let field = TextField::new((self.id.clone(), "editor"), self.label.clone(), editor)
191            .when_some(self.style.input_colors, TextField::colors);
192        let field = match self.input.take() {
193            Some(builder) => builder(field),
194            None => field.into_any_element(),
195        };
196        div()
197            .id((self.id.clone(), "input-region"))
198            .test_support()
199            .flex()
200            .flex_none()
201            .items_center()
202            .p_2()
203            .gap_2()
204            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
205            .child(
206                IconButton::new(
207                    (self.id.clone(), "close-search"),
208                    self.close_label.clone(),
209                    Icon::new(IconName::Close),
210                )
211                .on_activate(move |window, cx| {
212                    dismiss_search(&close, duration, window, cx);
213                }),
214            )
215            .child(
216                div()
217                    .flex_1()
218                    .min_w_0()
219                    .when_some(editor_width, |editor, width| editor.max_w(width))
220                    .capture_key_down(move |event, window, cx| {
221                        if event.keystroke.key != "down" || event.keystroke.modifiers.modified() {
222                            return;
223                        }
224                        if down_editor.update(cx, |input, cx| {
225                            input.marked_text_range(window, cx).is_some()
226                        }) {
227                            return;
228                        }
229                        let target = {
230                            let model = down_state.read(cx);
231                            model.rows().first().and_then(|row| {
232                                model
233                                    .result_focus
234                                    .get(&row.id)
235                                    .cloned()
236                                    .map(|focus| (row.id.clone(), focus, model.scroll.clone()))
237                            })
238                        };
239                        if let Some((first_id, focus, scroll)) = target {
240                            if scroll.bounds_for_item(0).is_some() {
241                                scroll.scroll_to_reveal_item(0);
242                            } else {
243                                scroll.scroll_to(gpui::ListOffset {
244                                    item_ix: 0,
245                                    offset_in_item: px(0.),
246                                });
247                            }
248                            down_state.update(cx, |state, _| {
249                                state.active_result = Some(first_id);
250                            });
251                            focus.focus(window, cx);
252                            window.refresh();
253                            cx.stop_propagation();
254                        }
255                    })
256                    .child(field),
257            )
258    }
259
260    fn render_results_region(
261        &mut self,
262        duration: Duration,
263        window: &mut Window,
264        cx: &mut App,
265    ) -> impl IntoElement + use<> {
266        let mut results = div()
267            .id((self.id.clone(), "results"))
268            .test_support()
269            .occlude()
270            .flex()
271            .flex_col()
272            .flex_1()
273            .min_h_0()
274            .overflow_hidden()
275            .children(
276                self.style
277                    .divider
278                    .map(|color| div().flex_none().h(px(1.)).bg(color)),
279            )
280            .children(
281                self.filters
282                    .take()
283                    .map(|filters| div().id("filters").flex_none().child(filters)),
284            );
285        if let Some(builder) = self.result_content.take() {
286            results = results.child(builder(&self.state, window, cx));
287        } else {
288            let status = status_info(
289                self.state.read(cx),
290                &self.prompt,
291                &self.loading_label,
292                &self.empty_label,
293            );
294            if let Some((message, loading, error)) = status {
295                results = results.child(search_status(&self.id, message, loading, error));
296            } else {
297                results = results.child(provider_results(
298                    &self.id,
299                    &self.state,
300                    self.row.take(),
301                    duration,
302                    window,
303                    cx,
304                ));
305            }
306        }
307        results
308    }
309}
310
311impl RenderOnce for SearchView {
312    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
313        let theme = current_material_theme(window, cx);
314        let rem_size = window.rem_size();
315        let font_revision = gpui_material_foundation::font_cache_revision(cx);
316        let (needs_animation, needs_layout) = {
317            let state = self.state.read(cx);
318            let needs_layout = match &state.result_layout {
319                Some((typography, cached_rem, cached_rev)) => {
320                    *cached_rem != rem_size
321                        || *cached_rev != font_revision
322                        || *typography != theme.typography
323                }
324                None => true,
325            };
326            (state.is_animating(), needs_layout)
327        };
328        let animate = if needs_animation || needs_layout {
329            let measurement =
330                needs_layout.then(|| (theme.typography.clone(), rem_size, font_revision));
331            self.state.update(cx, |state, cx| {
332                let animate = state.sample_animation(window, cx);
333                if let Some(measurement) = measurement {
334                    state.result_layout = Some(measurement);
335                    state.invalidate_result_measurements();
336                }
337                animate
338            })
339        } else {
340            false
341        };
342        if animate && window.is_visible() {
343            window.request_animation_frame();
344        }
345        let model = self.state.read(cx);
346        let progress = if model.presented() {
347            model.progress()
348        } else {
349            1.
350        };
351        let editor = model.input.clone();
352        let layout = theme.layout;
353        let direction = layout.direction;
354        let size = window.viewport_size();
355        let docked = self.variant == SearchViewVariant::Docked;
356        let contained = self.variant == SearchViewVariant::FullScreenContained;
357        let split = docked && (self.gap > px(0.) || self.style.results_shape.is_some());
358        let geometry = self.window.insets;
359        let (left, right) = layout.horizontal(length(geometry.left), length(geometry.right));
360        let width = if docked {
361            self.docked_dimensions
362                .0
363                .min((size.width - px(16.)).max(px(0.)))
364        } else {
365            (size.width - left - right).max(px(0.))
366        };
367        let height = if docked {
368            self.docked_dimensions.1.min(size.height * 0.65)
369        } else {
370            (size.height - length(geometry.top) - length(geometry.bottom)).max(px(0.))
371        };
372        let editor_limit = if contained {
373            (width - px(24.)).max(px(0.))
374        } else {
375            width
376        };
377        let editor_width = self
378            .focused_width
379            .or(contained.then_some(px(720.)))
380            .map(|width| width.min(editor_limit));
381        let dismiss = self.state.clone();
382        let duration = self.motion.collapse;
383        let close_on_escape = if docked {
384            self.popup.dismiss_on_escape
385        } else {
386            self.window.dismiss_on_escape
387        };
388
389        let input = self.render_input_region(&editor, editor_width, direction, duration);
390        let results = self.render_results_region(duration, window, cx);
391
392        let panel = panel_surface(self.style, docked, false).w(width).h(height);
393        let panel = if split {
394            div()
395                .flex()
396                .flex_col()
397                .w(width)
398                .h(height)
399                .child(panel_surface(self.style, true, false).child(input))
400                .child(div().flex_none().h(self.gap.min(height * 0.35)))
401                .child(
402                    panel_surface(self.style, true, true)
403                        .flex_1()
404                        .min_h_0()
405                        .child(results),
406                )
407                .into_any_element()
408        } else {
409            panel
410                .child(if contained {
411                    div()
412                        .flex()
413                        .justify_center()
414                        .p_3()
415                        .child(
416                            panel_surface(self.style, false, false)
417                                .shape(self.style.shape.unwrap_or(CornerShape::Full))
418                                .w(editor_width.unwrap_or(width))
419                                .child(input),
420                        )
421                        .into_any_element()
422                } else {
423                    input.into_any_element()
424                })
425                .child(results)
426                .into_any_element()
427        };
428        div()
429            .id(self.id)
430            .test_support()
431            .when(!docked, |view| {
432                view.pl(left)
433                    .pr(right)
434                    .pt(length(geometry.top))
435                    .pb(length(geometry.bottom))
436            })
437            .opacity(progress)
438            .capture_key_down(move |event, window, cx| {
439                if event.keystroke.key == "escape"
440                    && close_on_escape
441                    && dismiss_search(&dismiss, duration, window, cx)
442                {
443                    cx.stop_propagation();
444                }
445            })
446            .child(panel)
447    }
448}
449
450fn panel_surface(style: SearchStyle, docked: bool, results: bool) -> Surface {
451    Surface::new(ColorRole::SurfaceContainerHigh)
452        .flex()
453        .flex_col()
454        .when_some(style.container, Surface::container_color)
455        .when_some(style.content, Surface::content_color)
456        .when_some(
457            if results {
458                style.results_shape.or(style.shape)
459            } else {
460                style.shape
461            }
462            .or(docked.then_some(CornerShape::Radii([28.; 4]))),
463            Surface::shape,
464        )
465        .when_some(style.tonal_elevation, Surface::tonal_elevation)
466        .when_some(
467            style
468                .shadow_elevation
469                .or(docked.then_some(Elevation::Level3)),
470            Surface::shadow_elevation,
471        )
472}
473
474fn status_info(
475    model: &SearchState,
476    prompt: &SharedString,
477    loading: &SharedString,
478    empty: &SharedString,
479) -> Option<(SharedString, bool, bool)> {
480    match &model.response.results {
481        Results::Idle => Some((prompt.clone(), false, false)),
482        Results::Loading => Some((loading.clone(), true, false)),
483        Results::Ready(SearchOutcome::Error(error)) => Some((error.clone(), false, true)),
484        Results::Ready(SearchOutcome::Results(results)) if results.is_empty() => {
485            Some((empty.clone(), false, false))
486        }
487        Results::Ready(SearchOutcome::Results(_)) => None,
488    }
489}
490
491fn search_status(
492    id: &ElementId,
493    message: SharedString,
494    loading: bool,
495    error: bool,
496) -> impl IntoElement + use<> {
497    div()
498        .id((id.clone(), "search-status"))
499        .test_support()
500        .role(if error { Role::Alert } else { Role::Status })
501        .aria_label(message.clone())
502        .a11y_synthetic_children(move |tree| {
503            let node = tree.parent_node();
504            node.set_live(if error {
505                gpui::accesskit::Live::Assertive
506            } else {
507                gpui::accesskit::Live::Polite
508            });
509            node.set_live_atomic();
510        })
511        .p_4()
512        .flex()
513        .items_center()
514        .gap_3()
515        .when(loading, |status| {
516            status.child(LoadingIndicator::new("search-loading", message.clone()))
517        })
518        .child(Text::new(message).role(TypeRole::BodyMedium))
519}
520
521fn provider_results(
522    id: &ElementId,
523    state: &Entity<SearchState>,
524    custom_row: Option<RowBuilder>,
525    duration: Duration,
526    window: &Window,
527    cx: &App,
528) -> impl IntoElement + use<> {
529    let model = state.read(cx);
530    let scroll = model.scroll.clone();
531    let results_scope = model.results_scope.clone();
532    let entry = scroll.logical_scroll_top().item_ix;
533    let roving = results_scope.contains_focused(window, cx)
534        || model
535            .active_result
536            .as_ref()
537            .and_then(|id| model.result_focus.get(id))
538            .is_some_and(|focus| focus.is_focused(window));
539    let in_overlay = model.presented();
540    let keys = state.clone();
541    let row_state = state.clone();
542    div()
543        .id((id.clone(), "result-list"))
544        .role(Role::List)
545        .track_focus(&results_scope)
546        .flex_1()
547        .min_h_0()
548        .overflow_hidden()
549        .on_key_down(move |event, window, cx| {
550            if event.keystroke.modifiers.modified() {
551                return;
552            }
553            let (next_id, focus) = {
554                let model = keys.read(cx);
555                let rows = model.rows();
556                if rows.is_empty() {
557                    return;
558                }
559                let Some(current) = model
560                    .active_result
561                    .as_ref()
562                    .and_then(|id| {
563                        model
564                            .result_focus
565                            .get(id)
566                            .filter(|focus| focus.is_focused(window))
567                            .and_then(|_| rows.iter().position(|row| &row.id == id))
568                    })
569                    .or_else(|| {
570                        rows.iter()
571                            .position(|row| model.result_focus[&row.id].is_focused(window))
572                    })
573                else {
574                    return;
575                };
576                let next = match event.keystroke.key.as_str() {
577                    "up" => (current + rows.len() - 1) % rows.len(),
578                    "down" => (current + 1) % rows.len(),
579                    "home" => 0,
580                    "end" => rows.len() - 1,
581                    _ => return,
582                };
583                let next_id = rows[next].id.clone();
584                let focus = model.result_focus[&next_id].clone();
585                if model.scroll.bounds_for_item(next).is_some() {
586                    model.scroll.scroll_to_reveal_item(next);
587                } else {
588                    model.scroll.scroll_to(gpui::ListOffset {
589                        item_ix: next,
590                        offset_in_item: px(0.),
591                    });
592                }
593                (next_id, focus)
594            };
595            keys.update(cx, |state, _| {
596                state.active_result = Some(next_id);
597            });
598            focus.focus(window, cx);
599            window.refresh();
600            cx.stop_propagation();
601        })
602        .child(
603            gpui::list(scroll, move |index, window, cx| {
604                let model = row_state.read(cx);
605                let Some(result) = model.rows().get(index).cloned() else {
606                    return div().into_any_element();
607                };
608                let focus = model.result_focus[&result.id].clone();
609                let group = result.group.clone().filter(|group| {
610                    index == 0 || model.rows()[index - 1].group.as_ref() != Some(group)
611                });
612                let tab_stop = focus.is_focused(window) || index == entry && !roving;
613                let row = ListItem::new(result.id.clone(), result.label.clone())
614                    .when_some(result.supporting.clone(), ListItem::supporting_text)
615                    .when_some(result.icon, |item, icon| {
616                        item.leading(Icon::new(icon).size(px(24.)))
617                    });
618                let row = match &custom_row {
619                    Some(builder) => builder(row, &result, window, cx),
620                    None => row,
621                };
622                let state = row_state.clone();
623                let cell_id = (result.id.clone(), "search-result-cell");
624                let row = row
625                    .track_focus(&focus, tab_stop)
626                    .on_activate(move |window, cx| {
627                        state.update(cx, |state, cx| {
628                            if !in_overlay || state.is_open() {
629                                state.select_with_motion(result.clone(), duration, window, cx);
630                            }
631                        });
632                    });
633                div()
634                    .id(cell_id)
635                    .children(group.map(|group| {
636                        div()
637                            .id("search-group-title")
638                            .test_support()
639                            .role(Role::Heading)
640                            .aria_label(group.clone())
641                            .px_4()
642                            .pt_3()
643                            .child(Text::new(group).role(TypeRole::LabelMedium))
644                    }))
645                    .child(row)
646                    .into_any_element()
647            })
648            .size_full(),
649        )
650}
651
652pub(super) fn dismiss_search(
653    state: &Entity<SearchState>,
654    duration: Duration,
655    window: &mut Window,
656    cx: &mut App,
657) -> bool {
658    state.update(cx, |state, cx| {
659        let composing = state.input.update(cx, |input, cx| {
660            input.marked_text_range(window, cx).is_some()
661        });
662        if !composing {
663            state.animate_to(SearchValue::Collapsed, duration, window, cx);
664        }
665        !composing
666    })
667}