Skip to main content

gpui_material_extras/toolbar/bar/
render.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    App, Axis, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role,
5    ScrollHandle, Size, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder,
6    px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_components::ControlElevations;
10use gpui_material_foundation::{animate, color, current_material_theme, move_roving_focus};
11use gpui_material_theme::{CornerShape, Direction, Elevation, MotionKind, MotionSpec, MotionSpeed};
12
13use super::{
14    FabContent, Toolbar, ToolbarFabPosition, ToolbarOrientation, ToolbarPlacement,
15    actions::{
16        partition_actions, render_fab, render_overflow_menu, render_visible_actions,
17        sync_focused_scroll,
18    },
19    focus_handle,
20    layout::{StripGeometry, ToolbarSlot, apply_padding, arrange_horizontal},
21    palette::{
22        ScrollPresentation, ToolbarPalette, resolve_scroll_presentation, resolve_target_elevation,
23    },
24};
25
26impl RenderOnce for Toolbar {
27    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
28        if let Some(navigation) = self.navigation {
29            return navigation;
30        }
31        let theme = current_material_theme(window, cx);
32        let direction = theme.layout.direction;
33        let density = theme.layout.density;
34        let horizontal = self.orientation == ToolbarOrientation::Horizontal;
35        let rtl = direction == Direction::Rtl;
36        let docked = self.placement == ToolbarPlacement::Docked;
37        let palette = ToolbarPalette::resolve(&self, |role| color(theme.colors.color(role)));
38        let scheme = theme.motion;
39        let reduced = cx.reduce_motion();
40        let transition = if reduced {
41            MotionSpec::Instant
42        } else {
43            self.transition_motion
44                .unwrap_or_else(|| scheme.spec(MotionKind::Spatial, MotionSpeed::Fast, false))
45        };
46        let viewport = window.viewport_size();
47        let scope = focus_handle(&self.id, "strip-focus", window, cx);
48        let exposed = scope.contains_focused(window, cx);
49        let footprint = window
50            .use_keyed_state((self.id.clone(), "strip-footprint"), cx, |_, _| {
51                Rc::new(Cell::new(Size::<Pixels>::default()))
52            })
53            .read(cx)
54            .clone();
55        let behavior = self.scroll_behavior.unwrap_or_default();
56        let ScrollPresentation {
57            slide,
58            hidden_strip,
59        } = resolve_scroll_presentation(
60            &mut self, &footprint, behavior, scheme, reduced, exposed, rtl, window, cx,
61        );
62        let target_elevation =
63            resolve_target_elevation(self.placement, self.expanded, self.elevations);
64        let uses_elevation = !docked
65            || target_elevation != Elevation::Level0
66            || self.elevations != ControlElevations::default();
67        let elevation = if uses_elevation {
68            animate(
69                (self.id.clone(), "toolbar-elevation"),
70                target_elevation.dp(),
71                transition,
72                window,
73                cx,
74            )
75            .max(0.)
76        } else {
77            0.
78        };
79        let custom_surface = self.shape.is_some()
80            || uses_elevation
81            || behavior.exit_direction.is_some()
82            || self.content.is_some()
83            || self.leading.is_some()
84            || self.trailing.is_some()
85            || self.arrangement.is_some() && docked && horizontal;
86        let arrangement = self.arrangement.filter(|_| docked && horizontal);
87        let spacing = self.spacing.min(if horizontal {
88            viewport.width
89        } else {
90            viewport.height
91        });
92        let strip_min = px(density.interactive_size(64.));
93        let action_size = px(density.interactive_size(48.));
94        let toolbar_scroll = window
95            .use_keyed_state((self.id.clone(), "action-scroll"), cx, |_, _| {
96                ScrollHandle::new()
97            })
98            .read(cx)
99            .clone();
100
101        let actions = std::mem::take(&mut self.actions);
102        let (visible, hidden) = partition_actions(&self.id, actions, self.expanded, window, cx);
103        let has_more = !hidden.is_empty();
104        let overflow_focus = focus_handle(&self.id, "overflow-focus", window, cx);
105        let fab_focus = focus_handle(&self.id, "fab-focus", window, cx);
106        let fab = self.fab.take().filter(|_| !docked);
107        let fab_first = fab
108            .as_ref()
109            .is_some_and(|fab| fab.position == ToolbarFabPosition::Start);
110        let mut bar_order = visible
111            .iter()
112            .map(|(action, handle)| (handle.clone(), action.enabled))
113            .collect::<Vec<_>>();
114        if has_more {
115            bar_order.push((overflow_focus.clone(), true));
116        }
117        let first_tab = bar_order
118            .iter()
119            .position(|(handle, enabled)| *enabled && handle.is_focused(window))
120            .or_else(|| bar_order.iter().position(|(_, enabled)| *enabled));
121        let mirrored = horizontal && rtl;
122        let standard_fab = fab
123            .as_ref()
124            .is_some_and(|fab| matches!(fab.content, FabContent::Standard { .. }));
125        let fab_element =
126            fab.map(|fab| render_fab(&self, fab, &fab_focus, palette.default_fab_color));
127
128        let mut action_strip = div()
129            .id((self.id.clone(), "actions"))
130            .test_support()
131            .track_focus(&scope)
132            .tab_stop(false)
133            .flex()
134            .items_center()
135            .min_w_0()
136            .min_h_0()
137            .flex_shrink(1.)
138            .when(horizontal, |strip| strip.max_w_full().overflow_x_scroll())
139            .when(!horizontal, |strip| {
140                strip.flex_col().max_h_full().overflow_y_scroll()
141            })
142            .track_scroll(&toolbar_scroll)
143            .text_color(palette.ink)
144            .when(!custom_surface, |strip| {
145                strip
146                    .bg(palette.surface)
147                    .when(!docked, Styled::rounded_full)
148            })
149            .when(docked && horizontal, Styled::w_full)
150            .when(docked && !horizontal, Styled::h_full)
151            .when_else(
152                horizontal,
153                |strip| strip.min_h(strip_min),
154                |strip| strip.min_w(strip_min),
155            )
156            .when_else(
157                horizontal,
158                |strip| strip.px(px(if docked { 16. } else { 8. })).py(px(8.)),
159                |strip| strip.py(px(if docked { 16. } else { 8. })).px(px(8.)),
160            )
161            .when_some(
162                self.expanded_height.filter(|_| horizontal && docked),
163                |strip, height| {
164                    strip
165                        .h(height.min(viewport.height))
166                        .min_h_0()
167                        .overflow_y_hidden()
168                },
169            )
170            .gap(if arrangement.is_some() {
171                px(0.)
172            } else {
173                spacing
174            });
175        if let Some(padding) = self.padding {
176            action_strip = apply_padding(padding, action_strip, direction, viewport);
177        }
178
179        let mut commands =
180            render_visible_actions(&self.id, visible, first_tab, action_size, palette);
181        if has_more {
182            let count = bar_order.len();
183            commands.push(render_overflow_menu(
184                &self.id,
185                self.overflow_label,
186                hidden,
187                overflow_focus,
188                first_tab == Some(count - 1),
189                horizontal,
190                direction,
191                action_size,
192                palette,
193            ));
194        }
195
196        let mut strip_children = Vec::new();
197        if hidden_strip {
198            bar_order.clear();
199        } else {
200            let mut side = |part, element, expanded: Option<bool>| {
201                let slot = ToolbarSlot::new(&self.id, part, element, window, cx);
202                slot.expandable(
203                    expanded.unwrap_or(self.expanded),
204                    horizontal,
205                    transition,
206                    window,
207                    cx,
208                )
209            };
210            let leading = self
211                .leading
212                .take()
213                .and_then(|element| side("leading", element, self.leading_expanded));
214            let trailing = self
215                .trailing
216                .take()
217                .and_then(|element| side("trailing", element, self.trailing_expanded));
218            strip_children.extend(leading);
219            strip_children.extend(
220                self.content.take().map(|element| {
221                    ToolbarSlot::new(&self.id, "body", element, window, cx).content()
222                }),
223            );
224            let first_command = strip_children.len();
225            strip_children.extend(commands);
226            strip_children.extend(trailing);
227
228            sync_focused_scroll(
229                &self.id,
230                &strip_children,
231                first_command,
232                first_tab,
233                arrangement.is_some(),
234                mirrored,
235                &toolbar_scroll,
236                window,
237                cx,
238            );
239        }
240
241        let mut children = strip_children
242            .into_iter()
243            .map(|(element, _)| element)
244            .collect::<Vec<_>>();
245        if let Some(arrangement) = arrangement {
246            children = arrange_horizontal(children, arrangement, spacing);
247        }
248        if mirrored {
249            children.reverse();
250        }
251        action_strip = action_strip.children(children);
252        let action_strip = if custom_surface {
253            StripGeometry {
254                horizontal,
255                docked,
256                direction,
257                footprint,
258                track_footprint: behavior.exit_direction.is_some(),
259                shape: self.shape.unwrap_or(if docked {
260                    CornerShape::Radii([0.; 4])
261                } else {
262                    CornerShape::Full
263                }),
264                surface: palette.surface,
265                shadow: palette.shadow,
266                elevation,
267                slide,
268                hidden: hidden_strip,
269            }
270            .frame(action_strip)
271        } else {
272            action_strip.into_any_element()
273        };
274        if standard_fab {
275            let index = if fab_first { 0 } else { bar_order.len() };
276            bar_order.insert(index, (fab_focus, true));
277        }
278        let root = div()
279            .id(self.id)
280            .test_support()
281            .role(Role::Toolbar)
282            .aria_label(self.label)
283            .aria_orientation(if horizontal {
284                gpui::accesskit::Orientation::Horizontal
285            } else {
286                gpui::accesskit::Orientation::Vertical
287            })
288            .flex()
289            .items_center()
290            .min_w_0()
291            .min_h_0()
292            .max_w_full()
293            .max_h_full()
294            .when(horizontal && rtl, Styled::flex_row_reverse)
295            .when(!horizontal, Styled::flex_col)
296            .when(docked && horizontal, Styled::w_full)
297            .when(docked && !horizontal, Styled::h_full)
298            .gap(px(4.))
299            .on_key_down(move |event, window, cx| {
300                if event.keystroke.modifiers.modified()
301                    || !bar_order
302                        .iter()
303                        .any(|(handle, _)| handle.is_focused(window))
304                {
305                    return;
306                }
307                let items = bar_order
308                    .iter()
309                    .map(|(handle, enabled)| (handle, *enabled))
310                    .collect::<Vec<_>>();
311                if move_roving_focus(
312                    &items,
313                    &event.keystroke.key,
314                    if horizontal {
315                        Axis::Horizontal
316                    } else {
317                        Axis::Vertical
318                    },
319                    direction,
320                    window,
321                    cx,
322                )
323                .is_some()
324                {
325                    window.refresh();
326                    cx.stop_propagation();
327                }
328            });
329        if fab_first {
330            root.children(fab_element)
331                .child(action_strip)
332                .into_any_element()
333        } else {
334            root.child(action_strip)
335                .children(fab_element)
336                .into_any_element()
337        }
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use gpui_material_components::ControlElevations;
344    use gpui_material_theme::{Elevation, LogicalEdges};
345
346    use super::*;
347    use crate::ContentArrangement;
348
349    #[test]
350    fn floating_toolbar_defaults_to_level3_when_expanded_and_level0_when_collapsed() {
351        assert_eq!(
352            resolve_target_elevation(
353                ToolbarPlacement::Floating,
354                true,
355                ControlElevations::default()
356            ),
357            Elevation::Level3
358        );
359        assert_eq!(
360            resolve_target_elevation(
361                ToolbarPlacement::Floating,
362                false,
363                ControlElevations::default()
364            ),
365            Elevation::Level0
366        );
367        assert_eq!(
368            resolve_target_elevation(ToolbarPlacement::Docked, true, ControlElevations::default()),
369            Elevation::Level0
370        );
371        assert_eq!(
372            resolve_target_elevation(
373                ToolbarPlacement::Docked,
374                false,
375                ControlElevations::default()
376            ),
377            Elevation::Level0
378        );
379    }
380
381    #[test]
382    fn control_elevations_override_expanded_and_collapsed_toolbar_levels() {
383        let overrides = ControlElevations {
384            resting: Some(Elevation::Level1),
385            disabled: Some(Elevation::Level2),
386            ..Default::default()
387        };
388        assert_eq!(
389            resolve_target_elevation(ToolbarPlacement::Floating, true, overrides),
390            Elevation::Level1
391        );
392        assert_eq!(
393            resolve_target_elevation(ToolbarPlacement::Floating, false, overrides),
394            Elevation::Level2
395        );
396    }
397
398    #[test]
399    fn toolbar_builder_accepts_unified_primitives() {
400        let toolbar = Toolbar::new("bar", "Actions", [])
401            .arrangement(ContentArrangement::SpaceEvenly)
402            .padding(LogicalEdges::new(4., 8., 6., 10.))
403            .elevations(ControlElevations {
404                resting: Some(Elevation::Level2),
405                disabled: Some(Elevation::Level0),
406                ..Default::default()
407            });
408        assert_eq!(toolbar.arrangement, Some(ContentArrangement::SpaceEvenly));
409        assert_eq!(toolbar.padding, Some(LogicalEdges::new(4., 8., 6., 10.)));
410        assert_eq!(toolbar.elevations.resting, Some(Elevation::Level2));
411        assert_eq!(toolbar.elevations.disabled, Some(Elevation::Level0));
412    }
413}