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

use cfg_if::cfg_if;
use default_struct_builder::DefaultBuilder;
use leptos::leptos_dom::helpers::TimeoutHandle;
use leptos::*;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;

#[derive(Copy, Clone, DefaultBuilder, Default)]
pub struct DebounceOptions {
    /// The maximum time allowed to be delayed before it's invoked.
    /// In milliseconds.
    #[builder(into)]
    pub max_wait: MaybeSignal<Option<f64>>,
}

pub fn debounce_filter<R>(
    ms: impl Into<MaybeSignal<f64>>,
    options: DebounceOptions,
) -> impl Fn(Rc<dyn Fn() -> R>) -> Rc<RefCell<Option<R>>> + Clone
where
    R: 'static,
{
    let timer = Rc::new(Cell::new(None::<TimeoutHandle>));
    let max_timer = Rc::new(Cell::new(None::<TimeoutHandle>));
    let last_return_value: Rc<RefCell<Option<R>>> = Rc::new(RefCell::new(None));

    let clear_timeout = move |timer: &Rc<Cell<Option<TimeoutHandle>>>| {
        if let Some(handle) = timer.get() {
            handle.clear();
            timer.set(None);
        }
    };

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

        move || {
            clear_timeout(&timer);
        }
    });

    let ms = ms.into();
    let max_wait_signal = options.max_wait;

    move |_invoke: Rc<dyn Fn() -> R>| {
        let duration = ms.get_untracked();
        let max_duration = max_wait_signal.get_untracked();

        let last_return_val = Rc::clone(&last_return_value);
        let invoke = move || {
            #[cfg(debug_assertions)]
            let prev = SpecialNonReactiveZone::enter();

            let return_value = _invoke();

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

            let mut val_mut = last_return_val.borrow_mut();
            *val_mut = Some(return_value);
        };

        clear_timeout(&timer);

        if duration <= 0.0 || max_duration.is_some_and(|d| d <= 0.0) {
            clear_timeout(&max_timer);

            invoke();
            return Rc::clone(&last_return_value);
        }

        cfg_if! { if #[cfg(not(feature = "ssr"))] {
            // Create the max_timer. Clears the regular timer on invoke
            if let Some(max_duration) = max_duration {
                if max_timer.get().is_none() {
                    let timer = Rc::clone(&timer);
                    let invok = invoke.clone();
                    max_timer.set(
                        set_timeout_with_handle(
                            move || {
                                clear_timeout(&timer);
                                invok();
                            },
                            Duration::from_millis(max_duration as u64),
                        )
                        .ok(),
                    );
                }
            }

            let max_timer = Rc::clone(&max_timer);

            // Create the regular timer. Clears the max timer on invoke
            timer.set(
                set_timeout_with_handle(
                    move || {
                        clear_timeout(&max_timer);
                        invoke();
                    },
                    Duration::from_millis(duration as u64),
                )
                .ok(),
            );
        }}

        Rc::clone(&last_return_value)
    }
}