Skip to main content

use_interaction/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4/// Common UI interaction states.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
6pub enum InteractionState {
7    Idle,
8    Hovered,
9    Focused,
10    Active,
11    Disabled,
12    Selected,
13    Loading,
14    Pressed,
15    Expanded,
16    Collapsed,
17}
18
19impl InteractionState {
20    pub fn is_interactive(self) -> bool {
21        !matches!(self, Self::Disabled | Self::Loading)
22    }
23
24    pub fn is_disabled(self) -> bool {
25        matches!(self, Self::Disabled)
26    }
27
28    pub fn is_focus_visible_candidate(self) -> bool {
29        matches!(self, Self::Focused | Self::Active | Self::Pressed)
30    }
31}
32
33/// Input source or interaction channel.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
35pub enum InteractionKind {
36    Pointer,
37    Keyboard,
38    Touch,
39    Voice,
40    Programmatic,
41}
42
43/// User-facing intent for an interaction.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
45pub enum InteractionIntent {
46    Primary,
47    Secondary,
48    Destructive,
49    Confirm,
50    Cancel,
51    Navigate,
52    Disclose,
53}
54
55impl InteractionIntent {
56    pub fn is_committal(self) -> bool {
57        matches!(self, Self::Primary | Self::Destructive | Self::Confirm)
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::{InteractionIntent, InteractionKind, InteractionState};
64
65    #[test]
66    fn constructs_interaction_enums() {
67        assert_eq!(InteractionKind::Keyboard, InteractionKind::Keyboard);
68        assert_eq!(InteractionIntent::Cancel, InteractionIntent::Cancel);
69    }
70
71    #[test]
72    fn checks_interaction_state_helpers() {
73        assert!(InteractionState::Focused.is_interactive());
74        assert!(!InteractionState::Disabled.is_interactive());
75        assert!(InteractionState::Disabled.is_disabled());
76        assert!(InteractionState::Focused.is_focus_visible_candidate());
77        assert!(InteractionState::Pressed.is_focus_visible_candidate());
78        assert!(!InteractionState::Hovered.is_focus_visible_candidate());
79        assert!(InteractionIntent::Confirm.is_committal());
80        assert!(!InteractionIntent::Cancel.is_committal());
81    }
82}