Просмотр исходного кода

erase the original readable type

Evan Almloff 1 год назад
Родитель
Сommit
8689509eb5

+ 2 - 3
packages/signals/examples/map_signal.rs

@@ -1,7 +1,6 @@
 #![allow(non_snake_case)]
 
 use dioxus::prelude::*;
-use dioxus_signals::Signal;
 
 fn main() {
     launch(app);
@@ -34,12 +33,12 @@ fn app() -> Element {
 }
 
 #[component]
-fn Child(count: MappedSignal<i32, Signal<Vec<i32>>>) -> Element {
+fn Child(count: MappedSignal<i32>) -> Element {
     use_memo({
         to_owned![count];
         move || {
             let value = count.read();
-            print!("Child value: {value}");
+            println!("Child value: {value}");
         }
     });
 

+ 4 - 17
packages/signals/src/copy_value.rs

@@ -13,6 +13,7 @@ use dioxus_core::ScopeId;
 
 use generational_box::{GenerationalBox, Owner, Storage};
 
+use crate::ReadableRef;
 use crate::Writable;
 use crate::{ReactiveContext, Readable};
 
@@ -206,27 +207,13 @@ impl<T: 'static, S: Storage<T>> CopyValue<T, S> {
 
 impl<T: 'static, S: Storage<T>> Readable for CopyValue<T, S> {
     type Target = T;
-    type Ref<R: ?Sized + 'static> = S::Ref<R>;
+    type Storage = S;
 
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        S::map(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        S::try_map(ref_, f)
-    }
-
-    fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
         self.value.try_read()
     }
 
-    fn peek(&self) -> Self::Ref<T> {
+    fn peek(&self) -> ReadableRef<Self> {
         self.value.read()
     }
 }

+ 5 - 19
packages/signals/src/global/memo.rs

@@ -1,6 +1,6 @@
-use crate::read::Readable;
+use crate::{read::Readable, ReadableRef};
 use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
-use generational_box::{AnyStorage, UnsyncStorage};
+use generational_box::UnsyncStorage;
 use std::{mem::MaybeUninit, ops::Deref};
 
 use crate::{ReadOnlySignal, Signal};
@@ -53,29 +53,15 @@ impl<T: PartialEq + 'static> GlobalMemo<T> {
 
 impl<T: PartialEq + 'static> Readable for GlobalMemo<T> {
     type Target = T;
-    type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
-
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        <UnsyncStorage as AnyStorage>::map(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        <UnsyncStorage as AnyStorage>::try_map(ref_, f)
-    }
+    type Storage = UnsyncStorage;
 
     #[track_caller]
-    fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
         self.signal().try_read()
     }
 
     #[track_caller]
-    fn peek(&self) -> Self::Ref<T> {
+    fn peek(&self) -> ReadableRef<Self> {
         self.signal().peek()
     }
 }

+ 5 - 19
packages/signals/src/global/signal.rs

@@ -1,8 +1,8 @@
-use crate::read::Readable;
 use crate::write::Writable;
 use crate::Write;
+use crate::{read::Readable, ReadableRef};
 use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
-use generational_box::{AnyStorage, UnsyncStorage};
+use generational_box::UnsyncStorage;
 use std::{mem::MaybeUninit, ops::Deref};
 
 use super::get_global_context;
@@ -68,29 +68,15 @@ impl<T: 'static> GlobalSignal<T> {
 
 impl<T: 'static> Readable for GlobalSignal<T> {
     type Target = T;
-    type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
-
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        <UnsyncStorage as AnyStorage>::map(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        <UnsyncStorage as AnyStorage>::try_map(ref_, f)
-    }
+    type Storage = UnsyncStorage;
 
     #[track_caller]
-    fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
         self.signal().try_read()
     }
 
     #[track_caller]
-    fn peek(&self) -> Self::Ref<T> {
+    fn peek(&self) -> ReadableRef<Self> {
         self.signal().peek()
     }
 }

+ 2 - 2
packages/signals/src/impls.rs

@@ -3,7 +3,7 @@ use crate::read::Readable;
 use crate::signal::Signal;
 use crate::write::Writable;
 use crate::{GlobalMemo, GlobalSignal, MappedSignal, ReadOnlySignal, SignalData};
