1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use crate::core::now;
use crate::utils::Pausable;
use crate::{
    use_interval_fn_with_options, use_raf_fn_with_options, UseIntervalFnOptions, UseRafFnOptions,
};
use default_struct_builder::DefaultBuilder;
use leptos::*;
use std::rc::Rc;

/// Reactive current timestamp.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_timestamp)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::use_timestamp;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let timestamp = use_timestamp();
/// #
/// # view! { }
/// # }
/// ```
///
/// With controls:
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_timestamp_with_controls, UseTimestampReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let UseTimestampReturn {
///     timestamp,
///     is_active,
///     pause,
///     resume,
/// } = use_timestamp_with_controls();
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server this function will return a signal with the milliseconds since the Unix epoch.
/// But the signal will never update (as there's no `request_animation_frame` on the server).
pub fn use_timestamp() -> Signal<f64> {
    use_timestamp_with_controls().timestamp
}

/// Version of [`use_timestamp`] that takes a `UseTimestampOptions`. See [`use_timestamp`] for how to use.
pub fn use_timestamp_with_options(options: UseTimestampOptions) -> Signal<f64> {
    use_timestamp_with_controls_and_options(options).timestamp
}

/// Version of [`use_timestamp`] that returns controls. See [`use_timestamp`] for how to use.
pub fn use_timestamp_with_controls() -> UseTimestampReturn {
    use_timestamp_with_controls_and_options(UseTimestampOptions::default())
}

/// Version of [`use_timestamp`] that takes a `UseTimestampOptions` and returns controls. See [`use_timestamp`] for how to use.
pub fn use_timestamp_with_controls_and_options(options: UseTimestampOptions) -> UseTimestampReturn {
    let UseTimestampOptions {
        offset,
        immediate,
        interval,
        callback,
    } = options;

    let (ts, set_ts) = create_signal(now() + offset);

    let update = move || {
        set_ts.set(now() + offset);
    };

    let cb = {
        let callback = Rc::clone(&callback);

        move || {
            update();

            #[cfg(debug_assertions)]
            let prev = SpecialNonReactiveZone::enter();

            callback(ts.get_untracked());

            #[cfg(debug_assertions)]
            SpecialNonReactiveZone::exit(prev);
        }
    };

    match interval {
        TimestampInterval::RequestAnimationFrame => {
            let Pausable {
                pause,
                resume,
                is_active,
            } = use_raf_fn_with_options(
                move |_| cb(),
                UseRafFnOptions::default().immediate(immediate),
            );

            UseTimestampReturn {
                timestamp: ts.into(),
                is_active,
                pause: Rc::new(pause),
                resume: Rc::new(resume),
            }
        }

        TimestampInterval::Interval(interval) => {
            let Pausable {
                pause,
                resume,
                is_active,
            } = use_interval_fn_with_options(
                cb,
                interval,
                UseIntervalFnOptions::default().immediate(immediate),
            );

            UseTimestampReturn {
                timestamp: ts.into(),
                is_active,
                pause: Rc::new(pause),
                resume: Rc::new(resume),
            }
        }
    }
}

/// Options for [`use_timestamp_with_controls_and_options`].
#[derive(DefaultBuilder)]
pub struct UseTimestampOptions {
    /// Offset value in milliseconds that is added to the returned timestamp. Defaults to `0.0`.
    offset: f64,

    /// Whether to update the timestamp immediately. Defaults to `true`.
    immediate: bool,

    /// Update interval in milliseconds or `RequestAnimationFrame`. Defaults to `RequestAnimationFrame`.
    #[builder(into)]
    interval: TimestampInterval,

    /// Callback to be called whenever the timestamp is updated.
    callback: Rc<dyn Fn(f64)>,
}

/// Interval type for [`UseTimestampOptions`].
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum TimestampInterval {
    /// use [`fn@crate::use_raf_fn`] for updating the timestamp
    RequestAnimationFrame,

    /// use [`fn@crate::use_interval_fn`] for updating the timestamp
    Interval(u64),
}

impl From<u64> for TimestampInterval {
    fn from(value: u64) -> Self {
        Self::Interval(value)
    }
}

impl Default for UseTimestampOptions {
    fn default() -> Self {
        Self {
            offset: 0.0,
            immediate: true,
            interval: TimestampInterval::RequestAnimationFrame,
            callback: Rc::new(|_| {}),
        }
    }
}

/// Return type of [`use_timestamp_with_controls`].
pub struct UseTimestampReturn {
    /// The current timestamp
    pub timestamp: Signal<f64>,

    /// A Signal that indicates whether the timestamp updating is active. `false` when paused.
    pub is_active: Signal<bool>,

    /// Temporarily pause the timestamp from updating
    pub pause: Rc<dyn Fn()>,

    /// Resume the timestamp updating
    pub resume: Rc<dyn Fn()>,
}