use std::{cell::RefCell, rc::Rc};
use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{
ActiveArcLocale as _, ActiveArcTheme as _, Locale, Radii, Spacing, Typography, oklab_mix,
};
use gpui_kit::{
AnyElement, App, Bounds, Corners, Edges, ElementId, IntoElement, ParentElement, RenderOnce,
Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
quad,
};
type CompleteCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum CountdownUnit {
Days,
Hours,
Minutes,
Seconds,
}
impl CountdownUnit {
pub const DEFAULT_ALL: [CountdownUnit; 4] = [
CountdownUnit::Days,
CountdownUnit::Hours,
CountdownUnit::Minutes,
CountdownUnit::Seconds,
];
#[inline]
pub const fn seconds_per_unit(self) -> u64 {
match self {
Self::Days => 86_400,
Self::Hours => 3_600,
Self::Minutes => 60,
Self::Seconds => 1,
}
}
#[inline]
pub const fn wrap_limit(self) -> Option<u64> {
match self {
Self::Days => None,
Self::Hours => Some(24),
Self::Minutes | Self::Seconds => Some(60),
}
}
#[inline]
pub const fn label_large(self, locale: Locale) -> &'static str {
match self {
Self::Days => locale.text("天", "Days"),
Self::Hours => locale.text("时", "Hours"),
Self::Minutes => locale.text("分", "Minutes"),
Self::Seconds => locale.text("秒", "Seconds"),
}
}
#[inline]
pub const fn label_compact(self) -> &'static str {
match self {
Self::Days => "d",
Self::Hours => "h",
Self::Minutes => "m",
Self::Seconds => "s",
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum CountdownVariant {
#[default]
Large,
Compact,
}
pub fn countdown_split_units(
total_seconds: u64,
units: &[CountdownUnit],
) -> Vec<(CountdownUnit, u64)> {
let mut sorted: Vec<CountdownUnit> = if units.is_empty() {
CountdownUnit::DEFAULT_ALL.to_vec()
} else {
units.to_vec()
};
sorted.sort_by_key(|u| std::cmp::Reverse(u.seconds_per_unit()));
sorted.dedup();
sorted
.into_iter()
.enumerate()
.map(|(index, unit)| {
let divisor = unit.seconds_per_unit();
let raw = total_seconds / divisor;
let val = if index == 0 {
raw
} else if let Some(limit) = unit.wrap_limit() {
raw % limit
} else {
raw
};
(unit, val)
})
.collect()
}
pub fn countdown_wheel_bases(
unit: CountdownUnit,
is_largest: bool,
digit_count: usize,
) -> Vec<u32> {
(0..digit_count)
.map(|index| {
let is_tens = digit_count == 2 && index == 0 && !is_largest;
if is_tens {
match unit {
CountdownUnit::Hours => 3,
_ => 6,
}
} else {
10
}
})
.collect()
}
#[inline]
pub fn countdown_wheel_shortest_target(
prev_target: f32,
prev_digit: u32,
next_digit: u32,
base: u32,
) -> f32 {
let base = base.max(1);
if prev_digit == next_digit {
return prev_target;
}
let up = (next_digit + base - (prev_digit % base)) % base;
let down = base - up;
let delta = if down <= up {
-(down as f32)
} else {
up as f32
};
prev_target + delta
}
#[inline]
pub fn countdown_wheel_digit_offset(wheel_pos: f32, digit: u32, base: u32) -> f32 {
let b = (base.max(1)) as f32;
((digit as f32 - wheel_pos) % b + b * 1.5) % b - b * 0.5
}
#[derive(Clone)]
struct CountdownInternalState {
anchor_now: f64,
last_initial_secs: u64,
last_reset_nonce: u64,
fired_complete: bool,
wheel_targets: Vec<(u32, f32)>,
}
#[derive(IntoElement)]
pub struct Countdown {
id: ElementId,
initial_seconds: u64,
remaining_seconds: Option<u64>,
reset_nonce: u64,
paused: bool,
units: Vec<CountdownUnit>,
variant: CountdownVariant,
complete_label: Option<SharedString>,
label: SharedString,
on_complete: Option<CompleteCallback>,
}
impl Countdown {
pub fn new(id: impl Into<ElementId>, initial_seconds: u64) -> Self {
Self {
id: id.into(),
initial_seconds,
remaining_seconds: None,
reset_nonce: 0,
paused: false,
units: CountdownUnit::DEFAULT_ALL.to_vec(),
variant: CountdownVariant::Large,
complete_label: None,
label: SharedString::from("Time remaining"),
on_complete: None,
}
}
pub fn remaining_seconds(mut self, seconds: u64) -> Self {
self.remaining_seconds = Some(seconds);
self
}
pub fn reset_nonce(mut self, nonce: u64) -> Self {
self.reset_nonce = nonce;
self
}
pub fn paused(mut self, paused: bool) -> Self {
self.paused = paused;
self
}
pub fn units(mut self, units: impl IntoIterator<Item = CountdownUnit>) -> Self {
self.units = units.into_iter().collect();
self
}
pub fn variant(mut self, variant: CountdownVariant) -> Self {
self.variant = variant;
self
}
pub fn complete_label(mut self, label: impl Into<SharedString>) -> Self {
self.complete_label = Some(label.into());
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn on_complete(mut self, callback: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_complete = Some(Rc::new(callback));
self
}
}
impl RenderOnce for Countdown {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme();
let colors = theme.colors;
let motion = theme.motion;
let locale = cx.arc_locale();
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("countdown-state"),
),
cx,
|_, _| {
Rc::new(RefCell::new(CountdownInternalState {
anchor_now: now,
last_initial_secs: self.initial_seconds,
last_reset_nonce: self.reset_nonce,
fired_complete: false,
wheel_targets: Vec::new(),
}))
},
)
.read(cx)
.clone();
let (seconds_left, should_fire_complete) = {
let mut st = state_cell.borrow_mut();
if st.last_initial_secs != self.initial_seconds
|| st.last_reset_nonce != self.reset_nonce
{
st.anchor_now = now;
st.last_initial_secs = self.initial_seconds;
st.last_reset_nonce = self.reset_nonce;
st.fired_complete = false;
}
let left = if let Some(explicit) = self.remaining_seconds {
explicit
} else if self.paused {
let elapsed = (now - st.anchor_now).max(0.0);
let frozen_left = (self.initial_seconds as f64 - elapsed).ceil().max(0.0) as u64;
st.anchor_now = now - (self.initial_seconds.saturating_sub(frozen_left)) as f64;
frozen_left
} else {
let elapsed = (now - st.anchor_now).max(0.0);
(self.initial_seconds as f64 - elapsed).ceil().max(0.0) as u64
};
let fire = if left == 0 && !st.fired_complete && self.initial_seconds > 0 {
st.fired_complete = true;
true
} else {
false
};
(left, fire)
};
if should_fire_complete && let Some(cb) = self.on_complete.clone() {
window.defer(cx, move |window, cx| {
cb(&(), window, cx);
});
}
let is_complete = seconds_left == 0;
let is_compact = self.variant == CountdownVariant::Compact;
let mut needs_anim_frame = !self.paused && !is_complete && self.remaining_seconds.is_none();
let complete_text = self
.complete_label
.unwrap_or_else(|| SharedString::from(locale.text("已开始 Live now", "Live now")));
let parts = countdown_split_units(seconds_left, &self.units);
let mut flat_columns: Vec<(CountdownUnit, usize, usize, u32, u32)> = Vec::new();
for (group_idx, (unit, value)) in parts.iter().enumerate() {
let text = format!("{value:02}");
let bases = countdown_wheel_bases(*unit, group_idx == 0, text.len());
for (col_idx, ch) in text.chars().enumerate() {
let digit = ch.to_digit(10).unwrap_or(0);
let base = bases.get(col_idx).copied().unwrap_or(10);
flat_columns.push((*unit, group_idx, col_idx, digit, base));
}
}
let column_targets: Vec<f32> = {
let mut st = state_cell.borrow_mut();
if st.wheel_targets.len() != flat_columns.len() {
st.wheel_targets = flat_columns
.iter()
.map(|(_, _, _, digit, _)| (*digit, *digit as f32))
.collect();
}
let mut out = Vec::with_capacity(flat_columns.len());
for (i, (_, _, _, digit, base)) in flat_columns.iter().enumerate() {
let (prev_digit, prev_target) = st.wheel_targets[i];
let next_target =
countdown_wheel_shortest_target(prev_target, prev_digit, *digit, *base);
st.wheel_targets[i] = (*digit, next_target);
out.push(next_target);
}
out
};
let body_el: AnyElement = if is_complete {
let pulse_phase = if reduced {
0.0
} else {
needs_anim_frame = true;
((now * 0.5).fract()) as f32
};
let dot_size = if is_compact { 8.0 } else { 11.0 };
let success_color = colors.success;
let live_dot = div()
.relative()
.size(px(dot_size * 2.4))
.flex_none()
.flex()
.items_center()
.justify_center()
.child(
canvas(
move |bounds, _window, _cx| bounds,
move |bounds: Bounds<gpui_kit::Pixels>, _, window, _cx| {
let cx_pt = bounds.origin.x + bounds.size.width * 0.5;
let cy_pt = bounds.origin.y + bounds.size.height * 0.5;
if !reduced && pulse_phase < 0.75 {
let t = (pulse_phase / 0.75).clamp(0.0, 1.0);
let ring_scale = 1.0 + 1.6 * t;
let ring_alpha = 0.48 * (1.0 - t);
let ring_d = dot_size * ring_scale;
let mut c = success_color;
c.a *= ring_alpha;
window.paint_quad(quad(
Bounds::new(
point(cx_pt - px(ring_d * 0.5), cy_pt - px(ring_d * 0.5)),
gpui_kit::size(px(ring_d), px(ring_d)),
),
Corners::all(px(ring_d)),
c,
Edges::all(px(0.0)),
gpui_kit::transparent_black(),
gpui_kit::BorderStyle::default(),
));
}
window.paint_quad(quad(
Bounds::new(
point(cx_pt - px(dot_size * 0.5), cy_pt - px(dot_size * 0.5)),
gpui_kit::size(px(dot_size), px(dot_size)),
),
Corners::all(px(dot_size)),
success_color,
Edges::all(px(0.0)),
gpui_kit::transparent_black(),
gpui_kit::BorderStyle::default(),
));
},
)
.size_full(),
);
div()
.flex()
.flex_row()
.items_center()
.gap(if is_compact { px(4.0) } else { px(8.0) })
.child(live_dot)
.child(
div()
.text_size(if is_compact {
Typography::TEXT_SM
} else {
px(28.0)
})
.font_medium()
.text_color(if is_compact {
colors.success
} else {
colors.foreground
})
.child(complete_text),
)
.into_any_element()
} else {
let digit_h = if is_compact { 20.0 } else { 44.0 };
let digit_w = if is_compact { 9.5 } else { 24.0 };
let digit_font = if is_compact {
Typography::TEXT_SM
} else {
px(36.0)
};
let mut flat_cursor = 0usize;
let mut group_els: Vec<AnyElement> = Vec::with_capacity(parts.len());
for (group_idx, (unit, value)) in parts.iter().enumerate() {
let text = format!("{value:02}");
let col_count = text.chars().count();
let mut wheel_els: Vec<AnyElement> = Vec::with_capacity(col_count);
for col_idx in 0..col_count {
let (_, _, _, digit, base) = flat_columns[flat_cursor];
let target_pos = column_targets[flat_cursor];
flat_cursor += 1;
let wheel_pos = if reduced {
target_pos
} else {
let s = arc_spring(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("wheel-{group_idx}-{col_idx}")),
),
target_pos,
motion.spring.snappy,
window,
cx,
);
if (s - target_pos).abs() > 0.002 {
needs_anim_frame = true;
}
s
};
let mut wheel_box = div()
.relative()
.w(px(digit_w))
.h(px(digit_h))
.overflow_hidden();
for candidate in 0..base {
let offset = countdown_wheel_digit_offset(wheel_pos, candidate, base);
if offset.abs() < 0.98 {
let opacity = (1.0 - offset.abs()).clamp(0.0, 1.0);
let y_px = offset * digit_h;
let mut fg = colors.foreground;
fg.a *= opacity;
wheel_box = wheel_box.child(
div()
.absolute()
.left_0()
.top(px(y_px))
.w(px(digit_w))
.h(px(digit_h))
.flex()
.items_center()
.justify_center()
.text_size(digit_font)
.font_medium()
.text_color(fg)
.child(SharedString::from(format!("{candidate}"))),
);
} else if reduced && candidate == digit {
wheel_box = wheel_box.child(
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_size(digit_font)
.font_medium()
.text_color(colors.foreground)
.child(SharedString::from(format!("{candidate}"))),
);
}
}
wheel_els.push(wheel_box.into_any_element());
}
let group_node = if is_compact {
div()
.flex()
.flex_row()
.items_baseline()
.gap(px(1.0))
.child(div().flex().flex_row().items_center().children(wheel_els))
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(unit.label_compact()),
)
.into_any_element()
} else {
div()
.flex()
.flex_row()
.items_start()
.when(group_idx > 0, |this| {
let mut colon_c = colors.text_muted;
colon_c.a *= 0.6;
this.child(
div()
.h(px(digit_h))
.px(px(6.0))
.flex()
.items_center()
.justify_center()
.text_size(px(32.0))
.font_medium()
.text_color(colon_c)
.child(":"),
)
})
.child(
div()
.min_w(px(58.0))
.flex()
.flex_col()
.items_center()
.gap(px(6.0))
.child(div().flex().flex_row().items_center().children(wheel_els))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(unit.label_large(locale)),
),
)
.into_any_element()
};
group_els.push(group_node);
}
div()
.flex()
.flex_row()
.items_center()
.gap(if is_compact { px(6.0) } else { px(0.0) })
.children(group_els)
.into_any_element()
};
if needs_anim_frame {
window.request_animation_frame();
}
if is_compact {
let (border_c, bg_c) = if is_complete {
(
oklab_mix(colors.success, colors.border, 0.35),
oklab_mix(colors.success, colors.surface, 0.09),
)
} else {
(colors.border, colors.surface)
};
div()
.id(self.id)
.role(Role::Group)
.min_h(px(32.0))
.px(Spacing::S3)
.rounded(Radii::PILL)
.border_1()
.border_color(border_c)
.bg(bg_c)
.flex()
.flex_row()
.items_center()
.justify_center()
.child(body_el)
} else {
div()
.id(self.id)
.role(Role::Group)
.w_full()
.flex()
.flex_row()
.items_center()
.justify_center()
.child(body_el)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn countdown_split_units_lets_largest_unit_absorb_overflow() {
let all = countdown_split_units(105_129, &CountdownUnit::DEFAULT_ALL);
assert_eq!(
all,
vec![
(CountdownUnit::Days, 1),
(CountdownUnit::Hours, 5),
(CountdownUnit::Minutes, 12),
(CountdownUnit::Seconds, 9),
]
);
let hms = countdown_split_units(
105_129,
&[
CountdownUnit::Hours,
CountdownUnit::Minutes,
CountdownUnit::Seconds,
],
);
assert_eq!(
hms,
vec![
(CountdownUnit::Hours, 29),
(CountdownUnit::Minutes, 12),
(CountdownUnit::Seconds, 9),
]
);
}
#[test]
fn countdown_wheel_bases_and_shortest_path_wrap_00_to_59_in_one_step() {
assert_eq!(
countdown_wheel_bases(CountdownUnit::Minutes, false, 2),
vec![6, 10]
);
assert_eq!(
countdown_wheel_bases(CountdownUnit::Hours, false, 2),
vec![3, 10]
);
assert_eq!(
countdown_wheel_bases(CountdownUnit::Hours, true, 2),
vec![10, 10]
);
let t1 = countdown_wheel_shortest_target(0.0, 0, 5, 6);
assert!((t1 - (-1.0)).abs() < 1e-6);
let t2 = countdown_wheel_shortest_target(0.0, 0, 9, 10);
assert!((t2 - (-1.0)).abs() < 1e-6);
}
}