testing state management
This commit is contained in:
@@ -15,6 +15,7 @@ pub mod events;
|
||||
pub mod extensions;
|
||||
pub mod macros;
|
||||
pub mod render_scope;
|
||||
pub mod state;
|
||||
pub mod style;
|
||||
pub mod utils;
|
||||
|
||||
|
||||
+21
-8
@@ -1,3 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use osui::{
|
||||
element::{
|
||||
input::{Input, InputKeyPress},
|
||||
@@ -5,37 +7,48 @@ use osui::{
|
||||
},
|
||||
events::{Close, EventManager},
|
||||
extensions::{keypress::KeyPressExtension, tick_rate::TickRate, ExtensionManager},
|
||||
state::StateManager,
|
||||
style::Transform,
|
||||
Screen,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let states = StateManager::new(app);
|
||||
app(states);
|
||||
}
|
||||
|
||||
fn app(states: Arc<StateManager>) {
|
||||
let mut screen = Screen::new();
|
||||
let mut extensions = ExtensionManager::new();
|
||||
let mut events = EventManager::new();
|
||||
extensions.add(KeyPressExtension);
|
||||
extensions.add(TickRate(255));
|
||||
|
||||
let my_state = states.use_state(20);
|
||||
|
||||
screen
|
||||
.draw(Rect(0xffffff))
|
||||
.component(Transform::center().dimensions(30, 3));
|
||||
|
||||
screen
|
||||
.draw(format!("Type quit to quit"))
|
||||
.draw(format!("Type quit to quit {}", my_state.get()))
|
||||
.component(Transform::new().bottom().margin(0, -1));
|
||||
|
||||
screen
|
||||
.draw(Input::new())
|
||||
.component(Transform::new().bottom());
|
||||
|
||||
events.on(|events, event: Box<InputKeyPress>| match event.1.code {
|
||||
crossterm::event::KeyCode::Enter => {
|
||||
if event.0 == "quit" {
|
||||
events.dispatch(Close);
|
||||
events.on(
|
||||
move |events, event: Box<InputKeyPress>| match event.1.code {
|
||||
crossterm::event::KeyCode::Enter => {
|
||||
my_state.set(my_state.get() + 10);
|
||||
// if event.0 == "quit" {
|
||||
// events.dispatch(Close);
|
||||
// }
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
_ => {}
|
||||
},
|
||||
);
|
||||
|
||||
screen.run(&mut events, &mut extensions).unwrap();
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user