Skip to content

Commit

Permalink
Add swtich to example
Browse files Browse the repository at this point in the history
  • Loading branch information
giannissc committed Aug 28, 2023
1 parent f844364 commit 569cfe3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
34 changes: 23 additions & 11 deletions examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
use xilem::view::{button, h_stack, v_stack};
use xilem::view::{button, h_stack, switch, v_stack, Adapt};
use xilem::{view::View, App, AppLauncher};

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

// The actual UI Code starts here
v_stack((
button(label, |data| {
button(label, |data: &mut AppData| {
println!("clicked");
*data += 1;
data.count += 1;
}),
h_stack((
button("decrease", |data| {
button("decrease", |data: &mut AppData| {
println!("clicked decrease");
*data -= 1;
data.count -= 1;
}),
button("reset", |data| {
button("reset", |data: &mut AppData| {
println!("clicked reset");
*data = 0;
data.count = 0;
}),
switch(data, |data: &mut AppData| &mut data.is_on),
)),
))
.with_spacing(20.0)
}

struct AppData {
count: u32,
is_on: bool,
}

fn main() {
/*
let app = Application::new().unwrap();
Expand All @@ -40,6 +47,11 @@ fn main() {
window_handle.show();
app.run(None);
*/
let app = App::new(0, app_logic);
let data = AppData {
count: 0,
is_on: false,
};

let app = App::new(data, app_logic);
AppLauncher::new(app).run()
}
8 changes: 5 additions & 3 deletions src/view/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ pub struct Switch<T> {
callback: Box<dyn Fn(&mut T) -> &mut bool + Send>,
}

pub fn switch<T>(data: &mut T, clicked: impl Fn(&mut T) -> &mut bool + Send + 'static) -> Switch<T> {
pub fn switch<T>(
data: &mut T,
clicked: impl Fn(&mut T) -> &mut bool + Send + 'static,
) -> Switch<T> {
Switch::new(data, clicked)
}

impl<T> Switch<T> {
pub fn new(data: &mut T, clicked: impl Fn(&mut T) -> &mut bool + Send + 'static) -> Self {
let is_on = *(clicked)(data);
Switch{
Switch {
is_on,
callback: Box::new(clicked),

}
}
}
Expand Down

0 comments on commit 569cfe3

Please sign in to comment.