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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! Site and application chrome: `AppHeader`, `SiteHeader`, `SiteFooter`, `Sidebar`,
//! `SidebarItem`, `SidebarTrigger`, and `ContextNavigation`.

use std::rc::Rc;

use dioxus::prelude::*;

use crate::ButtonSize;
use crate::class::{Glass, compose};
use crate::hooks::use_unique_id;
use crate::overlay::{focus_element, is_escape};

use super::util::{has_content, has_slot, optional_text, resolve_safe_href};
use super::web::{use_scroll_past, use_site_header_sheet};

/// `data-surface` for a glass prop.
pub(crate) fn surface(glass: Glass) -> &'static str {
    if glass == Glass::Off {
        "default"
    } else {
        "glass"
    }
}

/// Whether a panel uses Lumen's styling or only its behavior hooks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum NavigationVariant {
    /// Lumen's surface styling.
    #[default]
    Default,
    /// Structure and hooks only, for custom styling.
    Unstyled,
}

impl NavigationVariant {
    /// The `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Unstyled => "unstyled",
        }
    }

    pub(crate) fn modifier(self, base: &str) -> Option<String> {
        (self == Self::Unstyled).then(|| format!("{base}--unstyled"))
    }
}

/// Props for [`AppHeader`].
#[derive(Props, Clone, PartialEq)]
pub struct AppHeaderProps {
    /// Leading control, usually the sidebar trigger.
    pub leading: Option<Element>,
    /// Badges, status dots, or metadata. Wraps below the title on narrow widths.
    pub status: Option<Element>,
    /// Trailing controls such as search, notifications, or the account menu.
    pub actions: Option<Element>,
    /// Keeps the bar pinned to the top of its scroll container.
    #[props(default)]
    pub sticky: bool,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<header>` or global attribute.
    #[props(extends = GlobalAttributes, extends = header)]
    pub attributes: Vec<Attribute>,
    /// The title or context, such as a [`Breadcrumb`](crate::Breadcrumb).
    pub children: Element,
}

/// The top bar of an application shell.
#[component]
pub fn AppHeader(props: AppHeaderProps) -> Element {
    let class = compose([
        Some("ui-app-header"),
        props.sticky.then_some("ui-app-header--sticky"),
        props.class.as_deref(),
    ]);
    let leading = props.leading.filter(|slot| has_slot(Some(slot)));
    let status = props.status.filter(|slot| has_slot(Some(slot)));
    let actions = props.actions.filter(|slot| has_slot(Some(slot)));

    rsx! {
        header {
            class,
            "data-slot": "app-header",
            "data-sticky": if props.sticky { "true" } else { "false" },
            ..props.attributes,
            if let Some(leading) = leading {
                div { class: "ui-app-header__leading", "data-slot": "app-header-leading", {leading} }
            }
            div { class: "ui-app-header__title", "data-slot": "app-header-title", {props.children} }
            if let Some(status) = status {
                div { class: "ui-app-header__status", "data-slot": "app-header-status", {status} }
            }
            if let Some(actions) = actions {
                div { class: "ui-app-header__actions", "data-slot": "app-header-actions", {actions} }
            }
        }
    }
}

/// Props for [`SiteFooter`].
#[derive(Props, Clone, PartialEq)]
pub struct SiteFooterProps {
    /// Logo lockup and a short description shown before the navigation groups.
    pub brand: Option<Element>,
    /// Bottom row for the copyright notice and attribution links.
    pub legal: Option<Element>,
    /// Accessible name of the footer navigation landmark. Defaults to `Footer`.
    #[props(default = "Footer".to_string(), into)]
    pub nav_label: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<footer>` or global attribute.
    #[props(extends = GlobalAttributes, extends = footer)]
    pub attributes: Vec<Attribute>,
    /// Navigation groups: each a `div { "data-slot": "site-footer-group", ... }` with a heading
    /// and a list of links.
    pub children: Element,
}

