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
use std::rc::Rc;

use yew::prelude::*;

use super::{use_mut_latest, use_timeout};

/// State handle for the [`use_throttle`] hook.
pub struct UseThrottleHandle {
    run: Rc<dyn Fn()>,
    cancel: Rc<dyn Fn()>,
}

impl UseThrottleHandle {
    /// Run the throttle.
    pub fn run(&self) {
        (self.run)();
    }

    /// Cancel the throttle.
    pub fn cancel(&self) {
        (self.cancel)();
    }
}

impl Clone for UseThrottleHandle {
    fn clone(&self) -> Self {
        Self {
            run: self.run.clone(),
            cancel: self.cancel.clone(),
        }
    }
}

/// A hook that throttles invoking a function, the function is only executed once every `millis`.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(Throttle)]
/// fn throttle() -> Html {
///     let state = use_state(|| 0);
///
///     let throttle = {
///         let state = state.clone();
///         use_throttle(
///             move || {
///                 state.set(*state + 1);
///             },
///             2000,
///         )
///     };
///
///     let onclick = {
///         let throttle = throttle.clone();
///         Callback::from(move |_| throttle.run())
///     };
///
///     let oncancel = { Callback::from(move |_| throttle.cancel()) };
///
///     html! {
///         <>
///             <button {onclick}>{ "Click fast!" }</button>
///             <button onclick={oncancel}>{ "Cancel throttle" }</button>
///             <b>{ "State: " }</b> {*state}
///         </>
///     }
/// }
/// ```
#[hook]
pub fn use_throttle<Callback>(callback: Callback, millis: u32) -> UseThrottleHandle
where
    Callback: FnMut() + 'static,
{
    let throttled = use_mut_ref(|| false);
    let callback_ref = use_mut_latest(callback);
    let timeout = {
        let throttled = throttled.clone();
        use_timeout(
            move || {
                *throttled.borrow_mut() = false;
            },
            millis,
        )
    };

    let run = {
        let throttled = throttled.clone();
        let timeout = timeout.clone();
        Rc::new(move || {
            let throttled_value = *throttled.borrow();
            if !throttled_value {
                let callback_ref = callback_ref.current();
                let callback = &mut *callback_ref.borrow_mut();
                callback();
                *throttled.borrow_mut() = true;
                timeout.reset();
            }
        })
    };

    let cancel = {
        Rc::new(move || {
            timeout.cancel();
            *throttled.borrow_mut() = false;
        })
    };

    UseThrottleHandle { run, cancel }
}