tui_world/focus.rs
1use crate::WidgetId;
2
3/// Tracks which widget currently has keyboard focus.
4///
5/// The `Focus` struct manages a single optional `WidgetId` representing the
6/// currently focused widget. Only one widget can have focus at a time, and
7/// focus can be cleared entirely.
8///
9/// # Example
10///
11/// ```ignore
12/// let mut focus = Focus::new(WidgetId("input"));
13/// assert!(focus.is_focused(WidgetId("input")));
14///
15/// focus.set(WidgetId("button"));
16/// assert!(focus.is_focused(WidgetId("button")));
17///
18/// focus.clear();
19/// assert!(!focus.is_focused(WidgetId("button")));
20/// ```
21#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
22pub struct Focus {
23 pub id: Option<WidgetId>,
24}
25
26impl Focus {
27 /// Creates a new Focus with a specific widget active.
28 #[must_use]
29 pub const fn new(id: WidgetId) -> Self {
30 Self { id: Some(id) }
31 }
32
33 /// Updates the focus. Accepts an `Option<WidgetId>`.
34 pub fn set(&mut self, id: impl Into<Option<WidgetId>>) {
35 self.id = id.into();
36 }
37
38 /// Clears the current focus.
39 pub fn clear(&mut self) {
40 self.id = None;
41 }
42
43 /// Returns true if the given widget has focus.
44 #[must_use]
45 pub fn is_focused(&self, id: WidgetId) -> bool {
46 self.id == Some(id)
47 }
48}