/// A website footer with brand, navigation groups, and a legal row.
#[component]
pub fn SiteFooter(props: SiteFooterProps) -> Element {
    let class = compose([Some("ui-site-footer"), props.class.as_deref()]);
    let brand = props.brand.filter(|slot| has_slot(Some(slot)));
    let legal = props.legal.filter(|slot| has_slot(Some(slot)));
    let has_navigation = has_slot(Some(&props.children));
    let nav_label = optional_text(Some(&props.nav_label)).unwrap_or_else(|| "Footer".to_string());

    rsx! {
        footer { class, "data-slot": "site-footer", ..props.attributes,
            div { class: "ui-site-footer__inner", "data-slot": "site-footer-inner",
                if brand.is_some() || has_navigation {
                    div { class: "ui-site-footer__top", "data-slot": "site-footer-top",
                        if let Some(brand) = brand {
                            div { class: "ui-site-footer__brand", "data-slot": "site-footer-brand", {brand} }
                        }
                        if has_navigation {
                            nav {
                                aria_label: nav_label,
                                class: "ui-site-footer__nav",
                                "data-slot": "site-footer-nav",
                                {props.children}
                            }
                        }
                    }
                }
                if let Some(legal) = legal {
                    div { class: "ui-site-footer__legal", "data-slot": "site-footer-legal", {legal} }
                }
            }
        }
    }
}

/// How a [`SiteHeader`] collapses its navigation and actions while it is narrower than 40rem.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SiteHeaderCollapse {
    /// Opens them inline below the brand. Server rendering keeps them visible until the header
    /// mounts.
    #[default]
    Panel,
    /// Opens them in an off-canvas native popover from the inline-end edge, which the toggle
    /// opens through the Popover API before hydration too.
    Sheet,
}

impl SiteHeaderCollapse {
    /// The collapse name, like lumen-core's `LumenSiteHeaderCollapse`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Panel => "panel",
            Self::Sheet => "sheet",
        }
    }
}

/// Props for [`SiteHeader`].
#[derive(Props, Clone, PartialEq)]
pub struct SiteHeaderProps {
    /// Logo lockup, usually a link to the home page.
    pub brand: Option<Element>,
    /// Theme toggle, repository link, or call to action. Collapses with the navigation.
    pub actions: Option<Element>,
    /// How the navigation and actions collapse below 40rem: `Panel` opens them inline below the
    /// brand; `Sheet` opens them in an off-canvas native popover from the inline-end edge.
    #[props(default)]
    pub collapse: SiteHeaderCollapse,
    /// Accessible name of the collapsed-menu toggle. Defaults to `Menu`.
    #[props(default = "Menu".to_string(), into)]
    pub menu_label: String,
    /// Accessible name of the close button inside the open sheet. Defaults to `Close menu`. Used
    /// with `collapse: SiteHeaderCollapse::Sheet`.
    #[props(default = "Close menu".to_string(), into)]
    pub close_label: String,
    /// Accessible name of the primary navigation landmark. Defaults to `Main`.
    #[props(default = "Main".to_string(), into)]
    pub nav_label: String,
    /// Keeps the header pinned to the top of the viewport while the page scrolls.
    #[props(default = true)]
    pub sticky: bool,
    /// Header id; the menu panel id is `{id}-panel`. Generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<header>` or global attribute.
    #[props(extends = GlobalAttributes, extends = header)]
    pub attributes: Vec<Attribute>,
    /// The primary navigation links.
    pub children: Element,
}

/// The root's `data-state` value.
fn open_state(open: bool) -> &'static str {
    if open { "open" } else { "closed" }
}

/// `"true"` or `"false"`.
fn bool_attribute(value: bool) -> &'static str {
    if value { "true" } else { "false" }
}

