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
use std::ops::Deref;
use std::rc::Rc;
use yew::prelude::*;
struct UseStatePtrEqReducer<T> {
value: Rc<T>,
}
impl<T> Reducible for UseStatePtrEqReducer<T> {
type Action = T;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
Rc::new(Self {
value: action.into(),
})
}
}
impl<T> PartialEq for UseStatePtrEqReducer<T> {
fn eq(&self, rhs: &Self) -> bool {
// Check if the two `Rc`s point to the same allocation, instead of PartialEq of the values.
Rc::ptr_eq(&self.value, &rhs.value)
}
}
/// State handle for the [`use_state_ptr_eq`] hook.
pub struct UseStatePtrEqHandle<T> {
inner: UseReducerHandle<UseStatePtrEqReducer<T>>,
}
impl<T> UseStatePtrEqHandle<T> {
/// Replaces the value
pub fn set(&self, value: T) {
self.inner.dispatch(value);
}
}
impl<T> Deref for UseStatePtrEqHandle<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&(*self.inner).value
}
}
impl<T> Clone for UseStatePtrEqHandle<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> PartialEq for UseStatePtrEqHandle<T>
where
T: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
*self.inner == *rhs.inner
}
}
/// Similar to `use_state_eq`, but check if the two `Rc`s of values point to the same allocation,
/// instead of PartialEq of the values.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(UseStatePtrEq)]
/// fn state_ptr_eq() -> Html {
/// let state = use_state_ptr_eq(|| "".to_string());
///
/// let onclick = {
/// let state = state.clone();
/// Callback::from(move |_| {
/// state.set("Hello, world!".to_string());
/// })
/// };
///
/// html! {
/// <>
/// <button {onclick}>{ "Hello, world!" }</button>
/// <p>
/// <b>{ "Current value: " }</b>
/// { &*state }
/// </p>
/// </>
/// }
/// }
/// ```
#[hook]
pub fn use_state_ptr_eq<T, F>(init_fn: F) -> UseStatePtrEqHandle<T>
where
T: 'static,
F: FnOnce() -> T,
{
let handle = use_reducer_eq(move || UseStatePtrEqReducer {
value: Rc::new(init_fn()),
});
UseStatePtrEqHandle { inner: handle }
}