testing state management

This commit is contained in:
2025-06-27 15:32:55 -05:00
parent 6c8ff5f3da
commit 3adfff41fb
3 changed files with 50 additions and 8 deletions
+1
View File
@@ -15,6 +15,7 @@ pub mod events;
pub mod extensions; pub mod extensions;
pub mod macros; pub mod macros;
pub mod render_scope; pub mod render_scope;
pub mod state;
pub mod style; pub mod style;
pub mod utils; pub mod utils;
+21 -8
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use osui::{ use osui::{
element::{ element::{
input::{Input, InputKeyPress}, input::{Input, InputKeyPress},
@@ -5,37 +7,48 @@ use osui::{
}, },
events::{Close, EventManager}, events::{Close, EventManager},
extensions::{keypress::KeyPressExtension, tick_rate::TickRate, ExtensionManager}, extensions::{keypress::KeyPressExtension, tick_rate::TickRate, ExtensionManager},
state::StateManager,
style::Transform, style::Transform,
Screen, Screen,
}; };
fn main() { fn main() {
let states = StateManager::new(app);
app(states);
}
fn app(states: Arc<StateManager>) {
let mut screen = Screen::new(); let mut screen = Screen::new();
let mut extensions = ExtensionManager::new(); let mut extensions = ExtensionManager::new();
let mut events = EventManager::new(); let mut events = EventManager::new();
extensions.add(KeyPressExtension); extensions.add(KeyPressExtension);
extensions.add(TickRate(255)); extensions.add(TickRate(255));
let my_state = states.use_state(20);
screen screen
.draw(Rect(0xffffff)) .draw(Rect(0xffffff))
.component(Transform::center().dimensions(30, 3)); .component(Transform::center().dimensions(30, 3));
screen screen
.draw(format!("Type quit to quit")) .draw(format!("Type quit to quit {}", my_state.get()))
.component(Transform::new().bottom().margin(0, -1)); .component(Transform::new().bottom().margin(0, -1));
screen screen
.draw(Input::new()) .draw(Input::new())
.component(Transform::new().bottom()); .component(Transform::new().bottom());
events.on(|events, event: Box<InputKeyPress>| match event.1.code { events.on(
crossterm::event::KeyCode::Enter => { move |events, event: Box<InputKeyPress>| match event.1.code {
if event.0 == "quit" { crossterm::event::KeyCode::Enter => {
events.dispatch(Close); my_state.set(my_state.get() + 10);
// if event.0 == "quit" {
// events.dispatch(Close);
// }
} }
} _ => {}
_ => {} },
}); );
screen.run(&mut events, &mut extensions).unwrap(); screen.run(&mut events, &mut extensions).unwrap();
} }
+28
View File
@@ -0,0 +1,28 @@
use std::sync::{Arc, Mutex};
pub struct StateManager(fn(Arc<StateManager>));
pub struct State<S>(Arc<StateManager>, Arc<Mutex<S>>);
impl StateManager {
pub fn new(recall: fn(Arc<StateManager>)) -> Arc<StateManager> {
Arc::new(StateManager(recall))
}
pub fn use_state<S>(self: Arc<Self>, state: S) -> State<S> {
State(self.clone(), Arc::new(Mutex::new(state)))
}
}
impl<S> State<S> {
pub fn set(&self, to: S) {
*self.1.lock().unwrap() = to;
(self.0 .0)(self.0.clone())
}
}
impl State<i32> {
pub fn get(&self) -> i32 {
*self.1.lock().unwrap()
}
}