Skip to main content

nex_core/
overlay_state.rs

1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub enum HotkeyAction {
3    ShowAndFocus,
4    Hide,
5    FocusExisting,
6}
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct OverlayState {
10    visible: bool,
11}
12
13impl Default for OverlayState {
14    fn default() -> Self {
15        Self { visible: false }
16    }
17}
18
19impl OverlayState {
20    pub fn set_visible(&mut self, visible: bool) {
21        self.visible = visible;
22    }
23
24    pub fn is_visible(&self) -> bool {
25        self.visible
26    }
27
28    pub fn on_hotkey(&mut self, has_focus: bool) -> HotkeyAction {
29        if !self.visible {
30            self.visible = true;
31            return HotkeyAction::ShowAndFocus;
32        }
33
34        if has_focus {
35            self.visible = false;
36            return HotkeyAction::Hide;
37        }
38
39        HotkeyAction::FocusExisting
40    }
41
42    pub fn on_escape(&mut self) -> bool {
43        if self.visible {
44            self.visible = false;
45            return true;
46        }
47        false
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::{HotkeyAction, OverlayState};
54
55    #[test]
56    fn hotkey_shows_hidden_overlay() {
57        let mut state = OverlayState::default();
58        let action = state.on_hotkey(false);
59        assert_eq!(action, HotkeyAction::ShowAndFocus);
60        assert!(state.is_visible());
61    }
62
63    #[test]
64    fn hotkey_hides_visible_overlay_when_focused() {
65        let mut state = OverlayState::default();
66        state.on_hotkey(false);
67        let action = state.on_hotkey(true);
68        assert_eq!(action, HotkeyAction::Hide);
69        assert!(!state.is_visible());
70    }
71
72    #[test]
73    fn hotkey_refocuses_visible_overlay_when_not_focused() {
74        let mut state = OverlayState::default();
75        state.on_hotkey(false);
76        let action = state.on_hotkey(false);
77        assert_eq!(action, HotkeyAction::FocusExisting);
78        assert!(state.is_visible());
79    }
80
81    #[test]
82    fn escape_hides_only_when_visible() {
83        let mut state = OverlayState::default();
84        assert!(!state.on_escape());
85        state.on_hotkey(false);
86        assert!(state.on_escape());
87        assert!(!state.is_visible());
88    }
89}