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
196
197
198
199
200
201
202
203
204
use crate::filter_builder_methods;
use crate::utils::{create_filter_wrapper, DebounceOptions, FilterOptions, ThrottleOptions};
use default_struct_builder::DefaultBuilder;
use leptos::*;
use std::cell::RefCell;
use std::rc::Rc;

/// A version of `leptos::watch` but with additional options.
///
/// ## Immediate
///
/// This is the same as for `leptos::watch`. But you don't have to specify it.
/// By default its set to `false`.
/// If `immediate` is `true`, the `callback` will run immediately (this is also true if throttled/debounced).
/// If it's `false`, the `callback` will run only after
/// the first change is detected of any signal that is accessed in `deps`.
///
/// ```
/// # use leptos::*;
/// # use leptos::logging::log;
/// # use leptos_use::{watch_with_options, WatchOptions};
/// #
/// # pub fn Demo() -> impl IntoView {
/// let (num, set_num) = create_signal(0);
///
/// watch_with_options(
///     move || num.get(),
///     move |num, _, _| {
///         log!("Number {}", num);
///     },
///     WatchOptions::default().immediate(true),
/// ); // > "Number 0"
///
/// set_num.set(1); // > "Number 1"
/// #    view! { }
/// # }
/// ```
///
/// ## Filters
///
/// The callback can be throttled or debounced. Please see [`watch_throttled`] and [`watch_debounced`] for details.
///
/// ```
/// # use leptos::*;
/// # use leptos::logging::log;
/// # use leptos_use::{watch_with_options, WatchOptions};
/// #
/// # pub fn Demo() -> impl IntoView {
/// # let (num, set_num) = create_signal(0);
/// #
/// watch_with_options(
///     move || num.get(),
///     move |num, _, _| {
///         log!("Number {}", num);
///     },
///     WatchOptions::default().throttle(100.0), // there's also `throttle_with_options`
/// );
/// #    view! { }
/// # }
/// ```
///
/// ```
/// # use leptos::*;
/// # use leptos::logging::log;
/// # use leptos_use::{watch_with_options, WatchOptions};
/// #
/// # pub fn Demo() -> impl IntoView {
/// # let (num, set_num) = create_signal(0);
/// #
/// watch_with_options(
///     move || num.get(),
///     move |num, _, _| {
///         log!("number {}", num);
///     },
///     WatchOptions::default().debounce(100.0), // there's also `debounce_with_options`
/// );
/// #    view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server this works just fine except if you throttle or debounce in which case the callback
/// will never be called except if you set `immediate` to `true` in which case the callback will be
/// called exactly once when `watch()` is executed.
///
/// ## See also
///
/// * [`watch_throttled`]
/// * [`watch_debounced`]

/// Version of `watch` that accepts `WatchOptions`. See [`watch`] for how to use.
pub fn watch_with_options<W, T, DFn, CFn>(
    deps: DFn,
    callback: CFn,
    options: WatchOptions,
) -> impl Fn() + Clone
where
    DFn: Fn() -> W + 'static,
    CFn: Fn(&W, Option<&W>, Option<T>) -> T + Clone + 'static,
    W: Clone + 'static,
    T: Clone + 'static,
{
    let cur_deps_value: Rc<RefCell<Option<W>>> = Rc::new(RefCell::new(None));
    let prev_deps_value: Rc<RefCell<Option<W>>> = Rc::new(RefCell::new(None));
    let prev_callback_value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));

    let wrapped_callback = {
        let cur_deps_value = Rc::clone(&cur_deps_value);
        let prev_deps_value = Rc::clone(&prev_deps_value);
        let prev_callback_val = Rc::clone(&prev_callback_value);

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

            let ret = callback(
                cur_deps_value
                    .borrow()
                    .as_ref()
                    .expect("this will not be called before there is deps value"),
                prev_deps_value.borrow().as_ref(),
                prev_callback_val.take(),
            );

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

            ret
        }
    };

    let filtered_callback =
        create_filter_wrapper(options.filter.filter_fn(), wrapped_callback.clone());

    leptos::watch(
        deps,
        move |deps_value, previous_deps_value, did_run_before| {
            cur_deps_value.replace(Some(deps_value.clone()));
            prev_deps_value.replace(previous_deps_value.cloned());

            let callback_value = if options.immediate && did_run_before.is_none() {
                Some(wrapped_callback())
            } else {
                filtered_callback().take()
            };

            prev_callback_value.replace(callback_value);
        },
        options.immediate,
    )

    // create_effect(move |did_run_before| {
    //     if !is_active.get() {
    //         return;
    //     }
    //
    //     let deps_value = deps();
    //
    //     if !options.immediate && did_run_before.is_none() {
    //         prev_deps_value.replace(Some(deps_value));
    //         return;
    //     }
    //
    //     cur_deps_value.replace(Some(deps_value.clone()));
    //
    //
    //     prev_deps_value.replace(Some(deps_value));
    // });
    //
    //
}

/// Options for `watch_with_options`
#[derive(DefaultBuilder, Default)]
pub struct WatchOptions {
    /// If `immediate` is true, the `callback` will run immediately.
    /// If it's `false, the `callback` will run only after
    /// the first change is detected of any signal that is accessed in `deps`.
    /// Defaults to `false`.
    immediate: bool,

    /// Allows to debounce or throttle the callback. Defaults to no filter.
    filter: FilterOptions,
}

impl WatchOptions {
    filter_builder_methods!(
        /// the watch callback
        filter
    );
}

#[deprecated(since = "0.7.0", note = "Use `leptos::watch` instead")]
#[inline(always)]
pub fn watch<W, T, DFn, CFn>(deps: DFn, callback: CFn) -> impl Fn() + Clone
where
    DFn: Fn() -> W + 'static,
    CFn: Fn(&W, Option<&W>, Option<T>) -> T + Clone + 'static,
    W: Clone + 'static,
    T: Clone + 'static,
{
    leptos::watch(deps, callback, false)
}