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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright 2019 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

use std::any::TypeId;

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

use crate::core::{
    AccessCtx, ChildrenIds, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx, PropertiesRef,
    RegisterCtx, UpdateCtx, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{LayoutSize, LenReq, Length};
use crate::properties::{BorderWidth, Padding};

/// A widget with bi-directional size enforcement.
///
/// It can either have an explicit size or it will adopt the size of its child.
///
/// ## Explicit size
///
/// There are two ways to define a size for `SizedBox`, in order of priority:
/// 1. [`Dimensions`] properties work as usual and take precedence over anything else.
/// 2. There are methods to configure the inner fields for width and height.
///
/// ## Adopted size
///
/// If there is no explicit size and the parent widget chooses to measure `SizedBox`,
/// then the `SizedBox::measure` method will forward its child's `measure` result.
/// This does not guarantee anything, but it usually means the parent will choose
/// the `SizedBox` child's measurement result as the size for `SizedBox`.
/// Set [`Dimensions::MAX`] for `SizedBox` to ensure there is no explicit size from props either.
///
/// ## Child's size
///
/// Whatever content-box size `SizedBox` ends up getting from its parent for layout,
/// `SizedBox` will force its child to use that same size for its border-box.
///
/// ## No child
///
/// The childless case works exactly as if there was a zero sized child.
/// The main impact being that the adopted size will be zero.
///
/// ## Borders and Padding
///
/// The explicit size may be increased to ensure that the border and padding fit.
/// When adopting the child's size, that size will be expanded by the `SizedBox` border and padding.
/// The size forced on the child is shrunk by the `SizedBox` border and padding.
///
/// [`Dimensions`]: crate::properties::Dimensions
/// [`Dimensions::MAX`]: crate::properties::Dimensions::MAX
#[doc = concat!(
    "![Box with blue border, pink background and a child label](",
    include_doc_path!("screenshots/sized_box_label_box_with_padding.png"),
    ")",
)]
pub struct SizedBox {
    child: Option<WidgetPod<dyn Widget>>,
    width: Option<Length>,
    height: Option<Length>,
}

// --- MARK: BUILDERS
impl SizedBox {
    /// Creates container with child, and both width and height unset.
    pub fn new(child: NewWidget<impl Widget + ?Sized>) -> Self {
        Self {
            child: Some(child.erased().to_pod()),
            width: None,
            height: None,
        }
    }

    /// Creates container without a child, and both width and height unset.
    ///
    /// In this state it will render no content but will still render its border and padding.
    #[doc(alias = "null")]
    pub fn empty() -> Self {
        Self {
            child: None,
            width: None,
            height: None,
        }
    }

    /// Returns the container with `width`.
    pub fn width(mut self, width: Length) -> Self {
        self.width = Some(width);
        self
    }

    /// Returns the container with `height`.
    pub fn height(mut self, height: Length) -> Self {
        self.height = Some(height);
        self
    }

    /// Returns the container with `width` and `height`.
    pub fn size(mut self, width: Length, height: Length) -> Self {
        self.width = Some(width);
        self.height = Some(height);
        self
    }

    /// Returns the container with `width`.
    ///
    /// `None` means that the width will be adopted from the child.
    pub fn raw_width(mut self, width: Option<Length>) -> Self {
        self.width = width;
        self
    }

    /// Returns the container with `height`.
    ///
    /// `None` means that the height will be adopted from the child.
    pub fn raw_height(mut self, height: Option<Length>) -> Self {
        self.height = height;
        self
    }
}

// --- MARK: METHODS
impl SizedBox {
    /// Returns the length of the given `axis`.
    pub const fn length(&self, axis: Axis) -> Option<Length> {
        match axis {
            Axis::Horizontal => self.width,
            Axis::Vertical => self.height,
        }
    }
}

