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

use dioxus::prelude::*;
use freya_elements::{
    elements as dioxus_elements,
    events::{
        keyboard::Key,
        KeyboardEvent,
        MouseEvent,
    },
};
use freya_hooks::{
    theme_with,
    use_applied_theme,
    use_focus,
    use_platform,
    DropdownItemThemeWith,
    DropdownTheme,
    DropdownThemeWith,
    IconThemeWith,
};
use winit::window::CursorIcon;

use crate::icons::ArrowIcon;

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

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

/// # Styling
/// Inherits the [`DropdownItemTheme`](freya_hooks::DropdownItemTheme) theme.
#[allow(non_snake_case)]
pub fn DropdownItem<T>(
    DropdownItemProps {
        theme,
        children,
        value,
        onclick,
    }: DropdownItemProps<T>,
) -> Element
where
    T: Clone + PartialEq + 'static,
{
    let selected = use_context::<Signal<T>>();
    let theme = use_applied_theme!(&theme, dropdown_item);
    let focus = use_focus();
    let mut status = use_signal(DropdownItemStatus::default);
    let platform = use_platform();

    let a11y_id = focus.attribute();
    let is_focused = focus.is_focused();
    let is_selected = *selected.read() == value;

    let background = match *status.read() {
        _ 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_drop(move || {
        if *status.peek() == DropdownItemStatus::Hovering {
            platform.set_cursor(CursorIcon::default());
        }
    });

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

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

    let onglobalkeydown = {
        to_owned![onclick];
        move |ev: KeyboardEvent| {
            if ev.key == Key::Enter && is_focused {
                if let Some(onclick) = &onclick {
                    onclick.call(())
                }
            }
        }
    };

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

    rsx!(
        rect {
            width: "fill-min",
            color: "{color}",
            a11y_id,
            a11y_role:"button",
            background: "{background}",
            padding: "6 22 6 16",
            corner_radius: "6",
            main_align: "center",
            onmouseenter,
            onmouseleave,
            onclick,
            onglobalkeydown,
            {children}
        }
    )
}

/// Properties for the [`Dropdown`] component.
#[derive(Props, Clone, PartialEq)]
pub struct DropdownProps<T: 'static + Clone + PartialEq> {
    /// Theme override.
    pub theme: Option<DropdownThemeWith>,
    /// Selectable items, like [`DropdownItem`]
    pub children: Element,
    /// 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,
}

/// Select from multiple options, use alongside [`DropdownItem`].
///
/// # Styling
/// Inherits the [`DropdownTheme`](freya_hooks::DropdownTheme) theme.
///
/// # Example
/// ```no_run
/// # use freya::prelude::*;
///
/// fn app() -> Element {
///     let values = use_hook(|| vec!["A".to_string(), "B".to_string(), "C".to_string()]);
///     let mut selected_dropdown = use_signal(|| "A".to_string());
///     rsx!(
///         Dropdown {
///             value: selected_dropdown.read().clone(),
///             for ch in values {
///                 DropdownItem {
///                     value: ch.to_string(),
///                     onclick: {
///                         to_owned![ch];
///                         move |_| selected_dropdown.set(ch.clone())
///                     },
///                     label { "{ch}" }
///                 }
///             }
///         }
///     )
/// }
/// ```
#[allow(non_snake_case)]
pub fn Dropdown<T>(props: DropdownProps<T>) -> Element
where
    T: PartialEq + Clone + Display + 'static,
{
    let mut selected = use_context_provider(|| Signal::new(props.value.clone()));
    let theme = use_applied_theme!(&props.theme, dropdown);
    let mut focus = use_focus();
    let mut status = use_signal(DropdownStatus::default);
    let mut opened = use_signal(|| false);
    let platform = use_platform();

    let is_opened = *opened.read();
    let is_focused = focus.is_focused();
    let a11y_id = focus.attribute();

    // Update the provided value if the passed value changes
    use_effect(use_reactive(&props.value, move |value| {
        *selected.write() = value;
    }));

    use_drop(move || {
        if *status.peek() == 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 onglobalkeydown = 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 = move |_| {
        platform.set_cursor(CursorIcon::Pointer);
        status.set(DropdownStatus::Hovering);
    };

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

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

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

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

    rsx!(
        rect {
            direction: "vertical",
            rect {
                width: "{width}",
                onmouseenter,
                onmouseleave,
                onclick,
                onglobalkeydown,
                margin: "{margin}",
                a11y_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 {
                    "{selected}"
                }
                ArrowIcon {
                    rotate: "0",
                    fill: "{arrow_fill}",
                    theme: theme_with!(IconTheme {
                        margin : "0 0 0 8".into(),
                    })
                }
            }
            if *opened.read() {
                rect {
                    height: "0",
                    width: "0",
                    rect {
                        width: "100v",
                        rect {
                            onglobalclick,
                            onglobalkeydown,
                            layer: "-99",
                            margin: "{margin}",
                            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",
                            content: "fit",
                            {props.children}
                        }
                    }
                }
            }
        }
    )
}

#[cfg(test)]
mod test {
    use freya::prelude::*;
    use freya_testing::prelude::*;

    #[tokio::test]
    pub async fn dropdown() {
        fn dropdown_app() -> Element {
            let values = use_hook(|| {
                vec![
                    "Value A".to_string(),
                    "Value B".to_string(),
                    "Value C".to_string(),
                ]
            });
            let mut selected_dropdown = use_signal(|| "Value A".to_string());

            rsx!(
                Dropdown {
                    value: selected_dropdown.read().clone(),
                    for ch in values {
                        DropdownItem {
                            value: ch.clone(),
                            onclick: {
                                to_owned![ch];
                                move |_| selected_dropdown.set(ch.clone())
                            },
                            label { "{ch}" }
                        }
                    }
                }
            )
        }

        let mut utils = launch_test(dropdown_app);
        let root = utils.root();
        let label = root.get(0).get(0).get(0);
        utils.wait_for_update().await;

        // Currently closed
        let start_size = utils.sdom().get().layout().size();

        // Default value
        assert_eq!(label.get(0).text(), Some("Value A"));

        // Open the dropdown
        utils.click_cursor((15., 15.)).await;
        utils.wait_for_update().await;

        // Now that the dropwdown is opened, there are more nodes in the layout
        assert!(utils.sdom().get().layout().size() > start_size);

        // Close the dropdown by clicking outside of it
        utils.click_cursor((200., 200.)).await;

        // Now the layout size is like in the begining
        assert_eq!(utils.sdom().get().layout().size(), start_size);

        // Open the dropdown again
        utils.click_cursor((15., 15.)).await;

        // Click on the second option
        utils.click_cursor((45., 100.)).await;
        utils.wait_for_update().await;
        utils.wait_for_update().await;

        // Now the layout size is like in the begining, again
        assert_eq!(utils.sdom().get().layout().size(), start_size);

        // The second optio was selected
        assert_eq!(label.get(0).text(), Some("Value B"));
    }
}