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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Page structure and content lists: `PageHeader`, `SectionHeader`, `Hero`, `Steps`,
//! `StepsItem`, `FeatureGrid`, and `FeatureGridItem`.

use dioxus::prelude::*;

use super::util::{attr, heading, heading_level, join_style};
use crate::class::compose;
use crate::hooks::use_id_or;

/// Whether an element prop carries content, like `hasHeaderContent` in `@santi020k/lumen-react`.
pub(crate) fn has_content(element: &Element) -> bool {
    match element {
        Ok(node) => *node != VNode::placeholder(),
        Err(_) => true,
    }
}

fn optional(element: Option<&Element>) -> Option<Element> {
    element.filter(|content| has_content(content)).cloned()
}

#[derive(Clone, Copy, PartialEq)]
enum HeaderPart {
    Page,
    Section,
}

impl HeaderPart {
    fn name(self) -> &'static str {
        match self {
            Self::Page => "page-header",
            Self::Section => "section-header",
        }
    }
}

struct HeaderParts {
    actions: Option<Element>,
    body: Element,
    count: Option<String>,
    description: Option<Element>,
    eyebrow: Option<Element>,
    leading: Option<Element>,
    level: u8,
    part: HeaderPart,
    title: Element,
}

fn header_parts(parts: HeaderParts) -> Element {
    let part = parts.part.name();
    let class = |name: &str| format!("ui-{part}__{name}");
    let slot = |name: &str| format!("{part}-{name}");
    let title_attributes = vec![
        attr("class", class("title")),
        attr("data-slot", slot("title")),
    ];
    let title = parts.title;
    let count = parts.count;
    let title_content = rsx! {
        {title}
        if let Some(count) = count {
            span { class: "ui-section-header__count", "data-slot": "section-header-count",
                span { class: "ui-sr-only", " (" }
                "{count}"
                span { class: "ui-sr-only", ")" }
            }
        }
    };
    let has_body = has_content(&parts.body);

    rsx! {
        if let Some(leading) = parts.leading {
            div { class: class("leading"), "data-slot": slot("leading"), {leading} }
        }
        div { class: class("content"), "data-slot": slot("content"),
            if let Some(eyebrow) = parts.eyebrow {
                p { class: format!("ui-eyebrow ui-{part}__eyebrow"), "data-slot": slot("eyebrow"), {eyebrow} }
            }
            {heading(parts.level, title_attributes, title_content)}
            if let Some(description) = parts.description {
                p { class: class("description"), "data-slot": slot("description"), {description} }
            }
        }
        if let Some(actions) = parts.actions {
            div { class: class("actions"), "data-slot": slot("actions"), {actions} }
        }
        if has_body {
            div { class: class("body"), "data-slot": slot("body"), {parts.body} }
        }
    }
}

/// Props for [`PageHeader`].
#[derive(Props, Clone, PartialEq)]
pub struct PageHeaderProps {
    /// The page title.
    pub title: Element,
    /// Short context label above the title.
    pub eyebrow: Option<Element>,
    /// Supporting sentence under the title.
    pub description: Option<Element>,
    /// Buttons or links beside the text.
    pub actions: Option<Element>,
    /// Icon or avatar tile before the text.
    pub leading: Option<Element>,
    /// Heading level for the title. Defaults to 1; values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<header>` or global attribute.
    #[props(extends = GlobalAttributes, extends = header)]
    pub attributes: Vec<Attribute>,
    /// Extra content under the header, such as a meta row or tabs.
    pub children: Element,
}

/// The top of a page or app view: eyebrow, title, description, actions, and a leading tile.
#[component]
pub fn PageHeader(props: PageHeaderProps) -> Element {
    let class = compose([Some("ui-page-header"), props.class.as_deref()]);
    let parts = header_parts(HeaderParts {
        actions: optional(props.actions.as_ref()),
        body: props.children,
        count: None,
        description: optional(props.description.as_ref()),
        eyebrow: optional(props.eyebrow.as_ref()),
        leading: optional(props.leading.as_ref()),
        level: heading_level(props.heading_level, 1),
        part: HeaderPart::Page,
        title: props.title,
    });

    rsx! {
        header { class, "data-slot": "page-header", ..props.attributes, {parts} }
    }
}

/// Visual hierarchy of a section title, independent of its heading level.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SectionHeaderSize {
    /// A compact heading inside a card.
    Sm,
    /// The default section heading.
    #[default]
    Md,
}

