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
use std::fmt::Display;

use crate::icons::ArrowIcon;
use dioxus::prelude::*;
use freya_elements::elements as dioxus_elements;
use freya_elements::events::keyboard::Key;
use freya_elements::events::{KeyboardEvent, MouseEvent};

use freya_hooks::{
    theme_with, use_applied_theme, use_focus, use_platform, ArrowIconThemeWith,
    DropdownItemThemeWith, DropdownTheme, DropdownThemeWith,
};
use winit::window::CursorIcon;

/// [`DropdownItem`] component properties.
#[derive(Props)]
pub struct DropdownItemProps<'a, T: 'static> {
    /// Theme override.
    pub theme: Option<DropdownItemThemeWith>,
    /// Selectable items, like [`DropdownItem`]
    pub children: Element<'a>,
    /// Selected value.
    pub value: T,
    /// Handler for the `onclick` event.
    #[props(optional)]
    pub onclick: Option<EventHandler<'a, ()>>,
}

/// Current status of the DropdownItem.
#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub enum DropdownItemStatus {
    /// Default state.
    #[default]
    Idle,
    /// Dropdown item is being hovered.
    Hovering,
}

/// `DropdownItem` component.
///
/// # Props
/// See [`DropdownItemProps`].
///
/// # Styling
/// Inherits the [`DropdownItemTheme`](freya_hooks::DropdownItemTheme) theme.
#[allow(non_snake_case)]
pub fn DropdownItem<'a, T>(cx: Scope<'a, DropdownItemProps<'a, T>>) -> Element<'a>
where
    T: PartialEq + 'static,
{
    let selected = use_shared_state::<T>(cx).unwrap();
    let theme = use_applied_theme!(cx, &cx.props.theme, dropdown_item);
    let focus = use_focus(cx);
    let status = use_state(cx, DropdownItemStatus::default);
    let platform = use_platform(cx);

    let focus_id = focus.attribute(cx);
    let is_focused = focus.is_focused();
    let is_selected = *selected.read() == cx.props.value;

    let background = match *status.get() {
        _ if is_selected => theme.select_background,
        _ if is_focused => theme.hover_background,
        DropdownItemStatus::Hovering => theme.hover_background,
        DropdownItemStatus::Idle => theme.background,
    };
    let color = theme.font_theme.color;

    use_on_destroy(cx, {
        to_owned![status, platform];
        move || {
            if *status.current() == DropdownItemStatus::Hovering {
                platform.set_cursor(CursorIcon::default());
            }
        }
    });

    let onclick = move |_: MouseEvent| {
        if let Some(onclick) = &cx.props.onclick {
            onclick.call(())
        }
    };

    let onmouseenter = {
        to_owned![platform];
        move |_| {
            platform.set_cursor(CursorIcon::Pointer);
            status.set(DropdownItemStatus::Hovering);
        }
    };

    let onmouseleave = move |_| {
        platform.set_cursor(CursorIcon::default());
        status.set(DropdownItemStatus::default());
    };

    let onkeydown = move |ev: KeyboardEvent| {
        if ev.key == Key::Enter && is_focused {
            if let Some(onclick) = &cx.props.onclick {
                onclick.call(())
            }
        }
    };

    render!(
        rect {
            color: "{color}",
            focus_id: focus_id,
            role: "button",
            background: "{background}",
            padding: "6 22 6 16",
            corner_radius: "6",
            main_align: "center",
            cross_align: "center",
            onmouseenter: onmouseenter,
            onmouseleave: onmouseleave,
            onclick: onclick,
            onkeydown: onkeydown,
            &cx.props.children
        }
    )
}

/// [`Dropdown`] component properties.
#[derive(Props)]
pub struct DropdownProps<'a, T: 'static> {
    /// Theme override.
    pub theme: Option<DropdownThemeWith>,
    /// Selectable items, like [`DropdownItem`]
    pub children: Element<'a>,
    /// Selected value.
    pub value: T,
}

/// Current status of the Dropdown.
#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub enum DropdownStatus {
    /// Default state.
    #[default]
    Idle,
    /// Dropdown is being hovered.
    Hovering,
}

