|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import uuid |
| 16 | + |
| 17 | +import anywidget # type: ignore |
| 18 | +import pandas as pd |
| 19 | +import traitlets |
| 20 | + |
| 21 | +import bigframes |
| 22 | + |
| 23 | + |
| 24 | +class TableWidget(anywidget.AnyWidget): |
| 25 | + """ |
| 26 | + An interactive, paginated table widget for BigFrames DataFrames. |
| 27 | + """ |
| 28 | + |
| 29 | + _esm = """ |
| 30 | + function render({ model, el }) { |
| 31 | + const container = document.createElement('div'); |
| 32 | + container.innerHTML = model.get('table_html'); |
| 33 | +
|
| 34 | + const buttonContainer = document.createElement('div'); |
| 35 | + const prevPage = document.createElement('button'); |
| 36 | + const label = document.createElement('span'); |
| 37 | + const nextPage = document.createElement('button'); |
| 38 | + prevPage.type = 'button'; |
| 39 | + nextPage.type = 'button'; |
| 40 | + prevPage.textContent = 'Prev'; |
| 41 | + nextPage.textContent = 'Next'; |
| 42 | +
|
| 43 | + // update button states and label |
| 44 | + function updateButtonStates() { |
| 45 | + const totalPages = Math.ceil(model.get('row_count') / model.get('page_size')); |
| 46 | + const currentPage = model.get('page'); |
| 47 | +
|
| 48 | + // Update label |
| 49 | + label.textContent = `Page ${currentPage + 1} of ${totalPages}`; |
| 50 | +
|
| 51 | + // Update button states |
| 52 | + prevPage.disabled = currentPage === 0; |
| 53 | + nextPage.disabled = currentPage >= totalPages - 1; |
| 54 | + } |
| 55 | +
|
| 56 | + // Initial button state setup |
| 57 | + updateButtonStates(); |
| 58 | +
|
| 59 | + prevPage.addEventListener('click', () => { |
| 60 | + let newPage = model.get('page') - 1; |
| 61 | + if (newPage < 0) { |
| 62 | + newPage = 0; |
| 63 | + } |
| 64 | + console.log(`Setting page to ${newPage}`) |
| 65 | + model.set('page', newPage); |
| 66 | + model.save_changes(); |
| 67 | + }); |
| 68 | +
|
| 69 | + nextPage.addEventListener('click', () => { |
| 70 | + const newPage = model.get('page') + 1; |
| 71 | + console.log(`Setting page to ${newPage}`) |
| 72 | + model.set('page', newPage); |
| 73 | + model.save_changes(); |
| 74 | + }); |
| 75 | +
|
| 76 | + model.on('change:table_html', () => { |
| 77 | + container.innerHTML = model.get('table_html'); |
| 78 | + updateButtonStates(); // Update button states when table changes |
| 79 | + }); |
| 80 | +
|
| 81 | + buttonContainer.appendChild(prevPage); |
| 82 | + buttonContainer.appendChild(label); |
| 83 | + buttonContainer.appendChild(nextPage); |
| 84 | + el.appendChild(container); |
| 85 | + el.appendChild(buttonContainer); |
| 86 | + } |
| 87 | + export default { render }; |
| 88 | + """ |
| 89 | + |
| 90 | + page = traitlets.Int(0).tag(sync=True) |
| 91 | + page_size = traitlets.Int(25).tag(sync=True) |
| 92 | + row_count = traitlets.Int(0).tag(sync=True) |
| 93 | + table_html = traitlets.Unicode().tag(sync=True) |
| 94 | + |
| 95 | + def __init__(self, dataframe): |
| 96 | + """ |
| 97 | + Initialize the TableWidget. |
| 98 | +
|
| 99 | + Args: |
| 100 | + dataframe: The Bigframes Dataframe to display |
| 101 | + """ |
| 102 | + super().__init__() |
| 103 | + self._dataframe = dataframe |
| 104 | + |
| 105 | + # respect display options |
| 106 | + self.page_size = bigframes.options.display.max_rows |
| 107 | + |
| 108 | + self._batches = dataframe.to_pandas_batches(page_size=self.page_size) |
| 109 | + self._cached_data = pd.DataFrame(columns=self._dataframe.columns) |
| 110 | + self._table_id = str(uuid.uuid4()) |
| 111 | + self._all_data_loaded = False |
| 112 | + |
| 113 | + # store the iterator as an instance variable |
| 114 | + self._batch_iterator = None |
| 115 | + |
| 116 | + # len(dataframe) is expensive, since it will trigger a |
| 117 | + # SELECT COUNT(*) query. It is a must have however. |
| 118 | + self.row_count = len(dataframe) |
| 119 | + |
| 120 | + # get the initial page |
| 121 | + self._set_table_html() |
| 122 | + |
| 123 | + def _get_next_batch(self): |
| 124 | + """Gets the next batch of data from the batches generator.""" |
| 125 | + if self._all_data_loaded: |
| 126 | + return False |
| 127 | + |
| 128 | + try: |
| 129 | + iterator = self._get_batch_iterator() |
| 130 | + batch = next(iterator) |
| 131 | + self._cached_data = pd.concat([self._cached_data, batch], ignore_index=True) |
| 132 | + return True |
| 133 | + except StopIteration: |
| 134 | + self._all_data_loaded = True |
| 135 | + # update row count if we loaded all data |
| 136 | + if self.row_count == 0: |
| 137 | + self.row_count = len(self._cached_data) |
| 138 | + return False |
| 139 | + except Exception as e: |
| 140 | + raise RuntimeError(f"Error during batch processing: {str(e)}") from e |
| 141 | + |
| 142 | + def _get_batch_iterator(self): |
| 143 | + """Get batch Iterator.""" |
| 144 | + if self._batch_iterator is None: |
| 145 | + self._batch_iterator = iter(self._batches) |
| 146 | + return self._batch_iterator |
| 147 | + |
| 148 | + def _set_table_html(self): |
| 149 | + """Sets the current html data based on the current page and page size.""" |
| 150 | + start = self.page * self.page_size |
| 151 | + end = start + self.page_size |
| 152 | + |
| 153 | + # fetch more dat if the requested page is outside our cache |
| 154 | + while len(self._cached_data) < end: |
| 155 | + prev_len = len(self._cached_data) |
| 156 | + self._get_next_batch() |
| 157 | + if len(self._cached_data) == prev_len: |
| 158 | + break |
| 159 | + # Get the data fro the current page |
| 160 | + page_data = self._cached_data.iloc[start:end] |
| 161 | + |
| 162 | + # Generate HTML table |
| 163 | + self.table_html = page_data.to_html( |
| 164 | + index=False, |
| 165 | + max_rows=None, |
| 166 | + table_id=f"table-{self._table_id}", |
| 167 | + classes="table table-striped table-hover", |
| 168 | + escape=False, |
| 169 | + ) |
| 170 | + |
| 171 | + @traitlets.observe("page") |
| 172 | + def _page_changed(self, change): |
| 173 | + """Handler for when the page nubmer is changed from the frontend""" |
| 174 | + self._set_table_html() |
0 commit comments