mtk-rs 0.1.0-beta.4

Muse Toolkit
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
use std::marker::PhantomData;
use std::time::Instant;
use winit::keyboard::{Key, NamedKey};

use crate::animation::{Animatable, AnimatedValue, Curve};
use crate::colors::Color;
use crate::debugger::SourceLocation;
use crate::effects::BoxShadow;
use crate::style::{
    AlignItems, FlexDirection, JustifyContent, Size, Style, TextStyle, VerticalAlignment,
};
use crate::text_property::FontWeight;
use crate::ui::event::EventResult;
use crate::ui::{Event, View};
use crate::{AccessibleInfo, Context, Node, clr, rgb, rgba};

/// Visual styling configuration for a [`Switch`] widget.
#[derive(Clone, Debug, PartialEq)]
pub struct SwitchStyle {
    pub on_bg: Color,
    pub off_bg: Color,
    pub disabled_bg: Color,
    pub knob_color: Color,
    pub label_style: Option<TextStyle>,
    pub gap: f32,
}

impl Default for SwitchStyle {
    fn default() -> Self {
        Self {
            on_bg: rgb!(59, 130, 246),
            off_bg: rgb!(226, 232, 240),
            disabled_bg: rgb!(203, 213, 225),
            knob_color: clr!(white),
            label_style: None,
            gap: 10.0,
        }
    }
}

impl SwitchStyle {
    /// Creates a new `SwitchStyle` with default visual properties.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the background color of the track when the switch is active (on).
    pub fn on_bg(mut self, color: Color) -> Self {
        self.on_bg = color;
        self
    }

    /// Sets the active (on) background color of the track.
    pub fn active_color(mut self, color: Color) -> Self {
        self.on_bg = color;
        self
    }

    /// Sets the background color of the track when the switch is inactive (off).
    pub fn off_bg(mut self, color: Color) -> Self {
        self.off_bg = color;
        self
    }

    /// Sets the inactive (off) background color of the track.
    pub fn inactive_color(mut self, color: Color) -> Self {
        self.off_bg = color;
        self
    }

    /// Sets the background color of the track when the switch is disabled.
    pub fn disabled_bg(mut self, color: Color) -> Self {
        self.disabled_bg = color;
        self
    }

    /// Sets the color of the sliding knob circle.
    pub fn knob_color(mut self, color: Color) -> Self {
        self.knob_color = color;
        self
    }

    /// Sets custom styling for the label text.
    pub fn label_style(mut self, style: TextStyle) -> Self {
        self.label_style = Some(style);
        self
    }

    /// Sets the text color of the label.
    pub fn label_color(mut self, color: Color) -> Self {
        let mut style = self.label_style.unwrap_or_default();
        style.color = color;
        self.label_style = Some(style);
        self
    }

    /// Sets the gap between the switch track and its label.
    pub fn gap(mut self, gap: f32) -> Self {
        self.gap = gap;
        self
    }
}

/// A smooth pill-shaped toggle switch widget with fluid animation and optional label.
pub struct Switch<Msg, F = fn(bool) -> Msg> {
    pub(crate) is_on: bool,
    pub(crate) label: Option<String>,
    pub(crate) on_toggle: Option<F>,
    pub(crate) disabled: bool,
    pub(crate) style: SwitchStyle,
    pub(crate) source_loc: Option<SourceLocation>,
    _marker: PhantomData<Msg>,
}

/// Creates a new `Switch` widget with the given boolean toggle state.
///
/// # Examples
/// ```rust,ignore
/// switch(state.notifications_enabled)
///     .label("Notifications")
///     .active_color(rgb!(16, 185, 129))
///     .on_toggle(|on| AppMsg::SetNotifications(on))
/// ```
#[track_caller]
pub fn switch<Msg>(is_on: bool) -> Switch<Msg, fn(bool) -> Msg> {
    Switch {
        is_on,
        label: None,
        on_toggle: None,
        disabled: false,
        style: SwitchStyle::default(),
        source_loc: Some(SourceLocation::here("Switch")),
        _marker: PhantomData,
    }
}

