aggrid.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from typing import Dict, List, Optional, cast
  2. from typing_extensions import Self
  3. from .. import optional_features
  4. from ..awaitable_response import AwaitableResponse
  5. from ..element import Element
  6. try:
  7. import pandas as pd
  8. optional_features.register('pandas')
  9. except ImportError:
  10. pass
  11. class AgGrid(Element, component='aggrid.js', libraries=['lib/aggrid/ag-grid-community.min.js']):
  12. def __init__(self,
  13. options: Dict, *,
  14. html_columns: List[int] = [],
  15. theme: str = 'balham',
  16. auto_size_columns: bool = True,
  17. ) -> None:
  18. """AG Grid
  19. An element to create a grid using `AG Grid <https://www.ag-grid.com/>`_.
  20. The methods `run_grid_method` and `run_column_method` can be used to interact with the AG Grid instance on the client.
  21. :param options: dictionary of AG Grid options
  22. :param html_columns: list of columns that should be rendered as HTML (default: `[]`)
  23. :param theme: AG Grid theme (default: 'balham')
  24. :param auto_size_columns: whether to automatically resize columns to fit the grid width (default: `True`)
  25. """
  26. super().__init__()
  27. self._props['options'] = options
  28. self._props['html_columns'] = html_columns
  29. self._props['auto_size_columns'] = auto_size_columns
  30. self._classes.append('nicegui-aggrid')
  31. self._classes.append(f'ag-theme-{theme}')
  32. @classmethod
  33. def from_pandas(cls,
  34. df: 'pd.DataFrame', *,
  35. theme: str = 'balham',
  36. auto_size_columns: bool = True,
  37. options: Dict = {}) -> Self:
  38. """Create an AG Grid from a Pandas DataFrame.
  39. Note:
  40. If the DataFrame contains non-serializable columns of type `datetime64[ns]`, `timedelta64[ns]`, `complex128` or `period[M]`,
  41. they will be converted to strings.
  42. To use a different conversion, convert the DataFrame manually before passing it to this method.
  43. See `issue 1698 <https://github.com/zauberzeug/nicegui/issues/1698>`_ for more information.
  44. :param df: Pandas DataFrame
  45. :param theme: AG Grid theme (default: 'balham')
  46. :param auto_size_columns: whether to automatically resize columns to fit the grid width (default: `True`)
  47. :param options: dictionary of additional AG Grid options
  48. :return: AG Grid element
  49. """
  50. date_cols = df.columns[df.dtypes == 'datetime64[ns]']
  51. time_cols = df.columns[df.dtypes == 'timedelta64[ns]']
  52. complex_cols = df.columns[df.dtypes == 'complex128']
  53. period_cols = df.columns[df.dtypes == 'period[M]']
  54. if len(date_cols) != 0 or len(time_cols) != 0 or len(complex_cols) != 0 or len(period_cols) != 0:
  55. df = df.copy()
  56. df[date_cols] = df[date_cols].astype(str)
  57. df[time_cols] = df[time_cols].astype(str)
  58. df[complex_cols] = df[complex_cols].astype(str)
  59. df[period_cols] = df[period_cols].astype(str)
  60. return cls({
  61. 'columnDefs': [{'field': str(col)} for col in df.columns],
  62. 'rowData': df.to_dict('records'),
  63. 'suppressDotNotation': True,
  64. **options,
  65. }, theme=theme, auto_size_columns=auto_size_columns)
  66. @property
  67. def options(self) -> Dict:
  68. """The options dictionary."""
  69. return self._props['options']
  70. def update(self) -> None:
  71. super().update()
  72. self.run_method('update_grid')
  73. def call_api_method(self, name: str, *args, timeout: float = 1, check_interval: float = 0.01) -> AwaitableResponse:
  74. """DEPRECATED: Use `run_grid_method` instead."""
  75. return self.run_grid_method(name, *args, timeout=timeout, check_interval=check_interval)
  76. def run_grid_method(self, name: str, *args, timeout: float = 1, check_interval: float = 0.01) -> AwaitableResponse:
  77. """Run an AG Grid API method.
  78. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/grid-api/>`_ for a list of methods.
  79. If the function is awaited, the result of the method call is returned.
  80. Otherwise, the method is executed without waiting for a response.
  81. :param name: name of the method
  82. :param args: arguments to pass to the method
  83. :param timeout: timeout in seconds (default: 1 second)
  84. :param check_interval: interval in seconds to check for a response (default: 0.01 seconds)
  85. :return: AwaitableResponse that can be awaited to get the result of the method call
  86. """
  87. return self.run_method('run_grid_method', name, *args, timeout=timeout, check_interval=check_interval)
  88. def call_column_method(self, name: str, *args, timeout: float = 1, check_interval: float = 0.01) -> AwaitableResponse:
  89. """DEPRECATED: Use `run_column_method` instead."""
  90. return self.run_column_method(name, *args, timeout=timeout, check_interval=check_interval)
  91. def run_column_method(self, name: str, *args,
  92. timeout: float = 1, check_interval: float = 0.01) -> AwaitableResponse:
  93. """Run an AG Grid Column API method.
  94. See `AG Grid Column API <https://www.ag-grid.com/javascript-data-grid/column-api/>`_ for a list of methods.
  95. If the function is awaited, the result of the method call is returned.
  96. Otherwise, the method is executed without waiting for a response.
  97. :param name: name of the method
  98. :param args: arguments to pass to the method
  99. :param timeout: timeout in seconds (default: 1 second)
  100. :param check_interval: interval in seconds to check for a response (default: 0.01 seconds)
  101. :return: AwaitableResponse that can be awaited to get the result of the method call
  102. """
  103. return self.run_method('run_column_method', name, *args, timeout=timeout, check_interval=check_interval)
  104. async def get_selected_rows(self) -> List[Dict]:
  105. """Get the currently selected rows.
  106. This method is especially useful when the grid is configured with ``rowSelection: 'multiple'``.
  107. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/row-selection/#reference-selection-getSelectedRows>`_ for more information.
  108. :return: list of selected row data
  109. """
  110. result = await self.run_grid_method('getSelectedRows')
  111. return cast(List[Dict], result)
  112. async def get_selected_row(self) -> Optional[Dict]:
  113. """Get the single currently selected row.
  114. This method is especially useful when the grid is configured with ``rowSelection: 'single'``.
  115. :return: row data of the first selection if any row is selected, otherwise `None`
  116. """
  117. rows = await self.get_selected_rows()
  118. return rows[0] if rows else None
  119. async def get_client_data(self, *, timeout: float = 1, check_interval: float = 0.01) -> List[Dict]:
  120. """Get the data from the client including any edits made by the client.
  121. This method is especially useful when the grid is configured with ``'editable': True``.
  122. See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/accessing-data/>`_ for more information.
  123. Note that when editing a cell, the row data is not updated until the cell exits the edit mode.
  124. This does not happen when the cell loses focus, unless ``stopEditingWhenCellsLoseFocus: True`` is set.
  125. :param timeout: timeout in seconds (default: 1 second)
  126. :param check_interval: interval in seconds to check for a response (default: 0.01 seconds)
  127. :return: list of row data
  128. """
  129. result = await self.client.run_javascript(f'''
  130. const rowData = [];
  131. getElement({self.id}).gridOptions.api.forEachNode(node => rowData.push(node.data));
  132. return rowData;
  133. ''', timeout=timeout, check_interval=check_interval)
  134. return cast(List[Dict], result)
  135. async def load_client_data(self) -> None:
  136. """Obtain client data and update the element's row data with it.
  137. This syncs edits made by the client in editable cells to the server.
  138. Note that when editing a cell, the row data is not updated until the cell exits the edit mode.
  139. This does not happen when the cell loses focus, unless ``stopEditingWhenCellsLoseFocus: True`` is set.
  140. """
  141. client_row_data = await self.get_client_data()
  142. self.options['rowData'] = client_row_data
  143. self.update()