lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! In-page navigation: `BackToTop`, `HeadingAnchor`, and `Anchor`.
// cspell:words fract onfocusin onpointerenter hrefs

use std::time::Duration;

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_controllable;
use crate::icons::{IconData, icon_svg, icon_svg_class, lucide};
use crate::time::sleep;
use crate::{ButtonSize, ButtonVariant};

use super::copy::CopyButton;
use super::util::{
    collapse_whitespace, decode_uri_component, element_text, encode_uri_component, format_template,
    optional_text,
};
use super::web::{
    Watcher, focus_element_by_id, focus_selector, location_href, scroll_window_to_top,
    use_scroll_past, watch_active_section,
};

/// Formats a pixel count like JavaScript's `String(number)` for the common cases.
fn js_number(value: f64) -> String {
    if value.fract() == 0.0 && value.abs() < 1e15 {
        format!("{value:.0}")
    } else {
        value.to_string()
    }
}

/// Props for [`BackToTop`].
#[derive(Props, Clone, PartialEq)]
pub struct BackToTopProps {
    /// Scroll distance in pixels after which the button appears. Omit to keep it visible.
    pub reveal_after: Option<f64>,
    /// CSS selector focused after activation (for example `#main`). Web and desktop only.
    #[props(into)]
    pub focus_target: Option<String>,
    /// Click handler, called before scrolling.
    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 buttons with `aria_label`.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button content, such as an arrow icon and "Back to top".
    pub children: Element,
}

