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