Skip to main content

waft_winui/controls/
toggle_switch.rs

1//! XAML `ToggleSwitch` with the Fluent style of `ToggleSwitch_themeresources.xaml`.
2//!
3//! Template, element by element: the root `Grid` (rows Auto and *) holds `HeaderContentPresenter` in row 0 and, in row 1 aligned top-left, the inner `Grid` whose rows are `ToggleSwitchPreContentMargin`, Auto and `ToggleSwitchPostContentMargin` and whose columns are Auto, 12 and Auto. Its children, in order: `SwitchAreaGrid` (spanning everything, `Margin="0,5"`, the container background, the focus target), `OffContentPresenter` and `OnContentPresenter` (column 2; the `ContentStates` group makes one opaque), `OuterBorder` and `SwitchKnobBounds` (row 1, 40 × 20 rounded rectangles, the off and the on track, crossfaded by `ToggleStates`), `SwitchKnob` (row 1, a 20 × 20 grid aligned left and moved by `KnobTranslateTransform`, holding `SwitchKnobOn` and `SwitchKnobOff`) and `SwitchThumb` (spanning everything, the drag surface).
4//!
5//! Behaviour is `ToggleSwitch_Partial.cpp`: a tap on the thumb toggles (`TapHandler`); a drag moves the knob with the pointer (`DragStartedHandler`, `DragDeltaHandler` → `MoveDelta`) and toggles at release when the knob passed half the track (`DragCompletedHandler` → `MoveCompleted`).
6
7use 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
25/// `OuterBorder` and `SwitchKnobBounds`: the track.
26pub const TRACK_WIDTH: f64 = 40.0;
27pub const TRACK_HEIGHT: f64 = 20.0;
28/// `SwitchKnob`: the grid the knob shapes are arranged in.
29pub const KNOB_AREA: f64 = 20.0;
30/// The gap column between the switch and its content.
31pub const CONTENT_GAP: f64 = 12.0;
32/// `FocusVisualMargin` of the style.
33pub const FOCUS_VISUAL_MARGIN: [f64; 4] = [-7.0, -3.0, -7.0, -3.0];
34/// `SwitchAreaGrid`'s `Margin="0,5"`: left, top, right, bottom.
35pub const SWITCH_AREA_MARGIN: [f64; 4] = [0.0, 5.0, 0.0, 5.0];
36/// `SwitchKnobOn`'s `CornerRadius` and `SwitchKnobOff`'s `RadiusX` / `RadiusY`.
37pub const KNOB_CORNER_RADIUS: f64 = 7.0;
38/// `KnobTranslateTransform.X` in the `On` state (`To="20"`): `m_maxKnobTranslation` of `SizeChangedHandler`, the knob bounds' width less the knob's; `m_minKnobTranslation` is 0.
39pub const KNOB_TRANSLATION_RANGE: f64 = TRACK_WIDTH - KNOB_AREA;
40
41/// The knob's size per common state: the storyboards animate `SwitchKnobOn` and `SwitchKnobOff` to 12 × 12 (`Normal`, `Disabled`), 14 × 14 (`PointerOver`) and 17 × 14 (`Pressed`) with `ControlFastOutSlowInKeySpline`.
42pub 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
50/// How long the knob takes to reach `knob_size`: `ControlNormalAnimationDuration` into `Disabled`, `ControlFasterAnimationDuration` into the other states.
51pub 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
58/// XAML `ControlFastOutSlowInKeySpline` as a curve.
59pub 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
64/// XAML `Toggled` handler, given the value the switch wants.
65pub type ToggledHandler = Rc<dyn Fn(&mut App, bool)>;
66
67/// A ToggleSwitch `ControlTemplate` replacing `DefaultToggleSwitchStyle`'s, as a style based on it sets one; the switch keeps its tap, drag and keyboard behaviour.
68pub type ToggleSwitchTemplate = Rc<
69    dyn Fn(
70        &mut App,
71        BuildContext,
72        &ToggleSwitch,
73        ToggleSwitchTemplateStates,
74        &ToggleSwitchTemplateParts,
75    ) -> WidgetRef,
76>;
77
78/// What a ToggleSwitch template is built for: `CommonStates`, focus, and where `ToggleStates` and the drag put the knob. `ContentStates` follows [`ToggleSwitch::is_on`].
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct ToggleSwitchTemplateStates {
81    /// `CommonStates`, which a drag holds in `Pressed`.
82    pub common: CommonState,
83    /// The focus visual shows.
84    pub focused: bool,
85    /// `ToggleStates` is `Dragging`: the knob follows the pointer, so a template moves it without animating.
86    pub is_dragging: bool,
87    /// `KnobTranslateTransform.X`: [`KNOB_TRANSLATION_RANGE`] in the `On` state, 0 in `Off`, and during a drag as far as the pointer has moved the knob between the two.
88    pub knob_translation: f64,
89}
90
91/// The template parts `ToggleSwitch::OnApplyTemplate` attaches its behaviour to.
92pub struct ToggleSwitchTemplateParts {
93    switch_thumb: WidgetRef,
94}
95
96impl ToggleSwitchTemplateParts {
97    /// `SwitchThumb`: the transparent surface whose horizontal drag moves the knob, which a template lays over everything a drag may start on.
98    pub fn switch_thumb(&self) -> WidgetRef {
99        self.switch_thumb.clone()
100    }
101}
102
103/// XAML `ToggleSwitch`: `IsOn` with `Toggled`, `Header`, `OnContent` and `OffContent`.
104#[derive(Clone)]
105pub struct ToggleSwitch {
106    pub is_on: bool,
107    /// XAML `Toggled`, with the value the switch wants.
108    pub toggled: ToggledHandler,
109    pub header: Option<WidgetRef>,
110    /// XAML `OnContent`; the control's default is the text "On".
111    pub on_content: Option<WidgetRef>,
112    /// XAML `OffContent`; the control's default is the text "Off".
113    pub off_content: Option<WidgetRef>,
114    pub is_enabled: bool,
115    /// The template of a style based on `DefaultToggleSwitchStyle`; `None` is that style's own.
116    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    /// Sets the `ControlTemplate` of a style that replaces `DefaultToggleSwitchStyle`'s.
158    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
188/// The drag of `ToggleSwitch_Partial.cpp`: `m_isDragging`, `m_wasDragged` and `m_knobTranslation`.
189pub struct ToggleSwitchState {
190    state: StateData<ToggleSwitch>,
191    /// `m_isDragging`: the thumb holds the pointer, so `CommonStates` shows `Pressed` and `ToggleStates` `Dragging`.
192    is_dragging: bool,
193    /// `m_wasDragged`: a `DragDelta` moved horizontally, so the release decides by position instead of leaving the toggle to the tap.
194    was_dragged: bool,
195    /// `m_knobTranslation`: the horizontal change since the drag started, accumulated unclamped; `SetTranslations` clamps what the knob shows.
196    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    /// `OnIsEnabledChanged`: disabling ends a drag.
240    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    // `HandlesKey` accepts Space and GamepadA.
294    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    /// `Toggle`: `IsOn` flips; here the `Toggled` handler is asked for the flipped value.
321    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    /// `DragStartedHandler`: the drag begins where the state left the knob (`GetTranslations`), shown pressed (`UpdateVisualState`).
329    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    /// `DragDeltaHandler` then `MoveDelta`: a horizontal change moves the knob and marks the drag as moved; vertical movement is allowed and ignored.
339    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    /// `DragCompletedHandler` then `MoveCompleted`: the switch toggles when the knob was dragged past half the track towards the other state; `ClearTranslations` returns the knob to its state's end either way.
350    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        // `(m_maxKnobTranslation - m_minKnobTranslation) / 2`, with `m_minKnobTranslation` 0.
357        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    /// The recogniser gives the drag up: the pointer was lost, or it was released inside the slop and the tap takes it. XAML raises `DragCompleted` for both; without movement `MoveCompleted` only restores the knob, and `Tapped` toggles.
371    fn drag_cancelled(self: Handle<Self>, app: &mut App) {
372        self.set_state(app, |state| state.is_dragging = false);
373    }
374
375    /// `SwitchThumb`'s `DragStarted` / `DragDelta` / `DragCompleted` as a `HorizontalDragGestureRecognizer`.
376    fn drag_factory(self: Handle<Self>) -> GestureRecognizerFactoryRef {
377        GestureRecognizerFactoryWithHandlers::<HorizontalDragGestureRecognizer>::new(
378            HorizontalDragGestureRecognizer::new,
379            move |app, recognizer| {
380                // `Thumb` measures every `DragDelta` from the press point, so the movement that
381                // made the recogniser win is not discarded.
382                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    /// The style's `ControlTemplate` for the current states.
411    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            // `ChangeVisualState`: a drag holds `CommonStates` in `Pressed`.
422            common: if is_dragging {
423                CommonState::Pressed
424            } else {
425                states.common
426            },
427            focused: states.focused,
428            is_dragging,
429            // `SetTranslations` clamps what the knob shows of a drag.
430            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    /// `SwitchThumb`: a `Thumb` templated as a transparent rectangle over the whole switch. Its `Tapped` is the tap of the `GestureDetector` around the template; its `DragStarted` / `DragDelta` / `DragCompleted` are a `HorizontalDragGestureRecognizer` here, in the same arena, so a press that moves past the slop becomes the drag and cancels the tap, and one that does not stays the tap — as `Thumb`'s drag and `Tapped` compose in XAML.
451    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
468/// `DefaultToggleSwitchStyle`'s template: the header over the inner `Grid`, at least `ToggleSwitchThemeMinWidth` wide.
469fn 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    // `HorizontalAlignment="Left"` `VerticalAlignment="Top"`: sized to the content and placed top-left in the star row.
482    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    // The root `Grid`: `Background`, `BorderBrush`, `BorderThickness` and `CornerRadius` are
492    // template bindings the style leaves unset, so it paints nothing.
493    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    // The style's `MinWidth`.
500    ConstrainedBox::new(BoxConstraints::new().min_width(resources.toggle_switch_theme_min_width))
501        .child(root)
502        .into_widget()
503}
504
505/// The inner `Grid`: the switch, the gap and the content, in rows of `ToggleSwitchPreContentMargin`, Auto and `ToggleSwitchPostContentMargin`.
506fn 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/// Where a template's alignment and margin put `SwitchKnobOn` and `SwitchKnobOff` across `SwitchKnob`, as the distance from its left edge.
587#[derive(Clone, Copy, Debug, PartialEq)]
588pub(crate) struct KnobShapeOffsets {
589    pub(crate) on: f64,
590    pub(crate) off: f64,
591}
592
593/// `SwitchKnob`: `HorizontalAlignment="Left"`, 20 × 20, moved by `KnobTranslateTransform`. `X` is 20 in the `On` state, the clamped `m_knobTranslation` while dragging (`SetTranslations`) and 0 otherwise; the `ToggleStates` transitions move it with `RepositionThemeAnimation`, here `control_fast_animation_duration` with `ControlFastOutSlowInKeySpline`.
594pub(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    // `VerticalAlignment` `Stretch` with an explicit `Height`: centred in the 20 pt grid.
610    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    // `Width="20" Height="20"` at the left of the cell; the transform moves the knob beyond
625    // that box, so the stack does not clip.
626    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
648/// The track, knob and content brushes for one state; the `{ThemeResource …}` values the `CommonStates` storyboards name.
649pub(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
710/// `HeaderContentPresenter`: `x:DeferLoadStrategy="Lazy"` and `Visibility="Collapsed"` until a `Header` is set, so it exists only with one; `Margin` `ToggleSwitchTopHeaderMargin`, `Foreground` per state, `TextWrapping="Wrap"`.
711pub(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
731/// `SwitchAreaGrid`: spans the inner grid with `Margin="0,5"` and the container background (transparent in every state) under the style's `CornerRadius`; `Control.IsTemplateFocusTarget`, so the system focus visual draws around it with the style's `FocusVisualMargin`.
732fn 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
752/// `OffContentPresenter` / `OnContentPresenter`: `Foreground` per state, `HorizontalContentAlignment` `Left` (the style), `VerticalContentAlignment` `Center` (`CControl`'s default), and `Opacity` from the `ContentStates` group, whose `Duration="0"` animations switch it discretely.
753fn 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
765/// A 40 × 20 `Rectangle` with `RadiusX` / `RadiusY` 10, faded by the `ToggleStates` storyboards over `ControlFasterAnimationDuration`.
766fn 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
790/// `OuterBorder`: the off track, `StrokeThickness` `ToggleSwitchOuterBorderStrokeThickness`, faded out by the `On` state.
791pub(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
801/// `SwitchKnobBounds`: the on track, `StrokeThickness` `ToggleSwitchOnStrokeThickness`, faded in by the `On` state.
802pub(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
816/// `SwitchKnobOn`: a `Border` with `ToggleSwitchKnobFillOn` and the circle elevation `BorderBrush` (its `BorderThickness` is unset, so 0), `BackgroundSizing="OuterBorderEdge"`, `CornerRadius` 7, faded in by the `On` state.
817fn 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
834/// `SwitchKnobOff`: a `Rectangle` filled with `ToggleSwitchKnobFillOff`, `RadiusX` / `RadiusY` 7, faded out by the `On` state.
835fn 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
851/// `FrameworkElement::ArrangeCore`: where an element with an explicit `width`, an `alignment` and a `margin` (left, right) lands in a slot `slot` wide. `Stretch` centres an element that has a `Width`.
852pub(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
868/// `SwitchKnobOn` in `SwitchKnob`: `HorizontalAlignment="Center"` with `Margin="0,0,1,0"`; the `Pressed` setters make it `Right` with `Margin="0,0,3,0"`, so it stretches towards the off end.
869fn 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
878/// `SwitchKnobOff` in `SwitchKnob`: `HorizontalAlignment="Center"` with `Margin="-1,0,0,0"`; the `Pressed` setters make it `Left` with `Margin="3,0,0,0"`, so it stretches towards the on end.
879fn 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}