use std::{
ops::Deref,
sync::atomic::{AtomicUsize, Ordering},
};
use crate::context::{ACTIVE, HOVER};
static ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WidgetId(usize);
impl Default for WidgetId {
fn default() -> Self {
WidgetId::next()
}
}
impl WidgetId {
pub const ZERO: WidgetId = WidgetId(0);
pub fn next() -> Self {
WidgetId(ID_COUNTER.fetch_add(1, Ordering::Relaxed))
}
pub fn custom(id: impl Into<usize>) -> Self {
let id = id.into();
if id == 0 {
panic!("Id could not be zero!");
}
WidgetId(id)
}
pub fn set_hover(&self) {
HOVER.store(self.0, Ordering::Release);
ACTIVE.store(0, Ordering::Release);
}
pub fn is_hover(&self) -> bool {
self.0 == HOVER.load(Ordering::Acquire)
}
pub fn is_active(&self) -> bool {
self.0 == ACTIVE.load(Ordering::Acquire)
}
}
impl Deref for WidgetId {
type Target = usize;
fn deref(&self) -> &Self::Target {
&self.0
}
}