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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/billing-toggle/billing-toggle.tsx` & `.module.css`
//!
//! P4 Component #27: `billing-toggle`
//!
//! - `BillingToggle`: billing period switch whose raised pill thumb glides between options on a
//!   critically damped spring (`BILLING_GLIDE_SPRING`: `0.34s, bounce = 0`), while the savings
//!   badge tints with `colors.success` and swaps to `active_badge` once selected.
//! - `BillingPrice`: rolling price readout powered by [`AnimatedCounter`] with an optional
//!   struck-through `was` price (shown when `was > amount`) and period suffix.
//!
//! Known deviations from upstream:
//! - In GPUI, the sliding thumb measures each option's bounds in a `canvas` prepaint pass and
//!   paints a rounded pill directly behind the options; under reduced motion it snaps instantly.
//! - `StableSwap` and `period` text swap directly with reserved layout width rather than CSS
//!   blur-crossfade layers.

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

use arc_motion::{arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    App, BorderStyle, Bounds, Corners, Edges, ElementId, FocusHandle, IntoElement, KeyDownEvent,
    ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    canvas, div, point,
    prelude::*,
    px, quad, size,
};

use crate::text::animated_counter::AnimatedCounter;

/// Critically damped glide spring for the billing toggle thumb (`billing-toggle.tsx` line 31).
pub const BILLING_GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.34, 0.0);

/// Critically damped clip/width spring for `BillingPrice` (`billing-toggle.tsx` line 152).
pub const BILLING_CLIP_SPRING: SpringSpec = SpringSpec::visual(0.36, 0.0);

/// Size variant for [`BillingToggle`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BillingToggleSize {
    #[default]
    Md,
    Lg,
}

impl BillingToggleSize {
    pub const fn height_px(self) -> f32 {
        match self {
            Self::Md => 34.0,
            Self::Lg => 42.0,
        }
    }

    pub const fn pad_px(self) -> f32 {
        match self {
            Self::Md => 3.0,
            Self::Lg => 4.0,
        }
    }
}

/// One billing period option.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BillingToggleOption {
    pub value: SharedString,
    pub label: SharedString,
    /// Short savings note, e.g. `"Save 20%"`.
    pub badge: Option<SharedString>,
    /// Badge text once this option is selected, e.g. `"You save $48"`. Defaults to `badge`.
    pub active_badge: Option<SharedString>,
}

impl BillingToggleOption {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            badge: None,
            active_badge: None,
        }
    }

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

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

    /// Returns the badge text for the current selection state.
    pub fn display_badge(&self, selected: bool) -> Option<&SharedString> {
        if selected {
            self.active_badge.as_ref().or(self.badge.as_ref())
        } else {
            self.badge.as_ref()
        }
    }
}

/// Default Monthly / Yearly options matching upstream `DEFAULT_OPTIONS`.
pub fn billing_default_options() -> Vec<BillingToggleOption> {
    vec![
        BillingToggleOption::new("monthly", "Monthly"),
        BillingToggleOption::new("yearly", "Yearly").badge("Save 20%"),
    ]
}

/// Resolves the target option index for keyboard navigation.
pub fn billing_next_index(current: usize, len: usize, key: &str) -> Option<usize> {
    if len == 0 {
        return None;
    }
    match key {
        "right" | "down" => Some((current + 1) % len),
        "left" | "up" => Some((current + len - 1) % len),
        "home" => Some(0),
        "end" => Some(len - 1),
        _ => None,
    }
}

#[derive(Clone)]
struct BillingToggleInternal {
    root_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    option_bounds: Rc<RefCell<Vec<Option<Bounds<Pixels>>>>>,
    focus_handle: FocusHandle,
}

impl BillingToggleInternal {
    fn new(cx: &mut App) -> Self {
        Self {
            root_bounds: Rc::new(RefCell::new(None)),
            option_bounds: Rc::new(RefCell::new(Vec::new())),
            focus_handle: cx.focus_handle(),
        }
    }
}

/// Arc `BillingToggle` — billing period pill switch with a critically damped sliding thumb and
/// tinting savings badge.
#[derive(IntoElement)]
pub struct BillingToggle {
    id: ElementId,
    value: SharedString,
    options: Vec<BillingToggleOption>,
    label: SharedString,
    size: BillingToggleSize,
    #[allow(clippy::type_complexity)]
    on_value_change: Option<Rc<dyn Fn(&SharedString, &mut Window, &mut App)>>,
}

impl BillingToggle {
    pub fn new(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            value: value.into(),
            options: billing_default_options(),
            label: "Billing period".into(),
            size: BillingToggleSize::Md,
            on_value_change: None,
        }
    }

    pub fn options(mut self, options: Vec<BillingToggleOption>) -> Self {
        if !options.is_empty() {
            self.options = options;
        }
        self
    }

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

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

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

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

        let selected_index = self
            .options
            .iter()
            .position(|o| o.value == self.value)
            .unwrap_or(0);

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-billing-toggle-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| BillingToggleInternal::new(cx));

        let opt_count = self.options.len();
        let (target_x, target_w, has_thumb, root_bounds_cell, option_bounds_cell, focus_handle) = {
            let snap = internal.read(cx);
            let mut list = snap.option_bounds.borrow_mut();
            if list.len() != opt_count {
                list.resize(opt_count, None);
            }
            let (tx, tw, valid) = if let (Some(root_b), Some(Some(opt_b))) = (
                *snap.root_bounds.borrow(),
                list.get(selected_index).copied(),
            ) {
                let x = f32::from(opt_b.origin.x) - f32::from(root_b.origin.x);
                let w = f32::from(opt_b.size.width);
                (x, w, w > 1.0)
            } else {
                (0.0, 0.0, false)
            };
            (
                tx,
                tw,
                valid,
                snap.root_bounds.clone(),
                snap.option_bounds.clone(),
                snap.focus_handle.clone(),
            )
        };

        let thumb_x = if !has_thumb || reduced {
            target_x
        } else {
            arc_spring(
                ElementId::NamedChild(self.id.clone().into(), "thumb-x".into()),
                target_x,
                BILLING_GLIDE_SPRING,
                window,
                cx,
            )
        };
        let thumb_w = if !has_thumb || reduced {
            target_w
        } else {
            arc_spring(
                ElementId::NamedChild(self.id.clone().into(), "thumb-w".into()),
                target_w,
                BILLING_GLIDE_SPRING,
                window,
                cx,
            )
        };

        let h_px = self.size.height_px();
        let pad_px = self.size.pad_px();
        let text_size = match self.size {
            BillingToggleSize::Md => Typography::TEXT_SM,
            BillingToggleSize::Lg => Typography::TEXT_BASE,
        };
        let thumb_bg = colors.surface_raised;
        let thumb_border = if is_dark {
            colors.border
        } else {
            colors.border_subtle
        };

        let bg_canvas = canvas(
            {
                let root_cell = root_bounds_cell.clone();
                move |bounds, _, _| {
                    *root_cell.borrow_mut() = Some(bounds);
                    bounds
                }
            },
            move |bounds, _, window, _| {
                if !has_thumb {
                    return;
                }
                let pill_bounds = Bounds {
                    origin: point(
                        px(f32::from(bounds.origin.x) + thumb_x),
                        px(f32::from(bounds.origin.y) + pad_px),
                    ),
                    size: size(px(thumb_w), px(h_px)),
                };
                window.paint_quad(quad(
                    pill_bounds,
                    Corners::all(px(h_px * 0.5)),
                    thumb_bg,
                    Edges::all(px(1.0)),
                    thumb_border,
                    BorderStyle::Solid,
                ));
            },
        )
        .size_full();

        let options_for_key = self.options.clone();
        let cb_key = self.on_value_change.clone();

        let option_els = self.options.iter().enumerate().map(|(idx, option)| {
            let selected = idx == selected_index;
            let opt_val = option.value.clone();
            let cb_click = self.on_value_change.clone();
            let badge_text = option.display_badge(selected).cloned();
            let has_badge = badge_text.is_some();

            let badge_bg = if selected {
                oklab_mix(
                    colors.success,
                    colors.surface,
                    if is_dark { 0.82 } else { 0.87 },
                )
            } else {
                oklab_mix(colors.foreground, colors.surface_muted, 0.92)
            };
            let badge_fg = if selected {
                if is_dark {
                    colors.success
                } else {
                    oklab_mix(colors.success, colors.foreground, 0.12)
                }
            } else {
                colors.text_secondary
            };

            let cell_bounds = option_bounds_cell.clone();
            let pad_left = match self.size {
                BillingToggleSize::Md => px(14.0),
                BillingToggleSize::Lg => px(18.0),
            };
            let pad_right = if has_badge {
                match self.size {
                    BillingToggleSize::Md => px(5.0),
                    BillingToggleSize::Lg => px(6.0),
                }
            } else {
                pad_left
            };

            BaseButton::new(ElementId::NamedChild(
                self.id.clone().into(),
                SharedString::from(format!("opt-{}", option.value)),
            ))
            .accessibility_label(option.label.clone())
            .on_click(move |_, window, cx| {
                if let Some(ref handler) = cb_click {
                    handler(&opt_val, window, cx);
                }
                window.refresh();
            })
            .relative()
            .h(px(h_px))
            .pl(pad_left)
            .pr(pad_right)
            .flex()
            .items_center()
            .gap(px(8.0))
            .rounded_full()
            .when(!has_thumb && selected, |b| b.bg(thumb_bg))
            .when(!selected, |b| b.cursor_pointer())
            .text_size(text_size)
            .font_medium()
            .text_color(if selected {
                colors.foreground
            } else {
                colors.text_muted
            })
            // Measure exact option bounds inside the root track for the gliding pill.
            .child(
                div().absolute().inset_0().child(
                    canvas(
                        move |bounds, _, _| {
                            let mut list = cell_bounds.borrow_mut();
                            if idx < list.len() {
                                list[idx] = Some(bounds);
                            }
                            bounds
                        },
                        |_, _, _, _| {},
                    )
                    .size_full(),
                ),
            )
            .child(option.label.clone())
            .when_some(badge_text, |this, text| {
                this.child(
                    div()
                        .h(px((h_px - 10.0).max(20.0)))
                        .px(px(8.0))
                        .flex()
                        .items_center()
                        .rounded_full()
                        .bg(badge_bg)
                        .text_size(Typography::TEXT_XS)
                        .font_medium()
                        .text_color(badge_fg)
                        .child(text),
                )
            })
        });

        div()
            .id(self.id.clone())
            .test_support()
            .track_focus(&focus_handle)
            .role(Role::RadioGroup)
            .aria_label(self.label.clone())
            .relative()
            .flex()
            .items_center()
            .p(px(pad_px))
            .rounded(Radii::PILL)
            .border_1()
            .border_color(colors.border_subtle)
            .bg(colors.surface_muted)
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if let Some(target_idx) = billing_next_index(
                    selected_index,
                    options_for_key.len(),
                    event.keystroke.key.as_str(),
                ) && let Some(opt) = options_for_key.get(target_idx)
                    && let Some(ref handler) = cb_key
                {
                    handler(&opt.value, window, cx);
                    window.refresh();
                }
            })
            .child(div().absolute().inset_0().child(bg_canvas))
            .children(option_els)
    }
}

/// Companion rolling price display paired with [`BillingToggle`].
#[derive(IntoElement)]
pub struct BillingPrice {
    id: ElementId,
    amount: f64,
    currency: SharedString,
    period: Option<SharedString>,
    was: Option<f64>,
    decimals: usize,
}

impl BillingPrice {
    pub fn new(id: impl Into<ElementId>, amount: f64) -> Self {
        Self {
            id: id.into(),
            amount,
            currency: "$".into(),
            period: None,
            was: None,
            decimals: 0,
        }
    }

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

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

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

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

impl RenderOnce for BillingPrice {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = cx.arc_theme().colors;
        let show_was = self.was.is_some_and(|w| w > self.amount);

        div()
            .id(self.id.clone())
            .test_support()
            .flex()
            .flex_wrap()
            .items_end()
            .gap(Spacing::S2)
            .child(
                div()
                    .flex()
                    .items_start()
                    .gap(px(2.0))
                    .child(
                        div()
                            .pt(px(4.0))
                            .text_size(Typography::TEXT_LG)
                            .text_color(colors.text_secondary)
                            .child(self.currency.clone()),
                    )
                    .child(
                        AnimatedCounter::new(
                            ElementId::NamedChild(self.id.clone().into(), "counter".into()),
                            self.amount,
                        )
                        .decimals(self.decimals)
                        .text_size(Typography::TEXT_3XL),
                    ),
            )
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap(px(6.0))
                    .pb(px(5.0))
                    .text_size(Typography::TEXT_SM)
                    .text_color(colors.text_muted)
                    .when(show_was, |this| {
                        let w = self.was.unwrap_or(0.0);
                        this.child(div().line_through().text_color(colors.text_muted).child(
                            SharedString::from(format!("{}{:.*}", self.currency, self.decimals, w)),
                        ))
                    })
                    .when_some(self.period, |this, period| this.child(period)),
            )
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn billing_navigation_and_badges() {
        let opts = [
            BillingToggleOption::new("monthly", "Monthly"),
            BillingToggleOption::new("yearly", "Yearly")
                .badge("Save 20%")
                .active_badge("You save $48"),
        ];
        assert_eq!(
            opts[1].display_badge(false).map(|s| s.as_ref()),
            Some("Save 20%")
        );
        assert_eq!(
            opts[1].display_badge(true).map(|s| s.as_ref()),
            Some("You save $48")
        );
        assert_eq!(billing_next_index(0, 2, "right"), Some(1));
        assert_eq!(billing_next_index(1, 2, "right"), Some(0));
        assert_eq!(billing_next_index(0, 2, "left"), Some(1));
        assert_eq!(billing_next_index(1, 2, "home"), Some(0));
        assert_eq!(billing_next_index(0, 2, "end"), Some(1));
    }

    struct BillingHost;

    impl Render for BillingHost {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(420.0))
                .p(px(16.0))
                .flex()
                .flex_col()
                .gap(Spacing::S4)
                .child(BillingToggle::new("bt-test", "yearly"))
                .child(
                    BillingPrice::new("bp-test", 19.0)
                        .was(24.0)
                        .period("per month"),
                )
        }
    }

    #[gpui_kit::test]
    fn billing_toggle_and_price_render(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let (_view, cx) = cx.add_window_view(|_, _| BillingHost);
        cx.update(|window, cx| {
            window.render_frame(cx);
            let group = window.find(ElementId::Name("bt-test".into()));
            assert_eq!(group.role(), Some(Role::RadioGroup));
            assert!(window.try_find(ElementId::Name("bp-test".into())).is_some());
        });
    }
}