Skip to content

Commit

Permalink
feat: implement From<Fn() -> T> for Signal<T> (#1801)
Browse files Browse the repository at this point in the history
  • Loading branch information
gbj committed Sep 29, 2023
1 parent d7fff5a commit 870808e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 19 deletions.
2 changes: 2 additions & 0 deletions leptos_reactive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#![cfg_attr(feature = "nightly", feature(fn_traits))]
#![cfg_attr(feature = "nightly", feature(unboxed_closures))]
#![cfg_attr(feature = "nightly", feature(type_name_of_val))]
#![cfg_attr(feature = "nightly", feature(auto_traits))]
#![cfg_attr(feature = "nightly", feature(negative_impls))]

//! The reactive system for the [Leptos](https://docs.rs/leptos/latest/leptos/) Web framework.
//!
Expand Down
49 changes: 30 additions & 19 deletions leptos_reactive/src/signal_wrappers_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,25 +428,6 @@ impl<T> From<Memo<T>> for Signal<T> {
}
}

impl<T: Clone> From<T> for Signal<T> {
#[track_caller]
fn from(value: T) -> Self {
Self {
inner: SignalTypes::DerivedSignal(store_value(Box::new(
move || value.clone(),
))),
#[cfg(any(debug_assertions, feature = "ssr"))]
defined_at: std::panic::Location::caller(),
}
}
}

impl From<&str> for Signal<String> {
fn from(value: &str) -> Self {
Self::from(value.to_string())
}
}

enum SignalTypes<T>
where
T: 'static,
Expand Down Expand Up @@ -854,6 +835,36 @@ impl From<&str> for MaybeSignal<String> {
}
}

#[cfg(feature = "nightly")]
mod from_fn_for_signals {
use super::{MaybeSignal, Memo, ReadSignal, RwSignal, Signal};
auto trait NotSignalMarker {}

impl<T> !NotSignalMarker for Signal<T> {}
impl<T> !NotSignalMarker for ReadSignal<T> {}
impl<T> !NotSignalMarker for Memo<T> {}
impl<T> !NotSignalMarker for RwSignal<T> {}
impl<T> !NotSignalMarker for MaybeSignal<T> {}

impl<F, T> From<F> for Signal<T>
where
F: Fn() -> T + NotSignalMarker + 'static,
{
fn from(value: F) -> Self {
Signal::derive(value)
}
}
}
#[cfg(not(feature = "nightly"))]
impl<F, T> From<F> for Signal<T>
where
F: Fn() -> T + 'static,
{
fn from(value: F) -> Self {
Signal::derive(value)
}
}

/// A wrapping type for an optional component prop, which can either be a signal or a
/// non-reactive value, and which may or may not have a value. In other words, this is
/// an `Option<MaybeSignal<Option<T>>>` that automatically flattens its getters.
Expand Down

0 comments on commit 870808e

Please sign in to comment.