Skip to main content

lumen_dioxus/
tabs.rs

1//! `Tabs`, `TabsList`, `TabsTrigger`, and `TabsPanel`.
2
3use std::cell::Cell;
4use std::collections::HashMap;
5use std::rc::Rc;
6
7use dioxus::prelude::*;
8
9use crate::class::{Glass, Orientation, compose};
10use crate::hooks::use_unique_id;
11
12#[derive(Clone)]
13struct TabsContext {
14    id: Rc<str>,
15    orientation: Orientation,
16    selected: Signal<String>,
17    /// Render-order counter, so triggers can be sorted without reading the DOM.
18    next_order: Rc<Cell<usize>>,
19    /// `(order, value, disabled)` for every mounted trigger.
20    triggers: Signal<Vec<(usize, String, bool)>>,
21    mounted: Signal<HashMap<String, Rc<MountedData>>>,
22    on_change: Signal<Option<EventHandler<String>>>,
23}
24
25impl TabsContext {
26    fn activate(&self, value: &str) {
27        let mut selected = self.selected;
28
29        if *selected.peek() == value {
30            return;
31        }
32
33        selected.set(value.to_string());
34
35        if let Some(handler) = *self.on_change.peek() {
36            handler.call(value.to_string());
37        }
38    }
39
40    fn trigger_id(&self, value: &str) -> String {
41        format!("{}-tab-{value}", self.id)
42    }
43
44    fn panel_id(&self, value: &str) -> String {
45        format!("{}-panel-{value}", self.id)
46    }
47
48    /// Enabled trigger values in render order.
49    fn enabled_values(&self) -> Vec<String> {
50        let mut triggers = self.triggers.peek().clone();
51        triggers.sort_by_key(|(order, _, _)| *order);
52        triggers
53            .into_iter()
54            .filter(|(_, _, disabled)| !disabled)
55            .map(|(_, value, _)| value)
56            .collect()
57    }
58}
59
60fn use_tabs(component: &str) -> TabsContext {
61    try_use_context::<TabsContext>()
62        .unwrap_or_else(|| panic!("{component} must be used inside its matching Lumen Tabs root."))
63}
64
65/// Props for [`Tabs`].
66#[derive(Props, Clone, PartialEq)]
67pub struct TabsProps {
68    /// The initially selected tab value.
69    #[props(default, into)]
70    pub default_value: String,
71    /// Called with the newly selected value.
72    pub on_value_change: Option<EventHandler<String>>,
73    /// Arrow-key direction of the tab list. Read once, when the tabs mount.
74    #[props(default)]
75    pub orientation: Orientation,
76    /// Base id for the generated tab and panel ids. Read once, when the tabs mount;
77    /// generated when unset.
78    #[props(into)]
79    pub id: Option<String>,
80    /// Glass intensity.
81    #[props(default, into)]
82    pub glass: Glass,
83    /// Extra classes appended after the Lumen classes.
84    #[props(into)]
85    pub class: Option<String>,
86    /// Any other `<div>` or global attribute.
87    #[props(extends = GlobalAttributes, extends = div)]
88    pub attributes: Vec<Attribute>,
89    /// A [`TabsList`] and its [`TabsPanel`]s.
90    pub children: Element,
91}
92
93/// Tabs with roving focus and arrow-key navigation, following the WAI-ARIA tabs pattern.
94///
95/// Arrow keys move and select, like `@santi020k/lumen-react`. Tab and panel ids are
96/// `{id}-tab-{value}` and `{id}-panel-{value}`.
97#[component]
98pub fn Tabs(props: TabsProps) -> Element {
99    let unique = use_unique_id();
100    let generated = format!("ui-tabs-{unique}");
101    let base_id = props.id.clone().unwrap_or(generated);
102    let mut on_change = use_signal(|| props.on_value_change);
103
104    use_context_provider(|| TabsContext {
105        id: Rc::from(base_id.as_str()),
106        orientation: props.orientation,
107        selected: Signal::new(props.default_value.clone()),
108        next_order: Rc::new(Cell::new(0)),
109        triggers: Signal::new(Vec::new()),
110        mounted: Signal::new(HashMap::new()),
111        on_change,
112    });
113
114    use_effect(use_reactive((&props.on_value_change,), move |(handler,)| {
115        on_change.set(handler);
116    }));
117
118    let glass = props.glass.class("ui-tabs");
119    let class = compose([Some("ui-tabs"), glass.as_deref(), props.class.as_deref()]);
120
121    rsx! {
122        div { "data-ui-tabs": "true", class, ..props.attributes, {props.children} }
123    }
124}
125
126/// Props for [`TabsList`].
127#[derive(Props, Clone, PartialEq)]
128pub struct TabsListProps {
129    /// Any other `<div>` or global attribute. Name the list with `aria_label`.
130    #[props(extends = GlobalAttributes, extends = div)]
131    pub attributes: Vec<Attribute>,
132    /// The [`TabsTrigger`]s.
133    pub children: Element,
134}
135
136/// The `tablist` that holds the triggers.
137#[component]
138pub fn TabsList(props: TabsListProps) -> Element {
139    let tabs = use_tabs("TabsList");
140    let orientation = tabs.orientation.as_str();
141
142    rsx! {
143        div { aria_orientation: orientation, role: "tablist", ..props.attributes, {props.children} }
144    }
145}
146
147/// Props for [`TabsTrigger`].
148#[derive(Props, Clone, PartialEq)]
149pub struct TabsTriggerProps {
150    /// The value this trigger selects. Must match a [`TabsPanel`] value.
151    #[props(into)]
152    pub value: String,
153    /// Skips the trigger during selection and keyboard navigation.
154    #[props(default)]
155    pub disabled: bool,
156    /// Any other `<button>` or global attribute.
157    #[props(extends = GlobalAttributes, extends = button)]
158    pub attributes: Vec<Attribute>,
159    /// Trigger label.
160    pub children: Element,
161}
162
163fn next_index(key: &Key, current: usize, len: usize, orientation: Orientation) -> Option<usize> {
164    let (previous, next) = match orientation {
165        Orientation::Horizontal => (Key::ArrowLeft, Key::ArrowRight),
166        Orientation::Vertical => (Key::ArrowUp, Key::ArrowDown),
167    };
168
169    match key {
170        key if *key == next => Some((current + 1) % len),
171        key if *key == previous => Some((current + len - 1) % len),
172        Key::Home => Some(0),
173        Key::End => Some(len - 1),
174        _ => None,
175    }
176}
177
178/// A `tab` button. Click, arrow keys, Home, and End move the selection.
179#[component]
180pub fn TabsTrigger(props: TabsTriggerProps) -> Element {
181    let tabs = use_tabs("TabsTrigger");
182    let value = props.value.clone();
183    let disabled = props.disabled;
184    let order = use_hook(|| {
185        let order = tabs.next_order.get();
186        tabs.next_order.set(order + 1);
187        order
188    });
189
190    let mut triggers = tabs.triggers;
191    use_effect(use_reactive(
192        (&value, &disabled),
193        move |(value, disabled)| {
194            let mut list = triggers.write();
195            list.retain(|(entry, _, _)| *entry != order);
196            list.push((order, value, disabled));
197        },
198    ));
199    use_drop(move || {
200        triggers.write().retain(|(entry, _, _)| *entry != order);
201    });
202
203    let selected = *tabs.selected.read() == value;
204    let (click_tabs, key_tabs) = (tabs.clone(), tabs.clone());
205    let click_value = value.clone();
206    let key_value = value.clone();
207    let mount_value = value.clone();
208    let mut mounted = tabs.mounted;
209
210    rsx! {
211        button {
212            aria_controls: tabs.panel_id(&value),
213            aria_selected: if selected { "true" } else { "false" },
214            disabled,
215            id: tabs.trigger_id(&value),
216            role: "tab",
217            tabindex: if selected { "0" } else { "-1" },
218            r#type: "button",
219            "data-value": value,
220            onclick: move |_| click_tabs.activate(&click_value),
221            onkeydown: move |event| {
222                let enabled = key_tabs.enabled_values();
223
224                if enabled.is_empty() {
225                    return;
226                }
227
228                let current = enabled.iter().position(|entry| *entry == key_value).unwrap_or(0);
229
230                if let Some(index) =
231                    next_index(&event.key(), current, enabled.len(), key_tabs.orientation)
232                {
233                    event.prevent_default();
234                    let next = enabled[index].clone();
235                    key_tabs.activate(&next);
236
237                    if let Some(node) = key_tabs.mounted.peek().get(&next).cloned() {
238                        spawn(async move {
239                            let _ = node.set_focus(true).await;
240                        });
241                    }
242                }
243            },
244            onmounted: move |event| {
245                mounted.write().insert(mount_value.clone(), event.data());
246            },
247            ..props.attributes,
248            {props.children}
249        }
250    }
251}
252
253/// Props for [`TabsPanel`].
254#[derive(Props, Clone, PartialEq)]
255pub struct TabsPanelProps {
256    /// The trigger value that shows this panel.
257    #[props(into)]
258    pub value: String,
259    /// Any other `<div>` or global attribute.
260    #[props(extends = GlobalAttributes, extends = div)]
261    pub attributes: Vec<Attribute>,
262    /// Panel content.
263    pub children: Element,
264}
265
266/// The `tabpanel` shown while its trigger is selected.
267#[component]
268pub fn TabsPanel(props: TabsPanelProps) -> Element {
269    let tabs = use_tabs("TabsPanel");
270    let selected = *tabs.selected.read() == props.value;
271
272    rsx! {
273        div {
274            aria_labelledby: tabs.trigger_id(&props.value),
275            hidden: !selected,
276            id: tabs.panel_id(&props.value),
277            role: "tabpanel",
278            tabindex: "0",
279            ..props.attributes,
280            {props.children}
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::{Key, Orientation, next_index};
288
289    #[test]
290    fn arrow_keys_loop_through_tabs() {
291        let h = Orientation::Horizontal;
292        assert_eq!(next_index(&Key::ArrowRight, 2, 3, h), Some(0));
293        assert_eq!(next_index(&Key::ArrowLeft, 0, 3, h), Some(2));
294        assert_eq!(next_index(&Key::Home, 2, 3, h), Some(0));
295        assert_eq!(next_index(&Key::End, 0, 3, h), Some(2));
296        assert_eq!(next_index(&Key::ArrowDown, 0, 3, h), None);
297        assert_eq!(
298            next_index(&Key::ArrowDown, 0, 3, Orientation::Vertical),
299            Some(1)
300        );
301    }
302}