Skip to main content

waft_material/
divider_theme.rs

1//! Flutter counterpart: material_ui's `divider_theme.dart`.
2
3use waft_embedder::{Color, lerp_double};
4use waft_foundation::{App, DiagnosticsProperty, DoubleProperty};
5use waft_painting::{BorderRadiusGeometry, ColorProperty};
6use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
7
8use crate::theme::Theme;
9
10/// Defines the visual properties of [`Divider`](crate::Divider), `VerticalDivider`,
11/// `Divider::create_border_side`, and `ListTile`'s dividers.
12///
13/// Descendant widgets obtain the current [`DividerThemeData`] object using
14/// [`DividerTheme::of`]. Instances of [`DividerThemeData`] can be customized with
15/// [`DividerThemeData::copy_with`].
16///
17/// Typically a [`DividerThemeData`] is specified as part of the overall `Theme` with
18/// `ThemeData::divider_theme`.
19///
20/// All [`DividerThemeData`] properties are `None` by default. When null, the `Divider`
21/// will use the values from `ThemeData` if they exist, otherwise it will provide its own
22/// defaults based on the overall `Theme`'s textTheme and colorScheme. See the individual
23/// `Divider` properties for details.
24///
25/// See also:
26///
27///  * [`DividerTheme`], an [`InheritedWidget`] that propagates the theme down its subtree.
28///  * `ThemeData::divider_theme`, which describes the overall theme information for the
29///    application.
30#[derive(Clone, Debug, Default, PartialEq)]
31pub struct DividerThemeData {
32    /// The color of [`Divider`](crate::Divider)s and `VerticalDivider`s.
33    pub color: Option<Color>,
34
35    /// The `Divider`'s height or the `VerticalDivider`'s width.
36    ///
37    /// This represents the amount of horizontal or vertical space the divider takes up.
38    pub space: Option<f64>,
39
40    /// The thickness of the line drawn within the divider.
41    pub thickness: Option<f64>,
42
43    /// The amount of empty space at the leading edge of [`Divider`](crate::Divider) or
44    /// top edge of `VerticalDivider`.
45    pub indent: Option<f64>,
46
47    /// The amount of empty space at the trailing edge of [`Divider`](crate::Divider) or
48    /// bottom edge of `VerticalDivider`.
49    pub end_indent: Option<f64>,
50
51    /// The border radius of the [`Divider`](crate::Divider) and `VerticalDivider`.
52    pub radius: Option<BorderRadiusGeometry>,
53}
54
55crate::theme_data_getters::theme_data_getters! {
56    /// Dart's getters of `DividerThemeData`: the theme data answers with its fields, and a defaults
57    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
58    /// are read.
59    pub trait DividerThemeDataGetters for DividerThemeData, fields: divider_theme_data {
60        color: Option<Color>,
61        space: Option<f64>,
62        thickness: Option<f64>,
63        indent: Option<f64>,
64        end_indent: Option<f64>,
65        radius: Option<BorderRadiusGeometry>,
66    }
67}
68
69impl DividerThemeData {
70    /// Creates a theme that can be used for `ThemeData::divider_theme`. Dart's optional
71    /// named arguments are the fluent setters.
72    pub fn new() -> DividerThemeData {
73        DividerThemeData::default()
74    }
75
76    /// Dart `DividerThemeData(color:)`.
77    pub fn color(mut self, color: Color) -> DividerThemeData {
78        self.color = Some(color);
79        self
80    }
81
82    /// Dart `DividerThemeData(space:)`.
83    pub fn space(mut self, space: f64) -> DividerThemeData {
84        self.space = Some(space);
85        self
86    }
87
88    /// Dart `DividerThemeData(thickness:)`.
89    pub fn thickness(mut self, thickness: f64) -> DividerThemeData {
90        self.thickness = Some(thickness);
91        self
92    }
93
94    /// Dart `DividerThemeData(indent:)`.
95    pub fn indent(mut self, indent: f64) -> DividerThemeData {
96        self.indent = Some(indent);
97        self
98    }
99
100    /// Dart `DividerThemeData(endIndent:)`.
101    pub fn end_indent(mut self, end_indent: f64) -> DividerThemeData {
102        self.end_indent = Some(end_indent);
103        self
104    }
105
106    /// Dart `DividerThemeData(radius:)`.
107    pub fn radius(mut self, radius: impl Into<BorderRadiusGeometry>) -> DividerThemeData {
108        self.radius = Some(radius.into());
109        self
110    }
111
112    /// Creates a copy of this object with the given fields replaced with the new values.
113    ///
114    /// Dart's named arguments are the fluent setters on the copy
115    /// (`data.copy_with().color(color)`).
116    pub fn copy_with(&self) -> DividerThemeData {
117        self.clone()
118    }
119
120    /// Linearly interpolate between two Divider themes.
121    ///
122    /// {@macro dart.ui.shadow.lerp}
123    pub fn lerp(
124        a: Option<&DividerThemeData>,
125        b: Option<&DividerThemeData>,
126        t: f64,
127    ) -> DividerThemeData {
128        if let (Some(a), Some(b)) = (a, b)
129            && std::ptr::eq(a, b)
130        {
131            return a.clone();
132        }
133        DividerThemeData {
134            color: Color::lerp(a.and_then(|a| a.color), b.and_then(|b| b.color), t),
135            space: lerp_double(a.and_then(|a| a.space), b.and_then(|b| b.space), t),
136            thickness: lerp_double(a.and_then(|a| a.thickness), b.and_then(|b| b.thickness), t),
137            indent: lerp_double(a.and_then(|a| a.indent), b.and_then(|b| b.indent), t),
138            end_indent: lerp_double(
139                a.and_then(|a| a.end_indent),
140                b.and_then(|b| b.end_indent),
141                t,
142            ),
143            radius: BorderRadiusGeometry::lerp(
144                a.and_then(|a| a.radius),
145                b.and_then(|b| b.radius),
146                t,
147            ),
148        }
149    }
150}
151
152/// An inherited widget that defines the configuration for
153/// [`Divider`](crate::Divider)s, `VerticalDivider`s, dividers between `ListTile`s, and
154/// dividers between rows in `DataTable`s in this widget's subtree.
155#[derive(Debug)]
156pub struct DividerTheme {
157    pub key: Option<KeyRef>,
158    /// The properties for descendant `Divider` widgets.
159    pub data: DividerThemeData,
160    pub child: WidgetRef,
161}
162
163impl DividerTheme {
164    /// Creates a divider theme that controls the configurations for
165    /// [`Divider`](crate::Divider)s and `VerticalDivider`s in its widget subtree.
166    #[cfg_attr(debug_assertions, track_caller)]
167    pub fn new<K>(data: DividerThemeData, child: impl IntoWidget<K>) -> DividerTheme {
168        DividerTheme {
169            key: None,
170            data,
171            child: child.into_widget(),
172        }
173    }
174
175    /// Dart `DividerTheme(key:)`.
176    pub fn key(mut self, key: KeyRef) -> DividerTheme {
177        self.key = Some(key);
178        self
179    }
180
181    /// The data from the closest instance of this class that encloses the given context.
182    ///
183    /// If there is no enclosing [`DividerTheme`] widget, then `ThemeData::divider_theme`
184    /// is used.
185    ///
186    /// Typical usage is as follows:
187    ///
188    /// ```text
189    /// let theme = DividerTheme::of(app, context);
190    /// ```
191    pub fn of(app: &mut App, context: BuildContext) -> DividerThemeData {
192        match context.depend_on_inherited_widget_of_exact_type::<DividerTheme>(app) {
193            Some(divider_theme) => divider_theme.data.clone(),
194            None => Theme::of(app, context).divider_theme.clone(),
195        }
196    }
197}
198
199impl InheritedTheme for DividerTheme {
200    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
201        DividerTheme::new(self.data.clone(), child).into_widget()
202    }
203}
204
205impl InheritedWidget for DividerTheme {
206    fn key(&self) -> Option<&KeyRef> {
207        self.key.as_ref()
208    }
209
210    fn child(&self) -> &WidgetRef {
211        &self.child
212    }
213
214    fn update_should_notify(&self, old_widget: &DividerTheme) -> bool {
215        self.data != old_widget.data
216    }
217
218    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
219        Some(self)
220    }
221}
222
223impl waft_foundation::Diagnosticable for DividerThemeData {
224    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
225        properties.add(ColorProperty::new("color", self.color).default_value(None));
226        properties.add(DoubleProperty::new("space", self.space).default_value(None));
227        properties.add(DoubleProperty::new("thickness", self.thickness).default_value(None));
228        properties.add(DoubleProperty::new("indent", self.indent).default_value(None));
229        properties.add(DoubleProperty::new("endIndent", self.end_indent).default_value(None));
230        properties.add(
231            DiagnosticsProperty::<BorderRadiusGeometry>::new("radius", self.radius)
232                .default_value(None),
233        );
234    }
235}
236
237impl std::fmt::Display for DividerThemeData {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    //! Ported from `test/divider_theme_test.dart`; the `debugFillProperties` cases wait for
246    //! diagnostics, and `hashCode` for `Hash`.
247
248    use waft_embedder::Radius;
249    use waft_painting::{BorderRadius, BorderRadiusGeometry};
250    use waft_widgets::DecoratedBox;
251
252    use waft_widgets::testing::{WidgetTester, test_widgets};
253
254    use super::*;
255    use crate::colors::Colors;
256    use crate::divider::tests::{assert_all_corners, border, border_radius, rect_of};
257    use crate::divider::{Divider, VerticalDivider};
258    use crate::scaffold::Scaffold;
259    use crate::theme_data::ThemeData;
260    use crate::tooltip::tests::{m2, m3, pump_app};
261
262    fn divider_theme() -> DividerThemeData {
263        DividerThemeData::new()
264            .color(Colors::ORANGE.primary())
265            .space(12.0)
266            .thickness(2.0)
267            .indent(7.0)
268            .end_indent(5.0)
269            .radius(BorderRadiusGeometry::only(
270                Radius::circular(1.0),
271                Radius::circular(2.0),
272                Radius::circular(3.0),
273                Radius::circular(4.0),
274            ))
275    }
276
277    /// `Scaffold(body: child)`.
278    fn body<K>(child: impl IntoWidget<K>) -> WidgetRef {
279        Scaffold::new().body(child).into_widget()
280    }
281
282    fn themed(divider_theme: DividerThemeData) -> impl Fn(&App) -> ThemeData {
283        move |app| {
284            ThemeData::builder()
285                .divider_theme(divider_theme.clone())
286                .build(app)
287        }
288    }
289
290    fn pump_with_theme<K>(
291        tester: &mut WidgetTester,
292        theme: impl FnOnce(&App) -> ThemeData,
293        child: impl IntoWidget<K>,
294    ) {
295        pump_app(tester, theme, move |_app| body(child));
296    }
297
298    fn assert_theme_radii(radius: BorderRadius) {
299        assert_eq!(radius.top_left, Radius::circular(1.0));
300        assert_eq!(radius.top_right, Radius::circular(2.0));
301        assert_eq!(radius.bottom_left, Radius::circular(3.0));
302        assert_eq!(radius.bottom_right, Radius::circular(4.0));
303    }
304
305    #[test]
306    fn divider_theme_data_copy_with_equality_basics() {
307        assert_eq!(DividerThemeData::new(), DividerThemeData::new().copy_with());
308    }
309
310    #[test]
311    fn divider_theme_data_null_fields_by_default() {
312        let divider_theme = DividerThemeData::new();
313        assert_eq!(divider_theme.color, None);
314        assert_eq!(divider_theme.space, None);
315        assert_eq!(divider_theme.thickness, None);
316        assert_eq!(divider_theme.indent, None);
317        assert_eq!(divider_theme.end_indent, None);
318        assert_eq!(divider_theme.radius, None);
319    }
320
321    #[test]
322    fn material3_horizontal_divider_passing_no_divider_theme_data_returns_defaults() {
323        test_widgets(|tester| {
324            let theme = ThemeData::new(&tester.cell.borrow());
325            pump_app(tester, m3, |_app| body(Divider::new()));
326
327            assert_eq!(rect_of::<Divider>(tester).height(), 16.0);
328            let border = border(tester);
329            assert_eq!(border.bottom.width, 1.0);
330            assert_eq!(border.bottom.color, theme.color_scheme.outline_variant());
331
332            let divider_rect = rect_of::<Divider>(tester);
333            let line_rect = rect_of::<DecoratedBox>(tester);
334            assert_eq!(line_rect.left, divider_rect.left);
335            assert_eq!(line_rect.right, divider_rect.right);
336        });
337    }
338
339    #[test]
340    fn material3_horizontal_divider_uses_values_from_divider_theme_data() {
341        test_widgets(|tester| {
342            let divider_theme = divider_theme();
343            pump_with_theme(tester, themed(divider_theme.clone()), Divider::new());
344
345            assert_eq!(
346                rect_of::<Divider>(tester).height(),
347                divider_theme.space.expect("a space")
348            );
349            let border = border(tester);
350            assert_eq!(
351                border.bottom.width,
352                divider_theme.thickness.expect("a thickness")
353            );
354            assert_eq!(border.bottom.color, divider_theme.color.expect("a color"));
355
356            let divider_rect = rect_of::<Divider>(tester);
357            let line_rect = rect_of::<DecoratedBox>(tester);
358            assert_eq!(
359                line_rect.left,
360                divider_rect.left + divider_theme.indent.expect("an indent")
361            );
362            assert_eq!(
363                line_rect.right,
364                divider_rect.right - divider_theme.end_indent.expect("an end indent")
365            );
366            assert_theme_radii(border_radius(tester));
367        });
368    }
369
370    #[test]
371    fn material3_horizontal_divider_divider_theme_overrides_defaults() {
372        test_widgets(|tester| {
373            let divider_theme = divider_theme();
374            pump_app(tester, m3, |_app| {
375                body(DividerTheme::new(divider_theme.clone(), Divider::new()))
376            });
377
378            let border = border(tester);
379            assert_eq!(
380                border.bottom.width,
381                divider_theme.thickness.expect("a thickness")
382            );
383            assert_eq!(border.bottom.color, divider_theme.color.expect("a color"));
384        });
385    }
386
387    #[test]
388    fn material3_horizontal_divider_widget_properties_take_priority_over_theme() {
389        test_widgets(|tester| {
390            let color = Colors::PURPLE.primary();
391            let (height, thickness, indent, end_indent) = (10.0, 5.0, 8.0, 9.0);
392            pump_with_theme(
393                tester,
394                themed(divider_theme()),
395                Divider::new()
396                    .color(color)
397                    .height(height)
398                    .thickness(thickness)
399                    .indent(indent)
400                    .end_indent(end_indent)
401                    .radius(BorderRadiusGeometry::all(Radius::circular(5.0))),
402            );
403
404            assert_eq!(rect_of::<Divider>(tester).height(), height);
405            let border = border(tester);
406            assert_eq!(border.bottom.width, thickness);
407            assert_eq!(border.bottom.color, color);
408
409            let divider_rect = rect_of::<Divider>(tester);
410            let line_rect = rect_of::<DecoratedBox>(tester);
411            assert_eq!(line_rect.left, divider_rect.left + indent);
412            assert_eq!(line_rect.right, divider_rect.right - end_indent);
413            assert_all_corners(border_radius(tester), 5.0);
414        });
415    }
416
417    #[test]
418    fn material3_vertical_divider_passing_no_divider_theme_data_returns_defaults() {
419        test_widgets(|tester| {
420            let theme = ThemeData::new(&tester.cell.borrow());
421            pump_app(tester, m3, |_app| body(VerticalDivider::new()));
422
423            assert_eq!(rect_of::<VerticalDivider>(tester).width(), 16.0);
424            let border = border(tester);
425            assert_eq!(border.left.width, 1.0);
426            assert_eq!(border.left.color, theme.color_scheme.outline_variant());
427
428            let divider_rect = rect_of::<VerticalDivider>(tester);
429            let line_rect = rect_of::<DecoratedBox>(tester);
430            assert_eq!(line_rect.top, divider_rect.top);
431            assert_eq!(line_rect.bottom, divider_rect.bottom);
432        });
433    }
434
435    #[test]
436    fn material3_vertical_divider_uses_values_from_divider_theme_data() {
437        test_widgets(|tester| {
438            let divider_theme = divider_theme();
439            pump_with_theme(
440                tester,
441                themed(divider_theme.clone()),
442                VerticalDivider::new(),
443            );
444
445            assert_eq!(
446                rect_of::<VerticalDivider>(tester).width(),
447                divider_theme.space.expect("a space")
448            );
449            let border = border(tester);
450            assert_eq!(
451                border.left.width,
452                divider_theme.thickness.expect("a thickness")
453            );
454            assert_eq!(border.left.color, divider_theme.color.expect("a color"));
455
456            let divider_rect = rect_of::<VerticalDivider>(tester);
457            let line_rect = rect_of::<DecoratedBox>(tester);
458            assert_eq!(
459                line_rect.top,
460                divider_rect.top + divider_theme.indent.expect("an indent")
461            );
462            assert_eq!(
463                line_rect.bottom,
464                divider_rect.bottom - divider_theme.end_indent.expect("an end indent")
465            );
466            assert_theme_radii(border_radius(tester));
467        });
468    }
469
470    #[test]
471    fn material3_vertical_divider_divider_theme_overrides_defaults() {
472        test_widgets(|tester| {
473            let divider_theme = divider_theme();
474            pump_app(tester, m3, |_app| {
475                body(DividerTheme::new(
476                    divider_theme.clone(),
477                    VerticalDivider::new(),
478                ))
479            });
480
481            let border = border(tester);
482            assert_eq!(
483                border.left.width,
484                divider_theme.thickness.expect("a thickness")
485            );
486            assert_eq!(border.left.color, divider_theme.color.expect("a color"));
487        });
488    }
489
490    #[test]
491    fn material3_vertical_divider_widget_properties_take_priority_over_theme() {
492        test_widgets(|tester| {
493            let color = Colors::PURPLE.primary();
494            let (width, thickness, indent, end_indent) = (10.0, 5.0, 8.0, 9.0);
495            pump_with_theme(
496                tester,
497                themed(divider_theme()),
498                VerticalDivider::new()
499                    .color(color)
500                    .width(width)
501                    .thickness(thickness)
502                    .indent(indent)
503                    .end_indent(end_indent)
504                    .radius(BorderRadiusGeometry::all(Radius::circular(5.0))),
505            );
506
507            assert_eq!(rect_of::<VerticalDivider>(tester).width(), width);
508            let border = border(tester);
509            assert_eq!(border.left.width, thickness);
510            assert_eq!(border.left.color, color);
511
512            let divider_rect = rect_of::<VerticalDivider>(tester);
513            let line_rect = rect_of::<DecoratedBox>(tester);
514            assert_eq!(line_rect.top, divider_rect.top + indent);
515            assert_eq!(line_rect.bottom, divider_rect.bottom - end_indent);
516            assert_all_corners(border_radius(tester), 5.0);
517        });
518    }
519
520    #[test]
521    fn material2_horizontal_divider_passing_no_divider_theme_data_returns_defaults() {
522        test_widgets(|tester| {
523            let theme = ThemeData::builder()
524                .use_material3(false)
525                .build(&tester.cell.borrow());
526            pump_app(tester, m2, |_app| body(Divider::new()));
527
528            assert_eq!(rect_of::<Divider>(tester).height(), 16.0);
529            let border = border(tester);
530            assert_eq!(border.bottom.width, 0.0);
531            assert_eq!(border.bottom.color, theme.divider_color);
532
533            let divider_rect = rect_of::<Divider>(tester);
534            let line_rect = rect_of::<DecoratedBox>(tester);
535            assert_eq!(line_rect.left, divider_rect.left);
536            assert_eq!(line_rect.right, divider_rect.right);
537        });
538    }
539
540    #[test]
541    fn material2_horizontal_divider_divider_theme_overrides_defaults() {
542        test_widgets(|tester| {
543            let theme = divider_theme();
544            pump_app(tester, m3, |_app| {
545                body(DividerTheme::new(theme.clone(), Divider::new()))
546            });
547
548            let border = border(tester);
549            assert_eq!(border.bottom.width, theme.thickness.expect("a thickness"));
550            assert_eq!(border.bottom.color, theme.color.expect("a color"));
551            assert_theme_radii(border_radius(tester));
552        });
553    }
554
555    #[test]
556    fn material2_vertical_divider_passing_no_divider_theme_data_returns_defaults() {
557        test_widgets(|tester| {
558            let theme = ThemeData::builder()
559                .use_material3(false)
560                .build(&tester.cell.borrow());
561            pump_app(tester, m2, |_app| body(VerticalDivider::new()));
562
563            assert_eq!(rect_of::<VerticalDivider>(tester).width(), 16.0);
564            let border = border(tester);
565            assert_eq!(border.left.width, 0.0);
566            assert_eq!(border.left.color, theme.divider_color);
567
568            let divider_rect = rect_of::<VerticalDivider>(tester);
569            let line_rect = rect_of::<DecoratedBox>(tester);
570            assert_eq!(line_rect.top, divider_rect.top);
571            assert_eq!(line_rect.bottom, divider_rect.bottom);
572        });
573    }
574    // Flutter's "Default DividerThemeData debugFillProperties".
575    #[test]
576    fn a_divider_theme_data_describes_nothing_by_default() {
577        assert_eq!(
578            waft_widgets::testing::describe_properties(|properties| {
579                waft_foundation::Diagnosticable::debug_fill_properties(
580                    &DividerThemeData::new(),
581                    properties,
582                )
583            }),
584            Vec::<String>::new()
585        );
586    }
587
588    // divider_theme_test.dart 'DividerThemeData implements debugFillProperties'.
589    #[test]
590    fn an_assigned_divider_theme_describes_every_property() {
591        let theme = DividerThemeData::new()
592            .color(Color::new(0xffffffff))
593            .space(5.0)
594            .thickness(4.0)
595            .indent(3.0)
596            .end_indent(2.0)
597            .radius(BorderRadiusGeometry::circular(20.0));
598        let description = waft_widgets::testing::describe_properties(|properties| {
599            waft_foundation::Diagnosticable::debug_fill_properties(&theme, properties)
600        });
601        let description: Vec<String> = description
602            .iter()
603            .map(|line| waft_rendering::testing::ignoring_hash_codes(line))
604            .collect();
605        assert_eq!(
606            description,
607            [
608                format!("color: {}", Color::new(0xffffffff)),
609                "space: 5.0".to_string(),
610                "thickness: 4.0".to_string(),
611                "indent: 3.0".to_string(),
612                "endIndent: 2.0".to_string(),
613                "radius: BorderRadius.circular(20.0)".to_string(),
614            ]
615        );
616    }
617}