Skip to main content

fc_ui/capabilities/data/
countdown.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::rc::Rc;
4use std::time::{Duration, SystemTime};
5
6type CompletionHandler = Rc<dyn Fn(&mut Window, &mut App) + 'static>;
7
8#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
9pub enum CountdownSize {
10    Sm,
11    #[default]
12    Md,
13    Lg,
14}
15
16impl CountdownSize {
17    fn digit_size(&self) -> Pixels {
18        match self {
19            CountdownSize::Sm => px(20.0),
20            CountdownSize::Md => px(32.0),
21            CountdownSize::Lg => px(48.0),
22        }
23    }
24
25    fn label_size(&self) -> Pixels {
26        match self {
27            CountdownSize::Sm => px(10.0),
28            CountdownSize::Md => px(12.0),
29            CountdownSize::Lg => px(14.0),
30        }
31    }
32
33    fn separator_size(&self) -> Pixels {
34        match self {
35            CountdownSize::Sm => px(16.0),
36            CountdownSize::Md => px(24.0),
37            CountdownSize::Lg => px(36.0),
38        }
39    }
40
41    fn unit_padding(&self) -> Pixels {
42        match self {
43            CountdownSize::Sm => px(8.0),
44            CountdownSize::Md => px(12.0),
45            CountdownSize::Lg => px(16.0),
46        }
47    }
48}
49
50#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
51pub enum CountdownSeparator {
52    #[default]
53    Colon,
54    Space,
55    Dash,
56    Dot,
57    None,
58}
59
60impl CountdownSeparator {
61    fn as_str(&self) -> &'static str {
62        match self {
63            CountdownSeparator::Colon => ":",
64            CountdownSeparator::Space => " ",
65            CountdownSeparator::Dash => "-",
66            CountdownSeparator::Dot => ".",
67            CountdownSeparator::None => "",
68        }
69    }
70}
71
72#[derive(Clone, Debug)]
73pub struct CountdownFormat {
74    pub show_days: bool,
75    pub show_hours: bool,
76    pub show_minutes: bool,
77    pub show_seconds: bool,
78    pub show_labels: bool,
79    pub pad_zeros: bool,
80}
81
82impl Default for CountdownFormat {
83    fn default() -> Self {
84        Self {
85            show_days: true,
86            show_hours: true,
87            show_minutes: true,
88            show_seconds: true,
89            show_labels: true,
90            pad_zeros: true,
91        }
92    }
93}
94
95impl CountdownFormat {
96    pub fn no_days() -> Self {
97        Self {
98            show_days: false,
99            ..Default::default()
100        }
101    }
102
103    pub fn time_only() -> Self {
104        Self {
105            show_days: false,
106            show_hours: true,
107            show_minutes: true,
108            show_seconds: true,
109            show_labels: false,
110            pad_zeros: true,
111        }
112    }
113
114    pub fn minimal() -> Self {
115        Self {
116            show_days: false,
117            show_hours: false,
118            show_minutes: true,
119            show_seconds: true,
120            show_labels: false,
121            pad_zeros: true,
122        }
123    }
124}
125
126#[derive(Clone, Debug)]
127pub struct TimeUnits {
128    pub days: u64,
129    pub hours: u64,
130    pub minutes: u64,
131    pub seconds: u64,
132    pub total_seconds: i64,
133}
134
135impl TimeUnits {
136    fn from_duration(duration: Duration) -> Self {
137        let total_secs = duration.as_secs();
138        let days = total_secs / 86400;
139        let hours = (total_secs % 86400) / 3600;
140        let minutes = (total_secs % 3600) / 60;
141        let seconds = total_secs % 60;
142
143        Self {
144            days,
145            hours,
146            minutes,
147            seconds,
148            total_seconds: total_secs as i64,
149        }
150    }
151
152    fn zero() -> Self {
153        Self {
154            days: 0,
155            hours: 0,
156            minutes: 0,
157            seconds: 0,
158            total_seconds: 0,
159        }
160    }
161}
162
163pub struct CountdownState {
164    target_time: Option<SystemTime>,
165    start_time: Option<SystemTime>,
166    count_up: bool,
167    running: bool,
168    completed: bool,
169    completion_handlers: Vec<(AnyWindowHandle, CompletionHandler)>,
170}
171
172impl CountdownState {
173    pub fn new(_cx: &mut Context<Self>) -> Self {
174        Self {
175            target_time: None,
176            start_time: None,
177            count_up: false,
178            running: false,
179            completed: false,
180            completion_handlers: Vec::new(),
181        }
182    }
183
184    pub fn set_target(&mut self, target: SystemTime, cx: &mut Context<Self>) {
185        self.target_time = Some(target);
186        self.count_up = false;
187        self.running = true;
188        self.completed = false;
189        self.schedule_tick(cx);
190        cx.notify();
191    }
192
193    pub fn set_duration(&mut self, duration: Duration, cx: &mut Context<Self>) {
194        let target = SystemTime::now() + duration;
195        self.set_target(target, cx);
196    }
197
198    pub fn set_count_up(&mut self, start: SystemTime, cx: &mut Context<Self>) {
199        self.start_time = Some(start);
200        self.target_time = None;
201        self.count_up = true;
202        self.running = true;
203        self.completed = false;
204        self.schedule_tick(cx);
205        cx.notify();
206    }
207
208    pub fn start_count_up(&mut self, cx: &mut Context<Self>) {
209        self.set_count_up(SystemTime::now(), cx);
210    }
211
212    fn register_completion_handler(
213        &mut self,
214        window: AnyWindowHandle,
215        handler: Option<CompletionHandler>,
216    ) {
217        self.completion_handlers
218            .retain(|(registered_window, _)| *registered_window != window);
219        if let Some(handler) = handler {
220            self.completion_handlers.push((window, handler));
221        }
222    }
223
224    pub fn stop(&mut self, cx: &mut Context<Self>) {
225        self.running = false;
226        cx.notify();
227    }
228
229    pub fn resume(&mut self, cx: &mut Context<Self>) {
230        if self.target_time.is_some() || self.start_time.is_some() {
231            self.running = true;
232            self.schedule_tick(cx);
233            cx.notify();
234        }
235    }
236
237    pub fn reset(&mut self, cx: &mut Context<Self>) {
238        self.target_time = None;
239        self.start_time = None;
240        self.running = false;
241        self.completed = false;
242        cx.notify();
243    }
244
245    pub fn is_running(&self) -> bool {
246        self.running
247    }
248
249    pub fn is_completed(&self) -> bool {
250        self.completed
251    }
252
253    pub fn time_units(&self) -> TimeUnits {
254        let now = SystemTime::now();
255
256        if self.count_up {
257            if let Some(start) = self.start_time {
258                if let Ok(elapsed) = now.duration_since(start) {
259                    return TimeUnits::from_duration(elapsed);
260                }
261            }
262        } else if let Some(target) = self.target_time {
263            if let Ok(remaining) = target.duration_since(now) {
264                return TimeUnits::from_duration(remaining);
265            }
266        }
267
268        TimeUnits::zero()
269    }
270
271    fn schedule_tick(&self, cx: &mut Context<Self>) {
272        if !self.running {
273            return;
274        }
275
276        cx.spawn(async |this, cx| {
277            cx.background_executor().timer(Duration::from_secs(1)).await;
278
279            let completion = this.update(cx, |state, cx| {
280                let mut completion = None;
281                if state.running {
282                    if !state.count_up {
283                        if let Some(target) = state.target_time {
284                            if SystemTime::now() >= target {
285                                state.completed = true;
286                                state.running = false;
287                                completion = Some(std::mem::take(&mut state.completion_handlers));
288                            }
289                        }
290                    }
291
292                    if state.running {
293                        state.schedule_tick(cx);
294                    }
295
296                    cx.notify();
297                }
298                completion
299            });
300            if let Ok(Some(handlers)) = completion {
301                for (window_handle, handler) in handlers {
302                    _ = cx.update_window(window_handle, |_, window, cx| {
303                        handler(window, cx);
304                    });
305                }
306            }
307        })
308        .detach();
309    }
310}
311
312impl Render for CountdownState {
313    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
314        div()
315    }
316}
317
318#[derive(IntoElement)]
319pub struct Countdown {
320    id: ElementId,
321    state: Entity<CountdownState>,
322    size: CountdownSize,
323    separator: CountdownSeparator,
324    format: CountdownFormat,
325    on_complete: Option<CompletionHandler>,
326    style: StyleRefinement,
327}
328
329impl Countdown {
330    pub fn new(id: impl Into<ElementId>, state: Entity<CountdownState>) -> Self {
331        Self {
332            id: id.into(),
333            state,
334            size: CountdownSize::Md,
335            separator: CountdownSeparator::Colon,
336            format: CountdownFormat::default(),
337            on_complete: None,
338            style: StyleRefinement::default(),
339        }
340    }
341
342    pub fn size(mut self, size: CountdownSize) -> Self {
343        self.size = size;
344        self
345    }
346
347    pub fn separator(mut self, separator: CountdownSeparator) -> Self {
348        self.separator = separator;
349        self
350    }
351
352    pub fn format(mut self, format: CountdownFormat) -> Self {
353        self.format = format;
354        self
355    }
356
357    pub fn show_days(mut self, show: bool) -> Self {
358        self.format.show_days = show;
359        self
360    }
361
362    pub fn show_hours(mut self, show: bool) -> Self {
363        self.format.show_hours = show;
364        self
365    }
366
367    pub fn show_minutes(mut self, show: bool) -> Self {
368        self.format.show_minutes = show;
369        self
370    }
371
372    pub fn show_seconds(mut self, show: bool) -> Self {
373        self.format.show_seconds = show;
374        self
375    }
376
377    pub fn show_labels(mut self, show: bool) -> Self {
378        self.format.show_labels = show;
379        self
380    }
381
382    pub fn pad_zeros(mut self, pad: bool) -> Self {
383        self.format.pad_zeros = pad;
384        self
385    }
386
387    pub fn on_complete(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
388        self.on_complete = Some(Rc::new(handler));
389        self
390    }
391
392    fn render_unit(
393        &self,
394        value: u64,
395        label: &str,
396        theme: &crate::capabilities::foundation::theme::Theme,
397    ) -> impl IntoElement {
398        let digit_text = if self.format.pad_zeros {
399            format!("{:02}", value)
400        } else {
401            format!("{}", value)
402        };
403
404        div()
405            .flex()
406            .flex_col()
407            .items_center()
408            .gap(px(4.0))
409            .px(self.size.unit_padding())
410            .child(
411                div()
412                    .text_size(self.size.digit_size())
413                    .font_weight(FontWeight::BOLD)
414                    .text_color(theme.tokens.foreground)
415                    .font_family(theme.tokens.font_mono.clone())
416                    .child(digit_text),
417            )
418            .when(self.format.show_labels, |this| {
419                this.child(
420                    div()
421                        .text_size(self.size.label_size())
422                        .text_color(theme.tokens.muted_foreground)
423                        .child(label.to_string()),
424                )
425            })
426    }
427
428    fn render_separator(
429        &self,
430        theme: &crate::capabilities::foundation::theme::Theme,
431    ) -> AnyElement {
432        let sep = self.separator.as_str();
433        if sep.is_empty() {
434            return div().into_any_element();
435        }
436
437        div()
438            .text_size(self.size.separator_size())
439            .font_weight(FontWeight::BOLD)
440            .text_color(theme.tokens.muted_foreground)
441            .child(sep.to_string())
442            .into_any_element()
443    }
444}
445
446impl Styled for Countdown {
447    fn style(&mut self) -> &mut StyleRefinement {
448        &mut self.style
449    }
450}
451
452impl RenderOnce for Countdown {
453    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
454        let theme = use_theme(cx);
455        let on_complete = self.on_complete.clone();
456        let window_handle = window.window_handle();
457        self.state.update(cx, move |state, _cx| {
458            state.register_completion_handler(window_handle, on_complete);
459        });
460        let state = self.state.read(cx);
461        let units = state.time_units();
462        let user_style = self.style.clone();
463
464        let mut elements: Vec<AnyElement> = Vec::new();
465
466        if self.format.show_days {
467            elements.push(
468                self.render_unit(units.days, "days", &theme)
469                    .into_any_element(),
470            );
471            if self.format.show_hours || self.format.show_minutes || self.format.show_seconds {
472                elements.push(self.render_separator(&theme));
473            }
474        }
475
476        if self.format.show_hours {
477            let hours = if self.format.show_days {
478                units.hours
479            } else {
480                units.days * 24 + units.hours
481            };
482            elements.push(self.render_unit(hours, "hours", &theme).into_any_element());
483            if self.format.show_minutes || self.format.show_seconds {
484                elements.push(self.render_separator(&theme));
485            }
486        }
487
488        if self.format.show_minutes {
489            let minutes = if self.format.show_hours {
490                units.minutes
491            } else {
492                (units.days * 24 + units.hours) * 60 + units.minutes
493            };
494            elements.push(self.render_unit(minutes, "min", &theme).into_any_element());
495            if self.format.show_seconds {
496                elements.push(self.render_separator(&theme));
497            }
498        }
499
500        if self.format.show_seconds {
501            let seconds = if self.format.show_minutes {
502                units.seconds
503            } else {
504                units.total_seconds as u64
505            };
506            elements.push(self.render_unit(seconds, "sec", &theme).into_any_element());
507        }
508
509        div()
510            .id(self.id)
511            .flex()
512            .items_center()
513            .justify_center()
514            .gap(px(4.0))
515            .map(|this| {
516                let mut d = this;
517                d.style().refine(&user_style);
518                d
519            })
520            .children(elements)
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use crate::capabilities::foundation::theme::{install_theme, Theme};
528    use std::cell::Cell;
529    use std::rc::Rc;
530
531    struct CountdownTestView {
532        state: Entity<CountdownState>,
533        completions: Rc<Cell<usize>>,
534    }
535
536    impl Render for CountdownTestView {
537        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
538            let completions = self.completions.clone();
539            Countdown::new("countdown", self.state.clone()).on_complete(move |_, _| {
540                completions.set(completions.get() + 1);
541            })
542        }
543    }
544
545    #[gpui::test]
546    fn shared_state_registers_completion_handler_per_window() {
547        let mut app = TestApp::new();
548        app.update(|cx| install_theme(cx, Theme::light()));
549
550        let state = app.update(|cx| cx.new(CountdownState::new));
551        let first_calls = Rc::new(Cell::new(0));
552        let second_calls = Rc::new(Cell::new(0));
553        let first_calls_for_view = first_calls.clone();
554        let second_calls_for_view = second_calls.clone();
555
556        let mut first_window = app.open_window(|_, _| CountdownTestView {
557            state: state.clone(),
558            completions: first_calls_for_view,
559        });
560        let mut second_window = app.open_window(|_, _| CountdownTestView {
561            state: state.clone(),
562            completions: second_calls_for_view,
563        });
564
565        first_window.draw();
566        second_window.draw();
567        first_window.draw();
568
569        app.read(|cx| {
570            assert_eq!(state.read(cx).completion_handlers.len(), 2);
571        });
572        assert_eq!(first_calls.get(), 0);
573        assert_eq!(second_calls.get(), 0);
574    }
575}