Skip to main content

waft_material/
paginated_data_table.rs

1//! Flutter counterpart: material_ui's `paginated_data_table.dart`.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::rc::Rc;
6
7use waft_embedder::Color;
8use waft_foundation::{App, Handle, Listenable, Listener, ValueChanged};
9use waft_gestures::DragStartBehavior;
10use waft_painting::Axis;
11use waft_painting::{
12    AlignmentGeometry, BoxDecoration, EdgeInsets, EdgeInsetsDirectional, FontWeight,
13};
14use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisAlignment};
15use waft_widgets::{
16    Align, BuildContext, Column, ConstrainedBox, DefaultTextStyle, Expanded, GlobalKey, IconTheme,
17    IconThemeData, IntoWidget, KeyRef, LayoutBuilder, Padding, PageStorage, Row,
18    ScrollControllerRef, Semantics, SingleChildScrollView, SizedBox, State, StateData,
19    StatefulWidget, Text, WidgetRef, WidgetStatePropertyRef,
20};
21
22use crate::card::Card;
23use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
24use crate::data_table::{DataCell, DataColumn, DataRow, DataTable};
25use crate::data_table_source::DataTableSourceRef;
26use crate::data_table_theme::DataTableSortIconBuilder;
27use crate::debug::debug_check_has_material_localizations;
28use crate::dropdown::{DropdownButton, DropdownButtonHideUnderline, DropdownMenuItem};
29use crate::icon_button::IconButton;
30use crate::icons::Icons;
31use crate::ink_decoration::Ink;
32use crate::material_localizations::MaterialLocalizations;
33use crate::progress_indicator::CircularProgressIndicator;
34use crate::theme::Theme;
35
36/// A table that follows the Material 2 design guidelines, with pagination.
37///
38/// A paginated data table shows [`rows_per_page`](Self::rows_per_page) rows of data per page
39/// and provides controls for showing other pages.
40///
41/// Data is addressed by index (0 is the top row). The [`columns`](Self::columns) define the
42/// columns of the table, and the [`source`](Self::source) provides the rows (see
43/// [`DataTableSource`](crate::DataTableSource)).
44///
45/// The [`PaginatedDataTable`] scrolls horizontally if it is too narrow for its columns.
46///
47/// See also:
48///
49///  * [`DataTable`], which is not paginated.
50///  * <https://material.io/go/design-data-tables#data-tables-tables-within-cards>
51#[derive(Clone)]
52pub struct PaginatedDataTable {
53    pub key: Option<KeyRef>,
54
55    /// The table card's optional header.
56    ///
57    /// This is typically a `Text` widget, but can also be a `Row` of `TextButton`s. To show
58    /// icon buttons at the top end side of the table with a header, set the
59    /// [`actions`](Self::actions) property.
60    ///
61    /// If items in the table are selectable, then, when the selection is not empty, the header
62    /// is replaced by a count of the selected items. The [`actions`](Self::actions) are still
63    /// visible when items are selected.
64    pub header: Option<WidgetRef>,
65
66    /// Icon buttons to show at the top end side of the table. The [`header`](Self::header)
67    /// must not be null to show the actions.
68    ///
69    /// Typically, the exact actions included in this list will vary based on whether any rows
70    /// are selected or not.
71    ///
72    /// These should be size 24.0 with default padding (8.0).
73    pub actions: Option<Vec<WidgetRef>>,
74
75    /// The configuration and labels for the columns in the table.
76    pub columns: Vec<DataColumn>,
77
78    /// The current primary sort key's column.
79    ///
80    /// See [`DataTable::sort_column_index`].
81    pub sort_column_index: Option<usize>,
82
83    /// Whether the column mentioned in [`sort_column_index`](Self::sort_column_index), if any,
84    /// is sorted in ascending order.
85    ///
86    /// See [`DataTable::sort_ascending`] for details.
87    pub sort_ascending: bool,
88
89    /// Invoked when the user selects or unselects every row, using the checkbox in the heading
90    /// row.
91    ///
92    /// See [`DataTable::on_select_all`].
93    pub on_select_all: Option<ValueChanged<Option<bool>>>,
94
95    /// The minimum height of each row (excluding the row that contains column headings).
96    ///
97    /// This value is optional and defaults to `K_MIN_INTERACTIVE_DIMENSION` if not specified.
98    pub data_row_min_height: Option<f64>,
99
100    /// The maximum height of each row (excluding the row that contains column headings).
101    ///
102    /// This value is optional and defaults to `K_MIN_INTERACTIVE_DIMENSION` if not specified.
103    pub data_row_max_height: Option<f64>,
104
105    /// The height of the heading row.
106    ///
107    /// This value is optional and defaults to 56.0 if not specified.
108    pub heading_row_height: f64,
109
110    /// The horizontal margin between the edges of the table and the content in the first and
111    /// last cells of each row.
112    ///
113    /// When a checkbox is displayed, it is also the margin between the checkbox the content in
114    /// the first data column.
115    ///
116    /// This value defaults to 24.0 to adhere to the Material Design specifications.
117    pub horizontal_margin: f64,
118
119    /// The horizontal margin between the contents of each data column.
120    ///
121    /// This value defaults to 56.0 to adhere to the Material Design specifications.
122    pub column_spacing: f64,
123
124    /// Whether the widget should display checkboxes for selectable rows.
125    ///
126    /// See [`DataTable::show_checkbox_column`].
127    pub show_checkbox_column: bool,
128
129    /// Whether to display buttons to go to the first and last pages.
130    ///
131    /// Defaults to false.
132    pub show_first_last_buttons: bool,
133
134    /// The index of the first row to display when the widget is first created.
135    pub initial_first_row_index: Option<usize>,
136
137    /// The thickness of the divider between rows.
138    ///
139    /// This value is optional and defaults to 1.0 if not specified.
140    pub divider_thickness: Option<f64>,
141
142    /// Invoked when the user switches to another page.
143    ///
144    /// The value is the index of the first row on the currently displayed page.
145    pub on_page_changed: Option<ValueChanged<usize>>,
146
147    /// The number of rows to show on each page.
148    ///
149    /// See also:
150    ///
151    ///  * [`on_rows_per_page_changed`](Self::on_rows_per_page_changed)
152    ///  * [`available_rows_per_page`](Self::available_rows_per_page)
153    pub rows_per_page: usize,
154
155    /// The options to offer for the rowsPerPage.
156    ///
157    /// The current [`rows_per_page`](Self::rows_per_page) must be a value in this list.
158    ///
159    /// The values in this list should be sorted in ascending order.
160    pub available_rows_per_page: Vec<usize>,
161
162    /// Invoked when the user selects a different number of rows per page.
163    ///
164    /// If this is null, then the value given by [`rows_per_page`](Self::rows_per_page) will be
165    /// used and no affordance will be provided to change the value.
166    pub on_rows_per_page_changed: Option<ValueChanged<Option<usize>>>,
167
168    /// The data source which provides data to show in each row.
169    ///
170    /// This object should generally have a lifetime longer than the [`PaginatedDataTable`]
171    /// widget itself; it should be reused each time the [`PaginatedDataTable`] constructor is
172    /// called.
173    pub source: DataTableSourceRef,
174
175    /// {@macro flutter.widgets.scrollable.dragStartBehavior}
176    pub drag_start_behavior: DragStartBehavior,
177
178    /// Horizontal margin around the checkbox, if it is displayed.
179    pub checkbox_horizontal_margin: Option<f64>,
180
181    /// Defines the color of the arrow heads in the footer.
182    pub arrow_head_color: Option<Color>,
183
184    /// Controls the scrolling of the horizontal table, which is only needed when the
185    /// [`PaginatedDataTable`] is too narrow.
186    ///
187    /// If null, a scroll controller is created internally by the scroll view.
188    pub controller: Option<ScrollControllerRef>,
189
190    /// Whether this is the primary scroll view associated with the parent
191    /// `PrimaryScrollController`.
192    ///
193    /// When true, the scroll view will use the ambient primary scroll controller.
194    pub primary: Option<bool>,
195
196    /// The background color for the heading row.
197    ///
198    /// See [`DataTable::heading_row_color`].
199    pub heading_row_color: Option<WidgetStatePropertyRef<Option<Color>>>,
200
201    /// Whether to display empty rows when the data source runs out of rows on the last page.
202    ///
203    /// Defaults to true.
204    pub show_empty_rows: bool,
205
206    /// Overrides the default sort indicator.
207    ///
208    /// See [`DataTable::sort_icon_builder`].
209    pub sort_icon_builder: Option<DataTableSortIconBuilder>,
210}
211
212impl PaginatedDataTable {
213    /// The default value for [`rows_per_page`](Self::rows_per_page).
214    ///
215    /// Defaults to 10, arbitrarily.
216    pub const DEFAULT_ROWS_PER_PAGE: usize = 10;
217
218    /// Creates a widget describing a paginated [`DataTable`] on a [`Card`]; Dart's optional
219    /// named arguments are the setters.
220    ///
221    /// The [`available_rows_per_page`](Self::available_rows_per_page) list must have at least
222    /// one member and must all be greater than zero.
223    pub fn new(columns: Vec<DataColumn>, source: DataTableSourceRef) -> PaginatedDataTable {
224        PaginatedDataTable {
225            key: None,
226            header: None,
227            actions: None,
228            columns,
229            sort_column_index: None,
230            sort_ascending: true,
231            on_select_all: None,
232            data_row_min_height: None,
233            data_row_max_height: None,
234            heading_row_height: 56.0,
235            horizontal_margin: 24.0,
236            column_spacing: 56.0,
237            show_checkbox_column: true,
238            show_first_last_buttons: false,
239            initial_first_row_index: Some(0),
240            divider_thickness: None,
241            on_page_changed: None,
242            rows_per_page: Self::DEFAULT_ROWS_PER_PAGE,
243            available_rows_per_page: vec![
244                Self::DEFAULT_ROWS_PER_PAGE,
245                Self::DEFAULT_ROWS_PER_PAGE * 2,
246                Self::DEFAULT_ROWS_PER_PAGE * 5,
247                Self::DEFAULT_ROWS_PER_PAGE * 10,
248            ],
249            on_rows_per_page_changed: None,
250            source,
251            drag_start_behavior: DragStartBehavior::Start,
252            checkbox_horizontal_margin: None,
253            arrow_head_color: None,
254            controller: None,
255            primary: None,
256            heading_row_color: None,
257            show_empty_rows: true,
258            sort_icon_builder: None,
259        }
260    }
261
262    /// Dart `PaginatedDataTable(key:)`.
263    pub fn key(mut self, key: KeyRef) -> PaginatedDataTable {
264        self.key = Some(key);
265        self
266    }
267
268    /// Dart `PaginatedDataTable(header:)`.
269    #[cfg_attr(debug_assertions, track_caller)]
270    pub fn header<K>(mut self, header: impl IntoWidget<K>) -> PaginatedDataTable {
271        self.header = Some(header.into_widget());
272        self
273    }
274
275    /// Dart `PaginatedDataTable(actions:)`.
276    pub fn actions(mut self, actions: Vec<WidgetRef>) -> PaginatedDataTable {
277        self.actions = Some(actions);
278        self
279    }
280
281    /// Dart `PaginatedDataTable(sortColumnIndex:)`.
282    pub fn sort_column_index(mut self, sort_column_index: usize) -> PaginatedDataTable {
283        self.sort_column_index = Some(sort_column_index);
284        self
285    }
286
287    /// Dart `PaginatedDataTable(sortAscending:)`.
288    pub fn sort_ascending(mut self, sort_ascending: bool) -> PaginatedDataTable {
289        self.sort_ascending = sort_ascending;
290        self
291    }
292
293    /// Dart `PaginatedDataTable(onSelectAll:)`.
294    pub fn on_select_all(
295        mut self,
296        on_select_all: impl Fn(&mut App, Option<bool>) + 'static,
297    ) -> PaginatedDataTable {
298        self.on_select_all = Some(Rc::new(on_select_all));
299        self
300    }
301
302    /// Dart's deprecated `PaginatedDataTable(dataRowHeight:)`: it sets
303    /// [`data_row_min_height`](Self::data_row_min_height) and
304    /// [`data_row_max_height`](Self::data_row_max_height) to one value.
305    ///
306    /// Dart asserts that the argument is not given with either of them; a fluent chain has no
307    /// one call to compare, so a later setter replaces what an earlier one wrote.
308    #[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."]
309    pub fn data_row_height(mut self, data_row_height: f64) -> PaginatedDataTable {
310        self.data_row_min_height = Some(data_row_height);
311        self.data_row_max_height = Some(data_row_height);
312        self
313    }
314
315    /// Dart `PaginatedDataTable(dataRowMinHeight:)`.
316    pub fn data_row_min_height(mut self, data_row_min_height: f64) -> PaginatedDataTable {
317        self.data_row_min_height = Some(data_row_min_height);
318        self
319    }
320
321    /// Dart `PaginatedDataTable(dataRowMaxHeight:)`.
322    pub fn data_row_max_height(mut self, data_row_max_height: f64) -> PaginatedDataTable {
323        self.data_row_max_height = Some(data_row_max_height);
324        self
325    }
326
327    /// Dart's deprecated `dataRowHeight` getter: the row height, if the minimum and the maximum
328    /// are the same.
329    #[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."]
330    pub fn data_row_height_value(&self) -> Option<f64> {
331        if self.data_row_min_height == self.data_row_max_height {
332            self.data_row_min_height
333        } else {
334            None
335        }
336    }
337
338    /// Dart `PaginatedDataTable(headingRowHeight:)`.
339    pub fn heading_row_height(mut self, heading_row_height: f64) -> PaginatedDataTable {
340        self.heading_row_height = heading_row_height;
341        self
342    }
343
344    /// Dart `PaginatedDataTable(horizontalMargin:)`.
345    pub fn horizontal_margin(mut self, horizontal_margin: f64) -> PaginatedDataTable {
346        self.horizontal_margin = horizontal_margin;
347        self
348    }
349
350    /// Dart `PaginatedDataTable(columnSpacing:)`.
351    pub fn column_spacing(mut self, column_spacing: f64) -> PaginatedDataTable {
352        self.column_spacing = column_spacing;
353        self
354    }
355
356    /// Dart `PaginatedDataTable(showCheckboxColumn:)`.
357    pub fn show_checkbox_column(mut self, show_checkbox_column: bool) -> PaginatedDataTable {
358        self.show_checkbox_column = show_checkbox_column;
359        self
360    }
361
362    /// Dart `PaginatedDataTable(showFirstLastButtons:)`.
363    pub fn show_first_last_buttons(mut self, show_first_last_buttons: bool) -> PaginatedDataTable {
364        self.show_first_last_buttons = show_first_last_buttons;
365        self
366    }
367
368    /// Dart `PaginatedDataTable(initialFirstRowIndex:)`; `None` is Dart's `null`.
369    pub fn initial_first_row_index(
370        mut self,
371        initial_first_row_index: Option<usize>,
372    ) -> PaginatedDataTable {
373        self.initial_first_row_index = initial_first_row_index;
374        self
375    }
376
377    /// Dart `PaginatedDataTable(dividerThickness:)`.
378    pub fn divider_thickness(mut self, divider_thickness: f64) -> PaginatedDataTable {
379        self.divider_thickness = Some(divider_thickness);
380        self
381    }
382
383    /// Dart `PaginatedDataTable(onPageChanged:)`.
384    pub fn on_page_changed(
385        mut self,
386        on_page_changed: impl Fn(&mut App, usize) + 'static,
387    ) -> PaginatedDataTable {
388        self.on_page_changed = Some(Rc::new(on_page_changed));
389        self
390    }
391
392    /// Dart `PaginatedDataTable(rowsPerPage:)`.
393    pub fn rows_per_page(mut self, rows_per_page: usize) -> PaginatedDataTable {
394        self.rows_per_page = rows_per_page;
395        self
396    }
397
398    /// Dart `PaginatedDataTable(availableRowsPerPage:)`.
399    pub fn available_rows_per_page(
400        mut self,
401        available_rows_per_page: Vec<usize>,
402    ) -> PaginatedDataTable {
403        self.available_rows_per_page = available_rows_per_page;
404        self
405    }
406
407    /// Dart `PaginatedDataTable(onRowsPerPageChanged:)`.
408    pub fn on_rows_per_page_changed(
409        mut self,
410        on_rows_per_page_changed: impl Fn(&mut App, Option<usize>) + 'static,
411    ) -> PaginatedDataTable {
412        self.on_rows_per_page_changed = Some(Rc::new(on_rows_per_page_changed));
413        self
414    }
415
416    /// Dart `PaginatedDataTable(dragStartBehavior:)`.
417    pub fn drag_start_behavior(
418        mut self,
419        drag_start_behavior: DragStartBehavior,
420    ) -> PaginatedDataTable {
421        self.drag_start_behavior = drag_start_behavior;
422        self
423    }
424
425    /// Dart `PaginatedDataTable(checkboxHorizontalMargin:)`.
426    pub fn checkbox_horizontal_margin(
427        mut self,
428        checkbox_horizontal_margin: f64,
429    ) -> PaginatedDataTable {
430        self.checkbox_horizontal_margin = Some(checkbox_horizontal_margin);
431        self
432    }
433
434    /// Dart `PaginatedDataTable(arrowHeadColor:)`.
435    pub fn arrow_head_color(mut self, arrow_head_color: Color) -> PaginatedDataTable {
436        self.arrow_head_color = Some(arrow_head_color);
437        self
438    }
439
440    /// Dart `PaginatedDataTable(controller:)`.
441    pub fn controller(mut self, controller: ScrollControllerRef) -> PaginatedDataTable {
442        self.controller = Some(controller);
443        self
444    }
445
446    /// Dart `PaginatedDataTable(primary:)`.
447    pub fn primary(mut self, primary: bool) -> PaginatedDataTable {
448        self.primary = Some(primary);
449        self
450    }
451
452    /// Dart `PaginatedDataTable(headingRowColor:)`.
453    pub fn heading_row_color(
454        mut self,
455        heading_row_color: WidgetStatePropertyRef<Option<Color>>,
456    ) -> PaginatedDataTable {
457        self.heading_row_color = Some(heading_row_color);
458        self
459    }
460
461    /// Dart `PaginatedDataTable(showEmptyRows:)`.
462    pub fn show_empty_rows(mut self, show_empty_rows: bool) -> PaginatedDataTable {
463        self.show_empty_rows = show_empty_rows;
464        self
465    }
466
467    /// Dart `PaginatedDataTable(sortIconBuilder:)`.
468    pub fn sort_icon_builder(
469        mut self,
470        sort_icon_builder: impl Fn(&mut App, BuildContext, bool, bool) -> WidgetRef + 'static,
471    ) -> PaginatedDataTable {
472        self.sort_icon_builder = Some(Rc::new(sort_icon_builder));
473        self
474    }
475}
476
477impl fmt::Debug for PaginatedDataTable {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        f.debug_struct("PaginatedDataTable")
480            .field("columns", &self.columns)
481            .field("rows_per_page", &self.rows_per_page)
482            .finish_non_exhaustive()
483    }
484}
485
486impl StatefulWidget for PaginatedDataTable {
487    type State = PaginatedDataTableState;
488
489    fn key(&self) -> Option<&KeyRef> {
490        self.key.as_ref()
491    }
492
493    fn debug_check_constructor(&self) {
494        debug_assert!(self.actions.is_none() || self.header.is_some());
495        debug_assert!(!self.columns.is_empty());
496        debug_assert!(
497            self.sort_column_index
498                .is_none_or(|index| index < self.columns.len())
499        );
500        debug_assert!(match (self.data_row_min_height, self.data_row_max_height) {
501            (Some(min), Some(max)) => max >= min,
502            _ => true,
503        });
504        debug_assert!(self.rows_per_page > 0);
505        debug_assert!(
506            self.divider_thickness
507                .is_none_or(|thickness| thickness >= 0.0)
508        );
509        if self.on_rows_per_page_changed.is_some() {
510            debug_assert!(self.available_rows_per_page.contains(&self.rows_per_page));
511        }
512        debug_assert!(
513            !(self.controller.is_some() && self.primary.unwrap_or(false)),
514            "Primary ScrollViews obtain their ScrollController via inheritance from a \
515             PrimaryScrollController widget. You cannot both set primary to true and pass an \
516             explicit controller."
517        );
518    }
519
520    fn create_state(&self) -> PaginatedDataTableState {
521        PaginatedDataTableState {
522            state: StateData::new(),
523            first_row_index: 0,
524            row_count: 0,
525            row_count_approximate: false,
526            selected_row_count: 0,
527            rows: HashMap::new(),
528            table_key: GlobalKey::new(),
529        }
530    }
531}
532
533/// The state of a [`PaginatedDataTable`]; Dart's `PaginatedDataTableState`.
534pub struct PaginatedDataTableState {
535    state: StateData<PaginatedDataTable>,
536    first_row_index: usize,
537    row_count: usize,
538    row_count_approximate: bool,
539    selected_row_count: usize,
540    rows: HashMap<usize, Option<DataRow>>,
541    table_key: GlobalKey,
542}
543
544impl PaginatedDataTableState {
545    fn handle_data_source_changed(self: Handle<Self>, app: &mut App) {
546        // Dart's `setState(_updateCaches)`.
547        self.update_caches(app);
548        self.set_state(app, |_state| {});
549    }
550
551    fn update_caches(self: Handle<Self>, app: &mut App) {
552        let source = self.widget(app).source.clone();
553        let row_count = source.handle().row_count(app);
554        let row_count_approximate = source.handle().is_row_count_approximate(app);
555        let selected_row_count = source.handle().selected_row_count(app);
556        let state = app.get_mut(self);
557        state.row_count = row_count;
558        state.row_count_approximate = row_count_approximate;
559        state.selected_row_count = selected_row_count;
560        state.rows.clear();
561    }
562
563    /// Ensures that the given row is visible.
564    pub fn page_to(self: Handle<Self>, app: &mut App, row_index: usize) {
565        let old_first_row_index = app.get(self).first_row_index;
566        let rows_per_page = self.widget(app).rows_per_page;
567        self.set_state(app, |state| {
568            state.first_row_index = (row_index / rows_per_page) * rows_per_page;
569        });
570        let first_row_index = app.get(self).first_row_index;
571        let on_page_changed = self.widget(app).on_page_changed.clone();
572        if let Some(on_page_changed) = on_page_changed
573            && old_first_row_index != first_row_index
574        {
575            on_page_changed(app, first_row_index);
576        }
577    }
578
579    fn get_blank_row_for(self: Handle<Self>, app: &App, index: usize) -> DataRow {
580        DataRow::by_index(
581            Some(index as i32),
582            self.widget(app)
583                .columns
584                .iter()
585                .map(|_column| DataCell::empty())
586                .collect(),
587        )
588    }
589
590    fn get_progress_indicator_row_for(self: Handle<Self>, app: &App, index: usize) -> DataRow {
591        let mut have_progress_indicator = false;
592        let mut cells: Vec<DataCell> = self
593            .widget(app)
594            .columns
595            .iter()
596            .map(|column| {
597                if !column.numeric {
598                    have_progress_indicator = true;
599                    return DataCell::new(CircularProgressIndicator::new());
600                }
601                DataCell::empty()
602            })
603            .collect();
604        if !have_progress_indicator {
605            cells[0] = DataCell::new(CircularProgressIndicator::new());
606        }
607        DataRow::by_index(Some(index as i32), cells)
608    }
609
610    fn get_rows(
611        self: Handle<Self>,
612        app: &mut App,
613        first_row_index: usize,
614        rows_per_page: usize,
615    ) -> Vec<DataRow> {
616        let mut result = Vec::new();
617        let next_page_first_row_index = first_row_index + rows_per_page;
618        let mut have_progress_indicator = false;
619        let source = self.widget(app).source.clone();
620        let show_empty_rows = self.widget(app).show_empty_rows;
621        for index in first_row_index..next_page_first_row_index {
622            let mut row: Option<DataRow> = None;
623            if index < app.get(self).row_count || app.get(self).row_count_approximate {
624                if !app.get(self).rows.contains_key(&index) {
625                    let new_row = source.handle().get_row(app, index);
626                    app.get_mut(self).rows.insert(index, new_row);
627                }
628                row = app.get(self).rows[&index].clone();
629                if row.is_none() && !have_progress_indicator {
630                    row = Some(self.get_progress_indicator_row_for(app, index));
631                    have_progress_indicator = true;
632                }
633            }
634
635            if show_empty_rows && row.is_none() {
636                row = Some(self.get_blank_row_for(app, index));
637            }
638
639            if let Some(row) = row {
640                result.push(row);
641            }
642        }
643        result
644    }
645
646    fn handle_first(self: Handle<Self>, app: &mut App) {
647        self.page_to(app, 0);
648    }
649
650    fn handle_previous(self: Handle<Self>, app: &mut App) {
651        let rows_per_page = self.widget(app).rows_per_page;
652        let first_row_index = app.get(self).first_row_index;
653        self.page_to(app, first_row_index.saturating_sub(rows_per_page));
654    }
655
656    fn handle_next(self: Handle<Self>, app: &mut App) {
657        let rows_per_page = self.widget(app).rows_per_page;
658        let first_row_index = app.get(self).first_row_index;
659        self.page_to(app, first_row_index + rows_per_page);
660    }
661
662    fn handle_last(self: Handle<Self>, app: &mut App) {
663        let rows_per_page = self.widget(app).rows_per_page;
664        let row_count = app.get(self).row_count;
665        self.page_to(
666            app,
667            (row_count.saturating_sub(1) / rows_per_page) * rows_per_page,
668        );
669    }
670
671    fn is_next_page_unavailable(self: Handle<Self>, app: &App) -> bool {
672        let state = app.get(self);
673        !state.row_count_approximate
674            && state.first_row_index + self.widget(app).rows_per_page >= state.row_count
675    }
676}
677
678impl State for PaginatedDataTableState {
679    type Widget = PaginatedDataTable;
680    waft_widgets::state_accessors!();
681
682    fn init_state(self: Handle<Self>, app: &mut App) {
683        let context = self.context(app);
684        let stored = PageStorage::maybe_of(app, context)
685            .and_then(|bucket| bucket.read_state(app, context, None))
686            .and_then(|state| state.downcast_ref::<usize>().copied());
687        app.get_mut(self).first_row_index = stored
688            .or(self.widget(app).initial_first_row_index)
689            .unwrap_or(0);
690        let source = self.widget(app).source.clone();
691        source.add_listener(
692            app,
693            Listener::handle_method(self, Self::handle_data_source_changed),
694        );
695        self.handle_data_source_changed(app);
696    }
697
698    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &PaginatedDataTable) {
699        let source = self.widget(app).source.clone();
700        if old_widget.source != source {
701            old_widget.source.remove_listener(
702                app,
703                &Listener::handle_method(self, Self::handle_data_source_changed),
704            );
705            source.add_listener(
706                app,
707                Listener::handle_method(self, Self::handle_data_source_changed),
708            );
709            self.update_caches(app);
710        }
711    }
712
713    fn dispose(self: Handle<Self>, app: &mut App) {
714        let source = self.widget(app).source.clone();
715        source.remove_listener(
716            app,
717            &Listener::handle_method(self, Self::handle_data_source_changed),
718        );
719    }
720
721    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
722        // TODO(ianh): This whole build function doesn't handle RTL yet.
723        debug_assert!(debug_check_has_material_localizations(app, context));
724        let theme_data = Theme::of(app, context);
725        let localizations = <dyn MaterialLocalizations>::of(app, context);
726        let widget = self.widget(app).clone();
727        let (first_row_index, row_count, row_count_approximate, selected_row_count) = {
728            let state = app.get(self);
729            (
730                state.first_row_index,
731                state.row_count,
732                state.row_count_approximate,
733                state.selected_row_count,
734            )
735        };
736        // HEADER
737        let mut header_widgets: Vec<WidgetRef> = Vec::new();
738        if selected_row_count == 0 && widget.header.is_some() {
739            header_widgets
740                .push(Expanded::new(widget.header.clone().expect("checked above")).into_widget());
741        } else if widget.header.is_some() {
742            header_widgets.push(
743                Expanded::new(Text::new(
744                    localizations.selected_row_count_title(selected_row_count as i32),
745                ))
746                .into_widget(),
747            );
748        }
749        if let Some(actions) = &widget.actions {
750            header_widgets.extend(actions.iter().map(|action| {
751                Padding::new(EdgeInsetsDirectional::only(24.0 - 8.0 * 2.0, 0.0, 0.0, 0.0))
752                    // 8.0 is the default padding of an icon button
753                    .child(action.clone())
754                    .into_widget()
755            }));
756        }
757
758        // FOOTER
759        let footer_text_style = theme_data
760            .text_theme
761            .body_small
762            .clone()
763            .expect("the theme's text theme has bodySmall");
764        let mut footer_widgets: Vec<WidgetRef> = Vec::new();
765        if let Some(on_rows_per_page_changed) = widget.on_rows_per_page_changed.clone() {
766            let available_rows_per_page: Vec<DropdownMenuItem<usize>> = widget
767                .available_rows_per_page
768                .iter()
769                .filter(|value| **value <= row_count || **value == widget.rows_per_page)
770                .map(|value| DropdownMenuItem::new(Text::new(value.to_string())).value(*value))
771                .collect();
772            footer_widgets.extend([
773                // Match trailing padding, in case we overflow and end up scrolling.
774                SizedBox::new().width(14.0).into_widget(),
775                Text::new(localizations.rows_per_page_title()).into_widget(),
776                ConstrainedBox::new(BoxConstraints {
777                    min_width: 64.0, // 40.0 for the text, 24.0 for the icon
778                    ..BoxConstraints::new()
779                })
780                .child(
781                    Align::new().alignment(AlignmentGeometry::CENTER_END).child(
782                        DropdownButtonHideUnderline::new(
783                            DropdownButton::new(
784                                Some(available_rows_per_page),
785                                Some(on_rows_per_page_changed),
786                            )
787                            .value(Some(widget.rows_per_page))
788                            .style(footer_text_style.clone()),
789                        ),
790                    ),
791                )
792                .into_widget(),
793            ]);
794        }
795        let arrow_button = |icon: waft_widgets::IconData,
796                            tooltip: String,
797                            on_pressed: Option<Listener>|
798         -> WidgetRef {
799            let mut button = IconButton::new(on_pressed, waft_widgets::Icon::new(Some(icon)))
800                .padding(EdgeInsets::ZERO.into())
801                .tooltip(tooltip);
802            if let Some(color) = widget.arrow_head_color {
803                button = button.color(color);
804            }
805            button.into_widget()
806        };
807        footer_widgets.push(SizedBox::new().width(32.0).into_widget());
808        footer_widgets.push(
809            Text::new(localizations.page_rows_info_title(
810                (first_row_index + 1) as i32,
811                (first_row_index + widget.rows_per_page).min(row_count) as i32,
812                row_count as i32,
813                row_count_approximate,
814            ))
815            .into_widget(),
816        );
817        footer_widgets.push(SizedBox::new().width(32.0).into_widget());
818        if widget.show_first_last_buttons {
819            footer_widgets.push(arrow_button(
820                Icons::skip_previous(),
821                localizations.first_page_tooltip(),
822                (first_row_index > 0).then(|| Listener::handle_method(self, Self::handle_first)),
823            ));
824        }
825        footer_widgets.push(arrow_button(
826            Icons::chevron_left(),
827            localizations.previous_page_tooltip(),
828            (first_row_index > 0).then(|| Listener::handle_method(self, Self::handle_previous)),
829        ));
830        footer_widgets.push(SizedBox::new().width(24.0).into_widget());
831        let next_enabled = !self.is_next_page_unavailable(app);
832        footer_widgets.push(arrow_button(
833            Icons::chevron_right(),
834            localizations.next_page_tooltip(),
835            next_enabled.then(|| Listener::handle_method(self, Self::handle_next)),
836        ));
837        if widget.show_first_last_buttons {
838            footer_widgets.push(arrow_button(
839                Icons::skip_next(),
840                localizations.last_page_tooltip(),
841                next_enabled.then(|| Listener::handle_method(self, Self::handle_last)),
842            ));
843        }
844        footer_widgets.push(SizedBox::new().width(14.0).into_widget());
845
846        let table_key = app.get(self).table_key.clone();
847        let header_style = if selected_row_count > 0 {
848            theme_data
849                .text_theme
850                .title_medium
851                .clone()
852                .expect("the theme's text theme has titleMedium")
853                .copy_with()
854                .color(theme_data.color_scheme.secondary())
855        } else {
856            theme_data
857                .text_theme
858                .title_large
859                .clone()
860                .expect("the theme's text theme has titleLarge")
861                .copy_with()
862                .font_weight(FontWeight::W400)
863        };
864        let secondary_header_color = theme_data.secondary_header_color;
865
866        // CARD
867        Card::new()
868            .semantic_container(false)
869            .child(
870                LayoutBuilder::new(move |app, _context, constraints| {
871                    let mut children: Vec<WidgetRef> = Vec::new();
872                    if !header_widgets.is_empty() {
873                        let mut ink = Ink::new().height(64.0);
874                        if selected_row_count > 0 {
875                            ink = ink.color(secondary_header_color);
876                        }
877                        children.push(
878                            Semantics::new()
879                                .container(true)
880                                .child(DefaultTextStyle::new(
881                                    // These typographic styles aren't quite the regular ones. We pick
882                                    // the closest ones from the regular list and then tweak them
883                                    // appropriately.
884                                    // See https://material.io/design/components/data-tables.html#tables-within-cards
885                                    header_style.clone(),
886                                    IconTheme::merge(
887                                        None,
888                                        IconThemeData::new().opacity(0.54),
889                                        ink.child(
890                                            Padding::new(EdgeInsetsDirectional::only(
891                                                24.0, 0.0, 14.0, 0.0,
892                                            ))
893                                            .child(
894                                                Row::new()
895                                                    .main_axis_alignment(MainAxisAlignment::End)
896                                                    .children(header_widgets.clone()),
897                                            ),
898                                        ),
899                                    ),
900                                ))
901                                .into_widget(),
902                        );
903                    }
904                    // Dart asks the source for the page's rows here, at layout.
905                    let rows = self.get_rows(app, first_row_index, widget.rows_per_page);
906                    let mut table = DataTable::new(widget.columns.clone(), rows)
907                        .key(table_key.clone().into())
908                        .sort_ascending(widget.sort_ascending)
909                        // Make sure no decoration is set on the DataTable from the theme, as its
910                        // already wrapped in a Card.
911                        .decoration(BoxDecoration::new())
912                        .heading_row_height(widget.heading_row_height)
913                        .horizontal_margin(widget.horizontal_margin)
914                        .column_spacing(widget.column_spacing)
915                        .show_checkbox_column(widget.show_checkbox_column)
916                        .show_bottom_border(true);
917                    table.sort_column_index = widget.sort_column_index;
918                    table.on_select_all = widget.on_select_all.clone();
919                    table.divider_thickness = widget.divider_thickness;
920                    table.data_row_min_height = widget.data_row_min_height;
921                    table.data_row_max_height = widget.data_row_max_height;
922                    table.checkbox_horizontal_margin = widget.checkbox_horizontal_margin;
923                    table.heading_row_color = widget.heading_row_color.clone();
924                    table.sort_icon_builder = widget.sort_icon_builder.clone();
925                    let mut scroll = SingleChildScrollView::new()
926                        .scroll_direction(Axis::Horizontal)
927                        .drag_start_behavior(widget.drag_start_behavior);
928                    if let Some(primary) = widget.primary {
929                        scroll = scroll.primary(primary);
930                    }
931                    if let Some(controller) = widget.controller.clone() {
932                        scroll = scroll.controller(controller);
933                    }
934                    children.push(
935                        scroll
936                            .child(
937                                ConstrainedBox::new(BoxConstraints {
938                                    min_width: constraints.min_width,
939                                    ..BoxConstraints::new()
940                                })
941                                .child(table),
942                            )
943                            .into_widget(),
944                    );
945                    if !widget.show_empty_rows {
946                        let missing = (widget.rows_per_page as i64 - row_count as i64
947                            + first_row_index as i64)
948                            .clamp(0, widget.rows_per_page as i64);
949                        children.push(
950                            SizedBox::new()
951                                .height(
952                                    widget
953                                        .data_row_max_height
954                                        .unwrap_or(K_MIN_INTERACTIVE_DIMENSION)
955                                        * missing as f64,
956                                )
957                                .into_widget(),
958                        );
959                    }
960                    children.push(
961                        DefaultTextStyle::new(
962                            footer_text_style.clone(),
963                            IconTheme::merge(
964                                None,
965                                IconThemeData::new().opacity(0.54),
966                                // TODO(bkonyi): this won't handle text zoom correctly,
967                                //  https://github.com/flutter/flutter/issues/48522
968                                SizedBox::new().height(56.0).child(
969                                    SingleChildScrollView::new()
970                                        .drag_start_behavior(widget.drag_start_behavior)
971                                        .scroll_direction(Axis::Horizontal)
972                                        .reverse(true)
973                                        .child(Row::new().children(footer_widgets.clone())),
974                                ),
975                            ),
976                        )
977                        .into_widget(),
978                    );
979                    Column::new()
980                        .cross_axis_alignment(CrossAxisAlignment::Stretch)
981                        .children(children)
982                        .into_widget()
983                })
984                .into_widget(),
985            )
986            .into_widget()
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    //! The cases of `test/paginated_data_table_test.dart`.
993
994    use std::cell::RefCell;
995    use std::collections::HashSet;
996    use std::rc::Rc;
997    use std::time::Duration;
998
999    use crate::bottom_navigation_bar::tests::paragraph_style;
1000    use waft_embedder::{Color, Offset, Size};
1001    use waft_foundation::{ChangeNotifier, ChangeNotifierData, Ref};
1002    use waft_painting::BoxDecoration;
1003    use waft_widgets::testing::{
1004        Finder, WidgetTester, assert_f32_equals, assert_more_or_less_equals, expect, find,
1005        finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
1006    };
1007    use waft_widgets::{
1008        Align, Center, Container, GlobalKey, Padding, SizedBox, Table, Text, WidgetStatePropertyAll,
1009    };
1010
1011    use super::*;
1012    use crate::checkbox::Checkbox;
1013    use crate::data_table::tests::{K_DESSERTS, app_of};
1014    use crate::data_table::{DataColumn, DataRow};
1015    use crate::data_table_source::{AnyDataTableSource, DataTableSource};
1016    use crate::data_table_theme::DataTableThemeData;
1017    use crate::icon_button::IconButton;
1018    use crate::material::Material;
1019    use crate::scaffold::Scaffold;
1020    use crate::test_support::material_app;
1021    use crate::theme_data::ThemeData;
1022    use crate::tooltip::tests::m3;
1023    use waft_painting::DecorationRef;
1024    use waft_widgets::Icon;
1025
1026    /// The `TestDataSource` of the test file.
1027    struct TestDataSource {
1028        change_notifier: ChangeNotifierData,
1029        allow_selection: bool,
1030        generation: i32,
1031        selected_rows: HashSet<usize>,
1032    }
1033
1034    impl ChangeNotifier for TestDataSource {
1035        fn change_notifier_data(&self) -> &ChangeNotifierData {
1036            &self.change_notifier
1037        }
1038
1039        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1040            &mut self.change_notifier
1041        }
1042    }
1043
1044    impl TestDataSource {
1045        fn new(app: &mut App, allow_selection: bool, generation: i32) -> Ref<TestDataSource> {
1046            app.create(TestDataSource {
1047                change_notifier: ChangeNotifierData::new(),
1048                allow_selection,
1049                generation,
1050                selected_rows: HashSet::new(),
1051            })
1052        }
1053
1054        fn set_generation(self: Handle<Self>, app: &mut App, value: i32) {
1055            if app.get(self).generation == value {
1056                return;
1057            }
1058            app.get_mut(self).generation = value;
1059            self.notify_listeners(app);
1060        }
1061
1062        fn handle_selected(
1063            self: Handle<Self>,
1064            app: &mut App,
1065            index: usize,
1066            selected: Option<bool>,
1067        ) {
1068            if selected.unwrap_or(false) {
1069                app.get_mut(self).selected_rows.insert(index);
1070            } else {
1071                app.get_mut(self).selected_rows.remove(&index);
1072            }
1073            self.notify_listeners(app);
1074        }
1075    }
1076
1077    impl DataTableSource for TestDataSource {
1078        fn get_row(self: Handle<Self>, app: &mut App, index: usize) -> Option<DataRow> {
1079            let dessert = &K_DESSERTS[index % K_DESSERTS.len()];
1080            let page = index / K_DESSERTS.len();
1081            let state = app.get(self);
1082            let selected = state.selected_rows.contains(&index);
1083            let generation = state.generation;
1084            let mut row = DataRow::by_index(
1085                Some(index as i32),
1086                vec![
1087                    DataCell::new(Text::new(format!("{} ({page})", dessert.name))),
1088                    DataCell::new(Text::new(dessert.calories.to_string())),
1089                    DataCell::new(Text::new(generation.to_string())),
1090                ],
1091            )
1092            .selected(selected);
1093            if state.allow_selection {
1094                row = row.on_select_changed(move |app, selected| {
1095                    self.handle_selected(app, index, selected)
1096                });
1097            }
1098            Some(row)
1099        }
1100
1101        fn row_count(self: Handle<Self>, _app: &App) -> usize {
1102            50 * K_DESSERTS.len()
1103        }
1104
1105        fn is_row_count_approximate(self: Handle<Self>, _app: &App) -> bool {
1106            false
1107        }
1108
1109        fn selected_row_count(self: Handle<Self>, app: &App) -> usize {
1110            app.get(self).selected_rows.len()
1111        }
1112    }
1113
1114    fn new_source(
1115        tester: &WidgetTester,
1116        allow_selection: bool,
1117        generation: i32,
1118    ) -> Ref<TestDataSource> {
1119        TestDataSource::new(&mut tester.cell.borrow_mut(), allow_selection, generation)
1120    }
1121
1122    fn erased(source: &Ref<TestDataSource>) -> DataTableSourceRef {
1123        source.erase::<AnyDataTableSource>()
1124    }
1125
1126    fn standard_columns() -> Vec<DataColumn> {
1127        vec![
1128            DataColumn::new(Text::new("Name")),
1129            DataColumn::new(Text::new("Calories")).numeric(true),
1130            DataColumn::new(Text::new("Generation")),
1131        ]
1132    }
1133
1134    fn page_button(finder_tooltip: &str) -> Finder {
1135        find::ancestor(
1136            find::by_tooltip(finder_tooltip),
1137            find::by_type::<IconButton>(),
1138        )
1139    }
1140
1141    fn page_button_enabled(tester: &WidgetTester, tooltip: &str) -> bool {
1142        tester.widget(page_button(tooltip), |button: &IconButton| {
1143            button.on_pressed.is_some()
1144        })
1145    }
1146
1147    type Log = Rc<RefCell<Vec<String>>>;
1148
1149    fn take_log(log: &Log) -> Vec<String> {
1150        std::mem::take(&mut *log.borrow_mut())
1151    }
1152
1153    #[test]
1154    fn paginated_data_table_paging() {
1155        test_widgets(|tester| {
1156            let source = new_source(tester, false, 0);
1157            let log: Log = Rc::default();
1158            let rows_log = Rc::clone(&log);
1159            let page_log = Rc::clone(&log);
1160            let table = PaginatedDataTable::new(standard_columns(), erased(&source))
1161                .header(Text::new("Test table"))
1162                .rows_per_page(2)
1163                .show_first_last_buttons(true)
1164                .available_rows_per_page(vec![2, 4, 8, 16])
1165                .on_rows_per_page_changed(move |_app, rows_per_page| {
1166                    rows_log.borrow_mut().push(format!(
1167                        "rows-per-page-changed: {}",
1168                        rows_per_page.map_or("null".to_owned(), |value| value.to_string())
1169                    ))
1170                })
1171                .on_page_changed(move |_app, row_index| {
1172                    page_log
1173                        .borrow_mut()
1174                        .push(format!("page-changed: {row_index}"))
1175                });
1176            let root = app_of(tester, table);
1177            tester.pump_widget(root);
1178
1179            tester.tap(find::by_tooltip("Next page"));
1180            assert_eq!(take_log(&log), ["page-changed: 2"]);
1181
1182            tester.pump();
1183            expect(tester, &find::text("Frozen yogurt (0)"), finds_nothing());
1184            expect(tester, &find::text("Eclair (0)"), finds_one_widget());
1185            expect(tester, &find::text("Gingerbread (0)"), finds_nothing());
1186
1187            tester.tap(find::by_icon(&Icons::chevron_left()));
1188            assert_eq!(take_log(&log), ["page-changed: 0"]);
1189
1190            tester.pump();
1191            expect(tester, &find::text("Frozen yogurt (0)"), finds_one_widget());
1192            expect(tester, &find::text("Eclair (0)"), finds_nothing());
1193            expect(tester, &find::text("Gingerbread (0)"), finds_nothing());
1194
1195            assert!(page_button_enabled(tester, "Last page"));
1196
1197            tester.tap(page_button("Last page"));
1198            assert_eq!(take_log(&log), ["page-changed: 498"]);
1199
1200            tester.pump();
1201            assert!(!page_button_enabled(tester, "Last page"));
1202
1203            expect(tester, &find::text("Frozen yogurt (0)"), finds_nothing());
1204            expect(tester, &find::text("Donut (49)"), finds_one_widget());
1205            expect(tester, &find::text("KitKat (49)"), finds_one_widget());
1206
1207            assert!(page_button_enabled(tester, "First page"));
1208
1209            tester.tap(page_button("First page"));
1210            assert_eq!(take_log(&log), ["page-changed: 0"]);
1211
1212            tester.pump();
1213            assert!(!page_button_enabled(tester, "First page"));
1214
1215            expect(tester, &find::text("Frozen yogurt (0)"), finds_one_widget());
1216            expect(tester, &find::text("Eclair (0)"), finds_nothing());
1217            expect(tester, &find::text("Gingerbread (0)"), finds_nothing());
1218
1219            tester.tap(find::by_icon(&Icons::chevron_left()));
1220            assert!(log.borrow().is_empty());
1221
1222            tester.tap(find::text("2"));
1223            tester.pump_and_settle_by(Duration::from_millis(200));
1224
1225            tester.tap(find::text("8").last());
1226            tester.pump_and_settle_by(Duration::from_millis(200));
1227
1228            assert_eq!(take_log(&log), ["rows-per-page-changed: 8"]);
1229        });
1230    }
1231
1232    #[test]
1233    fn paginated_data_table_footer_page_number() {
1234        test_widgets(|tester| {
1235            let source = new_source(tester, false, 0);
1236            let build_table = |tester: &WidgetTester, rows_per_page: usize| -> WidgetRef {
1237                app_of(
1238                    tester,
1239                    PaginatedDataTable::new(standard_columns(), erased(&source))
1240                        .header(Text::new("Test table"))
1241                        .rows_per_page(rows_per_page)
1242                        .show_first_last_buttons(true)
1243                        .available_rows_per_page(vec![2, 3, 4, 5, 7, 8])
1244                        .on_rows_per_page_changed(|_app, _rows_per_page| {})
1245                        .on_page_changed(|_app, _row_index| {}),
1246                )
1247            };
1248
1249            let root = build_table(tester, 2);
1250            tester.pump_widget(root);
1251            expect(tester, &find::text("1\u{2013}2 of 500"), finds_one_widget());
1252            tester.tap(find::by_tooltip("Next page"));
1253            tester.pump();
1254            expect(tester, &find::text("3\u{2013}4 of 500"), finds_one_widget());
1255
1256            assert!(page_button_enabled(tester, "Last page"));
1257            tester.tap(page_button("Last page"));
1258            tester.pump();
1259            expect(
1260                tester,
1261                &find::text("499\u{2013}500 of 500"),
1262                finds_one_widget(),
1263            );
1264
1265            let element = tester.element(find::by_type::<PaginatedDataTable>());
1266            let state = element
1267                .state_handle::<PaginatedDataTableState>(&tester.cell.borrow())
1268                .expect("a PaginatedDataTableState");
1269            state.page_to(&mut tester.cell.borrow_mut(), 1);
1270
1271            for (rows_per_page, first, next, last) in [
1272                (
1273                    3,
1274                    "1\u{2013}3 of 500",
1275                    "4\u{2013}6 of 500",
1276                    "499\u{2013}500 of 500",
1277                ),
1278                (
1279                    4,
1280                    "1\u{2013}4 of 500",
1281                    "5\u{2013}8 of 500",
1282                    "497\u{2013}500 of 500",
1283                ),
1284                (
1285                    5,
1286                    "1\u{2013}5 of 500",
1287                    "6\u{2013}10 of 500",
1288                    "496\u{2013}500 of 500",
1289                ),
1290                (
1291                    8,
1292                    "1\u{2013}8 of 500",
1293                    "9\u{2013}16 of 500",
1294                    "497\u{2013}500 of 500",
1295                ),
1296            ] {
1297                let root = build_table(tester, rows_per_page);
1298                tester.pump_widget(root);
1299                expect(tester, &find::text_containing(first), finds_one_widget());
1300                tester.tap(find::by_tooltip("Next page"));
1301                tester.pump();
1302                expect(tester, &find::text(next), finds_one_widget());
1303                assert!(page_button_enabled(tester, "Last page"));
1304                tester.tap(page_button("Last page"));
1305                tester.pump();
1306                expect(tester, &find::text(last), finds_one_widget());
1307                state.page_to(&mut tester.cell.borrow_mut(), 1);
1308            }
1309        });
1310    }
1311
1312    #[test]
1313    fn paginated_data_table_control_test() {
1314        test_widgets(|tester| {
1315            let log: Log = Rc::default();
1316            let build_table = |tester: &WidgetTester, source: &Ref<TestDataSource>| -> WidgetRef {
1317                let sort_log = Rc::clone(&log);
1318                let page_log = Rc::clone(&log);
1319                let action_log = Rc::clone(&log);
1320                app_of(
1321                    tester,
1322                    PaginatedDataTable::new(
1323                        vec![
1324                            DataColumn::new(Text::new("Name")).tooltip("Name"),
1325                            DataColumn::new(Text::new("Calories"))
1326                                .tooltip("Calories")
1327                                .numeric(true)
1328                                .on_sort(move |_app, column_index, ascending| {
1329                                    sort_log
1330                                        .borrow_mut()
1331                                        .push(format!("column-sort: {column_index} {ascending}"))
1332                                }),
1333                            DataColumn::new(Text::new("Generation")).tooltip("Generation"),
1334                        ],
1335                        erased(source),
1336                    )
1337                    .header(Text::new("Test table"))
1338                    .on_page_changed(move |_app, row_index| {
1339                        page_log
1340                            .borrow_mut()
1341                            .push(format!("page-changed: {row_index}"))
1342                    })
1343                    .actions(vec![
1344                        IconButton::new(
1345                            Some(Listener::new(move |_| {
1346                                action_log.borrow_mut().push("action: adjust".to_owned())
1347                            })),
1348                            Icon::new(Some(Icons::adjust())),
1349                        )
1350                        .into_widget(),
1351                    ]),
1352                )
1353            };
1354
1355            let source = new_source(tester, false, 42);
1356            let root = build_table(tester, &source);
1357            tester.pump_widget(root);
1358
1359            // (Dart also expects a RenderFlex overflow exception here, because the test forces
1360            // the column to 600 pixels high; Waft has no `takeException`.)
1361            expect(tester, &find::text("Gingerbread (0)"), finds_one_widget());
1362            expect(tester, &find::text("Gingerbread (1)"), finds_nothing());
1363            expect(tester, &find::text("42"), finds_n_widgets(10));
1364
1365            source
1366                .handle()
1367                .set_generation(&mut tester.cell.borrow_mut(), 43);
1368            tester.pump();
1369
1370            expect(tester, &find::text("42"), finds_nothing());
1371            expect(tester, &find::text("43"), finds_n_widgets(10));
1372
1373            let source = new_source(tester, false, 15);
1374            let root = build_table(tester, &source);
1375            tester.pump_widget(root);
1376
1377            expect(tester, &find::text("42"), finds_nothing());
1378            expect(tester, &find::text("43"), finds_nothing());
1379            expect(tester, &find::text("15"), finds_n_widgets(10));
1380
1381            let element = tester.element(find::by_type::<PaginatedDataTable>());
1382            let state = element
1383                .state_handle::<PaginatedDataTableState>(&tester.cell.borrow())
1384                .expect("a PaginatedDataTableState");
1385
1386            assert!(log.borrow().is_empty());
1387            state.page_to(&mut tester.cell.borrow_mut(), 23);
1388            assert_eq!(take_log(&log), ["page-changed: 20"]);
1389
1390            tester.pump();
1391            expect(tester, &find::text("Gingerbread (0)"), finds_nothing());
1392            expect(tester, &find::text("Gingerbread (1)"), finds_nothing());
1393            expect(tester, &find::text("Gingerbread (2)"), finds_one_widget());
1394
1395            tester.tap(find::by_icon(&Icons::adjust()));
1396            assert_eq!(take_log(&log), ["action: adjust"]);
1397        });
1398    }
1399
1400    #[test]
1401    fn paginated_data_table_text_alignment() {
1402        test_widgets(|tester| {
1403            let source = new_source(tester, false, 0);
1404            let root = app_of(
1405                tester,
1406                PaginatedDataTable::new(
1407                    vec![
1408                        DataColumn::new(Text::new("COL1")),
1409                        DataColumn::new(Text::new("COL2")),
1410                        DataColumn::new(Text::new("COL3")),
1411                    ],
1412                    erased(&source),
1413                )
1414                .header(Text::new("HEADER"))
1415                .rows_per_page(8)
1416                .available_rows_per_page(vec![8, 9])
1417                .on_rows_per_page_changed(|_app, _rows_per_page| {}),
1418            );
1419            tester.pump_widget(root);
1420
1421            expect(tester, &find::text("Rows per page:"), finds_one_widget());
1422            expect(tester, &find::text("8"), finds_one_widget());
1423            // Within f32: global positions go through valo's f32 matrices (waft-gestures'
1424            // Matrix4 entry), where Dart's are f64 and compare equal.
1425            assert_f32_equals(
1426                tester.get_top_right(find::text("8")).dx(),
1427                tester.get_top_right(find::text("Rows per page:")).dx() + 40.0,
1428            ); // per spec
1429        });
1430    }
1431
1432    #[test]
1433    fn paginated_data_table_with_and_without_header_and_actions() {
1434        test_widgets(|tester| {
1435            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1436            let header_text = "HEADER";
1437            let source = new_source(tester, true, 0);
1438            let build_table = |tester: &WidgetTester, header: Option<&str>, with_actions: bool| {
1439                let mut table = PaginatedDataTable::new(standard_columns(), erased(&source));
1440                if let Some(header) = header {
1441                    table = table.header(Text::new(header));
1442                }
1443                if with_actions {
1444                    table = table.actions(vec![
1445                        IconButton::new(Some(Listener::new(|_| {})), Icon::new(Some(Icons::add())))
1446                            .into_widget(),
1447                    ]);
1448                }
1449                app_of(tester, table)
1450            };
1451
1452            let root = build_table(tester, Some(header_text), false);
1453            tester.pump_widget(root);
1454            expect(tester, &find::text(header_text), finds_one_widget());
1455            expect(tester, &find::by_icon(&Icons::add()), finds_nothing());
1456
1457            let root = build_table(tester, Some(header_text), true);
1458            tester.pump_widget(root);
1459            expect(tester, &find::text(header_text), finds_one_widget());
1460            expect(tester, &find::by_icon(&Icons::add()), finds_one_widget());
1461
1462            let root = build_table(tester, None, false);
1463            tester.pump_widget(root);
1464            expect(tester, &find::text(header_text), finds_nothing());
1465            expect(tester, &find::by_icon(&Icons::add()), finds_nothing());
1466            tester.set_surface_size(None);
1467        });
1468    }
1469
1470    #[test]
1471    #[should_panic]
1472    fn paginated_data_table_actions_without_a_header_asserts() {
1473        test_widgets(|tester| {
1474            let source = new_source(tester, true, 0);
1475            let table = PaginatedDataTable::new(standard_columns(), erased(&source)).actions(vec![
1476                IconButton::new(Some(Listener::new(|_| {})), Icon::new(Some(Icons::add())))
1477                    .into_widget(),
1478            ]);
1479            let _ = table.into_widget();
1480        });
1481    }
1482
1483    #[test]
1484    fn paginated_data_table_table_fills_card_width() {
1485        test_widgets(|tester| {
1486            // 800 is wide enough to ensure that all of the columns fit in the Card. The test makes
1487            // sure that the DataTable is exactly as wide as the Card, minus the Card's margin.
1488            let original_width = 800.0;
1489            let expanded_width = 1600.0;
1490            let height = 400.0;
1491            // By default, the margin of a Card is 4 in all directions, so the size of the
1492            // DataTable (inside the Card) is horizontally reduced by 4 * 2; the left and right
1493            // margins.
1494            let card_margin = 8.0;
1495            let source = new_source(tester, false, 0);
1496            let build_widget = |tester: &WidgetTester| {
1497                app_of(
1498                    tester,
1499                    PaginatedDataTable::new(standard_columns(), erased(&source))
1500                        .header(Text::new("Test table"))
1501                        .rows_per_page(2)
1502                        .available_rows_per_page(vec![2, 4, 8, 16])
1503                        .on_rows_per_page_changed(|_app, _rows_per_page| {})
1504                        .on_page_changed(|_app, _row_index| {}),
1505                )
1506            };
1507            tester.set_surface_size(Some(Size::new(original_width, height)));
1508            let root = build_widget(tester);
1509            tester.pump_widget(root);
1510            let mut card_width = tester.get_size(find::by_type::<Card>().first()).width();
1511            // Widths should be equal before we resize...
1512            assert_more_or_less_equals(
1513                tester
1514                    .get_size(find::by_type::<DataTable>().first())
1515                    .width(),
1516                card_width - card_margin,
1517            );
1518
1519            tester.set_surface_size(Some(Size::new(expanded_width, height)));
1520            let root = build_widget(tester);
1521            tester.pump_widget(root);
1522            card_width = tester.get_size(find::by_type::<Card>().first()).width();
1523            // ... and should still be equal after the resize.
1524            assert_more_or_less_equals(
1525                tester
1526                    .get_size(find::by_type::<DataTable>().first())
1527                    .width(),
1528                card_width - card_margin,
1529            );
1530            // Double check to ensure we actually resized the surface properly.
1531            assert_more_or_less_equals(card_width, expanded_width);
1532            tester.set_surface_size(None);
1533        });
1534    }
1535
1536    #[test]
1537    fn paginated_data_table_with_optional_column_checkbox() {
1538        test_widgets(|tester| {
1539            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1540            let source = new_source(tester, true, 0);
1541            let build_table = |tester: &WidgetTester, checkbox: bool| {
1542                app_of(
1543                    tester,
1544                    PaginatedDataTable::new(standard_columns(), erased(&source))
1545                        .header(Text::new("Test table"))
1546                        .show_checkbox_column(checkbox),
1547                )
1548            };
1549            let root = build_table(tester, true);
1550            tester.pump_widget(root);
1551            expect(tester, &find::by_type::<Checkbox>(), finds_n_widgets(11));
1552
1553            let root = build_table(tester, false);
1554            tester.pump_widget(root);
1555            expect(tester, &find::by_type::<Checkbox>(), finds_nothing());
1556            tester.set_surface_size(None);
1557        });
1558    }
1559
1560    #[test]
1561    fn table_should_not_use_decoration_from_data_table_theme() {
1562        test_widgets(|tester| {
1563            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1564            let source = new_source(tester, true, 0);
1565            let theme = ThemeData::builder()
1566                .data_table_theme(
1567                    DataTableThemeData::new()
1568                        .decoration(BoxDecoration::new().color(Color::new(0xffffffff))),
1569                )
1570                .build(&tester.cell.borrow());
1571            let root = material_app(
1572                theme,
1573                Material::new()
1574                    .child(
1575                        PaginatedDataTable::new(standard_columns(), erased(&source))
1576                            .header(Text::new("Test table")),
1577                    )
1578                    .into_widget(),
1579            );
1580            tester.pump_widget(root);
1581
1582            let table_container =
1583                find::ancestor(find::by_type::<Table>(), find::by_type::<Container>()).first();
1584            let decoration = tester.widget(table_container, |container: &Container| {
1585                container.decoration.clone()
1586            });
1587            assert_eq!(decoration, Some(DecorationRef::new(BoxDecoration::new())));
1588            tester.set_surface_size(None);
1589        });
1590    }
1591
1592    #[test]
1593    fn paginated_data_table_arrow_head_color_set_properly() {
1594        test_widgets(|tester| {
1595            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1596            let arrow_head_color = Color::new(0xffe53935);
1597            let source = new_source(tester, false, 0);
1598            let root = app_of(
1599                tester,
1600                PaginatedDataTable::new(standard_columns(), erased(&source))
1601                    .arrow_head_color(arrow_head_color)
1602                    .show_first_last_buttons(true)
1603                    .header(Text::new("Test table")),
1604            );
1605            tester.pump_widget(root);
1606
1607            let icons = find::by_type::<IconButton>();
1608            for index in 0..4 {
1609                assert_eq!(
1610                    tester.widget(icons.clone().at(index), |button: &IconButton| button.color),
1611                    Some(arrow_head_color)
1612                );
1613            }
1614            tester.set_surface_size(None);
1615        });
1616    }
1617
1618    #[test]
1619    fn paginated_data_table_custom_heading_row_color() {
1620        test_widgets(|tester| {
1621            let heading_row_color = Color::new(0xffff0000);
1622            let source = new_source(tester, false, 0);
1623            let root = material_app(
1624                m3(&tester.cell.borrow()),
1625                Scaffold::new()
1626                    .body(
1627                        PaginatedDataTable::new(standard_columns(), erased(&source))
1628                            .primary(true)
1629                            .header(Text::new("Test table"))
1630                            .rows_per_page(2)
1631                            .heading_row_color(Rc::new(WidgetStatePropertyAll::new(Some(
1632                                heading_row_color,
1633                            )))),
1634                    )
1635                    .into_widget(),
1636            );
1637            tester.pump_widget(root);
1638
1639            let color = tester.widget(find::by_type::<Table>(), |table: &Table| {
1640                table.children[0]
1641                    .decoration
1642                    .as_ref()
1643                    .and_then(|decoration| decoration.as_any().downcast_ref::<BoxDecoration>())
1644                    .expect("a BoxDecoration")
1645                    .color
1646                    .clone()
1647                    .map(|color| color.color())
1648            });
1649            assert_eq!(color, Some(heading_row_color));
1650        });
1651    }
1652
1653    fn heading_row_bottom_border_width(tester: &WidgetTester) -> f64 {
1654        expect(tester, &find::by_type::<Table>(), finds_one_widget());
1655        tester.widget(find::by_type::<Table>(), |table: &Table| {
1656            table.children[0]
1657                .decoration
1658                .as_ref()
1659                .and_then(|decoration| decoration.as_any().downcast_ref::<BoxDecoration>())
1660                .expect("a BoxDecoration")
1661                .clone()
1662                .border
1663                .expect("a border")
1664                .bottom()
1665                .width
1666        })
1667    }
1668
1669    #[test]
1670    fn paginated_data_table_respects_custom_divider_thickness() {
1671        test_widgets(|tester| {
1672            let divider_thickness = 2.0;
1673            let source = new_source(tester, false, 0);
1674            let root = material_app(
1675                m3(&tester.cell.borrow()),
1676                Scaffold::new()
1677                    .body(
1678                        PaginatedDataTable::new(standard_columns(), erased(&source))
1679                            .primary(true)
1680                            .header(Text::new("Test table"))
1681                            .rows_per_page(2)
1682                            .divider_thickness(divider_thickness),
1683                    )
1684                    .into_widget(),
1685            );
1686            tester.pump_widget(root);
1687            assert_eq!(heading_row_bottom_border_width(tester), divider_thickness);
1688        });
1689    }
1690
1691    #[test]
1692    fn paginated_data_table_respects_default_divider_thickness() {
1693        test_widgets(|tester| {
1694            let source = new_source(tester, false, 0);
1695            let root = material_app(
1696                m3(&tester.cell.borrow()),
1697                Scaffold::new()
1698                    .body(
1699                        PaginatedDataTable::new(standard_columns(), erased(&source))
1700                            .primary(true)
1701                            .header(Text::new("Test table"))
1702                            .rows_per_page(2),
1703                    )
1704                    .into_widget(),
1705            );
1706            tester.pump_widget(root);
1707            assert_eq!(heading_row_bottom_border_width(tester), 1.0);
1708        });
1709    }
1710
1711    #[test]
1712    fn paginated_data_table_does_not_crash_at_zero_area() {
1713        test_widgets(|tester| {
1714            let source = new_source(tester, false, 0);
1715            let root = app_of(
1716                tester,
1717                Center::new().child(
1718                    SizedBox::shrink().child(
1719                        PaginatedDataTable::new(
1720                            vec![
1721                                DataColumn::new(Text::new("X")),
1722                                DataColumn::new(Text::new("Y")),
1723                                DataColumn::new(Text::new("Z")),
1724                            ],
1725                            erased(&source),
1726                        )
1727                        .into_widget(),
1728                    ),
1729                ),
1730            );
1731            tester.pump_widget(root);
1732            assert_eq!(
1733                tester.get_size(find::by_type::<PaginatedDataTable>()),
1734                Size::ZERO
1735            );
1736        });
1737    }
1738
1739    #[test]
1740    fn paginated_data_table_custom_sort_icon_builder_test() {
1741        test_widgets(|tester| {
1742            let source = new_source(tester, false, 0);
1743            let root = app_of(
1744                tester,
1745                PaginatedDataTable::new(
1746                    vec![
1747                        DataColumn::new(Text::new("Name")).on_sort(|_app, _index, _ascending| {}),
1748                        DataColumn::new(Text::new("Calories")).numeric(true),
1749                        DataColumn::new(Text::new("Generation")),
1750                    ],
1751                    erased(&source),
1752                )
1753                .sort_column_index(0)
1754                .sort_icon_builder(|_app, _context, visible, ascending| {
1755                    Text::new(if visible {
1756                        if ascending {
1757                            "PAGINATED_ASC"
1758                        } else {
1759                            "PAGINATED_DESC"
1760                        }
1761                    } else {
1762                        "PAGINATED_INACTIVE"
1763                    })
1764                    .into_widget()
1765                })
1766                .header(Text::new("Test Table"))
1767                .rows_per_page(2),
1768            );
1769            tester.pump_widget(root);
1770            expect(tester, &find::text("PAGINATED_ASC"), finds_one_widget());
1771        });
1772    }
1773
1774    #[test]
1775    fn paginated_data_table_state_is_reachable_by_a_global_key() {
1776        test_widgets(|tester| {
1777            let source = new_source(tester, false, 0);
1778            let key = GlobalKey::new();
1779            let root = app_of(
1780                tester,
1781                PaginatedDataTable::new(standard_columns(), erased(&source))
1782                    .key(key.clone().into()),
1783            );
1784            tester.pump_widget(root);
1785            let state = key
1786                .current_state::<PaginatedDataTableState>(&tester.cell.borrow())
1787                .expect("the state of the table");
1788            state.page_to(&mut tester.cell.borrow_mut(), 10);
1789            tester.pump();
1790            expect(tester, &find::text("Frozen yogurt (1)"), finds_one_widget());
1791        });
1792    }
1793    /// Dart's `find.byWidgetPredicate((Widget widget) => widget is SizedBox && widget.height == h)`.
1794    fn sized_box_of_height(height: f64) -> Finder {
1795        find::by_widget_predicate("a SizedBox of that height", move |_app, widget| {
1796            waft_widgets::downcast_widget::<SizedBox>(widget)
1797                .is_some_and(|sized_box| sized_box.height == Some(height))
1798        })
1799    }
1800
1801    #[test]
1802    #[allow(deprecated)]
1803    fn paginated_data_table_last_page_empty_space() {
1804        test_widgets(|tester| {
1805            let source = new_source(tester, false, 0);
1806            let row_count = 50 * K_DESSERTS.len();
1807            let build_table = |rows_per_page: usize| -> PaginatedDataTable {
1808                PaginatedDataTable::new(standard_columns(), erased(&source))
1809                    .header(Text::new("Test table"))
1810                    .rows_per_page(rows_per_page)
1811                    .show_first_last_buttons(true)
1812                    .data_row_height(46.0)
1813                    .available_rows_per_page(vec![3, 6, 7, 8, 9])
1814                    .on_rows_per_page_changed(|_app, _rows_per_page| {})
1815                    .on_page_changed(|_app, _row_index| {})
1816                    .show_empty_rows(false)
1817            };
1818            let theme = m3(&tester.cell.borrow());
1819
1820            let root = material_app(
1821                theme.clone(),
1822                Scaffold::new()
1823                    .body(Center::new().child(build_table(3)))
1824                    .into_widget(),
1825            );
1826            tester.pump_widget(root);
1827            expect(tester, &sized_box_of_height(0.0), finds_one_widget());
1828            tester.tap(find::by_icon(&Icons::skip_next()));
1829            tester.pump();
1830            let expected = (3 - (row_count % 3)) as f64 * 46.0;
1831            expect(tester, &sized_box_of_height(expected), finds_one_widget());
1832
1833            for rows_per_page in [6, 7, 8] {
1834                let root = material_app(
1835                    theme.clone(),
1836                    Material::new()
1837                        .child(build_table(rows_per_page))
1838                        .into_widget(),
1839                );
1840                tester.pump_widget(root);
1841                tester.tap(find::by_icon(&Icons::skip_previous()));
1842                tester.pump();
1843                expect(tester, &sized_box_of_height(0.0), finds_one_widget());
1844                tester.tap(find::by_icon(&Icons::skip_next()));
1845                tester.pump();
1846                let expected = (rows_per_page - (row_count % rows_per_page)) as f64 * 46.0;
1847                expect(tester, &sized_box_of_height(expected), finds_one_widget());
1848            }
1849        });
1850    }
1851
1852    #[test]
1853    fn paginated_data_table_footer_scrolls() {
1854        test_widgets(|tester| {
1855            let source = new_source(tester, false, 0);
1856            let theme = m3(&tester.cell.borrow());
1857            tester.pump_widget(material_app(
1858                theme,
1859                Align::new()
1860                    .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
1861                    .child(
1862                        SizedBox::new().width(100.0).child(
1863                            PaginatedDataTable::new(
1864                                vec![
1865                                    DataColumn::new(Text::new("COL1")),
1866                                    DataColumn::new(Text::new("COL2")),
1867                                    DataColumn::new(Text::new("COL3")),
1868                                ],
1869                                erased(&source),
1870                            )
1871                            .header(Text::new("HEADER"))
1872                            .rows_per_page(5)
1873                            .drag_start_behavior(waft_gestures::DragStartBehavior::Down)
1874                            .available_rows_per_page(vec![5])
1875                            .on_rows_per_page_changed(|_app, _rows_per_page| {}),
1876                        ),
1877                    )
1878                    .into_widget(),
1879            ));
1880            expect(tester, &find::text("Rows per page:"), finds_one_widget());
1881            // off screen
1882            assert!(tester.get_top_left(find::text("Rows per page:")).dx() < 0.0);
1883            let y = tester.get_top_left(find::text("Rows per page:")).dy();
1884            let pointer = tester.next_pointer();
1885            tester.drag_from(Offset::new(50.0, y), Offset::new(1000.0, 0.0), pointer);
1886            tester.pump_and_settle();
1887            expect(tester, &find::text("Rows per page:"), finds_one_widget());
1888            // 14 padding in the footer row, 4 padding from the card
1889            assert_eq!(tester.get_top_left(find::text("Rows per page:")).dx(), 18.0);
1890        });
1891    }
1892
1893    #[test]
1894    fn data_row_min_height_and_data_row_max_height_if_not_set_will_use_data_table_theme() {
1895        test_widgets(|tester| {
1896            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1897            let min_max_data_row_height = 30.0;
1898            let source = new_source(tester, true, 0);
1899            let theme = ThemeData::builder()
1900                .data_table_theme(
1901                    DataTableThemeData::new()
1902                        .data_row_min_height(min_max_data_row_height)
1903                        .data_row_max_height(min_max_data_row_height),
1904                )
1905                .build(&tester.cell.borrow());
1906            tester.pump_widget(material_app(
1907                theme,
1908                PaginatedDataTable::new(standard_columns(), erased(&source))
1909                    .header(Text::new("Test table"))
1910                    .into_widget(),
1911            ));
1912
1913            let row_container =
1914                find::descendant(find::by_type::<Table>(), find::by_type::<Container>()).last();
1915            let constraints =
1916                tester.widget(row_container, |container: &Container| container.constraints);
1917            let constraints = constraints.expect("the row container's constraints");
1918            assert_eq!(constraints.min_height, min_max_data_row_height);
1919            assert_eq!(constraints.max_height, min_max_data_row_height);
1920            tester.set_surface_size(None);
1921        });
1922    }
1923
1924    #[test]
1925    fn items_selected_text_uses_secondary_color() {
1926        test_widgets(|tester| {
1927            let selected_text_color = Color::new(0xff00ddff);
1928            let colors = crate::ColorScheme::light().with_secondary(selected_text_color);
1929            let theme = ThemeData::from(colors).build(&tester.cell.borrow());
1930            let source = new_source(tester, true, 0);
1931
1932            tester.set_surface_size(Some(Size::new(800.0, 800.0)));
1933            tester.pump_widget(material_app(
1934                theme,
1935                PaginatedDataTable::new(standard_columns(), erased(&source))
1936                    .header(Text::new("Test table"))
1937                    .into_widget(),
1938            ));
1939            expect(tester, &find::text("Test table"), finds_one_widget());
1940
1941            // Select a row with yogurt
1942            tester.tap(find::text("Frozen yogurt (0)"));
1943            tester.pump_and_settle();
1944
1945            // The header should be replace with a selected text item
1946            expect(tester, &find::text("Test table"), finds_nothing());
1947            expect(tester, &find::text("1 item selected"), finds_one_widget());
1948
1949            // The color of the selected text item should be the colorScheme.secondary
1950            let selected_text_style = paragraph_style(tester, "1 item selected");
1951            assert_eq!(
1952                selected_text_style.color.map(|color| color.color()),
1953                Some(selected_text_color)
1954            );
1955            tester.set_surface_size(None);
1956        });
1957    }
1958
1959    #[test]
1960    fn overflow_bar_header_left_alignment() {
1961        // Test an old special case that tried to align the first child of a ButtonBar
1962        // and the left edge of a Text header widget. Still possible with OverflowBar
1963        // albeit without any special case in the implementation's build method.
1964        test_widgets(|tester| {
1965            let source = new_source(tester, false, 0);
1966            let theme = m3(&tester.cell.borrow());
1967            let build_frame = |header: WidgetRef| {
1968                material_app(
1969                    theme.clone(),
1970                    PaginatedDataTable::new(standard_columns(), erased(&source))
1971                        .header(header)
1972                        .rows_per_page(2)
1973                        .into_widget(),
1974                )
1975            };
1976
1977            tester.pump_widget(build_frame(Text::new("HEADER").into_widget()));
1978            let header_x = tester.get_top_left(find::text("HEADER")).dx();
1979            let overflow_bar = waft_widgets::OverflowBar::new()
1980                .children(vec![
1981                    crate::ElevatedButton::new(
1982                        Some(Listener::new(|_app| {})),
1983                        Some(Text::new("BUTTON")),
1984                    )
1985                    .into_widget(),
1986                ])
1987                .into_widget();
1988            tester.pump_widget(build_frame(overflow_bar));
1989            assert_eq!(
1990                header_x,
1991                tester
1992                    .get_top_left(find::by_type::<crate::ElevatedButton>())
1993                    .dx()
1994            );
1995        });
1996    }
1997
1998    #[test]
1999    fn paginated_data_table_can_be_scrolled_using_scroll_controller() {
2000        test_widgets(|tester| {
2001            let scroll_controller: waft_widgets::ScrollControllerRef =
2002                waft_widgets::ScrollController::default(&mut tester.cell.borrow_mut())
2003                    .into_erased();
2004            let source = new_source(tester, false, 0);
2005            let theme = m3(&tester.cell.borrow());
2006            tester.pump_widget(material_app(
2007                theme,
2008                Align::new()
2009                    .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
2010                    .child(
2011                        SizedBox::new().width(100.0).child(
2012                            PaginatedDataTable::new(
2013                                vec![
2014                                    DataColumn::new(Text::new("Name")).tooltip("Name"),
2015                                    DataColumn::new(Text::new("Calories"))
2016                                        .tooltip("Calories")
2017                                        .numeric(true),
2018                                    DataColumn::new(Text::new("Generation")).tooltip("Generation"),
2019                                ],
2020                                erased(&source),
2021                            )
2022                            .controller(scroll_controller.clone())
2023                            .header(Text::new("Test table"))
2024                            .rows_per_page(2),
2025                        ),
2026                    )
2027                    .into_widget(),
2028            ));
2029
2030            // DataTable uses provided ScrollController
2031            let body_controller = tester.widget(
2032                find::by_type::<waft_widgets::Scrollable>().first(),
2033                |scrollable: &waft_widgets::Scrollable| scrollable.controller.clone(),
2034            );
2035            assert!(body_controller.as_ref() == Some(&scroll_controller));
2036
2037            assert_eq!(scroll_controller.offset(&tester.cell.borrow()), 0.0);
2038            scroll_controller.jump_to(&mut tester.cell.borrow_mut(), 50.0);
2039            tester.pump_and_settle();
2040
2041            assert_eq!(scroll_controller.offset(&tester.cell.borrow()), 50.0);
2042        });
2043    }
2044
2045    #[test]
2046    fn paginated_data_table_uses_primary_scroll_controller_when_primary() {
2047        test_widgets(|tester| {
2048            let primary_scroll_controller: waft_widgets::ScrollControllerRef =
2049                waft_widgets::ScrollController::default(&mut tester.cell.borrow_mut())
2050                    .into_erased();
2051            let source = new_source(tester, false, 0);
2052            let theme = m3(&tester.cell.borrow());
2053            tester.pump_widget(material_app(
2054                theme,
2055                waft_widgets::PrimaryScrollController::new(
2056                    primary_scroll_controller.clone(),
2057                    PaginatedDataTable::new(standard_columns(), erased(&source))
2058                        .primary(true)
2059                        .header(Text::new("Test table"))
2060                        .rows_per_page(2),
2061                )
2062                .into_widget(),
2063            ));
2064
2065            // DataTable uses primaryScrollController
2066            let body_controller = tester.widget(
2067                find::by_type::<waft_widgets::Scrollable>().first(),
2068                |scrollable: &waft_widgets::Scrollable| scrollable.controller.clone(),
2069            );
2070            assert!(body_controller.as_ref() == Some(&primary_scroll_controller));
2071
2072            // Footer does not use primaryScrollController
2073            let footer_controller = tester.widget(
2074                find::by_type::<waft_widgets::Scrollable>().last(),
2075                |scrollable: &waft_widgets::Scrollable| scrollable.controller.clone(),
2076            );
2077            assert!(footer_controller.is_none());
2078        });
2079    }
2080    #[test]
2081    #[allow(deprecated)]
2082    fn paginated_data_table_custom_row_height() {
2083        test_widgets(|tester| {
2084            let source = new_source(tester, false, 0);
2085            let theme = m3(&tester.cell.borrow());
2086            let height_of = |tester: &WidgetTester, text: &str| {
2087                tester
2088                    .get_size(find::widget_with_text::<Container>(text).first())
2089                    .height()
2090            };
2091            let build_table = |heading_row_height: f64,
2092                               data_row_height: Option<f64>,
2093                               min_max: Option<(f64, f64)>| {
2094                let mut table = PaginatedDataTable::new(standard_columns(), erased(&source))
2095                    .header(Text::new("Test table"))
2096                    .rows_per_page(2)
2097                    .available_rows_per_page(vec![2, 4, 8, 16])
2098                    .on_rows_per_page_changed(|_app, _rows_per_page| {})
2099                    .on_page_changed(|_app, _row_index| {})
2100                    .heading_row_height(heading_row_height);
2101                if let Some(data_row_height) = data_row_height {
2102                    table = table.data_row_height(data_row_height);
2103                }
2104                if let Some((min, max)) = min_max {
2105                    table = table.data_row_min_height(min).data_row_max_height(max);
2106                }
2107                material_app(theme.clone(), Material::new().child(table).into_widget())
2108            };
2109
2110            // DEFAULT VALUES
2111            let root = material_app(
2112                theme.clone(),
2113                PaginatedDataTable::new(standard_columns(), erased(&source))
2114                    .header(Text::new("Test table"))
2115                    .rows_per_page(2)
2116                    .available_rows_per_page(vec![2, 4, 8, 16])
2117                    .on_rows_per_page_changed(|_app, _rows_per_page| {})
2118                    .on_page_changed(|_app, _row_index| {})
2119                    .into_widget(),
2120            );
2121            tester.pump_widget(root);
2122            // This is the header row height
2123            assert_eq!(height_of(tester, "Name"), 56.0);
2124            // This is the data row height
2125            assert_eq!(height_of(tester, "Frozen yogurt (0)"), 48.0);
2126
2127            // CUSTOM VALUES
2128            tester.pump_widget(build_table(48.0, None, None));
2129            assert_eq!(height_of(tester, "Name"), 48.0);
2130
2131            tester.pump_widget(build_table(64.0, None, None));
2132            assert_eq!(height_of(tester, "Name"), 64.0);
2133
2134            tester.pump_widget(build_table(56.0, Some(30.0), None));
2135            assert_eq!(height_of(tester, "Frozen yogurt (0)"), 30.0);
2136
2137            tester.pump_widget(build_table(56.0, Some(56.0), None));
2138            assert_eq!(height_of(tester, "Frozen yogurt (0)"), 56.0);
2139
2140            tester.pump_widget(build_table(56.0, None, Some((51.0, 51.0))));
2141            assert_eq!(height_of(tester, "Frozen yogurt (0)"), 51.0);
2142        });
2143    }
2144
2145    #[test]
2146    fn paginated_data_table_custom_checkbox_horizontal_margin_properly_applied() {
2147        test_widgets(|tester| {
2148            let custom_checkbox_horizontal_margin = 15.0;
2149            let custom_horizontal_margin = 10.0;
2150            // Ensure the containing Card is small enough that we don't expand too much,
2151            // resulting in our custom margin being ignored.
2152            tester.set_surface_size(Some(Size::new(400.0, 400.0)));
2153            let source = new_source(tester, true, 0);
2154            let theme = m3(&tester.cell.borrow());
2155
2156            tester.pump_widget(material_app(
2157                theme,
2158                Material::new()
2159                    .child(
2160                        PaginatedDataTable::new(standard_columns(), erased(&source))
2161                            .header(Text::new("Test table"))
2162                            .rows_per_page(2)
2163                            .available_rows_per_page(vec![2, 4])
2164                            .on_rows_per_page_changed(|_app, _rows_per_page| {})
2165                            .on_page_changed(|_app, _row_index| {})
2166                            .on_select_all(|_app, _value| {})
2167                            .horizontal_margin(custom_horizontal_margin)
2168                            .checkbox_horizontal_margin(custom_checkbox_horizontal_margin),
2169                    )
2170                    .into_widget(),
2171            ));
2172
2173            // Custom checkbox padding.
2174            let checkbox = find::by_type::<Checkbox>().first();
2175            let padding = find::ancestor(checkbox.clone(), find::by_type::<Padding>()).first();
2176            assert_eq!(
2177                tester.get_rect(checkbox.clone()).left - tester.get_rect(padding.clone()).left,
2178                custom_checkbox_horizontal_margin
2179            );
2180            assert_eq!(
2181                tester.get_rect(padding).right - tester.get_rect(checkbox).right,
2182                custom_checkbox_horizontal_margin
2183            );
2184
2185            // Custom first column padding.
2186            let padding = find::widget_with_text::<Padding>("Frozen yogurt (0)").first();
2187            // DataTable wraps its DataCells in an Align widget.
2188            let cell_content = find::widget_with_text::<Align>("Frozen yogurt (0)");
2189            assert_eq!(
2190                tester.get_rect(cell_content).left - tester.get_rect(padding).left,
2191                custom_horizontal_margin
2192            );
2193            tester.set_surface_size(None);
2194        });
2195    }
2196}