/// A public website header whose navigation collapses behind a menu toggle on narrow widths.
///
/// With the default `collapse: SiteHeaderCollapse::Panel`, server rendering keeps the navigation
/// visible with the toggle hidden, like lumen-react before hydration. Once mounted, the toggle
/// appears and opens the menu; Escape closes it and returns focus to the toggle, and following a
/// navigation link closes it.
///
/// With `collapse: SiteHeaderCollapse::Sheet`, the panel is a native popover that the toggle and
/// the close button inside it open and hide through the Popover API, so it works before hydration
/// and closes on Escape and outside presses without a script. On web and desktop, a script then
/// mirrors lumen-core's sheet controller: it reflects the popover in `data-state` and
/// `aria-expanded`, moves focus to the close button when the sheet opens and back to the toggle
/// when Escape or the close button hides it, and hides the sheet after a plain link click, when
/// focus leaves it, and when the header grows wide enough to show the navigation inline. Dioxus
/// Native has no Popover API, so keep `collapse` at `Panel` there.
#[component]
pub fn SiteHeader(props: SiteHeaderProps) -> Element {
    let generated = use_unique_id();
    let panel_id = format!(
        "{}-panel",
        props
            .id
            .clone()
            .unwrap_or_else(|| format!("ui-site-header-{generated}"))
    );
    let sheet = props.collapse == SiteHeaderCollapse::Sheet;
    let mut open = use_signal(|| false);
    let mut enhanced = use_signal(|| false);
    let mut toggle_node = use_signal(|| None::<Rc<MountedData>>);
    let scrolled = use_scroll_past(Some(8.0));
    // The native popover owns the sheet's open state; this mirrors it once the script reports.
    let sheet_open = use_site_header_sheet(sheet.then_some(panel_id.as_str()));

    use_effect(move || enhanced.set(true));

    let enhanced = enhanced();
    // The panel disclosure state, which a sheet never uses.
    let is_open = !sheet && open();
    let sheet_open = sheet_open();
    let class = compose([
        Some("ui-site-header"),
        props.sticky.then_some("ui-site-header--sticky"),
        sheet.then_some("ui-site-header--sheet"),
        props.class.as_deref(),
    ]);
    let (state, expanded) = if sheet {
        (sheet_open.map(open_state), sheet_open.map(bool_attribute))
    } else {
        (
            enhanced.then_some(open_state(is_open)),
            Some(bool_attribute(is_open)),
        )
    };
    let brand = props.brand.filter(|slot| has_slot(Some(slot)));
    let actions = props.actions.filter(|slot| has_slot(Some(slot)));
    let menu_label = optional_text(Some(&props.menu_label)).unwrap_or_else(|| "Menu".to_string());
    let close_label =
        optional_text(Some(&props.close_label)).unwrap_or_else(|| "Close menu".to_string());
    let nav_label = optional_text(Some(&props.nav_label)).unwrap_or_else(|| "Main".to_string());
    let toggle_target = sheet.then(|| panel_id.clone());
    let close_target = panel_id.clone();

    rsx! {
        header {
            class,
            "data-collapse": sheet.then_some(props.collapse.as_str()),
            "data-collapsible": (!sheet && enhanced).then_some("true"),
            "data-scrolled": (scrolled() == Some(true)).then_some(""),
            "data-slot": "site-header",
            "data-state": state,
            "data-sticky": if props.sticky { "true" } else { "false" },
            "data-ui-owner": "dioxus",
            "data-ui-site-header": "true",
            id: props.id,
            ..props.attributes,
            div {
                class: "ui-site-header__inner",
                "data-slot": "site-header-inner",
                onkeydown: move |event| {
                    // The Popover API closes a sheet on Escape; only the panel needs this.
                    if !sheet && is_escape(&event) && open() {
                        event.prevent_default();
                        open.set(false);
                        focus_element(toggle_node());
                    }
                },
                if let Some(brand) = brand {
                    div { class: "ui-site-header__brand", "data-slot": "site-header-brand", {brand} }
                }
                // A sheet toggle stays visible and works through `popovertarget` before hydration,
                // and reports `aria-expanded` only once the script mirrors the popover.
                button {
                    aria_controls: panel_id.clone(),
                    aria_expanded: expanded,
                    class: "ui-site-header__toggle",
                    "data-slot": "site-header-toggle",
                    "data-ui-site-header-toggle": "true",
                    hidden: !sheet && !enhanced,
                    popovertarget: toggle_target,
                    r#type: "button",
                    onclick: move |_| {
                        if !sheet {
                            open.toggle();
                        }
                    },
                    onmounted: move |event| toggle_node.set(Some(event.data())),
                    span { aria_hidden: "true", class: "ui-site-header__toggle-icon" }
                    span { class: "ui-site-header__toggle-label", "{menu_label}" }
                }
                div {
                    class: "ui-site-header__panel",
                    "data-slot": "site-header-panel",
                    id: panel_id,
                    popover: sheet.then_some("auto"),
                    if sheet {
                        button {
                            class: "ui-site-header__close",
                            "data-slot": "site-header-close",
                            popovertarget: close_target,
                            popovertargetaction: "hide",
                            r#type: "button",
                            span { aria_hidden: "true", class: "ui-site-header__toggle-icon" }
                            span { class: "ui-site-header__toggle-label", "{close_label}" }
                        }
                    }
                    nav {
                        aria_label: nav_label,
                        class: "ui-site-header__nav",
                        "data-slot": "site-header-nav",
                        // Following a navigation link should leave the page with the menu closed.
                        onclick: move |_| {
                            if *open.peek() {
                                open.set(false);
                            }
                        },
                        {props.children}
                    }
                    if let Some(actions) = actions {
                        div { class: "ui-site-header__actions", "data-slot": "site-header-actions", {actions} }
                    }
                }
            }
        }
    }
}

