leptos_use/watch_with_options.rs
1use crate::filter_builder_methods;
2use crate::utils::{create_filter_wrapper, DebounceOptions, FilterOptions, ThrottleOptions};
3use default_struct_builder::DefaultBuilder;
4use leptos::prelude::*;
5use std::cell::RefCell;
6use std::rc::Rc;
7
8/// A version of `leptos::watch` but with additional options.
9///
10/// ## Immediate
11///
12/// This is the same as for `leptos::watch`. But you don't have to specify it.
13/// By default its set to `false`.
14/// If `immediate` is `true`, the `callback` will run immediately (this is also true if throttled/debounced).
15/// If it's `false`, the `callback` will run only after
16/// the first change is detected of any signal that is accessed in `deps`.
17///
18/// ```
19/// # use leptos::prelude::*;
20/// # use leptos::logging::log;
21/// # use leptos_use::{watch_with_options, WatchOptions};
22/// #
23/// # pub fn Demo() -> impl IntoView {
24/// let (num, set_num) = signal(0);
25///
26/// watch_with_options(
27/// move || num.get(),
28/// move |num, _, _| {
29/// log!("Number {}", num);
30/// },
31/// WatchOptions::default().immediate(true),
32/// ); // > "Number 0"
33///
34/// set_num.set(1); // > "Number 1"
35/// # view! { }
36/// # }
37/// ```
38///
39/// ## Filters
40///
41/// The callback can be throttled or debounced. Please see [`fn@crate::watch_throttled`]
42/// and [`fn@crate::watch_debounced`] for details.
43///
44/// ```
45/// # use leptos::prelude::*;
46/// # use leptos::logging::log;
47/// # use leptos_use::{watch_with_options, WatchOptions};
48/// #
49/// # pub fn Demo() -> impl IntoView {
50/// # let (num, set_num) = signal(0);
51/// #
52/// watch_with_options(
53/// move || num.get(),
54/// move |num, _, _| {
55/// log!("Number {}", num);
56/// },
57/// WatchOptions::default().throttle(100.0), // there's also `throttle_with_options`
58/// );
59/// # view! { }
60/// # }
61/// ```
62///
63/// ```
64/// # use leptos::prelude::*;
65/// # use leptos::logging::log;
66/// # use leptos_use::{watch_with_options, WatchOptions};
67/// #
68/// # pub fn Demo() -> impl IntoView {
69/// # let (num, set_num) = signal(0);
70/// #
71/// watch_with_options(
72/// move || num.get(),
73/// move |num, _, _| {
74/// log!("number {}", num);
75/// },
76/// WatchOptions::default().debounce(100.0), // there's also `debounce_with_options`
77/// );
78/// # view! { }
79/// # }
80/// ```
81///
82/// ## Server-Side Rendering
83///
84/// On the server this works just fine except if you throttle or debounce in which case the callback
85/// will never be called except if you set `immediate` to `true` in which case the callback will be
86/// called exactly once when `watch()` is executed.
87///
88/// ## See also
89///
90/// * [`fn@crate::watch_throttled`]
91/// * [`fn@crate::watch_debounced`]
92pub fn watch_with_options<W, T, DFn, CFn>(
93 deps: DFn,
94 callback: CFn,
95 options: WatchOptions,
96) -> impl Fn() + Clone + Send + Sync
97where
98 DFn: Fn() -> W + 'static,
99 CFn: Fn(&W, Option<&W>, Option<T>) -> T + Clone + 'static,
100 W: Clone + 'static,
101 T: Clone + 'static,
102{
103 let cur_deps_value: Rc<RefCell<Option<W>>> = Rc::new(RefCell::new(None));
104 let prev_deps_value: Rc<RefCell<Option<W>>> = Rc::new(RefCell::new(None));
105 let prev_callback_value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
106
107 let wrapped_callback = {
108 let cur_deps_value = Rc::clone(&cur_deps_value);
109 let prev_deps_value = Rc::clone(&prev_deps_value);
110 let prev_callback_val = Rc::clone(&prev_callback_value);
111
112 move || {
113 #[cfg(debug_assertions)]
114 let _z = leptos::reactive::diagnostics::SpecialNonReactiveZone::enter();
115
116 let ret = callback(
117 cur_deps_value
118 .borrow()
119 .as_ref()
120 .expect("this will not be called before there is deps value"),
121 prev_deps_value.borrow().as_ref(),
122 prev_callback_val.take(),
123 );
124
125 ret
126 }
127 };
128
129 let filtered_callback =
130 create_filter_wrapper(options.filter.filter_fn(), wrapped_callback.clone());
131
132 let effect = Effect::watch(
133 deps,
134 move |deps_value, previous_deps_value, did_run_before| {
135 cur_deps_value.replace(Some(deps_value.clone()));
136 prev_deps_value.replace(previous_deps_value.cloned());
137
138 let callback_value = if options.immediate && did_run_before.is_none() {
139 Some(wrapped_callback())
140 } else {
141 filtered_callback().lock().unwrap().take()
142 };
143
144 prev_callback_value.replace(callback_value);
145 },
146 options.immediate,
147 );
148
149 move || effect.stop()
150
151 // create_effect(move |did_run_before| {
152 // if !is_active.get() {
153 // return;
154 // }
155 //
156 // let deps_value = deps();
157 //
158 // if !options.immediate && did_run_before.is_none() {
159 // prev_deps_value.replace(Some(deps_value));
160 // return;
161 // }
162 //
163 // cur_deps_value.replace(Some(deps_value.clone()));
164 //
165 //
166 // prev_deps_value.replace(Some(deps_value));
167 // });
168 //
169 //
170}
171
172/// Options for `watch_with_options`
173#[derive(DefaultBuilder, Default)]
174pub struct WatchOptions {
175 /// If `immediate` is true, the `callback` will run immediately.
176 /// If it's `false, the `callback` will run only after
177 /// the first change is detected of any signal that is accessed in `deps`.
178 /// Defaults to `false`.
179 immediate: bool,
180
181 /// Allows to debounce or throttle the callback. Defaults to no filter.
182 filter: FilterOptions,
183}
184
185impl WatchOptions {
186 filter_builder_methods!(
187 /// the watch callback
188 filter
189 );
190}