-use generational_box::Storage;
+use generational_box::{AnyStorage, Storage};
 
 use std::{
     fmt::{Debug, Display},
@@ -164,4 +164,4 @@ default_impl!(GlobalSignal);
 
 read_impls!(GlobalMemo: PartialEq);
 
-read_impls!(MappedSignal, S: Readable, S: Readable);
+read_impls!(MappedSignal, S: AnyStorage, S: AnyStorage);

+ 30 - 45
packages/signals/src/map.rs

@@ -1,97 +1,82 @@
 use std::{ops::Deref, rc::Rc};
 
-use crate::read::Readable;
+use crate::{read::Readable, ReadableRef};
 use dioxus_core::prelude::*;
+use generational_box::{AnyStorage, UnsyncStorage};
 
 /// A read only signal that has been mapped to a new type.
-pub struct MappedSignal<O: ?Sized + 'static, R: Readable> {
-    readable: R,
-    mapping: Rc<dyn Fn(&R::Target) -> &O + 'static>,
+pub struct MappedSignal<O: ?Sized + 'static, S: AnyStorage = UnsyncStorage> {
+    try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
+    peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
 }
 
-impl<O: ?Sized, R: Readable + Clone> Clone for MappedSignal<O, R> {
+impl<O: ?Sized, S: AnyStorage> Clone for MappedSignal<O, S> {
     fn clone(&self) -> Self {
         MappedSignal {
-            readable: self.readable.clone(),
-            mapping: self.mapping.clone(),
+            try_read: self.try_read.clone(),
+            peek: self.peek.clone(),
         }
     }
 }
 
-impl<O, R> MappedSignal<O, R>
+impl<O, S> MappedSignal<O, S>
 where
     O: ?Sized,
-    R: Readable + 'static,
+    S: AnyStorage,
 {
     /// Create a new mapped signal.
-    pub(crate) fn new(readable: R, mapping: impl Fn(&R::Target) -> &O + 'static) -> Self {
-        MappedSignal {
-            readable,
-            mapping: Rc::new(mapping),
-        }
+    pub(crate) fn new(
+        try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
+        peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
+    ) -> Self {
+        MappedSignal { try_read, peek }
     }
 }
 
-impl<O, R> Readable for MappedSignal<O, R>
+impl<O, S> Readable for MappedSignal<O, S>
 where
     O: ?Sized,
-    R: Readable,
+    S: AnyStorage,
 {
     type Target = O;
-    type Ref<J: ?Sized + 'static> = R::Ref<J>;
-
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        R::map_ref(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        R::try_map_ref(ref_, f)
-    }
+    type Storage = S;
 
-    fn try_read(&self) -> Result<Self::Ref<O>, generational_box::BorrowError> {
-        self.readable
-            .try_read()
-            .map(|ref_| R::map_ref(ref_, |r| (self.mapping)(r)))
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
+        (self.try_read)()
     }
 
-    fn peek(&self) -> Self::Ref<Self::Target> {
-        R::map_ref(self.readable.peek(), |r| (self.mapping)(r))
+    fn peek(&self) -> ReadableRef<Self> {
+        (self.peek)()
     }
 }
 
-impl<O, R> IntoAttributeValue for MappedSignal<O, R>
+impl<O, S> IntoAttributeValue for MappedSignal<O, S>
 where
-    O: Clone + IntoAttributeValue + ?Sized,
-    R: Readable + 'static,
+    O: Clone + IntoAttributeValue,
+    S: AnyStorage,
 {
     fn into_value(self) -> dioxus_core::AttributeValue {
         self.with(|f| f.clone().into_value())
     }
 }
 
-impl<O, R> PartialEq for MappedSignal<O, R>
+impl<O, S> PartialEq for MappedSignal<O, S>
 where
     O: ?Sized,
-    R: PartialEq + Readable + 'static,
+    S: AnyStorage,
 {
     fn eq(&self, other: &Self) -> bool {
-        self.readable == other.readable && std::ptr::eq(&self.mapping, &other.mapping)
+        std::ptr::eq(&self.peek, &other.peek) && std::ptr::eq(&self.try_read, &other.try_read)
     }
 }
 
 /// Allow calling a signal with signal() syntax
 ///
 /// Currently only limited to copy types, though could probably specialize for string/arc/rc
-impl<O, R> Deref for MappedSignal<O, R>
+impl<O, S> Deref for MappedSignal<O, S>
 where
     O: Clone,
-    R: Readable + 'static,
+    S: AnyStorage + 'static,
 {
     type Target = dyn Fn() -> O;
 

+ 44 - 35
packages/signals/src/read.rs

@@ -1,47 +1,56 @@
-use std::{
-    mem::MaybeUninit,
-    ops::{Deref, Index},
-};
+use std::{mem::MaybeUninit, ops::Index, rc::Rc};
+
+use generational_box::AnyStorage;
 
 use crate::MappedSignal;
 
+/// A reference to a value that can be read from.
+#[allow(type_alias_bounds)]
+pub type ReadableRef<T: Readable, O = <T as Readable>::Target> = <T::Storage as AnyStorage>::Ref<O>;
+
 /// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadOnlySignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type.
 pub trait Readable {
     /// The target type of the reference.
     type Target: ?Sized + 'static;
 
-    /// The type of the reference.
-    type Ref<R: ?Sized + 'static>: Deref<Target = R> + 'static;
-
-    /// Map the reference to a new type.
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F)
-        -> Self::Ref<U>;
-
-    /// Try to map the reference to a new type.
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>>;
-
-    /// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
-    fn try_read(&self) -> Result<Self::Ref<Self::Target>, generational_box::BorrowError>;
+    /// The type of the storage this readable uses.
+    type Storage: AnyStorage;
 
     /// Map the readable type to a new type.
-    fn map<O>(self, f: impl Fn(&Self::Target) -> &O + 'static) -> MappedSignal<O, Self>
+    fn map<O>(self, f: impl Fn(&Self::Target) -> &O + 'static) -> MappedSignal<O, Self::Storage>
     where
-        Self: Sized + 'static,
+        Self: Clone + Sized + 'static,
     {
-        MappedSignal::new(self, f)
+        let mapping = Rc::new(f);
+        let try_read = Rc::new({
+            let self_ = self.clone();
+            let mapping = mapping.clone();
+            move || {
+                self_
+                    .try_read()
+                    .map(|ref_| <Self::Storage as AnyStorage>::map(ref_, |r| mapping(r)))
+            }
+        })
+            as Rc<
+                dyn Fn() -> Result<ReadableRef<Self, O>, generational_box::BorrowError> + 'static,
+            >;
+        let peek = Rc::new(move || <Self::Storage as AnyStorage>::map(self.peek(), |r| mapping(r)))
+            as Rc<dyn Fn() -> ReadableRef<Self, O> + 'static>;
+        MappedSignal::new(try_read, peek)
     }
 
     /// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
     #[track_caller]
-    fn read(&self) -> Self::Ref<Self::Target> {
+    fn read(&self) -> ReadableRef<Self> {
         self.try_read().unwrap()
     }
 
+    /// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic.
+    #[track_caller]
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError>;
+
     /// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic.
-    fn peek(&self) -> Self::Ref<Self::Target>;
+    fn peek(&self) -> ReadableRef<Self>;
 
     /// Clone the inner value and return it. If the value has been dropped, this will panic.
     #[track_caller]
@@ -66,11 +75,11 @@ pub trait Readable {
 
     /// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic.
     #[track_caller]
-    fn index<I>(&self, index: I) -> Self::Ref<<Self::Target as std::ops::Index<I>>::Output>
+    fn index<I>(&self, index: I) -> ReadableRef<Self, <Self::Target as std::ops::Index<I>>::Output>
     where
         Self::Target: std::ops::Index<I>,
     {
-        Self::map_ref(self.read(), |v| v.index(index))
+        <Self::Storage as AnyStorage>::map(self.read(), |v| v.index(index))
     }
 
     #[doc(hidden)]
@@ -124,20 +133,20 @@ pub trait ReadableVecExt<T: 'static>: Readable<Target = Vec<T>> {
 
     /// Get the first element of the inner vector.
     #[track_caller]
-    fn first(&self) -> Option<Self::Ref<T>> {
-        Self::try_map_ref(self.read(), |v| v.first())
+    fn first(&self) -> Option<ReadableRef<Self, T>> {
+        <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.first())
     }
 
     /// Get the last element of the inner vector.
     #[track_caller]
-    fn last(&self) -> Option<Self::Ref<T>> {
-        Self::try_map_ref(self.read(), |v| v.last())
+    fn last(&self) -> Option<ReadableRef<Self, T>> {
+        <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.last())
     }
 
     /// Get the element at the given index of the inner vector.
     #[track_caller]
-    fn get(&self, index: usize) -> Option<Self::Ref<T>> {
-        Self::try_map_ref(self.read(), |v| v.get(index))
+    fn get(&self, index: usize) -> Option<ReadableRef<Self, T>> {
+        <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(index))
     }
 
     /// Get an iterator over the values of the inner vector.
@@ -160,7 +169,7 @@ pub struct ReadableValueIterator<'a, R> {
 }
 
 impl<'a, T: 'static, R: Readable<Target = Vec<T>>> Iterator for ReadableValueIterator<'a, R> {
-    type Item = R::Ref<T>;
+    type Item = ReadableRef<R, T>;
 
     fn next(&mut self) -> Option<Self::Item> {
         let index = self.index;
@@ -189,8 +198,8 @@ pub trait ReadableOptionExt<T: 'static>: Readable<Target = Option<T>> {
 
     /// Attempts to read the inner value of the Option.
     #[track_caller]
-    fn as_ref(&self) -> Option<Self::Ref<T>> {
-        Self::try_map_ref(self.read(), |v| v.as_ref())
+    fn as_ref(&self) -> Option<ReadableRef<Self, T>> {
+        <Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref())
     }
 }
 

+ 3 - 17
packages/signals/src/read_only_signal.rs

@@ -1,4 +1,4 @@
-use crate::{read::Readable, Signal, SignalData};
+use crate::{read::Readable, ReadableRef, Signal, SignalData};
 use std::ops::Deref;
 
 use dioxus_core::{prelude::IntoAttributeValue, ScopeId};
@@ -56,24 +56,10 @@ impl<T: 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
 
 impl<T, S: Storage<SignalData<T>>> Readable for ReadOnlySignal<T, S> {
     type Target = T;
-    type Ref<R: ?Sized + 'static> = S::Ref<R>;
-
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        S::map(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        S::try_map(ref_, f)
-    }
+    type Storage = S;
 
     #[track_caller]
-    fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
         self.inner.try_read()
     }
 

+ 4 - 18
packages/signals/src/signal.rs

@@ -1,6 +1,6 @@
 use crate::{
     read::Readable, write::Writable, CopyValue, GlobalMemo, GlobalSignal, ReactiveContext,
-    ReadOnlySignal,
+    ReadOnlySignal, ReadableRef,
 };
 use dioxus_core::{
     prelude::{flush_sync, spawn, IntoAttributeValue},
@@ -195,24 +195,10 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
 
 impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
     type Target = T;
-    type Ref<R: ?Sized + 'static> = S::Ref<R>;
-
-    fn map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> &U>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Self::Ref<U> {
-        S::map(ref_, f)
-    }
-
-    fn try_map_ref<I: ?Sized, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
-        ref_: Self::Ref<I>,
-        f: F,
-    ) -> Option<Self::Ref<U>> {
-        S::try_map(ref_, f)
-    }
+    type Storage = S;
 
     #[track_caller]
-    fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
+    fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
         let inner = self.inner.try_read()?;
 
         let reactive_context = ReactiveContext::current();
@@ -224,7 +210,7 @@ impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
     /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
     ///
     /// If the signal has been dropped, this will panic.
-    fn peek(&self) -> S::Ref<T> {
+    fn peek(&self) -> ReadableRef<Self> {
         let inner = self.inner.read();
         S::map(inner, |v| &v.value)
     }