use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use mitsuami_reactive::{Owner, Signal, batch, effect, on_cleanup, signal, untrack};
use crate::task::{TaskHandle, current_ui, spawn_local};
pub struct Resource<T: 'static, E: 'static> {
data: Signal<Option<T>>,
error: Signal<Option<E>>,
loading: Signal<bool>,
refetches: Signal<u64>,
}
impl<T: 'static, E: 'static> Clone for Resource<T, E> {
fn clone(&self) -> Self {
*self
}
}
impl<T: 'static, E: 'static> Copy for Resource<T, E> {}
pub fn resource<T, E, Fut>(fetch: impl Fn() -> Fut + 'static) -> Resource<T, E>
where
Fut: Future<Output = Result<T, E>> + 'static,
{
resource_on(|| (), move |()| fetch())
}
pub fn resource_on<S, T, E, Fut>(source: impl Fn() -> S + 'static, fetch: impl Fn(S) -> Fut + 'static) -> Resource<T, E>
where
S: 'static,
Fut: Future<Output = Result<T, E>> + 'static,
{
let resource = Resource { data: signal(None), error: signal(None), loading: signal(false), refetches: signal(0) };
let Resource { data, error, loading, refetches } = resource;
effect(move || {
refetches.with(|_| ());
let source = source();
untrack(|| {
if !loading.get_untracked() {
loading.set(true);
}
let future = fetch(source);
spawn_local(async move {
let result = future.await;
batch(|| {
match result {
Ok(value) => {
data.set(Some(value));
if error.with_untracked(Option::is_some) {
error.set(None);
}
}
Err(e) => error.set(Some(e)),
}
loading.set(false);
});
});
});
});
resource
}
impl<T: 'static, E: 'static> Resource<T, E> {
pub fn loading(&self) -> bool {
self.loading.get()
}
pub fn data(&self) -> Option<T>
where
T: Clone,
{
self.data.get()
}
pub fn with_data<R>(&self, f: impl FnOnce(Option<&T>) -> R) -> R {
self.data.with(|data| f(data.as_ref()))
}
pub fn error(&self) -> Option<E>
where
E: Clone,
{
self.error.get()
}
pub fn with_error<R>(&self, f: impl FnOnce(Option<&E>) -> R) -> R {
self.error.with(|error| f(error.as_ref()))
}
pub fn refetch(&self) {
self.refetches.update(|n| *n += 1);
}
pub fn set_data(&self, value: T) {
self.data.set(Some(value));
}
}
type RunFn<I, O> = Rc<dyn Fn(I) -> Pin<Box<dyn Future<Output = O>>>>;
struct ActionState<I, O> {
run: RunFn<I, O>,
owner: Option<Owner>,
tasks: RefCell<HashMap<u64, TaskHandle>>,
dispatches: Cell<u64>,
}
pub struct Action<I: 'static, O: 'static> {
state: Signal<Rc<ActionState<I, O>>>,
pending: Signal<usize>,
value: Signal<Option<O>>,
}
impl<I: 'static, O: 'static> Clone for Action<I, O> {
fn clone(&self) -> Self {
*self
}
}
impl<I: 'static, O: 'static> Copy for Action<I, O> {}
pub fn action<I, O, Fut>(run: impl Fn(I) -> Fut + 'static) -> Action<I, O>
where
Fut: Future<Output = O> + 'static,
{
let state = Rc::new(ActionState {
run: Rc::new(move |input| Box::pin(run(input)) as Pin<Box<dyn Future<Output = O>>>),
owner: Owner::current(),
tasks: RefCell::default(),
dispatches: Cell::new(0),
});
let in_flight = state.clone();
on_cleanup(move || {
for (_, task) in in_flight.tasks.take() {
task.cancel();
}
});
Action { state: signal(state), pending: signal(0), value: signal(None) }
}
impl<I: 'static, O: 'static> Action<I, O> {
pub fn dispatch(&self, input: I) {
let state = self.state.get_untracked();
let future = (state.run)(input);
let number = state.dispatches.get() + 1;
state.dispatches.set(number);
let Action { pending, value, .. } = *self;
pending.update(|n| *n += 1);
let finished = state.clone();
let task = current_ui().spawn_in(
async move {
let output = future.await;
finished.tasks.borrow_mut().remove(&number);
batch(|| {
pending.update(|n| *n -= 1);
if finished.dispatches.get() == number {
value.set(Some(output));
}
});
},
state.owner,
);
state.tasks.borrow_mut().insert(number, task);
}
pub fn pending(&self) -> bool {
self.pending.get() > 0
}
pub fn value(&self) -> Option<O>
where
O: Clone,
{
self.value.get()
}
pub fn with_value<R>(&self, f: impl FnOnce(Option<&O>) -> R) -> R {
self.value.with(|value| f(value.as_ref()))
}
}