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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright 2026 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 masonry_core::debug_panic;
use tracing::{Span, trace, trace_span};

use crate::core::{
    AccessCtx, AccessEvent, ArcStr, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NewWidget,
    PaintCtx, PointerEvent, PrePaintProps, PropertiesMut, PropertiesRef, RegisterCtx, TextEvent,
    Update, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod, keyboard::Key,
    paint_background, paint_box_shadow,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Cap, Circle, Dashes, Join, Point, Size, Stroke};
use crate::layout::{LayoutSize, LenReq, Length, SizeDef};
use crate::properties::{BorderColor, BorderWidth, CheckmarkColor, CheckmarkStrokeWidth};
use crate::theme;
use crate::widgets::{Label, RadioGroup};

/// A radio button that can be toggled.
///
#[doc = concat!(
    "![Radio button with checked state](",
    include_doc_path!("screenshots/radio_button_hello_checked.png"),
    ")",
)]
///
/// Emits [`RadioButtonSelected`] when selected.
pub struct RadioButton {
    selected: bool,
    // FIXME - Remove label child, have this widget only be a box with a checkmark.
    label: WidgetPod<Label>,
    parent_group: Option<WidgetId>,
}

impl RadioButton {
    /// Create a new `RadioButton` with a text label.
    pub fn new(checked: bool, text: impl Into<ArcStr>) -> Self {
        Self {
            selected: checked,
            label: WidgetPod::new(Label::new(text)),
            parent_group: None,
        }
    }

    /// Create a new `RadioButton` with the given label.
    pub fn from_label(checked: bool, label: NewWidget<Label>) -> Self {
        Self {
            selected: checked,
            label: label.to_pod(),
            parent_group: None,
        }
    }
}

// --- MARK: WIDGETMUT
impl RadioButton {
    /// Check or uncheck the box.
    pub fn set_checked(this: &mut WidgetMut<'_, Self>, checked: bool) {
        this.widget.selected = checked;
        // Checked state impacts appearance and accessibility node
        this.ctx.request_render();

        let Some(parent_id) = this.widget.parent_group else {
            return;
        };
        let self_id = this.ctx.widget_id();
        this.ctx.mutate_later(parent_id, move |mut group| {
            let group = group.downcast::<RadioGroup>();
            Self::update_group(group, self_id, checked);
        });
    }

    /// Set the text.
    ///
    /// We enforce this to be an `ArcStr` to make the allocation explicit.
    pub fn set_text(this: &mut WidgetMut<'_, Self>, new_text: ArcStr) {
        Label::set_text(&mut Self::label_mut(this), new_text);
    }

    /// Get a mutable reference to the label.
    pub fn label_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, Label> {
        this.ctx.get_mut(&mut this.widget.label)
    }
}

impl UsesProperty<CheckmarkColor> for RadioButton {}

/// The action type emitted by [`RadioButton`] when it is selected.
///
/// There is no equivalent action for deselection.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct RadioButtonSelected;

// --- MARK: HELPERS
impl RadioButton {
    fn select(&mut self, ctx: &mut EventCtx<'_>) {
        self.selected = true;
        ctx.submit_action::<RadioButtonSelected>(RadioButtonSelected);
        ctx.request_render();

        let Some(parent_id) = self.parent_group else {
            return;
        };
        let self_id = ctx.widget_id();
        ctx.mutate_later(parent_id, move |mut group| {
            let group = group.downcast::<RadioGroup>();
            Self::update_group(group, self_id, true);
        });
    }

    fn update_group(mut group: WidgetMut<'_, RadioGroup>, self_id: WidgetId, selected: bool) {
        let selected_button = group.widget.selected_button;
        if let Some(button_id) = selected_button
            && button_id != self_id
            && selected
        {
            // We don't bother checking that the button still exists,
            // the mutate pass does that for us.
            group.ctx.mutate_later(button_id, move |mut group| {
                let mut button = group.downcast::<Self>();
                button.widget.selected = false;
                button.ctx.request_render();
            });
            // TODO - Submit action from RadioGroup?
        }

        if let Some(button_id) = selected_button
            && button_id == self_id
            && !selected
        {
            group.widget.selected_button = None;
        }
        if selected {
            group.widget.selected_button = Some(self_id);
        }
    }
}

// --- MARK: IMPL WIDGET
impl Widget for RadioButton {
    type Action = RadioButtonSelected;

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

