lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `TagGroup` and `TagGroupItem`: a list of tags that can be removed.
//!
//! lumen-react's `TagGroup` is a `role="list"` container; its tags are `[data-ui-tag]` list items
//! with optional `[data-ui-tag-remove]` buttons that the Lumen web runtime wires up. Here
//! [`TagGroupItem`] renders that markup and removal is state-driven: the remove button reports the
//! tag's value to `on_remove` handlers, and the app drops the tag from its list.

use dioxus::prelude::*;

use super::radio_group::is_space;
use crate::class::compose;

#[derive(Clone, Copy)]
struct TagGroupContext {
    on_remove: CopyValue<Option<EventHandler<String>>>,
}

/// Props for [`TagGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct TagGroupProps {
    /// ARIA role of the container. Defaults to `list`.
    #[props(default = "list".to_string(), into)]
    pub role: String,
    /// Called with a tag's value when one of its remove buttons is activated, like the
    /// `ui:tag-remove` event of the Lumen web runtime.
    pub on_remove: Option<EventHandler<String>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the list with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The [`TagGroupItem`]s.
    pub children: Element,
}

/// A wrapping list of tags, such as selected filters or entered keywords.
#[component]
pub fn TagGroup(props: TagGroupProps) -> Element {
    let mut on_remove = use_hook(|| CopyValue::new(None::<EventHandler<String>>));
    on_remove.set(props.on_remove);
    use_context_provider(|| TagGroupContext { on_remove });

    let class = compose([Some("ui-tag-group"), props.class.as_deref()]);

    rsx! {
        div { class, role: props.role, ..props.attributes, {props.children} }
    }
}

/// Props for [`TagGroupItem`].
#[derive(Props, Clone, PartialEq)]
pub struct TagGroupItemProps {
    /// The tag's value, rendered as `data-value` and reported when the tag is removed.
    #[props(into)]
    pub value: Option<String>,
    /// Shows the remove button even without an item `on_remove` handler, for groups that handle
    /// removal in [`TagGroup`]'s `on_remove`.
    #[props(default)]
    pub removable: bool,
    /// Accessible name of the remove button. Defaults to `Remove {value}`, or `Remove` without a
    /// value; set it to a readable phrase such as `Remove Astro`.
    #[props(into)]
    pub remove_label: Option<String>,
    /// Called with the tag's value (empty without one) when its remove button is activated. Setting
    /// it shows the remove button.
    pub on_remove: Option<EventHandler<String>>,
    /// Extra classes appended to the tag.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// The tag's text.
    pub children: Element,
}

/// One tag in a [`TagGroup`]: a `role="listitem"` with an optional remove button.
///
/// The remove button responds to click, Enter, and Space on every renderer and calls the item's
/// and the group's `on_remove` with the tag's `value`.
#[component]
pub fn TagGroupItem(props: TagGroupItemProps) -> Element {
    let group = try_use_context::<TagGroupContext>();
    let removable = props.removable || props.on_remove.is_some();
    let remove_label = props.remove_label.clone().unwrap_or_else(|| {
        props
            .value
            .as_ref()
            .map_or_else(|| "Remove".to_string(), |value| format!("Remove {value}"))
    });
    let reported = props.value.clone().unwrap_or_default();
    let item_handler = props.on_remove;

    let remove = move |value: &str| {
        if let Some(handler) = item_handler {
            handler.call(value.to_string());
        }

        if let Some(handler) = group.and_then(|group| *group.on_remove.peek()) {
            handler.call(value.to_string());
        }
    };
    let (click_value, down_value, up_value) = (reported.clone(), reported.clone(), reported);

    rsx! {
        span {
            class: props.class,
            "data-ui-tag": "true",
            "data-value": props.value,
            role: "listitem",
            ..props.attributes,
            {props.children}
            if removable {
                button {
                    aria_label: remove_label,
                    "data-ui-tag-remove": "true",
                    r#type: "button",
                    onclick: move |_| remove(&click_value),
                    onkeydown: move |event| {
                        // Browsers click a focused button on Enter key-down; handling it here gives
                        // one removal on the web and on Dioxus Native.
                        if event.key() == Key::Enter {
                            event.prevent_default();
                            remove(&down_value);
                        }
                    },
                    onkeyup: move |event| {
                        if is_space(&event.key()) {
                            event.prevent_default();
                            remove(&up_value);
                        }
                    },
                    "Remove"
                }
            }
        }
    }
}