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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::{node::NodeId, with_runtime, Disposer, Runtime, SignalDispose};
use cfg_if::cfg_if;
use std::{any::Any, cell::RefCell, marker::PhantomData, rc::Rc};

/// Effects run a certain chunk of code whenever the signals they depend on change.
/// `create_effect` queues the given function to run once, tracks its dependence
/// on any signal values read within it, and reruns the function whenever the value
/// of a dependency changes.
///
/// Effects are intended to run *side-effects* of the system, not to synchronize state
/// *within* the system. In other words: don't write to signals within effects, unless
/// you’re coordinating with some other non-reactive side effect.
/// (If you need to define a signal that depends on the value of other signals, use a
/// derived signal or [`create_memo`](crate::create_memo)).
///
/// This first run is queued for the next microtask, i.e., it runs after all other
/// synchronous code has completed. In practical terms, this means that if you use
/// `create_effect` in the body of the component, it will run *after* the view has been
/// created and (presumably) mounted. (If you need an effect that runs immediately, use
/// [`create_render_effect`].)
///
/// The effect function is called with an argument containing whatever value it returned
/// the last time it ran. On the initial run, this is `None`.
///
/// By default, effects **do not run on the server**. This means you can call browser-specific
/// APIs within the effect function without causing issues. If you need an effect to run on
/// the server, use [`create_isomorphic_effect`].
/// ```
/// # use leptos_reactive::*;
/// # use log::*;
/// # let runtime = create_runtime();
/// let (a, set_a) = create_signal(0);
/// let (b, set_b) = create_signal(0);
///
/// // ✅ use effects to interact between reactive state and the outside world
/// create_effect(move |_| {
///   // immediately prints "Value: 0" and subscribes to `a`
///   log::debug!("Value: {}", a.get());
/// });
///
/// set_a.set(1);
/// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
///
/// // ❌ don't use effects to synchronize state within the reactive system
/// create_effect(move |_| {
///   // this technically works but can cause unnecessary re-renders
///   // and easily lead to problems like infinite loops
///   set_b.set(a.get() + 1);
/// });
/// # if !cfg!(feature = "ssr") {
/// # assert_eq!(b.get(), 2);
/// # }
/// # runtime.dispose();
/// ```
#[cfg_attr(
    any(debug_assertions, feature="ssr"),
    instrument(
        level = "trace",
        skip_all,
        fields(
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
#[inline(always)]
pub fn create_effect<T>(f: impl Fn(Option<T>) -> T + 'static) -> Effect<T>
where
    T: 'static,
{
    cfg_if! {
        if #[cfg(not(feature = "ssr"))] {
            use crate::{Owner, queue_microtask, with_owner};

            let runtime = Runtime::current();
            let owner = Owner::current();
            let id = runtime.create_effect(f);

            queue_microtask(move || {
                with_owner(owner.unwrap(), move || {
                    _ = with_runtime( |runtime| {
                        runtime.update_if_necessary(id);
                    });
                });
            });

            Effect { id, ty: PhantomData }
        } else {
            // clear warnings
            _ = f;
            Effect { id: Default::default(), ty: PhantomData }
        }
    }
}

impl<T> Effect<T>
where
    T: 'static,
{
    /// Effects run a certain chunk of code whenever the signals they depend on change.
    /// `create_effect` immediately runs the given function once, tracks its dependence
    /// on any signal values read within it, and reruns the function whenever the value
    /// of a dependency changes.
    ///
    /// Effects are intended to run *side-effects* of the system, not to synchronize state
    /// *within* the system. In other words: don't write to signals within effects.
    /// (If you need to define a signal that depends on the value of other signals, use a
    /// derived signal or [`create_memo`](crate::create_memo)).
    ///
    /// The effect function is called with an argument containing whatever value it returned
    /// the last time it ran. On the initial run, this is `None`.
    ///
    /// By default, effects **do not run on the server**. This means you can call browser-specific
    /// APIs within the effect function without causing issues. If you need an effect to run on
    /// the server, use [`create_isomorphic_effect`].
    /// ```
    /// # use leptos_reactive::*;
    /// # use log::*;
    /// # let runtime = create_runtime();
    /// let a = RwSignal::new(0);
    /// let b = RwSignal::new(0);
    ///
    /// // ✅ use effects to interact between reactive state and the outside world
    /// Effect::new(move |_| {
    ///   // immediately prints "Value: 0" and subscribes to `a`
    ///   log::debug!("Value: {}", a.get());
    /// });
    ///
    /// a.set(1);
    /// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
    ///
    /// // ❌ don't use effects to synchronize state within the reactive system
    /// Effect::new(move |_| {
    ///   // this technically works but can cause unnecessary re-renders
    ///   // and easily lead to problems like infinite loops
    ///   b.set(a.get() + 1);
    /// });
    /// # if !cfg!(feature = "ssr") {
    /// # assert_eq!(b.get(), 2);
    /// # }
    /// # runtime.dispose();
    /// ```
    #[track_caller]
    #[inline(always)]
    pub fn new(f: impl Fn(Option<T>) -> T + 'static) -> Self {
        create_effect(f)
    }

    /// Creates an effect; unlike effects created by [`create_effect`], isomorphic effects will run on
    /// the server as well as the client.
    /// ```
    /// # use leptos_reactive::*;
    /// # use log::*;
    /// # let runtime = create_runtime();
    /// let a = RwSignal::new(0);
    /// let b = RwSignal::new(0);
    ///
    /// // ✅ use effects to interact between reactive state and the outside world
    /// Effect::new_isomorphic(move |_| {
    ///   // immediately prints "Value: 0" and subscribes to `a`
    ///   log::debug!("Value: {}", a.get());
    /// });
    ///
    /// a.set(1);
    /// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
    ///
    /// // ❌ don't use effects to synchronize state within the reactive system
    /// Effect::new_isomorphic(move |_| {
    ///   // this technically works but can cause unnecessary re-renders
    ///   // and easily lead to problems like infinite loops
    ///   b.set(a.get() + 1);
    /// });
    /// # assert_eq!(b.get(), 2);
    /// # runtime.dispose();
    #[track_caller]
    #[inline(always)]
    pub fn new_isomorphic(f: impl Fn(Option<T>) -> T + 'static) -> Self {
        create_isomorphic_effect(f)
    }

    /// Applies the given closure to the most recent value of the effect.
    ///
    /// Because effect functions can return values, each time an effect runs it
    /// consumes its previous value. This allows an effect to store additional state
    /// (like a DOM node, a timeout handle, or a type that implements `Drop`) and
    /// keep it alive across multiple runs.
    ///
    /// This method allows access to the effect’s value outside the effect function.
    /// The next time a signal change causes the effect to run, it will receive the
    /// mutated value.
    pub fn with_value_mut<U>(
        &self,
        f: impl FnOnce(&mut Option<T>) -> U,
    ) -> Option<U> {
        with_runtime(|runtime| {
            let nodes = runtime.nodes.borrow();
            let node = nodes.get(self.id)?;
            let value = node.value.clone()?;
            let mut value = value.borrow_mut();
            let value = value.downcast_mut()?;
            Some(f(value))
        })
        .ok()
        .flatten()
    }
}

/// Creates an effect; unlike effects created by [`create_effect`], isomorphic effects will run on
/// the server as well as the client.
/// ```
/// # use leptos_reactive::*;
/// # use log::*;
/// # let runtime = create_runtime();
/// let (a, set_a) = create_signal(0);
/// let (b, set_b) = create_signal(0);
///
/// // ✅ use effects to interact between reactive state and the outside world
/// create_isomorphic_effect(move |_| {
///   // immediately prints "Value: 0" and subscribes to `a`
///   log::debug!("Value: {}", a.get());
/// });
///
/// set_a.set(1);
/// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
///
/// // ❌ don't use effects to synchronize state within the reactive system
/// create_isomorphic_effect(move |_| {
///   // this technically works but can cause unnecessary re-renders
///   // and easily lead to problems like infinite loops
///   set_b.set(a.get() + 1);
/// });
/// # assert_eq!(b.get(), 2);
/// # runtime.dispose();
#[cfg_attr(
    any(debug_assertions, feature="ssr"),
    instrument(
        level = "trace",
        skip_all,
        fields(
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
#[inline(always)]
pub fn create_isomorphic_effect<T>(
    f: impl Fn(Option<T>) -> T + 'static,
) -> Effect<T>
where
    T: 'static,
{
    let runtime = Runtime::current();
    let id = runtime.create_effect(f);
    //crate::macros::debug_warn!("creating effect {e:?}");
    _ = with_runtime(|runtime| {
        runtime.update_if_necessary(id);
    });
    Effect {
        id,
        ty: PhantomData,
    }
}

/// Creates an effect exactly like [`create_effect`], but runs immediately rather
/// than being queued until the end of the current microtask. This is mostly used
/// inside the renderer but is available for use cases in which scheduling the effect
/// for the next tick is not optimal.
#[cfg_attr(
    any(debug_assertions, feature="ssr"),
    instrument(
        level = "trace",
        skip_all,
        fields(
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[inline(always)]
pub fn create_render_effect<T>(
    f: impl Fn(Option<T>) -> T + 'static,
) -> Effect<T>
where
    T: 'static,
{
    cfg_if! {
        if #[cfg(not(feature = "ssr"))] {
            let runtime = Runtime::current();
            let id = runtime.create_effect(f);
            _ = with_runtime( |runtime| {
                runtime.update_if_necessary(id);
            });
            Effect { id, ty: PhantomData }
        } else {
            // clear warnings
            _ = f;
            Effect { id: Default::default(), ty: PhantomData }
        }
    }
}

/// A handle to an effect, can be used to explicitly dispose of the effect.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Effect<T> {
    pub(crate) id: NodeId,
    ty: PhantomData<T>,
}

impl<T> From<Effect<T>> for Disposer {
    fn from(effect: Effect<T>) -> Self {
        Disposer(effect.id)
    }
}

impl<T> SignalDispose for Effect<T> {
    fn dispose(self) {
        drop(Disposer::from(self));
    }
}

pub(crate) struct EffectState<T, F>
where
    T: 'static,
    F: Fn(Option<T>) -> T,
{
    pub(crate) f: F,
    pub(crate) ty: PhantomData<T>,
    #[cfg(any(debug_assertions, feature = "ssr"))]
    pub(crate) defined_at: &'static std::panic::Location<'static>,
}

pub(crate) trait AnyComputation {
    fn run(&self, value: Rc<RefCell<dyn Any>>) -> bool;
}

impl<T, F> AnyComputation for EffectState<T, F>
where
    T: 'static,
    F: Fn(Option<T>) -> T,
{
    #[cfg_attr(
        any(debug_assertions, feature = "ssr"),
        instrument(
            name = "Effect::run()",
            level = "trace",
            skip_all,
            fields(
              defined_at = %self.defined_at,
              ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn run(&self, value: Rc<RefCell<dyn Any>>) -> bool {
        // we defensively take and release the BorrowMut twice here
        // in case a change during the effect running schedules a rerun
        // ideally this should never happen, but this guards against panic
        let curr_value = {
            // downcast value
            let mut value = value.borrow_mut();
            let value = value
                .downcast_mut::<Option<T>>()
                .expect("to downcast effect value");
            value.take()
        };

        // run the effect
        let new_value = (self.f)(curr_value);

        // set new value
        let mut value = value.borrow_mut();
        let value = value
            .downcast_mut::<Option<T>>()
            .expect("to downcast effect value");
        *value = Some(new_value);

        true
    }
}