Skip to main content

waft_material/
data_table_theme.rs

1//! Flutter counterpart: material_ui's `data_table_theme.dart`.
2
3use std::fmt;
4use std::rc::Rc;
5
6use waft_embedder::{Color, lerp_double};
7use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty};
8use waft_painting::{DecorationRef, TextStyle};
9use waft_rendering::MainAxisAlignment;
10use waft_services::MouseCursorRef;
11use waft_widgets::{
12    BuildContext, InheritedWidget, IntoWidget, KeyRef, WidgetRef, WidgetStateProperty,
13    WidgetStatePropertyRef,
14};
15
16use crate::theme::Theme;
17
18/// Signature of the builder of a `DataTable`'s sort arrow: whether the arrow is `visible`,
19/// and whether the column sorts `ascending`.
20pub type DataTableSortIconBuilder = Rc<dyn Fn(&mut App, BuildContext, bool, bool) -> WidgetRef>;
21
22/// Defines default property values for descendant `DataTable` widgets.
23///
24/// Descendant widgets obtain the current [`DataTableThemeData`] object using
25/// [`DataTableTheme::of`]. Instances of [`DataTableThemeData`] can be customized with
26/// [`DataTableThemeData::copy_with`].
27///
28/// Typically a [`DataTableThemeData`] is specified as part of the overall `Theme` with
29/// `ThemeData::data_table_theme`.
30///
31/// All [`DataTableThemeData`] properties are `None` by default. When null, the `DataTable`
32/// provides its own defaults.
33///
34/// See also:
35///
36///  * [`DataTable`](crate::DataTable), which uses this to style itself.
37///  * `ThemeData`, which describes the overall theme information for the application.
38#[derive(Clone, Default)]
39pub struct DataTableThemeData {
40    /// The background and borders of the table used by a `DataTable` widget.
41    ///
42    /// The `DataTable` stacks this decoration with the `Material` it is rendered in.
43    pub decoration: Option<DecorationRef>,
44
45    /// The background color of the table's rows.
46    ///
47    /// If `None`, `DataTable` uses `ThemeData::data_table_theme`'s default instead.
48    pub data_row_color: Option<WidgetStatePropertyRef<Option<Color>>>,
49
50    /// The height of each row (excluding the row that contains column headings).
51    ///
52    /// Dart's `dataRowMinHeight`; `None` lets `DataTable` default it.
53    pub data_row_min_height: Option<f64>,
54
55    /// The maximum height of each row (excluding the row that contains column headings).
56    pub data_row_max_height: Option<f64>,
57
58    /// The text style for data rows.
59    pub data_text_style: Option<TextStyle>,
60
61    /// The background color of the heading row.
62    pub heading_row_color: Option<WidgetStatePropertyRef<Option<Color>>>,
63
64    /// The height of the heading row.
65    pub heading_row_height: Option<f64>,
66
67    /// The text style for the heading row.
68    pub heading_text_style: Option<TextStyle>,
69
70    /// The horizontal margin between the edges of the table and the content in the first and
71    /// last cells of each row.
72    pub horizontal_margin: Option<f64>,
73
74    /// The horizontal margin between the contents of each data column.
75    pub column_spacing: Option<f64>,
76
77    /// The thickness of the divider between rows.
78    pub divider_thickness: Option<f64>,
79
80    /// Horizontal margin around the checkbox, if it is displayed.
81    pub checkbox_horizontal_margin: Option<f64>,
82
83    /// If specified, overrides the default value of `DataColumn::mouse_cursor`.
84    pub heading_cell_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
85
86    /// If specified, overrides the default value of `DataRow::mouse_cursor`.
87    pub data_row_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
88
89    /// If specified, overrides the default value of `DataTable::heading_row_alignment`.
90    pub heading_row_alignment: Option<MainAxisAlignment>,
91
92    /// If specified, overrides the default value of `DataTable::sort_icon_builder`.
93    pub sort_icon_builder: Option<DataTableSortIconBuilder>,
94}
95
96impl DataTableThemeData {
97    /// Creates a theme that can be used for `ThemeData::data_table_theme` and
98    /// [`DataTableTheme`]; Dart's optional named arguments are the fluent setters.
99    pub fn new() -> DataTableThemeData {
100        DataTableThemeData::default()
101    }
102
103    /// Dart `DataTableThemeData(decoration:)`.
104    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> DataTableThemeData {
105        self.decoration = Some(decoration.into());
106        self
107    }
108
109    /// Dart `DataTableThemeData(dataRowColor:)`.
110    pub fn data_row_color(
111        mut self,
112        data_row_color: WidgetStatePropertyRef<Option<Color>>,
113    ) -> DataTableThemeData {
114        self.data_row_color = Some(data_row_color);
115        self
116    }
117
118    /// Dart's deprecated `DataTableThemeData(dataRowHeight:)`: it sets
119    /// [`data_row_min_height`](Self::data_row_min_height) and
120    /// [`data_row_max_height`](Self::data_row_max_height) to one value.
121    ///
122    /// Dart asserts that the argument is not given with either of them in one call; a fluent
123    /// chain has no call to compare, so a later setter replaces what an earlier one wrote.
124    #[deprecated = "Migrate to use data_row_min_height and data_row_max_height instead. This feature was deprecated after v3.7.0-5.0.pre."]
125    pub fn data_row_height(mut self, data_row_height: f64) -> DataTableThemeData {
126        self.data_row_min_height = Some(data_row_height);
127        self.data_row_max_height = Some(data_row_height);
128        self
129    }
130
131    /// Dart `DataTableThemeData(dataRowMinHeight:)`.
132    pub fn data_row_min_height(mut self, data_row_min_height: f64) -> DataTableThemeData {
133        self.data_row_min_height = Some(data_row_min_height);
134        self
135    }
136
137    /// Dart `DataTableThemeData(dataRowMaxHeight:)`.
138    pub fn data_row_max_height(mut self, data_row_max_height: f64) -> DataTableThemeData {
139        self.data_row_max_height = Some(data_row_max_height);
140        self
141    }
142
143    /// Dart `DataTableThemeData(dataTextStyle:)`.
144    pub fn data_text_style(mut self, data_text_style: TextStyle) -> DataTableThemeData {
145        self.data_text_style = Some(data_text_style);
146        self
147    }
148
149    /// Dart `DataTableThemeData(headingRowColor:)`.
150    pub fn heading_row_color(
151        mut self,
152        heading_row_color: WidgetStatePropertyRef<Option<Color>>,
153    ) -> DataTableThemeData {
154        self.heading_row_color = Some(heading_row_color);
155        self
156    }
157
158    /// Dart `DataTableThemeData(headingRowHeight:)`.
159    pub fn heading_row_height(mut self, heading_row_height: f64) -> DataTableThemeData {
160        self.heading_row_height = Some(heading_row_height);
161        self
162    }
163
164    /// Dart `DataTableThemeData(headingTextStyle:)`.
165    pub fn heading_text_style(mut self, heading_text_style: TextStyle) -> DataTableThemeData {
166        self.heading_text_style = Some(heading_text_style);
167        self
168    }
169
170    /// Dart `DataTableThemeData(horizontalMargin:)`.
171    pub fn horizontal_margin(mut self, horizontal_margin: f64) -> DataTableThemeData {
172        self.horizontal_margin = Some(horizontal_margin);
173        self
174    }
175
176    /// Dart `DataTableThemeData(columnSpacing:)`.
177    pub fn column_spacing(mut self, column_spacing: f64) -> DataTableThemeData {
178        self.column_spacing = Some(column_spacing);
179        self
180    }
181
182    /// Dart `DataTableThemeData(dividerThickness:)`.
183    pub fn divider_thickness(mut self, divider_thickness: f64) -> DataTableThemeData {
184        self.divider_thickness = Some(divider_thickness);
185        self
186    }
187
188    /// Dart `DataTableThemeData(checkboxHorizontalMargin:)`.
189    pub fn checkbox_horizontal_margin(
190        mut self,
191        checkbox_horizontal_margin: f64,
192    ) -> DataTableThemeData {
193        self.checkbox_horizontal_margin = Some(checkbox_horizontal_margin);
194        self
195    }
196
197    /// Dart `DataTableThemeData(headingCellCursor:)`.
198    pub fn heading_cell_cursor(
199        mut self,
200        heading_cell_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
201    ) -> DataTableThemeData {
202        self.heading_cell_cursor = Some(heading_cell_cursor);
203        self
204    }
205
206    /// Dart `DataTableThemeData(dataRowCursor:)`.
207    pub fn data_row_cursor(
208        mut self,
209        data_row_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
210    ) -> DataTableThemeData {
211        self.data_row_cursor = Some(data_row_cursor);
212        self
213    }
214
215    /// Dart `DataTableThemeData(headingRowAlignment:)`.
216    pub fn heading_row_alignment(
217        mut self,
218        heading_row_alignment: MainAxisAlignment,
219    ) -> DataTableThemeData {
220        self.heading_row_alignment = Some(heading_row_alignment);
221        self
222    }
223
224    /// Dart `DataTableThemeData(sortIconBuilder:)`.
225    pub fn sort_icon_builder(
226        mut self,
227        sort_icon_builder: impl Fn(&mut App, BuildContext, bool, bool) -> WidgetRef + 'static,
228    ) -> DataTableThemeData {
229        self.sort_icon_builder = Some(Rc::new(sort_icon_builder));
230        self
231    }
232
233    /// Dart's deprecated `dataRowHeight` getter: the row height, if the minimum and the
234    /// maximum are the same.
235    #[deprecated = "Migrate to use data_row_min_height and data_row_max_height instead. This feature was deprecated after v3.7.0-5.0.pre."]
236    pub fn data_row_height_value(&self) -> Option<f64> {
237        if self.data_row_min_height == self.data_row_max_height {
238            self.data_row_min_height
239        } else {
240            None
241        }
242    }
243
244    /// Creates a copy of this object but with the given fields replaced with the new values.
245    ///
246    /// Dart's named arguments are the fluent setters on the copy
247    /// (`data.copy_with().divider_thickness(2.0)`); the deprecated `dataRowHeight` argument
248    /// is [`data_row_height`](Self::data_row_height), which replaces both heights.
249    pub fn copy_with(&self) -> DataTableThemeData {
250        self.clone()
251    }
252
253    /// Linearly interpolates between two [`DataTableThemeData`].
254    ///
255    /// {@macro dart.ui.shadow.lerp}
256    pub fn lerp(a: &DataTableThemeData, b: &DataTableThemeData, t: f64) -> DataTableThemeData {
257        if std::ptr::eq(a, b) {
258            return a.clone();
259        }
260        DataTableThemeData {
261            decoration: DecorationRef::lerp(a.decoration.as_ref(), b.decoration.as_ref(), t),
262            data_row_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
263                a.data_row_color.clone(),
264                b.data_row_color.clone(),
265                t,
266                Color::lerp,
267            ),
268            data_row_min_height: lerp_double(a.data_row_min_height, b.data_row_min_height, t),
269            data_row_max_height: lerp_double(a.data_row_max_height, b.data_row_max_height, t),
270            data_text_style: TextStyle::lerp(
271                a.data_text_style.as_ref(),
272                b.data_text_style.as_ref(),
273                t,
274            ),
275            heading_row_color: <dyn WidgetStateProperty<Option<Color>>>::lerp_optional(
276                a.heading_row_color.clone(),
277                b.heading_row_color.clone(),
278                t,
279                Color::lerp,
280            ),
281            heading_row_height: lerp_double(a.heading_row_height, b.heading_row_height, t),
282            heading_text_style: TextStyle::lerp(
283                a.heading_text_style.as_ref(),
284                b.heading_text_style.as_ref(),
285                t,
286            ),
287            horizontal_margin: lerp_double(a.horizontal_margin, b.horizontal_margin, t),
288            column_spacing: lerp_double(a.column_spacing, b.column_spacing, t),
289            divider_thickness: lerp_double(a.divider_thickness, b.divider_thickness, t),
290            checkbox_horizontal_margin: lerp_double(
291                a.checkbox_horizontal_margin,
292                b.checkbox_horizontal_margin,
293                t,
294            ),
295            heading_cell_cursor: pick(a, b, t, |theme| theme.heading_cell_cursor.clone()),
296            data_row_cursor: pick(a, b, t, |theme| theme.data_row_cursor.clone()),
297            heading_row_alignment: pick(a, b, t, |theme| theme.heading_row_alignment),
298            sort_icon_builder: pick(a, b, t, |theme| theme.sort_icon_builder.clone()),
299        }
300    }
301}
302
303/// Dart's `t < 0.5 ? a.field : b.field`.
304fn pick<T>(
305    a: &DataTableThemeData,
306    b: &DataTableThemeData,
307    t: f64,
308    field: impl Fn(&DataTableThemeData) -> Option<T>,
309) -> Option<T> {
310    if t < 0.5 { field(a) } else { field(b) }
311}
312
313impl fmt::Debug for DataTableThemeData {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        f.debug_struct("DataTableThemeData")
316            .field("decoration", &self.decoration)
317            .field("data_row_color", &self.data_row_color)
318            .field("data_row_min_height", &self.data_row_min_height)
319            .field("data_row_max_height", &self.data_row_max_height)
320            .field("data_text_style", &self.data_text_style)
321            .field("heading_row_color", &self.heading_row_color)
322            .field("heading_row_height", &self.heading_row_height)
323            .field("heading_text_style", &self.heading_text_style)
324            .field("horizontal_margin", &self.horizontal_margin)
325            .field("column_spacing", &self.column_spacing)
326            .field("divider_thickness", &self.divider_thickness)
327            .field(
328                "checkbox_horizontal_margin",
329                &self.checkbox_horizontal_margin,
330            )
331            .field("heading_cell_cursor", &self.heading_cell_cursor)
332            .field("data_row_cursor", &self.data_row_cursor)
333            .field("heading_row_alignment", &self.heading_row_alignment)
334            .field("has_sort_icon_builder", &self.sort_icon_builder.is_some())
335            .finish()
336    }
337}
338
339impl PartialEq for DataTableThemeData {
340    fn eq(&self, other: &DataTableThemeData) -> bool {
341        if std::ptr::eq(self, other) {
342            return true;
343        }
344        other.decoration == self.decoration
345            && other.data_row_color == self.data_row_color
346            && other.data_row_min_height == self.data_row_min_height
347            && other.data_row_max_height == self.data_row_max_height
348            && other.data_text_style == self.data_text_style
349            && other.heading_row_color == self.heading_row_color
350            && other.heading_row_height == self.heading_row_height
351            && other.heading_text_style == self.heading_text_style
352            && other.horizontal_margin == self.horizontal_margin
353            && other.column_spacing == self.column_spacing
354            && other.divider_thickness == self.divider_thickness
355            && other.checkbox_horizontal_margin == self.checkbox_horizontal_margin
356            && other.heading_cell_cursor == self.heading_cell_cursor
357            && other.data_row_cursor == self.data_row_cursor
358            && other.heading_row_alignment == self.heading_row_alignment
359            && match (&other.sort_icon_builder, &self.sort_icon_builder) {
360                (Some(a), Some(b)) => Rc::ptr_eq(a, b),
361                (None, None) => true,
362                _ => false,
363            }
364    }
365}
366
367/// Applies a data table theme to descendant [`DataTable`](crate::DataTable) widgets.
368///
369/// Descendant widgets obtain the current theme's [`DataTableTheme`] object using
370/// [`DataTableTheme::of`]. When a widget uses [`DataTableTheme::of`], it is automatically
371/// rebuilt if the theme later changes.
372///
373/// A data table theme can be specified as part of the overall Material theme using
374/// `ThemeData::data_table_theme`.
375///
376/// See also:
377///
378///  * [`DataTableThemeData`], which describes the actual configuration of a data table theme.
379#[derive(Debug)]
380pub struct DataTableTheme {
381    pub key: Option<KeyRef>,
382    /// Specifies the visual properties used by descendant `DataTable` widgets.
383    pub data: DataTableThemeData,
384    pub child: WidgetRef,
385}
386
387impl DataTableTheme {
388    /// Constructs a data table theme that configures all descendant `DataTable` widgets.
389    #[cfg_attr(debug_assertions, track_caller)]
390    pub fn new<K>(data: DataTableThemeData, child: impl IntoWidget<K>) -> DataTableTheme {
391        DataTableTheme {
392            key: None,
393            data,
394            child: child.into_widget(),
395        }
396    }
397
398    /// Dart `DataTableTheme(key:)`.
399    pub fn key(mut self, key: KeyRef) -> DataTableTheme {
400        self.key = Some(key);
401        self
402    }
403
404    /// Returns the configuration [`data`](Self::data) from the closest [`DataTableTheme`]
405    /// ancestor. If there is no ancestor, it returns `ThemeData::data_table_theme`.
406    ///
407    /// Typical usage is as follows:
408    ///
409    /// ```text
410    /// let theme = DataTableTheme::of(app, context);
411    /// ```
412    pub fn of(app: &mut App, context: BuildContext) -> DataTableThemeData {
413        match context.depend_on_inherited_widget_of_exact_type::<DataTableTheme>(app) {
414            Some(data_table_theme) => data_table_theme.data.clone(),
415            None => Theme::of(app, context).data_table_theme.clone(),
416        }
417    }
418}
419
420impl InheritedWidget for DataTableTheme {
421    fn key(&self) -> Option<&KeyRef> {
422        self.key.as_ref()
423    }
424
425    fn child(&self) -> &WidgetRef {
426        &self.child
427    }
428
429    fn update_should_notify(&self, old_widget: &DataTableTheme) -> bool {
430        self.data != old_widget.data
431    }
432}
433
434impl waft_foundation::Diagnosticable for DataTableThemeData {
435    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
436        properties.add(
437            DiagnosticsProperty::<DecorationRef>::new("decoration", self.decoration.clone())
438                .default_value(None),
439        );
440        properties.add(
441            DiagnosticsProperty::<String>::new(
442                "dataRowColor",
443                self.data_row_color
444                    .as_deref()
445                    .map(|property| property.to_string()),
446            )
447            .default_value(None),
448        );
449        properties.add(
450            DoubleProperty::new("dataRowMinHeight", self.data_row_min_height).default_value(None),
451        );
452        properties.add(
453            DoubleProperty::new("dataRowMaxHeight", self.data_row_max_height).default_value(None),
454        );
455        properties.add(
456            DiagnosticsProperty::<TextStyle>::new("dataTextStyle", self.data_text_style.clone())
457                .default_value(None),
458        );
459        properties.add(
460            DiagnosticsProperty::<String>::new(
461                "headingRowColor",
462                self.heading_row_color
463                    .as_deref()
464                    .map(|property| property.to_string()),
465            )
466            .default_value(None),
467        );
468        properties.add(
469            DoubleProperty::new("headingRowHeight", self.heading_row_height).default_value(None),
470        );
471        properties.add(
472            DiagnosticsProperty::<TextStyle>::new(
473                "headingTextStyle",
474                self.heading_text_style.clone(),
475            )
476            .default_value(None),
477        );
478        properties.add(
479            DoubleProperty::new("horizontalMargin", self.horizontal_margin).default_value(None),
480        );
481        properties
482            .add(DoubleProperty::new("columnSpacing", self.column_spacing).default_value(None));
483        properties.add(
484            DoubleProperty::new("dividerThickness", self.divider_thickness).default_value(None),
485        );
486        properties.add(
487            DoubleProperty::new("checkboxHorizontalMargin", self.checkbox_horizontal_margin)
488                .default_value(None),
489        );
490        properties.add(
491            DiagnosticsProperty::<String>::new(
492                "headingCellCursor",
493                self.heading_cell_cursor
494                    .as_deref()
495                    .map(|property| property.to_string()),
496            )
497            .default_value(None),
498        );
499        properties.add(
500            DiagnosticsProperty::<String>::new(
501                "dataRowCursor",
502                self.data_row_cursor
503                    .as_deref()
504                    .map(|property| property.to_string()),
505            )
506            .default_value(None),
507        );
508        properties.add(
509            EnumProperty::<MainAxisAlignment>::new(
510                "headingRowAlignment",
511                self.heading_row_alignment,
512            )
513            .default_value(None),
514        );
515    }
516}
517
518impl std::fmt::Display for DataTableThemeData {
519    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    //! The cases of `test/data_table_theme_test.dart`.
527
528    use waft_embedder::Color;
529    use waft_painting::BoxDecoration;
530    use waft_services::SystemMouseCursors;
531    use waft_widgets::testing::{
532        Finder, TestPointer, WidgetTester, assert_f32_equals, find, test_widgets,
533    };
534    use waft_widgets::{Container, Table, Text, WidgetStatePropertyAll, WidgetStates};
535
536    use super::*;
537    use crate::bottom_navigation_bar::tests::paragraph_style;
538    use crate::data_table::{DataCell, DataColumn, DataRow, DataTable};
539    use crate::scaffold::Scaffold;
540    use crate::test_support::material_app;
541    use crate::theme_data::ThemeData;
542
543    fn all_color(color: Color) -> WidgetStatePropertyRef<Option<Color>> {
544        Rc::new(WidgetStatePropertyAll::new(Some(color)))
545    }
546
547    fn all_cursor(cursor: MouseCursorRef) -> WidgetStatePropertyRef<Option<MouseCursorRef>> {
548        Rc::new(WidgetStatePropertyAll::new(Some(cursor)))
549    }
550
551    fn box_decoration(color: Color) -> DecorationRef {
552        DecorationRef::new(BoxDecoration::new().color(color))
553    }
554
555    /// Dart's `_tableRowBoxDecoration`: the decoration of the table's row `index`.
556    fn table_row_box_decoration(tester: &WidgetTester, index: usize) -> BoxDecoration {
557        tester.widget(find::by_type::<Table>(), |table: &Table| {
558            table.children[index]
559                .decoration
560                .as_ref()
561                .and_then(|decoration| decoration.as_any().downcast_ref::<BoxDecoration>())
562                .expect("a BoxDecoration")
563                .clone()
564        })
565    }
566
567    /// Dart's `_findFirstContainerFor`: the finder matches with the `Container` of the cell
568    /// content, as well as the `Container` wrapping the whole table. The first one is used to
569    /// test row heights.
570    fn find_first_container_for(text: &str) -> Finder {
571        find::widget_with_text::<Container>(text).first()
572    }
573
574    fn table_container_decoration(tester: &WidgetTester) -> Option<DecorationRef> {
575        tester.widget(
576            find::ancestor(find::by_type::<Table>(), find::by_type::<Container>()).first(),
577            |container: &Container| container.decoration.clone(),
578        )
579    }
580
581    fn font_size_of(tester: &WidgetTester, text: &str) -> Option<f64> {
582        paragraph_style(tester, text).font_size
583    }
584
585    fn two_column_table(show_checkbox_column: bool) -> DataTable {
586        DataTable::new(
587            vec![
588                DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
589                DataColumn::new(Text::new("B")),
590            ],
591            vec![
592                DataRow::new(vec![
593                    DataCell::new(Text::new("Data")),
594                    DataCell::new(Text::new("Data 2")),
595                ])
596                .on_select_changed(|_app, _selected| {}),
597            ],
598        )
599        .sort_column_index(0)
600        .show_checkbox_column(show_checkbox_column)
601    }
602
603    fn app_with_theme<K>(
604        tester: &WidgetTester,
605        data_table_theme: DataTableThemeData,
606        body: impl IntoWidget<K>,
607    ) -> WidgetRef {
608        let theme = ThemeData::builder()
609            .data_table_theme(data_table_theme)
610            .build(&tester.cell.borrow());
611        material_app(theme, Scaffold::new().body(body).into_widget())
612    }
613
614    #[test]
615    fn data_table_theme_data_copy_with_equals_basics() {
616        assert_eq!(
617            DataTableThemeData::new(),
618            DataTableThemeData::new().copy_with()
619        );
620    }
621
622    #[test]
623    #[expect(deprecated)]
624    fn data_table_theme_data_copy_with_data_row_height() {
625        let theme_data = DataTableThemeData::new()
626            .data_row_min_height(10.0)
627            .data_row_max_height(10.0);
628        assert_eq!(theme_data, theme_data.copy_with());
629        assert_eq!(
630            theme_data
631                .copy_with()
632                .data_row_min_height(20.0)
633                .data_row_max_height(20.0),
634            DataTableThemeData::new().data_row_height(20.0)
635        );
636    }
637
638    #[test]
639    fn data_table_theme_data_lerp_special_cases() {
640        let data = DataTableThemeData::new();
641        assert_eq!(DataTableThemeData::lerp(&data, &data, 0.5), data);
642    }
643
644    #[test]
645    fn data_table_theme_data_defaults() {
646        let theme_data = DataTableThemeData::new();
647        assert_eq!(theme_data.decoration, None);
648        assert!(theme_data.data_row_color.is_none());
649        #[expect(deprecated)]
650        let data_row_height = theme_data.data_row_height_value();
651        assert_eq!(data_row_height, None);
652        assert_eq!(theme_data.data_row_min_height, None);
653        assert_eq!(theme_data.data_row_max_height, None);
654        assert_eq!(theme_data.data_text_style, None);
655        assert!(theme_data.heading_row_color.is_none());
656        assert_eq!(theme_data.heading_row_height, None);
657        assert_eq!(theme_data.heading_text_style, None);
658        assert_eq!(theme_data.horizontal_margin, None);
659        assert_eq!(theme_data.column_spacing, None);
660        assert_eq!(theme_data.divider_thickness, None);
661        assert_eq!(theme_data.checkbox_horizontal_margin, None);
662        assert!(theme_data.heading_cell_cursor.is_none());
663        assert!(theme_data.data_row_cursor.is_none());
664        assert_eq!(theme_data.heading_row_alignment, None);
665        assert!(theme_data.sort_icon_builder.is_none());
666    }
667
668    #[test]
669    fn data_table_is_themeable() {
670        test_widgets(|tester| {
671            let decoration = box_decoration(Color::new(0xfffffff0));
672            let data_row_color = all_color(Color::new(0xfffffff1));
673            let min_max_data_row_height = 41.0;
674            let data_text_style = TextStyle::new().font_size(12.5);
675            let heading_row_color = all_color(Color::new(0xfffffff2));
676            let heading_row_height = 52.0;
677            let heading_text_style = TextStyle::new().font_size(14.5);
678            let horizontal_margin = 3.0;
679            let column_spacing = 4.0;
680            let divider_thickness = 5.0;
681            let heading_cell_cursor = all_cursor(SystemMouseCursors::GRAB.into());
682            let data_row_cursor = all_cursor(SystemMouseCursors::FORBIDDEN.into());
683
684            let theme = DataTableThemeData::new()
685                .decoration(decoration.clone())
686                .data_row_color(data_row_color.clone())
687                .data_row_min_height(min_max_data_row_height)
688                .data_row_max_height(min_max_data_row_height)
689                .data_text_style(data_text_style.clone())
690                .heading_row_color(heading_row_color.clone())
691                .heading_row_height(heading_row_height)
692                .heading_text_style(heading_text_style.clone())
693                .horizontal_margin(horizontal_margin)
694                .column_spacing(column_spacing)
695                .divider_thickness(divider_thickness)
696                .heading_cell_cursor(heading_cell_cursor)
697                .data_row_cursor(data_row_cursor);
698            let root = app_with_theme(tester, theme, two_column_table(false));
699            tester.pump_widget(root);
700
701            assert_eq!(table_container_decoration(tester), Some(decoration));
702
703            assert_eq!(font_size_of(tester, "Data"), data_text_style.font_size);
704            assert_eq!(
705                table_row_box_decoration(tester, 1)
706                    .color
707                    .map(|color| color.color()),
708                data_row_color.resolve(&WidgetStates::new())
709            );
710            assert_eq!(
711                table_row_box_decoration(tester, 1)
712                    .border
713                    .expect("a border")
714                    .top()
715                    .width,
716                divider_thickness
717            );
718            assert_eq!(
719                tester.get_size(find_first_container_for("Data")).height(),
720                min_max_data_row_height
721            );
722
723            assert_eq!(font_size_of(tester, "A"), heading_text_style.font_size);
724            assert_eq!(
725                table_row_box_decoration(tester, 0)
726                    .color
727                    .map(|color| color.color()),
728                heading_row_color.resolve(&WidgetStates::new())
729            );
730
731            assert_eq!(
732                tester.get_size(find_first_container_for("A")).height(),
733                heading_row_height
734            );
735            assert_eq!(tester.get_top_left(find::text("A")).dx(), horizontal_margin);
736            assert_eq!(
737                tester.get_top_left(find::text("Data 2")).dx()
738                    - tester.get_top_right(find::text("Data")).dx(),
739                column_spacing
740            );
741
742            let mut gesture = TestPointer::mouse(1, 0);
743            let at = tester.get_center(find::text("A"));
744            tester.add_pointer(&mut gesture, at);
745            tester.pump();
746
747            let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
748            assert!(*tester.active_cursor(1) == *grab);
749
750            let at = tester.get_center(find::text("Data"));
751            tester.move_to(&mut gesture, at, false);
752            tester.pump();
753
754            let forbidden: MouseCursorRef = SystemMouseCursors::FORBIDDEN.into();
755            assert!(*tester.active_cursor(1) == *forbidden);
756        });
757    }
758
759    #[test]
760    #[expect(deprecated)]
761    fn data_table_is_themeable_separate_test_for_deprecated_data_row_height() {
762        test_widgets(|tester| {
763            let data_row_height = 51.0;
764            let table = DataTable::new(
765                vec![
766                    DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
767                    DataColumn::new(Text::new("B")),
768                ],
769                vec![DataRow::new(vec![
770                    DataCell::new(Text::new("Data")),
771                    DataCell::new(Text::new("Data 2")),
772                ])],
773            )
774            .sort_column_index(0);
775            let root = app_with_theme(
776                tester,
777                DataTableThemeData::new().data_row_height(data_row_height),
778                table,
779            );
780            tester.pump_widget(root);
781
782            assert_eq!(
783                tester.get_size(find_first_container_for("Data")).height(),
784                data_row_height
785            );
786        });
787    }
788
789    #[test]
790    fn data_table_properties_are_taken_over_the_theme_values() {
791        test_widgets(|tester| {
792            let theme_decoration = box_decoration(Color::new(0xfffffff1));
793            let theme_data_row_color = all_color(Color::new(0xfffffff0));
794            let min_max_theme_data_row_height = 50.0;
795            let theme_data_text_style = TextStyle::new().font_size(11.5);
796            let theme_heading_row_color = all_color(Color::new(0xfffffff1));
797            let theme_heading_row_height = 51.0;
798            let theme_heading_text_style = TextStyle::new().font_size(13.5);
799            let theme_heading_cell_cursor = all_cursor(SystemMouseCursors::COPY.into());
800            let theme_data_row_cursor = all_cursor(SystemMouseCursors::COPY.into());
801
802            let decoration = box_decoration(Color::new(0xfffffff0));
803            let data_row_color = all_color(Color::new(0xfffffff1));
804            let min_max_data_row_height = 51.0;
805            let data_text_style = TextStyle::new().font_size(12.5);
806            let heading_row_color = all_color(Color::new(0xfffffff2));
807            let heading_row_height = 52.0;
808            let heading_text_style = TextStyle::new().font_size(14.5);
809            let horizontal_margin = 3.0;
810            let column_spacing = 4.0;
811            let divider_thickness = 5.0;
812            let heading_cell_cursor = all_cursor(SystemMouseCursors::FORBIDDEN.into());
813            let data_row_cursor = all_cursor(SystemMouseCursors::FORBIDDEN.into());
814
815            let theme = DataTableThemeData::new()
816                .decoration(theme_decoration)
817                .data_row_color(theme_data_row_color)
818                .data_row_min_height(min_max_theme_data_row_height)
819                .data_row_max_height(min_max_theme_data_row_height)
820                .data_text_style(theme_data_text_style)
821                .heading_row_color(theme_heading_row_color)
822                .heading_row_height(theme_heading_row_height)
823                .heading_text_style(theme_heading_text_style)
824                .horizontal_margin(2.0)
825                .column_spacing(3.0)
826                .divider_thickness(4.0)
827                .heading_cell_cursor(theme_heading_cell_cursor)
828                .data_row_cursor(theme_data_row_cursor);
829            let table = DataTable::new(
830                vec![
831                    DataColumn::new(Text::new("A"))
832                        .mouse_cursor(heading_cell_cursor)
833                        .on_sort(|_app, _index, _ascending| {}),
834                    DataColumn::new(Text::new("B")),
835                ],
836                vec![
837                    DataRow::new(vec![
838                        DataCell::new(Text::new("Data")),
839                        DataCell::new(Text::new("Data 2")),
840                    ])
841                    .mouse_cursor(data_row_cursor)
842                    .on_select_changed(|_app, _selected| {}),
843                ],
844            )
845            .show_checkbox_column(false)
846            .decoration(decoration.clone())
847            .data_row_color(data_row_color.clone())
848            .data_row_min_height(min_max_data_row_height)
849            .data_row_max_height(min_max_data_row_height)
850            .data_text_style(data_text_style.clone())
851            .heading_row_color(heading_row_color.clone())
852            .heading_row_height(heading_row_height)
853            .heading_text_style(heading_text_style.clone())
854            .horizontal_margin(horizontal_margin)
855            .column_spacing(column_spacing)
856            .divider_thickness(divider_thickness)
857            .sort_column_index(0);
858            let root = app_with_theme(tester, theme, table);
859            tester.pump_widget(root);
860
861            assert_eq!(table_container_decoration(tester), Some(decoration));
862
863            assert_eq!(font_size_of(tester, "Data"), data_text_style.font_size);
864            assert_eq!(
865                table_row_box_decoration(tester, 1)
866                    .color
867                    .map(|color| color.color()),
868                data_row_color.resolve(&WidgetStates::new())
869            );
870            assert_eq!(
871                table_row_box_decoration(tester, 1)
872                    .border
873                    .expect("a border")
874                    .top()
875                    .width,
876                divider_thickness
877            );
878            assert_eq!(
879                tester.get_size(find_first_container_for("Data")).height(),
880                min_max_data_row_height
881            );
882
883            assert_eq!(font_size_of(tester, "A"), heading_text_style.font_size);
884            assert_eq!(
885                table_row_box_decoration(tester, 0)
886                    .color
887                    .map(|color| color.color()),
888                heading_row_color.resolve(&WidgetStates::new())
889            );
890
891            assert_eq!(
892                tester.get_size(find_first_container_for("A")).height(),
893                heading_row_height
894            );
895            assert_eq!(tester.get_top_left(find::text("A")).dx(), horizontal_margin);
896            assert_eq!(
897                tester.get_top_left(find::text("Data 2")).dx()
898                    - tester.get_top_right(find::text("Data")).dx(),
899                column_spacing
900            );
901
902            let mut gesture = TestPointer::mouse(1, 0);
903            let at = tester.get_center(find::text("A"));
904            tester.add_pointer(&mut gesture, at);
905            tester.pump();
906            let forbidden: MouseCursorRef = SystemMouseCursors::FORBIDDEN.into();
907            assert!(*tester.active_cursor(1) == *forbidden);
908
909            let at = tester.get_center(find::text("Data"));
910            tester.move_to(&mut gesture, at, false);
911            tester.pump();
912            assert!(*tester.active_cursor(1) == *forbidden);
913        });
914    }
915
916    #[test]
917    #[expect(deprecated)]
918    fn data_table_properties_are_taken_over_the_theme_values_separate_test_for_deprecated_data_row_height()
919     {
920        test_widgets(|tester| {
921            let data_row_height = 51.0;
922            let table = DataTable::new(
923                vec![
924                    DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
925                    DataColumn::new(Text::new("B")),
926                ],
927                vec![DataRow::new(vec![
928                    DataCell::new(Text::new("Data")),
929                    DataCell::new(Text::new("Data 2")),
930                ])],
931            )
932            .data_row_height(data_row_height)
933            .sort_column_index(0);
934            let root = app_with_theme(
935                tester,
936                DataTableThemeData::new().data_row_height(50.0),
937                table,
938            );
939            tester.pump_widget(root);
940
941            assert_eq!(
942                tester.get_size(find_first_container_for("Data")).height(),
943                data_row_height
944            );
945        });
946    }
947
948    #[test]
949    fn local_data_table_theme_can_override_global_data_table_theme() {
950        test_widgets(|tester| {
951            let global = DataTableThemeData::new()
952                .decoration(box_decoration(Color::new(0xfffffff1)))
953                .data_row_color(all_color(Color::new(0xfffffff0)))
954                .data_row_min_height(50.0)
955                .data_row_max_height(50.0)
956                .data_text_style(TextStyle::new().font_size(11.5))
957                .heading_row_color(all_color(Color::new(0xfffffff1)))
958                .heading_row_height(51.0)
959                .heading_text_style(TextStyle::new().font_size(13.5))
960                .horizontal_margin(2.0)
961                .column_spacing(3.0)
962                .divider_thickness(4.0)
963                .heading_cell_cursor(all_cursor(SystemMouseCursors::ALL_SCROLL.into()))
964                .data_row_cursor(all_cursor(SystemMouseCursors::ALL_SCROLL.into()));
965
966            let local_decoration = box_decoration(Color::new(0xfffffff0));
967            let local_data_row_color = all_color(Color::new(0xfffffff1));
968            let local_heading_row_color = all_color(Color::new(0xfffffff2));
969            let local = DataTableThemeData::new()
970                .decoration(local_decoration.clone())
971                .data_row_color(local_data_row_color.clone())
972                .data_row_min_height(51.0)
973                .data_row_max_height(51.0)
974                .data_text_style(TextStyle::new().font_size(12.5))
975                .heading_row_color(local_heading_row_color.clone())
976                .heading_row_height(52.0)
977                .heading_text_style(TextStyle::new().font_size(14.5))
978                .horizontal_margin(3.0)
979                .column_spacing(4.0)
980                .divider_thickness(5.0)
981                .heading_cell_cursor(all_cursor(SystemMouseCursors::MOVE.into()))
982                .data_row_cursor(all_cursor(SystemMouseCursors::MOVE.into()));
983            let root = app_with_theme(
984                tester,
985                global,
986                DataTableTheme::new(local, two_column_table(false)),
987            );
988            tester.pump_widget(root);
989
990            assert_eq!(table_container_decoration(tester), Some(local_decoration));
991
992            assert_eq!(font_size_of(tester, "Data"), Some(12.5));
993            assert_eq!(
994                table_row_box_decoration(tester, 1)
995                    .color
996                    .map(|color| color.color()),
997                local_data_row_color.resolve(&WidgetStates::new())
998            );
999            assert_eq!(
1000                table_row_box_decoration(tester, 1)
1001                    .border
1002                    .expect("a border")
1003                    .top()
1004                    .width,
1005                5.0
1006            );
1007            assert_eq!(
1008                tester.get_size(find_first_container_for("Data")).height(),
1009                51.0
1010            );
1011
1012            assert_eq!(font_size_of(tester, "A"), Some(14.5));
1013            assert_eq!(
1014                table_row_box_decoration(tester, 0)
1015                    .color
1016                    .map(|color| color.color()),
1017                local_heading_row_color.resolve(&WidgetStates::new())
1018            );
1019
1020            assert_eq!(
1021                tester.get_size(find_first_container_for("A")).height(),
1022                52.0
1023            );
1024            assert_eq!(tester.get_top_left(find::text("A")).dx(), 3.0);
1025            assert_eq!(
1026                tester.get_top_left(find::text("Data 2")).dx()
1027                    - tester.get_top_right(find::text("Data")).dx(),
1028                4.0
1029            );
1030
1031            let mut gesture = TestPointer::mouse(1, 0);
1032            let at = tester.get_center(find::text("A"));
1033            tester.add_pointer(&mut gesture, at);
1034            tester.pump();
1035            let move_cursor: MouseCursorRef = SystemMouseCursors::MOVE.into();
1036            assert!(*tester.active_cursor(1) == *move_cursor);
1037
1038            let at = tester.get_center(find::text("Data"));
1039            tester.move_to(&mut gesture, at, false);
1040            tester.pump();
1041            assert!(*tester.active_cursor(1) == *move_cursor);
1042        });
1043    }
1044
1045    #[test]
1046    #[expect(deprecated)]
1047    fn local_data_table_theme_can_override_global_data_table_theme_separate_test_for_deprecated_data_row_height()
1048     {
1049        test_widgets(|tester| {
1050            let local_theme_data_row_height = 51.0;
1051            let table = DataTable::new(
1052                vec![
1053                    DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
1054                    DataColumn::new(Text::new("B")),
1055                ],
1056                vec![DataRow::new(vec![
1057                    DataCell::new(Text::new("Data")),
1058                    DataCell::new(Text::new("Data 2")),
1059                ])],
1060            )
1061            .sort_column_index(0);
1062            let root = app_with_theme(
1063                tester,
1064                DataTableThemeData::new().data_row_height(50.0),
1065                DataTableTheme::new(
1066                    DataTableThemeData::new().data_row_height(local_theme_data_row_height),
1067                    table,
1068                ),
1069            );
1070            tester.pump_widget(root);
1071
1072            assert_eq!(
1073                tester.get_size(find_first_container_for("Data")).height(),
1074                local_theme_data_row_height
1075            );
1076        });
1077    }
1078
1079    #[test]
1080    fn data_column_label_can_be_centered_with_data_table_theme_heading_row_alignment() {
1081        test_widgets(|tester| {
1082            let horizontal_margin = 24.0;
1083            let build_table = |tester: &WidgetTester,
1084                               heading_row_alignment: Option<MainAxisAlignment>,
1085                               sort_enabled: bool|
1086             -> WidgetRef {
1087                let mut theme = DataTableThemeData::new();
1088                theme.heading_row_alignment = heading_row_alignment;
1089                let mut column = DataColumn::new(Text::new("Header"));
1090                if sort_enabled {
1091                    column = column.on_sort(|_app, _index, _ascending| {});
1092                }
1093                let table = DataTable::new(
1094                    vec![column],
1095                    vec![DataRow::new(vec![DataCell::new(Text::new("Data"))])],
1096                );
1097                let theme = ThemeData::builder()
1098                    .data_table_theme(theme)
1099                    .build(&tester.cell.borrow());
1100                material_app(
1101                    theme,
1102                    crate::material::Material::new().child(table).into_widget(),
1103                )
1104            };
1105
1106            // Test mainAxisAlignment without sort arrow.
1107            let root = build_table(tester, None, false);
1108            tester.pump_widget(root);
1109            assert_eq!(
1110                tester.get_top_left(find::text("Header")).dx(),
1111                horizontal_margin
1112            );
1113
1114            // Test mainAxisAlignment.center without sort arrow.
1115            let root = build_table(tester, Some(MainAxisAlignment::Center), false);
1116            tester.pump_widget(root);
1117            tester.pump_and_settle();
1118            assert_f32_equals(tester.get_center(find::text("Header")).dx(), 400.0);
1119
1120            // Test mainAxisAlignment with sort arrow.
1121            let root = build_table(tester, None, true);
1122            tester.pump_widget(root);
1123            tester.pump_and_settle();
1124            assert_eq!(
1125                tester.get_top_left(find::text("Header")).dx(),
1126                horizontal_margin
1127            );
1128
1129            // Test mainAxisAlignment.center with sort arrow.
1130            let root = build_table(tester, Some(MainAxisAlignment::Center), true);
1131            tester.pump_widget(root);
1132            tester.pump_and_settle();
1133            assert_f32_equals(tester.get_center(find::text("Header")).dx(), 400.0);
1134        });
1135    }
1136
1137    #[test]
1138    fn data_table_theme_data_lerp_interpolates_numbers_and_picks_discrete_fields_at_half() {
1139        let a = DataTableThemeData::new()
1140            .horizontal_margin(2.0)
1141            .heading_row_alignment(MainAxisAlignment::Start);
1142        let b = DataTableThemeData::new()
1143            .horizontal_margin(4.0)
1144            .heading_row_alignment(MainAxisAlignment::End);
1145        let lerp = DataTableThemeData::lerp(&a, &b, 0.25);
1146        assert_f32_equals(lerp.horizontal_margin.expect("a margin"), 2.5);
1147        assert_eq!(lerp.heading_row_alignment, Some(MainAxisAlignment::Start));
1148        let lerp = DataTableThemeData::lerp(&a, &b, 0.75);
1149        assert_eq!(lerp.heading_row_alignment, Some(MainAxisAlignment::End));
1150    }
1151    // Flutter's "Default DataTableThemeData debugFillProperties".
1152    #[test]
1153    fn a_data_table_theme_data_describes_nothing_by_default() {
1154        assert_eq!(
1155            waft_widgets::testing::describe_properties(|properties| {
1156                waft_foundation::Diagnosticable::debug_fill_properties(
1157                    &DataTableThemeData::new(),
1158                    properties,
1159                )
1160            }),
1161            Vec::<String>::new()
1162        );
1163    }
1164}