use core::any::type_name;
use core::cell::Ref;
use core::fmt;
use core::ops::Deref;
use super::FromView;
use crate::page::ViewContext;
pub struct LayoutData<'f, T: 'static>(Ref<'f, T>);
impl<S: 'static, D, T: 'static> FromView<S, D> for LayoutData<'_, T> {
type Item<'f> = LayoutData<'f, T>;
fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> LayoutData<'f, T> {
let mut borrowed_mut = false;
for loaded in cx.layouts().iter().rev().flatten() {
let Ok(data) = loaded.data.try_borrow() else {
borrowed_mut = true;
continue;
};
if let Ok(data) = Ref::filter_map(data, |data| data.downcast_ref::<T>()) {
return LayoutData(data);
}
}
let hint = if borrowed_mut {
" (a layout that takes its data as `&mut` can't share it: take it as `&` instead)"
} else {
""
};
panic!(
"egui-kit: no layout around the view loaded a `{}`{hint}",
type_name::<T>()
);
}
}
impl<T> Deref for LayoutData<'_, T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: fmt::Debug> fmt::Debug for LayoutData<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("LayoutData").field(&**self).finish()
}
}