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
use std::cell::Cell;
use super::behaviors::MouseBehavior;
use crate::prelude::*;
#[derive(Default)]
pub struct SwitchState {
selected: Cell<bool>,
}
impl SwitchState {
fn toggle_selection(&self) {
self.selected.set(!self.selected.get());
}
}
impl State for SwitchState {
fn update(&self, ctx: &mut Context<'_>) {
if *ctx.widget().get::<bool>("selected") == self.selected.get() {
return;
}
ctx.widget().set("selected", self.selected.get());
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.child("switch_toggle");
if self.selected.get() {
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);
}
let entity = ctx.entity_of_child("switch_toggle").unwrap();
ctx.get_widget(entity).update_theme_by_state(false);
}
}
widget!(
Switch<SwitchState>: MouseHandler {
background: Brush,
border_radius: f64,
border_width: Thickness,
border_brush: Brush,
padding: Thickness,
selector: Selector,
pressed: bool,
selected: bool
}
);
impl Template for Switch {
fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
let state = self.clone_state();
self.name("Switch")
.selector("switch")
.pressed(false)
.selected(false)
.width(56.0)
.height(32.0)
.border_brush(colors::BOMBAY_COLOR)
.background(colors::SLATE_GRAY_COLOR)
.border_radius(2.0)
.border_width(1.0)
.padding(4.0)
.child(
MouseBehavior::create()
.pressed(id)
.enabled(id)
.selector(id)
.on_click(move |_| {
state.toggle_selection();
false
})
.child(
Container::create()
.background(id)
.border_radius(id)
.border_width(id)
.border_brush(id)
.padding(id)
.child(
Grid::create()
.child(Container::create().size(24.0, 24.0).build(ctx))
.border_radius(1.0)
.selector(Selector::from("switch-toggle").id("switch_toggle"))
.vertical_alignment("center")
.horizontal_alignment("start")
.build(ctx),
)
.build(ctx),
)
.build(ctx),
)
}
}