/// Props for [`SectionHeader`].
#[derive(Props, Clone, PartialEq)]
pub struct SectionHeaderProps {
    /// The section title.
    pub title: Element,
    /// Visual hierarchy; does not change `heading_level`.
    #[props(default)]
    pub size: SectionHeaderSize,
    /// Neutral count after the title, read as "Title (count)" by assistive technology. Blank
    /// values are ignored.
    #[props(into)]
    pub count: Option<String>,
    /// Short context label above the title.
    pub eyebrow: Option<Element>,
    /// Supporting sentence under the title.
    pub description: Option<Element>,
    /// Buttons or links beside the text.
    pub actions: Option<Element>,
    /// Icon or avatar tile before the text.
    pub leading: Option<Element>,
    /// Heading level for the title. Defaults to 2; values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<header>` or global attribute.
    #[props(extends = GlobalAttributes, extends = header)]
    pub attributes: Vec<Attribute>,
    /// Extra content under the header.
    pub children: Element,
}

/// A heading row for a section inside a page, with an optional neutral count.
#[component]
pub fn SectionHeader(props: SectionHeaderProps) -> Element {
    let class = compose([
        Some("ui-section-header"),
        (props.size == SectionHeaderSize::Sm).then_some("ui-section-header--sm"),
        props.class.as_deref(),
    ]);
    let count = props
        .count
        .as_deref()
        .map(str::trim)
        .filter(|count| !count.is_empty())
        .map(str::to_string);
    let parts = header_parts(HeaderParts {
        actions: optional(props.actions.as_ref()),
        body: props.children,
        count,
        description: optional(props.description.as_ref()),
        eyebrow: optional(props.eyebrow.as_ref()),
        leading: optional(props.leading.as_ref()),
        level: heading_level(props.heading_level, 2),
        part: HeaderPart::Section,
        title: props.title,
    });

    rsx! {
        header { class, "data-slot": "section-header", ..props.attributes, {parts} }
    }
}

/// Arrangement of a [`Hero`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeroLayout {
    /// Copy beside the aside on wide containers, stacked otherwise.
    #[default]
    Split,
    /// Centered copy with the aside below.
    Centered,
}

impl HeroLayout {
    /// The class suffix and `data-layout` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Split => "split",
            Self::Centered => "centered",
        }
    }
}

/// Props for [`Hero`].
#[derive(Props, Clone, PartialEq)]
pub struct HeroProps {
    /// The hero title. It also names the section.
    pub title: Element,
    /// Short context label above the title.
    pub eyebrow: Option<Element>,
    /// Supporting paragraph under the title.
    pub description: Option<Element>,
    /// Calls to action.
    pub actions: Option<Element>,
    /// Small block under the actions, such as an install command.
    pub footnote: Option<Element>,
    /// Media or visual beside or below the copy.
    pub aside: Option<Element>,
    /// Arrangement.
    #[props(default)]
    pub layout: HeroLayout,
    /// Heading level for the title. Defaults to 1; values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Section id. The title id is `{id}-title`; generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// Extra content under the copy.
    pub children: Element,
}

/// A landing hero labelled by its own heading.
#[component]
pub fn Hero(props: HeroProps) -> Element {
    let base_id = use_id_or(props.id.as_deref());
    let title_id = format!("{base_id}-title");
    let layout = props.layout.as_str();
    let layout_class = format!("ui-hero--{layout}");
    let class = compose([
        Some("ui-hero"),
        Some(layout_class.as_str()),
        props.class.as_deref(),
    ]);
    let title_attributes = vec![
        attr("class", "ui-hero__title"),
        attr("data-slot", "hero-title"),
        attr("id", title_id.clone()),
    ];
    let title = heading(
        heading_level(props.heading_level, 1),
        title_attributes,
        props.title,
    );
    let eyebrow = optional(props.eyebrow.as_ref());
    let description = optional(props.description.as_ref());
    let actions = optional(props.actions.as_ref());
    let footnote = optional(props.footnote.as_ref());
    let aside = optional(props.aside.as_ref());
    let has_body = has_content(&props.children);

    rsx! {
        section {
            aria_labelledby: title_id,
            class,
            "data-layout": layout,
            "data-slot": "hero",
            id: props.id,
            ..props.attributes,
            div { class: "ui-hero__content", "data-slot": "hero-content",
                if let Some(eyebrow) = eyebrow {
                    p { class: "ui-eyebrow ui-hero__eyebrow", "data-slot": "hero-eyebrow", {eyebrow} }
                }
                {title}
                if let Some(description) = description {
                    p { class: "ui-hero__description", "data-slot": "hero-description", {description} }
                }
                if let Some(actions) = actions {
                    div { class: "ui-hero__actions", "data-slot": "hero-actions", {actions} }
                }
                if let Some(footnote) = footnote {
                    div { class: "ui-hero__footnote", "data-slot": "hero-footnote", {footnote} }
                }
                if has_body {
                    div { class: "ui-hero__body", "data-slot": "hero-body", {props.children} }
                }
            }
            if let Some(aside) = aside {
                div { class: "ui-hero__aside", "data-slot": "hero-aside", {aside} }
            }
        }
    }
}

