waft-material 0.14.1

Material Design widgets for Waft
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Flutter counterpart: material_ui's `divider_theme.dart`.

use waft_embedder::{Color, lerp_double};
use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
use waft_painting::{BorderRadiusGeometry, ColorProperty};
use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};

use crate::theme::Theme;

/// Defines the visual properties of [`Divider`](crate::Divider), `VerticalDivider`,
/// `Divider::create_border_side`, and `ListTile`'s dividers.
///
/// Descendant widgets obtain the current [`DividerThemeData`] object using
/// [`DividerTheme::of`]. Instances of [`DividerThemeData`] can be customized with
/// [`DividerThemeData::copy_with`].
///
/// Typically a [`DividerThemeData`] is specified as part of the overall `Theme` with
/// `ThemeData::divider_theme`.
///
/// All [`DividerThemeData`] properties are `None` by default. When null, the `Divider`
/// will use the values from `ThemeData` if they exist, otherwise it will provide its own
/// defaults based on the overall `Theme`'s textTheme and colorScheme. See the individual
/// `Divider` properties for details.
///
/// See also:
///
///  * [`DividerTheme`], an [`InheritedWidget`] that propagates the theme down its subtree.
///  * `ThemeData::divider_theme`, which describes the overall theme information for the
///    application.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DividerThemeData {
    /// The color of [`Divider`](crate::Divider)s and `VerticalDivider`s.
    pub color: Option<Color>,

    /// The `Divider`'s height or the `VerticalDivider`'s width.
    ///
    /// This represents the amount of horizontal or vertical space the divider takes up.
    pub space: Option<f64>,

    /// The thickness of the line drawn within the divider.
    pub thickness: Option<f64>,

    /// The amount of empty space at the leading edge of [`Divider`](crate::Divider) or
    /// top edge of `VerticalDivider`.
    pub indent: Option<f64>,

    /// The amount of empty space at the trailing edge of [`Divider`](crate::Divider) or
    /// bottom edge of `VerticalDivider`.
    pub end_indent: Option<f64>,

    /// The border radius of the [`Divider`](crate::Divider) and `VerticalDivider`.
    pub radius: Option<BorderRadiusGeometry>,
}

crate::theme_data_getters::theme_data_getters! {
    /// Dart's getters of `DividerThemeData`: the theme data answers with its fields, and a defaults
    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
    /// are read.
    pub trait DividerThemeDataGetters for DividerThemeData, fields: divider_theme_data {
        color: Option<Color>,
        space: Option<f64>,
        thickness: Option<f64>,
        indent: Option<f64>,
        end_indent: Option<f64>,
        radius: Option<BorderRadiusGeometry>,
    }
}

impl DividerThemeData {
    /// Creates a theme that can be used for `ThemeData::divider_theme`. Dart's optional
    /// named arguments are the fluent setters.
    pub fn new() -> DividerThemeData {
        DividerThemeData::default()
    }

    /// Dart `DividerThemeData(color:)`.
    pub fn color(mut self, color: Color) -> DividerThemeData {
        self.color = Some(color);
        self
    }

    /// Dart `DividerThemeData(space:)`.
    pub fn space(mut self, space: f64) -> DividerThemeData {
        self.space = Some(space);
        self
    }

    /// Dart `DividerThemeData(thickness:)`.
    pub fn thickness(mut self, thickness: f64) -> DividerThemeData {
        self.thickness = Some(thickness);
        self
    }

    /// Dart `DividerThemeData(indent:)`.
    pub fn indent(mut self, indent: f64) -> DividerThemeData {
        self.indent = Some(indent);
        self
    }

    /// Dart `DividerThemeData(endIndent:)`.
    pub fn end_indent(mut self, end_indent: f64) -> DividerThemeData {
        self.end_indent = Some(end_indent);
        self
    }

    /// Dart `DividerThemeData(radius:)`.
    pub fn radius(mut self, radius: impl Into<BorderRadiusGeometry>) -> DividerThemeData {
        self.radius = Some(radius.into());
        self
    }

