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
#![forbid(unsafe_code)]
use crate::{
    store_value, RwSignal, Scope, SignalSet, StoredValue, WriteSignal,
};

/// Helper trait for converting `Fn(T)` into [`SignalSetter<T>`].
pub trait IntoSignalSetter<T>: Sized {
    /// Consumes `self`, returning [`SignalSetter<T>`].
    fn mapped_signal_setter(self, cx: Scope) -> SignalSetter<T>;
}

impl<F, T> IntoSignalSetter<T> for F
where
    F: Fn(T) + 'static,
{
    fn mapped_signal_setter(self, cx: Scope) -> SignalSetter<T> {
        SignalSetter::map(cx, self)
    }
}

/// A wrapper for any kind of settable reactive signal: a [WriteSignal](crate::WriteSignal),
/// [RwSignal](crate::RwSignal), or closure that receives a value and sets a signal depending
/// on it.
///
/// This allows you to create APIs that take any kind of `SignalSetter<T>` as an argument,
/// rather than adding a generic `F: Fn(T)`. Values can be set with the same
/// function call or `set()`, API as other signals.
///
/// ## Core Trait Implementations
/// - [`.set()`](#impl-SignalSet<T>-for-SignalSetter<T>) (or calling the setter as a function)
///   sets the signal’s value, and notifies all subscribers that the signal’s value has changed.
///   to subscribe to the signal, and to re-run whenever the value of the signal changes.
///
/// ## Examples
/// ```rust
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 2);
/// let set_double_input = SignalSetter::map(cx, move |n| set_count(n * 2));
///
/// // this function takes any kind of signal setter
/// fn set_to_4(setter: &SignalSetter<i32>) {
///     // ✅ calling the signal sets the value
///     //    it is a shorthand for arg.set()
///     setter(4);
/// }
///
/// set_to_4(&set_count.into());
/// assert_eq!(count(), 4);
/// set_to_4(&set_double_input);
/// assert_eq!(count(), 8);
/// # });
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct SignalSetter<T>
where
    T: 'static,
{
    inner: SignalSetterTypes<T>,
    #[cfg(debug_assertions)]
    defined_at: &'static std::panic::Location<'static>,
}

impl<T> Clone for SignalSetter<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner,
            #[cfg(debug_assertions)]
            defined_at: self.defined_at,
        }
    }
}

impl<T: Default + 'static> Default for SignalSetter<T> {
    #[track_caller]
    fn default() -> Self {
        Self {
            inner: SignalSetterTypes::Default,
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }
}

impl<T> Copy for SignalSetter<T> {}

impl<T> SignalSet<T> for SignalSetter<T> {
    fn set(&self, new_value: T) {
        match self.inner {
            SignalSetterTypes::Default => {}
            SignalSetterTypes::Write(w) => w.set(new_value),
            SignalSetterTypes::Mapped(_, s) => {
                s.with_value(|setter| setter(new_value))
            }
        }
    }

    fn try_set(&self, new_value: T) -> Option<T> {
        match self.inner {
            SignalSetterTypes::Default => Some(new_value),
            SignalSetterTypes::Write(w) => w.try_set(new_value),
            SignalSetterTypes::Mapped(_, s) => {
                let mut new_value = Some(new_value);

                let _ = s
                    .try_with_value(|setter| setter(new_value.take().unwrap()));

                new_value
            }
        }
    }
}

impl<T> SignalSetter<T>
where
    T: 'static,
{
    /// Wraps a signal-setting closure, i.e., any computation that sets one or more
    /// reactive signals.
    /// ```rust
    /// # use leptos_reactive::*;
    /// # create_scope(create_runtime(), |cx| {
    /// let (count, set_count) = create_signal(cx, 2);
    /// let set_double_count = SignalSetter::map(cx, move |n| set_count(n * 2));
    ///
    /// // this function takes any kind of signal setter
    /// fn set_to_4(setter: &SignalSetter<i32>) {
    ///     // ✅ calling the signal sets the value
    ///     //    it is a shorthand for arg.set()
    ///     setter(4)
    /// }
    ///
    /// set_to_4(&set_count.into());
    /// assert_eq!(count(), 4);
    /// set_to_4(&set_double_count);
    /// assert_eq!(count(), 8);
    /// # });
    /// ```
    #[track_caller]
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            skip_all,
            fields(
                cx = ?cx.id,
            )
        )
    )]
    pub fn map(cx: Scope, mapped_setter: impl Fn(T) + 'static) -> Self {
        Self {
            inner: SignalSetterTypes::Mapped(
                cx,
                store_value(cx, Box::new(mapped_setter)),
            ),
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }

    /// Calls the setter function with the given value.
    ///
    /// ```rust
    /// # use leptos_reactive::*;
    /// # create_scope(create_runtime(), |cx| {
    /// let (count, set_count) = create_signal(cx, 2);
    /// let set_double_count = SignalSetter::map(cx, move |n| set_count(n * 2));
    ///
    /// // this function takes any kind of signal setter
    /// fn set_to_4(setter: &SignalSetter<i32>) {
    ///   // ✅ calling the signal sets the value
    ///   //    it is a shorthand for arg.set()
    ///   setter(4);
    /// }
    ///
    /// set_to_4(&set_count.into());
    /// assert_eq!(count(), 4);
    /// set_to_4(&set_double_count);
    /// assert_eq!(count(), 8);
    /// # });
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            skip_all,
            fields(
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    pub fn set(&self, value: T) {
        match &self.inner {
            SignalSetterTypes::Write(s) => s.set(value),
            SignalSetterTypes::Mapped(_, s) => s.with_value(|s| s(value)),
            SignalSetterTypes::Default => {}
        }
    }
}

impl<T> From<WriteSignal<T>> for SignalSetter<T> {
    #[track_caller]
    fn from(value: WriteSignal<T>) -> Self {
        Self {
            inner: SignalSetterTypes::Write(value),
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }
}

impl<T> From<RwSignal<T>> for SignalSetter<T> {
    #[track_caller]
    fn from(value: RwSignal<T>) -> Self {
        Self {
            inner: SignalSetterTypes::Write(value.write_only()),
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }
}

enum SignalSetterTypes<T>
where
    T: 'static,
{
    Write(WriteSignal<T>),
    Mapped(Scope, StoredValue<Box<dyn Fn(T)>>),
    Default,
}

impl<T> Clone for SignalSetterTypes<T> {
    fn clone(&self) -> Self {
        match self {
            Self::Write(arg0) => Self::Write(*arg0),
            Self::Mapped(cx, f) => Self::Mapped(*cx, *f),
            Self::Default => Self::Default,
        }
    }
}

impl<T> Copy for SignalSetterTypes<T> {}

impl<T> std::fmt::Debug for SignalSetterTypes<T>
where
    T: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Write(arg0) => {
                f.debug_tuple("WriteSignal").field(arg0).finish()
            }
            Self::Mapped(_, _) => f.debug_tuple("Mapped").finish(),
            Self::Default => f.debug_tuple("SignalSetter<Default>").finish(),
        }
    }
}

impl<T> PartialEq for SignalSetterTypes<T>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Write(l0), Self::Write(r0)) => l0 == r0,
            (Self::Mapped(_, l0), Self::Mapped(_, r0)) => std::ptr::eq(l0, r0),
            _ => false,
        }
    }
}

impl<T> Eq for SignalSetterTypes<T> where T: PartialEq {}

impl_set_fn_traits![SignalSetter];