1use std::rc::Rc;
16
17use arc_motion::{arc_spring, is_reduced_motion};
18use arc_tokens::{ActiveArcTheme as _, SpringSpec};
19use gpui_kit::{
20 App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
21 Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
22 relative,
23};
24pub const RULE_END: f32 = 0.84;
28const RULE_TOP_RATIO: f32 = 0.46;
30const BOX_SWELL: f32 = 0.35;
32const TICK_VIEW: f32 = 24.0;
34const TICK_STROKE: f32 = 2.6;
36const TICK_P0: (f32, f32) = (5.0, 12.5);
38const TICK_P1: (f32, f32) = (10.0, 17.5);
39const TICK_P2: (f32, f32) = (19.0, 6.5);
40
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum StrikeOrigin {
44 #[default]
46 Left,
47 Center,
49 Right,
51 None,
53}
54
55impl StrikeOrigin {
56 pub fn parse(value: &str) -> Self {
58 match value {
59 "center" => Self::Center,
60 "right" => Self::Right,
61 "none" => Self::None,
62 _ => Self::Left,
63 }
64 }
65}
66
67fn zeta_of(bounce: f32) -> f32 {
70 if bounce <= 0.0 {
71 return 1.0;
72 }
73 let l = f64::from(bounce).ln();
74 (-l / (std::f64::consts::PI.powi(2) + l * l).sqrt()) as f32
75}
76
77#[derive(Clone, Debug)]
79pub struct SpringCheckConfig {
80 pub color: Hsla,
82 pub fill_color: Hsla,
84 pub check_color: Hsla,
86 pub box_size: f32,
88 pub box_radius: f32,
90 pub font_size: f32,
92 pub bounce: f32,
94 pub strike_lag: f32,
96 pub done_opacity: f32,
98 pub strike: StrikeOrigin,
100 pub disabled: bool,
102}
103
104impl Default for SpringCheckConfig {
105 fn default() -> Self {
106 Self {
107 color: Hsla::default(),
108 fill_color: Hsla::default(),
109 check_color: Hsla::default(),
110 box_size: 28.0,
111 box_radius: 9.0,
112 font_size: 18.0,
113 bounce: 0.2,
114 strike_lag: 0.12,
115 done_opacity: 0.42,
116 strike: StrikeOrigin::Left,
117 disabled: false,
118 }
119 }
120}
121
122impl SpringCheckConfig {
123 fn resolve_theme(mut self, colors: arc_tokens::ArcColors) -> Self {
124 if self.color.a == 0.0 {
125 self.color = colors.foreground;
126 }
127 if self.fill_color.a == 0.0 {
128 self.fill_color = colors.accent;
129 }
130 if self.check_color.a == 0.0 {
131 self.check_color = colors.accent_foreground;
132 }
133 self
134 }
135
136 pub fn normalized(mut self) -> Self {
138 self.box_size = self.box_size.clamp(14.0, 80.0).max(1.0);
139 self.box_radius = self.box_radius.clamp(0.0, self.box_size / 2.0);
140 self.font_size = self.font_size.clamp(10.0, 40.0);
141 self.bounce = self.bounce.clamp(0.0, 0.5);
142 self.strike_lag = self.strike_lag.clamp(0.0, 0.6);
143 self.done_opacity = self.done_opacity.clamp(0.0, 1.0);
144 self
145 }
146}
147
148#[derive(Clone, Copy)]
150struct SpringCheckInternal {
151 uncontrolled: bool,
152 hovered: bool,
153 pressed: bool,
154}
155
156pub type SpringCheckChange = bool;
158type ChangeHandler = Rc<dyn Fn(&SpringCheckChange, &mut Window, &mut App)>;
159
160#[derive(IntoElement)]
165pub struct SpringCheck {
166 id: ElementId,
168 label: SharedString,
170 aria_label: Option<SharedString>,
172 checked: Option<bool>,
174 default_checked: bool,
176 config: SpringCheckConfig,
178 on_change: Option<ChangeHandler>,
180}
181
182impl SpringCheck {
183 pub fn new(id: impl Into<ElementId>) -> Self {
185 Self {
186 id: id.into(),
187 label: "Ship the build".into(),
188 aria_label: None,
189 checked: None,
190 default_checked: false,
191 config: SpringCheckConfig::default(),
192 on_change: None,
193 }
194 }
195
196 pub fn label(mut self, v: impl Into<SharedString>) -> Self {
198 self.label = v.into();
199 self
200 }
201
202 pub fn aria_label(mut self, v: impl Into<SharedString>) -> Self {
204 self.aria_label = Some(v.into());
205 self
206 }
207
208 pub fn checked(mut self, v: bool) -> Self {
210 self.checked = Some(v);
211 self
212 }
213
214 pub fn default_checked(mut self, v: bool) -> Self {
216 self.default_checked = v;
217 self
218 }
219
220 pub fn config(mut self, v: SpringCheckConfig) -> Self {
222 self.config = v;
223 self
224 }
225
226 pub fn on_change(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
228 self.on_change = Some(Rc::new(f));
229 self
230 }
231}
232
233fn rule_scale(t: f32, strike_lag: f32) -> f32 {
236 if strike_lag >= RULE_END {
237 return 0.0;
238 }
239 ((t - strike_lag) / (RULE_END - strike_lag)).clamp(0.0, 1.0)
240}
241
242fn tick_total_len() -> f32 {
244 let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
245 let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
246 seg1 + seg2
247}
248
249fn tick_points_to(drawn: f32) -> Vec<(f32, f32)> {
251 let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
252 let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
253 let mut pts = vec![TICK_P0];
254 if drawn >= seg1 {
255 pts.push(TICK_P1);
256 if drawn >= seg1 + seg2 {
257 pts.push(TICK_P2);
258 } else {
259 let f = (drawn - seg1) / seg2;
260 pts.push((
261 TICK_P1.0 + (TICK_P2.0 - TICK_P1.0) * f,
262 TICK_P1.1 + (TICK_P2.1 - TICK_P1.1) * f,
263 ));
264 }
265 } else {
266 let f = drawn / seg1;
267 pts.push((
268 TICK_P0.0 + (TICK_P1.0 - TICK_P0.0) * f,
269 TICK_P0.1 + (TICK_P1.1 - TICK_P0.1) * f,
270 ));
271 }
272 pts
273}
274
275fn rule_segment(scale: f32, origin: StrikeOrigin) -> Option<(f32, f32)> {
277 match origin {
278 StrikeOrigin::None => None,
279 StrikeOrigin::Left => Some((0.0, scale)),
280 StrikeOrigin::Center => {
281 let half = scale / 2.0;
282 Some((0.5 - half, 0.5 + half))
283 }
284 StrikeOrigin::Right => Some((1.0 - scale, 1.0)),
285 }
286}
287
288#[derive(Clone, Copy)]
290struct FillCanvas {
291 ox: f32,
292 oy: f32,
293 scale: f32,
294}
295
296impl RenderOnce for SpringCheck {
297 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
298 let reduced = is_reduced_motion(cx);
299 let cfg = self
300 .config
301 .normalized()
302 .resolve_theme(cx.arc_theme().colors);
303
304 let state_id = ElementId::NamedChild(self.id.clone().into(), "__spring-check-state".into());
305 let internal = window.use_keyed_state(state_id, cx, |_, _| SpringCheckInternal {
306 uncontrolled: self.default_checked,
307 hovered: false,
308 pressed: false,
309 });
310 let snap = *internal.read(cx);
311
312 let is_controlled = self.checked.is_some();
313 let is_on = self.checked.unwrap_or(snap.uncontrolled);
314
315 let spec = SpringSpec::visual(0.2, 1.0 - zeta_of(cfg.bounce));
317 let t = if reduced {
318 if is_on { 1.0 } else { 0.0 }
319 } else {
320 arc_spring(
321 (self.id.clone(), "check-t"),
322 if is_on { 1.0 } else { 0.0 },
323 spec,
324 window,
325 cx,
326 )
327 };
328 let press_scale = if reduced {
329 1.0
330 } else {
331 arc_spring(
332 (self.id.clone(), "press-scale"),
333 if !cfg.disabled && snap.pressed {
334 0.95
335 } else {
336 1.0
337 },
338 SpringSpec::visual(0.16, 0.0),
339 window,
340 cx,
341 )
342 };
343
344 let fill_scale = t.max(0.0);
346 let tick_alpha = t.clamp(0.0, 1.0);
347 let word_opacity = 1.0 - (1.0 - cfg.done_opacity) * t.clamp(0.0, 1.0);
348 let rule = if cfg.strike == StrikeOrigin::None {
349 0.0
350 } else {
351 rule_scale(t, cfg.strike_lag)
352 };
353 let box_growth = BOX_SWELL * (t - 1.0).max(0.0); let ring_opacity = if !cfg.disabled && snap.hovered {
355 0.5
356 } else {
357 0.28
358 };
359
360 let ring_w = if cfg.box_size >= 24.0 { 2.0 } else { 1.5 };
362 let gap = (cfg.box_size * 0.43).round().clamp(8.0, 16.0);
363 let rule_h = ((cfg.font_size / 6.0).round() / 2.0).max(1.5);
364 let row_h = (cfg.box_size + 16.0).max(44.0);
365 let box_px = px(cfg.box_size);
366 let box_size_now = px(cfg.box_size * (1.0 + box_growth));
367
368 let fill_id = ElementId::NamedChild(self.id.clone().into(), "fill-canvas".into());
370 let fill_color = cfg.fill_color;
371 let check_color = cfg.check_color;
372 let radius = cfg.box_radius;
373 let total_len = tick_total_len();
374 let drawn_len = total_len * tick_alpha;
375 let fill_canvas = div().id(fill_id).size(box_size_now).flex_none().child(
376 canvas(
377 move |_, _, _| {},
378 move |rect, _, window, _| {
379 let ox = f32::from(rect.origin.x);
380 let oy = f32::from(rect.origin.y);
381 let s = f32::from(rect.size.width).min(f32::from(rect.size.height));
382 if s <= 0.0 {
383 return;
384 }
385 let cv = FillCanvas { ox, oy, scale: s };
386 cv.fill_round_rect(fill_scale, radius, fill_color, window);
387 if drawn_len > 0.5 {
388 let pts = tick_points_to(drawn_len);
389 let k = s / TICK_VIEW;
390 cv.stroke_polyline(TICK_STROKE * k, &pts, false, check_color, window);
391 }
392 },
393 )
394 .size_full(),
395 );
396
397 let ring_color = Hsla {
399 a: cfg.color.a * ring_opacity * (ring_w / 2.0),
400 ..cfg.color
401 };
402 let box_outer = div()
403 .relative()
404 .size(box_size_now)
405 .rounded(px(radius))
406 .border_1()
407 .border_color(ring_color)
408 .overflow_hidden()
409 .flex()
410 .items_center()
411 .justify_center()
412 .child(fill_canvas);
413
414 let label_color = Hsla {
416 a: cfg.color.a * word_opacity,
417 ..cfg.color
418 };
419 let rule_color = Hsla {
420 a: cfg.color.a,
421 ..cfg.color
422 };
423 let rule_seg = rule_segment(rule, cfg.strike);
424 let label_block = div()
425 .relative()
426 .text_size(px(cfg.font_size))
427 .font_medium()
428 .whitespace_nowrap()
429 .text_color(label_color)
430 .child(self.label.clone())
431 .when_some(rule_seg, |el, (x0, x1)| {
432 el.child(
434 div()
435 .absolute()
436 .top(relative(RULE_TOP_RATIO))
437 .h(px(rule_h))
438 .rounded(px(2.0))
439 .bg(rule_color)
440 .left(relative(x0))
441 .w(relative(x1 - x0)),
442 )
443 });
444
445 let on_change = self.on_change.clone();
447 let state_hover = internal.clone();
448 let state_down = internal.clone();
449 let state_up = internal.clone();
450 let state_out = internal.clone();
451 let row = div()
452 .id(self.id.clone())
453 .test_support()
454 .role(Role::CheckBox)
455 .aria_toggled(if is_on {
456 gpui_kit::Toggled::True
457 } else {
458 gpui_kit::Toggled::False
459 })
460 .aria_label(
461 self.aria_label
462 .clone()
463 .unwrap_or_else(|| self.label.clone()),
464 )
465 .flex()
466 .items_center()
467 .gap(px(gap))
468 .h(px(row_h))
469 .cursor_pointer()
470 .when(cfg.disabled, |el| el.opacity(0.5).cursor_default())
471 .when(!cfg.disabled, |el| {
472 el.on_hover({
473 move |h: &bool, window, cx| {
474 state_hover.update(cx, |s, _| {
475 s.hovered = *h;
476 if !*h {
477 s.pressed = false;
478 }
479 });
480 window.refresh();
481 }
482 })
483 .on_mouse_down(MouseButton::Left, {
484 move |_, window, cx| {
485 state_down.update(cx, |s, _| s.pressed = true);
486 window.refresh();
487 }
488 })
489 .on_mouse_up(MouseButton::Left, {
490 move |_, window, cx| {
491 state_up.update(cx, |s, _| s.pressed = false);
492 let next = !self.checked.unwrap_or(state_up.read(cx).uncontrolled);
493 if !is_controlled {
494 state_up.update(cx, |s, _| s.uncontrolled = next);
495 }
496 if let Some(cb) = &on_change {
497 cb(&next, window, cx);
498 }
499 window.refresh();
500 }
501 })
502 .on_mouse_up_out(MouseButton::Left, {
503 move |_, window, cx| {
504 state_out.update(cx, |s, _| s.pressed = false);
505 window.refresh();
506 }
507 })
508 })
509 .child(div().flex_none().size(box_px).child(box_outer))
510 .child(label_block);
511
512 let press_inset = (1.0 - press_scale) * 0.5 * f32::from(box_px);
514 let row = row.p(px(press_inset));
515
516 let _ = FillCanvas {
517 ox: 0.0,
518 oy: 0.0,
519 scale: 0.0,
520 };
521 row
522 }
523}
524
525impl FillCanvas {
526 fn fill_round_rect(self, grow: f32, radius: f32, color: Hsla, window: &mut Window) {
527 if color.a <= 0.005 || grow <= 0.001 {
528 return;
529 }
530 let side = self.scale * grow;
531 let x = self.ox + (self.scale - side) / 2.0;
532 let y = self.oy + (self.scale - side) / 2.0;
533 let quad = gpui_kit::quad(
534 gpui_kit::Bounds {
535 origin: point(px(x), px(y)),
536 size: gpui_kit::Size {
537 width: px(side),
538 height: px(side),
539 },
540 },
541 px(radius * grow.min(1.0)),
542 color,
543 gpui_kit::Edges::default(),
544 gpui_kit::black(),
545 gpui_kit::BorderStyle::Solid,
546 );
547 window.paint_quad(quad);
548 }
549
550 fn stroke_polyline(
551 self,
552 sw: f32,
553 pts: &[(f32, f32)],
554 closed: bool,
555 color: Hsla,
556 window: &mut Window,
557 ) {
558 if color.a <= 0.005 || pts.len() < 2 {
559 return;
560 }
561 let mut b = gpui_kit::PathBuilder::stroke(px(sw));
562 for (i, (x, y)) in pts.iter().enumerate() {
563 let p = point(px(self.ox + x * self.scale), px(self.oy + y * self.scale));
564 if i == 0 {
565 b.move_to(p);
566 } else {
567 b.line_to(p);
568 }
569 }
570 if closed {
571 b.close();
572 }
573 if let Ok(path) = b.build() {
574 window.paint_path(path, color);
575 }
576 }
577}
578
579#[cfg(test)]
580mod tests {
581 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
582 use gpui_kit::test::{TestEventExt as _, TestWindowExt as _};
583 use gpui_kit::{Context, Render, Role, TestAppContext, div};
584
585 use super::*;
586
587 #[gpui_kit::test]
588 fn spring_check_theme_defaults_and_explicit_colors(cx: &mut TestAppContext) {
589 cx.update(|cx| {
590 gpui_kit::init(cx);
591 for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
592 install_arc_theme(mode, Accent::Neutral, cx);
593 let colors = cx.arc_theme().colors;
594 let cfg = SpringCheckConfig::default().resolve_theme(colors);
595 assert_eq!(cfg.color, colors.foreground);
596 assert_eq!(cfg.fill_color, colors.accent);
597 assert_eq!(cfg.check_color, colors.accent_foreground);
598 let custom = SpringCheckConfig {
599 color: colors.danger,
600 ..Default::default()
601 }
602 .resolve_theme(colors);
603 assert_eq!(custom.color, colors.danger);
604 }
605 });
606 }
607
608 struct Host {
609 events: Rc<std::cell::RefCell<Vec<bool>>>,
610 checked: Option<bool>,
611 default_checked: bool,
612 }
613
614 impl Render for Host {
615 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
616 let events = self.events.clone();
617 let check = SpringCheck::new("sc-test")
618 .label("Ship the build")
619 .default_checked(self.default_checked)
620 .on_change(move |v, _, _| events.borrow_mut().push(*v));
621 let check = if let Some(c) = self.checked {
622 check.checked(c)
623 } else {
624 check
625 };
626 div().size_full().child(check)
627 }
628 }
629
630 fn setup(cx: &mut TestAppContext) {
631 cx.update(|cx| {
632 gpui_kit::init(cx);
633 install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
634 });
635 }
636
637 #[gpui_kit::test]
638 fn spring_check_rule_scale_matches_source() {
639 assert!((rule_scale(0.12, 0.12)).abs() < 1e-4);
641 assert!((rule_scale(0.84, 0.12) - 1.0).abs() < 1e-4);
642 assert!((rule_scale(0.48, 0.12) - 0.5).abs() < 1e-4);
643 assert!((rule_scale(0.06, 0.12)).abs() < 1e-4);
644 assert!((rule_scale(1.0, 0.12) - 1.0).abs() < 1e-4);
645 assert!((rule_scale(1.0, 0.9)).abs() < 1e-4);
647 }
648
649 #[gpui_kit::test]
650 fn spring_check_zeta_matches_source() {
651 assert!((zeta_of(0.0) - 1.0).abs() < 1e-4);
652 assert!(zeta_of(1.0).abs() < 1e-4);
654 assert!(zeta_of(0.2) > 0.0 && zeta_of(0.2) < 1.0);
655 }
656
657 #[gpui_kit::test]
658 fn spring_check_tick_clip_and_rule_segment() {
659 let total = tick_total_len();
660 assert!(total > 10.0);
661 let half = tick_points_to(total * 0.5);
663 assert_eq!(half.len(), 3);
664 assert_eq!(tick_points_to(total).len(), 3);
666 assert_eq!(tick_points_to(0.0).len(), 2);
668 assert_eq!(tick_points_to(total * 2.0).len(), 3);
670 assert_eq!(rule_segment(1.0, StrikeOrigin::Left), Some((0.0, 1.0)));
672 assert_eq!(rule_segment(0.5, StrikeOrigin::Center), Some((0.25, 0.75)));
673 assert_eq!(rule_segment(0.5, StrikeOrigin::Right), Some((0.5, 1.0)));
674 assert_eq!(rule_segment(1.0, StrikeOrigin::None), None);
675 }
676
677 #[gpui_kit::test]
678 fn spring_check_click_toggles_and_reports(cx: &mut TestAppContext) {
679 setup(cx);
680 let events = Rc::new(std::cell::RefCell::new(Vec::new()));
681 let (_view, cx) = cx.add_window_view(|_, _| Host {
682 events: events.clone(),
683 checked: None,
684 default_checked: false,
685 });
686 cx.update(|window, cx| {
687 window.render_frame(cx);
688 let b = window.find("sc-test").bounds();
689 let pos = b.center();
690 window.pointer_down(pos, MouseButton::Left, cx);
691 window.pointer_up(pos, MouseButton::Left, cx);
692 window.render_frame(cx);
693 assert_eq!(events.borrow().clone(), vec![true]);
694 });
695 }
696
697 #[gpui_kit::test]
698 fn spring_check_row_has_checkbox_role(cx: &mut TestAppContext) {
699 setup(cx);
700 let (_view, cx) = cx.add_window_view(|_, _| Host {
701 events: Rc::new(std::cell::RefCell::new(Vec::new())),
702 checked: None,
703 default_checked: false,
704 });
705 cx.update(|window, cx| {
706 window.render_frame(cx);
707 assert_eq!(window.find("sc-test").role(), Some(Role::CheckBox));
708 });
709 }
710}