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_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: SharedString,
199    overflow_label: 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: "App bar actions".into(),
210            overflow_label: "More actions".into(),
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 (default `"App bar actions"`).
237            pub fn label(mut self, label: impl Into<SharedString>) -> Self {
238                self.0.label = label.into();
239                self
240            }
241
242            /// Limits inline children, including the overflow trigger when it is needed.
243            pub fn max_item_count(mut self, count: usize) -> Self {
244                self.0.max_item_count = count.max(1);
245                self
246            }
247
248            /// Sets the accessible label of the overflow menu trigger button (default `"More actions"`).
249            pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
250                self.0.overflow_label = label.into();
251                self
252            }
253
254            /// Replaces the decorative content of the built-in overflow button.
255            pub fn overflow_indicator<E: IntoElement>(
256                mut self,
257                build: impl FnOnce(AppBarMenuState) -> E + 'static,
258            ) -> Self {
259                self.0.overflow_indicator =
260                    Some(Box::new(move |state| build(state).into_any_element()));
261                self
262            }
263        }
264
265        impl RenderOnce for $name {
266            fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
267                StripLayout::new(self.0, $axis, window, cx)
268            }
269        }
270    };
271}
272
273action_strip!(AppBarRow, Axis::Horizontal);
274action_strip!(AppBarColumn, Axis::Vertical);
275
276#[derive(Clone, Copy, PartialEq, Eq)]
277enum Axis {
278    Horizontal,
279    Vertical,
280}
281
282impl Axis {
283    fn extent(self, size: Size<Pixels>) -> Pixels {
284        match self {
285            Self::Horizontal => size.width,
286            Self::Vertical => size.height,
287        }
288    }
289
290    fn cross(self, size: Size<Pixels>) -> Pixels {
291        match self {
292            Self::Horizontal => size.height,
293            Self::Vertical => size.width,
294        }
295    }
296
297    fn size(self, extent: Pixels, cross: Pixels) -> Size<Pixels> {
298        match self {
299            Self::Horizontal => size(extent, cross),
300            Self::Vertical => size(cross, extent),
301        }
302    }
303
304    fn origin(
305        self,
306        bounds: Bounds<Pixels>,
307        child: Size<Pixels>,
308        offset: Pixels,
309        direction: Direction,
310    ) -> Point<Pixels> {
311        let delta = (self.cross(bounds.size) - self.cross(child)).max(px(0.)) / 2.;
312        match (self, direction) {
313            (Self::Horizontal, Direction::Rtl) => {
314                point(bounds.right() - offset - child.width, bounds.top() + delta)
315            }
316            (Self::Horizontal, Direction::Ltr) => {
317                point(bounds.left() + offset, bounds.top() + delta)
318            }
319            (Self::Vertical, _) => point(bounds.left() + delta, bounds.top() + offset),
320        }
321    }
322}
323
324struct StripLayout {
325    strip: Strip,
326    axis: Axis,
327    direction: Direction,
328    ink: Hsla,
329    overflow: OverflowStripHandle<ElementId>,
330}
331
332impl StripLayout {
333    fn new(strip: Strip, axis: Axis, window: &mut Window, cx: &mut App) -> Self {
334        let overflow = OverflowStripHandle::use_state(&strip.id, "app-bar-overflow", window, cx);
335        Self {
336            strip,
337            axis,
338            direction: current_material_theme(window, cx).layout.direction,
339            ink: window.text_style().color,
340            overflow,
341        }
342    }
343
344    fn menu_state(&self) -> AppBarMenuState {
345        AppBarMenuState {
346            controller: self.overflow.controller.clone(),
347        }
348    }
349
350    fn transfer_focus(
351        &self,
352        shown: usize,
353        items: &[Prepared],
354        overflow: bool,
355        window: &mut Window,
356        cx: &mut App,
357    ) {
358        let hidden_focused = overflow.then(|| {
359            items[shown..]
360                .iter()
361                .find(|item| item.focus.contains_focused(window, cx))
362                .map(|item| (item.id.clone(), item.focus.clone()))
363        });
364        self.overflow.transfer_focus(
365            overflow,
366            hidden_focused.flatten(),
367            |id| {
368                items[..shown]
369                    .iter()
370                    .any(|item| item.enabled && item.id == *id)
371            },
372            || {
373                items[..shown]
374                    .iter()
375                    .find(|item| item.enabled)
376                    .map(|item| item.focus.clone())
377            },
378            window,
379            cx,
380        );
381    }
382
383    fn overflow_menu(&mut self, hidden: &mut [Prepared], size: Size<Pixels>) -> AnyElement {
384        let state = self.menu_state();
385        let entries: Vec<_> = hidden
386            .iter_mut()
387            .filter_map(|item| item.menu.take().map(|build| build(state.clone())))
388            .collect();
389        let trigger_focus = self.overflow.focus.clone();
390        let label = self.strip.overflow_label.clone();
391        let trigger_id = ElementId::from((self.strip.id.clone(), "overflow"));
392        let ink = self.ink;
393        let glyph = self.strip.overflow_indicator.take().map_or_else(
394            || {
395                let unit = px(4.).min(size.width / 4.).min(size.height / 4.);
396                div()
397                    .flex()
398                    .flex_col()
399                    .gap(unit / 2.)
400                    .children((0..3).map(|_| div().size(unit).rounded_full().bg(ink)))
401                    .into_any_element()
402            },
403            |build| build(state.clone()),
404        );
405        let observed = state.clone();
406        Menu::composed(
407            (self.strip.id.clone(), "menu"),
408            entries,
409            move |_, toggle| {
410                let return_focus = trigger_focus.clone();
411                Button::new(trigger_id)
412                    .track_focus(&trigger_focus)
413                    .accessibility_label(label)
414                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
415                        return_focus.focus(window, cx);
416                        toggle(window, cx);
417                    })
418                    .w(size.width)
419                    .h(size.height)
420                    .p_0()
421                    .flex()
422                    .items_center()
423                    .justify_center()
424                    .overflow_hidden()
425                    .rounded_full()
426                    .text_color(ink)
427                    .hover(move |button| button.bg(ink.opacity(0.08)))
428                    .focus_visible(move |button| button.border_2().border_color(ink))
429                    .child(glyph)
430                    .into_any_element()
431            },
432        )
433        .open(state.is_showing())
434        .on_open_change(move |open, window, cx| observed.set(open, window, cx))
435        .into_any_element()
436    }
437}
438
439impl Element for StripLayout {
440    type RequestLayoutState = Vec<Prepared>;
441    type PrepaintState = (usize, Option<AnyElement>);
442
443    fn id(&self) -> Option<ElementId> {
444        Some(self.strip.id.clone())
445    }
446
447    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
448        None
449    }
450
451    fn a11y_role(&self) -> Option<Role> {
452        Some(Role::Group)
453    }
454
455    fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) {
456        node.set_label(self.strip.label.as_ref());
457    }
458
459    fn request_layout(
460        &mut self,
461        _: Option<&GlobalElementId>,
462        _: Option<&InspectorElementId>,
463        window: &mut Window,
464        cx: &mut App,
465    ) -> (LayoutId, Self::RequestLayoutState) {
466        let strip_id = self.strip.id.clone();
467        let items: Vec<_> = std::mem::take(&mut self.strip.items)
468            .into_iter()
469            .map(|item| item.prepare(&strip_id, self.ink, window, cx))
470            .collect();
471        let limited = items.len() > self.strip.max_item_count;
472        let preferred_count = if limited {
473            self.strip.max_item_count - 1
474        } else {
475            items.len()
476        };
477        let main = items[..preferred_count]
478            .iter()
479            .map(|item| self.axis.extent(item.preferred))
480            .sum::<Pixels>()
481            + if limited { TRIGGER_SIZE } else { px(0.) };
482        let cross = items
483            .iter()
484            .map(|item| self.axis.cross(item.preferred))
485            .fold(
486                if items.is_empty() {
487                    px(0.)
488                } else {
489                    TRIGGER_SIZE
490                },
491                Pixels::max,
492            );
493        let style = Style {
494            size: self.axis.size(main, cross).map(Into::into),
495            min_size: size(px(0.).into(), px(0.).into()),
496            max_size: size(relative(1.).into(), relative(1.).into()),
497            ..Default::default()
498        };
499        (window.request_layout(style, None, cx), items)
500    }
501
502    fn prepaint(
503        &mut self,
504        _: Option<&GlobalElementId>,
505        _: Option<&InspectorElementId>,
506        bounds: Bounds<Pixels>,
507        items: &mut Self::RequestLayoutState,
508        window: &mut Window,
509        cx: &mut App,
510    ) -> Self::PrepaintState {
511        let length = self.axis.extent(bounds.size);
512        let breadth = self.axis.cross(bounds.size);
513        let has_space = length > px(0.) && breadth > px(0.);
514        let shown = if has_space {
515            fit(
516                items.iter().map(|item| self.axis.extent(item.preferred)),
517                self.strip.max_item_count,
518                length,
519                TRIGGER_SIZE,
520            )
521        } else {
522            0
523        };
524        let overflow = has_space && shown < items.len();
525        self.transfer_focus(shown, items, overflow, window, cx);
526        let mut offset = px(0.);
527        for item in &mut items[..shown] {
528            let extent = self.axis.extent(item.preferred);
529            let child = if self.axis.cross(item.preferred) > breadth {
530                let cap = self.axis.size(extent, breadth);
531                item.inline
532                    .layout_as_root(cap.map(AvailableSpace::Definite), window, cx)
533            } else {
534                item.preferred
535            };
536            let origin = self.axis.origin(bounds, child, offset, self.direction);
537            window.with_content_mask(Some(ContentMask { bounds }), |window| {
538                item.inline.prepaint_at(origin, window, cx)
539            });
540            offset += extent;
541        }
542        let menu = overflow.then(|| {
543            let size = self
544                .axis
545                .size(TRIGGER_SIZE.min(length - offset), TRIGGER_SIZE.min(breadth));
546            let mut menu = self.overflow_menu(&mut items[shown..], size);
547            let child = menu.layout_as_root(size.map(AvailableSpace::Definite), window, cx);
548            menu.prepaint_at(
549                self.axis.origin(bounds, child, offset, self.direction),
550                window,
551                cx,
552            );
553            menu
554        });
555        (shown, menu)
556    }
557
558    fn paint(
559        &mut self,
560        _: Option<&GlobalElementId>,
561        _: Option<&InspectorElementId>,
562        bounds: Bounds<Pixels>,
563        items: &mut Self::RequestLayoutState,
564        (shown, menu): &mut Self::PrepaintState,
565        window: &mut Window,
566        cx: &mut App,
567    ) {
568        window.with_content_mask(Some(ContentMask { bounds }), |window| {
569            for item in &mut items[..*shown] {
570                item.inline.paint(window, cx);
571            }
572        });
573        if let Some(menu) = menu {
574            menu.paint(window, cx);
575        }
576    }
577}
578
579fn fit<I: Clone + ExactSizeIterator<Item = Pixels>>(
580    extents: I,
581    max_count: usize,
582    available: Pixels,
583    trigger: Pixels,
584) -> usize {
585    if extents.len() <= max_count && extents.clone().sum::<Pixels>() <= available {
586        return extents.len();
587    }
588    let mut remaining = available - trigger;
589    extents
590        .take(max_count.saturating_sub(1))
591        .take_while(|extent| {
592            remaining -= *extent;
593            remaining >= px(0.)
594        })
595        .count()
596}
597
598#[cfg(test)]
599mod tests {
600    use super::fit;
601    use gpui::px;
602
603    #[test]
604    fn fit_keeps_all_when_within_limit_and_reserves_trigger_on_overflow() {
605        let widths = [px(48.), px(48.), px(48.)];
606        assert_eq!(fit(widths.into_iter(), 5, px(200.), px(48.)), 3);
607        assert_eq!(fit(widths.into_iter(), 2, px(200.), px(48.)), 1);
608        assert_eq!(fit(widths.into_iter(), 5, px(120.), px(48.)), 1);
609        assert_eq!(fit(widths.into_iter(), 5, px(40.), px(48.)), 0);
610    }
611}