    /// Creates a copy of this object with the given fields replaced with the new values.
    ///
    /// Dart's named arguments are the fluent setters on the copy
    /// (`data.copy_with().color(color)`).
    pub fn copy_with(&self) -> DividerThemeData {
        self.clone()
    }

    /// Linearly interpolate between two Divider themes.
    ///
    /// {@macro dart.ui.shadow.lerp}
    pub fn lerp(
        a: Option<&DividerThemeData>,
        b: Option<&DividerThemeData>,
        t: f64,
    ) -> DividerThemeData {
        if let (Some(a), Some(b)) = (a, b)
            && std::ptr::eq(a, b)
        {
            return a.clone();
        }
        DividerThemeData {
            color: Color::lerp(a.and_then(|a| a.color), b.and_then(|b| b.color), t),
            space: lerp_double(a.and_then(|a| a.space), b.and_then(|b| b.space), t),
            thickness: lerp_double(a.and_then(|a| a.thickness), b.and_then(|b| b.thickness), t),
            indent: lerp_double(a.and_then(|a| a.indent), b.and_then(|b| b.indent), t),
            end_indent: lerp_double(
                a.and_then(|a| a.end_indent),
                b.and_then(|b| b.end_indent),
                t,
            ),
            radius: BorderRadiusGeometry::lerp(
                a.and_then(|a| a.radius),
                b.and_then(|b| b.radius),
                t,
            ),
        }
    }
}

/// An inherited widget that defines the configuration for
/// [`Divider`](crate::Divider)s, `VerticalDivider`s, dividers between `ListTile`s, and
/// dividers between rows in `DataTable`s in this widget's subtree.
#[derive(Debug)]
pub struct DividerTheme {
    pub key: Option<KeyRef>,
    /// The properties for descendant `Divider` widgets.
    pub data: DividerThemeData,
    pub child: WidgetRef,
}

impl DividerTheme {
    /// Creates a divider theme that controls the configurations for
    /// [`Divider`](crate::Divider)s and `VerticalDivider`s in its widget subtree.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(data: DividerThemeData, child: impl IntoWidget<K>) -> DividerTheme {
        DividerTheme {
            key: None,
            data,
            child: child.into_widget(),
        }
    }

    /// Dart `DividerTheme(key:)`.
    pub fn key(mut self, key: KeyRef) -> DividerTheme {
        self.key = Some(key);
        self
    }

    /// The data from the closest instance of this class that encloses the given context.
    ///
    /// If there is no enclosing [`DividerTheme`] widget, then `ThemeData::divider_theme`
    /// is used.
    ///
    /// Typical usage is as follows:
    ///
    /// ```text
    /// let theme = DividerTheme::of(app, context);
    /// ```
    pub fn of(app: &mut App, context: BuildContext) -> DividerThemeData {
        match context.depend_on_inherited_widget_of_exact_type::<DividerTheme>(app) {
            Some(divider_theme) => divider_theme.data.clone(),
            None => Theme::of(app, context).divider_theme.clone(),
        }
    }
}

impl InheritedTheme for DividerTheme {
    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
        DividerTheme::new(self.data.clone(), child).into_widget()
    }
}

impl InheritedWidget for DividerTheme {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &DividerTheme) -> bool {
        self.data != old_widget.data
    }

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        Some(self)
    }
}

impl waft_foundation::Diagnosticable for DividerThemeData {
    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
        properties.add(ColorProperty::new("color", self.color).default_value(None));
        properties.add(DoubleProperty::new("space", self.space).default_value(None));
        properties.add(DoubleProperty::new("thickness", self.thickness).default_value(None));
        properties.add(DoubleProperty::new("indent", self.indent).default_value(None));
        properties.add(DoubleProperty::new("endIndent", self.end_indent).default_value(None));
        properties.add(
            DiagnosticsProperty::<BorderRadiusGeometry>::new("radius", self.radius)
                .default_value(None),
        );
    }
}

impl std::fmt::Display for DividerThemeData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
    }
}

#[cfg(test)]
mod tests {
    //! Ported from `test/divider_theme_test.dart`; the `debugFillProperties` cases wait for
    //! diagnostics, and `hashCode` for `Hash`.

