lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Menubar`, `MenubarItem`, `NavigationMenu`, `NavigationMenuLink`, `Toggle`, and `ToggleGroup`.

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::hooks::use_controllable;

use super::chrome::{NavigationVariant, surface};
use super::roving::{Roving, RovingAxis, roving_move};

/// Roving focus shared by a [`Menubar`] and its [`MenubarItem`]s.
#[derive(Clone, Copy)]
struct MenubarContext(Roving);

/// Arrow-key movement shared by a [`NavigationMenu`] and its [`NavigationMenuLink`]s.
#[derive(Clone, Copy)]
struct NavigationMenuContext(Roving);

/// Roving focus shared by a [`ToggleGroup`] and its [`Toggle`]s.
#[derive(Clone, Copy)]
struct ToggleGroupContext(Roving);

/// Handles a roving key on an item; returns whether focus moved.
fn handle_roving_key(roving: Roving, key: usize, event: &KeyboardEvent) -> bool {
    let modifiers = event.modifiers();

    if event.is_composing() || modifiers.alt() || modifiers.ctrl() || modifiers.meta() {
        return false;
    }

    let Some(movement) = roving_move(&event.key(), RovingAxis::Both, false) else {
        return false;
    };

    event.prevent_default();
    roving.move_focus(Some(key), movement).is_some()
}

/// Props for [`Menubar`].
#[derive(Props, Clone, PartialEq)]
pub struct MenubarProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<nav>` or global attribute. Name the bar with `aria_label`.
    #[props(extends = GlobalAttributes, extends = nav)]
    pub attributes: Vec<Attribute>,
    /// The [`MenubarItem`]s.
    pub children: Element,
}

