Skip to main content

rust_glass/widgets/
toggle.rs

1//! Switch.
2
3use crate::accessibility::{Action, Role};
4use crate::animation::Tuning;
5use crate::color::Color;
6use crate::context::{Cursor, Response, Sense};
7use crate::geometry::{Rect, vec2};
8use crate::input::Key;
9use crate::material::Corner;
10use crate::text::TextStyle;
11use crate::ui::{Ui, Widget};
12use crate::widgets::thumb::{drag_target, load_thumb, store_thumb, thumb_glass, thumb_rect};
13
14/// On and off.
15pub struct Toggle<'a> {
16    on: &'a mut bool,
17    label: &'a str,
18    tint: Color,
19    scale: f32,
20}
21
22impl<'a> Toggle<'a> {
23    /// Creates a switch for `on`.
24    pub fn new(on: &'a mut bool) -> Self {
25        Self { on, label: "", tint: Color::GREEN, scale: 1.0 }
26    }
27    /// Shows `label` before the switch. In a vertical layout the row then
28    /// takes the full width, with the switch at the end.
29    pub fn label(mut self, label: &'a str) -> Self {
30        self.label = label;
31        self
32    }
33    /// Sets the color when on. The default is green.
34    pub fn tint(mut self, color: Color) -> Self {
35        self.tint = color;
36        self
37    }
38    /// Scales the switch.
39    pub fn scale(mut self, scale: f32) -> Self {
40        self.scale = scale;
41        self
42    }
43}
44
45impl Widget for Toggle<'_> {
46    fn ui(self, ui: &mut Ui) -> Response {
47        let k = self.scale;
48        let size = vec2(60.0, 27.0) * k;
49        let rest = vec2(36.0, 23.0) * k;
50        let lifted = vec2(52.0, 35.0) * k;
51        let st = TextStyle::new(ui.ctx.theme.body_size);
52        let text = (!self.label.is_empty()).then(|| ui.layout_text(self.label, &st));
53        let fill_row = text.is_some() && !ui.is_horizontal();
54        let tw = text.as_ref().map_or(0.0, |t| t.size.x + 12.0);
55        let total = if fill_row { ui.available_width() } else { size.x + tw };
56        let rect = ui.allocate(vec2(total, size.y + 4.0));
57        let id = ui.next_id();
58        let track = Rect::from_min_size(vec2(rect.max.x - size.x, rect.center().y - size.y * 0.5), size)
59            .snap(ui.ctx.pixels_per_point);
60        let mut r = ui.interact(id, rect, Sense::Drag);
61        ui.ctx.focusable(id);
62        if r.hovered {
63            ui.ctx.cursor = Cursor::Pointer;
64        }
65        let pad = 2.0 * k;
66        let ox = track.min.x;
67        let x0 = pad + rest.x * 0.5;
68        let x1 = track.width() - pad - rest.x * 0.5;
69        let mut d = load_thumb(ui.ctx, id);
70        let before = *self.on;
71        let dragged = drag_target(ui.ctx, id, &r, ox, d.pos.value, x0, x1, 5.0 * k);
72        let mid = (x0 + x1) * 0.5;
73        if r.released {
74            let moved = r.pointer.is_some_and(|p| (p.x - ui.ctx.input.press_origin.x).abs() > 4.0);
75            *self.on = if moved { d.pos.value > mid } else { !before };
76        }
77        if (r.focused && (ui.ctx.input.take_key(Key::Space) || ui.ctx.input.take_key(Key::Enter)))
78            || ui.ctx.access_requested(id, &Action::Click)
79        {
80            *self.on = !*self.on;
81        }
82        if let Some(n) = ui.access(id, Role::Switch, rect) {
83            n.label(self.label).toggled(*self.on);
84        }
85        r.changed = before != *self.on;
86        let home = if *self.on { x1 } else { x0 };
87        // Without a drag a press only lifts the thumb where it is.
88        let moved = r.pointer.is_some_and(|p| (p.x - ui.ctx.input.press_origin.x).abs() > 3.0);
89        let target = dragged.filter(|_| moved).unwrap_or(home);
90        if r.changed && d.lift.value < 0.3 {
91            d.lift.value = 0.31;
92        }
93        let follow =
94            if dragged.is_some() && moved { Tuning::new(0.14, 0.9) } else { Tuning::new(0.32, 0.80) };
95        let f = d.step(ui.ctx, target, follow, r.held, rest, lifted);
96        store_thumb(ui.ctx, id, d);
97
98        let t = ((d.pos.value - x0) / (x1 - x0)).clamp(0.0, 1.0);
99        let off = ui.surface.strong_fill_color();
100        let knob = ui.surface.thumb_color();
101        let thumb = thumb_rect(ui.ctx, vec2(ox + d.pos.value, track.center().y), &f);
102        let glass = thumb_glass(ui.ctx, thumb, &f, knob, k);
103        let tc = ui.surface.text_color();
104        let on_c = self.tint;
105        let mut p = ui.painter();
106        if let Some(l) = &text {
107            p.text(vec2(rect.min.x, rect.center().y - l.size.y * 0.5), l, tc);
108        }
109        p.fill(track, Corner::Capsule, off);
110        p.fill(track, Corner::Capsule, on_c.fade(t));
111        p.glass(&glass);
112        ui.focus_ring(id, track, Corner::Capsule);
113        r
114    }
115}
116
117impl Ui<'_> {
118    /// Adds a switch with a label.
119    pub fn toggle(&mut self, on: &mut bool, label: &str) -> Response {
120        self.add(Toggle::new(on).label(label))
121    }
122}