Skip to main content

gpui_material_extras/search/presentation/
bar.rs

1use std::{cell::Cell, rc::Rc, time::Duration};
2
3use gpui::{
4    Anchor, AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString, Size,
6    StatefulInteractiveElement, Styled, Window, canvas, deferred, div, point,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::{Dialog, FocusTrapElement, Popup, Positioner, TestSupportExt};
10use gpui_material_components::{
11    ButtonVariant, ControlSize, Icon, IconName, button_composition::ButtonPart,
12};
13use gpui_material_foundation::{Scrim, ThemeScope, current_material_theme, logical_anchor};
14use gpui_material_theme::Direction;
15
16use super::{
17    SearchMotion, SearchScrim, SearchStyle, SearchView, SearchViewVariant, length, valid_dimension,
18    view::dismiss_search,
19};
20use crate::search::{SearchScrollState, SearchState, SearchValue};
21
22/// A Material search entry that can occupy the existing AppBar search slot.
23#[derive(IntoElement)]
24pub struct SearchBar {
25    id: ElementId,
26    view: SearchView,
27    collapsed_width: Option<Pixels>,
28    leading: Option<AnyElement>,
29    trailing: Option<AnyElement>,
30    trigger_content: Option<AnyElement>,
31    track_focus: Option<FocusHandle>,
32    scroll: Option<Entity<SearchScrollState>>,
33    linked_scroll: Option<ScrollHandle>,
34}
35
36impl SearchBar {
37    /// Creates a search bar trigger paired with an expandable [`SearchView`] backed by `state`.
38    pub fn new(
39        id: impl Into<ElementId>,
40        label: impl Into<SharedString>,
41        state: &Entity<SearchState>,
42    ) -> Self {
43        let id = id.into();
44        Self {
45            view: SearchView::new((id.clone(), "search-view"), label, state),
46            id,
47            collapsed_width: None,
48            leading: None,
49            trailing: None,
50            trigger_content: None,
51            track_focus: None,
52            scroll: None,
53            linked_scroll: None,
54        }
55    }
56
57    /// Sets the expanded search view's presentation variant (`Docked`, `FullScreen`, or `FullScreenContained`).
58    pub fn variant(mut self, variant: SearchViewVariant) -> Self {
59        self.view.variant = variant;
60        self
61    }
62
63    /// Sets localized accessibility and status labels for closing, loading, empty results, and idle prompt.
64    pub fn labels(
65        mut self,
66        close: impl Into<SharedString>,
67        loading: impl Into<SharedString>,
68        empty: impl Into<SharedString>,
69        prompt: impl Into<SharedString>,
70    ) -> Self {
71        self.view = self
72            .view
73            .labels(close.into(), loading.into(), empty.into(), prompt.into());
74        self
75    }
76
77    /// Applies explicit widths to the trigger and its focused editor.
78    pub fn widths(mut self, collapsed: Pixels, focused: Pixels) -> Self {
79        self.collapsed_width = valid_dimension(collapsed);
80        self.view.focused_width = valid_dimension(focused);
81        self
82    }
83
84    /// Places a leading slot element before the search trigger button.
85    pub fn leading(mut self, element: impl IntoElement) -> Self {
86        self.leading = Some(element.into_any_element());
87        self
88    }
89
90    /// Places a trailing slot element after the search trigger button.
91    pub fn trailing(mut self, element: impl IntoElement) -> Self {
92        self.trailing = Some(element.into_any_element());
93        self
94    }
95
96    /// Replaces the visible content inside the trigger button while retaining its accessible label.
97    pub fn trigger_content(mut self, element: impl IntoElement) -> Self {
98        self.trigger_content = Some(element.into_any_element());
99        self
100    }
101
102    /// Applies visual style overrides to both the trigger and the expanded search view.
103    pub fn style(mut self, style: SearchStyle) -> Self {
104        self.view.style = style;
105        self
106    }
107
108    /// Configures expand and collapse animation durations.
109    pub fn motion(mut self, motion: SearchMotion) -> Self {
110        self.view.motion = motion;
111        self
112    }
113
114    /// Customizes the inner [`SearchView`] directly via a builder closure.
115    pub fn expanded_view(mut self, configure: impl FnOnce(SearchView) -> SearchView) -> Self {
116        self.view = configure(self.view);
117        self
118    }
119
120    /// Connects a [`SearchScrollState`] to hide and reveal the collapsed bar on scroll.
121    pub fn scroll_behavior(mut self, state: &Entity<SearchScrollState>) -> Self {
122        self.scroll = Some(state.clone());
123        self
124    }
125
126    /// Links a GPUI [`ScrollHandle`] whose vertical offset drives [`Self::scroll_behavior`].
127    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
128        self.linked_scroll = Some(handle.clone());
129        self
130    }
131
132    /// Attaches a caller-owned focus handle to the search bar trigger button.
133    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
134        self.track_focus = Some(focus.clone());
135        self
136    }
137}
138
139impl RenderOnce for SearchBar {
140    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
141        let mut view = self.view;
142        let state = view.state.clone();
143        if state.read(cx).is_animating()
144            && state.update(cx, |model, cx| model.sample_animation(window, cx))
145            && window.is_visible()
146        {
147            window.request_animation_frame();
148        }
149        view.sampled_in_bar = true;
150        let model = state.read(cx);
151        let focus = self.track_focus.unwrap_or_else(|| model.trigger.clone());
152        let scope = model.scope.clone();
153        let visible = model.presented();
154        let focused = focus.is_focused(window);
155        let progress = model.progress();
156        let label = if model.query.is_empty() {
157            view.label.clone()
158        } else {
159            model.query.clone()
160        };
161        let theme = current_material_theme(window, cx);
162        let direction = theme.layout.direction;
163        let default_height = px(theme.layout.density.interactive_size(56.));
164        let viewport = window.viewport_size();
165        let size_limit = (viewport.width - px(16.)).max(px(1.));
166        let width = match (self.collapsed_width, view.focused_width) {
167            (Some(rest), Some(active)) if visible => Some(rest + (active - rest) * progress),
168            (_, Some(active)) if focused => Some(active),
169            (rest, _) => rest,
170        };
171        let id: ElementId = (self.id.clone(), "search-trigger").into();
172        let button = match width {
173            Some(width) => ButtonPart::new(id, label, width.min(size_limit)),
174            None => ButtonPart::intrinsic(id, label),
175        };
176        let open = state.clone();
177        let trigger_focus = focus.clone();
178        let motion = view.motion;
179        let button = button
180            .track_focus(&focus)
181            .size(ControlSize::Medium)
182            .variant(ButtonVariant::FilledTonal)
183            .leading_icon(Icon::new(IconName::Search))
184            .when_some(view.style.trigger_shapes, ButtonPart::shapes)
185            .when_some(view.style.trigger_colors, ButtonPart::colors)
186            .when_some(self.trigger_content, ButtonPart::content)
187            .on_activate(move |window, cx| {
188                trigger_focus.focus(window, cx);
189                open.update(cx, |state, cx| {
190                    state.animate_to(SearchValue::Expanded, motion.expand, window, cx)
191                });
192            });
193        let trigger = div()
194            .id((self.id.clone(), "trigger-slots"))
195            .flex()
196            .items_center()
197            .gap_2()
198            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
199            .children(
200                self.leading
201                    .map(|element| div().id((self.id.clone(), "leading")).child(element)),
202            )
203            .child(button)
204            .children(
205                self.trailing
206                    .map(|element| div().id((self.id.clone(), "trailing")).child(element)),
207            );
208
209        if !visible {
210            return match self.scroll {
211                Some(scroll) => scroll_trigger(
212                    self.id,
213                    trigger,
214                    scroll,
215                    self.linked_scroll,
216                    default_height,
217                    focused,
218                    window,
219                    cx,
220                ),
221                None => trigger.into_any_element(),
222            };
223        }
224        if let Some(scroll) = self.scroll {
225            scroll.update(cx, |scroll, _| {
226                scroll.measure(
227                    self.linked_scroll.as_ref().map(|handle| -handle.offset().y),
228                    default_height,
229                    true,
230                );
231            });
232        }
233
234        match view.variant {
235            SearchViewVariant::Docked => render_docked_overlay(
236                self.id, trigger, view, state, scope, direction, viewport, progress, window, cx,
237            ),
238            SearchViewVariant::FullScreen | SearchViewVariant::FullScreenContained => {
239                render_fullscreen_overlay(
240                    self.id, trigger, view, state, scope, progress, window, cx,
241                )
242            }
243        }
244    }
245}
246
247#[allow(clippy::too_many_arguments)]
248fn render_docked_overlay(
249    id: ElementId,
250    trigger: impl IntoElement,
251    view: SearchView,
252    state: Entity<SearchState>,
253    scope: FocusHandle,
254    direction: Direction,
255    viewport: Size<Pixels>,
256    progress: f32,
257    window: &mut Window,
258    cx: &mut App,
259) -> AnyElement {
260    let label = view.label.clone();
261    let close_label = view.close_label.clone();
262    let motion = view.motion;
263    let options = view.popup;
264    let outside = state.clone();
265    let mount = div()
266        .id((id.clone(), "docked-search"))
267        .role(Role::Dialog)
268        .aria_label(label)
269        .track_focus(&scope)
270        .occlude()
271        .when(
272            options.dismiss_on_outside && options.scrim.is_none(),
273            |dock| {
274                dock.on_mouse_down_out(move |_, window, cx| {
275                    dismiss_search(&outside, motion.collapse, window, cx);
276                })
277            },
278        )
279        .child(view);
280    let trap = options.trap_focus || options.scrim.is_some();
281    let content = if trap {
282        let focus = window
283            .use_keyed_state((id.clone(), "dock-trap"), cx, |_, cx| {
284                cx.focus_handle().tab_stop(false)
285            })
286            .read(cx)
287            .clone();
288        mount
289            .focus_trap((id.clone(), "docked-search-trap"), &focus)
290            .into_any_element()
291    } else {
292        mount.into_any_element()
293    };
294    let popup = Popup::new(id.clone(), trigger)
295        .anchor(logical_anchor(options.logical_anchor, direction))
296        .offset(length(options.offset))
297        .content(ThemeScope::inherit(content, window, cx));
298    div()
299        .relative()
300        .children(options.scrim.map(|style| {
301            let backdrop = backdrop(
302                id,
303                style,
304                close_label,
305                progress,
306                options.dismiss_on_outside,
307                state,
308                motion.collapse,
309            );
310            deferred(
311                Positioner::corner(Anchor::TopLeft, point(px(0.), px(0.)))
312                    .margin(px(0.))
313                    .occlude()
314                    .child(
315                        div()
316                            .relative()
317                            .w(viewport.width)
318                            .h(viewport.height)
319                            .child(ThemeScope::inherit(backdrop, window, cx)),
320                    ),
321            )
322            .with_priority(99)
323        }))
324        .child(popup)
325        .into_any_element()
326}
327
328#[allow(clippy::too_many_arguments)]
329fn render_fullscreen_overlay(
330    id: ElementId,
331    trigger: impl IntoElement,
332    view: SearchView,
333    state: Entity<SearchState>,
334    scope: FocusHandle,
335    progress: f32,
336    window: &mut Window,
337    cx: &mut App,
338) -> AnyElement {
339    let label = view.label.clone();
340    let close_label = view.close_label.clone();
341    let motion = view.motion;
342    let options = view.window;
343    let insets = options.insets;
344    let exposed = [insets.left, insets.right, insets.top, insets.bottom]
345        .into_iter()
346        .any(|inset| length(inset) > px(0.));
347    let backdrop = backdrop(
348        id,
349        options.scrim,
350        close_label,
351        progress,
352        options.dismiss_on_outside && exposed,
353        state.clone(),
354        motion.collapse,
355    );
356    div()
357        .child(trigger)
358        .child(
359            Dialog::new(cx)
360                .accessibility_label(label)
361                .focus_handle(scope)
362                .close_on_backdrop_press(false)
363                .backdrop(ThemeScope::inherit(backdrop, window, cx))
364                .on_ok(|_, _, _| false)
365                .on_cancel(move |_, window, cx| {
366                    if options.dismiss_on_escape {
367                        dismiss_search(&state, motion.collapse, window, cx);
368                    }
369                    false
370                })
371                .popup(ThemeScope::inherit(view, window, cx)),
372        )
373        .into_any_element()
374}
375
376fn backdrop(
377    id: ElementId,
378    style: SearchScrim,
379    label: SharedString,
380    progress: f32,
381    dismissible: bool,
382    state: Entity<SearchState>,
383    duration: Duration,
384) -> impl IntoElement {
385    let opacity = if style.opacity.is_nan() {
386        0.32
387    } else {
388        style.opacity.clamp(0., 1.)
389    };
390    Scrim::new((id, "search-scrim"))
391        .opacity(opacity * progress)
392        .when_some(style.color, Scrim::color)
393        .when(dismissible, |scrim| {
394            scrim
395                .accessibility_label(label)
396                .on_click(move |window, cx| {
397                    dismiss_search(&state, duration, window, cx);
398                })
399        })
400}
401
402#[allow(clippy::too_many_arguments)]
403fn scroll_trigger(
404    id: ElementId,
405    trigger: impl IntoElement,
406    state: Entity<SearchScrollState>,
407    linked: Option<ScrollHandle>,
408    default_height: Pixels,
409    held_open: bool,
410    window: &mut Window,
411    cx: &mut App,
412) -> AnyElement {
413    let size = window
414        .use_keyed_state((id.clone(), "search-scroll-height"), cx, |_, _| {
415            Rc::new(Cell::new(default_height))
416        })
417        .read(cx)
418        .clone();
419    let linked_offset = linked.as_ref().map(|handle| -handle.offset().y);
420    let distance = state.update(cx, |state, _| {
421        state.measure(linked_offset, size.get(), held_open)
422    });
423    div()
424        .id((id, "search-scroll"))
425        .test_support()
426        .relative()
427        .h(size.get() - distance)
428        .overflow_hidden()
429        .child(
430            div().relative().top(-distance).child(trigger).child(
431                canvas(
432                    move |bounds, window, _| {
433                        if size.replace(bounds.size.height) != bounds.size.height
434                            || linked
435                                .as_ref()
436                                .is_some_and(|handle| Some(-handle.offset().y) != linked_offset)
437                        {
438                            window.refresh();
439                        }
440                    },
441                    |_, _, _, _| {},
442                )
443                .absolute()
444                .inset_0(),
445            ),
446        )
447        .into_any_element()
448}