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 a11y_id = use_a11y();
133        let focus = use_focus(a11y_id);
134        let mut status = use_state(SelectStatus::default);
135        let mut open = use_state(|| false);
136        use_provide_context(|| MenuGroup { group_id: a11y_id });
137
138        let animation = use_animation(move |conf| {
139            conf.on_change(OnChange::Rerun);
140            conf.on_creation(OnCreation::Finish);
141
142            let scale = AnimNum::new(0.9, 1.)
143                .time(125)
144                .ease(Ease::Out)
145                .function(Function::Quart);
146            let opacity = AnimNum::new(0., 1.)
147                .time(125)
148                .ease(Ease::Out)
149                .function(Function::Quart);
150            let offset_y = AnimNum::new(-8., 1.)
151                .time(125)
152                .ease(Ease::Out)
153                .function(Function::Quart);
154            if open() {
155                (scale, opacity, offset_y)
156            } else {
157                (
158                    scale.into_reversed(),
159                    opacity.into_reversed(),
160                    offset_y.into_reversed(),
161                )
162            }
163        });
164
165        let cursor_icon = self.cursor_icon;
166        use_drop(move || {
167            if status() == SelectStatus::Hovering {
168                Cursor::set(CursorIcon::default());
169            }
170        });
171
172        // Close the select when the focused accessibility node changes and its not the select or any of its children
173        use_side_effect(move || {
174            let platform = Platform::get();
175            if *platform.navigation_mode.read() == NavigationMode::Keyboard {
176                let should_close = platform
177                    .focused_accessibility_node
178                    .read()
179                    .member_of()
180                    .is_none_or(|member_of| member_of != a11y_id);
181                if should_close {
182                    open.set_if_modified(false);
183                }
184            }
185        });
186
187        let on_press = move |e: Event<PressEventData>| {
188            a11y_id.request_focus();
189            open.toggle();
190            // Prevent global mouse up
191            e.prevent_default();
192            e.stop_propagation();
193        };
194
195        let on_pointer_enter = move |_| {
196            *status.write() = SelectStatus::Hovering;
197            Cursor::set(cursor_icon);
198        };
199
200        let on_pointer_leave = move |_| {
201            *status.write() = SelectStatus::Idle;
202            Cursor::set(CursorIcon::default());
203        };
204
205        // Close the select if clicked anywhere
206        let on_global_pointer_press = move |_: Event<PointerEventData>| {
207            open.set_if_modified(false);
208        };
209
210        let on_global_key_down = move |e: Event<KeyboardEventData>| match e.key {
211            Key::Named(NamedKey::Escape) => {
212                open.set_if_modified(false);
213            }
214            Key::Named(NamedKey::Enter) if a11y_id.is_focused() => {
215                open.toggle();
216            }
217            _ => {}
218        };
219
220        let (scale, opacity, offset_y) = animation.read().value();
221
222        let background = match *status.read() {
223            SelectStatus::Hovering => theme.hover_background,
224            SelectStatus::Idle => theme.background_button,
225        };
226
227        let border = if focus() == Focus::Keyboard {
228            Border::new()
229                .fill(theme.focus_border_fill)
230                .width(2.)
231                .alignment(BorderAlignment::Inner)
232        } else {
233            Border::new()
234                .fill(theme.border_fill)
235                .width(1.)
236                .alignment(BorderAlignment::Inner)
237        };
238
239        rect()
240            .child(
241                rect()
242                    .a11y_id(a11y_id)
243                    .a11y_member_of(a11y_id)
244                    .a11y_role(AccessibilityRole::ListBox)
245                    .a11y_focusable(Focusable::Enabled)
246                    .on_pointer_enter(on_pointer_enter)
247                    .on_pointer_leave(on_pointer_leave)
248                    .on_press(on_press)
249                    .on_global_key_down(on_global_key_down)
250                    .on_global_pointer_press(on_global_pointer_press)
251                    .width(theme.width)
252                    .margin(theme.margin)
253                    .background(background)
254                    .padding((8., 18., 8., 18.))
255                    .border(border)
256                    .horizontal()
257                    .center()
258                    .color(theme.color)
259                    .corner_radius(8.)
260                    .maybe_child(self.selected_item.clone())
261                    .child(
262                        ArrowIcon::new()
263                            .margin((0., 0., 0., 8.))
264                            .rotate(0.)
265                            .fill(theme.arrow_fill),
266                    ),
267            )
268            .maybe_child((open() || opacity > 0.).then(|| {
269                rect().height(Size::px(0.)).width(Size::px(0.)).child(
270                    rect()
271                        .width(Size::window_percent(100.))
272                        .margin(Gaps::new(4., 0., 0., 0.))
273                        .offset_y(offset_y)
274                        .child(
275                            rect()
276                                .layer(Layer::Overlay)
277                                .border(
278                                    Border::new()
279                                        .fill(theme.border_fill)
280                                        .width(1.)
281                                        .alignment(BorderAlignment::Inner),
282                                )
283                                .overflow(Overflow::Clip)
284                                .corner_radius(8.)
285                                .background(theme.select_background)
286                                .padding(4.)
287                                .content(Content::Fit)
288                                .opacity(opacity)
289                                .scale(scale)
290                                .children(self.children.clone()),
291                        ),
292                )
293            }))
294    }
295
296    fn render_key(&self) -> DiffKey {
297        self.key.clone().or(self.default_key())
298    }
299}