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
use dioxus::prelude::*;
use freya_elements::{
    elements as dioxus_elements,
    events::KeyboardEvent,
};
use freya_hooks::{
    theme_with,
    use_applied_theme,
    ButtonThemeWith,
    PopupTheme,
    PopupThemeWith,
};

use crate::{
    Button,
    CrossIcon,
};

/// The background of the [`Popup`] component.
#[allow(non_snake_case)]
#[component]
pub fn PopupBackground(children: Element) -> Element {
    rsx!(rect {
        height: "100v",
        width: "100v",
        background: "rgb(0, 0, 0, 150)",
        position: "absolute",
        position_top: "0",
        position_left: "0",
        layer: "-99",
        main_align: "center",
        cross_align: "center",
        {children}
    })
}

/// Floating window intended for quick interactions. Also called `Dialog` in other frameworks.
///
/// # Styling
/// Inherits the [`PopupTheme`](freya_hooks::PopupTheme) theme.
/// ```rust, no_run
/// # use freya::prelude::*;
/// fn app() -> Element {
///     let mut show_popup = use_signal(|| false);
///
///     rsx!(
///         if *show_popup.read() {
///              Popup {
///                  oncloserequest: move |_| {
///                      show_popup.set(false)
///                  },
///                  PopupTitle {
///                      label {
///                          "Awesome Popup"
///                      }
///                  }
///                  PopupContent {
///                      label {
///                          "Some content"
///                      }
///                  }
///              }
///          }
///          Button {
///              onpress: move |_| show_popup.set(true),
///              label {
///                  "Open"
///              }
///          }
///     )
/// }
/// ```
#[allow(non_snake_case)]
#[component]
pub fn Popup(
    /// Theme override.
    theme: Option<PopupThemeWith>,
    /// Popup inner content.
    children: Element,
    /// Optional close request handler.
    oncloserequest: Option<EventHandler>,
    /// Whether to show or no the cross button in the top right corner.
    #[props(default = true)]
    show_close_button: bool,
    /// Whether to trigger close request handler when the Escape key is pressed.
    #[props(default = true)]
    close_on_escape_key: bool,
) -> Element {
    let PopupTheme {
        background,
        color,
        cross_fill,
        width,
        height,
    } = use_applied_theme!(&theme, popup);

    let request_to_close = move || {
        if let Some(oncloserequest) = &oncloserequest {
            oncloserequest.call(());
        }
    };

    let onkeydown = move |event: KeyboardEvent| {
        if close_on_escape_key && event.key == Key::Escape {
            request_to_close()
        }
    };

    let onpress = move |_| request_to_close();

    rsx!(
        PopupBackground {
            rect {
                padding: "14",
                corner_radius: "8",
                background: "{background}",
                color: "{color}",
                shadow: "0 4 5 0 rgb(0, 0, 0, 30)",
                width: "{width}",
                height: "{height}",
                onkeydown,
                if show_close_button {
                    rect {
                        height: "0",
                        width: "fill",
                        cross_align: "end",
                        Button {
                            theme: theme_with!(ButtonTheme {
                                padding: "6".into(),
                                margin: "0".into(),
                                width: "30".into(),
                                height: "30".into(),
                                corner_radius: "999".into(),
                                shadow: "none".into()
                            }),
                            onpress,
                            CrossIcon {
                                fill: cross_fill
                             }
                        }
                    }
                }
                {children}
            }
        }
    )
}

/// Optionally use a styled title inside a [`Popup`].
#[allow(non_snake_case)]
#[component]
pub fn PopupTitle(children: Element) -> Element {
    rsx!(
        rect {
            font_size: "18",
            margin: "4 2 8 2",
            font_weight: "bold",
            {children}
        }
    )
}

/// Optionally wrap the content of your [`Popup`] in a styled container.
#[allow(non_snake_case)]
#[component]
pub fn PopupContent(children: Element) -> Element {
    rsx!(
        rect {
            font_size: "15",
            margin: "6 2",
            {children}
        }
    )
}

#[cfg(test)]
mod test {
    use dioxus::prelude::use_signal;
    use freya::prelude::*;
    use freya_elements::events::keyboard::{
        Code,
        Key,
        Modifiers,
    };
    use freya_testing::prelude::*;

    #[tokio::test]
    pub async fn popup() {
        fn popup_app() -> Element {
            let mut show_popup = use_signal(|| false);

            rsx!(
                if *show_popup.read() {
                    Popup {
                        oncloserequest: move |_| {
                            show_popup.set(false)
                        },
                        label {
                            "Hello, World!"
                        }
                    }
                }
                Button {
                    onpress: move |_| show_popup.set(true),
                    label {
                        "Open"
                    }
                }
            )
        }

        let mut utils = launch_test(popup_app);
        utils.wait_for_update().await;

        // Check the popup is closed
        assert_eq!(utils.sdom().get().layout().size(), 4);

        // Open the popup
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::Click,
            cursor: (15.0, 15.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;

        // Check the popup is opened
        assert_eq!(utils.sdom().get().layout().size(), 10);

        utils.push_event(PlatformEvent::Mouse {
            name: EventName::Click,
            cursor: (395.0, 180.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;

        // Check the popup is closed
        assert_eq!(utils.sdom().get().layout().size(), 4);

        // Open the popup
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::Click,
            cursor: (15.0, 15.0).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;

        // Send a random keydown event
        utils.push_event(PlatformEvent::Keyboard {
            name: EventName::KeyDown,
            key: Key::ArrowDown,
            code: Code::ArrowDown,
            modifiers: Modifiers::empty(),
        });
        utils.wait_for_update().await;
        // Check the popup is still open
        assert_eq!(utils.sdom().get().layout().size(), 10);

        // Send a ESC keydown event
        utils.push_event(PlatformEvent::Keyboard {
            name: EventName::KeyDown,
            key: Key::Escape,
            code: Code::Escape,
            modifiers: Modifiers::empty(),
        });
        utils.wait_for_update().await;
        // Check the popup is closed
        assert_eq!(utils.sdom().get().layout().size(), 4);
    }
}