Skip to content

Commit

Permalink
Make app state a struct
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoburns committed Nov 21, 2023
1 parent b27cb2a commit abc6ff6
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions examples/taffy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,23 @@ const COLORS: [Color; 4] = [
Color::HOT_PINK,
];

fn app_logic(data: &mut i32) -> impl View<i32> {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AppState {
count: u32,
}

impl AppState {
fn new() -> Self {
Self { count: 1 }
}
}

fn app_logic(state: &mut AppState) -> impl View<AppState> {
// here's some logic, deriving state for the view from our state
let label = if *data == 1 {
let label = if state.count == 1 {
"Square count: 1".to_string()
} else {
format!("Square count: {data}")
format!("Square count: {}", state.count)
};

// The actual UI Code starts here
Expand All @@ -30,19 +41,19 @@ fn app_logic(data: &mut i32) -> impl View<i32> {

flex_row((
label,
button("increase", |data| {
button("increase", |state: &mut AppState| {
println!("clicked increase");
*data += 1;
state.count += 1;
}),
button("decrease", |data| {
button("decrease", |state: &mut AppState| {
println!("clicked decrease");
if *data > 0 {
*data -= 1;
if state.count > 0 {
state.count -= 1;
}
}),
button("reset", |data| {
button("reset", |state: &mut AppState| {
println!("clicked reset");
*data = 1;
state.count = 1;
}),
))
.with_background_color(Color::BLUE_VIOLET)
Expand All @@ -61,7 +72,7 @@ fn app_logic(data: &mut i32) -> impl View<i32> {
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),

flex_row((0..*data).map(|i| {
flex_row((0..state.count).map(|i| {
div(()).with_background_color(COLORS[(i % 4) as usize]).with_style(|s| {
s.size.width = length(200.0);
s.size.height = length(200.0);
Expand Down Expand Up @@ -94,6 +105,6 @@ fn app_logic(data: &mut i32) -> impl View<i32> {
}

fn main() {
let app = App::new(1, app_logic);
let app = App::new(AppState::new(), app_logic);
AppLauncher::new(app).run()
}

0 comments on commit abc6ff6

Please sign in to comment.