1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 Anchor, AnyElement, App, Axis, ElementId, FocusHandle, Hsla, InteractiveElement, IntoElement,
5 ParentElement, Pixels, Point, RenderOnce, Role, ScrollHandle, SharedString, Size,
6 StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, TestSupportExt};
9use gpui_material_components::{Fab, FabColor, FabSize, Icon, IconName, Menu, MenuItem};
10use gpui_material_foundation::{animate, color, current_material_theme, move_roving_focus};
11use gpui_material_theme::{
12 ColorRole, CornerShape, Direction, Elevation, MotionKind, MotionScheme, MotionSpec, MotionSpeed,
13};
14
15use super::{
16 ActionIcon, FabContent, Invoke, Toolbar, ToolbarAction, ToolbarColor, ToolbarElevations,
17 ToolbarExitDirection, ToolbarFab, ToolbarFabPosition, ToolbarOrientation, ToolbarPlacement,
18 ToolbarScrollBehavior, ToolbarScrollState, activate_key, focus_handle,
19 layout::{StripGeometry, ToolbarSlot, arrange_horizontal},
20 style_button,
21};
22
23impl ActionIcon {
24 fn render_inline(&self) -> AnyElement {
25 match self {
26 Self::Symbol(icon) => Icon::new(*icon).size(px(24.)).into_any_element(),
27 Self::Custom(build) => build(),
28 }
29 }
30
31 fn render_overflow(&self) -> AnyElement {
32 match self {
33 Self::Symbol(icon) => Icon::new(*icon).size(px(20.)).into_any_element(),
34 Self::Custom(build) => build(),
35 }
36 }
37}
38
39#[derive(Clone, Copy)]
40struct ToolbarPalette {
41 surface: Hsla,
42 ink: Hsla,
43 selected_fill: Hsla,
44 selected_ink: Hsla,
45 ring: Hsla,
46 shadow: Hsla,
47 default_fab_color: FabColor,
48}
49
50impl ToolbarPalette {
51 fn resolve(toolbar: &Toolbar, tone: impl Fn(ColorRole) -> Hsla) -> Self {
52 let (surface_role, content_role, selected_role, selected_ink_role, default_fab_color) =
53 match toolbar.color {
54 ToolbarColor::Standard => (
55 ColorRole::SurfaceContainer,
56 ColorRole::OnSurfaceVariant,
57 ColorRole::SecondaryContainer,
58 ColorRole::OnSecondaryContainer,
59 FabColor::Primary,
60 ),
61 ToolbarColor::Vibrant => (
62 ColorRole::PrimaryContainer,
63 ColorRole::OnPrimaryContainer,
64 ColorRole::SurfaceContainer,
65 ColorRole::OnSurface,
66 FabColor::Tertiary,
67 ),
68 };
69 Self {
70 surface: toolbar
71 .colors
72 .container
73 .unwrap_or_else(|| tone(surface_role)),
74 ink: toolbar.colors.content.unwrap_or_else(|| tone(content_role)),
75 selected_fill: toolbar
76 .colors
77 .selected_container
78 .unwrap_or_else(|| tone(selected_role)),
79 selected_ink: toolbar
80 .colors
81 .selected_content
82 .unwrap_or_else(|| tone(selected_ink_role)),
83 ring: tone(ColorRole::Secondary),
84 shadow: tone(ColorRole::Shadow),
85 default_fab_color,
86 }
87 }
88}
89
90struct ScrollPresentation {
91 slide: Point<Pixels>,
92 hidden_strip: bool,
93}
94
95#[allow(clippy::too_many_arguments)]
96fn resolve_scroll_presentation(
97 toolbar: &mut Toolbar,
98 footprint: &Rc<Cell<Size<Pixels>>>,
99 behavior: ToolbarScrollBehavior,
100 scheme: MotionScheme,
101 reduced: bool,
102 exposed: bool,
103 rtl: bool,
104 window: &mut Window,
105 cx: &mut App,
106) -> ScrollPresentation {
107 let limit = behavior.exit_direction.map_or(0., |edge| {
108 let size = footprint.get();
109 f32::from(match edge {
110 ToolbarExitDirection::Start | ToolbarExitDirection::End => size.width,
111 ToolbarExitDirection::Top | ToolbarExitDirection::Bottom => size.height,
112 })
113 });
114 let scroll_state = toolbar.scroll_state.take().or_else(|| {
115 (toolbar.scroll.is_some() || toolbar.scroll_behavior.is_some()).then(|| {
116 window.use_keyed_state((toolbar.id.clone(), "scroll-expansion"), cx, |_, _| {
117 ToolbarScrollState::new()
118 })
119 })
120 });
121 let Some(state) = scroll_state else {
122 return ScrollPresentation {
123 slide: Point::default(),
124 hidden_strip: false,
125 };
126 };
127 let linked = toolbar.scroll.as_ref().map(|scroll| -scroll.offset().y);
128 let position = state.update(cx, |state, _| state.prepare(linked, limit, behavior));
129 let fraction = animate(
130 (toolbar.id.clone(), "toolbar-scroll"),
131 position.target,
132 position.motion.spec(behavior, scheme, reduced),
133 window,
134 cx,
135 )
136 .clamp(0., 1.);
137 toolbar.expanded &= position.expanded;
138 state.update(cx, |state, cx| {
139 if state.display(position, fraction, limit, exposed) {
140 cx.notify();
141 }
142 });
143 let distance = px(if exposed { 0. } else { fraction * limit });
144 let hidden_strip = limit > 0. && distance >= px(limit);
145 let slide = match behavior.exit_direction {
146 Some(ToolbarExitDirection::Top) => gpui::point(px(0.), -distance),
147 Some(ToolbarExitDirection::Bottom) => gpui::point(px(0.), distance),
148 Some(ToolbarExitDirection::Start) if rtl => gpui::point(distance, px(0.)),
149 Some(ToolbarExitDirection::End) if !rtl => gpui::point(distance, px(0.)),
150 Some(ToolbarExitDirection::Start | ToolbarExitDirection::End) => {
151 gpui::point(-distance, px(0.))
152 }
153 None => Point::default(),
154 };
155 ScrollPresentation {
156 slide,
157 hidden_strip,
158 }
159}
160
161fn partition_actions(
162 id: &ElementId,
163 actions: Vec<ToolbarAction>,
164 expanded: bool,
165 window: &mut Window,
166 cx: &mut App,
167) -> (Vec<(ToolbarAction, FocusHandle)>, Vec<ToolbarAction>) {
168 let mut visible = Vec::new();
169 let mut hidden = Vec::new();
170 for action in actions {
171 let action_id = ElementId::from((id.clone(), action.id.clone()));
172 let handle = focus_handle(&action_id, "focus", window, cx);
173 if expanded || !action.secondary || handle.is_focused(window) {
175 visible.push((action, handle));
176 } else {
177 hidden.push(action);
178 }
179 }
180 (visible, hidden)
181}
182
183fn render_fab(
184 toolbar: &Toolbar,
185 fab: ToolbarFab,
186 fab_focus: &FocusHandle,
187 default_color: FabColor,
188) -> AnyElement {
189 let content = match fab.content {
190 FabContent::Standard {
191 icon,
192 label,
193 invoke,
194 } => Fab::new((toolbar.id.clone(), "fab"), label, Icon::new(icon))
195 .track_focus(fab_focus)
196 .color(toolbar.fab_color.unwrap_or(default_color))
197 .colors(toolbar.fab_colors)
198 .size(if toolbar.expanded {
199 FabSize::Small
200 } else {
201 FabSize::Medium
202 })
203 .on_activate(move |window, cx| invoke(window, cx))
204 .into_any_element(),
205 FabContent::Custom(content) => content,
206 };
207 div().flex_none().child(content).into_any_element()
208}
209
210fn render_visible_actions(
211 id: &ElementId,
212 visible: Vec<(ToolbarAction, FocusHandle)>,
213 first_tab: Option<usize>,
214 palette: ToolbarPalette,
215) -> Vec<(AnyElement, FocusHandle)> {
216 visible
217 .into_iter()
218 .enumerate()
219 .map(|(index, (action, handle))| {
220 let callback = action.invoke;
221 let selected = action.selected.unwrap_or(false);
222 let fill = if selected {
223 palette.selected_fill
224 } else {
225 palette.surface
226 };
227 let foreground = if !action.enabled {
228 palette.ink.opacity(0.38)
229 } else if selected {
230 palette.selected_ink
231 } else {
232 palette.ink
233 };
234 let button = Button::new((id.clone(), action.id))
235 .track_focus(&handle)
236 .tab_stop(first_tab == Some(index))
237 .accessibility_label(action.label)
238 .disabled(!action.enabled)
239 .size(px(48.))
240 .flex_none()
241 .rounded_full()
242 .child(action.icon.render_inline())
243 .when_some(action.selected, |button, selected| {
244 button.aria_toggled(if selected {
245 gpui::accesskit::Toggled::True
246 } else {
247 gpui::accesskit::Toggled::False
248 })
249 })
250 .when_some(callback.filter(|_| action.enabled), |button, callback| {
251 let key = callback.clone();
252 let a11y = callback.clone();
253 button
254 .on_click(move |_, window, cx| callback(window, cx))
255 .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
256 a11y(window, cx)
257 })
258 .capture_key_down(move |event, window, cx| {
259 activate_key(event, window, cx, &*key)
260 })
261 });
262 (
263 style_button(button, fill, foreground, palette.ring, action.enabled)
264 .into_any_element(),
265 handle,
266 )
267 })
268 .collect()
269}
270
271#[allow(clippy::too_many_arguments)]
272fn render_overflow_menu(
273 id: &ElementId,
274 overflow_label: SharedString,
275 hidden: Vec<ToolbarAction>,
276 overflow_focus: FocusHandle,
277 is_tab_stop: bool,
278 horizontal: bool,
279 palette: ToolbarPalette,
280) -> (AnyElement, FocusHandle) {
281 let entries = hidden.into_iter().map(|action| {
282 let icon = action.icon;
283 let item = MenuItem::new(action.id, action.label)
284 .disabled(!action.enabled)
285 .leading(move || icon.render_overflow());
286 let item = if let Some(selected) = action.selected {
287 item.checked(selected)
288 } else {
289 item
290 };
291 if let Some(invoke) = action.invoke {
292 item.on_activate(move |window, cx| invoke(window, cx))
293 } else {
294 item
295 }
296 });
297 let trigger_id = id.clone();
298 let scroll_focus = overflow_focus.clone();
299 let trigger = move |open, toggle: Invoke| {
300 let focus = overflow_focus.clone();
301 let accessibility_toggle = toggle.clone();
302 let button = Button::new((trigger_id, "overflow"))
303 .accessibility_label(overflow_label)
304 .aria_expanded(open)
305 .track_focus(&overflow_focus)
306 .tab_stop(is_tab_stop)
307 .size(px(48.))
308 .rounded_full()
309 .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
310 focus.focus(window, cx);
311 toggle(window, cx);
312 })
313 .on_a11y_action(
314 if open {
315 gpui::AccessibleAction::Collapse
316 } else {
317 gpui::AccessibleAction::Expand
318 },
319 {
320 let focus = overflow_focus.clone();
321 move |_, window, cx| {
322 focus.focus(window, cx);
323 accessibility_toggle(window, cx);
324 }
325 },
326 )
327 .child(Icon::new(IconName::ArrowDropDown).size(px(24.)));
328 style_button(button, palette.surface, palette.ink, palette.ring, true).into_any_element()
329 };
330 (
331 div()
332 .flex_none()
333 .child(
334 Menu::composed((id.clone(), "overflow-menu"), entries, trigger).anchor(
335 if horizontal {
336 Anchor::BottomRight
337 } else {
338 Anchor::LeftCenter
339 },
340 ),
341 )
342 .into_any_element(),
343 scroll_focus,
344 )
345}
346
347#[allow(clippy::too_many_arguments)]
348fn sync_focused_scroll(
349 id: &ElementId,
350 strip_children: &[(AnyElement, FocusHandle)],
351 first_command: usize,
352 first_tab: Option<usize>,
353 arranged: bool,
354 mirrored: bool,
355 toolbar_scroll: &ScrollHandle,
356 window: &mut Window,
357 cx: &mut App,
358) {
359 let mut children_count = strip_children.len();
362 if arranged && children_count > 0 {
363 children_count = children_count * 2 + 1;
364 }
365 let reveal_index = strip_children
366 .iter()
367 .position(|(_, handle)| handle.contains_focused(window, cx))
368 .or_else(|| first_tab.map(|index| first_command + index))
369 .map(|index| {
370 let index = if arranged { index * 2 + 1 } else { index };
371 if mirrored {
372 children_count - index - 1
373 } else {
374 index
375 }
376 });
377 let reveal = window.use_keyed_state((id.clone(), "focused-action"), cx, |_, _| {
378 None::<(usize, Size<Pixels>)>
379 });
380 let target = reveal_index.map(|index| (index, toolbar_scroll.bounds().size));
381 reveal.update(cx, |previous, _| {
382 if *previous != target {
383 if let Some((index, _)) = target {
384 toolbar_scroll.scroll_to_item(index);
385 }
386 *previous = target;
387 }
388 });
389}
390
391impl RenderOnce for Toolbar {
392 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
393 if let Some(navigation) = self.navigation {
394 return navigation;
395 }
396 let theme = current_material_theme(window, cx);
397 let direction = theme.layout.direction;
398 let horizontal = self.orientation == ToolbarOrientation::Horizontal;
399 let rtl = direction == Direction::Rtl;
400 let docked = self.placement == ToolbarPlacement::Docked;
401 let palette = ToolbarPalette::resolve(&self, |role| color(theme.colors.color(role)));
402 let scheme = theme.motion;
403 let reduced = cx.reduce_motion();
404 let transition = if reduced {
405 MotionSpec::Instant
406 } else {
407 self.transition_motion
408 .unwrap_or_else(|| scheme.spec(MotionKind::Spatial, MotionSpeed::Fast, false))
409 };
410 let viewport = window.viewport_size();
411 let scope = focus_handle(&self.id, "strip-focus", window, cx);
412 let exposed = scope.contains_focused(window, cx);
413 let footprint = window
414 .use_keyed_state((self.id.clone(), "strip-footprint"), cx, |_, _| {
415 Rc::new(Cell::new(Size::<Pixels>::default()))
416 })
417 .read(cx)
418 .clone();
419 let behavior = self.scroll_behavior.unwrap_or_default();
420 let ScrollPresentation {
421 slide,
422 hidden_strip,
423 } = resolve_scroll_presentation(
424 &mut self, &footprint, behavior, scheme, reduced, exposed, rtl, window, cx,
425 );
426 let custom_surface = self.shape.is_some()
427 || self.elevations != ToolbarElevations::default()
428 || behavior.exit_direction.is_some()
429 || self.content.is_some()
430 || self.leading.is_some()
431 || self.trailing.is_some()
432 || self.arrangement.is_some() && docked && horizontal;
433 let elevation = if self.elevations != ToolbarElevations::default() {
434 let elevation = if self.expanded {
435 self.elevations.expanded
436 } else {
437 self.elevations.collapsed
438 };
439 animate(
440 (self.id.clone(), "toolbar-elevation"),
441 elevation.unwrap_or(Elevation::Level0).dp(),
442 transition,
443 window,
444 cx,
445 )
446 .max(0.)
447 } else {
448 0.
449 };
450 let arrangement = self.arrangement.filter(|_| docked && horizontal);
451 let spacing = self.spacing.min(if horizontal {
452 viewport.width
453 } else {
454 viewport.height
455 });
456 let toolbar_scroll = window
457 .use_keyed_state((self.id.clone(), "action-scroll"), cx, |_, _| {
458 ScrollHandle::new()
459 })
460 .read(cx)
461 .clone();
462
463 let actions = std::mem::take(&mut self.actions);
464 let (visible, hidden) = partition_actions(&self.id, actions, self.expanded, window, cx);
465 let has_more = !hidden.is_empty();
466 let overflow_focus = focus_handle(&self.id, "overflow-focus", window, cx);
467 let fab_focus = focus_handle(&self.id, "fab-focus", window, cx);
468 let fab = self.fab.take().filter(|_| !docked);
469 let fab_first = fab
470 .as_ref()
471 .is_some_and(|fab| fab.position == ToolbarFabPosition::Start);
472 let mut bar_order = visible
473 .iter()
474 .map(|(action, handle)| (handle.clone(), action.enabled))
475 .collect::<Vec<_>>();
476 if has_more {
477 bar_order.push((overflow_focus.clone(), true));
478 }
479 let first_tab = bar_order
480 .iter()
481 .position(|(handle, enabled)| *enabled && handle.is_focused(window))
482 .or_else(|| bar_order.iter().position(|(_, enabled)| *enabled));
483 let mirrored = horizontal && rtl;
484 let standard_fab = fab
485 .as_ref()
486 .is_some_and(|fab| matches!(fab.content, FabContent::Standard { .. }));
487 let fab_element =
488 fab.map(|fab| render_fab(&self, fab, &fab_focus, palette.default_fab_color));
489
490 let mut action_strip = div()
491 .id((self.id.clone(), "actions"))
492 .test_support()
493 .track_focus(&scope)
494 .tab_stop(false)
495 .flex()
496 .items_center()
497 .min_w_0()
498 .min_h_0()
499 .flex_shrink(1.)
500 .when(horizontal, |strip| strip.max_w_full().overflow_x_scroll())
501 .when(!horizontal, |strip| {
502 strip.flex_col().max_h_full().overflow_y_scroll()
503 })
504 .track_scroll(&toolbar_scroll)
505 .text_color(palette.ink)
506 .when(!custom_surface, |strip| {
507 strip
508 .bg(palette.surface)
509 .when(!docked, Styled::rounded_full)
510 })
511 .when(docked && horizontal, Styled::w_full)
512 .when(docked && !horizontal, Styled::h_full)
513 .when_else(
514 horizontal,
515 |strip| strip.min_h(px(64.)),
516 |strip| strip.min_w(px(64.)),
517 )
518 .when_else(
519 horizontal,
520 |strip| strip.px(px(if docked { 16. } else { 8. })).py(px(8.)),
521 |strip| strip.py(px(if docked { 16. } else { 8. })).px(px(8.)),
522 )
523 .when_some(
524 self.expanded_height.filter(|_| horizontal && docked),
525 |strip, height| {
526 strip
527 .h(height.min(viewport.height))
528 .min_h_0()
529 .overflow_y_hidden()
530 },
531 )
532 .gap(if arrangement.is_some() {
533 px(0.)
534 } else {
535 spacing
536 });
537 if let Some(padding) = self.padding {
538 action_strip = padding.apply(action_strip, direction, viewport);
539 }
540
541 let mut commands = render_visible_actions(&self.id, visible, first_tab, palette);
542 if has_more {
543 let count = bar_order.len();
544 commands.push(render_overflow_menu(
545 &self.id,
546 self.overflow_label,
547 hidden,
548 overflow_focus,
549 first_tab == Some(count - 1),
550 horizontal,
551 palette,
552 ));
553 }
554
555 let mut strip_children = Vec::new();
556 if hidden_strip {
557 bar_order.clear();
558 } else {
559 let mut side = |part, element, expanded: Option<bool>| {
560 let slot = ToolbarSlot::new(&self.id, part, element, window, cx);
561 window.with_id(self.id.clone(), |window| {
564 window.with_id((self.id.clone(), "actions"), |window| {
565 slot.expandable(
566 expanded.unwrap_or(self.expanded),
567 horizontal,
568 transition,
569 palette.ink,
570 window,
571 cx,
572 )
573 })
574 })
575 };
576 let leading = self
577 .leading
578 .take()
579 .and_then(|element| side("leading", element, self.leading_expanded));
580 let trailing = self
581 .trailing
582 .take()
583 .and_then(|element| side("trailing", element, self.trailing_expanded));
584 strip_children.extend(leading);
585 strip_children.extend(
586 self.content.take().map(|element| {
587 ToolbarSlot::new(&self.id, "body", element, window, cx).content()
588 }),
589 );
590 let first_command = strip_children.len();
591 strip_children.extend(commands);
592 strip_children.extend(trailing);
593
594 sync_focused_scroll(
595 &self.id,
596 &strip_children,
597 first_command,
598 first_tab,
599 arrangement.is_some(),
600 mirrored,
601 &toolbar_scroll,
602 window,
603 cx,
604 );
605 }
606
607 let mut children = strip_children
608 .into_iter()
609 .map(|(element, _)| element)
610 .collect::<Vec<_>>();
611 if let Some(arrangement) = arrangement {
612 children = arrange_horizontal(children, arrangement, spacing);
613 }
614 if mirrored {
615 children.reverse();
616 }
617 action_strip = action_strip.children(children);
618 let action_strip = if custom_surface {
619 StripGeometry {
620 horizontal,
621 docked,
622 direction,
623 footprint,
624 track_footprint: behavior.exit_direction.is_some(),
625 shape: self.shape.unwrap_or(if docked {
626 CornerShape::Radii([0.; 4])
627 } else {
628 CornerShape::Full
629 }),
630 surface: palette.surface,
631 shadow: palette.shadow,
632 elevation,
633 slide,
634 hidden: hidden_strip,
635 }
636 .frame(action_strip)
637 } else {
638 action_strip.into_any_element()
639 };
640 if standard_fab {
641 let index = if fab_first { 0 } else { bar_order.len() };
642 bar_order.insert(index, (fab_focus, true));
643 }
644 let root = div()
645 .id(self.id)
646 .test_support()
647 .role(Role::Toolbar)
648 .aria_label(self.label)
649 .aria_orientation(if horizontal {
650 gpui::accesskit::Orientation::Horizontal
651 } else {
652 gpui::accesskit::Orientation::Vertical
653 })
654 .flex()
655 .items_center()
656 .min_w_0()
657 .min_h_0()
658 .max_w_full()
659 .max_h_full()
660 .when(horizontal && rtl, Styled::flex_row_reverse)
661 .when(!horizontal, Styled::flex_col)
662 .when(docked && horizontal, Styled::w_full)
663 .when(docked && !horizontal, Styled::h_full)
664 .gap(px(4.))
665 .on_key_down(move |event, window, cx| {
666 if event.keystroke.modifiers.modified()
667 || !bar_order
668 .iter()
669 .any(|(handle, _)| handle.is_focused(window))
670 {
671 return;
672 }
673 let items = bar_order
674 .iter()
675 .map(|(handle, enabled)| (handle, *enabled))
676 .collect::<Vec<_>>();
677 if move_roving_focus(
678 &items,
679 &event.keystroke.key,
680 if horizontal {
681 Axis::Horizontal
682 } else {
683 Axis::Vertical
684 },
685 direction,
686 window,
687 cx,
688 )
689 .is_some()
690 {
691 window.refresh();
692 cx.stop_propagation();
693 }
694 });
695 if fab_first {
696 root.children(fab_element)
697 .child(action_strip)
698 .into_any_element()
699 } else {
700 root.child(action_strip)
701 .children(fab_element)
702 .into_any_element()
703 }
704 }
705}