forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstandard_widgets.rs
More file actions
755 lines (711 loc) · 23.4 KB
/
standard_widgets.rs
File metadata and controls
755 lines (711 loc) · 23.4 KB
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
//! This experimental example illustrates how to create widgets using the `bevy_ui_widgets` widget set.
//!
//! These widgets have no inherent styling, so this example also shows how to implement custom styles.
//!
//! The patterns shown here are likely to change substantially as the `bevy_ui_widgets` crate
//! matures, so please exercise caution if you are using this as a reference for your own code,
//! and note that there are still "user experience" issues with this API.
use bevy::{
color::palettes::basic::*,
input_focus::{
tab_navigation::{TabGroup, TabIndex, TabNavigationPlugin},
InputDispatchPlugin,
},
picking::hover::Hovered,
prelude::*,
ui::{Checked, InteractionDisabled, Pressed},
ui_widgets::{
checkbox_self_update, observe, Activate, Button, Checkbox, CoreSliderDragState,
RadioButton, RadioGroup, Slider, SliderRange, SliderThumb, SliderValue, TrackClick,
UiWidgetsPlugins, ValueChange,
},
};
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
UiWidgetsPlugins,
InputDispatchPlugin,
TabNavigationPlugin,
))
.insert_resource(DemoWidgetStates {
slider_value: 50.0,
slider_click: TrackClick::Snap,
})
.add_systems(Startup, setup)
.add_systems(
Update,
(
update_widget_values,
update_button_style,
update_button_style2,
update_slider_style.after(update_widget_values),
update_slider_style2.after(update_widget_values),
update_checkbox_or_radio_style.after(update_widget_values),
update_checkbox_or_radio_style2.after(update_widget_values),
toggle_disabled,
),
)
.run();
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
const SLIDER_TRACK: Color = Color::srgb(0.05, 0.05, 0.05);
const SLIDER_THUMB: Color = Color::srgb(0.35, 0.75, 0.35);
const ELEMENT_OUTLINE: Color = Color::srgb(0.45, 0.45, 0.45);
const ELEMENT_FILL: Color = Color::srgb(0.35, 0.75, 0.35);
const ELEMENT_FILL_DISABLED: Color = Color::srgb(0.5019608, 0.5019608, 0.5019608);
/// Marker which identifies buttons with a particular style, in this case the "Demo style".
#[derive(Component)]
struct DemoButton;
/// Marker which identifies sliders with a particular style.
#[derive(Component, Default)]
struct DemoSlider;
/// Marker which identifies the slider's thumb element.
#[derive(Component, Default)]
struct DemoSliderThumb;
/// Marker which identifies checkboxes with a particular style.
#[derive(Component, Default)]
struct DemoCheckbox;
/// Marker which identifies a styled radio button. We'll use this to change the track click
/// behavior.
#[derive(Component, Default)]
struct DemoRadio(TrackClick);
/// A struct to hold the state of various widgets shown in the demo.
///
/// While it is possible to use the widget's own state components as the source of truth,
/// in many cases widgets will be used to display dynamic data coming from deeper within the app,
/// using some kind of data-binding. This example shows how to maintain an external source of
/// truth for widget states.
#[derive(Resource)]
struct DemoWidgetStates {
slider_value: f32,
slider_click: TrackClick,
}
/// Update the widget states based on the changing resource.
fn update_widget_values(
res: Res<DemoWidgetStates>,
mut sliders: Query<(Entity, &mut Slider), With<DemoSlider>>,
radios: Query<(Entity, &DemoRadio, Has<Checked>)>,
mut commands: Commands,
) {
if res.is_changed() {
for (slider_ent, mut slider) in sliders.iter_mut() {
commands
.entity(slider_ent)
.insert(SliderValue(res.slider_value));
slider.track_click = res.slider_click;
}
for (radio_id, radio_value, checked) in radios.iter() {
let will_be_checked = radio_value.0 == res.slider_click;
if will_be_checked != checked {
if will_be_checked {
commands.entity(radio_id).insert(Checked);
} else {
commands.entity(radio_id).remove::<Checked>();
}
}
}
}
}
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
// ui camera
commands.spawn(Camera2d);
commands.spawn(demo_root(&assets));
}
fn demo_root(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: px(10),
..default()
},
TabGroup::default(),
children![
(
button(asset_server),
observe(|_activate: On<Activate>| {
info!("Button clicked!");
}),
),
(
slider(0.0, 100.0, 50.0),
observe(
|value_change: On<ValueChange<f32>>,
mut widget_states: ResMut<DemoWidgetStates>| {
widget_states.slider_value = value_change.value;
},
)
),
(
checkbox(asset_server, "Checkbox"),
observe(checkbox_self_update)
),
(
radio_group(asset_server),
observe(
|value_change: On<ValueChange<Entity>>,
mut widget_states: ResMut<DemoWidgetStates>,
q_radios: Query<&DemoRadio>| {
if let Ok(radio) = q_radios.get(value_change.value) {
widget_states.slider_click = radio.0;
}
},
)
),
Text::new("Press 'D' to toggle widget disabled states"),
],
)
}
fn button(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: px(150),
height: px(65),
border: UiRect::all(px(5)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
DemoButton,
Button,
Hovered::default(),
TabIndex(0),
BorderColor::all(Color::BLACK),
BorderRadius::MAX,
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Button"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)],
)
}
fn update_button_style(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
(
Or<(
Changed<Pressed>,
Changed<Hovered>,
Added<InteractionDisabled>,
)>,
With<DemoButton>,
),
>,
mut text_query: Query<&mut Text>,
) {
for (pressed, hovered, disabled, mut color, mut border_color, children) in &mut buttons {
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
}
/// Supplementary system to detect removed marker components
fn update_button_style2(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut removed_depressed: RemovedComponents<Pressed>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
mut text_query: Query<&mut Text>,
) {
removed_depressed
.read()
.chain(removed_disabled.read())
.for_each(|entity| {
if let Ok((pressed, hovered, disabled, mut color, mut border_color, children)) =
buttons.get_mut(entity)
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
});
}
fn set_button_style(
disabled: bool,
hovered: bool,
pressed: bool,
color: &mut BackgroundColor,
border_color: &mut BorderColor,
text: &mut Text,
) {
match (disabled, hovered, pressed) {
// Disabled button
(true, _, _) => {
**text = "Disabled".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(GRAY);
}
// Pressed and hovered button
(false, true, true) => {
**text = "Press".to_string();
*color = PRESSED_BUTTON.into();
border_color.set_all(RED);
}
// Hovered, unpressed button
(false, true, false) => {
**text = "Hover".to_string();
*color = HOVERED_BUTTON.into();
border_color.set_all(WHITE);
}
// Unhovered button (either pressed or not).
(false, false, _) => {
**text = "Button".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(BLACK);
}
}
}
/// Create a demo slider
fn slider(min: f32, max: f32, value: f32) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Stretch,
justify_items: JustifyItems::Center,
column_gap: px(4),
height: px(12),
width: percent(30),
..default()
},
Name::new("Slider"),
Hovered::default(),
DemoSlider,
Slider {
track_click: TrackClick::Snap,
},
SliderValue(value),
SliderRange::new(min, max),
TabIndex(0),
Children::spawn((
// Slider background rail
Spawn((
Node {
height: px(6),
..default()
},
BackgroundColor(SLIDER_TRACK), // Border color for the slider
BorderRadius::all(px(3)),
)),
// Invisible track to allow absolute placement of thumb entity. This is narrower than
// the actual slider, which allows us to position the thumb entity using simple
// percentages, without having to measure the actual width of the slider thumb.
Spawn((
Node {
display: Display::Flex,
position_type: PositionType::Absolute,
left: px(0),
// Track is short by 12px to accommodate the thumb.
right: px(12),
top: px(0),
bottom: px(0),
..default()
},
children![(
// Thumb
DemoSliderThumb,
SliderThumb,
Node {
display: Display::Flex,
width: px(12),
height: px(12),
position_type: PositionType::Absolute,
left: percent(0), // This will be updated by the slider's value
..default()
},
BorderRadius::MAX,
BackgroundColor(SLIDER_THUMB),
)],
)),
)),
)
}
/// Update the visuals of the slider based on the slider state.
fn update_slider_style(
sliders: Query<
(
Entity,
&SliderValue,
&SliderRange,
&Hovered,
&CoreSliderDragState,
Has<InteractionDisabled>,
),
(
Or<(
Changed<SliderValue>,
Changed<SliderRange>,
Changed<Hovered>,
Changed<CoreSliderDragState>,
Added<InteractionDisabled>,
)>,
With<DemoSlider>,
),
>,
children: Query<&Children>,
mut thumbs: Query<(&mut Node, &mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>,
) {
for (slider_ent, value, range, hovered, drag_state, disabled) in sliders.iter() {
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_node, mut thumb_bg, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_node.left = percent(range.thumb_position(value.0) * 100.0);
thumb_bg.0 = thumb_color(disabled, hovered.0 | drag_state.dragging);
}
}
}
}
fn update_slider_style2(
sliders: Query<
(
Entity,
&Hovered,
&CoreSliderDragState,
Has<InteractionDisabled>,
),
With<DemoSlider>,
>,
children: Query<&Children>,
mut thumbs: Query<(&mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
) {
removed_disabled.read().for_each(|entity| {
if let Ok((slider_ent, hovered, drag_state, disabled)) = sliders.get(entity) {
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_bg, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_bg.0 = thumb_color(disabled, hovered.0 | drag_state.dragging);
}
}
}
});
}
fn thumb_color(disabled: bool, hovered: bool) -> Color {
match (disabled, hovered) {
(true, _) => ELEMENT_FILL_DISABLED,
(false, true) => SLIDER_THUMB.lighter(0.3),
_ => SLIDER_THUMB,
}
}
/// Create a demo checkbox
fn checkbox(asset_server: &AssetServer, caption: &str) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
column_gap: px(4),
..default()
},
Name::new("Checkbox"),
Hovered::default(),
DemoCheckbox,
Checkbox,
TabIndex(0),
Children::spawn((
Spawn((
// Checkbox outer
Node {
display: Display::Flex,
width: px(16),
height: px(16),
border: UiRect::all(px(2)),
..default()
},
BorderColor::all(ELEMENT_OUTLINE), // Border color for the checkbox
BorderRadius::all(px(3)),
children![
// Checkbox inner
(
Node {
display: Display::Flex,
width: px(8),
height: px(8),
position_type: PositionType::Absolute,
left: px(2),
top: px(2),
..default()
},
BackgroundColor(ELEMENT_FILL),
),
],
)),
Spawn((
Text::new(caption),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 20.0,
..default()
},
)),
)),
)
}
// Update the element's styles.
fn update_checkbox_or_radio_style(
mut q_checkbox: Query<
(Has<Checked>, &Hovered, Has<InteractionDisabled>, &Children),
(
Or<(With<DemoCheckbox>, With<DemoRadio>)>,
Or<(
Added<DemoCheckbox>,
Changed<Hovered>,
Added<Checked>,
Added<InteractionDisabled>,
)>,
),
>,
mut q_border_color: Query<
(&mut BorderColor, &mut Children),
(Without<DemoCheckbox>, Without<DemoRadio>),
>,
mut q_bg_color: Query<&mut BackgroundColor, (Without<DemoCheckbox>, Without<Children>)>,
) {
for (checked, Hovered(is_hovering), is_disabled, children) in q_checkbox.iter_mut() {
let Some(border_id) = children.first() else {
continue;
};
let Ok((mut border_color, border_children)) = q_border_color.get_mut(*border_id) else {
continue;
};
let Some(mark_id) = border_children.first() else {
warn!("Checkbox does not have a mark entity.");
continue;
};
let Ok(mut mark_bg) = q_bg_color.get_mut(*mark_id) else {
warn!("Checkbox mark entity lacking a background color.");
continue;
};
set_checkbox_or_radio_style(
is_disabled,
*is_hovering,
checked,
&mut border_color,
&mut mark_bg,
);
}
}
fn update_checkbox_or_radio_style2(
mut q_checkbox: Query<
(Has<Checked>, &Hovered, Has<InteractionDisabled>, &Children),
Or<(With<DemoCheckbox>, With<DemoRadio>)>,
>,
mut q_border_color: Query<
(&mut BorderColor, &mut Children),
(Without<DemoCheckbox>, Without<DemoRadio>),
>,
mut q_bg_color: Query<
&mut BackgroundColor,
(Without<DemoCheckbox>, Without<DemoRadio>, Without<Children>),
>,
mut removed_checked: RemovedComponents<Checked>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
) {
removed_checked
.read()
.chain(removed_disabled.read())
.for_each(|entity| {
if let Ok((checked, Hovered(is_hovering), is_disabled, children)) =
q_checkbox.get_mut(entity)
{
let Some(border_id) = children.first() else {
return;
};
let Ok((mut border_color, border_children)) = q_border_color.get_mut(*border_id)
else {
return;
};
let Some(mark_id) = border_children.first() else {
warn!("Checkbox does not have a mark entity.");
return;
};
let Ok(mut mark_bg) = q_bg_color.get_mut(*mark_id) else {
warn!("Checkbox mark entity lacking a background color.");
return;
};
set_checkbox_or_radio_style(
is_disabled,
*is_hovering,
checked,
&mut border_color,
&mut mark_bg,
);
}
});
}
fn set_checkbox_or_radio_style(
disabled: bool,
hovering: bool,
checked: bool,
border_color: &mut BorderColor,
mark_bg: &mut BackgroundColor,
) {
let color: Color = if disabled {
// If the element is disabled, use a lighter color
ELEMENT_OUTLINE.with_alpha(0.2)
} else if hovering {
// If hovering, use a lighter color
ELEMENT_OUTLINE.lighter(0.2)
} else {
// Default color for the element
ELEMENT_OUTLINE
};
// Update the background color of the element
border_color.set_all(color);
let mark_color: Color = match (disabled, checked) {
(true, true) => ELEMENT_FILL_DISABLED,
(false, true) => ELEMENT_FILL,
(_, false) => Srgba::NONE.into(),
};
if mark_bg.0 != mark_color {
// Update the color of the element
mark_bg.0 = mark_color;
}
}
/// Create a demo radio group
fn radio_group(asset_server: &AssetServer) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
align_items: AlignItems::Start,
column_gap: px(4),
..default()
},
Name::new("RadioGroup"),
RadioGroup,
TabIndex::default(),
children![
(radio(asset_server, TrackClick::Drag, "Slider Drag"),),
(radio(asset_server, TrackClick::Step, "Slider Step"),),
(radio(asset_server, TrackClick::Snap, "Slider Snap"),)
],
)
}
/// Create a demo radio button
fn radio(asset_server: &AssetServer, value: TrackClick, caption: &str) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
column_gap: px(4),
..default()
},
Name::new("RadioButton"),
Hovered::default(),
DemoRadio(value),
RadioButton,
Children::spawn((
Spawn((
// Radio outer
Node {
display: Display::Flex,
width: px(16),
height: px(16),
border: UiRect::all(px(2)),
..default()
},
BorderColor::all(ELEMENT_OUTLINE), // Border color for the radio button
BorderRadius::MAX,
children![
// Radio inner
(
Node {
display: Display::Flex,
width: px(8),
height: px(8),
position_type: PositionType::Absolute,
left: px(2),
top: px(2),
..default()
},
BorderRadius::MAX,
BackgroundColor(ELEMENT_FILL),
),
],
)),
Spawn((
Text::new(caption),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 20.0,
..default()
},
)),
)),
)
}
fn toggle_disabled(
input: Res<ButtonInput<KeyCode>>,
mut interaction_query: Query<
(Entity, Has<InteractionDisabled>),
Or<(
With<Button>,
With<Slider>,
With<Checkbox>,
With<RadioButton>,
)>,
>,
mut commands: Commands,
) {
if input.just_pressed(KeyCode::KeyD) {
for (entity, disabled) in &mut interaction_query {
if disabled {
info!("Widget enabled");
commands.entity(entity).remove::<InteractionDisabled>();
} else {
info!("Widget disabled");
commands.entity(entity).insert(InteractionDisabled);
}
}
}
}