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