From 60ff299feead1105ba24c873caf076024ee0f5e0 Mon Sep 17 00:00:00 2001 From: Nico Burns Date: Tue, 21 Nov 2023 15:32:39 +0000 Subject: [PATCH] Make app state a struct --- examples/taffy.rs | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/examples/taffy.rs b/examples/taffy.rs index 4e6865537..27c22d6be 100644 --- a/examples/taffy.rs +++ b/examples/taffy.rs @@ -1,4 +1,5 @@ use xilem::{view::View, App, AppLauncher}; +use vello::peniko::Color; const COLORS: [Color; 4] = [ Color::LIGHT_GREEN, @@ -7,23 +8,34 @@ const COLORS: [Color; 4] = [ Color::HOT_PINK, ]; +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct AppState { + count: u32, +} + +impl AppState { + fn new() -> Self { + Self { count: 1 } + } +} + #[cfg(not(feature = "taffy"))] -fn app_logic(_data: &mut i32) -> impl View { +fn app_logic(_data: &mut AppState) -> impl View { "Error: this example requires the 'taffy' feature to be enabled" } #[cfg(feature = "taffy")] -fn app_logic(data: &mut i32) -> impl View { +fn app_logic(state: &mut AppState) -> impl View { use taffy::style::{AlignItems, FlexWrap, JustifyContent}; use taffy::style_helpers::length; - use vello::peniko::Color; + use xilem::view::{button, div, flex_column, flex_row, scroll_view}; // 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 @@ -36,19 +48,19 @@ fn app_logic(data: &mut i32) -> impl View { 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) @@ -67,7 +79,7 @@ fn app_logic(data: &mut i32) -> impl View { .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); @@ -100,6 +112,6 @@ fn app_logic(data: &mut i32) -> impl View { } fn main() { - let app = App::new(1, app_logic); + let app = App::new(AppState::new(), app_logic); AppLauncher::new(app).run() }