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 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        let model = state.read(cx);
150        let focus = self.track_focus.unwrap_or_else(|| model.trigger.clone());
151        let scope = model.scope.clone();
152        let visible = model.presented();
153        let focused = focus.is_focused(window);
154        let progress = model.progress();
155        let label = if model.query.is_empty() {
156            view.label.clone()
157        } else {
158            model.query.clone()
159        };
160        let theme = current_material_theme(window, cx);
161        let direction = theme.layout.direction;
162        let viewport = window.viewport_size();
163        let size_limit = (viewport.width - px(16.)).max(px(1.));
164        let width = match (self.collapsed_width, view.focused_width) {
165            (Some(rest), Some(active)) if visible => Some(rest + (active - rest) * progress),
166            (_, Some(active)) if focused => Some(active),
167            (rest, _) => rest,
168        };
169        let id: ElementId = (self.id.clone(), "search-trigger").into();
170        let button = match width {
171            Some(width) => ButtonPart::new(id, label, width.min(size_limit)),
172            None => ButtonPart::intrinsic(id, label),
173        };
174        let open = state.clone();
175        let trigger_focus = focus.clone();
176        let motion = view.motion;
177        let button = button
178            .track_focus(&focus)
179            .size(ControlSize::Medium)
180            .variant(ButtonVariant::FilledTonal)
181            .leading_icon(Icon::new(IconName::Search))
182            .when_some(view.style.trigger_shapes, ButtonPart::shapes)
183            .when_some(view.style.trigger_colors, ButtonPart::colors)
184            .when_some(self.trigger_content, ButtonPart::content)
185            .on_activate(move |window, cx| {
186                trigger_focus.focus(window, cx);
187                open.update(cx, |state, cx| {
188                    state.animate_to(SearchValue::Expanded, motion.expand, window, cx)
189                });
190            });
191        let trigger = div()
192            .id((self.id.clone(), "trigger-slots"))
193            .flex()
194            .items_center()
195            .gap_2()
196            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
197            .children(
198                self.leading
199                    .map(|element| div().id("leading").child(element)),
200            )
201            .child(button)
202            .children(
203                self.trailing
204                    .map(|element| div().id("trailing").child(element)),
205            );
206
207        if !visible {
208            return match self.scroll {
209                Some(scroll) => scroll_trigger(
210                    self.id,
211                    trigger,
212                    scroll,
213                    self.linked_scroll,
214                    focused,
215                    window,
216                    cx,
217                ),
218                None => trigger.into_any_element(),
219            };
220        }
221        if let Some(scroll) = self.scroll {
222            scroll.update(cx, |scroll, _| {
223                scroll.measure(
224                    self.linked_scroll.as_ref().map(|handle| -handle.offset().y),
225                    px(56.),
226                    true,
227                );
228            });
229        }
230
231        match view.variant {
232            SearchViewVariant::Docked => render_docked_overlay(
233                self.id, trigger, view, state, scope, direction, viewport, progress, window, cx,
234            ),
235            SearchViewVariant::FullScreen | SearchViewVariant::FullScreenContained => {
236                render_fullscreen_overlay(
237                    self.id, trigger, view, state, scope, progress, window, cx,
238                )
239            }
240        }
241    }
242}
243
244#[allow(clippy::too_many_arguments)]
245fn render_docked_overlay(
246    id: ElementId,
247    trigger: impl IntoElement,
248    view: SearchView,
249    state: Entity<SearchState>,
250    scope: FocusHandle,
251    direction: Direction,
252    viewport: Size<Pixels>,
253    progress: f32,
254    window: &mut Window,
255    cx: &mut App,
256) -> AnyElement {
257    let label = view.label.clone();
258    let close_label = view.close_label.clone();
259    let motion = view.motion;
260    let options = view.popup;
261    let outside = state.clone();
262    let mount = div()
263        .id("docked-search")
264        .role(Role::Dialog)
265        .aria_label(label)
266        .track_focus(&scope)
267        .occlude()
268        .when(
269            options.dismiss_on_outside && options.scrim.is_none(),
270            |dock| {
271                dock.on_mouse_down_out(move |_, window, cx| {
272                    dismiss_search(&outside, motion.collapse, window, cx);
273                })
274            },
275        )
276        .child(view);
277    let trap = options.trap_focus || options.scrim.is_some();
278    let content = if trap {
279        let focus = window
280            .use_keyed_state((id.clone(), "dock-trap"), cx, |_, cx| {
281                cx.focus_handle().tab_stop(false)
282            })
283            .read(cx)
284            .clone();
285        mount.focus_trap("docked-search", &focus).into_any_element()
286    } else {
287        mount.into_any_element()
288    };
289    let popup = Popup::new(id.clone(), trigger)
290        .anchor(logical_anchor(options.logical_anchor, direction))
291        .offset(length(options.offset))
292        .content(ThemeScope::inherit(content, window, cx));
293    div()
294        .relative()
295        .children(options.scrim.map(|style| {
296            let backdrop = backdrop(
297                id,
298                style,
299                close_label,
300                progress,
301                options.dismiss_on_outside,
302                state,
303                motion.collapse,
304            );
305            deferred(
306                Positioner::corner(Anchor::TopLeft, point(px(0.), px(0.)))
307                    .margin(px(0.))
308                    .occlude()
309                    .child(
310                        div()
311                            .relative()
312                            .w(viewport.width)
313                            .h(viewport.height)
314                            .child(ThemeScope::inherit(backdrop, window, cx)),
315                    ),
316            )
317            .with_priority(99)
318        }))
319        .child(popup)
320        .into_any_element()
321}
322
323#[allow(clippy::too_many_arguments)]
324fn render_fullscreen_overlay(
325    id: ElementId,
326    trigger: impl IntoElement,
327    view: SearchView,
328    state: Entity<SearchState>,
329    scope: FocusHandle,
330    progress: f32,
331    window: &mut Window,
332    cx: &mut App,
333) -> AnyElement {
334    let label = view.label.clone();
335    let close_label = view.close_label.clone();
336    let motion = view.motion;
337    let options = view.window;
338    let insets = options.insets;
339    let exposed = [insets.left, insets.right, insets.top, insets.bottom]
340        .into_iter()
341        .any(|inset| length(inset) > px(0.));
342    let backdrop = backdrop(
343        id,
344        options.scrim,
345        close_label,
346        progress,
347        options.dismiss_on_outside && exposed,
348        state.clone(),
349        motion.collapse,
350    );
351    div()
352        .child(trigger)
353        .child(
354            Dialog::new(cx)
355                .accessibility_label(label)
356                .focus_handle(scope)
357                .close_on_backdrop_press(false)
358                .backdrop(ThemeScope::inherit(backdrop, window, cx))
359                .on_ok(|_, _, _| false)
360                .on_cancel(move |_, window, cx| {
361                    if options.dismiss_on_escape {
362                        dismiss_search(&state, motion.collapse, window, cx);
363                    }
364                    false
365                })
366                .popup(ThemeScope::inherit(view, window, cx)),
367        )
368        .into_any_element()
369}
370
371fn backdrop(
372    id: ElementId,
373    style: SearchScrim,
374    label: SharedString,
375    progress: f32,
376    dismissible: bool,
377    state: Entity<SearchState>,
378    duration: Duration,
379) -> impl IntoElement {
380    let opacity = if style.opacity.is_nan() {
381        0.32
382    } else {
383        style.opacity.clamp(0., 1.)
384    };
385    Scrim::new((id, "search-scrim"))
386        .opacity(opacity * progress)
387        .when_some(style.color, Scrim::color)
388        .when(dismissible, |scrim| {
389            scrim
390                .accessibility_label(label)
391                .on_click(move |window, cx| {
392                    dismiss_search(&state, duration, window, cx);
393                })
394        })
395}
396
397fn scroll_trigger(
398    id: ElementId,
399    trigger: impl IntoElement,
400    state: Entity<SearchScrollState>,
401    linked: Option<ScrollHandle>,
402    held_open: bool,
403    window: &mut Window,
404    cx: &mut App,
405) -> AnyElement {
406    let size = window
407        .use_keyed_state((id.clone(), "search-scroll-height"), cx, |_, _| {
408            Rc::new(Cell::new(px(56.)))
409        })
410        .read(cx)
411        .clone();
412    let linked_offset = linked.as_ref().map(|handle| -handle.offset().y);
413    let distance = state.update(cx, |state, _| {
414        state.measure(linked_offset, size.get(), held_open)
415    });
416    div()
417        .id((id, "search-scroll"))
418        .test_support()
419        .relative()
420        .h(size.get() - distance)
421        .overflow_hidden()
422        .child(
423            div().relative().top(-distance).child(trigger).child(
424                canvas(
425                    move |bounds, window, _| {
426                        if size.replace(bounds.size.height) != bounds.size.height
427                            || linked
428                                .as_ref()
429                                .is_some_and(|handle| Some(-handle.offset().y) != linked_offset)
430                        {
431                            window.refresh();
432                        }
433                    },
434                    |_, _, _, _| {},
435                )
436                .absolute()
437                .inset_0(),
438            ),
439        )
440        .into_any_element()
441}