Add callbackbuilder

This commit is contained in:
hodasemi 2024-04-04 09:11:42 +02:00
parent 1baf6a488e
commit a4f0c0bcc8
3 changed files with 57 additions and 0 deletions

View file

@ -0,0 +1,55 @@
use std::any::Any;
use anyhow::Result;
use super::ControllerButton;
macro_rules! callbacks {
($name:ident, $($cb:tt)*) => {
#[derive(Default)]
pub struct $name<'a> {
callbacks: Vec<(&'a str, Box<dyn $($cb)*>)>,
}
impl<'a> $name<'a> {
pub fn add(mut self, name: &'a str, callback: impl $($cb)* + 'static)->Self {
self.callbacks.push((name, Box::new(callback)));
self
}
}
impl<'a> Into<Vec<(&'a str, Box<dyn $($cb)*>)>> for $name<'a> {
fn into(self) -> Vec<(&'a str, Box<dyn $($cb)*>)> {
self.callbacks
}
}
};
}
callbacks!(ClickCallbacks, Fn() -> Result<()> + Send + Sync);
callbacks!(SelectCallbacks, Fn(bool) -> anyhow::Result<()> + Send + Sync);
callbacks!(CustomCallbacks, Fn(ControllerButton) -> anyhow::Result<bool> + Send + Sync);
callbacks!(VecCallbacks, Fn(&dyn Any) -> Result<()> + Send + Sync);
#[test]
fn test_click_callback_builder() {
struct Test;
impl Test {
fn set_click_callbacks(
&self,
_callbacks: Vec<(&str, Box<dyn Fn() -> Result<()> + Send + Sync>)>,
) -> Result<()> {
Ok(())
}
}
let t = Test;
let cbs = ClickCallbacks::default().add("test", || {
println!("hello world!");
Ok(())
});
t.set_click_callbacks(cbs.into()).unwrap();
}

View file

@ -22,6 +22,7 @@ pub mod uielement;
pub mod traits; pub mod traits;
mod callback_builder;
pub mod prelude; pub mod prelude;
pub(crate) struct TextableWrapper { pub(crate) struct TextableWrapper {

View file

@ -1,5 +1,6 @@
pub use super::{ pub use super::{
button::{Button, ButtonBuilder, ButtonSelectMode}, button::{Button, ButtonBuilder, ButtonSelectMode},
callback_builder::*,
fill_type::FillTypeInfo, fill_type::FillTypeInfo,
grid::Grid, grid::Grid,
icon::Icon, icon::Icon,