waft-material 0.16.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
//! Flutter counterpart: material_ui's `button_bar_theme.dart`.
#![allow(
    deprecated,
    reason = "Dart deprecates `ButtonBarThemeData` and `ButtonBarTheme`, which this file implements"
)]

use waft_embedder::lerp_double;
use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, FlagProperty};
use waft_painting::EdgeInsetsGeometry;
use waft_widgets::{
    BuildContext, InheritedWidget, IntoWidget, KeyRef, MainAxisAlignment, MainAxisSize,
    VerticalDirection, WidgetRef,
};

use crate::button_theme::{ButtonBarLayoutBehavior, ButtonTextTheme};
use crate::theme::Theme;

/// Defines the visual properties of `ButtonBar` widgets.
///
/// Used by [`ButtonBarTheme`] to control the visual properties of `ButtonBar` instances in a
/// widget subtree.
///
/// See also:
///
///  * [`ButtonBarTheme`], an `InheritedWidget` that propagates the theme down its subtree.
///  * `ButtonBar`, which uses this to configure itself and its children button widgets.
#[deprecated(note = "Use OverflowBar instead. This feature was deprecated after v3.21.0-10.0.pre.")]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ButtonBarThemeData {
    /// How the children should be placed along the horizontal axis.
    pub alignment: Option<MainAxisAlignment>,
    /// How much horizontal space is available. See `Row::main_axis_size`.
    pub main_axis_size: Option<MainAxisSize>,
    /// Defines a `ButtonBar` button's base colors, and the defaults for the button's minimum
    /// size, internal padding, and shape.
    pub button_text_theme: Option<ButtonTextTheme>,
    /// The minimum width for `ButtonBar` buttons.
    pub button_min_width: Option<f64>,
    /// The minimum height for `ButtonBar` buttons.
    pub button_height: Option<f64>,
    /// Padding for a `ButtonBar` button's child (typically the button's label).
    pub button_padding: Option<EdgeInsetsGeometry>,
    /// If true, then a `DropdownButton` menu's width will match the `ButtonBar` button's
    /// width.
    pub button_aligned_dropdown: Option<bool>,
    /// Defines whether a `ButtonBar` should size itself with a minimum size constraint or with
    /// padding.
    pub layout_behavior: Option<ButtonBarLayoutBehavior>,
    /// Defines the vertical direction of a `ButtonBar`'s children if it overflows.
    pub overflow_direction: Option<VerticalDirection>,
}

impl ButtonBarThemeData {
    /// Creates the set of properties used to configure `ButtonBar` widgets; Dart's optional
    /// named arguments are the `with_*` setters.
    pub fn new() -> ButtonBarThemeData {
        ButtonBarThemeData::default()
    }

    /// Dart `ButtonBarThemeData(alignment:)`.
    pub fn with_alignment(mut self, alignment: MainAxisAlignment) -> ButtonBarThemeData {
        self.alignment = Some(alignment);
        self
    }

    /// Dart `ButtonBarThemeData(mainAxisSize:)`.
    pub fn with_main_axis_size(mut self, main_axis_size: MainAxisSize) -> ButtonBarThemeData {
        self.main_axis_size = Some(main_axis_size);
        self
    }

    /// Dart `ButtonBarThemeData(buttonTextTheme:)`.
    pub fn with_button_text_theme(
        mut self,
        button_text_theme: ButtonTextTheme,
    ) -> ButtonBarThemeData {
        self.button_text_theme = Some(button_text_theme);
        self
    }

    /// Dart `ButtonBarThemeData(buttonMinWidth:)`.
    pub fn with_button_min_width(mut self, button_min_width: f64) -> ButtonBarThemeData {
        debug_assert!(button_min_width >= 0.0);
        self.button_min_width = Some(button_min_width);
        self
    }

    /// Dart `ButtonBarThemeData(buttonHeight:)`.
    pub fn with_button_height(mut self, button_height: f64) -> ButtonBarThemeData {
        debug_assert!(button_height >= 0.0);
        self.button_height = Some(button_height);
        self
    }

    /// Dart `ButtonBarThemeData(buttonPadding:)`.
    pub fn with_button_padding(
        mut self,
        button_padding: impl Into<EdgeInsetsGeometry>,
    ) -> ButtonBarThemeData {
        self.button_padding = Some(button_padding.into());
        self
    }

