Skip to main content

egui_kit/extract/
parent.rs

1//! [`Parent`]: the data of the layouts above a load.
2
3use core::any::type_name;
4use core::cell::{Cell, RefCell};
5use core::future::poll_fn;
6use core::task::Poll;
7use std::rc::Rc;
8
9use super::FromRequest;
10use crate::error::{Rejection, RouteError};
11use crate::load::DataCell;
12use crate::request::{Deps, Request};
13
14/// The progress of the layouts and page of a route being loaded, by level.
15pub(crate) enum Slot {
16    /// No layout at this level.
17    Empty,
18    Waiting,
19    Ready(DataCell),
20    Failed,
21}
22
23pub(crate) type Slots = Rc<RefCell<Vec<Slot>>>;
24
25/// What a load needs to wait for its parents' data.
26#[derive(Clone)]
27pub(crate) struct ParentHandle {
28    slots: Slots,
29    /// The loading node's level; its parents are the levels before.
30    index: usize,
31    deps: Rc<Cell<Deps>>,
32}
33
34impl ParentHandle {
35    pub(crate) fn new(slots: Slots, index: usize, deps: Rc<Cell<Deps>>) -> Self {
36        Self { slots, index, deps }
37    }
38}
39
40/// Access to the data loaded by the layouts above, in a layout's or page's `load`.
41///
42/// ```no_run
43/// # use egui_kit::Rejection;
44/// # use egui_kit::extract::Parent;
45/// #[derive(Clone)]
46/// struct BlogLayout { posts: Vec<String> }
47///
48/// async fn load(parent: Parent) -> Result<usize, Rejection> {
49///     let blog = parent.get::<BlogLayout>().await?;
50///     Ok(blog.posts.len())
51/// }
52/// ```
53///
54/// Using it makes the load rerun whenever a parent layout reloads.
55pub struct Parent(ParentHandle);
56
57impl<S> FromRequest<S> for Parent {
58    fn from_request(req: &Request, _state: &S) -> Result<Self, Rejection> {
59        req.parent
60            .clone()
61            .map(Parent)
62            .ok_or_else(|| RouteError::internal("`Parent` is only available in a `load`").into())
63    }
64}
65
66impl Parent {
67    /// Waits for the layouts above and returns a copy of the innermost one's data of type `T`.
68    ///
69    /// # Errors
70    ///
71    /// Fails with a 500 if no parent layout loaded a `T`, or if a parent layout failed.
72    pub async fn get<T: Clone + 'static>(&self) -> Result<T, Rejection> {
73        let handle = &self.0;
74        let mut deps = handle.deps.get();
75        deps.parent = true;
76        handle.deps.set(deps);
77
78        poll_fn(|_| {
79            let slots = handle.slots.borrow();
80            let parents = &slots[..handle.index];
81            if parents.iter().any(|slot| matches!(slot, Slot::Waiting)) {
82                // Polled again by the loader once a parent finished.
83                return Poll::Pending;
84            }
85            if parents.iter().any(|slot| matches!(slot, Slot::Failed)) {
86                return Poll::Ready(Err(
87                    RouteError::internal("a parent layout failed to load").into()
88                ));
89            }
90            let data = parents.iter().rev().find_map(|slot| match slot {
91                Slot::Ready(data) => data.borrow().downcast_ref::<T>().cloned(),
92                _ => None,
93            });
94            Poll::Ready(data.ok_or_else(|| {
95                RouteError::internal(format!("no parent layout loaded a `{}`", type_name::<T>()))
96                    .into()
97            }))
98        })
99        .await
100    }
101}