Skip to main content

lumen_dioxus/navigation/
menus.rs

1//! `Menubar`, `MenubarItem`, `NavigationMenu`, `NavigationMenuLink`, `Toggle`, and `ToggleGroup`.
2
3use dioxus::prelude::*;
4
5use crate::class::{Glass, compose};
6use crate::hooks::use_controllable;
7
8use super::chrome::{NavigationVariant, surface};
9use super::roving::{Roving, RovingAxis, roving_move};
10
11/// Roving focus shared by a [`Menubar`] and its [`MenubarItem`]s.
12#[derive(Clone, Copy)]
13struct MenubarContext(Roving);
14
15/// Arrow-key movement shared by a [`NavigationMenu`] and its [`NavigationMenuLink`]s.
16#[derive(Clone, Copy)]
17struct NavigationMenuContext(Roving);
18
19/// Roving focus shared by a [`ToggleGroup`] and its [`Toggle`]s.
20#[derive(Clone, Copy)]
21struct ToggleGroupContext(Roving);
22
23/// Handles a roving key on an item; returns whether focus moved.
24fn handle_roving_key(roving: Roving, key: usize, event: &KeyboardEvent) -> bool {
25    let modifiers = event.modifiers();
26
27    if event.is_composing() || modifiers.alt() || modifiers.ctrl() || modifiers.meta() {
28        return false;
29    }
30
31    let Some(movement) = roving_move(&event.key(), RovingAxis::Both, false) else {
32        return false;
33    };
34
35    event.prevent_default();
36    roving.move_focus(Some(key), movement).is_some()
37}
38
39/// Props for [`Menubar`].
40#[derive(Props, Clone, PartialEq)]
41pub struct MenubarProps {
42    /// Glass intensity.
43    #[props(default, into)]
44    pub glass: Glass,
45    /// Extra classes appended after the Lumen classes.
46    #[props(into)]
47    pub class: Option<String>,
48    /// Any other `<nav>` or global attribute. Name the bar with `aria_label`.
49    #[props(extends = GlobalAttributes, extends = nav)]
50    pub attributes: Vec<Attribute>,
51    /// The [`MenubarItem`]s.
52    pub children: Element,
53}
54
55/// A horizontal bar of application menus with one tab stop and arrow-key movement.
56///
57/// Arrow keys, Home, and End move focus between [`MenubarItem`]s, skipping disabled ones, like
58/// Lumen's roving web runtime. Once mounted, only the focused item is in the tab order.
59#[component]
60pub fn Menubar(props: MenubarProps) -> Element {
61    let roving = Roving::use_new();
62    use_context_provider(|| MenubarContext(roving));
63
64    let glass = props.glass.class("ui-menubar");
65    let class = compose([Some("ui-menubar"), glass.as_deref(), props.class.as_deref()]);
66
67    rsx! {
68        nav {
69            class,
70            "data-surface": surface(props.glass),
71            "data-ui-menubar": "true",
72            ..props.attributes,
73            {props.children}
74        }
75    }
76}
77
78/// Props for [`MenubarItem`].
79#[derive(Props, Clone, PartialEq)]
80pub struct MenubarItemProps {
81    /// Skips the item during keyboard movement and disables it.
82    #[props(default)]
83    pub disabled: bool,
84    /// Activation handler.
85    pub onclick: Option<EventHandler<MouseEvent>>,
86    /// Extra classes.
87    #[props(into)]
88    pub class: Option<String>,
89    /// Any other `<button>` or global attribute, such as `aria_haspopup` for a menu trigger.
90    #[props(extends = GlobalAttributes, extends = button)]
91    pub attributes: Vec<Attribute>,
92    /// Item label.
93    pub children: Element,
94}
95
96/// A `menuitem` button inside a [`Menubar`].
97#[component]
98pub fn MenubarItem(props: MenubarItemProps) -> Element {
99    let MenubarContext(roving) = try_use_context::<MenubarContext>()
100        .unwrap_or_else(|| panic!("MenubarItem must be used inside a Lumen Menubar."));
101    let key = roving.use_item(props.disabled, false);
102    let onclick = props.onclick;
103
104    rsx! {
105        button {
106            class: props.class,
107            disabled: props.disabled,
108            role: "menuitem",
109            tabindex: roving.tabindex(key),
110            r#type: "button",
111            onclick: move |event| {
112                if let Some(handler) = onclick {
113                    handler.call(event);
114                }
115            },
116            onfocus: move |_| roving.focused(key),
117            onkeydown: move |event| {
118                handle_roving_key(roving, key, &event);
119            },
120            onmounted: move |event| roving.mount(key, event.data()),
121            ..props.attributes,
122            {props.children}
123        }
124    }
125}
126
127/// Props for [`NavigationMenu`].
128#[derive(Props, Clone, PartialEq)]
129pub struct NavigationMenuProps {
130    /// Surface styling or hooks only.
131    #[props(default)]
132    pub variant: NavigationVariant,
133    /// Glass intensity.
134    #[props(default, into)]
135    pub glass: Glass,
136    /// Extra classes appended after the Lumen classes.
137    #[props(into)]
138    pub class: Option<String>,
139    /// Any other `<nav>` or global attribute. Name the landmark with `aria_label`.
140    #[props(extends = GlobalAttributes, extends = nav)]
141    pub attributes: Vec<Attribute>,
142    /// The links, usually [`NavigationMenuLink`]s.
143    pub children: Element,
144}
145
146/// A row of primary navigation links.
147///
148/// Every link stays in the tab order. [`NavigationMenuLink`]s also move focus with the arrow
149/// keys, Home, and End.
150#[component]
151pub fn NavigationMenu(props: NavigationMenuProps) -> Element {
152    let roving = Roving::use_new();
153    use_context_provider(|| NavigationMenuContext(roving));
154
155    let unstyled = props.variant.modifier("ui-navigation-menu");
156    let glass = props.glass.class("ui-navigation-menu");
157    let class = compose([
158        Some("ui-navigation-menu"),
159        unstyled.as_deref(),
160        glass.as_deref(),
161        props.class.as_deref(),
162    ]);
163
164    rsx! {
165        nav {
166            class,
167            "data-slot": "navigation-menu",
168            "data-surface": surface(props.glass),
169            "data-ui-navigation-menu": "true",
170            "data-variant": props.variant.as_str(),
171            ..props.attributes,
172            {props.children}
173        }
174    }
175}
176
177/// Props for [`NavigationMenuLink`].
178#[derive(Props, Clone, PartialEq)]
179pub struct NavigationMenuLinkProps {
180    /// Marks the link as the current page with `aria-current="page"`.
181    #[props(default)]
182    pub current: bool,
183    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
184    pub onclick: Option<EventHandler<MouseEvent>>,
185    /// Extra classes.
186    #[props(into)]
187    pub class: Option<String>,
188    /// Any other `<a>` or global attribute, such as `href`.
189    #[props(extends = GlobalAttributes, extends = a)]
190    pub attributes: Vec<Attribute>,
191    /// Link text.
192    pub children: Element,
193}
194
195/// A link inside a [`NavigationMenu`]. Outside one it is a plain link.
196#[component]
197pub fn NavigationMenuLink(props: NavigationMenuLinkProps) -> Element {
198    let roving =
199        try_use_context::<NavigationMenuContext>().map(|NavigationMenuContext(roving)| roving);
200    let key = roving.map(|roving| roving.use_item(false, false));
201    let onclick = props.onclick;
202
203    rsx! {
204        a {
205            aria_current: props.current.then_some("page"),
206            class: props.class,
207            onclick: move |event| {
208                if let Some(handler) = onclick {
209                    handler.call(event);
210                }
211            },
212            onkeydown: move |event| {
213                if let (Some(roving), Some(key)) = (roving, key) {
214                    handle_roving_key(roving, key, &event);
215                }
216            },
217            onmounted: move |event| {
218                if let (Some(roving), Some(key)) = (roving, key) {
219                    roving.mount(key, event.data());
220                }
221            },
222            ..props.attributes,
223            {props.children}
224        }
225    }
226}
227
228/// Props for [`Toggle`].
229#[derive(Props, Clone, PartialEq)]
230pub struct ToggleProps {
231    /// Controlled pressed state. Setting it renders `data-ui-controlled`, like lumen-react's
232    /// `controlled` prop.
233    pub pressed: Option<bool>,
234    /// Initial state when uncontrolled.
235    #[props(default)]
236    pub default_pressed: bool,
237    /// Called with the next pressed state.
238    pub on_pressed_change: Option<EventHandler<bool>>,
239    /// Disables the toggle.
240    #[props(default)]
241    pub disabled: bool,
242    /// Click handler, called before the state changes.
243    pub onclick: Option<EventHandler<MouseEvent>>,
244    /// Extra classes appended after the Lumen class.
245    #[props(into)]
246    pub class: Option<String>,
247    /// Any other `<button>` or global attribute. Name icon-only toggles with `aria_label`.
248    #[props(extends = GlobalAttributes, extends = button)]
249    pub attributes: Vec<Attribute>,
250    /// Toggle label or icon.
251    pub children: Element,
252}
253
254/// A two-state button with `aria-pressed`, such as bold or mute.
255///
256/// Inside a [`ToggleGroup`] it joins the group's single tab stop and arrow-key movement.
257#[component]
258pub fn Toggle(props: ToggleProps) -> Element {
259    let pressed = use_controllable(
260        props.pressed,
261        || props.default_pressed,
262        props.on_pressed_change,
263    );
264    let group = try_use_context::<ToggleGroupContext>().map(|ToggleGroupContext(roving)| roving);
265    let key = group.map(|roving| roving.use_item(props.disabled, false));
266    let class = compose([Some("ui-toggle"), props.class.as_deref()]);
267    let is_pressed = pressed.get();
268    let onclick = props.onclick;
269
270    rsx! {
271        button {
272            aria_pressed: if is_pressed { "true" } else { "false" },
273            class,
274            "data-ui-controlled": props.pressed.is_some().then_some("true"),
275            "data-ui-toggle": "true",
276            disabled: props.disabled,
277            tabindex: group.zip(key).and_then(|(roving, key)| roving.tabindex(key)),
278            r#type: "button",
279            onclick: move |event| {
280                if let Some(handler) = onclick {
281                    handler.call(event);
282                }
283
284                pressed.set(!pressed.peek());
285            },
286            onfocus: move |_| {
287                if let (Some(roving), Some(key)) = (group, key) {
288                    roving.focused(key);
289                }
290            },
291            onkeydown: move |event| {
292                if let (Some(roving), Some(key)) = (group, key) {
293                    handle_roving_key(roving, key, &event);
294                }
295            },
296            onmounted: move |event| {
297                if let (Some(roving), Some(key)) = (group, key) {
298                    roving.mount(key, event.data());
299                }
300            },
301            ..props.attributes,
302            {props.children}
303        }
304    }
305}
306
307/// Props for [`ToggleGroup`].
308#[derive(Props, Clone, PartialEq)]
309pub struct ToggleGroupProps {
310    /// Extra classes appended after the Lumen class.
311    #[props(into)]
312    pub class: Option<String>,
313    /// Any other `<div>` or global attribute. Name the group with `role: "group"` and
314    /// `aria_label`.
315    #[props(extends = GlobalAttributes, extends = div)]
316    pub attributes: Vec<Attribute>,
317    /// The [`Toggle`]s.
318    pub children: Element,
319}
320
321/// A set of related [`Toggle`]s with one tab stop and arrow-key movement.
322#[component]
323pub fn ToggleGroup(props: ToggleGroupProps) -> Element {
324    let roving = Roving::use_new();
325    use_context_provider(|| ToggleGroupContext(roving));
326
327    let class = compose([Some("ui-toggle-group"), props.class.as_deref()]);
328
329    rsx! {
330        div { class, "data-ui-toggle-group": "true", ..props.attributes, {props.children} }
331    }
332}