leptos_use/
sync_signal.rs

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
378
379
380
381
382
383
384
385
386
387
388
use crate::core::UseRwSignal;
use default_struct_builder::DefaultBuilder;
use leptos::*;
use std::rc::Rc;

/// Two-way Signals synchronization.
///
/// > Note: Please consider first if you can achieve your goals with the
/// > ["Good Options" described in the Leptos book](https://book.leptos.dev/reactivity/working_with_signals.html#making-signals-depend-on-each-other)
/// > Only if you really have to, use this function. This is, in effect, the
/// > ["If you really must..." option](https://book.leptos.dev/reactivity/working_with_signals.html#if-you-really-must).
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/sync_signal)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::sync_signal;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal(1);
/// let (b, set_b) = create_signal(2);
///
/// let stop = sync_signal((a, set_a), (b, set_b));
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 1, b: 1
///
/// set_b.set(3);
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 3, b: 3
///
/// set_a.set(4);
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 4, b: 4
/// #
/// # view! { }
/// # }
/// ```
///
/// ### `RwSignal`
///
/// You can mix and match `RwSignal`s and `Signal`-`WriteSignal` pairs.
///
/// ```
/// # use leptos::*;
/// # use leptos_use::sync_signal;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal(1);
/// let (b, set_b) = create_signal(2);
/// let c_rw = create_rw_signal(3);
/// let d_rw = create_rw_signal(4);
///
/// sync_signal((a, set_a), c_rw);
/// sync_signal(d_rw, (b, set_b));
/// sync_signal(c_rw, d_rw);
///
/// #
/// # view! { }
/// # }
/// ```
///
/// ### One directional
///
/// You can synchronize a signal only from left to right or right to left.
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions, SyncDirection};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal(1);
/// let (b, set_b) = create_signal(2);
///
/// let stop = sync_signal_with_options(
///     (a, set_a),
///     (b, set_b),
///     SyncSignalOptions::default().direction(SyncDirection::LeftToRight)
/// );
///
/// set_b.set(3); // doesn't sync
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 1, b: 3
///
/// set_a.set(4);
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 4, b: 4
/// #
/// # view! { }
/// # }
/// ```
///
/// ### Custom Transform
///
/// You can optionally provide custom transforms between the two signals.
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal(10);
/// let (b, set_b) = create_signal(2);
///
/// let stop = sync_signal_with_options(
///     (a, set_a),
///     (b, set_b),
///     SyncSignalOptions::with_transforms(
///         |left| *left * 2,
///         |right| *right / 2,
///     ),
/// );
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 10, b: 20
///
/// set_b.set(30);
///
/// logging::log!("a: {}, b: {}", a.get(), b.get()); // a: 15, b: 30
/// #
/// # view! { }
/// # }
/// ```
///
/// #### Different Types
///
/// `SyncSignalOptions::default()` is only defined if the two signal types are identical.
/// Otherwise, you have to initialize the options with `with_transforms` or `with_assigns` instead
/// of `default`.
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions};
/// # use std::str::FromStr;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal("10".to_string());
/// let (b, set_b) = create_signal(2);
///
/// let stop = sync_signal_with_options(
///     (a, set_a),
///     (b, set_b),
///     SyncSignalOptions::with_transforms(
///         |left: &String| i32::from_str(left).unwrap_or_default(),
///         |right: &i32| right.to_string(),
///     ),
/// );
/// #
/// # view! { }
/// # }
/// ```
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions};
/// # use std::str::FromStr;
/// #
/// #[derive(Clone)]
/// pub struct Foo {
///     bar: i32,
/// }
///
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let (a, set_a) = create_signal(Foo { bar: 10 });
/// let (b, set_b) = create_signal(2);
///
/// let stop = sync_signal_with_options(
///     (a, set_a),
///     (b, set_b),
///     SyncSignalOptions::with_assigns(
///         |b: &mut i32, a: &Foo| *b = a.bar,
///         |a: &mut Foo, b: &i32| a.bar = *b,
///     ),
/// );
/// #
/// # view! { }
/// # }
/// ```
pub fn sync_signal<T>(
    left: impl Into<UseRwSignal<T>>,
    right: impl Into<UseRwSignal<T>>,
) -> impl Fn() + Clone
where
    T: Clone + 'static,
{
    sync_signal_with_options(left, right, SyncSignalOptions::<T, T>::default())
}

