Skip to main content

egui_kit/page/
handler.rs

1//! [`Handler`]: async functions of extractors, used as `load`s and hooks.
2
3use core::any::Any;
4use core::future::{Future, ready};
5use core::pin::Pin;
6use std::rc::Rc;
7
8use crate::error::Rejection;
9use crate::extract::FromRequest;
10use crate::request::Request;
11
12pub(crate) type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
13
14/// A type-erased handler producing a value (the data of a `load`, or `()` for a hook).
15pub(crate) type ErasedHandler<S> =
16    Rc<dyn Fn(&Request, &S) -> LocalBoxFuture<Result<Box<dyn Any>, Rejection>>>;
17
18/// An async function whose arguments are all [`FromRequest`] extractors.
19///
20/// Implemented for `Fn(T1, …, T16) -> impl Future`. `T` is a tuple of
21/// the extractor types and only exists to keep the implementations apart.
22///
23/// The futures do not have to be `Send`, so browser futures (e.g. `fetch`) work on wasm.
24/// They are polled once per frame by the router and wake egui up when they make progress.
25pub trait Handler<T, S>: 'static {
26    type Output;
27    type Future: Future<Output = Self::Output> + 'static;
28
29    /// Runs the extractors and creates the handler's future.
30    ///
31    /// # Errors
32    ///
33    /// Returns the [`Rejection`] of the first extractor that fails.
34    fn call(&self, req: &Request, state: &S) -> Result<Self::Future, Rejection>;
35}
36
37macro_rules! impl_handler {
38    ($($ty:ident),*) => {
39        #[expect(
40            clippy::allow_attributes,
41            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
42        )]
43        impl<F, Fut, S, $($ty,)*> Handler<($($ty,)*), S> for F
44        where
45            F: Fn($($ty),*) -> Fut + 'static,
46            Fut: Future + 'static,
47            $($ty: FromRequest<S>,)*
48        {
49            type Output = Fut::Output;
50            type Future = Fut;
51
52            #[allow(non_snake_case, unused_variables)]
53            fn call(&self, req: &Request, state: &S) -> Result<Fut, Rejection> {
54                $(let $ty = $ty::from_request(req, state)?;)*
55                Ok(self($($ty),*))
56            }
57        }
58    };
59}
60
61crate::all_tuples!(impl_handler);
62
63/// Erases a handler returning `Result<D, E>` into one returning boxed data.
64pub(crate) fn erase<H, T, S, D, E>(handler: H) -> ErasedHandler<S>
65where
66    H: Handler<T, S, Output = Result<D, E>>,
67    D: 'static,
68    E: Into<Rejection>,
69{
70    Rc::new(move |req, state| match handler.call(req, state) {
71        Ok(fut) => Box::pin(async move {
72            fut.await
73                .map(|data| Box::new(data) as Box<dyn Any>)
74                .map_err(Into::into)
75        }),
76        Err(rejection) => Box::pin(ready(Err(rejection))),
77    })
78}
79
80/// A handler that does nothing and yields `()` as data.
81pub(crate) fn unit<S: 'static>() -> ErasedHandler<S> {
82    Rc::new(|_, _| Box::pin(ready(Ok(Box::new(()) as Box<dyn Any>))))
83}