Skip to main content

waft_material/
data_table_source.rs

1//! Flutter counterpart: material_ui's `data_table_source.dart`.
2
3use std::any::TypeId;
4use std::fmt::{self, Debug};
5
6use waft_foundation::{App, Handle, HandleId, Listenable, ListenableObject, Listener, Retained};
7
8use crate::data_table::DataRow;
9
10/// A data source for obtaining row data for [`PaginatedDataTable`](crate::PaginatedDataTable)
11/// objects.
12///
13/// A data table source provides two main pieces of information:
14///
15///  * The number of rows in the data table ([`row_count`](Self::row_count)).
16///  * The data for each row (indexed from `0` to `row_count - 1`).
17///
18/// It also provides some control over sort indicators and which rows are selected.
19///
20/// The data source is expected to expose some mechanism for sorting the data. To retrieve a
21/// row's data, [`get_row`](Self::get_row) is called with the row's index. The data source
22/// notifies its listeners whenever the data changes. It is the data source's responsibility to
23/// be a `ChangeNotifier`, which gives it its [`ListenableObject`] side.
24///
25/// Dart's abstract `DataTableSource extends ChangeNotifier`: a data source is an arena object
26/// that holds `ChangeNotifierData` and implements `ChangeNotifier`.
27pub trait DataTableSource: ListenableObject {
28    /// Called to obtain the data about a particular row.
29    ///
30    /// Rows should be keyed so that state can be maintained when the data source is sorted
31    /// (e.g. with `DataRow::by_index`).
32    ///
33    /// Return `None` if the data for this row is unavailable (for example, if the row is
34    /// still being loaded). The table will show a progress indicator for the first unavailable
35    /// row of each page.
36    ///
37    /// If the given index is greater than or equal to [`row_count`](Self::row_count), this
38    /// method should return `None` (but if [`is_row_count_approximate`](Self::is_row_count_approximate)
39    /// is true, it may instead return a row for the data not yet loaded).
40    fn get_row(self: Handle<Self>, app: &mut App, index: usize) -> Option<DataRow>;
41
42    /// Called to obtain the number of rows to tell the user are available.
43    ///
44    /// If [`is_row_count_approximate`](Self::is_row_count_approximate) is false, then this
45    /// must be an accurate number, and [`get_row`](Self::get_row) must return a non-null value
46    /// for all indices in the range 0 to one less than the row count.
47    ///
48    /// If [`is_row_count_approximate`](Self::is_row_count_approximate) is true, then this must
49    /// be an estimate.
50    fn row_count(self: Handle<Self>, app: &App) -> usize;
51
52    /// Called to establish if [`row_count`](Self::row_count) is a precise number or might be
53    /// an over-estimate. If this returns true (i.e. the count is approximate), and then later
54    /// the exact number becomes available, then call `notify_listeners`.
55    fn is_row_count_approximate(self: Handle<Self>, app: &App) -> bool;
56
57    /// Called to obtain the number of rows that are currently selected.
58    ///
59    /// If the selected row count changes, call `notify_listeners`.
60    ///
61    /// Selected rows are those whose [`DataRow::selected`] property is set to true.
62    fn selected_row_count(self: Handle<Self>, app: &App) -> usize;
63
64    /// The type-erased `DataTableSource` handle. Free: the vtable is a `const`, and the id is
65    /// copied.
66    fn as_data_table_source(self: Handle<Self>) -> AnyDataTableSource {
67        AnyDataTableSource {
68            id: self.id(),
69            vtable: const { &DataTableSourceVTable::of::<Self>() },
70        }
71    }
72}
73
74/// The vtable of an erased [`AnyDataTableSource`]: one `&'static` table per concrete
75/// [`DataTableSource`] type.
76struct DataTableSourceVTable {
77    type_name: fn() -> &'static str,
78    add_listener: fn(&mut App, HandleId, Listener),
79    remove_listener: fn(&mut App, HandleId, &Listener),
80    get_row: fn(&mut App, HandleId, usize) -> Option<DataRow>,
81    row_count: fn(&App, HandleId) -> usize,
82    is_row_count_approximate: fn(&App, HandleId) -> bool,
83    selected_row_count: fn(&App, HandleId) -> usize,
84    runtime_type: fn() -> TypeId,
85}
86
87impl DataTableSourceVTable {
88    const fn of<T: DataTableSource>() -> DataTableSourceVTable {
89        DataTableSourceVTable {
90            type_name: std::any::type_name::<T>,
91            runtime_type: TypeId::of::<T>,
92            add_listener: |app, id, listener| {
93                ListenableObject::add_listener(Handle::<T>::from_id(id), app, listener)
94            },
95            remove_listener: |app, id, listener| {
96                ListenableObject::remove_listener(Handle::<T>::from_id(id), app, listener)
97            },
98            get_row: |app, id, index| T::get_row(Handle::<T>::from_id(id), app, index),
99            row_count: |app, id| T::row_count(Handle::<T>::from_id(id), app),
100            is_row_count_approximate: |app, id| {
101                T::is_row_count_approximate(Handle::<T>::from_id(id), app)
102            },
103            selected_row_count: |app, id| T::selected_row_count(Handle::<T>::from_id(id), app),
104        }
105    }
106}
107
108/// Erased [`DataTableSource`]: what a field or parameter Dart types as `DataTableSource`
109/// becomes.
110///
111/// Equality is Dart's `==` on an object reference.
112#[derive(Clone, Copy)]
113pub struct AnyDataTableSource {
114    id: HandleId,
115    vtable: &'static DataTableSourceVTable,
116}
117
118/// A field Dart types as the erased object, kept: [`AnyDataTableSource`] with its count.
119pub type DataTableSourceRef = Retained<AnyDataTableSource>;
120
121waft_foundation::erased_handle!(AnyDataTableSource: DataTableSource => DataTableSource::as_data_table_source);
122
123impl AnyDataTableSource {
124    /// The arena id behind this handle.
125    pub fn id(self) -> HandleId {
126        self.id
127    }
128
129    /// Dart's `runtimeType`.
130    pub fn runtime_type(self) -> TypeId {
131        (self.vtable.runtime_type)()
132    }
133
134    /// Dart's `source as S`: the typed handle when this source is an `S`, else `None`.
135    pub fn downcast<S: 'static>(self, app: &App) -> Option<Handle<S>> {
136        app.handle::<S>(self.id)
137    }
138
139    /// See [`DataTableSource::get_row`].
140    pub fn get_row(self, app: &mut App, index: usize) -> Option<DataRow> {
141        (self.vtable.get_row)(app, self.id, index)
142    }
143
144    /// See [`DataTableSource::row_count`].
145    pub fn row_count(self, app: &App) -> usize {
146        (self.vtable.row_count)(app, self.id)
147    }
148
149    /// See [`DataTableSource::is_row_count_approximate`].
150    pub fn is_row_count_approximate(self, app: &App) -> bool {
151        (self.vtable.is_row_count_approximate)(app, self.id)
152    }
153
154    /// See [`DataTableSource::selected_row_count`].
155    pub fn selected_row_count(self, app: &App) -> usize {
156        (self.vtable.selected_row_count)(app, self.id)
157    }
158}
159
160impl Debug for AnyDataTableSource {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
163    }
164}
165
166impl Listenable for AnyDataTableSource {
167    fn add_listener(&self, app: &mut App, listener: Listener) {
168        (self.vtable.add_listener)(app, self.id, listener)
169    }
170
171    fn remove_listener(&self, app: &mut App, listener: &Listener) {
172        (self.vtable.remove_listener)(app, self.id, listener)
173    }
174}