use std::rc::Rc;
use arc_motion::{arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, SpringSpec};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
relative,
};
pub const RULE_END: f32 = 0.84;
const RULE_TOP_RATIO: f32 = 0.46;
const BOX_SWELL: f32 = 0.35;
const TICK_VIEW: f32 = 24.0;
const TICK_STROKE: f32 = 2.6;
const TICK_P0: (f32, f32) = (5.0, 12.5);
const TICK_P1: (f32, f32) = (10.0, 17.5);
const TICK_P2: (f32, f32) = (19.0, 6.5);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrikeOrigin {
#[default]
Left,
Center,
Right,
None,
}
impl StrikeOrigin {
pub fn parse(value: &str) -> Self {
match value {
"center" => Self::Center,
"right" => Self::Right,
"none" => Self::None,
_ => Self::Left,
}
}
}
fn zeta_of(bounce: f32) -> f32 {
if bounce <= 0.0 {
return 1.0;
}
let l = f64::from(bounce).ln();
(-l / (std::f64::consts::PI.powi(2) + l * l).sqrt()) as f32
}
#[derive(Clone, Debug)]
pub struct SpringCheckConfig {
pub color: Hsla,
pub fill_color: Hsla,
pub check_color: Hsla,
pub box_size: f32,
pub box_radius: f32,
pub font_size: f32,
pub bounce: f32,
pub strike_lag: f32,
pub done_opacity: f32,
pub strike: StrikeOrigin,
pub disabled: bool,
}
impl Default for SpringCheckConfig {
fn default() -> Self {
Self {
color: Hsla::default(),
fill_color: Hsla::default(),
check_color: Hsla::default(),
box_size: 28.0,
box_radius: 9.0,
font_size: 18.0,
bounce: 0.2,
strike_lag: 0.12,
done_opacity: 0.42,
strike: StrikeOrigin::Left,
disabled: false,
}
}
}
impl SpringCheckConfig {
fn resolve_theme(mut self, colors: arc_tokens::ArcColors) -> Self {
if self.color.a == 0.0 {
self.color = colors.foreground;
}
if self.fill_color.a == 0.0 {
self.fill_color = colors.accent;
}
if self.check_color.a == 0.0 {
self.check_color = colors.accent_foreground;
}
self
}
pub fn normalized(mut self) -> Self {
self.box_size = self.box_size.clamp(14.0, 80.0).max(1.0);
self.box_radius = self.box_radius.clamp(0.0, self.box_size / 2.0);
self.font_size = self.font_size.clamp(10.0, 40.0);
self.bounce = self.bounce.clamp(0.0, 0.5);
self.strike_lag = self.strike_lag.clamp(0.0, 0.6);
self.done_opacity = self.done_opacity.clamp(0.0, 1.0);
self
}
}
#[derive(Clone, Copy)]
struct SpringCheckInternal {
uncontrolled: bool,
hovered: bool,
pressed: bool,
}
pub type SpringCheckChange = bool;
type ChangeHandler = Rc<dyn Fn(&SpringCheckChange, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct SpringCheck {
id: ElementId,
label: SharedString,
aria_label: Option<SharedString>,
checked: Option<bool>,
default_checked: bool,
config: SpringCheckConfig,
on_change: Option<ChangeHandler>,
}
impl SpringCheck {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: "Ship the build".into(),
aria_label: None,
checked: None,
default_checked: false,
config: SpringCheckConfig::default(),
on_change: None,
}
}
pub fn label(mut self, v: impl Into<SharedString>) -> Self {
self.label = v.into();
self
}
pub fn aria_label(mut self, v: impl Into<SharedString>) -> Self {
self.aria_label = Some(v.into());
self
}
pub fn checked(mut self, v: bool) -> Self {
self.checked = Some(v);
self
}
pub fn default_checked(mut self, v: bool) -> Self {
self.default_checked = v;
self
}
pub fn config(mut self, v: SpringCheckConfig) -> Self {
self.config = v;
self
}
pub fn on_change(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
self.on_change = Some(Rc::new(f));
self
}
}
fn rule_scale(t: f32, strike_lag: f32) -> f32 {
if strike_lag >= RULE_END {
return 0.0;
}
((t - strike_lag) / (RULE_END - strike_lag)).clamp(0.0, 1.0)
}
fn tick_total_len() -> f32 {
let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
seg1 + seg2
}
fn tick_points_to(drawn: f32) -> Vec<(f32, f32)> {
let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
let mut pts = vec![TICK_P0];
if drawn >= seg1 {
pts.push(TICK_P1);
if drawn >= seg1 + seg2 {
pts.push(TICK_P2);
} else {
let f = (drawn - seg1) / seg2;
pts.push((
TICK_P1.0 + (TICK_P2.0 - TICK_P1.0) * f,
TICK_P1.1 + (TICK_P2.1 - TICK_P1.1) * f,
));
}
} else {
let f = drawn / seg1;
pts.push((
TICK_P0.0 + (TICK_P1.0 - TICK_P0.0) * f,
TICK_P0.1 + (TICK_P1.1 - TICK_P0.1) * f,
));
}
pts
}
fn rule_segment(scale: f32, origin: StrikeOrigin) -> Option<(f32, f32)> {
match origin {
StrikeOrigin::None => None,
StrikeOrigin::Left => Some((0.0, scale)),
StrikeOrigin::Center => {
let half = scale / 2.0;
Some((0.5 - half, 0.5 + half))
}
StrikeOrigin::Right => Some((1.0 - scale, 1.0)),
}
}
#[derive(Clone, Copy)]
struct FillCanvas {
ox: f32,
oy: f32,
scale: f32,
}
impl RenderOnce for SpringCheck {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let reduced = is_reduced_motion(cx);
let cfg = self
.config
.normalized()
.resolve_theme(cx.arc_theme().colors);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__spring-check-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| SpringCheckInternal {
uncontrolled: self.default_checked,
hovered: false,
pressed: false,
});
let snap = *internal.read(cx);
let is_controlled = self.checked.is_some();
let is_on = self.checked.unwrap_or(snap.uncontrolled);
let spec = SpringSpec::visual(0.2, 1.0 - zeta_of(cfg.bounce));
let t = if reduced {
if is_on { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "check-t"),
if is_on { 1.0 } else { 0.0 },
spec,
window,
cx,
)
};
let press_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "press-scale"),
if !cfg.disabled && snap.pressed {
0.95
} else {
1.0
},
SpringSpec::visual(0.16, 0.0),
window,
cx,
)
};
let fill_scale = t.max(0.0);
let tick_alpha = t.clamp(0.0, 1.0);
let word_opacity = 1.0 - (1.0 - cfg.done_opacity) * t.clamp(0.0, 1.0);
let rule = if cfg.strike == StrikeOrigin::None {
0.0
} else {
rule_scale(t, cfg.strike_lag)
};
let box_growth = BOX_SWELL * (t - 1.0).max(0.0); let ring_opacity = if !cfg.disabled && snap.hovered {
0.5
} else {
0.28
};
let ring_w = if cfg.box_size >= 24.0 { 2.0 } else { 1.5 };
let gap = (cfg.box_size * 0.43).round().clamp(8.0, 16.0);
let rule_h = ((cfg.font_size / 6.0).round() / 2.0).max(1.5);
let row_h = (cfg.box_size + 16.0).max(44.0);
let box_px = px(cfg.box_size);
let box_size_now = px(cfg.box_size * (1.0 + box_growth));
let fill_id = ElementId::NamedChild(self.id.clone().into(), "fill-canvas".into());
let fill_color = cfg.fill_color;
let check_color = cfg.check_color;
let radius = cfg.box_radius;
let total_len = tick_total_len();
let drawn_len = total_len * tick_alpha;
let fill_canvas = div().id(fill_id).size(box_size_now).flex_none().child(
canvas(
move |_, _, _| {},
move |rect, _, window, _| {
let ox = f32::from(rect.origin.x);
let oy = f32::from(rect.origin.y);
let s = f32::from(rect.size.width).min(f32::from(rect.size.height));
if s <= 0.0 {
return;
}
let cv = FillCanvas { ox, oy, scale: s };
cv.fill_round_rect(fill_scale, radius, fill_color, window);
if drawn_len > 0.5 {
let pts = tick_points_to(drawn_len);
let k = s / TICK_VIEW;
cv.stroke_polyline(TICK_STROKE * k, &pts, false, check_color, window);
}
},
)
.size_full(),
);
let ring_color = Hsla {
a: cfg.color.a * ring_opacity * (ring_w / 2.0),
..cfg.color
};
let box_outer = div()
.relative()
.size(box_size_now)
.rounded(px(radius))
.border_1()
.border_color(ring_color)
.overflow_hidden()
.flex()
.items_center()
.justify_center()
.child(fill_canvas);
let label_color = Hsla {
a: cfg.color.a * word_opacity,
..cfg.color
};
let rule_color = Hsla {
a: cfg.color.a,
..cfg.color
};
let rule_seg = rule_segment(rule, cfg.strike);
let label_block = div()
.relative()
.text_size(px(cfg.font_size))
.font_medium()
.whitespace_nowrap()
.text_color(label_color)
.child(self.label.clone())
.when_some(rule_seg, |el, (x0, x1)| {
el.child(
div()
.absolute()
.top(relative(RULE_TOP_RATIO))
.h(px(rule_h))
.rounded(px(2.0))
.bg(rule_color)
.left(relative(x0))
.w(relative(x1 - x0)),
)
});
let on_change = self.on_change.clone();
let state_hover = internal.clone();
let state_down = internal.clone();
let state_up = internal.clone();
let state_out = internal.clone();
let row = div()
.id(self.id.clone())
.test_support()
.role(Role::CheckBox)
.aria_toggled(if is_on {
gpui_kit::Toggled::True
} else {
gpui_kit::Toggled::False
})
.aria_label(
self.aria_label
.clone()
.unwrap_or_else(|| self.label.clone()),
)
.flex()
.items_center()
.gap(px(gap))
.h(px(row_h))
.cursor_pointer()
.when(cfg.disabled, |el| el.opacity(0.5).cursor_default())
.when(!cfg.disabled, |el| {
el.on_hover({
move |h: &bool, window, cx| {
state_hover.update(cx, |s, _| {
s.hovered = *h;
if !*h {
s.pressed = false;
}
});
window.refresh();
}
})
.on_mouse_down(MouseButton::Left, {
move |_, window, cx| {
state_down.update(cx, |s, _| s.pressed = true);
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, {
move |_, window, cx| {
state_up.update(cx, |s, _| s.pressed = false);
let next = !self.checked.unwrap_or(state_up.read(cx).uncontrolled);
if !is_controlled {
state_up.update(cx, |s, _| s.uncontrolled = next);
}
if let Some(cb) = &on_change {
cb(&next, window, cx);
}
window.refresh();
}
})
.on_mouse_up_out(MouseButton::Left, {
move |_, window, cx| {
state_out.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
})
.child(div().flex_none().size(box_px).child(box_outer))
.child(label_block);
let press_inset = (1.0 - press_scale) * 0.5 * f32::from(box_px);
let row = row.p(px(press_inset));
let _ = FillCanvas {
ox: 0.0,
oy: 0.0,
scale: 0.0,
};
row
}
}
impl FillCanvas {
fn fill_round_rect(self, grow: f32, radius: f32, color: Hsla, window: &mut Window) {
if color.a <= 0.005 || grow <= 0.001 {
return;
}
let side = self.scale * grow;
let x = self.ox + (self.scale - side) / 2.0;
let y = self.oy + (self.scale - side) / 2.0;
let quad = gpui_kit::quad(
gpui_kit::Bounds {
origin: point(px(x), px(y)),
size: gpui_kit::Size {
width: px(side),
height: px(side),
},
},
px(radius * grow.min(1.0)),
color,
gpui_kit::Edges::default(),
gpui_kit::black(),
gpui_kit::BorderStyle::Solid,
);
window.paint_quad(quad);
}
fn stroke_polyline(
self,
sw: f32,
pts: &[(f32, f32)],
closed: bool,
color: Hsla,
window: &mut Window,
) {
if color.a <= 0.005 || pts.len() < 2 {
return;
}
let mut b = gpui_kit::PathBuilder::stroke(px(sw));
for (i, (x, y)) in pts.iter().enumerate() {
let p = point(px(self.ox + x * self.scale), px(self.oy + y * self.scale));
if i == 0 {
b.move_to(p);
} else {
b.line_to(p);
}
}
if closed {
b.close();
}
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::test::{TestEventExt as _, TestWindowExt as _};
use gpui_kit::{Context, Render, Role, TestAppContext, div};
use super::*;
#[gpui_kit::test]
fn spring_check_theme_defaults_and_explicit_colors(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
install_arc_theme(mode, Accent::Neutral, cx);
let colors = cx.arc_theme().colors;
let cfg = SpringCheckConfig::default().resolve_theme(colors);
assert_eq!(cfg.color, colors.foreground);
assert_eq!(cfg.fill_color, colors.accent);
assert_eq!(cfg.check_color, colors.accent_foreground);
let custom = SpringCheckConfig {
color: colors.danger,
..Default::default()
}
.resolve_theme(colors);
assert_eq!(custom.color, colors.danger);
}
});
}
struct Host {
events: Rc<std::cell::RefCell<Vec<bool>>>,
checked: Option<bool>,
default_checked: bool,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
let check = SpringCheck::new("sc-test")
.label("Ship the build")
.default_checked(self.default_checked)
.on_change(move |v, _, _| events.borrow_mut().push(*v));
let check = if let Some(c) = self.checked {
check.checked(c)
} else {
check
};
div().size_full().child(check)
}
}
fn setup(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
}
#[gpui_kit::test]
fn spring_check_rule_scale_matches_source() {
assert!((rule_scale(0.12, 0.12)).abs() < 1e-4);
assert!((rule_scale(0.84, 0.12) - 1.0).abs() < 1e-4);
assert!((rule_scale(0.48, 0.12) - 0.5).abs() < 1e-4);
assert!((rule_scale(0.06, 0.12)).abs() < 1e-4);
assert!((rule_scale(1.0, 0.12) - 1.0).abs() < 1e-4);
assert!((rule_scale(1.0, 0.9)).abs() < 1e-4);
}
#[gpui_kit::test]
fn spring_check_zeta_matches_source() {
assert!((zeta_of(0.0) - 1.0).abs() < 1e-4);
assert!(zeta_of(1.0).abs() < 1e-4);
assert!(zeta_of(0.2) > 0.0 && zeta_of(0.2) < 1.0);
}
#[gpui_kit::test]
fn spring_check_tick_clip_and_rule_segment() {
let total = tick_total_len();
assert!(total > 10.0);
let half = tick_points_to(total * 0.5);
assert_eq!(half.len(), 3);
assert_eq!(tick_points_to(total).len(), 3);
assert_eq!(tick_points_to(0.0).len(), 2);
assert_eq!(tick_points_to(total * 2.0).len(), 3);
assert_eq!(rule_segment(1.0, StrikeOrigin::Left), Some((0.0, 1.0)));
assert_eq!(rule_segment(0.5, StrikeOrigin::Center), Some((0.25, 0.75)));
assert_eq!(rule_segment(0.5, StrikeOrigin::Right), Some((0.5, 1.0)));
assert_eq!(rule_segment(1.0, StrikeOrigin::None), None);
}
#[gpui_kit::test]
fn spring_check_click_toggles_and_reports(cx: &mut TestAppContext) {
setup(cx);
let events = Rc::new(std::cell::RefCell::new(Vec::new()));
let (_view, cx) = cx.add_window_view(|_, _| Host {
events: events.clone(),
checked: None,
default_checked: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
let b = window.find("sc-test").bounds();
let pos = b.center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
window.render_frame(cx);
assert_eq!(events.borrow().clone(), vec![true]);
});
}
#[gpui_kit::test]
fn spring_check_row_has_checkbox_role(cx: &mut TestAppContext) {
setup(cx);
let (_view, cx) = cx.add_window_view(|_, _| Host {
events: Rc::new(std::cell::RefCell::new(Vec::new())),
checked: None,
default_checked: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(window.find("sc-test").role(), Some(Role::CheckBox));
});
}
}