    /// Dart `ButtonBarThemeData(buttonAlignedDropdown:)`.
    pub fn with_button_aligned_dropdown(
        mut self,
        button_aligned_dropdown: bool,
    ) -> ButtonBarThemeData {
        self.button_aligned_dropdown = Some(button_aligned_dropdown);
        self
    }

    /// Dart `ButtonBarThemeData(layoutBehavior:)`.
    pub fn with_layout_behavior(
        mut self,
        layout_behavior: ButtonBarLayoutBehavior,
    ) -> ButtonBarThemeData {
        self.layout_behavior = Some(layout_behavior);
        self
    }

    /// Dart `ButtonBarThemeData(overflowDirection:)`.
    pub fn with_overflow_direction(
        mut self,
        overflow_direction: VerticalDirection,
    ) -> ButtonBarThemeData {
        self.overflow_direction = Some(overflow_direction);
        self
    }

    /// Creates a copy of this object but with the given fields replaced with the new values.
    pub fn copy_with(&self) -> ButtonBarThemeData {
        self.clone()
    }

    /// Linearly interpolate between two button bar themes.
    ///
    /// If both arguments are null, then null is returned.
    pub fn lerp(
        a: Option<&ButtonBarThemeData>,
        b: Option<&ButtonBarThemeData>,
        t: f64,
    ) -> Option<ButtonBarThemeData> {
        match (a, b) {
            (None, None) => return None,
            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
            _ => {}
        }
        let a = a.cloned().unwrap_or_default();
        let b = b.cloned().unwrap_or_default();
        let pick = |t: f64| t < 0.5;
        Some(ButtonBarThemeData {
            alignment: if pick(t) { a.alignment } else { b.alignment },
            main_axis_size: if pick(t) {
                a.main_axis_size
            } else {
                b.main_axis_size
            },
            button_text_theme: if pick(t) {
                a.button_text_theme
            } else {
                b.button_text_theme
            },
            button_min_width: lerp_double(a.button_min_width, b.button_min_width, t),
            button_height: lerp_double(a.button_height, b.button_height, t),
            button_padding: EdgeInsetsGeometry::lerp(a.button_padding, b.button_padding, t),
            button_aligned_dropdown: if pick(t) {
                a.button_aligned_dropdown
            } else {
                b.button_aligned_dropdown
            },
            layout_behavior: if pick(t) {
                a.layout_behavior
            } else {
                b.layout_behavior
            },
            overflow_direction: if pick(t) {
                a.overflow_direction
            } else {
                b.overflow_direction
            },
        })
    }
}

/// Applies a button bar theme to descendant `ButtonBar` widgets.
///
/// A button bar theme describes the layout and properties for the buttons contained in a
/// `ButtonBar`.
#[deprecated(note = "Use OverflowBar instead. This feature was deprecated after v3.21.0-10.0.pre.")]
pub struct ButtonBarTheme {
    pub key: Option<KeyRef>,
    /// The properties used for all descendant `ButtonBar` widgets.
    pub data: ButtonBarThemeData,
    pub child: WidgetRef,
}

impl ButtonBarTheme {
    /// Constructs a button bar theme that configures all descendant `ButtonBar` widgets.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(data: ButtonBarThemeData, child: impl IntoWidget<K>) -> ButtonBarTheme {
        ButtonBarTheme {
            key: None,
            data,
            child: child.into_widget(),
        }
    }

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

    /// Returns the configuration `data` from the closest [`ButtonBarTheme`] ancestor. If there
    /// is no ancestor, it returns `ThemeData::button_bar_theme`.
    pub fn of(app: &mut App, context: BuildContext) -> ButtonBarThemeData {
        if let Some(button_bar_theme) =
            context.depend_on_inherited_widget_of_exact_type::<ButtonBarTheme>(app)
        {
            return button_bar_theme.data.clone();
        }
        Theme::of(app, context).button_bar_theme.clone()
    }
}

impl std::fmt::Debug for ButtonBarTheme {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ButtonBarTheme")
            .field("data", &self.data)
            .finish_non_exhaustive()
    }
}

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

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

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

