1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum KeyboardCommand {
5 Submit,
6 Palette,
7 Search,
8 Help,
9 Dismiss,
10}
11
12#[derive(Clone, Copy, Debug, Default)]
13pub struct KeyboardInput<'a> {
14 pub key: &'a str,
15 pub control: bool,
16 pub meta: bool,
17 pub alt: bool,
18 pub shift: bool,
19 pub repeat: bool,
20 pub composing: bool,
21 pub editable: bool,
22}
23
24impl<'a> KeyboardInput<'a> {
25 pub fn typeahead(self, at_millis: u64) -> Option<&'a str> {
28 (!self.editable
29 && !self.composing
30 && !self.control
31 && !self.meta
32 && !self.alt
33 && crate::validate_typeahead(self.key, at_millis).is_ok())
34 .then_some(self.key)
35 }
36 pub fn command(self) -> Option<KeyboardCommand> {
37 if self.repeat || self.composing || self.alt {
38 return None;
39 }
40 if self.key == "Escape" {
41 return Some(KeyboardCommand::Dismiss);
42 }
43 if self.editable {
44 return (self.key == "Enter" && !self.shift).then_some(KeyboardCommand::Submit);
45 }
46 let chord = self.control || self.meta;
47 if chord && !self.shift && self.key.eq_ignore_ascii_case("k") {
48 Some(KeyboardCommand::Palette)
49 } else if chord && !self.shift && self.key.eq_ignore_ascii_case("f") {
50 Some(KeyboardCommand::Search)
51 } else if (chord && self.key == "/") || self.key == "?" || (self.shift && self.key == "/") {
52 Some(KeyboardCommand::Help)
53 } else {
54 None
55 }
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62 #[test]
63 fn composition_repeat_editing_and_modifiers_preserve_native_text() {
64 let input = KeyboardInput {
65 key: "Enter",
66 editable: true,
67 ..Default::default()
68 };
69 assert_eq!(input.command(), Some(KeyboardCommand::Submit));
70 assert_eq!(
71 KeyboardInput {
72 control: true,
73 ..input
74 }
75 .command(),
76 Some(KeyboardCommand::Submit)
77 );
78 for ignored in [
79 KeyboardInput {
80 shift: true,
81 ..input
82 },
83 KeyboardInput { alt: true, ..input },
84 KeyboardInput {
85 repeat: true,
86 ..input
87 },
88 KeyboardInput {
89 composing: true,
90 ..input
91 },
92 ] {
93 assert_eq!(ignored.command(), None);
94 }
95 assert_eq!(
96 KeyboardInput {
97 key: "?",
98 editable: true,
99 ..Default::default()
100 }
101 .command(),
102 None
103 );
104 assert_eq!(
105 KeyboardInput {
106 key: "k",
107 control: true,
108 editable: true,
109 ..Default::default()
110 }
111 .command(),
112 None
113 );
114 assert_eq!(
115 KeyboardInput {
116 key: "k",
117 control: true,
118 ..Default::default()
119 }
120 .command(),
121 Some(KeyboardCommand::Palette)
122 );
123 assert_eq!(
124 KeyboardInput {
125 key: "f",
126 meta: true,
127 ..Default::default()
128 }
129 .command(),
130 Some(KeyboardCommand::Search)
131 );
132 }
133}