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 [`Children`](super::Children) after the `Ui`, then extractors. Render the child
15/// with [`Children::show`](super::Children::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 children with a `ViewTransition`.
21    pub(crate) transitions: Cell<bool>,
22    /// Whether the view takes its data as `&mut D`, which keeps the views below from reading it.
23    pub(crate) data_mut: bool,
24}
25
26impl<S: 'static> Layout<S> {
27    /// A layout without a `load` handler.
28    pub fn new<V, U>(view: V) -> Self
29    where
30        V: LayoutView<U, S, ()>,
31    {
32        Self {
33            loader: Loader::new(unit()),
34            data_mut: view.borrows_data_mut(),
35            view: Rc::new(move |ui, children, cx| view.call(ui, children, cx)),
36            reset: None,
37            transitions: Cell::new(false),
38        }
39    }
40
41    /// A layout whose view can extract the data produced by `load` (as `&mut D` or `&D`).
42    /// The loads below can read it with [`Parent`](crate::extract::Parent), and the views below
43    /// with [`LayoutData`](crate::extract::LayoutData) unless this view takes it as `&mut D`.
44    pub fn with_load<H, T, D, E, V, U>(load: H, view: V) -> Self
45    where
46        H: Handler<T, S, Output = Result<D, E>>,
47        D: 'static,
48        E: Into<Rejection>,
49        V: LayoutView<U, S, D>,
50    {
51        Self {
52            loader: Loader::new(erase(load)),
53            data_mut: view.borrows_data_mut(),
54            view: Rc::new(move |ui, children, cx| view.call(ui, children, cx)),
55            reset: None,
56            transitions: Cell::new(false),
57        }
58    }
59
60    /// See [`Page::depends`](super::Page::depends).
61    pub fn depends(mut self, key: impl Into<String>) -> Self {
62        self.loader.keys.push(key.into());
63        self
64    }
65
66    /// Wraps this layout in the root layout only, skipping the layouts in between.
67    pub fn reset_layouts(mut self) -> Self {
68        self.reset = Some(LayoutReset::Root);
69        self
70    }
71
72    /// Wraps this layout in the layouts up to the router [named](crate::Router::named) `name`.
73    pub fn reset_layouts_to(mut self, name: impl Into<String>) -> Self {
74        self.reset = Some(LayoutReset::To(name.into()));
75        self
76    }
77}