leptos-use/src/core/maybe_rw_signal.rs

95 lines
2.2 KiB
Rust
Raw Normal View History

use leptos::*;
pub enum MaybeRwSignal<T>
where
T: 'static,
{
Static(T),
2023-06-24 01:12:43 +01:00
DynamicRw(Signal<T>, WriteSignal<T>),
DynamicRead(Signal<T>),
}
impl<T: Clone> Clone for MaybeRwSignal<T> {
fn clone(&self) -> Self {
match self {
Self::Static(t) => Self::Static(t.clone()),
2023-06-24 01:12:43 +01:00
Self::DynamicRw(r, w) => Self::DynamicRw(*r, *w),
Self::DynamicRead(s) => Self::DynamicRead(*s),
}
}
}
impl<T: Copy> Copy for MaybeRwSignal<T> {}
impl<T> From<T> for MaybeRwSignal<T> {
fn from(t: T) -> Self {
Self::Static(t)
}
}
impl<T: Default> Default for MaybeRwSignal<T> {
fn default() -> Self {
Self::Static(T::default())
}
}
impl<T> From<Signal<T>> for MaybeRwSignal<T> {
fn from(s: Signal<T>) -> Self {
Self::DynamicRead(s)
}
}
impl<T> From<ReadSignal<T>> for MaybeRwSignal<T> {
fn from(s: ReadSignal<T>) -> Self {
Self::DynamicRead(s.into())
}
}
impl<T> From<Memo<T>> for MaybeRwSignal<T> {
fn from(s: Memo<T>) -> Self {
Self::DynamicRead(s.into())
}
}
impl<T> From<RwSignal<T>> for MaybeRwSignal<T> {
fn from(s: RwSignal<T>) -> Self {
let (r, w) = s.split();
2023-06-24 01:12:43 +01:00
Self::DynamicRw(r.into(), w)
}
}
impl<T> From<(ReadSignal<T>, WriteSignal<T>)> for MaybeRwSignal<T> {
fn from(s: (ReadSignal<T>, WriteSignal<T>)) -> Self {
2023-06-24 01:12:43 +01:00
Self::DynamicRw(s.0.into(), s.1)
}
}
impl<T> From<(Signal<T>, WriteSignal<T>)> for MaybeRwSignal<T> {
fn from(s: (Signal<T>, WriteSignal<T>)) -> Self {
Self::DynamicRw(s.0, s.1)
}
}
impl From<&str> for MaybeRwSignal<String> {
fn from(s: &str) -> Self {
Self::Static(s.to_string())
}
}
2023-06-24 01:12:43 +01:00
impl<T: Clone> MaybeRwSignal<T> {
pub fn to_signal(&self, cx: Scope) -> (Signal<T>, WriteSignal<T>) {
match self {
2023-06-24 01:12:43 +01:00
Self::DynamicRead(s) => {
// TODO : this feels hacky
let (_, w) = create_signal(cx, s.get_untracked());
(*s, w)
}
2023-06-24 01:12:43 +01:00
Self::DynamicRw(r, w) => (*r, *w),
Self::Static(v) => {
let (r, w) = create_signal(cx, v.clone());
(Signal::from(r), w)
}
}
}
}