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
use crate::{css, Bus, Css, Element, Length, Widget};
pub use iced_style::checkbox::{Style, StyleSheet};
use dodrio::bumpalo;
use std::rc::Rc;
#[allow(missing_debug_implementations)]
pub struct Checkbox<Message> {
is_checked: bool,
on_toggle: Rc<dyn Fn(bool) -> Message>,
label: String,
id: Option<String>,
width: Length,
style: Box<dyn StyleSheet>,
}
impl<Message> Checkbox<Message> {
pub fn new<F>(is_checked: bool, label: impl Into<String>, f: F) -> Self
where
F: 'static + Fn(bool) -> Message,
{
Checkbox {
is_checked,
on_toggle: Rc::new(f),
label: label.into(),
id: None,
width: Length::Shrink,
style: Default::default(),
}
}
pub fn width(mut self, width: Length) -> Self {
self.width = width;
self
}
pub fn style(mut self, style: impl Into<Box<dyn StyleSheet>>) -> Self {
self.style = style.into();
self
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
}
impl<Message> Widget<Message> for Checkbox<Message>
where
Message: 'static,
{
fn node<'b>(
&self,
bump: &'b bumpalo::Bump,
bus: &Bus<Message>,
style_sheet: &mut Css<'b>,
) -> dodrio::Node<'b> {
use dodrio::builder::*;
use dodrio::bumpalo::collections::String;
let checkbox_label =
String::from_str_in(&self.label, bump).into_bump_str();
let event_bus = bus.clone();
let on_toggle = self.on_toggle.clone();
let is_checked = self.is_checked;
let row_class = style_sheet.insert(bump, css::Rule::Row);
let spacing_class = style_sheet.insert(bump, css::Rule::Spacing(5));
let (label, input) = if let Some(id) = &self.id {
let id = String::from_str_in(id, bump).into_bump_str();
(label(bump).attr("for", id), input(bump).attr("id", id))
} else {
(label(bump), input(bump))
};
label
.attr(
"class",
bumpalo::format!(in bump, "{} {}", row_class, spacing_class)
.into_bump_str(),
)
.attr(
"style",
bumpalo::format!(in bump, "width: {}; align-items: center", css::length(self.width))
.into_bump_str(),
)
.children(vec![
input
.attr("type", "checkbox")
.bool_attr("checked", self.is_checked)
.on("click", move |_root, vdom, _event| {
let msg = on_toggle(!is_checked);
event_bus.publish(msg);
vdom.schedule_render();
})
.finish(),
text(checkbox_label),
])
.finish()
}
}
impl<'a, Message> From<Checkbox<Message>> for Element<'a, Message>
where
Message: 'static,
{
fn from(checkbox: Checkbox<Message>) -> Element<'a, Message> {
Element::new(checkbox)
}
}