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
use super::behaviors::MouseBehavior;
use crate::prelude::*;
static SWITCH_TRACK: &'static str = "switch_track";
static SWITCH_TOGGLE: &'static str = "switch_toggle";
#[derive(Default, AsAny)]
pub struct SwitchState {
selected: bool,
switch_toggle: Entity,
}
impl SwitchState {
fn toggle_selection(&mut self) {
self.selected = !self.selected;
}
}
impl State for SwitchState {
fn init(&mut self, _: &mut Registry, ctx: &mut Context) {
self.switch_toggle = ctx
.entity_of_child(SWITCH_TOGGLE)
.expect("SwitchState.init: Switch toggle child could not be found.");
}
fn update(&mut self, _: &mut Registry, ctx: &mut Context<'_>) {
if *ctx.widget().get::<bool>("selected") == self.selected {
return;
}
ctx.widget().set("selected", self.selected);
let element = ctx.widget().clone::<Selector>("selector").element.unwrap();
if let Some(parent) = ctx.parent_entity_by_element(&*element) {
ctx.get_widget(parent).update_theme_by_state(false);
}
{
let mut switch_toggle = ctx.get_widget(self.switch_toggle);
if self.selected {
switch_toggle.set("horizontal_alignment", Alignment::from("end"));
add_selector_to_widget("selected", &mut switch_toggle);
} else {
switch_toggle.set("horizontal_alignment", Alignment::from("start"));
remove_selector_from_widget("selected", &mut switch_toggle);
}
switch_toggle.update_theme_by_state(true);
}
ctx.push_event_strategy_by_entity(
ChangedEvent(ctx.entity),
ctx.entity,
EventStrategy::Direct,
);
ctx.get_widget(self.switch_toggle)
.update_theme_by_state(false);
}
}
widget!(
Switch<SwitchState>: MouseHandler {
background: Brush,
border_radius: f64,
border_width: Thickness,
border_brush: Brush,
padding: Thickness,
pressed: bool,
selected: bool
}
);
impl Template for Switch {
fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
self.name("Switch")
.element("switch")
.pressed(false)
.selected(false)
.width(36.0)
.height(30.0)
.border_radius(8.0)
.border_width(1.0)
.padding(4.0)
.child(
MouseBehavior::create()
.pressed(id)
.enabled(id)
.target(id.0)
.on_click(move |states, _| {
states.get_mut::<SwitchState>(id).toggle_selection();
false
})
.child(
Grid::create()
.child(
Container::create()
.element(SWITCH_TRACK)
.vertical_alignment("center")
.build(ctx),
)
.child(
Container::create()
.element(SWITCH_TOGGLE)
.id(SWITCH_TOGGLE)
.vertical_alignment("center")
.horizontal_alignment("start")
.width(20.0)
.height(20.0)
.border_radius(10.0)
.build(ctx),
)
.build(ctx),
)
.build(ctx),
)
}
}