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 22, 2023
1 parent 1b795a3 commit 60ff299
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions examples/taffy.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use xilem::{view::View, App, AppLauncher};
use vello::peniko::Color;

const COLORS: [Color; 4] = [
Color::LIGHT_GREEN,
Expand All @@ -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<i32> {
fn app_logic(_data: &mut AppState) -> impl View<AppState> {
"Error: this example requires the 'taffy' feature to be enabled"
}

#[cfg(feature = "taffy")]
fn app_logic(data: &mut i32) -> impl View<i32> {
fn app_logic(state: &mut AppState) -> impl View<AppState> {
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
Expand All @@ -36,19 +48,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 @@ -67,7 +79,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 @@ -100,6 +112,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 60ff299

Please sign in to comment.