/// Version of [`sync_signal`] that takes a `SyncSignalOptions`. See [`sync_signal`] for how to use.
pub fn sync_signal_with_options<L, R>(
    left: impl Into<UseRwSignal<L>>,
    right: impl Into<UseRwSignal<R>>,
    options: SyncSignalOptions<L, R>,
) -> impl Fn() + Clone
where
    L: Clone + 'static,
    R: Clone + 'static,
{
    let SyncSignalOptions {
        immediate,
        direction,
        transforms,
    } = options;

    let (assign_ltr, assign_rtl) = transforms.assigns();

    let left = left.into();
    let right = right.into();

    let mut stop_watch_left = None;
    let mut stop_watch_right = None;

    let is_sync_update = StoredValue::new(false);

    if matches!(direction, SyncDirection::Both | SyncDirection::LeftToRight) {
        stop_watch_left = Some(watch(
            move || left.get(),
            move |new_value, _, _| {
                if !is_sync_update.get_value() {
                    is_sync_update.set_value(true);
                    right.update(|right| assign_ltr(right, new_value));
                    is_sync_update.set_value(false);
                }
            },
            immediate,
        ));
    }

    if matches!(direction, SyncDirection::Both | SyncDirection::RightToLeft) {
        stop_watch_right = Some(watch(
            move || right.get(),
            move |new_value, _, _| {
                if !is_sync_update.get_value() {
                    is_sync_update.set_value(true);
                    left.update(|left| assign_rtl(left, new_value));
                    is_sync_update.set_value(false);
                }
            },
            immediate,
        ));
    }

    move || {
        if let Some(stop_watch_left) = &stop_watch_left {
            stop_watch_left();
        }
        if let Some(stop_watch_right) = &stop_watch_right {
            stop_watch_right();
        }
    }
}

/// Direction of syncing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum SyncDirection {
    LeftToRight,
    RightToLeft,
    #[default]
    Both,
}

pub type AssignFn<T, S> = Rc<dyn Fn(&mut T, &S)>;

/// Transforms or assigns for syncing.
pub enum SyncTransforms<L, R> {
    /// Transform the signal into each other by calling the transform functions.
    /// The values are then simply assigned.
    Transforms {
        /// Transforms the left signal into the right signal.
        ltr: Rc<dyn Fn(&L) -> R>,
        /// Transforms the right signal into the left signal.
        rtl: Rc<dyn Fn(&R) -> L>,
    },

    /// Assign the signals to each other. Instead of using `=` to assign the signals,
    /// these functions are called.
    Assigns {
        /// Assigns the left signal to the right signal.
        ltr: AssignFn<R, L>,
        /// Assigns the right signal to the left signal.
        rtl: AssignFn<L, R>,
    },
}

impl<T> Default for SyncTransforms<T, T>
where
    T: Clone,
{
    fn default() -> Self {
        Self::Assigns {
            ltr: Rc::new(|right, left| *right = left.clone()),
            rtl: Rc::new(|left, right| *left = right.clone()),
        }
    }
}

impl<L, R> SyncTransforms<L, R>
where
    L: 'static,
    R: 'static,
{
    /// Returns assign functions for both directions that respect the value of this enum.
    pub fn assigns(&self) -> (AssignFn<R, L>, AssignFn<L, R>) {
        match self {
            SyncTransforms::Transforms { ltr, rtl } => {
                let ltr = Rc::clone(ltr);
                let rtl = Rc::clone(rtl);
                (
                    Rc::new(move |right, left| *right = ltr(left)),
                    Rc::new(move |left, right| *left = rtl(right)),
                )
            }
            SyncTransforms::Assigns { ltr, rtl } => (Rc::clone(ltr), Rc::clone(rtl)),
        }
    }
}

/// Options for [`sync_signal_with_options`].
#[derive(DefaultBuilder)]
pub struct SyncSignalOptions<L, R> {
    /// If `true`, the signals will be immediately synced when this function is called.
    /// If `false`, a signal is only updated when the other signal's value changes.
    /// Defaults to `true`.
    immediate: bool,

    /// Direction of syncing. Defaults to `SyncDirection::Both`.
    direction: SyncDirection,

    /// How to transform or assign the values to each other
    /// If `L` and `R` are identical this defaults to the simple `=` operator. If the types are
    /// not the same, then you have to choose to either use [`SyncSignalOptions::with_transforms`]
    /// or [`SyncSignalOptions::with_assigns`].
    #[builder(skip)]
    transforms: SyncTransforms<L, R>,
}

impl<L, R> SyncSignalOptions<L, R> {
    /// Initializes options with transforms functions that convert the signals into each other.
    pub fn with_transforms(
        transform_ltr: impl Fn(&L) -> R + 'static,
        transform_rtl: impl Fn(&R) -> L + 'static,
    ) -> Self {
        Self {
            immediate: true,
            direction: SyncDirection::Both,
            transforms: SyncTransforms::Transforms {
                ltr: Rc::new(transform_ltr),
                rtl: Rc::new(transform_rtl),
            },
        }
    }

    /// Initializes options with assign functions that replace the default `=` operator.
    pub fn with_assigns(
        assign_ltr: impl Fn(&mut R, &L) + 'static,
        assign_rtl: impl Fn(&mut L, &R) + 'static,
    ) -> Self {
        Self {
            immediate: true,
            direction: SyncDirection::Both,
            transforms: SyncTransforms::Assigns {
                ltr: Rc::new(assign_ltr),
                rtl: Rc::new(assign_rtl),
            },
        }
    }
}

impl<T> Default for SyncSignalOptions<T, T>
where
    T: Clone,
{
    fn default() -> Self {
        Self {
            immediate: true,
            direction: Default::default(),
            transforms: Default::default(),
        }
    }
}