Skip to main content

rust_glass/widgets/
segmented.rs

1//! Segmented control.
2
3use crate::accessibility::{Action, Role};
4use crate::animation::Tuning;
5use crate::color::Color;
6use crate::context::{Cursor, Response, Sense};
7use crate::geometry::{Rect, lerp, vec2};
8use crate::input::Key;
9use crate::material::Corner;
10use crate::paint::Feather;
11use crate::text::{TextStyle, Weight};
12use crate::ui::{Ui, Widget};
13use crate::widgets::thumb::{drag_target, load_thumb, store_thumb, thumb_glass, thumb_rect};
14
15/// Pick one of a few options. The selected label is drawn inside the thumb and
16/// seen through it, so it bends and splits at the rim while the thumb moves.
17pub struct Segmented<'a> {
18    selected: &'a mut usize,
19    labels: &'a [&'a str],
20    width: Option<f32>,
21    scale: f32,
22    knob: Option<Color>,
23    track: Option<Color>,
24    fit: bool,
25}
26
27impl<'a> Segmented<'a> {
28    /// Creates a control that sets `selected` to the index of the chosen label.
29    pub fn new(selected: &'a mut usize, labels: &'a [&'a str]) -> Self {
30        Self { selected, labels, width: None, scale: 1.0, knob: None, track: None, fit: false }
31    }
32    /// Sets the width. The default fits the labels.
33    pub fn width(mut self, width: f32) -> Self {
34        self.width = Some(width);
35        self
36    }
37    /// Scales the whole control.
38    pub fn scale(mut self, scale: f32) -> Self {
39        self.scale = scale;
40        self
41    }
42    /// Sets the color of the thumb at rest.
43    pub fn thumb_color(mut self, color: Color) -> Self {
44        self.knob = Some(color);
45        self
46    }
47    /// Sets the color of the track.
48    pub fn track_color(mut self, color: Color) -> Self {
49        self.track = Some(color);
50        self
51    }
52    /// Segments as wide as their label instead of equal.
53    pub fn fit(mut self) -> Self {
54        self.fit = true;
55        self
56    }
57}
58
59impl Widget for Segmented<'_> {
60    fn ui(self, ui: &mut Ui) -> Response {
61        let k = self.scale;
62        let h = 34.0 * k;
63        let font = 12.8 * k;
64        let n = self.labels.len().max(1);
65        let quiet = TextStyle::new(font).weight(Weight::Medium);
66        let loud = TextStyle::new(font).weight(Weight::Semibold);
67        let texts: Vec<_> =
68            self.labels.iter().map(|l| (ui.layout_text(l, &quiet), ui.layout_text(l, &loud))).collect();
69        let natural: Vec<f32> = texts.iter().map(|t| t.1.size.x + 36.0 * k).collect();
70        let total: f32 = if self.fit {
71            natural.iter().sum()
72        } else {
73            natural.iter().cloned().fold(0.0, f32::max) * n as f32
74        };
75        let w = self.width.unwrap_or(total).min(ui.available_width().max(60.0));
76        let mut widths: Vec<f32> =
77            if self.fit { natural.iter().map(|x| x * w / total).collect() } else { vec![w / n as f32; n] };
78        if widths.is_empty() {
79            widths.push(w);
80        }
81        let mut r = ui.allocate_response(vec2(w, h), Sense::Drag);
82        ui.ctx.focusable(r.id);
83        let rect = r.rect;
84        let mut x = rect.min.x;
85        let cells: Vec<Rect> = widths
86            .iter()
87            .map(|cw| {
88                let c = Rect::from_min_size(vec2(x, rect.min.y), vec2(*cw, h));
89                x += cw;
90                c
91            })
92            .collect();
93
94        let before = *self.selected;
95        *self.selected = before.min(n - 1);
96        let mut d = load_thumb(ui.ctx, r.id);
97        let ox = rect.min.x;
98        let first = cells[0].center().x - ox;
99        let last = cells[n - 1].center().x - ox;
100        let dragged = drag_target(ui.ctx, r.id, &r, ox, d.pos.value, first, last, 8.0 * k);
101        let nearest = |x: f32| {
102            (0..n)
103                .min_by(|a, b| {
104                    let da = (cells[*a].center().x - ox - x).abs();
105                    let db = (cells[*b].center().x - ox - x).abs();
106                    da.total_cmp(&db)
107                })
108                .unwrap_or(0)
109        };
110        if r.released {
111            let p = r.pointer.map_or(d.pos.value + ox, |p| p.x);
112            let moved = (p - ui.ctx.input.press_origin.x).abs() > 4.0;
113            *self.selected = if moved {
114                nearest(d.pos.value)
115            } else {
116                cells.iter().position(|c| p >= c.min.x && p < c.max.x).unwrap_or(nearest(p - ox))
117            };
118        }
119        if r.focused {
120            if ui.ctx.input.take_key(Key::Right) {
121                *self.selected = (*self.selected + 1).min(n - 1);
122            }
123            if ui.ctx.input.take_key(Key::Left) {
124                *self.selected = self.selected.saturating_sub(1);
125            }
126        }
127        if r.hovered {
128            ui.ctx.cursor = Cursor::Pointer;
129        }
130        for (i, cell) in cells.iter().enumerate() {
131            let sid = r.id.with(("segment", i));
132            if ui.ctx.access_requested(sid, &Action::Click) {
133                *self.selected = i;
134            }
135            let sel = *self.selected == i;
136            if let Some(node) = ui.access(sid, Role::Tab, *cell) {
137                node.label(self.labels.get(i).copied().unwrap_or_default()).selected(sel);
138            }
139        }
140        r.changed = before != *self.selected;
141
142        let sel = *self.selected;
143        let target = dragged.unwrap_or(cells[sel].center().x - ox);
144        // Interpolate the resting width while travelling between cells.
145        let hover_cell = nearest(target);
146        let cell_w = ui.ctx.animate(r.id.with("w"), cells[hover_cell].width(), Tuning::SMOOTH);
147        let rest = vec2(cell_w, h - 1.0 * k);
148        let lifted = vec2(cell_w * 1.07 + 4.0 * k, h * 1.34);
149        let follow =
150            if dragged.is_some() && !r.pressed { Tuning::new(0.13, 0.9) } else { Tuning::new(0.36, 0.80) };
151        if r.changed && d.lift.value < 0.3 {
152            // A tap: hop into the lens for the trip.
153            d.lift.value = 0.31;
154        }
155        let f = d.step(ui.ctx, target, follow, r.held, rest, lifted);
156        store_thumb(ui.ctx, r.id, d);
157
158        let thumb = thumb_rect(ui.ctx, vec2(ox + d.pos.value, rect.center().y), &f);
159        let lift = f.lift.clamp(0.0, 1.0);
160        let knob =
161            self.knob.unwrap_or(if ui.surface.darkness() > 0.5 { Color::gray(0.42) } else { Color::WHITE });
162        let track_c = self.track.unwrap_or(ui.surface.fill_color());
163        let text_c = Color::BLACK.lerp(Color::WHITE, ui.surface.darkness());
164        let quiet_c = ui.surface.secondary_color().fade(0.78);
165        // The face is painted as a separate platter below the labels, so the
166        // labels stay sharp on top of it and both bend in the lens.
167        let mut glass = thumb_glass(ui.ctx, thumb, &f, knob, k);
168        glass.material.tint = None;
169        glass.material.blur = 0.0;
170        glass.material.refraction *= 0.72;
171        glass.material.depth *= 0.55;
172        glass.material.dispersion *= 0.06;
173        glass.material.dark_edge *= 0.10;
174        glass.material.inner_glow *= 1.9;
175        glass.material.shadow *= 0.48;
176        glass.material.shadow_radius *= 1.0 + 0.7 * lift;
177        glass.material.shadow_y *= 1.0 + 0.9 * lift;
178        glass.material.shadow_tint *= 0.3;
179        glass.material.saturation = 1.0;
180        glass.material.light_range.0 = 0.0;
181        glass.material.dark_range.0 = 0.0;
182        let grow = 1.0 + 0.15 * lift;
183        // How much of the platter stays under the lifted lens.
184        let clear = lerp(0.68, 0.92, ui.ctx.theme.tint_above_default());
185
186        let mut p = ui.painter();
187        p.fill(rect, Corner::Capsule, track_c);
188        let outside = p.add_mask(thumb, Corner::Capsule, true, Feather::default());
189        p.with_mask(outside, |p| {
190            for (i, c) in cells.iter().enumerate() {
191                p.text_centered(*c, &texts[i].0, quiet_c, 1.0);
192            }
193        });
194        p.fill(thumb, Corner::Capsule, knob.fade(lerp(1.0, clear, lift)));
195        let inside = p.add_mask(thumb, Corner::Capsule, false, Feather::default());
196        p.with_mask(inside, |p| {
197            for (i, c) in cells.iter().enumerate() {
198                p.text_centered(*c, &texts[i].1, text_c, grow);
199            }
200        });
201        p.glass(&glass);
202        ui.focus_ring(r.id, rect, Corner::Capsule);
203        r
204    }
205}
206
207impl Ui<'_> {
208    /// Adds a segmented control that sets `selected` to the index of the
209    /// chosen label.
210    pub fn segmented(&mut self, selected: &mut usize, labels: &[&str]) -> Response {
211        self.add(Segmented::new(selected, labels))
212    }
213}