impl<Msg, F> Switch<Msg, F> {
    /// Sets a text label next to the switch.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the visual style configuration for the switch.
    pub fn style(mut self, style: SwitchStyle) -> Self {
        self.style = style;
        self
    }

    /// Sets the active (on) background color of the track.
    pub fn active_color(mut self, color: Color) -> Self {
        self.style = self.style.active_color(color);
        self
    }

    /// Sets the inactive (off) background color of the track.
    pub fn inactive_color(mut self, color: Color) -> Self {
        self.style = self.style.inactive_color(color);
        self
    }

    /// Sets the color of the sliding knob circle.
    pub fn knob_color(mut self, color: Color) -> Self {
        self.style = self.style.knob_color(color);
        self
    }

    /// Sets custom styling for the label text.
    pub fn label_style(mut self, style: TextStyle) -> Self {
        self.style = self.style.label_style(style);
        self
    }

    /// Sets the text color of the label.
    pub fn label_color(mut self, color: Color) -> Self {
        self.style = self.style.label_color(color);
        self
    }

    /// Sets the gap between the switch track and its label.
    pub fn gap(mut self, gap: f32) -> Self {
        self.style = self.style.gap(gap);
        self
    }

    /// Sets the callback invoked when the switch is toggled.
    pub fn on_toggle<NewF: Fn(bool) -> Msg>(self, on_toggle: NewF) -> Switch<Msg, NewF> {
        Switch {
            is_on: self.is_on,
            label: self.label,
            on_toggle: Some(on_toggle),
            disabled: self.disabled,
            style: self.style,
            source_loc: self.source_loc,
            _marker: PhantomData,
        }
    }

