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 {
70            frame: self.frame,
71            depth: self.layouts.len(),
72        }
73    }
74
75    pub(crate) fn frame(&self) -> &Frame<'a> {
76        self.frame
77    }
78
79    /// The page state and snapshots of the view's page or layout.
80    pub(crate) fn store(&self) -> &'a ViewStore {
81        self.store
82    }
83
84    /// Lets `f` read the view's data, before an extractor takes it.
85    pub(crate) fn peek_data<R>(&self, f: impl FnOnce(&dyn Any) -> R) -> R {
86        let data = self
87            .data
88            .take()
89            .expect("egui-kit: the view's data was already extracted (this is a bug)");
90        let result = f(match &data {
91            ViewData::Mut(data) => &**data,
92            ViewData::Shared(data) => *data,
93        });
94        self.data.set(Some(data));
95        result
96    }
97
98    /// Takes the view's data; it can only be extracted once.
99    pub(crate) fn take_data(&self) -> &'a (dyn Any + 'static) {
100        match self.take() {
101            ViewData::Mut(data) => data,
102            ViewData::Shared(data) => data,
103        }
104    }
105
106    /// Takes the view's data mutably; it can only be extracted once.
107    pub(crate) fn take_data_mut(&self) -> &'a mut (dyn Any + 'static) {
108        match self.take() {
109            ViewData::Mut(data) => data,
110            ViewData::Shared(_) => panic!("egui-kit: the data is shared (this is a bug)"),
111        }
112    }
113
114    fn take(&self) -> ViewData<'a> {
115        self.data
116            .take()
117            .expect("egui-kit: a view can only extract its data once")
118    }
119
120    /// The data of the layouts around the view, outermost first.
121    pub(crate) fn layouts(&self) -> &'a [Option<Loaded>] {
122        self.layouts
123    }
124}
125
126/// A page or error view: `Fn(&mut Ui, T1, …, T16)` where every `T` is a [`FromView`] extractor,
127/// in any order. `T` is a tuple of the extractor types and only keeps the implementations apart.
128///
129/// The data extractors are checked against what the `load` returns:
130///
131/// ```compile_fail
132/// # use egui_kit::Rejection;
133/// # use egui_kit::page::Page;
134/// async fn load() -> Result<u32, Rejection> {
135///     Ok(1)
136/// }
137///
138/// fn view(ui: &mut egui::Ui, data: &String) {}
139///
140/// let page = Page::<()>::with_load(load, view); // `load` returns a `u32`, not a `String`
141/// ```
142#[diagnostic::on_unimplemented(
143    message = "`{Self}` is not a view: `fn(&mut Ui, extractors...)` with up to 16 view extractors",
144    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
145    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
146    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
147    note = "see the `egui_kit::extract` module for the available extractors"
148)]
149pub trait View<T, S, D>: 'static {
150    fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>);
151}
152
153/// A layout view: `Fn(&mut Ui, Children, T1, …, T16)` where every `T` is a [`FromView`] extractor.
154#[diagnostic::on_unimplemented(
155    message = "`{Self}` is not a layout view: `fn(&mut Ui, Children, extractors...)` with up to 16 view extractors",
156    note = "views borrow the app state: `State<&T>` rather than `State<T>`, and `HistoryState<&T>`",
157    note = "the data must be what the `load` returned: `&mut {D}` or `&{D}`",
158    note = "closures need annotated arguments, e.g. `|ui: &mut Ui, nav: Nav| ...`",
159    note = "see the `egui_kit::extract` module for the available extractors"
160)]
161pub trait LayoutView<T, S, D>: 'static {
162    fn call(&self, ui: &mut Ui, children: Children<'_>, cx: &ViewContext<'_, S>);
163
164    /// Whether the view takes its data as `&mut D`. If not, the views below can read it with
165    /// [`LayoutData`](crate::extract::LayoutData).
166    #[doc(hidden)]
167    fn borrows_data_mut(&self) -> bool {
168        true
169    }
170}
171
172// Both `Fn` bounds are needed: the first infers the extractor types from the function, the
173// second lets it take them with the lifetime of the frame (as bevy does for systems).
174macro_rules! impl_views {
175    ($($ty:ident),*) => {
176        #[expect(
177            clippy::allow_attributes,
178            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
179        )]
180        impl<F, S: 'static, D, $($ty,)*> View<($($ty,)*), S, D> for F
181        where
182            F: Fn(&mut Ui, $($ty),*) + 'static,
183            F: for<'f> Fn(&mut Ui, $(<$ty as FromView<S, D>>::Item<'f>),*),
184            $($ty: FromView<S, D>,)*
185        {
186            #[allow(non_snake_case, unused_variables)]
187            fn call(&self, ui: &mut Ui, cx: &ViewContext<'_, S>) {
188                #[allow(clippy::too_many_arguments)]
189                fn call_inner<$($ty),*>(f: impl Fn(&mut Ui, $($ty),*), ui: &mut Ui, $($ty: $ty),*) {
190                    f(ui, $($ty),*)
191                }
192                $($ty::prepare(cx);)*
193                $(let $ty = $ty::from_view(cx);)*
194                call_inner(self, ui, $($ty),*)
195            }
196        }
197
198        #[expect(
199            clippy::allow_attributes,
200            reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
201        )]
202        impl<F, S: 'static, D, $($ty,)*> LayoutView<($($ty,)*), S, D> for F
203        where
204            F: Fn(&mut Ui, Children<'_>, $($ty),*) + 'static,
205            F: for<'f> Fn(&mut Ui, Children<'_>, $(<$ty as FromView<S, D>>::Item<'f>),*),
206            $($ty: FromView<S, D>,)*
207        {
208            #[allow(non_snake_case, unused_variables)]
209            fn call(&self, ui: &mut Ui, children: Children<'_>, cx: &ViewContext<'_, S>) {
210                #[allow(clippy::too_many_arguments)]
211                fn call_inner<$($ty),*>(
212                    f: impl Fn(&mut Ui, Children<'_>, $($ty),*),
213                    ui: &mut Ui,
214                    children: Children<'_>,
215                    $($ty: $ty),*
216                ) {
217                    f(ui, children, $($ty),*)
218                }
219                $($ty::prepare(cx);)*
220                $(let $ty = $ty::from_view(cx);)*
221                call_inner(self, ui, children, $($ty),*)
222            }
223
224            fn borrows_data_mut(&self) -> bool {
225                [$(<$ty as FromView<S, D>>::BORROWS_DATA_MUT),*].contains(&true)
226            }
227        }
228    };
229}
230
231crate::all_tuples!(impl_views);
232
233/// The slot a [`Layout`](crate::page::Layout) renders its child (a nested layout, a page or an error
234/// page) into. Layout views get it as their second argument.
235///
236/// Show it with [`Children::show`], or animated with a [`ViewTransition`](crate::ViewTransition).
237pub struct Children<'o> {
238    pub(crate) inner: &'o mut dyn FnMut(&mut Ui),
239    /// Remembers that this layout animates page changes.
240    pub(crate) uses_transitions: &'o Cell<bool>,
241    pub(crate) transition: Option<&'o mut dyn TransitionHandle>,
242}
243
244impl Children<'_> {
245    pub fn show(&mut self, ui: &mut Ui) {
246        (self.inner)(ui);
247    }
248}