Skip to main content

egui_kit/page/
layout.rs

1//! [`Layout`]: what wraps the pages of a router.
2
3use core::cell::Cell;
4use std::rc::Rc;
5
6use super::handler::{Handler, erase, unit};
7use super::loader::{ErasedLayoutView, LayoutReset, Loader};
8use super::view::LayoutView;
9use crate::error::Rejection;
10
11/// A layout wrapping every page of a [`Router`](crate::Router),
12/// including those of nested routers.
13///
14/// Its [view](LayoutView) gets the [`Outlet`](super::Outlet) after the `Ui`, then extractors. Render the child
15/// with [`Outlet::show`](super::Outlet::show), or animated with a [`ViewTransition`](crate::ViewTransition).
16pub struct Layout<S> {
17    pub(crate) loader: Loader<S>,
18    pub(crate) view: ErasedLayoutView<S>,
19    pub(crate) reset: Option<LayoutReset>,
20    /// Set once the layout rendered its outlet with a `ViewTransition`.
21    pub(crate) transitions: Cell<bool>,
22}
23
24impl<S: 'static> Layout<S> {
25    /// A layout without a `load` handler.
26    pub fn new<V, U>(view: V) -> Self
27    where
28        V: LayoutView<U, S, ()>,
29    {
30        Self {
31            loader: Loader::new(unit()),
32            view: Rc::new(move |ui, outlet, cx| view.call(ui, outlet, cx)),
33            reset: None,
34            transitions: Cell::new(false),
35        }
36    }
37
38    /// A layout whose view can extract the data produced by `load` (as `&mut D` or `&D`).
39    /// The loads below can read it with [`Parent`](crate::extract::Parent).
40    pub fn with_load<H, T, D, E, V, U>(load: H, view: V) -> Self
41    where
42        H: Handler<T, S, Output = Result<D, E>>,
43        D: 'static,
44        E: Into<Rejection>,
45        V: LayoutView<U, S, D>,
46    {
47        Self {
48            loader: Loader::new(erase(load)),
49            view: Rc::new(move |ui, outlet, cx| view.call(ui, outlet, cx)),
50            reset: None,
51            transitions: Cell::new(false),
52        }
53    }
54
55    /// See [`Page::depends`](super::Page::depends).
56    pub fn depends(mut self, key: impl Into<String>) -> Self {
57        self.loader.keys.push(key.into());
58        self
59    }
60
61    /// Wraps this layout in the root layout only, skipping the layouts in between.
62    pub fn reset_layouts(mut self) -> Self {
63        self.reset = Some(LayoutReset::Root);
64        self
65    }
66
67    /// Wraps this layout in the layouts up to the router [named](crate::Router::named) `name`.
68    pub fn reset_layouts_to(mut self, name: impl Into<String>) -> Self {
69        self.reset = Some(LayoutReset::To(name.into()));
70        self
71    }
72}