lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Breadcrumb` and `PageNav`.

use dioxus::prelude::*;

use crate::class::compose;
use crate::icons::{icon_svg, icon_svg_class, lucide};

use super::util::{optional_text, resolve_safe_href};

/// One entry of a [`Breadcrumb`] trail.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BreadcrumbItem {
    /// Visible text.
    pub label: String,
    /// Link destination. Ignored for the current page.
    pub href: Option<String>,
    /// Marks this entry as the current page. Defaults to the last entry.
    pub current: bool,
}

impl BreadcrumbItem {
    /// A linked ancestor.
    pub fn link(label: impl Into<String>, href: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            href: Some(href.into()),
            current: false,
        }
    }

    /// An entry rendered as text, such as the current page.
    pub fn text(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            href: None,
            current: false,
        }
    }
}

/// Resolves a trail to a single current page, like `resolveLumenBreadcrumbItems`: the first entry
/// marked `current`, otherwise the last. The current entry and entries without `href` never link.
pub fn breadcrumb_items(items: &[BreadcrumbItem]) -> Vec<BreadcrumbItem> {
    let current_index = items
        .iter()
        .position(|item| item.current)
        .unwrap_or(items.len().saturating_sub(1));

    items
        .iter()
        .enumerate()
        .map(|(index, item)| {
            let current = index == current_index;

            BreadcrumbItem {
                label: item.label.clone(),
                href: if current { None } else { item.href.clone() },
                current,
            }
        })
        .collect()
}

/// Props for [`Breadcrumb`].
#[derive(Props, Clone, PartialEq)]
pub struct BreadcrumbProps {
    /// Renders an ordered trail and replaces `children`. The last entry, or the first marked
    /// `current`, becomes the current page.
    pub items: Option<Vec<BreadcrumbItem>>,
    /// Accessible name of the landmark. Defaults to `Breadcrumb`.
    #[props(default = "Breadcrumb".to_string(), into)]
    pub aria_label: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<nav>` or global attribute.
    #[props(extends = GlobalAttributes, extends = nav)]
    pub attributes: Vec<Attribute>,
    /// A hand-written trail, usually an `ol` of links, used when `items` is unset.
    pub children: Element,
}

/// The path from the site root to the current page.
#[component]
pub fn Breadcrumb(props: BreadcrumbProps) -> Element {
    let class = compose([Some("ui-breadcrumb"), props.class.as_deref()]);

    rsx! {
        nav { aria_label: props.aria_label, class, ..props.attributes,
            if let Some(items) = props.items {
                if !items.is_empty() {
                    ol {
                        for (index, item) in breadcrumb_items(&items).into_iter().enumerate() {
                            li { key: "{index}:{item.href.clone().unwrap_or_default()}",
                                if item.current {
                                    span { aria_current: "page", "{item.label}" }
                                } else if let Some(href) = item.href {
                                    a { href, "{item.label}" }
                                } else {
                                    span { "{item.label}" }
                                }
                            }
                        }
                    }
                }
            } else {
                {props.children}
            }
        }
    }
}

/// One side of a [`PageNav`]: the destination and the title of the page it leads to.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageNavLink {
    /// Destination. Must be a relative reference or a credential-free `http(s)` URL.
    pub href: String,
    /// Title of the page it leads to.
    pub title: String,
}

impl PageNavLink {
    /// A link to `href` titled `title`.
    pub fn new(href: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            href: href.into(),
            title: title.into(),
        }
    }

    /// The validated link, like `resolveLumenPageNavLink`: blank titles and unsafe destinations
    /// are dropped.
    fn resolve(&self) -> Option<Self> {
        let title = optional_text(Some(&self.title))?;
        let href = resolve_safe_href(&self.href)?;

        Some(Self { href, title })
    }
}

/// Localizable [`PageNav`] copy. Blank values fall back to the English defaults.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageNavLabels {
    /// Accessible name of the landmark. Defaults to `Previous and next pages`.
    pub label: Option<String>,
    /// Direction text of the next link. Defaults to `Next`.
    pub next: Option<String>,
    /// Direction text of the previous link. Defaults to `Previous`.
    pub previous: Option<String>,
}

