2021-10-04 14:22:20 +00:00
|
|
|
use std::{
|
2022-01-07 16:51:25 +00:00
|
|
|
cell::{Ref, RefCell, RefMut},
|
2021-10-04 14:22:20 +00:00
|
|
|
rc::Rc,
|
|
|
|
};
|
2021-09-21 16:11:04 +00:00
|
|
|
|
2021-12-14 07:27:59 +00:00
|
|
|
use dioxus_core::ScopeState;
|
2021-09-21 16:11:04 +00:00
|
|
|
|
2022-01-07 05:56:43 +00:00
|
|
|
pub fn use_ref<'a, T: 'static>(cx: &'a ScopeState, f: impl FnOnce() -> T) -> &'a UseRef<T> {
|
2022-01-08 14:32:53 +00:00
|
|
|
cx.use_hook(|_| UseRef {
|
2022-01-02 07:15:04 +00:00
|
|
|
update_callback: cx.schedule_update(),
|
2022-01-07 05:56:43 +00:00
|
|
|
value: Rc::new(RefCell::new(f())),
|
2022-01-08 14:32:53 +00:00
|
|
|
})
|
2021-10-04 14:22:20 +00:00
|
|
|
}
|
|
|
|
|
2022-01-07 05:56:43 +00:00
|
|
|
pub struct UseRef<T> {
|
2021-10-04 14:22:20 +00:00
|
|
|
update_callback: Rc<dyn Fn()>,
|
2022-01-07 05:56:43 +00:00
|
|
|
value: Rc<RefCell<T>>,
|
2021-09-21 16:11:04 +00:00
|
|
|
}
|
|
|
|
|
2022-01-07 05:56:43 +00:00
|
|
|
impl<T> UseRef<T> {
|
2021-09-21 16:11:04 +00:00
|
|
|
pub fn read(&self) -> Ref<'_, T> {
|
2022-01-07 05:56:43 +00:00
|
|
|
self.value.borrow()
|
2021-09-21 16:11:04 +00:00
|
|
|
}
|
|
|
|
|
2021-11-19 05:49:04 +00:00
|
|
|
pub fn set(&self, new: T) {
|
2022-01-07 05:56:43 +00:00
|
|
|
*self.value.borrow_mut() = new;
|
2021-11-19 05:49:04 +00:00
|
|
|
self.needs_update();
|
|
|
|
}
|
|
|
|
|
2021-09-21 16:11:04 +00:00
|
|
|
pub fn read_write(&self) -> (Ref<'_, T>, &Self) {
|
|
|
|
(self.read(), self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Calling "write" will force the component to re-render
|
|
|
|
pub fn write(&self) -> RefMut<'_, T> {
|
2021-10-04 14:22:20 +00:00
|
|
|
self.needs_update();
|
2022-01-07 05:56:43 +00:00
|
|
|
self.value.borrow_mut()
|
2021-09-21 16:11:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Allows the ability to write the value without forcing a re-render
|
|
|
|
pub fn write_silent(&self) -> RefMut<'_, T> {
|
2022-01-07 05:56:43 +00:00
|
|
|
self.value.borrow_mut()
|
2021-10-04 14:22:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn needs_update(&self) {
|
2022-01-07 05:56:43 +00:00
|
|
|
(self.update_callback)();
|
2021-09-21 16:11:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-07 05:56:43 +00:00
|
|
|
impl<T> Clone for UseRef<T> {
|
2021-09-21 16:11:04 +00:00
|
|
|
fn clone(&self) -> Self {
|
2022-01-07 05:56:43 +00:00
|
|
|
Self {
|
|
|
|
update_callback: self.update_callback.clone(),
|
|
|
|
value: self.value.clone(),
|
|
|
|
}
|
2021-09-21 16:11:04 +00:00
|
|
|
}
|
|
|
|
}
|