/// A button that returns to the top of the page.
///
/// With `reveal_after` or `focus_target` set it scrolls the window to the top (smoothly unless
/// the user prefers reduced motion) and focuses the target. With `reveal_after` it stays hidden
/// and inert until the page scrolls that far. Scrolling and focus use the browser on web and
/// desktop; Dioxus Native has no window scroll position, so there the button stays visible and
/// only calls `onclick`.
#[component]
pub fn BackToTop(props: BackToTopProps) -> Element {
    let reveal = props
        .reveal_after
        .filter(|value| value.is_finite() && *value >= 0.0);
    let focus_target = optional_text(props.focus_target.as_deref());
    let scrolls = reveal.is_some() || focus_target.is_some();
    let past = use_scroll_past(reveal);
    let mut focused = use_signal(|| false);
    let class = compose([Some("ui-back-to-top"), props.class.as_deref()]);
    // `None` means the renderer has no scroll position (Dioxus Native): keep the button usable.
    let should_show = past().is_none_or(|past| past);
    // Without a focus target, a focused button stays visible until keyboard focus moves on.
    let hidden = reveal.is_some() && !should_show && !(focused() && focus_target.is_none());
    let state = reveal.map(|_| if hidden { "hidden" } else { "visible" });
    let mut latest_target = use_hook(|| CopyValue::new(None::<String>));
    latest_target.set(focus_target.clone());

    use_effect(move || {
        let leaving = past() == Some(false) && focused();

        if leaving && let Some(selector) = latest_target.peek().clone() {
            spawn(async move {
                focus_selector(selector).await;
            });
        }
    });

    let onclick = props.onclick;

    rsx! {
        button {
            class,
            "data-state": state,
            "data-ui-back-to-top-reveal": reveal.map(js_number),
            inert: hidden,
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }

                if !scrolls {
                    return;
                }

                scroll_window_to_top();

                if let Some(selector) = focus_target.clone() {
                    spawn(async move {
                        focus_selector(selector).await;
                    });
                }
            },
            onfocus: move |_| focused.set(true),
            onblur: move |_| focused.set(false),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Heading level of a [`HeadingAnchor`]. The page title (h1) does not take a permalink.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeadingAnchorLevel {
    /// `h2`.
    #[default]
    H2,
    /// `h3`.
    H3,
    /// `h4`.
    H4,
    /// `h5`.
    H5,
    /// `h6`.
    H6,
}

impl HeadingAnchorLevel {
    /// The level from a number, like `normalizeLumenHeadingAnchorLevel`: anything but 2–6 is 2.
    pub fn from_number(level: u8) -> Self {
        match level {
            3 => Self::H3,
            4 => Self::H4,
            5 => Self::H5,
            6 => Self::H6,
            _ => Self::H2,
        }
    }

    /// The level as a number.
    pub fn number(self) -> u8 {
        match self {
            Self::H2 => 2,
            Self::H3 => 3,
            Self::H4 => 4,
            Self::H5 => 5,
            Self::H6 => 6,
        }
    }
}

/// The same-document fragment for a heading id, or `None` for a blank id, like
/// `resolveLumenHeadingAnchorHref`.
pub fn heading_anchor_href(id: &str) -> Option<String> {
    let trimmed = id.trim();

    (!trimmed.is_empty()).then(|| format!("#{}", encode_uri_component(trimmed)))
}

/// The absolute URL of a section: `base` without its fragment, plus the heading id, like
/// `resolveLumenHeadingAnchorUrl`.
pub fn heading_anchor_url(id: &str, base: &str) -> Option<String> {
    let href = heading_anchor_href(id)?;
    let base = base.split_once('#').map_or(base, |(before, _)| before);

    if base.is_empty() || !base.contains(':') {
        return None;
    }

    Some(format!("{base}{href}"))
}

/// Default copy, with `{heading}` replaced by the section name.
const LINK_LABEL: &str = "Link to section: {heading}";
const COPY_LABEL: &str = "Copy link to section: {heading}";
const COPIED_LABEL: &str = "Link copied";
const ERROR_LABEL: &str = "Could not copy the link";

fn heading_label(template: Option<&str>, heading: &str, fallback: &str) -> String {
    let template = template
        .filter(|value| !value.trim().is_empty())
        .unwrap_or(fallback);

    format_template(template, &[("heading", heading.trim())])
}

/// Props for [`HeadingAnchor`].
#[derive(Props, Clone, PartialEq)]
pub struct HeadingAnchorProps {
    /// The heading id and the fragment the permalink points to. A blank id renders the heading
    /// without a permalink.
    #[props(into)]
    pub id: String,
    /// Heading level. Defaults to 2.
    #[props(default)]
    pub level: HeadingAnchorLevel,
    /// Section name used in accessible names. Defaults to the text of `children`.
    #[props(into)]
    pub label: Option<String>,
    /// Shows the copy-link button once the page location is known. Defaults to true.
    #[props(default = true)]
    pub copy: bool,
    /// Accessible name of the permalink; `{heading}` is the section name.
    #[props(into)]
    pub link_label: Option<String>,
    /// Accessible name of the copy button; `{heading}` is the section name.
    #[props(into)]
    pub copy_label: Option<String>,
    /// Announced after a successful copy.
    #[props(into)]
    pub copied_label: Option<String>,
    /// Announced when copying fails.
    #[props(into)]
    pub error_label: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Heading content.
    pub children: Element,
}

fn heading_element(level: HeadingAnchorLevel, id: Option<String>, children: Element) -> Element {
    match level {
        HeadingAnchorLevel::H2 => {
            rsx! { h2 { class: "ui-heading-anchor__heading", id, {children} } }
        }
        HeadingAnchorLevel::H3 => {
            rsx! { h3 { class: "ui-heading-anchor__heading", id, {children} } }
        }
        HeadingAnchorLevel::H4 => {
            rsx! { h4 { class: "ui-heading-anchor__heading", id, {children} } }
        }
        HeadingAnchorLevel::H5 => {
            rsx! { h5 { class: "ui-heading-anchor__heading", id, {children} } }
        }
        HeadingAnchorLevel::H6 => {
            rsx! { h6 { class: "ui-heading-anchor__heading", id, {children} } }
        }
    }
}

/// A section heading with a permalink and a copy-link button.
///
/// The permalink is a plain fragment link. The copy button stays hidden until the page location
/// is known (web and desktop read it from the browser), then copies the section's absolute URL.
/// Dioxus Native has no page location, so the button stays hidden there.
#[component]
pub fn HeadingAnchor(props: HeadingAnchorProps) -> Element {
    let mut location = use_signal(|| None::<String>);
    let heading_id = props.id.trim().to_string();
    let href = heading_anchor_href(&heading_id);
    let section = optional_text(props.label.as_deref())
        .unwrap_or_else(|| collapse_whitespace(&element_text(&props.children)));
    let url = location().and_then(|base| heading_anchor_url(&heading_id, &base));
    let class = compose([Some("ui-heading-anchor"), props.class.as_deref()]);
    let refresh = move || {
        spawn(async move {
            let next = location_href().await;

            if next.is_some() && *location.peek() != next {
                location.set(next);
            }
        });
    };

    use_effect(refresh);

    let level = props.level;
    let link_label = heading_label(props.link_label.as_deref(), &section, LINK_LABEL);
    let copy_label = heading_label(props.copy_label.as_deref(), &section, COPY_LABEL);
    let copied_label =
        optional_text(props.copied_label.as_deref()).unwrap_or_else(|| COPIED_LABEL.to_string());
    let error_label =
        optional_text(props.error_label.as_deref()).unwrap_or_else(|| ERROR_LABEL.to_string());
    let copy_value = url.clone().or_else(|| href.clone()).unwrap_or_default();

    rsx! {
        div {
            class,
            "data-level": "{level.number()}",
            "data-slot": "heading-anchor",
            "data-ui-heading-anchor": "",
            "data-ui-owner": "dioxus",
            ..props.attributes,
            {heading_element(level, (!heading_id.is_empty()).then(|| heading_id.clone()), props.children)}
            if let Some(href) = href {
                span {
                    class: "ui-heading-anchor__actions",
                    "data-slot": "heading-anchor-actions",
                    // The location can change without an event (pushState); read it again before a copy.
                    onfocusin: move |_| refresh(),
                    onpointerenter: move |_| refresh(),
                    a {
                        aria_label: link_label,
                        class: "ui-heading-anchor__link",
                        "data-slot": "heading-anchor-link",
                        href,
                        span { aria_hidden: "true", class: "ui-heading-anchor__hash", "#" }
                    }
                    if props.copy {
                        CopyButton {
                            class: "ui-heading-anchor__copy",
                            copied_content: rsx! { {heading_icon(&lucide::CHECK)} },
                            copied_label,
                            error_content: rsx! { {heading_icon(&lucide::X)} },
                            error_label,
                            hidden: url.is_none(),
                            label: copy_label,
                            size: ButtonSize::Icon,
                            value: copy_value,
                            variant: ButtonVariant::Ghost,
                            {heading_icon(&lucide::COPY)}
                        }
                    }
                }
            }
        }
    }
}

/// Catalog artwork for the copy button, with the `ui-heading-anchor__icon` hook that sizes it.
fn heading_icon(icon: &'static IconData) -> Element {
    icon_svg(
        icon,
        &format!("{} ui-heading-anchor__icon", icon_svg_class(icon)),
    )
}

/// One link of an [`Anchor`] table of contents.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AnchorLink {
    /// Destination, usually a fragment such as `#install`.
    pub href: String,
    /// Visible text.
    pub label: String,
    /// Secondary line under the label.
    pub description: Option<String>,
    /// Nesting depth from 1 to 6, rendered as `data-depth` for indentation.
    pub depth: Option<u8>,
    /// Leading number or marker, such as `1.2`.
    pub index: Option<String>,
}

