Skip to main content

arc_ui/feedback/
countdown.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Source: `Arc源码/arc-library/registry/components/countdown/countdown.tsx` & `countdown.module.css`
3//!
4//! A fixed-moment countdown (`countdown`) for launches, live events, and deadlines:
5//! - Splits remaining seconds across the requested units (`Days`, `Hours`, `Minutes`, `Seconds`),
6//!   sorted largest-first so the leading unit absorbs overflow (`countdown_split_units`).
7//! - Shortest-path digit wheels (`countdown_wheel_shortest_target`) with column-specific modular
8//!   bases (`countdown_wheel_bases`: `3` for hours tens, `6` for minutes/seconds tens, `10` for ones
9//!   and largest-unit columns) so `00 -> 59` or `00 -> 23` wraps in a single step.
10//! - Supports `Large` (display typography with unit labels and colons) and `Compact` (`32px` pill
11//!   with inline `d / h / m / s` letters) variants.
12//! - Morphs into `complete_label` with a pulsing green live indicator dot (`2.0s` cycle) and fires
13//!   `on_complete` once when reaching zero.
14
15use std::{cell::RefCell, rc::Rc};
16
17use arc_motion::{arc_spring, is_reduced_motion, motion_now};
18use arc_tokens::{
19    ActiveArcLocale as _, ActiveArcTheme as _, Locale, Radii, Spacing, Typography, oklab_mix,
20};
21use gpui_kit::{
22    AnyElement, App, Bounds, Corners, Edges, ElementId, IntoElement, ParentElement, RenderOnce,
23    Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
24    quad,
25};
26
27type CompleteCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
28
29/// Time unit displayed in [`Countdown`].
30#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
31pub enum CountdownUnit {
32    Days,
33    Hours,
34    Minutes,
35    Seconds,
36}
37
38impl CountdownUnit {
39    pub const DEFAULT_ALL: [CountdownUnit; 4] = [
40        CountdownUnit::Days,
41        CountdownUnit::Hours,
42        CountdownUnit::Minutes,
43        CountdownUnit::Seconds,
44    ];
45
46    #[inline]
47    pub const fn seconds_per_unit(self) -> u64 {
48        match self {
49            Self::Days => 86_400,
50            Self::Hours => 3_600,
51            Self::Minutes => 60,
52            Self::Seconds => 1,
53        }
54    }
55
56    #[inline]
57    pub const fn wrap_limit(self) -> Option<u64> {
58        match self {
59            Self::Days => None,
60            Self::Hours => Some(24),
61            Self::Minutes | Self::Seconds => Some(60),
62        }
63    }
64
65    #[inline]
66    pub const fn label_large(self, locale: Locale) -> &'static str {
67        match self {
68            Self::Days => locale.text("天", "Days"),
69            Self::Hours => locale.text("时", "Hours"),
70            Self::Minutes => locale.text("分", "Minutes"),
71            Self::Seconds => locale.text("秒", "Seconds"),
72        }
73    }
74
75    #[inline]
76    pub const fn label_compact(self) -> &'static str {
77        match self {
78            Self::Days => "d",
79            Self::Hours => "h",
80            Self::Minutes => "m",
81            Self::Seconds => "s",
82        }
83    }
84}
85
86/// Visual size / layout variant of [`Countdown`].
87#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
88pub enum CountdownVariant {
89    #[default]
90    Large,
91    Compact,
92}
93
94/// Splits `total_seconds` across `units` (automatically sorted largest-first and deduplicated).
95///
96/// The largest unit absorbs all remaining whole units without modulo wrapping, so if `Days` is
97/// omitted, `Hours` can exceed `24`.
98pub fn countdown_split_units(
99    total_seconds: u64,
100    units: &[CountdownUnit],
101) -> Vec<(CountdownUnit, u64)> {
102    let mut sorted: Vec<CountdownUnit> = if units.is_empty() {
103        CountdownUnit::DEFAULT_ALL.to_vec()
104    } else {
105        units.to_vec()
106    };
107    sorted.sort_by_key(|u| std::cmp::Reverse(u.seconds_per_unit()));
108    sorted.dedup();
109
110    sorted
111        .into_iter()
112        .enumerate()
113        .map(|(index, unit)| {
114            let divisor = unit.seconds_per_unit();
115            let raw = total_seconds / divisor;
116            let val = if index == 0 {
117                raw
118            } else if let Some(limit) = unit.wrap_limit() {
119                raw % limit
120            } else {
121                raw
122            };
123            (unit, val)
124        })
125        .collect()
126}
127
128/// Returns the modular wheel base for each digit column of `unit`.
129///
130/// Mirrors `basesFor(unit, largest, length)` in `countdown.tsx`:
131/// - For non-largest two-digit groups, the tens column uses base `3` for `Hours` (`0..=2`) and
132///   base `6` for `Minutes`/`Seconds` (`0..=5`), so `00 -> 59` wraps in a single step.
133/// - All other columns use base `10`.
134pub fn countdown_wheel_bases(
135    unit: CountdownUnit,
136    is_largest: bool,
137    digit_count: usize,
138) -> Vec<u32> {
139    (0..digit_count)
140        .map(|index| {
141            let is_tens = digit_count == 2 && index == 0 && !is_largest;
142            if is_tens {
143                match unit {
144                    CountdownUnit::Hours => 3,
145                    _ => 6,
146                }
147            } else {
148                10
149            }
150        })
151        .collect()
152}
153
154/// Computes the next cumulative wheel target position taking the shortest path around a modular
155/// wheel of size `base` from `prev_digit` to `next_digit`.
156#[inline]
157pub fn countdown_wheel_shortest_target(
158    prev_target: f32,
159    prev_digit: u32,
160    next_digit: u32,
161    base: u32,
162) -> f32 {
163    let base = base.max(1);
164    if prev_digit == next_digit {
165        return prev_target;
166    }
167    let up = (next_digit + base - (prev_digit % base)) % base;
168    let down = base - up;
169    let delta = if down <= up {
170        -(down as f32)
171    } else {
172        up as f32
173    };
174    prev_target + delta
175}
176
177/// Computes the signed circular offset (`-base/2 .. +base/2`) of `digit` relative to continuous
178/// wheel position `wheel_pos` on a wheel of size `base`.
179#[inline]
180pub fn countdown_wheel_digit_offset(wheel_pos: f32, digit: u32, base: u32) -> f32 {
181    let b = (base.max(1)) as f32;
182
183    ((digit as f32 - wheel_pos) % b + b * 1.5) % b - b * 0.5
184}
185
186#[derive(Clone)]
187struct CountdownInternalState {
188    anchor_now: f64,
189    last_initial_secs: u64,
190    last_reset_nonce: u64,
191    fired_complete: bool,
192    wheel_targets: Vec<(u32, f32)>,
193}
194
195/// Fixed-moment / duration countdown component (`countdown`).
196#[derive(IntoElement)]
197pub struct Countdown {
198    id: ElementId,
199    /// Remaining seconds from mount (or from the latest `reset_nonce` / `initial_seconds` change)
200    /// when running in self-ticking mode.
201    initial_seconds: u64,
202    /// Optional controlled remaining seconds override.
203    remaining_seconds: Option<u64>,
204    /// Monotonic nonce allowing callers to restart the countdown to `initial_seconds`.
205    reset_nonce: u64,
206    paused: bool,
207    units: Vec<CountdownUnit>,
208    variant: CountdownVariant,
209    complete_label: Option<SharedString>,
210    label: SharedString,
211    on_complete: Option<CompleteCallback>,
212}
213
214impl Countdown {
215    pub fn new(id: impl Into<ElementId>, initial_seconds: u64) -> Self {
216        Self {
217            id: id.into(),
218            initial_seconds,
219            remaining_seconds: None,
220            reset_nonce: 0,
221            paused: false,
222            units: CountdownUnit::DEFAULT_ALL.to_vec(),
223            variant: CountdownVariant::Large,
224            complete_label: None,
225            label: SharedString::from("Time remaining"),
226            on_complete: None,
227        }
228    }
229
230    /// Overrides the countdown with an explicit controlled remaining seconds value.
231    pub fn remaining_seconds(mut self, seconds: u64) -> Self {
232        self.remaining_seconds = Some(seconds);
233        self
234    }
235
236    /// Bumping `nonce` restarts the internal countdown clock back to `initial_seconds`.
237    pub fn reset_nonce(mut self, nonce: u64) -> Self {
238        self.reset_nonce = nonce;
239        self
240    }
241
242    pub fn paused(mut self, paused: bool) -> Self {
243        self.paused = paused;
244        self
245    }
246
247    pub fn units(mut self, units: impl IntoIterator<Item = CountdownUnit>) -> Self {
248        self.units = units.into_iter().collect();
249        self
250    }
251
252    pub fn variant(mut self, variant: CountdownVariant) -> Self {
253        self.variant = variant;
254        self
255    }
256
257    pub fn complete_label(mut self, label: impl Into<SharedString>) -> Self {
258        self.complete_label = Some(label.into());
259        self
260    }
261
262    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
263        self.label = label.into();
264        self
265    }
266
267    pub fn on_complete(mut self, callback: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
268        self.on_complete = Some(Rc::new(callback));
269        self
270    }
271}
272
273impl RenderOnce for Countdown {
274    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
275        let theme = cx.arc_theme();
276        let colors = theme.colors;
277        let motion = theme.motion;
278        let locale = cx.arc_locale();
279        let reduced = is_reduced_motion(cx);
280        let now = motion_now(cx);
281
282        let state_cell = window
283            .use_keyed_state(
284                ElementId::NamedChild(
285                    self.id.clone().into(),
286                    SharedString::from("countdown-state"),
287                ),
288                cx,
289                |_, _| {
290                    Rc::new(RefCell::new(CountdownInternalState {
291                        anchor_now: now,
292                        last_initial_secs: self.initial_seconds,
293                        last_reset_nonce: self.reset_nonce,
294                        fired_complete: false,
295                        wheel_targets: Vec::new(),
296                    }))
297                },
298            )
299            .read(cx)
300            .clone();
301
302        let (seconds_left, should_fire_complete) = {
303            let mut st = state_cell.borrow_mut();
304            if st.last_initial_secs != self.initial_seconds
305                || st.last_reset_nonce != self.reset_nonce
306            {
307                st.anchor_now = now;
308                st.last_initial_secs = self.initial_seconds;
309                st.last_reset_nonce = self.reset_nonce;
310                st.fired_complete = false;
311            }
312
313            let left = if let Some(explicit) = self.remaining_seconds {
314                explicit
315            } else if self.paused {
316                // Keep anchor sliding while paused so remaining time freezes
317                let elapsed = (now - st.anchor_now).max(0.0);
318                let frozen_left = (self.initial_seconds as f64 - elapsed).ceil().max(0.0) as u64;
319                st.anchor_now = now - (self.initial_seconds.saturating_sub(frozen_left)) as f64;
320                frozen_left
321            } else {
322                let elapsed = (now - st.anchor_now).max(0.0);
323                (self.initial_seconds as f64 - elapsed).ceil().max(0.0) as u64
324            };
325
326            let fire = if left == 0 && !st.fired_complete && self.initial_seconds > 0 {
327                st.fired_complete = true;
328                true
329            } else {
330                false
331            };
332            (left, fire)
333        };
334
335        if should_fire_complete && let Some(cb) = self.on_complete.clone() {
336            window.defer(cx, move |window, cx| {
337                cb(&(), window, cx);
338            });
339        }
340
341        let is_complete = seconds_left == 0;
342        let is_compact = self.variant == CountdownVariant::Compact;
343        let mut needs_anim_frame = !self.paused && !is_complete && self.remaining_seconds.is_none();
344
345        let complete_text = self
346            .complete_label
347            .unwrap_or_else(|| SharedString::from(locale.text("已开始 Live now", "Live now")));
348
349        let parts = countdown_split_units(seconds_left, &self.units);
350
351        // Flatten all digit columns across groups to maintain stable wheel targets
352        let mut flat_columns: Vec<(CountdownUnit, usize, usize, u32, u32)> = Vec::new();
353        for (group_idx, (unit, value)) in parts.iter().enumerate() {
354            let text = format!("{value:02}");
355            let bases = countdown_wheel_bases(*unit, group_idx == 0, text.len());
356            for (col_idx, ch) in text.chars().enumerate() {
357                let digit = ch.to_digit(10).unwrap_or(0);
358                let base = bases.get(col_idx).copied().unwrap_or(10);
359                flat_columns.push((*unit, group_idx, col_idx, digit, base));
360            }
361        }
362
363        // Update shortest-path cumulative wheel targets
364        let column_targets: Vec<f32> = {
365            let mut st = state_cell.borrow_mut();
366            if st.wheel_targets.len() != flat_columns.len() {
367                st.wheel_targets = flat_columns
368                    .iter()
369                    .map(|(_, _, _, digit, _)| (*digit, *digit as f32))
370                    .collect();
371            }
372            let mut out = Vec::with_capacity(flat_columns.len());
373            for (i, (_, _, _, digit, base)) in flat_columns.iter().enumerate() {
374                let (prev_digit, prev_target) = st.wheel_targets[i];
375                let next_target =
376                    countdown_wheel_shortest_target(prev_target, prev_digit, *digit, *base);
377                st.wheel_targets[i] = (*digit, next_target);
378                out.push(next_target);
379            }
380            out
381        };
382
383        let body_el: AnyElement = if is_complete {
384            // Complete badge with pulsing green live dot
385            let pulse_phase = if reduced {
386                0.0
387            } else {
388                needs_anim_frame = true;
389                ((now * 0.5).fract()) as f32
390            };
391            let dot_size = if is_compact { 8.0 } else { 11.0 };
392            let success_color = colors.success;
393
394            let live_dot = div()
395                .relative()
396                .size(px(dot_size * 2.4))
397                .flex_none()
398                .flex()
399                .items_center()
400                .justify_center()
401                .child(
402                    canvas(
403                        move |bounds, _window, _cx| bounds,
404                        move |bounds: Bounds<gpui_kit::Pixels>, _, window, _cx| {
405                            let cx_pt = bounds.origin.x + bounds.size.width * 0.5;
406                            let cy_pt = bounds.origin.y + bounds.size.height * 0.5;
407
408                            // Expanding ripple ring (`0..0.7` of the 2s cycle)
409                            if !reduced && pulse_phase < 0.75 {
410                                let t = (pulse_phase / 0.75).clamp(0.0, 1.0);
411                                let ring_scale = 1.0 + 1.6 * t;
412                                let ring_alpha = 0.48 * (1.0 - t);
413                                let ring_d = dot_size * ring_scale;
414                                let mut c = success_color;
415                                c.a *= ring_alpha;
416                                window.paint_quad(quad(
417                                    Bounds::new(
418                                        point(cx_pt - px(ring_d * 0.5), cy_pt - px(ring_d * 0.5)),
419                                        gpui_kit::size(px(ring_d), px(ring_d)),
420                                    ),
421                                    Corners::all(px(ring_d)),
422                                    c,
423                                    Edges::all(px(0.0)),
424                                    gpui_kit::transparent_black(),
425                                    gpui_kit::BorderStyle::default(),
426                                ));
427                            }
428
429                            // Solid center dot
430                            window.paint_quad(quad(
431                                Bounds::new(
432                                    point(cx_pt - px(dot_size * 0.5), cy_pt - px(dot_size * 0.5)),
433                                    gpui_kit::size(px(dot_size), px(dot_size)),
434                                ),
435                                Corners::all(px(dot_size)),
436                                success_color,
437                                Edges::all(px(0.0)),
438                                gpui_kit::transparent_black(),
439                                gpui_kit::BorderStyle::default(),
440                            ));
441                        },
442                    )
443                    .size_full(),
444                );
445
446            div()
447                .flex()
448                .flex_row()
449                .items_center()
450                .gap(if is_compact { px(4.0) } else { px(8.0) })
451                .child(live_dot)
452                .child(
453                    div()
454                        .text_size(if is_compact {
455                            Typography::TEXT_SM
456                        } else {
457                            px(28.0)
458                        })
459                        .font_medium()
460                        .text_color(if is_compact {
461                            colors.success
462                        } else {
463                            colors.foreground
464                        })
465                        .child(complete_text),
466                )
467                .into_any_element()
468        } else {
469            // Render unit groups and rolling digit wheels
470            let digit_h = if is_compact { 20.0 } else { 44.0 };
471            let digit_w = if is_compact { 9.5 } else { 24.0 };
472            let digit_font = if is_compact {
473                Typography::TEXT_SM
474            } else {
475                px(36.0)
476            };
477
478            let mut flat_cursor = 0usize;
479            let mut group_els: Vec<AnyElement> = Vec::with_capacity(parts.len());
480
481            for (group_idx, (unit, value)) in parts.iter().enumerate() {
482                let text = format!("{value:02}");
483                let col_count = text.chars().count();
484                let mut wheel_els: Vec<AnyElement> = Vec::with_capacity(col_count);
485
486                for col_idx in 0..col_count {
487                    let (_, _, _, digit, base) = flat_columns[flat_cursor];
488                    let target_pos = column_targets[flat_cursor];
489                    flat_cursor += 1;
490
491                    let wheel_pos = if reduced {
492                        target_pos
493                    } else {
494                        let s = arc_spring(
495                            ElementId::NamedChild(
496                                self.id.clone().into(),
497                                SharedString::from(format!("wheel-{group_idx}-{col_idx}")),
498                            ),
499                            target_pos,
500                            motion.spring.snappy,
501                            window,
502                            cx,
503                        );
504                        if (s - target_pos).abs() > 0.002 {
505                            needs_anim_frame = true;
506                        }
507                        s
508                    };
509
510                    // Render visible digits on the modular wheel (`|offset| < 1.0`)
511                    let mut wheel_box = div()
512                        .relative()
513                        .w(px(digit_w))
514                        .h(px(digit_h))
515                        .overflow_hidden();
516
517                    for candidate in 0..base {
518                        let offset = countdown_wheel_digit_offset(wheel_pos, candidate, base);
519                        if offset.abs() < 0.98 {
520                            let opacity = (1.0 - offset.abs()).clamp(0.0, 1.0);
521                            let y_px = offset * digit_h;
522                            let mut fg = colors.foreground;
523                            fg.a *= opacity;
524
525                            wheel_box = wheel_box.child(
526                                div()
527                                    .absolute()
528                                    .left_0()
529                                    .top(px(y_px))
530                                    .w(px(digit_w))
531                                    .h(px(digit_h))
532                                    .flex()
533                                    .items_center()
534                                    .justify_center()
535                                    .text_size(digit_font)
536                                    .font_medium()
537                                    .text_color(fg)
538                                    .child(SharedString::from(format!("{candidate}"))),
539                            );
540                        } else if reduced && candidate == digit {
541                            wheel_box = wheel_box.child(
542                                div()
543                                    .size_full()
544                                    .flex()
545                                    .items_center()
546                                    .justify_center()
547                                    .text_size(digit_font)
548                                    .font_medium()
549                                    .text_color(colors.foreground)
550                                    .child(SharedString::from(format!("{candidate}"))),
551                            );
552                        }
553                    }
554
555                    wheel_els.push(wheel_box.into_any_element());
556                }
557
558                let group_node = if is_compact {
559                    div()
560                        .flex()
561                        .flex_row()
562                        .items_baseline()
563                        .gap(px(1.0))
564                        .child(div().flex().flex_row().items_center().children(wheel_els))
565                        .child(
566                            div()
567                                .text_size(Typography::TEXT_SM)
568                                .text_color(colors.text_muted)
569                                .child(unit.label_compact()),
570                        )
571                        .into_any_element()
572                } else {
573                    div()
574                        .flex()
575                        .flex_row()
576                        .items_start()
577                        .when(group_idx > 0, |this| {
578                            let mut colon_c = colors.text_muted;
579                            colon_c.a *= 0.6;
580                            this.child(
581                                div()
582                                    .h(px(digit_h))
583                                    .px(px(6.0))
584                                    .flex()
585                                    .items_center()
586                                    .justify_center()
587                                    .text_size(px(32.0))
588                                    .font_medium()
589                                    .text_color(colon_c)
590                                    .child(":"),
591                            )
592                        })
593                        .child(
594                            div()
595                                .min_w(px(58.0))
596                                .flex()
597                                .flex_col()
598                                .items_center()
599                                .gap(px(6.0))
600                                .child(div().flex().flex_row().items_center().children(wheel_els))
601                                .child(
602                                    div()
603                                        .text_size(Typography::TEXT_XS)
604                                        .text_color(colors.text_muted)
605                                        .child(unit.label_large(locale)),
606                                ),
607                        )
608                        .into_any_element()
609                };
610
611                group_els.push(group_node);
612            }
613
614            div()
615                .flex()
616                .flex_row()
617                .items_center()
618                .gap(if is_compact { px(6.0) } else { px(0.0) })
619                .children(group_els)
620                .into_any_element()
621        };
622
623        if needs_anim_frame {
624            window.request_animation_frame();
625        }
626
627        if is_compact {
628            let (border_c, bg_c) = if is_complete {
629                (
630                    oklab_mix(colors.success, colors.border, 0.35),
631                    oklab_mix(colors.success, colors.surface, 0.09),
632                )
633            } else {
634                (colors.border, colors.surface)
635            };
636
637            div()
638                .id(self.id)
639                .role(Role::Group)
640                .min_h(px(32.0))
641                .px(Spacing::S3)
642                .rounded(Radii::PILL)
643                .border_1()
644                .border_color(border_c)
645                .bg(bg_c)
646                .flex()
647                .flex_row()
648                .items_center()
649                .justify_center()
650                .child(body_el)
651        } else {
652            div()
653                .id(self.id)
654                .role(Role::Group)
655                .w_full()
656                .flex()
657                .flex_row()
658                .items_center()
659                .justify_center()
660                .child(body_el)
661        }
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn countdown_split_units_lets_largest_unit_absorb_overflow() {
671        // 1 day (86400) + 5 hours (18000) + 12 minutes (720) + 9 seconds = 105_129s
672        let all = countdown_split_units(105_129, &CountdownUnit::DEFAULT_ALL);
673        assert_eq!(
674            all,
675            vec![
676                (CountdownUnit::Days, 1),
677                (CountdownUnit::Hours, 5),
678                (CountdownUnit::Minutes, 12),
679                (CountdownUnit::Seconds, 9),
680            ]
681        );
682
683        // Without Days, Hours absorbs the full 29 hours
684        let hms = countdown_split_units(
685            105_129,
686            &[
687                CountdownUnit::Hours,
688                CountdownUnit::Minutes,
689                CountdownUnit::Seconds,
690            ],
691        );
692        assert_eq!(
693            hms,
694            vec![
695                (CountdownUnit::Hours, 29),
696                (CountdownUnit::Minutes, 12),
697                (CountdownUnit::Seconds, 9),
698            ]
699        );
700    }
701
702    #[test]
703    fn countdown_wheel_bases_and_shortest_path_wrap_00_to_59_in_one_step() {
704        // Minutes (not largest): tens column has base 6, ones column has base 10
705        assert_eq!(
706            countdown_wheel_bases(CountdownUnit::Minutes, false, 2),
707            vec![6, 10]
708        );
709        // Hours (not largest): tens column has base 3, ones column has base 10
710        assert_eq!(
711            countdown_wheel_bases(CountdownUnit::Hours, false, 2),
712            vec![3, 10]
713        );
714        // Largest unit: all columns use base 10
715        assert_eq!(
716            countdown_wheel_bases(CountdownUnit::Hours, true, 2),
717            vec![10, 10]
718        );
719
720        // Wrapping 0 -> 5 on a base-6 tens wheel moves by -1 step (downward), not +5
721        let t1 = countdown_wheel_shortest_target(0.0, 0, 5, 6);
722        assert!((t1 - (-1.0)).abs() < 1e-6);
723
724        // Wrapping 0 -> 9 on a base-10 ones wheel moves by -1 step
725        let t2 = countdown_wheel_shortest_target(0.0, 0, 9, 10);
726        assert!((t2 - (-1.0)).abs() < 1e-6);
727    }
728}