From c9a7af276d57b508df3d4fdaff683fd6b1138899 Mon Sep 17 00:00:00 2001 From: Matt Hunzinger Date: Sat, 23 Sep 2023 21:04:32 -0400 Subject: [PATCH] Create button fn in example --- README.md | 10 ++++++++++ examples/counter.rs | 37 +++++++++++++++++-------------------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 426fafa..808dc08 100644 --- a/README.md +++ b/README.md @@ -44,3 +44,13 @@ let root = Element::builder() viewbuilder::run(tree, root) ``` + +```rust +fn button(tree: &mut Tree, mut f: impl FnMut(&mut Tree) + 'static) -> DefaultKey { + Element::builder() + .on_click(Box::new(move |tree, _event| f(tree))) + .background_color(Color4f::new(1., 1., 0., 1.)) + .child(tree.insert("More!")) + .build(tree) +} +``` \ No newline at end of file diff --git a/examples/counter.rs b/examples/counter.rs index 7ad2fee..e71da0e 100644 --- a/examples/counter.rs +++ b/examples/counter.rs @@ -1,9 +1,18 @@ use skia_safe::Color4f; +use slotmap::DefaultKey; use std::rc::Rc; use std::sync::atomic::{AtomicI64, Ordering}; use taffy::style::FlexDirection; use viewbuilder::{node::Element, Tree}; +fn button(tree: &mut Tree, mut f: impl FnMut(&mut Tree) + 'static) -> DefaultKey { + Element::builder() + .on_click(Box::new(move |tree, _event| f(tree))) + .background_color(Color4f::new(1., 1., 0., 1.)) + .child(tree.insert("More!")) + .build(tree) +} + fn main() { let mut tree = Tree::default(); @@ -17,26 +26,14 @@ fn main() { .child( Element::builder() .flex_direction(FlexDirection::Row) - .child( - Element::builder() - .on_click(Box::new(move |tree, _event| { - inc_count.fetch_add(1, Ordering::SeqCst); - tree.set_text(text, inc_count.load(Ordering::SeqCst).to_string()) - })) - .background_color(Color4f::new(1., 1., 0., 1.)) - .child(tree.insert("More!")) - .build(&mut tree), - ) - .child( - Element::builder() - .on_click(Box::new(move |tree, _event| { - dec_count.fetch_sub(1, Ordering::SeqCst); - tree.set_text(text, dec_count.load(Ordering::SeqCst).to_string()) - })) - .background_color(Color4f::new(1., 1., 0., 1.)) - .child(tree.insert("Less!")) - .build(&mut tree), - ) + .child(button(&mut tree, move |tree| { + inc_count.fetch_add(1, Ordering::SeqCst); + tree.set_text(text, inc_count.load(Ordering::SeqCst).to_string()) + })) + .child(button(&mut tree, move |tree| { + dec_count.fetch_sub(1, Ordering::SeqCst); + tree.set_text(text, dec_count.load(Ordering::SeqCst).to_string()) + })) .build(&mut tree), ) .build(&mut tree);