use blit::{Context, InteractCx, KeyboardEvent};
pub trait Handler: FnOnce(KeyboardEvent<'_>) -> Option<Self::Action> + Copy + 'static {
type Action: Copy + 'static;
}
impl<A: Copy + 'static, F> Handler for F
where
F: FnOnce(KeyboardEvent<'_>) -> Option<A> + Copy + 'static,
{
type Action = A;
}
blit::builder! {
#[derive(Clone, Copy)]
pub struct Interact<F> {
new(handler: F),
require_focus: bool = false,
}
}
impl<C: Context, F: Handler> blit::Interact<C> for Interact<F> {
type State = ();
type Response = Option<F::Action>;
fn update(&self, _: &mut (), cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response {
if self.require_focus && !cx.focused() {
return None;
}
let action = (self.handler)(cx.keyboard()?)?;
cx.claim_keyboard();
Some(action)
}
}