impl AnchorLink {
    /// A link to `href` labelled `label`.
    pub fn new(href: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            href: href.into(),
            label: label.into(),
            ..Self::default()
        }
    }

    /// The same link at a nesting depth.
    #[must_use]
    pub fn depth(mut self, depth: u8) -> Self {
        self.depth = Some(depth.clamp(1, 6));
        self
    }
}

/// The element id a fragment link points to, decoded like `decodeLumenAnchorFragment`.
fn fragment_id(href: &str) -> Option<String> {
    href.strip_prefix('#')
        .filter(|fragment| !fragment.is_empty())
        .map(decode_uri_component)
}

/// Props for [`Anchor`].
#[derive(Props, Clone, PartialEq)]
pub struct AnchorProps {
    /// The table of contents.
    #[props(default)]
    pub items: Vec<AnchorLink>,
    /// Controlled active link, by `href`.
    #[props(into)]
    pub value: Option<String>,
    /// Called with the `href` of the newly active link.
    pub on_value_change: Option<EventHandler<String>>,
    /// Distance in pixels from the top of the viewport where a section becomes active.
    /// Defaults to 96.
    #[props(default = 96.0)]
    pub activation_offset: f64,
    /// Accessible name of the landmark. Defaults to `On this page`.
    #[props(default = "On this page".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>,
    /// Extra content after the list.
    pub children: Element,
}

