Skip to main content

arc_ui/inputs/
billing_toggle.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/billing-toggle/billing-toggle.tsx` & `.module.css`
3//!
4//! P4 Component #27: `billing-toggle`
5//!
6//! - `BillingToggle`: billing period switch whose raised pill thumb glides between options on a
7//!   critically damped spring (`BILLING_GLIDE_SPRING`: `0.34s, bounce = 0`), while the savings
8//!   badge tints with `colors.success` and swaps to `active_badge` once selected.
9//! - `BillingPrice`: rolling price readout powered by [`AnimatedCounter`] with an optional
10//!   struck-through `was` price (shown when `was > amount`) and period suffix.
11//!
12//! Known deviations from upstream:
13//! - In GPUI, the sliding thumb measures each option's bounds in a `canvas` prepaint pass and
14//!   paints a rounded pill directly behind the options; under reduced motion it snaps instantly.
15//! - `StableSwap` and `period` text swap directly with reserved layout width rather than CSS
16//!   blur-crossfade layers.
17
18use std::{cell::RefCell, rc::Rc};
19
20use arc_motion::{arc_spring, is_reduced_motion};
21use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
22use gpui_kit::{
23    App, BorderStyle, Bounds, Corners, Edges, ElementId, FocusHandle, IntoElement, KeyDownEvent,
24    ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
25    base::{Button as BaseButton, StyledExt as _},
26    canvas, div, point,
27    prelude::*,
28    px, quad, size,
29};
30
31use crate::text::animated_counter::AnimatedCounter;
32
33/// Critically damped glide spring for the billing toggle thumb (`billing-toggle.tsx` line 31).
34pub const BILLING_GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.34, 0.0);
35
36/// Critically damped clip/width spring for `BillingPrice` (`billing-toggle.tsx` line 152).
37pub const BILLING_CLIP_SPRING: SpringSpec = SpringSpec::visual(0.36, 0.0);
38
39/// Size variant for [`BillingToggle`].
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41pub enum BillingToggleSize {
42    #[default]
43    Md,
44    Lg,
45}
46
47impl BillingToggleSize {
48    pub const fn height_px(self) -> f32 {
49        match self {
50            Self::Md => 34.0,
51            Self::Lg => 42.0,
52        }
53    }
54
55    pub const fn pad_px(self) -> f32 {
56        match self {
57            Self::Md => 3.0,
58            Self::Lg => 4.0,
59        }
60    }
61}
62
63/// One billing period option.
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct BillingToggleOption {
66    pub value: SharedString,
67    pub label: SharedString,
68    /// Short savings note, e.g. `"Save 20%"`.
69    pub badge: Option<SharedString>,
70    /// Badge text once this option is selected, e.g. `"You save $48"`. Defaults to `badge`.
71    pub active_badge: Option<SharedString>,
72}
73
74impl BillingToggleOption {
75    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
76        Self {
77            value: value.into(),
78            label: label.into(),
79            badge: None,
80            active_badge: None,
81        }
82    }
83
84    pub fn badge(mut self, badge: impl Into<SharedString>) -> Self {
85        self.badge = Some(badge.into());
86        self
87    }
88
89    pub fn active_badge(mut self, active_badge: impl Into<SharedString>) -> Self {
90        self.active_badge = Some(active_badge.into());
91        self
92    }
93
94    /// Returns the badge text for the current selection state.
95    pub fn display_badge(&self, selected: bool) -> Option<&SharedString> {
96        if selected {
97            self.active_badge.as_ref().or(self.badge.as_ref())
98        } else {
99            self.badge.as_ref()
100        }
101    }
102}
103
104/// Default Monthly / Yearly options matching upstream `DEFAULT_OPTIONS`.
105pub fn billing_default_options() -> Vec<BillingToggleOption> {
106    vec![
107        BillingToggleOption::new("monthly", "Monthly"),
108        BillingToggleOption::new("yearly", "Yearly").badge("Save 20%"),
109    ]
110}
111
112/// Resolves the target option index for keyboard navigation.
113pub fn billing_next_index(current: usize, len: usize, key: &str) -> Option<usize> {
114    if len == 0 {
115        return None;
116    }
117    match key {
118        "right" | "down" => Some((current + 1) % len),
119        "left" | "up" => Some((current + len - 1) % len),
120        "home" => Some(0),
121        "end" => Some(len - 1),
122        _ => None,
123    }
124}
125
126#[derive(Clone)]
127struct BillingToggleInternal {
128    root_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
129    option_bounds: Rc<RefCell<Vec<Option<Bounds<Pixels>>>>>,
130    focus_handle: FocusHandle,
131}
132
133impl BillingToggleInternal {
134    fn new(cx: &mut App) -> Self {
135        Self {
136            root_bounds: Rc::new(RefCell::new(None)),
137            option_bounds: Rc::new(RefCell::new(Vec::new())),
138            focus_handle: cx.focus_handle(),
139        }
140    }
141}
142
143/// Arc `BillingToggle` — billing period pill switch with a critically damped sliding thumb and
144/// tinting savings badge.
145#[derive(IntoElement)]
146pub struct BillingToggle {
147    id: ElementId,
148    value: SharedString,
149    options: Vec<BillingToggleOption>,
150    label: SharedString,
151    size: BillingToggleSize,
152    #[allow(clippy::type_complexity)]
153    on_value_change: Option<Rc<dyn Fn(&SharedString, &mut Window, &mut App)>>,
154}
155
156impl BillingToggle {
157    pub fn new(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
158        Self {
159            id: id.into(),
160            value: value.into(),
161            options: billing_default_options(),
162            label: "Billing period".into(),
163            size: BillingToggleSize::Md,
164            on_value_change: None,
165        }
166    }
167
168    pub fn options(mut self, options: Vec<BillingToggleOption>) -> Self {
169        if !options.is_empty() {
170            self.options = options;
171        }
172        self
173    }
174
175    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
176        self.label = label.into();
177        self
178    }
179
180    pub fn size(mut self, size: BillingToggleSize) -> Self {
181        self.size = size;
182        self
183    }
184
185    pub fn on_value_change(
186        mut self,
187        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
188    ) -> Self {
189        self.on_value_change = Some(Rc::new(handler));
190        self
191    }
192}
193
194impl RenderOnce for BillingToggle {
195    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
196        let theme = cx.arc_theme().clone();
197        let colors = theme.colors;
198        let is_dark = theme.mode.is_dark();
199        let reduced = is_reduced_motion(cx);
200
201        let selected_index = self
202            .options
203            .iter()
204            .position(|o| o.value == self.value)
205            .unwrap_or(0);
206
207        let state_id =
208            ElementId::NamedChild(self.id.clone().into(), "__arc-billing-toggle-state".into());
209        let internal = window.use_keyed_state(state_id, cx, |_, cx| BillingToggleInternal::new(cx));
210
211        let opt_count = self.options.len();
212        let (target_x, target_w, has_thumb, root_bounds_cell, option_bounds_cell, focus_handle) = {
213            let snap = internal.read(cx);
214            let mut list = snap.option_bounds.borrow_mut();
215            if list.len() != opt_count {
216                list.resize(opt_count, None);
217            }
218            let (tx, tw, valid) = if let (Some(root_b), Some(Some(opt_b))) = (
219                *snap.root_bounds.borrow(),
220                list.get(selected_index).copied(),
221            ) {
222                let x = f32::from(opt_b.origin.x) - f32::from(root_b.origin.x);
223                let w = f32::from(opt_b.size.width);
224                (x, w, w > 1.0)
225            } else {
226                (0.0, 0.0, false)
227            };
228            (
229                tx,
230                tw,
231                valid,
232                snap.root_bounds.clone(),
233                snap.option_bounds.clone(),
234                snap.focus_handle.clone(),
235            )
236        };
237
238        let thumb_x = if !has_thumb || reduced {
239            target_x
240        } else {
241            arc_spring(
242                ElementId::NamedChild(self.id.clone().into(), "thumb-x".into()),
243                target_x,
244                BILLING_GLIDE_SPRING,
245                window,
246                cx,
247            )
248        };
249        let thumb_w = if !has_thumb || reduced {
250            target_w
251        } else {
252            arc_spring(
253                ElementId::NamedChild(self.id.clone().into(), "thumb-w".into()),
254                target_w,
255                BILLING_GLIDE_SPRING,
256                window,
257                cx,
258            )
259        };
260
261        let h_px = self.size.height_px();
262        let pad_px = self.size.pad_px();
263        let text_size = match self.size {
264            BillingToggleSize::Md => Typography::TEXT_SM,
265            BillingToggleSize::Lg => Typography::TEXT_BASE,
266        };
267        let thumb_bg = colors.surface_raised;
268        let thumb_border = if is_dark {
269            colors.border
270        } else {
271            colors.border_subtle
272        };
273
274        let bg_canvas = canvas(
275            {
276                let root_cell = root_bounds_cell.clone();
277                move |bounds, _, _| {
278                    *root_cell.borrow_mut() = Some(bounds);
279                    bounds
280                }
281            },
282            move |bounds, _, window, _| {
283                if !has_thumb {
284                    return;
285                }
286                let pill_bounds = Bounds {
287                    origin: point(
288                        px(f32::from(bounds.origin.x) + thumb_x),
289                        px(f32::from(bounds.origin.y) + pad_px),
290                    ),
291                    size: size(px(thumb_w), px(h_px)),
292                };
293                window.paint_quad(quad(
294                    pill_bounds,
295                    Corners::all(px(h_px * 0.5)),
296                    thumb_bg,
297                    Edges::all(px(1.0)),
298                    thumb_border,
299                    BorderStyle::Solid,
300                ));
301            },
302        )
303        .size_full();
304
305        let options_for_key = self.options.clone();
306        let cb_key = self.on_value_change.clone();
307
308        let option_els = self.options.iter().enumerate().map(|(idx, option)| {
309            let selected = idx == selected_index;
310            let opt_val = option.value.clone();
311            let cb_click = self.on_value_change.clone();
312            let badge_text = option.display_badge(selected).cloned();
313            let has_badge = badge_text.is_some();
314
315            let badge_bg = if selected {
316                oklab_mix(
317                    colors.success,
318                    colors.surface,
319                    if is_dark { 0.82 } else { 0.87 },
320                )
321            } else {
322                oklab_mix(colors.foreground, colors.surface_muted, 0.92)
323            };
324            let badge_fg = if selected {
325                if is_dark {
326                    colors.success
327                } else {
328                    oklab_mix(colors.success, colors.foreground, 0.12)
329                }
330            } else {
331                colors.text_secondary
332            };
333
334            let cell_bounds = option_bounds_cell.clone();
335            let pad_left = match self.size {
336                BillingToggleSize::Md => px(14.0),
337                BillingToggleSize::Lg => px(18.0),
338            };
339            let pad_right = if has_badge {
340                match self.size {
341                    BillingToggleSize::Md => px(5.0),
342                    BillingToggleSize::Lg => px(6.0),
343                }
344            } else {
345                pad_left
346            };
347
348            BaseButton::new(ElementId::NamedChild(
349                self.id.clone().into(),
350                SharedString::from(format!("opt-{}", option.value)),
351            ))
352            .accessibility_label(option.label.clone())
353            .on_click(move |_, window, cx| {
354                if let Some(ref handler) = cb_click {
355                    handler(&opt_val, window, cx);
356                }
357                window.refresh();
358            })
359            .relative()
360            .h(px(h_px))
361            .pl(pad_left)
362            .pr(pad_right)
363            .flex()
364            .items_center()
365            .gap(px(8.0))
366            .rounded_full()
367            .when(!has_thumb && selected, |b| b.bg(thumb_bg))
368            .when(!selected, |b| b.cursor_pointer())
369            .text_size(text_size)
370            .font_medium()
371            .text_color(if selected {
372                colors.foreground
373            } else {
374                colors.text_muted
375            })
376            // Measure exact option bounds inside the root track for the gliding pill.
377            .child(
378                div().absolute().inset_0().child(
379                    canvas(
380                        move |bounds, _, _| {
381                            let mut list = cell_bounds.borrow_mut();
382                            if idx < list.len() {
383                                list[idx] = Some(bounds);
384                            }
385                            bounds
386                        },
387                        |_, _, _, _| {},
388                    )
389                    .size_full(),
390                ),
391            )
392            .child(option.label.clone())
393            .when_some(badge_text, |this, text| {
394                this.child(
395                    div()
396                        .h(px((h_px - 10.0).max(20.0)))
397                        .px(px(8.0))
398                        .flex()
399                        .items_center()
400                        .rounded_full()
401                        .bg(badge_bg)
402                        .text_size(Typography::TEXT_XS)
403                        .font_medium()
404                        .text_color(badge_fg)
405                        .child(text),
406                )
407            })
408        });
409
410        div()
411            .id(self.id.clone())
412            .test_support()
413            .track_focus(&focus_handle)
414            .role(Role::RadioGroup)
415            .aria_label(self.label.clone())
416            .relative()
417            .flex()
418            .items_center()
419            .p(px(pad_px))
420            .rounded(Radii::PILL)
421            .border_1()
422            .border_color(colors.border_subtle)
423            .bg(colors.surface_muted)
424            .on_key_down(move |event: &KeyDownEvent, window, cx| {
425                if let Some(target_idx) = billing_next_index(
426                    selected_index,
427                    options_for_key.len(),
428                    event.keystroke.key.as_str(),
429                ) && let Some(opt) = options_for_key.get(target_idx)
430                    && let Some(ref handler) = cb_key
431                {
432                    handler(&opt.value, window, cx);
433                    window.refresh();
434                }
435            })
436            .child(div().absolute().inset_0().child(bg_canvas))
437            .children(option_els)
438    }
439}
440
441/// Companion rolling price display paired with [`BillingToggle`].
442#[derive(IntoElement)]
443pub struct BillingPrice {
444    id: ElementId,
445    amount: f64,
446    currency: SharedString,
447    period: Option<SharedString>,
448    was: Option<f64>,
449    decimals: usize,
450}
451
452impl BillingPrice {
453    pub fn new(id: impl Into<ElementId>, amount: f64) -> Self {
454        Self {
455            id: id.into(),
456            amount,
457            currency: "$".into(),
458            period: None,
459            was: None,
460            decimals: 0,
461        }
462    }
463
464    pub fn currency(mut self, currency: impl Into<SharedString>) -> Self {
465        self.currency = currency.into();
466        self
467    }
468
469    pub fn period(mut self, period: impl Into<SharedString>) -> Self {
470        self.period = Some(period.into());
471        self
472    }
473
474    pub fn was(mut self, was: f64) -> Self {
475        self.was = Some(was);
476        self
477    }
478
479    pub fn decimals(mut self, decimals: usize) -> Self {
480        self.decimals = decimals;
481        self
482    }
483}
484
485impl RenderOnce for BillingPrice {
486    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
487        let colors = cx.arc_theme().colors;
488        let show_was = self.was.is_some_and(|w| w > self.amount);
489
490        div()
491            .id(self.id.clone())
492            .test_support()
493            .flex()
494            .flex_wrap()
495            .items_end()
496            .gap(Spacing::S2)
497            .child(
498                div()
499                    .flex()
500                    .items_start()
501                    .gap(px(2.0))
502                    .child(
503                        div()
504                            .pt(px(4.0))
505                            .text_size(Typography::TEXT_LG)
506                            .text_color(colors.text_secondary)
507                            .child(self.currency.clone()),
508                    )
509                    .child(
510                        AnimatedCounter::new(
511                            ElementId::NamedChild(self.id.clone().into(), "counter".into()),
512                            self.amount,
513                        )
514                        .decimals(self.decimals)
515                        .text_size(Typography::TEXT_3XL),
516                    ),
517            )
518            .child(
519                div()
520                    .flex()
521                    .items_center()
522                    .gap(px(6.0))
523                    .pb(px(5.0))
524                    .text_size(Typography::TEXT_SM)
525                    .text_color(colors.text_muted)
526                    .when(show_was, |this| {
527                        let w = self.was.unwrap_or(0.0);
528                        this.child(div().line_through().text_color(colors.text_muted).child(
529                            SharedString::from(format!("{}{:.*}", self.currency, self.decimals, w)),
530                        ))
531                    })
532                    .when_some(self.period, |this, period| this.child(period)),
533            )
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
540    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
541
542    use super::*;
543
544    #[test]
545    fn billing_navigation_and_badges() {
546        let opts = [
547            BillingToggleOption::new("monthly", "Monthly"),
548            BillingToggleOption::new("yearly", "Yearly")
549                .badge("Save 20%")
550                .active_badge("You save $48"),
551        ];
552        assert_eq!(
553            opts[1].display_badge(false).map(|s| s.as_ref()),
554            Some("Save 20%")
555        );
556        assert_eq!(
557            opts[1].display_badge(true).map(|s| s.as_ref()),
558            Some("You save $48")
559        );
560        assert_eq!(billing_next_index(0, 2, "right"), Some(1));
561        assert_eq!(billing_next_index(1, 2, "right"), Some(0));
562        assert_eq!(billing_next_index(0, 2, "left"), Some(1));
563        assert_eq!(billing_next_index(1, 2, "home"), Some(0));
564        assert_eq!(billing_next_index(0, 2, "end"), Some(1));
565    }
566
567    struct BillingHost;
568
569    impl Render for BillingHost {
570        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
571            div()
572                .w(px(420.0))
573                .p(px(16.0))
574                .flex()
575                .flex_col()
576                .gap(Spacing::S4)
577                .child(BillingToggle::new("bt-test", "yearly"))
578                .child(
579                    BillingPrice::new("bp-test", 19.0)
580                        .was(24.0)
581                        .period("per month"),
582                )
583        }
584    }
585
586    #[gpui_kit::test]
587    fn billing_toggle_and_price_render(cx: &mut TestAppContext) {
588        cx.update(|cx| {
589            gpui_kit::init(cx);
590            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
591        });
592
593        let (_view, cx) = cx.add_window_view(|_, _| BillingHost);
594        cx.update(|window, cx| {
595            window.render_frame(cx);
596            let group = window.find(ElementId::Name("bt-test".into()));
597            assert_eq!(group.role(), Some(Role::RadioGroup));
598            assert!(window.try_find(ElementId::Name("bp-test".into())).is_some());
599        });
600    }
601}