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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! Material Design 3 Select/Dropdown Components
//!
//! # M3 Color Role Usage
//!
//! - **surfaceContainerHighest**: Filled select background
//! - **onSurface**: Select text, dropdown text
//! - **onSurfaceVariant**: Label text, supporting text
//! - **outline**: Outlined select border
//! - **primary**: Selected item indicator, focused state
//! - **secondaryContainer**: Selected item background in dropdown
//! - **onSecondaryContainer**: Selected item text
//! - **State layers**: onSurface @ 8% (hover), 12% (press)
use crate::theme::get_global_color;
use egui::{
self, Color32, FontFamily, FontId, Key, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, Widget,
};
/// Material Design select/dropdown component.
///
/// Select components allow users to choose one option from a list.
/// They display the currently selected option in a text field-style input
/// and show all options in a dropdown menu when activated.
///
/// Supports Material Design 3 variants (filled and outlined), filtering,
/// validation, and comprehensive keyboard navigation.
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selected = Some(1);
///
/// ui.add(MaterialSelect::new(&mut selected)
/// .variant(SelectVariant::Outlined)
/// .label("Choose an option")
/// .option(0, "Option 1")
/// .option(1, "Option 2")
/// .option(2, "Option 3")
/// .helper_text("Select your preferred option"));
/// # });
/// ```
/// Visual variant of the select component.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Default)]
pub enum SelectVariant {
/// Filled variant with background color
#[default]
Filled,
/// Outlined variant with border
Outlined,
}
/// Menu alignment options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Default)]
pub enum MenuAlignment {
/// Align menu to start edge
#[default]
Start,
/// Align menu to end edge
End,
}
#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
pub struct MaterialSelect<'a> {
/// Reference to the currently selected option
selected: &'a mut Option<usize>,
/// List of available options
options: Vec<SelectOption>,
/// Placeholder text when no option is selected
placeholder: String,
/// Label text (floats above when focused or has content)
label: Option<String>,
/// Visual variant (filled or outlined)
variant: SelectVariant,
/// Whether the select is enabled for interaction
enabled: bool,
/// Fixed width of the select component
width: Option<f32>,
/// Error message to display below the select
error_text: Option<String>,
/// Helper text to display below the select
helper_text: Option<String>,
/// Icon to show at the start of the select field
leading_icon: Option<String>,
/// Icon to show at the end of the select field (overrides default dropdown arrow)
trailing_icon: Option<String>,
/// Whether to keep the dropdown open after selecting an option
keep_open_on_select: bool,
/// Enable filtering of options by typing
enable_filter: bool,
/// Enable search highlighting while typing
enable_search: bool,
/// Mark field as required
required: bool,
/// Independent menu width
menu_width: Option<f32>,
/// Maximum menu height
menu_max_height: Option<f32>,
/// Border radius for menu
border_radius: Option<f32>,
/// Menu alignment
menu_alignment: MenuAlignment,
}
/// Individual option in a select component.
#[derive(Clone)]
pub struct SelectOption {
/// Unique identifier for this option
value: usize,
/// Display text for this option
text: String,
}
impl<'a> MaterialSelect<'a> {
/// Create a new select component.
///
/// # Arguments
/// * `selected` - Mutable reference to the currently selected option value
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// let select = MaterialSelect::new(&mut selection);
/// # });
/// ```
pub fn new(selected: &'a mut Option<usize>) -> Self {
Self {
selected,
options: Vec::new(),
placeholder: "Select an option".to_string(),
label: None,
variant: SelectVariant::default(),
enabled: true,
width: None,
error_text: None,
helper_text: None,
leading_icon: None,
trailing_icon: None,
keep_open_on_select: false,
enable_filter: false,
enable_search: true,
required: false,
menu_width: None,
menu_max_height: None,
border_radius: None,
menu_alignment: MenuAlignment::default(),
}
}
/// Add an option to the select component.
///
/// # Arguments
/// * `value` - Unique identifier for this option
/// * `text` - Display text for this option
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .option(1, "First Option")
/// .option(2, "Second Option"));
/// # });
/// ```
pub fn option(mut self, value: usize, text: impl Into<String>) -> Self {
self.options.push(SelectOption {
value,
text: text.into(),
});
self
}
/// Set placeholder text shown when no option is selected.
///
/// # Arguments
/// * `placeholder` - The placeholder text to display
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .placeholder("Choose your option"));
/// # });
/// ```
pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = placeholder.into();
self
}
/// Set label text that floats above the field when focused or has content.
///
/// # Arguments
/// * `label` - The label text to display
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .label("Color"));
/// # });
/// ```
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Set the visual variant of the select component.
///
/// # Arguments
/// * `variant` - The variant (Filled or Outlined)
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .variant(SelectVariant::Outlined));
/// # });
/// ```
pub fn variant(mut self, variant: SelectVariant) -> Self {
self.variant = variant;
self
}
/// Enable or disable the select component.
///
/// # Arguments
/// * `enabled` - Whether the select should be enabled (true) or disabled (false)
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .enabled(false)); // Disabled select
/// # });
/// ```
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Set a fixed width for the select component.
///
/// # Arguments
/// * `width` - The width in pixels
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .width(300.0)); // Fixed width of 300 pixels
/// # });
/// ```
pub fn width(mut self, width: f32) -> Self {
self.width = Some(width);
self
}
/// Set error text to display below the select component.
///
/// # Arguments
/// * `text` - The error message text
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .error_text("This field is required")); // Error message
/// # });
/// ```
pub fn error_text(mut self, text: impl Into<String>) -> Self {
self.error_text = Some(text.into());
self
}
/// Set helper text to display below the select component.
///
/// # Arguments
/// * `text` - The helper message text
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .helper_text("Select an option from the list")); // Helper text
/// # });
/// ```
pub fn helper_text(mut self, text: impl Into<String>) -> Self {
self.helper_text = Some(text.into());
self
}
/// Set an icon to display at the start of the select field.
///
/// # Arguments
/// * `icon` - The icon identifier (e.g., "home", "settings")
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .leading_icon("settings")); // Gear icon on the left
/// # });
/// ```
pub fn leading_icon(mut self, icon: impl Into<String>) -> Self {
self.leading_icon = Some(icon.into());
self
}
/// Set an icon to display at the end of the select field (overrides default dropdown arrow).
///
/// # Arguments
/// * `icon` - The icon identifier (e.g., "check", "close")
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .trailing_icon("check")); // Check icon on the right
/// # });
/// ```
pub fn trailing_icon(mut self, icon: impl Into<String>) -> Self {
self.trailing_icon = Some(icon.into());
self
}
/// Set whether to keep the dropdown open after selecting an option.
///
/// # Arguments
/// * `keep_open` - If true, the dropdown remains open after selection;
/// if false, it closes (default behavior)
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = None;
/// ui.add(MaterialSelect::new(&mut selection)
/// .keep_open_on_select(true)); // Dropdown stays open after selection
/// # });
/// ```
pub fn keep_open_on_select(mut self, keep_open: bool) -> Self {
self.keep_open_on_select = keep_open;
self
}
/// Enable filtering of options by typing.
///
/// # Arguments
/// * `enable` - If true, allows filtering options by text input
pub fn enable_filter(mut self, enable: bool) -> Self {
self.enable_filter = enable;
self
}
/// Enable search highlighting while typing.
///
/// # Arguments
/// * `enable` - If true, highlights matching options while typing
pub fn enable_search(mut self, enable: bool) -> Self {
self.enable_search = enable;
self
}
/// Mark the field as required.
///
/// # Arguments
/// * `required` - If true, marks the field as required
pub fn required(mut self, required: bool) -> Self {
self.required = required;
self
}
/// Set independent menu width.
///
/// # Arguments
/// * `width` - The width of the menu in pixels
pub fn menu_width(mut self, width: f32) -> Self {
self.menu_width = Some(width);
self
}
/// Set maximum menu height.
///
/// # Arguments
/// * `height` - The maximum height of the menu in pixels
pub fn menu_max_height(mut self, height: f32) -> Self {
self.menu_max_height = Some(height);
self
}
/// Set border radius for menu.
///
/// # Arguments
/// * `radius` - The border radius in pixels
pub fn border_radius(mut self, radius: f32) -> Self {
self.border_radius = Some(radius);
self
}
/// Set menu alignment.
///
/// # Arguments
/// * `alignment` - The menu alignment (Start or End)
pub fn menu_alignment(mut self, alignment: MenuAlignment) -> Self {
self.menu_alignment = alignment;
self
}
}
impl<'a> Widget for MaterialSelect<'a> {
fn ui(self, ui: &mut Ui) -> Response {
let width = self.width.unwrap_or(200.0);
let height = 56.0;
let desired_size = Vec2::new(width, height);
let (rect, mut response) = ui.allocate_exact_size(desired_size, Sense::click());
// Use persistent state for dropdown open/close with global coordination
let select_id = egui::Id::new((
"select_widget",
rect.min.x as i32,
rect.min.y as i32,
self.placeholder.clone(),
self.label.clone(),
));
let mut open = ui.memory(|mem| mem.data.get_temp::<bool>(select_id).unwrap_or(false));
// Handle Escape key to close dropdown
if open && ui.input(|i| i.key_pressed(Key::Escape)) {
open = false;
ui.memory_mut(|mem| mem.data.insert_temp(select_id, false));
}
// Global state to close other select menus
let global_open_select_id = egui::Id::new("global_open_select");
let current_open_select =
ui.memory(|mem| mem.data.get_temp::<egui::Id>(global_open_select_id));
if response.clicked() && self.enabled {
if open {
// Close this select
open = false;
ui.memory_mut(|mem| mem.data.remove::<egui::Id>(global_open_select_id));
} else {
// Close any other open select and open this one
if let Some(other_id) = current_open_select {
if other_id != select_id {
ui.memory_mut(|mem| mem.data.insert_temp(other_id, false));
}
}
open = true;
ui.memory_mut(|mem| mem.data.insert_temp(global_open_select_id, select_id));
}
ui.memory_mut(|mem| mem.data.insert_temp(select_id, open));
}
// Material Design colors
let primary_color = get_global_color("primary");
let surface = get_global_color("surface");
let surface_variant = get_global_color("surfaceVariant");
let on_surface = get_global_color("onSurface");
let on_surface_variant = get_global_color("onSurfaceVariant");
let outline = get_global_color("outline");
let error_color = get_global_color("error");
// Determine if we should show floating label
let has_content = self.selected.is_some();
let should_float_label = has_content || open || response.hovered();
// Hide label if field is empty and not focused (placeholder will be shown instead)
let should_show_label = self.label.is_some() && should_float_label;
// Determine colors based on state
let (bg_color, border_color, text_color) = if !self.enabled {
(
surface_variant.linear_multiply(0.38),
outline.linear_multiply(0.38),
on_surface.linear_multiply(0.38),
)
} else if self.error_text.is_some() {
match self.variant {
SelectVariant::Filled => (surface_variant, error_color, on_surface),
SelectVariant::Outlined => (surface, error_color, on_surface),
}
} else if response.hovered() || open {
match self.variant {
SelectVariant::Filled => (surface_variant, primary_color, on_surface),
SelectVariant::Outlined => (surface, primary_color, on_surface),
}
} else {
match self.variant {
SelectVariant::Filled => (surface_variant, outline, on_surface_variant),
SelectVariant::Outlined => (surface, outline, on_surface_variant),
}
};
// Draw select field background
match self.variant {
SelectVariant::Filled => {
ui.painter().rect_filled(rect, 4.0, bg_color);
// Draw bottom border for filled variant
if !self.enabled {
ui.painter().line_segment(
[
Pos2::new(rect.min.x, rect.max.y),
Pos2::new(rect.max.x, rect.max.y),
],
Stroke::new(1.0, border_color),
);
} else {
ui.painter().line_segment(
[
Pos2::new(rect.min.x, rect.max.y),
Pos2::new(rect.max.x, rect.max.y),
],
Stroke::new(if open || response.hovered() { 2.0 } else { 1.0 }, border_color),
);
}
}
SelectVariant::Outlined => {
ui.painter().rect_filled(rect, 4.0, bg_color);
ui.painter().rect_stroke(
rect,
4.0,
Stroke::new(if open || response.hovered() { 2.0 } else { 1.0 }, border_color),
egui::epaint::StrokeKind::Outside,
);
}
}
// Draw floating label if present and should be shown
if should_show_label {
let label_text = self.label.as_ref().unwrap();
let label_font = if should_float_label {
FontId::new(12.0, FontFamily::Proportional)
} else {
FontId::new(16.0, FontFamily::Proportional)
};
let label_color = if !self.enabled {
on_surface.linear_multiply(0.38)
} else if self.error_text.is_some() {
error_color
} else if open {
primary_color
} else {
on_surface_variant
};
let label_pos = if should_float_label {
Pos2::new(rect.min.x + 16.0, rect.min.y + 8.0)
} else {
Pos2::new(rect.min.x + 16.0, rect.center().y)
};
ui.painter().text(
label_pos,
egui::Align2::LEFT_TOP,
label_text,
label_font,
label_color,
);
}
// Draw selected text or placeholder
let display_text = if let Some(selected_value) = *self.selected {
self.options
.iter()
.find(|option| option.value == selected_value)
.map(|option| option.text.as_str())
.unwrap_or(&self.placeholder)
} else {
&self.placeholder
};
// Use consistent font styling for select field
let select_font = FontId::new(16.0, FontFamily::Proportional);
let text_y_offset = if should_show_label && should_float_label { 12.0 } else { 0.0 };
let text_pos = Pos2::new(rect.min.x + 16.0, rect.center().y + text_y_offset);
let display_color = if self.selected.is_none() {
on_surface_variant.linear_multiply(0.6)
} else {
text_color
};
ui.painter().text(
text_pos,
egui::Align2::LEFT_CENTER,
display_text,
select_font.clone(),
display_color,
);
// Draw dropdown arrow
let arrow_center = Pos2::new(rect.max.x - 24.0, rect.center().y);
let arrow_size = 8.0;
if open {
// Up arrow
ui.painter().line_segment(
[
Pos2::new(
arrow_center.x - arrow_size / 2.0,
arrow_center.y + arrow_size / 4.0,
),
Pos2::new(arrow_center.x, arrow_center.y - arrow_size / 4.0),
],
Stroke::new(2.0, text_color),
);
ui.painter().line_segment(
[
Pos2::new(arrow_center.x, arrow_center.y - arrow_size / 4.0),
Pos2::new(
arrow_center.x + arrow_size / 2.0,
arrow_center.y + arrow_size / 4.0,
),
],
Stroke::new(2.0, text_color),
);
} else {
// Down arrow
ui.painter().line_segment(
[
Pos2::new(
arrow_center.x - arrow_size / 2.0,
arrow_center.y - arrow_size / 4.0,
),
Pos2::new(arrow_center.x, arrow_center.y + arrow_size / 4.0),
],
Stroke::new(2.0, text_color),
);
ui.painter().line_segment(
[
Pos2::new(arrow_center.x, arrow_center.y + arrow_size / 4.0),
Pos2::new(
arrow_center.x + arrow_size / 2.0,
arrow_center.y - arrow_size / 4.0,
),
],
Stroke::new(2.0, text_color),
);
}
// Show dropdown if open - using Area for proper z-layering like menu component
if open {
// Calculate available space below and above using viewport for accurate detection
// This ensures dropdown opens upward when select is at bottom of screen
let viewport_rect = ui.ctx().content_rect();
let available_space_below = viewport_rect.max.y - rect.max.y - 4.0;
let available_space_above = rect.min.y - viewport_rect.min.y - 4.0;
let item_height = 48.0;
let dropdown_padding = 16.0;
// Use menu_max_height if specified, otherwise use available space
let effective_max_height = if let Some(max_h) = self.menu_max_height {
max_h
} else {
available_space_below.max(available_space_above)
};
let max_items_below =
((available_space_below.min(effective_max_height) - dropdown_padding) / item_height).floor() as usize;
let max_items_above =
((available_space_above.min(effective_max_height) - dropdown_padding) / item_height).floor() as usize;
// Determine dropdown position and size
let (dropdown_y, visible_items, scroll_needed) = if max_items_below
>= self.options.len()
{
// Fit below
(rect.max.y + 4.0, self.options.len(), false)
} else if max_items_above >= self.options.len() {
// Fit above
let dropdown_height = self.options.len() as f32 * item_height + dropdown_padding;
(
rect.min.y - 4.0 - dropdown_height,
self.options.len(),
false,
)
} else if max_items_below >= max_items_above {
// Partial fit below with scroll
(rect.max.y + 4.0, max_items_below.max(3), true)
} else {
// Partial fit above with scroll
let visible_items = max_items_above.max(3);
let dropdown_height = visible_items as f32 * item_height + dropdown_padding;
(rect.min.y - 4.0 - dropdown_height, visible_items, true)
};
let dropdown_height = visible_items as f32 * item_height + dropdown_padding;
// Use menu_width if specified, otherwise use field width
let menu_width = self.menu_width.unwrap_or(width);
let menu_border_radius = self.border_radius.unwrap_or(8.0);
let dropdown_pos = Pos2::new(rect.min.x, dropdown_y);
let dropdown_size = Vec2::new(menu_width, dropdown_height);
// Use page background color as specified
let dropdown_bg_color = ui.visuals().window_fill;
// Clone/copy data needed in the Area closure
let ctx = ui.ctx().clone();
let options = self.options.clone();
let selected = self.selected;
let keep_open_on_select = self.keep_open_on_select;
// Use Area widget for proper z-layering (like menu component)
egui::Area::new(select_id.with("dropdown"))
.fixed_pos(dropdown_pos)
.order(egui::Order::Foreground)
.interactable(true)
.show(&ctx, |ui| {
let dropdown_rect = Rect::from_min_size(dropdown_pos, dropdown_size);
// Draw subtle elevation shadow
let shadow_color = Color32::from_rgba_premultiplied(0, 0, 0, 30);
ui.painter().rect_filled(
dropdown_rect.translate(Vec2::new(0.0, 2.0)),
menu_border_radius,
shadow_color,
);
// Draw dropdown background
ui.painter().rect_filled(dropdown_rect, menu_border_radius, dropdown_bg_color);
// Draw dropdown border
ui.painter().rect_stroke(
dropdown_rect,
menu_border_radius,
Stroke::new(1.0, outline),
egui::epaint::StrokeKind::Outside,
);
// Render options with scrolling support
if scroll_needed && visible_items < options.len() {
let scroll_area_rect = Rect::from_min_size(
Pos2::new(dropdown_rect.min.x + 8.0, dropdown_rect.min.y + 8.0),
Vec2::new(menu_width - 16.0, dropdown_height - 16.0),
);
ui.scope_builder(egui::UiBuilder::new().max_rect(scroll_area_rect), |ui| {
egui::ScrollArea::vertical()
.max_height(dropdown_height - 16.0)
.scroll_bar_visibility(
egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded,
)
.auto_shrink([false; 2])
.show(ui, |ui| {
for option in &options {
// Calculate text layout first to determine actual height needed
let available_width = ui.available_width() - 32.0;
let is_selected = *selected == Some(option.value);
let text_color = if is_selected {
get_global_color("primary")
} else {
on_surface
};
let galley = ui.painter().layout_job(egui::text::LayoutJob {
text: option.text.clone(),
sections: vec![egui::text::LayoutSection {
leading_space: 0.0,
byte_range: 0..option.text.len(),
format: egui::TextFormat {
font_id: select_font.clone(),
color: text_color,
..Default::default()
},
}],
wrap: egui::text::TextWrapping {
max_width: available_width,
..Default::default()
},
break_on_newline: true,
halign: egui::Align::LEFT,
justify: false,
first_row_min_height: 0.0,
round_output_to_gui: true,
});
// Use actual text height + padding, with minimum of 48.0
let min_height = 48.0;
let text_height = galley.size().y;
let vertical_padding = 12.0;
let option_height = (text_height + vertical_padding).max(min_height);
let (option_rect, option_response) = ui.allocate_exact_size(
Vec2::new(ui.available_width(), option_height),
Sense::click(),
);
let option_bg_color = if is_selected {
Color32::from_rgba_premultiplied(
on_surface.r(),
on_surface.g(),
on_surface.b(),
30,
)
} else if option_response.hovered() {
Color32::from_rgba_premultiplied(
on_surface.r(),
on_surface.g(),
on_surface.b(),
20,
)
} else {
Color32::TRANSPARENT
};
if option_bg_color != Color32::TRANSPARENT {
ui.painter().rect_filled(option_rect, 4.0, option_bg_color);
}
let text_pos = Pos2::new(option_rect.min.x + 16.0, option_rect.center().y - text_height / 2.0);
ui.painter().galley(text_pos, galley, text_color);
if option_response.clicked() {
*selected = Some(option.value);
if !keep_open_on_select {
open = false;
ui.memory_mut(|mem| {
mem.data.insert_temp(select_id, open);
mem.data.remove::<egui::Id>(global_open_select_id);
});
}
response.mark_changed();
}
}
});
});
} else {
// Draw options without scrolling
let mut current_y = dropdown_rect.min.y + 8.0;
let items_to_show = visible_items.min(options.len());
for option in options.iter().take(items_to_show) {
// Calculate text layout first to determine actual height needed
let is_selected = *selected == Some(option.value);
let text_color = if is_selected {
get_global_color("primary")
} else {
on_surface
};
let available_width = menu_width - 16.0 - 32.0;
let galley = ui.painter().layout_job(egui::text::LayoutJob {
text: option.text.clone(),
sections: vec![egui::text::LayoutSection {
leading_space: 0.0,
byte_range: 0..option.text.len(),
format: egui::TextFormat {
font_id: select_font.clone(),
color: text_color,
..Default::default()
},
}],
wrap: egui::text::TextWrapping {
max_width: available_width,
..Default::default()
},
break_on_newline: true,
halign: egui::Align::LEFT,
justify: false,
first_row_min_height: 0.0,
round_output_to_gui: true,
});
// Use actual text height + padding, with minimum of 48.0
let min_height = 48.0;
let text_height = galley.size().y;
let vertical_padding = 12.0;
let option_height = (text_height + vertical_padding).max(min_height);
let option_rect = Rect::from_min_size(
Pos2::new(dropdown_rect.min.x + 8.0, current_y),
Vec2::new(menu_width - 16.0, option_height),
);
let option_response = ui.interact(
option_rect,
egui::Id::new(("select_option", option.value, option.text.clone())),
Sense::click(),
);
let option_bg_color = if is_selected {
Color32::from_rgba_premultiplied(
on_surface.r(),
on_surface.g(),
on_surface.b(),
30,
)
} else if option_response.hovered() {
Color32::from_rgba_premultiplied(
on_surface.r(),
on_surface.g(),
on_surface.b(),
20,
)
} else {
Color32::TRANSPARENT
};
if option_bg_color != Color32::TRANSPARENT {
ui.painter().rect_filled(option_rect, 4.0, option_bg_color);
}
if option_response.clicked() {
*selected = Some(option.value);
if !keep_open_on_select {
open = false;
ui.memory_mut(|mem| {
mem.data.insert_temp(select_id, open);
mem.data.remove::<egui::Id>(global_open_select_id);
});
}
response.mark_changed();
}
let text_pos = Pos2::new(option_rect.min.x + 16.0, option_rect.center().y - text_height / 2.0);
ui.painter().galley(text_pos, galley, text_color);
current_y += option_height;
}
}
});
}
// Draw helper text or error text below the field
if let Some(ref error) = self.error_text {
let error_font = FontId::new(12.0, FontFamily::Proportional);
let error_pos = Pos2::new(rect.min.x + 16.0, rect.max.y + 4.0);
ui.painter().text(
error_pos,
egui::Align2::LEFT_TOP,
error,
error_font,
error_color,
);
} else if let Some(ref helper) = self.helper_text {
let helper_font = FontId::new(12.0, FontFamily::Proportional);
let helper_pos = Pos2::new(rect.min.x + 16.0, rect.max.y + 4.0);
ui.painter().text(
helper_pos,
egui::Align2::LEFT_TOP,
helper,
helper_font,
on_surface_variant,
);
}
response
}
}
/// Convenience function to create a select component.
///
/// Shorthand for `MaterialSelect::new()`.
///
/// # Arguments
/// * `selected` - Mutable reference to the currently selected option value
///
/// # Example
/// ```rust
/// # egui::__run_test_ui(|ui| {
/// let mut selection = Some(1);
/// ui.add(select(&mut selection)
/// .option(0, "Option 1")
/// .option(1, "Option 2"));
/// # });
/// ```
pub fn select<'a>(selected: &'a mut Option<usize>) -> MaterialSelect<'a> {
MaterialSelect::new(selected)
}