    /// Disables or enables the switch.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

pub struct SwitchElement {
    container_node: Node,
    track_node: Node,
    knob_node: Node,
    label_node: Option<Node>,
    is_pressed: bool,
    anim_progress: AnimatedValue<f32>,
    anim_start: Instant,
}

impl<State, Msg, F> View<State> for Switch<Msg, F>
where
    F: Fn(bool) -> Msg,
{
    type Element = SwitchElement;
    type Message = Msg;

    fn build(&self, ctx: &mut Context) -> Self::Element {
        let container_node = ctx.create_node();
        if let Some(loc) = self.source_loc {
            ctx.set_node_source(container_node, loc);
        }
        let track_node = ctx.create_node();
        let knob_node = ctx.create_node();

        Style::new()
            .flex_direction(FlexDirection::Row)
            .align_items(AlignItems::Center)
            .gap(self.style.gap)
            .apply_to_node(ctx, container_node);

        let initial_progress = if self.is_on { 1.0f32 } else { 0.0f32 };
        let anim_progress = AnimatedValue::new(initial_progress);
        let anim_start = Instant::now();

        let track_bg = if self.disabled {
            self.style.disabled_bg
        } else {
            Color::interpolate(
                &self.style.off_bg,
                &self.style.on_bg,
                initial_progress as f64,
            )
        };

        let initial_pad_left = 2.0 + initial_progress * 20.0;

        Style::new()
            .flex_direction(FlexDirection::Row)
            .width(Size::Fixed(44))
            .height(Size::Fixed(24))
            .corner_radius(12.0)
            .bg_color(track_bg)
            .padding_xy(2.0, 2.0)
            .justify_content(JustifyContent::Start)
            .align_items(AlignItems::Center)
            .apply_to_node(ctx, track_node);

        track_node.update_constraints(ctx, |c| {
            c.padding.left = initial_pad_left;
        });

        Style::new()
            .width(Size::Fixed(20))
            .height(Size::Fixed(20))
            .corner_radius(10.0)
            .bg_color(self.style.knob_color)
            .box_shadow(
                BoxShadow::new(rgba!(0, 0, 0, 40))
                    .blur(4.0)
                    .offset(0.0, 1.0),
            )
            .apply_to_node(ctx, knob_node);

        track_node.append(ctx, knob_node);
        container_node.append(ctx, track_node);

        let label_node = if let Some(ref text_str) = self.label {
            let l_node = ctx.create_node();
            let mut text_style = self.style.label_style.clone().unwrap_or_else(|| TextStyle {
                font_size: 14.0,
                font_weight: FontWeight::MEDIUM,
                vertical_alignment: VerticalAlignment::Center,
                color: rgb!(15, 23, 42),
                ..Default::default()
            });
            if self.disabled {
                text_style.color = rgb!(148, 163, 184);
            }
            l_node.set_text_with_userdata(ctx, text_str, text_style);
            container_node.append(ctx, l_node);
            Some(l_node)
        } else {
            None
        };

        if !self.disabled {
            ctx.register_focusable(track_node);
        }

        let mut a11y_info = AccessibleInfo::new(accesskit::Role::Switch)
            .with_toggled(self.is_on)
            .with_disabled(self.disabled)
            .with_action(accesskit::Action::Click)
            .with_action(accesskit::Action::Focus);
        if let Some(ref l) = self.label {
            a11y_info = a11y_info.with_label(l);
        }
        ctx.set_accessible(track_node, a11y_info);

        SwitchElement {
            container_node,
            track_node,
            knob_node,
            label_node,
            is_pressed: false,
            anim_progress,
            anim_start,
        }
    }

    fn rebuild(&self, prev: &Self, ctx: &mut Context, element: &mut Self::Element) {
        if self.is_on != prev.is_on {
            let target = if self.is_on { 1.0f32 } else { 0.0f32 };
            let now = element.anim_start.elapsed().as_secs_f64() * 1000.0;
            element
                .anim_progress
                .set_target(target, now, 160.0, Curve::ease_out());
            ctx.request_frame();
        }

        if self.style.gap != prev.style.gap {
            element.container_node.update_constraints(ctx, |c| {
                c.gap = self.style.gap;
            });
        }

        if self.style.knob_color != prev.style.knob_color {
            element.knob_node.update_effects(ctx, |e| {
                e.background_color = self.style.knob_color;
            });
        }

        if self.disabled != prev.disabled || self.style != prev.style {
            let track_bg = if self.disabled {
                self.style.disabled_bg
            } else {
                Color::interpolate(
                    &self.style.off_bg,
                    &self.style.on_bg,
                    element.anim_progress.get() as f64,
                )
            };

            element.track_node.update_effects(ctx, |e| {
                e.background_color = track_bg;
            });
        }

        if self.label != prev.label
            || self.style.label_style != prev.style.label_style
            || self.disabled != prev.disabled
        {
            if let (Some(l_node), Some(text_str)) = (element.label_node, &self.label) {
                let mut text_style = self.style.label_style.clone().unwrap_or_else(|| TextStyle {
                    font_size: 14.0,
                    font_weight: FontWeight::MEDIUM,
                    vertical_alignment: VerticalAlignment::Center,
                    color: rgb!(15, 23, 42),
                    ..Default::default()
                });
                if self.disabled {
                    text_style.color = rgb!(148, 163, 184);
                }
                l_node.set_text_with_userdata(ctx, text_str, text_style);
            }
        }

        if self.is_on != prev.is_on || self.disabled != prev.disabled || self.label != prev.label {
            let mut a11y_info = AccessibleInfo::new(accesskit::Role::Switch)
                .with_toggled(self.is_on)
                .with_disabled(self.disabled)
                .with_action(accesskit::Action::Click)
                .with_action(accesskit::Action::Focus);
            if let Some(ref l) = self.label {
                a11y_info = a11y_info.with_label(l);
            }
            ctx.set_accessible(element.track_node, a11y_info);
        }
    }

    fn teardown(&self, ctx: &mut Context, element: &mut Self::Element) {
        ctx.remove_accessible(element.track_node);
        ctx.unregister_focusable(element.track_node);
        if let Some(l_node) = element.label_node {
            l_node.remove(ctx);
            ctx.destroy_node(l_node);
        }
        element.knob_node.remove(ctx);
        ctx.destroy_node(element.knob_node);
        element.track_node.remove(ctx);
        ctx.destroy_node(element.track_node);
        element.container_node.remove(ctx);
        ctx.destroy_node(element.container_node);
    }

    fn get_node(&self, element: &Self::Element) -> Node {
        element.container_node
    }

    fn handle_event(
        &self,
        element: &mut Self::Element,
        _state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>) {
        if let Event::Tick { .. } = event {
            let now = element.anim_start.elapsed().as_secs_f64() * 1000.0;
            if element.anim_progress.tick(now) || element.anim_progress.is_animating() {
                let progress = element.anim_progress.get();
                let pad_left = 2.0 + progress * 20.0;

                element.track_node.update_constraints(ctx, |c| {
                    c.padding.left = pad_left;
                });

                if !self.disabled {
                    let bg =
                        Color::interpolate(&self.style.off_bg, &self.style.on_bg, progress as f64);
                    element.track_node.update_effects(ctx, |e| {
                        e.background_color = bg;
                    });
                }

                ctx.request_frame();
                return (EventResult::Handled, None);
            }
        }

        if self.disabled {
            return (EventResult::Ignored, None);
        }

        match event {
            Event::MouseInput {
                pressed, hit_nodes, ..
            } => {
                let is_hit = hit_nodes.contains(&element.container_node)
                    || hit_nodes.contains(&element.track_node)
                    || hit_nodes.contains(&element.knob_node)
                    || element
                        .label_node
                        .map(|l| hit_nodes.contains(&l))
                        .unwrap_or(false);

                if is_hit && pressed {
                    element.is_pressed = true;
                    ctx.request_focus(element.track_node);
                    (EventResult::Handled, None)
                } else if !pressed && element.is_pressed {
                    element.is_pressed = false;
                    if is_hit {
                        let new_val = !self.is_on;
                        let msg = self.on_toggle.as_ref().map(|f| f(new_val));
                        (EventResult::Handled, msg)
                    } else {
                        (EventResult::Handled, None)
                    }
                } else {
                    (EventResult::Ignored, None)
                }
            }
            Event::KeyboardInput { event: k_event, .. } => {
                if Some(element.track_node) == ctx.focused_node() && k_event.state.is_pressed() {
                    match k_event.logical_key {
                        Key::Named(NamedKey::Enter) => {
                            let new_val = !self.is_on;
                            let msg = self.on_toggle.as_ref().map(|f| f(new_val));
                            (EventResult::Handled, msg)
                        }
                        Key::Character(ref s) if s == " " => {
                            let new_val = !self.is_on;
                            let msg = self.on_toggle.as_ref().map(|f| f(new_val));
                            (EventResult::Handled, msg)
                        }
                        _ => (EventResult::Ignored, None),
                    }
                } else {
                    (EventResult::Ignored, None)
                }
            }
            Event::Action { node, action, .. } => {
                if node == element.track_node || node == element.container_node {
                    match action {
                        accesskit::Action::Click => {
                            let new_val = !self.is_on;
                            let msg = self.on_toggle.as_ref().map(|f| f(new_val));
                            (EventResult::Handled, msg)
                        }
                        accesskit::Action::Focus => {
                            ctx.request_focus(element.track_node);
                            (EventResult::Handled, None)
                        }
                        _ => (EventResult::Ignored, None),
                    }
                } else {
                    (EventResult::Ignored, None)
                }
            }
            _ => (EventResult::Ignored, None),
        }
    }
}