diff --git a/CHANGELOG.md b/CHANGELOG.md index c94e8e9..6150878 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] - + +### New Functions 🚀 + +- `sync_signal` + ## [0.10.6] - 2024-04-02 ### Fixes 🍕 diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index e01bce2..51ca13f 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -87,6 +87,7 @@ - [signal_debounced](reactivity/signal_debounced.md) - [signal_throttled](reactivity/signal_throttled.md) +- [sync_signal](reactivity/sync_signal.md) # Iterable diff --git a/docs/book/src/reactivity/sync_signal.md b/docs/book/src/reactivity/sync_signal.md new file mode 100644 index 0000000..0a3f77b --- /dev/null +++ b/docs/book/src/reactivity/sync_signal.md @@ -0,0 +1,3 @@ +# sync_signal + + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 3bd37f5..4d56bbf 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -5,6 +5,7 @@ members = [ "on_click_outside", "signal_debounced", "signal_throttled", + "sync_signal", "use_abs", "use_active_element", "use_and", diff --git a/examples/sync_signal/Cargo.toml b/examples/sync_signal/Cargo.toml new file mode 100644 index 0000000..0eae2b1 --- /dev/null +++ b/examples/sync_signal/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "sync_signal" +version = "0.1.0" +edition = "2021" + +[dependencies] +leptos = { version = "0.6", features = ["nightly", "csr"] } +console_error_panic_hook = "0.1" +console_log = "1" +log = "0.4" +leptos-use = { path = "../..", features = ["docs"] } +web-sys = "0.3" + +[dev-dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-test = "0.3.0" diff --git a/examples/sync_signal/README.md b/examples/sync_signal/README.md new file mode 100644 index 0000000..aab326e --- /dev/null +++ b/examples/sync_signal/README.md @@ -0,0 +1,23 @@ +A simple example for `sync_signal`. + +If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation) +as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target: + +```bash +cargo install trunk +npm install -D tailwindcss @tailwindcss/forms +rustup toolchain install nightly +rustup target add wasm32-unknown-unknown +``` + +Then, open two terminals. In the first one, run: + +``` +npx tailwindcss -i ./input.css -o ./style/output.css --watch +``` + +In the second one, run: + +```bash +trunk serve --open +``` \ No newline at end of file diff --git a/examples/sync_signal/Trunk.toml b/examples/sync_signal/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/sync_signal/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/sync_signal/index.html b/examples/sync_signal/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/sync_signal/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/sync_signal/input.css b/examples/sync_signal/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/sync_signal/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/sync_signal/rust-toolchain.toml b/examples/sync_signal/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/sync_signal/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/sync_signal/src/main.rs b/examples/sync_signal/src/main.rs new file mode 100644 index 0000000..8fdb931 --- /dev/null +++ b/examples/sync_signal/src/main.rs @@ -0,0 +1,25 @@ +use leptos::*; +use leptos_use::docs::demo_or_body; +use leptos_use::sync_signal; + +#[component] +fn Demo() -> impl IntoView { + let (a, set_a) = create_signal(String::new()); + let (b, set_b) = create_signal(String::new()); + + let _ = sync_signal((a, set_a), (b, set_b)); + + view! { + + + } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} diff --git a/examples/sync_signal/style/output.css b/examples/sync_signal/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/sync_signal/style/output.css @@ -0,0 +1,289 @@ +[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + background-color: #fff; + border-color: #6b7280; + border-width: 1px; + border-radius: 0px; + padding-top: 0.5rem; + padding-right: 0.75rem; + padding-bottom: 0.5rem; + padding-left: 0.75rem; + font-size: 1rem; + line-height: 1.5rem; + --tw-shadow: 0 0 #0000; +} + +[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus { + outline: 2px solid transparent; + outline-offset: 2px; + --tw-ring-inset: var(--tw-empty,/*!*/ /*!*/); + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: #2563eb; + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + border-color: #2563eb; +} + +input::-moz-placeholder, textarea::-moz-placeholder { + color: #6b7280; + opacity: 1; +} + +input::placeholder,textarea::placeholder { + color: #6b7280; + opacity: 1; +} + +::-webkit-datetime-edit-fields-wrapper { + padding: 0; +} + +::-webkit-date-and-time-value { + min-height: 1.5em; +} + +::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field { + padding-top: 0; + padding-bottom: 0; +} + +select { + background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e"); + background-position: right 0.5rem center; + background-repeat: no-repeat; + background-size: 1.5em 1.5em; + padding-right: 2.5rem; + -webkit-print-color-adjust: exact; + print-color-adjust: exact; +} + +[multiple] { + background-image: initial; + background-position: initial; + background-repeat: unset; + background-size: initial; + padding-right: 0.75rem; + -webkit-print-color-adjust: unset; + print-color-adjust: unset; +} + +[type='checkbox'],[type='radio'] { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + padding: 0; + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + display: inline-block; + vertical-align: middle; + background-origin: border-box; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + flex-shrink: 0; + height: 1rem; + width: 1rem; + color: #2563eb; + background-color: #fff; + border-color: #6b7280; + border-width: 1px; + --tw-shadow: 0 0 #0000; +} + +[type='checkbox'] { + border-radius: 0px; +} + +[type='radio'] { + border-radius: 100%; +} + +[type='checkbox']:focus,[type='radio']:focus { + outline: 2px solid transparent; + outline-offset: 2px; + --tw-ring-inset: var(--tw-empty,/*!*/ /*!*/); + --tw-ring-offset-width: 2px; + --tw-ring-offset-color: #fff; + --tw-ring-color: #2563eb; + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); +} + +[type='checkbox']:checked,[type='radio']:checked { + border-color: transparent; + background-color: currentColor; + background-size: 100% 100%; + background-position: center; + background-repeat: no-repeat; +} + +[type='checkbox']:checked { + background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e"); +} + +[type='radio']:checked { + background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e"); +} + +[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus { + border-color: transparent; + background-color: currentColor; +} + +[type='checkbox']:indeterminate { + background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e"); + border-color: transparent; + background-color: currentColor; + background-size: 100% 100%; + background-position: center; + background-repeat: no-repeat; +} + +[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus { + border-color: transparent; + background-color: currentColor; +} + +[type='file'] { + background: unset; + border-color: inherit; + border-width: 0; + border-radius: 0; + padding: 0; + font-size: unset; + line-height: inherit; +} + +[type='file']:focus { + outline: 1px solid ButtonText; + outline: 1px auto -webkit-focus-ring-color; +} + +*, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; +} + +::backdrop { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; +} + +.block { + display: block; +} + +.text-\[--brand-color\] { + color: var(--brand-color); +} + +.text-green-600 { + --tw-text-opacity: 1; + color: rgb(22 163 74 / var(--tw-text-opacity)); +} + +.opacity-75 { + opacity: 0.75; +} + +@media (prefers-color-scheme: dark) { + .dark\:text-green-500 { + --tw-text-opacity: 1; + color: rgb(34 197 94 / var(--tw-text-opacity)); + } +} \ No newline at end of file diff --git a/examples/sync_signal/tailwind.config.js b/examples/sync_signal/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/sync_signal/tailwind.config.js @@ -0,0 +1,15 @@ +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: { + files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"], + }, + theme: { + extend: {}, + }, + corePlugins: { + preflight: false, + }, + plugins: [ + require('@tailwindcss/forms'), + ], +} \ No newline at end of file diff --git a/src/core/mod.rs b/src/core/mod.rs index 577cf7f..3fe5ca3 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -10,6 +10,7 @@ mod size; mod ssr_safe_method; mod storage; pub(crate) mod url; +mod use_rw_signal; pub use connection_ready_state::*; pub(crate) use datetime::*; @@ -22,3 +23,4 @@ pub use position::*; pub use size::*; pub(crate) use ssr_safe_method::*; pub use storage::*; +pub use use_rw_signal::*; diff --git a/src/core/use_rw_signal.rs b/src/core/use_rw_signal.rs new file mode 100644 index 0000000..ba19a44 --- /dev/null +++ b/src/core/use_rw_signal.rs @@ -0,0 +1,171 @@ +use leptos::*; + +pub enum UseRwSignal { + Separate(Signal, WriteSignal), + Combined(RwSignal), +} + +impl From> for UseRwSignal { + fn from(s: RwSignal) -> Self { + Self::Combined(s) + } +} + +impl From<(RS, WriteSignal)> for UseRwSignal +where + RS: Into>, +{ + fn from(s: (RS, WriteSignal)) -> Self { + Self::Separate(s.0.into(), s.1) + } +} + +impl Default for UseRwSignal +where + T: Default, +{ + fn default() -> Self { + Self::Combined(Default::default()) + } +} + +impl Clone for UseRwSignal { + fn clone(&self) -> Self { + match self { + Self::Separate(s, w) => Self::Separate(s.clone(), w.clone()), + Self::Combined(s) => Self::Combined(s.clone()), + } + } +} + +impl Copy for UseRwSignal {} + +impl SignalGet for UseRwSignal +where + T: Clone, +{ + type Value = T; + + fn get(&self) -> T { + match self { + Self::Separate(s, _) => s.get(), + Self::Combined(s) => s.get(), + } + } + + fn try_get(&self) -> Option { + match self { + Self::Separate(s, _) => s.try_get(), + Self::Combined(s) => s.try_get(), + } + } +} + +impl SignalGetUntracked for UseRwSignal +where + T: Clone, +{ + type Value = T; + + fn get_untracked(&self) -> T { + match self { + Self::Separate(s, _) => s.get_untracked(), + Self::Combined(s) => s.get_untracked(), + } + } + + fn try_get_untracked(&self) -> Option { + match self { + Self::Separate(s, _) => s.try_get_untracked(), + Self::Combined(s) => s.try_get_untracked(), + } + } +} + +impl SignalWith for UseRwSignal { + type Value = T; + + fn with(&self, f: impl FnOnce(&T) -> R) -> R { + match self { + Self::Separate(s, _) => s.with(f), + Self::Combined(s) => s.with(f), + } + } + + fn try_with(&self, f: impl FnOnce(&T) -> R) -> Option { + match self { + Self::Separate(s, _) => s.try_with(f), + Self::Combined(s) => s.try_with(f), + } + } +} + +impl SignalWithUntracked for UseRwSignal { + type Value = T; + + fn with_untracked(&self, f: impl FnOnce(&T) -> R) -> R { + match self { + Self::Separate(s, _) => s.with_untracked(f), + Self::Combined(s) => s.with_untracked(f), + } + } + + fn try_with_untracked(&self, f: impl FnOnce(&T) -> R) -> Option { + match self { + Self::Separate(s, _) => s.try_with_untracked(f), + Self::Combined(s) => s.try_with_untracked(f), + } + } +} + +impl SignalSet for UseRwSignal { + type Value = T; + + fn set(&self, new_value: T) { + match *self { + Self::Separate(_, s) => s.set(new_value), + Self::Combined(s) => s.set(new_value), + } + } + + fn try_set(&self, new_value: T) -> Option { + match *self { + Self::Separate(_, s) => s.try_set(new_value), + Self::Combined(s) => s.try_set(new_value), + } + } +} + +impl SignalSetUntracked for UseRwSignal { + fn set_untracked(&self, new_value: T) { + match self { + Self::Separate(_, s) => s.set_untracked(new_value), + Self::Combined(s) => s.set_untracked(new_value), + } + } + + fn try_set_untracked(&self, new_value: T) -> Option { + match self { + Self::Separate(_, s) => s.try_set_untracked(new_value), + Self::Combined(s) => s.try_set_untracked(new_value), + } + } +} + +impl SignalUpdate for UseRwSignal { + type Value = T; + + fn update(&self, f: impl FnOnce(&mut T)) { + match self { + Self::Separate(_, s) => s.update(f), + Self::Combined(s) => s.update(f), + } + } + + fn try_update(&self, f: impl FnOnce(&mut T) -> O) -> Option { + match self { + Self::Separate(_, s) => s.try_update(f), + Self::Combined(s) => s.try_update(f), + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 1672844..58dc229 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,7 @@ mod is_none; mod is_ok; mod is_some; mod on_click_outside; +mod sync_signal; mod signal_debounced; mod signal_throttled; mod use_active_element; @@ -88,6 +89,7 @@ pub use is_none::*; pub use is_ok::*; pub use is_some::*; pub use on_click_outside::*; +pub use sync_signal::*; pub use signal_debounced::*; pub use signal_throttled::*; pub use use_active_element::*; diff --git a/src/sync_signal.rs b/src/sync_signal.rs new file mode 100644 index 0000000..d94da74 --- /dev/null +++ b/src/sync_signal.rs @@ -0,0 +1,258 @@ +use crate::core::UseRwSignal; +use default_struct_builder::DefaultBuilder; +use leptos::*; +use std::fmt::Debug; +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) +/// > firstly. Only if you really have to, use this function. This is in effect the +/// > ["If you really must..."](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::default() +/// .transform_ltr(|left| *left * 2) +/// .transform_rtl(|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! { } +/// # } +/// ``` +pub fn sync_signal( + left: impl Into>, + right: impl Into>, +) -> impl Fn() + Clone +where + T: Clone + PartialEq + 'static, +{ + sync_signal_with_options(left, right, SyncSignalOptions::default()) +} + +/// Version of [`sync_signal`] that takes a `SyncSignalOptions`. See [`sync_signal`] for how to use. +pub fn sync_signal_with_options( + left: impl Into>, + right: impl Into>, + options: SyncSignalOptions, +) -> impl Fn() + Clone +where + L: Clone + PartialEq + 'static, + R: Clone + PartialEq + 'static, +{ + let SyncSignalOptions { + immediate, + direction, + transform_ltr, + transform_rtl, + } = options; + + let left = left.into(); + let right = right.into(); + + let mut stop_watch_left = None; + let mut stop_watch_right = None; + + if matches!(direction, SyncDirection::Both | SyncDirection::LeftToRight) { + stop_watch_left = Some(watch( + move || left.get(), + move |new_value, _, _| { + let new_value = (*transform_ltr)(new_value); + + if right.with_untracked(|right| right != &new_value) { + right.update(|right| *right = new_value); + } + }, + immediate, + )); + } + + if matches!(direction, SyncDirection::Both | SyncDirection::RightToLeft) { + stop_watch_right = Some(watch( + move || right.get(), + move |new_value, _, _| { + let new_value = (*transform_rtl)(new_value); + + if left.with_untracked(|left| left != &new_value) { + left.update(|left| *left = new_value); + } + }, + 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. +pub enum SyncDirection { + LeftToRight, + RightToLeft, + Both, +} + +/// Options for [`sync_signal_with_options`]. +#[derive(DefaultBuilder)] +pub struct SyncSignalOptions { + /// 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, + + /// Transforms the left signal into the right signal. + /// Defaults to identity. + #[builder(skip)] + transform_ltr: Rc R>, + + /// Transforms the right signal into the left signal. + /// Defaults to identity. + #[builder(skip)] + transform_rtl: Rc L>, +} + +impl SyncSignalOptions { + /// Transforms the left signal into the right signal. + /// Defaults to identity. + pub fn transform_ltr(self, transform_ltr: impl Fn(&L) -> R + 'static) -> Self { + Self { + transform_ltr: Rc::new(transform_ltr), + ..self + } + } + + /// Transforms the right signal into the left signal. + /// Defaults to identity. + pub fn transform_rtl(self, transform_rtl: impl Fn(&R) -> L + 'static) -> Self { + Self { + transform_rtl: Rc::new(transform_rtl), + ..self + } + } +} + +impl Default for SyncSignalOptions { + fn default() -> Self { + Self { + immediate: true, + direction: SyncDirection::Both, + transform_ltr: Rc::new(|x| x.clone()), + transform_rtl: Rc::new(|x| x.clone()), + } + } +}