keymap-rs
is a library for defining input events from configurations and mapping them to the terminal library's event. (such as crossterm or termion)
Please check the examples directory for complete examples.
Click to show
Cargo.toml
.
toml
[dependencies]
keymap = "0.1"
Let's started by defining a simple structure for mapping input key to String
.
```rs use keymap::{KeyMap, Key}; use serde::Deserialize;
struct Config(pub HashMap
let config = r#"
up = "Up"
down = "Down"
g = "Top"
G = "Bottom" # This is the same as shift-g
esc = "Quit"
"
```
Then in your terminal library of choice (we'll be using crossterm as an example). You can use any deserializer (e.g. toml
, json
, etc.) to deserialize a key from the configuration above into the terminal library's event (e.g. crossterm::event::KeyEvent
).
```rs let mapping: Config = toml::from_str(config).unwrap();
// Read input event
match read()? {
Event::Key(key) => {
// Key::from
will convert crossterm::event::KeyEvent
to keymap::Key
if let Some(action) = config.0.get(&Key::from(key)) {
match action {
"Up" => println!("Move up!"),
"Down" => println!("Move down!"),
// ...
"Quit" => break,
}
}
}
}
```