holoviz/panel · #9128

fix: Fire Tabulator on_edit when its edit event arrives after the data patch

philippjfr · merged Nov 20, 20263 files · 151 + / 8 −
panel/tests/widgets/test_tables.py81 + / 1 −
@@ -27,7 +27,7 @@     async_wait_until, mpl_available, serve_and_request, wait_until, ) from panel.widgets import Button, TextInput-from panel.widgets.tables import DataFrame, Tabulator+from panel.widgets.tables import DataFrame, Tabulator, _values_equal  pd_old = pytest.mark.skipif(Version(pd.__version__) < Version('1.3'),                             reason="Requires latest pandas")@@ -3071,6 +3071,86 @@ def test_server_edit_event():     assert events[0].old == 1  +@pytest.mark.parametrize('value', [3.14, np.nan])+def test_tabulator_edit_event_after_patch(document, comm, value):+    # An edit event deferred while the document is busy is processed after the patch.+    table = Tabulator(makeMixedDataFrame())+    model = table.get_root(document, comm)++    events = []+    table.on_edit(lambda e: events.append(e))++    new_data = dict(model.source.data)+    new_data['B'] = new_data['B'].copy()+    new_data['B'][1] = value+    table._process_events({'data': new_data})+    assert events == []++    table._process_event(TableEditEvent(model, 'B', 1, value=value, old=1))++    assert len(events) == 1+    assert events[0].old == 1+    np.testing.assert_equal(events[0].value, value)++    table._process_events({'data': new_data})+    assert len(events) == 1+    assert table._pending_edits == {}+++@pytest.mark.parametrize('dtype', ['Float64', 'Int64'])+def test_tabulator_edit_event_after_patch_masked_na(document, comm, dtype):+    table = Tabulator(pd.DataFrame({'A': pd.array([1, 2, 3], dtype=dtype)}))+    model = table.get_root(document, comm)+    events = []+    table.on_edit(events.append)++    table._process_events({'data': dict(model.source.data, A=np.array([1, np.nan, 3]))})+    table._process_event(TableEditEvent(model, 'A', 1, value=np.nan, old=2))++    assert len(events) == 1+    assert table._pending_edits == {}+++def test_tabulator_edit_event_revert_before_patch(document, comm):+    # The cell holds the reverted value only because the first patch has not+    # landed, so the second edit must wait instead of firing first.+    table = Tabulator(pd.DataFrame({'A': [1, 2, 3]}))+    model = table.get_root(document, comm)+    events = []+    table.on_edit(events.append)++    table._process_event(TableEditEvent(model, 'A', 1, value=5, old=2))+    table._process_event(TableEditEvent(model, 'A', 1, value=2, old=5))+    assert events == []++    table._process_events({'data': dict(model.source.data, A=np.array([1, 5, 3]))})+    assert [e.value for e in events] == [5, 2]+    assert table._pending_edits == {}+++@pytest.mark.parametrize('a, b, expected', [+    (1.5, 1.5, True),+    (1.5, 2.5, False),+    ('a', 'a', True),+    ('a', 'b', False),+    (np.nan, np.nan, True),+    (np.nan, None, True),+    (pd.NA, np.nan, True),+    (pd.NA, pd.NA, True),+    (pd.NaT, np.datetime64('NaT', 'ns'), True),+    (pd.NA, 1, False),+    (np.nan, 0.0, False),+    (None, 'a', False),+    (pd.Timestamp('2020-01-01'), np.datetime64('2020-01-01'), True),+    (dt.datetime(2020, 1, 1), pd.Timestamp('2020-01-01'), True),+    (pd.Timestamp('2020-01-01'), pd.NaT, False),+    (np.array([1, 2]), np.array([1, 2]), False),+    ([1, 2], np.nan, False),+])+def test_tabulator_values_equal(a, b, expected):+    assert _values_equal(a, b) is expected++ def test_server_edit_event_from_param():     class Test(param.Parameterized): 
panel/tests/widgets/test_tables_narwhals.py19 + / 0 −
@@ -634,6 +634,25 @@ def test_tabulator_edit_event(frame):     assert to_dict(table.value)['str'] == ['A', 'B', 'Z']  +@pytest.mark.parametrize('value', ['Z', None])+def test_tabulator_edit_event_after_patch_remote_pagination(frame, value):+    table = Tabulator(frame, sorters=[{'field': 'int', 'dir': 'desc'}], pagination='remote', page_size=2)+    table.page = 2+    events = []+    table.on_edit(events.append)++    table._process_events({'data': {'str': [value]}})+    assert events == []++    # A cleared cell arrives as NaN while the frame stores None.+    table._process_event(TableEditEvent(model=None, column='str', row=0, value=value or np.nan, old='A'))++    assert len(events) == 1+    assert events[0].row == 0+    assert to_dict(table.value)['str'] == [value, 'B', 'C']+    assert table._pending_edits == {}++ def test_tabulator_cell_click_event(frame):     table = Tabulator(frame, sorters=[{'field': 'int', 'dir': 'desc'}], pagination='remote')     values = []
panel/widgets/tables.py51 + / 7 −
@@ -97,6 +97,31 @@ def _convert_datetime_array_ignore_list(v):         return convert_datetime_array(v)     return v +def _is_missing(value) -> bool:+    if value is None:+        return True+    # pd.NA and pd.NaT can only exist once pandas was imported, and Tabulator+    # must work on polars or pyarrow data without importing it.+    pd = sys.modules.get('pandas')+    if pd is not None and pd.api.types.is_scalar(value):+        return bool(pd.isna(value))+    try:+        return bool(value != value)+    except (TypeError, ValueError):+        return False++def _values_equal(a, b) -> bool:+    # A cleared cell may come back as NaN, None, NaT or pd.NA depending on+    # the dtype, and none of these compare equal to each other.+    a_missing, b_missing = _is_missing(a), _is_missing(b)+    if a_missing or b_missing:+        return a_missing and b_missing+    try:+        return bool(a == b)+    except (TypeError, ValueError):+        # Array-like cells compare elementwise.+        return False+ def _get_value_from_keys(d:dict, key1, key2, default=None):     if key1 in d:         return d[key1]@@ -1863,7 +1888,15 @@ def _process_event(self, event) -> None:             # on_edit only fires once self.value/current_view reflect it,             # without depending on the relative order these two independently             # dispatched messages (this event and that patch) are handled in.-            self._pending_edits.setdefault((event_col, idx), []).append(event)+            # An event deferred while the document is busy is only processed+            # after the pending changes, so the patch may have landed already.+            # While an earlier edit to the cell is queued, the current value+            # may match only because that patch has not landed yet (A -> B -> A).+            key = (event_col, idx)+            if key not in self._pending_edits and self._edit_applied(event, event_col, indexed):+                self._fire_edits([event])+            else:+                self._pending_edits.setdefault(key, []).append(event)             return          if event_col not in self.buttons:@@ -1879,17 +1912,28 @@ def _process_event(self, event) -> None:         for cb in self._on_click_callbacks.get(event_col, []):             state.execute(partial(cb, event), schedule=False) +    def _edit_applied(self, event: TableEditEvent, column: str, indexed: bool) -> bool:+        if _values_equal(event.old, event.value) or not (0 <= event.row < len(self.value)):+            return False+        if indexed:+            current = self.value[column].iloc[event.row]+        else:+            current = to_narwhals(self.value).item(event.row, column)+        return _values_equal(current, event.value)+     def _fire_pending_edits(self, column: str, index) -> None:         if not self._pending_edits:             return         for ind in index:             events = self._pending_edits.pop((column, ind), None)-            if not events:-                continue-            for event in events:-                for cb in self._on_edit_callbacks:-                    state.execute(partial(cb, event), schedule=False)-            self._update_style()+            if events:+                self._fire_edits(events)++    def _fire_edits(self, events: list[TableEditEvent]) -> None:+        for event in events:+            for cb in self._on_edit_callbacks:+                state.execute(partial(cb, event), schedule=False)+        self._update_style()      def _get_theme(self, theme, resources=None):         from ..models.tabulator import _TABULATOR_THEMES_MAPPING, THEME_PATH