Skip to main content

lumen_dioxus/
button.rs

1//! `Button`.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6
7/// Visual treatment of a [`Button`].
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ButtonVariant {
11    /// Solid brand button for the primary action.
12    #[default]
13    Default,
14    /// Quiet filled button.
15    Secondary,
16    /// Bordered button.
17    Outline,
18    /// Button without a border or fill.
19    Ghost,
20    /// Destructive action.
21    Destructive,
22    /// Text link styled as a button.
23    Link,
24}
25
26impl ButtonVariant {
27    /// The class suffix and `data-variant` value.
28    pub fn as_str(self) -> &'static str {
29        match self {
30            Self::Default => "default",
31            Self::Secondary => "secondary",
32            Self::Outline => "outline",
33            Self::Ghost => "ghost",
34            Self::Destructive => "destructive",
35            Self::Link => "link",
36        }
37    }
38}
39
40/// Semantic color, independent of button prominence.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum ButtonTone {
44    /// A destructive action.
45    Danger,
46    /// A positive action.
47    Success,
48}
49
50impl ButtonTone {
51    fn class(self) -> &'static str {
52        match self {
53            Self::Danger => "ui-button--tone-danger",
54            Self::Success => "ui-button--tone-success",
55        }
56    }
57}
58
59/// Size of a [`Button`].
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum ButtonSize {
63    /// Default control height.
64    #[default]
65    Default,
66    /// Compact control.
67    Sm,
68    /// Large control.
69    Lg,
70    /// Square icon-only control. Give it an `aria_label`.
71    Icon,
72}
73
74impl ButtonSize {
75    /// The size modifier class, such as `ui-button--sm`.
76    pub(crate) fn class(self) -> &'static str {
77        match self {
78            Self::Default => "ui-button--default-size",
79            Self::Sm => "ui-button--sm",
80            Self::Lg => "ui-button--lg",
81            Self::Icon => "ui-button--icon",
82        }
83    }
84}
85
86/// Props for [`Button`].
87#[derive(Props, Clone, PartialEq)]
88pub struct ButtonProps {
89    /// Visual treatment.
90    #[props(default)]
91    pub variant: ButtonVariant,
92    /// Optional semantic color. Omit to preserve the variant color.
93    pub tone: Option<ButtonTone>,
94    /// Control size.
95    #[props(default)]
96    pub size: ButtonSize,
97    /// Disables the button.
98    #[props(default)]
99    pub disabled: bool,
100    /// Shows a spinner and sets `aria-busy` and `aria-disabled`. The button stays focusable, so
101    /// keyboard focus survives the request, and ignores clicks until loading ends.
102    #[props(default)]
103    pub loading: bool,
104    /// The native button type. Defaults to `button`, so it never submits a form by accident.
105    #[props(default = "button".to_string(), into)]
106    pub r#type: String,
107    /// Extra classes appended after the Lumen classes.
108    #[props(into)]
109    pub class: Option<String>,
110    /// Click handler.
111    pub onclick: Option<EventHandler<MouseEvent>>,
112    /// Any other `<button>` or global attribute.
113    #[props(extends = GlobalAttributes, extends = button)]
114    pub attributes: Vec<Attribute>,
115    /// Button label and icons.
116    pub children: Element,
117}
118
119/// A button with Lumen's variants, sizes, and loading state.
120///
121/// Renders the same markup as `Button` in `@santi020k/lumen-react`.
122#[component]
123pub fn Button(props: ButtonProps) -> Element {
124    let loading = props.loading;
125    let variant = format!("ui-button--{}", props.variant.as_str());
126    let class = compose([
127        Some("ui-button"),
128        props.tone.map(ButtonTone::class),
129        Some(variant.as_str()),
130        Some(props.size.class()),
131        loading.then_some("ui-button--loading"),
132        props.class.as_deref(),
133    ]);
134    let onclick = props.onclick;
135
136    // Loading uses `aria-disabled` rather than the native attribute, which would drop keyboard
137    // focus mid-request. Canceling the click also cancels a submit button's form submission.
138    rsx! {
139        button {
140            aria_busy: loading.then_some("true"),
141            aria_disabled: loading.then_some("true"),
142            class,
143            "data-slot": "button",
144            disabled: props.disabled,
145            r#type: props.r#type,
146            onclick: move |event| {
147                if loading {
148                    event.prevent_default();
149                    event.stop_propagation();
150                } else if let Some(handler) = onclick {
151                    handler.call(event);
152                }
153            },
154            ..props.attributes,
155            if loading {
156                span { aria_hidden: "true", class: "ui-spinner" }
157            }
158            span { class: "ui-button__content", {props.children} }
159        }
160    }
161}