/// `Dropdown` component.
///
/// # Props
/// See [`DropdownProps`].
///
/// # Styling
/// Inherits the [`DropdownTheme`](freya_hooks::DropdownTheme) theme.
///
/// # Example
/// ```no_run
/// # use freya::prelude::*;
///
/// fn app(cx: Scope) -> Element {
///     let values = cx.use_hook(|| vec!["A".to_string(), "B".to_string(), "C".to_string()]);
///     let selected_dropdown = use_state(cx, || "A".to_string());
///     render!(
///         Dropdown {
///             value: selected_dropdown.get().clone(),
///             values.iter().map(|ch| {
///                 rsx!(
///                     DropdownItem {
///                         value: ch.to_string(),
///                         onclick: move |_| selected_dropdown.set(ch.to_string()),
///                         label { "{ch}" }
///                     }
///                 )
///             })
///         }
///     )
/// }
/// ```
#[allow(non_snake_case)]
pub fn Dropdown<'a, T>(cx: Scope<'a, DropdownProps<'a, T>>) -> Element<'a>
where
    T: PartialEq + Clone + Display + 'static,
{
    use_shared_state_provider(cx, || cx.props.value.clone());
    let selected = use_shared_state::<T>(cx).unwrap();
    let theme = use_applied_theme!(cx, &cx.props.theme, dropdown);
    let focus = use_focus(cx);
    let status = use_state(cx, DropdownStatus::default);
    let opened = use_state(cx, || false);
    let platform = use_platform(cx);

    let is_opened = *opened.get();
    let is_focused = focus.is_focused();
    let focus_id = focus.attribute(cx);

    // Update the provided value if the passed value changes
    let _ = use_memo(cx, &cx.props.value, move |value| {
        *selected.write() = value;
    });

    use_on_destroy(cx, {
        to_owned![status, platform];
        move || {
            if *status.current() == DropdownStatus::Hovering {
                platform.set_cursor(CursorIcon::default());
            }
        }
    });

    // Close the dropdown if clicked anywhere
    let onglobalclick = move |_: MouseEvent| {
        opened.set(false);
    };

    let onclick = move |_| {
        focus.focus();
        opened.set(true)
    };

    let onkeydown = move |e: KeyboardEvent| {
        match e.key {
            // Close when `Escape` key is pressed
            Key::Escape => {
                opened.set(false);
            }
            // Open the dropdown items when the `Enter` key is pressed
            Key::Enter if is_focused && !is_opened => {
                opened.set(true);
            }
            _ => {}
        }
    };

    let onmouseenter = {
        to_owned![status, platform];
        move |_| {
            platform.set_cursor(CursorIcon::Pointer);
            status.set(DropdownStatus::Hovering);
        }
    };

    let onmouseleave = move |_| {
        platform.set_cursor(CursorIcon::default());
        status.set(DropdownStatus::default());
    };

    let DropdownTheme {
        font_theme,
        dropdown_background,
        background_button,
        hover_background,
        border_fill,
        arrow_fill,
    } = &theme;

    let button_background = match *status.get() {
        DropdownStatus::Hovering => hover_background,
        DropdownStatus::Idle => background_button,
    };

    let selected = selected.read().to_string();

    render!(
        rect {
            onmouseenter: onmouseenter,
            onmouseleave: onmouseleave,
            onclick: onclick,
            onkeydown: onkeydown,
            margin: "4",
            focus_id: focus_id,
            background: "{button_background}",
            color: "{font_theme.color}",
            corner_radius: "8",
            padding: "8 16",
            border: "1 solid {border_fill}",
            shadow: "0 4 5 0 rgb(0, 0, 0, 0.1)",
            direction: "horizontal",
            main_align: "center",
            cross_align: "center",
            label {
                text_align: "center",
                "{selected}"
            }
            ArrowIcon {
                rotate: "0",
                fill: "{arrow_fill}",
                theme: theme_with!(ArrowIconTheme {
                    margin : "0 0 0 8".into(),
                })
            }
        }
        if *opened.get() {
            rsx!(
                rect {
                    height: "0",
                    rect {
                        onglobalclick: onglobalclick,
                        onkeydown: onkeydown,
                        layer: "-99",
                        margin: "4",
                        border: "1 solid {border_fill}",
                        overflow: "clip",
                        corner_radius: "8",
                        background: "{dropdown_background}",
                        shadow: "0 4 5 0 rgb(0, 0, 0, 0.3)",
                        padding: "6",
                        &cx.props.children
                    }
                }
            )
        }
    )
}