1use std::{cell::RefCell, collections::HashMap, rc::Rc};
17
18use arc_motion::{
19 LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
20 sample_shared_layout,
21};
22use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, ThemeMode, Typography};
23use gpui_kit::{
24 App, BorderStyle, Bounds, Edges, ElementId, Hsla, IntoElement, MouseButton, ParentElement,
25 Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
26 base::Button as BaseButton, bounds, canvas, deferred, div, point, prelude::*, px, quad, size,
27};
28
29use crate::overlay::tooltip::TooltipSide;
30
31fn with_alpha(color: Hsla, alpha: f32) -> Hsla {
32 Hsla {
33 a: (color.a * alpha).clamp(0.0, 1.0),
34 ..color
35 }
36}
37
38type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
39type ActionHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
40
41pub const FBG_PRESS_SCALE: f32 = 0.965;
43
44pub const FBG_APPEAR_SCALE: f32 = 0.94;
46
47#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
48pub enum FloatingButtonGroupVariant {
49 #[default]
50 Muted,
51 Floating,
52}
53
54#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
55pub enum FloatingButtonGroupSize {
56 Sm,
57 #[default]
58 Md,
59}
60
61impl FloatingButtonGroupSize {
62 pub const fn item_height(self) -> Pixels {
63 match self {
64 Self::Sm => px(28.0),
65 Self::Md => px(32.0),
66 }
67 }
68
69 pub const fn tray_pad(self) -> Pixels {
70 match self {
71 Self::Sm => px(3.0),
72 Self::Md => px(3.0),
73 }
74 }
75
76 pub const fn item_gap(self) -> Pixels {
77 match self {
78 Self::Sm => px(2.0),
79 Self::Md => px(3.0),
80 }
81 }
82
83 pub const fn item_pad_x(self) -> Pixels {
84 match self {
85 Self::Sm => px(8.0),
86 Self::Md => px(10.0),
87 }
88 }
89
90 pub fn outer_radius(self) -> Pixels {
91 match self {
92 Self::Sm => Radii::CONTROL,
93 Self::Md => Radii::PANEL,
94 }
95 }
96
97 pub fn inner_radius(self) -> Pixels {
98 (self.outer_radius() - self.tray_pad()).max(px(5.0))
99 }
100}
101
102#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
103pub enum FloatingButtonGroupOrientation {
104 #[default]
105 Horizontal,
106 Vertical,
107}
108
109#[derive(Clone)]
110pub struct FloatingButtonGroupAction {
111 pub id: SharedString,
112 pub label: SharedString,
113 pub icon: Option<IconName>,
114 pub icon_only: Option<bool>,
115 pub disabled: bool,
116 pub pressed: Option<bool>,
117 pub shortcut: Option<SharedString>,
118 pub reserve_labels: Vec<SharedString>,
119 pub on_select: Option<SelectHandler>,
120}
121
122impl FloatingButtonGroupAction {
123 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
124 Self {
125 id: id.into(),
126 label: label.into(),
127 icon: None,
128 icon_only: None,
129 disabled: false,
130 pressed: None,
131 shortcut: None,
132 reserve_labels: Vec::new(),
133 on_select: None,
134 }
135 }
136
137 pub fn icon(mut self, icon: IconName) -> Self {
138 self.icon = Some(icon);
139 self
140 }
141
142 pub fn icon_only(mut self, icon_only: bool) -> Self {
143 self.icon_only = Some(icon_only);
144 self
145 }
146
147 pub fn disabled(mut self, disabled: bool) -> Self {
148 self.disabled = disabled;
149 self
150 }
151
152 pub fn pressed(mut self, pressed: bool) -> Self {
153 self.pressed = Some(pressed);
154 self
155 }
156
157 pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
158 self.shortcut = Some(shortcut.into());
159 self
160 }
161
162 pub fn reserve_labels<I, S>(mut self, labels: I) -> Self
163 where
164 I: IntoIterator<Item = S>,
165 S: Into<SharedString>,
166 {
167 self.reserve_labels = labels.into_iter().map(Into::into).collect();
168 self
169 }
170
171 pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
172 self.on_select = Some(Rc::new(handler));
173 self
174 }
175}
176
177#[derive(Clone)]
178pub enum FloatingButtonGroupItem {
179 Action(FloatingButtonGroupAction),
180 Separator(Option<SharedString>),
181}
182
183impl FloatingButtonGroupItem {
184 pub fn action(action: FloatingButtonGroupAction) -> Self {
185 Self::Action(action)
186 }
187
188 pub fn separator() -> Self {
189 Self::Separator(None)
190 }
191
192 pub fn separator_with_id(id: impl Into<SharedString>) -> Self {
193 Self::Separator(Some(id.into()))
194 }
195}
196
197impl From<FloatingButtonGroupAction> for FloatingButtonGroupItem {
198 fn from(action: FloatingButtonGroupAction) -> Self {
199 Self::Action(action)
200 }
201}
202
203pub fn fbg_highlight_target_scale(has_active: bool, pressing: bool) -> f32 {
205 if has_active && pressing {
206 FBG_PRESS_SCALE
207 } else {
208 1.0
209 }
210}
211
212pub fn fbg_reserved_content_width(
215 label: &str,
216 reserve_labels: &[SharedString],
217 has_icon: bool,
218 icon_only: bool,
219 size: FloatingButtonGroupSize,
220) -> f32 {
221 if icon_only {
222 return 16.0;
223 }
224 let char_adv = match size {
225 FloatingButtonGroupSize::Sm => 6.8,
226 FloatingButtonGroupSize::Md => 7.6,
227 };
228 let max_chars = std::iter::once(label)
229 .chain(reserve_labels.iter().map(|s| s.as_ref()))
230 .map(|s| {
231 s.chars()
232 .map(|c| if c.is_ascii() { 1.0_f32 } else { 1.75_f32 })
233 .sum::<f32>()
234 })
235 .fold(0.0_f32, f32::max);
236 let icon_part = if has_icon { 16.0 + 6.0 } else { 0.0 };
237 (max_chars * char_adv + icon_part).ceil()
238}
239
240pub fn scale_bounds_around_center(rect: Bounds<Pixels>, factor: f32) -> Bounds<Pixels> {
242 let w = f32::from(rect.size.width);
243 let h = f32::from(rect.size.height);
244 let nw = (w * factor).max(0.0);
245 let nh = (h * factor).max(0.0);
246 let dx = (w - nw) * 0.5;
247 let dy = (h - nh) * 0.5;
248 bounds(
249 point(rect.origin.x + px(dx), rect.origin.y + px(dy)),
250 size(px(nw), px(nh)),
251 )
252}
253
254#[derive(Clone, Default)]
255struct FloatingButtonGroupInternal {
256 hovered_id: Option<SharedString>,
257 pressed_id: Option<SharedString>,
258 item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
259 tray_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
260}
261
262#[derive(IntoElement)]
265pub struct FloatingButtonGroup {
266 id: ElementId,
267 label: SharedString,
268 items: Vec<FloatingButtonGroupItem>,
269 variant: FloatingButtonGroupVariant,
270 size: FloatingButtonGroupSize,
271 orientation: FloatingButtonGroupOrientation,
272 icon_only: bool,
273 tooltip_side: Option<TooltipSide>,
274 on_action: Option<ActionHandler>,
275}
276
277impl FloatingButtonGroup {
278 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
279 Self {
280 id: id.into(),
281 label: label.into(),
282 items: Vec::new(),
283 variant: FloatingButtonGroupVariant::Muted,
284 size: FloatingButtonGroupSize::Md,
285 orientation: FloatingButtonGroupOrientation::Horizontal,
286 icon_only: false,
287 tooltip_side: None,
288 on_action: None,
289 }
290 }
291
292 pub fn item(mut self, item: impl Into<FloatingButtonGroupItem>) -> Self {
293 self.items.push(item.into());
294 self
295 }
296
297 pub fn items(mut self, items: impl IntoIterator<Item = FloatingButtonGroupItem>) -> Self {
298 self.items.extend(items);
299 self
300 }
301
302 pub fn variant(mut self, variant: FloatingButtonGroupVariant) -> Self {
303 self.variant = variant;
304 self
305 }
306
307 pub fn size(mut self, size: FloatingButtonGroupSize) -> Self {
308 self.size = size;
309 self
310 }
311
312 pub fn orientation(mut self, orientation: FloatingButtonGroupOrientation) -> Self {
313 self.orientation = orientation;
314 self
315 }
316
317 pub fn icon_only(mut self, icon_only: bool) -> Self {
318 self.icon_only = icon_only;
319 self
320 }
321
322 pub fn tooltip_side(mut self, side: TooltipSide) -> Self {
323 self.tooltip_side = Some(side);
324 self
325 }
326
327 pub fn on_action(
328 mut self,
329 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
330 ) -> Self {
331 self.on_action = Some(Rc::new(handler));
332 self
333 }
334}
335
336impl RenderOnce for FloatingButtonGroup {
337 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
338 let theme = cx.arc_theme().clone();
339 let colors = theme.colors;
340 let motion = theme.motion;
341 let reduced = is_reduced_motion(cx);
342 let dark = theme.mode == ThemeMode::Dark;
343
344 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-fbg-state".into());
345 let internal =
346 window.use_keyed_state(state_id, cx, |_, _| FloatingButtonGroupInternal::default());
347 let snap = internal.read(cx).clone();
348
349 let vertical = self.orientation == FloatingButtonGroupOrientation::Vertical;
350 let resolved_tip_side = self.tooltip_side.unwrap_or(if vertical {
351 TooltipSide::Right
352 } else {
353 TooltipSide::Top
354 });
355
356 let enabled_action = |id: &SharedString| -> bool {
357 self.items.iter().any(|it| {
358 matches!(
359 it,
360 FloatingButtonGroupItem::Action(a) if &a.id == id && !a.disabled
361 )
362 })
363 };
364
365 let active_id: Option<SharedString> = snap
366 .hovered_id
367 .as_ref()
368 .filter(|id| enabled_action(id))
369 .cloned()
370 .or_else(|| {
371 snap.pressed_id
372 .as_ref()
373 .filter(|id| enabled_action(id))
374 .cloned()
375 });
376
377 let pressing = active_id.is_some() && active_id == snap.pressed_id;
378
379 let highlight_opacity = arc_transition(
380 (self.id.clone(), "fbg-hi-op"),
381 if active_id.is_some() { 1.0 } else { 0.0 },
382 if reduced {
383 motion.duration.instant
384 } else if active_id.is_some() {
385 motion.duration.fast
386 } else {
387 motion.duration.standard
388 },
389 motion.ease.standard,
390 window,
391 cx,
392 );
393
394 let target_scale = fbg_highlight_target_scale(active_id.is_some(), pressing);
395 let highlight_scale = if reduced {
396 target_scale
397 } else {
398 arc_spring(
399 (self.id.clone(), "fbg-hi-scale"),
400 if active_id.is_some() {
401 target_scale
402 } else {
403 FBG_APPEAR_SCALE
404 },
405 motion.spring.snappy,
406 window,
407 cx,
408 )
409 };
410
411 let hi_alpha = if pressing {
413 if dark { 0.15 } else { 0.12 }
414 } else if dark {
415 0.09
416 } else {
417 0.07
418 };
419 let hi_color = with_alpha(colors.foreground, hi_alpha * highlight_opacity);
420 let on_tint = with_alpha(colors.control_on, if dark { 0.16 } else { 0.12 });
421 let rule_color = with_alpha(colors.foreground, 0.12);
422 let (tray_bg, tray_border) = match self.variant {
423 FloatingButtonGroupVariant::Muted => (
424 with_alpha(colors.foreground, if dark { 0.06 } else { 0.045 }),
425 with_alpha(colors.foreground, if dark { 0.05 } else { 0.03 }),
426 ),
427 FloatingButtonGroupVariant::Floating => (colors.surface_raised, colors.border),
428 };
429
430 let item_h = self.size.item_height();
431 let tray_pad = self.size.tray_pad();
432 let item_gap = self.size.item_gap();
433 let item_pad_x = self.size.item_pad_x();
434 let outer_radius = self.size.outer_radius();
435 let inner_radius = self.size.inner_radius();
436
437 let scope = layout_scope_key(&self.id);
439 let item_bounds_ref = snap.item_bounds.clone();
440 let tray_bounds_ref = snap.tray_bounds.clone();
441 let active_for_hi = active_id.clone();
442 let morph_spring = motion.spring.morph;
443
444 let highlight_canvas = canvas(
445 move |rect, _, _| {
446 *tray_bounds_ref.borrow_mut() = Some(rect);
447 },
448 move |tray_rect, _, window, cx| {
449 if let Some(key) = &active_for_hi
450 && highlight_opacity > 0.01
451 && let Some(item_rect) = item_bounds_ref.borrow().get(key).copied()
452 {
453 let local_rect = bounds(
454 point(
455 item_rect.origin.x - tray_rect.origin.x,
456 item_rect.origin.y - tray_rect.origin.y,
457 ),
458 item_rect.size,
459 );
460 let target = LayoutSnapshot::uniform_radius(local_rect, inner_radius);
461 let flip = sample_shared_layout(
462 scope.clone(),
463 "fbg-highlight",
464 target,
465 if reduced { None } else { Some(morph_spring) },
466 window,
467 cx,
468 );
469 let world_rect =
470 bounds(tray_rect.origin + flip.bounds.origin, flip.bounds.size);
471 let scaled_rect = scale_bounds_around_center(world_rect, highlight_scale);
472 window.paint_quad(quad(
473 scaled_rect,
474 flip.corner_radii,
475 hi_color,
476 Edges::default(),
477 Hsla::transparent_black(),
478 BorderStyle::Solid,
479 ));
480 }
481 },
482 )
483 .absolute()
484 .inset_0();
485
486 let mut children = Vec::with_capacity(self.items.len());
487 let mut active_tip_overlay = None;
488
489 for (pos, item) in self.items.iter().enumerate() {
490 match item {
491 FloatingButtonGroupItem::Separator(sep_id) => {
492 let sep_key = sep_id
493 .clone()
494 .unwrap_or_else(|| SharedString::from(format!("sep-{pos}")));
495 let sep_len = item_h * 0.5;
496 let sep = if vertical {
497 div()
498 .id(ElementId::NamedChild(self.id.clone().into(), sep_key))
499 .flex_none()
500 .self_center()
501 .w(sep_len)
502 .h(px(1.0))
503 .my(px(2.0))
504 .rounded(px(1.0))
505 .bg(rule_color)
506 } else {
507 div()
508 .id(ElementId::NamedChild(self.id.clone().into(), sep_key))
509 .flex_none()
510 .self_center()
511 .w(px(1.0))
512 .h(sep_len)
513 .mx(px(2.0))
514 .rounded(px(1.0))
515 .bg(rule_color)
516 };
517 children.push(sep.into_any_element());
518 }
519 FloatingButtonGroupItem::Action(action) => {
520 let id = action.id.clone();
521 let is_icon_only =
522 action.icon.is_some() && action.icon_only.unwrap_or(self.icon_only);
523 let is_active = active_id.as_ref() == Some(&id);
524 let is_pressed_mode = action.pressed.unwrap_or(false);
525 let is_disabled = action.disabled;
526
527 let reserved_w = fbg_reserved_content_width(
528 action.label.as_ref(),
529 &action.reserve_labels,
530 action.icon.is_some(),
531 is_icon_only,
532 self.size,
533 );
534
535 let item_bounds = snap.item_bounds.clone();
536 let id_measure = id.clone();
537 let probe = canvas(
538 move |rect, _, _| {
539 item_bounds.borrow_mut().insert(id_measure.clone(), rect);
540 },
541 |_, _, _, _| {},
542 )
543 .absolute()
544 .inset_0();
545
546 let fg_color = if is_disabled {
547 colors.text_muted
548 } else if is_active || is_pressed_mode {
549 colors.foreground
550 } else {
551 colors.text_secondary
552 };
553
554 let btn_id = ElementId::NamedChild(
555 self.id.clone().into(),
556 SharedString::from(format!("item-{}", action.id)),
557 );
558
559 let int_hover = internal.clone();
560 let int_down = internal.clone();
561 let int_up = internal.clone();
562 let int_out = internal.clone();
563 let id_hover = id.clone();
564 let id_down = id.clone();
565 let id_click = id.clone();
566 let on_select = action.on_select.clone();
567 let on_action = self.on_action.clone();
568
569 let pad_left = if action.icon.is_some() && !is_icon_only {
570 (item_pad_x - px(2.0)).max(px(6.0))
571 } else {
572 item_pad_x
573 };
574
575 let btn = BaseButton::new(btn_id)
576 .disabled(is_disabled)
577 .accessibility_label(action.label.clone())
578 .on_click(move |_, window, cx| {
579 if is_disabled {
580 return;
581 }
582 if let Some(cb) = &on_select {
583 cb(&(), window, cx);
584 }
585 if let Some(cb) = &on_action {
586 cb(&id_click, window, cx);
587 }
588 window.refresh();
589 })
590 .relative()
591 .flex_none()
592 .flex()
593 .flex_row()
594 .items_center()
595 .when(vertical && !is_icon_only, |this| {
596 this.w_full().justify_start()
597 })
598 .when(!vertical || is_icon_only, |this| this.justify_center())
599 .when(vertical && is_icon_only, |this| this.self_center())
600 .h(item_h)
601 .when(is_icon_only, |this| this.w(item_h))
602 .when(!is_icon_only, |this| {
603 this.min_w(item_h).pl(pad_left).pr(item_pad_x)
604 })
605 .rounded(inner_radius)
606 .when(is_pressed_mode, |this| this.bg(on_tint))
607 .text_size(match self.size {
608 FloatingButtonGroupSize::Sm => Typography::TEXT_XS,
609 FloatingButtonGroupSize::Md => Typography::TEXT_SM,
610 })
611 .text_color(fg_color)
612 .when(is_disabled, |this| this.opacity(0.5))
613 .when(!is_disabled, |this| this.cursor_pointer())
614 .on_hover(move |hovered, window, cx| {
615 if is_disabled {
616 return;
617 }
618 int_hover.update(cx, |s, _| {
619 if *hovered {
620 s.hovered_id = Some(id_hover.clone());
621 } else if s.hovered_id.as_ref() == Some(&id_hover) {
622 s.hovered_id = None;
623 s.pressed_id = None;
624 }
625 });
626 window.refresh();
627 })
628 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
629 if is_disabled {
630 return;
631 }
632 int_down.update(cx, |s, _| {
633 s.hovered_id = Some(id_down.clone());
634 s.pressed_id = Some(id_down.clone());
635 });
636 window.refresh();
637 })
638 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
639 int_up.update(cx, |s, _| s.pressed_id = None);
640 window.refresh();
641 })
642 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
643 int_out.update(cx, |s, _| s.pressed_id = None);
644 window.refresh();
645 })
646 .child(probe)
647 .child(
648 div()
649 .flex()
650 .flex_row()
651 .items_center()
652 .when(!vertical || is_icon_only, |this| this.justify_center())
653 .when(vertical && !is_icon_only, |this| this.justify_start())
654 .when(!is_icon_only, |this| this.min_w(px(reserved_w)))
655 .gap(px(6.0))
656 .when_some(action.icon, |this, icon| this.child(icon))
657 .when(!is_icon_only, |this| this.child(action.label.clone())),
658 );
659
660 if is_active && (is_icon_only || action.shortcut.is_some()) {
661 let tip_label = action.label.clone();
662 let tip_shortcut = action.shortcut.clone();
663 let kbd_fg = with_alpha(colors.background, 0.58);
664 let tip_border = with_alpha(colors.background, 0.14);
665
666 let tip_bubble = div()
667 .px(Spacing::S3)
668 .py(Spacing::S2)
669 .rounded(Radii::CONTROL)
670 .border_1()
671 .border_color(tip_border)
672 .bg(colors.foreground)
673 .text_color(colors.background)
674 .text_size(Typography::TEXT_XS)
675 .shadow(Shadows::raised(theme.mode))
676 .flex()
677 .flex_row()
678 .items_center()
679 .gap(Spacing::S2)
680 .whitespace_nowrap()
681 .child(tip_label)
682 .when_some(tip_shortcut, |this, kbd| {
683 this.child(div().text_color(kbd_fg).child(kbd))
684 });
685
686 let positioned_tip = match resolved_tip_side {
687 TooltipSide::Top => div()
688 .absolute()
689 .bottom(item_h + tray_pad * 2.0 + px(8.0))
690 .left_0()
691 .child(tip_bubble),
692 TooltipSide::Bottom => div()
693 .absolute()
694 .top(item_h + tray_pad * 2.0 + px(8.0))
695 .left_0()
696 .child(tip_bubble),
697 TooltipSide::Right => div()
698 .absolute()
699 .left(item_h + tray_pad * 2.0 + px(8.0))
700 .top(px(pos as f32 * f32::from(item_h + item_gap)))
701 .child(tip_bubble),
702 TooltipSide::Left => div()
703 .absolute()
704 .right(item_h + tray_pad * 2.0 + px(8.0))
705 .top(px(pos as f32 * f32::from(item_h + item_gap)))
706 .child(tip_bubble),
707 };
708
709 active_tip_overlay = Some(deferred(positioned_tip).with_priority(2));
710 }
711
712 children.push(btn.into_any_element());
713 }
714 }
715 }
716
717 div()
718 .id(self.id)
719 .test_support()
720 .role(Role::Toolbar)
721 .aria_label(self.label)
722 .relative()
723 .self_start()
724 .flex_none()
725 .flex()
726 .when(vertical, |this| this.flex_col().items_stretch())
727 .when(!vertical, |this| this.flex_row().items_center())
728 .gap(item_gap)
729 .p(tray_pad)
730 .rounded(outer_radius)
731 .border_1()
732 .border_color(tray_border)
733 .bg(tray_bg)
734 .when(
735 self.variant == FloatingButtonGroupVariant::Floating,
736 |this| this.shadow(Shadows::floating(theme.mode)),
737 )
738 .child(highlight_canvas)
739 .children(children)
740 .when_some(active_tip_overlay, |this, tip| this.child(tip))
741 }
742}
743
744#[cfg(test)]
745mod tests {
746 use std::{cell::Cell, rc::Rc};
747
748 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
749 use gpui_kit::{
750 Context, MouseButton, Render, Role, TestAppContext, div,
751 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
752 };
753
754 use super::*;
755
756 #[test]
757 fn highlight_scale_and_reserved_width_behave_as_expected() {
758 assert!((fbg_highlight_target_scale(true, false) - 1.0).abs() < 1e-5);
759 assert!((fbg_highlight_target_scale(true, true) - FBG_PRESS_SCALE).abs() < 1e-5);
760 assert!((fbg_highlight_target_scale(false, true) - 1.0).abs() < 1e-5);
761
762 let w_short =
763 fbg_reserved_content_width("Share", &[], true, false, FloatingButtonGroupSize::Md);
764 let w_reserved = fbg_reserved_content_width(
765 "Share",
766 &[SharedString::from("Copied link")],
767 true,
768 false,
769 FloatingButtonGroupSize::Md,
770 );
771 assert!(w_reserved > w_short);
772
773 let w_same_after_swap = fbg_reserved_content_width(
774 "Copied link",
775 &[SharedString::from("Share")],
776 true,
777 false,
778 FloatingButtonGroupSize::Md,
779 );
780 assert!((w_reserved - w_same_after_swap).abs() < 1e-4);
781 }
782
783 struct Host {
784 count: Rc<Cell<usize>>,
785 last_action: Rc<RefCell<Option<SharedString>>>,
786 }
787
788 impl Render for Host {
789 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
790 let count = self.count.clone();
791 let last_action = self.last_action.clone();
792 div().p(Spacing::S6).child(
793 FloatingButtonGroup::new("board-toolbar", "Board actions")
794 .variant(FloatingButtonGroupVariant::Floating)
795 .items([
796 FloatingButtonGroupItem::action(
797 FloatingButtonGroupAction::new("comment", "Comment").on_select(
798 cx.listener(move |_, _, _, _| {
799 count.set(count.get() + 1);
800 }),
801 ),
802 ),
803 FloatingButtonGroupItem::separator(),
804 FloatingButtonGroupItem::action(
805 FloatingButtonGroupAction::new("share", "Share")
806 .reserve_labels(["Copied"])
807 .shortcut("⌘L"),
808 ),
809 ])
810 .on_action(cx.listener(move |_, id: &SharedString, _, _| {
811 *last_action.borrow_mut() = Some(id.clone());
812 })),
813 )
814 }
815 }
816
817 #[gpui_kit::test]
818 fn floating_button_group_fires_item_and_group_callbacks(cx: &mut TestAppContext) {
819 cx.update(|cx| {
820 gpui_kit::init(cx);
821 install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
822 });
823 let count = Rc::new(Cell::new(0usize));
824 let last_action = Rc::new(RefCell::new(None));
825 let (_view, cx) = cx.add_window_view(|_, _| Host {
826 count: count.clone(),
827 last_action: last_action.clone(),
828 });
829
830 cx.update(|window, cx| {
831 window.render_frame(cx);
832 let comment = window.find_by_label("Comment");
833 assert_eq!(comment.role(), Some(Role::Button));
834 let pos = comment.bounds().center();
835 window.pointer_down(pos, MouseButton::Left, cx);
836 window.pointer_up(pos, MouseButton::Left, cx);
837 assert_eq!(count.get(), 1);
838 assert_eq!(last_action.borrow().as_deref(), Some("comment"));
839 });
840 }
841}