arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/floating-button-group/floating-button-group.tsx` & `.module.css`
//!
//! P3 Component #15: `floating-button-group`
//!
//! - Separate soft buttons in a quiet tray with real gaps (`4px` in `Md`, `3px` in `Sm`).
//! - Variants: `Muted` (translucent quiet tint) | `Floating` (raised surface + floating shadow).
//! - Sizes: `Sm` (30px button height) | `Md` (36px button height).
//! - Orientations: `Horizontal` | `Vertical`.
//! - One shared highlight pill travels between active items along `motion.spring.morph`,
//!   scales from `0.94 -> 1.0` when appearing, and settles to `0.965` with darker fill while pressed.
//! - Supports `pressed` mode buttons (persistent quiet tint), hairline separators,
//!   `reserve_labels` fixed-width slots so dynamic label swaps never shift neighbors,
//!   and directional shortcut tooltips (`Top | Bottom | Left | Right`).

use std::{cell::RefCell, collections::HashMap, rc::Rc};

use arc_motion::{
    LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
    sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, ThemeMode, Typography};
use gpui_kit::{
    App, BorderStyle, Bounds, Edges, ElementId, Hsla, IntoElement, MouseButton, ParentElement,
    Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
    base::Button as BaseButton, bounds, canvas, deferred, div, point, prelude::*, px, quad, size,
};

use crate::overlay::tooltip::TooltipSide;

fn with_alpha(color: Hsla, alpha: f32) -> Hsla {
    Hsla {
        a: (color.a * alpha).clamp(0.0, 1.0),
        ..color
    }
}

type SelectHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
type ActionHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

/// Press scale factor applied to the shared highlight pill while a button is held down.
pub const FBG_PRESS_SCALE: f32 = 0.965;

/// Initial entrance scale factor when the highlight first appears from idle.
pub const FBG_APPEAR_SCALE: f32 = 0.94;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupVariant {
    #[default]
    Muted,
    Floating,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupSize {
    Sm,
    #[default]
    Md,
}

impl FloatingButtonGroupSize {
    pub const fn item_height(self) -> Pixels {
        match self {
            Self::Sm => px(28.0),
            Self::Md => px(32.0),
        }
    }

    pub const fn tray_pad(self) -> Pixels {
        match self {
            Self::Sm => px(3.0),
            Self::Md => px(3.0),
        }
    }

    pub const fn item_gap(self) -> Pixels {
        match self {
            Self::Sm => px(2.0),
            Self::Md => px(3.0),
        }
    }

    pub const fn item_pad_x(self) -> Pixels {
        match self {
            Self::Sm => px(8.0),
            Self::Md => px(10.0),
        }
    }

    pub fn outer_radius(self) -> Pixels {
        match self {
            Self::Sm => Radii::CONTROL,
            Self::Md => Radii::PANEL,
        }
    }

    pub fn inner_radius(self) -> Pixels {
        (self.outer_radius() - self.tray_pad()).max(px(5.0))
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum FloatingButtonGroupOrientation {
    #[default]
    Horizontal,
    Vertical,
}

#[derive(Clone)]
pub struct FloatingButtonGroupAction {
    pub id: SharedString,
    pub label: SharedString,
    pub icon: Option<IconName>,
    pub icon_only: Option<bool>,
    pub disabled: bool,
    pub pressed: Option<bool>,
    pub shortcut: Option<SharedString>,
    pub reserve_labels: Vec<SharedString>,
    pub on_select: Option<SelectHandler>,
}

impl FloatingButtonGroupAction {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            icon: None,
            icon_only: None,
            disabled: false,
            pressed: None,
            shortcut: None,
            reserve_labels: Vec::new(),
            on_select: None,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn icon_only(mut self, icon_only: bool) -> Self {
        self.icon_only = Some(icon_only);
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn pressed(mut self, pressed: bool) -> Self {
        self.pressed = Some(pressed);
        self
    }

    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    pub fn reserve_labels<I, S>(mut self, labels: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.reserve_labels = labels.into_iter().map(Into::into).collect();
        self
    }

    pub fn on_select(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }
}

#[derive(Clone)]
pub enum FloatingButtonGroupItem {
    Action(FloatingButtonGroupAction),
    Separator(Option<SharedString>),
}

impl FloatingButtonGroupItem {
    pub fn action(action: FloatingButtonGroupAction) -> Self {
        Self::Action(action)
    }

    pub fn separator() -> Self {
        Self::Separator(None)
    }

    pub fn separator_with_id(id: impl Into<SharedString>) -> Self {
        Self::Separator(Some(id.into()))
    }
}

impl From<FloatingButtonGroupAction> for FloatingButtonGroupItem {
    fn from(action: FloatingButtonGroupAction) -> Self {
        Self::Action(action)
    }
}

/// Computes the scale of the shared highlight pill (`0.965` while pressing an active button, `1.0` at rest).
pub fn fbg_highlight_target_scale(has_active: bool, pressing: bool) -> f32 {
    if has_active && pressing {
        FBG_PRESS_SCALE
    } else {
        1.0
    }
}

/// Estimates the minimum reserved content width (in `px`) across `label` and `reserve_labels`
/// so dynamic label swaps (e.g. `"Share" -> "Copied"`) never resize the button or shift neighbors.
pub fn fbg_reserved_content_width(
    label: &str,
    reserve_labels: &[SharedString],
    has_icon: bool,
    icon_only: bool,
    size: FloatingButtonGroupSize,
) -> f32 {
    if icon_only {
        return 16.0;
    }
    let char_adv = match size {
        FloatingButtonGroupSize::Sm => 6.8,
        FloatingButtonGroupSize::Md => 7.6,
    };
    let max_chars = std::iter::once(label)
        .chain(reserve_labels.iter().map(|s| s.as_ref()))
        .map(|s| {
            s.chars()
                .map(|c| if c.is_ascii() { 1.0_f32 } else { 1.75_f32 })
                .sum::<f32>()
        })
        .fold(0.0_f32, f32::max);
    let icon_part = if has_icon { 16.0 + 6.0 } else { 0.0 };
    (max_chars * char_adv + icon_part).ceil()
}

/// Scale bounds around center for the highlight pill.
pub fn scale_bounds_around_center(rect: Bounds<Pixels>, factor: f32) -> Bounds<Pixels> {
    let w = f32::from(rect.size.width);
    let h = f32::from(rect.size.height);
    let nw = (w * factor).max(0.0);
    let nh = (h * factor).max(0.0);
    let dx = (w - nw) * 0.5;
    let dy = (h - nh) * 0.5;
    bounds(
        point(rect.origin.x + px(dx), rect.origin.y + px(dy)),
        size(px(nw), px(nh)),
    )
}

#[derive(Clone, Default)]
struct FloatingButtonGroupInternal {
    hovered_id: Option<SharedString>,
    pressed_id: Option<SharedString>,
    item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
    tray_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}

/// Arc `FloatingButtonGroup`: separate soft buttons in a quiet or raised tray with one shared
/// morphing highlight pill, fixed-width reserved label slots, and directional shortcut tooltips.
#[derive(IntoElement)]
pub struct FloatingButtonGroup {
    id: ElementId,
    label: SharedString,
    items: Vec<FloatingButtonGroupItem>,
    variant: FloatingButtonGroupVariant,
    size: FloatingButtonGroupSize,
    orientation: FloatingButtonGroupOrientation,
    icon_only: bool,
    tooltip_side: Option<TooltipSide>,
    on_action: Option<ActionHandler>,
}

impl FloatingButtonGroup {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            items: Vec::new(),
            variant: FloatingButtonGroupVariant::Muted,
            size: FloatingButtonGroupSize::Md,
            orientation: FloatingButtonGroupOrientation::Horizontal,
            icon_only: false,
            tooltip_side: None,
            on_action: None,
        }
    }

    pub fn item(mut self, item: impl Into<FloatingButtonGroupItem>) -> Self {
        self.items.push(item.into());
        self
    }

    pub fn items(mut self, items: impl IntoIterator<Item = FloatingButtonGroupItem>) -> Self {
        self.items.extend(items);
        self
    }

    pub fn variant(mut self, variant: FloatingButtonGroupVariant) -> Self {
        self.variant = variant;
        self
    }

    pub fn size(mut self, size: FloatingButtonGroupSize) -> Self {
        self.size = size;
        self
    }

    pub fn orientation(mut self, orientation: FloatingButtonGroupOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    pub fn icon_only(mut self, icon_only: bool) -> Self {
        self.icon_only = icon_only;
        self
    }

    pub fn tooltip_side(mut self, side: TooltipSide) -> Self {
        self.tooltip_side = Some(side);
        self
    }

    pub fn on_action(
        mut self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_action = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for FloatingButtonGroup {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let dark = theme.mode == ThemeMode::Dark;

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-fbg-state".into());
        let internal =
            window.use_keyed_state(state_id, cx, |_, _| FloatingButtonGroupInternal::default());
        let snap = internal.read(cx).clone();

        let vertical = self.orientation == FloatingButtonGroupOrientation::Vertical;
        let resolved_tip_side = self.tooltip_side.unwrap_or(if vertical {
            TooltipSide::Right
        } else {
            TooltipSide::Top
        });

        let enabled_action = |id: &SharedString| -> bool {
            self.items.iter().any(|it| {
                matches!(
                    it,
                    FloatingButtonGroupItem::Action(a) if &a.id == id && !a.disabled
                )
            })
        };

        let active_id: Option<SharedString> = snap
            .hovered_id
            .as_ref()
            .filter(|id| enabled_action(id))
            .cloned()
            .or_else(|| {
                snap.pressed_id
                    .as_ref()
                    .filter(|id| enabled_action(id))
                    .cloned()
            });

        let pressing = active_id.is_some() && active_id == snap.pressed_id;

        let highlight_opacity = arc_transition(
            (self.id.clone(), "fbg-hi-op"),
            if active_id.is_some() { 1.0 } else { 0.0 },
            if reduced {
                motion.duration.instant
            } else if active_id.is_some() {
                motion.duration.fast
            } else {
                motion.duration.standard
            },
            motion.ease.standard,
            window,
            cx,
        );

        let target_scale = fbg_highlight_target_scale(active_id.is_some(), pressing);
        let highlight_scale = if reduced {
            target_scale
        } else {
            arc_spring(
                (self.id.clone(), "fbg-hi-scale"),
                if active_id.is_some() {
                    target_scale
                } else {
                    FBG_APPEAR_SCALE
                },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // Palette tokens matching `.group` in `floating-button-group.module.css`
        let hi_alpha = if pressing {
            if dark { 0.15 } else { 0.12 }
        } else if dark {
            0.09
        } else {
            0.07
        };
        let hi_color = with_alpha(colors.foreground, hi_alpha * highlight_opacity);
        let on_tint = with_alpha(colors.control_on, if dark { 0.16 } else { 0.12 });
        let rule_color = with_alpha(colors.foreground, 0.12);
        let (tray_bg, tray_border) = match self.variant {
            FloatingButtonGroupVariant::Muted => (
                with_alpha(colors.foreground, if dark { 0.06 } else { 0.045 }),
                with_alpha(colors.foreground, if dark { 0.05 } else { 0.03 }),
            ),
            FloatingButtonGroupVariant::Floating => (colors.surface_raised, colors.border),
        };

        let item_h = self.size.item_height();
        let tray_pad = self.size.tray_pad();
        let item_gap = self.size.item_gap();
        let item_pad_x = self.size.item_pad_x();
        let outer_radius = self.size.outer_radius();
        let inner_radius = self.size.inner_radius();

        // Shared highlight pill rendered in tray-local coordinates on `motion.spring.morph`.
        let scope = layout_scope_key(&self.id);
        let item_bounds_ref = snap.item_bounds.clone();
        let tray_bounds_ref = snap.tray_bounds.clone();
        let active_for_hi = active_id.clone();
        let morph_spring = motion.spring.morph;

        let highlight_canvas = canvas(
            move |rect, _, _| {
                *tray_bounds_ref.borrow_mut() = Some(rect);
            },
            move |tray_rect, _, window, cx| {
                if let Some(key) = &active_for_hi
                    && highlight_opacity > 0.01
                    && let Some(item_rect) = item_bounds_ref.borrow().get(key).copied()
                {
                    let local_rect = bounds(
                        point(
                            item_rect.origin.x - tray_rect.origin.x,
                            item_rect.origin.y - tray_rect.origin.y,
                        ),
                        item_rect.size,
                    );
                    let target = LayoutSnapshot::uniform_radius(local_rect, inner_radius);
                    let flip = sample_shared_layout(
                        scope.clone(),
                        "fbg-highlight",
                        target,
                        if reduced { None } else { Some(morph_spring) },
                        window,
                        cx,
                    );
                    let world_rect =
                        bounds(tray_rect.origin + flip.bounds.origin, flip.bounds.size);
                    let scaled_rect = scale_bounds_around_center(world_rect, highlight_scale);
                    window.paint_quad(quad(
                        scaled_rect,
                        flip.corner_radii,
                        hi_color,
                        Edges::default(),
                        Hsla::transparent_black(),
                        BorderStyle::Solid,
                    ));
                }
            },
        )
        .absolute()
        .inset_0();

        let mut children = Vec::with_capacity(self.items.len());
        let mut active_tip_overlay = None;

        for (pos, item) in self.items.iter().enumerate() {
            match item {
                FloatingButtonGroupItem::Separator(sep_id) => {
                    let sep_key = sep_id
                        .clone()
                        .unwrap_or_else(|| SharedString::from(format!("sep-{pos}")));
                    let sep_len = item_h * 0.5;
                    let sep = if vertical {
                        div()
                            .id(ElementId::NamedChild(self.id.clone().into(), sep_key))
                            .flex_none()
                            .self_center()
                            .w(sep_len)
                            .h(px(1.0))
                            .my(px(2.0))
                            .rounded(px(1.0))
                            .bg(rule_color)
                    } else {
                        div()
                            .id(ElementId::NamedChild(self.id.clone().into(), sep_key))
                            .flex_none()
                            .self_center()
                            .w(px(1.0))
                            .h(sep_len)
                            .mx(px(2.0))
                            .rounded(px(1.0))
                            .bg(rule_color)
                    };
                    children.push(sep.into_any_element());
                }
                FloatingButtonGroupItem::Action(action) => {
                    let id = action.id.clone();
                    let is_icon_only =
                        action.icon.is_some() && action.icon_only.unwrap_or(self.icon_only);
                    let is_active = active_id.as_ref() == Some(&id);
                    let is_pressed_mode = action.pressed.unwrap_or(false);
                    let is_disabled = action.disabled;

                    let reserved_w = fbg_reserved_content_width(
                        action.label.as_ref(),
                        &action.reserve_labels,
                        action.icon.is_some(),
                        is_icon_only,
                        self.size,
                    );

                    let item_bounds = snap.item_bounds.clone();
                    let id_measure = id.clone();
                    let probe = canvas(
                        move |rect, _, _| {
                            item_bounds.borrow_mut().insert(id_measure.clone(), rect);
                        },
                        |_, _, _, _| {},
                    )
                    .absolute()
                    .inset_0();

                    let fg_color = if is_disabled {
                        colors.text_muted
                    } else if is_active || is_pressed_mode {
                        colors.foreground
                    } else {
                        colors.text_secondary
                    };

                    let btn_id = ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("item-{}", action.id)),
                    );

                    let int_hover = internal.clone();
                    let int_down = internal.clone();
                    let int_up = internal.clone();
                    let int_out = internal.clone();
                    let id_hover = id.clone();
                    let id_down = id.clone();
                    let id_click = id.clone();
                    let on_select = action.on_select.clone();
                    let on_action = self.on_action.clone();

                    let pad_left = if action.icon.is_some() && !is_icon_only {
                        (item_pad_x - px(2.0)).max(px(6.0))
                    } else {
                        item_pad_x
                    };

                    let btn = BaseButton::new(btn_id)
                        .disabled(is_disabled)
                        .accessibility_label(action.label.clone())
                        .on_click(move |_, window, cx| {
                            if is_disabled {
                                return;
                            }
                            if let Some(cb) = &on_select {
                                cb(&(), window, cx);
                            }
                            if let Some(cb) = &on_action {
                                cb(&id_click, window, cx);
                            }
                            window.refresh();
                        })
                        .relative()
                        .flex_none()
                        .flex()
                        .flex_row()
                        .items_center()
                        .when(vertical && !is_icon_only, |this| {
                            this.w_full().justify_start()
                        })
                        .when(!vertical || is_icon_only, |this| this.justify_center())
                        .when(vertical && is_icon_only, |this| this.self_center())
                        .h(item_h)
                        .when(is_icon_only, |this| this.w(item_h))
                        .when(!is_icon_only, |this| {
                            this.min_w(item_h).pl(pad_left).pr(item_pad_x)
                        })
                        .rounded(inner_radius)
                        .when(is_pressed_mode, |this| this.bg(on_tint))
                        .text_size(match self.size {
                            FloatingButtonGroupSize::Sm => Typography::TEXT_XS,
                            FloatingButtonGroupSize::Md => Typography::TEXT_SM,
                        })
                        .text_color(fg_color)
                        .when(is_disabled, |this| this.opacity(0.5))
                        .when(!is_disabled, |this| this.cursor_pointer())
                        .on_hover(move |hovered, window, cx| {
                            if is_disabled {
                                return;
                            }
                            int_hover.update(cx, |s, _| {
                                if *hovered {
                                    s.hovered_id = Some(id_hover.clone());
                                } else if s.hovered_id.as_ref() == Some(&id_hover) {
                                    s.hovered_id = None;
                                    s.pressed_id = None;
                                }
                            });
                            window.refresh();
                        })
                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                            if is_disabled {
                                return;
                            }
                            int_down.update(cx, |s, _| {
                                s.hovered_id = Some(id_down.clone());
                                s.pressed_id = Some(id_down.clone());
                            });
                            window.refresh();
                        })
                        .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                            int_up.update(cx, |s, _| s.pressed_id = None);
                            window.refresh();
                        })
                        .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                            int_out.update(cx, |s, _| s.pressed_id = None);
                            window.refresh();
                        })
                        .child(probe)
                        .child(
                            div()
                                .flex()
                                .flex_row()
                                .items_center()
                                .when(!vertical || is_icon_only, |this| this.justify_center())
                                .when(vertical && !is_icon_only, |this| this.justify_start())
                                .when(!is_icon_only, |this| this.min_w(px(reserved_w)))
                                .gap(px(6.0))
                                .when_some(action.icon, |this, icon| this.child(icon))
                                .when(!is_icon_only, |this| this.child(action.label.clone())),
                        );

                    if is_active && (is_icon_only || action.shortcut.is_some()) {
                        let tip_label = action.label.clone();
                        let tip_shortcut = action.shortcut.clone();
                        let kbd_fg = with_alpha(colors.background, 0.58);
                        let tip_border = with_alpha(colors.background, 0.14);

                        let tip_bubble = div()
                            .px(Spacing::S3)
                            .py(Spacing::S2)
                            .rounded(Radii::CONTROL)
                            .border_1()
                            .border_color(tip_border)
                            .bg(colors.foreground)
                            .text_color(colors.background)
                            .text_size(Typography::TEXT_XS)
                            .shadow(Shadows::raised(theme.mode))
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(Spacing::S2)
                            .whitespace_nowrap()
                            .child(tip_label)
                            .when_some(tip_shortcut, |this, kbd| {
                                this.child(div().text_color(kbd_fg).child(kbd))
                            });

                        let positioned_tip = match resolved_tip_side {
                            TooltipSide::Top => div()
                                .absolute()
                                .bottom(item_h + tray_pad * 2.0 + px(8.0))
                                .left_0()
                                .child(tip_bubble),
                            TooltipSide::Bottom => div()
                                .absolute()
                                .top(item_h + tray_pad * 2.0 + px(8.0))
                                .left_0()
                                .child(tip_bubble),
                            TooltipSide::Right => div()
                                .absolute()
                                .left(item_h + tray_pad * 2.0 + px(8.0))
                                .top(px(pos as f32 * f32::from(item_h + item_gap)))
                                .child(tip_bubble),
                            TooltipSide::Left => div()
                                .absolute()
                                .right(item_h + tray_pad * 2.0 + px(8.0))
                                .top(px(pos as f32 * f32::from(item_h + item_gap)))
                                .child(tip_bubble),
                        };

                        active_tip_overlay = Some(deferred(positioned_tip).with_priority(2));
                    }

                    children.push(btn.into_any_element());
                }
            }
        }

        div()
            .id(self.id)
            .test_support()
            .role(Role::Toolbar)
            .aria_label(self.label)
            .relative()
            .self_start()
            .flex_none()
            .flex()
            .when(vertical, |this| this.flex_col().items_stretch())
            .when(!vertical, |this| this.flex_row().items_center())
            .gap(item_gap)
            .p(tray_pad)
            .rounded(outer_radius)
            .border_1()
            .border_color(tray_border)
            .bg(tray_bg)
            .when(
                self.variant == FloatingButtonGroupVariant::Floating,
                |this| this.shadow(Shadows::floating(theme.mode)),
            )
            .child(highlight_canvas)
            .children(children)
            .when_some(active_tip_overlay, |this, tip| this.child(tip))
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn highlight_scale_and_reserved_width_behave_as_expected() {
        assert!((fbg_highlight_target_scale(true, false) - 1.0).abs() < 1e-5);
        assert!((fbg_highlight_target_scale(true, true) - FBG_PRESS_SCALE).abs() < 1e-5);
        assert!((fbg_highlight_target_scale(false, true) - 1.0).abs() < 1e-5);

        let w_short =
            fbg_reserved_content_width("Share", &[], true, false, FloatingButtonGroupSize::Md);
        let w_reserved = fbg_reserved_content_width(
            "Share",
            &[SharedString::from("Copied link")],
            true,
            false,
            FloatingButtonGroupSize::Md,
        );
        assert!(w_reserved > w_short);

        let w_same_after_swap = fbg_reserved_content_width(
            "Copied link",
            &[SharedString::from("Share")],
            true,
            false,
            FloatingButtonGroupSize::Md,
        );
        assert!((w_reserved - w_same_after_swap).abs() < 1e-4);
    }

    struct Host {
        count: Rc<Cell<usize>>,
        last_action: Rc<RefCell<Option<SharedString>>>,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let count = self.count.clone();
            let last_action = self.last_action.clone();
            div().p(Spacing::S6).child(
                FloatingButtonGroup::new("board-toolbar", "Board actions")
                    .variant(FloatingButtonGroupVariant::Floating)
                    .items([
                        FloatingButtonGroupItem::action(
                            FloatingButtonGroupAction::new("comment", "Comment").on_select(
                                cx.listener(move |_, _, _, _| {
                                    count.set(count.get() + 1);
                                }),
                            ),
                        ),
                        FloatingButtonGroupItem::separator(),
                        FloatingButtonGroupItem::action(
                            FloatingButtonGroupAction::new("share", "Share")
                                .reserve_labels(["Copied"])
                                .shortcut("⌘L"),
                        ),
                    ])
                    .on_action(cx.listener(move |_, id: &SharedString, _, _| {
                        *last_action.borrow_mut() = Some(id.clone());
                    })),
            )
        }
    }

    #[gpui_kit::test]
    fn floating_button_group_fires_item_and_group_callbacks(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
        });
        let count = Rc::new(Cell::new(0usize));
        let last_action = Rc::new(RefCell::new(None));
        let (_view, cx) = cx.add_window_view(|_, _| Host {
            count: count.clone(),
            last_action: last_action.clone(),
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let comment = window.find_by_label("Comment");
            assert_eq!(comment.role(), Some(Role::Button));
            let pos = comment.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            assert_eq!(count.get(), 1);
            assert_eq!(last_action.borrow().as_deref(), Some("comment"));
        });
    }
}