fn label_or(value: Option<&String>, fallback: &str) -> String {
    match value {
        Some(text) if !text.trim().is_empty() => text.clone(),
        _ => fallback.to_string(),
    }
}

/// Props for [`PageNav`].
#[derive(Props, Clone, PartialEq)]
pub struct PageNavProps {
    /// The preceding page in the series. Unsafe or untitled links are omitted.
    pub previous: Option<PageNavLink>,
    /// The following page in the series. Unsafe or untitled links are omitted.
    pub next: Option<PageNavLink>,
    /// Position text, such as "Part 2 of 5".
    #[props(into)]
    pub position: Option<String>,
    /// Localized landmark name and direction labels.
    #[props(default)]
    pub labels: PageNavLabels,
    /// Accessible name of the landmark. Overrides `labels.label`.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<nav>` or global attribute.
    #[props(extends = GlobalAttributes, extends = nav)]
    pub attributes: Vec<Attribute>,
}

/// Previous and next links between pages of a series.
#[component]
pub fn PageNav(props: PageNavProps) -> Element {
    let class = compose([Some("ui-page-nav"), props.class.as_deref()]);
    let aria_label = optional_text(props.aria_label.as_deref())
        .unwrap_or_else(|| label_or(props.labels.label.as_ref(), "Previous and next pages"));
    let position = optional_text(props.position.as_deref());
    let sides = [
        (
            "previous",
            label_or(props.labels.previous.as_ref(), "Previous"),
            props.previous.as_ref().and_then(PageNavLink::resolve),
            "prev",
            &lucide::ARROW_LEFT,
        ),
        (
            "next",
            label_or(props.labels.next.as_ref(), "Next"),
            props.next.as_ref().and_then(PageNavLink::resolve),
            "next",
            &lucide::ARROW_RIGHT,
        ),
    ];

    rsx! {
        nav { aria_label, class, "data-slot": "page-nav", ..props.attributes,
            if let Some(position) = position {
                p { class: "ui-page-nav__position", "data-slot": "page-nav-position", "{position}" }
            }
            for (direction, label, link, rel, icon) in sides {
                if let Some(link) = link {
                    a {
                        key: "{direction}",
                        class: "ui-page-nav__link",
                        "data-direction": direction,
                        "data-slot": "page-nav-{direction}",
                        href: link.href,
                        rel,
                        span { class: "ui-page-nav__direction",
                            {icon_svg(icon, &format!("{} ui-page-nav__icon", icon_svg_class(icon)))}
                            span { "{label}" }
                        }
                        span { class: "ui-page-nav__title", "{link.title}" }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BreadcrumbItem, PageNavLink, breadcrumb_items};

    #[test]
    fn the_last_item_is_current_by_default() {
        let items = breadcrumb_items(&[
            BreadcrumbItem::link("Home", "/"),
            BreadcrumbItem::link("Docs", "/docs"),
        ]);
        assert!(!items[0].current);
        assert_eq!(items[0].href.as_deref(), Some("/"));
        assert!(items[1].current);
        assert_eq!(items[1].href, None);
    }

    #[test]
    fn the_first_marked_item_wins() {
        let mut middle = BreadcrumbItem::link("Docs", "/docs");
        middle.current = true;
        let mut last = BreadcrumbItem::link("Guide", "/guide");
        last.current = true;
        let items = breadcrumb_items(&[BreadcrumbItem::link("Home", "/"), middle, last]);
        assert!(items[1].current && !items[2].current);
        assert_eq!(items[2].href.as_deref(), Some("/guide"));
        assert_eq!(breadcrumb_items(&[]), Vec::new());
    }

    #[test]
    fn page_nav_links_drop_unsafe_or_untitled_sides() {
        assert_eq!(
            PageNavLink::new("/a", "  A ").resolve(),
            Some(PageNavLink::new("/a", "A"))
        );
        assert_eq!(PageNavLink::new("javascript:x", "A").resolve(), None);
        assert_eq!(PageNavLink::new("/a", " ").resolve(), None);
    }
}