masonry 0.5.0

Traits and types of the Masonry toolkit.
Documentation
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
// Copyright 2025 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

use std::any::TypeId;

use accesskit::{Node, Role, Toggled};
use include_doc_path::include_doc_path;
use tracing::{Span, trace, trace_span};

use crate::core::keyboard::Key;
use crate::core::{
    AccessCtx, AccessEvent, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, PaintCtx, PointerEvent,
    PropertiesMut, PropertiesRef, RegisterCtx, TextEvent, Update, UpdateCtx, UsesProperty, Widget,
    WidgetId, WidgetMut,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Circle, Join, Point, Rect, Size, Stroke};
use crate::layout::{LenReq, Length};
use crate::properties::{
    Background, BorderColor, BorderWidth, CornerRadius, ThumbColor, ThumbRadius, TrackThickness,
};

/// A switch switch that can be turned on or off.
///
#[doc = concat!(
    "![Switch in on state](",
    include_doc_path!("screenshots/switch_on_initial.png"),
    ")",
)]
///
/// This is a boolean control similar to a checkbox, but with a sliding switch appearance.
/// The switch displays a track with a circular thumb that sits on the left when off
/// and on the right when on.
///
/// Emits [`SwitchToggled`] when the user activates it.
/// Note that the on state does not automatically switch, and so one of
/// the responses to a `SwitchToggled` is to call [`Switch::set_on`]
/// on the originating widget.
///
/// This allows higher-level components to choose how the switch responds,
/// and ensure that its value is based on their correct source of truth.
///
/// # Classes
///
/// When toggled, this widget will have the `#toggled` [class].
///
/// [class]: masonry_core::doc::masonry_concepts#classes
pub struct Switch {
    on: bool,
}

// --- MARK: BUILDERS
impl Switch {
    /// Creates a new `Switch` with the given initial state.
    pub fn new(on: bool) -> Self {
        Self { on }
    }

    /// Returns whether the switch is currently on.
    pub fn is_on(&self) -> bool {
        self.on
    }
}

// --- MARK: WIDGETMUT
impl Switch {
    /// Sets the switch state.
    pub fn set_on(this: &mut WidgetMut<'_, Self>, on: bool) {
        this.widget.on = on;
        if on {
            this.ctx.add_class("#toggled");
        } else {
            this.ctx.remove_class("#toggled");
        }
    }
}

// --- MARK: HELPERS
impl Switch {
    /// Calculates the track dimensions based on properties.
    ///
    /// Returns `(track_width, track_height)`.
    fn track_dimensions(track_thickness: Length, thumb_radius: Length) -> (Length, Length) {
        // The track height is the larger of track_thickness or thumb diameter
        let track_height = track_thickness.max(thumb_radius.saturating_add(thumb_radius));
        // The track width is approximately 2x the height (pill shape)
        let track_width = track_height.saturating_add(track_height);

        (track_width, track_height)
    }
}

impl UsesProperty<ThumbRadius> for Switch {}
impl UsesProperty<ThumbColor> for Switch {}
impl UsesProperty<TrackThickness> for Switch {}

/// The action type emitted by [`Switch`] when it is activated.
///
/// The field is the target switch state (i.e. true is "this switch would like to become on").
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct SwitchToggled(pub bool);

// --- MARK: IMPL WIDGET
impl Widget for Switch {
    type Action = SwitchToggled;

