Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* ⌨️ **Key Patterns**: Supports single keys (`a`), combinations (`ctrl-b`), and multi-key sequences (`ctrl-b n`).
* 🧠 **Key Groups**: Use built-in pattern matching for common key groups (`@upper`, `@lower`, `@alpha`, `@alnum`, and `@any`).
* 📸 **Key Group Capturing**: Capture specific keypress data (like the actual `char` from `@any` or `@digit`) directly into your action enum variants at runtime.
* 🏷️ **Custom Symbols & Help**: Define custom display symbols (e.g., `^B`) and help text for key bindings.
* 🧬 **Compile-Time Safety**: The `keymap_derive` macro validates key syntax at compile time, preventing runtime errors.
* 🌐 **Backend-Agnostic**: Works with multiple backends, including `crossterm`, `termion`, and `wasm`.
* 🪶 **Lightweight & Extensible**: Designed to be minimal and easy to extend with new backends or features.
Expand Down Expand Up @@ -95,8 +96,8 @@ pub enum Action {
#[key("right", "l")]
Right,

/// Jump.
#[key("space")]
/// Jump with custom key, display symbol and help text.
#[key("space", symbol = "␣", help = "jump over obstacles")]
Jump,

/// Key Group Capturing action (e.g. tracking which character was pressed).
Expand All @@ -119,7 +120,8 @@ let config = Action::keymap_config();
match config.get(&key) {
Some(action) => match action {
Action::Quit => break,
Action::Jump => println!("Jump!"),
Action::Jump => println!("Jump! Symbol: {:?}, Help: {:?}",
action.keymap_item().symbol, action.keymap_item().help),
_ => println!("Action: {action:?} - {}", action.keymap_item().description),
}
_ => {}
Expand Down Expand Up @@ -241,6 +243,8 @@ assert_eq!(
| **Key Combinations** | Keys pressed simultaneously with modifiers (Ctrl, Alt, Shift). | `ctrl-c`, `alt-f4`, `ctrl-alt-shift-f1` |
| **Key Sequences** | Multiple keys pressed in order. | `g g` (press `g` twice), `ctrl-b n` (Ctrl+B, then N), `ctrl-b c` (tmux-style new window) |
| **Key Groups** | Predefined patterns matching sets of keys. | `@upper` (A-Z), `@alpha` (A-Z, a-z), `@any` (any key) |
| **Custom Symbols** | Custom display symbols for key bindings (e.g., for UI display). | `symbol = "^B"` |
| **Help Text** | Short help descriptions for key bindings. | `help = "jump"` |

**Examples in Configuration:**
```toml
Expand Down
52 changes: 32 additions & 20 deletions examples/wasm/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,8 @@ class Game {
this.gameSpeed = CONFIG.GAME.INITIAL_SPEED;
this.gameOver = false;
this.paused = false;
this.key = "";
this.symbol = "";
this.help = "";

// Delta time approach instead of frame limiting
this.lastTime = 0;
Expand Down Expand Up @@ -501,7 +502,8 @@ class Game {
this.gameSpeed = CONFIG.GAME.INITIAL_SPEED;
this.gameOver = false;
this.paused = false;
this.key = "";
this.symbol = "";
this.help = "";
this._hideGameOverUI();
this.accumulator = 0; // Ensure game logic runs on first frame after reset

Expand All @@ -512,11 +514,9 @@ class Game {
});
}

setKey(key, desc) {
this.key = [key, desc]
.filter(Boolean)
.map((s) => s.toLowerCase())
.join(" - ");
setKey(symbol = "", help = "") {
this.symbol = symbol;
this.help = help;
}

togglePause() {
Expand Down Expand Up @@ -551,14 +551,13 @@ class Game {
}

_drawKey() {
let fontSize = 10;
ctx.fillStyle = "#ccc";
ctx.font = `${fontSize}px "${CONFIG.GAME.FONT_FACE}"`;
ctx.textAlign = "center";
ctx.fillStyle = "#ccc";
ctx.font = `10px "${CONFIG.GAME.FONT_FACE}"`;
ctx.fillText(
this.key,
[this.symbol, this.help].filter(Boolean).join(" "),
canvas.width / 2,
GROUND_Y + CONFIG.GROUND_HEIGHT - (CONFIG.GROUND_HEIGHT - fontSize) / 2,
GROUND_Y + CONFIG.GROUND_HEIGHT - (CONFIG.GROUND_HEIGHT - 10) / 2,
);
}

Expand Down Expand Up @@ -693,17 +692,30 @@ export function pauseGame() {
}
}

export function setKey(key, description) {
game.setKey(key, description);
export function setKey(key, description, symbol, help) {
game.setKey(key, description, symbol, help);
}

export function setSkin(c) {
// Handle char code or string character
const char = typeof c === 'number' ? String.fromCharCode(c) : c;
const digit = parseInt(char);
if (isNaN(digit)) return;
export function renderKeybindings(info) {
const data = JSON.parse(info);
const container = document.getElementById("keybindings-info");
if (!container) return;

container.innerHTML = data
.map((entry) => {
const keys = entry.keys.join(", ");
const sym = entry.symbol || keys || "";
const help = entry.help || "";
return `<div class="keybinding-row">
<span class="keybinding-symbol">${sym}</span>
<span class="keybinding-help">${help}</span>
<span class="keybinding-keys">${keys}</span>
</div>`;
})
.join("");
}

// Change rainbow trail colors based on digit
export function setSkin(digit) {
const baseHue = (digit * 36) % 360;
game.rainbowTrail.colors = Array.from({ length: 6 }, (_, i) => {
return `hsl(${(baseHue + i * 20) % 360}, 100%, 50%)`;
Expand Down
33 changes: 33 additions & 0 deletions examples/wasm/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,39 @@ canvas {
#share-button:hover {
background-color: #282828;
}
#keybindings-info {
display: flex;
flex-wrap: wrap;
gap: 2px 16px;
padding: 8px 12px;
background: #1a1a2e;
border-top: 2px solid #333;
font-family: 'Silkscreen', cursive;
font-size: 12px;
}
.keybinding-row {
display: flex;
align-items: center;
gap: 6px;
width: calc(50% - 8px);
padding: 2px 0;
}
.keybinding-symbol {
color: #ffd93d;
font-weight: 700;
min-width: 24px;
text-align: center;
}
.keybinding-help {
color: #ccc;
flex-shrink: 0;
font-size: 12px;
}
.keybinding-keys {
color: #6b7280;
font-size: 10px;
margin-left: auto;
}
.rainbow {
font-family: 'Press Start 2P', cursive;
animation: rainbowColors 4s linear infinite;
Expand Down
23 changes: 14 additions & 9 deletions examples/wasm/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,39 +33,44 @@ <h3>DEMO: Nyan Jump! (WASM Edition)</h3>
<div id="game-over">GAME OVER!</div>
<button id="restart-button">Restart</button>
<button id="share-button">Share on X</button>
<div id="keybindings-info"></div>
</div>
<h4>EXAMPLE: Derive Macro</h4>
<p>
Define an enum and automatically derive key bindings using the <code>#[derive(KeyMap)]</code> macro.
</p>
<pre><code class="language-rust">#[derive(keymap::KeyMap, Hash, PartialEq, Eq, Clone)]
<pre><code class="language-rust">#[derive(Debug, Clone, keymap::KeyMap, Hash, PartialEq, Eq)]
pub enum Action {
/// Jump over obstacles
#[key("space")]
#[key("space", symbol = "↑", help = "jump")] // symbol gets overridden by toml config
Jump,

/// Move leftward
#[key("left")]
#[key("left", help = "move left")]
Left,

/// Move rightward
#[key("right")]
#[key("right", help = "move right")]
Right,

/// Select a skin (Key Group Capturing!)
#[key("@digit")]
SelectSkin(char),
/// Pause
#[key("p", help = "pause")]
Pause,

/// Restart
#[key("q", "esc")]
#[key("q", "esc", help = "quit")]
Quit,

/// Select a skin
#[key("@digit", symbol = "0-9", help = "select skin")]
SelectSkin(u8),
}</code></pre>
<h4>EXAMPLE: Key Override</h4>
<p>
Customize or extend key bindings through configuration files without changing the source code.
</p>
<pre><code class="language-yaml"># Now both 'space' and the 'up' arrow can be used to jump
Jump = { keys = ["space", "up"], description = "Jump Jump!" }
Jump = { keys = ["space", "up"], symbol = "␣", help = "jump", description = "Jump Jump!" }
</code></pre>
<script src="https://unpkg.com/@highlightjs/cdn-assets@11.11.1/highlight.min.js" defer></script>
<script src="https://unpkg.com/@highlightjs/cdn-assets@11.11.1/languages/rust.min.js" defer></script>
Expand Down
68 changes: 47 additions & 21 deletions examples/wasm/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,66 +12,84 @@ extern "C" {
fn isGameOver() -> bool;
fn resetGame();
fn pauseGame();
fn setKey(key: String, desc: String);
fn setSkin(c: char);
fn setKey(key: String, desc: String, symbol: String, help: String);
fn setSkin(digit: u8);
fn renderKeybindings(info: String);
}

#[derive(Debug, Clone, keymap::KeyMap, Hash, PartialEq, Eq)]
pub enum Action {
/// Jump over obstacles
#[key("space")]
#[key("space", symbol = "↑", help = "jump")] // symbol gets overridden by toml config
Jump,

/// Move leftward
#[key("left")]
#[key("left", help = "move left")]
Left,

/// Move rightward
#[key("right")]
#[key("right", help = "move right")]
Right,

/// Pause
#[key("p")]
#[key("p", help = "pause")]
Pause,

/// Restart
#[key("q", "esc")]
#[key("q", "esc", help = "quit")]
Quit,

/// Select a skin
#[key("@digit")]
SelectSkin(char),
#[key("@digit", symbol = "0-9", help = "select skin")]
SelectSkin(u8),
}

/// Overrides the default keymap
#[allow(unused)]
pub const DERIVED_CONFIG: &str = r#"
Jump = { keys = ["space", "up"], description = "Jump Jump!" }
Quit = { keys = ["q", "esc"], description = "Quit!" }
Left = { keys = ["left", "alt-l"], description = "Move Left" }
Right = { keys = ["right", "alt-r"], description = "Move Right" }
SelectSkin = { keys = ["@digit"], description = "Select a skin" }
Jump = { keys = ["space", "up"], symbol = "␣", help = "jump", description = "Jump Jump!" }
Quit = { keys = ["q", "esc"], symbol = "↩", help = "quit", description = "Quit!" }
Left = { keys = ["left", "alt-l"], symbol = "←", help = "move left", description = "Move Left" }
Right = { keys = ["right", "alt-r"], symbol = "→", help = "move right", description = "Move Right" }
SelectSkin = { keys = ["@digit"], symbol = "0-9", help = "select skin", description = "Select a skin" }
"#;

#[allow(unused)]
pub fn derived_config() -> DerivedConfig<Action> {
toml::from_str(DERIVED_CONFIG).unwrap()
}

fn json_escape(s: &str) -> String {
let mut buf = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => buf.push_str("\\\""),
'\\' => buf.push_str("\\\\"),
'\n' => buf.push_str("\\n"),
'\r' => buf.push_str("\\r"),
'\t' => buf.push_str("\\t"),
c if c.is_control() => buf.push_str(&format!("\\u{:04x}", c as u32)),
c => buf.push(c),
}
}
buf
}

#[wasm_bindgen]
pub fn get_keymap_as_json() -> String {
let keymap = derived_config();
let keymap_info: Vec<String> = keymap
.items
.iter()
.map(|(action, entry)| {
let keys: Vec<String> = entry.keys.iter().map(|k| format!("\"{}\"", k)).collect();
let description = entry.description.clone();
let keys: Vec<String> = entry.keys.iter().map(|k| format!("\"{}\"", json_escape(k))).collect();
let description = json_escape(&entry.description);
let symbol = json_escape(entry.symbol.as_deref().unwrap_or_default());
let help = json_escape(entry.help.as_deref().unwrap_or_default());
let action_str = json_escape(&format!("{:?}", action));
format!(
"{{ \"action\": \"{:?}\", \"keys\": [{}], \"description\": \"{}\" }}",
action,
"{{ \"action\": \"{action_str}\", \"keys\": [{}], \"description\": \"{description}\", \"symbol\": \"{symbol}\", \"help\": \"{help}\" }}",
keys.join(","),
description
)
})
.collect();
Expand Down Expand Up @@ -99,6 +117,7 @@ pub fn main() {
on_keydown.forget();
on_keyup.forget();

renderKeybindings(get_keymap_as_json());
resetGame();
}

Expand All @@ -110,11 +129,19 @@ pub fn handle_key_event(event: &KeyboardEvent, is_keydown: bool) {
if is_keydown {
let key = event.to_keymap().unwrap();
let mut desc = String::new();
let mut symbol = String::new();
let mut help = String::new();
if let Some((_, item)) = config.get_item(event) {
desc = item.description.clone();
if item.keys.iter().any(|k| k.starts_with('@')) {
symbol = key.to_string();
} else {
symbol = item.symbol.clone().unwrap_or_default();
}
help = item.help.clone().unwrap_or_default();
};

setKey(key.to_string(), desc);
setKey(key.to_string(), desc, symbol, help);
}

// Use .get_bound() to support Key Group Capturing for SelectSkin
Expand All @@ -128,7 +155,6 @@ pub fn handle_key_event(event: &KeyboardEvent, is_keydown: bool) {
Action::SelectSkin(c) => {
if is_keydown {
setSkin(c);
setKey(format!("Skin selected: {c}"), "Key Group Capturing!".to_string());
}
}
_ if !is_game_over => match action {
Expand Down
Loading
Loading