Skip to main content

uzor/ui/widgets/composite/select/
mod.rs

1//! The open list of a `<select>`: a framework-agnostic model and painter.
2//!
3//! [`SelectState`] is the browser listbox behaviour: the highlighted row, type-to-search
4//! (`query`), the first visible row of a [`SelectStyle::rows`] window, and the keys a
5//! native select answers (arrows, Page Up/Down, Home/End, Enter picks, Escape closes,
6//! Backspace edits the search). [`place`] anchors the list under its trigger and keeps it
7//! inside a container (a modal card, the window): it flips above when there is no room
8//! below and shifts left / up instead of running past the container edge. [`draw_list`]
9//! paints it from a CSS-driven [`SelectStyle`] (`div.select-list { --row-h: 30px; ... }`).
10//!
11//! Both the kit builder (`uzor_framework::widgets::kit::select`) and apps that host the
12//! list in their own overlay use these, so every select behaves the same.
13
14use crate::input::keyboard::KeyCode;
15use crate::layout::{place_anchored, Side};
16use crate::render::{RenderContext, TextAlign};
17use crate::types::Rect;
18use crate::ui::css_box::ellipsize;
19use crate::ui::css_text::{fill_text_css, INTER};
20use crate::ui::widgets::composite::dialog::{draw_card, fill_round_rect, CardStyle, Shadow};
21
22mod tokens;
23
24/// The look of an open list, set from CSS (`Styled`): standard `background`,
25/// `border-color`, `border-radius`, `box-shadow`, `color`, `font-size`, plus the custom
26/// properties named after the fields (`--row-h`, `--row-hi`, `--check`, ...).
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct SelectStyle {
29    pub bg: &'static str,
30    pub border: Option<&'static str>,
31    pub radius: f64,
32    pub shadow: Option<Shadow>,
33    /// Option text.
34    pub color: &'static str,
35    /// Placeholder / "No matches".
36    pub sub: &'static str,
37    pub px: f64,
38    pub row_h: f64,
39    pub row_radius: f64,
40    /// Hovered row fill.
41    pub row_hover: &'static str,
42    /// Highlighted (keyboard) row fill.
43    pub row_hi: &'static str,
44    /// Tick on the chosen row.
45    pub check: &'static str,
46    pub search_bg: &'static str,
47    /// Rows shown at once; more scroll.
48    pub rows: f64,
49    /// Minimum list width (a narrow trigger still gets a readable list).
50    pub min_w: f64,
51    /// Minimum width of a searchable list.
52    pub search_min_w: f64,
53    /// Scroll thumb.
54    pub thumb: &'static str,
55    /// Space between trigger and list.
56    pub gap: f64,
57}
58
59crate::styled!(SelectStyle {
60    bg = "background",
61    border = "border-color",
62    radius = "border-radius",
63    shadow = "box-shadow",
64    color = "color",
65    px = "font-size",
66    sub,
67    row_h,
68    row_radius,
69    row_hover,
70    row_hi,
71    check,
72    search_bg,
73    rows,
74    min_w,
75    search_min_w,
76    thumb,
77    gap,
78});
79
80const PAD: f64 = 4.0;
81const SEARCH_H: f64 = 34.0;
82
83impl SelectStyle {
84    /// Rows in the window.
85    pub fn window(&self) -> usize {
86        (self.rows.max(1.0)) as usize
87    }
88    /// This style with as many rows as fit a container `h` tall (at least 3), so a list
89    /// never runs past a short dialog: it scrolls instead.
90    pub fn fit(mut self, h: f64, searchable: bool) -> Self {
91        let room = h - 8.0 - 2.0 * PAD - if searchable { SEARCH_H } else { 0.0 };
92        self.rows = self.rows.min((room / self.row_h).floor().max(3.0));
93        self
94    }
95    /// Size of the list for `n` matching options under a trigger `anchor_w` wide.
96    pub fn list_size(&self, n: usize, searchable: bool, anchor_w: f64) -> (f64, f64) {
97        let w = anchor_w.max(if searchable { self.search_min_w } else { self.min_w });
98        (w, 2.0 * PAD + if searchable { SEARCH_H } else { 0.0 } + self.row_h * n.clamp(1, self.window()) as f64)
99    }
100}
101
102/// `value` / `label` match the search `query` (case-insensitive; `_` and `/` match spaces,
103/// so `new york` finds `America/New_York`).
104pub fn matches(value: &str, label: &str, query: &str) -> bool {
105    let norm = |s: &str| crate::ui::i18n::case::lower(s).replace(['_', '/'], " ");
106    let q = norm(query.trim());
107    q.is_empty() || norm(label).contains(&q) || norm(value).contains(&q)
108}
109
110/// Indices of the `(value, label)` options matching `query`.
111pub fn filter<V: AsRef<str>, L: AsRef<str>>(opts: &[(V, L)], query: &str) -> Vec<usize> {
112    opts.iter().enumerate().filter(|(_, (v, l))| matches(v.as_ref(), l.as_ref(), query)).map(|(i, _)| i).collect()
113}
114
115/// What a key did to an open list.
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117pub enum SelectKey {
118    /// Highlight or search changed: repaint.
119    Changed,
120    /// Pick this row of the filtered list (Enter).
121    Pick(usize),
122    /// Close without picking (Escape).
123    Close,
124    /// Not a list key: let it through.
125    Ignored,
126}
127
128/// An open list: highlighted row (index into the filtered list), search text, first
129/// visible row.
130#[derive(Clone, Debug, Default, PartialEq, Eq)]
131pub struct SelectState {
132    pub hi: usize,
133    pub query: String,
134    pub top: usize,
135}
136
137impl SelectState {
138    /// Opened on option `chosen` (highlighted and scrolled into a `window`-row view).
139    pub fn open_at(chosen: Option<usize>, window: usize) -> Self {
140        let hi = chosen.unwrap_or(0);
141        Self { hi, query: String::new(), top: scroll_to(0, hi, window) }
142    }
143
144    /// Apply a key to a list of `n` matching rows. `text` is the key's logical text,
145    /// `command` = Ctrl or Meta held (shortcuts are not search text).
146    pub fn key(&mut self, code: KeyCode, text: Option<&str>, command: bool, n: usize, searchable: bool, window: usize) -> SelectKey {
147        let last = n.saturating_sub(1);
148        match code {
149            KeyCode::ArrowDown => self.hi = (self.hi + 1).min(last),
150            KeyCode::ArrowUp => self.hi = self.hi.saturating_sub(1),
151            KeyCode::PageDown => self.hi = (self.hi + window).min(last),
152            KeyCode::PageUp => self.hi = self.hi.saturating_sub(window),
153            KeyCode::Home => self.hi = 0,
154            KeyCode::End => self.hi = last,
155            KeyCode::Enter => return if n > 0 { SelectKey::Pick(self.hi.min(last)) } else { SelectKey::Close },
156            KeyCode::Escape => return SelectKey::Close,
157            KeyCode::Backspace if searchable => {
158                self.query.pop();
159                self.hi = 0;
160            }
161            _ => match text {
162                Some(t) if searchable && !command && !t.is_empty() && !t.chars().any(char::is_control) && !(t == " " && self.query.is_empty()) => {
163                    self.query.push_str(t);
164                    self.hi = 0;
165                }
166                _ => return SelectKey::Ignored,
167            },
168        }
169        self.top = scroll_to(self.top, self.hi, window).min(n.saturating_sub(window));
170        SelectKey::Changed
171    }
172
173    /// Wheel `dy` (positive = down) over a list of `n` rows: scroll the window by 3.
174    pub fn wheel(&mut self, dy: f64, n: usize, window: usize) -> bool {
175        if dy == 0.0 || n <= window {
176            return false;
177        }
178        let max = n - window;
179        let top = if dy > 0.0 { (self.top + 3).min(max) } else { self.top.saturating_sub(3) };
180        let moved = top != self.top;
181        self.top = top;
182        moved
183    }
184}
185
186/// Keep `hi` visible: the first row of a `window`-row view starting at `top`.
187pub fn scroll_to(top: usize, hi: usize, window: usize) -> usize {
188    if hi < top {
189        hi
190    } else if hi >= top + window {
191        hi + 1 - window
192    } else {
193        top
194    }
195}
196
197/// Where a `w`×`h` list opens for a trigger `anchor`: under it (left-aligned), flipped
198/// above when it does not fit below and above has more room, then shifted to stay inside
199/// `within` (the modal card or window that contains the trigger).
200pub fn place(anchor: Rect, w: f64, h: f64, within: Rect, gap: f64) -> Rect {
201    let w = w.min(within.width - 8.0).max(0.0);
202    place_anchored(anchor, w, h, within, Side::Below, gap, 4.0, 0.0)
203}
204
205/// The taller of the two places a list can open for `anchor` inside `within` (below or
206/// above it, less the `gap` and the 4px margin): feed it to [`SelectStyle::fit`] so the
207/// list never covers its own trigger.
208pub fn room(anchor: Rect, within: Rect, gap: f64) -> f64 {
209    let below = within.y + within.height - 4.0 - (anchor.y + anchor.height + gap);
210    let above = anchor.y - gap - (within.y + 4.0);
211    below.max(above) + 8.0
212}
213
214/// Paint the list in `b`: an optional search line showing `query`, then the rows of the
215/// window from `st.top` (`rows`: label, chosen), the highlighted one filled, the chosen
216/// one ticked. `hover(i)` = row `i` is under the pointer. Returns `(row index, rect)` of
217/// the painted rows.
218pub fn draw_list(ctx: &mut dyn RenderContext, b: Rect, rows: &[(&str, bool)], st: &SelectState, query: Option<&str>, hover: &dyn Fn(usize) -> bool, s: &SelectStyle) -> Vec<(usize, Rect)> {
219    draw_card(ctx, b, &CardStyle { bg: s.bg, border: s.border, radius: s.radius, shadow: s.shadow });
220    let font = format!("400 {}px Inter, sans-serif", s.px);
221    let lh = (s.px * 1.5).round();
222    let mut y = b.y + PAD;
223    if let Some(q) = query {
224        let r = Rect::new(b.x + 6.0, y + 2.0, b.width - 12.0, SEARCH_H - 6.0);
225        fill_round_rect(ctx, r, s.row_radius, s.search_bg);
226        magnifier(ctx, r.x + 8.0, r.y + r.height / 2.0, s.sub);
227        let (t, col) = if q.is_empty() { ("Type to search", s.sub) } else { (q, s.color) };
228        ctx.set_font(&font);
229        let t = ellipsize(ctx, t, r.width - 40.0);
230        ctx.set_fill_color(col);
231        fill_text_css(ctx, &t, r.x + 28.0, r.y + (r.height - lh) / 2.0, s.px, lh, INTER, TextAlign::Left);
232        if !q.is_empty() {
233            let cx = r.x + 28.0 + ctx.measure_text(&t) + 1.0;
234            ctx.set_fill_color(s.color);
235            ctx.fill_rect(cx, r.y + 6.0, 1.0, r.height - 12.0);
236        }
237        y += SEARCH_H;
238    }
239    let win = s.window();
240    let list_y = y;
241    if rows.is_empty() {
242        ctx.set_font(&font);
243        ctx.set_fill_color(s.sub);
244        fill_text_css(ctx, "No matches", b.x + 14.0, y + (s.row_h - lh) / 2.0, s.px, lh, INTER, TextAlign::Left);
245    }
246    let mut out = Vec::new();
247    for (i, (label, on)) in rows.iter().enumerate().skip(st.top).take(win) {
248        let r = Rect::new(b.x + PAD, y, b.width - 2.0 * PAD, s.row_h);
249        if i == st.hi {
250            fill_round_rect(ctx, r, s.row_radius, s.row_hi);
251        } else if hover(i) {
252            fill_round_rect(ctx, r, s.row_radius, s.row_hover);
253        }
254        if *on {
255            tick(ctx, r.x + 8.0, r.y + r.height / 2.0, s.check);
256        }
257        ctx.set_font(&font);
258        let t = ellipsize(ctx, label, r.width - 40.0);
259        ctx.set_fill_color(s.color);
260        fill_text_css(ctx, &t, r.x + 28.0, r.y + (r.height - lh) / 2.0, s.px, lh, INTER, TextAlign::Left);
261        out.push((i, r));
262        y += s.row_h;
263    }
264    let n = rows.len();
265    if n > win {
266        let lh = s.row_h * win as f64;
267        let th = (lh * win as f64 / n as f64).max(18.0);
268        let ty = list_y + (lh - th) * st.top as f64 / (n - win) as f64;
269        fill_round_rect(ctx, Rect::new(b.x + b.width - 6.0, ty, 3.0, th), 1.5, s.thumb);
270    }
271    out
272}
273
274fn tick(ctx: &mut dyn RenderContext, x: f64, cy: f64, color: &str) {
275    ctx.set_stroke_color(color);
276    ctx.set_stroke_width(2.0);
277    ctx.set_line_cap("round");
278    ctx.set_line_join("round");
279    ctx.begin_path();
280    ctx.move_to(x + 1.0, cy);
281    ctx.line_to(x + 5.0, cy + 4.0);
282    ctx.line_to(x + 12.0, cy - 4.0);
283    ctx.stroke();
284    ctx.set_line_cap("butt");
285}
286
287fn magnifier(ctx: &mut dyn RenderContext, x: f64, cy: f64, color: &str) {
288    ctx.set_stroke_color(color);
289    ctx.set_stroke_width(1.5);
290    ctx.set_line_cap("round");
291    ctx.begin_path();
292    ctx.arc(x + 5.5, cy - 1.0, 4.5, 0.0, std::f64::consts::TAU);
293    ctx.stroke();
294    ctx.begin_path();
295    ctx.move_to(x + 9.0, cy + 2.5);
296    ctx.line_to(x + 12.0, cy + 5.5);
297    ctx.stroke();
298    ctx.set_line_cap("butt");
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use crate::ui::style::{Sheet, Styled};
305
306    fn zones() -> Vec<(String, String)> {
307        ["Asia/Yekaterinburg", "Europe/Berlin", "America/New_York"].iter().map(|z| (z.to_string(), z.to_string())).collect()
308    }
309
310    #[test]
311    fn filter_matches_like_a_person_types() {
312        let o = zones();
313        assert_eq!(filter(&o, "new york"), vec![2]);
314        assert_eq!(filter(&o, "BER"), vec![1]);
315        assert_eq!(filter(&o, "").len(), 3);
316    }
317
318    #[test]
319    fn keys_move_search_pick_and_close() {
320        let mut s = SelectState::open_at(Some(12), 10);
321        assert_eq!(s.top, 3);
322        assert_eq!(s.key(KeyCode::Home, None, false, 30, true, 10), SelectKey::Changed);
323        assert_eq!((s.hi, s.top), (0, 0));
324        s.key(KeyCode::PageDown, None, false, 30, true, 10);
325        assert_eq!((s.hi, s.top), (10, 1));
326        s.key(KeyCode::End, None, false, 30, true, 10);
327        assert_eq!((s.hi, s.top), (29, 20));
328        s.key(KeyCode::ArrowDown, None, false, 30, true, 10);
329        assert_eq!(s.hi, 29);
330        // Typing filters (and restarts the highlight); a shortcut or a leading space does not.
331        assert_eq!(s.key(KeyCode::B, Some("b"), false, 30, true, 10), SelectKey::Changed);
332        assert_eq!((s.query.as_str(), s.hi, s.top), ("b", 0, 0));
333        assert_eq!(s.key(KeyCode::C, Some("c"), true, 3, true, 10), SelectKey::Ignored);
334        assert_eq!(s.key(KeyCode::Space, Some(" "), false, 3, false, 10), SelectKey::Ignored);
335        s.key(KeyCode::Backspace, None, false, 30, true, 10);
336        assert_eq!(s.query, "");
337        s.key(KeyCode::ArrowDown, None, false, 3, true, 10);
338        assert_eq!(s.key(KeyCode::Enter, None, false, 3, true, 10), SelectKey::Pick(1));
339        assert_eq!(s.key(KeyCode::Escape, None, false, 3, true, 10), SelectKey::Close);
340        assert_eq!(SelectState::default().key(KeyCode::Enter, None, false, 0, true, 10), SelectKey::Close);
341    }
342
343    #[test]
344    fn wheel_scrolls_the_window() {
345        let mut s = SelectState::default();
346        assert!(s.wheel(1.0, 12, 10));
347        assert_eq!(s.top, 2);
348        assert!(!s.wheel(1.0, 12, 10));
349        assert!(!s.wheel(1.0, 5, 10));
350    }
351
352    #[test]
353    fn list_stays_inside_its_container() {
354        let modal = Rect::new(100.0, 100.0, 600.0, 400.0);
355        // A trigger near the modal's right edge: the list shifts left to stay inside.
356        let r = place(Rect::new(600.0, 150.0, 90.0, 28.0), 280.0, 200.0, modal, 4.0);
357        assert!(r.x + r.width <= 696.0 + 0.01 && r.y == 182.0, "{r:?}");
358        // Near the bottom: it flips above the trigger.
359        let r = place(Rect::new(300.0, 440.0, 120.0, 28.0), 160.0, 200.0, modal, 4.0);
360        assert_eq!(r.y, 440.0 - 4.0 - 200.0);
361        // Taller than the room on both sides: shifted to stay within the container.
362        let r = place(Rect::new(300.0, 300.0, 120.0, 28.0), 160.0, 380.0, modal, 4.0);
363        assert!(r.y >= 104.0 && r.y + r.height <= 496.0 + 0.01, "{r:?}");
364        // A long list in a short container shows fewer rows.
365        let s = SelectStyle::default().fit(300.0, true);
366        assert_eq!(s.window(), 8);
367        assert!(s.list_size(30, true, 90.0).1 <= 292.0);
368    }
369
370    #[test]
371    fn style_from_css() {
372        let sh = Sheet::parse("div.select-list{background:black;border-radius:12px;--row-h:28px;--rows:8;--check:green;font-size:14px}").unwrap();
373        let s = SelectStyle::from_sheet(&sh, "div.select-list");
374        assert_eq!((s.bg, s.radius, s.row_h, s.window(), s.check, s.px), ("black", 12.0, 28.0, 8, "green", 14.0));
375        assert_eq!(s.list_size(30, true, 100.0), (280.0, 8.0 + 34.0 + 28.0 * 8.0));
376    }
377}