Skip to content

Commit

Permalink
feat: implement access method for get_client_data (#3582)
Browse files Browse the repository at this point in the history
* feat: implement access method for get_client_data

Allows access to client data in a way that also takes care of sorting and filtering.

Fixes: #3581

* code review

* add pytest

---------

Co-authored-by: Jeppe Klitgaard <jkl@nanonord.dk>
Co-authored-by: Falko Schindler <falko@zauberzeug.com>
  • Loading branch information
3 people authored Aug 28, 2024
1 parent 327fa47 commit c3f1ab1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
20 changes: 17 additions & 3 deletions nicegui/elements/aggrid.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import importlib.util
from typing import TYPE_CHECKING, Dict, List, Optional, cast
from typing import TYPE_CHECKING, Dict, List, Literal, Optional, cast

from typing_extensions import Self

Expand Down Expand Up @@ -173,7 +173,13 @@ async def get_selected_row(self) -> Optional[Dict]:
rows = await self.get_selected_rows()
return rows[0] if rows else None

async def get_client_data(self, *, timeout: float = 1, check_interval: float = 0.01) -> List[Dict]:
async def get_client_data(
self,
*,
timeout: float = 1,
check_interval: float = 0.01,
method: Literal['all_unsorted', 'filtered_unsorted', 'filtered_sorted', 'leaf'] = 'all_unsorted'
) -> List[Dict]:
"""Get the data from the client including any edits made by the client.
This method is especially useful when the grid is configured with ``'editable': True``.
Expand All @@ -184,12 +190,20 @@ async def get_client_data(self, *, timeout: float = 1, check_interval: float = 0
This does not happen when the cell loses focus, unless ``stopEditingWhenCellsLoseFocus: True`` is set.
:param timeout: timeout in seconds (default: 1 second)
:param check_interval: interval in seconds to check for the result (default: 0.01 seconds)
:param method: method to access the data, "all_unsorted" (default), "filtered_unsorted", "filtered_sorted", "leaf"
:return: list of row data
"""
API_METHODS = {
'all_unsorted': 'forEachNode',
'filtered_unsorted': 'forEachNodeAfterFilter',
'filtered_sorted': 'forEachNodeAfterFilterAndSort',
'leaf': 'forEachLeafNode',
}
result = await self.client.run_javascript(f'''
const rowData = [];
getElement({self.id}).gridOptions.api.forEachNode(node => rowData.push(node.data));
getElement({self.id}).gridOptions.api.{API_METHODS[method]}(node => rowData.push(node.data));
return rowData;
''', timeout=timeout, check_interval=check_interval)
return cast(List[Dict], result)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_aggrid.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime, timedelta, timezone
from typing import List

import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains
Expand Down Expand Up @@ -248,3 +249,38 @@ async def print_row(index: int) -> None:
screen.open('/')
screen.click('Print Row 0')
screen.should_contain("Row 0: {'name': 'Alice'}")


def test_get_client_data(screen: Screen):
data: List = []

@ui.page('/')
def page():
grid = ui.aggrid({
'columnDefs': [
{'field': 'name'},
{'field': 'age', 'sort': 'desc'},
],
'rowData': [
{'name': 'Alice', 'age': 18},
{'name': 'Bob', 'age': 21},
{'name': 'Carol', 'age': 42},
],
})

async def get_data():
data[:] = await grid.get_client_data()
ui.button('Get Data', on_click=get_data)

async def get_sorted_data():
data[:] = await grid.get_client_data(method='filtered_sorted')
ui.button('Get Sorted Data', on_click=get_sorted_data)

screen.open('/')
screen.click('Get Data')
screen.wait(0.5)
assert data == [{'name': 'Alice', 'age': 18}, {'name': 'Bob', 'age': 21}, {'name': 'Carol', 'age': 42}]

screen.click('Get Sorted Data')
screen.wait(0.5)
assert data == [{'name': 'Carol', 'age': 42}, {'name': 'Bob', 'age': 21}, {'name': 'Alice', 'age': 18}]

0 comments on commit c3f1ab1

Please sign in to comment.