use crate::locked;
use crate::state_unit::StateUnit;
use crate::types::AnnotationId;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::task::AbortHandle;
#[derive(Default)]
struct Dwell {
hovering: Option<AnnotationId>,
resting: Option<AbortHandle>,
rest: u64,
disposed: bool,
}
impl Dwell {
fn interrupt(&mut self) {
self.rest += 1;
if let Some(resting) = self.resting.take() {
resting.abort();
}
}
}
type Say = dyn Fn(Option<&AnnotationId>) + Send + Sync;
pub struct HoverDwell {
dwell: Arc<Mutex<Dwell>>,
say: Arc<Say>,
delay: Duration,
}
impl HoverDwell {
pub fn new(
say: impl Fn(Option<&AnnotationId>) + Send + Sync + 'static,
delay: Duration,
) -> HoverDwell {
HoverDwell {
dwell: Arc::new(Mutex::new(Dwell::default())),
say: Arc::new(say),
delay,
}
}
pub fn enter(&self, annotation_id: &AnnotationId) {
let mut dwell = locked(&self.dwell);
if dwell.disposed || dwell.hovering.as_ref() == Some(annotation_id) {
return;
}
dwell.interrupt();
let (rest, delay) = (dwell.rest, self.delay);
let (shared, say) = (self.dwell.clone(), self.say.clone());
let annotation_id = annotation_id.clone();
let resting = tokio::spawn(async move {
tokio::time::sleep(delay).await;
{
let mut dwell = locked(&shared);
if dwell.rest != rest {
return;
}
dwell.resting = None;
dwell.hovering = Some(annotation_id.clone());
}
say(Some(&annotation_id));
});
dwell.resting = Some(resting.abort_handle());
}
pub fn leave(&self) {
let was_hovering = {
let mut dwell = locked(&self.dwell);
if dwell.disposed {
return;
}
dwell.interrupt();
dwell.hovering.take().is_some()
};
if was_hovering {
(self.say)(None);
}
}
}
impl StateUnit for HoverDwell {
fn dispose(&self) {
let mut dwell = locked(&self.dwell);
dwell.interrupt();
dwell.disposed = true;
}
}
impl Drop for HoverDwell {
fn drop(&mut self) {
self.dispose();
}
}