Skip to main content

decode_key_event

Function decode_key_event 

Source
pub fn decode_key_event(code: u32, mods: u8) -> Option<KeyEvent>
Expand description

Decodes a (code, mods) pair from JS into a retroglyph_core::event::KeyEvent.

retroglyph_core::event::KeyCode/KeyModifiers are not wasm-bindgen FFI-safe types, so JS crosses the boundary with plain integers instead:

  • code: for printable characters, the Unicode scalar value (as from event.key.codePointAt(0) for a single-character key); for named keys, one of key_codes’s constants (e.g. key_codes::LEFT).
  • mods: a bitmask matching retroglyph_core::event::KeyModifiers’s layout (SHIFT = 1, CONTROL = 2, ALT = 4, SUPER = 8). SUPER maps to the JS metaKey (Cmd on macOS, the Windows/Super key elsewhere).

§Examples

use retroglyph_core::event::KeyCode;
use retroglyph_terminal_wasm::{decode_key_event, key_codes};

// A printable character: `code` is its Unicode scalar value.
let key = decode_key_event(u32::from('a'), 0).unwrap();
assert_eq!(key.code, KeyCode::Char('a'));

// A named key, with the Control modifier bit (0b010) set.
let key = decode_key_event(key_codes::LEFT, 0b010).unwrap();
assert_eq!(key.code, KeyCode::Left);
assert!(key.modifiers.contains(retroglyph_core::event::KeyModifiers::CONTROL));

// A lone UTF-16 surrogate half is neither a named key nor a valid `char`.
assert!(decode_key_event(0xD800, 0).is_none());