material_dioxus/
button.rs

1use std::marker::PhantomData;
2
3use dioxus::prelude::*;
4use gloo::events::EventListener;
5use wasm_bindgen::prelude::*;
6
7use crate::StaticCallback;
8
9#[wasm_bindgen(module = "/build/mwc-button.js")]
10extern "C" {
11    #[derive(Debug)]
12    type Button;
13
14    // This needs to be added to each component
15    #[wasm_bindgen(getter, static_method_of = Button)]
16    fn _dummy_loader() -> JsValue;
17}
18
19// call the macro with the type
20loader_hack!(Button);
21
22/// Props for [`MatButton`]
23///
24/// [MWC Documentation for properties](https://github.com/material-components/material-components-web-components/tree/v0.27.0/packages/button#propertiesattributes)
25#[derive(Props)]
26pub struct ButtonProps<'a> {
27    #[props(into)]
28    pub label: String,
29    #[props(into)]
30    pub icon: Option<String>,
31    // TODO: variant enum
32    #[props(default)]
33    pub raised: bool,
34    #[props(default)]
35    pub unelevated: bool,
36    #[props(default)]
37    pub outlined: bool,
38    #[props(default)]
39    pub dense: bool,
40    #[props(default)]
41    pub disabled: bool,
42    #[props(default)]
43    pub trailing_icon: bool,
44
45    #[props(into)]
46    // the name cannot start with `on` or dioxus will expect an `EventHandler` which aren't static
47    // and thus cannot be used here
48    pub _onclick: Option<StaticCallback<()>>,
49    _lifetime: Option<PhantomData<&'a ()>>,
50
51    #[props(into, default)]
52    pub style: String,
53    #[props(into, default)]
54    pub class: String,
55    #[props(into)]
56    pub slot: Option<String>,
57    #[props(default)]
58    pub dialog_initial_focus: bool,
59}
60
61fn render<'a>(cx: Scope<'a, ButtonProps<'a>>) -> Element<'a> {
62    let id = crate::use_id(cx, "button");
63    let click_listener = cx.use_hook(|| None);
64    if let Some(elem) = crate::get_elem_by_id(id) {
65        let target = elem;
66        if let Some(listener) = cx.props._onclick.clone() {
67            *click_listener = Some(EventListener::new(&target, "click", move |_| {
68                listener.call(())
69            }));
70        }
71    }
72
73    render! {
74        mwc-button {
75            id: id,
76
77            icon: optional_string_attr!(cx.props.icon),
78            label: string_attr!(cx.props.label),
79            disabled: bool_attr!(cx.props.disabled),
80            raised: bool_attr!(cx.props.raised),
81            unelevated: bool_attr!(cx.props.unelevated),
82            outlined: bool_attr!(cx.props.outlined),
83            dense: bool_attr!(cx.props.dense),
84            trailingIcon: bool_attr!(cx.props.trailing_icon),
85
86            style: string_attr!(cx.props.style),
87            class: string_attr!(cx.props.class),
88            slot: optional_string_attr!(cx.props.slot),
89            dialogInitialFocus: bool_attr!(cx.props.dialog_initial_focus),
90        }
91    }
92}
93
94component!('a, MatButton, ButtonProps, render, Button, "button");