better global state structure?

This commit is contained in:
2025-12-19 21:54:48 -05:00
parent 30bc55c78e
commit bae17235c6
23 changed files with 335 additions and 230 deletions

View File

@@ -1,29 +1,47 @@
use crate::{Event, EventCtx, EventLike, EventManager, HasEvents, HasUi, IdLike};
use crate::{
Event, EventCtx, EventLike, EventManager, HasUi, IdLike, Widget, WidgetEventFn, WidgetRef,
};
pub trait HasRsc: Sized + 'static {
type Rsc: HasEvents<State = Self> + HasUi;
fn rsc(&self) -> &Self::Rsc;
fn rsc_mut(&mut self) -> &mut Self::Rsc;
pub trait HasState {
type State: HasUi;
}
fn run_event<E: EventLike>(&mut self, id: impl IdLike, data: &mut <E::Event as Event>::Data<'_>)
where
Self: 'static,
pub trait HasEvents: Sized + HasState + HasUi {
fn get(&self) -> &EventManager<Self::State>;
fn get_mut(&mut self) -> &mut EventManager<Self::State>;
fn events(&self) -> &EventManager<Self::State> {
HasEvents::get(self)
}
fn events_mut(&mut self) -> &mut EventManager<Self::State> {
HasEvents::get_mut(self)
}
fn register_event<W: Widget + ?Sized, E: EventLike>(
&mut self,
id: WidgetRef<W>,
event: E,
f: impl for<'a> WidgetEventFn<Self::State, <E::Event as Event>::Data<'a>, W>,
) where
Self::State: 'static,
{
let f = self.rsc_mut().events().get_type::<E>().run_fn(id);
self.events_mut().register(id, event, f);
self.ui_mut()
.widgets
.data_mut(id)
.unwrap()
.event_mgrs
.insert(EventManager::<Self::State>::type_key::<E>());
}
}
pub trait RunEvents: HasEvents + HasState<State = Self> + 'static {
fn run_event<E: EventLike>(
&mut self,
id: impl IdLike,
data: &mut <E::Event as Event>::Data<'_>,
) {
let f = self.events_mut().get_type::<E>().run_fn(id);
f(EventCtx { state: self, data })
}
fn events(&mut self) -> &mut EventManager<Self> {
self.rsc_mut().events()
}
}
impl<R: HasRsc> HasUi for R {
fn ui_ref(&self) -> &crate::Ui {
self.rsc().ui_ref()
}
fn ui(&mut self) -> &mut crate::Ui {
self.rsc_mut().ui()
}
}
impl<T: HasEvents + HasState<State = Self> + 'static> RunEvents for T {}