    fn on_text_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &TextEvent,
    ) {
        match event {
            TextEvent::Keyboard(event) if event.state.is_up() => {
                if matches!(&event.key, Key::Character(c) if c == " ") {
                    self.select(ctx);
                }
            }
            _ => (),
        }
    }

    fn accepts_focus(&self) -> bool {
        // RadioButton can be tab-focused...
        true
    }

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

    fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
        match event {
            Update::WidgetAdded => {
                let Some((_, id)) = ctx.nearest_ancestor::<RadioGroup>() else {
                    let id = ctx.widget_id();
                    debug_panic!("RadioButton {id} is not a child of a RadioGroup");
                    return;
                };

                self.parent_group = Some(id);
            }
            Update::HoveredChanged(_)
            | Update::ActiveChanged(_)
            | Update::FocusChanged(_)
            | Update::DisabledChanged(_) => {
                ctx.request_paint_only();
            }

            _ => {}
        }
    }

    fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
        ctx.register_child(&mut self.label);
    }

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        CheckmarkStrokeWidth::prop_changed(ctx, property_type);
        CheckmarkColor::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 check_side = theme::BASIC_WIDGET_HEIGHT;
        let check_padding = theme::WIDGET_CONTROL_COMPONENT_PADDING;

        let calc_other_length = |axis| match axis {
            Axis::Horizontal => check_side.saturating_add(check_padding),
            Axis::Vertical => Length::ZERO,
        };
        let other_length = calc_other_length(axis);

        let cross = axis.cross();
        let cross_space = cross_length.map(|cross_length| {
            let cross_other_length = calc_other_length(cross);
            cross_length.saturating_sub(cross_other_length)
        });

        let auto_length = len_req.reduce(other_length).into();
        let context_size = LayoutSize::maybe(cross, cross_space);

        let label_length = ctx.compute_length(
            &mut self.label,
            auto_length,
            context_size,
            axis,
            cross_space,
        );

        match axis {
            Axis::Horizontal => label_length.saturating_add(other_length),
            Axis::Vertical => label_length.max(check_side).saturating_add(other_length),
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
        let check_side = theme::BASIC_WIDGET_HEIGHT.get();
        let check_padding = theme::WIDGET_CONTROL_COMPONENT_PADDING.get();

        let space = Size::new(
            (size.width - (check_side + check_padding)).max(0.),
            size.height,
        );

        let label_size = ctx.compute_size(&mut self.label, SizeDef::fit(space), space.into());
        ctx.run_layout(&mut self.label, label_size);

        let label_origin = Point::new(check_side + check_padding, 0.);
        ctx.place_child(&mut self.label, label_origin);

        ctx.derive_baselines(&self.label);
    }

    fn pre_paint(
        &mut self,
        ctx: &mut PaintCtx<'_>,
        props: &PropertiesRef<'_>,
        painter: &mut Painter<'_>,
    ) {
        let bbox = ctx.border_box();
        let cache = ctx.property_cache();
        let p = PrePaintProps::fetch(props, cache);

        paint_box_shadow(painter, bbox, p.box_shadow, p.corner_radius);
        paint_background(painter, bbox, p.background, p.border_width, p.corner_radius);

        // Paint focus indicator around the entire widget (box + label)
        if ctx.is_focus_target() || ctx.is_hovered() {
            // TODO: Replace this custom implementation with the general paint_border()

            let focus_rect = bbox.inflate(2.0, 2.0);

            let focus_color = p.border_color.color;
            let focus_width = 2.0;
            let focus_radius = 4.0;

            let focus_stroke = Stroke {
                width: focus_width,
                join: Join::Round,
                miter_limit: 10.0,
                start_cap: Cap::Round,
                end_cap: Cap::Round,
                dash_pattern: Dashes::default(),
                dash_offset: 0.0,
            };
            let focus_path = focus_rect.to_rounded_rect(focus_radius);
            painter
                .stroke(focus_path, &focus_stroke, focus_color)
                .draw();
        }
        // Skip painting the regular border while the check border uses that property
    }

    fn paint(
        &mut self,
        ctx: &mut PaintCtx<'_>,
        props: &PropertiesRef<'_>,
        painter: &mut Painter<'_>,
    ) {
        let cache = ctx.property_cache();
        let border_color = *props.get::<BorderColor>(cache);
        let border_width = *props.get::<BorderWidth>(cache);
        let brush = *props.get::<CheckmarkColor>(cache);

        let check_side = theme::BASIC_WIDGET_HEIGHT.get();
        let check_size = Size::new(check_side, check_side);

        let border_circle = Circle::new(
            check_size.to_rect().center(),
            (check_side - border_width.width.get()) * 0.5,
        );

        // Paint the radio button border
        let border_stroke = Stroke::new(border_width.width.get());
        painter
            .stroke(border_circle, &border_stroke, border_color.color)
            .draw();

        // Paint the checkmark if checked
        if self.selected {
            // TODO: Create a prop for ellipse size. Default: 50% of border size
            let check_circle = Circle::new(check_size.to_rect().center(), check_side * 0.25);
            painter.fill(check_circle, brush.color).draw();
        }
    }

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

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

    fn children_ids(&self) -> ChildrenIds {
        ChildrenIds::from_slice(&[self.label.id()])
    }

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

    fn get_debug_text(&self) -> Option<String> {
        if self.selected {
            Some("(X)".to_string())
        } else {
            Some("( )".to_string())
        }
    }
}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{StyleProperty, WidgetTag};
    use crate::properties::ContentColor;
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::{ACCENT_COLOR, default_property_set};
    use crate::widgets::Flex;

    #[test]
    fn simple_radio_button() {
        let radio_tag = WidgetTag::unique();
        let widget = NewWidget::new(RadioButton::new(false, "Hello")).with_tag(radio_tag);
        let widget = NewWidget::new(RadioGroup::new(widget));

        let mut harness = TestHarness::create_with_size(default_property_set(), widget, (100, 40));
        let radio_id = harness.get_widget(radio_tag).id();

        assert_render_snapshot!(harness, "radio_button_hello_unchecked");

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

        harness.mouse_move_to(radio_tag);

        assert_render_snapshot!(harness, "radio_button_hello_hovered");

        harness.mouse_click_on(radio_tag, None);
        assert_eq!(
            harness.pop_action::<RadioButtonSelected>(),
            Some((RadioButtonSelected, radio_id))
        );

        assert_render_snapshot!(harness, "radio_button_hello_checked");

        harness.edit_root_widget(|mut group| {
            let mut radio = RadioGroup::child_mut(&mut group);
            let mut radio = radio.downcast();
            RadioButton::set_checked(&mut radio, false);
        });

        // The radio button should be unchecked again, but still hovered
        assert_render_snapshot!(harness, "radio_button_hello_hovered");

        harness.clear_focus();
        harness.press_tab_key(false);
        assert_eq!(harness.focused_widget().map(|w| w.id()), Some(radio_id));
    }

    #[test]
    fn radio_button_focus_indicator() {
        use crate::properties::types::MainAxisAlignment;

        let radio_tag = WidgetTag::unique();
        let radio = NewWidget::new(RadioButton::new(true, "Focus test")).with_tag(radio_tag);
        let group = NewWidget::new(RadioGroup::new(radio));

        let root = NewWidget::new(
            Flex::row()
                .with_fixed(group)
                .main_axis_alignment(MainAxisAlignment::Center),
        );
        let mut harness = TestHarness::create_with_size(default_property_set(), root, (120, 40));

        harness.focus_on(radio_tag);
        assert_render_snapshot!(harness, "radio_button_focus_focused");
    }

    #[test]
    fn edit_radio_button() {
        let image_1 = {
            let label = Label::new("The quick brown fox jumps over the lazy dog")
                .with_style(StyleProperty::FontSize(20.0));
            let label = NewWidget::new(label).with_props(ContentColor::new(ACCENT_COLOR));
            let radio = NewWidget::new(RadioButton::from_label(true, label));
            let group = NewWidget::new(RadioGroup::new(radio));

            let mut harness =
                TestHarness::create_with_size(default_property_set(), group, (50, 50));

            harness.render()
        };

        let image_2 = {
            let radio = NewWidget::new(RadioButton::new(false, "Hello world"));
            let group = NewWidget::new(RadioGroup::new(radio));

            let mut harness =
                TestHarness::create_with_size(default_property_set(), group, (50, 50));

            harness.edit_root_widget(|mut group| {
                let mut radio = RadioGroup::child_mut(&mut group);
                let mut radio = radio.downcast();
                RadioButton::set_checked(&mut radio, true);
                RadioButton::set_text(
                    &mut radio,
                    ArcStr::from("The quick brown fox jumps over the lazy dog"),
                );

                let mut label = RadioButton::label_mut(&mut radio);
                label.insert_prop(ContentColor::new(ACCENT_COLOR));
                Label::insert_style(&mut label, StyleProperty::FontSize(20.0));
            });

            harness.render()
        };

        // We don't use assert_eq because we don't want rich assert
        assert!(image_1 == image_2);
    }
}