use std::time::{Duration, Instant};
pub const AUTO_HIDE_DWELL: Duration = Duration::from_millis(400);
#[derive(Default)]
pub struct SidebarDwell {
anchor: Option<Instant>,
}
impl SidebarDwell {
pub fn arm(&mut self, now: Instant) {
if self.anchor.is_none() {
self.anchor = Some(now);
}
}
pub fn due(&self, now: Instant, threshold: Duration) -> bool {
matches!(self.anchor, Some(a) if now.duration_since(a) >= threshold)
}
pub fn armed(&self) -> bool {
self.anchor.is_some()
}
pub fn disarm(&mut self) {
self.anchor = None;
}
pub fn restamp(&mut self, now: Instant) {
if self.anchor.is_some() {
self.anchor = Some(now);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dwell_becomes_due_only_after_the_threshold() {
let mut d = SidebarDwell::default();
let t0 = Instant::now();
d.arm(t0);
assert!(
!d.due(t0, AUTO_HIDE_DWELL),
"not due the instant focus left"
);
assert!(
!d.due(t0 + Duration::from_millis(399), AUTO_HIDE_DWELL),
"not due one ms before the threshold"
);
assert!(
d.due(t0 + Duration::from_millis(400), AUTO_HIDE_DWELL),
"due once the 400ms grace elapses"
);
}
#[test]
fn an_unarmed_dwell_is_never_due() {
let d = SidebarDwell::default();
let t0 = Instant::now();
assert!(!d.armed());
assert!(
!d.due(t0 + Duration::from_secs(10), AUTO_HIDE_DWELL),
"no focus move means nothing to collapse, however long we wait"
);
}
#[test]
fn re_arming_does_not_push_the_deadline() {
let mut d = SidebarDwell::default();
let t0 = Instant::now();
d.arm(t0);
d.arm(t0 + Duration::from_millis(100));
d.arm(t0 + Duration::from_millis(200));
d.arm(t0 + Duration::from_millis(399));
assert!(
d.due(t0 + Duration::from_millis(400), AUTO_HIDE_DWELL),
"the deadline is anchored at the FIRST departure, not the latest"
);
}
#[test]
fn disarming_cancels_a_pending_collapse() {
let mut d = SidebarDwell::default();
let t0 = Instant::now();
d.arm(t0);
d.disarm();
assert!(!d.armed());
assert!(
!d.due(t0 + Duration::from_secs(1), AUTO_HIDE_DWELL),
"focus coming back cancels the collapse outright"
);
}
#[test]
fn re_arming_after_a_disarm_starts_a_fresh_window() {
let mut d = SidebarDwell::default();
let t0 = Instant::now();
d.arm(t0);
d.disarm();
let t1 = t0 + Duration::from_millis(500);
d.arm(t1);
assert!(
!d.due(t1 + Duration::from_millis(399), AUTO_HIDE_DWELL),
"the second departure gets its own full grace period"
);
assert!(d.due(t1 + Duration::from_millis(400), AUTO_HIDE_DWELL));
}
}