datatable.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """Table components."""
  2. from typing import Any, List, Optional
  3. from pynecone import utils
  4. from pynecone.components.component import Component, ImportDict
  5. from pynecone.components.tags import Tag
  6. from pynecone.var import BaseVar, Var
  7. class Gridjs(Component):
  8. """A component that wraps a nivo bar component."""
  9. library = "gridjs-react"
  10. class DataTable(Gridjs):
  11. """A data table component."""
  12. tag = "Grid"
  13. # The data to display. Either a list of dictionaries or a pandas dataframe.
  14. data: Any
  15. # The columns to display.
  16. columns: Var[List]
  17. # Enable a search bar.
  18. search: Var[bool]
  19. # Enable sorting on columns.
  20. sort: Var[bool]
  21. # Enable resizable columns.
  22. resizable: Var[bool]
  23. # Enable pagination.
  24. pagination: Var[bool]
  25. @classmethod
  26. def get_alias(cls) -> Optional[str]:
  27. """Get the alias for the component.
  28. Returns:
  29. The alias.
  30. """
  31. return "DataTableGrid"
  32. @classmethod
  33. def create(cls, *children, **props):
  34. """Create a datatable component.
  35. Args:
  36. *children: The children of the component.
  37. **props: The props to pass to the component.
  38. Returns:
  39. The datatable component.
  40. Raises:
  41. ValueError: If a pandas dataframe is passed in and columns are also provided.
  42. """
  43. # If data is a pandas dataframe and columns are provided throw an error.
  44. if utils.is_dataframe(type(props.get("data"))) and props.get("columns"):
  45. raise ValueError(
  46. "Cannot pass in both a pandas dataframe and columns to the data_table component."
  47. )
  48. # Create the component.
  49. return super().create(
  50. *children,
  51. **props,
  52. )
  53. def _get_imports(self) -> ImportDict:
  54. return utils.merge_imports(
  55. super()._get_imports(), {"": {"gridjs/dist/theme/mermaid.css"}}
  56. )
  57. def _render(self) -> Tag:
  58. # If given a var dataframe, get the data and columns
  59. if isinstance(self.data, Var):
  60. self.columns = BaseVar(
  61. name=f"{self.data.name}.columns",
  62. type_=List[Any],
  63. state=self.data.state,
  64. )
  65. self.data = BaseVar(
  66. name=f"{self.data.name}.data",
  67. type_=List[List[Any]],
  68. state=self.data.state,
  69. )
  70. # If given a pandas df break up the data and columns
  71. if utils.is_dataframe(type(self.data)):
  72. self.columns = Var.create(list(self.data.columns.values.tolist())) # type: ignore
  73. self.data = Var.create(utils.format_dataframe_values(self.data)) # type: ignore
  74. # Render the table.
  75. return super()._render()