/// How a [`Sidebar`] behaves on narrow viewports.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SidebarCollapse {
    /// The sidebar always stays in the page flow.
    #[default]
    None,
    /// The sidebar stays in the page flow from 48rem and becomes an off-canvas popover sheet
    /// below that width, opened by a [`SidebarTrigger`]. The sidebar needs an `id`.
    Sheet,
}

impl SidebarCollapse {
    /// The collapse name, like lumen-core's `LumenSidebarCollapse`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Sheet => "sheet",
        }
    }
}

/// Props for [`Sidebar`].
#[derive(Props, Clone, PartialEq)]
pub struct SidebarProps {
    /// Surface styling or hooks only.
    #[props(default)]
    pub variant: NavigationVariant,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Narrow-viewport behavior. `Sheet` requires an `id`, which [`SidebarTrigger`] targets.
    #[props(default)]
    pub collapse: SidebarCollapse,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<aside>` or global attribute. Set `id` when `collapse` is `Sheet`.
    #[props(extends = GlobalAttributes, extends = aside)]
    pub attributes: Vec<Attribute>,
    /// Navigation, usually a `nav` of [`SidebarItem`]s.
    pub children: Element,
}

/// The side panel of an application shell.
///
/// With `collapse: SidebarCollapse::Sheet` and an `id`, the sidebar is a native popover: it stays
/// in the page flow from 48rem and is hidden below that width until a [`SidebarTrigger`] opens it
/// as a drawer with a scrim. The browser's Popover API opens and closes it, closes it on Escape
/// and outside presses, and returns focus, without a script. Unlike lumen-react, the sheet does
/// not close itself after a link click inside it or when the viewport grows past 48rem. Dioxus
/// Native has no Popover API, so keep `collapse` at `None` there: below 48rem the sheet would stay
/// hidden.
#[component]
pub fn Sidebar(props: SidebarProps) -> Element {
    let sheet = props.collapse == SidebarCollapse::Sheet;
    let unstyled = props.variant.modifier("ui-sidebar");
    let glass = props.glass.class("ui-sidebar");
    let class = compose([
        Some("ui-sidebar"),
        sheet.then_some("ui-sidebar--sheet"),
        unstyled.as_deref(),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        aside {
            class,
            "data-collapse": sheet.then_some(props.collapse.as_str()),
            "data-slot": "sidebar",
            "data-surface": surface(props.glass),
            // lumen-react marks the sheet so Lumen's web runtime leaves it alone.
            "data-ui-owner": sheet.then_some("dioxus"),
            "data-ui-sidebar": sheet.then_some(""),
            "data-variant": props.variant.as_str(),
            popover: sheet.then_some("auto"),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`SidebarItem`].
#[derive(Props, Clone, PartialEq)]
pub struct SidebarItemProps {
    /// Visible link text.
    #[props(into)]
    pub label: String,
    /// Destination. Unsafe values (executable schemes, credentials) are dropped.
    #[props(into)]
    pub href: Option<String>,
    /// Secondary line under the label.
    #[props(into)]
    pub description: Option<String>,
    /// Leading icon, hidden from assistive technology because the label names the link.
    pub icon: Option<Element>,
    /// Trailing count or short status, read as "Label (badge)". Blank values render nothing.
    #[props(into)]
    pub badge: Option<String>,
    /// Marks the link as the current page.
    #[props(default)]
    pub current: bool,
    /// Renders the link without `href` and with `aria-disabled`, so it cannot navigate or take
    /// focus.
    #[props(default)]
    pub disabled: bool,
    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<a>` or global attribute.
    #[props(extends = GlobalAttributes, extends = a)]
    pub attributes: Vec<Attribute>,
}