    use waft_embedder::Radius;
    use waft_painting::{BorderRadius, BorderRadiusGeometry};
    use waft_widgets::DecoratedBox;

    use waft_widgets::testing::{WidgetTester, test_widgets};

    use super::*;
    use crate::colors::Colors;
    use crate::divider::tests::{assert_all_corners, border, border_radius, rect_of};
    use crate::divider::{Divider, VerticalDivider};
    use crate::scaffold::Scaffold;
    use crate::theme_data::ThemeData;
    use crate::tooltip::tests::{m2, m3, pump_app};

    fn divider_theme() -> DividerThemeData {
        DividerThemeData::new()
            .color(Colors::ORANGE.primary())
            .space(12.0)
            .thickness(2.0)
            .indent(7.0)
            .end_indent(5.0)
            .radius(BorderRadiusGeometry::only(
                Radius::circular(1.0),
                Radius::circular(2.0),
                Radius::circular(3.0),
                Radius::circular(4.0),
            ))
    }

    /// `Scaffold(body: child)`.
    fn body<K>(child: impl IntoWidget<K>) -> WidgetRef {
        Scaffold::new().body(child).into_widget()
    }

    fn themed(divider_theme: DividerThemeData) -> impl Fn(&App) -> ThemeData {
        move |app| {
            ThemeData::builder()
                .divider_theme(divider_theme.clone())
                .build(app)
        }
    }

    fn pump_with_theme<K>(
        tester: &mut WidgetTester,
        theme: impl FnOnce(&App) -> ThemeData,
        child: impl IntoWidget<K>,
    ) {
        pump_app(tester, theme, move |_app| body(child));
    }

    fn assert_theme_radii(radius: BorderRadius) {
        assert_eq!(radius.top_left, Radius::circular(1.0));
        assert_eq!(radius.top_right, Radius::circular(2.0));
        assert_eq!(radius.bottom_left, Radius::circular(3.0));
        assert_eq!(radius.bottom_right, Radius::circular(4.0));
    }

    #[test]
    fn divider_theme_data_copy_with_equality_basics() {
        assert_eq!(DividerThemeData::new(), DividerThemeData::new().copy_with());
    }

    #[test]
    fn divider_theme_data_null_fields_by_default() {
        let divider_theme = DividerThemeData::new();
        assert_eq!(divider_theme.color, None);
        assert_eq!(divider_theme.space, None);
        assert_eq!(divider_theme.thickness, None);
        assert_eq!(divider_theme.indent, None);
        assert_eq!(divider_theme.end_indent, None);
        assert_eq!(divider_theme.radius, None);
    }

