use core::any::{Any, TypeId};
use core::cell::RefCell;
use core::future::Future;
use core::marker::PhantomData;
use core::task::Poll;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;
use crate::error::RouteError;
use crate::exec;
use crate::extract::{FromView, ViewStore};
use crate::load::Invalidation;
use crate::page::{Frame, LocalBoxFuture, ViewContext};
pub trait Query<S>: Clone + PartialEq + 'static {
type Output: 'static;
fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;
fn depends(&self) -> Vec<String> {
Vec::new()
}
}
pub trait Command<S>: 'static {
type Output: 'static;
fn run(self, state: S) -> impl Future<Output = Result<Self::Output, RouteError>> + 'static;
fn refreshes(&self) -> Vec<String> {
Vec::new()
}
}
type QueryFuture = LocalBoxFuture<Result<Rc<dyn Any>, RouteError>>;
struct QueryEntry {
query: Box<dyn Any>,
keys: Vec<String>,
value: Option<Rc<dyn Any>>,
error: Option<RouteError>,
future: Option<QueryFuture>,
stale: bool,
read: bool,
}
#[derive(Default)]
pub(crate) struct RemoteStore {
queries: RefCell<Vec<QueryEntry>>,
commands: RefCell<Vec<LocalBoxFuture<Vec<String>>>>,
}
impl RemoteStore {
fn query<S: Clone, Q: Query<S>>(
&self,
query: &Q,
state: &S,
ctx: &egui::Context,
) -> QueryState<Q::Output> {
let mut queries = self.queries.borrow_mut();
let index = queries
.iter()
.position(|entry| entry.query.downcast_ref::<Q>() == Some(query))
.unwrap_or_else(|| {
queries.push(QueryEntry {
query: Box::new(query.clone()),
keys: query.depends(),
value: None,
error: None,
future: None,
stale: true,
read: false,
});
queries.len() - 1
});
let entry = &mut queries[index];
entry.read = true;
if entry.stale {
entry.stale = false;
let future = query.clone().run(state.clone());
entry.future = Some(Box::pin(async move {
future.await.map(|value| Rc::new(value) as Rc<dyn Any>)
}));
}
if let Some(future) = &mut entry.future
&& let Poll::Ready(result) = exec::poll_once(ctx, future.as_mut())
{
entry.future = None;
match result {
Ok(value) => {
entry.value = Some(value);
entry.error = None;
}
Err(error) => entry.error = Some(error),
}
}
QueryState {
value: entry
.value
.clone()
.map(|value| value.downcast().expect("stored by type")),
error: entry.error.clone(),
loading: entry.future.is_some(),
}
}
fn refresh<Q: 'static + PartialEq>(&self, query: &Q) {
for entry in self.queries.borrow_mut().iter_mut() {
if entry.query.downcast_ref::<Q>() == Some(query) {
entry.stale = true;
entry.future = None;
}
}
}
pub(crate) fn invalidate(&self, invalidation: &Invalidation) {
for entry in self.queries.borrow_mut().iter_mut() {
if invalidation.hits(&entry.keys) {
entry.stale = true;
entry.future = None;
}
}
}
pub(crate) fn end_frame(&self) {
self.queries.borrow_mut().retain_mut(|entry| {
let read = entry.read;
entry.read = false;
read
});
}
pub(crate) fn poll_commands(&self, ctx: &egui::Context) -> Vec<String> {
let mut refreshes = Vec::new();
self.commands.borrow_mut().retain_mut(|future| {
match exec::poll_once(ctx, future.as_mut()) {
Poll::Ready(keys) => {
refreshes.extend(keys);
false
}
Poll::Pending => true,
}
});
refreshes
}
}
pub struct QueryState<T> {
value: Option<Rc<T>>,
error: Option<RouteError>,
loading: bool,
}
impl<T> QueryState<T> {
pub fn current(&self) -> Option<&T> {
self.value.as_deref()
}
pub fn error(&self) -> Option<&RouteError> {
self.error.as_ref()
}
pub fn is_loading(&self) -> bool {
self.loading
}
}
impl<T: fmt::Debug> fmt::Debug for QueryState<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueryState")
.field("current", &self.value)
.field("error", &self.error)
.field("loading", &self.loading)
.finish()
}
}
pub struct Remote<'f, S> {
frame: &'f Frame<'f>,
store: &'f ViewStore,
state: &'f S,
}
impl<S> Clone for Remote<'_, S> {
fn clone(&self) -> Self {
*self
}
}
impl<S> Copy for Remote<'_, S> {}
impl<S: 'static, D> FromView<S, D> for Remote<'_, S> {
type Item<'f> = Remote<'f, S>;
fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Remote<'f, S> {
Remote {
frame: cx.frame(),
store: cx.store(),
state: cx.state(),
}
}
}
impl<'f, S: Clone + 'static> Remote<'f, S> {
#[expect(
clippy::needless_pass_by_value,
reason = "`remote.query(SearchAuthors(prefix))` reads better than with a reference"
)]
pub fn query<Q: Query<S>>(&self, query: Q) -> QueryState<Q::Output> {
self.frame.remote.query(&query, self.state, &self.frame.ctx)
}
pub fn refresh<Q: Query<S>>(&self, query: &Q) {
self.frame.remote.refresh(query);
self.frame.ctx.request_repaint();
}
pub fn command<C: Command<S>>(&self) -> CommandHandle<'f, S, C> {
let slot = Rc::clone(
self.store
.commands
.borrow_mut()
.entry(TypeId::of::<C>())
.or_insert_with(|| Rc::new(RefCell::new(CommandSlot::<C::Output>::default()))),
);
CommandHandle {
remote: *self,
slot: slot.downcast().expect("stored by type"),
command: PhantomData,
}
}
}
struct CommandSlot<T> {
pending: usize,
output: Option<T>,
error: Option<RouteError>,
}
impl<T> Default for CommandSlot<T> {
fn default() -> Self {
Self {
pending: 0,
output: None,
error: None,
}
}
}
pub(crate) type CommandSlots = RefCell<HashMap<TypeId, Rc<dyn Any>>>;
pub struct CommandHandle<'f, S, C: Command<S>> {
remote: Remote<'f, S>,
slot: Rc<RefCell<CommandSlot<C::Output>>>,
command: PhantomData<fn(C)>,
}
impl<S: Clone + 'static, C: Command<S>> CommandHandle<'_, S, C> {
pub fn run(&self, command: C) {
if self.remote.frame.outgoing {
return;
}
let refreshes = command.refreshes();
let future = command.run(self.remote.state.clone());
let slot = Rc::clone(&self.slot);
{
let mut slot = slot.borrow_mut();
slot.pending += 1;
slot.error = None;
}
self.remote
.frame
.remote
.commands
.borrow_mut()
.push(Box::pin(async move {
let result = future.await;
let mut slot = slot.borrow_mut();
slot.pending -= 1;
match result {
Ok(output) => {
slot.output = Some(output);
refreshes
}
Err(error) => {
slot.error = Some(error);
Vec::new()
}
}
}));
self.remote.frame.ctx.request_repaint();
}
pub fn is_pending(&self) -> bool {
self.slot.borrow().pending > 0
}
pub fn take_output(&self) -> Option<C::Output> {
self.slot.borrow_mut().output.take()
}
pub fn error(&self) -> Option<RouteError> {
self.slot.borrow().error.clone()
}
}