/// A sidebar navigation link with an optional icon, a two-line label, and a trailing count.
#[component]
pub fn SidebarItem(props: SidebarItemProps) -> Element {
    let class = compose([Some("ui-sidebar-item"), props.class.as_deref()]);
    let href = if props.disabled {
        None
    } else {
        props.href.as_deref().and_then(resolve_safe_href)
    };
    let badge = props
        .badge
        .as_deref()
        .map(str::trim)
        .filter(|badge| !badge.is_empty())
        .map(str::to_string);
    let description = props
        .description
        .filter(|description| !description.trim().is_empty());
    let icon = props.icon.filter(|slot| has_slot(Some(slot)));
    let onclick = props.onclick;
    let disabled = props.disabled;

    rsx! {
        a {
            aria_current: props.current.then_some("page"),
            aria_disabled: disabled.then_some("true"),
            class,
            "data-slot": "sidebar-item",
            href,
            role: disabled.then_some("link"),
            onclick: move |event| {
                if disabled {
                    return;
                }

                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            ..props.attributes,
            if let Some(icon) = icon {
                span { aria_hidden: "true", class: "ui-sidebar-item__icon", "data-slot": "sidebar-item-icon", {icon} }
            }
            span { class: "ui-sidebar-item__text", "data-slot": "sidebar-item-text",
                span { class: "ui-sidebar-item__label", "data-slot": "sidebar-item-label", "{props.label}" }
                if let Some(description) = description {
                    span { class: "ui-sidebar-item__description", "data-slot": "sidebar-item-description", "{description}" }
                }
            }
            if let Some(badge) = badge {
                span { class: "ui-sidebar-item__badge", "data-slot": "sidebar-item-badge",
                    span { class: "ui-sr-only", " (" }
                    "{badge}"
                    span { class: "ui-sr-only", ")" }
                }
            }
        }
    }
}

/// What a [`SidebarTrigger`] does to its sheet.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SidebarTriggerAction {
    /// Opens the sheet, or closes it when it is open. For a trigger outside the sheet.
    #[default]
    Toggle,
    /// Closes the sheet. For a trigger inside it.
    Close,
}

impl SidebarTriggerAction {
    /// The `data-action` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Toggle => "toggle",
            Self::Close => "close",
        }
    }

    /// The `popovertargetaction` value, like `resolveLumenSidebarTriggerAction`.
    fn popover_target_action(self) -> &'static str {
        match self {
            Self::Toggle => "toggle",
            Self::Close => "hide",
        }
    }

    /// The default accessible name, like `resolveLumenSidebarTriggerLabel`.
    fn default_label(self) -> &'static str {
        match self {
            Self::Toggle => "Menu",
            Self::Close => "Close menu",
        }
    }
}

