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