Skip to main content

lumen_dioxus/navigation/
breadcrumb.rs

1//! `Breadcrumb` and `PageNav`.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6use crate::icons::{icon_svg, icon_svg_class, lucide};
7
8use super::util::{optional_text, resolve_safe_href};
9
10/// One entry of a [`Breadcrumb`] trail.
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct BreadcrumbItem {
13    /// Visible text.
14    pub label: String,
15    /// Link destination. Ignored for the current page.
16    pub href: Option<String>,
17    /// Marks this entry as the current page. Defaults to the last entry.
18    pub current: bool,
19}
20
21impl BreadcrumbItem {
22    /// A linked ancestor.
23    pub fn link(label: impl Into<String>, href: impl Into<String>) -> Self {
24        Self {
25            label: label.into(),
26            href: Some(href.into()),
27            current: false,
28        }
29    }
30
31    /// An entry rendered as text, such as the current page.
32    pub fn text(label: impl Into<String>) -> Self {
33        Self {
34            label: label.into(),
35            href: None,
36            current: false,
37        }
38    }
39}
40
41/// Resolves a trail to a single current page, like `resolveLumenBreadcrumbItems`: the first entry
42/// marked `current`, otherwise the last. The current entry and entries without `href` never link.
43pub fn breadcrumb_items(items: &[BreadcrumbItem]) -> Vec<BreadcrumbItem> {
44    let current_index = items
45        .iter()
46        .position(|item| item.current)
47        .unwrap_or(items.len().saturating_sub(1));
48
49    items
50        .iter()
51        .enumerate()
52        .map(|(index, item)| {
53            let current = index == current_index;
54
55            BreadcrumbItem {
56                label: item.label.clone(),
57                href: if current { None } else { item.href.clone() },
58                current,
59            }
60        })
61        .collect()
62}
63
64/// Props for [`Breadcrumb`].
65#[derive(Props, Clone, PartialEq)]
66pub struct BreadcrumbProps {
67    /// Renders an ordered trail and replaces `children`. The last entry, or the first marked
68    /// `current`, becomes the current page.
69    pub items: Option<Vec<BreadcrumbItem>>,
70    /// Accessible name of the landmark. Defaults to `Breadcrumb`.
71    #[props(default = "Breadcrumb".to_string(), into)]
72    pub aria_label: String,
73    /// Extra classes appended after the Lumen class.
74    #[props(into)]
75    pub class: Option<String>,
76    /// Any other `<nav>` or global attribute.
77    #[props(extends = GlobalAttributes, extends = nav)]
78    pub attributes: Vec<Attribute>,
79    /// A hand-written trail, usually an `ol` of links, used when `items` is unset.
80    pub children: Element,
81}
82
83/// The path from the site root to the current page.
84#[component]
85pub fn Breadcrumb(props: BreadcrumbProps) -> Element {
86    let class = compose([Some("ui-breadcrumb"), props.class.as_deref()]);
87
88    rsx! {
89        nav { aria_label: props.aria_label, class, ..props.attributes,
90            if let Some(items) = props.items {
91                if !items.is_empty() {
92                    ol {
93                        for (index, item) in breadcrumb_items(&items).into_iter().enumerate() {
94                            li { key: "{index}:{item.href.clone().unwrap_or_default()}",
95                                if item.current {
96                                    span { aria_current: "page", "{item.label}" }
97                                } else if let Some(href) = item.href {
98                                    a { href, "{item.label}" }
99                                } else {
100                                    span { "{item.label}" }
101                                }
102                            }
103                        }
104                    }
105                }
106            } else {
107                {props.children}
108            }
109        }
110    }
111}
112
113/// One side of a [`PageNav`]: the destination and the title of the page it leads to.
114#[derive(Clone, Debug, Default, PartialEq, Eq)]
115pub struct PageNavLink {
116    /// Destination. Must be a relative reference or a credential-free `http(s)` URL.
117    pub href: String,
118    /// Title of the page it leads to.
119    pub title: String,
120}
121
122impl PageNavLink {
123    /// A link to `href` titled `title`.
124    pub fn new(href: impl Into<String>, title: impl Into<String>) -> Self {
125        Self {
126            href: href.into(),
127            title: title.into(),
128        }
129    }
130
131    /// The validated link, like `resolveLumenPageNavLink`: blank titles and unsafe destinations
132    /// are dropped.
133    fn resolve(&self) -> Option<Self> {
134        let title = optional_text(Some(&self.title))?;
135        let href = resolve_safe_href(&self.href)?;
136
137        Some(Self { href, title })
138    }
139}
140
141/// Localizable [`PageNav`] copy. Blank values fall back to the English defaults.
142#[derive(Clone, Debug, Default, PartialEq, Eq)]
143pub struct PageNavLabels {
144    /// Accessible name of the landmark. Defaults to `Previous and next pages`.
145    pub label: Option<String>,
146    /// Direction text of the next link. Defaults to `Next`.
147    pub next: Option<String>,
148    /// Direction text of the previous link. Defaults to `Previous`.
149    pub previous: Option<String>,
150}
151
152fn label_or(value: Option<&String>, fallback: &str) -> String {
153    match value {
154        Some(text) if !text.trim().is_empty() => text.clone(),
155        _ => fallback.to_string(),
156    }
157}
158
159/// Props for [`PageNav`].
160#[derive(Props, Clone, PartialEq)]
161pub struct PageNavProps {
162    /// The preceding page in the series. Unsafe or untitled links are omitted.
163    pub previous: Option<PageNavLink>,
164    /// The following page in the series. Unsafe or untitled links are omitted.
165    pub next: Option<PageNavLink>,
166    /// Position text, such as "Part 2 of 5".
167    #[props(into)]
168    pub position: Option<String>,
169    /// Localized landmark name and direction labels.
170    #[props(default)]
171    pub labels: PageNavLabels,
172    /// Accessible name of the landmark. Overrides `labels.label`.
173    #[props(into)]
174    pub aria_label: Option<String>,
175    /// Extra classes appended after the Lumen class.
176    #[props(into)]
177    pub class: Option<String>,
178    /// Any other `<nav>` or global attribute.
179    #[props(extends = GlobalAttributes, extends = nav)]
180    pub attributes: Vec<Attribute>,
181}
182
183/// Previous and next links between pages of a series.
184#[component]
185pub fn PageNav(props: PageNavProps) -> Element {
186    let class = compose([Some("ui-page-nav"), props.class.as_deref()]);
187    let aria_label = optional_text(props.aria_label.as_deref())
188        .unwrap_or_else(|| label_or(props.labels.label.as_ref(), "Previous and next pages"));
189    let position = optional_text(props.position.as_deref());
190    let sides = [
191        (
192            "previous",
193            label_or(props.labels.previous.as_ref(), "Previous"),
194            props.previous.as_ref().and_then(PageNavLink::resolve),
195            "prev",
196            &lucide::ARROW_LEFT,
197        ),
198        (
199            "next",
200            label_or(props.labels.next.as_ref(), "Next"),
201            props.next.as_ref().and_then(PageNavLink::resolve),
202            "next",
203            &lucide::ARROW_RIGHT,
204        ),
205    ];
206
207    rsx! {
208        nav { aria_label, class, "data-slot": "page-nav", ..props.attributes,
209            if let Some(position) = position {
210                p { class: "ui-page-nav__position", "data-slot": "page-nav-position", "{position}" }
211            }
212            for (direction, label, link, rel, icon) in sides {
213                if let Some(link) = link {
214                    a {
215                        key: "{direction}",
216                        class: "ui-page-nav__link",
217                        "data-direction": direction,
218                        "data-slot": "page-nav-{direction}",
219                        href: link.href,
220                        rel,
221                        span { class: "ui-page-nav__direction",
222                            {icon_svg(icon, &format!("{} ui-page-nav__icon", icon_svg_class(icon)))}
223                            span { "{label}" }
224                        }
225                        span { class: "ui-page-nav__title", "{link.title}" }
226                    }
227                }
228            }
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::{BreadcrumbItem, PageNavLink, breadcrumb_items};
236
237    #[test]
238    fn the_last_item_is_current_by_default() {
239        let items = breadcrumb_items(&[
240            BreadcrumbItem::link("Home", "/"),
241            BreadcrumbItem::link("Docs", "/docs"),
242        ]);
243        assert!(!items[0].current);
244        assert_eq!(items[0].href.as_deref(), Some("/"));
245        assert!(items[1].current);
246        assert_eq!(items[1].href, None);
247    }
248
249    #[test]
250    fn the_first_marked_item_wins() {
251        let mut middle = BreadcrumbItem::link("Docs", "/docs");
252        middle.current = true;
253        let mut last = BreadcrumbItem::link("Guide", "/guide");
254        last.current = true;
255        let items = breadcrumb_items(&[BreadcrumbItem::link("Home", "/"), middle, last]);
256        assert!(items[1].current && !items[2].current);
257        assert_eq!(items[2].href.as_deref(), Some("/guide"));
258        assert_eq!(breadcrumb_items(&[]), Vec::new());
259    }
260
261    #[test]
262    fn page_nav_links_drop_unsafe_or_untitled_sides() {
263        assert_eq!(
264            PageNavLink::new("/a", "  A ").resolve(),
265            Some(PageNavLink::new("/a", "A"))
266        );
267        assert_eq!(PageNavLink::new("javascript:x", "A").resolve(), None);
268        assert_eq!(PageNavLink::new("/a", " ").resolve(), None);
269    }
270}