/// An "On this page" table of contents that marks the section in view.
///
/// The first link starts active. Activating a link marks it active and, on web and desktop,
/// focuses its section; while the page scrolls, the section under the activation line becomes
/// active. Dioxus Native has no scroll position, so there only activation updates the link.
#[component]
pub fn Anchor(props: AnchorProps) -> Element {
    let first = props
        .items
        .first()
        .map_or_else(String::new, |item| item.href.clone());
    let active = use_controllable(props.value.clone(), || first, props.on_value_change);
    let offset = if props.activation_offset.is_finite() {
        props.activation_offset.max(0.0)
    } else {
        0.0
    };
    let class = compose([Some("ui-anchor"), props.class.as_deref()]);
    let current = active.get();
    let sections: Vec<(String, String)> = props
        .items
        .iter()
        .filter_map(|item| fragment_id(&item.href).map(|id| (id, item.href.clone())))
        .collect();
    let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));

    use_effect(use_reactive(
        (&sections, &offset),
        move |(sections, offset)| {
            if let Some(previous) = watcher.write().take() {
                previous.stop();
            }

            if sections.is_empty() {
                return;
            }

            let ids = sections.iter().map(|(id, _)| id.clone()).collect();
            let next = watch_active_section(ids, offset, move |index| {
                if let Some((_, href)) = sections.get(index) {
                    active.set(href.clone());
                }
            });
            watcher.set(Some(next));
        },
    ));

    use_drop(move || {
        if let Some(previous) = watcher.write().take() {
            previous.stop();
        }
    });

    rsx! {
        nav {
            aria_label: props.aria_label,
            class,
            "data-ui-anchor": "true",
            "data-ui-anchor-offset": js_number(offset),
            "data-ui-owner": "dioxus",
            ..props.attributes,
            if !props.items.is_empty() {
                ol {
                    for item in props.items {
                        {
                            let is_active = item.href == current;
                            let href = item.href.clone();

                            rsx! {
                                li { key: "{item.href}",
                                    a {
                                        aria_current: is_active.then_some("location"),
                                        "data-active": if is_active { "true" } else { "false" },
                                        "data-depth": item.depth.map(|depth| depth.to_string()),
                                        href: item.href.clone(),
                                        onclick: move |_| {
                                            active.set(href.clone());

                                            if let Some(id) = fragment_id(&href) {
                                                spawn(async move {
                                                    // Let the browser follow the fragment first.
                                                    sleep(Duration::ZERO).await;
                                                    focus_element_by_id(id, None).await;
                                                });
                                            }
                                        },
                                        if let Some(index) = item.index {
                                            span { class: "ui-anchor__index", "{index}" }
                                        }
                                        span { class: "ui-anchor__content",
                                            span { class: "ui-anchor__label", "{item.label}" }
                                            if let Some(description) = item.description.filter(|text| !text.is_empty()) {
                                                span { class: "ui-anchor__description", "{description}" }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            {props.children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        HeadingAnchorLevel, fragment_id, heading_anchor_href, heading_anchor_url, heading_label,
        js_number,
    };

    #[test]
    fn heading_hrefs_and_urls_follow_lumen_core() {
        assert_eq!(
            heading_anchor_href(" install ").as_deref(),
            Some("#install")
        );
        assert_eq!(heading_anchor_href("a b/c").as_deref(), Some("#a%20b%2Fc"));
        assert_eq!(heading_anchor_href("  "), None);
        assert_eq!(
            heading_anchor_url("install", "https://example.com/docs?x=1#old").as_deref(),
            Some("https://example.com/docs?x=1#install")
        );
        assert_eq!(heading_anchor_url("install", "not a url"), None);
        assert_eq!(heading_anchor_url("", "https://example.com/"), None);
    }

    #[test]
    fn levels_and_labels_normalize() {
        assert_eq!(HeadingAnchorLevel::from_number(1), HeadingAnchorLevel::H2);
        assert_eq!(HeadingAnchorLevel::from_number(4).number(), 4);
        assert_eq!(
            heading_label(None, " Install ", "Link to section: {heading}"),
            "Link to section: Install"
        );
        assert_eq!(heading_label(Some("  "), "A", "Go {heading}"), "Go A");
        assert_eq!(heading_label(Some("Ir a {heading}"), "A", "x"), "Ir a A");
    }

    #[test]
    fn fragments_decode_and_numbers_format() {
        assert_eq!(fragment_id("#a%20b").as_deref(), Some("a b"));
        assert_eq!(fragment_id("#100%").as_deref(), Some("100%"));
        assert_eq!(fragment_id("/page"), None);
        assert_eq!(fragment_id("#"), None);
        assert_eq!(js_number(96.0), "96");
        assert_eq!(js_number(12.5), "12.5");
    }
}