use std::cell::RefCell;
use std::rc::Rc;
use std::task::Poll;
pub trait Prop<T: Clone + 'static> {
fn read(&self) -> T;
fn on_change(&self, callback: Box<dyn Fn()>) -> PropSubscription;
}
pub struct PropSubscription {
_cleanup: Option<Box<dyn FnOnce()>>,
}
impl PropSubscription {
pub fn noop() -> Self {
Self { _cleanup: None }
}
pub fn new(cleanup: impl FnOnce() + 'static) -> Self {
Self {
_cleanup: Some(Box::new(cleanup)),
}
}
}
impl Drop for PropSubscription {
fn drop(&mut self) {
if let Some(cleanup) = self._cleanup.take() {
cleanup();
}
}
}
impl<T: Clone + 'static> Prop<T> for T {
fn read(&self) -> T {
self.clone()
}
fn on_change(&self, _callback: Box<dyn Fn()>) -> PropSubscription {
PropSubscription::noop() }
}
impl<T: Clone + 'static> Prop<T> for auralis_signal::Signal<T> {
fn read(&self) -> T {
auralis_signal::Signal::read(self)
}
fn on_change(&self, callback: Box<dyn Fn()>) -> PropSubscription {
let id = auralis_signal::subscribe(self, std::rc::Rc::new(callback));
let sig = self.clone();
PropSubscription::new(move || {
auralis_signal::unsubscribe(&sig, id);
})
}
}
impl<T: Clone + 'static> Prop<T> for std::rc::Rc<T> {
fn read(&self) -> T {
(**self).clone()
}
fn on_change(&self, _callback: Box<dyn Fn()>) -> PropSubscription {
PropSubscription::noop()
}
}
impl Prop<String> for &str {
fn read(&self) -> String {
self.to_string()
}
fn on_change(&self, _callback: Box<dyn Fn()>) -> PropSubscription {
PropSubscription::noop()
}
}
pub fn until_change<T: Clone + 'static>(prop: &impl Prop<T>) -> PropChangeFuture<T> {
PropChangeFuture {
prop_value: Some(prop.read()),
_subscription: None,
waker: Rc::new(RefCell::new(None)),
}
}
pub struct PropChangeFuture<T: Clone + 'static> {
prop_value: Option<T>,
_subscription: Option<PropSubscription>,
#[allow(dead_code)]
waker: Rc<RefCell<Option<std::task::Waker>>>,
}
impl<T: Clone + 'static + std::marker::Unpin> std::future::Future for PropChangeFuture<T> {
type Output = T;
fn poll(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let this = self.get_mut();
if let Some(val) = this.prop_value.take() {
Poll::Ready(val)
} else {
Poll::Pending
}
}
}