Skip to main content

tea_cli/tui/
selectors.rs

1use tea_protocol::{BranchId, ModelRef, ReasoningEffort, SessionId};
2
3const MAX_SELECTOR_ITEMS: usize = 512;
4const MAX_SELECTOR_QUERY_BYTES: usize = 256;
5
6/// Typed value returned by a local selector.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum SelectorValue {
9    /// Durable session selection.
10    Session(SessionId),
11    /// Provider model selection.
12    Model(ModelRef),
13    /// Provider-neutral reasoning effort selection.
14    Reasoning(ReasoningEffort),
15    /// Durable branch selection.
16    Branch(BranchId),
17}
18
19/// One bounded selector row.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SelectorItem {
22    label: String,
23    value: SelectorValue,
24}
25
26impl SelectorItem {
27    /// Creates one selector row.
28    #[must_use]
29    pub fn new(label: impl Into<String>, value: SelectorValue) -> Self {
30        Self {
31            label: label.into(),
32            value,
33        }
34    }
35
36    /// Returns the display label.
37    #[must_use]
38    pub fn label(&self) -> &str {
39        &self.label
40    }
41
42    /// Returns the typed value.
43    #[must_use]
44    pub const fn value(&self) -> &SelectorValue {
45        &self.value
46    }
47}
48
49/// Invalid selector construction.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
51pub enum SelectorError {
52    /// The title, row label, or collection bound is invalid.
53    #[error("selector is invalid")]
54    Invalid,
55}
56
57/// Filterable deterministic local selection view.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Selector {
60    title: String,
61    items: Vec<SelectorItem>,
62    visible: Vec<usize>,
63    query: String,
64    selected: usize,
65}
66
67impl Selector {
68    /// Creates a selector with stable source order.
69    ///
70    /// # Errors
71    ///
72    /// Rejects empty/oversized/control labels and oversized item collections.
73    pub fn new<I>(title: impl Into<String>, items: I) -> Result<Self, SelectorError>
74    where
75        I: IntoIterator<Item = SelectorItem>,
76    {
77        let title = title.into();
78        let items = items.into_iter().collect::<Vec<_>>();
79        if !valid_text(&title)
80            || items.len() > MAX_SELECTOR_ITEMS
81            || items.iter().any(|item| !valid_text(&item.label))
82        {
83            return Err(SelectorError::Invalid);
84        }
85        let visible = (0..items.len()).collect();
86        Ok(Self {
87            title,
88            items,
89            visible,
90            query: String::new(),
91            selected: 0,
92        })
93    }
94
95    /// Returns the selector title.
96    #[must_use]
97    pub fn title(&self) -> &str {
98        &self.title
99    }
100
101    /// Returns the current filter query.
102    #[must_use]
103    pub fn query(&self) -> &str {
104        &self.query
105    }
106
107    /// Replaces the case-insensitive query with a bounded value.
108    pub fn set_query(&mut self, query: &str) {
109        let mut boundary = query.len().min(MAX_SELECTOR_QUERY_BYTES);
110        while !query.is_char_boundary(boundary) {
111            boundary -= 1;
112        }
113        query[..boundary].clone_into(&mut self.query);
114        let query = self.query.to_lowercase();
115        self.visible = self
116            .items
117            .iter()
118            .enumerate()
119            .filter_map(|(index, item)| item.label.to_lowercase().contains(&query).then_some(index))
120            .collect();
121        self.selected = 0;
122    }
123
124    /// Returns currently visible rows.
125    #[must_use]
126    pub fn visible_items(&self) -> Vec<&SelectorItem> {
127        self.visible
128            .iter()
129            .map(|index| &self.items[*index])
130            .collect()
131    }
132
133    /// Moves to the next visible row with wraparound.
134    pub fn move_next(&mut self) {
135        if !self.visible.is_empty() {
136            self.selected = (self.selected + 1) % self.visible.len();
137        }
138    }
139
140    /// Moves to the previous visible row with wraparound.
141    pub fn move_previous(&mut self) {
142        if !self.visible.is_empty() {
143            self.selected = self
144                .selected
145                .checked_sub(1)
146                .unwrap_or(self.visible.len() - 1);
147        }
148    }
149
150    /// Selects one currently visible typed value when present.
151    pub fn select_value(&mut self, value: &SelectorValue) {
152        if let Some(index) = self
153            .visible
154            .iter()
155            .position(|index| self.items[*index].value == *value)
156        {
157            self.selected = index;
158        }
159    }
160
161    /// Returns the selected row label.
162    #[must_use]
163    pub fn selected_label(&self) -> Option<&str> {
164        self.visible
165            .get(self.selected)
166            .map(|index| self.items[*index].label.as_str())
167    }
168
169    /// Returns a clone of the selected typed value.
170    #[must_use]
171    pub fn accept(&self) -> Option<SelectorValue> {
172        self.visible
173            .get(self.selected)
174            .map(|index| self.items[*index].value.clone())
175    }
176}
177
178fn valid_text(value: &str) -> bool {
179    !value.is_empty() && value.len() <= 512 && !value.chars().any(char::is_control)
180}