Type Alias intuitive::event::KeyHandler

source ·
pub type KeyHandler = Handler<KeyEvent>;
Expand description

A handler for KeyEvents.

Creating a KeyHandler

A KeyHandler is used to manipulate closures or functions that take in a KeyEvent as a parameter, and return a Propagate. KeyHandlers are often created using the on_key! macro. For example,

#[component(Root)]
fn render() {
  let text = use_state(|| String::new());

  let on_key = on_key! { [text]
    KeyEvent { code: Char(c), .. } => text.mutate(|text| text.push(c)),
  };

  render! {
    Text(text: format!("Hi There {}", text.get()), on_key)
  }
}

Using a KeyHandler

A KeyEvent can be handled by a KeyHandler through the Handler::handle method. KeyHandler implements Default, and the default handler ignores the KeyEvent, and always returns Propagate::Next.

Typically, components want to take some default action when implementing on_key, but allow the user of this component to override this handler. This can be done using the KeyHandler::handle_or method:

struct Frozen {
  on_key: KeyHandler,
}

impl Element for Frozen {
  fn on_key(&self, event: KeyEvent) {
    self.on_key.handle_or(event, |event| { /* default functionality here */ })
  }
}

Here, Frozen::on_key calls the handler that was provided if one was. If no KeyHandler was provided, then self.on_key is the default handler, which always returns Propagate::Next. This causes the closure above to be executed.

Propagation

A user of a component can control when the default key handler is run by returning one of Propagate::{Next, Stop}. For example, to create an input box that receives input keys, but quits on the escape key:

#[component(Root)]
fn render() {
  let text = use_state(|| String::new);

  let on_key = on_key! { [text]
    KeyEvent { code: Esc, .. } => event::quit(),

    _ => return Propagate::Next,
  };

  render! {
    Input(on_key)
  }
}

This will cause all key events other than Esc to be handled by Input’s default key handler.

Aliased Type§

struct KeyHandler { /* private fields */ }