1use crate::{
8 BackgroundSizing, Brush, ColumnDefinition, CommonState, ControlBorder, ControlStates,
9 FocusVisual, Grid, GridCell, GridLength, HorizontalAlignment, RowDefinition, Theme,
10 ThemeResources, control_text_style,
11};
12use std::{any::TypeId, fmt, rc::Rc, time::Duration};
13use waft_animation::{Cubic, Curve};
14use waft_embedder::{Clip, Color, FontWeight};
15use waft_foundation::{App, Handle, Listener, Ref};
16use waft_gestures::{
17 DragDownDetails, DragEndDetails, DragGestureRecognizer, DragStartBehavior, DragUpdateDetails,
18 HorizontalDragGestureRecognizer,
19};
20use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, TextStyle};
21use waft_rendering::{BoxConstraints, HitTestBehavior};
22use waft_services::{KeyEvent, LogicalKeyboardKey};
23use waft_widgets::*;
24
25pub const TRACK_WIDTH: f64 = 40.0;
27pub const TRACK_HEIGHT: f64 = 20.0;
28pub const KNOB_AREA: f64 = 20.0;
30pub const CONTENT_GAP: f64 = 12.0;
32pub const FOCUS_VISUAL_MARGIN: [f64; 4] = [-7.0, -3.0, -7.0, -3.0];
34pub const SWITCH_AREA_MARGIN: [f64; 4] = [0.0, 5.0, 0.0, 5.0];
36pub const KNOB_CORNER_RADIUS: f64 = 7.0;
38pub const KNOB_TRANSLATION_RANGE: f64 = TRACK_WIDTH - KNOB_AREA;
40
41pub fn knob_size(state: CommonState) -> (f64, f64) {
43 match state {
44 CommonState::Normal | CommonState::Disabled => (12.0, 12.0),
45 CommonState::PointerOver => (14.0, 14.0),
46 CommonState::Pressed => (17.0, 14.0),
47 }
48}
49
50pub fn knob_size_duration(r: &ThemeResources, state: CommonState) -> Duration {
52 match state {
53 CommonState::Disabled => r.control_normal_animation_duration,
54 _ => r.control_faster_animation_duration,
55 }
56}
57
58pub fn fast_out_slow_in(r: &ThemeResources) -> Rc<dyn Curve> {
60 let [x1, y1, x2, y2] = r.control_fast_out_slow_in_key_spline;
61 Rc::new(Cubic::new(x1, y1, x2, y2))
62}
63
64pub type ToggledHandler = Rc<dyn Fn(&mut App, bool)>;
66
67pub type ToggleSwitchTemplate = Rc<
69 dyn Fn(
70 &mut App,
71 BuildContext,
72 &ToggleSwitch,
73 ToggleSwitchTemplateStates,
74 &ToggleSwitchTemplateParts,
75 ) -> WidgetRef,
76>;
77
78#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct ToggleSwitchTemplateStates {
81 pub common: CommonState,
83 pub focused: bool,
85 pub is_dragging: bool,
87 pub knob_translation: f64,
89}
90
91pub struct ToggleSwitchTemplateParts {
93 switch_thumb: WidgetRef,
94}
95
96impl ToggleSwitchTemplateParts {
97 pub fn switch_thumb(&self) -> WidgetRef {
99 self.switch_thumb.clone()
100 }
101}
102
103#[derive(Clone)]
105pub struct ToggleSwitch {
106 pub is_on: bool,
107 pub toggled: ToggledHandler,
109 pub header: Option<WidgetRef>,
110 pub on_content: Option<WidgetRef>,
112 pub off_content: Option<WidgetRef>,
114 pub is_enabled: bool,
115 pub template: Option<ToggleSwitchTemplate>,
117 pub key: Option<KeyRef>,
118}
119
120impl ToggleSwitch {
121 pub fn new(is_on: bool, toggled: impl Fn(&mut App, bool) + 'static) -> ToggleSwitch {
122 ToggleSwitch {
123 is_on,
124 toggled: Rc::new(toggled),
125 header: None,
126 on_content: None,
127 off_content: None,
128 is_enabled: true,
129 template: None,
130 key: None,
131 }
132 }
133
134 #[cfg_attr(debug_assertions, track_caller)]
135 pub fn header<K>(mut self, header: impl IntoWidget<K>) -> ToggleSwitch {
136 self.header = Some(header.into_widget());
137 self
138 }
139
140 #[cfg_attr(debug_assertions, track_caller)]
141 pub fn on_content<K>(mut self, content: impl IntoWidget<K>) -> ToggleSwitch {
142 self.on_content = Some(content.into_widget());
143 self
144 }
145
146 #[cfg_attr(debug_assertions, track_caller)]
147 pub fn off_content<K>(mut self, content: impl IntoWidget<K>) -> ToggleSwitch {
148 self.off_content = Some(content.into_widget());
149 self
150 }
151
152 pub fn is_enabled(mut self, enabled: bool) -> ToggleSwitch {
153 self.is_enabled = enabled;
154 self
155 }
156
157 pub fn template(
159 mut self,
160 builder: impl Fn(
161 &mut App,
162 BuildContext,
163 &ToggleSwitch,
164 ToggleSwitchTemplateStates,
165 &ToggleSwitchTemplateParts,
166 ) -> WidgetRef
167 + 'static,
168 ) -> ToggleSwitch {
169 self.template = Some(Rc::new(builder));
170 self
171 }
172
173 pub fn key(mut self, key: KeyRef) -> ToggleSwitch {
174 self.key = Some(key);
175 self
176 }
177}
178
179impl fmt::Debug for ToggleSwitch {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 f.debug_struct("ToggleSwitch")
182 .field("is_on", &self.is_on)
183 .field("is_enabled", &self.is_enabled)
184 .finish_non_exhaustive()
185 }
186}
187
188pub struct ToggleSwitchState {
190 state: StateData<ToggleSwitch>,
191 is_dragging: bool,
193 was_dragged: bool,
195 knob_translation: f64,
197 focus_node: Option<Ref<FocusNode>>,
198 hovered: bool,
199 focused: bool,
200 handled_key_down: bool,
201}
202
203impl StatefulWidget for ToggleSwitch {
204 type State = ToggleSwitchState;
205
206 fn key(&self) -> Option<&KeyRef> {
207 self.key.as_ref()
208 }
209
210 fn create_state(&self) -> ToggleSwitchState {
211 ToggleSwitchState {
212 state: StateData::new(),
213 is_dragging: false,
214 was_dragged: false,
215 knob_translation: 0.0,
216 focus_node: None,
217 hovered: false,
218 focused: false,
219 handled_key_down: false,
220 }
221 }
222}
223
224impl State for ToggleSwitchState {
225 type Widget = ToggleSwitch;
226 waft_widgets::state_accessors!();
227
228 fn init_state(self: Handle<Self>, app: &mut App) {
229 crate::InputDevice::initialize(app);
230 app.get_mut(self).focus_node = Some(FocusNode::new(app));
231 }
232
233 fn dispose(self: Handle<Self>, app: &mut App) {
234 if let Some(node) = app.get_mut(self).focus_node.take() {
235 node.dispose(app);
236 }
237 }
238
239 fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &ToggleSwitch) {
241 if !self.widget(app).is_enabled {
242 let state = app.get_mut(self);
243 state.is_dragging = false;
244 state.hovered = false;
245 state.handled_key_down = false;
246 }
247 }
248
249 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
250 let is_enabled = self.widget(app).is_enabled;
251 let state = app.get(self);
252 let states = ControlStates {
253 common: if !is_enabled {
254 CommonState::Disabled
255 } else if state.hovered {
256 CommonState::PointerOver
257 } else {
258 CommonState::Normal
259 },
260 focused: is_enabled && state.focused,
261 };
262 let node = state.focus_node.clone().unwrap();
263 let body = self.template(app, context, states);
264 let mut tapped = GestureDetector::new()
265 .behavior(HitTestBehavior::Opaque)
266 .child(body);
267 if is_enabled {
268 tapped = tapped.on_tap(Listener::new(move |app| {
269 if !app.get(self).is_dragging {
270 self.toggle(app);
271 }
272 }));
273 }
274 let detector = FocusableActionDetector::new(tapped)
275 .focus_node(node.erase())
276 .enabled(is_enabled)
277 .on_focus_change(move |app, focused| {
278 let focused = focused && crate::FocusState::current(app).shows_focus_visual();
279 self.set_state(app, |state| state.focused = focused);
280 })
281 .on_show_hover_highlight(move |app, hovered| {
282 self.set_state(app, |state| state.hovered = hovered);
283 });
284 Focus::new(detector)
285 .can_request_focus(false)
286 .skip_traversal(true)
287 .on_key_event(Rc::new(move |app, _, event| self.handle_key(app, event)))
288 .into_widget()
289 }
290}
291
292impl ToggleSwitchState {
293 fn handle_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
295 if !self.widget(app).is_enabled {
296 return KeyEventResult::Ignored;
297 }
298 let gamepad = event.logical_key() == LogicalKeyboardKey::GAME_BUTTON_A;
299 let handles_key = event.logical_key() == LogicalKeyboardKey::SPACE || gamepad;
300 match event {
301 KeyEvent::Down(_) | KeyEvent::Repeat(_) if !app.get(self).is_dragging => {
302 app.get_mut(self).handled_key_down = handles_key;
303 if handles_key {
304 return KeyEventResult::Handled;
305 }
306 }
307 KeyEvent::Up(_) if handles_key => {
308 let handled = app.get(self).handled_key_down;
309 app.get_mut(self).handled_key_down = false;
310 if gamepad || (handled && !app.get(self).is_dragging) {
311 self.toggle(app);
312 return KeyEventResult::Handled;
313 }
314 }
315 _ => {}
316 }
317 KeyEventResult::Ignored
318 }
319
320 fn toggle(self: Handle<Self>, app: &mut App) {
322 let widget = self.widget(app).clone();
323 if widget.is_enabled {
324 (widget.toggled)(app, !widget.is_on);
325 }
326 }
327
328 fn drag_started(self: Handle<Self>, app: &mut App) {
330 let is_on = self.widget(app).is_on;
331 self.set_state(app, |state| {
332 state.is_dragging = true;
333 state.was_dragged = false;
334 state.knob_translation = if is_on { KNOB_TRANSLATION_RANGE } else { 0.0 };
335 });
336 }
337
338 fn drag_delta(self: Handle<Self>, app: &mut App, horizontal_change: f64) {
340 if horizontal_change == 0.0 {
341 return;
342 }
343 self.set_state(app, |state| {
344 state.was_dragged = true;
345 state.knob_translation += horizontal_change;
346 });
347 }
348
349 fn drag_completed(self: Handle<Self>, app: &mut App) {
351 let is_on = self.widget(app).is_on;
352 let (was_dragged, knob_translation) = {
353 let state = app.get(self);
354 (state.was_dragged, state.knob_translation)
355 };
356 let half_of_translation_range = KNOB_TRANSLATION_RANGE / 2.0;
358 let was_toggled = was_dragged
359 && if is_on {
360 knob_translation <= half_of_translation_range
361 } else {
362 knob_translation >= half_of_translation_range
363 };
364 self.set_state(app, |state| state.is_dragging = false);
365 if was_toggled {
366 self.toggle(app);
367 }
368 }
369
370 fn drag_cancelled(self: Handle<Self>, app: &mut App) {
372 self.set_state(app, |state| state.is_dragging = false);
373 }
374
375 fn drag_factory(self: Handle<Self>) -> GestureRecognizerFactoryRef {
377 GestureRecognizerFactoryWithHandlers::<HorizontalDragGestureRecognizer>::new(
378 HorizontalDragGestureRecognizer::new,
379 move |app, recognizer| {
380 recognizer.set_drag_start_behavior(app, DragStartBehavior::Down);
383 recognizer.set_on_down(
384 app,
385 Some(Rc::new(move |app: &mut App, _: DragDownDetails| {
386 self.drag_started(app)
387 })),
388 );
389 recognizer.set_on_update(
390 app,
391 Some(Rc::new(move |app: &mut App, details: DragUpdateDetails| {
392 self.drag_delta(app, details.primary_delta.unwrap_or(0.0))
393 })),
394 );
395 recognizer.set_on_end(
396 app,
397 Some(Rc::new(move |app: &mut App, _: DragEndDetails| {
398 self.drag_completed(app)
399 })),
400 );
401 recognizer.set_on_cancel(
402 app,
403 Some(Listener::new(move |app| self.drag_cancelled(app))),
404 );
405 },
406 )
407 .into_factory()
408 }
409
410 fn template(
412 self: Handle<Self>,
413 app: &mut App,
414 context: BuildContext,
415 states: ControlStates,
416 ) -> WidgetRef {
417 let widget = self.widget(app).clone();
418 let state = app.get(self);
419 let is_dragging = state.is_dragging;
420 let states = ToggleSwitchTemplateStates {
421 common: if is_dragging {
423 CommonState::Pressed
424 } else {
425 states.common
426 },
427 focused: states.focused,
428 is_dragging,
429 knob_translation: if is_dragging {
431 state.knob_translation.clamp(0.0, KNOB_TRANSLATION_RANGE)
432 } else if widget.is_on {
433 KNOB_TRANSLATION_RANGE
434 } else {
435 0.0
436 },
437 };
438 let parts = ToggleSwitchTemplateParts {
439 switch_thumb: self.switch_thumb(widget.is_enabled),
440 };
441 match widget.template.clone() {
442 Some(template) => template(app, context, &widget, states, &parts),
443 None => {
444 let resources = ThemeResources::of(app, context);
445 default_template(&resources, &widget, states, &parts)
446 }
447 }
448 }
449
450 fn switch_thumb(self: Handle<Self>, is_enabled: bool) -> WidgetRef {
452 let gestures = if is_enabled {
453 vec![(
454 TypeId::of::<HorizontalDragGestureRecognizer>(),
455 self.drag_factory(),
456 )]
457 } else {
458 Vec::new()
459 };
460 RawGestureDetector::new()
461 .gestures(gestures)
462 .behavior(HitTestBehavior::Opaque)
463 .child(SizedBox::new())
464 .into_widget()
465 }
466}
467
468fn default_template(
470 resources: &ThemeResources,
471 widget: &ToggleSwitch,
472 states: ToggleSwitchTemplateStates,
473 parts: &ToggleSwitchTemplateParts,
474) -> WidgetRef {
475 let brushes = switch_brushes(resources, states.common);
476 let header = widget
477 .header
478 .clone()
479 .map(|header| header_content_presenter(resources, header, brushes.header));
480 let inner = inner_grid(widget, resources, &brushes, states, parts);
481 let inner = GridCell::new(
483 Align::new()
484 .alignment(AlignmentGeometry::TOP_LEFT)
485 .width_factor(1.0)
486 .height_factor(1.0)
487 .child(inner),
488 )
489 .row(1)
490 .into_widget();
491 let root = Grid::new()
494 .row_definitions([
495 RowDefinition::new(GridLength::AUTO),
496 RowDefinition::new(GridLength::STAR),
497 ])
498 .children(header.into_iter().chain([inner]));
499 ConstrainedBox::new(BoxConstraints::new().min_width(resources.toggle_switch_theme_min_width))
501 .child(root)
502 .into_widget()
503}
504
505fn inner_grid(
507 widget: &ToggleSwitch,
508 resources: &ThemeResources,
509 brushes: &SwitchBrushes,
510 states: ToggleSwitchTemplateStates,
511 parts: &ToggleSwitchTemplateParts,
512) -> Grid {
513 let is_on = widget.is_on;
514 let text = control_text_style(
515 resources,
516 resources.control_content_theme_font_size,
517 FontWeight::W400,
518 brushes.foreground,
519 );
520 let off_content = widget
521 .off_content
522 .clone()
523 .unwrap_or_else(|| Text::new("Off").into_widget());
524 let on_content = widget
525 .on_content
526 .clone()
527 .unwrap_or_else(|| Text::new("On").into_widget());
528 Grid::new()
529 .row_definitions([
530 RowDefinition::new(GridLength::pixel(
531 resources.toggle_switch_pre_content_margin,
532 )),
533 RowDefinition::new(GridLength::AUTO),
534 RowDefinition::new(GridLength::pixel(
535 resources.toggle_switch_post_content_margin,
536 )),
537 ])
538 .column_definitions([
539 ColumnDefinition::new(GridLength::AUTO),
540 ColumnDefinition::new(GridLength::pixel(CONTENT_GAP)).max_width(CONTENT_GAP),
541 ColumnDefinition::new(GridLength::AUTO),
542 ])
543 .children([
544 GridCell::new(switch_area_grid(
545 resources,
546 resources.theme,
547 brushes.container,
548 states.focused,
549 ))
550 .row_span(3)
551 .column_span(3)
552 .into_widget(),
553 GridCell::new(content_presenter(text.clone(), off_content, !is_on))
554 .row_span(3)
555 .column(2)
556 .into_widget(),
557 GridCell::new(content_presenter(text, on_content, is_on))
558 .row_span(3)
559 .column(2)
560 .into_widget(),
561 GridCell::new(outer_border(resources, brushes, is_on))
562 .row(1)
563 .into_widget(),
564 GridCell::new(switch_knob_bounds(resources, brushes, is_on))
565 .row(1)
566 .into_widget(),
567 GridCell::new(switch_knob(
568 resources,
569 brushes,
570 states,
571 is_on,
572 KnobShapeOffsets {
573 on: knob_on_left(states.common, knob_size(states.common).0),
574 off: knob_off_left(states.common, knob_size(states.common).0),
575 },
576 ))
577 .row(1)
578 .into_widget(),
579 GridCell::new(parts.switch_thumb())
580 .row_span(3)
581 .column_span(3)
582 .into_widget(),
583 ])
584}
585
586#[derive(Clone, Copy, Debug, PartialEq)]
588pub(crate) struct KnobShapeOffsets {
589 pub(crate) on: f64,
590 pub(crate) off: f64,
591}
592
593pub(crate) fn switch_knob(
595 resources: &ThemeResources,
596 brushes: &SwitchBrushes,
597 states: ToggleSwitchTemplateStates,
598 is_on: bool,
599 shapes: KnobShapeOffsets,
600) -> WidgetRef {
601 let common = states.common;
602 let curve = fast_out_slow_in(resources);
603 let duration = if states.is_dragging {
604 Duration::ZERO
605 } else {
606 resources.control_fast_animation_duration
607 };
608 let (knob_width, knob_height) = knob_size(common);
609 let top = (KNOB_AREA - knob_height) / 2.0;
611 let shape = |child: WidgetRef, left: f64| {
612 AnimatedPositioned::new(child, knob_size_duration(resources, common))
613 .curve(curve.clone())
614 .left(left)
615 .top(top)
616 .width(knob_width)
617 .height(knob_height)
618 .into_widget()
619 };
620 let knob = Stack::new().children(vec![
621 shape(switch_knob_on(resources, brushes, is_on), shapes.on),
622 shape(switch_knob_off(resources, brushes, is_on), shapes.off),
623 ]);
624 let translated = Stack::new().clip_behavior(Clip::None).children(vec![
627 AnimatedPositioned::new(knob, duration)
628 .curve(curve)
629 .left(states.knob_translation)
630 .top(0.0)
631 .width(KNOB_AREA)
632 .height(KNOB_AREA)
633 .into_widget(),
634 ]);
635 Align::new()
636 .alignment(AlignmentGeometry::CENTER_LEFT)
637 .width_factor(1.0)
638 .height_factor(1.0)
639 .child(
640 SizedBox::new()
641 .width(KNOB_AREA)
642 .height(KNOB_AREA)
643 .child(translated),
644 )
645 .into_widget()
646}
647
648pub(crate) struct SwitchBrushes {
650 fill_off: Color,
651 stroke_off: Color,
652 fill_on: Color,
653 stroke_on: Color,
654 knob_off: Color,
655 knob_on: Color,
656 pub(crate) container: Color,
657 pub(crate) foreground: Color,
658 pub(crate) header: Color,
659}
660
661pub(crate) fn switch_brushes(r: &ThemeResources, state: CommonState) -> SwitchBrushes {
662 match state {
663 CommonState::Normal => SwitchBrushes {
664 fill_off: r.toggle_switch_fill_off,
665 stroke_off: r.toggle_switch_stroke_off,
666 fill_on: r.toggle_switch_fill_on,
667 stroke_on: r.toggle_switch_stroke_on,
668 knob_off: r.toggle_switch_knob_fill_off,
669 knob_on: r.toggle_switch_knob_fill_on,
670 container: r.toggle_switch_container_background,
671 foreground: r.toggle_switch_content_foreground,
672 header: r.toggle_switch_header_foreground,
673 },
674 CommonState::PointerOver => SwitchBrushes {
675 fill_off: r.toggle_switch_fill_off_pointer_over,
676 stroke_off: r.toggle_switch_stroke_off_pointer_over,
677 fill_on: r.toggle_switch_fill_on_pointer_over,
678 stroke_on: r.toggle_switch_stroke_on_pointer_over,
679 knob_off: r.toggle_switch_knob_fill_off_pointer_over,
680 knob_on: r.toggle_switch_knob_fill_on_pointer_over,
681 container: r.toggle_switch_container_background_pointer_over,
682 foreground: r.toggle_switch_content_foreground,
683 header: r.toggle_switch_header_foreground,
684 },
685 CommonState::Pressed => SwitchBrushes {
686 fill_off: r.toggle_switch_fill_off_pressed,
687 stroke_off: r.toggle_switch_stroke_off_pressed,
688 fill_on: r.toggle_switch_fill_on_pressed,
689 stroke_on: r.toggle_switch_stroke_on_pressed,
690 knob_off: r.toggle_switch_knob_fill_off_pressed,
691 knob_on: r.toggle_switch_knob_fill_on_pressed,
692 container: r.toggle_switch_container_background_pressed,
693 foreground: r.toggle_switch_content_foreground,
694 header: r.toggle_switch_header_foreground,
695 },
696 CommonState::Disabled => SwitchBrushes {
697 fill_off: r.toggle_switch_fill_off_disabled,
698 stroke_off: r.toggle_switch_stroke_off_disabled,
699 fill_on: r.toggle_switch_fill_on_disabled,
700 stroke_on: r.toggle_switch_stroke_on_disabled,
701 knob_off: r.toggle_switch_knob_fill_off_disabled,
702 knob_on: r.toggle_switch_knob_fill_on_disabled,
703 container: r.toggle_switch_container_background_disabled,
704 foreground: r.toggle_switch_content_foreground_disabled,
705 header: r.toggle_switch_header_foreground_disabled,
706 },
707 }
708}
709
710pub(crate) fn header_content_presenter(
712 r: &ThemeResources,
713 header: WidgetRef,
714 foreground: Color,
715) -> WidgetRef {
716 let [left, top, right, bottom] = r.toggle_switch_top_header_margin;
717 let text = control_text_style(
718 r,
719 r.control_content_theme_font_size,
720 FontWeight::W400,
721 foreground,
722 );
723 GridCell::new(
724 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
725 .child(DefaultTextStyle::new(text, header)),
726 )
727 .row(0)
728 .into_widget()
729}
730
731fn switch_area_grid(
733 r: &ThemeResources,
734 theme: Theme,
735 container: Color,
736 focused: bool,
737) -> WidgetRef {
738 let [left, top, right, bottom] = SWITCH_AREA_MARGIN;
739 let area = Grid::new()
740 .background(Brush::Solid(container))
741 .corner_radius(r.control_corner_radius[0]);
742 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
743 .child(
744 FocusVisual::new(area, theme)
745 .visible(focused)
746 .margin(FOCUS_VISUAL_MARGIN)
747 .corner_radius(r.control_corner_radius[0]),
748 )
749 .into_widget()
750}
751
752fn content_presenter(text: TextStyle, content: WidgetRef, visible: bool) -> WidgetRef {
754 Opacity::new(if visible { 1.0 } else { 0.0 })
755 .child(
756 Align::new()
757 .alignment(AlignmentGeometry::CENTER_LEFT)
758 .width_factor(1.0)
759 .height_factor(1.0)
760 .child(DefaultTextStyle::new(text, content)),
761 )
762 .into_widget()
763}
764
765fn track(
767 r: &ThemeResources,
768 fill: Color,
769 stroke: Color,
770 stroke_thickness: f64,
771 visible: bool,
772) -> WidgetRef {
773 AnimatedOpacity::new(
774 if visible { 1.0 } else { 0.0 },
775 r.control_faster_animation_duration,
776 )
777 .child(
778 SizedBox::new()
779 .width(TRACK_WIDTH)
780 .height(TRACK_HEIGHT)
781 .child(
782 ControlBorder::new(Brush::Solid(fill), Brush::Solid(stroke))
783 .border_thickness(stroke_thickness)
784 .corner_radius(TRACK_HEIGHT / 2.0),
785 ),
786 )
787 .into_widget()
788}
789
790pub(crate) fn outer_border(r: &ThemeResources, brushes: &SwitchBrushes, is_on: bool) -> WidgetRef {
792 track(
793 r,
794 brushes.fill_off,
795 brushes.stroke_off,
796 r.toggle_switch_outer_border_stroke_thickness,
797 !is_on,
798 )
799}
800
801pub(crate) fn switch_knob_bounds(
803 r: &ThemeResources,
804 brushes: &SwitchBrushes,
805 is_on: bool,
806) -> WidgetRef {
807 track(
808 r,
809 brushes.fill_on,
810 brushes.stroke_on,
811 r.toggle_switch_on_stroke_thickness,
812 is_on,
813 )
814}
815
816fn switch_knob_on(resources: &ThemeResources, brushes: &SwitchBrushes, is_on: bool) -> WidgetRef {
818 AnimatedOpacity::new(
819 if is_on { 1.0 } else { 0.0 },
820 resources.control_faster_animation_duration,
821 )
822 .child(
823 ControlBorder::new(
824 Brush::Solid(brushes.knob_on),
825 Brush::CircleElevation(resources.toggle_switch_knob_stroke_on),
826 )
827 .border_thickness(0.0)
828 .background_sizing(BackgroundSizing::OuterBorderEdge)
829 .corner_radius(KNOB_CORNER_RADIUS),
830 )
831 .into_widget()
832}
833
834fn switch_knob_off(r: &ThemeResources, brushes: &SwitchBrushes, is_on: bool) -> WidgetRef {
836 AnimatedOpacity::new(
837 if is_on { 0.0 } else { 1.0 },
838 r.control_faster_animation_duration,
839 )
840 .child(
841 ControlBorder::new(
842 Brush::Solid(brushes.knob_off),
843 Brush::Solid(Color::from_argb(0, 0, 0, 0)),
844 )
845 .border_thickness(0.0)
846 .corner_radius(KNOB_CORNER_RADIUS),
847 )
848 .into_widget()
849}
850
851pub(crate) fn arranged_left(
853 slot: f64,
854 width: f64,
855 alignment: HorizontalAlignment,
856 margin: (f64, f64),
857) -> f64 {
858 let (left, right) = margin;
859 match alignment {
860 HorizontalAlignment::Left => left,
861 HorizontalAlignment::Center | HorizontalAlignment::Stretch => {
862 left + (slot - left - right - width) / 2.0
863 }
864 HorizontalAlignment::Right => slot - right - width,
865 }
866}
867
868fn knob_on_left(state: CommonState, width: f64) -> f64 {
870 match state {
871 CommonState::Pressed => {
872 arranged_left(KNOB_AREA, width, HorizontalAlignment::Right, (0.0, 3.0))
873 }
874 _ => arranged_left(KNOB_AREA, width, HorizontalAlignment::Center, (0.0, 1.0)),
875 }
876}
877
878fn knob_off_left(state: CommonState, width: f64) -> f64 {
880 match state {
881 CommonState::Pressed => {
882 arranged_left(KNOB_AREA, width, HorizontalAlignment::Left, (3.0, 0.0))
883 }
884 _ => arranged_left(KNOB_AREA, width, HorizontalAlignment::Center, (-1.0, 0.0)),
885 }
886}