use egui::{Response, Ui};
#[derive(Clone, Copy, Debug, PartialEq)]
struct Grab {
from: f32,
frac: f64,
moved: bool,
}
pub(crate) fn thumb_drag(
ui: &Ui,
r: &Response,
at: Option<f32>,
track: (f32, f32),
thumb: (f32, f32),
frac: f64,
) -> Option<f64> {
let id = r.id.with("thumb grab");
let at = at.filter(|_| r.dragged() || r.is_pointer_button_down_on());
let Some(at) = at else {
ui.data_mut(|d| d.remove::<Grab>(id));
return None;
};
let prev = if ui.input(|i| i.pointer.any_pressed()) {
None
} else {
ui.data(|d| d.get_temp::<Grab>(id))
};
let (grab, to) = step(prev, at, track, thumb, frac);
ui.data_mut(|d| d.insert_temp(id, grab));
to
}
fn step(
prev: Option<Grab>,
at: f32,
track: (f32, f32),
thumb: (f32, f32),
frac: f64,
) -> (Grab, Option<f64>) {
let room = (track.1 - thumb.1).max(1.0);
match prev {
None if at >= thumb.0 && at <= thumb.0 + thumb.1 => (
Grab {
from: at,
frac,
moved: false,
},
None,
),
None => {
let f = ((at - track.0 - thumb.1 / 2.0) / room).clamp(0.0, 1.0) as f64;
let grab = Grab {
from: at,
frac: f,
moved: false,
};
(grab, Some(f))
}
Some(g) if !g.moved && at == g.from => (g, None),
Some(g) => {
let f = (g.frac + ((at - g.from) / room) as f64).clamp(0.0, 1.0);
(Grab { moved: true, ..g }, Some(f))
}
}
}
#[cfg(test)]
mod tests {
use super::step;
const TRACK: (f32, f32) = (0.0, 500.0);
const THUMB: (f32, f32) = (200.0, 100.0);
#[test]
fn a_click_on_the_thumb_leaves_the_view_where_it_is() {
let (g, to) = step(None, 290.0, TRACK, THUMB, 0.5);
assert_eq!(to, None);
let (g, to) = step(Some(g), 290.0, TRACK, THUMB, 0.5);
assert_eq!(to, None);
assert!(!g.moved);
}
#[test]
fn a_drag_moves_the_thumb_as_far_as_the_pointer() {
let (g, _) = step(None, 290.0, TRACK, THUMB, 0.5);
let (g, to) = step(Some(g), 330.0, TRACK, THUMB, 0.5);
assert!(to.is_some_and(|f| (f - 0.6).abs() < 1e-6), "{to:?}");
let (g, to) = step(Some(g), 290.0, TRACK, THUMB, 0.6);
assert_eq!(to, Some(0.5));
let (g, to) = step(Some(g), 1000.0, TRACK, THUMB, 0.5);
assert_eq!(to, Some(1.0));
let (_, to) = step(Some(g), -1000.0, TRACK, THUMB, 1.0);
assert_eq!(to, Some(0.0));
}
#[test]
fn a_press_on_the_track_puts_the_thumb_middle_there() {
let (g, to) = step(None, 450.0, TRACK, THUMB, 0.5);
assert_eq!(to, Some(1.0));
let (_, to) = step(Some(g), 450.0, TRACK, THUMB, 1.0);
assert_eq!(to, None);
let (_, to) = step(None, 150.0, TRACK, THUMB, 0.5);
assert_eq!(to, Some(0.25));
}
}