1use std::time::Duration;
4
5use crate::{Element, anim};
6use iced_core::renderer::{self, Renderer};
7use iced_core::widget::{self, Tree, tree};
8use iced_core::{
9 Border, Clipboard, Event, Layout, Length, Pixels, Rectangle, Shell, Size, Widget, alignment,
10 layout, mouse, text, touch, window,
11};
12use iced_widget::Id;
13use iced_widget::toggler::Status;
14
15pub use iced_widget::toggler::Catalog;
16
17pub fn toggler<'a, Message>(is_checked: bool) -> Toggler<'a, Message> {
18 Toggler::new(is_checked)
19}
20#[allow(missing_debug_implementations)]
22pub struct Toggler<'a, Message> {
23 id: Id,
24 is_toggled: bool,
25 on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>,
26 label: Option<String>,
27 width: Length,
28 size: f32,
29 text_size: Option<f32>,
30 text_line_height: text::LineHeight,
31 text_alignment: text::Alignment,
32 text_shaping: text::Shaping,
33 spacing: f32,
34 font: Option<crate::font::Font>,
35 duration: Duration,
36 ellipsize: text::Ellipsize,
37}
38
39impl<'a, Message> Toggler<'a, Message> {
40 pub const DEFAULT_SIZE: f32 = 24.0;
42
43 pub fn new(is_toggled: bool) -> Self {
52 Toggler {
53 id: Id::unique(),
54 is_toggled,
55 on_toggle: None,
56 label: None,
57 width: Length::Shrink,
58 size: Self::DEFAULT_SIZE,
59 text_size: None,
60 text_line_height: text::LineHeight::default(),
61 text_alignment: text::Alignment::Left,
62 text_shaping: text::Shaping::Advanced,
63 spacing: 0.0,
64 font: None,
65 duration: Duration::from_millis(200),
66 ellipsize: text::Ellipsize::None,
67 }
68 }
69
70 pub fn size(mut self, size: impl Into<Pixels>) -> Self {
72 self.size = size.into().0;
73 self
74 }
75
76 pub fn width(mut self, width: impl Into<Length>) -> Self {
78 self.width = width.into();
79 self
80 }
81
82 pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self {
84 self.text_size = Some(text_size.into().0);
85 self
86 }
87
88 pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self {
90 self.text_line_height = line_height.into();
91 self
92 }
93
94 pub fn text_alignment(mut self, alignment: text::Alignment) -> Self {
96 self.text_alignment = alignment;
97 self
98 }
99
100 pub fn text_shaping(mut self, shaping: text::Shaping) -> Self {
102 self.text_shaping = shaping;
103 self
104 }
105
106 pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
108 self.spacing = spacing.into().0;
109 self
110 }
111
112 pub fn ellipsize(mut self, ellipsize: text::Ellipsize) -> Self {
114 self.ellipsize = ellipsize;
115 self
116 }
117
118 pub fn font(mut self, font: impl Into<crate::font::Font>) -> Self {
122 self.font = Some(font.into());
123 self
124 }
125
126 pub fn id(mut self, id: Id) -> Self {
127 self.id = id;
128 self
129 }
130
131 pub fn duration(mut self, dur: Duration) -> Self {
132 self.duration = dur;
133 self
134 }
135
136 pub fn on_toggle(mut self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self {
137 self.on_toggle = Some(Box::new(on_toggle));
138 self
139 }
140
141 pub fn on_toggle_maybe(mut self, on_toggle: Option<impl Fn(bool) -> Message + 'a>) -> Self {
142 self.on_toggle = on_toggle.map(|t| Box::new(t) as _);
143 self
144 }
145
146 pub fn label(mut self, label: impl Into<Option<String>>) -> Self {
148 self.label = label.into();
149 self
150 }
151}
152
153impl<'a, Message> Widget<Message, crate::Theme, crate::Renderer> for Toggler<'a, Message> {
154 fn size(&self) -> Size<Length> {
155 Size::new(self.width, Length::Shrink)
156 }
157
158 fn tag(&self) -> tree::Tag {
159 tree::Tag::of::<State>()
160 }
161
162 fn state(&self) -> tree::State {
163 tree::State::new(State {
164 prev_toggled: self.is_toggled,
165 ..State::default()
166 })
167 }
168
169 fn id(&self) -> Option<Id> {
170 Some(self.id.clone())
171 }
172
173 fn set_id(&mut self, id: Id) {
174 self.id = id;
175 }
176
177 fn layout(
178 &mut self,
179 tree: &mut Tree,
180 renderer: &crate::Renderer,
181 limits: &layout::Limits,
182 ) -> layout::Node {
183 let limits = limits.width(self.width);
184
185 next_to_each_other(
186 &limits,
187 self.spacing,
188 |limits| {
189 if let Some(label) = self.label.as_deref() {
190 let state = tree.state.downcast_mut::<State>();
191 let node = iced_core::widget::text::layout(
192 &mut state.text,
193 renderer,
194 limits,
195 label,
196 widget::text::Format {
197 width: self.width,
198 height: Length::Shrink,
199 line_height: self.text_line_height,
200 size: self.text_size.map(iced::Pixels),
201 font: self.font,
202 align_x: self.text_alignment,
203 align_y: alignment::Vertical::Top,
204 shaping: self.text_shaping,
205 wrapping: iced_core::text::Wrapping::default(),
206 ellipsize: self.ellipsize,
207 },
208 );
209 match self.width {
210 Length::Fill => {
211 let size = node.size();
212 layout::Node::with_children(
213 Size::new(limits.width(Length::Fill).max().width, size.height),
214 vec![node],
215 )
216 }
217 _ => node,
218 }
219 } else {
220 layout::Node::new(iced_core::Size::ZERO)
221 }
222 },
223 |_| layout::Node::new(Size::new(48., 24.)),
224 )
225 }
226
227 fn update(
228 &mut self,
229 tree: &mut Tree,
230 event: &Event,
231 layout: Layout<'_>,
232 cursor_position: mouse::Cursor,
233 _renderer: &crate::Renderer,
234 _clipboard: &mut dyn Clipboard,
235 shell: &mut Shell<'_, Message>,
236 _viewport: &Rectangle,
237 ) {
238 let Some(on_toggle) = self.on_toggle.as_ref() else {
239 return;
240 };
241 let state = tree.state.downcast_mut::<State>();
242
243 if state.prev_toggled != self.is_toggled {
245 state.anim.changed(self.duration);
246 shell.request_redraw();
247 state.prev_toggled = self.is_toggled;
248 }
249
250 match event {
251 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
252 | Event::Touch(touch::Event::FingerLifted { .. }) => {
253 let mouse_over = cursor_position.is_over(layout.bounds());
254
255 if mouse_over {
256 shell.publish((on_toggle)(!self.is_toggled));
257 state.anim.changed(self.duration);
258 state.prev_toggled = !self.is_toggled;
259 shell.capture_event();
260 }
261 }
262 Event::Window(window::Event::RedrawRequested(_now)) => {
263 state.anim.anim_done(self.duration);
264 if state.anim.last_change.is_some() {
265 shell.request_redraw();
266 }
267 }
268 Event::Mouse(mouse::Event::CursorMoved { .. }) => {
269 let toggler_bounds = layout
270 .children()
271 .nth(1)
272 .map_or_else(|| layout.bounds(), |l| l.bounds());
273 let hovered = cursor_position.is_over(toggler_bounds);
274 if state.hovered != hovered {
275 state.hovered = hovered;
276 shell.request_redraw();
277 }
278 }
279 _ => {}
280 }
281 }
282
283 fn mouse_interaction(
284 &self,
285 _state: &Tree,
286 layout: Layout<'_>,
287 cursor_position: mouse::Cursor,
288 _viewport: &Rectangle,
289 _renderer: &crate::Renderer,
290 ) -> mouse::Interaction {
291 if self.on_toggle.is_some() && cursor_position.is_over(layout.bounds()) {
292 mouse::Interaction::Pointer
293 } else {
294 mouse::Interaction::default()
295 }
296 }
297
298 fn draw(
299 &self,
300 tree: &Tree,
301 renderer: &mut crate::Renderer,
302 theme: &crate::Theme,
303 style: &renderer::Style,
304 layout: Layout<'_>,
305 cursor_position: mouse::Cursor,
306 viewport: &Rectangle,
307 ) {
308 let state = tree.state.downcast_ref::<State>();
309
310 let mut children = layout.children();
311 let label_layout = children.next().unwrap();
312
313 if let Some(_label) = &self.label {
314 let state: &State = tree.state.downcast_ref();
315 iced_widget::text::draw(
316 renderer,
317 style,
318 label_layout.bounds(),
319 state.text.raw(),
320 iced_widget::text::Style::default(),
321 viewport,
322 );
323 }
324
325 let toggler_layout = children.next().unwrap();
326 let bounds = toggler_layout.bounds();
327
328 let is_mouse_over = cursor_position.is_over(bounds);
329
330 let style = theme.style(
351 &(),
352 if self.on_toggle.is_none() {
353 Status::Disabled {
354 is_toggled: self.is_toggled,
355 }
356 } else if is_mouse_over {
357 Status::Hovered {
358 is_toggled: self.is_toggled,
359 }
360 } else {
361 Status::Active {
362 is_toggled: self.is_toggled,
363 }
364 },
365 );
366
367 let space = style.handle_margin;
368
369 let toggler_background_bounds = Rectangle {
370 x: bounds.x,
371 y: bounds.y,
372 width: bounds.width,
373 height: bounds.height,
374 };
375
376 renderer.fill_quad(
377 renderer::Quad {
378 bounds: toggler_background_bounds,
379 border: Border {
380 radius: style.border_radius,
381 ..Default::default()
382 },
383 ..renderer::Quad::default()
384 },
385 style.background,
386 );
387 let t = state.anim.t(self.duration, self.is_toggled);
388
389 let toggler_foreground_bounds = Rectangle {
390 x: bounds.x
391 + anim::slerp(
392 space,
393 bounds.width - space - (bounds.height - (2.0 * space)),
394 t,
395 ),
396
397 y: bounds.y + space,
398 width: bounds.height - (2.0 * space),
399 height: bounds.height - (2.0 * space),
400 };
401
402 renderer.fill_quad(
403 renderer::Quad {
404 bounds: toggler_foreground_bounds,
405 border: Border {
406 radius: style.handle_radius,
407 ..Default::default()
408 },
409 ..renderer::Quad::default()
410 },
411 style.foreground,
412 );
413 }
414}
415
416impl<'a, Message: 'static> From<Toggler<'a, Message>> for Element<'a, Message> {
417 fn from(toggler: Toggler<'a, Message>) -> Element<'a, Message> {
418 Element::new(toggler)
419 }
420}
421
422pub fn next_to_each_other(
424 limits: &iced::Limits,
425 spacing: f32,
426 left: impl FnOnce(&iced::Limits) -> iced_core::layout::Node,
427 right: impl FnOnce(&iced::Limits) -> iced_core::layout::Node,
428) -> iced_core::layout::Node {
429 let mut right_node = right(limits);
430 let right_size = right_node.size();
431
432 let left_limits = limits.shrink(Size::new(right_size.width + spacing, 0.0));
433 let mut left_node = left(&left_limits);
434 let left_size = left_node.size();
435
436 let (left_y, right_y) = if left_size.height > right_size.height {
437 (0.0, (left_size.height - right_size.height) / 2.0)
438 } else {
439 ((right_size.height - left_size.height) / 2.0, 0.0)
440 };
441
442 left_node = left_node.move_to(iced::Point::new(0.0, left_y));
443 right_node = right_node.move_to(iced::Point::new(left_size.width + spacing, right_y));
444
445 iced_core::layout::Node::with_children(
446 Size::new(
447 left_size.width + spacing + right_size.width,
448 left_size.height.max(right_size.height),
449 ),
450 vec![left_node, right_node],
451 )
452}
453
454#[derive(Debug, Default)]
455pub struct State {
456 text: widget::text::State<<crate::Renderer as iced_core::text::Renderer>::Paragraph>,
457 anim: anim::State,
458 prev_toggled: bool,
459 hovered: bool,
460}