Skip to main content

lumen_dioxus/inputs/
tag_group.rs

1//! `TagGroup` and `TagGroupItem`: a list of tags that can be removed.
2//!
3//! lumen-react's `TagGroup` is a `role="list"` container; its tags are `[data-ui-tag]` list items
4//! with optional `[data-ui-tag-remove]` buttons that the Lumen web runtime wires up. Here
5//! [`TagGroupItem`] renders that markup and removal is state-driven: the remove button reports the
6//! tag's value to `on_remove` handlers, and the app drops the tag from its list.
7
8use dioxus::prelude::*;
9
10use super::radio_group::is_space;
11use crate::class::compose;
12
13#[derive(Clone, Copy)]
14struct TagGroupContext {
15    on_remove: CopyValue<Option<EventHandler<String>>>,
16}
17
18/// Props for [`TagGroup`].
19#[derive(Props, Clone, PartialEq)]
20pub struct TagGroupProps {
21    /// ARIA role of the container. Defaults to `list`.
22    #[props(default = "list".to_string(), into)]
23    pub role: String,
24    /// Called with a tag's value when one of its remove buttons is activated, like the
25    /// `ui:tag-remove` event of the Lumen web runtime.
26    pub on_remove: Option<EventHandler<String>>,
27    /// Extra classes appended after the Lumen class.
28    #[props(into)]
29    pub class: Option<String>,
30    /// Any other `<div>` or global attribute. Name the list with `aria_label`.
31    #[props(extends = GlobalAttributes, extends = div)]
32    pub attributes: Vec<Attribute>,
33    /// The [`TagGroupItem`]s.
34    pub children: Element,
35}
36
37/// A wrapping list of tags, such as selected filters or entered keywords.
38#[component]
39pub fn TagGroup(props: TagGroupProps) -> Element {
40    let mut on_remove = use_hook(|| CopyValue::new(None::<EventHandler<String>>));
41    on_remove.set(props.on_remove);
42    use_context_provider(|| TagGroupContext { on_remove });
43
44    let class = compose([Some("ui-tag-group"), props.class.as_deref()]);
45
46    rsx! {
47        div { class, role: props.role, ..props.attributes, {props.children} }
48    }
49}
50
51/// Props for [`TagGroupItem`].
52#[derive(Props, Clone, PartialEq)]
53pub struct TagGroupItemProps {
54    /// The tag's value, rendered as `data-value` and reported when the tag is removed.
55    #[props(into)]
56    pub value: Option<String>,
57    /// Shows the remove button even without an item `on_remove` handler, for groups that handle
58    /// removal in [`TagGroup`]'s `on_remove`.
59    #[props(default)]
60    pub removable: bool,
61    /// Accessible name of the remove button. Defaults to `Remove {value}`, or `Remove` without a
62    /// value; set it to a readable phrase such as `Remove Astro`.
63    #[props(into)]
64    pub remove_label: Option<String>,
65    /// Called with the tag's value (empty without one) when its remove button is activated. Setting
66    /// it shows the remove button.
67    pub on_remove: Option<EventHandler<String>>,
68    /// Extra classes appended to the tag.
69    #[props(into)]
70    pub class: Option<String>,
71    /// Any other `<span>` or global attribute.
72    #[props(extends = GlobalAttributes, extends = span)]
73    pub attributes: Vec<Attribute>,
74    /// The tag's text.
75    pub children: Element,
76}
77
78/// One tag in a [`TagGroup`]: a `role="listitem"` with an optional remove button.
79///
80/// The remove button responds to click, Enter, and Space on every renderer and calls the item's
81/// and the group's `on_remove` with the tag's `value`.
82#[component]
83pub fn TagGroupItem(props: TagGroupItemProps) -> Element {
84    let group = try_use_context::<TagGroupContext>();
85    let removable = props.removable || props.on_remove.is_some();
86    let remove_label = props.remove_label.clone().unwrap_or_else(|| {
87        props
88            .value
89            .as_ref()
90            .map_or_else(|| "Remove".to_string(), |value| format!("Remove {value}"))
91    });
92    let reported = props.value.clone().unwrap_or_default();
93    let item_handler = props.on_remove;
94
95    let remove = move |value: &str| {
96        if let Some(handler) = item_handler {
97            handler.call(value.to_string());
98        }
99
100        if let Some(handler) = group.and_then(|group| *group.on_remove.peek()) {
101            handler.call(value.to_string());
102        }
103    };
104    let (click_value, down_value, up_value) = (reported.clone(), reported.clone(), reported);
105
106    rsx! {
107        span {
108            class: props.class,
109            "data-ui-tag": "true",
110            "data-value": props.value,
111            role: "listitem",
112            ..props.attributes,
113            {props.children}
114            if removable {
115                button {
116                    aria_label: remove_label,
117                    "data-ui-tag-remove": "true",
118                    r#type: "button",
119                    onclick: move |_| remove(&click_value),
120                    onkeydown: move |event| {
121                        // Browsers click a focused button on Enter key-down; handling it here gives
122                        // one removal on the web and on Dioxus Native.
123                        if event.key() == Key::Enter {
124                            event.prevent_default();
125                            remove(&down_value);
126                        }
127                    },
128                    onkeyup: move |event| {
129                        if is_space(&event.key()) {
130                            event.prevent_default();
131                            remove(&up_value);
132                        }
133                    },
134                    "Remove"
135                }
136            }
137        }
138    }
139}