Skip to main content

freya_components/
select.rs

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