Skip to main content

gpui_material_components/navigation/app_bar/
actions.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, AvailableSpace, Bounds, ContentMask, Element, ElementId,
5    FocusHandle, GlobalElementId, Hsla, InspectorElementId, InteractiveElement, IntoElement,
6    LayoutId, ParentElement, Pixels, Point, RenderOnce, Role, SharedString, Size,
7    StatefulInteractiveElement, Style, Styled, Window, div, point, px, relative, size,
8};
9use gpui_base::Button;
10use gpui_material_foundation::{current_material_strings, current_material_theme};
11use gpui_material_theme::Direction;
12
13use crate::{
14    ButtonColors, IconButton, Menu, MenuItem,
15    navigation::overflow_strip::{OverflowMenuController, OverflowStripHandle},
16};
17
18const TRIGGER_SIZE: Pixels = px(48.);
19type OnActivate = Rc<dyn Fn(&mut Window, &mut App)>;
20type MenuItemBuilder = Box<dyn FnOnce(AppBarMenuState) -> MenuItem>;
21type OverflowIndicator = Box<dyn FnOnce(AppBarMenuState) -> AnyElement>;
22
23enum ItemContent {
24    Clickable {
25        label: SharedString,
26        icon: Rc<dyn Fn() -> AnyElement>,
27        on_activate: Option<OnActivate>,
28    },
29    Custom {
30        inline: AnyElement,
31        menu: MenuItemBuilder,
32    },
33}
34
35/// One action with an inline representation and an overflow menu representation.
36pub struct AppBarItem {
37    id: ElementId,
38    disabled: bool,
39    content: ItemContent,
40}
41
42impl AppBarItem {
43    /// Creates an icon button and a matching named menu command.
44    /// The icon factory may be called for either representation.
45    pub fn clickable<E: IntoElement>(
46        id: impl Into<ElementId>,
47        label: impl Into<SharedString>,
48        icon: impl Fn() -> E + 'static,
49    ) -> Self {
50        Self {
51            id: id.into(),
52            disabled: false,
53            content: ItemContent::Clickable {
54                label: label.into(),
55                icon: Rc::new(move || icon().into_any_element()),
56                on_activate: None,
57            },
58        }
59    }
60
61    /// Supplies an inline element and the corresponding Material menu item.
62    pub fn custom(
63        id: impl Into<ElementId>,
64        inline: impl IntoElement,
65        menu: impl FnOnce(AppBarMenuState) -> MenuItem + 'static,
66    ) -> Self {
67        Self {
68            id: id.into(),
69            disabled: false,
70            content: ItemContent::Custom {
71                inline: inline.into_any_element(),
72                menu: Box::new(menu),
73            },
74        }
75    }
76
77    /// Disables the action in both its inline and overflow menu representations.
78    pub fn disabled(mut self, disabled: bool) -> Self {
79        self.disabled = disabled;
80        self
81    }
82
83    /// Sets the activation callback for both representations of a clickable item.
84    pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
85        if let ItemContent::Clickable { on_activate, .. } = &mut self.content {
86            *on_activate = Some(Rc::new(action));
87        }
88        self
89    }
90
91    fn prepare(
92        self,
93        strip_id: &ElementId,
94        ink: Hsla,
95        window: &mut Window,
96        cx: &mut App,
97    ) -> Prepared {
98        let scoped_id: ElementId = (strip_id.clone(), self.id.to_string()).into();
99        let focus = window
100            .use_keyed_state((scoped_id.clone(), "app-bar-item"), cx, |_, cx| {
101                cx.focus_handle()
102            })
103            .read(cx)
104            .clone();
105        let (mut inline, menu) = match self.content {
106            ItemContent::Clickable {
107                label,
108                icon,
109                on_activate,
110            } => {
111                let mut inline = IconButton::new(scoped_id.clone(), label.clone(), icon())
112                    .colors(ButtonColors {
113                        content: Some(ink),
114                        ..Default::default()
115                    })
116                    .disabled(self.disabled)
117                    .track_focus(&focus);
118                if let Some(on_activate) = on_activate.clone() {
119                    inline = inline.on_activate(move |window, cx| on_activate(window, cx));
120                }
121                let menu_id = scoped_id.clone();
122                let disabled = self.disabled;
123                let menu = move |_| {
124                    let mut item = MenuItem::new(menu_id, label)
125                        .leading(move || icon())
126                        .disabled(disabled);
127                    if let Some(on_activate) = on_activate {
128                        item = item.on_activate(move |window, cx| on_activate(window, cx));
129                    }
130                    item
131                };
132                (inline.into_any_element(), Box::new(menu) as MenuItemBuilder)
133            }
134            ItemContent::Custom { inline, menu } => (
135                div()
136                    .id(scoped_id.clone())
137                    .track_focus(&focus)
138                    .child(inline)
139                    .into_any_element(),
140                menu,
141            ),
142        };
143        let preferred = inline.layout_as_root(
144            size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
145            window,
146            cx,
147        );
148        Prepared {
149            id: self.id,
150            inline,
151            menu: Some(menu),
152            focus,
153            preferred,
154            enabled: !self.disabled,
155        }
156    }
157}
158
159struct Prepared {
160    id: ElementId,
161    inline: AnyElement,
162    menu: Option<MenuItemBuilder>,
163    focus: FocusHandle,
164    preferred: Size<Pixels>,
165    enabled: bool,
166}
167
168/// Handle to the active strip's overflow menu, available to its item and trigger builders.
169#[derive(Clone)]
170pub struct AppBarMenuState {
171    controller: OverflowMenuController,
172}
173
174impl AppBarMenuState {
175    /// Returns whether the overflow menu is currently open.
176    pub fn is_showing(&self) -> bool {
177        self.controller.is_showing()
178    }
179
180    /// Opens the overflow menu if any items are currently overflowed.
181    pub fn show(&self, window: &mut Window, cx: &mut App) {
182        self.controller.show(window, cx);
183    }
184
185    /// Closes the overflow menu.
186    pub fn dismiss(&self, window: &mut Window, cx: &mut App) {
187        self.controller.dismiss(window, cx);
188    }
189
190    fn set(&self, shown: bool, window: &mut Window, cx: &mut App) {
191        self.controller.set(shown, window, cx);
192    }
193}
194
195struct Strip {
196    id: ElementId,
197    items: Vec<AppBarItem>,
198    label: Option<SharedString>,
199    overflow_label: Option<SharedString>,
200    overflow_indicator: Option<OverflowIndicator>,
201    max_item_count: usize,
202}
203
204impl Strip {
205    fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = AppBarItem>) -> Self {
206        Self {
207            id: id.into(),
208            items: items.into_iter().collect(),
209            label: None,
210            overflow_label: None,
211            overflow_indicator: None,
212            max_item_count: usize::MAX,
213        }
214    }
215}
216
217/// Horizontal actions with responsive overflow.
218#[derive(IntoElement)]
219pub struct AppBarRow(Strip);
220
221/// Vertical actions with responsive overflow.
222#[derive(IntoElement)]
223pub struct AppBarColumn(Strip);
224
225macro_rules! action_strip {
226    ($name:ident, $axis:expr) => {
227        impl $name {
228            /// Creates an action strip with the given element ID and items.
229            pub fn new(
230                id: impl Into<ElementId>,
231                items: impl IntoIterator<Item = AppBarItem>,
232            ) -> Self {
233                Self(Strip::new(id, items))
234            }
235
236            /// Sets the accessible label of the action strip toolbar (defaults to
237            /// [`gpui_material_theme::MaterialStrings::app_bar_actions`], `"App bar actions"`).
238            pub fn label(mut self, label: impl Into<SharedString>) -> Self {
239                self.0.label = Some(label.into());
240                self
241            }
242
243            /// Limits inline children, including the overflow trigger when it is needed.
244            pub fn max_item_count(mut self, count: usize) -> Self {
245                self.0.max_item_count = count.max(1);
246                self
247            }
248
249            /// Sets the accessible label of the overflow menu trigger button (defaults to
250            /// [`gpui_material_theme::MaterialStrings::more_actions`], `"More actions"`).
251            pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
252                self.0.overflow_label = Some(label.into());
253                self
254            }
255
256            /// Replaces the decorative content of the built-in overflow button.
257            pub fn overflow_indicator<E: IntoElement>(
258                mut self,
259                build: impl FnOnce(AppBarMenuState) -> E + 'static,
260            ) -> Self {
261                self.0.overflow_indicator =
262                    Some(Box::new(move |state| build(state).into_any_element()));
263                self
264            }
265        }
266
267        impl RenderOnce for $name {
268            fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
269                StripLayout::new(self.0, $axis, window, cx)
270            }
271        }
272    };
273}
274
275action_strip!(AppBarRow, Axis::Horizontal);
276action_strip!(AppBarColumn, Axis::Vertical);
277
278#[derive(Clone, Copy, PartialEq, Eq)]
279enum Axis {
280    Horizontal,
281    Vertical,
282}
283
284impl Axis {
285    fn extent(self, size: Size<Pixels>) -> Pixels {
286        match self {
287            Self::Horizontal => size.width,
288            Self::Vertical => size.height,
289        }
290    }
291
292    fn cross(self, size: Size<Pixels>) -> Pixels {
293        match self {
294            Self::Horizontal => size.height,
295            Self::Vertical => size.width,
296        }
297    }
298
299    fn size(self, extent: Pixels, cross: Pixels) -> Size<Pixels> {
300        match self {
301            Self::Horizontal => size(extent, cross),
302            Self::Vertical => size(cross, extent),
303        }
304    }
305
306    fn origin(
307        self,
308        bounds: Bounds<Pixels>,
309        child: Size<Pixels>,
310        offset: Pixels,
311        direction: Direction,
312    ) -> Point<Pixels> {
313        let delta = (self.cross(bounds.size) - self.cross(child)).max(px(0.)) / 2.;
314        match (self, direction) {
315            (Self::Horizontal, Direction::Rtl) => {
316                point(bounds.right() - offset - child.width, bounds.top() + delta)
317            }
318            (Self::Horizontal, Direction::Ltr) => {
319                point(bounds.left() + offset, bounds.top() + delta)
320            }
321            (Self::Vertical, _) => point(bounds.left() + delta, bounds.top() + offset),
322        }
323    }
324}
325
326struct StripLayout {
327    strip: Strip,
328    label: SharedString,
329    overflow_label: SharedString,
330    axis: Axis,
331    direction: Direction,
332    ink: Hsla,
333    overflow: OverflowStripHandle<ElementId>,
334}
335
336impl StripLayout {
337    fn new(mut strip: Strip, axis: Axis, window: &mut Window, cx: &mut App) -> Self {
338        let strings = current_material_strings(window, cx);
339        let label = strip
340            .label
341            .take()
342            .unwrap_or_else(|| SharedString::from(strings.app_bar_actions.clone()));
343        let overflow_label = strip
344            .overflow_label
345            .take()
346            .unwrap_or_else(|| SharedString::from(strings.more_actions.clone()));
347        drop(strings);
348        let overflow = OverflowStripHandle::use_state(&strip.id, "app-bar-overflow", window, cx);
349        Self {
350            strip,
351            label,
352            overflow_label,
353            axis,
354            direction: current_material_theme(window, cx).layout.direction,
355            ink: window.text_style().color,
356            overflow,
357        }
358    }
359
360    fn menu_state(&self) -> AppBarMenuState {
361        AppBarMenuState {
362            controller: self.overflow.controller.clone(),
363        }
364    }
365
366    fn transfer_focus(
367        &self,
368        shown: usize,
369        items: &[Prepared],
370        overflow: bool,
371        window: &mut Window,
372        cx: &mut App,
373    ) {
374        let hidden_focused = overflow.then(|| {
375            items[shown..]
376                .iter()
377                .find(|item| item.focus.contains_focused(window, cx))
378                .map(|item| (item.id.clone(), item.focus.clone()))
379        });
380        self.overflow.transfer_focus(
381            overflow,
382            hidden_focused.flatten(),
383            |id| {
384                items[..shown]
385                    .iter()
386                    .any(|item| item.enabled && item.id == *id)
387            },
388            || {
389                items[..shown]
390                    .iter()
391                    .find(|item| item.enabled)
392                    .map(|item| item.focus.clone())
393            },
394            window,
395            cx,
396        );
397    }
398
399    fn overflow_menu(&mut self, hidden: &mut [Prepared], size: Size<Pixels>) -> AnyElement {
400        let state = self.menu_state();
401        let entries: Vec<_> = hidden
402            .iter_mut()
403            .filter_map(|item| item.menu.take().map(|build| build(state.clone())))
404            .collect();
405        let trigger_focus = self.overflow.focus.clone();
406        let label = self.overflow_label.clone();
407        let trigger_id = ElementId::from((self.strip.id.clone(), "overflow"));
408        let ink = self.ink;
409        let glyph = self.strip.overflow_indicator.take().map_or_else(
410            || {
411                let unit = px(4.).min(size.width / 4.).min(size.height / 4.);
412                div()
413                    .flex()
414                    .flex_col()
415                    .gap(unit / 2.)
416                    .children((0..3).map(|_| div().size(unit).rounded_full().bg(ink)))
417                    .into_any_element()
418            },
419            |build| build(state.clone()),
420        );
421        let observed = state.clone();
422        Menu::composed(
423            (self.strip.id.clone(), "menu"),
424            entries,
425            move |_, toggle| {
426                let return_focus = trigger_focus.clone();
427                Button::new(trigger_id)
428                    .track_focus(&trigger_focus)
429                    .accessibility_label(label)
430                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
431                        return_focus.focus(window, cx);
432                        toggle(window, cx);
433                    })
434                    .w(size.width)
435                    .h(size.height)
436                    .p_0()
437                    .flex()
438                    .items_center()
439                    .justify_center()
440                    .overflow_hidden()
441                    .rounded_full()
442                    .text_color(ink)
443                    .hover(move |button| button.bg(ink.opacity(0.08)))
444                    .focus_visible(move |button| button.border_2().border_color(ink))
445                    .child(glyph)
446                    .into_any_element()
447            },
448        )
449        .open(state.is_showing())
450        .on_open_change(move |open, window, cx| observed.set(open, window, cx))
451        .into_any_element()
452    }
453}
454
455impl Element for StripLayout {
456    type RequestLayoutState = Vec<Prepared>;
457    type PrepaintState = (usize, Option<AnyElement>);
458
459    fn id(&self) -> Option<ElementId> {
460        Some(self.strip.id.clone())
461    }
462
463    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
464        None
465    }
466
467    fn a11y_role(&self) -> Option<Role> {
468        Some(Role::Group)
469    }
470
471    fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) {
472        node.set_label(self.label.as_ref());
473    }
474
475    fn request_layout(
476        &mut self,
477        _: Option<&GlobalElementId>,
478        _: Option<&InspectorElementId>,
479        window: &mut Window,
480        cx: &mut App,
481    ) -> (LayoutId, Self::RequestLayoutState) {
482        let strip_id = self.strip.id.clone();
483        let items: Vec<_> = std::mem::take(&mut self.strip.items)
484            .into_iter()
485            .map(|item| item.prepare(&strip_id, self.ink, window, cx))
486            .collect();
487        let limited = items.len() > self.strip.max_item_count;
488        let preferred_count = if limited {
489            self.strip.max_item_count - 1
490        } else {
491            items.len()
492        };
493        let main = items[..preferred_count]
494            .iter()
495            .map(|item| self.axis.extent(item.preferred))
496            .sum::<Pixels>()
497            + if limited { TRIGGER_SIZE } else { px(0.) };
498        let cross = items
499            .iter()
500            .map(|item| self.axis.cross(item.preferred))
501            .fold(
502                if items.is_empty() {
503                    px(0.)
504                } else {
505                    TRIGGER_SIZE
506                },
507                Pixels::max,
508            );
509        let style = Style {
510            size: self.axis.size(main, cross).map(Into::into),
511            min_size: size(px(0.).into(), px(0.).into()),
512            max_size: size(relative(1.).into(), relative(1.).into()),
513            ..Default::default()
514        };
515        (window.request_layout(style, None, cx), items)
516    }
517
518    fn prepaint(
519        &mut self,
520        _: Option<&GlobalElementId>,
521        _: Option<&InspectorElementId>,
522        bounds: Bounds<Pixels>,
523        items: &mut Self::RequestLayoutState,
524        window: &mut Window,
525        cx: &mut App,
526    ) -> Self::PrepaintState {
527        let length = self.axis.extent(bounds.size);
528        let breadth = self.axis.cross(bounds.size);
529        let has_space = length > px(0.) && breadth > px(0.);
530        let shown = if has_space {
531            fit(
532                items.iter().map(|item| self.axis.extent(item.preferred)),
533                self.strip.max_item_count,
534                length,
535                TRIGGER_SIZE,
536            )
537        } else {
538            0
539        };
540        let overflow = has_space && shown < items.len();
541        self.transfer_focus(shown, items, overflow, window, cx);
542        let mut offset = px(0.);
543        for item in &mut items[..shown] {
544            let extent = self.axis.extent(item.preferred);
545            let child = if self.axis.cross(item.preferred) > breadth {
546                let cap = self.axis.size(extent, breadth);
547                item.inline
548                    .layout_as_root(cap.map(AvailableSpace::Definite), window, cx)
549            } else {
550                item.preferred
551            };
552            let origin = self.axis.origin(bounds, child, offset, self.direction);
553            window.with_content_mask(Some(ContentMask { bounds }), |window| {
554                item.inline.prepaint_at(origin, window, cx)
555            });
556            offset += extent;
557        }
558        let menu = overflow.then(|| {
559            let size = self
560                .axis
561                .size(TRIGGER_SIZE.min(length - offset), TRIGGER_SIZE.min(breadth));
562            let mut menu = self.overflow_menu(&mut items[shown..], size);
563            let child = menu.layout_as_root(size.map(AvailableSpace::Definite), window, cx);
564            menu.prepaint_at(
565                self.axis.origin(bounds, child, offset, self.direction),
566                window,
567                cx,
568            );
569            menu
570        });
571        (shown, menu)
572    }
573
574    fn paint(
575        &mut self,
576        _: Option<&GlobalElementId>,
577        _: Option<&InspectorElementId>,
578        bounds: Bounds<Pixels>,
579        items: &mut Self::RequestLayoutState,
580        (shown, menu): &mut Self::PrepaintState,
581        window: &mut Window,
582        cx: &mut App,
583    ) {
584        window.with_content_mask(Some(ContentMask { bounds }), |window| {
585            for item in &mut items[..*shown] {
586                item.inline.paint(window, cx);
587            }
588        });
589        if let Some(menu) = menu {
590            menu.paint(window, cx);
591        }
592    }
593}
594
595fn fit<I: Clone + ExactSizeIterator<Item = Pixels>>(
596    extents: I,
597    max_count: usize,
598    available: Pixels,
599    trigger: Pixels,
600) -> usize {
601    if extents.len() <= max_count && extents.clone().sum::<Pixels>() <= available {
602        return extents.len();
603    }
604    let mut remaining = available - trigger;
605    extents
606        .take(max_count.saturating_sub(1))
607        .take_while(|extent| {
608            remaining -= *extent;
609            remaining >= px(0.)
610        })
611        .count()
612}
613
614#[cfg(test)]
615mod tests {
616    use super::fit;
617    use gpui::px;
618
619    #[test]
620    fn fit_keeps_all_when_within_limit_and_reserves_trigger_on_overflow() {
621        let widths = [px(48.), px(48.), px(48.)];
622        assert_eq!(fit(widths.into_iter(), 5, px(200.), px(48.)), 3);
623        assert_eq!(fit(widths.into_iter(), 2, px(200.), px(48.)), 1);
624        assert_eq!(fit(widths.into_iter(), 5, px(120.), px(48.)), 1);
625        assert_eq!(fit(widths.into_iter(), 5, px(40.), px(48.)), 0);
626    }
627}