keymap 0.1.0

A library for defining and parsing input events from configuration
Documentation

keymap-rs

crates.io Rust License: MIT

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)

Getting started

Please check the examples directory for complete examples.

[dependencies]
keymap = "0.1"

Let's started by defining a simple structure for mapping input key to String.

use keymap::{KeyMap, Key};
use serde::Deserialize;

#[derive(Deserialize)]
struct Config(pub HashMap<KeyMap, String>)

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).

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,
            }
        }
    }
}