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::navigation::Navigation;
11use crate::request::Request;
12use crate::transition::TransitionHandle;
13
14/// What all views of a page share during a frame.
15pub(crate) struct Frame<'a> {
16    pub(crate) request: &'a Request,
17    pub(crate) url: &'a str,
18    pub(crate) ctx: egui::Context,
19    pub(crate) history_state: Option<&'a (dyn Any + 'static)>,
20    pub(crate) navigation: &'a Navigation,
21    pub(crate) page_id: u64,
22    pub(crate) scroll: &'a PageScroll,
23    /// Whether this is the previous page, drawn while a transition animates it out.
24    pub(crate) outgoing: bool,
25    pub(crate) nav: &'a RefCell<NavState>,
26}
27
28/// What a view's extractors are extracted from: the app state, the page and the view's data.
29pub struct ViewContext<'a, S> {
30    state: &'a S,
31    frame: &'a Frame<'a>,
32    /// The data of the view, until an extractor takes it.
33    data: Cell<Option<&'a mut (dyn Any + 'static)>>,
34    store: &'a ViewStore,
35}
36
37impl<'a, S> ViewContext<'a, S> {
38    pub(crate) fn new(
39        state: &'a S,
40        frame: &'a Frame<'a>,
41        data: &'a mut (dyn Any + 'static),
42        store: &'a ViewStore,
43    ) -> Self {
44        Self {
45            state,
46            frame,
47            data: Cell::new(Some(data)),
48            store,
49        }
50    }
51
52    pub fn state(&self) -> &S {
53        self.state
54    }
55
56    pub fn nav(&self) -> Nav<'_> {
57        Nav { frame: self.frame }
58    }
59
60    pub(crate) fn frame(&self) -> &Frame<'a> {
61        self.frame
62    }
63
64    /// The page state and snapshots of the view's page or layout.
65    pub(crate) fn store(&self) -> &'a ViewStore {
66        self.store
67    }
68
69    /// Takes the view's data; it can only be extracted once.
70    pub(crate) fn take_data(&self) -> &'a mut (dyn Any + 'static) {
71        self.data
72            .take()
73            .expect("egui-kit: a view can only extract its data once")
74    }
75}
76
77/// A page or error view: `Fn(&mut Ui, T1, …, T16)` where every `T` is a [`FromView`] extractor,
78/// in any order. `T` is a tuple of the extractor types and only keeps the implementations apart.
79///
80/// The data extractors are checked against what the `load` returns:
81///
82/// ```compile_fail
83/// # use egui_kit::Rejection;
84/// # use egui_kit::page::Page;
85/// async fn load() -> Result<u32, Rejection> {
86///     Ok(1)
87/// }
88///
89/// fn view(ui: &mut egui::Ui, data: &String) {}
90///
91/// let page = Page::<()>::with_load(load, view); // `load` returns a `u32`, not a `String`
92/// ```
93#[diagnostic::on_unimplemented(
94    message = "`{Self}` is not a view: `fn(&mut Ui, extractors...)` with up to 16 view extractors",
95    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
96    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
97    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
98    note = "see the `egui_kit::extract` module for the available extractors"
99)]
100pub trait View<T, S, D>: 'static {
101    fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>);
102}
103
104/// A layout view: `Fn(&mut Ui, Outlet, T1, …, T16)` where every `T` is a [`FromView`] extractor.
105#[diagnostic::on_unimplemented(
106    message = "`{Self}` is not a layout view: `fn(&mut Ui, Outlet, extractors...)` with up to 16 view extractors",
107    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
108    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
109    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
110    note = "see the `egui_kit::extract` module for the available extractors"
111)]
112pub trait LayoutView<T, S, D>: 'static {
113    fn call(&self, ui: &mut Ui, outlet: Outlet<'_>, cx: &ViewContext<'_, S>);
114}
115
116// Both `Fn` bounds are needed: the first infers the extractor types from the function, the
117// second lets it take them with the lifetime of the frame (as bevy does for systems).
118macro_rules! impl_views {
119    ($($ty:ident),*) => {
120        #[expect(
121            clippy::allow_attributes,
122            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
123        )]
124        impl<F, S: 'static, D, $($ty,)*> View<($($ty,)*), S, D> for F
125        where
126            F: Fn(&mut Ui, $($ty),*) + 'static,
127            F: for<'f> Fn(&mut Ui, $(<$ty as FromView<S, D>>::Item<'f>),*),
128            $($ty: FromView<S, D>,)*
129        {
130            #[allow(non_snake_case, unused_variables)]
131            fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>) {
132                #[allow(clippy::too_many_arguments)]
133                fn call_inner<$($ty),*>(f: impl Fn(&mut Ui, $($ty),*), ui: &mut Ui, $($ty: $ty),*) {
134                    f(ui, $($ty),*)
135                }
136                $(let $ty = $ty::from_view(cx);)*
137                call_inner(self, ui, $($ty),*)
138            }
139        }
140
141        #[expect(
142            clippy::allow_attributes,
143            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
144        )]
145        impl<F, S: 'static, D, $($ty,)*> LayoutView<($($ty,)*), S, D> for F
146        where
147            F: Fn(&mut Ui, Outlet<'_>, $($ty),*) + 'static,
148            F: for<'f> Fn(&mut Ui, Outlet<'_>, $(<$ty as FromView<S, D>>::Item<'f>),*),
149            $($ty: FromView<S, D>,)*
150        {
151            #[allow(non_snake_case, unused_variables)]
152            fn call(&self, ui: &mut Ui, outlet: Outlet<'_>, cx: &ViewContext<'_, S>) {
153                #[allow(clippy::too_many_arguments)]
154                fn call_inner<$($ty),*>(
155                    f: impl Fn(&mut Ui, Outlet<'_>, $($ty),*),
156                    ui: &mut Ui,
157                    outlet: Outlet<'_>,
158                    $($ty: $ty),*
159                ) {
160                    f(ui, outlet, $($ty),*)
161                }
162                $(let $ty = $ty::from_view(cx);)*
163                call_inner(self, ui, outlet, $($ty),*)
164            }
165        }
166    };
167}
168
169crate::all_tuples!(impl_views);
170
171/// The slot a [`Layout`](crate::page::Layout) renders its child (a nested layout, a page or an error
172/// page) into. Layout views get it as their second argument.
173///
174/// Show it with [`Outlet::show`], or animated with a [`ViewTransition`](crate::ViewTransition).
175pub struct Outlet<'o> {
176    pub(crate) inner: &'o mut dyn FnMut(&mut Ui),
177    /// Remembers that this layout animates page changes.
178    pub(crate) uses_transitions: &'o Cell<bool>,
179    pub(crate) transition: Option<&'o mut dyn TransitionHandle>,
180}
181
182impl Outlet<'_> {
183    pub fn show(&mut self, ui: &mut Ui) {
184        (self.inner)(ui);
185    }
186}