/// Arrangement of [`Steps`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StepsLayout {
    /// Stacked numbered steps.
    #[default]
    List,
    /// Steps joined by a vertical connector between markers.
    Rail,
}

impl StepsLayout {
    /// The class suffix and `data-layout` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::List => "list",
            Self::Rail => "rail",
        }
    }
}

/// Largest absolute `start` accepted; larger values fall back to 1, like `lumen-core`.
const MAX_STEPS_START: i64 = 1_000_000;

/// The first number [`Steps`] shows, like `resolveLumenStepsStart` in `lumen-core`.
pub(crate) fn steps_start(start: Option<i64>) -> i64 {
    start
        .filter(|value| (-MAX_STEPS_START..=MAX_STEPS_START).contains(value))
        .unwrap_or(1)
}

/// Props for [`Steps`].
#[derive(Props, Clone, PartialEq)]
pub struct StepsProps {
    /// Arrangement.
    #[props(default)]
    pub layout: StepsLayout,
    /// First number shown. Values beyond one million in either direction use 1.
    pub start: Option<i64>,
    /// Inline style. The counter offset is appended after it.
    #[props(into)]
    pub style: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<ol>` or global attribute.
    #[props(extends = GlobalAttributes, extends = ol)]
    pub attributes: Vec<Attribute>,
    /// [`StepsItem`]s.
    pub children: Element,
}

/// Numbered documentation or quick-start steps. Numbering works without JavaScript.
#[component]
pub fn Steps(props: StepsProps) -> Element {
    let layout = props.layout.as_str();
    let layout_class = format!("ui-steps--{layout}");
    let class = compose([
        Some("ui-steps"),
        Some(layout_class.as_str()),
        props.class.as_deref(),
    ]);
    let start = steps_start(props.start);
    let offset = (start != 1).then(|| format!("--ui-steps-offset: {}", start - 1));
    let style = join_style([props.style.as_deref(), offset.as_deref()]);

    rsx! {
        ol {
            class,
            "data-layout": layout,
            "data-slot": "steps",
            role: "list",
            start: (start != 1).then(|| start.to_string()),
            style,
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`StepsItem`].
#[derive(Props, Clone, PartialEq)]
pub struct StepsItemProps {
    /// Step title.
    pub title: Element,
    /// Custom marker such as "01", "A", or an icon. Defaults to the step number.
    pub marker: Option<Element>,
    /// Exposes a custom marker to assistive technology when it adds meaning.
    #[props(default)]
    pub announce_marker: bool,
    /// Heading level for the title. Defaults to 3; values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<li>` or global attribute.
    #[props(extends = GlobalAttributes, extends = li)]
    pub attributes: Vec<Attribute>,
    /// Step body: text, code, or links.
    pub children: Element,
}

/// One step inside [`Steps`]. The marker is hidden from screen readers unless announced.
#[component]
pub fn StepsItem(props: StepsItemProps) -> Element {
    let marker = optional(props.marker.as_ref());
    let hidden = !(marker.is_some() && props.announce_marker);
    let class = compose([Some("ui-steps__item"), props.class.as_deref()]);
    let title = has_content(&props.title).then(|| {
        heading(
            heading_level(props.heading_level, 3),
            vec![
                attr("class", "ui-steps__title"),
                attr("data-slot", "steps-title"),
            ],
            props.title.clone(),
        )
    });
    let has_body = has_content(&props.children);

    rsx! {
        li { class, "data-slot": "steps-item", ..props.attributes,
            span {
                aria_hidden: hidden.then_some("true"),
                class: "ui-steps__marker",
                "data-slot": "steps-marker",
                {marker}
            }
            div { class: "ui-steps__content", "data-slot": "steps-content",
                {title}
                if has_body {
                    div { class: "ui-steps__body", "data-slot": "steps-body", {props.children} }
                }
            }
        }
    }
}

