use std::sync::atomic::{AtomicUsize, Ordering};
use dioxus::prelude::*;
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
pub(crate) const GENERATED_ID_PREFIX: &str = "lumen-uid-";
pub fn use_unique_id() -> String {
use_hook(|| {
format!(
"{GENERATED_ID_PREFIX}{}",
NEXT_ID.fetch_add(1, Ordering::Relaxed)
)
})
}
pub fn use_id_or(id: Option<&str>) -> String {
let generated = use_unique_id();
id.filter(|value| !value.trim().is_empty())
.map_or(generated, str::to_string)
}
pub struct Controllable<T: 'static> {
internal: Signal<T>,
controlled: Memo<Option<T>>,
on_change: CopyValue<Option<EventHandler<T>>>,
}
impl<T: 'static> Clone for Controllable<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: 'static> Copy for Controllable<T> {}
impl<T: Clone + PartialEq + 'static> Controllable<T> {
pub fn get(&self) -> T {
if let Some(value) = self.controlled.read().clone() {
return value;
}
self.internal.read().clone()
}
pub fn peek(&self) -> T {
if let Some(value) = self.controlled.peek().clone() {
return value;
}
self.internal.peek().clone()
}
pub fn is_controlled(&self) -> bool {
self.controlled.peek().is_some()
}
pub fn set(&self, next: T) {
if self.peek() == next {
return;
}
self.select(next);
}
pub fn select(&self, next: T) {
if !self.is_controlled() && *self.internal.peek() != next {
let mut internal = self.internal;
internal.set(next.clone());
}
if let Some(handler) = *self.on_change.peek() {
handler.call(next);
}
}
}
pub fn use_controllable<T: Clone + PartialEq + 'static>(
controlled: impl Into<Option<T>>,
default: impl FnOnce() -> T,
on_change: Option<EventHandler<T>>,
) -> Controllable<T> {
let controlled: Option<T> = controlled.into();
let internal = use_signal(default);
let controlled = use_memo(use_reactive((&controlled,), |(value,)| value));
let mut change_store = use_hook(|| CopyValue::new(None::<EventHandler<T>>));
change_store.set(on_change);
Controllable {
internal,
controlled,
on_change: change_store,
}
}