|
16 | 16 |
|
17 | 17 | from __future__ import annotations |
18 | 18 |
|
| 19 | +import dataclasses |
19 | 20 | from importlib import resources |
20 | 21 | import functools |
21 | 22 | import math |
|
28 | 29 | from bigframes.core import blocks |
29 | 30 | import bigframes.dataframe |
30 | 31 | import bigframes.display.html |
| 32 | +import bigframes.dtypes as dtypes |
31 | 33 |
|
32 | 34 | # anywidget and traitlets are optional dependencies. We don't want the import of |
33 | 35 | # this module to fail if they aren't installed, though. Instead, we try to |
|
48 | 50 | WIDGET_BASE = object |
49 | 51 |
|
50 | 52 |
|
| 53 | +@dataclasses.dataclass(frozen=True) |
| 54 | +class _SortState: |
| 55 | + column: str |
| 56 | + ascending: bool |
| 57 | + |
| 58 | + |
51 | 59 | class TableWidget(WIDGET_BASE): |
52 | 60 | """An interactive, paginated table widget for BigFrames DataFrames. |
53 | 61 |
|
@@ -63,6 +71,9 @@ class TableWidget(WIDGET_BASE): |
63 | 71 | allow_none=True, |
64 | 72 | ).tag(sync=True) |
65 | 73 | table_html = traitlets.Unicode().tag(sync=True) |
| 74 | + sort_column = traitlets.Unicode("").tag(sync=True) |
| 75 | + sort_ascending = traitlets.Bool(True).tag(sync=True) |
| 76 | + orderable_columns = traitlets.List(traitlets.Unicode(), []).tag(sync=True) |
66 | 77 | _initial_load_complete = traitlets.Bool(False).tag(sync=True) |
67 | 78 | _batches: Optional[blocks.PandasBatches] = None |
68 | 79 | _error_message = traitlets.Unicode(allow_none=True, default_value=None).tag( |
@@ -89,15 +100,25 @@ def __init__(self, dataframe: bigframes.dataframe.DataFrame): |
89 | 100 | self._all_data_loaded = False |
90 | 101 | self._batch_iter: Optional[Iterator[pd.DataFrame]] = None |
91 | 102 | self._cached_batches: List[pd.DataFrame] = [] |
| 103 | + self._last_sort_state: Optional[_SortState] = None |
92 | 104 |
|
93 | 105 | # respect display options for initial page size |
94 | 106 | initial_page_size = bigframes.options.display.max_rows |
95 | 107 |
|
96 | 108 | # set traitlets properties that trigger observers |
| 109 | + # TODO(b/462525985): Investigate and improve TableWidget UX for DataFrames with a large number of columns. |
97 | 110 | self.page_size = initial_page_size |
| 111 | + # TODO(b/463754889): Support non-string column labels for sorting. |
| 112 | + if all(isinstance(col, str) for col in dataframe.columns): |
| 113 | + self.orderable_columns = [ |
| 114 | + str(col_name) |
| 115 | + for col_name, dtype in dataframe.dtypes.items() |
| 116 | + if dtypes.is_orderable(dtype) |
| 117 | + ] |
| 118 | + else: |
| 119 | + self.orderable_columns = [] |
98 | 120 |
|
99 | | - # len(dataframe) is expensive, since it will trigger a |
100 | | - # SELECT COUNT(*) query. It is a must have however. |
| 121 | + # obtain the row counts |
101 | 122 | # TODO(b/428238610): Start iterating over the result of `to_pandas_batches()` |
102 | 123 | # before we get here so that the count might already be cached. |
103 | 124 | self._reset_batches_for_new_page_size() |
@@ -121,6 +142,11 @@ def __init__(self, dataframe: bigframes.dataframe.DataFrame): |
121 | 142 | # Also used as a guard to prevent observers from firing during initialization. |
122 | 143 | self._initial_load_complete = True |
123 | 144 |
|
| 145 | + @traitlets.observe("_initial_load_complete") |
| 146 | + def _on_initial_load_complete(self, change: Dict[str, Any]): |
| 147 | + if change["new"]: |
| 148 | + self._set_table_html() |
| 149 | + |
124 | 150 | @functools.cached_property |
125 | 151 | def _esm(self): |
126 | 152 | """Load JavaScript code from external file.""" |
@@ -221,13 +247,17 @@ def _cached_data(self) -> pd.DataFrame: |
221 | 247 | return pd.DataFrame(columns=self._dataframe.columns) |
222 | 248 | return pd.concat(self._cached_batches, ignore_index=True) |
223 | 249 |
|
| 250 | + def _reset_batch_cache(self) -> None: |
| 251 | + """Resets batch caching attributes.""" |
| 252 | + self._cached_batches = [] |
| 253 | + self._batch_iter = None |
| 254 | + self._all_data_loaded = False |
| 255 | + |
224 | 256 | def _reset_batches_for_new_page_size(self) -> None: |
225 | 257 | """Reset the batch iterator when page size changes.""" |
226 | 258 | self._batches = self._dataframe._to_pandas_batches(page_size=self.page_size) |
227 | 259 |
|
228 | | - self._cached_batches = [] |
229 | | - self._batch_iter = None |
230 | | - self._all_data_loaded = False |
| 260 | + self._reset_batch_cache() |
231 | 261 |
|
232 | 262 | def _set_table_html(self) -> None: |
233 | 263 | """Sets the current html data based on the current page and page size.""" |
@@ -237,6 +267,21 @@ def _set_table_html(self) -> None: |
237 | 267 | ) |
238 | 268 | return |
239 | 269 |
|
| 270 | + # Apply sorting if a column is selected |
| 271 | + df_to_display = self._dataframe |
| 272 | + if self.sort_column: |
| 273 | + # TODO(b/463715504): Support sorting by index columns. |
| 274 | + df_to_display = df_to_display.sort_values( |
| 275 | + by=self.sort_column, ascending=self.sort_ascending |
| 276 | + ) |
| 277 | + |
| 278 | + # Reset batches when sorting changes |
| 279 | + if self._last_sort_state != _SortState(self.sort_column, self.sort_ascending): |
| 280 | + self._batches = df_to_display._to_pandas_batches(page_size=self.page_size) |
| 281 | + self._reset_batch_cache() |
| 282 | + self._last_sort_state = _SortState(self.sort_column, self.sort_ascending) |
| 283 | + self.page = 0 # Reset to first page |
| 284 | + |
240 | 285 | start = self.page * self.page_size |
241 | 286 | end = start + self.page_size |
242 | 287 |
|
@@ -272,8 +317,14 @@ def _set_table_html(self) -> None: |
272 | 317 | self.table_html = bigframes.display.html.render_html( |
273 | 318 | dataframe=page_data, |
274 | 319 | table_id=f"table-{self._table_id}", |
| 320 | + orderable_columns=self.orderable_columns, |
275 | 321 | ) |
276 | 322 |
|
| 323 | + @traitlets.observe("sort_column", "sort_ascending") |
| 324 | + def _sort_changed(self, _change: Dict[str, Any]): |
| 325 | + """Handler for when sorting parameters change from the frontend.""" |
| 326 | + self._set_table_html() |
| 327 | + |
277 | 328 | @traitlets.observe("page") |
278 | 329 | def _page_changed(self, _change: Dict[str, Any]) -> None: |
279 | 330 | """Handler for when the page number is changed from the frontend.""" |
@@ -288,6 +339,9 @@ def _page_size_changed(self, _change: Dict[str, Any]) -> None: |
288 | 339 | return |
289 | 340 | # Reset the page to 0 when page size changes to avoid invalid page states |
290 | 341 | self.page = 0 |
| 342 | + # Reset the sort state to default (no sort) |
| 343 | + self.sort_column = "" |
| 344 | + self.sort_ascending = True |
291 | 345 |
|
292 | 346 | # Reset batches to use new page size for future data fetching |
293 | 347 | self._reset_batches_for_new_page_size() |
|