/// Props for [`SidebarTrigger`].
#[derive(Props, Clone, PartialEq)]
pub struct SidebarTriggerProps {
    /// The `id` of a [`Sidebar`] rendered with `collapse: SidebarCollapse::Sheet`.
    #[props(into)]
    pub target: String,
    /// `Toggle` opens and closes the sheet from outside it; `Close` hides it from inside.
    #[props(default)]
    pub action: SidebarTriggerAction,
    /// Accessible name of the default icon. Defaults to `Menu`, or `Close menu` for `Close`.
    /// Ignored when the trigger has children.
    #[props(into)]
    pub label: Option<String>,
    /// Disables the button.
    #[props(default)]
    pub disabled: bool,
    /// Click handler.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute. `target` and `action` already set
    /// `popovertarget` and `popovertargetaction`.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Visible content. It replaces the default icon and its visually hidden label.
    pub children: Element,
}

/// A ghost [`Button`](crate::Button) that opens or closes a [`Sidebar`] rendered with
/// `collapse: SidebarCollapse::Sheet`.
///
/// It is wired with `popovertarget`, so the browser's Popover API runs it without a script. It is
/// an icon button with a visually hidden label unless it has children, which render at the default
/// button size instead. Lumen's CSS hides the trigger from 48rem and in browsers without the
/// Popover API.
#[component]
pub fn SidebarTrigger(props: SidebarTriggerProps) -> Element {
    let action = props.action;
    let has_children = has_content(&props.children);
    let size = if has_children {
        ButtonSize::Default
    } else {
        ButtonSize::Icon
    };
    let class = compose([
        Some("ui-button"),
        Some("ui-button--ghost"),
        Some(size.class()),
        Some("ui-sidebar-trigger"),
        props.class.as_deref(),
    ]);
    let label =
        optional_text(props.label.as_deref()).unwrap_or_else(|| action.default_label().to_string());
    let controls = props.target.clone();
    let onclick = props.onclick;

    // Rendered directly rather than through `Button` so `data-slot` names the trigger, like
    // `DialogClose`.
    rsx! {
        button {
            aria_controls: controls,
            class,
            "data-action": action.as_str(),
            "data-slot": "sidebar-trigger",
            disabled: props.disabled,
            popovertarget: props.target,
            popovertargetaction: action.popover_target_action(),
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            ..props.attributes,
            span { class: "ui-button__content",
                if has_children {
                    {props.children}
                } else {
                    span { aria_hidden: "true", class: "ui-sidebar-trigger__icon" }
                    span { class: "ui-sr-only", "{label}" }
                }
            }
        }
    }
}

/// Props for [`ContextNavigation`].
#[derive(Props, Clone, PartialEq)]
pub struct ContextNavigationProps {
    /// A context switcher, such as a platform or version select, shown before the navigation.
    pub context: Option<Element>,
    /// Surface styling or hooks only.
    #[props(default)]
    pub variant: NavigationVariant,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The navigation for the selected context, usually a [`NavigationMenu`](crate::NavigationMenu).
    pub children: Element,
}

/// Navigation that changes with a context switcher, such as docs for one platform.
#[component]
pub fn ContextNavigation(props: ContextNavigationProps) -> Element {
    let unstyled = props.variant.modifier("ui-context-navigation");
    let class = compose([
        Some("ui-context-navigation"),
        unstyled.as_deref(),
        props.class.as_deref(),
    ]);
    let context = props.context.filter(|slot| has_slot(Some(slot)));

    rsx! {
        div {
            class,
            "data-slot": "context-navigation",
            "data-variant": props.variant.as_str(),
            ..props.attributes,
            if let Some(context) = context {
                div {
                    class: "ui-context-navigation__context",
                    "data-slot": "context-navigation-context",
                    {context}
                }
            }
            {props.children}
        }
    }
}