use std::rc::Rc;
use gpui::{App, ElementId, Entity, Window};
pub type EventHandler<Event> = Rc<dyn Fn(&Event, &mut Window, &mut App) + 'static>;
pub struct State<Value: 'static> {
entity: Entity<Value>,
}
impl<Value: 'static> Clone for State<Value> {
fn clone(&self) -> Self {
Self {
entity: self.entity.clone(),
}
}
}
impl<Value: 'static> State<Value> {
#[must_use]
pub fn from_entity(entity: Entity<Value>) -> Self {
Self { entity }
}
pub fn read<'context>(&self, cx: &'context App) -> &'context Value {
self.entity.read(cx)
}
pub fn get(&self, cx: &App) -> Value
where
Value: Clone,
{
self.entity.read(cx).clone()
}
pub fn set(&self, value: Value, cx: &mut App) {
self.entity.update(cx, |current_value, cx| {
*current_value = value;
cx.notify();
});
}
pub fn update(&self, cx: &mut App, change: impl FnOnce(&mut Value)) {
self.entity.update(cx, |current_value, cx| {
change(current_value);
cx.notify();
});
}
#[must_use]
pub fn entity(&self) -> &Entity<Value> {
&self.entity
}
}
#[track_caller]
pub fn use_state<Value: 'static>(
window: &mut Window,
cx: &mut App,
initial_value: impl FnOnce() -> Value,
) -> State<Value> {
let entity = window.use_state(cx, |_, _| initial_value());
State { entity }
}
pub fn use_keyed_state<Value: 'static>(
key: impl Into<ElementId>,
window: &mut Window,
cx: &mut App,
initial_value: impl FnOnce() -> Value,
) -> State<Value> {
let entity = window.use_keyed_state(key, cx, |_, _| initial_value());
State { entity }
}