freya_components/
select.rs

1use freya_animation::prelude::*;
2use freya_core::prelude::*;
3use torin::prelude::*;
4
5use crate::{
6    get_theme,
7    icons::arrow::ArrowIcon,
8    menu::MenuGroup,
9    theming::component_themes::SelectThemePartial,
10};
11
12#[derive(Debug, Default, PartialEq, Clone, Copy)]
13pub enum SelectStatus {
14    #[default]
15    Idle,
16    Hovering,
17}
18
19/// Select between different items component.
20///
21/// # Example
22///
23/// ```rust
24/// # use freya::prelude::*;
25/// fn app() -> impl IntoElement {
26///     let values = use_hook(|| {
27///         vec![
28///             "Rust".to_string(),
29///             "Turbofish".to_string(),
30///             "Crabs".to_string(),
31///         ]
32///     });
33///     let mut selected_select = use_state(|| 0);
34///
35///     Select::new()
36///         .selected_item(values[selected_select()].to_string())
37///         .children_iter(values.iter().enumerate().map(|(i, val)| {
38///             MenuItem::new()
39///                 .selected(selected_select() == i)
40///                 .on_press(move |_| selected_select.set(i))
41///                 .child(val.to_string())
42///                 .into()
43///         }))
44/// }
45///
46/// # use freya_testing::prelude::*;
47/// # use std::time::Duration;
48/// # launch_doc(|| {
49/// #   rect().center().expanded().child(app())
50/// # }, "./images/gallery_select.png").with_hook(|t| { t.move_cursor((125., 125.)); t.click_cursor((125., 125.)); t.poll(Duration::from_millis(1), Duration::from_millis(350)); }).with_scale_factor(1.).render();
51/// ```
52///
53/// # Preview
54/// ![Select Preview][select]
55#[cfg_attr(feature = "docs",
56    doc = embed_doc_image::embed_image!("select", "images/gallery_select.png")
57)]
58#[derive(Clone, PartialEq)]
59pub struct Select {
60    pub(crate) theme: Option<SelectThemePartial>,
61    pub selected_item: Option<Element>,
62    pub children: Vec<Element>,
63    pub key: DiffKey,
64}
65
66impl ChildrenExt for Select {
67    fn get_children(&mut self) -> &mut Vec<Element> {
68        &mut self.children
69    }
70}
71
72impl Default for Select {
73    fn default() -> Self {
74        Self::new()
75    }
76}
77
78impl Select {
79    pub fn new() -> Self {
80        Self {
81            theme: None,
82            selected_item: None,
83            children: Vec::new(),
84            key: DiffKey::None,
85        }
86    }
87
88    pub fn theme(mut self, theme: SelectThemePartial) -> Self {
89        self.theme = Some(theme);
90        self
91    }
92
93    pub fn selected_item(mut self, item: impl Into<Element>) -> Self {
94        self.selected_item = Some(item.into());
95        self
96    }
97
98    pub fn key(mut self, key: impl Into<DiffKey>) -> Self {
99        self.key = key.into();
100        self
101    }
102}
103
104impl Component for Select {
105    fn render(&self) -> impl IntoElement {
106        let theme = get_theme!(&self.theme, select);
107        let focus = use_focus();
108        let focus_status = use_focus_status(focus);
109        let mut status = use_state(SelectStatus::default);
110        let mut open = use_state(|| false);
111        use_provide_context(|| MenuGroup {
112            group_id: focus.a11y_id(),
113        });
114
115        let animation = use_animation(move |conf| {
116            conf.on_change(OnChange::Rerun);
117            conf.on_creation(OnCreation::Finish);
118
119            let scale = AnimNum::new(0.8, 1.)
120                .time(350)
121                .ease(Ease::Out)
122                .function(Function::Expo);
123            let opacity = AnimNum::new(0., 1.)
124                .time(350)
125                .ease(Ease::Out)
126                .function(Function::Expo);
127            if open() {
128                (scale, opacity)
129            } else {
130                (scale.into_reversed(), opacity.into_reversed())
131            }
132        });
133
134        use_drop(move || {
135            if status() == SelectStatus::Hovering {
136                Cursor::set(CursorIcon::default());
137            }
138        });
139
140        // Close the select when the focused accessibility node changes and its not the select or any of its children
141        use_side_effect(move || {
142            if let Some(member_of) = Platform::get()
143                .focused_accessibility_node
144                .read()
145                .member_of()
146            {
147                if member_of != focus.a11y_id() {
148                    open.set_if_modified(false);
149                }
150            } else {
151                open.set_if_modified(false);
152            }
153        });
154
155        let on_press = move |e: Event<PressEventData>| {
156            focus.request_focus();
157            open.toggle();
158            // Prevent global mouse up
159            e.prevent_default();
160            e.stop_propagation();
161        };
162
163        let on_pointer_enter = move |_| {
164            *status.write() = SelectStatus::Hovering;
165            Cursor::set(CursorIcon::Pointer);
166        };
167
168        let on_pointer_leave = move |_| {
169            *status.write() = SelectStatus::Idle;
170            Cursor::set(CursorIcon::default());
171        };
172
173        // Close the select if clicked anywhere
174        let on_global_mouse_up = move |_| {
175            open.set_if_modified(false);
176        };
177
178        let on_global_key_down = move |e: Event<KeyboardEventData>| match e.key {
179            Key::Named(NamedKey::Escape) => {
180                open.set_if_modified(false);
181            }
182            Key::Named(NamedKey::Enter) if focus.is_focused() => {
183                open.toggle();
184            }
185            _ => {}
186        };
187
188        let (scale, opacity) = animation.read().value();
189
190        let background = match *status.read() {
191            SelectStatus::Hovering => theme.hover_background,
192            SelectStatus::Idle => theme.background_button,
193        };
194
195        let border = if focus_status() == FocusStatus::Keyboard {
196            Border::new()
197                .fill(theme.focus_border_fill)
198                .width(2.)
199                .alignment(BorderAlignment::Inner)
200        } else {
201            Border::new()
202                .fill(theme.border_fill)
203                .width(1.)
204                .alignment(BorderAlignment::Inner)
205        };
206
207        rect()
208            .child(
209                rect()
210                    .a11y_id(focus.a11y_id())
211                    .a11y_member_of(focus.a11y_id())
212                    .a11y_role(AccessibilityRole::ListBox)
213                    .a11y_focusable(Focusable::Enabled)
214                    .on_pointer_enter(on_pointer_enter)
215                    .on_pointer_leave(on_pointer_leave)
216                    .on_press(on_press)
217                    .on_global_key_down(on_global_key_down)
218                    .on_global_mouse_up(on_global_mouse_up)
219                    .width(theme.width)
220                    .margin(theme.margin)
221                    .background(background)
222                    .padding((6., 16., 6., 16.))
223                    .border(border)
224                    .horizontal()
225                    .center()
226                    .color(theme.color)
227                    .corner_radius(8.)
228                    .maybe_child(self.selected_item.clone())
229                    .child(
230                        ArrowIcon::new()
231                            .margin((0., 0., 0., 8.))
232                            .rotate(0.)
233                            .fill(theme.arrow_fill),
234                    ),
235            )
236            .maybe_child((open() || opacity > 0.).then(|| {
237                rect().height(Size::px(0.)).width(Size::px(0.)).child(
238                    rect()
239                        .width(Size::window_percent(100.))
240                        .margin(Gaps::new(4., 0., 0., 0.))
241                        .child(
242                            rect()
243                                .layer(Layer::Overlay)
244                                .border(
245                                    Border::new()
246                                        .fill(theme.border_fill)
247                                        .width(1.)
248                                        .alignment(BorderAlignment::Inner),
249                                )
250                                .overflow(Overflow::Clip)
251                                .corner_radius(8.)
252                                .background(theme.select_background)
253                                // TODO: Shadows
254                                .padding(6.)
255                                .content(Content::Fit)
256                                .opacity(opacity)
257                                .scale(scale)
258                                .children(self.children.clone()),
259                        ),
260                )
261            }))
262    }
263
264    fn render_key(&self) -> DiffKey {
265        self.key.clone().or(self.default_key())
266    }
267}