1use std::{cell::RefCell, collections::VecDeque, rc::Rc, time::Duration};
7
8use arc_motion::{
9 CubicBezier, ScalarTween, SpringSolver, TweenEase, is_reduced_motion, motion_now,
10};
11use arc_tokens::{ActiveArcTheme as _, SpringSpec};
12use gpui_kit::{
13 App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
14 MouseMoveEvent, MouseUpEvent, ParentElement, RenderOnce, Role, SharedString, Styled,
15 TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div, prelude::*,
16 px, svg,
17};
18
19const PAD: f32 = 4.;
20const SQUASH_MAX: f32 = 0.08;
21const SQUASH_DIV: f32 = 110.;
22const SWELL: f32 = 1.03;
24const SHAKE_MS: f64 = 450.;
25const HOME_DELAY_MS: f64 = 300.;
26const SPINNER_STROKE: f32 = 2.4;
27
28fn ease_out() -> TweenEase {
30 TweenEase::CubicBezier(CubicBezier::new(0.23, 1., 0.32, 1.))
31}
32
33fn on_color(c: Hsla) -> Hsla {
35 let rgb: gpui_kit::Rgba = c.into();
36 if (rgb.r * 299. + rgb.g * 587. + rgb.b * 114.) / 1000. >= 150. / 255. {
37 arc_tokens::hex(0x111111, 1.)
38 } else {
39 arc_tokens::hex(0xffffff, 1.)
40 }
41}
42
43#[derive(Clone, Debug)]
45pub enum SlideCommitConfirm {
46 Ok,
48 Err(SharedString),
50 PendingOk(Duration),
52 PendingErr(Duration, SharedString),
54}
55
56pub type ConfirmHandler = Rc<dyn Fn(&mut Window, &mut App) -> SlideCommitConfirm>;
57pub type DoneHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
58pub type ErrorHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
59
60#[derive(Clone, Debug)]
61pub struct SlideCommitConfig {
62 pub track_color: Option<Hsla>,
63 pub handle_color: Option<Hsla>,
64 pub success_color: Option<Hsla>,
65 pub danger_color: Option<Hsla>,
66 pub width: f32,
67 pub height: f32,
68 pub radius: f32,
69 pub speed: f32,
71 pub return_bounce: f32,
73 pub landing_dip: f32,
75 pub hold_ms: f64,
77 pub min_pending_ms: f64,
79 pub disabled: bool,
80}
81
82impl Default for SlideCommitConfig {
83 fn default() -> Self {
84 Self {
85 track_color: None,
86 handle_color: None,
87 success_color: None,
88 danger_color: None,
89 width: 280.,
90 height: 56.,
91 radius: 28.,
92 speed: 50.,
93 return_bounce: 0.38,
94 landing_dip: 0.026,
95 hold_ms: 1500.,
96 min_pending_ms: 300.,
97 disabled: false,
98 }
99 }
100}
101
102impl SlideCommitConfig {
103 fn normalized(&self) -> Self {
104 let mut c = self.clone();
105 let d = Self::default();
106 macro_rules! norm {
107 ($f:ident, $lo:expr, $hi:expr) => {
108 c.$f = if c.$f.is_finite() {
109 c.$f.clamp($lo, $hi)
110 } else {
111 d.$f
112 };
113 };
114 }
115 norm!(width, 160., 640.);
116 norm!(height, 40., 120.);
117 let max_radius = c.height / 2.;
118 norm!(radius, 0., max_radius);
119 norm!(speed, 0., 100.);
120 norm!(return_bounce, 0., 0.5);
121 norm!(landing_dip, 0., 0.2);
122 c.hold_ms = if c.hold_ms.is_finite() {
123 c.hold_ms.max(0.)
124 } else {
125 d.hold_ms
126 };
127 c.min_pending_ms = if c.min_pending_ms.is_finite() {
128 c.min_pending_ms.max(0.)
129 } else {
130 d.min_pending_ms
131 };
132 c
133 }
134}
135
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137enum Phase {
138 Idle,
139 Pending,
140 Done,
141 Error,
142}
143
144struct Channel {
146 value: f32,
147 target: f32,
148 start: f64,
149 duration: f64,
150 spring: Option<SpringSolver>,
151 tween: ScalarTween,
152}
153
154impl Channel {
155 fn new(v: f32) -> Self {
156 Self {
157 value: v,
158 target: v,
159 start: 0.,
160 duration: 0.,
161 spring: None,
162 tween: ScalarTween::new(v),
163 }
164 }
165 fn set(&mut self, v: f32) {
166 *self = Self::new(v);
167 }
168 fn spring(&mut self, target: f32, now: f64, spec: SpringSpec, velocity: f32) {
169 self.target = target;
170 self.start = now;
171 self.duration = 1.;
172 self.spring = Some(SpringSolver::new(
173 spec,
174 self.value as f64,
175 target as f64,
176 velocity as f64,
177 ));
178 }
179 fn ease(&mut self, target: f32, now: f64, duration: f64, delay: f64, reduced: bool) {
180 self.spring = None;
181 self.tween = ScalarTween::new(self.value);
182 self.tween.retarget(
183 target,
184 now,
185 duration as f32,
186 delay as f32,
187 ease_out(),
188 reduced,
189 );
190 self.target = target;
191 self.start = now;
192 self.duration = duration;
193 }
194 fn tick(&mut self, now: f64) -> bool {
195 if let Some(s) = &self.spring {
196 let sample = s.sample((now - self.start).max(0.));
197 self.value = sample.value;
198 if sample.settled {
199 self.set(self.target);
200 return false;
201 }
202 return true;
203 }
204 if self.tween.settled(now) {
205 if self.value != self.target {
206 self.set(self.target);
207 }
208 return false;
209 }
210 self.value = self.tween.sample(now);
211 true
212 }
213}
214
215struct Timed {
217 start: f64,
218 duration: f64,
219 keys: Vec<(f32, f32)>,
220}
221
222impl Timed {
223 fn sample(&self, now: f64) -> f32 {
224 let u = (((now - self.start) / self.duration).clamp(0., 1.)) as f32;
225 if u <= 0. {
226 return self.keys[0].1;
227 }
228 if u >= 1. {
229 return self.keys[self.keys.len() - 1].1;
230 }
231 for w in self.keys.windows(2) {
232 if u >= w[0].0 && u <= w[1].0 {
233 let t = (u - w[0].0) / (w[1].0 - w[0].0).max(1e-6);
234 return w[0].1 + (w[1].1 - w[0].1) * ease_out().sample(t);
235 }
236 }
237 self.keys[self.keys.len() - 1].1
238 }
239 fn done(&self, now: f64) -> bool {
240 now >= self.start + self.duration
241 }
242}
243
244fn shake_timeline(now: f64) -> Timed {
246 Timed {
247 start: now,
248 duration: SHAKE_MS / 1000.,
249 keys: vec![
250 (0., 0.),
251 (1. / 6., -5.),
252 (2. / 6., 5.),
253 (3. / 6., -3.),
254 (4. / 6., 3.),
255 (5. / 6., -1.),
256 (1., 0.),
257 ],
258 }
259}
260
261struct Grip {
262 x_start: f32,
264 grab: Option<f32>,
266 ax: f32,
268 moved: bool,
269 vertical: bool,
270 hist: VecDeque<(f64, f32)>,
271}
272
273struct PendingWait {
274 #[allow(dead_code)]
276 run: u32,
277 ok: bool,
278 reason: SharedString,
279 deadline: f64,
280}
281
282enum Event {
283 Done,
284 Error(SharedString),
285}
286
287struct State {
288 config: SlideCommitConfig,
289 label: SharedString,
290 done_label: SharedString,
291 error_label: SharedString,
292 on_confirm: Option<ConfirmHandler>,
293 on_done: Option<DoneHandler>,
294 on_error: Option<ErrorHandler>,
295 bounds: Bounds<gpui_kit::Pixels>,
296 phase: Phase,
297 phase_start: f64,
298 run: u32,
299 x: Channel,
300 anchor: Channel,
301 shown: Channel,
302 spin: Channel,
303 done_fade: Channel,
304 err_fade: Channel,
305 shake: Option<Timed>,
306 pulse: Option<Timed>,
307 grip: Option<Grip>,
308 pending: Option<PendingWait>,
309 settle_deadline: Option<(u32, f64)>,
310 home_deadline: Option<f64>,
311 error_reset: Option<f64>,
312 hot: bool,
314 focus: FocusHandle,
315}
316
317impl State {
318 fn travel(&self) -> f32 {
319 let c = &self.config;
320 let grip = (c.height - PAD * 2.).max(1.);
321 let inner = (c.width - PAD * 2.).max(grip + 1.);
322 (inner - grip).max(1.)
323 }
324 fn interactive(&self) -> bool {
325 !self.config.disabled && self.phase == Phase::Idle
326 }
327 fn spring_specs(&self) -> (SpringSpec, SpringSpec) {
328 let k = 260. + self.config.speed * 6.4;
329 let mass = 0.9;
330 let critical = 2. * (k * mass).sqrt();
331 (
332 SpringSpec::physics_with_mass(k, critical, mass),
333 SpringSpec::physics_with_mass(k, critical * (1. - self.config.return_bounce), mass),
334 )
335 }
336 fn go_home(&mut self, velocity: f32, now: f64, reduced: bool) {
337 if reduced {
338 self.x.ease(0., now, 0.2, 0., true);
339 } else {
340 let (_, home) = self.spring_specs();
341 self.x.spring(0., now, home, velocity.min(0.));
342 }
343 }
344 fn settle(&mut self, now: f64, reduced: bool) {
345 self.phase = Phase::Idle;
346 self.done_fade.ease(0., now, 0.2, 0., reduced);
347 self.shown.ease(1., now, 0.2, 0.12, reduced);
348 self.err_fade.ease(0., now, 0.2, 0., reduced);
349 if reduced {
350 self.anchor.set(0.);
351 } else {
352 self.anchor
353 .spring(0., now, SpringSpec::duration(0.3, 0.), 0.);
354 }
355 }
356 fn resolve(&mut self, via_key: bool, now: f64, reduced: bool) -> Vec<Event> {
357 self.phase = Phase::Done;
358 self.anchor.set(self.x.value);
359 self.spin.ease(0., now, 0.12, 0., reduced);
360 self.done_fade.ease(1., now, 0.2, 0., reduced);
361 if reduced {
362 self.x.set(0.);
363 } else {
364 let (commit, _) = self.spring_specs();
365 self.x.spring(0., now, commit, 0.);
366 if !via_key && self.config.landing_dip > 0. {
367 self.pulse = Some(Timed {
368 start: now + 0.1,
369 duration: 0.46,
370 keys: vec![(0., 1.), (0.62, 1. - self.config.landing_dip), (1., 1.)],
371 });
372 }
373 }
374 if self.config.hold_ms > 0. {
375 self.settle_deadline = Some((self.run, now + self.config.hold_ms / 1000.));
376 }
377 vec![Event::Done]
378 }
379 fn reject(&mut self, reason: SharedString, now: f64, reduced: bool) -> Vec<Event> {
380 self.phase = Phase::Error;
381 self.spin.ease(0., now, 0.12, 0., reduced);
382 self.shown.ease(1., now, 0.2, 0.12, reduced);
383 self.err_fade.ease(1., now, 0.2, 0., reduced);
384 if reduced {
385 self.go_home(0., now, true);
386 } else {
387 self.shake = Some(shake_timeline(now));
388 self.home_deadline = Some(now + HOME_DELAY_MS / 1000.);
389 }
390 self.error_reset = Some(now + (self.config.hold_ms.max(1500.)) / 1000.);
391 vec![Event::Error(reason)]
392 }
393 fn begin_confirm(
395 &mut self,
396 outcome: SlideCommitConfirm,
397 now: f64,
398 reduced: bool,
399 ) -> Vec<Event> {
400 match outcome {
401 SlideCommitConfirm::Ok => self.resolve(false, now, reduced),
402 SlideCommitConfirm::Err(reason) => self.reject(reason, now, reduced),
403 SlideCommitConfirm::PendingOk(delay) => {
404 self.enter_pending(true, SharedString::new(""), delay, now, reduced);
405 Vec::new()
406 }
407 SlideCommitConfirm::PendingErr(delay, reason) => {
408 self.enter_pending(false, reason, delay, now, reduced);
409 Vec::new()
410 }
411 }
412 }
413 fn enter_pending(
414 &mut self,
415 ok: bool,
416 reason: SharedString,
417 delay: Duration,
418 now: f64,
419 reduced: bool,
420 ) {
421 self.phase = Phase::Pending;
422 self.phase_start = now;
423 self.shown.ease(0., now, 0.2, 0., reduced);
424 self.spin.ease(1., now, 0.2, 0., reduced);
425 let min = self.config.min_pending_ms / 1000.;
426 self.pending = Some(PendingWait {
427 run: self.run,
428 ok,
429 reason,
430 deadline: now + (min.max(delay.as_secs_f64())),
431 });
432 }
433 fn commit(&mut self, now: f64, reduced: bool) -> u32 {
435 self.run += 1;
436 self.settle_deadline = None;
437 self.x.set(self.travel());
438 self.shown.ease(0., now, 0.12, 0., reduced);
439 self.run
440 }
441 fn release(&mut self, velocity: f32, now: f64, reduced: bool) -> Option<u32> {
443 let g = self.grip.take()?;
444 let travel = self.travel();
445 if self.x.value >= travel - 0.01 {
446 return Some(self.commit(now, reduced));
447 }
448 if g.moved {
449 self.go_home(velocity, now, reduced);
450 } else if self.x.value > 0.01 {
451 self.go_home(0., now, reduced);
453 }
454 None
455 }
456 fn velocity_of(&self) -> f32 {
457 let g = match &self.grip {
458 Some(g) => g,
459 None => return 0.,
460 };
461 match (g.hist.front(), g.hist.back()) {
462 (Some(a), Some(b)) => {
463 ((b.1 - a.1) / ((b.0 - a.0).max(0.001) as f32)).clamp(-1500., 1500.)
464 }
465 _ => 0.,
466 }
467 }
468 fn advance(&mut self, now: f64, reduced: bool) -> (bool, Vec<Event>) {
470 let mut running = self.x.tick(now)
471 | self.anchor.tick(now)
472 | self.shown.tick(now)
473 | self.spin.tick(now)
474 | self.done_fade.tick(now)
475 | self.err_fade.tick(now);
476 for slot in [&mut self.shake, &mut self.pulse] {
477 if let Some(a) = slot {
478 if a.done(now) {
479 *slot = None;
480 } else {
481 running = true;
482 }
483 }
484 }
485 let mut events = Vec::new();
486 match self.phase {
487 Phase::Pending => {
488 running = true;
490 if let Some(p) = self.pending.take() {
491 if now >= p.deadline {
492 if p.ok {
493 events.extend(self.resolve(false, now, reduced));
494 } else {
495 events.extend(self.reject(p.reason.clone(), now, reduced));
496 }
497 } else {
498 self.pending = Some(p);
499 }
500 }
501 }
502 Phase::Done => {
503 if let Some((_, at)) = self.settle_deadline {
504 if now >= at {
505 self.settle_deadline = None;
506 self.settle(now, reduced);
507 } else {
508 running = true;
509 }
510 }
511 }
512 Phase::Error => {
513 if let Some(at) = self.home_deadline {
514 if now >= at {
515 self.home_deadline = None;
516 self.go_home(0., now, reduced);
517 } else {
518 running = true;
519 }
520 }
521 if let Some(at) = self.error_reset {
522 if now >= at {
523 self.error_reset = None;
524 self.home_deadline = None;
525 self.phase = Phase::Idle;
526 self.err_fade.ease(0., now, 0.2, 0., reduced);
527 } else {
528 running = true;
529 }
530 }
531 }
532 Phase::Idle => {}
533 }
534 (running, events)
535 }
536}
537
538#[derive(IntoElement)]
541pub struct SlideCommit {
542 id: ElementId,
543 label: SharedString,
544 done_label: SharedString,
545 error_label: SharedString,
546 config: SlideCommitConfig,
547 on_confirm: Option<ConfirmHandler>,
548 on_done: Option<DoneHandler>,
549 on_error: Option<ErrorHandler>,
550}
551
552impl SlideCommit {
553 pub fn new(id: impl Into<ElementId>) -> Self {
554 Self {
555 id: id.into(),
556 label: "Slide to pay".into(),
557 done_label: "Paid".into(),
558 error_label: "Payment failed".into(),
559 config: Default::default(),
560 on_confirm: None,
561 on_done: None,
562 on_error: None,
563 }
564 }
565 pub fn label(mut self, v: impl Into<SharedString>) -> Self {
566 self.label = v.into();
567 self
568 }
569 pub fn done_label(mut self, v: impl Into<SharedString>) -> Self {
570 self.done_label = v.into();
571 self
572 }
573 pub fn error_label(mut self, v: impl Into<SharedString>) -> Self {
574 self.error_label = v.into();
575 self
576 }
577 pub fn config(mut self, c: SlideCommitConfig) -> Self {
578 self.config = c;
579 self
580 }
581 pub fn on_confirm(
583 mut self,
584 v: impl Fn(&mut Window, &mut App) -> SlideCommitConfirm + 'static,
585 ) -> Self {
586 self.on_confirm = Some(Rc::new(v));
587 self
588 }
589 pub fn on_done(mut self, v: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
590 self.on_done = Some(Rc::new(v));
591 self
592 }
593 pub fn on_error(mut self, v: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
594 self.on_error = Some(Rc::new(v));
595 self
596 }
597}
598
599fn notify_events(events: Vec<Event>, state: &State, window: &mut Window, cx: &mut App) {
600 for e in events {
601 match e {
602 Event::Done => {
603 if let Some(cb) = &state.on_done {
604 cb(&(), window, cx);
605 }
606 }
607 Event::Error(reason) => {
608 if let Some(cb) = &state.on_error {
609 cb(&reason, window, cx);
610 }
611 }
612 }
613 }
614}
615
616fn drag_to(s: &mut State, next: f32, now: f64) -> bool {
618 let Some(g) = s.grip.as_mut() else {
619 return false;
620 };
621 let prev = s.x.value;
622 let moved_flag = (next - prev).abs() > 0.5;
623 g.moved |= moved_flag;
624 g.hist.push_back((now, next));
625 while g.hist.len() > 4 {
626 g.hist.pop_front();
627 }
628 s.x.set(next);
629 moved_flag
630}
631
632fn release_and_confirm(cell: &Rc<RefCell<State>>, window: &mut Window, cx: &mut App) {
633 let now = motion_now(cx);
634 let red = is_reduced_motion(cx);
635 let events = {
636 let run = {
637 let mut s = cell.borrow_mut();
638 let v = s.velocity_of();
639 s.release(v, now, red)
640 };
641 match run {
642 Some(run) => confirm_with_host(cell, run, window, cx, now, red),
643 None => Vec::new(),
644 }
645 };
646 if !events.is_empty() {
647 let s = cell.borrow();
648 notify_events(events, &s, window, cx);
649 }
650 window.refresh();
651}
652
653fn confirm_with_host(
655 cell: &Rc<RefCell<State>>,
656 run: u32,
657 window: &mut Window,
658 cx: &mut App,
659 now: f64,
660 reduced: bool,
661) -> Vec<Event> {
662 let outcome = {
663 let s = cell.borrow();
664 if s.run != run {
665 return Vec::new();
666 }
667 match &s.on_confirm {
668 Some(cb) => cb(window, cx),
669 None => SlideCommitConfirm::Ok,
670 }
671 };
672 cell.borrow_mut().begin_confirm(outcome, now, reduced)
673}
674
675fn commit_and_confirm(cell: &Rc<RefCell<State>>, window: &mut Window, cx: &mut App) {
676 let now = motion_now(cx);
677 let red = is_reduced_motion(cx);
678 let events = {
679 let run = {
680 let mut s = cell.borrow_mut();
681 if !s.interactive() {
682 return;
683 }
684 s.commit(now, red)
685 };
686 confirm_with_host(cell, run, window, cx, now, red)
687 };
688 if !events.is_empty() {
689 let s = cell.borrow();
690 notify_events(events, &s, window, cx);
691 }
692 window.refresh();
693}
694
695impl RenderOnce for SlideCommit {
696 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
697 let now = motion_now(cx);
698 let reduced = is_reduced_motion(cx);
699 let colors = cx.arc_theme().colors;
700 let config = self.config.normalized();
701 let id = self.id.clone();
702
703 let cell = window
704 .use_keyed_state(
705 ElementId::NamedChild(id.clone().into(), "state".into()),
706 cx,
707 |_, cx| {
708 Rc::new(RefCell::new(State {
709 config: SlideCommitConfig::default(),
710 label: "".into(),
711 done_label: "".into(),
712 error_label: "".into(),
713 on_confirm: None,
714 on_done: None,
715 on_error: None,
716 bounds: Bounds::default(),
717 phase: Phase::Idle,
718 phase_start: 0.,
719 run: 0,
720 x: Channel::new(0.),
721 anchor: Channel::new(0.),
722 shown: Channel::new(1.),
723 spin: Channel::new(0.),
724 done_fade: Channel::new(0.),
725 err_fade: Channel::new(0.),
726 shake: None,
727 pulse: None,
728 grip: None,
729 pending: None,
730 settle_deadline: None,
731 home_deadline: None,
732 error_reset: None,
733 hot: false,
734 focus: cx.focus_handle().tab_index(0).tab_stop(true),
735 }))
736 },
737 )
738 .read(cx)
739 .clone();
740
741 let (running, events) = {
743 let mut s = cell.borrow_mut();
744 s.config = config.clone();
745 s.label = self.label.clone();
746 s.done_label = self.done_label.clone();
747 s.error_label = self.error_label.clone();
748 s.on_confirm = self.on_confirm.clone();
749 s.on_done = self.on_done.clone();
750 s.on_error = self.on_error.clone();
751 s.advance(now, reduced)
752 };
753 if running {
754 window.request_animation_frame();
755 }
756 if !events.is_empty() {
757 let s = cell.borrow();
759 notify_events(events, &s, window, cx);
760 }
761
762 let s = cell.borrow();
763 let width = config.width;
764 let height = config.height;
765 let grip = (height - PAD * 2.).max(1.);
766 let inner = (width - PAD * 2.).max(grip + 1.);
767 let travel = (inner - grip).max(1.);
768 let r = config.radius.min(height / 2.);
769 let grip_r = (r - PAD).max(0.);
770 let font_size = ((height * 0.25).round() as i32).clamp(13, 17) as f32;
771 let icon_size = (grip * 0.42).round();
772 let check_size = (grip * 0.38).round();
773
774 let phase = s.phase;
775 let held = s.grip.is_some();
776 let dragging = held && s.grip.as_ref().is_some_and(|g| g.grab.is_some());
777 let x = s.x.value;
778 let seen = x.clamp(0., travel);
779 let anchor = s.anchor.value;
780 let edge = seen + grip + (anchor - seen).clamp(0., travel);
781 let swell = if s.hot && s.grip.is_none() && phase == Phase::Idle && !reduced {
784 SWELL
785 } else {
786 1.
787 };
788 let q = 1. - ((-x).max(0.) / SQUASH_DIV).min(SQUASH_MAX);
789 let capsule_w = (seen + (edge - seen) * q * swell).max(grip * 0.2);
790 let capsule_h = grip * swell / q.max(1e-3);
791 let content_center = seen + ((seen + edge) / 2. - seen) * q;
792 let content_left = content_center - inner / 2.;
793 let say = (1. - seen / (travel * 0.55)).clamp(0., 1.);
795 let arrow_op = s.shown.value * (1. - (seen - travel * 0.55) / (travel * 0.4)).clamp(0., 1.);
796 let spin_op = s.spin.value;
797 let done_op = s.done_fade.value;
798 let err_op = s.err_fade.value;
799 let percent = ((seen / travel * 100.).round() as i32).clamp(0, 100);
800 let pulse_scale = s.pulse.as_ref().map(|a| a.sample(now)).unwrap_or(1.);
802 let shake_dx = s.shake.as_ref().map(|a| a.sample(now)).unwrap_or(0.);
803 let pending_spin_angle = if phase == Phase::Pending {
804 (((now - s.phase_start) % 1.) as f32 * std::f32::consts::TAU) as f32
805 } else {
806 0.
807 };
808 let breathe = if reduced && phase == Phase::Pending {
809 (0.7 + 0.3 * f32::sin((now * std::f64::consts::TAU / 1.4) as f32)) as f32
810 } else {
811 1.
812 };
813 let interactive = s.interactive();
814 let focus = s.focus.clone();
815 let cell_for_probe = cell.clone();
816 let cell_for_touch = cell.clone();
817 let cell_for_down = cell.clone();
818 let cell_for_key = cell.clone();
819 let cell_for_hover = cell.clone();
820 drop(s);
821
822 let track_color = config.track_color.unwrap_or(colors.surface_muted);
823 let ink = config.handle_color.unwrap_or(colors.foreground);
824 let success = config.success_color.unwrap_or(colors.success);
825 let danger = config.danger_color.unwrap_or(colors.danger);
826 let capsule_bg = match phase {
827 Phase::Done => success,
828 Phase::Error => danger,
829 _ => ink,
830 };
831 let on_ink = on_color(capsule_bg);
832 let say_color = match phase {
833 Phase::Error => danger,
834 _ => ink.opacity(0.45),
835 };
836
837 let ring_color = on_ink.opacity((spin_op * breathe) as f32 * 0.25);
839 let arc_color = on_ink.opacity((spin_op * breathe) as f32);
840 let arc_angle = pending_spin_angle;
841 let radius_px = (icon_size / 2. - SPINNER_STROKE).max(1.);
842 let spinner = canvas(
843 |_, _, _| {},
844 move |bounds, _, window, _| {
845 if ring_color.a <= 0.01 {
846 return;
847 }
848 let cx0 = f32::from(bounds.size.width) / 2.;
849 let cy0 = f32::from(bounds.size.height) / 2.;
850 let circle = (0..=40).map(|i| {
851 let a = (i as f32 / 40.) * std::f32::consts::TAU;
852 gpui_kit::point(px(cx0 + a.cos() * radius_px), px(cy0 + a.sin() * radius_px))
853 });
854 if let Some(builder) = arc_motion::PolylinePath::new(
855 circle
856 .map(|p| arc_motion::PathPoint::new(f32::from(p.x), f32::from(p.y)))
857 .collect(),
858 )
859 .to_stroke_builder(
860 bounds.origin.x,
861 bounds.origin.y,
862 px(SPINNER_STROKE),
863 ) && let Ok(path) = builder.build()
864 {
865 window.paint_path(path, ring_color);
866 }
867 let arc = (0..=16).map(|i| {
868 let a = arc_angle - std::f32::consts::FRAC_PI_2
869 + (i as f32 / 16.) * std::f32::consts::FRAC_PI_2;
870 gpui_kit::point(px(cx0 + a.cos() * radius_px), px(cy0 + a.sin() * radius_px))
871 });
872 if let Some(builder) = arc_motion::PolylinePath::new(
873 arc.map(|p| arc_motion::PathPoint::new(f32::from(p.x), f32::from(p.y)))
874 .collect(),
875 )
876 .to_stroke_builder(
877 bounds.origin.x,
878 bounds.origin.y,
879 px(SPINNER_STROKE),
880 ) && let Ok(path) = builder.build()
881 {
882 window.paint_path(path, arc_color);
883 }
884 },
885 )
886 .absolute()
887 .size(px(icon_size));
888
889 let probe = canvas(
891 {
892 let cell = cell_for_probe.clone();
893 move |bounds, _, _| {
894 cell.borrow_mut().bounds = bounds;
895 }
896 },
897 move |_, _, window, _| {
898 if cell_for_probe.borrow().grip.is_none() {
899 return;
900 }
901 let st = cell_for_probe.clone();
902 window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
903 if !phase.bubble() {
904 return;
905 }
906 if st.borrow().grip.is_none() {
907 return;
908 }
909 if e.pressed_button != Some(MouseButton::Left) {
910 release_and_confirm(&st, window, cx);
911 return;
912 }
913 let now = motion_now(cx);
914 let red = is_reduced_motion(cx);
915 #[allow(unused_assignments)]
916 #[allow(unused_assignments)]
917 let mut moved = false;
918 {
919 let mut s = st.borrow_mut();
920 if !s.interactive() && s.grip.is_some() {
921 s.grip = None;
923 s.go_home(0., now, red);
924 moved = true;
925 } else {
926 let travel = s.travel();
927 let at = f32::from(e.position.x) - f32::from(s.bounds.origin.x);
928 let cur = s.x.value.clamp(0., travel);
929 let Some(g) = s.grip.as_mut() else {
930 return;
931 };
932 if g.grab.is_none() {
933 g.grab = Some(at - cur);
934 return;
935 }
936 let next = (at - g.grab.unwrap()).clamp(0., travel);
937 moved = drag_to(&mut s, next, now);
938 }
939 }
940 if moved {
941 cx.stop_propagation();
942 window.refresh();
943 }
944 });
945 let st = cell_for_probe.clone();
946 window.on_mouse_event(move |e: &MouseUpEvent, phase, window, cx| {
947 if phase.bubble() && e.button == MouseButton::Left {
948 release_and_confirm(&st, window, cx);
949 }
950 });
951 },
952 )
953 .absolute()
954 .size_full();
955
956 let label_el = div()
957 .absolute()
958 .inset_0()
959 .flex()
960 .items_center()
961 .justify_center()
962 .whitespace_nowrap()
963 .text_size(px(font_size))
964 .font_medium()
965 .child(
966 div()
967 .text_color(say_color)
968 .opacity(say * (1. - err_op))
969 .child(self.label.clone()),
970 )
971 .child(
972 div()
973 .absolute()
974 .text_color(danger)
975 .opacity(err_op)
976 .child(self.error_label.clone()),
977 );
978
979 let content = div()
980 .absolute()
981 .left(px(content_left))
982 .w(px(inner))
983 .h_full()
984 .when(phase == Phase::Done, |el| {
985 el.flex()
986 .items_center()
987 .justify_center()
988 .gap(px(8.))
989 .opacity(done_op)
990 .child(
991 svg()
992 .path(IconName::Check.path())
993 .size(px(check_size))
994 .text_color(on_ink),
995 )
996 .child(
997 div()
998 .text_size(px(font_size))
999 .font_semibold()
1000 .whitespace_nowrap()
1001 .text_color(on_ink)
1002 .child(self.done_label.clone()),
1003 )
1004 })
1005 .when(phase != Phase::Done, |el| {
1006 el.child(
1007 div()
1008 .absolute()
1009 .inset_0()
1010 .flex()
1011 .items_center()
1012 .justify_center()
1013 .opacity(arrow_op)
1014 .child(
1015 svg()
1016 .path(IconName::ArrowRight.path())
1017 .size(px(icon_size))
1018 .text_color(on_ink),
1019 ),
1020 )
1021 .when(spin_op > 0.01, |el| {
1022 el.child(
1023 div()
1024 .absolute()
1025 .inset_0()
1026 .flex()
1027 .items_center()
1028 .justify_center()
1029 .child(spinner),
1030 )
1031 })
1032 });
1033
1034 let capsule = div()
1035 .id(ElementId::NamedChild(id.clone().into(), "capsule".into()))
1036 .test_support()
1037 .role(Role::Slider)
1038 .aria_label(self.label.clone())
1039 .aria_value(format!("{}%, {}%", percent, self.label))
1040 .when(interactive, |el| {
1041 el.track_focus(&focus).tab_stop(true).cursor_grab()
1042 })
1043 .when(!interactive, |el| el.tab_stop(false).cursor_default())
1044 .when(dragging, |el| el.cursor_grabbing())
1045 .when(focus.is_focused(window), |el| {
1046 el.border_2().border_color(track_color)
1047 })
1048 .absolute()
1049 .left(px(PAD))
1050 .top(px(PAD + (grip - capsule_h) / 2.))
1051 .w(px(capsule_w))
1052 .h(px(capsule_h))
1053 .rounded(px(grip_r.min(capsule_h / 2.)))
1054 .bg(capsule_bg)
1055 .overflow_hidden()
1056 .on_key_down(move |e: &KeyDownEvent, window, cx| {
1057 let key = e.keystroke.key.as_str();
1058 let now = motion_now(cx);
1059 let red = is_reduced_motion(cx);
1060 let step = {
1061 let mut s = cell_for_key.borrow_mut();
1062 if !s.interactive() {
1063 return;
1064 }
1065 let travel = s.travel();
1066 match key {
1067 "end" => Some(()),
1068 "right" | "up" => {
1069 let next = (s.x.value + travel / 10.).min(travel);
1070 s.x.set(next);
1071 if next >= travel - 0.01 {
1072 Some(())
1073 } else {
1074 None
1075 }
1076 }
1077 "left" | "down" => {
1078 let v = s.x.value;
1079 s.x.set((v - travel / 10.).max(0.));
1080 None
1081 }
1082 "home" | "escape" => {
1083 s.grip = None;
1084 s.go_home(0., now, red);
1085 None
1086 }
1087 _ => return,
1088 }
1089 };
1090 cx.stop_propagation();
1091 window.prevent_default();
1092 if let Some(()) = step {
1093 commit_and_confirm(&cell_for_key, window, cx);
1094 }
1095 window.refresh();
1096 })
1097 .child(content);
1098
1099 let track = div()
1100 .id(ElementId::NamedChild(id.clone().into(), "track".into()))
1101 .test_support()
1102 .relative()
1103 .w(px(width * pulse_scale))
1104 .h(px(height * pulse_scale))
1105 .ml(px(shake_dx))
1106 .rounded(px(r * pulse_scale))
1107 .bg(track_color)
1108 .overflow_hidden()
1109 .opacity(if config.disabled { 0.55 } else { 1. })
1110 .when(interactive && !dragging, |el| el.cursor_grab())
1111 .when(phase == Phase::Pending || phase == Phase::Done, |el| {
1112 el.cursor_default()
1113 })
1114 .on_hover(move |hovered, window, _cx| {
1115 let mut s = cell_for_hover.borrow_mut();
1117 if s.hot != *hovered {
1118 s.hot = *hovered;
1119 drop(s);
1120 window.refresh();
1121 }
1122 })
1123 .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
1124 let mut s = cell_for_down.borrow_mut();
1125 if !s.interactive() {
1126 return;
1127 }
1128 let v = s.x.value;
1130 s.x.set(v);
1131 s.grip = Some(Grip {
1132 x_start: v,
1133 grab: None,
1134 ax: 0.,
1135 moved: false,
1136 vertical: false,
1137 hist: VecDeque::with_capacity(4),
1138 });
1139 drop(s);
1140 window.refresh();
1141 })
1142 .child(probe)
1143 .child(label_el)
1144 .child(capsule);
1145
1146 div()
1148 .id(id)
1149 .test_support()
1150 .role(Role::Group)
1151 .aria_label(format!(
1152 "{} · {}%",
1153 self.label,
1154 ((seen / travel * 100.).round() as i32).clamp(0, 100)
1155 ))
1156 .relative()
1157 .w(px(width))
1158 .h(px(height))
1159 .flex_none()
1160 .flex()
1161 .items_center()
1162 .justify_center()
1163 .on_scroll(move |e, window, cx| {
1164 if !window.last_input_was_touch() {
1165 return;
1166 }
1167 let delta = e.delta.pixel_delta(px(16.));
1168 let dx = f32::from(delta.x);
1169 let dy = f32::from(delta.y);
1170 let now = motion_now(cx);
1171 let red = is_reduced_motion(cx);
1172 let ended = matches!(
1173 e.touch_phase,
1174 gpui_kit::TouchPhase::Ended | gpui_kit::TouchPhase::Cancelled
1175 );
1176 if ended {
1177 let run = {
1178 let mut s = cell_for_touch.borrow_mut();
1179 let v = s.velocity_of();
1180 s.release(v, now, red)
1181 };
1182 if let Some(run) = run {
1183 confirm_with_host(&cell_for_touch, run, window, cx, now, red);
1184 }
1185 cx.stop_propagation();
1186 window.refresh();
1187 return;
1188 }
1189 #[allow(unused_assignments)]
1190 let mut moved = false;
1191 {
1192 let mut s = cell_for_touch.borrow_mut();
1193 if !s.interactive() {
1194 return;
1195 }
1196 let travel = s.travel();
1197 if e.touch_phase == gpui_kit::TouchPhase::Started {
1198 let x0 = s.x.value;
1199 s.x.set(x0);
1200 s.grip = Some(Grip {
1201 x_start: x0,
1202 grab: None,
1203 ax: 0.,
1204 moved: false,
1205 vertical: false,
1206 hist: VecDeque::with_capacity(4),
1207 });
1208 }
1209 let Some(g) = s.grip.as_mut() else {
1210 return;
1211 };
1212 if g.vertical {
1213 return;
1214 }
1215 if g.grab.is_none() {
1216 if dy.abs() >= 10. && dy.abs() > dx.abs() {
1217 g.vertical = true;
1218 return;
1219 }
1220 if dx.abs() < 10. || dx.abs() < dy.abs() {
1221 return;
1222 }
1223 g.grab = Some(10.);
1224 }
1225 g.ax += dx;
1226 let next = (g.x_start + g.ax - g.grab.unwrap()).clamp(0., travel);
1227 moved = drag_to(&mut s, next, now);
1228 }
1229 if moved {
1230 cx.stop_propagation();
1231 window.refresh();
1232 }
1233 })
1234 .child(track)
1235 }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240 use super::*;
1241 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1242 use gpui_kit::{
1243 Context, Render, TestAppContext, point,
1244 test::{TestEventExt as _, TestWindowExt as _},
1245 };
1246
1247 struct Host {
1248 disabled: bool,
1249 mode: &'static str,
1250 events: Vec<String>,
1251 events_log: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
1252 }
1253
1254 fn host(mode: &'static str) -> Host {
1255 Host {
1256 disabled: false,
1257 mode,
1258 events: vec![],
1259 events_log: std::rc::Rc::new(std::cell::RefCell::new(vec![])),
1260 }
1261 }
1262
1263 impl Render for Host {
1264 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1265 let mode = self.mode;
1266 let log = self.events_log.clone();
1267 div().w(px(360.)).p(px(8.)).child(
1268 SlideCommit::new("sc-test")
1269 .label("Slide to pay")
1270 .done_label("Paid")
1271 .error_label("Payment failed")
1272 .config(SlideCommitConfig {
1273 disabled: self.disabled,
1274 ..Default::default()
1275 })
1276 .on_confirm(move |_, _| match mode {
1277 "async" => SlideCommitConfirm::PendingOk(Duration::from_millis(800)),
1278 "fail" => SlideCommitConfirm::Err("declined".into()),
1279 "async_fail" => SlideCommitConfirm::PendingErr(
1280 Duration::from_millis(500),
1281 "timeout".into(),
1282 ),
1283 _ => SlideCommitConfirm::Ok,
1284 })
1285 .on_done(cx.listener(|this, _: &(), _, cx| {
1286 this.events.push("done".into());
1287 cx.notify();
1288 }))
1289 .on_error(move |reason, _, _| {
1290 log.borrow_mut().push(reason.to_string());
1291 }),
1292 )
1293 }
1294 }
1295
1296 fn drag_to_end(window: &mut Window, cx: &mut App) {
1297 window.render_frame(cx);
1298 let track = window.find(track_id()).bounds();
1299 let cy = track.center().y;
1300 window.pointer_down(
1301 point(px(f32::from(track.left()) + 20.), cy),
1302 MouseButton::Left,
1303 cx,
1304 );
1305 window.render_frame(cx);
1306 window.pointer_move(
1307 point(px(f32::from(track.left()) + 40.), cy),
1308 Some(MouseButton::Left),
1309 cx,
1310 );
1311 window.render_frame(cx);
1312 window.pointer_move(
1313 point(px(f32::from(track.right()) + 60.), cy),
1314 Some(MouseButton::Left),
1315 cx,
1316 );
1317 window.render_frame(cx);
1318 window.pointer_up(
1319 point(px(f32::from(track.right()) + 60.), cy),
1320 MouseButton::Left,
1321 cx,
1322 );
1323 window.render_frame(cx);
1324 }
1325
1326 fn capsule_id() -> ElementId {
1327 ElementId::NamedChild(ElementId::from("sc-test").into(), "capsule".into())
1328 }
1329
1330 fn track_id() -> ElementId {
1331 ElementId::NamedChild(ElementId::from("sc-test").into(), "track".into())
1332 }
1333
1334 fn setup(cx: &mut TestAppContext) {
1335 cx.update(|cx| {
1336 gpui_kit::init(cx);
1337 install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
1338 });
1339 }
1340
1341 #[gpui_kit::test]
1342 fn slide_commit_drag_commit_and_hold(cx: &mut TestAppContext) {
1343 setup(cx);
1344 let (view, cx) = cx.add_window_view(|_, _| host("sync"));
1345 cx.update(|w, cx| {
1346 w.render_frame(cx);
1347 let track = w.find(track_id()).bounds();
1348 let cy = track.center().y;
1349 w.pointer_down(
1350 point(px(f32::from(track.left()) + 20.), cy),
1351 MouseButton::Left,
1352 cx,
1353 );
1354 w.render_frame(cx);
1355 w.pointer_move(
1357 point(px(f32::from(track.left()) + 40.), cy),
1358 Some(MouseButton::Left),
1359 cx,
1360 );
1361 w.render_frame(cx);
1362 w.pointer_move(
1363 point(px(f32::from(track.right()) + 60.), cy),
1364 Some(MouseButton::Left),
1365 cx,
1366 );
1367 w.render_frame(cx);
1368 assert!(f32::from(w.find(capsule_id()).bounds().size.width) > 60.);
1369 w.pointer_up(
1370 point(px(f32::from(track.right()) + 60.), cy),
1371 MouseButton::Left,
1372 cx,
1373 );
1374 w.render_frame(cx);
1375 assert_eq!(view.read(cx).events, vec!["done"]);
1376 });
1377 cx.executor()
1379 .advance_clock(std::time::Duration::from_millis(1700));
1380 cx.update(|w, cx| {
1381 w.render_frame(cx);
1382 assert_eq!(view.read(cx).events, vec!["done"]);
1383 });
1384 cx.executor()
1385 .advance_clock(std::time::Duration::from_millis(400));
1386 cx.update(|w, cx| {
1387 w.render_frame(cx);
1388 w.render_frame(cx);
1389 let grip = (56.0f32 - 8.).max(1.);
1390 assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
1391 });
1392 }
1393
1394 #[gpui_kit::test]
1395 fn slide_commit_release_early_returns_home(cx: &mut TestAppContext) {
1396 setup(cx);
1397 let (view, cx) = cx.add_window_view(|_, _| host("sync"));
1398 cx.update(|w, cx| {
1399 w.render_frame(cx);
1400 let track = w.find(track_id()).bounds();
1401 let cy = track.center().y;
1402 w.pointer_down(
1403 point(px(f32::from(track.left()) + 20.), cy),
1404 MouseButton::Left,
1405 cx,
1406 );
1407 w.render_frame(cx);
1408 w.pointer_move(
1409 point(px(f32::from(track.left()) + 40.), cy),
1410 Some(MouseButton::Left),
1411 cx,
1412 );
1413 w.render_frame(cx);
1414 w.pointer_move(
1415 point(px(f32::from(track.left()) + 100.), cy),
1416 Some(MouseButton::Left),
1417 cx,
1418 );
1419 w.render_frame(cx);
1420 assert!(f32::from(w.find(capsule_id()).bounds().size.width) > 60.);
1421 w.pointer_up(
1422 point(px(f32::from(track.left()) + 100.), cy),
1423 MouseButton::Left,
1424 cx,
1425 );
1426 assert!(view.read(cx).events.is_empty());
1427 });
1428 cx.executor()
1429 .advance_clock(std::time::Duration::from_millis(500));
1430 cx.update(|w, cx| {
1431 w.render_frame(cx);
1432 let grip = (56.0f32 - 8.).max(1.);
1433 assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
1434 });
1435 }
1436
1437 #[gpui_kit::test]
1438 fn slide_commit_keyboard_end_commits(cx: &mut TestAppContext) {
1439 setup(cx);
1440 let (view, cx) = cx.add_window_view(|_, _| host("sync"));
1441 cx.update(|w, cx| {
1442 w.render_frame(cx);
1443 w.focus_next(cx);
1444 w.press("end", cx);
1445 w.render_frame(cx);
1446 assert_eq!(view.read(cx).events, vec!["done"]);
1447 });
1448 }
1449
1450 #[gpui_kit::test]
1451 fn slide_commit_disabled_ignores_input(cx: &mut TestAppContext) {
1452 setup(cx);
1453 let (view, cx) = cx.add_window_view(|_, _| Host {
1454 disabled: true,
1455 ..host("sync")
1456 });
1457 cx.update(|w, cx| {
1458 w.render_frame(cx);
1459 w.focus_next(cx);
1460 w.press("end", cx);
1461 w.render_frame(cx);
1462 assert!(view.read(cx).events.is_empty());
1463 });
1464 }
1465
1466 #[gpui_kit::test]
1467 fn slide_commit_async_pending_then_done(cx: &mut TestAppContext) {
1468 setup(cx);
1469 let (view, cx) = cx.add_window_view(|_, _| host("async"));
1470 cx.update(|w, cx| {
1471 drag_to_end(w, cx);
1472 assert!(view.read(cx).events.is_empty());
1474 });
1475 cx.executor()
1477 .advance_clock(std::time::Duration::from_millis(1000));
1478 cx.update(|w, cx| {
1479 w.render_frame(cx);
1480 w.render_frame(cx);
1481 assert_eq!(view.read(cx).events, vec!["done"]);
1482 });
1483 }
1484
1485 #[gpui_kit::test]
1486 fn slide_commit_async_error_shakes_and_homes(cx: &mut TestAppContext) {
1487 setup(cx);
1488 let (view, cx) = cx.add_window_view(|_, _| host("async_fail"));
1489 cx.update(|w, cx| {
1490 drag_to_end(w, cx);
1491 assert!(view.read(cx).events.is_empty());
1492 });
1493 cx.executor()
1494 .advance_clock(std::time::Duration::from_millis(800));
1495 cx.update(|w, cx| {
1496 w.render_frame(cx);
1497 w.render_frame(cx);
1498 assert!(view.read(cx).events.is_empty());
1499 });
1500 cx.executor()
1502 .advance_clock(std::time::Duration::from_millis(1600));
1503 cx.update(|w, cx| {
1504 w.render_frame(cx);
1505 });
1506 cx.executor()
1507 .advance_clock(std::time::Duration::from_millis(900));
1508 cx.update(|w, cx| {
1509 w.render_frame(cx);
1510 w.render_frame(cx);
1511 let grip = (56.0f32 - 8.).max(1.);
1512 assert!((f32::from(w.find(capsule_id()).bounds().size.width) - grip).abs() < 2.);
1513 });
1514 }
1515}