/// A horizontal bar of application menus with one tab stop and arrow-key movement.
///
/// Arrow keys, Home, and End move focus between [`MenubarItem`]s, skipping disabled ones, like
/// Lumen's roving web runtime. Once mounted, only the focused item is in the tab order.
#[component]
pub fn Menubar(props: MenubarProps) -> Element {
    let roving = Roving::use_new();
    use_context_provider(|| MenubarContext(roving));

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

    rsx! {
        nav {
            class,
            "data-surface": surface(props.glass),
            "data-ui-menubar": "true",
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`MenubarItem`].
#[derive(Props, Clone, PartialEq)]
pub struct MenubarItemProps {
    /// Skips the item during keyboard movement and disables it.
    #[props(default)]
    pub disabled: bool,
    /// Activation handler.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute, such as `aria_haspopup` for a menu trigger.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Item label.
    pub children: Element,
}

/// A `menuitem` button inside a [`Menubar`].
#[component]
pub fn MenubarItem(props: MenubarItemProps) -> Element {
    let MenubarContext(roving) = try_use_context::<MenubarContext>()
        .unwrap_or_else(|| panic!("MenubarItem must be used inside a Lumen Menubar."));
    let key = roving.use_item(props.disabled, false);
    let onclick = props.onclick;

    rsx! {
        button {
            class: props.class,
            disabled: props.disabled,
            role: "menuitem",
            tabindex: roving.tabindex(key),
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            onfocus: move |_| roving.focused(key),
            onkeydown: move |event| {
                handle_roving_key(roving, key, &event);
            },
            onmounted: move |event| roving.mount(key, event.data()),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`NavigationMenu`].
#[derive(Props, Clone, PartialEq)]
pub struct NavigationMenuProps {
    /// Surface styling or hooks only.
    #[props(default)]
    pub variant: NavigationVariant,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<nav>` or global attribute. Name the landmark with `aria_label`.
    #[props(extends = GlobalAttributes, extends = nav)]
    pub attributes: Vec<Attribute>,
    /// The links, usually [`NavigationMenuLink`]s.
    pub children: Element,
}

/// A row of primary navigation links.
///
/// Every link stays in the tab order. [`NavigationMenuLink`]s also move focus with the arrow
/// keys, Home, and End.
#[component]
pub fn NavigationMenu(props: NavigationMenuProps) -> Element {
    let roving = Roving::use_new();
    use_context_provider(|| NavigationMenuContext(roving));

    let unstyled = props.variant.modifier("ui-navigation-menu");
    let glass = props.glass.class("ui-navigation-menu");
    let class = compose([
        Some("ui-navigation-menu"),
        unstyled.as_deref(),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        nav {
            class,
            "data-slot": "navigation-menu",
            "data-surface": surface(props.glass),
            "data-ui-navigation-menu": "true",
            "data-variant": props.variant.as_str(),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`NavigationMenuLink`].
#[derive(Props, Clone, PartialEq)]
pub struct NavigationMenuLinkProps {
    /// Marks the link as the current page with `aria-current="page"`.
    #[props(default)]
    pub current: bool,
    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<a>` or global attribute, such as `href`.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
    /// Link text.
    pub children: Element,
}

/// A link inside a [`NavigationMenu`]. Outside one it is a plain link.
#[component]
pub fn NavigationMenuLink(props: NavigationMenuLinkProps) -> Element {
    let roving =
        try_use_context::<NavigationMenuContext>().map(|NavigationMenuContext(roving)| roving);
    let key = roving.map(|roving| roving.use_item(false, false));
    let onclick = props.onclick;

    rsx! {
        a {
            aria_current: props.current.then_some("page"),
            class: props.class,
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            onkeydown: move |event| {
                if let (Some(roving), Some(key)) = (roving, key) {
                    handle_roving_key(roving, key, &event);
                }
            },
            onmounted: move |event| {
                if let (Some(roving), Some(key)) = (roving, key) {
                    roving.mount(key, event.data());
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`Toggle`].
#[derive(Props, Clone, PartialEq)]
pub struct ToggleProps {
    /// Controlled pressed state. Setting it renders `data-ui-controlled`, like lumen-react's
    /// `controlled` prop.
    pub pressed: Option<bool>,
    /// Initial state when uncontrolled.
    #[props(default)]
    pub default_pressed: bool,
    /// Called with the next pressed state.
    pub on_pressed_change: Option<EventHandler<bool>>,
    /// Disables the toggle.
    #[props(default)]
    pub disabled: bool,
    /// Click handler, called before the state changes.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute. Name icon-only toggles with `aria_label`.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Toggle label or icon.
    pub children: Element,
}

/// A two-state button with `aria-pressed`, such as bold or mute.
///
/// Inside a [`ToggleGroup`] it joins the group's single tab stop and arrow-key movement.
#[component]
pub fn Toggle(props: ToggleProps) -> Element {
    let pressed = use_controllable(
        props.pressed,
        || props.default_pressed,
        props.on_pressed_change,
    );
    let group = try_use_context::<ToggleGroupContext>().map(|ToggleGroupContext(roving)| roving);
    let key = group.map(|roving| roving.use_item(props.disabled, false));
    let class = compose([Some("ui-toggle"), props.class.as_deref()]);
    let is_pressed = pressed.get();
    let onclick = props.onclick;

    rsx! {
        button {
            aria_pressed: if is_pressed { "true" } else { "false" },
            class,
            "data-ui-controlled": props.pressed.is_some().then_some("true"),
            "data-ui-toggle": "true",
            disabled: props.disabled,
            tabindex: group.zip(key).and_then(|(roving, key)| roving.tabindex(key)),
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }

                pressed.set(!pressed.peek());
            },
            onfocus: move |_| {
                if let (Some(roving), Some(key)) = (group, key) {
                    roving.focused(key);
                }
            },
            onkeydown: move |event| {
                if let (Some(roving), Some(key)) = (group, key) {
                    handle_roving_key(roving, key, &event);
                }
            },
            onmounted: move |event| {
                if let (Some(roving), Some(key)) = (group, key) {
                    roving.mount(key, event.data());
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`ToggleGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct ToggleGroupProps {
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the group with `role: "group"` and
    /// `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The [`Toggle`]s.
    pub children: Element,
}

/// A set of related [`Toggle`]s with one tab stop and arrow-key movement.
#[component]
pub fn ToggleGroup(props: ToggleGroupProps) -> Element {
    let roving = Roving::use_new();
    use_context_provider(|| ToggleGroupContext(roving));

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

    rsx! {
        div { class, "data-ui-toggle-group": "true", ..props.attributes, {props.children} }
    }
}