lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Hooks shared by the components: generated ids and controlled or uncontrolled state.

use std::sync::atomic::{AtomicUsize, Ordering};

use dioxus::prelude::*;

static NEXT_ID: AtomicUsize = AtomicUsize::new(0);

/// The prefix of every generated id. The parity tests normalize ids that start with it.
pub(crate) const GENERATED_ID_PREFIX: &str = "lumen-uid-";

/// A unique id that stays stable for the lifetime of the calling component, like React's `useId`.
///
/// Generated ids look like `lumen-uid-7`. Use them to wire `aria-controls`, `aria-labelledby`,
/// and `for` attributes when the app does not pass its own id.
pub fn use_unique_id() -> String {
    use_hook(|| {
        format!(
            "{GENERATED_ID_PREFIX}{}",
            NEXT_ID.fetch_add(1, Ordering::Relaxed)
        )
    })
}

/// The `id` prop when it is set and not empty, otherwise a stable generated id.
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)
}

/// A value that is either controlled by a prop or kept internally, like the controlled and
/// uncontrolled props of `@santi020k/lumen-react` components.
///
/// It is `Copy`, so event handlers can capture it. [`Controllable::set`] updates the internal value
/// only while uncontrolled and calls the change handler when the value changes;
/// [`Controllable::select`] always calls it, for picks that confirm the current value.
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> {
    /// The current value. Reading it subscribes the reader to both controlled and internal
    /// changes, so compound parts that read it through context re-render when the prop changes.
    pub fn get(&self) -> T {
        if let Some(value) = self.controlled.read().clone() {
            return value;
        }

        self.internal.read().clone()
    }

    /// The current value without subscribing.
    pub fn peek(&self) -> T {
        if let Some(value) = self.controlled.peek().clone() {
            return value;
        }

        self.internal.peek().clone()
    }

    /// Whether a prop owns the value.
    pub fn is_controlled(&self) -> bool {
        self.controlled.peek().is_some()
    }

    /// Requests a new value: stores it when uncontrolled and notifies the change handler when the
    /// value differs from the current one.
    pub fn set(&self, next: T) {
        if self.peek() == next {
            return;
        }

        self.select(next);
    }

    /// Like [`Controllable::set`], but always calls the change handler, even when `next` equals
    /// the current value. Use it when picking the current value is a meaningful confirmation,
    /// such as choosing the already selected day in a date picker.
    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);
        }
    }
}

/// Keeps a value that a prop may control.
///
/// Call it on every render with the current `controlled` prop (`Some(value)` or `None`) and change
/// handler; `default` seeds the internal value once.
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);
    // A memo keyed on the prop, so readers subscribe to controlled changes too.
    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,
    }
}