Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tabulator: fix the edit event with a python filter #3829

Merged
merged 4 commits into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions panel/reactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,6 @@ class ReactiveData(SyncableData):

def __init__(self, **params):
super().__init__(**params)
self._old = None

def _update_selection(self, indices: List[int]) -> None:
self.selection = indices
Expand Down Expand Up @@ -1054,10 +1053,9 @@ def _convert_column(
def _process_data(self, data: Mapping[str, List | Dict[int, Any] | np.ndarray]) -> None:
if self._updating:
return

# Get old data to compare to
old_raw, old_data = self._get_data()
self._old = old_raw = old_raw.copy()
old_raw = old_raw.copy()
if hasattr(old_raw, 'columns'):
columns = list(old_raw.columns) # type: ignore
else:
Expand Down
43 changes: 43 additions & 0 deletions panel/tests/ui/widgets/test_tabulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3210,3 +3210,46 @@ def test_tabulator_sort_algorithm_by_type(page, port, col, vals):
page,
lambda: client_index == list(widget.current_view.index)
)


def test_tabulator_python_filter_edit(page, port):
df = pd.DataFrame({
'values': ['A', 'A', 'B', 'B'],
}, index=['idx0', 'idx1', 'idx2', 'idx3'])

widget = Tabulator(df)

fltr, col = 'B', 'values'
widget.add_filter(fltr, col)

values = []
widget.on_edit(lambda e: values.append((e.column, e.row, e.old, e.value)))

serve(widget, port=port, threaded=True, show=False)

time.sleep(0.2)

page.goto(f"http://localhost:{port}")

# Check the table has the right number of rows
expect(page.locator('.tabulator-row')).to_have_count(2)

cell = page.locator('text="B"').nth(1)
cell.click()
editable_cell = page.locator('input[type="text"]')
editable_cell.fill("X")
editable_cell.press('Enter')

wait_until(page, lambda: len(values) == 1)
assert values[0] == ('values', len(df) - 1, 'B', 'X')
assert df.at['idx3', 'values'] == 'X'

cell = page.locator('text="X"')
cell.click()
editable_cell = page.locator('input[type="text"]')
editable_cell.fill("Y")
editable_cell.press('Enter')

wait_until(page, lambda: len(values) == 2)
assert values[-1] == ('values', len(df) - 1, 'X', 'Y')
assert df.at['idx3', 'values'] == 'Y'
18 changes: 12 additions & 6 deletions panel/widgets/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,7 @@ def __init__(self, value=None, **params):
self._explicit_pagination = 'pagination' in params
self._on_edit_callbacks = []
self._on_click_callbacks = {}
self._old_value = None
super().__init__(value=value, **params)
self._configuration = configuration
self.param.watch(self._update_children, self._content_params)
Expand Down Expand Up @@ -1131,6 +1132,8 @@ def _cleanup(self, root: Model | None = None) -> None:
super()._cleanup(root)

def _process_event(self, event):
if not self._on_click_callbacks and not self._on_edit_callbacks:
return
event_col = self._renamed_cols.get(event.column, event.column)
processed = self._sort_df(self._processed)
if self.pagination in ['local', 'remote']:
Expand All @@ -1142,19 +1145,17 @@ def _process_event(self, event):
event.value = processed.index[event_row]
else:
event.value = processed[event_col].iloc[event_row]
# Set the old attribute on a table edit event
if event.event_name == 'table-edit' and self._old is not None:
old_processed = self._sort_df(self._old)
event.old = old_processed[event_col].iloc[event_row]
# We want to return the index of the original `value` dataframe.
if self._filters or self.filters or self.sorters:
idx = processed.index[event.row]
iloc = self.value.index.get_loc(idx)
self._validate_iloc(idx, iloc)
event.row = iloc
# Set the old attribute on a table edit event
if event.event_name == 'table-edit' and self._old_value is not None:
event.old = self._old_value[event_col].iloc[event.row]
if event.event_name == 'table-edit':
for cb in self._on_edit_callbacks:
print(cb)
state.execute(partial(cb, event))
self._update_style()
else:
Expand Down Expand Up @@ -1213,7 +1214,12 @@ def _process_data(self, data):
# _processed data is already filtered, this made the comparison between
# the new data and old data wrong. This extension replicates the
# front-end filtering - if need be - to be able to correctly make the
# comparison and update the data hold by the backend.
# comparison and update the data held by the backend.

# It also makes a copy of the value dataframe, to use it to obtain
# the old value in a table-edit event.
self._old_value = self.value.copy()

if not self.filters:
return super()._process_data(data)
import pandas as pd
Expand Down