Skip to main content

rust_glass/widgets/
list.rs

1//! Lists: navigation list, settings rows, sections and tables.
2
3use crate::accessibility::Role;
4use crate::animation::Tuning;
5use crate::color::Color;
6use crate::context::{Cursor, Sense};
7use crate::geometry::{Rect, Vec2, vec2};
8use crate::icon::Icon;
9use crate::material::Corner;
10use crate::text::{TextStyle, Weight};
11use crate::ui::Ui;
12
13/// Vertical navigation list with a sliding highlight. Returns true on change.
14pub fn nav_list(ui: &mut Ui, selected: &mut usize, items: &[(Icon, &str)]) -> bool {
15    let before = *selected;
16    let w = ui.available_width();
17    let h = 38.0;
18    let id = ui.make_id("nav");
19    let old = ui.spacing;
20    ui.spacing = 2.0;
21    let top = ui.next_pos().y;
22    let y = ui.ctx.animate(id, *selected as f32, Tuning::new(0.34, 0.78));
23    let v = ui.ctx.get::<crate::animation::Spring>(id).velocity;
24    let accent = ui.ctx.theme.accent.lerp(Color::WHITE, 0.35 * ui.surface.darkness());
25    // The highlight stretches along its way.
26    let s = (v.abs() * 0.9).min(9.0);
27    let hl = Rect::from_min_size(vec2(ui.cursor.x, top + y * (h + 2.0)), vec2(w, h))
28        .expand2(vec2(-s * 0.2, s * 0.35));
29    let c = ui.surface.strong_fill_color();
30    ui.painter().fill(hl, Corner::Capsule, c);
31    for (i, (icon, label)) in items.iter().enumerate() {
32        let r = ui.allocate_response(vec2(w, h), Sense::Click);
33        ui.ctx.focusable(r.id);
34        if r.clicked {
35            *selected = i;
36        }
37        if let Some(n) = ui.access(r.id, crate::accessibility::Role::Tab, r.rect) {
38            n.label(*label).selected(*selected == i);
39        }
40        if r.hovered {
41            ui.ctx.cursor = Cursor::Pointer;
42        }
43        let hov = ui.ctx.animate_bool(r.id.with("h"), r.hovered && i != *selected, Tuning::SNAP);
44        let on = ui.ctx.animate_bool(r.id.with("on"), i == *selected, Tuning::SNAP);
45        let weight = if i == *selected { Weight::Semibold } else { Weight::Medium };
46        let st = TextStyle::new(ui.ctx.theme.body_size).weight(weight);
47        let l = ui.layout_text(label, &st);
48        let (f, t) = (ui.surface.fill_color(), ui.surface.text_color());
49        let mut p = ui.painter();
50        p.fill(r.rect, Corner::Capsule, f.fade(hov * 0.7));
51        p.icon(vec2(r.rect.min.x + 22.0, r.rect.center().y), 18.0, *icon, t.lerp(accent, on));
52        p.text(vec2(r.rect.min.x + 42.0, r.rect.center().y - l.size.y * 0.5), &l, t);
53        ui.focus_ring(r.id, r.rect, Corner::Capsule);
54    }
55    ui.spacing = old;
56    before != *selected
57}
58
59/// Groups the widgets added in `f` on a card that starts with `title`.
60///
61/// The title is inside the card, so it stays readable over any wallpaper.
62pub fn section(ui: &mut Ui, title: &str, f: impl FnOnce(&mut Ui)) {
63    ui.card(|ui| {
64        let style = TextStyle::new(ui.ctx.theme.body_size + 1.0).weight(Weight::Semibold);
65        let color = ui.surface.text_color();
66        ui.styled_text(title, style, color);
67        f(ui);
68    });
69}
70
71/// A table with a header row. Columns share the width equally.
72pub fn table(ui: &mut Ui, header: &[&str], rows: &[Vec<String>]) {
73    let n = header.len().max(1);
74    let w = ui.available_width() / n as f32;
75    let (tc, sc, sep) = (ui.surface.text_color(), ui.surface.secondary_color(), ui.surface.separator_color());
76    let hs = TextStyle::new(12.0).weight(Weight::Semibold);
77    let bs = TextStyle::new(ui.ctx.theme.body_size);
78    let total = ui.available_width();
79    let old = ui.spacing;
80    ui.spacing = 0.0;
81    let line = |ui: &mut Ui, cells: &[&str], st: &TextStyle, c: Color, h: f32, i: usize| {
82        let r = ui.allocate_response(vec2(total, h), Sense::Hover);
83        let hov = ui.ctx.animate_bool(r.id, r.hovered && i > 0, Tuning::SNAP);
84        let ls: Vec<_> = cells.iter().map(|t| ui.layout_text(t, st)).collect();
85        let f = ui.surface.fill_color();
86        let mut p = ui.painter();
87        p.fill(r.rect.expand2(vec2(8.0, 0.0)), 8.0, f.fade(hov * 0.8));
88        for (k, l) in ls.iter().enumerate() {
89            p.text(vec2(r.rect.min.x + w * k as f32, r.rect.center().y - l.size.y * 0.5), l, c);
90        }
91        p.fill(
92            Rect { min: vec2(r.rect.min.x, r.rect.max.y - 0.5), max: vec2(r.rect.max.x, r.rect.max.y + 0.5) },
93            0.0,
94            sep,
95        );
96    };
97    line(ui, header, &hs, sc, 28.0, 0);
98    for (i, r) in rows.iter().enumerate() {
99        let cells: Vec<&str> = r.iter().map(String::as_str).collect();
100        line(ui, &cells, &bs, tc, 34.0, i + 1);
101    }
102    ui.spacing = old;
103}
104
105/// A row of a settings list: an optional colored icon, a title, and controls
106/// at the trailing end. Screen readers name the trailing controls after the
107/// title.
108pub struct SettingsRow<'a> {
109    icon: Option<(Icon, Color)>,
110    title: &'a str,
111}
112
113impl<'a> SettingsRow<'a> {
114    /// Creates a row with a title.
115    pub fn new(title: &'a str) -> Self {
116        Self { icon: None, title }
117    }
118    /// Shows `icon` in white on a rounded square of `color` before the title.
119    pub fn icon(mut self, icon: Icon, color: Color) -> Self {
120        self.icon = Some((icon, color));
121        self
122    }
123
124    /// Shows the row. `trailing` draws the controls at its end.
125    pub fn show(self, ui: &mut Ui, trailing: impl FnOnce(&mut Ui)) {
126        let w = ui.available_width();
127        let r = ui.allocate(vec2(w, 40.0));
128        let st = TextStyle::new(ui.ctx.theme.body_size);
129        let l = ui.layout_text(self.title, &st);
130        let c = ui.surface.text_color();
131        let mut x = r.min.x;
132        let mut p = ui.painter();
133        if let Some((i, bg)) = self.icon {
134            let b = Rect::from_center_size(vec2(x + 14.0, r.center().y), Vec2::splat(28.0));
135            p.gradient(b, 8.0, bg.lerp(Color::WHITE, 0.14), bg, vec2(0.0, 1.0));
136            p.icon(b.center(), 17.0, i, Color::WHITE);
137            x += 40.0;
138        }
139        p.text(vec2(x, r.center().y - l.size.y * 0.5), &l, c);
140        let left = x + l.size.x + 16.0;
141        let id = ui.next_id();
142        if let Some(n) = ui.access(id.with("title"), Role::Label, r) {
143            n.label(self.title);
144        }
145        // Right aligned by remembering last frame's width.
146        #[derive(Clone, Copy, Default)]
147        struct W(f32);
148        let prev: Option<W> = ui.ctx.try_get(id);
149        if prev.is_none() {
150            ui.ctx.request_relayout();
151        }
152        let tw = prev.map_or(0.0, |w| w.0);
153        let tr = Rect { min: vec2((r.max.x - tw).max(left), r.min.y), max: r.max };
154        let from = ui.ctx.access_nodes().len();
155        let (_, used) = ui.row_sized(id, tr, trailing);
156        ui.ctx.access_label_since(from, self.title);
157        ui.ctx.set(id, W(used.x));
158    }
159}