use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use crate::tasks::spawn_cancelable;
use super::runtime::NodeId;
use super::signal::RwSignal;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResourceState<T> {
Loading,
Ready(T),
Error(String),
}
impl<T> ResourceState<T> {
pub fn is_loading(&self) -> bool {
matches!(self, ResourceState::Loading)
}
pub fn is_ready(&self) -> bool {
matches!(self, ResourceState::Ready(_))
}
pub fn is_error(&self) -> bool {
matches!(self, ResourceState::Error(_))
}
}
pub struct Resource<T: Clone + 'static> {
state: RwSignal<ResourceState<T>>,
}
impl<T: Clone + 'static> Copy for Resource<T> {}
impl<T: Clone + 'static> Clone for Resource<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: Clone + 'static> Resource<T> {
#[doc(hidden)]
pub fn from_state(state: RwSignal<ResourceState<T>>) -> Self {
Self { state }
}
pub fn state(&self) -> ResourceState<T> {
self.state.get()
}
pub fn get(&self) -> Option<T> {
match self.state.get() {
ResourceState::Ready(v) => Some(v),
_ => None,
}
}
pub fn loading(&self) -> bool {
matches!(self.state.get(), ResourceState::Loading)
}
pub fn error(&self) -> Option<String> {
match self.state.get() {
ResourceState::Error(e) => Some(e),
_ => None,
}
}
}
pub fn resource<T, F, Fut>(fetcher: F) -> Resource<T>
where
T: Clone + 'static,
F: Fn() -> Fut + 'static,
Fut: Future<Output = Result<T, String>> + 'static,
{
let state = RwSignal::new(ResourceState::Loading);
let generation = Rc::new(Cell::new(0u64));
let fetcher = Rc::new(fetcher);
let mut pending: Option<crate::lifetime::Cancellation> = None;
super::effect::effect(move || {
let node = super::current_tracker().expect("resource effect must run under a tracker");
if let Some(previous) = pending.take() {
previous.cancel();
}
let my_gen = generation.get().wrapping_add(1);
generation.set(my_gen);
let fut = (fetcher)();
state.update_untracked(|s| *s = ResourceState::Loading);
pending = Some(spawn_cancelable(ScopedFetch {
node,
my_gen,
generation: generation.clone(),
state,
fut: Box::pin(fut),
}));
});
Resource { state }
}
struct ScopedFetch<T: Clone + 'static> {
node: NodeId,
my_gen: u64,
generation: Rc<Cell<u64>>,
state: RwSignal<ResourceState<T>>,
fut: Pin<Box<dyn Future<Output = Result<T, String>>>>,
}
impl<T: Clone + 'static> Future for ScopedFetch<T> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let this = self.get_mut();
if this.generation.get() != this.my_gen {
return Poll::Ready(());
}
let node = this.node;
let fut = &mut this.fut;
let poll = super::with_observer(node, || fut.as_mut().poll(cx));
match poll {
Poll::Pending => Poll::Pending,
Poll::Ready(result) => {
if this.generation.get() == this.my_gen {
this.state.set(match result {
Ok(v) => ResourceState::Ready(v),
Err(e) => ResourceState::Error(e),
});
}
Poll::Ready(())
}
}
}
}
pub fn resource_sync<T, F>(fetcher: F) -> Resource<T>
where
T: Clone + 'static,
F: FnOnce() -> Result<T, String>,
{
let state = RwSignal::new(match super::untrack(fetcher) {
Ok(v) => ResourceState::Ready(v),
Err(e) => ResourceState::Error(e),
});
Resource { state }
}