aggrid.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from __future__ import annotations
  2. from typing import Dict, List, Optional, cast
  3. from ..dependencies import register_component
  4. from ..element import Element
  5. from ..functions.javascript import run_javascript
  6. register_component('aggrid', __file__, 'aggrid.js', ['lib/ag-grid-community.min.js'])
  7. class AgGrid(Element):
  8. def __init__(self, options: Dict, *, html_columns: List[int] = [], theme: str = 'balham') -> None:
  9. """AG Grid
  10. An element to create a grid using `AG Grid <https://www.ag-grid.com/>`_.
  11. The `call_api_method` method can be used to call an AG Grid API method.
  12. :param options: dictionary of AG Grid options
  13. :param html_columns: list of columns that should be rendered as HTML (default: `[]`)
  14. :param theme: AG Grid theme (default: 'balham')
  15. """
  16. super().__init__('aggrid')
  17. self._props['options'] = options
  18. self._props['html_columns'] = html_columns
  19. self._classes = ['nicegui-aggrid', f'ag-theme-{theme}']
  20. @staticmethod
  21. def from_pandas(df: 'pandas.DataFrame', *, theme: str = 'balham') -> AgGrid:
  22. """Create an AG Grid from a Pandas DataFrame.
  23. :param df: Pandas DataFrame
  24. :param theme: AG Grid theme (default: 'balham')
  25. :return: AG Grid
  26. """
  27. return AgGrid({
  28. 'columnDefs': [{'field': col} for col in df.columns],
  29. 'rowData': df.to_dict('records'),
  30. }, theme=theme)
  31. @property
  32. def options(self) -> Dict:
  33. return self._props['options']
  34. def update(self) -> None:
  35. super().update()
  36. self.run_method('update_grid')
  37. def call_api_method(self, name: str, *args) -> None:
  38. """Call an AG Grid API method.
  39. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/grid-api/>`_ for a list of methods.
  40. :param name: name of the method
  41. :param args: arguments to pass to the method
  42. """
  43. self.run_method('call_api_method', name, *args)
  44. async def get_selected_rows(self) -> List[Dict]:
  45. """Get the currently selected rows.
  46. This method is especially useful when the grid is configured with ``rowSelection: 'multiple'``.
  47. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/row-selection/#reference-selection-getSelectedRows>`_ for more information.
  48. :return: list of selected row data
  49. """
  50. result = await run_javascript(f'return getElement({self.id}).gridOptions.api.getSelectedRows();')
  51. return cast(List[Dict], result)
  52. async def get_selected_row(self) -> Optional[Dict]:
  53. """Get the single currently selected row.
  54. This method is especially useful when the grid is configured with ``rowSelection: 'single'``.
  55. :return: row data of the first selection if any row is selected, otherwise `None`
  56. """
  57. rows = await self.get_selected_rows()
  58. return rows[0] if rows else None
  59. async def get_client_data(self) -> List[Dict]:
  60. """Gets the data from the client including any edits made by the client.
  61. This method is especially useful when the grid is configured with ``'editable': True``.
  62. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/accessing-data/>`_ for more information.
  63. :return: list of row data
  64. """
  65. result = await run_javascript(
  66. f"""
  67. let rowData = [];
  68. getElement({self.id}).gridOptions.api.forEachNode(node => rowData.push(node.data));
  69. return rowData;
  70. """
  71. )
  72. return cast(List[Dict], result)
  73. async def load_client_data(self) -> None:
  74. """Obtains client data and updates the element's row data with it.
  75. This syncs edits made by the client in editable cells to the server.
  76. """
  77. client_row_data = await self.get_client_data()
  78. self.options["rowData"] = client_row_data
  79. self.update()