/// Framing of a [`FeatureGrid`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FeatureGridVariant {
    /// Features laid on the page.
    #[default]
    Plain,
    /// Each feature framed in a bordered surface.
    Card,
}

impl FeatureGridVariant {
    /// The class suffix and `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Plain => "plain",
            Self::Card => "card",
        }
    }
}

/// Props for [`FeatureGrid`].
#[derive(Props, Clone, PartialEq)]
pub struct FeatureGridProps {
    /// Most columns on wide containers. Clamps to 2-4; defaults to 3.
    #[props(default = 3)]
    pub columns: u8,
    /// Framing.
    #[props(default)]
    pub variant: FeatureGridVariant,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<ul>` or global attribute.
    #[props(extends = GlobalAttributes, extends = ul)]
    pub attributes: Vec<Attribute>,
    /// [`FeatureGridItem`]s.
    pub children: Element,
}

/// A responsive list of product features.
#[component]
pub fn FeatureGrid(props: FeatureGridProps) -> Element {
    let columns = props.columns.clamp(2, 4).to_string();
    let variant = props.variant.as_str();
    let columns_class = format!("ui-feature-grid--columns-{columns}");
    let variant_class = format!("ui-feature-grid--{variant}");
    let class = compose([
        Some("ui-feature-grid"),
        Some(columns_class.as_str()),
        Some(variant_class.as_str()),
        props.class.as_deref(),
    ]);

    rsx! {
        ul {
            class,
            "data-columns": columns,
            "data-slot": "feature-grid",
            "data-variant": variant,
            role: "list",
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`FeatureGridItem`].
#[derive(Props, Clone, PartialEq)]
pub struct FeatureGridItemProps {
    /// Feature title.
    pub title: Element,
    /// Supporting sentence under the title.
    pub description: Option<Element>,
    /// Turns the title into a link. In the card variant the whole card becomes the target.
    #[props(into)]
    pub href: Option<String>,
    /// Decorative icon above the title. Takes precedence over `index`.
    pub icon: Option<Element>,
    /// Decorative index such as "01" above the title.
    pub index: Option<Element>,
    /// Heading level for the title. Defaults to 3; values outside 1-6 clamp.
    pub heading_level: Option<i64>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<li>` or global attribute.
    #[props(extends = GlobalAttributes, extends = li)]
    pub attributes: Vec<Attribute>,
    /// Extra content under the description, such as secondary links.
    pub children: Element,
}

/// One feature inside [`FeatureGrid`]. Icon and index markers are decorative.
#[component]
pub fn FeatureGridItem(props: FeatureGridItemProps) -> Element {
    let class = compose([Some("ui-feature-grid__item"), props.class.as_deref()]);
    let icon = optional(props.icon.as_ref());
    let index = if icon.is_none() {
        optional(props.index.as_ref())
    } else {
        None
    };
    let description = optional(props.description.as_ref());
    let title_content = match props.href.clone() {
        Some(href) => rsx! {
            a { class: "ui-feature-grid__link", "data-slot": "feature-grid-link", href, {props.title.clone()} }
        },
        None => props.title.clone(),
    };
    let title = heading(
        heading_level(props.heading_level, 3),
        vec![
            attr("class", "ui-feature-grid__title"),
            attr("data-slot", "feature-grid-title"),
        ],
        title_content,
    );
    let has_body = has_content(&props.children);

    rsx! {
        li { class, "data-slot": "feature-grid-item", ..props.attributes,
            if let Some(icon) = icon {
                span { aria_hidden: "true", class: "ui-feature-grid__icon", "data-slot": "feature-grid-icon", {icon} }
            }
            if let Some(index) = index {
                span { aria_hidden: "true", class: "ui-feature-grid__index", "data-slot": "feature-grid-index", {index} }
            }
            {title}
            if let Some(description) = description {
                p { class: "ui-feature-grid__description", "data-slot": "feature-grid-description", {description} }
            }
            if has_body {
                div { class: "ui-feature-grid__body", "data-slot": "feature-grid-body", {props.children} }
            }
        }
    }
}

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

    #[test]
    fn steps_start_falls_back_outside_the_range() {
        assert_eq!(steps_start(None), 1);
        assert_eq!(steps_start(Some(3)), 3);
        assert_eq!(steps_start(Some(-2)), -2);
        assert_eq!(steps_start(Some(1_000_000)), 1_000_000);
        assert_eq!(steps_start(Some(1_000_001)), 1);
        assert_eq!(steps_start(Some(i64::MIN)), 1);
    }
}