impl waft_foundation::Diagnosticable for ButtonBarThemeData {
    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
        properties.add(
            DiagnosticsProperty::<waft_foundation::DartEnum<MainAxisAlignment>>::new(
                "alignment",
                self.alignment.map(waft_foundation::DartEnum),
            )
            .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<waft_foundation::DartEnum<MainAxisSize>>::new(
                "mainAxisSize",
                self.main_axis_size.map(waft_foundation::DartEnum),
            )
            .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<waft_foundation::DartEnum<ButtonTextTheme>>::new(
                "textTheme",
                self.button_text_theme.map(waft_foundation::DartEnum),
            )
            .default_value(None),
        );
        properties.add(DoubleProperty::new("minWidth", self.button_min_width).default_value(None));
        properties.add(DoubleProperty::new("height", self.button_height).default_value(None));
        properties.add(
            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.button_padding)
                .default_value(None),
        );
        properties.add(
            FlagProperty::new("buttonAlignedDropdown", self.button_aligned_dropdown)
                .if_true("dropdown width matches button")
                .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<waft_foundation::DartEnum<ButtonBarLayoutBehavior>>::new(
                "layoutBehavior",
                self.layout_behavior.map(waft_foundation::DartEnum),
            )
            .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<waft_foundation::DartEnum<VerticalDirection>>::new(
                "overflowDirection",
                self.overflow_direction.map(waft_foundation::DartEnum),
            )
            .default_value(None),
        );
    }
}

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

#[cfg(test)]
mod tests {
    use waft_widgets::testing::test_widgets;
    use waft_widgets::{Builder, Center, MainAxisAlignment, MainAxisSize, Text, VerticalDirection};

    use super::*;
    use crate::test_support::material_app;
    use crate::theme_data::ThemeData;

    #[test]
    fn button_bar_theme_data_lerp_special_cases() {
        assert_eq!(ButtonBarThemeData::lerp(None, None, 0.0), None);
        let data = ButtonBarThemeData::new();
        assert_eq!(
            ButtonBarThemeData::lerp(Some(&data), Some(&data), 0.5),
            Some(data)
        );
    }

    #[test]
    fn every_field_is_null_by_default() {
        let theme = ButtonBarThemeData::new();
        assert_eq!(theme.alignment, None);
        assert_eq!(theme.main_axis_size, None);
        assert_eq!(theme.button_text_theme, None);
        assert_eq!(theme.button_min_width, None);
        assert_eq!(theme.button_height, None);
        assert_eq!(theme.button_padding, None);
        assert_eq!(theme.button_aligned_dropdown, None);
        assert_eq!(theme.layout_behavior, None);
        assert_eq!(theme.overflow_direction, None);
    }

    #[test]
    fn theme_data_uses_the_default_button_bar_theme_data() {
        let cell = waft_foundation::AppCell::new();
        let theme = ThemeData::builder().build(&cell.borrow());
        assert_eq!(theme.button_bar_theme, ButtonBarThemeData::default());
    }

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

    #[test]
    fn the_fields_lerp_correctly() {
        let primary = ButtonBarThemeData::new()
            .with_alignment(MainAxisAlignment::End)
            .with_main_axis_size(MainAxisSize::Min)
            .with_button_text_theme(ButtonTextTheme::Primary)
            .with_button_min_width(20.0)
            .with_button_height(20.0)
            .with_button_padding(waft_painting::EdgeInsets::symmetric(5.0, 0.0))
            .with_button_aligned_dropdown(false)
            .with_layout_behavior(ButtonBarLayoutBehavior::Padded)
            .with_overflow_direction(VerticalDirection::Down);
        let accent = ButtonBarThemeData::new()
            .with_alignment(MainAxisAlignment::Center)
            .with_main_axis_size(MainAxisSize::Max)
            .with_button_text_theme(ButtonTextTheme::Accent)
            .with_button_min_width(10.0)
            .with_button_height(40.0)
            .with_button_padding(waft_painting::EdgeInsets::symmetric(0.0, 10.0))
            .with_button_aligned_dropdown(true)
            .with_layout_behavior(ButtonBarLayoutBehavior::Constrained)
            .with_overflow_direction(VerticalDirection::Up);

        let lerp = ButtonBarThemeData::lerp(Some(&primary), Some(&accent), 0.5)
            .expect("two themes lerp to a theme");
        assert_eq!(lerp.alignment, Some(MainAxisAlignment::Center));
        assert_eq!(lerp.main_axis_size, Some(MainAxisSize::Max));
        assert_eq!(lerp.button_text_theme, Some(ButtonTextTheme::Accent));
        assert_eq!(lerp.button_min_width, Some(15.0));
        assert_eq!(lerp.button_height, Some(30.0));
        assert_eq!(
            lerp.button_padding,
            Some(waft_painting::EdgeInsets::from_ltrb(5.0, 2.5, 5.0, 2.5).into())
        );
        assert_eq!(lerp.button_aligned_dropdown, Some(true));
        assert_eq!(
            lerp.layout_behavior,
            Some(ButtonBarLayoutBehavior::Constrained)
        );
        assert_eq!(lerp.overflow_direction, Some(VerticalDirection::Up));
    }

