Skip to main content

lumen_dioxus/navigation/
anchors.rs

1//! In-page navigation: `BackToTop`, `HeadingAnchor`, and `Anchor`.
2// cspell:words fract onfocusin onpointerenter hrefs
3
4use std::time::Duration;
5
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::hooks::use_controllable;
10use crate::icons::{IconData, icon_svg, icon_svg_class, lucide};
11use crate::time::sleep;
12use crate::{ButtonSize, ButtonVariant};
13
14use super::copy::CopyButton;
15use super::util::{
16    collapse_whitespace, decode_uri_component, element_text, encode_uri_component, format_template,
17    optional_text,
18};
19use super::web::{
20    Watcher, focus_element_by_id, focus_selector, location_href, scroll_window_to_top,
21    use_scroll_past, watch_active_section,
22};
23
24/// Formats a pixel count like JavaScript's `String(number)` for the common cases.
25fn js_number(value: f64) -> String {
26    if value.fract() == 0.0 && value.abs() < 1e15 {
27        format!("{value:.0}")
28    } else {
29        value.to_string()
30    }
31}
32
33/// Props for [`BackToTop`].
34#[derive(Props, Clone, PartialEq)]
35pub struct BackToTopProps {
36    /// Scroll distance in pixels after which the button appears. Omit to keep it visible.
37    pub reveal_after: Option<f64>,
38    /// CSS selector focused after activation (for example `#main`). Web and desktop only.
39    #[props(into)]
40    pub focus_target: Option<String>,
41    /// Click handler, called before scrolling.
42    pub onclick: Option<EventHandler<MouseEvent>>,
43    /// Extra classes appended after the Lumen class.
44    #[props(into)]
45    pub class: Option<String>,
46    /// Any other `<button>` or global attribute. Name icon-only buttons with `aria_label`.
47    #[props(extends = GlobalAttributes, extends = button)]
48    pub attributes: Vec<Attribute>,
49    /// Button content, such as an arrow icon and "Back to top".
50    pub children: Element,
51}
52
53/// A button that returns to the top of the page.
54///
55/// With `reveal_after` or `focus_target` set it scrolls the window to the top (smoothly unless
56/// the user prefers reduced motion) and focuses the target. With `reveal_after` it stays hidden
57/// and inert until the page scrolls that far. Scrolling and focus use the browser on web and
58/// desktop; Dioxus Native has no window scroll position, so there the button stays visible and
59/// only calls `onclick`.
60#[component]
61pub fn BackToTop(props: BackToTopProps) -> Element {
62    let reveal = props
63        .reveal_after
64        .filter(|value| value.is_finite() && *value >= 0.0);
65    let focus_target = optional_text(props.focus_target.as_deref());
66    let scrolls = reveal.is_some() || focus_target.is_some();
67    let past = use_scroll_past(reveal);
68    let mut focused = use_signal(|| false);
69    let class = compose([Some("ui-back-to-top"), props.class.as_deref()]);
70    // `None` means the renderer has no scroll position (Dioxus Native): keep the button usable.
71    let should_show = past().is_none_or(|past| past);
72    // Without a focus target, a focused button stays visible until keyboard focus moves on.
73    let hidden = reveal.is_some() && !should_show && !(focused() && focus_target.is_none());
74    let state = reveal.map(|_| if hidden { "hidden" } else { "visible" });
75    let mut latest_target = use_hook(|| CopyValue::new(None::<String>));
76    latest_target.set(focus_target.clone());
77
78    use_effect(move || {
79        let leaving = past() == Some(false) && focused();
80
81        if leaving && let Some(selector) = latest_target.peek().clone() {
82            spawn(async move {
83                focus_selector(selector).await;
84            });
85        }
86    });
87
88    let onclick = props.onclick;
89
90    rsx! {
91        button {
92            class,
93            "data-state": state,
94            "data-ui-back-to-top-reveal": reveal.map(js_number),
95            inert: hidden,
96            r#type: "button",
97            onclick: move |event| {
98                if let Some(handler) = onclick {
99                    handler.call(event);
100                }
101
102                if !scrolls {
103                    return;
104                }
105
106                scroll_window_to_top();
107
108                if let Some(selector) = focus_target.clone() {
109                    spawn(async move {
110                        focus_selector(selector).await;
111                    });
112                }
113            },
114            onfocus: move |_| focused.set(true),
115            onblur: move |_| focused.set(false),
116            ..props.attributes,
117            {props.children}
118        }
119    }
120}
121
122/// Heading level of a [`HeadingAnchor`]. The page title (h1) does not take a permalink.
123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124#[non_exhaustive]
125pub enum HeadingAnchorLevel {
126    /// `h2`.
127    #[default]
128    H2,
129    /// `h3`.
130    H3,
131    /// `h4`.
132    H4,
133    /// `h5`.
134    H5,
135    /// `h6`.
136    H6,
137}
138
139impl HeadingAnchorLevel {
140    /// The level from a number, like `normalizeLumenHeadingAnchorLevel`: anything but 2–6 is 2.
141    pub fn from_number(level: u8) -> Self {
142        match level {
143            3 => Self::H3,
144            4 => Self::H4,
145            5 => Self::H5,
146            6 => Self::H6,
147            _ => Self::H2,
148        }
149    }
150
151    /// The level as a number.
152    pub fn number(self) -> u8 {
153        match self {
154            Self::H2 => 2,
155            Self::H3 => 3,
156            Self::H4 => 4,
157            Self::H5 => 5,
158            Self::H6 => 6,
159        }
160    }
161}
162
163/// The same-document fragment for a heading id, or `None` for a blank id, like
164/// `resolveLumenHeadingAnchorHref`.
165pub fn heading_anchor_href(id: &str) -> Option<String> {
166    let trimmed = id.trim();
167
168    (!trimmed.is_empty()).then(|| format!("#{}", encode_uri_component(trimmed)))
169}
170
171/// The absolute URL of a section: `base` without its fragment, plus the heading id, like
172/// `resolveLumenHeadingAnchorUrl`.
173pub fn heading_anchor_url(id: &str, base: &str) -> Option<String> {
174    let href = heading_anchor_href(id)?;
175    let base = base.split_once('#').map_or(base, |(before, _)| before);
176
177    if base.is_empty() || !base.contains(':') {
178        return None;
179    }
180
181    Some(format!("{base}{href}"))
182}
183
184/// Default copy, with `{heading}` replaced by the section name.
185const LINK_LABEL: &str = "Link to section: {heading}";
186const COPY_LABEL: &str = "Copy link to section: {heading}";
187const COPIED_LABEL: &str = "Link copied";
188const ERROR_LABEL: &str = "Could not copy the link";
189
190fn heading_label(template: Option<&str>, heading: &str, fallback: &str) -> String {
191    let template = template
192        .filter(|value| !value.trim().is_empty())
193        .unwrap_or(fallback);
194
195    format_template(template, &[("heading", heading.trim())])
196}
197
198/// Props for [`HeadingAnchor`].
199#[derive(Props, Clone, PartialEq)]
200pub struct HeadingAnchorProps {
201    /// The heading id and the fragment the permalink points to. A blank id renders the heading
202    /// without a permalink.
203    #[props(into)]
204    pub id: String,
205    /// Heading level. Defaults to 2.
206    #[props(default)]
207    pub level: HeadingAnchorLevel,
208    /// Section name used in accessible names. Defaults to the text of `children`.
209    #[props(into)]
210    pub label: Option<String>,
211    /// Shows the copy-link button once the page location is known. Defaults to true.
212    #[props(default = true)]
213    pub copy: bool,
214    /// Accessible name of the permalink; `{heading}` is the section name.
215    #[props(into)]
216    pub link_label: Option<String>,
217    /// Accessible name of the copy button; `{heading}` is the section name.
218    #[props(into)]
219    pub copy_label: Option<String>,
220    /// Announced after a successful copy.
221    #[props(into)]
222    pub copied_label: Option<String>,
223    /// Announced when copying fails.
224    #[props(into)]
225    pub error_label: Option<String>,
226    /// Extra classes appended after the Lumen class.
227    #[props(into)]
228    pub class: Option<String>,
229    /// Any other `<div>` or global attribute.
230    #[props(extends = GlobalAttributes, extends = div)]
231    pub attributes: Vec<Attribute>,
232    /// Heading content.
233    pub children: Element,
234}
235
236fn heading_element(level: HeadingAnchorLevel, id: Option<String>, children: Element) -> Element {
237    match level {
238        HeadingAnchorLevel::H2 => {
239            rsx! { h2 { class: "ui-heading-anchor__heading", id, {children} } }
240        }
241        HeadingAnchorLevel::H3 => {
242            rsx! { h3 { class: "ui-heading-anchor__heading", id, {children} } }
243        }
244        HeadingAnchorLevel::H4 => {
245            rsx! { h4 { class: "ui-heading-anchor__heading", id, {children} } }
246        }
247        HeadingAnchorLevel::H5 => {
248            rsx! { h5 { class: "ui-heading-anchor__heading", id, {children} } }
249        }
250        HeadingAnchorLevel::H6 => {
251            rsx! { h6 { class: "ui-heading-anchor__heading", id, {children} } }
252        }
253    }
254}
255
256/// A section heading with a permalink and a copy-link button.
257///
258/// The permalink is a plain fragment link. The copy button stays hidden until the page location
259/// is known (web and desktop read it from the browser), then copies the section's absolute URL.
260/// Dioxus Native has no page location, so the button stays hidden there.
261#[component]
262pub fn HeadingAnchor(props: HeadingAnchorProps) -> Element {
263    let mut location = use_signal(|| None::<String>);
264    let heading_id = props.id.trim().to_string();
265    let href = heading_anchor_href(&heading_id);
266    let section = optional_text(props.label.as_deref())
267        .unwrap_or_else(|| collapse_whitespace(&element_text(&props.children)));
268    let url = location().and_then(|base| heading_anchor_url(&heading_id, &base));
269    let class = compose([Some("ui-heading-anchor"), props.class.as_deref()]);
270    let refresh = move || {
271        spawn(async move {
272            let next = location_href().await;
273
274            if next.is_some() && *location.peek() != next {
275                location.set(next);
276            }
277        });
278    };
279
280    use_effect(refresh);
281
282    let level = props.level;
283    let link_label = heading_label(props.link_label.as_deref(), &section, LINK_LABEL);
284    let copy_label = heading_label(props.copy_label.as_deref(), &section, COPY_LABEL);
285    let copied_label =
286        optional_text(props.copied_label.as_deref()).unwrap_or_else(|| COPIED_LABEL.to_string());
287    let error_label =
288        optional_text(props.error_label.as_deref()).unwrap_or_else(|| ERROR_LABEL.to_string());
289    let copy_value = url.clone().or_else(|| href.clone()).unwrap_or_default();
290
291    rsx! {
292        div {
293            class,
294            "data-level": "{level.number()}",
295            "data-slot": "heading-anchor",
296            "data-ui-heading-anchor": "",
297            "data-ui-owner": "dioxus",
298            ..props.attributes,
299            {heading_element(level, (!heading_id.is_empty()).then(|| heading_id.clone()), props.children)}
300            if let Some(href) = href {
301                span {
302                    class: "ui-heading-anchor__actions",
303                    "data-slot": "heading-anchor-actions",
304                    // The location can change without an event (pushState); read it again before a copy.
305                    onfocusin: move |_| refresh(),
306                    onpointerenter: move |_| refresh(),
307                    a {
308                        aria_label: link_label,
309                        class: "ui-heading-anchor__link",
310                        "data-slot": "heading-anchor-link",
311                        href,
312                        span { aria_hidden: "true", class: "ui-heading-anchor__hash", "#" }
313                    }
314                    if props.copy {
315                        CopyButton {
316                            class: "ui-heading-anchor__copy",
317                            copied_content: rsx! { {heading_icon(&lucide::CHECK)} },
318                            copied_label,
319                            error_content: rsx! { {heading_icon(&lucide::X)} },
320                            error_label,
321                            hidden: url.is_none(),
322                            label: copy_label,
323                            size: ButtonSize::Icon,
324                            value: copy_value,
325                            variant: ButtonVariant::Ghost,
326                            {heading_icon(&lucide::COPY)}
327                        }
328                    }
329                }
330            }
331        }
332    }
333}
334
335/// Catalog artwork for the copy button, with the `ui-heading-anchor__icon` hook that sizes it.
336fn heading_icon(icon: &'static IconData) -> Element {
337    icon_svg(
338        icon,
339        &format!("{} ui-heading-anchor__icon", icon_svg_class(icon)),
340    )
341}
342
343/// One link of an [`Anchor`] table of contents.
344#[derive(Clone, Debug, Default, PartialEq, Eq)]
345pub struct AnchorLink {
346    /// Destination, usually a fragment such as `#install`.
347    pub href: String,
348    /// Visible text.
349    pub label: String,
350    /// Secondary line under the label.
351    pub description: Option<String>,
352    /// Nesting depth from 1 to 6, rendered as `data-depth` for indentation.
353    pub depth: Option<u8>,
354    /// Leading number or marker, such as `1.2`.
355    pub index: Option<String>,
356}
357
358impl AnchorLink {
359    /// A link to `href` labelled `label`.
360    pub fn new(href: impl Into<String>, label: impl Into<String>) -> Self {
361        Self {
362            href: href.into(),
363            label: label.into(),
364            ..Self::default()
365        }
366    }
367
368    /// The same link at a nesting depth.
369    #[must_use]
370    pub fn depth(mut self, depth: u8) -> Self {
371        self.depth = Some(depth.clamp(1, 6));
372        self
373    }
374}
375
376/// The element id a fragment link points to, decoded like `decodeLumenAnchorFragment`.
377fn fragment_id(href: &str) -> Option<String> {
378    href.strip_prefix('#')
379        .filter(|fragment| !fragment.is_empty())
380        .map(decode_uri_component)
381}
382
383/// Props for [`Anchor`].
384#[derive(Props, Clone, PartialEq)]
385pub struct AnchorProps {
386    /// The table of contents.
387    #[props(default)]
388    pub items: Vec<AnchorLink>,
389    /// Controlled active link, by `href`.
390    #[props(into)]
391    pub value: Option<String>,
392    /// Called with the `href` of the newly active link.
393    pub on_value_change: Option<EventHandler<String>>,
394    /// Distance in pixels from the top of the viewport where a section becomes active.
395    /// Defaults to 96.
396    #[props(default = 96.0)]
397    pub activation_offset: f64,
398    /// Accessible name of the landmark. Defaults to `On this page`.
399    #[props(default = "On this page".to_string(), into)]
400    pub aria_label: String,
401    /// Extra classes appended after the Lumen class.
402    #[props(into)]
403    pub class: Option<String>,
404    /// Any other `<nav>` or global attribute.
405    #[props(extends = GlobalAttributes, extends = nav)]
406    pub attributes: Vec<Attribute>,
407    /// Extra content after the list.
408    pub children: Element,
409}
410
411/// An "On this page" table of contents that marks the section in view.
412///
413/// The first link starts active. Activating a link marks it active and, on web and desktop,
414/// focuses its section; while the page scrolls, the section under the activation line becomes
415/// active. Dioxus Native has no scroll position, so there only activation updates the link.
416#[component]
417pub fn Anchor(props: AnchorProps) -> Element {
418    let first = props
419        .items
420        .first()
421        .map_or_else(String::new, |item| item.href.clone());
422    let active = use_controllable(props.value.clone(), || first, props.on_value_change);
423    let offset = if props.activation_offset.is_finite() {
424        props.activation_offset.max(0.0)
425    } else {
426        0.0
427    };
428    let class = compose([Some("ui-anchor"), props.class.as_deref()]);
429    let current = active.get();
430    let sections: Vec<(String, String)> = props
431        .items
432        .iter()
433        .filter_map(|item| fragment_id(&item.href).map(|id| (id, item.href.clone())))
434        .collect();
435    let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
436
437    use_effect(use_reactive(
438        (&sections, &offset),
439        move |(sections, offset)| {
440            if let Some(previous) = watcher.write().take() {
441                previous.stop();
442            }
443
444            if sections.is_empty() {
445                return;
446            }
447
448            let ids = sections.iter().map(|(id, _)| id.clone()).collect();
449            let next = watch_active_section(ids, offset, move |index| {
450                if let Some((_, href)) = sections.get(index) {
451                    active.set(href.clone());
452                }
453            });
454            watcher.set(Some(next));
455        },
456    ));
457
458    use_drop(move || {
459        if let Some(previous) = watcher.write().take() {
460            previous.stop();
461        }
462    });
463
464    rsx! {
465        nav {
466            aria_label: props.aria_label,
467            class,
468            "data-ui-anchor": "true",
469            "data-ui-anchor-offset": js_number(offset),
470            "data-ui-owner": "dioxus",
471            ..props.attributes,
472            if !props.items.is_empty() {
473                ol {
474                    for item in props.items {
475                        {
476                            let is_active = item.href == current;
477                            let href = item.href.clone();
478
479                            rsx! {
480                                li { key: "{item.href}",
481                                    a {
482                                        aria_current: is_active.then_some("location"),
483                                        "data-active": if is_active { "true" } else { "false" },
484                                        "data-depth": item.depth.map(|depth| depth.to_string()),
485                                        href: item.href.clone(),
486                                        onclick: move |_| {
487                                            active.set(href.clone());
488
489                                            if let Some(id) = fragment_id(&href) {
490                                                spawn(async move {
491                                                    // Let the browser follow the fragment first.
492                                                    sleep(Duration::ZERO).await;
493                                                    focus_element_by_id(id, None).await;
494                                                });
495                                            }
496                                        },
497                                        if let Some(index) = item.index {
498                                            span { class: "ui-anchor__index", "{index}" }
499                                        }
500                                        span { class: "ui-anchor__content",
501                                            span { class: "ui-anchor__label", "{item.label}" }
502                                            if let Some(description) = item.description.filter(|text| !text.is_empty()) {
503                                                span { class: "ui-anchor__description", "{description}" }
504                                            }
505                                        }
506                                    }
507                                }
508                            }
509                        }
510                    }
511                }
512            }
513            {props.children}
514        }
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use super::{
521        HeadingAnchorLevel, fragment_id, heading_anchor_href, heading_anchor_url, heading_label,
522        js_number,
523    };
524
525    #[test]
526    fn heading_hrefs_and_urls_follow_lumen_core() {
527        assert_eq!(
528            heading_anchor_href(" install ").as_deref(),
529            Some("#install")
530        );
531        assert_eq!(heading_anchor_href("a b/c").as_deref(), Some("#a%20b%2Fc"));
532        assert_eq!(heading_anchor_href("  "), None);
533        assert_eq!(
534            heading_anchor_url("install", "https://example.com/docs?x=1#old").as_deref(),
535            Some("https://example.com/docs?x=1#install")
536        );
537        assert_eq!(heading_anchor_url("install", "not a url"), None);
538        assert_eq!(heading_anchor_url("", "https://example.com/"), None);
539    }
540
541    #[test]
542    fn levels_and_labels_normalize() {
543        assert_eq!(HeadingAnchorLevel::from_number(1), HeadingAnchorLevel::H2);
544        assert_eq!(HeadingAnchorLevel::from_number(4).number(), 4);
545        assert_eq!(
546            heading_label(None, " Install ", "Link to section: {heading}"),
547            "Link to section: Install"
548        );
549        assert_eq!(heading_label(Some("  "), "A", "Go {heading}"), "Go A");
550        assert_eq!(heading_label(Some("Ir a {heading}"), "A", "x"), "Ir a A");
551    }
552
553    #[test]
554    fn fragments_decode_and_numbers_format() {
555        assert_eq!(fragment_id("#a%20b").as_deref(), Some("a b"));
556        assert_eq!(fragment_id("#100%").as_deref(), Some("100%"));
557        assert_eq!(fragment_id("/page"), None);
558        assert_eq!(fragment_id("#"), None);
559        assert_eq!(js_number(96.0), "96");
560        assert_eq!(js_number(12.5), "12.5");
561    }
562}