Skip to main content

egui_kit/extract/
layout_data.rs

1//! [`LayoutData`]: the data of a layout around the view.
2
3use core::any::type_name;
4use core::cell::Ref;
5use core::fmt;
6use core::ops::Deref;
7
8use super::FromView;
9use crate::page::ViewContext;
10
11/// The data loaded by the nearest layout around the view that loaded a `T`: what
12/// [`Parent`](super::Parent) is to `load`s, for views.
13///
14/// ```
15/// use egui::Ui;
16/// use egui_kit::Rejection;
17/// use egui_kit::extract::LayoutData;
18/// use egui_kit::page::{Layout, Outlet, Page};
19///
20/// struct Workspace {
21///     name: String,
22/// }
23///
24/// async fn load_workspace() -> Result<Workspace, Rejection> {
25///     Ok(Workspace { name: "Physio".into() })
26/// }
27///
28/// // Takes its data as `&Workspace`, so the views below can read it too.
29/// fn workspace_layout(ui: &mut Ui, mut outlet: Outlet, workspace: &Workspace) {
30///     ui.heading(&workspace.name);
31///     outlet.show(ui);
32/// }
33///
34/// fn settings(ui: &mut Ui, workspace: LayoutData<Workspace>) {
35///     ui.label(format!("Settings of {}", workspace.name));
36/// }
37///
38/// let router = egui_kit::Router::<()>::new()
39///     .layout(Layout::with_load(load_workspace, workspace_layout))
40///     .page("/settings", Page::new(settings));
41/// ```
42///
43/// # Panics
44///
45/// When no layout around the view loaded a `T`, or when the one that did takes its data as
46/// `&mut T` in its view: it can't be read while that view runs (and the views below run inside
47/// it). Take it as `&T` to share it.
48pub struct LayoutData<'f, T: 'static>(Ref<'f, T>);
49
50impl<S: 'static, D, T: 'static> FromView<S, D> for LayoutData<'_, T> {
51    type Item<'f> = LayoutData<'f, T>;
52
53    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> LayoutData<'f, T> {
54        let mut borrowed_mut = false;
55        for loaded in cx.layouts().iter().rev().flatten() {
56            let Ok(data) = loaded.data.try_borrow() else {
57                borrowed_mut = true;
58                continue;
59            };
60            if let Ok(data) = Ref::filter_map(data, |data| data.downcast_ref::<T>()) {
61                return LayoutData(data);
62            }
63        }
64        let hint = if borrowed_mut {
65            " (a layout that takes its data as `&mut` can't share it: take it as `&` instead)"
66        } else {
67            ""
68        };
69        panic!(
70            "egui-kit: no layout around the view loaded a `{}`{hint}",
71            type_name::<T>()
72        );
73    }
74}
75
76impl<T> Deref for LayoutData<'_, T> {
77    type Target = T;
78
79    fn deref(&self) -> &T {
80        &self.0
81    }
82}
83
84impl<T: fmt::Debug> fmt::Debug for LayoutData<'_, T> {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_tuple("LayoutData").field(&**self).finish()
87    }
88}