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
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports))]

use crate::utils::Pausable;
use default_struct_builder::DefaultBuilder;
use leptos::leptos_dom::helpers::IntervalHandle;
use leptos::*;
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;

/// Wrapper for `set_interval` with controls.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_interval_fn)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::use_interval_fn;
/// # use leptos_use::utils::Pausable;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let Pausable { pause, resume, is_active } = use_interval_fn(
///     || {
///         // do something
///     },
///     1000,
/// );
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server this function will simply be ignored.
pub fn use_interval_fn<CbFn, N>(
    callback: CbFn,
    interval: N,
) -> Pausable<impl Fn() + Clone, impl Fn() + Clone>
where
    CbFn: Fn() + Clone + 'static,
    N: Into<MaybeSignal<u64>>,
{
    use_interval_fn_with_options(callback, interval, UseIntervalFnOptions::default())
}

/// Version of [`use_interval_fn`] that takes `UseIntervalFnOptions`. See [`use_interval_fn`] for how to use.
pub fn use_interval_fn_with_options<CbFn, N>(
    callback: CbFn,
    interval: N,
    options: UseIntervalFnOptions,
) -> Pausable<impl Fn() + Clone, impl Fn() + Clone>
where
    CbFn: Fn() + Clone + 'static,
    N: Into<MaybeSignal<u64>>,
{
    let UseIntervalFnOptions {
        immediate,
        immediate_callback,
    } = options;

    let timer: Rc<Cell<Option<IntervalHandle>>> = Rc::new(Cell::new(None));

    let (is_active, set_active) = create_signal(false);

    let clean = {
        let timer = Rc::clone(&timer);

        move || {
            if let Some(handle) = timer.take() {
                handle.clear();
            }
        }
    };

    let pause = {
        let clean = clean.clone();

        move || {
            set_active.set(false);
            clean();
        }
    };

    let interval = interval.into();

    let resume = move || {
        #[cfg(not(feature = "ssr"))]
        {
            let interval_value = interval.get();
            if interval_value == 0 {
                return;
            }

            set_active.set(true);

            let callback = {
                let callback = callback.clone();

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

                    callback();

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

            if immediate_callback {
                callback.clone()();
            }
            clean();

            timer.set(
                set_interval_with_handle(callback.clone(), Duration::from_millis(interval_value))
                    .ok(),
            );
        }
    };

    if immediate {
        resume();
    }

    if matches!(interval, MaybeSignal::Dynamic(_)) {
        let resume = resume.clone();

        let stop_watch = watch(
            move || interval.get(),
            move |_, _, _| {
                if is_active.get() {
                    resume();
                }
            },
            false,
        );
        on_cleanup(stop_watch);
    }

    on_cleanup(pause.clone());

    Pausable {
        is_active: is_active.into(),
        pause,
        resume,
    }
}

/// Options for [`use_interval_fn_with_options`]
#[derive(DefaultBuilder)]
pub struct UseIntervalFnOptions {
    /// Start the timer immediately. Defaults to `true`.
    pub immediate: bool,

    /// Execute the callback immediate after calling this function. Defaults to `false`
    pub immediate_callback: bool,
}

impl Default for UseIntervalFnOptions {
    fn default() -> Self {
        Self {
            immediate: true,
            immediate_callback: false,
        }
    }
}