Skip to main content

egui_kit/page/
view.rs

1//! Views: functions of a `&mut Ui` and [extractors](crate::extract), the view-side twin of
2//! [`Handler`](super::Handler).
3
4use core::any::Any;
5use core::cell::{Cell, RefCell};
6
7use egui::Ui;
8
9use crate::extract::{FromView, Nav, NavState, PageScroll, ViewStore};
10use crate::load::Loaded;
11use crate::navigation::Navigation;
12use crate::request::Request;
13use crate::transition::TransitionHandle;
14
15/// What all views of a page share during a frame.
16pub(crate) struct Frame<'a> {
17    pub(crate) request: &'a Request,
18    pub(crate) url: &'a str,
19    pub(crate) ctx: egui::Context,
20    pub(crate) history_state: Option<&'a (dyn Any + 'static)>,
21    pub(crate) navigation: &'a Navigation,
22    pub(crate) page_id: u64,
23    pub(crate) scroll: &'a PageScroll,
24    /// Whether this is the previous page, drawn while a transition animates it out.
25    pub(crate) outgoing: bool,
26    pub(crate) nav: &'a RefCell<NavState>,
27}
28
29/// The data of a view: shared for layouts whose view doesn't take it as `&mut D`, so that the
30/// views below can read it too.
31pub(crate) enum ViewData<'a> {
32    Mut(&'a mut (dyn Any + 'static)),
33    Shared(&'a (dyn Any + 'static)),
34}
35
36/// What a view's extractors are extracted from: the app state, the page and the view's data.
37pub struct ViewContext<'a, S> {
38    state: &'a S,
39    frame: &'a Frame<'a>,
40    /// The data of the view, until an extractor takes it.
41    data: Cell<Option<ViewData<'a>>>,
42    store: &'a ViewStore,
43    /// The data of the layouts around the view, outermost first.
44    layouts: &'a [Option<Loaded>],
45}
46
47impl<'a, S> ViewContext<'a, S> {
48    pub(crate) fn new(
49        state: &'a S,
50        frame: &'a Frame<'a>,
51        data: ViewData<'a>,
52        store: &'a ViewStore,
53        layouts: &'a [Option<Loaded>],
54    ) -> Self {
55        Self {
56            state,
57            frame,
58            data: Cell::new(Some(data)),
59            store,
60            layouts,
61        }
62    }
63
64    pub fn state(&self) -> &S {
65        self.state
66    }
67
68    pub fn nav(&self) -> Nav<'_> {
69        Nav { frame: self.frame }
70    }
71
72    pub(crate) fn frame(&self) -> &Frame<'a> {
73        self.frame
74    }
75
76    /// The page state and snapshots of the view's page or layout.
77    pub(crate) fn store(&self) -> &'a ViewStore {
78        self.store
79    }
80
81    /// Lets `f` read the view's data, before an extractor takes it.
82    pub(crate) fn peek_data<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
83        let data = self
84            .data
85            .take()
86            .expect("egui-kit: the view's data was already extracted (this is a bug)");
87        let result = f(match &data {
88            ViewData::Mut(data) => &**data,
89            ViewData::Shared(data) => *data,
90        });
91        self.data.set(Some(data));
92        result
93    }
94
95    /// Takes the view's data; it can only be extracted once.
96    pub(crate) fn take_data(&self) -> &'a (dyn Any + 'static) {
97        match self.take() {
98            ViewData::Mut(data) => data,
99            ViewData::Shared(data) => data,
100        }
101    }
102
103    /// Takes the view's data mutably; it can only be extracted once.
104    pub(crate) fn take_data_mut(&self) -> &'a mut (dyn Any + 'static) {
105        match self.take() {
106            ViewData::Mut(data) => data,
107            ViewData::Shared(_) => panic!("egui-kit: the data is shared (this is a bug)"),
108        }
109    }
110
111    fn take(&self) -> ViewData<'a> {
112        self.data
113            .take()
114            .expect("egui-kit: a view can only extract its data once")
115    }
116
117    /// The data of the layouts around the view, outermost first.
118    pub(crate) fn layouts(&self) -> &'a [Option<Loaded>] {
119        self.layouts
120    }
121}
122
123/// A page or error view: `Fn(&mut Ui, T1, …, T16)` where every `T` is a [`FromView`] extractor,
124/// in any order. `T` is a tuple of the extractor types and only keeps the implementations apart.
125///
126/// The data extractors are checked against what the `load` returns:
127///
128/// ```compile_fail
129/// # use egui_kit::Rejection;
130/// # use egui_kit::page::Page;
131/// async fn load() -> Result<u32, Rejection> {
132///     Ok(1)
133/// }
134///
135/// fn view(ui: &mut egui::Ui, data: &String) {}
136///
137/// let page = Page::<()>::with_load(load, view); // `load` returns a `u32`, not a `String`
138/// ```
139#[diagnostic::on_unimplemented(
140    message = "`{Self}` is not a view: `fn(&mut Ui, extractors...)` with up to 16 view extractors",
141    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
142    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
143    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
144    note = "see the `egui_kit::extract` module for the available extractors"
145)]
146pub trait View<T, S, D>: 'static {
147    fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>);
148}
149
150/// A layout view: `Fn(&mut Ui, Outlet, T1, …, T16)` where every `T` is a [`FromView`] extractor.
151#[diagnostic::on_unimplemented(
152    message = "`{Self}` is not a layout view: `fn(&mut Ui, Outlet, extractors...)` with up to 16 view extractors",
153    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
154    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
155    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
156    note = "see the `egui_kit::extract` module for the available extractors"
157)]
158pub trait LayoutView<T, S, D>: 'static {
159    fn call(&self, ui: &mut Ui, outlet: Outlet<'_>, cx: &ViewContext<'_, S>);
160
161    /// Whether the view takes its data as `&mut D`. If not, the views below can read it with
162    /// [`LayoutData`](crate::extract::LayoutData).
163    #[doc(hidden)]
164    fn borrows_data_mut(&self) -> bool {
165        true
166    }
167}
168
169// Both `Fn` bounds are needed: the first infers the extractor types from the function, the
170// second lets it take them with the lifetime of the frame (as bevy does for systems).
171macro_rules! impl_views {
172    ($($ty:ident),*) => {
173        #[expect(
174            clippy::allow_attributes,
175            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
176        )]
177        impl<F, S: 'static, D, $($ty,)*> View<($($ty,)*), S, D> for F
178        where
179            F: Fn(&mut Ui, $($ty),*) + 'static,
180            F: for<'f> Fn(&mut Ui, $(<$ty as FromView<S, D>>::Item<'f>),*),
181            $($ty: FromView<S, D>,)*
182        {
183            #[allow(non_snake_case, unused_variables)]
184            fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>) {
185                #[allow(clippy::too_many_arguments)]
186                fn call_inner<$($ty),*>(f: impl Fn(&mut Ui, $($ty),*), ui: &mut Ui, $($ty: $ty),*) {
187                    f(ui, $($ty),*)
188                }
189                $($ty::prepare(cx);)*
190                $(let $ty = $ty::from_view(cx);)*
191                call_inner(self, ui, $($ty),*)
192            }
193        }
194
195        #[expect(
196            clippy::allow_attributes,
197            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
198        )]
199        impl<F, S: 'static, D, $($ty,)*> LayoutView<($($ty,)*), S, D> for F
200        where
201            F: Fn(&mut Ui, Outlet<'_>, $($ty),*) + 'static,
202            F: for<'f> Fn(&mut Ui, Outlet<'_>, $(<$ty as FromView<S, D>>::Item<'f>),*),
203            $($ty: FromView<S, D>,)*
204        {
205            #[allow(non_snake_case, unused_variables)]
206            fn call(&self, ui: &mut Ui, outlet: Outlet<'_>, cx: &ViewContext<'_, S>) {
207                #[allow(clippy::too_many_arguments)]
208                fn call_inner<$($ty),*>(
209                    f: impl Fn(&mut Ui, Outlet<'_>, $($ty),*),
210                    ui: &mut Ui,
211                    outlet: Outlet<'_>,
212                    $($ty: $ty),*
213                ) {
214                    f(ui, outlet, $($ty),*)
215                }
216                $($ty::prepare(cx);)*
217                $(let $ty = $ty::from_view(cx);)*
218                call_inner(self, ui, outlet, $($ty),*)
219            }
220
221            fn borrows_data_mut(&self) -> bool {
222                [$(<$ty as FromView<S, D>>::BORROWS_DATA_MUT),*].contains(&true)
223            }
224        }
225    };
226}
227
228crate::all_tuples!(impl_views);
229
230/// The slot a [`Layout`](crate::page::Layout) renders its child (a nested layout, a page or an error
231/// page) into. Layout views get it as their second argument.
232///
233/// Show it with [`Outlet::show`], or animated with a [`ViewTransition`](crate::ViewTransition).
234pub struct Outlet<'o> {
235    pub(crate) inner: &'o mut dyn FnMut(&mut Ui),
236    /// Remembers that this layout animates page changes.
237    pub(crate) uses_transitions: &'o Cell<bool>,
238    pub(crate) transition: Option<&'o mut dyn TransitionHandle>,
239}
240
241impl Outlet<'_> {
242    pub fn show(&mut self, ui: &mut Ui) {
243        (self.inner)(ui);
244    }
245}