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;
pub const BILLING_GLIDE_SPRING: SpringSpec = SpringSpec::visual(0.34, 0.0);
pub const BILLING_CLIP_SPRING: SpringSpec = SpringSpec::visual(0.36, 0.0);
#[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,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BillingToggleOption {
pub value: SharedString,
pub label: SharedString,
pub badge: Option<SharedString>,
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
}
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()
}
}
}
pub fn billing_default_options() -> Vec<BillingToggleOption> {
vec![
BillingToggleOption::new("monthly", "Monthly"),
BillingToggleOption::new("yearly", "Yearly").badge("Save 20%"),
]
}
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(),
}
}
}
#[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
})
.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)
}
}
#[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());
});
}
}