datatable.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """Table components."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Union
  4. from reflex.components.component import Component
  5. from reflex.components.tags import Tag
  6. from reflex.utils import imports, types
  7. from reflex.utils.serializers import serialize
  8. from reflex.vars import BaseVar, ComputedVar, Var
  9. class Gridjs(Component):
  10. """A component that wraps a nivo bar component."""
  11. library = "gridjs-react@6.0.1"
  12. lib_dependencies: List[str] = ["gridjs@6.0.6"]
  13. class DataTable(Gridjs):
  14. """A data table component."""
  15. tag = "Grid"
  16. alias = "DataTableGrid"
  17. # The data to display. Either a list of lists or a pandas dataframe.
  18. data: Any
  19. # The list of columns to display. Required if data is a list and should not be provided
  20. # if the data field is a dataframe
  21. columns: Var[List]
  22. # Enable a search bar.
  23. search: Var[bool]
  24. # Enable sorting on columns.
  25. sort: Var[bool]
  26. # Enable resizable columns.
  27. resizable: Var[bool]
  28. # Enable pagination.
  29. pagination: Var[Union[bool, Dict]]
  30. @classmethod
  31. def create(cls, *children, **props):
  32. """Create a datatable component.
  33. Args:
  34. *children: The children of the component.
  35. **props: The props to pass to the component.
  36. Returns:
  37. The datatable component.
  38. Raises:
  39. ValueError: If a pandas dataframe is passed in and columns are also provided.
  40. """
  41. data = props.get("data")
  42. columns = props.get("columns")
  43. # The annotation should be provided if data is a computed var. We need this to know how to
  44. # render pandas dataframes.
  45. if isinstance(data, ComputedVar) and data._var_type == Any:
  46. raise ValueError(
  47. "Annotation of the computed var assigned to the data field should be provided."
  48. )
  49. if (
  50. columns is not None
  51. and isinstance(columns, ComputedVar)
  52. and columns._var_type == Any
  53. ):
  54. raise ValueError(
  55. "Annotation of the computed var assigned to the column field should be provided."
  56. )
  57. # If data is a pandas dataframe and columns are provided throw an error.
  58. if (
  59. types.is_dataframe(type(data))
  60. or (isinstance(data, Var) and types.is_dataframe(data._var_type))
  61. ) and columns is not None:
  62. raise ValueError(
  63. "Cannot pass in both a pandas dataframe and columns to the data_table component."
  64. )
  65. # If data is a list and columns are not provided, throw an error
  66. if (
  67. (isinstance(data, Var) and types._issubclass(data._var_type, List))
  68. or issubclass(type(data), List)
  69. ) and columns is None:
  70. raise ValueError(
  71. "column field should be specified when the data field is a list type"
  72. )
  73. # Create the component.
  74. return super().create(
  75. *children,
  76. **props,
  77. )
  78. def _get_imports(self) -> imports.ImportDict:
  79. return imports.merge_imports(
  80. super()._get_imports(),
  81. {"": {imports.ImportVar(tag="gridjs/dist/theme/mermaid.css")}},
  82. )
  83. def _render(self) -> Tag:
  84. if isinstance(self.data, Var) and types.is_dataframe(self.data._var_type):
  85. self.columns = BaseVar(
  86. _var_name=f"{self.data._var_name}.columns",
  87. _var_type=List[Any],
  88. _var_full_name_needs_state_prefix=True,
  89. )._replace(merge_var_data=self.data._var_data)
  90. self.data = BaseVar(
  91. _var_name=f"{self.data._var_name}.data",
  92. _var_type=List[List[Any]],
  93. _var_full_name_needs_state_prefix=True,
  94. )._replace(merge_var_data=self.data._var_data)
  95. if types.is_dataframe(type(self.data)):
  96. # If given a pandas df break up the data and columns
  97. data = serialize(self.data)
  98. assert isinstance(data, dict), "Serialized dataframe should be a dict."
  99. self.columns = Var.create_safe(data["columns"])
  100. self.data = Var.create_safe(data["data"])
  101. # Render the table.
  102. return super()._render()