freya_components/
select.rs1use 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#[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 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 let mut button_area = use_state(|| None::<Area>);
137 let mut list_size = use_state(|| None::<Size2D>);
138 use_provide_context(|| MenuGroup { group_id: a11y_id });
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 use_side_effect(move || {
176 let platform = Platform::get();
177 let should_close = platform
178 .focused_accessibility_node
179 .read()
180 .member_of()
181 .is_none_or(|member_of| member_of != a11y_id);
182 if should_close {
183 open.set_if_modified(false);
184 }
185 });
186
187 let on_press = move |e: Event<PressEventData>| {
188 a11y_id.request_focus();
189 open.toggle();
190 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 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, slide) = animation.read().value();
221
222 let offset_y = match (button_area(), list_size()) {
223 (Some(button), Some(list)) => {
224 let root_height = Platform::get().root_size.peek().height;
225 let space_below = root_height - button.max_y();
226 let space_above = button.min_y();
227 let flips = list.height > space_below && list.height <= space_above;
228 if flips {
229 -(button.height() + list.height) - slide
230 } else {
231 slide
232 }
233 }
234 _ => slide,
235 };
236
237 let opacity = if list_size().is_some() { opacity } else { 0. };
238
239 let background = match *status.read() {
240 SelectStatus::Hovering => theme.hover_background,
241 SelectStatus::Idle => theme.background_button,
242 };
243
244 let border = if focus() == Focus::Keyboard {
245 Border::new()
246 .fill(theme.focus_border_fill)
247 .width(2.)
248 .alignment(BorderAlignment::Inner)
249 } else {
250 Border::new()
251 .fill(theme.border_fill)
252 .width(1.)
253 .alignment(BorderAlignment::Inner)
254 };
255
256 rect()
257 .child(
258 rect()
259 .a11y_id(a11y_id)
260 .a11y_member_of(a11y_id)
261 .a11y_role(AccessibilityRole::ListBox)
262 .a11y_focusable(Focusable::Enabled)
263 .on_pointer_enter(on_pointer_enter)
264 .on_pointer_leave(on_pointer_leave)
265 .on_press(on_press)
266 .on_global_key_down(on_global_key_down)
267 .on_global_pointer_press(on_global_pointer_press)
268 .on_sized(move |e: Event<SizedEventData>| {
269 button_area.set_if_modified(Some(e.area));
270 })
271 .width(theme.width)
272 .margin(theme.margin)
273 .background(background)
274 .padding((8., 18., 8., 18.))
275 .border(border)
276 .horizontal()
277 .center()
278 .color(theme.color)
279 .corner_radius(8.)
280 .maybe_child(self.selected_item.clone())
281 .child(
282 ArrowIcon::new()
283 .margin((0., 0., 0., 8.))
284 .rotate(0.)
285 .fill(theme.arrow_fill),
286 ),
287 )
288 .maybe_child((open() || opacity > 0.).then(|| {
289 rect().height(Size::px(0.)).width(Size::px(0.)).child(
290 rect()
291 .width(Size::window_percent(100.))
292 .margin(Gaps::new(4., 0., 4., 0.))
293 .offset_y(offset_y)
294 .on_sized(move |e: Event<SizedEventData>| {
295 list_size.set_if_modified(Some(e.area.size));
296 })
297 .child(
298 rect()
299 .layer(Layer::Overlay)
300 .border(
301 Border::new()
302 .fill(theme.border_fill)
303 .width(1.)
304 .alignment(BorderAlignment::Inner),
305 )
306 .overflow(Overflow::Clip)
307 .corner_radius(8.)
308 .background(theme.select_background)
309 .padding(4.)
310 .content(Content::Fit)
311 .opacity(opacity)
312 .scale(scale)
313 .children(self.children.clone()),
314 ),
315 )
316 }))
317 }
318
319 fn render_key(&self) -> DiffKey {
320 self.key.clone().or(self.default_key())
321 }
322}