Skip to main content

gpui_material_components/navigation/app_bar/
actions.rs

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