#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyboardEvent {
KeyDown {
key: String,
code: String,
},
KeyPress {
key: String,
code: String,
},
Input {
key: String,
},
KeyUp {
key: String,
code: String,
},
}
impl KeyboardEvent {
pub fn event_type(&self) -> &'static str {
match self {
KeyboardEvent::KeyDown { .. } => "keydown",
KeyboardEvent::KeyPress { .. } => "keypress",
KeyboardEvent::Input { .. } => "input",
KeyboardEvent::KeyUp { .. } => "keyup",
}
}
}
#[must_use]
pub fn key_to_code(ch: char) -> String {
match ch {
'\u{0008}' => "Backspace",
'\n' | '\r' => "Enter",
'\t' => "Tab",
' ' => "Space",
c if c.is_ascii_alphabetic() => return format!("Key{}", c.to_ascii_uppercase()),
c if c.is_ascii_digit() => return format!("Digit{c}"),
'!' => "Digit1",
'@' => "Digit2",
'#' => "Digit3",
'$' => "Digit4",
'%' => "Digit5",
'^' => "Digit6",
'&' => "Digit7",
'*' => "Digit8",
'(' => "Digit9",
')' => "Digit0",
'`' | '~' => "Backquote",
'-' | '_' => "Minus",
'=' | '+' => "Equal",
'[' | '{' => "BracketLeft",
']' | '}' => "BracketRight",
'\\' | '|' => "Backslash",
';' | ':' => "Semicolon",
'\'' | '"' => "Quote",
',' | '<' => "Comma",
'.' | '>' => "Period",
'/' | '?' => "Slash",
_ => "",
}
.to_string()
}
#[must_use]
pub fn key_to_key_value(ch: char) -> String {
match ch {
'\u{0008}' => "Backspace".to_string(),
'\n' | '\r' => "Enter".to_string(),
'\t' => "Tab".to_string(),
_ => ch.to_string(),
}
}
#[must_use]
pub fn key_to_bidi_dispatch_key(ch: char) -> String {
match ch {
'\n' | '\r' => '\u{E006}'.to_string(),
_ => key_to_key_value(ch),
}
}
#[must_use]
pub fn needs_shift(ch: char) -> bool {
ch.is_ascii_uppercase()
|| matches!(
ch,
'!' | '@'
| '#'
| '$'
| '%'
| '^'
| '&'
| '*'
| '('
| ')'
| '_'
| '+'
| '{'
| '}'
| '|'
| ':'
| '"'
| '<'
| '>'
| '?'
| '~'
)
}
#[must_use]
pub fn plan_key_events(ch: char) -> Vec<KeyboardEvent> {
let key = key_to_key_value(ch);
let code = key_to_code(ch);
let mut out = vec![KeyboardEvent::KeyDown {
key: key.clone(),
code: code.clone(),
}];
if is_printable(ch) {
out.push(KeyboardEvent::KeyPress {
key: key.clone(),
code: code.clone(),
});
out.push(KeyboardEvent::Input { key: key.clone() });
}
out.push(KeyboardEvent::KeyUp { key, code });
out
}
fn is_printable(ch: char) -> bool {
!ch.is_control() && !ch.is_ascii_control()
}
#[must_use]
pub fn plan_typed_text(text: &str) -> Vec<KeyboardEvent> {
text.chars().flat_map(plan_key_events).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn printable_char_has_full_sequence() {
let seq = plan_key_events('a');
assert_eq!(seq.len(), 4);
assert_eq!(seq[0].event_type(), "keydown");
assert_eq!(seq[1].event_type(), "keypress");
assert_eq!(seq[2].event_type(), "input");
assert_eq!(seq[3].event_type(), "keyup");
}
#[test]
fn backspace_has_no_input_event() {
let seq = plan_key_events('\u{0008}');
assert_eq!(seq.len(), 2);
assert_eq!(seq[0].event_type(), "keydown");
assert_eq!(seq[1].event_type(), "keyup");
}
#[test]
fn needs_shift_covers_uppercase_and_shifted_symbols() {
for c in 'A'..='Z' {
assert!(needs_shift(c), "{c} (uppercase) must need Shift");
}
for c in "!@#$%^&*()_+{}|:\"<>?~".chars() {
assert!(needs_shift(c), "{c:?} (shifted symbol) must need Shift");
}
for c in 'a'..='z' {
assert!(!needs_shift(c), "{c} (lowercase) must not need Shift");
}
for c in "0123456789 `-=[]\\;',./".chars() {
assert!(!needs_shift(c), "{c:?} (unshifted) must not need Shift");
}
assert!(!needs_shift('\u{0008}'));
}
#[test]
fn bidi_dispatch_sends_main_return_codepoint_for_newline() {
assert_eq!(key_to_bidi_dispatch_key('\n'), "\u{E006}");
assert_eq!(key_to_bidi_dispatch_key('\r'), "\u{E006}");
assert_ne!(key_to_bidi_dispatch_key('\n'), "Enter");
assert_eq!(key_to_bidi_dispatch_key('\n').chars().count(), 1);
assert_eq!(key_to_bidi_dispatch_key('\u{0008}'), "Backspace");
assert_eq!(key_to_bidi_dispatch_key('\t'), "Tab");
for c in "aZ9!@ _-".chars() {
assert_eq!(key_to_bidi_dispatch_key(c), c.to_string());
assert_eq!(key_to_bidi_dispatch_key(c), key_to_key_value(c));
}
}
#[test]
fn code_matches_key_for_letters() {
let seq = plan_key_events('A');
assert!(matches!(
&seq[0],
KeyboardEvent::KeyDown { key, code } if key == "A" && code == "KeyA"
));
}
#[test]
fn code_matches_key_for_digits() {
let seq = plan_key_events('7');
assert!(matches!(
&seq[0],
KeyboardEvent::KeyDown { key, code } if key == "7" && code == "Digit7"
));
}
#[test]
fn typed_text_concatenates_sequences() {
let seq = plan_typed_text("ab");
assert_eq!(seq.len(), 8);
}
#[test]
fn symbol_keys_map_to_physical_code() {
for (ch, want) in [
('-', "Minus"),
('_', "Minus"),
('=', "Equal"),
('+', "Equal"),
('[', "BracketLeft"),
('{', "BracketLeft"),
(']', "BracketRight"),
('}', "BracketRight"),
('\\', "Backslash"),
('|', "Backslash"),
(';', "Semicolon"),
(':', "Semicolon"),
('\'', "Quote"),
('"', "Quote"),
(',', "Comma"),
('<', "Comma"),
('.', "Period"),
('>', "Period"),
('/', "Slash"),
('?', "Slash"),
('`', "Backquote"),
('~', "Backquote"),
] {
assert_eq!(key_to_code(ch), want, "code for {ch:?}");
}
}
#[test]
fn shifted_number_row_shares_digit_physical_key() {
for (ch, want) in [
('!', "Digit1"),
('@', "Digit2"),
('#', "Digit3"),
('$', "Digit4"),
('%', "Digit5"),
('^', "Digit6"),
('&', "Digit7"),
('*', "Digit8"),
('(', "Digit9"),
(')', "Digit0"),
] {
assert_eq!(key_to_code(ch), want, "code for {ch:?}");
}
}
#[test]
fn every_printable_ascii_has_nonempty_code() {
for byte in 0x20u8..=0x7E {
let ch = byte as char;
let code = key_to_code(ch);
assert!(
!code.is_empty(),
"printable ASCII {ch:?} (0x{byte:02X}) produced an empty code"
);
assert!(
code.is_ascii(),
"code {code:?} for {ch:?} must be an ASCII identifier"
);
}
}
#[test]
fn named_keys_map_to_canonical_codes() {
assert_eq!(key_to_code(' '), "Space");
assert_eq!(key_to_code('\u{0008}'), "Backspace");
assert_eq!(key_to_code('\n'), "Enter");
assert_eq!(key_to_code('\r'), "Enter");
assert_eq!(key_to_code('\t'), "Tab");
}
#[test]
fn off_layout_char_has_empty_code_not_a_fabricated_one() {
assert_eq!(key_to_code('é'), "");
assert_eq!(key_to_code('好'), "");
assert_ne!(key_to_code('é'), "é");
}
#[test]
fn logical_key_value_is_coherent_with_code_for_named_keys() {
assert_eq!(key_to_key_value('\n'), "Enter");
assert_eq!(key_to_key_value('\r'), "Enter");
assert_eq!(key_to_key_value('\t'), "Tab");
assert_eq!(key_to_key_value('\u{0008}'), "Backspace");
assert_eq!(key_to_key_value('a'), "a");
assert_eq!(key_to_key_value('!'), "!");
}
#[test]
fn plan_key_events_uses_canonical_key_name_for_enter() {
let seq = plan_key_events('\n');
match &seq[0] {
KeyboardEvent::KeyDown { key, code } => {
assert_eq!(key, "Enter");
assert_eq!(code, "Enter");
}
other => panic!("expected KeyDown, got {other:?}"),
}
}
}