Skip to main content

waft_material/
data_table.rs

1//! Flutter counterpart: material_ui's `data_table.dart`.
2//!
3//! Dart's `_NullTableColumnWidth` and `_NullWidget` are placeholders that fill the lists
4//! `build` then writes cell by cell; here the lists are built with their values, so neither
5//! exists.
6
7use std::collections::HashMap;
8use std::f64::consts::PI;
9use std::fmt;
10use std::rc::Rc;
11use std::sync::OnceLock;
12use std::time::Duration;
13
14use waft_animation::{
15    Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
16    AnimationStatusListener, CurveTween, CurvedAnimation, Curves, Drive, Tween,
17};
18use waft_embedder::{Clip, Color, Matrix4, Rect, TextDirection};
19use waft_foundation::{App, Handle, Listener, LocalKey, Ref, UniqueKey, ValueChanged, ValueKey};
20use waft_gestures::{
21    GestureLongPressCallback, GestureTapCallback, GestureTapCancelCallback, GestureTapDownCallback,
22};
23use waft_painting::{
24    AlignmentGeometry, Border, BoxDecoration, DecorationRef, EdgeInsetsDirectional,
25    EdgeInsetsGeometry, TextStyle,
26};
27use waft_rendering::{
28    AnyRenderBox, AnyRenderObject, BoxConstraints, FixedColumnWidth, IntrinsicColumnWidth,
29    MainAxisAlignment, RenderBox, RenderTable, TableCellParentData, TableCellVerticalAlignment,
30    TableColumnWidthRef,
31};
32use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
33use waft_services::MouseCursorRef;
34use waft_widgets::{
35    AnimatedDefaultTextStyle, BuildContext, Center, Container, DefaultTextStyle, FadeTransition,
36    Icon, IntoWidget, KeyRef, Padding, Row, Semantics, SizedBox, State, StateData, StatefulWidget,
37    StatelessWidget, Table, TableBorder, TableCell, TableRow, TickerProviderStateMixin,
38    TickerProviderStateMixinData, Transform, WidgetRef, WidgetState, WidgetStateProperty,
39    WidgetStatePropertyRef, WidgetStates, debug_check_has_table,
40};
41
42use crate::checkbox::Checkbox;
43use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
44use crate::data_table_theme::{DataTableSortIconBuilder, DataTableTheme};
45use crate::debug::debug_check_has_material;
46use crate::divider::Divider;
47use crate::dropdown::DropdownButtonHideUnderline;
48use crate::icons::Icons;
49use crate::ink_well::{InkResponse, InkWell};
50use crate::material::{Material, MaterialType, RectCallback};
51use crate::theme::Theme;
52use crate::tooltip::Tooltip;
53
54/// Signature for [`DataColumn::on_sort`] and `DataTable`'s sort callbacks.
55pub type DataColumnSortCallback = Rc<dyn Fn(&mut App, i32, bool)>;
56
57/// Column configuration for a [`DataTable`].
58///
59/// One column configuration must be provided for each column to display in the table. The list
60/// of [`DataColumn`] objects is passed as the `columns` argument to the [`DataTable::new`]
61/// constructor.
62#[derive(Clone)]
63pub struct DataColumn {
64    /// The column heading.
65    ///
66    /// Typically, this will be a `Text` widget. It could also be an `Icon` (typically using size
67    /// 18), or a `Row` with an icon and some text.
68    ///
69    /// The [label] is placed within a [`Row`] along with an arrow icon (if [`on_sort`] is
70    /// non-null). By default, [label] is only as wide as needed to fit its contents.
71    pub label: WidgetRef,
72
73    /// How the horizontal extents of this column of the table should be determined.
74    ///
75    /// The [`FixedColumnWidth`] class can be used to specify a specific width in pixels. This is
76    /// the cheapest way to size a table's columns.
77    ///
78    /// The layout performance of the table depends critically on which column sizing algorithms
79    /// are used here. In particular, [`IntrinsicColumnWidth`] is quite expensive because it needs
80    /// to measure each cell in the column to determine the intrinsic size of the column.
81    ///
82    /// If this is `None`, the column width is determined by the table, as described by
83    /// [`DataTable`].
84    pub column_width: Option<TableColumnWidthRef>,
85
86    /// The column heading's tooltip.
87    ///
88    /// This is a longer description of the column heading, for cases where the heading might have
89    /// been abbreviated to keep the column width to a reasonable size.
90    pub tooltip: Option<String>,
91
92    /// Whether this column represents numeric data or not.
93    ///
94    /// The contents of cells of columns containing numeric data are right-aligned.
95    pub numeric: bool,
96
97    /// Called when the user asks to sort the table using this column.
98    ///
99    /// If non-null, the user can sort the table using this column. The callback is passed the
100    /// column index and whether the new sort is ascending.
101    pub on_sort: Option<DataColumnSortCallback>,
102
103    /// The cursor for a mouse pointer when it enters or is hovering over the heading row.
104    ///
105    /// [`WidgetStateProperty::resolve`] is used for the following [`WidgetState`]s:
106    ///
107    ///  * [`WidgetState::Disabled`].
108    ///
109    /// If this is `None`, then the value of [`DataTableThemeData::heading_cell_cursor`] is used.
110    /// If that's `None` too, then `SystemMouseCursors::click` is used.
111    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
112
113    /// Defines the horizontal layout of the [`label`](Self::label) and sort indicator in the
114    /// heading row.
115    ///
116    /// If [`DataTable::heading_row_alignment`] is set, it takes precedence over this value.
117    pub heading_row_alignment: Option<MainAxisAlignment>,
118}
119
120impl DataColumn {
121    /// Creates the configuration for a column of a [`DataTable`]; Dart's optional named
122    /// arguments are the setters.
123    #[cfg_attr(debug_assertions, track_caller)]
124    pub fn new<K>(label: impl IntoWidget<K>) -> DataColumn {
125        DataColumn {
126            label: label.into_widget(),
127            column_width: None,
128            tooltip: None,
129            numeric: false,
130            on_sort: None,
131            mouse_cursor: None,
132            heading_row_alignment: None,
133        }
134    }
135
136    /// Dart `DataColumn(columnWidth:)`.
137    pub fn column_width(mut self, column_width: TableColumnWidthRef) -> DataColumn {
138        self.column_width = Some(column_width);
139        self
140    }
141
142    /// Dart `DataColumn(tooltip:)`.
143    pub fn tooltip(mut self, tooltip: impl Into<String>) -> DataColumn {
144        self.tooltip = Some(tooltip.into());
145        self
146    }
147
148    /// Dart `DataColumn(numeric:)`.
149    pub fn numeric(mut self, numeric: bool) -> DataColumn {
150        self.numeric = numeric;
151        self
152    }
153
154    /// Dart `DataColumn(onSort:)`.
155    pub fn on_sort(mut self, on_sort: impl Fn(&mut App, i32, bool) + 'static) -> DataColumn {
156        self.on_sort = Some(Rc::new(on_sort));
157        self
158    }
159
160    /// Dart `DataColumn(mouseCursor:)`.
161    pub fn mouse_cursor(
162        mut self,
163        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
164    ) -> DataColumn {
165        self.mouse_cursor = Some(mouse_cursor);
166        self
167    }
168
169    /// Dart `DataColumn(headingRowAlignment:)`.
170    pub fn heading_row_alignment(mut self, heading_row_alignment: MainAxisAlignment) -> DataColumn {
171        self.heading_row_alignment = Some(heading_row_alignment);
172        self
173    }
174
175    /// Dart's `_debugInteractive`.
176    fn debug_interactive(&self) -> bool {
177        self.on_sort.is_some()
178    }
179}
180
181impl fmt::Debug for DataColumn {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        f.debug_struct("DataColumn")
184            .field("label", &self.label)
185            .field("tooltip", &self.tooltip)
186            .field("numeric", &self.numeric)
187            .field("sortable", &self.on_sort.is_some())
188            .finish_non_exhaustive()
189    }
190}
191
192/// Row configuration and cell data for a [`DataTable`].
193///
194/// One row configuration must be provided for each row to display in the table. The list of
195/// [`DataRow`] objects is passed as the `rows` argument to the [`DataTable::new`] constructor.
196///
197/// The data for this row of the table is provided in the [`cells`](Self::cells) property of the
198/// [`DataRow`] object.
199#[derive(Clone)]
200pub struct DataRow {
201    /// A [`LocalKey`] that identifies the row.
202    ///
203    /// Rows must have a key if the table can be reordered.
204    pub key: Option<Rc<dyn LocalKey>>,
205
206    /// Called when the user selects or unselects a selectable row.
207    ///
208    /// If this is not null, then the row is selectable. The current selection state of the row is
209    /// given by [`selected`](Self::selected).
210    ///
211    /// If any row is selectable, then the table's heading row will have a checkbox that can be
212    /// checked to select all selectable rows (and which is checked if all the rows are selected),
213    /// and each subsequent row will have a checkbox to toggle just that row.
214    ///
215    /// A row whose [`on_select_changed`](Self::on_select_changed) callback is null is ignored for
216    /// the purposes of determining the state of the "all" checkbox, and its checkbox is disabled.
217    ///
218    /// If a [`DataCell`] in the row has its [`DataCell::on_tap`] callback defined, that callback
219    /// behavior overrides the gesture behavior of the row for that particular cell.
220    pub on_select_changed: Option<ValueChanged<Option<bool>>>,
221
222    /// Called if the row is long-pressed.
223    ///
224    /// If a [`DataCell`] in the row has its [`DataCell::on_tap`], [`DataCell::on_double_tap`],
225    /// [`DataCell::on_long_press`], [`DataCell::on_tap_cancel`] or [`DataCell::on_tap_down`]
226    /// callback defined, that callback behavior overrides the gesture behavior of the row for
227    /// that particular cell.
228    pub on_long_press: Option<GestureLongPressCallback>,
229
230    /// Called when a pointer enters or exits the row.
231    ///
232    /// The boolean value passed to the callback is true if a pointer has entered the row and
233    /// false if it has exited.
234    pub on_hover: Option<ValueChanged<bool>>,
235
236    /// Whether the row is selected.
237    ///
238    /// If [`on_select_changed`](Self::on_select_changed) is non-null for any row in the table,
239    /// then a checkbox is shown at the start of each row. If the row is selected
240    /// (`true`), the checkbox will be checked and the row will be highlighted.
241    ///
242    /// Otherwise, the checkbox, if present, will not be checked.
243    pub selected: bool,
244
245    /// The data for this row.
246    ///
247    /// There must be exactly as many cells as there are columns in the table.
248    pub cells: Vec<DataCell>,
249
250    /// The color for the row.
251    ///
252    /// By default, the color is transparent unless selected. Selected rows has a grey translucent
253    /// color.
254    ///
255    /// The effective color can depend on the [`WidgetState`] state, if the row is selected,
256    /// pressed, hovered, focused, disabled or enabled. The color is painted as an overlay to the
257    /// row. To make sure that the row's [`InkWell`] is visible (when pressed, hovered and
258    /// focused), it is recommended to use a translucent color.
259    pub color: Option<WidgetStatePropertyRef<Option<Color>>>,
260
261    /// The cursor for a mouse pointer when it enters or is hovering over the data row.
262    ///
263    /// [`WidgetStateProperty::resolve`] is used for the following [`WidgetState`]s:
264    ///
265    ///  * [`WidgetState::Selected`].
266    ///
267    /// If this is `None`, then the value of [`DataTableThemeData::data_row_cursor`] is used. If
268    /// that's `None` too, then `SystemMouseCursors::click` is used.
269    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
270}
271
272impl DataRow {
273    /// Creates the configuration for a row of a [`DataTable`]; Dart's optional named arguments
274    /// are the setters.
275    pub fn new(cells: Vec<DataCell>) -> DataRow {
276        DataRow {
277            key: None,
278            on_select_changed: None,
279            on_long_press: None,
280            on_hover: None,
281            selected: false,
282            cells,
283            color: None,
284            mouse_cursor: None,
285        }
286    }
287
288    /// Dart's `DataRow.byIndex`: creates the configuration for a row of a [`DataTable`], deriving
289    /// the key from a row index.
290    ///
291    /// The row is keyed with a `ValueKey<Option<i32>>` of `index`.
292    pub fn by_index(index: Option<i32>, cells: Vec<DataCell>) -> DataRow {
293        DataRow {
294            key: Some(Rc::new(ValueKey::new(index))),
295            ..DataRow::new(cells)
296        }
297    }
298
299    /// Dart `DataRow(key:)`.
300    pub fn key(mut self, key: impl LocalKey + 'static) -> DataRow {
301        self.key = Some(Rc::new(key));
302        self
303    }
304
305    /// Dart `DataRow(selected:)`.
306    pub fn selected(mut self, selected: bool) -> DataRow {
307        self.selected = selected;
308        self
309    }
310
311    /// Dart `DataRow(onSelectChanged:)`.
312    pub fn on_select_changed(
313        mut self,
314        on_select_changed: impl Fn(&mut App, Option<bool>) + 'static,
315    ) -> DataRow {
316        self.on_select_changed = Some(Rc::new(on_select_changed));
317        self
318    }
319
320    /// Dart `DataRow(onLongPress:)`.
321    pub fn on_long_press(mut self, on_long_press: GestureLongPressCallback) -> DataRow {
322        self.on_long_press = Some(on_long_press);
323        self
324    }
325
326    /// Dart `DataRow(onHover:)`.
327    pub fn on_hover(mut self, on_hover: impl Fn(&mut App, bool) + 'static) -> DataRow {
328        self.on_hover = Some(Rc::new(on_hover));
329        self
330    }
331
332    /// Dart `DataRow(color:)`.
333    pub fn color(mut self, color: WidgetStatePropertyRef<Option<Color>>) -> DataRow {
334        self.color = Some(color);
335        self
336    }
337
338    /// Dart `DataRow(mouseCursor:)`.
339    pub fn mouse_cursor(
340        mut self,
341        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>>,
342    ) -> DataRow {
343        self.mouse_cursor = Some(mouse_cursor);
344        self
345    }
346
347    /// Dart's `_debugInteractive`.
348    fn debug_interactive(&self) -> bool {
349        self.on_select_changed.is_some() || self.cells.iter().any(DataCell::debug_interactive)
350    }
351}
352
353impl fmt::Debug for DataRow {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        f.debug_struct("DataRow")
356            .field("key", &self.key)
357            .field("selected", &self.selected)
358            .field("selectable", &self.on_select_changed.is_some())
359            .field("cells", &self.cells)
360            .finish_non_exhaustive()
361    }
362}
363
364/// The data for a cell of a [`DataTable`].
365///
366/// One list of [`DataCell`] objects must be provided for each [`DataRow`] in the [`DataTable`],
367/// in the new [`DataRow`] constructor's `cells` argument. This list must have the same length as
368/// the [`DataTable::columns`] argument to the [`DataTable`].
369#[derive(Clone)]
370pub struct DataCell {
371    /// The data for the row.
372    ///
373    /// Typically a `Text` widget or a `DropdownButton` widget.
374    ///
375    /// If the cell has no data, then a `Text` widget with placeholder text should be provided
376    /// instead, and then the [`placeholder`](Self::placeholder) argument should be set to true.
377    pub child: WidgetRef,
378
379    /// Whether the [`child`](Self::child) is actually a placeholder.
380    ///
381    /// If this is true, the default text style for the cell is changed to be appropriate for
382    /// placeholder text.
383    pub placeholder: bool,
384
385    /// Whether to show an edit icon at the end of the cell.
386    ///
387    /// This does not make the cell actually editable; the caller must implement editing behavior
388    /// if desired (initiated from the [`on_tap`](Self::on_tap) callback).
389    ///
390    /// If this is set, [`on_tap`](Self::on_tap) should also be set, otherwise tapping the icon
391    /// will have no effect.
392    pub show_edit_icon: bool,
393
394    /// Called if the cell is tapped.
395    ///
396    /// If non-null, tapping the cell will call this callback. If null (including
397    /// [`on_double_tap`](Self::on_double_tap), [`on_long_press`](Self::on_long_press),
398    /// [`on_tap_cancel`](Self::on_tap_cancel) and [`on_tap_down`](Self::on_tap_down)), tapping the
399    /// cell will attempt to select the row (if [`DataRow::on_select_changed`] is provided).
400    pub on_tap: Option<GestureTapCallback>,
401
402    /// Called when the cell is double tapped.
403    ///
404    /// If non-null, tapping the cell will call this callback. If null, tapping the cell will
405    /// attempt to select the row (if [`DataRow::on_select_changed`] is provided).
406    pub on_double_tap: Option<GestureTapCallback>,
407
408    /// Called if the cell is long-pressed.
409    ///
410    /// If non-null, long-pressing the cell will call this callback. If null, long-pressing the
411    /// cell will attempt to select the row (if [`DataRow::on_select_changed`] is provided).
412    pub on_long_press: Option<GestureLongPressCallback>,
413
414    /// Called if the cell is tapped down.
415    ///
416    /// If non-null, tapping down the cell will call this callback. If null, tapping down the
417    /// cell will attempt to select the row (if [`DataRow::on_select_changed`] is provided).
418    pub on_tap_down: Option<GestureTapDownCallback>,
419
420    /// Called if the user cancels a tap was started on cell.
421    ///
422    /// If non-null, canceling the tap gesture will call this callback. If null, canceling the
423    /// tap gesture will attempt to select the row (if [`DataRow::on_select_changed`] is
424    /// provided).
425    pub on_tap_cancel: Option<GestureTapCancelCallback>,
426}
427
428impl DataCell {
429    /// Creates a data cell for a [`DataTable`]; Dart's optional named arguments are the setters.
430    #[cfg_attr(debug_assertions, track_caller)]
431    pub fn new<K>(child: impl IntoWidget<K>) -> DataCell {
432        DataCell {
433            child: child.into_widget(),
434            placeholder: false,
435            show_edit_icon: false,
436            on_tap: None,
437            on_double_tap: None,
438            on_long_press: None,
439            on_tap_down: None,
440            on_tap_cancel: None,
441        }
442    }
443
444    /// A data cell that has no content and that has zero width and height.
445    ///
446    /// This cell is used by default for cells in a [`DataRow`] where no cell is specified.
447    ///
448    /// Dart's `static const DataCell empty`.
449    pub fn empty() -> DataCell {
450        DataCell::new(SizedBox::shrink())
451    }
452
453    /// Dart `DataCell(placeholder:)`.
454    pub fn placeholder(mut self, placeholder: bool) -> DataCell {
455        self.placeholder = placeholder;
456        self
457    }
458
459    /// Dart `DataCell(showEditIcon:)`.
460    pub fn show_edit_icon(mut self, show_edit_icon: bool) -> DataCell {
461        self.show_edit_icon = show_edit_icon;
462        self
463    }
464
465    /// Dart `DataCell(onTap:)`.
466    pub fn on_tap(mut self, on_tap: GestureTapCallback) -> DataCell {
467        self.on_tap = Some(on_tap);
468        self
469    }
470
471    /// Dart `DataCell(onDoubleTap:)`.
472    pub fn on_double_tap(mut self, on_double_tap: GestureTapCallback) -> DataCell {
473        self.on_double_tap = Some(on_double_tap);
474        self
475    }
476
477    /// Dart `DataCell(onLongPress:)`.
478    pub fn on_long_press(mut self, on_long_press: GestureLongPressCallback) -> DataCell {
479        self.on_long_press = Some(on_long_press);
480        self
481    }
482
483    /// Dart `DataCell(onTapDown:)`.
484    pub fn on_tap_down(mut self, on_tap_down: GestureTapDownCallback) -> DataCell {
485        self.on_tap_down = Some(on_tap_down);
486        self
487    }
488
489    /// Dart `DataCell(onTapCancel:)`.
490    pub fn on_tap_cancel(mut self, on_tap_cancel: GestureTapCancelCallback) -> DataCell {
491        self.on_tap_cancel = Some(on_tap_cancel);
492        self
493    }
494
495    /// Dart's `_debugInteractive`.
496    fn debug_interactive(&self) -> bool {
497        self.on_tap.is_some()
498            || self.on_double_tap.is_some()
499            || self.on_long_press.is_some()
500            || self.on_tap_down.is_some()
501            || self.on_tap_cancel.is_some()
502    }
503}
504
505impl fmt::Debug for DataCell {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        f.debug_struct("DataCell")
508            .field("child", &self.child)
509            .field("placeholder", &self.placeholder)
510            .field("show_edit_icon", &self.show_edit_icon)
511            .finish_non_exhaustive()
512    }
513}
514
515/// The key of the heading row, Dart's `static final LocalKey _headingRowKey = UniqueKey()`.
516fn heading_row_key() -> Rc<dyn LocalKey> {
517    static KEY: OnceLock<UniqueKey> = OnceLock::new();
518    Rc::new(*KEY.get_or_init(UniqueKey::new))
519}
520
521const HEADING_ROW_HEIGHT: f64 = 56.0;
522const HORIZONTAL_MARGIN: f64 = 24.0;
523const COLUMN_SPACING: f64 = 56.0;
524const SORT_ARROW_PADDING: f64 = 2.0;
525const DIVIDER_THICKNESS: f64 = 1.0;
526const SORT_ARROW_ANIMATION_DURATION: Duration = Duration::from_millis(150);
527
528/// A Material Design data table.
529///
530/// Displaying data in a table is expected to be a common operation. For example, a list of
531/// users, with each user having a name, an age, and so on.
532///
533/// If the [`on_select_changed`](DataRow::on_select_changed) of any row is set, a checkbox
534/// column is shown first, and a [`DataRow`] with a null `on_select_changed` is disabled.
535///
536/// The [`DataTable`] widget does not scroll on its own: if the table might be too large for its
537/// parent, wrap it in a scrollable. A [`DataTable`] must have a `Material` ancestor if any of
538/// its columns or rows are interactive.
539///
540/// The width of each column is determined by the algorithm in `Table`: by default, a column
541/// that is the only non-numeric column gets an [`IntrinsicColumnWidth`] with a flex of 1, and
542/// every other column an [`IntrinsicColumnWidth`] without one, unless the [`DataColumn`] gives a
543/// [`column_width`](DataColumn::column_width).
544///
545/// See also:
546///
547///  * `PaginatedDataTable`, which shows part of the data in a data table and provides controls
548///    for paging through the remainder of the data.
549///  * `TableRowInkWell`, a widget used to provide ink to a table row.
550#[derive(Clone)]
551pub struct DataTable {
552    pub key: Option<KeyRef>,
553
554    /// The configuration and labels for the columns in the table.
555    pub columns: Vec<DataColumn>,
556
557    /// The current primary sort key's column.
558    ///
559    /// If non-null, indicates that the indicated column is the column by which the data is
560    /// sorted. The number must correspond to the index of the relevant column in [`columns`].
561    ///
562    /// Setting this will cause the relevant column to have a sort indicator displayed.
563    ///
564    /// When this is null, it implies that the table's sort order does not correspond to any of
565    /// the columns.
566    ///
567    /// The direction of the sort is specified using [`sort_ascending`](Self::sort_ascending).
568    pub sort_column_index: Option<usize>,
569
570    /// Whether the column mentioned in [`sort_column_index`](Self::sort_column_index), if any,
571    /// is sorted in ascending order.
572    ///
573    /// If true, the order is ascending (meaning the rows with the smallest values for the
574    /// current sort column are first in the table).
575    ///
576    /// If false, the order is descending (meaning the rows with the smallest values for the
577    /// current sort column are last in the table).
578    ///
579    /// Ascending order is represented by an upwards-facing arrow.
580    pub sort_ascending: bool,
581
582    /// Overrides the default sort indicator (an arrow) shown in a sortable column's heading.
583    ///
584    /// If null, the default arrow is used. Otherwise it is called with whether the column is
585    /// sorted and whether it is sorted ascending.
586    pub sort_icon_builder: Option<DataTableSortIconBuilder>,
587
588    /// Invoked when the user selects or unselects every row, using the checkbox in the heading
589    /// row.
590    ///
591    /// If this is null, then the [`DataRow::on_select_changed`] callback of every row in the
592    /// table is invoked appropriately instead.
593    ///
594    /// To control whether a particular row is selectable or not, see
595    /// [`DataRow::on_select_changed`]. This callback is only relevant if any row is selectable.
596    pub on_select_all: Option<ValueChanged<Option<bool>>>,
597
598    /// The background and border decoration for the table.
599    pub decoration: Option<DecorationRef>,
600
601    /// The background color for the data rows.
602    ///
603    /// The effective background color can be made to depend on the [`WidgetState`] state, i.e. if
604    /// the row is selected, pressed, hovered, focused, disabled or enabled. The color is painted
605    /// as an overlay to the row. To make sure that the row's [`InkWell`] is visible (when
606    /// pressed, hovered and focused), it is recommended to use a translucent color.
607    ///
608    /// If [`DataRow::color`] is non-null for a row, that color is used for that row instead.
609    pub data_row_color: Option<WidgetStatePropertyRef<Option<Color>>>,
610
611    /// The minimum height of each row (excluding the row that contains column headings).
612    ///
613    /// This value is optional and defaults to `K_MIN_INTERACTIVE_DIMENSION` if not specified.
614    pub data_row_min_height: Option<f64>,
615
616    /// The maximum height of each row (excluding the row that contains column headings).
617    ///
618    /// This value is optional and defaults to `K_MIN_INTERACTIVE_DIMENSION` if not specified.
619    pub data_row_max_height: Option<f64>,
620
621    /// The text style for data rows.
622    ///
623    /// By default, the text style is `TextTheme::body_medium`.
624    pub data_text_style: Option<TextStyle>,
625
626    /// The background color for the heading row.
627    ///
628    /// The effective background color can be made to depend on the [`WidgetState`] state, i.e. if
629    /// the row is pressed, hovered, focused when sorted. The color is painted as an overlay to
630    /// the row.
631    pub heading_row_color: Option<WidgetStatePropertyRef<Option<Color>>>,
632
633    /// The height of the heading row.
634    ///
635    /// This value is optional and defaults to 56.0 if not specified.
636    pub heading_row_height: Option<f64>,
637
638    /// The text style for the heading row.
639    ///
640    /// By default, the text style is `TextTheme::title_small`.
641    pub heading_text_style: Option<TextStyle>,
642
643    /// The horizontal margin between the edges of the table and the content in the first and
644    /// last cells of each row.
645    ///
646    /// When a checkbox is displayed, it is also the margin between the checkbox the content in
647    /// the first data column.
648    ///
649    /// This value defaults to 24.0 to adhere to the Material Design specifications.
650    ///
651    /// If [`checkbox_horizontal_margin`](Self::checkbox_horizontal_margin) is null, then
652    /// [`horizontal_margin`](Self::horizontal_margin) is also the margin between the edge of the
653    /// table and the checkbox, as well as the margin between the checkbox and the content in the
654    /// first data column.
655    pub horizontal_margin: Option<f64>,
656
657    /// The horizontal margin between the contents of each data column.
658    ///
659    /// This value defaults to 56.0 to adhere to the Material Design specifications.
660    pub column_spacing: Option<f64>,
661
662    /// Whether the widget should display checkboxes for selectable rows.
663    ///
664    /// If true, a [`Checkbox`] will be placed at the beginning of each row that is selectable.
665    /// However, if [`DataRow::on_select_changed`] is not set for any row, checkboxes will not be
666    /// placed, even if this value is true.
667    ///
668    /// If false, all rows will not display a [`Checkbox`].
669    pub show_checkbox_column: bool,
670
671    /// The data to show in each row (excluding the row that contains the column headings).
672    ///
673    /// The list may be empty.
674    pub rows: Vec<DataRow>,
675
676    /// The thickness of the divider between rows.
677    ///
678    /// This value is optional and defaults to 1.0 if not specified.
679    pub divider_thickness: Option<f64>,
680
681    /// Whether a border at the bottom of the table is displayed.
682    ///
683    /// By default, a border is not shown at the bottom to allow for a border around the table
684    /// defined by [`decoration`](Self::decoration).
685    pub show_bottom_border: bool,
686
687    /// Horizontal margin around the checkbox, if it is displayed.
688    ///
689    /// If null, then [`horizontal_margin`](Self::horizontal_margin) is used as the margin
690    /// between the edge of the table and the checkbox, as well as the margin between the
691    /// checkbox and the content in the first data column. This value defaults to 24.0.
692    pub checkbox_horizontal_margin: Option<f64>,
693
694    /// The style to use when painting the boundary and interior divisions of the table.
695    pub border: Option<TableBorder>,
696
697    /// {@macro flutter.material.Material.clipBehavior}
698    ///
699    /// This can be used to clip the content within the border of the [`DataTable`].
700    ///
701    /// Defaults to [`Clip::None`].
702    pub clip_behavior: Clip,
703
704    /// Dart's `final int? _onlyTextColumn`: the index of the only non-numeric column, if there is
705    /// exactly one.
706    only_text_column: Option<usize>,
707}
708
709impl DataTable {
710    /// Creates a widget describing a data table; Dart's optional named arguments are the
711    /// setters.
712    ///
713    /// The [`columns`](Self::columns) argument must be a list of as many [`DataColumn`] objects
714    /// as the table is to have columns, ignoring the leading checkbox column which may be
715    /// omitted. The [`rows`](Self::rows) argument must be a list of [`DataRow`] objects to be
716    /// shown, each with a [`DataRow::cells`] list of the same length as `columns`.
717    pub fn new(columns: Vec<DataColumn>, rows: Vec<DataRow>) -> DataTable {
718        let only_text_column = Self::init_only_text_column(&columns);
719        DataTable {
720            key: None,
721            columns,
722            sort_column_index: None,
723            sort_ascending: true,
724            sort_icon_builder: None,
725            on_select_all: None,
726            decoration: None,
727            data_row_color: None,
728            data_row_min_height: None,
729            data_row_max_height: None,
730            data_text_style: None,
731            heading_row_color: None,
732            heading_row_height: None,
733            heading_text_style: None,
734            horizontal_margin: None,
735            column_spacing: None,
736            show_checkbox_column: true,
737            rows,
738            divider_thickness: None,
739            show_bottom_border: false,
740            checkbox_horizontal_margin: None,
741            border: None,
742            clip_behavior: Clip::None,
743            only_text_column,
744        }
745    }
746
747    /// Dart `DataTable(key:)`.
748    pub fn key(mut self, key: KeyRef) -> DataTable {
749        self.key = Some(key);
750        self
751    }
752
753    /// Dart `DataTable(sortColumnIndex:)`.
754    pub fn sort_column_index(mut self, sort_column_index: usize) -> DataTable {
755        self.sort_column_index = Some(sort_column_index);
756        self
757    }
758
759    /// Dart `DataTable(sortAscending:)`.
760    pub fn sort_ascending(mut self, sort_ascending: bool) -> DataTable {
761        self.sort_ascending = sort_ascending;
762        self
763    }
764
765    /// Dart `DataTable(sortIconBuilder:)`.
766    pub fn sort_icon_builder(
767        mut self,
768        sort_icon_builder: impl Fn(&mut App, BuildContext, bool, bool) -> WidgetRef + 'static,
769    ) -> DataTable {
770        self.sort_icon_builder = Some(Rc::new(sort_icon_builder));
771        self
772    }
773
774    /// Dart `DataTable(onSelectAll:)`.
775    pub fn on_select_all(
776        mut self,
777        on_select_all: impl Fn(&mut App, Option<bool>) + 'static,
778    ) -> DataTable {
779        self.on_select_all = Some(Rc::new(on_select_all));
780        self
781    }
782
783    /// Dart `DataTable(decoration:)`.
784    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> DataTable {
785        self.decoration = Some(decoration.into());
786        self
787    }
788
789    /// Dart `DataTable(dataRowColor:)`.
790    pub fn data_row_color(
791        mut self,
792        data_row_color: WidgetStatePropertyRef<Option<Color>>,
793    ) -> DataTable {
794        self.data_row_color = Some(data_row_color);
795        self
796    }
797
798    /// Dart's deprecated `DataTable(dataRowHeight:)`: it sets
799    /// [`data_row_min_height`](Self::data_row_min_height) and
800    /// [`data_row_max_height`](Self::data_row_max_height) to one value.
801    ///
802    /// Dart asserts that the argument is not given with either of them; a fluent chain has no
803    /// one call to compare, so a later setter replaces what an earlier one wrote.
804    #[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."]
805    pub fn data_row_height(mut self, data_row_height: f64) -> DataTable {
806        self.data_row_min_height = Some(data_row_height);
807        self.data_row_max_height = Some(data_row_height);
808        self
809    }
810
811    /// Dart `DataTable(dataRowMinHeight:)`.
812    pub fn data_row_min_height(mut self, data_row_min_height: f64) -> DataTable {
813        self.data_row_min_height = Some(data_row_min_height);
814        self
815    }
816
817    /// Dart `DataTable(dataRowMaxHeight:)`.
818    pub fn data_row_max_height(mut self, data_row_max_height: f64) -> DataTable {
819        self.data_row_max_height = Some(data_row_max_height);
820        self
821    }
822
823    /// Dart `DataTable(dataTextStyle:)`.
824    pub fn data_text_style(mut self, data_text_style: TextStyle) -> DataTable {
825        self.data_text_style = Some(data_text_style);
826        self
827    }
828
829    /// Dart `DataTable(headingRowColor:)`.
830    pub fn heading_row_color(
831        mut self,
832        heading_row_color: WidgetStatePropertyRef<Option<Color>>,
833    ) -> DataTable {
834        self.heading_row_color = Some(heading_row_color);
835        self
836    }
837
838    /// Dart `DataTable(headingRowHeight:)`.
839    pub fn heading_row_height(mut self, heading_row_height: f64) -> DataTable {
840        self.heading_row_height = Some(heading_row_height);
841        self
842    }
843
844    /// Dart `DataTable(headingTextStyle:)`.
845    pub fn heading_text_style(mut self, heading_text_style: TextStyle) -> DataTable {
846        self.heading_text_style = Some(heading_text_style);
847        self
848    }
849
850    /// Dart `DataTable(horizontalMargin:)`.
851    pub fn horizontal_margin(mut self, horizontal_margin: f64) -> DataTable {
852        self.horizontal_margin = Some(horizontal_margin);
853        self
854    }
855
856    /// Dart `DataTable(columnSpacing:)`.
857    pub fn column_spacing(mut self, column_spacing: f64) -> DataTable {
858        self.column_spacing = Some(column_spacing);
859        self
860    }
861
862    /// Dart `DataTable(showCheckboxColumn:)`.
863    pub fn show_checkbox_column(mut self, show_checkbox_column: bool) -> DataTable {
864        self.show_checkbox_column = show_checkbox_column;
865        self
866    }
867
868    /// Dart `DataTable(showBottomBorder:)`.
869    pub fn show_bottom_border(mut self, show_bottom_border: bool) -> DataTable {
870        self.show_bottom_border = show_bottom_border;
871        self
872    }
873
874    /// Dart `DataTable(dividerThickness:)`.
875    pub fn divider_thickness(mut self, divider_thickness: f64) -> DataTable {
876        debug_assert!(divider_thickness >= 0.0);
877        self.divider_thickness = Some(divider_thickness);
878        self
879    }
880
881    /// Dart `DataTable(checkboxHorizontalMargin:)`.
882    pub fn checkbox_horizontal_margin(mut self, checkbox_horizontal_margin: f64) -> DataTable {
883        self.checkbox_horizontal_margin = Some(checkbox_horizontal_margin);
884        self
885    }
886
887    /// Dart `DataTable(border:)`.
888    pub fn border(mut self, border: TableBorder) -> DataTable {
889        self.border = Some(border);
890        self
891    }
892
893    /// Dart `DataTable(clipBehavior:)`.
894    pub fn clip_behavior(mut self, clip_behavior: Clip) -> DataTable {
895        self.clip_behavior = clip_behavior;
896        self
897    }
898
899    /// Dart's deprecated `dataRowHeight` getter: the row height, if the minimum and the maximum
900    /// are the same.
901    #[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."]
902    pub fn data_row_height_value(&self) -> Option<f64> {
903        if self.data_row_min_height == self.data_row_max_height {
904            self.data_row_min_height
905        } else {
906            None
907        }
908    }
909
910    /// Dart's `_initOnlyTextColumn`: the index of the only column that is non-numeric, if there
911    /// is exactly one, otherwise `None`.
912    fn init_only_text_column(columns: &[DataColumn]) -> Option<usize> {
913        let mut result = None;
914        for (index, column) in columns.iter().enumerate() {
915            if !column.numeric {
916                if result.is_some() {
917                    return None;
918                }
919                result = Some(index);
920            }
921        }
922        result
923    }
924
925    /// Dart's `_debugInteractive`.
926    fn debug_interactive(&self) -> bool {
927        self.columns.iter().any(DataColumn::debug_interactive)
928            || self.rows.iter().any(DataRow::debug_interactive)
929    }
930
931    fn handle_select_all(&self, app: &mut App, checked: Option<bool>, some_checked: bool) {
932        // If some checkboxes are checked, all checkboxes are selected. Otherwise, use the new
933        // checked value but default to false if it's null.
934        let effective_checked = some_checked || checked.unwrap_or(false);
935        if let Some(on_select_all) = &self.on_select_all {
936            on_select_all(app, Some(effective_checked));
937        } else {
938            for row in &self.rows {
939                if let Some(on_select_changed) = &row.on_select_changed
940                    && row.selected != effective_checked
941                {
942                    on_select_changed(app, Some(effective_checked));
943                }
944            }
945        }
946    }
947
948    #[expect(clippy::too_many_arguments, reason = "Dart's named arguments")]
949    fn build_checkbox(
950        &self,
951        app: &mut App,
952        context: BuildContext,
953        checked: Option<bool>,
954        on_row_tap: Option<Listener>,
955        on_checkbox_changed: Option<ValueChanged<Option<bool>>>,
956        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
957        tristate: bool,
958        row_mouse_cursor: Option<MouseCursorRef>,
959    ) -> WidgetRef {
960        let theme_data = Theme::of(app, context);
961        let effective_horizontal_margin = self
962            .horizontal_margin
963            .or(theme_data.data_table_theme.horizontal_margin)
964            .unwrap_or(HORIZONTAL_MARGIN);
965        let effective_checkbox_horizontal_margin_start = self
966            .checkbox_horizontal_margin
967            .or(theme_data.data_table_theme.checkbox_horizontal_margin)
968            .unwrap_or(effective_horizontal_margin);
969        let effective_checkbox_horizontal_margin_end = self
970            .checkbox_horizontal_margin
971            .or(theme_data.data_table_theme.checkbox_horizontal_margin)
972            .unwrap_or(effective_horizontal_margin / 2.0);
973        let mut contents = Semantics::new()
974            .container(true)
975            .child(
976                Padding::new(EdgeInsetsDirectional::only(
977                    effective_checkbox_horizontal_margin_start,
978                    0.0,
979                    effective_checkbox_horizontal_margin_end,
980                    0.0,
981                ))
982                .child(
983                    Center::new()
984                        .child(Checkbox::new(checked, on_checkbox_changed).tristate(tristate)),
985                ),
986            )
987            .into_widget();
988        if let Some(on_row_tap) = on_row_tap {
989            let mut ink_well = TableRowInkWell::new().on_tap(on_row_tap);
990            if let Some(overlay_color) = overlay_color {
991                ink_well = ink_well.overlay_color(overlay_color);
992            }
993            if let Some(row_mouse_cursor) = row_mouse_cursor {
994                ink_well = ink_well.mouse_cursor(row_mouse_cursor);
995            }
996            contents = ink_well.child(contents).into_widget();
997        }
998        TableCell::new(contents)
999            .vertical_alignment(TableCellVerticalAlignment::Fill)
1000            .into_widget()
1001    }
1002
1003    #[expect(clippy::too_many_arguments, reason = "Dart's named arguments")]
1004    fn build_heading_cell(
1005        &self,
1006        app: &mut App,
1007        context: BuildContext,
1008        padding: EdgeInsetsGeometry,
1009        label: WidgetRef,
1010        tooltip: Option<String>,
1011        numeric: bool,
1012        on_sort: Option<Listener>,
1013        sorted: bool,
1014        ascending: bool,
1015        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1016        mouse_cursor: Option<MouseCursorRef>,
1017        heading_row_alignment: MainAxisAlignment,
1018    ) -> WidgetRef {
1019        let theme_data = Theme::of(app, context);
1020        let data_table_theme = DataTableTheme::of(app, context);
1021        let effective_sort_icon_builder = self
1022            .sort_icon_builder
1023            .clone()
1024            .or_else(|| data_table_theme.sort_icon_builder.clone());
1025
1026        let mut row = Row::new().main_axis_alignment(heading_row_alignment);
1027        if numeric {
1028            row = row.text_direction(TextDirection::Rtl);
1029        }
1030        let mut children = Vec::new();
1031        if heading_row_alignment == MainAxisAlignment::Center && on_sort.is_some() {
1032            children.push(
1033                SizedBox::new()
1034                    .width(SortArrowState::ARROW_ICON_SIZE + SORT_ARROW_PADDING)
1035                    .into_widget(),
1036            );
1037        }
1038        children.push(label);
1039        if on_sort.is_some() {
1040            children.push(match effective_sort_icon_builder {
1041                Some(builder) => builder(app, context, sorted, ascending),
1042                None => SortArrow {
1043                    visible: sorted,
1044                    up: if sorted { Some(ascending) } else { None },
1045                    duration: SORT_ARROW_ANIMATION_DURATION,
1046                }
1047                .into_widget(),
1048            });
1049            children.push(SizedBox::new().width(SORT_ARROW_PADDING).into_widget());
1050        }
1051        let label = Semantics::new()
1052            .role(waft_embedder::SemanticsRole::ColumnHeader)
1053            .child(row.children(children))
1054            .into_widget();
1055
1056        let effective_heading_text_style = self
1057            .heading_text_style
1058            .clone()
1059            .or_else(|| data_table_theme.heading_text_style.clone())
1060            .or_else(|| theme_data.data_table_theme.heading_text_style.clone())
1061            .unwrap_or_else(|| {
1062                theme_data
1063                    .text_theme
1064                    .title_small
1065                    .clone()
1066                    .expect("the theme's text theme has titleSmall")
1067            });
1068        let effective_heading_row_height = self
1069            .heading_row_height
1070            .or(data_table_theme.heading_row_height)
1071            .or(theme_data.data_table_theme.heading_row_height)
1072            .unwrap_or(HEADING_ROW_HEIGHT);
1073        let default_text_style = DefaultTextStyle::of(app, context);
1074        let mut label = Container::new()
1075            .padding(padding)
1076            .height(effective_heading_row_height)
1077            .alignment(if numeric {
1078                AlignmentGeometry::CENTER_RIGHT
1079            } else {
1080                AlignmentGeometry::CENTER_START
1081            })
1082            .child(
1083                AnimatedDefaultTextStyle::new(
1084                    label,
1085                    default_text_style
1086                        .style
1087                        .merge(Some(&effective_heading_text_style)),
1088                    SORT_ARROW_ANIMATION_DURATION,
1089                )
1090                .soft_wrap(false),
1091            )
1092            .into_widget();
1093        if let Some(tooltip) = tooltip {
1094            label = Tooltip::new().message(tooltip).child(label).into_widget();
1095        }
1096
1097        let mut ink_well = InkWell::new();
1098        if let Some(on_sort) = on_sort {
1099            ink_well = ink_well.on_tap(on_sort);
1100        }
1101        if let Some(overlay_color) = overlay_color {
1102            ink_well = ink_well.overlay_color(overlay_color);
1103        }
1104        if let Some(mouse_cursor) = mouse_cursor {
1105            ink_well = ink_well.mouse_cursor(mouse_cursor);
1106        }
1107        ink_well.child(label).into_widget()
1108    }
1109
1110    #[expect(clippy::too_many_arguments, reason = "Dart's named arguments")]
1111    #[allow(deprecated)] // Dart's `withOpacity`.
1112    fn build_data_cell(
1113        &self,
1114        app: &mut App,
1115        context: BuildContext,
1116        padding: EdgeInsetsGeometry,
1117        label: WidgetRef,
1118        numeric: bool,
1119        placeholder: bool,
1120        show_edit_icon: bool,
1121        on_tap: Option<GestureTapCallback>,
1122        on_select_changed: Option<Listener>,
1123        on_double_tap: Option<GestureTapCallback>,
1124        on_long_press: Option<GestureLongPressCallback>,
1125        on_tap_down: Option<GestureTapDownCallback>,
1126        on_tap_cancel: Option<GestureTapCancelCallback>,
1127        overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1128        on_row_long_press: Option<GestureLongPressCallback>,
1129        on_row_hover: Option<ValueChanged<bool>>,
1130        mouse_cursor: Option<MouseCursorRef>,
1131    ) -> WidgetRef {
1132        let theme_data = Theme::of(app, context);
1133        let data_table_theme = DataTableTheme::of(app, context);
1134        let mut label = label;
1135        if show_edit_icon {
1136            let icon = Icon::new(Some(Icons::edit())).size(18.0);
1137            label = waft_widgets::Expanded::new(label).into_widget();
1138            let mut row = Row::new();
1139            if numeric {
1140                row = row.text_direction(TextDirection::Rtl);
1141            }
1142            label = row.children(vec![label, icon.into_widget()]).into_widget();
1143        }
1144
1145        let effective_data_text_style = self
1146            .data_text_style
1147            .clone()
1148            .or_else(|| data_table_theme.data_text_style.clone())
1149            .or_else(|| theme_data.data_table_theme.data_text_style.clone())
1150            .unwrap_or_else(|| {
1151                theme_data
1152                    .text_theme
1153                    .body_medium
1154                    .clone()
1155                    .expect("the theme's text theme has bodyMedium")
1156            });
1157        let effective_data_row_min_height = self
1158            .data_row_min_height
1159            .or(data_table_theme.data_row_min_height)
1160            .or(theme_data.data_table_theme.data_row_min_height)
1161            .unwrap_or(K_MIN_INTERACTIVE_DIMENSION);
1162        let effective_data_row_max_height = self
1163            .data_row_max_height
1164            .or(data_table_theme.data_row_max_height)
1165            .or(theme_data.data_table_theme.data_row_max_height)
1166            .unwrap_or(K_MIN_INTERACTIVE_DIMENSION);
1167        let default_text_style = DefaultTextStyle::of(app, context);
1168        let merged = default_text_style
1169            .style
1170            .merge(Some(&effective_data_text_style));
1171        let style = if placeholder {
1172            merged.copy_with().color(
1173                effective_data_text_style
1174                    .color
1175                    .as_ref()
1176                    .expect("a data text style has a color")
1177                    .color()
1178                    .with_opacity(0.6),
1179            )
1180        } else {
1181            merged
1182        };
1183        let mut label = Container::new()
1184            .padding(padding)
1185            .constraints(BoxConstraints {
1186                min_height: effective_data_row_min_height,
1187                max_height: effective_data_row_max_height,
1188                ..BoxConstraints::new()
1189            })
1190            .alignment(if numeric {
1191                AlignmentGeometry::CENTER_RIGHT
1192            } else {
1193                AlignmentGeometry::CENTER_START
1194            })
1195            .child(DefaultTextStyle::new(
1196                style,
1197                DropdownButtonHideUnderline::new(label),
1198            ))
1199            .into_widget();
1200        if on_tap.is_some()
1201            || on_double_tap.is_some()
1202            || on_long_press.is_some()
1203            || on_tap_down.is_some()
1204            || on_tap_cancel.is_some()
1205        {
1206            let mut ink_well = InkWell::new();
1207            if let Some(on_tap) = on_tap {
1208                ink_well = ink_well.on_tap(on_tap);
1209            }
1210            if let Some(on_double_tap) = on_double_tap {
1211                ink_well = ink_well.on_double_tap(on_double_tap);
1212            }
1213            if let Some(on_long_press) = on_long_press {
1214                ink_well = ink_well.on_long_press(on_long_press);
1215            }
1216            if let Some(on_tap_cancel) = on_tap_cancel {
1217                ink_well = ink_well.on_tap_cancel(on_tap_cancel);
1218            }
1219            if let Some(on_tap_down) = on_tap_down {
1220                ink_well = ink_well.on_tap_down(on_tap_down);
1221            }
1222            if let Some(overlay_color) = overlay_color {
1223                ink_well = ink_well.overlay_color(overlay_color);
1224            }
1225            label = ink_well.child(label).into_widget();
1226        } else if on_select_changed.is_some()
1227            || on_row_long_press.is_some()
1228            || on_row_hover.is_some()
1229        {
1230            let mut ink_well = TableRowInkWell::new();
1231            if let Some(on_select_changed) = on_select_changed {
1232                ink_well = ink_well.on_tap(on_select_changed);
1233            }
1234            if let Some(on_row_long_press) = on_row_long_press {
1235                ink_well = ink_well.on_long_press(on_row_long_press);
1236            }
1237            if let Some(on_row_hover) = on_row_hover {
1238                ink_well = ink_well.on_hover(on_row_hover);
1239            }
1240            if let Some(overlay_color) = overlay_color {
1241                ink_well = ink_well.overlay_color(overlay_color);
1242            }
1243            if let Some(mouse_cursor) = mouse_cursor {
1244                ink_well = ink_well.mouse_cursor(mouse_cursor);
1245            }
1246            label = ink_well.child(label).into_widget();
1247        }
1248        TableCell::new(label).into_widget()
1249    }
1250}
1251
1252impl fmt::Debug for DataTable {
1253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1254        f.debug_struct("DataTable")
1255            .field("columns", &self.columns)
1256            .field("rows", &self.rows)
1257            .field("sort_column_index", &self.sort_column_index)
1258            .field("sort_ascending", &self.sort_ascending)
1259            .finish_non_exhaustive()
1260    }
1261}
1262
1263impl StatelessWidget for DataTable {
1264    fn key(&self) -> Option<&KeyRef> {
1265        self.key.as_ref()
1266    }
1267
1268    fn debug_check_constructor(&self) {
1269        debug_assert!(!self.columns.is_empty());
1270        debug_assert!(
1271            self.sort_column_index
1272                .is_none_or(|index| index < self.columns.len())
1273        );
1274        debug_assert!(
1275            self.rows
1276                .iter()
1277                .all(|row| row.cells.len() == self.columns.len()),
1278            "All rows must have the same number of cells as there are header cells ({})",
1279            self.columns.len()
1280        );
1281        debug_assert!(
1282            self.divider_thickness
1283                .is_none_or(|thickness| thickness >= 0.0)
1284        );
1285        debug_assert!(match (self.data_row_min_height, self.data_row_max_height) {
1286            (Some(min), Some(max)) => max >= min,
1287            _ => true,
1288        });
1289    }
1290
1291    #[allow(deprecated)] // Dart's `withOpacity`.
1292    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1293        debug_assert!(!self.debug_interactive() || debug_check_has_material(app, context));
1294
1295        let theme = Theme::of(app, context);
1296        let data_table_theme = DataTableTheme::of(app, context);
1297        let effective_heading_row_color = self
1298            .heading_row_color
1299            .clone()
1300            .or_else(|| data_table_theme.heading_row_color.clone())
1301            .or_else(|| theme.data_table_theme.heading_row_color.clone());
1302        let effective_data_row_color = self
1303            .data_row_color
1304            .clone()
1305            .or_else(|| data_table_theme.data_row_color.clone())
1306            .or_else(|| theme.data_table_theme.data_row_color.clone());
1307        let primary = theme.color_scheme.primary();
1308        let default_row_color =
1309            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
1310                if states.contains(&WidgetState::Selected) {
1311                    return Some(primary.with_opacity(0.08));
1312                }
1313                None
1314            });
1315        let any_row_selectable = self.rows.iter().any(|row| row.on_select_changed.is_some());
1316        let display_checkbox_column = self.show_checkbox_column && any_row_selectable;
1317        let rows_with_checkbox: Vec<&DataRow> = if display_checkbox_column {
1318            self.rows
1319                .iter()
1320                .filter(|row| row.on_select_changed.is_some())
1321                .collect()
1322        } else {
1323            Vec::new()
1324        };
1325        let rows_checked = rows_with_checkbox.iter().filter(|row| row.selected).count();
1326        let all_checked = display_checkbox_column && rows_checked == rows_with_checkbox.len();
1327        let any_checked = display_checkbox_column && rows_checked > 0;
1328        let some_checked = any_checked && !all_checked;
1329        let effective_horizontal_margin = self
1330            .horizontal_margin
1331            .or(data_table_theme.horizontal_margin)
1332            .or(theme.data_table_theme.horizontal_margin)
1333            .unwrap_or(HORIZONTAL_MARGIN);
1334        let effective_checkbox_horizontal_margin_start = self
1335            .checkbox_horizontal_margin
1336            .or(data_table_theme.checkbox_horizontal_margin)
1337            .or(theme.data_table_theme.checkbox_horizontal_margin)
1338            .unwrap_or(effective_horizontal_margin);
1339        let effective_checkbox_horizontal_margin_end = self
1340            .checkbox_horizontal_margin
1341            .or(data_table_theme.checkbox_horizontal_margin)
1342            .or(theme.data_table_theme.checkbox_horizontal_margin)
1343            .unwrap_or(effective_horizontal_margin / 2.0);
1344        let effective_column_spacing = self
1345            .column_spacing
1346            .or(data_table_theme.column_spacing)
1347            .or(theme.data_table_theme.column_spacing)
1348            .unwrap_or(COLUMN_SPACING);
1349
1350        let table_column_count = self.columns.len() + usize::from(display_checkbox_column);
1351        let mut table_columns: Vec<Option<TableColumnWidthRef>> = vec![None; table_column_count];
1352        // The first row is the heading; each cell is filled in below.
1353        let mut cells: Vec<Vec<Option<WidgetRef>>> =
1354            vec![vec![None; table_column_count]; self.rows.len() + 1];
1355        let mut row_decorations = Vec::with_capacity(self.rows.len() + 1);
1356        for index in 0..=self.rows.len() {
1357            let is_selected = index > 0 && self.rows[index - 1].selected;
1358            let is_disabled =
1359                index > 0 && any_row_selectable && self.rows[index - 1].on_select_changed.is_none();
1360            let mut states = WidgetStates::new();
1361            if is_selected {
1362                states.insert(WidgetState::Selected);
1363            }
1364            if is_disabled {
1365                states.insert(WidgetState::Disabled);
1366            }
1367            let resolved_data_row_color = if index > 0 {
1368                self.rows[index - 1]
1369                    .color
1370                    .clone()
1371                    .or_else(|| effective_data_row_color.clone())
1372                    .and_then(|color| color.resolve(&states))
1373            } else {
1374                None
1375            };
1376            let resolved_heading_row_color = effective_heading_row_color
1377                .as_ref()
1378                .and_then(|color| color.resolve(&WidgetStates::new()));
1379            let row_color = if index > 0 {
1380                resolved_data_row_color
1381            } else {
1382                resolved_heading_row_color
1383            };
1384            let border_side = Divider::create_border_side(
1385                app,
1386                Some(context),
1387                None,
1388                Some(
1389                    self.divider_thickness
1390                        .or(data_table_theme.divider_thickness)
1391                        .or(theme.data_table_theme.divider_thickness)
1392                        .unwrap_or(DIVIDER_THICKNESS),
1393                ),
1394            );
1395            let border = if self.show_bottom_border {
1396                Some(Border {
1397                    bottom: border_side,
1398                    ..Border::default()
1399                })
1400            } else if index == 0 {
1401                None
1402            } else {
1403                Some(Border {
1404                    top: border_side,
1405                    ..Border::default()
1406                })
1407            };
1408            let mut decoration = BoxDecoration::new();
1409            if let Some(border) = border {
1410                decoration = decoration.border(border);
1411            }
1412            if let Some(color) = row_color.or_else(|| default_row_color.resolve(&states)) {
1413                decoration = decoration.color(color);
1414            }
1415            row_decorations.push(decoration);
1416        }
1417
1418        let mut display_column_index = 0;
1419        if display_checkbox_column {
1420            table_columns[0] = Some(Rc::new(FixedColumnWidth::new(
1421                effective_checkbox_horizontal_margin_start
1422                    + Checkbox::WIDTH
1423                    + effective_checkbox_horizontal_margin_end,
1424            )));
1425            let this = self.clone();
1426            cells[0][0] = Some(self.build_checkbox(
1427                app,
1428                context,
1429                if some_checked {
1430                    None
1431                } else {
1432                    Some(all_checked)
1433                },
1434                None,
1435                Some(Rc::new(move |app: &mut App, checked: Option<bool>| {
1436                    this.handle_select_all(app, checked, some_checked);
1437                })),
1438                None,
1439                true,
1440                None,
1441            ));
1442            for (row_index, row) in self.rows.iter().enumerate() {
1443                let mut states = WidgetStates::new();
1444                if row.selected {
1445                    states.insert(WidgetState::Selected);
1446                }
1447                let on_row_tap = row.on_select_changed.clone().map(|on_select_changed| {
1448                    let selected = row.selected;
1449                    Listener::new(move |app: &mut App| on_select_changed(app, Some(!selected)))
1450                });
1451                cells[row_index + 1][0] = Some(
1452                    self.build_checkbox(
1453                        app,
1454                        context,
1455                        Some(row.selected),
1456                        on_row_tap,
1457                        row.on_select_changed.clone(),
1458                        row.color
1459                            .clone()
1460                            .or_else(|| effective_data_row_color.clone()),
1461                        false,
1462                        row.mouse_cursor
1463                            .as_ref()
1464                            .and_then(|cursor| cursor.resolve(&states))
1465                            .or_else(|| {
1466                                data_table_theme
1467                                    .data_row_cursor
1468                                    .as_ref()
1469                                    .and_then(|cursor| cursor.resolve(&states))
1470                            }),
1471                    ),
1472                );
1473            }
1474            display_column_index += 1;
1475        }
1476
1477        for (data_column_index, column) in self.columns.iter().enumerate() {
1478            let padding_start = if data_column_index == 0
1479                && display_checkbox_column
1480                && self.checkbox_horizontal_margin.is_none()
1481            {
1482                effective_horizontal_margin / 2.0
1483            } else if data_column_index == 0 {
1484                effective_horizontal_margin
1485            } else {
1486                effective_column_spacing / 2.0
1487            };
1488            let padding_end = if data_column_index == self.columns.len() - 1 {
1489                effective_horizontal_margin
1490            } else {
1491                effective_column_spacing / 2.0
1492            };
1493            let padding: EdgeInsetsGeometry =
1494                EdgeInsetsDirectional::only(padding_start, 0.0, padding_end, 0.0).into();
1495            table_columns[display_column_index] = Some(match &column.column_width {
1496                Some(width) => Rc::clone(width),
1497                None if Some(data_column_index) == self.only_text_column => {
1498                    Rc::new(IntrinsicColumnWidth::new(Some(1.0)))
1499                }
1500                None => Rc::new(IntrinsicColumnWidth::new(None)),
1501            });
1502
1503            let mut header_states = WidgetStates::new();
1504            if column.on_sort.is_none() {
1505                header_states.insert(WidgetState::Disabled);
1506            }
1507            let on_sort = column.on_sort.clone().map(|on_sort| {
1508                let sort_column_index = self.sort_column_index;
1509                let sort_ascending = self.sort_ascending;
1510                Listener::new(move |app: &mut App| {
1511                    on_sort(
1512                        app,
1513                        data_column_index as i32,
1514                        sort_column_index != Some(data_column_index) || !sort_ascending,
1515                    )
1516                })
1517            });
1518            cells[0][display_column_index] = Some(
1519                self.build_heading_cell(
1520                    app,
1521                    context,
1522                    padding,
1523                    column.label.clone(),
1524                    column.tooltip.clone(),
1525                    column.numeric,
1526                    on_sort,
1527                    Some(data_column_index) == self.sort_column_index,
1528                    self.sort_ascending,
1529                    effective_heading_row_color.clone(),
1530                    column
1531                        .mouse_cursor
1532                        .as_ref()
1533                        .and_then(|cursor| cursor.resolve(&header_states))
1534                        .or_else(|| {
1535                            data_table_theme
1536                                .heading_cell_cursor
1537                                .as_ref()
1538                                .and_then(|cursor| cursor.resolve(&header_states))
1539                        }),
1540                    column
1541                        .heading_row_alignment
1542                        .or(data_table_theme.heading_row_alignment)
1543                        .unwrap_or(MainAxisAlignment::Start),
1544                ),
1545            );
1546            for (row_index, row) in self.rows.iter().enumerate() {
1547                let mut states = WidgetStates::new();
1548                if row.selected {
1549                    states.insert(WidgetState::Selected);
1550                }
1551                let cell = &row.cells[data_column_index];
1552                let on_select_changed = row.on_select_changed.clone().map(|on_select_changed| {
1553                    let selected = row.selected;
1554                    Listener::new(move |app: &mut App| on_select_changed(app, Some(!selected)))
1555                });
1556                cells[row_index + 1][display_column_index] = Some(
1557                    self.build_data_cell(
1558                        app,
1559                        context,
1560                        padding,
1561                        cell.child.clone(),
1562                        column.numeric,
1563                        cell.placeholder,
1564                        cell.show_edit_icon,
1565                        cell.on_tap.clone(),
1566                        on_select_changed,
1567                        cell.on_double_tap.clone(),
1568                        cell.on_long_press.clone(),
1569                        cell.on_tap_down.clone(),
1570                        cell.on_tap_cancel.clone(),
1571                        row.color
1572                            .clone()
1573                            .or_else(|| effective_data_row_color.clone()),
1574                        row.on_long_press.clone(),
1575                        row.on_hover.clone(),
1576                        row.mouse_cursor
1577                            .as_ref()
1578                            .and_then(|cursor| cursor.resolve(&states))
1579                            .or_else(|| {
1580                                data_table_theme
1581                                    .data_row_cursor
1582                                    .as_ref()
1583                                    .and_then(|cursor| cursor.resolve(&states))
1584                            }),
1585                    ),
1586                );
1587            }
1588            display_column_index += 1;
1589        }
1590
1591        let table_rows: Vec<TableRow> = cells
1592            .into_iter()
1593            .zip(row_decorations)
1594            .enumerate()
1595            .map(|(index, (children, decoration))| {
1596                {
1597                    let mut row = TableRow::new().decoration(decoration);
1598                    if index == 0 {
1599                        row = row.key(heading_row_key());
1600                    } else if let Some(key) = self.rows[index - 1].key.clone() {
1601                        row = row.key(key);
1602                    }
1603                    row
1604                }
1605                .children(
1606                    children
1607                        .into_iter()
1608                        .map(|child| child.expect("every cell is built")),
1609                )
1610            })
1611            .collect();
1612        let column_widths: HashMap<usize, TableColumnWidthRef> = table_columns
1613            .into_iter()
1614            .enumerate()
1615            .map(|(index, width)| (index, width.expect("every column has a width")))
1616            .collect();
1617
1618        let mut table = Table::new()
1619            .column_widths(column_widths)
1620            .default_vertical_alignment(TableCellVerticalAlignment::Middle)
1621            .children(table_rows);
1622        if let Some(border) = &self.border {
1623            table = table.border(*border);
1624        }
1625        let mut material = Material::new()
1626            .r#type(MaterialType::Transparency)
1627            .clip_behavior(self.clip_behavior);
1628        if let Some(border) = &self.border {
1629            material = material.border_radius(border.border_radius);
1630        }
1631        let mut container = Container::new();
1632        if let Some(decoration) = self
1633            .decoration
1634            .clone()
1635            .or_else(|| data_table_theme.decoration.clone())
1636            .or_else(|| theme.data_table_theme.decoration.clone())
1637        {
1638            container = container.decoration(decoration);
1639        }
1640        container
1641            .child(material.child(table.into_widget()))
1642            .into_widget()
1643    }
1644}
1645
1646/// An ink well for the cells of a [`DataTable`] row that paints its highlight across the whole
1647/// row.
1648///
1649/// A [`TableRowInkWell`] must be in the same coordinate space (modulo translations) as the
1650/// `Table` widget that it is a descendant of. A [`TableRowInkWell`] must be an ancestor of the
1651/// `Table`'s cells' render objects, and a descendant of a `Table`.
1652///
1653/// This widget is the cell of a row, which makes the whole row respond to input.
1654///
1655/// See also:
1656///
1657///  * [`DataTable`], which makes use of [`TableRowInkWell`] when [`DataRow::on_select_changed`]
1658///    is set, or one of its cells has gesture callbacks.
1659///  * [`InkResponse`], which is the base class of this widget.
1660#[derive(Clone, Debug)]
1661pub struct TableRowInkWell {
1662    /// Dart's `extends InkResponse`: the fields it inherits.
1663    pub ink_response: InkResponse,
1664}
1665
1666impl TableRowInkWell {
1667    /// Creates an ink well for a table row; Dart's optional named arguments are the setters.
1668    pub fn new() -> TableRowInkWell {
1669        TableRowInkWell {
1670            ink_response: InkResponse {
1671                contained_ink_well: true,
1672                highlight_shape: waft_painting::BoxShape::Rectangle,
1673                get_rect_callback: Rc::new(TableRowInkWell::get_rect_callback),
1674                debug_check_context: Rc::new(|app, context| {
1675                    debug_check_has_table(app, context)
1676                        && InkResponse::debug_check_context(app, context)
1677                }),
1678                ..InkResponse::default()
1679            },
1680        }
1681    }
1682
1683    /// Dart `TableRowInkWell(key:)`.
1684    pub fn key(mut self, key: KeyRef) -> TableRowInkWell {
1685        self.ink_response.key = Some(key);
1686        self
1687    }
1688
1689    /// Dart `TableRowInkWell(child:)`.
1690    #[cfg_attr(debug_assertions, track_caller)]
1691    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> TableRowInkWell {
1692        self.ink_response.child = Some(child.into_widget());
1693        self
1694    }
1695
1696    /// Dart `TableRowInkWell(onTap:)`.
1697    pub fn on_tap(mut self, on_tap: GestureTapCallback) -> TableRowInkWell {
1698        self.ink_response.on_tap = Some(on_tap);
1699        self
1700    }
1701
1702    /// Dart `TableRowInkWell(onDoubleTap:)`.
1703    pub fn on_double_tap(mut self, on_double_tap: GestureTapCallback) -> TableRowInkWell {
1704        self.ink_response.on_double_tap = Some(on_double_tap);
1705        self
1706    }
1707
1708    /// Dart `TableRowInkWell(onLongPress:)`.
1709    pub fn on_long_press(mut self, on_long_press: GestureLongPressCallback) -> TableRowInkWell {
1710        self.ink_response.on_long_press = Some(on_long_press);
1711        self
1712    }
1713
1714    /// Dart `TableRowInkWell(onHighlightChanged:)`.
1715    pub fn on_highlight_changed(
1716        mut self,
1717        on_highlight_changed: ValueChanged<bool>,
1718    ) -> TableRowInkWell {
1719        self.ink_response.on_highlight_changed = Some(on_highlight_changed);
1720        self
1721    }
1722
1723    /// Dart `TableRowInkWell(onHover:)`.
1724    pub fn on_hover(mut self, on_hover: ValueChanged<bool>) -> TableRowInkWell {
1725        self.ink_response.on_hover = Some(on_hover);
1726        self
1727    }
1728
1729    /// Dart `TableRowInkWell(onSecondaryTap:)`.
1730    pub fn on_secondary_tap(mut self, on_secondary_tap: GestureTapCallback) -> TableRowInkWell {
1731        self.ink_response.on_secondary_tap = Some(on_secondary_tap);
1732        self
1733    }
1734
1735    /// Dart `TableRowInkWell(onSecondaryTapDown:)`.
1736    pub fn on_secondary_tap_down(
1737        mut self,
1738        on_secondary_tap_down: GestureTapDownCallback,
1739    ) -> TableRowInkWell {
1740        self.ink_response.on_secondary_tap_down = Some(on_secondary_tap_down);
1741        self
1742    }
1743
1744    /// Dart `TableRowInkWell(overlayColor:)`.
1745    pub fn overlay_color(
1746        mut self,
1747        overlay_color: WidgetStatePropertyRef<Option<Color>>,
1748    ) -> TableRowInkWell {
1749        self.ink_response.overlay_color = Some(overlay_color);
1750        self
1751    }
1752
1753    /// Dart `TableRowInkWell(mouseCursor:)`.
1754    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> TableRowInkWell {
1755        self.ink_response.mouse_cursor = Some(mouse_cursor);
1756        self
1757    }
1758
1759    /// Dart's override of `getRectCallback`: the rect of the whole table row the reference box
1760    /// is a cell of, in the reference box's coordinate space.
1761    fn get_rect_callback(_app: &App, reference_box: AnyRenderBox) -> Option<RectCallback> {
1762        Some(Rc::new(move |app: &App| {
1763            let mut cell: AnyRenderObject = reference_box.as_object();
1764            let mut table = cell.parent(app);
1765            let mut transform = Matrix4::IDENTITY;
1766            while let Some(parent) = table {
1767                if parent.downcast::<RenderTable>(app).is_some() {
1768                    break;
1769                }
1770                parent.apply_paint_transform(app, cell, &mut transform);
1771                debug_assert_eq!(Some(parent), cell.parent(app));
1772                cell = parent;
1773                table = parent.parent(app);
1774            }
1775            if let Some(table) = table.and_then(|table| table.downcast::<RenderTable>(app)) {
1776                let cell_parent_data = cell.parent_data_of::<TableCellParentData>(app);
1777                let row = cell_parent_data.y.expect("a laid-out cell has a row");
1778                let rect = table.get_row_box(app, row);
1779                // The rect is in the table's coordinate space. We need to change it to the
1780                // TableRowInkWell's coordinate space.
1781                table
1782                    .as_object()
1783                    .apply_paint_transform(app, cell, &mut transform);
1784                if let Some(offset) = waft_painting::get_as_translation(transform) {
1785                    return rect.shift(-offset);
1786                }
1787            }
1788            Rect::ZERO
1789        }))
1790    }
1791}
1792
1793impl Default for TableRowInkWell {
1794    fn default() -> TableRowInkWell {
1795        TableRowInkWell::new()
1796    }
1797}
1798
1799impl StatelessWidget for TableRowInkWell {
1800    fn key(&self) -> Option<&KeyRef> {
1801        self.ink_response.key.as_ref()
1802    }
1803
1804    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1805        self.ink_response.build_state_widget(app, context)
1806    }
1807}
1808
1809/// Dart's `_SortArrow`.
1810#[derive(Debug)]
1811struct SortArrow {
1812    visible: bool,
1813    up: Option<bool>,
1814    duration: Duration,
1815}
1816
1817impl StatefulWidget for SortArrow {
1818    type State = SortArrowState;
1819
1820    fn create_state(&self) -> SortArrowState {
1821        SortArrowState {
1822            state: StateData::new(),
1823            ticker_provider: TickerProviderStateMixinData::new(),
1824            opacity_controller: None,
1825            opacity_animation: None,
1826            orientation_controller: None,
1827            orientation_animation: None,
1828            turn_tween: None,
1829            orientation_offset: 0.0,
1830            up: None,
1831        }
1832    }
1833}
1834
1835/// Dart's `_SortArrowState`.
1836struct SortArrowState {
1837    state: StateData<SortArrow>,
1838    ticker_provider: TickerProviderStateMixinData,
1839    opacity_controller: Option<Ref<AnimationController>>,
1840    opacity_animation: Option<Ref<CurvedAnimation>>,
1841    orientation_controller: Option<Ref<AnimationController>>,
1842    orientation_animation: Option<AnimationRef<f64>>,
1843    /// Dart's `static final Animatable<double> _turnTween`.
1844    turn_tween: Option<Ref<Tween<f64>>>,
1845    orientation_offset: f64,
1846    up: Option<bool>,
1847}
1848
1849impl SortArrowState {
1850    const ARROW_ICON_BASELINE_OFFSET: f64 = -1.5;
1851    const ARROW_ICON_SIZE: f64 = 16.0;
1852
1853    fn opacity_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1854        app.get(self)
1855            .opacity_controller
1856            .as_ref()
1857            .expect("created in init_state")
1858            .handle()
1859    }
1860
1861    fn orientation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1862        app.get(self)
1863            .orientation_controller
1864            .as_ref()
1865            .expect("created in init_state")
1866            .handle()
1867    }
1868
1869    fn rebuild(self: Handle<Self>, app: &mut App) {
1870        // The animations changed, so we need to rebuild.
1871        self.set_state(app, |_state| {});
1872    }
1873
1874    fn reset_orientation_animation(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
1875        if status.is_completed() {
1876            let orientation_animation = app
1877                .get(self)
1878                .orientation_animation
1879                .clone()
1880                .expect("created in init_state");
1881            debug_assert_eq!(orientation_animation.value(app), PI);
1882            app.get_mut(self).orientation_offset += PI;
1883            self.orientation_controller(app).set_value(app, 0.0); // TODO(ianh): This triggers a pointless rebuild.
1884        }
1885    }
1886}
1887
1888impl TickerProviderStateMixin for SortArrowState {
1889    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
1890        &app.get(self).ticker_provider
1891    }
1892
1893    fn ticker_provider_data_mut(
1894        self: Handle<Self>,
1895        app: &mut App,
1896    ) -> &mut TickerProviderStateMixinData {
1897        &mut app.get_mut(self).ticker_provider
1898    }
1899}
1900
1901/// Dart's `vsync: this`.
1902impl TickerProviderObject for SortArrowState {
1903    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1904        TickerProviderStateMixin::create_ticker(self, app, on_tick)
1905    }
1906}
1907
1908impl State for SortArrowState {
1909    type Widget = SortArrow;
1910    waft_widgets::state_accessors!();
1911
1912    fn init_state(self: Handle<Self>, app: &mut App) {
1913        let widget_up = self.widget(app).up;
1914        let widget_visible = self.widget(app).visible;
1915        let duration = self.widget(app).duration;
1916        let opacity_controller = AnimationController::new(
1917            app,
1918            None,
1919            Some(duration),
1920            None,
1921            0.0,
1922            1.0,
1923            AnimationBehavior::Normal,
1924            self,
1925        );
1926        let opacity_animation = CurvedAnimation::new(
1927            app,
1928            opacity_controller.erase(),
1929            Curves::fast_out_slow_in(),
1930            None,
1931        );
1932        opacity_animation.add_listener(app, Listener::handle_method(self, Self::rebuild));
1933        opacity_controller.set_value(app, if widget_visible { 1.0 } else { 0.0 });
1934        let orientation_controller = AnimationController::new(
1935            app,
1936            None,
1937            Some(duration),
1938            None,
1939            0.0,
1940            1.0,
1941            AnimationBehavior::Normal,
1942            self,
1943        );
1944        let turn_tween = Tween::new(app, Some(0.0), Some(PI));
1945        let ease_in = CurveTween::new(app, Curves::ease_in());
1946        let orientation_animation =
1947            orientation_controller.drive(app, turn_tween.clone().chain(ease_in));
1948        orientation_animation.add_listener(app, Listener::handle_method(self, Self::rebuild));
1949        orientation_animation.add_status_listener(
1950            app,
1951            AnimationStatusListener::new(move |status, app| {
1952                self.reset_orientation_animation(app, status)
1953            }),
1954        );
1955        let state = app.get_mut(self);
1956        state.up = widget_up;
1957        state.opacity_controller = Some(opacity_controller);
1958        state.opacity_animation = Some(opacity_animation);
1959        state.orientation_controller = Some(orientation_controller);
1960        state.orientation_animation = Some(orientation_animation);
1961        state.turn_tween = Some(turn_tween);
1962        if widget_visible {
1963            state.orientation_offset = if widget_up.expect("a visible arrow has a direction") {
1964                0.0
1965            } else {
1966                PI
1967            };
1968        }
1969    }
1970
1971    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SortArrow) {
1972        let mut skip_arrow = false;
1973        let widget_up = self.widget(app).up;
1974        let widget_visible = self.widget(app).visible;
1975        let new_up = widget_up.or(app.get(self).up);
1976        if old_widget.visible != widget_visible {
1977            let opacity_controller = self.opacity_controller(app);
1978            if widget_visible && opacity_controller.is_dismissed(app) {
1979                let orientation_controller = self.orientation_controller(app);
1980                orientation_controller.stop(app, false);
1981                orientation_controller.set_value(app, 0.0);
1982                app.get_mut(self).orientation_offset =
1983                    if new_up.expect("a visible arrow has a direction") {
1984                        0.0
1985                    } else {
1986                        PI
1987                    };
1988                skip_arrow = true;
1989            }
1990            if widget_visible {
1991                opacity_controller.forward(app, None);
1992            } else {
1993                opacity_controller.reverse(app, None);
1994            }
1995        }
1996        if app.get(self).up != new_up && !skip_arrow {
1997            let orientation_controller = self.orientation_controller(app);
1998            if orientation_controller.is_dismissed(app) {
1999                orientation_controller.forward(app, None);
2000            } else {
2001                orientation_controller.reverse(app, None);
2002            }
2003        }
2004        app.get_mut(self).up = new_up;
2005    }
2006
2007    fn activate(self: Handle<Self>, app: &mut App) {
2008        TickerProviderStateMixin::activate(self, app);
2009    }
2010
2011    fn dispose(self: Handle<Self>, app: &mut App) {
2012        self.opacity_controller(app).dispose(app);
2013        self.orientation_controller(app).dispose(app);
2014        app.get(self)
2015            .opacity_animation
2016            .as_ref()
2017            .expect("created in init_state")
2018            .handle()
2019            .dispose(app);
2020        TickerProviderStateMixin::dispose(self, app);
2021    }
2022
2023    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2024        let state = app.get(self);
2025        let opacity = state
2026            .opacity_animation
2027            .as_ref()
2028            .expect("created in init_state")
2029            .erase();
2030        let orientation = state
2031            .orientation_animation
2032            .clone()
2033            .expect("created in init_state")
2034            .value(app);
2035        let angle = (state.orientation_offset + orientation) as f32;
2036        let [a, b, c, d, _, _] = Matrix4::rotation(angle).to_affine();
2037        let transform = Matrix4::from_affine(
2038            a,
2039            b,
2040            c,
2041            d,
2042            0.0,
2043            SortArrowState::ARROW_ICON_BASELINE_OFFSET as f32,
2044        );
2045        FadeTransition::new(opacity)
2046            .child(
2047                Transform::new(transform)
2048                    .alignment(AlignmentGeometry::CENTER)
2049                    .child(
2050                        Icon::new(Some(Icons::arrow_upward()))
2051                            .size(SortArrowState::ARROW_ICON_SIZE),
2052                    ),
2053            )
2054            .into_widget()
2055    }
2056}
2057
2058#[cfg(test)]
2059pub(crate) mod tests {
2060    //! The cases of `test/data_table_test.dart`.
2061
2062    use std::cell::RefCell;
2063    use std::f64::consts::PI;
2064    use std::rc::Rc;
2065    use std::time::Duration;
2066
2067    use waft_embedder::{Offset, Rect, Size};
2068    use waft_gestures::TapDownDetails;
2069    use waft_painting::{Border, BorderRadius, BorderSide, BorderStyle, BoxDecoration, TextStyle};
2070    use waft_rendering::FlexColumnWidth;
2071    use waft_rendering::testing::{PaintCall, paints};
2072    use waft_services::SystemMouseCursors;
2073    use waft_widgets::testing::{
2074        Finder, TestPointer, WidgetTester, assert_f32_equals, expect, find, finds_n_widgets,
2075        finds_nothing, finds_one_widget, test_widgets,
2076    };
2077    use waft_widgets::{Align, Builder, Column, Expanded, Text, WidgetStatePropertyAll};
2078
2079    use super::*;
2080    use crate::bottom_navigation_bar::tests::paragraph_style;
2081    use crate::checkbox_theme::CheckboxThemeData;
2082    use crate::colors::Colors;
2083    use crate::data_table_theme::DataTableThemeData;
2084    use crate::scaffold::Scaffold;
2085    use crate::test_support::PaintInspection;
2086    use crate::test_support::material_app;
2087    use crate::theme_data::ThemeData;
2088    use crate::tooltip::tests::m3;
2089
2090    /// The `Dessert` of `data_table_test_utils.dart`, with the fields the cases read.
2091    pub(crate) struct Dessert {
2092        pub name: &'static str,
2093        pub calories: i32,
2094        pub fat: f64,
2095    }
2096
2097    /// `kDesserts` of `data_table_test_utils.dart`.
2098    pub(crate) const K_DESSERTS: [Dessert; 10] = [
2099        Dessert {
2100            name: "Frozen yogurt",
2101            calories: 159,
2102            fat: 6.0,
2103        },
2104        Dessert {
2105            name: "Ice cream sandwich",
2106            calories: 237,
2107            fat: 9.0,
2108        },
2109        Dessert {
2110            name: "Eclair",
2111            calories: 262,
2112            fat: 16.0,
2113        },
2114        Dessert {
2115            name: "Cupcake",
2116            calories: 305,
2117            fat: 3.7,
2118        },
2119        Dessert {
2120            name: "Gingerbread",
2121            calories: 356,
2122            fat: 16.0,
2123        },
2124        Dessert {
2125            name: "Jelly bean",
2126            calories: 375,
2127            fat: 0.0,
2128        },
2129        Dessert {
2130            name: "Lollipop",
2131            calories: 392,
2132            fat: 0.2,
2133        },
2134        Dessert {
2135            name: "Honeycomb",
2136            calories: 408,
2137            fat: 3.2,
2138        },
2139        Dessert {
2140            name: "Donut",
2141            calories: 452,
2142            fat: 25.0,
2143        },
2144        Dessert {
2145            name: "KitKat",
2146            calories: 518,
2147            fat: 26.0,
2148        },
2149    ];
2150
2151    type Log = Rc<RefCell<Vec<String>>>;
2152
2153    fn new_log() -> Log {
2154        Rc::default()
2155    }
2156
2157    fn log_of(log: &Log) -> Vec<String> {
2158        log.borrow().clone()
2159    }
2160
2161    fn take_log(log: &Log) -> Vec<String> {
2162        std::mem::take(&mut *log.borrow_mut())
2163    }
2164
2165    /// Dart's `MaterialApp(home: Material(child: child))`.
2166    pub(crate) fn app_of<K>(tester: &WidgetTester, child: impl IntoWidget<K>) -> WidgetRef {
2167        material_app(
2168            m3(&tester.cell.borrow()),
2169            Material::new().child(child).into_widget(),
2170        )
2171    }
2172
2173    fn name_column() -> DataColumn {
2174        DataColumn::new(Text::new("Name")).tooltip("Name")
2175    }
2176
2177    fn calories_column() -> DataColumn {
2178        DataColumn::new(Text::new("Calories")).tooltip("Calories")
2179    }
2180
2181    fn name_rows() -> Vec<DataRow> {
2182        K_DESSERTS
2183            .iter()
2184            .map(|dessert| DataRow::new(vec![DataCell::new(Text::new(dessert.name))]))
2185            .collect()
2186    }
2187
2188    fn rotation_of(tester: &WidgetTester, finder: Finder) -> [f32; 4] {
2189        tester.widget(finder, |transform: &Transform| {
2190            let [a, b, c, d, _, _] = transform.transform.to_affine();
2191            [a, b, c, d]
2192        })
2193    }
2194
2195    fn assert_rotation(actual: [f32; 4], expected: [f32; 4]) {
2196        for (actual, expected) in actual.into_iter().zip(expected) {
2197            assert!((actual - expected).abs() < 1e-6, "{actual} vs {expected}");
2198        }
2199    }
2200
2201    fn control_table(
2202        log: &Log,
2203        sort_column_index: Option<usize>,
2204        sort_ascending: bool,
2205    ) -> DataTable {
2206        let select_all_log = Rc::clone(log);
2207        let sort_log = Rc::clone(log);
2208        let rows = K_DESSERTS
2209            .iter()
2210            .map(|dessert| {
2211                let name = dessert.name;
2212                let calories = dessert.calories;
2213                let selected_log = Rc::clone(log);
2214                let long_press_log = Rc::clone(log);
2215                let hover_log = Rc::clone(log);
2216                let tap_log = Rc::clone(log);
2217                let double_tap_log = Rc::clone(log);
2218                let cell_long_press_log = Rc::clone(log);
2219                let cancel_log = Rc::clone(log);
2220                let down_log = Rc::clone(log);
2221                DataRow::new(vec![
2222                    DataCell::new(Text::new(name)),
2223                    DataCell::new(Text::new(calories.to_string()))
2224                        .show_edit_icon(true)
2225                        .on_tap(Listener::new(move |_| {
2226                            tap_log.borrow_mut().push(format!("cell-tap: {calories}"))
2227                        }))
2228                        .on_double_tap(Listener::new(move |_| {
2229                            double_tap_log
2230                                .borrow_mut()
2231                                .push(format!("cell-doubleTap: {calories}"))
2232                        }))
2233                        .on_long_press(Listener::new(move |_| {
2234                            cell_long_press_log
2235                                .borrow_mut()
2236                                .push(format!("cell-longPress: {calories}"))
2237                        }))
2238                        .on_tap_cancel(Listener::new(move |_| {
2239                            cancel_log
2240                                .borrow_mut()
2241                                .push(format!("cell-tapCancel: {calories}"))
2242                        }))
2243                        .on_tap_down(Rc::new(move |_app: &mut App, _details: TapDownDetails| {
2244                            down_log
2245                                .borrow_mut()
2246                                .push(format!("cell-tapDown: {calories}"))
2247                        })),
2248                ])
2249                .key(ValueKey::new(name.to_owned()))
2250                .on_select_changed(move |_app, _selected| {
2251                    selected_log
2252                        .borrow_mut()
2253                        .push(format!("row-selected: {name}"))
2254                })
2255                .on_long_press(Listener::new(move |_| {
2256                    long_press_log
2257                        .borrow_mut()
2258                        .push(format!("onLongPress: {name}"))
2259                }))
2260                .on_hover(move |_app, hovering| {
2261                    if hovering {
2262                        hover_log.borrow_mut().push(format!("onHover: {name}"));
2263                    }
2264                })
2265            })
2266            .collect();
2267        let mut table = DataTable::new(
2268            vec![
2269                name_column(),
2270                calories_column()
2271                    .numeric(true)
2272                    .on_sort(move |_app, column_index, ascending| {
2273                        sort_log
2274                            .borrow_mut()
2275                            .push(format!("column-sort: {column_index} {ascending}"))
2276                    }),
2277            ],
2278            rows,
2279        )
2280        .sort_ascending(sort_ascending)
2281        .on_select_all(move |_app, value| {
2282            select_all_log.borrow_mut().push(format!(
2283                "select-all: {}",
2284                value.map_or("null".to_owned(), |v| v.to_string())
2285            ))
2286        });
2287        table.sort_column_index = sort_column_index;
2288        table
2289    }
2290
2291    #[test]
2292    fn data_table_control_test() {
2293        test_widgets(|tester| {
2294            let log = new_log();
2295            let root = app_of(tester, control_table(&log, None, true));
2296            tester.pump_widget(root);
2297
2298            tester.tap(find::by_type::<Checkbox>().first());
2299            assert_eq!(take_log(&log), ["select-all: true"]);
2300
2301            tester.tap(find::text("Cupcake"));
2302            assert_eq!(take_log(&log), ["row-selected: Cupcake"]);
2303
2304            tester.long_press(find::text("Cupcake"));
2305            assert_eq!(take_log(&log), ["onLongPress: Cupcake"]);
2306
2307            let mut gesture = TestPointer::mouse(1, 0);
2308            tester.add_pointer(&mut gesture, Offset::ZERO);
2309            tester.pump();
2310            let at = tester.get_center(find::text("Cupcake"));
2311            tester.move_to(&mut gesture, at, false);
2312            assert_eq!(take_log(&log), ["onHover: Cupcake"]);
2313
2314            tester.tap(find::text("Calories"));
2315            assert_eq!(take_log(&log), ["column-sort: 1 true"]);
2316
2317            let root = app_of(tester, control_table(&log, Some(1), true));
2318            tester.pump_widget(root);
2319            tester.pump_and_settle_by(Duration::from_millis(200));
2320            tester.tap(find::text("Calories"));
2321            assert_eq!(take_log(&log), ["column-sort: 1 false"]);
2322
2323            let root = app_of(tester, control_table(&log, Some(1), false));
2324            tester.pump_widget(root);
2325            tester.pump_and_settle_by(Duration::from_millis(200));
2326
2327            tester.long_press(find::text("375"));
2328            // The tap down is triggered on gesture down. Then, the cancel is triggered when the
2329            // gesture arena recognizes that the long press overrides the tap event so it
2330            // triggers a tap cancel, followed by the long press.
2331            assert_eq!(
2332                take_log(&log),
2333                [
2334                    "cell-tapDown: 375",
2335                    "cell-tapCancel: 375",
2336                    "cell-longPress: 375"
2337                ]
2338            );
2339
2340            let mut gesture = TestPointer::touch(tester.next_pointer());
2341            let center = tester.get_rect(find::text("375")).center();
2342            tester.down(&mut gesture, center);
2343            tester.pump_by(Duration::from_millis(100));
2344            // onTapDown callback is registered.
2345            assert_eq!(log_of(&log), ["cell-tapDown: 375"]);
2346            tester.up(&gesture);
2347
2348            tester.pump_by(Duration::from_secs(1));
2349            // onTap callback is registered after the gesture is removed.
2350            assert_eq!(take_log(&log), ["cell-tapDown: 375", "cell-tap: 375"]);
2351
2352            // dragging off the bounds of the cell calls the cancel callback
2353            let mut gesture = TestPointer::touch(tester.next_pointer());
2354            let center = tester.get_rect(find::text("375")).center();
2355            tester.down(&mut gesture, center);
2356            tester.pump_by(Duration::from_millis(100));
2357            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
2358            tester.cancel(&gesture);
2359            assert_eq!(take_log(&log), ["cell-tapDown: 375", "cell-tapCancel: 375"]);
2360
2361            tester.tap(find::by_type::<Checkbox>().last());
2362            assert_eq!(take_log(&log), ["row-selected: KitKat"]);
2363        });
2364    }
2365
2366    fn tristate_table(log: &Log, selected: [bool; 3], disabled_index: Option<usize>) -> DataTable {
2367        let select_all_log = Rc::clone(log);
2368        let rows = (0..3)
2369            .map(|index| {
2370                let row_log = Rc::clone(log);
2371                let mut row = DataRow::new(vec![DataCell::new(Text::new(format!("Row {index}")))])
2372                    .selected(selected[index]);
2373                if Some(index) != disabled_index {
2374                    row = row.on_select_changed(move |_app, _value| {
2375                        row_log.borrow_mut().push(format!("row-selected: {index}"))
2376                    });
2377                }
2378                row
2379            })
2380            .collect();
2381        DataTable::new(vec![name_column()], rows).on_select_all(move |_app, value| {
2382            select_all_log.borrow_mut().push(format!(
2383                "select-all: {}",
2384                value.map_or("null".to_owned(), |v| v.to_string())
2385            ))
2386        })
2387    }
2388
2389    #[test]
2390    fn data_table_control_test_tristate() {
2391        test_widgets(|tester| {
2392            let log = new_log();
2393            // Tapping the parent checkbox when no rows are selected, selects all.
2394            let root = app_of(tester, tristate_table(&log, [false, false, false], None));
2395            tester.pump_widget(root);
2396            tester.tap(find::by_type::<Checkbox>().first());
2397            assert_eq!(take_log(&log), ["select-all: true"]);
2398
2399            // Tapping the parent checkbox when some rows are selected, selects all.
2400            let root = app_of(tester, tristate_table(&log, [true, false, true], None));
2401            tester.pump_widget(root);
2402            tester.tap(find::by_type::<Checkbox>().first());
2403            assert_eq!(take_log(&log), ["select-all: true"]);
2404
2405            // Tapping the parent checkbox when all rows are selected, deselects all.
2406            let root = app_of(tester, tristate_table(&log, [true, true, true], None));
2407            tester.pump_widget(root);
2408            tester.tap(find::by_type::<Checkbox>().first());
2409            assert_eq!(take_log(&log), ["select-all: false"]);
2410
2411            // Tapping the parent checkbox when all rows are selected and one is disabled,
2412            // deselects all.
2413            let root = app_of(tester, tristate_table(&log, [true, true, false], Some(2)));
2414            tester.pump_widget(root);
2415            tester.tap(find::by_type::<Checkbox>().first());
2416            assert_eq!(take_log(&log), ["select-all: false"]);
2417        });
2418    }
2419
2420    fn no_checkbox_table(log: &Log, checkboxes: bool) -> DataTable {
2421        let select_all_log = Rc::clone(log);
2422        let rows = K_DESSERTS
2423            .iter()
2424            .map(|dessert| {
2425                let name = dessert.name;
2426                let calories = dessert.calories;
2427                let selected_log = Rc::clone(log);
2428                let tap_log = Rc::clone(log);
2429                DataRow::new(vec![
2430                    DataCell::new(Text::new(name)),
2431                    DataCell::new(Text::new(calories.to_string()))
2432                        .show_edit_icon(true)
2433                        .on_tap(Listener::new(move |_| {
2434                            tap_log.borrow_mut().push(format!("cell-tap: {calories}"))
2435                        })),
2436                ])
2437                .key(ValueKey::new(name.to_owned()))
2438                .on_select_changed(move |_app, _selected| {
2439                    selected_log
2440                        .borrow_mut()
2441                        .push(format!("row-selected: {name}"))
2442                })
2443            })
2444            .collect();
2445        DataTable::new(vec![name_column(), calories_column().numeric(true)], rows)
2446            .show_checkbox_column(checkboxes)
2447            .on_select_all(move |_app, value| {
2448                select_all_log.borrow_mut().push(format!(
2449                    "select-all: {}",
2450                    value.map_or("null".to_owned(), |v| v.to_string())
2451                ))
2452            })
2453    }
2454
2455    #[test]
2456    fn data_table_control_test_no_checkboxes() {
2457        test_widgets(|tester| {
2458            let log = new_log();
2459            let root = app_of(tester, no_checkbox_table(&log, false));
2460            tester.pump_widget(root);
2461
2462            expect(tester, &find::by_type::<Checkbox>(), finds_nothing());
2463            tester.tap(find::text("Cupcake"));
2464            assert_eq!(take_log(&log), ["row-selected: Cupcake"]);
2465
2466            let root = app_of(tester, no_checkbox_table(&log, true));
2467            tester.pump_widget(root);
2468
2469            tester.pump_and_settle_by(Duration::from_millis(200));
2470            let checkboxes = find::by_type::<Checkbox>();
2471            expect(tester, &checkboxes, finds_n_widgets(11));
2472            tester.tap(checkboxes.first());
2473            assert_eq!(take_log(&log), ["select-all: true"]);
2474        });
2475    }
2476
2477    fn lone_table(label: String, cell: String) -> DataTable {
2478        DataTable::new(
2479            vec![DataColumn::new(Text::new(label))],
2480            vec![DataRow::new(vec![DataCell::new(Text::new(cell))])],
2481        )
2482    }
2483
2484    fn width_of(tester: &WidgetTester, finder: Finder) -> f64 {
2485        tester.get_size(finder.first()).width()
2486    }
2487
2488    #[test]
2489    fn data_table_overflow_test_header() {
2490        test_widgets(|tester| {
2491            let table = DataTable::new(
2492                vec![DataColumn::new(Text::new("X".repeat(2000)))],
2493                vec![DataRow::new(vec![DataCell::new(Text::new("X"))])],
2494            )
2495            .heading_text_style(
2496                // Will overflow if letter spacing is larger than 0.0.
2497                TextStyle::new().font_size(14.0).letter_spacing(0.0),
2498            );
2499            let root = app_of(tester, table);
2500            tester.pump_widget(root);
2501
2502            assert!(width_of(tester, find::by_type::<Text>()) > 800.0);
2503            assert!(width_of(tester, find::by_type::<Row>()) > 800.0);
2504            // column overflows table, but text doesn't overflow cell
2505        });
2506    }
2507
2508    #[test]
2509    fn data_table_overflow_test_cell() {
2510        test_widgets(|tester| {
2511            let root = app_of(tester, lone_table("X".to_owned(), "X".repeat(2000)));
2512            tester.pump_widget(root);
2513            assert!(width_of(tester, find::by_type::<Text>()) < 800.0);
2514            assert!(width_of(tester, find::by_type::<Row>()) > 800.0);
2515            // cell overflows table, but text doesn't overflow cell
2516        });
2517    }
2518
2519    #[test]
2520    fn data_table_overflow_test_cell_that_wraps() {
2521        test_widgets(|tester| {
2522            let root = app_of(tester, lone_table("X".to_owned(), "X ".repeat(2000)));
2523            tester.pump_widget(root);
2524            assert!(width_of(tester, find::by_type::<Text>()) < 800.0);
2525            assert!(width_of(tester, find::by_type::<Row>()) < 800.0);
2526        });
2527    }
2528
2529    #[test]
2530    fn data_table_column_on_sort_test() {
2531        test_widgets(|tester| {
2532            let root = app_of(
2533                tester,
2534                lone_table("Dessert".to_owned(), "Lollipop".to_owned()),
2535            );
2536            tester.pump_widget(root);
2537            tester.tap(find::text("Dessert"));
2538            tester.pump();
2539        });
2540    }
2541
2542    fn sort_table(title: &str, ascending: bool) -> DataTable {
2543        DataTable::new(
2544            vec![
2545                DataColumn::new(Text::new(title))
2546                    .tooltip("Name")
2547                    .on_sort(|_app, _index, _ascending| {}),
2548            ],
2549            name_rows(),
2550        )
2551        .sort_column_index(0)
2552        .sort_ascending(ascending)
2553    }
2554
2555    #[test]
2556    fn data_table_sort_indicator_orientation() {
2557        test_widgets(|tester| {
2558            let icon_finder = find::descendant(
2559                find::by_type::<DataTable>(),
2560                find::widget_with_icon::<Transform>(&Icons::arrow_upward()),
2561            );
2562            // Check for ascending list
2563            let root = app_of(tester, sort_table("Name", true));
2564            tester.pump_widget(root);
2565            // The `tester.widget` ensures that there is exactly one upward arrow.
2566            assert_rotation(
2567                rotation_of(tester, icon_finder.clone()),
2568                [1.0, 0.0, 0.0, 1.0],
2569            );
2570
2571            // Check for descending list.
2572            let root = app_of(tester, sort_table("Name", false));
2573            tester.pump_widget(root);
2574            tester.pump_and_settle();
2575            assert_rotation(
2576                rotation_of(tester, icon_finder),
2577                [
2578                    PI.cos() as f32,
2579                    PI.sin() as f32,
2580                    -PI.sin() as f32,
2581                    PI.cos() as f32,
2582                ],
2583            );
2584        });
2585    }
2586
2587    #[test]
2588    fn data_table_sort_indicator_orientation_does_not_change_on_state_update() {
2589        test_widgets(|tester| {
2590            let icon_finder = find::descendant(
2591                find::by_type::<DataTable>(),
2592                find::widget_with_icon::<Transform>(&Icons::arrow_upward()),
2593            );
2594            let root = app_of(tester, sort_table("Name1", true));
2595            tester.pump_widget(root);
2596            assert_rotation(
2597                rotation_of(tester, icon_finder.clone()),
2598                [1.0, 0.0, 0.0, 1.0],
2599            );
2600
2601            // Cause a rebuild by updating the widget
2602            let root = app_of(tester, sort_table("Name2", true));
2603            tester.pump_widget(root);
2604            tester.pump_and_settle();
2605            assert_rotation(rotation_of(tester, icon_finder), [1.0, 0.0, 0.0, 1.0]);
2606        });
2607    }
2608
2609    #[test]
2610    fn data_table_sort_indicator_orientation_does_not_change_on_state_update_reverse() {
2611        test_widgets(|tester| {
2612            let icon_finder = find::descendant(
2613                find::by_type::<DataTable>(),
2614                find::widget_with_icon::<Transform>(&Icons::arrow_upward()),
2615            );
2616            let expected = [
2617                PI.cos() as f32,
2618                PI.sin() as f32,
2619                -PI.sin() as f32,
2620                PI.cos() as f32,
2621            ];
2622            let root = app_of(tester, sort_table("Name1", false));
2623            tester.pump_widget(root);
2624            assert_rotation(rotation_of(tester, icon_finder.clone()), expected);
2625
2626            let root = app_of(tester, sort_table("Name2", false));
2627            tester.pump_widget(root);
2628            tester.pump_and_settle();
2629            assert_rotation(rotation_of(tester, icon_finder), expected);
2630        });
2631    }
2632
2633    #[test]
2634    fn data_table_row_on_select_changed_test() {
2635        test_widgets(|tester| {
2636            let root = app_of(
2637                tester,
2638                lone_table("Dessert".to_owned(), "Lollipop".to_owned()),
2639            );
2640            tester.pump_widget(root);
2641            tester.tap(find::text("Lollipop"));
2642            tester.pump();
2643        });
2644    }
2645
2646    fn first_container_for(text: &str) -> Finder {
2647        find::widget_with_text::<Container>(text).first()
2648    }
2649
2650    fn row_height_table(
2651        data_row_min_height: Option<f64>,
2652        data_row_max_height: Option<f64>,
2653        heading_row_height: f64,
2654    ) -> DataTable {
2655        let rows = K_DESSERTS
2656            .iter()
2657            .map(|dessert| {
2658                DataRow::new(vec![
2659                    DataCell::new(Text::new(dessert.name)),
2660                    DataCell::new(Text::new(dessert.calories.to_string()))
2661                        .show_edit_icon(true)
2662                        .on_tap(Listener::new(|_| {})),
2663                ])
2664                .key(ValueKey::new(dessert.name.to_owned()))
2665                .on_select_changed(|_app, _selected| {})
2666            })
2667            .collect();
2668        let mut table = DataTable::new(
2669            vec![
2670                name_column(),
2671                calories_column()
2672                    .numeric(true)
2673                    .on_sort(|_app, _index, _ascending| {}),
2674            ],
2675            rows,
2676        )
2677        .on_select_all(|_app, _value| {})
2678        .heading_row_height(heading_row_height);
2679        table.data_row_min_height = data_row_min_height;
2680        table.data_row_max_height = data_row_max_height;
2681        table
2682    }
2683
2684    #[test]
2685    fn data_table_custom_row_height() {
2686        test_widgets(|tester| {
2687            // DEFAULT VALUES
2688            let root = app_of(tester, row_height_table(None, None, 56.0));
2689            tester.pump_widget(root);
2690
2691            // The finder matches with the Container of the cell content, as well as the
2692            // Container wrapping the whole table. The first one is used to test row heights.
2693            assert_eq!(tester.get_size(first_container_for("Name")).height(), 56.0);
2694            assert_eq!(
2695                tester
2696                    .get_size(first_container_for("Frozen yogurt"))
2697                    .height(),
2698                K_MIN_INTERACTIVE_DIMENSION
2699            );
2700
2701            // CUSTOM VALUES
2702            let root = app_of(tester, row_height_table(None, None, 48.0));
2703            tester.pump_widget(root);
2704            assert_eq!(tester.get_size(first_container_for("Name")).height(), 48.0);
2705
2706            let root = app_of(tester, row_height_table(None, None, 64.0));
2707            tester.pump_widget(root);
2708            assert_eq!(tester.get_size(first_container_for("Name")).height(), 64.0);
2709
2710            let root = app_of(tester, row_height_table(Some(30.0), Some(30.0), 56.0));
2711            tester.pump_widget(root);
2712            assert_eq!(
2713                tester
2714                    .get_size(first_container_for("Frozen yogurt"))
2715                    .height(),
2716                30.0
2717            );
2718
2719            let root = app_of(
2720                tester,
2721                row_height_table(Some(0.0), Some(f64::INFINITY), 56.0),
2722            );
2723            tester.pump_widget(root);
2724            assert!(
2725                tester
2726                    .get_size(first_container_for("Frozen yogurt"))
2727                    .height()
2728                    > 0.0
2729            );
2730        });
2731    }
2732
2733    #[test]
2734    fn data_table_custom_row_height_one_row_taller_than_others() {
2735        test_widgets(|tester| {
2736            let multiline_text = "Line one.\nLine two.\nLine three.\nLine four.";
2737            let table = DataTable::new(
2738                vec![
2739                    DataColumn::new(Text::new("SingleRowColumn")),
2740                    DataColumn::new(Text::new("MultiRowColumn")),
2741                ],
2742                vec![DataRow::new(vec![
2743                    DataCell::new(Text::new("Data")),
2744                    DataCell::new(
2745                        Column::new().children(vec![Text::new(multiline_text).into_widget()]),
2746                    ),
2747                ])],
2748            )
2749            .data_row_min_height(0.0)
2750            .data_row_max_height(f64::INFINITY);
2751            let root = app_of(tester, table);
2752            tester.pump_widget(root);
2753
2754            let single_line_row_height = tester.get_size(first_container_for("Data")).height();
2755            let multiline_row_height = tester
2756                .get_size(first_container_for(multiline_text))
2757                .height();
2758
2759            assert!(multiline_row_height > single_line_row_height);
2760        });
2761    }
2762
2763    #[test]
2764    #[expect(deprecated)]
2765    fn data_table_custom_row_height_separate_test_for_deprecated_data_row_height() {
2766        test_widgets(|tester| {
2767            let mut table = row_height_table(None, None, 56.0);
2768            table = table.data_row_height(30.0);
2769            let root = app_of(tester, table);
2770            tester.pump_widget(root);
2771            assert_eq!(
2772                tester
2773                    .get_size(first_container_for("Frozen yogurt"))
2774                    .height(),
2775                30.0
2776            );
2777        });
2778    }
2779
2780    #[test]
2781    fn data_table_custom_sort_icon_builder_test() {
2782        test_widgets(|tester| {
2783            let build_table = |sort_icon_builder: Option<DataTableSortIconBuilder>,
2784                               theme_data: Option<DataTableThemeData>,
2785                               sort_column_index: usize,
2786                               sort_ascending: bool|
2787             -> DataTable {
2788                let mut table = DataTable::new(
2789                    vec![
2790                        DataColumn::new(Text::new("Name")).on_sort(|_app, _index, _ascending| {}),
2791                        DataColumn::new(Text::new("Calories"))
2792                            .on_sort(|_app, _index, _ascending| {}),
2793                    ],
2794                    K_DESSERTS
2795                        .iter()
2796                        .map(|dessert| {
2797                            DataRow::new(vec![
2798                                DataCell::new(Text::new(dessert.name)),
2799                                DataCell::new(Text::new(dessert.calories.to_string())),
2800                            ])
2801                        })
2802                        .collect(),
2803                )
2804                .sort_column_index(sort_column_index)
2805                .sort_ascending(sort_ascending);
2806                table.sort_icon_builder = sort_icon_builder;
2807                let _ = theme_data;
2808                table
2809            };
2810            let pump = |tester: &mut WidgetTester,
2811                        sort_icon_builder: Option<DataTableSortIconBuilder>,
2812                        theme_data: Option<DataTableThemeData>,
2813                        sort_column_index: usize,
2814                        sort_ascending: bool| {
2815                let table = build_table(sort_icon_builder, None, sort_column_index, sort_ascending);
2816                let home: WidgetRef = match theme_data {
2817                    Some(data) => DataTableTheme::new(data, table).into_widget(),
2818                    None => table.into_widget(),
2819                };
2820                let root = app_of(tester, home);
2821                tester.pump_widget(root);
2822            };
2823            let builder = |f: fn(bool, bool) -> &'static str| -> DataTableSortIconBuilder {
2824                Rc::new(move |_app, _context, visible, ascending| {
2825                    Text::new(f(visible, ascending)).into_widget()
2826                })
2827            };
2828
2829            // Default (null sortIconBuilder): uses standard Icon(Icons.arrow_upward).
2830            pump(tester, None, None, 0, true);
2831            expect(
2832                tester,
2833                &find::descendant(
2834                    find::by_type::<DataTable>(),
2835                    find::by_icon(&Icons::arrow_upward()),
2836                ),
2837                finds_n_widgets(2),
2838            );
2839
2840            // Custom sortIconBuilder on DataTable.
2841            let labels = builder(|visible, ascending| {
2842                if visible {
2843                    if ascending { "ASC" } else { "DESC" }
2844                } else {
2845                    "INACTIVE"
2846                }
2847            });
2848            pump(tester, Some(labels.clone()), None, 0, true);
2849            expect(tester, &find::text("ASC"), finds_one_widget());
2850            expect(tester, &find::text("INACTIVE"), finds_one_widget());
2851
2852            // Verify sortAscending = false passes ascending = false.
2853            pump(tester, Some(labels), None, 0, false);
2854            expect(tester, &find::text("DESC"), finds_one_widget());
2855            expect(tester, &find::text("INACTIVE"), finds_one_widget());
2856
2857            // Verify sorted column index change passes updated visible flags.
2858            pump(
2859                tester,
2860                Some(builder(|visible, _ascending| {
2861                    if visible {
2862                        "SORTED_COL1"
2863                    } else {
2864                        "UNSORTED_COL0"
2865                    }
2866                })),
2867                None,
2868                1,
2869                true,
2870            );
2871            expect(tester, &find::text("SORTED_COL1"), finds_one_widget());
2872            expect(tester, &find::text("UNSORTED_COL0"), finds_one_widget());
2873
2874            // Verify DataTableThemeData.sortIconBuilder theme resolution.
2875            let theme_builder = builder(|_visible, _ascending| "THEME_BUILDER");
2876            let mut theme = DataTableThemeData::new();
2877            theme.sort_icon_builder = Some(theme_builder.clone());
2878            pump(tester, None, Some(theme.clone()), 0, true);
2879            expect(tester, &find::text("THEME_BUILDER"), finds_n_widgets(2));
2880
2881            // Verify DataTable.sortIconBuilder overrides DataTableThemeData.sortIconBuilder.
2882            pump(
2883                tester,
2884                Some(builder(|_visible, _ascending| "WIDGET_BUILDER")),
2885                Some(theme),
2886                0,
2887                true,
2888            );
2889            expect(tester, &find::text("WIDGET_BUILDER"), finds_n_widgets(2));
2890            expect(tester, &find::text("THEME_BUILDER"), finds_nothing());
2891        });
2892    }
2893
2894    fn padding_table(
2895        horizontal_margin: Option<f64>,
2896        column_spacing: Option<f64>,
2897        checkbox_horizontal_margin: Option<f64>,
2898        selectable: bool,
2899    ) -> DataTable {
2900        let rows = K_DESSERTS
2901            .iter()
2902            .map(|dessert| {
2903                let mut row = DataRow::new(vec![
2904                    DataCell::new(Text::new(dessert.name)),
2905                    DataCell::new(Text::new(dessert.calories.to_string()))
2906                        .show_edit_icon(true)
2907                        .on_tap(Listener::new(|_| {})),
2908                    DataCell::new(Text::new(format!("{:?}", dessert.fat)))
2909                        .show_edit_icon(true)
2910                        .on_tap(Listener::new(|_| {})),
2911                ])
2912                .key(ValueKey::new(dessert.name.to_owned()));
2913                if selectable {
2914                    row = row.on_select_changed(|_app, _selected| {});
2915                }
2916                row
2917            })
2918            .collect();
2919        let mut table = DataTable::new(
2920            vec![
2921                name_column(),
2922                calories_column()
2923                    .numeric(true)
2924                    .on_sort(|_app, _index, _ascending| {}),
2925                DataColumn::new(Text::new("Fat"))
2926                    .tooltip("Fat")
2927                    .numeric(true)
2928                    .on_sort(|_app, _index, _ascending| {}),
2929            ],
2930            rows,
2931        );
2932        if selectable {
2933            table = table.on_select_all(|_app, _value| {});
2934        }
2935        table.horizontal_margin = horizontal_margin;
2936        table.column_spacing = column_spacing;
2937        table.checkbox_horizontal_margin = checkbox_horizontal_margin;
2938        table
2939    }
2940
2941    /// The distances Dart's padding tests read: the content's left from the padding's left, and
2942    /// the padding's right from the content's right.
2943    fn padding_around(tester: &WidgetTester, text: &str, first_padding: bool) -> (f64, f64) {
2944        let mut padding = find::widget_with_text::<Padding>(text);
2945        if first_padding {
2946            padding = padding.first();
2947        }
2948        let cell_content = find::widget_with_text::<Align>(text);
2949        (
2950            tester.get_rect(cell_content.clone()).left - tester.get_rect(padding.clone()).left,
2951            tester.get_rect(padding).right - tester.get_rect(cell_content).right,
2952        )
2953    }
2954
2955    #[test]
2956    fn data_table_custom_horizontal_padding_checkbox() {
2957        test_widgets(|tester| {
2958            let default_horizontal_margin = 24.0;
2959            let default_column_spacing = 56.0;
2960            let custom_horizontal_margin = 10.0;
2961            let custom_column_spacing = 15.0;
2962
2963            // DEFAULT VALUES
2964            let root = app_of(tester, padding_table(None, None, None, true));
2965            tester.pump_widget(root);
2966
2967            // default checkbox padding
2968            let checkbox = find::by_type::<Checkbox>().first();
2969            let padding = find::ancestor(checkbox.clone(), find::by_type::<Padding>());
2970            assert_eq!(
2971                tester.get_rect(checkbox.clone()).left - tester.get_rect(padding.clone()).left,
2972                default_horizontal_margin
2973            );
2974            assert_eq!(
2975                tester.get_rect(padding).right - tester.get_rect(checkbox).right,
2976                default_horizontal_margin / 2.0
2977            );
2978
2979            // default first column padding
2980            assert_eq!(
2981                padding_around(tester, "Frozen yogurt", false),
2982                (
2983                    default_horizontal_margin / 2.0,
2984                    default_column_spacing / 2.0
2985                )
2986            );
2987            // default middle column padding
2988            assert_eq!(
2989                padding_around(tester, "159", false),
2990                (default_column_spacing / 2.0, default_column_spacing / 2.0)
2991            );
2992            // default last column padding
2993            assert_eq!(
2994                padding_around(tester, "6.0", false),
2995                (default_column_spacing / 2.0, default_horizontal_margin)
2996            );
2997
2998            // CUSTOM VALUES
2999            let root = app_of(
3000                tester,
3001                padding_table(
3002                    Some(custom_horizontal_margin),
3003                    Some(custom_column_spacing),
3004                    None,
3005                    true,
3006                ),
3007            );
3008            tester.pump_widget(root);
3009
3010            // custom checkbox padding
3011            let checkbox = find::by_type::<Checkbox>().first();
3012            let padding = find::ancestor(checkbox.clone(), find::by_type::<Padding>());
3013            assert_eq!(
3014                tester.get_rect(checkbox.clone()).left - tester.get_rect(padding.clone()).left,
3015                custom_horizontal_margin
3016            );
3017            assert_eq!(
3018                tester.get_rect(padding).right - tester.get_rect(checkbox).right,
3019                custom_horizontal_margin / 2.0
3020            );
3021
3022            // custom first column padding
3023            assert_eq!(
3024                padding_around(tester, "Frozen yogurt", true),
3025                (custom_horizontal_margin / 2.0, custom_column_spacing / 2.0)
3026            );
3027            // custom middle column padding
3028            assert_eq!(
3029                padding_around(tester, "159", false),
3030                (custom_column_spacing / 2.0, custom_column_spacing / 2.0)
3031            );
3032            // custom last column padding
3033            assert_eq!(
3034                padding_around(tester, "6.0", false),
3035                (custom_column_spacing / 2.0, custom_horizontal_margin)
3036            );
3037        });
3038    }
3039
3040    #[test]
3041    fn data_table_custom_horizontal_padding_no_checkbox() {
3042        test_widgets(|tester| {
3043            let default_horizontal_margin = 24.0;
3044            let default_column_spacing = 56.0;
3045            let custom_horizontal_margin = 10.0;
3046            let custom_column_spacing = 15.0;
3047
3048            // DEFAULT VALUES
3049            let root = app_of(tester, padding_table(None, None, None, false));
3050            tester.pump_widget(root);
3051
3052            assert_eq!(
3053                padding_around(tester, "Frozen yogurt", false),
3054                (default_horizontal_margin, default_column_spacing / 2.0)
3055            );
3056            assert_eq!(
3057                padding_around(tester, "159", false),
3058                (default_column_spacing / 2.0, default_column_spacing / 2.0)
3059            );
3060            assert_eq!(
3061                padding_around(tester, "6.0", false),
3062                (default_column_spacing / 2.0, default_horizontal_margin)
3063            );
3064
3065            // CUSTOM VALUES
3066            let root = app_of(
3067                tester,
3068                padding_table(
3069                    Some(custom_horizontal_margin),
3070                    Some(custom_column_spacing),
3071                    None,
3072                    false,
3073                ),
3074            );
3075            tester.pump_widget(root);
3076
3077            assert_eq!(
3078                padding_around(tester, "Frozen yogurt", false),
3079                (custom_horizontal_margin, custom_column_spacing / 2.0)
3080            );
3081            assert_eq!(
3082                padding_around(tester, "159", false),
3083                (custom_column_spacing / 2.0, custom_column_spacing / 2.0)
3084            );
3085            assert_eq!(
3086                padding_around(tester, "6.0", false),
3087                (custom_column_spacing / 2.0, custom_horizontal_margin)
3088            );
3089        });
3090    }
3091
3092    #[test]
3093    fn checkbox_horizontal_margin_properly_applied() {
3094        test_widgets(|tester| {
3095            let custom_checkbox_horizontal_margin = 15.0;
3096            let custom_horizontal_margin = 10.0;
3097            let root = app_of(
3098                tester,
3099                padding_table(
3100                    Some(custom_horizontal_margin),
3101                    None,
3102                    Some(custom_checkbox_horizontal_margin),
3103                    true,
3104                ),
3105            );
3106            tester.pump_widget(root);
3107
3108            // Custom checkbox padding.
3109            let checkbox = find::by_type::<Checkbox>().first();
3110            let padding = find::ancestor(checkbox.clone(), find::by_type::<Padding>());
3111            assert_eq!(
3112                tester.get_rect(checkbox.clone()).left - tester.get_rect(padding.clone()).left,
3113                custom_checkbox_horizontal_margin
3114            );
3115            assert_eq!(
3116                tester.get_rect(padding).right - tester.get_rect(checkbox).right,
3117                custom_checkbox_horizontal_margin
3118            );
3119
3120            // First column padding.
3121            assert_eq!(
3122                padding_around(tester, "Frozen yogurt", true).0,
3123                custom_horizontal_margin
3124            );
3125        });
3126    }
3127
3128    fn two_row_table() -> (Vec<DataColumn>, Vec<DataRow>) {
3129        let cells = || {
3130            vec![
3131                DataCell::new(Text::new("cell1")),
3132                DataCell::new(Text::new("cell2")),
3133            ]
3134        };
3135        (
3136            vec![
3137                DataColumn::new(Text::new("column1")),
3138                DataColumn::new(Text::new("column2")),
3139            ],
3140            vec![DataRow::new(cells()), DataRow::new(cells())],
3141        )
3142    }
3143
3144    fn last_row_decoration(tester: &WidgetTester) -> BoxDecoration {
3145        tester.widget(find::by_type::<Table>(), |table: &Table| {
3146            table
3147                .children
3148                .last()
3149                .expect("rows")
3150                .decoration
3151                .as_ref()
3152                .and_then(|decoration| decoration.as_any().downcast_ref::<BoxDecoration>())
3153                .expect("a BoxDecoration")
3154                .clone()
3155        })
3156    }
3157
3158    #[test]
3159    fn data_table_set_border_width_test() {
3160        test_widgets(|tester| {
3161            // no thickness provided - border should be default: i.e "1.0" as it set in DataTable
3162            // constructor
3163            let (columns, rows) = two_row_table();
3164            let root = app_of(tester, DataTable::new(columns, rows));
3165            tester.pump_widget(root);
3166            assert_eq!(
3167                last_row_decoration(tester)
3168                    .border
3169                    .expect("a border")
3170                    .top()
3171                    .width,
3172                1.0
3173            );
3174
3175            let thickness = 4.2;
3176            let (columns, rows) = two_row_table();
3177            let root = app_of(
3178                tester,
3179                DataTable::new(columns, rows).divider_thickness(thickness),
3180            );
3181            tester.pump_widget(root);
3182            assert_eq!(
3183                last_row_decoration(tester)
3184                    .border
3185                    .expect("a border")
3186                    .top()
3187                    .width,
3188                thickness
3189            );
3190        });
3191    }
3192
3193    #[test]
3194    fn data_table_set_show_bottom_border() {
3195        test_widgets(|tester| {
3196            let (columns, rows) = two_row_table();
3197            let root = app_of(
3198                tester,
3199                DataTable::new(columns, rows).show_bottom_border(true),
3200            );
3201            tester.pump_widget(root);
3202            assert_eq!(
3203                last_row_decoration(tester)
3204                    .border
3205                    .expect("a border")
3206                    .bottom()
3207                    .width,
3208                1.0
3209            );
3210
3211            let (columns, rows) = two_row_table();
3212            let root = app_of(tester, DataTable::new(columns, rows));
3213            tester.pump_widget(root);
3214            assert_eq!(
3215                last_row_decoration(tester)
3216                    .border
3217                    .expect("a border")
3218                    .bottom()
3219                    .width,
3220                0.0
3221            );
3222        });
3223    }
3224
3225    #[test]
3226    fn data_table_column_heading_cell_with_and_without_sorting() {
3227        test_widgets(|tester| {
3228            let build_table = |sort_column_index: Option<usize>, sort_enabled: bool| {
3229                let mut column =
3230                    DataColumn::new(Expanded::new(Center::new().child(Text::new("Name"))))
3231                        .tooltip("Name");
3232                if sort_enabled {
3233                    column = column.on_sort(|_app, _index, _ascending| {});
3234                }
3235                let mut table = DataTable::new(
3236                    vec![column],
3237                    vec![DataRow::new(vec![DataCell::new(Text::new(
3238                        "A long desert name",
3239                    ))])],
3240                );
3241                table.sort_column_index = sort_column_index;
3242                table
3243            };
3244            let name_cell =
3245                || find::ancestor(find::text("Name"), find::by_type::<Container>()).first();
3246
3247            // Start with without sorting
3248            let root = app_of(tester, build_table(None, false));
3249            tester.pump_widget(root);
3250            expect(tester, &find::text("Name"), finds_one_widget());
3251            // Within f32: global positions go through valo's f32 matrices (waft-gestures'
3252            // Matrix4 entry), where Dart's are f64 and compare equal.
3253            let (text_center, cell_center) = (
3254                tester.get_center(find::text("Name")),
3255                tester.get_center(name_cell()),
3256            );
3257            assert_f32_equals(text_center.dx(), cell_center.dx());
3258            assert_f32_equals(text_center.dy(), cell_center.dy());
3259            expect(
3260                tester,
3261                &find::descendant(name_cell(), find::by_type::<Icon>()),
3262                finds_nothing(),
3263            );
3264
3265            // Turn on sorting
3266            let root = app_of(tester, build_table(None, true));
3267            tester.pump_widget(root);
3268            expect(tester, &find::text("Name"), finds_one_widget());
3269            expect(
3270                tester,
3271                &find::descendant(name_cell(), find::by_type::<Icon>()),
3272                finds_one_widget(),
3273            );
3274
3275            // Turn off sorting again
3276            let root = app_of(tester, build_table(None, false));
3277            tester.pump_widget(root);
3278            expect(tester, &find::text("Name"), finds_one_widget());
3279            // Within f32: global positions go through valo's f32 matrices (waft-gestures'
3280            // Matrix4 entry), where Dart's are f64 and compare equal.
3281            let (text_center, cell_center) = (
3282                tester.get_center(find::text("Name")),
3283                tester.get_center(name_cell()),
3284            );
3285            assert_f32_equals(text_center.dx(), cell_center.dx());
3286            assert_f32_equals(text_center.dy(), cell_center.dy());
3287            expect(
3288                tester,
3289                &find::descendant(name_cell(), find::by_type::<Icon>()),
3290                finds_nothing(),
3291            );
3292        });
3293    }
3294
3295    #[test]
3296    #[allow(deprecated)] // Dart's `withOpacity`.
3297    fn data_row_renders_default_selected_row_colors() {
3298        test_widgets(|tester| {
3299            let theme_data = m3(&tester.cell.borrow());
3300            let build_table = |selected: bool| {
3301                material_app(
3302                    theme_data.clone(),
3303                    Material::new()
3304                        .child(DataTable::new(
3305                            vec![DataColumn::new(Text::new("Column1"))],
3306                            vec![
3307                                DataRow::new(vec![DataCell::new(Text::new("Content1"))])
3308                                    .on_select_changed(|_app, _checked| {})
3309                                    .selected(selected),
3310                            ],
3311                        ))
3312                        .into_widget(),
3313                )
3314            };
3315
3316            tester.pump_widget(build_table(false));
3317            assert_eq!(last_row_decoration(tester).color, None);
3318
3319            tester.pump_widget(build_table(true));
3320            assert_eq!(
3321                last_row_decoration(tester).color.map(|color| color.color()),
3322                Some(theme_data.color_scheme.primary().with_opacity(0.08))
3323            );
3324        });
3325    }
3326
3327    fn state_color_table(
3328        selected: bool,
3329        disabled: bool,
3330        selected_color: Color,
3331        disabled_color: Color,
3332        default_color: Color,
3333    ) -> WidgetRef {
3334        let color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
3335            if states.contains(&WidgetState::Selected) {
3336                return Some(selected_color);
3337            }
3338            if states.contains(&WidgetState::Disabled) {
3339                return Some(disabled_color);
3340            }
3341            Some(default_color)
3342        });
3343        let mut rows = Vec::new();
3344        if disabled || !selected {
3345            rows.push(
3346                DataRow::new(vec![DataCell::new(Text::new("Content1"))])
3347                    .on_select_changed(|_app, _value| {}),
3348            );
3349        }
3350        let mut row = DataRow::new(vec![DataCell::new(Text::new("Content2"))])
3351            .selected(selected)
3352            .color(color);
3353        if !disabled {
3354            row = row.on_select_changed(|_app, _value| {});
3355        }
3356        rows.push(row);
3357        Material::new()
3358            .child(DataTable::new(
3359                vec![DataColumn::new(Text::new("Column1"))],
3360                rows,
3361            ))
3362            .into_widget()
3363    }
3364
3365    #[test]
3366    fn data_row_renders_custom_colors_when_selected() {
3367        test_widgets(|tester| {
3368            let theme = m3(&tester.cell.borrow());
3369            tester.pump_widget(material_app(
3370                theme.clone(),
3371                state_color_table(
3372                    false,
3373                    false,
3374                    Colors::GREEN.primary(),
3375                    Colors::GREY.primary(),
3376                    Colors::RED.primary(),
3377                ),
3378            ));
3379            assert_eq!(
3380                last_row_decoration(tester).color.map(|color| color.color()),
3381                Some(Colors::RED.primary())
3382            );
3383
3384            tester.pump_widget(material_app(
3385                theme,
3386                state_color_table(
3387                    true,
3388                    false,
3389                    Colors::GREEN.primary(),
3390                    Colors::GREY.primary(),
3391                    Colors::RED.primary(),
3392                ),
3393            ));
3394            assert_eq!(
3395                last_row_decoration(tester).color.map(|color| color.color()),
3396                Some(Colors::GREEN.primary())
3397            );
3398        });
3399    }
3400
3401    #[test]
3402    fn data_row_renders_custom_colors_when_disabled() {
3403        test_widgets(|tester| {
3404            let theme = m3(&tester.cell.borrow());
3405            tester.pump_widget(material_app(
3406                theme.clone(),
3407                state_color_table(
3408                    false,
3409                    false,
3410                    Colors::GREEN.primary(),
3411                    Colors::GREY.primary(),
3412                    Colors::RED.primary(),
3413                ),
3414            ));
3415            assert_eq!(
3416                last_row_decoration(tester).color.map(|color| color.color()),
3417                Some(Colors::RED.primary())
3418            );
3419
3420            tester.pump_widget(material_app(
3421                theme,
3422                state_color_table(
3423                    false,
3424                    true,
3425                    Colors::GREEN.primary(),
3426                    Colors::GREY.primary(),
3427                    Colors::RED.primary(),
3428                ),
3429            ));
3430            assert_eq!(
3431                last_row_decoration(tester).color.map(|color| color.color()),
3432                Some(Colors::GREY.primary())
3433            );
3434        });
3435    }
3436
3437    #[test]
3438    fn material2_data_row_renders_custom_colors_when_pressed() {
3439        test_widgets(|tester| {
3440            let pressed_color = Color::new(0xff4caf50);
3441            let color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
3442                if states.contains(&WidgetState::Pressed) {
3443                    return Some(pressed_color);
3444                }
3445                Some(Colors::TRANSPARENT)
3446            });
3447            let theme = ThemeData::builder()
3448                .use_material3(false)
3449                .build(&tester.cell.borrow());
3450            tester.pump_widget(material_app(
3451                theme,
3452                Material::new()
3453                    .child(DataTable::new(
3454                        vec![DataColumn::new(Text::new("Column1"))],
3455                        vec![
3456                            DataRow::new(vec![DataCell::new(Text::new("Content1"))])
3457                                .color(color)
3458                                .on_select_changed(|_app, _value| {}),
3459                        ],
3460                    ))
3461                    .into_widget(),
3462            ));
3463
3464            let mut gesture = TestPointer::touch(1);
3465            let center = tester.get_center(find::text("Content1"));
3466            tester.down(&mut gesture, center);
3467            tester.pump_by(Duration::from_millis(200)); // splash is well underway
3468            // valo records no circle of radius 0, which the splash has until its first frame
3469            // after this one; Flutter's `paints` sees the zero circle.
3470            tester.pump_by(Duration::from_millis(16));
3471            let ink_well = tester.element(find::by_type::<InkWell>());
3472            let ops = tester.nearest_material_ops(ink_well);
3473            assert!(
3474                paints(
3475                    &ops,
3476                    &[PaintCall::Circle {
3477                        x: Some(68.0),
3478                        y: Some(24.0),
3479                        radius: None,
3480                        color: Some(pressed_color),
3481                        style: None,
3482                    }],
3483                )
3484                .is_ok()
3485            );
3486            tester.up(&gesture);
3487        });
3488    }
3489
3490    #[test]
3491    fn table_row_ink_well_can_handle_secondary_taps() {
3492        test_widgets(|tester| {
3493            let secondary_tapped = Rc::new(std::cell::Cell::new(false));
3494            let secondary_tapped_down = Rc::new(std::cell::Cell::new(false));
3495            let theme = m3(&tester.cell.borrow());
3496            tester.pump_widget(material_app(
3497                theme,
3498                Material::new()
3499                    .child(
3500                        Table::new()
3501                            .children(vec![TableRow::new().children(vec![
3502                            TableRowInkWell::new()
3503                                .on_secondary_tap({
3504                                    let secondary_tapped = Rc::clone(&secondary_tapped);
3505                                    Listener::new(move |_app| secondary_tapped.set(true))
3506                                })
3507                                .on_secondary_tap_down({
3508                                    let secondary_tapped_down = Rc::clone(&secondary_tapped_down);
3509                                    Rc::new(move |_app: &mut App, _details: TapDownDetails| {
3510                                        secondary_tapped_down.set(true)
3511                                    })
3512                                })
3513                                .child(SizedBox::new().width(100.0).height(100.0))
3514                                .into_widget(),
3515                    ])])
3516                            .into_widget(),
3517                    )
3518                    .into_widget(),
3519            ));
3520            assert!(!secondary_tapped.get());
3521            assert!(!secondary_tapped_down.get());
3522            expect(
3523                tester,
3524                &find::by_type::<TableRowInkWell>(),
3525                finds_one_widget(),
3526            );
3527
3528            let center = tester.get_center(find::by_type::<TableRowInkWell>());
3529            let mut mouse = TestPointer::mouse(1, waft_gestures::K_SECONDARY_MOUSE_BUTTON);
3530            tester.down(&mut mouse, center);
3531            tester.up(&mouse);
3532            tester.pump_and_settle();
3533
3534            assert!(secondary_tapped.get());
3535            assert!(secondary_tapped_down.get());
3536        });
3537    }
3538
3539    #[test]
3540    fn data_table_correctly_renders_with_a_mouse() {
3541        test_widgets(|tester| {
3542            let build_table = |sort_column_index: Option<usize>| {
3543                let mut table = DataTable::new(
3544                    vec![
3545                        DataColumn::new(Expanded::new(Center::new().child(Text::new("column1"))))
3546                            .tooltip("Column1"),
3547                        DataColumn::new(Expanded::new(Center::new().child(Text::new("column2"))))
3548                            .tooltip("Column2")
3549                            .on_sort(|_app, _index, _ascending| {}),
3550                    ],
3551                    vec![DataRow::new(vec![
3552                        DataCell::new(Text::new("Content1")),
3553                        DataCell::new(Text::new("Content2")),
3554                    ])],
3555                );
3556                table.sort_column_index = sort_column_index;
3557                table
3558            };
3559            let root = app_of(tester, build_table(None));
3560            tester.pump_widget(root);
3561
3562            let attached = |tester: &WidgetTester, text: &str| {
3563                let render = tester.render_object(find::text(text));
3564                render.attached(&tester.cell.borrow())
3565            };
3566            assert!(attached(tester, "column1"));
3567            assert!(attached(tester, "column2"));
3568
3569            let mut gesture = TestPointer::mouse(1, 0);
3570            tester.add_pointer(&mut gesture, Offset::ZERO);
3571
3572            tester.pump_and_settle();
3573            assert!(attached(tester, "column1"));
3574            assert!(attached(tester, "column2"));
3575
3576            // Wait for the tooltip timer to expire to prevent it scheduling a new frame after
3577            // the view is destroyed, which causes exceptions.
3578            tester.pump_and_settle_by(Duration::from_secs(1));
3579        });
3580    }
3581
3582    #[test]
3583    fn data_row_is_disabled_when_on_select_changed_is_not_set() {
3584        test_widgets(|tester| {
3585            let table = DataTable::new(
3586                vec![
3587                    DataColumn::new(Text::new("Col1")),
3588                    DataColumn::new(Text::new("Col2")),
3589                ],
3590                vec![
3591                    DataRow::new(vec![
3592                        DataCell::new(Text::new("Hello")),
3593                        DataCell::new(Text::new("world")),
3594                    ])
3595                    .on_select_changed(|_app, _value| {}),
3596                    DataRow::new(vec![
3597                        DataCell::new(Text::new("Bug")),
3598                        DataCell::new(Text::new("report")),
3599                    ]),
3600                    DataRow::new(vec![
3601                        DataCell::new(Text::new("GitHub")),
3602                        DataCell::new(Text::new("issue")),
3603                    ]),
3604                ],
3605            );
3606            let root = app_of(tester, table);
3607            tester.pump_widget(root);
3608            expect(
3609                tester,
3610                &find::widget_with_text::<TableRowInkWell>("Hello"),
3611                finds_one_widget(),
3612            );
3613            expect(
3614                tester,
3615                &find::widget_with_text::<TableRowInkWell>("Bug"),
3616                finds_nothing(),
3617            );
3618            expect(
3619                tester,
3620                &find::widget_with_text::<TableRowInkWell>("GitHub"),
3621                finds_nothing(),
3622            );
3623        });
3624    }
3625
3626    #[test]
3627    fn data_table_set_interior_border_test() {
3628        test_widgets(|tester| {
3629            let (columns, rows) = two_row_table();
3630            let root = app_of(
3631                tester,
3632                DataTable::new(columns, rows).border(TableBorder::all(
3633                    Colors::RED.primary(),
3634                    2.0,
3635                    BorderStyle::Solid,
3636                    BorderRadius::ZERO,
3637                )),
3638            );
3639            tester.pump_widget(root);
3640            assert_eq!(
3641                tester.get_size(find::by_type::<DataTable>()),
3642                Size::new(800.0, 600.0)
3643            );
3644
3645            let (columns, rows) = two_row_table();
3646            let root = app_of(
3647                tester,
3648                DataTable::new(columns, rows).border(TableBorder::all(
3649                    Colors::RED.primary(),
3650                    1.0,
3651                    BorderStyle::Solid,
3652                    BorderRadius::ZERO,
3653                )),
3654            );
3655            tester.pump_widget(root);
3656            let border = tester.widget(find::by_type::<Table>(), |table: &Table| table.border);
3657            let border = border.expect("a border");
3658            assert_eq!(border.top.color, Colors::RED.primary());
3659            assert_eq!(border.bottom.width, 1.0);
3660
3661            let (columns, rows) = two_row_table();
3662            let root = app_of(tester, DataTable::new(columns, rows));
3663            tester.pump_widget(root);
3664            let border = tester.widget(find::by_type::<Table>(), |table: &Table| table.border);
3665            assert!(border.is_none());
3666        });
3667    }
3668
3669    #[test]
3670    fn do_not_crashes_when_paint_borders_in_a_narrow_space() {
3671        test_widgets(|tester| {
3672            let (columns, rows) = two_row_table();
3673            let root = app_of(
3674                tester,
3675                Center::new().child(SizedBox::new().width(117.0).child(
3676                    DataTable::new(columns, rows).border(TableBorder::all(
3677                        Colors::RED.primary(),
3678                        2.0,
3679                        BorderStyle::Solid,
3680                        BorderRadius::ZERO,
3681                    )),
3682                )),
3683            );
3684            tester.pump_widget(root);
3685            // Go without crashes.
3686        });
3687    }
3688
3689    #[test]
3690    fn data_table_clip_behavior() {
3691        test_widgets(|tester| {
3692            let border_radius = BorderRadius::circular(30.0);
3693            let theme = m3(&tester.cell.borrow());
3694            let build_table = |clip_behavior: Clip| {
3695                let border =
3696                    TableBorder::all(Colors::BLACK, 1.0, BorderStyle::Solid, border_radius);
3697                material_app(
3698                    theme.clone(),
3699                    Material::new()
3700                        .child(
3701                            DataTable::new(
3702                                vec![DataColumn::new(Text::new("Column1"))],
3703                                vec![DataRow::new(vec![DataCell::new(Text::new("Content1"))])],
3704                            )
3705                            .clip_behavior(clip_behavior)
3706                            .border(border),
3707                        )
3708                        .into_widget(),
3709                )
3710            };
3711
3712            tester.pump_widget(build_table(Clip::None));
3713            let (clip_behavior, radius) = tester
3714                .widget(find::by_type::<Material>().last(), |material: &Material| {
3715                    (material.clip_behavior, material.border_radius)
3716                });
3717            assert_eq!(clip_behavior, Clip::None);
3718            assert_eq!(radius, Some(border_radius.into()));
3719
3720            tester.pump_widget(build_table(Clip::HardEdge));
3721            let (clip_behavior, radius) = tester
3722                .widget(find::by_type::<Material>().last(), |material: &Material| {
3723                    (material.clip_behavior, material.border_radius)
3724                });
3725            assert_eq!(clip_behavior, Clip::HardEdge);
3726            assert_eq!(radius, Some(border_radius.into()));
3727        });
3728    }
3729
3730    fn mouse_cursor_table(columns: Vec<DataColumn>, rows: Vec<DataRow>) -> DataTable {
3731        DataTable::new(columns, rows).sort_column_index(0)
3732    }
3733
3734    fn cursor_by_state(
3735        selected_or_disabled: WidgetState,
3736        when: MouseCursorRef,
3737        otherwise: MouseCursorRef,
3738    ) -> WidgetStatePropertyRef<Option<MouseCursorRef>> {
3739        <dyn WidgetStateProperty<Option<MouseCursorRef>>>::resolve_with(move |states| {
3740            if states.contains(&selected_or_disabled) {
3741                return Some(when.clone());
3742            }
3743            Some(otherwise.clone())
3744        })
3745    }
3746
3747    fn assert_active_cursor(tester: &WidgetTester, expected: MouseCursorRef) {
3748        assert!(
3749            *tester.active_cursor(1) == *expected,
3750            "the active cursor is {:?}, not {expected:?}",
3751            tester.active_cursor(1)
3752        );
3753    }
3754
3755    #[test]
3756    fn heading_cell_cursor_resolves_widget_state_mouse_cursor_correctly() {
3757        test_widgets(|tester| {
3758            let cursor = || {
3759                cursor_by_state(
3760                    WidgetState::Disabled,
3761                    SystemMouseCursors::FORBIDDEN.into(),
3762                    SystemMouseCursors::COPY.into(),
3763                )
3764            };
3765            let table = mouse_cursor_table(
3766                vec![
3767                    // This column can be sorted.
3768                    DataColumn::new(Text::new("A"))
3769                        .mouse_cursor(cursor())
3770                        .on_sort(|_app, _index, _ascending| {}),
3771                    // This column cannot be sorted.
3772                    DataColumn::new(Text::new("B")).mouse_cursor(cursor()),
3773                ],
3774                vec![
3775                    DataRow::new(vec![
3776                        DataCell::new(Text::new("Data 1")),
3777                        DataCell::new(Text::new("Data 2")),
3778                    ]),
3779                    DataRow::new(vec![
3780                        DataCell::new(Text::new("Data 3")),
3781                        DataCell::new(Text::new("Data 4")),
3782                    ]),
3783                ],
3784            );
3785            let root = material_app(
3786                m3(&tester.cell.borrow()),
3787                Scaffold::new().body(table).into_widget(),
3788            );
3789            tester.pump_widget(root);
3790
3791            let mut gesture = TestPointer::mouse(1, 0);
3792            let at = tester.get_center(find::text("A"));
3793            tester.add_pointer(&mut gesture, at);
3794            tester.pump();
3795            assert_active_cursor(tester, SystemMouseCursors::COPY.into());
3796
3797            let at = tester.get_center(find::text("B"));
3798            tester.move_to(&mut gesture, at, false);
3799            tester.pump();
3800            assert_active_cursor(tester, SystemMouseCursors::FORBIDDEN.into());
3801        });
3802    }
3803
3804    #[test]
3805    fn data_row_cursor_resolves_widget_state_mouse_cursor_correctly() {
3806        test_widgets(|tester| {
3807            let cursor = || {
3808                cursor_by_state(
3809                    WidgetState::Selected,
3810                    SystemMouseCursors::COPY.into(),
3811                    SystemMouseCursors::FORBIDDEN.into(),
3812                )
3813            };
3814            let table = mouse_cursor_table(
3815                vec![
3816                    DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
3817                    DataColumn::new(Text::new("B")),
3818                ],
3819                vec![
3820                    // This row can be selected.
3821                    DataRow::new(vec![
3822                        DataCell::new(Text::new("Data 1")),
3823                        DataCell::new(Text::new("Data 2")),
3824                    ])
3825                    .mouse_cursor(cursor())
3826                    .on_select_changed(|_app, _selected| {}),
3827                    // This row is selected.
3828                    DataRow::new(vec![
3829                        DataCell::new(Text::new("Data 3")),
3830                        DataCell::new(Text::new("Data 4")),
3831                    ])
3832                    .selected(true)
3833                    .on_select_changed(|_app, _selected| {})
3834                    .mouse_cursor(cursor()),
3835                ],
3836            );
3837            let root = material_app(
3838                m3(&tester.cell.borrow()),
3839                Scaffold::new().body(table).into_widget(),
3840            );
3841            tester.pump_widget(root);
3842
3843            let mut gesture = TestPointer::mouse(1, 0);
3844            let at = tester.get_center(find::text("Data 1"));
3845            tester.add_pointer(&mut gesture, at);
3846            tester.pump();
3847            assert_active_cursor(tester, SystemMouseCursors::FORBIDDEN.into());
3848
3849            let at = tester.get_center(find::text("Data 3"));
3850            tester.move_to(&mut gesture, at, false);
3851            tester.pump();
3852            assert_active_cursor(tester, SystemMouseCursors::COPY.into());
3853        });
3854    }
3855
3856    #[test]
3857    fn data_row_cursor_doesnt_update_checkbox_cursor() {
3858        test_widgets(|tester| {
3859            let copy: WidgetStatePropertyRef<Option<MouseCursorRef>> = Rc::new(
3860                WidgetStatePropertyAll::new(Some(SystemMouseCursors::COPY.into())),
3861            );
3862            let table = mouse_cursor_table(
3863                vec![
3864                    DataColumn::new(Text::new("A")).on_sort(|_app, _index, _ascending| {}),
3865                    DataColumn::new(Text::new("B")),
3866                ],
3867                vec![
3868                    DataRow::new(vec![
3869                        DataCell::new(Text::new("Data")),
3870                        DataCell::new(Text::new("Data 2")),
3871                    ])
3872                    .on_select_changed(|_app, _selected| {})
3873                    .mouse_cursor(copy),
3874                ],
3875            );
3876            let root = material_app(
3877                m3(&tester.cell.borrow()),
3878                Scaffold::new().body(table).into_widget(),
3879            );
3880            tester.pump_widget(root);
3881
3882            let mut gesture = TestPointer::mouse(1, 0);
3883            let at = tester.get_center(find::by_type::<Checkbox>().last());
3884            tester.add_pointer(&mut gesture, at);
3885            tester.pump();
3886            // Test that the checkbox cursor is not changed.
3887            assert_active_cursor(tester, SystemMouseCursors::BASIC.into());
3888
3889            let at = tester.get_center(find::text("Data"));
3890            tester.move_to(&mut gesture, at, false);
3891            tester.pump();
3892            // Test that cursor is updated for the row.
3893            assert_active_cursor(tester, SystemMouseCursors::COPY.into());
3894        });
3895    }
3896
3897    #[test]
3898    fn data_table_text_styles_are_merged_with_default_text_style() {
3899        test_widgets(|tester| {
3900            let default_text_style: Rc<RefCell<Option<DefaultTextStyle>>> = Rc::default();
3901            let slot = Rc::clone(&default_text_style);
3902            let body = Builder::new(move |app, context| {
3903                *slot.borrow_mut() = Some(DefaultTextStyle::of(app, context));
3904                DataTable::new(
3905                    vec![
3906                        DataColumn::new(Text::new("Header 1")),
3907                        DataColumn::new(Text::new("Header 2")),
3908                    ],
3909                    vec![DataRow::new(vec![
3910                        DataCell::new(Text::new("Data 1")),
3911                        DataCell::new(Text::new("Data 2")),
3912                    ])],
3913                )
3914                .heading_text_style(TextStyle::new())
3915                .data_text_style(TextStyle::new())
3916                .into_widget()
3917            });
3918            let root = material_app(
3919                m3(&tester.cell.borrow()),
3920                Scaffold::new().body(body).into_widget(),
3921            );
3922            tester.pump_widget(root);
3923
3924            let default_style = default_text_style
3925                .borrow()
3926                .clone()
3927                .expect("the builder ran")
3928                .style;
3929            assert_eq!(paragraph_style(tester, "Header 1"), default_style);
3930            assert_eq!(paragraph_style(tester, "Data 1"), default_style);
3931        });
3932    }
3933
3934    #[test]
3935    fn data_column_label_can_be_centered() {
3936        test_widgets(|tester| {
3937            let horizontal_margin = 24.0;
3938            let build_table = |heading_row_alignment: Option<MainAxisAlignment>,
3939                               sort_enabled: bool| {
3940                let mut column = DataColumn::new(Text::new("Header"));
3941                column.heading_row_alignment = heading_row_alignment;
3942                if sort_enabled {
3943                    column = column.on_sort(|_app, _index, _ascending| {});
3944                }
3945                DataTable::new(
3946                    vec![column],
3947                    vec![DataRow::new(vec![DataCell::new(Text::new("Data"))])],
3948                )
3949            };
3950
3951            // Test mainAxisAlignment without sort arrow.
3952            let root = app_of(tester, build_table(None, false));
3953            tester.pump_widget(root);
3954            assert_eq!(
3955                tester.get_top_left(find::text("Header")).dx(),
3956                horizontal_margin
3957            );
3958
3959            // Test mainAxisAlignment.center without sort arrow.
3960            let root = app_of(tester, build_table(Some(MainAxisAlignment::Center), false));
3961            tester.pump_widget(root);
3962            assert_f32_equals(tester.get_center(find::text("Header")).dx(), 400.0);
3963
3964            // Test mainAxisAlignment with sort arrow.
3965            let root = app_of(tester, build_table(None, true));
3966            tester.pump_widget(root);
3967            assert_eq!(
3968                tester.get_top_left(find::text("Header")).dx(),
3969                horizontal_margin
3970            );
3971
3972            // Test mainAxisAlignment.center with sort arrow.
3973            let root = app_of(tester, build_table(Some(MainAxisAlignment::Center), true));
3974            tester.pump_widget(root);
3975            assert_f32_equals(tester.get_center(find::text("Header")).dx(), 400.0);
3976        });
3977    }
3978
3979    fn custom_widths_table(selectable: bool) -> WidgetRef {
3980        let mut row = DataRow::new(vec![
3981            DataCell::new(Text::new("1")),
3982            DataCell::new(Text::new("1")),
3983            DataCell::new(Text::new("D")),
3984        ]);
3985        if selectable {
3986            row = row.on_select_changed(|_app, _value| {});
3987        }
3988        SizedBox::new()
3989            .width(500.0)
3990            .child(DataTable::new(
3991                vec![
3992                    DataColumn::new(Text::new("Flex Numeric"))
3993                        .column_width(Rc::new(FlexColumnWidth::new(1.0)))
3994                        .numeric(true),
3995                    DataColumn::new(Text::new("Numeric")).numeric(true),
3996                    DataColumn::new(Text::new("Text")),
3997                ],
3998                vec![row],
3999            ))
4000            .into_widget()
4001    }
4002
4003    fn column_width_debug(tester: &WidgetTester, column: usize) -> String {
4004        tester.widget(find::by_type::<Table>(), |table: &Table| {
4005            format!(
4006                "{:?}",
4007                table.column_widths.as_ref().expect("column widths")[&column]
4008            )
4009        })
4010    }
4011
4012    #[test]
4013    fn data_table_with_custom_column_widths_checkbox() {
4014        test_widgets(|tester| {
4015            let root = app_of(tester, custom_widths_table(true));
4016            tester.pump_widget(root);
4017            assert!(column_width_debug(tester, 0).starts_with("FixedColumnWidth")); // Checkbox column
4018            assert_eq!(
4019                column_width_debug(tester, 1),
4020                format!("{:?}", FlexColumnWidth::new(1.0))
4021            );
4022            assert_eq!(
4023                column_width_debug(tester, 2),
4024                format!("{:?}", IntrinsicColumnWidth::new(None))
4025            );
4026            assert_eq!(
4027                column_width_debug(tester, 3),
4028                format!("{:?}", IntrinsicColumnWidth::new(Some(1.0)))
4029            );
4030        });
4031    }
4032
4033    #[test]
4034    fn data_table_with_custom_column_widths_no_checkbox() {
4035        test_widgets(|tester| {
4036            let root = app_of(tester, custom_widths_table(false));
4037            tester.pump_widget(root);
4038            assert_eq!(
4039                column_width_debug(tester, 0),
4040                format!("{:?}", FlexColumnWidth::new(1.0))
4041            );
4042            assert_eq!(
4043                column_width_debug(tester, 1),
4044                format!("{:?}", IntrinsicColumnWidth::new(None))
4045            );
4046            assert_eq!(
4047                column_width_debug(tester, 2),
4048                format!("{:?}", IntrinsicColumnWidth::new(Some(1.0)))
4049            );
4050        });
4051    }
4052
4053    #[test]
4054    fn data_table_data_column_data_row_and_data_cell_render_at_zero_area() {
4055        test_widgets(|tester| {
4056            let root = app_of(
4057                tester,
4058                SizedBox::shrink().child(DataTable::new(
4059                    vec![DataColumn::new(Text::new("X"))],
4060                    vec![DataRow::new(vec![DataCell::new(Text::new("X"))])],
4061                )),
4062            );
4063            tester.pump_widget(root);
4064        });
4065    }
4066
4067    #[test]
4068    fn table_row_ink_well_renders_at_zero_area() {
4069        test_widgets(|tester| {
4070            let table = Table::new().children(vec![TableRow::new().children(vec![
4071                TableRowInkWell::new().child(Text::new("X")).into_widget(),
4072            ])]);
4073            let root = app_of(tester, SizedBox::shrink().child(table.into_widget()));
4074            tester.pump_widget(root);
4075        });
4076    }
4077
4078    #[test]
4079    fn data_table_renders_with_border_and_background_decoration() {
4080        test_widgets(|tester| {
4081            let (width, height) = (800.0, 600.0);
4082            let (border_horizontal, border_vertical) = (5.0, 10.0);
4083            let border_color = Color::new(0xff2196f3);
4084            let background_color = Color::new(0xfff5f5f5);
4085            let vertical = BorderSide {
4086                width: border_vertical,
4087                color: border_color,
4088                ..BorderSide::default()
4089            };
4090            let horizontal = BorderSide {
4091                width: border_horizontal,
4092                color: border_color,
4093                ..BorderSide::default()
4094            };
4095            let table = DataTable::new(
4096                vec![DataColumn::new(Text::new("Col1"))],
4097                vec![DataRow::new(vec![DataCell::new(Text::new("1"))])],
4098            )
4099            .decoration(
4100                BoxDecoration::new()
4101                    .color(background_color)
4102                    .border(Border::symmetric(vertical, horizontal)),
4103            );
4104            let root = material_app(m3(&tester.cell.borrow()), table.into_widget());
4105            tester.pump_widget(root);
4106
4107            let container = find::ancestor(find::by_type::<Table>(), find::by_type::<Container>());
4108            let ops = tester.painted_ops(tester.render_object(container));
4109            assert!(
4110                paints(
4111                    &ops,
4112                    &[PaintCall::rect_at(
4113                        Rect::from_ltrb(
4114                            border_vertical / 2.0,
4115                            border_horizontal / 2.0,
4116                            width - border_vertical / 2.0,
4117                            height - border_horizontal / 2.0,
4118                        ),
4119                        Some(background_color),
4120                    )]
4121                )
4122                .is_ok()
4123            );
4124            assert!(paints(&ops, &[PaintCall::path(Some(border_color))]).is_ok());
4125            assert_eq!(
4126                tester.get_top_left(find::by_type::<Table>()),
4127                Offset::new(border_vertical, border_horizontal)
4128            );
4129            assert_eq!(
4130                tester.get_bottom_right(find::by_type::<Table>()),
4131                Offset::new(width - border_vertical, height - border_horizontal)
4132            );
4133        });
4134    }
4135
4136    #[test]
4137    fn data_row_renders_checkbox_with_colors_from_checkbox_theme() {
4138        test_widgets(|tester| {
4139            let fill_color = Color::new(0xFF00FF00);
4140            let check_color = Color::new(0xFF0000FF);
4141            let theme = ThemeData::builder()
4142                .checkbox_theme(
4143                    CheckboxThemeData::new()
4144                        .fill_color(Rc::new(WidgetStatePropertyAll::new(Some(fill_color))))
4145                        .check_color(Rc::new(WidgetStatePropertyAll::new(Some(check_color)))),
4146                )
4147                .build(&tester.cell.borrow());
4148            let table = DataTable::new(
4149                vec![DataColumn::new(Text::new("Column1"))],
4150                vec![
4151                    DataRow::new(vec![DataCell::new(Text::new("Content1"))])
4152                        .selected(true)
4153                        .on_select_changed(|_app, _checked| {}),
4154                ],
4155            );
4156            let root = material_app(theme, Material::new().child(table).into_widget());
4157            tester.pump_widget(root);
4158
4159            let checkbox = tester.element(find::by_type::<Checkbox>().last());
4160            let ops = tester.nearest_material_ops(checkbox);
4161            assert!(
4162                paints(
4163                    &ops,
4164                    &[
4165                        PaintCall::rrect(Some(fill_color)),
4166                        PaintCall::path(Some(check_color)),
4167                    ]
4168                )
4169                .is_ok()
4170            );
4171        });
4172    }
4173}