Skip to main content

gpui_material_extras/toolbar/
bar.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, Hsla, IntoElement, Pixels, ScrollHandle, SharedString,
5    Window, px,
6};
7use gpui_material_components::{ButtonColors, ControlElevations, FabColor, IconName};
8use gpui_material_theme::{CornerShape, LogicalEdges, MotionSpec};
9
10use super::{Invoke, activate_key, focus_handle, style_button};
11use crate::ContentArrangement;
12
13mod actions;
14mod layout;
15mod palette;
16mod render;
17mod scroll;
18
19use scroll::length;
20pub use scroll::{ToolbarExitDirection, ToolbarFling, ToolbarScrollBehavior, ToolbarScrollState};
21
22/// Surface layout mode for a [`Toolbar`].
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum ToolbarPlacement {
25    /// Pill-shaped elevated toolbar floating above content, with optional adjacent FAB.
26    #[default]
27    Floating,
28    /// Edge-to-edge toolbar spanning the full width or height of its container.
29    Docked,
30}
31
32/// Primary layout axis of a [`Toolbar`].
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub enum ToolbarOrientation {
35    /// Arranges actions left-to-right (or right-to-left in RTL).
36    #[default]
37    Horizontal,
38    /// Arranges actions top-to-bottom.
39    Vertical,
40}
41
42/// Material 3 color treatment preset for a [`Toolbar`].
43#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
44pub enum ToolbarColor {
45    /// Neutral surface container styling.
46    #[default]
47    Standard,
48    /// Expressive primary-container styling for high emphasis.
49    Vibrant,
50}
51
52/// Optional toolbar pigments. The adjacent FAB uses its own palette.
53#[derive(Clone, Copy, Debug, Default, PartialEq)]
54pub struct ToolbarColors {
55    /// Background fill color for the toolbar strip.
56    pub container: Option<Hsla>,
57    /// Foreground icon and text color for unselected actions.
58    pub content: Option<Hsla>,
59    /// Background fill color for selected toggle actions.
60    pub selected_container: Option<Hsla>,
61    /// Foreground icon and text color for selected toggle actions.
62    pub selected_content: Option<Hsla>,
63}
64
65/// Places the FAB in logical order. Horizontal positions mirror in RTL.
66#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
67pub enum ToolbarFabPosition {
68    /// Places the FAB before the toolbar strip (leading edge, mirrored in RTL).
69    Start,
70    /// Places the FAB after the toolbar strip (trailing edge, mirrored in RTL).
71    #[default]
72    End,
73}
74
75#[derive(Clone)]
76pub(super) enum ActionIcon {
77    Symbol(IconName),
78    Custom(Rc<dyn Fn() -> AnyElement>),
79}
80
81/// One labeled command or toggle rendered inside a [`Toolbar`].
82pub struct ToolbarAction {
83    id: SharedString,
84    label: SharedString,
85    icon: ActionIcon,
86    enabled: bool,
87    selected: Option<bool>,
88    secondary: bool,
89    invoke: Option<Invoke>,
90}
91
92impl ToolbarAction {
93    /// Creates a toolbar action with a stable `id`, accessible `label`, and Material `icon`.
94    pub fn new(
95        id: impl Into<SharedString>,
96        label: impl Into<SharedString>,
97        icon: IconName,
98    ) -> Self {
99        Self {
100            id: id.into(),
101            label: label.into(),
102            icon: ActionIcon::Symbol(icon),
103            enabled: true,
104            selected: None,
105            secondary: false,
106            invoke: None,
107        }
108    }
109
110    /// Creates a toolbar action with a custom repeatable icon factory used both inline
111    /// and in the collapsed overflow menu.
112    pub fn with_icon<E: IntoElement>(
113        id: impl Into<SharedString>,
114        label: impl Into<SharedString>,
115        icon: impl Fn() -> E + 'static,
116    ) -> Self {
117        Self {
118            id: id.into(),
119            label: label.into(),
120            icon: ActionIcon::Custom(Rc::new(move || icon().into_any_element())),
121            enabled: true,
122            selected: None,
123            secondary: false,
124            invoke: None,
125        }
126    }
127
128    /// Disables activation for this action when `true`.
129    pub fn disabled(mut self, disabled: bool) -> Self {
130        self.enabled = !disabled;
131        self
132    }
133
134    /// Marks a controlled toggle and specifies its current state.
135    pub fn selected(mut self, selected: bool) -> Self {
136        self.selected = Some(selected);
137        self
138    }
139
140    /// Places this action in the overflow menu when the toolbar is collapsed.
141    pub fn secondary(mut self, secondary: bool) -> Self {
142        self.secondary = secondary;
143        self
144    }
145
146    /// Registers a callback invoked when the action is activated via pointer, keyboard, or accessibility.
147    pub fn on_activate(mut self, invoke: impl Fn(&mut Window, &mut App) + 'static) -> Self {
148        self.invoke = Some(std::rc::Rc::new(invoke));
149        self
150    }
151}
152
153struct ToolbarFab {
154    position: ToolbarFabPosition,
155    content: FabContent,
156}
157
158enum FabContent {
159    Standard {
160        icon: IconName,
161        label: SharedString,
162        invoke: Invoke,
163    },
164    Custom(AnyElement),
165}
166
167/// A floating or docked group of labeled actions with optional adjacent FAB.
168/// Supply a bounded main-axis extent for scrollable overflow. The toolbar
169/// reveals the focused action even when its scroll container is narrower.
170#[derive(IntoElement)]
171pub struct Toolbar {
172    id: ElementId,
173    label: SharedString,
174    actions: Vec<ToolbarAction>,
175    placement: ToolbarPlacement,
176    orientation: ToolbarOrientation,
177    color: ToolbarColor,
178    fab: Option<ToolbarFab>,
179    expanded: bool,
180    scroll: Option<ScrollHandle>,
181    navigation: Option<AnyElement>,
182    overflow_label: SharedString,
183    content: Option<AnyElement>,
184    leading: Option<AnyElement>,
185    trailing: Option<AnyElement>,
186    leading_expanded: Option<bool>,
187    trailing_expanded: Option<bool>,
188    arrangement: Option<ContentArrangement>,
189    spacing: Pixels,
190    expanded_height: Option<Pixels>,
191    padding: Option<LogicalEdges>,
192    shape: Option<CornerShape>,
193    elevations: ControlElevations,
194    colors: ToolbarColors,
195    fab_color: Option<FabColor>,
196    fab_colors: ButtonColors,
197    scroll_state: Option<Entity<ToolbarScrollState>>,
198    scroll_behavior: Option<ToolbarScrollBehavior>,
199    transition_motion: Option<MotionSpec>,
200}
201
202impl Toolbar {
203    /// Creates a floating horizontal toolbar with an element `id`, accessible `label`, and `actions`.
204    pub fn new(
205        id: impl Into<ElementId>,
206        label: impl Into<SharedString>,
207        actions: impl IntoIterator<Item = ToolbarAction>,
208    ) -> Self {
209        Self {
210            id: id.into(),
211            label: label.into(),
212            actions: actions.into_iter().collect(),
213            placement: ToolbarPlacement::Floating,
214            orientation: ToolbarOrientation::Horizontal,
215            color: ToolbarColor::Standard,
216            fab: None,
217            expanded: true,
218            scroll: None,
219            navigation: None,
220            overflow_label: "More actions".into(),
221            content: None,
222            leading: None,
223            trailing: None,
224            leading_expanded: None,
225            trailing_expanded: None,
226            arrangement: None,
227            spacing: px(4.),
228            expanded_height: None,
229            padding: None,
230            shape: None,
231            elevations: ControlElevations::default(),
232            colors: ToolbarColors::default(),
233            fab_color: None,
234            fab_colors: ButtonColors::default(),
235            scroll_state: None,
236            scroll_behavior: None,
237            transition_motion: None,
238        }
239    }
240
241    /// Sets whether the toolbar renders as [`ToolbarPlacement::Floating`] or [`ToolbarPlacement::Docked`].
242    pub fn placement(mut self, placement: ToolbarPlacement) -> Self {
243        self.placement = placement;
244        self
245    }
246
247    /// Sets the primary layout axis ([`ToolbarOrientation::Horizontal`] or [`ToolbarOrientation::Vertical`]).
248    pub fn orientation(mut self, orientation: ToolbarOrientation) -> Self {
249        self.orientation = orientation;
250        self
251    }
252
253    /// Sets the Material 3 color treatment ([`ToolbarColor::Standard`] or [`ToolbarColor::Vibrant`]).
254    pub fn color(mut self, color: ToolbarColor) -> Self {
255        self.color = color;
256        self
257    }
258
259    /// Adds an adjacent FAB to a floating toolbar. Add the primary action
260    /// through the action list when it belongs inside a docked toolbar.
261    pub fn fab(
262        mut self,
263        position: ToolbarFabPosition,
264        label: impl Into<SharedString>,
265        icon: IconName,
266        invoke: impl Fn(&mut Window, &mut App) + 'static,
267    ) -> Self {
268        self.fab = Some(ToolbarFab {
269            position,
270            content: FabContent::Standard {
271                icon,
272                label: label.into(),
273                invoke: Rc::new(invoke),
274            },
275        });
276        self
277    }
278
279    /// Uses a caller-authored adjacent control in a floating toolbar.
280    pub fn fab_content(mut self, position: ToolbarFabPosition, element: impl IntoElement) -> Self {
281        self.fab = Some(ToolbarFab {
282            position,
283            content: FabContent::Custom(element.into_any_element()),
284        });
285        self
286    }
287
288    /// Overrides the adjacent FAB's Material color role preset.
289    pub fn fab_color(mut self, color: FabColor) -> Self {
290        self.fab_color = Some(color);
291        self
292    }
293
294    /// Overrides individual container and content colors on the adjacent FAB.
295    pub fn fab_colors(mut self, colors: ButtonColors) -> Self {
296        self.fab_colors = colors;
297        self
298    }
299
300    /// Inserts arbitrary content before the generated actions.
301    pub fn content(mut self, element: impl IntoElement) -> Self {
302        self.content = Some(element.into_any_element());
303        self
304    }
305
306    /// Adds an expandable leading slot before the main toolbar content.
307    pub fn leading_content(mut self, element: impl IntoElement) -> Self {
308        self.leading = Some(element.into_any_element());
309        self
310    }
311
312    /// Adds an expandable trailing slot after the main toolbar content.
313    pub fn trailing_content(mut self, element: impl IntoElement) -> Self {
314        self.trailing = Some(element.into_any_element());
315        self
316    }
317
318    /// Overrides whether the leading slot is expanded independently of the toolbar's expanded state.
319    pub fn leading_expanded(mut self, expanded: bool) -> Self {
320        self.leading_expanded = Some(expanded);
321        self
322    }
323
324    /// Overrides whether the trailing slot is expanded independently of the toolbar's expanded state.
325    pub fn trailing_expanded(mut self, expanded: bool) -> Self {
326        self.trailing_expanded = Some(expanded);
327        self
328    }
329
330    /// Distributes free space in a horizontal docked toolbar.
331    pub fn arrangement(mut self, arrangement: ContentArrangement) -> Self {
332        self.arrangement = Some(arrangement);
333        self
334    }
335
336    /// Sets the gap between toolbar items in logical pixels. Defaults to `4px`.
337    pub fn spacing(mut self, spacing: Pixels) -> Self {
338        self.spacing = px(length(spacing).unwrap_or(4.));
339        self
340    }
341
342    /// Sets the height of a horizontal docked toolbar.
343    pub fn expanded_height(mut self, height: Pixels) -> Self {
344        self.expanded_height = length(height).filter(|height| *height > 0.).map(px);
345        self
346    }
347
348    /// Overrides the logical content padding inside the toolbar strip.
349    pub fn padding(mut self, padding: LogicalEdges) -> Self {
350        self.padding = Some(padding);
351        self
352    }
353
354    /// Overrides the corner shape of the toolbar strip.
355    pub fn shape(mut self, shape: CornerShape) -> Self {
356        self.shape = Some(shape);
357        self
358    }
359
360    /// Overrides the shadow elevations for expanded (`resting`) and collapsed (`disabled`) states.
361    ///
362    /// Floating toolbars default to [`gpui_material_theme::Elevation::Level3`] when expanded
363    /// and [`gpui_material_theme::Elevation::Level0`] when collapsed; docked toolbars default
364    /// to [`gpui_material_theme::Elevation::Level0`].
365    pub fn elevations(mut self, elevations: ControlElevations) -> Self {
366        self.elevations = elevations;
367        self
368    }
369
370    /// Overrides the toolbar's container, content, and selected-action colors.
371    pub fn colors(mut self, colors: ToolbarColors) -> Self {
372        self.colors = colors;
373        self
374    }
375
376    /// Controls whether secondary actions appear directly in the toolbar.
377    pub fn expanded(mut self, expanded: bool) -> Self {
378        self.expanded = expanded;
379        self
380    }
381
382    /// Uses the linked content's vertical scroll offset to collapse and expand
383    /// the toolbar after a 40 dp change in the scroll direction.
384    pub fn track_scroll(mut self, scroll: &ScrollHandle) -> Self {
385        self.scroll = Some(scroll.clone());
386        self
387    }
388
389    /// Attaches a caller-owned [`ToolbarScrollState`] entity for scroll-driven collapsing and exit.
390    pub fn scroll_state(mut self, state: &Entity<ToolbarScrollState>) -> Self {
391        self.scroll_state = Some(state.clone());
392        self
393    }
394
395    /// Configures scroll thresholds, exit direction, and snap/fling motion.
396    pub fn scroll_behavior(mut self, behavior: ToolbarScrollBehavior) -> Self {
397        self.scroll_behavior = Some(behavior);
398        self
399    }
400
401    /// Overrides the [`MotionSpec`] used for expanding and collapsing leading/trailing slots.
402    pub fn transition_motion(mut self, motion: MotionSpec) -> Self {
403        self.transition_motion = Some(motion);
404        self
405    }
406
407    /// Renders the supplied navigation instead of the toolbar. Use this for
408    /// a responsive region shared between navigation and contextual actions.
409    pub fn navigation(mut self, navigation: impl IntoElement) -> Self {
410        self.navigation = Some(navigation.into_any_element());
411        self
412    }
413
414    /// Sets the accessible label for the collapsed overflow trigger button. Defaults to `"More actions"`.
415    pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
416        self.overflow_label = label.into();
417        self
418    }
419}