Skip to main content

slt/context/
state.rs

1use super::*;
2
3/// Handle to state created by `use_state()`. Access via `.get(ui)` / `.get_mut(ui)`.
4#[derive(Debug, Copy, Clone, PartialEq, Eq)]
5pub struct State<T> {
6    idx: usize,
7    _marker: std::marker::PhantomData<T>,
8}
9
10impl<T: 'static> State<T> {
11    pub(crate) fn from_idx(idx: usize) -> Self {
12        Self {
13            idx,
14            _marker: std::marker::PhantomData,
15        }
16    }
17
18    /// Read the current value.
19    pub fn get<'a>(&self, ui: &'a Context) -> &'a T {
20        ui.hook_states[self.idx]
21            .downcast_ref::<T>()
22            .unwrap_or_else(|| {
23                panic!(
24                    "use_state type mismatch at hook index {} — expected {}",
25                    self.idx,
26                    std::any::type_name::<T>()
27                )
28            })
29    }
30
31    /// Mutably access the current value.
32    pub fn get_mut<'a>(&self, ui: &'a mut Context) -> &'a mut T {
33        ui.hook_states[self.idx]
34            .downcast_mut::<T>()
35            .unwrap_or_else(|| {
36                panic!(
37                    "use_state type mismatch at hook index {} — expected {}",
38                    self.idx,
39                    std::any::type_name::<T>()
40                )
41            })
42    }
43}
44
45/// Interaction response returned by all widgets.
46///
47/// Container methods return a [`Response`]. Check `.clicked`, `.changed`, etc.
48/// to react to user interactions.
49/// `rect` is meaningful after the widget has participated in layout.
50/// Container responses describe the container's own interaction area, not
51/// automatically the focus state of every child widget.
52///
53/// # Examples
54///
55/// ```
56/// # use slt::*;
57/// # TestBackend::new(80, 24).render(|ui| {
58/// let r = ui.row(|ui| {
59///     ui.text("Save");
60/// });
61/// if r.clicked {
62///     // handle save
63/// }
64/// # });
65/// ```
66#[derive(Debug, Clone, Default)]
67#[must_use = "Response contains interaction state — check .clicked, .hovered, or .changed"]
68pub struct Response {
69    /// Whether the widget was clicked this frame.
70    pub clicked: bool,
71    /// Whether the mouse is hovering over the widget.
72    pub hovered: bool,
73    /// Whether the widget's value changed this frame.
74    pub changed: bool,
75    /// Whether the widget currently has keyboard focus.
76    pub focused: bool,
77    /// The rectangle the widget occupies after layout.
78    pub rect: Rect,
79}
80
81impl Response {
82    /// Create a Response with all fields false/default.
83    pub fn none() -> Self {
84        Self::default()
85    }
86}