Skip to main content

lumen_dioxus/layout/
headers.rs

1//! Page structure and content lists: `PageHeader`, `SectionHeader`, `Hero`, `Steps`,
2//! `StepsItem`, `FeatureGrid`, and `FeatureGridItem`.
3
4use dioxus::prelude::*;
5
6use super::util::{attr, heading, heading_level, join_style};
7use crate::class::compose;
8use crate::hooks::use_id_or;
9
10/// Whether an element prop carries content, like `hasHeaderContent` in `@santi020k/lumen-react`.
11pub(crate) fn has_content(element: &Element) -> bool {
12    match element {
13        Ok(node) => *node != VNode::placeholder(),
14        Err(_) => true,
15    }
16}
17
18fn optional(element: Option<&Element>) -> Option<Element> {
19    element.filter(|content| has_content(content)).cloned()
20}
21
22#[derive(Clone, Copy, PartialEq)]
23enum HeaderPart {
24    Page,
25    Section,
26}
27
28impl HeaderPart {
29    fn name(self) -> &'static str {
30        match self {
31            Self::Page => "page-header",
32            Self::Section => "section-header",
33        }
34    }
35}
36
37struct HeaderParts {
38    actions: Option<Element>,
39    body: Element,
40    count: Option<String>,
41    description: Option<Element>,
42    eyebrow: Option<Element>,
43    leading: Option<Element>,
44    level: u8,
45    part: HeaderPart,
46    title: Element,
47}
48
49fn header_parts(parts: HeaderParts) -> Element {
50    let part = parts.part.name();
51    let class = |name: &str| format!("ui-{part}__{name}");
52    let slot = |name: &str| format!("{part}-{name}");
53    let title_attributes = vec![
54        attr("class", class("title")),
55        attr("data-slot", slot("title")),
56    ];
57    let title = parts.title;
58    let count = parts.count;
59    let title_content = rsx! {
60        {title}
61        if let Some(count) = count {
62            span { class: "ui-section-header__count", "data-slot": "section-header-count",
63                span { class: "ui-sr-only", " (" }
64                "{count}"
65                span { class: "ui-sr-only", ")" }
66            }
67        }
68    };
69    let has_body = has_content(&parts.body);
70
71    rsx! {
72        if let Some(leading) = parts.leading {
73            div { class: class("leading"), "data-slot": slot("leading"), {leading} }
74        }
75        div { class: class("content"), "data-slot": slot("content"),
76            if let Some(eyebrow) = parts.eyebrow {
77                p { class: format!("ui-eyebrow ui-{part}__eyebrow"), "data-slot": slot("eyebrow"), {eyebrow} }
78            }
79            {heading(parts.level, title_attributes, title_content)}
80            if let Some(description) = parts.description {
81                p { class: class("description"), "data-slot": slot("description"), {description} }
82            }
83        }
84        if let Some(actions) = parts.actions {
85            div { class: class("actions"), "data-slot": slot("actions"), {actions} }
86        }
87        if has_body {
88            div { class: class("body"), "data-slot": slot("body"), {parts.body} }
89        }
90    }
91}
92
93/// Props for [`PageHeader`].
94#[derive(Props, Clone, PartialEq)]
95pub struct PageHeaderProps {
96    /// The page title.
97    pub title: Element,
98    /// Short context label above the title.
99    pub eyebrow: Option<Element>,
100    /// Supporting sentence under the title.
101    pub description: Option<Element>,
102    /// Buttons or links beside the text.
103    pub actions: Option<Element>,
104    /// Icon or avatar tile before the text.
105    pub leading: Option<Element>,
106    /// Heading level for the title. Defaults to 1; values outside 1-6 clamp.
107    pub heading_level: Option<i64>,
108    /// Extra classes appended after the Lumen class.
109    #[props(into)]
110    pub class: Option<String>,
111    /// Any other `<header>` or global attribute.
112    #[props(extends = GlobalAttributes, extends = header)]
113    pub attributes: Vec<Attribute>,
114    /// Extra content under the header, such as a meta row or tabs.
115    pub children: Element,
116}
117
118/// The top of a page or app view: eyebrow, title, description, actions, and a leading tile.
119#[component]
120pub fn PageHeader(props: PageHeaderProps) -> Element {
121    let class = compose([Some("ui-page-header"), props.class.as_deref()]);
122    let parts = header_parts(HeaderParts {
123        actions: optional(props.actions.as_ref()),
124        body: props.children,
125        count: None,
126        description: optional(props.description.as_ref()),
127        eyebrow: optional(props.eyebrow.as_ref()),
128        leading: optional(props.leading.as_ref()),
129        level: heading_level(props.heading_level, 1),
130        part: HeaderPart::Page,
131        title: props.title,
132    });
133
134    rsx! {
135        header { class, "data-slot": "page-header", ..props.attributes, {parts} }
136    }
137}
138
139/// Visual hierarchy of a section title, independent of its heading level.
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum SectionHeaderSize {
143    /// A compact heading inside a card.
144    Sm,
145    /// The default section heading.
146    #[default]
147    Md,
148}
149
150/// Props for [`SectionHeader`].
151#[derive(Props, Clone, PartialEq)]
152pub struct SectionHeaderProps {
153    /// The section title.
154    pub title: Element,
155    /// Visual hierarchy; does not change `heading_level`.
156    #[props(default)]
157    pub size: SectionHeaderSize,
158    /// Neutral count after the title, read as "Title (count)" by assistive technology. Blank
159    /// values are ignored.
160    #[props(into)]
161    pub count: Option<String>,
162    /// Short context label above the title.
163    pub eyebrow: Option<Element>,
164    /// Supporting sentence under the title.
165    pub description: Option<Element>,
166    /// Buttons or links beside the text.
167    pub actions: Option<Element>,
168    /// Icon or avatar tile before the text.
169    pub leading: Option<Element>,
170    /// Heading level for the title. Defaults to 2; values outside 1-6 clamp.
171    pub heading_level: Option<i64>,
172    /// Extra classes appended after the Lumen class.
173    #[props(into)]
174    pub class: Option<String>,
175    /// Any other `<header>` or global attribute.
176    #[props(extends = GlobalAttributes, extends = header)]
177    pub attributes: Vec<Attribute>,
178    /// Extra content under the header.
179    pub children: Element,
180}
181
182/// A heading row for a section inside a page, with an optional neutral count.
183#[component]
184pub fn SectionHeader(props: SectionHeaderProps) -> Element {
185    let class = compose([
186        Some("ui-section-header"),
187        (props.size == SectionHeaderSize::Sm).then_some("ui-section-header--sm"),
188        props.class.as_deref(),
189    ]);
190    let count = props
191        .count
192        .as_deref()
193        .map(str::trim)
194        .filter(|count| !count.is_empty())
195        .map(str::to_string);
196    let parts = header_parts(HeaderParts {
197        actions: optional(props.actions.as_ref()),
198        body: props.children,
199        count,
200        description: optional(props.description.as_ref()),
201        eyebrow: optional(props.eyebrow.as_ref()),
202        leading: optional(props.leading.as_ref()),
203        level: heading_level(props.heading_level, 2),
204        part: HeaderPart::Section,
205        title: props.title,
206    });
207
208    rsx! {
209        header { class, "data-slot": "section-header", ..props.attributes, {parts} }
210    }
211}
212
213/// Arrangement of a [`Hero`].
214#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
215#[non_exhaustive]
216pub enum HeroLayout {
217    /// Copy beside the aside on wide containers, stacked otherwise.
218    #[default]
219    Split,
220    /// Centered copy with the aside below.
221    Centered,
222}
223
224impl HeroLayout {
225    /// The class suffix and `data-layout` value.
226    pub fn as_str(self) -> &'static str {
227        match self {
228            Self::Split => "split",
229            Self::Centered => "centered",
230        }
231    }
232}
233
234/// Props for [`Hero`].
235#[derive(Props, Clone, PartialEq)]
236pub struct HeroProps {
237    /// The hero title. It also names the section.
238    pub title: Element,
239    /// Short context label above the title.
240    pub eyebrow: Option<Element>,
241    /// Supporting paragraph under the title.
242    pub description: Option<Element>,
243    /// Calls to action.
244    pub actions: Option<Element>,
245    /// Small block under the actions, such as an install command.
246    pub footnote: Option<Element>,
247    /// Media or visual beside or below the copy.
248    pub aside: Option<Element>,
249    /// Arrangement.
250    #[props(default)]
251    pub layout: HeroLayout,
252    /// Heading level for the title. Defaults to 1; values outside 1-6 clamp.
253    pub heading_level: Option<i64>,
254    /// Section id. The title id is `{id}-title`; generated when unset.
255    #[props(into)]
256    pub id: Option<String>,
257    /// Extra classes appended after the Lumen classes.
258    #[props(into)]
259    pub class: Option<String>,
260    /// Any other `<section>` or global attribute.
261    #[props(extends = GlobalAttributes, extends = section)]
262    pub attributes: Vec<Attribute>,
263    /// Extra content under the copy.
264    pub children: Element,
265}
266
267/// A landing hero labelled by its own heading.
268#[component]
269pub fn Hero(props: HeroProps) -> Element {
270    let base_id = use_id_or(props.id.as_deref());
271    let title_id = format!("{base_id}-title");
272    let layout = props.layout.as_str();
273    let layout_class = format!("ui-hero--{layout}");
274    let class = compose([
275        Some("ui-hero"),
276        Some(layout_class.as_str()),
277        props.class.as_deref(),
278    ]);
279    let title_attributes = vec![
280        attr("class", "ui-hero__title"),
281        attr("data-slot", "hero-title"),
282        attr("id", title_id.clone()),
283    ];
284    let title = heading(
285        heading_level(props.heading_level, 1),
286        title_attributes,
287        props.title,
288    );
289    let eyebrow = optional(props.eyebrow.as_ref());
290    let description = optional(props.description.as_ref());
291    let actions = optional(props.actions.as_ref());
292    let footnote = optional(props.footnote.as_ref());
293    let aside = optional(props.aside.as_ref());
294    let has_body = has_content(&props.children);
295
296    rsx! {
297        section {
298            aria_labelledby: title_id,
299            class,
300            "data-layout": layout,
301            "data-slot": "hero",
302            id: props.id,
303            ..props.attributes,
304            div { class: "ui-hero__content", "data-slot": "hero-content",
305                if let Some(eyebrow) = eyebrow {
306                    p { class: "ui-eyebrow ui-hero__eyebrow", "data-slot": "hero-eyebrow", {eyebrow} }
307                }
308                {title}
309                if let Some(description) = description {
310                    p { class: "ui-hero__description", "data-slot": "hero-description", {description} }
311                }
312                if let Some(actions) = actions {
313                    div { class: "ui-hero__actions", "data-slot": "hero-actions", {actions} }
314                }
315                if let Some(footnote) = footnote {
316                    div { class: "ui-hero__footnote", "data-slot": "hero-footnote", {footnote} }
317                }
318                if has_body {
319                    div { class: "ui-hero__body", "data-slot": "hero-body", {props.children} }
320                }
321            }
322            if let Some(aside) = aside {
323                div { class: "ui-hero__aside", "data-slot": "hero-aside", {aside} }
324            }
325        }
326    }
327}
328
329/// Arrangement of [`Steps`].
330#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
331#[non_exhaustive]
332pub enum StepsLayout {
333    /// Stacked numbered steps.
334    #[default]
335    List,
336    /// Steps joined by a vertical connector between markers.
337    Rail,
338}
339
340impl StepsLayout {
341    /// The class suffix and `data-layout` value.
342    pub fn as_str(self) -> &'static str {
343        match self {
344            Self::List => "list",
345            Self::Rail => "rail",
346        }
347    }
348}
349
350/// Largest absolute `start` accepted; larger values fall back to 1, like `lumen-core`.
351const MAX_STEPS_START: i64 = 1_000_000;
352
353/// The first number [`Steps`] shows, like `resolveLumenStepsStart` in `lumen-core`.
354pub(crate) fn steps_start(start: Option<i64>) -> i64 {
355    start
356        .filter(|value| (-MAX_STEPS_START..=MAX_STEPS_START).contains(value))
357        .unwrap_or(1)
358}
359
360/// Props for [`Steps`].
361#[derive(Props, Clone, PartialEq)]
362pub struct StepsProps {
363    /// Arrangement.
364    #[props(default)]
365    pub layout: StepsLayout,
366    /// First number shown. Values beyond one million in either direction use 1.
367    pub start: Option<i64>,
368    /// Inline style. The counter offset is appended after it.
369    #[props(into)]
370    pub style: Option<String>,
371    /// Extra classes appended after the Lumen classes.
372    #[props(into)]
373    pub class: Option<String>,
374    /// Any other `<ol>` or global attribute.
375    #[props(extends = GlobalAttributes, extends = ol)]
376    pub attributes: Vec<Attribute>,
377    /// [`StepsItem`]s.
378    pub children: Element,
379}
380
381/// Numbered documentation or quick-start steps. Numbering works without JavaScript.
382#[component]
383pub fn Steps(props: StepsProps) -> Element {
384    let layout = props.layout.as_str();
385    let layout_class = format!("ui-steps--{layout}");
386    let class = compose([
387        Some("ui-steps"),
388        Some(layout_class.as_str()),
389        props.class.as_deref(),
390    ]);
391    let start = steps_start(props.start);
392    let offset = (start != 1).then(|| format!("--ui-steps-offset: {}", start - 1));
393    let style = join_style([props.style.as_deref(), offset.as_deref()]);
394
395    rsx! {
396        ol {
397            class,
398            "data-layout": layout,
399            "data-slot": "steps",
400            role: "list",
401            start: (start != 1).then(|| start.to_string()),
402            style,
403            ..props.attributes,
404            {props.children}
405        }
406    }
407}
408
409/// Props for [`StepsItem`].
410#[derive(Props, Clone, PartialEq)]
411pub struct StepsItemProps {
412    /// Step title.
413    pub title: Element,
414    /// Custom marker such as "01", "A", or an icon. Defaults to the step number.
415    pub marker: Option<Element>,
416    /// Exposes a custom marker to assistive technology when it adds meaning.
417    #[props(default)]
418    pub announce_marker: bool,
419    /// Heading level for the title. Defaults to 3; values outside 1-6 clamp.
420    pub heading_level: Option<i64>,
421    /// Extra classes appended after the Lumen class.
422    #[props(into)]
423    pub class: Option<String>,
424    /// Any other `<li>` or global attribute.
425    #[props(extends = GlobalAttributes, extends = li)]
426    pub attributes: Vec<Attribute>,
427    /// Step body: text, code, or links.
428    pub children: Element,
429}
430
431/// One step inside [`Steps`]. The marker is hidden from screen readers unless announced.
432#[component]
433pub fn StepsItem(props: StepsItemProps) -> Element {
434    let marker = optional(props.marker.as_ref());
435    let hidden = !(marker.is_some() && props.announce_marker);
436    let class = compose([Some("ui-steps__item"), props.class.as_deref()]);
437    let title = has_content(&props.title).then(|| {
438        heading(
439            heading_level(props.heading_level, 3),
440            vec![
441                attr("class", "ui-steps__title"),
442                attr("data-slot", "steps-title"),
443            ],
444            props.title.clone(),
445        )
446    });
447    let has_body = has_content(&props.children);
448
449    rsx! {
450        li { class, "data-slot": "steps-item", ..props.attributes,
451            span {
452                aria_hidden: hidden.then_some("true"),
453                class: "ui-steps__marker",
454                "data-slot": "steps-marker",
455                {marker}
456            }
457            div { class: "ui-steps__content", "data-slot": "steps-content",
458                {title}
459                if has_body {
460                    div { class: "ui-steps__body", "data-slot": "steps-body", {props.children} }
461                }
462            }
463        }
464    }
465}
466
467/// Framing of a [`FeatureGrid`].
468#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
469#[non_exhaustive]
470pub enum FeatureGridVariant {
471    /// Features laid on the page.
472    #[default]
473    Plain,
474    /// Each feature framed in a bordered surface.
475    Card,
476}
477
478impl FeatureGridVariant {
479    /// The class suffix and `data-variant` value.
480    pub fn as_str(self) -> &'static str {
481        match self {
482            Self::Plain => "plain",
483            Self::Card => "card",
484        }
485    }
486}
487
488/// Props for [`FeatureGrid`].
489#[derive(Props, Clone, PartialEq)]
490pub struct FeatureGridProps {
491    /// Most columns on wide containers. Clamps to 2-4; defaults to 3.
492    #[props(default = 3)]
493    pub columns: u8,
494    /// Framing.
495    #[props(default)]
496    pub variant: FeatureGridVariant,
497    /// Extra classes appended after the Lumen classes.
498    #[props(into)]
499    pub class: Option<String>,
500    /// Any other `<ul>` or global attribute.
501    #[props(extends = GlobalAttributes, extends = ul)]
502    pub attributes: Vec<Attribute>,
503    /// [`FeatureGridItem`]s.
504    pub children: Element,
505}
506
507/// A responsive list of product features.
508#[component]
509pub fn FeatureGrid(props: FeatureGridProps) -> Element {
510    let columns = props.columns.clamp(2, 4).to_string();
511    let variant = props.variant.as_str();
512    let columns_class = format!("ui-feature-grid--columns-{columns}");
513    let variant_class = format!("ui-feature-grid--{variant}");
514    let class = compose([
515        Some("ui-feature-grid"),
516        Some(columns_class.as_str()),
517        Some(variant_class.as_str()),
518        props.class.as_deref(),
519    ]);
520
521    rsx! {
522        ul {
523            class,
524            "data-columns": columns,
525            "data-slot": "feature-grid",
526            "data-variant": variant,
527            role: "list",
528            ..props.attributes,
529            {props.children}
530        }
531    }
532}
533
534/// Props for [`FeatureGridItem`].
535#[derive(Props, Clone, PartialEq)]
536pub struct FeatureGridItemProps {
537    /// Feature title.
538    pub title: Element,
539    /// Supporting sentence under the title.
540    pub description: Option<Element>,
541    /// Turns the title into a link. In the card variant the whole card becomes the target.
542    #[props(into)]
543    pub href: Option<String>,
544    /// Decorative icon above the title. Takes precedence over `index`.
545    pub icon: Option<Element>,
546    /// Decorative index such as "01" above the title.
547    pub index: Option<Element>,
548    /// Heading level for the title. Defaults to 3; values outside 1-6 clamp.
549    pub heading_level: Option<i64>,
550    /// Extra classes appended after the Lumen class.
551    #[props(into)]
552    pub class: Option<String>,
553    /// Any other `<li>` or global attribute.
554    #[props(extends = GlobalAttributes, extends = li)]
555    pub attributes: Vec<Attribute>,
556    /// Extra content under the description, such as secondary links.
557    pub children: Element,
558}
559
560/// One feature inside [`FeatureGrid`]. Icon and index markers are decorative.
561#[component]
562pub fn FeatureGridItem(props: FeatureGridItemProps) -> Element {
563    let class = compose([Some("ui-feature-grid__item"), props.class.as_deref()]);
564    let icon = optional(props.icon.as_ref());
565    let index = if icon.is_none() {
566        optional(props.index.as_ref())
567    } else {
568        None
569    };
570    let description = optional(props.description.as_ref());
571    let title_content = match props.href.clone() {
572        Some(href) => rsx! {
573            a { class: "ui-feature-grid__link", "data-slot": "feature-grid-link", href, {props.title.clone()} }
574        },
575        None => props.title.clone(),
576    };
577    let title = heading(
578        heading_level(props.heading_level, 3),
579        vec![
580            attr("class", "ui-feature-grid__title"),
581            attr("data-slot", "feature-grid-title"),
582        ],
583        title_content,
584    );
585    let has_body = has_content(&props.children);
586
587    rsx! {
588        li { class, "data-slot": "feature-grid-item", ..props.attributes,
589            if let Some(icon) = icon {
590                span { aria_hidden: "true", class: "ui-feature-grid__icon", "data-slot": "feature-grid-icon", {icon} }
591            }
592            if let Some(index) = index {
593                span { aria_hidden: "true", class: "ui-feature-grid__index", "data-slot": "feature-grid-index", {index} }
594            }
595            {title}
596            if let Some(description) = description {
597                p { class: "ui-feature-grid__description", "data-slot": "feature-grid-description", {description} }
598            }
599            if has_body {
600                div { class: "ui-feature-grid__body", "data-slot": "feature-grid-body", {props.children} }
601            }
602        }
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use super::steps_start;
609
610    #[test]
611    fn steps_start_falls_back_outside_the_range() {
612        assert_eq!(steps_start(None), 1);
613        assert_eq!(steps_start(Some(3)), 3);
614        assert_eq!(steps_start(Some(-2)), -2);
615        assert_eq!(steps_start(Some(1_000_000)), 1_000_000);
616        assert_eq!(steps_start(Some(1_000_001)), 1);
617        assert_eq!(steps_start(Some(i64::MIN)), 1);
618    }
619}