    #[test]
    fn material3_horizontal_divider_passing_no_divider_theme_data_returns_defaults() {
        test_widgets(|tester| {
            let theme = ThemeData::new(&tester.cell.borrow());
            pump_app(tester, m3, |_app| body(Divider::new()));

            assert_eq!(rect_of::<Divider>(tester).height(), 16.0);
            let border = border(tester);
            assert_eq!(border.bottom.width, 1.0);
            assert_eq!(border.bottom.color, theme.color_scheme.outline_variant());

            let divider_rect = rect_of::<Divider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.left, divider_rect.left);
            assert_eq!(line_rect.right, divider_rect.right);
        });
    }

    #[test]
    fn material3_horizontal_divider_uses_values_from_divider_theme_data() {
        test_widgets(|tester| {
            let divider_theme = divider_theme();
            pump_with_theme(tester, themed(divider_theme.clone()), Divider::new());

            assert_eq!(
                rect_of::<Divider>(tester).height(),
                divider_theme.space.expect("a space")
            );
            let border = border(tester);
            assert_eq!(
                border.bottom.width,
                divider_theme.thickness.expect("a thickness")
            );
            assert_eq!(border.bottom.color, divider_theme.color.expect("a color"));

            let divider_rect = rect_of::<Divider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(
                line_rect.left,
                divider_rect.left + divider_theme.indent.expect("an indent")
            );
            assert_eq!(
                line_rect.right,
                divider_rect.right - divider_theme.end_indent.expect("an end indent")
            );
            assert_theme_radii(border_radius(tester));
        });
    }

    #[test]
    fn material3_horizontal_divider_divider_theme_overrides_defaults() {
        test_widgets(|tester| {
            let divider_theme = divider_theme();
            pump_app(tester, m3, |_app| {
                body(DividerTheme::new(divider_theme.clone(), Divider::new()))
            });

            let border = border(tester);
            assert_eq!(
                border.bottom.width,
                divider_theme.thickness.expect("a thickness")
            );
            assert_eq!(border.bottom.color, divider_theme.color.expect("a color"));
        });
    }

    #[test]
    fn material3_horizontal_divider_widget_properties_take_priority_over_theme() {
        test_widgets(|tester| {
            let color = Colors::PURPLE.primary();
            let (height, thickness, indent, end_indent) = (10.0, 5.0, 8.0, 9.0);
            pump_with_theme(
                tester,
                themed(divider_theme()),
                Divider::new()
                    .color(color)
                    .height(height)
                    .thickness(thickness)
                    .indent(indent)
                    .end_indent(end_indent)
                    .radius(BorderRadiusGeometry::all(Radius::circular(5.0))),
            );

            assert_eq!(rect_of::<Divider>(tester).height(), height);
            let border = border(tester);
            assert_eq!(border.bottom.width, thickness);
            assert_eq!(border.bottom.color, color);

            let divider_rect = rect_of::<Divider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.left, divider_rect.left + indent);
            assert_eq!(line_rect.right, divider_rect.right - end_indent);
            assert_all_corners(border_radius(tester), 5.0);
        });
    }

    #[test]
    fn material3_vertical_divider_passing_no_divider_theme_data_returns_defaults() {
        test_widgets(|tester| {
            let theme = ThemeData::new(&tester.cell.borrow());
            pump_app(tester, m3, |_app| body(VerticalDivider::new()));

            assert_eq!(rect_of::<VerticalDivider>(tester).width(), 16.0);
            let border = border(tester);
            assert_eq!(border.left.width, 1.0);
            assert_eq!(border.left.color, theme.color_scheme.outline_variant());

            let divider_rect = rect_of::<VerticalDivider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.top, divider_rect.top);
            assert_eq!(line_rect.bottom, divider_rect.bottom);
        });
    }

    #[test]
    fn material3_vertical_divider_uses_values_from_divider_theme_data() {
        test_widgets(|tester| {
            let divider_theme = divider_theme();
            pump_with_theme(
                tester,
                themed(divider_theme.clone()),
                VerticalDivider::new(),
            );

            assert_eq!(
                rect_of::<VerticalDivider>(tester).width(),
                divider_theme.space.expect("a space")
            );
            let border = border(tester);
            assert_eq!(
                border.left.width,
                divider_theme.thickness.expect("a thickness")
            );
            assert_eq!(border.left.color, divider_theme.color.expect("a color"));

            let divider_rect = rect_of::<VerticalDivider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(
                line_rect.top,
                divider_rect.top + divider_theme.indent.expect("an indent")
            );
            assert_eq!(
                line_rect.bottom,
                divider_rect.bottom - divider_theme.end_indent.expect("an end indent")
            );
            assert_theme_radii(border_radius(tester));
        });
    }

    #[test]
    fn material3_vertical_divider_divider_theme_overrides_defaults() {
        test_widgets(|tester| {
            let divider_theme = divider_theme();
            pump_app(tester, m3, |_app| {
                body(DividerTheme::new(
                    divider_theme.clone(),
                    VerticalDivider::new(),
                ))
            });

            let border = border(tester);
            assert_eq!(
                border.left.width,
                divider_theme.thickness.expect("a thickness")
            );
            assert_eq!(border.left.color, divider_theme.color.expect("a color"));
        });
    }

    #[test]
    fn material3_vertical_divider_widget_properties_take_priority_over_theme() {
        test_widgets(|tester| {
            let color = Colors::PURPLE.primary();
            let (width, thickness, indent, end_indent) = (10.0, 5.0, 8.0, 9.0);
            pump_with_theme(
                tester,
                themed(divider_theme()),
                VerticalDivider::new()
                    .color(color)
                    .width(width)
                    .thickness(thickness)
                    .indent(indent)
                    .end_indent(end_indent)
                    .radius(BorderRadiusGeometry::all(Radius::circular(5.0))),
            );

            assert_eq!(rect_of::<VerticalDivider>(tester).width(), width);
            let border = border(tester);
            assert_eq!(border.left.width, thickness);
            assert_eq!(border.left.color, color);

            let divider_rect = rect_of::<VerticalDivider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.top, divider_rect.top + indent);
            assert_eq!(line_rect.bottom, divider_rect.bottom - end_indent);
            assert_all_corners(border_radius(tester), 5.0);
        });
    }

    #[test]
    fn material2_horizontal_divider_passing_no_divider_theme_data_returns_defaults() {
        test_widgets(|tester| {
            let theme = ThemeData::builder()
                .use_material3(false)
                .build(&tester.cell.borrow());
            pump_app(tester, m2, |_app| body(Divider::new()));

            assert_eq!(rect_of::<Divider>(tester).height(), 16.0);
            let border = border(tester);
            assert_eq!(border.bottom.width, 0.0);
            assert_eq!(border.bottom.color, theme.divider_color);

            let divider_rect = rect_of::<Divider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.left, divider_rect.left);
            assert_eq!(line_rect.right, divider_rect.right);
        });
    }

    #[test]
    fn material2_horizontal_divider_divider_theme_overrides_defaults() {
        test_widgets(|tester| {
            let theme = divider_theme();
            pump_app(tester, m3, |_app| {
                body(DividerTheme::new(theme.clone(), Divider::new()))
            });

            let border = border(tester);
            assert_eq!(border.bottom.width, theme.thickness.expect("a thickness"));
            assert_eq!(border.bottom.color, theme.color.expect("a color"));
            assert_theme_radii(border_radius(tester));
        });
    }

    #[test]
    fn material2_vertical_divider_passing_no_divider_theme_data_returns_defaults() {
        test_widgets(|tester| {
            let theme = ThemeData::builder()
                .use_material3(false)
                .build(&tester.cell.borrow());
            pump_app(tester, m2, |_app| body(VerticalDivider::new()));

            assert_eq!(rect_of::<VerticalDivider>(tester).width(), 16.0);
            let border = border(tester);
            assert_eq!(border.left.width, 0.0);
            assert_eq!(border.left.color, theme.divider_color);

            let divider_rect = rect_of::<VerticalDivider>(tester);
            let line_rect = rect_of::<DecoratedBox>(tester);
            assert_eq!(line_rect.top, divider_rect.top);
            assert_eq!(line_rect.bottom, divider_rect.bottom);
        });
    }
    // Flutter's "Default DividerThemeData debugFillProperties".
    #[test]
    fn a_divider_theme_data_describes_nothing_by_default() {
        assert_eq!(
            waft_widgets::testing::describe_properties(|properties| {
                waft_foundation::Diagnosticable::debug_fill_properties(
                    &DividerThemeData::new(),
                    properties,
                )
            }),
            Vec::<String>::new()
        );
    }

    // divider_theme_test.dart 'DividerThemeData implements debugFillProperties'.
    #[test]
    fn an_assigned_divider_theme_describes_every_property() {
        let theme = DividerThemeData::new()
            .color(Color::new(0xffffffff))
            .space(5.0)
            .thickness(4.0)
            .indent(3.0)
            .end_indent(2.0)
            .radius(BorderRadiusGeometry::circular(20.0));
        let description = waft_widgets::testing::describe_properties(|properties| {
            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
        });
        let description: Vec<String> = description
            .iter()
            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
            .collect();
        assert_eq!(
            description,
            [
                format!("color: {}", Color::new(0xffffffff)),
                "space: 5.0".to_string(),
                "thickness: 4.0".to_string(),
                "indent: 3.0".to_string(),
                "endIndent: 2.0".to_string(),
                "radius: BorderRadius.circular(20.0)".to_string(),
            ]
        );
    }
}