    fn on_pointer_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &PointerEvent,
    ) {
        match event {
            PointerEvent::Down { .. } => {
                ctx.request_focus();
                ctx.capture_pointer();
                trace!("Switch {:?} pressed", ctx.widget_id());
            }
            PointerEvent::Up { .. } if ctx.is_active() && ctx.is_hovered() => {
                ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
                trace!("Switch {:?} released", ctx.widget_id());
            }
            _ => (),
        }
    }

    fn on_text_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &TextEvent,
    ) {
        match event {
            TextEvent::Keyboard(event) if event.state.is_up() => {
                // Space toggles the switch (per ARIA guidelines, Enter should submit forms)
                if matches!(&event.key, Key::Character(c) if c == " ") {
                    ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
                    ctx.set_handled();
                }
            }
            _ => (),
        }
    }

    fn accepts_focus(&self) -> bool {
        true
    }

    fn on_access_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &AccessEvent,
    ) {
        match event.action {
            accesskit::Action::Click => {
                ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
            }
            _ => {}
        }
    }

    fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
        match event {
            Update::WidgetAdded if self.on => {
                ctx.add_class("#toggled");
            }
            Update::HoveredChanged(_)
            | Update::ActiveChanged(_)
            | Update::FocusChanged(_)
            | Update::DisabledChanged(_) => {
                ctx.request_paint_only();
            }

            _ => {}
        }
    }

    fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        ThumbRadius::prop_changed(ctx, property_type);
        ThumbColor::prop_changed(ctx, property_type);
        TrackThickness::prop_changed(ctx, property_type);
    }

    fn measure(
        &mut self,
        ctx: &mut MeasureCtx<'_>,
        props: &PropertiesRef<'_>,
        axis: Axis,
        _len_req: LenReq,
        _cross_length: Option<Length>,
    ) -> Length {
        let cache = ctx.property_cache();
        let track_thickness = props.get::<TrackThickness>(cache).0;
        let thumb_radius = props.get::<ThumbRadius>(cache).0;
        let (track_width, track_height) = Self::track_dimensions(track_thickness, thumb_radius);

        match axis {
            Axis::Horizontal => track_width,
            Axis::Vertical => track_height,
        }
    }

    fn layout(&mut self, _ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, _size: Size) {}

    fn pre_paint(
        &mut self,
        _ctx: &mut PaintCtx<'_>,
        _props: &PropertiesRef<'_>,
        _painter: &mut Painter<'_>,
    ) {
        // TODO: Make Switch painting work with generic shadow/background/border
    }

    fn paint(
        &mut self,
        ctx: &mut PaintCtx<'_>,
        props: &PropertiesRef<'_>,
        painter: &mut Painter<'_>,
    ) {
        let is_disabled = ctx.is_disabled();

        let size = ctx.border_box().size();

        let border_box_translation = ctx.border_box_translation();
        let cache = ctx.property_cache();
        let track_thickness_val = props.get::<TrackThickness>(cache).0;
        let thumb_radius_val = props.get::<ThumbRadius>(cache).0;
        let (track_width, track_height) =
            Self::track_dimensions(track_thickness_val, thumb_radius_val);
        let track_width = track_width.get();
        let track_height = track_height.get();
        let thumb_radius = thumb_radius_val.get();
        let border_width = props.get::<BorderWidth>(cache).width.get();
        let corner_radius = props.get::<CornerRadius>(cache).radius.get();
        let thumb_color = props.get::<ThumbColor>(cache).0;

        // Center the track within the available space
        let track_x = (size.width - track_width) / 2.0;
        let track_y = (size.height - track_height) / 2.0;
        let track_rect = Rect::new(
            track_x,
            track_y,
            track_x + track_width,
            track_y + track_height,
        ) - border_box_translation;

        let track_bg = props.get::<Background>(cache);

        // Paint track background
        let track_corner_radius = corner_radius.min(track_height / 2.0);
        let track_rounded = track_rect.to_rounded_rect(track_corner_radius);
        let brush = track_bg.get_peniko_brush_for_rect(track_rect);
        painter.fill(track_rounded, &brush).draw();

        let border_color = props.get::<BorderColor>(cache);

        // Paint track border
        if border_width > 0.0 {
            // Use miter joins so a zero-radius track keeps square corners.
            let stroke = Stroke::new(border_width).with_join(Join::Miter);
            painter
                .stroke(track_rounded, &stroke, border_color.color)
                .draw();
        }

        // Calculate thumb position (centered vertically, left/right based on state)
        let thumb_y = size.height / 2.0 - border_box_translation.y;
        let thumb_x = if self.on {
            // Thumb on the right
            track_rect.x1 - thumb_radius - border_width / 2.0
        } else {
            // Thumb on the left
            track_rect.x0 + thumb_radius + border_width / 2.0
        };

        // Paint thumb
        let thumb_circle = Circle::new(Point::new(thumb_x, thumb_y), thumb_radius);
        let thumb_brush = if is_disabled {
            thumb_color.with_alpha(0.5)
        } else {
            thumb_color
        };
        painter.fill(thumb_circle, thumb_brush).draw();
    }

    fn accessibility_role(&self) -> Role {
        Role::Switch
    }

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        node: &mut Node,
    ) {
        node.add_action(accesskit::Action::Click);
        if self.on {
            node.set_toggled(Toggled::True);
        } else {
            node.set_toggled(Toggled::False);
        }
    }

    fn children_ids(&self) -> ChildrenIds {
        ChildrenIds::new()
    }

    fn make_trace_span(&self, id: WidgetId) -> Span {
        trace_span!("Switch", id = id.trace())
    }

    fn get_debug_text(&self) -> Option<String> {
        if self.on {
            Some("[ON]".to_string())
        } else {
            Some("[OFF]".to_string())
        }
    }
}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::TextEvent;
    use crate::properties::types::{CrossAxisAlignment, MainAxisAlignment};
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::test_property_set;
    use crate::widgets::Flex;

    // --- MARK: NON-RENDERING BEHAVIOR TESTS

    #[test]
    fn click_emits_action_and_focuses() {
        let widget = Switch::new(false).prepare();
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
        let switch_id = harness.root_id();
        let switch_tag = harness.root_tag();

        // Initially not focused, and no actions
        assert!(harness.focused_widget().is_none());
        // Initially no actions
        assert!(harness.pop_action_erased().is_none());

        // Click on switch (off -> wants to be on)
        harness.mouse_click_on(switch_tag, None);
        assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));
        assert_eq!(
            harness.pop_action::<SwitchToggled>(),
            Some((SwitchToggled(true), switch_id))
        );

        // Update state to on
        harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));

        // Click again (on -> wants to be off)
        harness.mouse_click_on(switch_tag, None);
        assert_eq!(
            harness.pop_action::<SwitchToggled>(),
            Some((SwitchToggled(false), switch_id))
        );
    }

    #[test]
    fn space_emits_action_when_focused() {
        let widget = Switch::new(false).prepare();
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
        let switch_id = harness.root_id();

        // Focus via tab
        harness.clear_focus();
        harness.press_tab_key(false);
        assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));

        // Space key should switch (off -> wants on)
        harness.process_text_event(TextEvent::key_down(Key::Character(" ".into())));
        harness.process_text_event(TextEvent::key_up(Key::Character(" ".into())));
        assert_eq!(
            harness.pop_action::<SwitchToggled>(),
            Some((SwitchToggled(true), switch_id))
        );

        // Update state
        harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));

        // Space again (on -> wants off)
        harness.process_text_event(TextEvent::key_down(Key::Character(" ".into())));
        harness.process_text_event(TextEvent::key_up(Key::Character(" ".into())));
        assert_eq!(
            harness.pop_action::<SwitchToggled>(),
            Some((SwitchToggled(false), switch_id))
        );
    }

    #[test]
    fn measure_dimensions() {
        // Test that the switch measures to expected dimensions based on theme properties.
        // Theme defaults: ThumbRadius(8px), TrackThickness(20px), BorderWidth(1px)
        // Expected: track_height = max(20, 8*2) = 20, track_width = 20*2 = 40
        // With borders: width = 42, height = 22
        let switch = Switch::new(false).prepare();
        let switch_id = switch.id();

        // Wrap in Flex with Start alignment so it doesn't stretch the switch
        let flex = Flex::row()
            .with_fixed(switch)
            .main_axis_alignment(MainAxisAlignment::Start)
            .cross_axis_alignment(CrossAxisAlignment::Start);

        // Give it much more space than needed
        let harness =
            TestHarness::create_with_size(test_property_set(), flex.prepare(), (200, 100));

        let size = harness
            .get_widget_with_id(switch_id)
            .ctx()
            .border_box()
            .size();

        // Switch should maintain its intrinsic size, not fill available space
        assert_eq!(
            size.width, 42.0,
            "Switch width should be 2*track_height + 2*border"
        );
        assert_eq!(
            size.height, 22.0,
            "Switch height should be track_height + 2*border"
        );
    }

    // --- MARK: SNAPSHOT TESTS

    #[test]
    fn simple_switch() {
        let widget = Switch::new(false).prepare();

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
        let switch_id = harness.root_id();
        let switch_tag = harness.root_tag();

        assert_render_snapshot!(harness, "switch_off");

        assert!(harness.pop_action_erased().is_none());

        // Hover without clicking to show hovered state (no focus)
        harness.mouse_move_to(switch_tag);
        assert_render_snapshot!(harness, "switch_off_hovered");

        // Now click to switch
        harness.mouse_click_on(switch_tag, None);
        assert_eq!(
            harness.pop_action::<SwitchToggled>(),
            Some((SwitchToggled(true), switch_id))
        );

        harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));

        // After clicking, the switch is both focused and hovered
        assert_render_snapshot!(harness, "switch_on_focused_hovered");
    }

    #[test]
    fn focus_visual() {
        let widget = Switch::new(false).prepare();

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
        let switch_tag = harness.root_tag();
        let switch_id = harness.root_id();

        // Focus directly (not via click) to get focused-but-not-hovered state
        harness.focus_on(switch_tag);
        assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));

        assert_render_snapshot!(harness, "switch_focused");
    }

    #[test]
    fn on_state() {
        let widget = Switch::new(true).prepare();

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));

        assert_render_snapshot!(harness, "switch_on_initial");
    }
}