lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Link`, `SkipLink`, `ButtonLink`, and `ButtonGroup`.

use dioxus::prelude::*;

use crate::class::compose;

/// Color treatment of a [`Link`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LinkVariant {
    /// Brand-colored, underlined link.
    #[default]
    Default,
    /// Inherits the surrounding text color.
    Inherit,
}

impl LinkVariant {
    /// The `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Inherit => "inherit",
        }
    }
}

/// `rel` with `noopener noreferrer` added once, keeping the author's tokens first.
fn new_tab_rel(rel: Option<&str>) -> String {
    let mut tokens: Vec<&str> = Vec::new();

    for token in rel
        .unwrap_or_default()
        .split_whitespace()
        .chain(["noopener", "noreferrer"])
    {
        if !tokens.contains(&token) {
            tokens.push(token);
        }
    }

    tokens.join(" ")
}

/// Props for [`Link`].
#[derive(Props, Clone, PartialEq)]
pub struct LinkProps {
    /// Opens the destination in a new tab and adds `noopener noreferrer` to `rel`.
    #[props(default)]
    pub new_tab: bool,
    /// Color treatment.
    #[props(default)]
    pub variant: LinkVariant,
    /// Link relationship. `new_tab` adds `noopener noreferrer`.
    #[props(into)]
    pub rel: Option<String>,
    /// Browsing context. `new_tab` sets `_blank`.
    #[props(into)]
    pub target: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Any other `<a>` or global attribute, such as `href`.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
    /// Link text.
    pub children: Element,
}

/// An inline text link.
#[component]
pub fn Link(props: LinkProps) -> Element {
    let class = compose([
        Some("ui-link"),
        (props.variant == LinkVariant::Inherit).then_some("ui-link--inherit"),
        props.class.as_deref(),
    ]);
    let rel = if props.new_tab {
        Some(new_tab_rel(props.rel.as_deref()))
    } else {
        props.rel
    };
    let target = if props.new_tab {
        Some("_blank".to_string())
    } else {
        props.target
    };
    let onclick = props.onclick;

    rsx! {
        a {
            class,
            "data-slot": "link",
            "data-variant": props.variant.as_str(),
            rel,
            target,
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`SkipLink`].
#[derive(Props, Clone, PartialEq)]
pub struct SkipLinkProps {
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<a>` or global attribute. Point `href` at the main content, such as `#main`.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
    /// Link text, such as "Skip to content".
    pub children: Element,
}

/// A link that stays hidden until it receives keyboard focus, for skipping repeated navigation.
#[component]
pub fn SkipLink(props: SkipLinkProps) -> Element {
    let class = compose([Some("ui-skip-link"), props.class.as_deref()]);

    rsx! {
        a { class, ..props.attributes, {props.children} }
    }
}

/// Visual treatment of a [`ButtonLink`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ButtonLinkVariant {
    /// Solid brand button.
    #[default]
    Primary,
    /// Quiet filled button.
    Secondary,
    /// Bordered button without a fill, like Button's outline variant.
    Outline,
    /// Button without a fill or border.
    Ghost,
    /// A button-styled inline link.
    Inline,
    /// Only the `ui-button-link` hook, for custom styling.
    Unstyled,
}

impl ButtonLinkVariant {
    /// The variant classes, including the radius and border utilities lumen-react adds to styled
    /// variants. Height comes from the shared Button token.
    fn class(self) -> &'static str {
        match self {
            Self::Unstyled => "ui-button-link--unstyled",
            Self::Inline => "ui-button ui-button--inline",
            Self::Primary => {
                "ui-button ui-button--primary rounded-[var(--ui-button-link-radius,9999px)] border"
            }
            Self::Secondary => {
                "ui-button ui-button--secondary rounded-[var(--ui-button-link-radius,9999px)] border"
            }
            Self::Outline => {
                "ui-button ui-button--outline rounded-[var(--ui-button-link-radius,9999px)] border"
            }
            Self::Ghost => {
                "ui-button ui-button--ghost rounded-[var(--ui-button-link-radius,9999px)] border"
            }
        }
    }
}

/// Shape of a [`ButtonLink`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ButtonLinkShape {
    /// Text and optional icons.
    #[default]
    Default,
    /// Square icon-only link. Give it an `aria_label`.
    Icon,
}

/// Layout utilities lumen-react adds to every styled button link.
const BUTTON_LINK_LAYOUT: &str = "group inline-flex cursor-pointer items-center justify-center gap-2 text-sm font-semibold tracking-[0.01em]";

/// Props for [`ButtonLink`].
#[derive(Props, Clone, PartialEq)]
pub struct ButtonLinkProps {
    /// Visual treatment.
    #[props(default)]
    pub variant: ButtonLinkVariant,
    /// Text or icon-only shape. Ignored by the inline variant.
    #[props(default)]
    pub shape: ButtonLinkShape,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Any other `<a>` or global attribute, such as `href`.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
    /// Link text and icons.
    pub children: Element,
}

/// A link styled as a button, for navigation that looks like an action.
///
/// lumen-react's `asChild` has no Dioxus equivalent; wrap your router link's content instead, or
/// pass the same classes to it.
#[component]
pub fn ButtonLink(props: ButtonLinkProps) -> Element {
    let styled = props.variant != ButtonLinkVariant::Unstyled;
    let icon = props.shape == ButtonLinkShape::Icon && props.variant != ButtonLinkVariant::Inline;
    let class = compose([
        Some("ui-button-link"),
        styled.then_some(BUTTON_LINK_LAYOUT),
        Some(props.variant.class()),
        icon.then_some("ui-button-link--icon"),
        props.class.as_deref(),
    ]);

    let onclick = props.onclick;

    rsx! {
        a {
            class,
            "data-slot": "button-link",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`ButtonGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct ButtonGroupProps {
    /// 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` when the buttons belong together.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The buttons.
    pub children: Element,
}

/// Joins related buttons into one segmented control.
#[component]
pub fn ButtonGroup(props: ButtonGroupProps) -> Element {
    let class = compose([Some("ui-button-group"), props.class.as_deref()]);

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

#[cfg(test)]
mod tests {
    use super::new_tab_rel;

    #[test]
    fn new_tab_rel_adds_tokens_once() {
        assert_eq!(new_tab_rel(None), "noopener noreferrer");
        assert_eq!(new_tab_rel(Some("me noopener")), "me noopener noreferrer");
        assert_eq!(new_tab_rel(Some("  ")), "noopener noreferrer");
    }
}