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