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
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
//! Material Design 3 Select (Dropdown) component
//!
//! Select menus display a list of choices on a temporary surface and allow users to select one.
//! Reference: <https://m3.material.io/components/menus/overview>
use bevy::prelude::*;
use crate::{
i18n::{MaterialI18n, MaterialLanguage, MaterialLanguageOverride},
icons::{icon_by_name, MaterialIcon, ICON_EXPAND_MORE},
telemetry::{InsertTestIdIfExists, TelemetryConfig, TestId},
theme::MaterialTheme,
tokens::{CornerRadius, Spacing},
};
use crate::scroll::ScrollContainer;
use crate::scroll::ScrollContent;
/// Plugin for the select component
pub struct SelectPlugin;
impl Plugin for SelectPlugin {
fn build(&self, app: &mut App) {
if !app.is_plugin_added::<crate::MaterialUiCorePlugin>() {
app.add_plugins(crate::MaterialUiCorePlugin);
}
app.add_message::<SelectChangeEvent>().add_systems(
Update,
(
select_interaction_system,
select_style_system,
select_content_style_system,
select_theme_refresh_system,
select_localization_system,
select_dropdown_rebuild_options_system,
select_dropdown_sync_system,
select_dropdown_virtualization_system,
select_option_interaction_system,
select_telemetry_system,
),
);
}
}
#[derive(Component, Debug, Default, Clone, PartialEq, Eq)]
pub struct SelectLocalization {
pub label_key: Option<String>,
pub supporting_text_key: Option<String>,
pub error_text_key: Option<String>,
}
impl SelectLocalization {
pub fn label_key(mut self, key: impl Into<String>) -> Self {
self.label_key = Some(key.into());
self
}
pub fn supporting_text_key(mut self, key: impl Into<String>) -> Self {
self.supporting_text_key = Some(key.into());
self
}
pub fn error_text_key(mut self, key: impl Into<String>) -> Self {
self.error_text_key = Some(key.into());
self
}
fn is_enabled(&self) -> bool {
self.label_key.is_some()
|| self.supporting_text_key.is_some()
|| self.error_text_key.is_some()
}
}
#[derive(Component, Debug, Default, Clone, PartialEq, Eq)]
struct SelectLocalizationState {
last_revision: u64,
last_language: String,
}
fn resolve_language_tag(
mut entity: Entity,
child_of: &Query<&ChildOf>,
overrides: &Query<&MaterialLanguageOverride>,
global: &MaterialLanguage,
) -> String {
if let Ok(ov) = overrides.get(entity) {
return ov.tag.clone();
}
while let Ok(parent) = child_of.get(entity) {
entity = parent.parent();
if let Ok(ov) = overrides.get(entity) {
return ov.tag.clone();
}
}
global.tag.clone()
}
fn select_localization_system(
i18n: Option<Res<MaterialI18n>>,
language: Option<Res<MaterialLanguage>>,
child_of: Query<&ChildOf>,
overrides: Query<&MaterialLanguageOverride>,
mut selects: Query<(
Entity,
&SelectLocalization,
&mut MaterialSelect,
Option<&mut SelectLocalizationState>,
)>,
mut commands: Commands,
) {
let (Some(i18n), Some(language)) = (i18n, language) else {
return;
};
let global_revision = i18n.revision();
for (entity, loc, mut select, state) in selects.iter_mut() {
if !loc.is_enabled() {
continue;
}
let resolved_language = resolve_language_tag(entity, &child_of, &overrides, &language);
let needs_update = match &state {
Some(s) => s.last_revision != global_revision || s.last_language != resolved_language,
None => true,
};
if !needs_update {
continue;
}
if let Some(key) = loc.label_key.as_deref() {
if let Some(v) = i18n.translate(&resolved_language, key) {
let next = v.to_string();
if select.label.as_deref() != Some(next.as_str()) {
select.label = Some(next);
}
}
}
if let Some(key) = loc.supporting_text_key.as_deref() {
if let Some(v) = i18n.translate(&resolved_language, key) {
let next = v.to_string();
if select.supporting_text.as_deref() != Some(next.as_str()) {
select.supporting_text = Some(next);
}
}
}
if let Some(key) = loc.error_text_key.as_deref() {
if let Some(v) = i18n.translate(&resolved_language, key) {
let next = v.to_string();
if select.error_text.as_deref() != Some(next.as_str()) {
select.error_text = Some(next);
}
}
}
// Localize option labels.
for option in select.options.iter_mut() {
let Some(key) = option.label_key.as_deref() else {
continue;
};
if let Some(v) = i18n.translate(&resolved_language, key) {
let next = v.to_string();
if option.label != next {
option.label = next;
}
}
}
if let Some(mut state) = state {
state.last_revision = global_revision;
state.last_language = resolved_language;
} else {
commands.entity(entity).insert(SelectLocalizationState {
last_revision: global_revision,
last_language: resolved_language,
});
}
}
}
fn select_telemetry_system(
mut commands: Commands,
telemetry: Option<Res<TelemetryConfig>>,
selects: Query<(&TestId, &Children), With<MaterialSelect>>,
children_query: Query<&Children>,
virtual_rows: Query<(), With<SelectVirtualRow>>,
mut queries: ParamSet<(
Query<(), With<SelectDisplayText>>,
Query<(), With<SelectDropdownArrow>>,
Query<(), With<SelectDropdown>>,
Query<&SelectOptionItem>,
Query<(), With<SelectOptionLabelText>>,
Query<(), With<SelectOptionIcon>>,
)>,
) {
let Some(telemetry) = telemetry else {
return;
};
if !telemetry.enabled {
return;
}
for (test_id, children) in selects.iter() {
let base = test_id.id();
let mut found_display = false;
let mut found_arrow = false;
let mut found_dropdown = false;
let mut options: Vec<(Entity, usize)> = Vec::new();
let mut stack: Vec<Entity> = children.iter().collect();
while let Some(entity) = stack.pop() {
if !found_display && queries.p0().get(entity).is_ok() {
found_display = true;
commands.queue(InsertTestIdIfExists {
entity,
id: format!("{base}/display_text"),
});
}
if !found_arrow && queries.p1().get(entity).is_ok() {
found_arrow = true;
commands.queue(InsertTestIdIfExists {
entity,
id: format!("{base}/arrow"),
});
}
if !found_dropdown && queries.p2().get(entity).is_ok() {
found_dropdown = true;
commands.queue(InsertTestIdIfExists {
entity,
id: format!("{base}/dropdown"),
});
}
if let Ok(option) = queries.p3().get(entity) {
// Virtualized rows are reused for multiple indices as you scroll; tagging them
// with an index-based test id would be misleading.
if virtual_rows.get(entity).is_ok() {
continue;
}
let option_base = format!("{base}/option/{}", option.index);
commands.queue(InsertTestIdIfExists {
entity,
id: option_base.clone(),
});
options.push((entity, option.index));
}
if let Ok(children) = children_query.get(entity) {
stack.extend(children.iter());
}
}
// Tag label/icon nodes under each option row with stable derived IDs.
for (row_entity, index) in options {
let Ok(children) = children_query.get(row_entity) else {
continue;
};
let mut found_label = false;
let mut found_icon = false;
let mut stack: Vec<Entity> = children.iter().collect();
while let Some(entity) = stack.pop() {
if !found_icon && queries.p5().get(entity).is_ok() {
found_icon = true;
commands.queue(InsertTestIdIfExists {
entity,
id: format!("{base}/option/{index}/icon"),
});
}
if !found_label && queries.p4().get(entity).is_ok() {
found_label = true;
commands.queue(InsertTestIdIfExists {
entity,
id: format!("{base}/option/{index}/label"),
});
}
if found_label && found_icon {
break;
}
if let Ok(children) = children_query.get(entity) {
stack.extend(children.iter());
}
}
}
}
}
/// Select variants
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum SelectVariant {
/// Filled select field
#[default]
Filled,
/// Outlined select field
Outlined,
}
/// Material select component
#[derive(Component)]
pub struct MaterialSelect {
/// Select variant
pub variant: SelectVariant,
/// Currently selected option index
pub selected_index: Option<usize>,
/// Options list
pub options: Vec<SelectOption>,
/// Label text
pub label: Option<String>,
/// Supporting text
pub supporting_text: Option<String>,
/// Whether the select is disabled
pub disabled: bool,
/// Whether there's an error
pub error: bool,
/// Error message
pub error_text: Option<String>,
/// Whether the dropdown is open
pub open: bool,
/// Interaction states
pub focused: bool,
pub hovered: bool,
}
impl MaterialSelect {
/// Create a new select
pub fn new(options: Vec<SelectOption>) -> Self {
Self {
variant: SelectVariant::default(),
selected_index: None,
options,
label: None,
supporting_text: None,
disabled: false,
error: false,
error_text: None,
open: false,
focused: false,
hovered: false,
}
}
/// Set variant
pub fn with_variant(mut self, variant: SelectVariant) -> Self {
self.variant = variant;
self
}
/// Set initially selected option
pub fn selected(mut self, index: usize) -> Self {
if index < self.options.len() {
self.selected_index = Some(index);
}
self
}
/// Set label
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Set supporting text
pub fn supporting_text(mut self, text: impl Into<String>) -> Self {
self.supporting_text = Some(text.into());
self
}
/// Set disabled state
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Set error state
pub fn error(mut self, error: bool) -> Self {
self.error = error;
self
}
/// Set error text
pub fn error_text(mut self, text: impl Into<String>) -> Self {
self.error_text = Some(text.into());
self.error = true;
self
}
/// Get the selected option
pub fn selected_option(&self) -> Option<&SelectOption> {
self.selected_index.and_then(|i| self.options.get(i))
}
/// Get the display text for the current selection
pub fn display_text(&self) -> String {
self.selected_option()
.map(|o| o.label.clone())
.unwrap_or_default()
}
/// Get the container color
pub fn container_color(&self, theme: &MaterialTheme) -> Color {
if self.disabled {
return theme.on_surface.with_alpha(0.04);
}
match self.variant {
SelectVariant::Filled => theme.surface_container_highest,
SelectVariant::Outlined => Color::NONE,
}
}
/// Get the indicator/outline color
pub fn indicator_color(&self, theme: &MaterialTheme) -> Color {
if self.disabled {
return theme.on_surface.with_alpha(0.38);
}
if self.error {
return theme.error;
}
if self.focused || self.open {
theme.primary
} else {
theme.on_surface_variant
}
}
/// Get the label color
pub fn label_color(&self, theme: &MaterialTheme) -> Color {
if self.disabled {
return theme.on_surface.with_alpha(0.38);
}
if self.error {
return theme.error;
}
if self.focused || self.open {
theme.primary
} else {
theme.on_surface_variant
}
}
/// Get the text color
pub fn text_color(&self, theme: &MaterialTheme) -> Color {
if self.disabled {
theme.on_surface.with_alpha(0.38)
} else {
theme.on_surface
}
}
/// Get the trailing icon color
pub fn trailing_icon_color(&self, theme: &MaterialTheme) -> Color {
if self.disabled {
theme.on_surface.with_alpha(0.38)
} else if self.error {
theme.error
} else {
theme.on_surface_variant
}
}
}
/// A select option
#[derive(Debug, Clone)]
pub struct SelectOption {
/// Display label
pub label: String,
/// Optional i18n key for the label.
pub label_key: Option<String>,
/// Optional value (can be used for form submission)
pub value: Option<String>,
/// Optional leading icon
pub icon: Option<String>,
/// Whether this option is disabled
pub disabled: bool,
}
impl SelectOption {
/// Create a new option
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
label_key: None,
value: None,
icon: None,
disabled: false,
}
}
/// Set the label from an i18n key.
pub fn label_key(mut self, key: impl Into<String>) -> Self {
self.label = String::new();
self.label_key = Some(key.into());
self
}
/// Set the value
pub fn value(mut self, value: impl Into<String>) -> Self {
self.value = Some(value.into());
self
}
/// Set the icon
pub fn icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
/// Set disabled
pub fn disabled(mut self) -> Self {
self.disabled = true;
self
}
}
/// Event when selection changes
#[derive(Event, bevy::prelude::Message)]
pub struct SelectChangeEvent {
pub entity: Entity,
pub index: usize,
pub option: SelectOption,
}
/// Select dimensions
pub const SELECT_HEIGHT: f32 = 56.0;
pub const SELECT_OPTION_HEIGHT: f32 = 48.0;
const SELECT_DROPDOWN_PADDING_Y: f32 = 8.0;
const SELECT_DROPDOWN_PADDING_TOTAL: f32 = SELECT_DROPDOWN_PADDING_Y * 2.0;
/// System to handle select interactions
fn select_interaction_system(
mut interaction_query: Query<
(&Interaction, &mut MaterialSelect),
(Changed<Interaction>, With<MaterialSelect>),
>,
) {
for (interaction, mut select) in interaction_query.iter_mut() {
if select.disabled {
continue;
}
match *interaction {
Interaction::Pressed => {
select.open = !select.open;
select.focused = true;
}
Interaction::Hovered => {
select.hovered = true;
}
Interaction::None => {
select.hovered = false;
}
}
}
}
/// System to update select styles
fn select_style_system(
theme: Option<Res<MaterialTheme>>,
mut selects: Query<
(&MaterialSelect, &mut BackgroundColor, &mut BorderColor),
Changed<MaterialSelect>,
>,
) {
let Some(theme) = theme else { return };
for (select, mut bg_color, mut border_color) in selects.iter_mut() {
*bg_color = BackgroundColor(select.container_color(&theme));
*border_color = BorderColor::all(select.indicator_color(&theme));
}
}
/// Update select child visuals (text colors, dropdown surface, option selection highlight)
/// whenever select state changes.
fn select_content_style_system(
theme: Option<Res<MaterialTheme>>,
changed_selects: Query<Entity, Changed<MaterialSelect>>,
selects: Query<&MaterialSelect>,
mut text_colors: ParamSet<(
Query<(&ChildOf, &mut TextColor), With<SelectDisplayText>>,
Query<(&ChildOf, &mut MaterialIcon), With<SelectDropdownArrow>>,
Query<&mut TextColor, With<SelectOptionLabelText>>,
Query<&mut MaterialIcon, With<SelectOptionIcon>>,
)>,
mut dropdowns: Query<
(&ChildOf, &mut BackgroundColor),
(
With<SelectDropdown>,
Without<SelectOptionItem>,
Without<MaterialSelect>,
),
>,
mut option_rows: Query<
(
&SelectOwner,
&SelectOptionItem,
&mut BackgroundColor,
&Children,
),
(Without<SelectDropdown>, Without<MaterialSelect>),
>,
) {
let Some(theme) = theme else { return };
if changed_selects.iter().next().is_none() {
return;
}
for (parent, mut color) in text_colors.p0().iter_mut() {
if let Ok(select) = selects.get(parent.parent()) {
color.0 = select.text_color(&theme);
}
}
for (parent, mut color) in text_colors.p1().iter_mut() {
if let Ok(select) = selects.get(parent.parent()) {
color.color = select.label_color(&theme);
}
}
for (parent, mut bg) in dropdowns.iter_mut() {
if selects.get(parent.parent()).is_ok() {
bg.0 = theme.surface_container;
}
}
for (owner, option_item, mut row_bg, children) in option_rows.iter_mut() {
let Ok(select) = selects.get(owner.0) else {
continue;
};
let is_selected = select
.selected_index
.is_some_and(|i| i == option_item.index);
row_bg.0 = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
let base = theme.on_surface;
let is_disabled = select
.options
.get(option_item.index)
.is_some_and(|o| o.disabled);
let text_color = if is_disabled {
base.with_alpha(0.38)
} else {
base
};
for child in children.iter() {
if let Ok(mut c) = text_colors.p2().get_mut(child) {
c.0 = text_color;
}
if let Ok(mut c) = text_colors.p3().get_mut(child) {
c.color = text_color;
}
}
}
}
/// Refresh select visuals when the theme changes.
fn select_theme_refresh_system(
theme: Option<Res<MaterialTheme>>,
selects: Query<&MaterialSelect>,
mut triggers: Query<
(&MaterialSelect, &mut BackgroundColor, &mut BorderColor),
(Without<SelectDropdown>, Without<SelectOptionItem>),
>,
mut text_colors: ParamSet<(
Query<(&ChildOf, &mut TextColor), With<SelectDisplayText>>,
Query<(&ChildOf, &mut MaterialIcon), With<SelectDropdownArrow>>,
Query<&mut TextColor, With<SelectOptionLabelText>>,
Query<&mut MaterialIcon, With<SelectOptionIcon>>,
)>,
mut dropdowns: Query<
(&ChildOf, &mut BackgroundColor),
(
With<SelectDropdown>,
Without<SelectOptionItem>,
Without<MaterialSelect>,
),
>,
mut option_rows: Query<
(
&SelectOwner,
&SelectOptionItem,
&mut BackgroundColor,
&Children,
),
(Without<SelectDropdown>, Without<MaterialSelect>),
>,
) {
let Some(theme) = theme else { return };
if !theme.is_changed() {
return;
}
for (select, mut bg, mut border) in triggers.iter_mut() {
bg.0 = select.container_color(&theme);
*border = BorderColor::all(select.indicator_color(&theme));
}
for (parent, mut color) in text_colors.p0().iter_mut() {
if let Ok(select) = selects.get(parent.parent()) {
color.0 = select.text_color(&theme);
}
}
for (parent, mut color) in text_colors.p1().iter_mut() {
if let Ok(select) = selects.get(parent.parent()) {
color.color = select.label_color(&theme);
}
}
for (parent, mut bg) in dropdowns.iter_mut() {
if selects.get(parent.parent()).is_ok() {
bg.0 = theme.surface_container;
}
}
for (owner, option_item, mut row_bg, children) in option_rows.iter_mut() {
let Ok(select) = selects.get(owner.0) else {
continue;
};
let is_selected = select
.selected_index
.is_some_and(|i| i == option_item.index);
row_bg.0 = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
let base = theme.on_surface;
let is_disabled = select
.options
.get(option_item.index)
.is_some_and(|o| o.disabled);
let text_color = if is_disabled {
base.with_alpha(0.38)
} else {
base
};
for child in children.iter() {
if let Ok(mut c) = text_colors.p2().get_mut(child) {
c.0 = text_color;
}
if let Ok(mut c) = text_colors.p3().get_mut(child) {
c.color = text_color;
}
}
}
}
/// Builder for select components
pub struct SelectBuilder {
select: MaterialSelect,
width: Val,
localization: SelectLocalization,
dropdown_max_height: Option<Val>,
dropdown_virtualize: bool,
}
impl SelectBuilder {
/// Create a new select builder
pub fn new(options: Vec<SelectOption>) -> Self {
Self {
select: MaterialSelect::new(options),
width: Val::Px(210.0),
localization: SelectLocalization::default(),
dropdown_max_height: None,
dropdown_virtualize: false,
}
}
/// Set a maximum height for the dropdown list.
///
/// When set, the dropdown becomes vertically scrollable so long lists don't expand
/// beyond this height.
pub fn dropdown_max_height(mut self, height: Val) -> Self {
self.dropdown_max_height = Some(height);
self
}
/// Enable dropdown virtualization.
///
/// When enabled, the dropdown only spawns a small fixed pool of option row entities and
/// reuses them as you scroll. This significantly improves performance for very large option
/// lists.
///
/// Note: virtualization requires `dropdown_max_height(...)` so the dropdown is scrollable.
pub fn virtualize(mut self, enabled: bool) -> Self {
self.dropdown_virtualize = enabled;
self
}
/// Localize the select's placeholder/label via a translation key.
pub fn label_key(mut self, key: impl Into<String>) -> Self {
self.localization = self.localization.label_key(key);
self
}
/// Localize the select's supporting text via a translation key.
pub fn supporting_text_key(mut self, key: impl Into<String>) -> Self {
self.localization = self.localization.supporting_text_key(key);
self
}
/// Localize the select's error text via a translation key.
pub fn error_text_key(mut self, key: impl Into<String>) -> Self {
self.localization = self.localization.error_text_key(key);
self
}
/// Set variant
pub fn variant(mut self, variant: SelectVariant) -> Self {
self.select.variant = variant;
self
}
/// Make filled
pub fn filled(self) -> Self {
self.variant(SelectVariant::Filled)
}
/// Make outlined
pub fn outlined(self) -> Self {
self.variant(SelectVariant::Outlined)
}
/// Set initially selected option
pub fn selected(mut self, index: usize) -> Self {
if index < self.select.options.len() {
self.select.selected_index = Some(index);
}
self
}
/// Set label
pub fn label(mut self, label: impl Into<String>) -> Self {
self.select.label = Some(label.into());
self
}
/// Set supporting text
pub fn supporting_text(mut self, text: impl Into<String>) -> Self {
self.select.supporting_text = Some(text.into());
self
}
/// Set disabled
pub fn disabled(mut self, disabled: bool) -> Self {
self.select.disabled = disabled;
self
}
/// Set error state
pub fn error(mut self, error: bool) -> Self {
self.select.error = error;
self
}
/// Set error text
pub fn error_text(mut self, text: impl Into<String>) -> Self {
self.select.error_text = Some(text.into());
self.select.error = true;
self
}
/// Set width
pub fn width(mut self, width: Val) -> Self {
self.width = width;
self
}
/// Build the select bundle
pub fn build(self, theme: &MaterialTheme) -> impl Bundle {
let bg_color = self.select.container_color(theme);
let border_color = self.select.indicator_color(theme);
let is_outlined = self.select.variant == SelectVariant::Outlined;
(
self.select,
self.localization,
Button,
Node {
width: self.width,
height: Val::Px(SELECT_HEIGHT),
padding: UiRect::axes(Val::Px(Spacing::LARGE), Val::Px(Spacing::MEDIUM)),
border: if is_outlined {
UiRect::all(Val::Px(1.0))
} else {
UiRect::bottom(Val::Px(1.0))
},
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceBetween,
border_radius: BorderRadius::top(Val::Px(CornerRadius::EXTRA_SMALL)),
..default()
},
BackgroundColor(bg_color),
BorderColor::all(border_color),
)
}
}
/// Marker for select dropdown
#[derive(Component)]
pub struct SelectDropdown;
/// Internal marker for the dropdown's scroll/content container.
///
/// Option rows are spawned under this entity.
#[derive(Component)]
struct SelectDropdownContent;
/// Optional max height configuration for a select dropdown.
///
/// When present on `SelectDropdownContent`, the dropdown viewport height is computed as:
/// `min(max_height, content_height)` so the dropdown only becomes scrollable when needed.
#[derive(Component, Clone, Copy, Debug, PartialEq)]
struct SelectDropdownMaxHeight(pub Val);
/// Internal marker for a virtualized dropdown list.
///
/// Virtualized dropdowns render a fixed pool of rows with top/bottom spacers.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
struct SelectDropdownVirtualized {
pool_size: usize,
}
#[derive(Component)]
struct SelectVirtualTopSpacer;
#[derive(Component)]
struct SelectVirtualBottomSpacer;
#[derive(Component)]
struct SelectVirtualRow;
#[derive(Component)]
struct SelectVirtualIcon;
/// Internal marker for option icons rendered as embedded bitmaps.
#[derive(Component)]
struct SelectOptionIcon;
/// Internal marker used to route option clicks back to the owning select.
#[derive(Component, Clone, Copy)]
struct SelectOwner(Entity);
/// Marker for select option item (component attached to each option in the dropdown)
#[derive(Component)]
pub struct SelectOptionItem {
/// Index of this option in the options list
pub index: usize,
/// Display label for this option
pub label: String,
}
/// Marker for select container (parent of trigger and dropdown)
#[derive(Component)]
pub struct SelectContainer;
/// Marker for select trigger button
#[derive(Component)]
pub struct SelectTrigger {
/// Available options
#[allow(dead_code)]
pub options: Vec<String>,
/// Currently selected index
pub selected_index: usize,
}
/// Marker for select's displayed text
#[derive(Component)]
pub struct SelectDisplayText;
/// Marker for the dropdown arrow text node.
#[derive(Component)]
pub struct SelectDropdownArrow;
/// Marker for select option label text nodes.
#[derive(Component)]
pub struct SelectOptionLabelText;
/// Rebuild dropdown option rows when `MaterialSelect.options` changes.
///
/// The select component spawns option rows at build time. Some UIs (like the
/// showcase Translations view) populate options dynamically after spawn.
fn select_dropdown_rebuild_options_system(
theme: Option<Res<MaterialTheme>>,
selects: Query<(Entity, &MaterialSelect, &Children), Changed<MaterialSelect>>,
dropdowns: Query<(), With<SelectDropdown>>,
dropdown_contents: Query<(), With<SelectDropdownContent>>,
dropdown_max_heights: Query<&SelectDropdownMaxHeight>,
mut dropdown_virtualized: Query<&mut SelectDropdownVirtualized>,
mut dropdown_content_nodes: Query<&mut Node, With<SelectDropdownContent>>,
dropdown_children: Query<&Children, With<SelectDropdown>>,
content_children: Query<&Children, With<SelectDropdownContent>>,
is_scroll_content: Query<(), With<ScrollContent>>,
virtual_top_spacers: Query<(), With<SelectVirtualTopSpacer>>,
virtual_rows: Query<(), With<SelectVirtualRow>>,
virtual_bottom_spacers: Query<(), With<SelectVirtualBottomSpacer>>,
option_rows: Query<(), With<SelectOptionItem>>,
children_query: Query<&Children>,
mut commands: Commands,
) {
let Some(theme) = theme else { return };
for (select_entity, select, children) in selects.iter() {
// Find dropdown child.
let Some(dropdown_entity) = children.iter().find(|e| dropdowns.get(*e).is_ok()) else {
continue;
};
// Find the content container where option rows live.
let content_entity = dropdown_children
.get(dropdown_entity)
.ok()
.and_then(|kids| kids.iter().find(|e| dropdown_contents.get(*e).is_ok()))
.unwrap_or(dropdown_entity);
// For scrollable dropdowns, the UI system re-parents children under a `ScrollContent`
// wrapper. Look there when enumerating rows so we don't accidentally spawn duplicates.
let mut list_root = content_entity;
if let Ok(kids) = children_query.get(content_entity) {
if let Some(wrapper) = kids
.iter()
.find(|&child| is_scroll_content.get(child).is_ok())
{
list_root = wrapper;
}
}
// Virtualized dropdowns manage their own row pool; don't despawn/rebuild rows here.
// We still update the viewport height (below) so the dropdown only scrolls when needed.
if let Ok(mut virt) = dropdown_virtualized.get_mut(content_entity) {
let options = select.options.clone();
// Keep viewport height in sync.
let mut desired_pool_size = virt.pool_size;
if let Ok(max_h) = dropdown_max_heights.get(content_entity).copied() {
if let Ok(mut node) = dropdown_content_nodes.get_mut(content_entity) {
match max_h.0 {
Val::Px(max_px) => {
let items_px = (options.len() as f32) * SELECT_OPTION_HEIGHT;
let viewport_items_px = items_px.min(max_px);
node.height =
Val::Px(SELECT_DROPDOWN_PADDING_TOTAL + viewport_items_px);
node.max_height = Val::Px(SELECT_DROPDOWN_PADDING_TOTAL + max_px);
// Resize the row pool based on the (items) viewport.
let visible =
(viewport_items_px / SELECT_OPTION_HEIGHT).ceil() as usize;
desired_pool_size = (visible + 2).max(1);
}
other => {
node.height = other;
node.max_height = other;
}
}
}
}
// If the dropdown was spawned with empty options (common for dynamic population),
// the initial pool can be too small. Rebuild the pool when it needs to grow/shrink.
if desired_pool_size != virt.pool_size {
virt.pool_size = desired_pool_size;
// Remove old virtual rows + spacers.
if let Ok(kids) = children_query.get(list_root) {
let mut to_remove = Vec::new();
for child in kids.iter() {
if virtual_top_spacers.get(child).is_ok()
|| virtual_rows.get(child).is_ok()
|| virtual_bottom_spacers.get(child).is_ok()
{
to_remove.push(child);
}
}
for row in to_remove {
let mut stack = vec![row];
let mut to_despawn = Vec::new();
while let Some(e) = stack.pop() {
to_despawn.push(e);
if let Ok(kids) = children_query.get(e) {
stack.extend(kids.iter());
}
}
for e in to_despawn.into_iter().rev() {
commands.entity(e).despawn();
}
}
}
// Spawn new virtual pool.
let icon_default = icon_by_name("check").expect("embedded icon 'check' not found");
let option_text_color = theme.on_surface;
let selected_index = select.selected_index;
commands.entity(list_root).with_children(|list| {
list.spawn((
SelectVirtualTopSpacer,
Node {
height: Val::Px(0.0),
min_height: Val::Px(0.0),
flex_shrink: 0.0,
..default()
},
));
for pool_index in 0..desired_pool_size {
let (index, label) = options
.get(pool_index)
.map(|o| (pool_index, o.label.clone()))
.unwrap_or((usize::MAX, String::new()));
let is_disabled = options.get(index).is_some_and(|o| o.disabled);
let is_selected = selected_index.is_some_and(|i| i == index);
let row_bg = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
list.spawn((
SelectVirtualRow,
SelectOwner(select_entity),
SelectOptionItem {
index,
label: label.clone(),
},
Button,
Interaction::None,
Node {
height: Val::Px(SELECT_OPTION_HEIGHT),
min_height: Val::Px(SELECT_OPTION_HEIGHT),
flex_shrink: 0.0,
padding: UiRect::horizontal(Val::Px(Spacing::LARGE)),
align_items: AlignItems::Center,
column_gap: Val::Px(Spacing::MEDIUM),
..default()
},
BackgroundColor(row_bg),
))
.with_children(|row| {
row.spawn((
SelectVirtualIcon,
SelectOptionIcon,
MaterialIcon::new(icon_default)
.with_size(20.0)
.with_color(option_text_color),
Node {
display: Display::None,
..default()
},
));
row.spawn((
SelectOptionLabelText,
Text::new(label),
TextFont {
font_size: 14.0,
..default()
},
TextColor(if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
}),
));
});
}
list.spawn((
SelectVirtualBottomSpacer,
Node {
height: Val::Px(0.0),
min_height: Val::Px(0.0),
flex_shrink: 0.0,
..default()
},
));
});
}
continue;
}
// Collect current option row entities.
// Note: If the container was spawned with zero children, it won't have a `Children`
// component, so we treat a missing Children as "zero existing rows".
let existing_rows: Vec<Entity> = content_children
.get(list_root)
.map(|kids| {
kids.iter()
.filter(|e| option_rows.get(*e).is_ok())
.collect()
})
.unwrap_or_default();
if existing_rows.len() == select.options.len() {
continue;
}
// Remove old rows.
for row in existing_rows {
let mut stack = vec![row];
let mut to_despawn = Vec::new();
while let Some(e) = stack.pop() {
to_despawn.push(e);
if let Ok(kids) = children_query.get(e) {
stack.extend(kids.iter());
}
}
for e in to_despawn.into_iter().rev() {
commands.entity(e).despawn();
}
}
// Spawn new rows.
let option_text_color = theme.on_surface;
let selected_index = select.selected_index;
let options = select.options.clone();
// If this dropdown is configured with a max height, compute the viewport height
// based on the number of options so rows keep the standard height.
if let Ok(max_h) = dropdown_max_heights.get(content_entity).copied() {
if let Ok(mut node) = dropdown_content_nodes.get_mut(content_entity) {
match max_h.0 {
Val::Px(max_px) => {
// `dropdown_max_height(Px)` caps the visible *items* area, not the padding.
// This keeps the "N rows" mental model intuitive (e.g. 240px => 5 rows at 48px).
let items_px = (options.len() as f32) * SELECT_OPTION_HEIGHT;
let viewport_items_px = items_px.min(max_px);
node.height = Val::Px(SELECT_DROPDOWN_PADDING_TOTAL + viewport_items_px);
node.max_height = Val::Px(SELECT_DROPDOWN_PADDING_TOTAL + max_px);
}
other => {
// For non-pixel values we can't compute content height reliably,
// so use the configured height as the viewport height.
node.height = other;
node.max_height = other;
}
}
}
}
commands.entity(content_entity).with_children(|dropdown| {
for (index, option) in options.iter().enumerate() {
let is_disabled = option.disabled;
let is_selected = selected_index.is_some_and(|i| i == index);
let row_bg = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
dropdown
.spawn((
SelectOwner(select_entity),
SelectOptionItem {
index,
label: option.label.clone(),
},
Button,
Interaction::None,
Node {
height: Val::Px(SELECT_OPTION_HEIGHT),
min_height: Val::Px(SELECT_OPTION_HEIGHT),
flex_shrink: 0.0,
padding: UiRect::horizontal(Val::Px(Spacing::LARGE)),
align_items: AlignItems::Center,
column_gap: Val::Px(Spacing::MEDIUM),
..default()
},
BackgroundColor(row_bg),
))
.with_children(|row| {
if let Some(icon) = &option.icon {
if let Some(id) = icon_by_name(icon.as_str()) {
row.spawn((
SelectOptionIcon,
MaterialIcon::new(id).with_size(20.0).with_color(
if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
},
),
));
}
}
row.spawn((
SelectOptionLabelText,
Text::new(option.label.clone()),
TextFont {
font_size: 14.0,
..default()
},
TextColor(if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
}),
));
});
}
});
}
}
/// Keep dropdown visibility + displayed text in sync with `MaterialSelect`.
fn select_dropdown_sync_system(
mut selects: Query<(Entity, &MaterialSelect, &Children), Changed<MaterialSelect>>,
mut dropdowns: Query<&mut Visibility, With<SelectDropdown>>,
mut display_texts: Query<&mut Text, (With<SelectDisplayText>, Without<SelectOptionLabelText>)>,
mut option_rows: Query<(&SelectOwner, &mut SelectOptionItem, &Children)>,
mut option_labels: Query<&mut Text, (With<SelectOptionLabelText>, Without<SelectDisplayText>)>,
) {
for (select_entity, select, children) in selects.iter_mut() {
// Update dropdown visibility
for child in children.iter() {
if let Ok(mut vis) = dropdowns.get_mut(child) {
*vis = if select.open {
Visibility::Inherited
} else {
Visibility::Hidden
};
}
}
// Update displayed text
let placeholder = select.label.as_deref().unwrap_or("");
let display = select
.selected_option()
.map(|o| o.label.as_str())
.unwrap_or(placeholder);
for child in children.iter() {
if let Ok(mut text) = display_texts.get_mut(child) {
*text = Text::new(display);
}
}
// Update option row labels in the dropdown.
for (owner, mut option_item, row_children) in option_rows.iter_mut() {
if owner.0 != select_entity {
continue;
}
let Some(opt) = select.options.get(option_item.index) else {
continue;
};
if option_item.label != opt.label {
option_item.label = opt.label.clone();
}
for child in row_children.iter() {
if let Ok(mut text) = option_labels.get_mut(child) {
*text = Text::new(opt.label.clone());
}
}
}
}
}
/// Handle clicks on option items.
fn select_option_interaction_system(
mut interactions: Query<(&Interaction, &SelectOptionItem, &SelectOwner), Changed<Interaction>>,
mut selects: Query<(Entity, &mut MaterialSelect)>,
mut events: MessageWriter<SelectChangeEvent>,
) {
for (interaction, option_item, owner) in interactions.iter_mut() {
if *interaction != Interaction::Pressed {
continue;
}
let Ok((select_entity, mut select)) = selects.get_mut(owner.0) else {
continue;
};
// Ignore disabled options
let Some(option) = select.options.get(option_item.index).cloned() else {
continue;
};
if option.disabled {
continue;
}
select.selected_index = Some(option_item.index);
select.open = false;
select.focused = true;
events.write(SelectChangeEvent {
entity: select_entity,
index: option_item.index,
option,
});
}
}
// (no icon font system; icons are embedded bitmaps)
// ============================================================================
// Spawn Traits for ChildSpawnerCommands
// ============================================================================
/// Extension trait to spawn Material selects as children
pub trait SpawnSelectChild {
/// Spawn a filled select
fn spawn_filled_select(
&mut self,
theme: &MaterialTheme,
label: impl Into<String>,
options: Vec<SelectOption>,
);
/// Spawn an outlined select
fn spawn_outlined_select(
&mut self,
theme: &MaterialTheme,
label: impl Into<String>,
options: Vec<SelectOption>,
);
/// Spawn a select with full builder control
fn spawn_select_with(&mut self, theme: &MaterialTheme, builder: SelectBuilder);
}
impl SpawnSelectChild for ChildSpawnerCommands<'_> {
fn spawn_filled_select(
&mut self,
theme: &MaterialTheme,
label: impl Into<String>,
options: Vec<SelectOption>,
) {
self.spawn_select_with(theme, SelectBuilder::new(options).label(label).filled());
}
fn spawn_outlined_select(
&mut self,
theme: &MaterialTheme,
label: impl Into<String>,
options: Vec<SelectOption>,
) {
self.spawn_select_with(theme, SelectBuilder::new(options).label(label).outlined());
}
fn spawn_select_with(&mut self, theme: &MaterialTheme, builder: SelectBuilder) {
let label_color = builder.select.label_color(theme);
let text_color = builder.select.text_color(theme);
let option_text_color = theme.on_surface;
let dropdown_max_height = builder.dropdown_max_height;
let dropdown_virtualize = builder.dropdown_virtualize;
// Clone options for building the dropdown list
let options = builder.select.options.clone();
let selected_index = builder.select.selected_index;
let placeholder = if builder.select.label.is_some() {
builder.select.label.clone().unwrap_or_default()
} else if builder.localization.label_key.is_some() {
// Let `select_localization_system` resolve the placeholder without flashing a hard-coded string.
String::new()
} else {
"Select".to_string()
};
let mut select_entity_commands = self.spawn(builder.build(theme));
let select_entity = select_entity_commands.id();
select_entity_commands.with_children(|select| {
// Display text
let display_label = selected_index
.and_then(|idx| options.get(idx))
.map(|o| o.label.as_str())
.unwrap_or(placeholder.as_str());
select.spawn((
SelectDisplayText,
Text::new(display_label),
TextFont {
font_size: 16.0,
..default()
},
TextColor(text_color),
Node {
flex_grow: 1.0,
..default()
},
));
// Dropdown arrow
select.spawn((
SelectDropdownArrow,
MaterialIcon::from_name(ICON_EXPAND_MORE)
.expect("embedded icon 'expand_more' not found")
.with_size(20.0)
.with_color(label_color),
));
// Dropdown list (hidden by default)
select
.spawn((
SelectDropdown,
Visibility::Hidden,
// Ensure the dropdown renders above later siblings (e.g. code blocks).
// NOTE: Dialog scrims in this project use `GlobalZIndex(1000)`.
// If the dropdown is promoted to a root node by `GlobalZIndex`, it must
// be above modal overlays, otherwise it will render "behind" dialogs.
GlobalZIndex(1100),
Node {
position_type: PositionType::Absolute,
top: Val::Px(SELECT_HEIGHT + 4.0),
left: Val::Px(0.0),
width: Val::Percent(100.0),
border_radius: BorderRadius::all(Val::Px(8.0)),
// The outer node draws the dropdown surface.
..default()
},
BackgroundColor(theme.surface_container),
))
.with_children(|dropdown| {
// Content container. Option rows are spawned under this child.
// If `dropdown_max_height` is set, this becomes a scroll container.
let mut virtual_pool_size: Option<usize> = None;
let mut content = if let Some(max_height) = dropdown_max_height {
let viewport_height = match max_height {
Val::Px(max_px) => {
let items_px = (options.len() as f32) * SELECT_OPTION_HEIGHT;
let viewport_items_px = items_px.min(max_px);
Val::Px(SELECT_DROPDOWN_PADDING_TOTAL + viewport_items_px)
}
other => other,
};
// Virtualization is only supported for pixel max heights and only makes sense
// when the dropdown needs to scroll.
let wants_virtualize = dropdown_virtualize
&& matches!(max_height, Val::Px(_))
&& (options.len() as f32 * SELECT_OPTION_HEIGHT)
> match max_height {
Val::Px(px) => px,
_ => f32::INFINITY,
};
if wants_virtualize {
let pool_size = match viewport_height {
Val::Px(viewport_px) => {
// Count visible rows based on the items area (excluding padding).
let available_for_rows =
(viewport_px - SELECT_DROPDOWN_PADDING_TOTAL).max(0.0);
let visible =
(available_for_rows / SELECT_OPTION_HEIGHT).ceil() as usize;
(visible + 2).max(1)
}
_ => 12,
};
virtual_pool_size = Some(pool_size);
dropdown.spawn((
SelectDropdownContent,
SelectDropdownMaxHeight(max_height),
SelectDropdownVirtualized { pool_size },
SelectOwner(select_entity),
ScrollContainer::vertical(),
ScrollPosition::default(),
Node {
width: Val::Percent(100.0),
height: viewport_height,
max_height,
overflow: Overflow::scroll_y(),
flex_direction: FlexDirection::Column,
padding: UiRect::vertical(Val::Px(SELECT_DROPDOWN_PADDING_Y)),
..default()
},
))
} else {
dropdown.spawn((
SelectDropdownContent,
SelectDropdownMaxHeight(max_height),
ScrollContainer::vertical(),
ScrollPosition::default(),
Node {
width: Val::Percent(100.0),
height: viewport_height,
max_height,
overflow: Overflow::scroll_y(),
flex_direction: FlexDirection::Column,
padding: UiRect::vertical(Val::Px(SELECT_DROPDOWN_PADDING_Y)),
..default()
},
))
}
} else {
dropdown.spawn((
SelectDropdownContent,
Node {
width: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
padding: UiRect::vertical(Val::Px(8.0)),
..default()
},
))
};
// Virtualized dropdown: fixed pool of rows + spacers.
if let Some(pool_size) = virtual_pool_size {
let icon_default =
icon_by_name("check").expect("embedded icon 'check' not found");
content.with_children(|list| {
list.spawn((
SelectVirtualTopSpacer,
Node {
height: Val::Px(0.0),
min_height: Val::Px(0.0),
flex_shrink: 0.0,
..default()
},
));
for pool_index in 0..pool_size {
let (index, label) = options
.get(pool_index)
.map(|o| (pool_index, o.label.clone()))
.unwrap_or((usize::MAX, String::new()));
let is_disabled = options.get(index).is_some_and(|o| o.disabled);
let is_selected = selected_index.is_some_and(|i| i == index);
let row_bg = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
list.spawn((
SelectVirtualRow,
SelectOwner(select_entity),
SelectOptionItem {
index,
label: label.clone(),
},
Button,
Interaction::None,
Node {
height: Val::Px(SELECT_OPTION_HEIGHT),
min_height: Val::Px(SELECT_OPTION_HEIGHT),
flex_shrink: 0.0,
padding: UiRect::horizontal(Val::Px(Spacing::LARGE)),
align_items: AlignItems::Center,
column_gap: Val::Px(Spacing::MEDIUM),
..default()
},
BackgroundColor(row_bg),
))
.with_children(|row| {
// Virtual icon placeholder. We'll toggle display based on the option.
row.spawn((
SelectVirtualIcon,
SelectOptionIcon,
MaterialIcon::new(icon_default)
.with_size(20.0)
.with_color(option_text_color),
Node {
display: Display::None,
..default()
},
));
row.spawn((
SelectOptionLabelText,
Text::new(label),
TextFont {
font_size: 14.0,
..default()
},
TextColor(if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
}),
));
});
}
list.spawn((
SelectVirtualBottomSpacer,
Node {
height: Val::Px(0.0),
min_height: Val::Px(0.0),
flex_shrink: 0.0,
..default()
},
));
});
} else {
// Non-virtualized: spawn every option row.
content.with_children(|dropdown| {
for (index, option) in options.iter().enumerate() {
let is_disabled = option.disabled;
let is_selected = selected_index.is_some_and(|i| i == index);
let row_bg = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
dropdown
.spawn((
SelectOwner(select_entity),
SelectOptionItem {
index,
label: option.label.clone(),
},
Button,
Interaction::None,
Node {
height: Val::Px(SELECT_OPTION_HEIGHT),
min_height: Val::Px(SELECT_OPTION_HEIGHT),
flex_shrink: 0.0,
padding: UiRect::horizontal(Val::Px(Spacing::LARGE)),
align_items: AlignItems::Center,
column_gap: Val::Px(Spacing::MEDIUM),
..default()
},
BackgroundColor(row_bg),
))
.with_children(|row| {
// Optional leading icon
if let Some(icon) = &option.icon {
if let Some(id) = icon_by_name(icon.as_str()) {
row.spawn((
SelectOptionIcon,
MaterialIcon::new(id)
.with_size(20.0)
.with_color(if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
}),
));
}
}
row.spawn((
SelectOptionLabelText,
Text::new(option.label.clone()),
TextFont {
font_size: 14.0,
..default()
},
TextColor(if is_disabled {
option_text_color.with_alpha(0.38)
} else {
option_text_color
}),
));
});
}
});
}
});
});
}
}
/// Update virtualized dropdown rows based on scroll position.
fn select_dropdown_virtualization_system(
theme: Option<Res<MaterialTheme>>,
selects: Query<&MaterialSelect>,
children_query: Query<&Children>,
is_scroll_content: Query<(), With<ScrollContent>>,
mut contents: Query<
(
Entity,
&SelectOwner,
&SelectDropdownVirtualized,
&ScrollPosition,
&Children,
),
With<SelectDropdownContent>,
>,
mut nodes: ParamSet<(
Query<&mut Node, With<SelectVirtualTopSpacer>>,
Query<&mut Node, With<SelectVirtualBottomSpacer>>,
Query<
(
&mut Node,
&mut SelectOptionItem,
&mut BackgroundColor,
&Children,
),
With<SelectVirtualRow>,
>,
Query<(&mut MaterialIcon, &mut Node), With<SelectVirtualIcon>>,
)>,
mut label_texts: Query<(&mut Text, &mut TextColor), With<SelectOptionLabelText>>,
) {
let Some(theme) = theme else { return };
for (content_entity, owner, virt, scroll_pos, content_children) in contents.iter_mut() {
let Ok(select) = selects.get(owner.0) else {
continue;
};
if !select.open {
continue;
}
// Find the actual list root. For ScrollContainers, children are moved under ScrollContent.
let mut list_root = content_entity;
if let Some(wrapper) = content_children
.iter()
.find(|c| is_scroll_content.get(*c).is_ok())
{
list_root = wrapper;
}
let Ok(list_children) = children_query.get(list_root) else {
continue;
};
let options_len = select.options.len();
let pool_size = virt.pool_size.max(1);
// Account for the dropdown's internal vertical padding.
let scroll_y = (scroll_pos.y - SELECT_DROPDOWN_PADDING_Y).max(0.0);
let mut start_index = (scroll_y / SELECT_OPTION_HEIGHT).floor() as usize;
if options_len > pool_size {
start_index = start_index.min(options_len - pool_size);
} else {
start_index = 0;
}
let top_px = (start_index as f32) * SELECT_OPTION_HEIGHT;
let bottom_px =
(options_len.saturating_sub(start_index + pool_size) as f32) * SELECT_OPTION_HEIGHT;
// Update spacers.
{
let mut top_spacers = nodes.p0();
for child in list_children.iter() {
if let Ok(mut node) = top_spacers.get_mut(child) {
node.height = Val::Px(top_px);
node.min_height = Val::Px(top_px);
}
}
}
{
let mut bottom_spacers = nodes.p1();
for child in list_children.iter() {
if let Ok(mut node) = bottom_spacers.get_mut(child) {
node.height = Val::Px(bottom_px);
node.min_height = Val::Px(bottom_px);
}
}
}
// Update row pool.
let base_text = theme.on_surface;
let mut row_i = 0usize;
for child in list_children.iter() {
// First pass: update the row container + label text. Capture row children so we can
// update icons in a second pass without conflicting ParamSet borrows.
let (row_children_entities, icon_name, text_color) = {
let mut row_query = nodes.p2();
let Ok((mut row_node, mut item, mut row_bg, row_children)) =
row_query.get_mut(child)
else {
continue;
};
let idx = start_index + row_i;
row_i += 1;
if idx >= options_len {
row_node.display = Display::None;
item.index = usize::MAX;
item.label.clear();
(Vec::new(), None, base_text)
} else {
row_node.display = Display::Flex;
let opt = &select.options[idx];
item.index = idx;
if item.label != opt.label {
item.label = opt.label.clone();
}
let is_disabled = opt.disabled;
let is_selected = select.selected_index.is_some_and(|i| i == idx);
row_bg.0 = if is_selected {
theme.secondary_container
} else {
Color::NONE
};
let text_color = if is_disabled {
base_text.with_alpha(0.38)
} else {
base_text
};
for row_child in row_children.iter() {
if let Ok((mut text, mut color)) = label_texts.get_mut(row_child) {
*text = Text::new(opt.label.clone());
color.0 = text_color;
}
}
(
row_children.iter().collect::<Vec<_>>(),
opt.icon.as_deref().map(|s| s.to_string()),
text_color,
)
}
};
// Second pass: update icons.
if !row_children_entities.is_empty() {
let mut icon_query = nodes.p3();
for row_child in row_children_entities {
if let Ok((mut icon, mut icon_node)) = icon_query.get_mut(row_child) {
if let Some(name) = icon_name.as_deref() {
if let Some(id) = icon_by_name(name) {
icon.id = id;
icon.color = text_color;
icon_node.display = Display::Flex;
} else {
icon_node.display = Display::None;
}
} else {
icon_node.display = Display::None;
}
}
}
}
if row_i >= pool_size {
break;
}
}
}
}