    #[test]
    fn of_falls_back_to_the_theme_data_field() {
        test_widgets(|tester| {
            let data = ButtonBarThemeData::new().with_button_min_width(42.0);
            let theme = ThemeData::builder()
                .button_bar_theme(data.clone())
                .build(&tester.cell.borrow());
            let seen = std::rc::Rc::new(std::cell::RefCell::new(None));
            let captured = std::rc::Rc::clone(&seen);
            tester.pump_widget(material_app(
                theme,
                Builder::new(move |app, context| {
                    *captured.borrow_mut() = Some(ButtonBarTheme::of(app, context));
                    Center::new().child(Text::new("x")).into_widget()
                })
                .into_widget(),
            ));
            assert_eq!(seen.borrow().clone(), Some(data));
            assert_eq!(
                seen.borrow()
                    .as_ref()
                    .and_then(|theme| theme.button_min_width),
                Some(42.0)
            );
        });
    }

    #[test]
    fn an_ancestor_button_bar_theme_overrides_the_theme_data_field() {
        test_widgets(|tester| {
            let default_bar_theme = ButtonBarThemeData::new().with_button_min_width(42.0);
            let override_theme = ButtonBarThemeData::new().with_button_min_width(84.0);
            let theme = ThemeData::builder()
                .button_bar_theme(default_bar_theme)
                .build(&tester.cell.borrow());
            let seen = std::rc::Rc::new(std::cell::RefCell::new(None));
            let captured = std::rc::Rc::clone(&seen);
            let override_clone = override_theme.clone();
            tester.pump_widget(material_app(
                theme,
                ButtonBarTheme::new(
                    override_clone,
                    Builder::new(move |app, context| {
                        *captured.borrow_mut() = Some(ButtonBarTheme::of(app, context));
                        Center::new().child(Text::new("x")).into_widget()
                    }),
                )
                .into_widget(),
            ));
            assert_eq!(seen.borrow().clone(), Some(override_theme));
            assert_eq!(
                seen.borrow()
                    .as_ref()
                    .and_then(|theme| theme.button_min_width),
                Some(84.0)
            );
        });
    }
    // Flutter's "Default ButtonBarThemeData debugFillProperties".
    #[test]
    fn a_button_bar_theme_data_describes_nothing_by_default() {
        assert_eq!(
            waft_widgets::testing::describe_properties(|properties| {
                waft_foundation::Diagnosticable::debug_fill_properties(
                    &ButtonBarThemeData::new(),
                    properties,
                )
            }),
            Vec::<String>::new()
        );
    }

    // button_bar_theme_test.dart 'ButtonBarThemeData implements debugFillProperties'.
    #[test]
    fn an_assigned_button_bar_theme_describes_every_property() {
        let theme = ButtonBarThemeData::new()
            .with_alignment(MainAxisAlignment::Center)
            .with_main_axis_size(MainAxisSize::Max)
            .with_button_text_theme(ButtonTextTheme::Accent)
            .with_button_min_width(10.0)
            .with_button_height(42.0)
            .with_button_padding(EdgeInsetsGeometry::symmetric(0.0, 7.3))
            .with_button_aligned_dropdown(true)
            .with_layout_behavior(ButtonBarLayoutBehavior::Constrained)
            .with_overflow_direction(VerticalDirection::Up);
        let description = waft_widgets::testing::describe_properties(|properties| {
            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
        });
        assert_eq!(
            description,
            [
                "alignment: MainAxisAlignment.center".to_string(),
                "mainAxisSize: MainAxisSize.max".to_string(),
                "textTheme: ButtonTextTheme.accent".to_string(),
                "minWidth: 10.0".to_string(),
                "height: 42.0".to_string(),
                "padding: EdgeInsets(7.3, 0.0, 7.3, 0.0)".to_string(),
                "dropdown width matches button".to_string(),
                "layoutBehavior: ButtonBarLayoutBehavior.constrained".to_string(),
                "overflowDirection: VerticalDirection.up".to_string(),
            ]
        );
    }
}