// --- MARK: WIDGETMUT
impl SizedBox {
    /// Replaces the child widget with a new one.
    pub fn set_child(this: &mut WidgetMut<'_, Self>, child: NewWidget<impl Widget + ?Sized>) {
        if let Some(child) = this.widget.child.take() {
            this.ctx.remove_child(child);
        }
        this.widget.child = Some(child.erased().to_pod());
        this.ctx.children_changed();
    }

    /// Removes the child widget.
    ///
    /// (If this widget has no child, this method does nothing.)
    pub fn remove_child(this: &mut WidgetMut<'_, Self>) {
        if let Some(child) = this.widget.child.take() {
            this.ctx.remove_child(child);
        }
    }

    /// Sets container's width.
    pub fn set_width(this: &mut WidgetMut<'_, Self>, width: Length) {
        this.widget.width = Some(width);
        this.ctx.request_layout();
    }

    /// Sets container's height.
    pub fn set_height(this: &mut WidgetMut<'_, Self>, height: Length) {
        this.widget.height = Some(height);
        this.ctx.request_layout();
    }

    /// Sets container's width and height.
    pub fn set_size(this: &mut WidgetMut<'_, Self>, width: Length, height: Length) {
        this.widget.width = Some(width);
        this.widget.height = Some(height);
        this.ctx.request_layout();
    }

    /// Unsets container's width.
    pub fn unset_width(this: &mut WidgetMut<'_, Self>) {
        this.widget.width = None;
        this.ctx.request_layout();
    }

    /// Unsets container's height.
    pub fn unset_height(this: &mut WidgetMut<'_, Self>) {
        this.widget.height = None;
        this.ctx.request_layout();
    }

    /// Sets the container's `width` directly.
    ///
    /// `None` means that the width will be adopted from the child.
    pub fn set_raw_width(this: &mut WidgetMut<'_, Self>, width: Option<Length>) {
        this.widget.width = width;
        this.ctx.request_layout();
    }

    /// Sets the container's `height` directly.
    ///
    /// `None` means that the height will be adopted from the child.
    pub fn set_raw_height(this: &mut WidgetMut<'_, Self>, height: Option<Length>) {
        this.widget.height = height;
        this.ctx.request_layout();
    }

    /// Returns mutable reference to the child widget, if any.
    pub fn child_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> Option<WidgetMut<'t, dyn Widget>> {
        let child = this.widget.child.as_mut()?;
        Some(this.ctx.get_mut(child))
    }
}

// --- MARK: IMPL WIDGET
impl Widget for SizedBox {
    type Action = NoAction;

    fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
        if let Some(ref mut child) = self.child {
            ctx.register_child(child);
        }
    }

    fn property_changed(&mut self, _ctx: &mut UpdateCtx<'_>, _property_type: TypeId) {}

    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 border = props.get::<BorderWidth>(cache);
        let padding = props.get::<Padding>(cache);

        let border_length = border.length(axis);
        let padding_length = padding.length(axis);

        // First see if we have an explicitly defined length
        if let Some(length) = self.length(axis) {
            return length
                .saturating_sub(border_length)
                .saturating_sub(padding_length);
        }

        // Otherwise measure the child
        if let Some(child) = self.child.as_mut() {
            let cross = axis.cross();
            let cross_length = cross_length.or_else(|| {
                // Can't use self.length() due to borrow checker stupidity,
                // so we need to manually inline that method.
                let length = match cross {
                    Axis::Horizontal => self.width,
                    Axis::Vertical => self.height,
                };
                length.map(|length| {
                    length
                        .saturating_sub(border.length(cross))
                        .saturating_sub(padding.length(cross))
                })
            });

            let auto_length = len_req.into();
            let context_size = LayoutSize::maybe(cross, cross_length);

            ctx.compute_length(child, auto_length, context_size, axis, cross_length)
        } else {
            Length::ZERO
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
        let Some(child) = self.child.as_mut() else {
            // No child, so no layout work beyond resetting baselines
            ctx.clear_baselines();
            return;
        };

        ctx.run_layout(child, size);
        ctx.place_child(child, Point::ORIGIN);
        ctx.derive_baselines(child);
    }

    fn paint(
        &mut self,
        _ctx: &mut PaintCtx<'_>,
        _props: &PropertiesRef<'_>,
        _painter: &mut Painter<'_>,
    ) {
    }

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

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        _node: &mut Node,
    ) {
    }

    fn children_ids(&self) -> ChildrenIds {
        if let Some(child) = &self.child {
            ChildrenIds::from_slice(&[child.id()])
        } else {
            ChildrenIds::from_slice(&[])
        }
    }

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

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::PropertySet;
    use crate::layout::{AsUnit, UnitPoint};
    use crate::palette;
    use crate::properties::types::Gradient;
    use crate::properties::{Background, BorderColor, CornerRadius};
    use crate::testing::{TestHarness, assert_failing_render_snapshot, assert_render_snapshot};
    use crate::theme::test_property_set;
    use crate::widgets::Label;

    // TODO - Add WidgetMut tests

    #[test]
    fn empty_box() {
        let mut box_props = PropertySet::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(5.px()));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_empty_box");
    }

    #[test]
    fn label_box_no_size() {
        let mut box_props = PropertySet::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(5.px()));

        let widget = SizedBox::new(Label::new("hello").prepare())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_label_box_no_size");
    }

    #[test]
    fn label_box_with_size() {
        let mut box_props = PropertySet::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(5.px()));

        let widget = SizedBox::new(Label::new("hello").prepare())
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_label_box_with_size");
    }

    #[test]
    fn label_box_with_padding() {
        let mut box_props = PropertySet::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(5.px()));
        box_props.insert(Padding::from_vh(15.px(), 10.px()));

        let widget = SizedBox::new(Label::new("hello").prepare())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_label_box_with_padding");
    }

    #[test]
    fn label_box_with_solid_background() {
        let mut box_props = PropertySet::new();
        box_props.insert(Background::Color(palette::css::PLUM));

        let widget = SizedBox::new(Label::new("hello").prepare())
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_label_box_with_solid_background");
    }

    #[test]
    fn empty_box_with_gradient_background() {
        let mut box_props = PropertySet::new();

        let gradient = Gradient::new_linear(2.0).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(10.px()));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_empty_box_with_gradient_background");
    }

    #[test]
    fn radial_gradient_background() {
        let mut box_props = PropertySet::new();

        let gradient = Gradient::new_radial(UnitPoint::CENTER).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(10.px()));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_radial_gradient_background");
    }

    #[test]
    fn sweep_gradient_background() {
        let mut box_props = PropertySet::new();

        let gradient = Gradient::new_full_sweep(UnitPoint::CENTER, 0.).with_stops([
            palette::css::WHITE,
            palette::css::BLACK,
            palette::css::RED,
            palette::css::GREEN,
            palette::css::WHITE,
        ]);
        box_props.insert(Background::Gradient(gradient));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(10.px()));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_sweep_gradient_background");
    }

    #[test]
    fn label_box_with_padding_and_background() {
        let mut box_props = PropertySet::new();
        box_props.insert(Background::Color(palette::css::PLUM));
        box_props.insert(BorderColor::new(palette::css::LIGHT_SKY_BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(Padding::all(25.px()));

        let widget = SizedBox::new(Label::new("hello").prepare())
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_render_snapshot!(harness, "sized_box_label_box_with_background_and_padding");
    }

    // --- MARK: INVALID SCREENSHOT TESTS

    #[test]
    fn invalid_screenshot() {
        // Copy-pasted from empty_box
        let mut box_props = PropertySet::new();
        box_props.insert(BorderColor::new(palette::css::BLUE));
        box_props.insert(BorderWidth::all(5.px()));
        box_props.insert(CornerRadius::all(5.px()));

        // This is the difference
        box_props.insert(BorderWidth::all(5.2.px()));

        let widget = SizedBox::empty()
            .width(20.px())
            .height(20.px())
            .prepare()
            .with_props(box_props);

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

        assert_failing_render_snapshot!(harness, "sized_box_empty_box");
    }
}