dataeditor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. """Data Editor component from glide-data-grid."""
  2. from __future__ import annotations
  3. from enum import Enum
  4. from typing import Any, Callable, Dict, List, Optional, Union
  5. from reflex.base import Base
  6. from reflex.components.component import Component, NoSSRComponent
  7. from reflex.components.literals import LiteralRowMarker
  8. from reflex.utils import console, format, imports, types
  9. from reflex.utils.serializers import serializer
  10. from reflex.vars import ImportVar, Var, get_unique_variable_name
  11. # TODO: Fix the serialization issue for custom types.
  12. class GridColumnIcons(Enum):
  13. """An Enum for the available icons in DataEditor."""
  14. Array = "array"
  15. AudioUri = "audio_uri"
  16. Boolean = "boolean"
  17. HeaderCode = "code"
  18. Date = "date"
  19. Email = "email"
  20. Emoji = "emoji"
  21. GeoDistance = "geo_distance"
  22. IfThenElse = "if_then_else"
  23. Image = "image"
  24. JoinStrings = "join_strings"
  25. Lookup = "lookup"
  26. Markdown = "markdown"
  27. Math = "math"
  28. Number = "number"
  29. Phone = "phone"
  30. Reference = "reference"
  31. Rollup = "rollup"
  32. RowID = "row_id"
  33. SingleValue = "single_value"
  34. SplitString = "split_string"
  35. String = "string"
  36. TextTemplate = "text_template"
  37. Time = "time"
  38. Uri = "uri"
  39. VideoUri = "video_uri"
  40. # @serializer
  41. # def serialize_gridcolumn_icon(icon: GridColumnIcons) -> str:
  42. # """Serialize grid column icon.
  43. # Args:
  44. # icon: the Icon to serialize.
  45. # Returns:
  46. # The serialized value.
  47. # """
  48. # return "prefix" + str(icon)
  49. # class DataEditorColumn(Base):
  50. # """Column."""
  51. # title: str
  52. # id: Optional[str] = None
  53. # type_: str = "str"
  54. class DataEditorTheme(Base):
  55. """The theme for the DataEditor component."""
  56. accent_color: Optional[str] = None
  57. accent_fg: Optional[str] = None
  58. accent_light: Optional[str] = None
  59. base_font_style: Optional[str] = None
  60. bg_bubble: Optional[str] = None
  61. bg_bubble_selected: Optional[str] = None
  62. bg_cell: Optional[str] = None
  63. bg_cell_medium: Optional[str] = None
  64. bg_header: Optional[str] = None
  65. bg_header_has_focus: Optional[str] = None
  66. bg_header_hovered: Optional[str] = None
  67. bg_icon_header: Optional[str] = None
  68. bg_search_result: Optional[str] = None
  69. border_color: Optional[str] = None
  70. cell_horizontal_padding: Optional[int] = None
  71. cell_vertical_padding: Optional[int] = None
  72. drilldown_border: Optional[str] = None
  73. editor_font_size: Optional[str] = None
  74. fg_icon_header: Optional[str] = None
  75. font_family: Optional[str] = None
  76. header_bottom_border_color: Optional[str] = None
  77. header_font_style: Optional[str] = None
  78. horizontal_border_color: Optional[str] = None
  79. line_height: Optional[int] = None
  80. link_color: Optional[str] = None
  81. text_bubble: Optional[str] = None
  82. text_dark: Optional[str] = None
  83. text_group_header: Optional[str] = None
  84. text_header: Optional[str] = None
  85. text_header_selected: Optional[str] = None
  86. text_light: Optional[str] = None
  87. text_medium: Optional[str] = None
  88. class DataEditor(NoSSRComponent):
  89. """The DataEditor Component."""
  90. tag = "DataEditor"
  91. is_default = True
  92. library: str = "@glideapps/glide-data-grid@^5.3.0"
  93. lib_dependencies: List[str] = ["lodash", "marked", "react-responsive-carousel"]
  94. # Number of rows.
  95. rows: Var[int]
  96. # Headers of the columns for the data grid.
  97. columns: Var[List[Dict[str, Any]]]
  98. # The data.
  99. data: Var[List[List[Any]]]
  100. # The name of the callback used to find the data to display.
  101. get_cell_content: Var[str]
  102. # Allow selection for copying.
  103. get_cell_for_selection: Var[bool]
  104. # Allow paste.
  105. on_paste: Var[bool]
  106. # Controls the drawing of the focus ring.
  107. draw_focus_ring: Var[bool]
  108. # Enables or disables the overlay shadow when scrolling horizontally.
  109. fixed_shadow_x: Var[bool]
  110. # Enables or disables the overlay shadow when scrolling vertically.
  111. fixed_shadow_y: Var[bool]
  112. # The number of columns which should remain in place when scrolling horizontally. Doesn't include rowMarkers.
  113. freeze_columns: Var[int]
  114. # Controls the header of the group header row.
  115. group_header_height: Var[int]
  116. # Controls the height of the header row.
  117. header_height: Var[int]
  118. # Additional header icons:
  119. # header_icons: Var[Any] # (TODO: must be a map of name: svg)
  120. # The maximum width a column can be automatically sized to.
  121. max_column_auto_width: Var[int]
  122. # The maximum width a column can be resized to.
  123. max_column_width: Var[int]
  124. # The minimum width a column can be resized to.
  125. min_column_width: Var[int]
  126. # Determins the height of each row.
  127. row_height: Var[int]
  128. # Kind of row markers.
  129. row_markers: Var[LiteralRowMarker]
  130. # Changes the starting index for row markers.
  131. row_marker_start_index: Var[int]
  132. # Sets the width of row markers in pixels, if unset row markers will automatically size.
  133. row_marker_width: Var[int]
  134. # Enable horizontal smooth scrolling.
  135. smooth_scroll_x: Var[bool]
  136. # Enable vertical smooth scrolling.
  137. smooth_scroll_y: Var[bool]
  138. # Controls the drawing of the left hand vertical border of a column. If set to a boolean value it controls all borders.
  139. vertical_border: Var[bool] # TODO: support a mapping (dict[int, bool])
  140. # Allow columns selections. ("none", "single", "multiple")
  141. column_select: Var[str]
  142. # Prevent diagonal scrolling.
  143. prevent_diagonal_scrolling: Var[bool]
  144. # Allow to scroll past the limit of the actual content on the horizontal axis.
  145. overscroll_x: Var[int]
  146. # Allow to scroll past the limit of the actual content on the vertical axis.
  147. overscroll_y: Var[int]
  148. # Initial scroll offset on the horizontal axis.
  149. scroll_offset_x: Var[int]
  150. # Initial scroll offset on the vertical axis.
  151. scroll_offset_y: Var[int]
  152. # global theme
  153. theme: Var[Union[DataEditorTheme, Dict]]
  154. def _get_imports(self):
  155. return imports.merge_imports(
  156. super()._get_imports(),
  157. {
  158. "": {
  159. ImportVar(
  160. tag=f"{format.format_library_name(self.library)}/dist/index.css"
  161. )
  162. },
  163. self.library: {ImportVar(tag="GridCellKind")},
  164. "/utils/helpers/dataeditor.js": {
  165. ImportVar(
  166. tag=f"formatDataEditorCells", is_default=False, install=False
  167. ),
  168. },
  169. },
  170. )
  171. def get_event_triggers(self) -> Dict[str, Callable]:
  172. """The event triggers of the component.
  173. Returns:
  174. The dict describing the event triggers.
  175. """
  176. def edit_sig(pos, data: dict[str, Any]):
  177. return [pos, data]
  178. return {
  179. "on_cell_activated": lambda pos: [pos],
  180. "on_cell_clicked": lambda pos: [pos],
  181. "on_cell_context_menu": lambda pos: [pos],
  182. "on_cell_edited": edit_sig,
  183. "on_group_header_clicked": edit_sig,
  184. "on_group_header_context_menu": lambda grp_idx, data: [grp_idx, data],
  185. "on_group_header_renamed": lambda idx, val: [idx, val],
  186. "on_header_clicked": lambda pos: [pos],
  187. "on_header_context_menu": lambda pos: [pos],
  188. "on_header_menu_click": lambda col, pos: [col, pos],
  189. "on_item_hovered": lambda pos: [pos],
  190. "on_delete": lambda selection: [selection],
  191. "on_finished_editing": lambda new_value, movement: [new_value, movement],
  192. "on_row_appended": lambda: [],
  193. "on_selection_cleared": lambda: [],
  194. }
  195. def _get_hooks(self) -> str | None:
  196. # Define the id of the component in case multiple are used in the same page.
  197. editor_id = get_unique_variable_name()
  198. # Define the name of the getData callback associated with this component and assign to get_cell_content.
  199. data_callback = f"getData_{editor_id}"
  200. self.get_cell_content = Var.create(data_callback, _var_is_local=False) # type: ignore
  201. code = [f"function {data_callback}([col, row])" "{"]
  202. columns_path = f"{self.columns._var_full_name}"
  203. data_path = f"{self.data._var_full_name}"
  204. code.extend(
  205. [
  206. f" return formatDataEditorCells(col, row, {columns_path}, {data_path});",
  207. " }",
  208. ]
  209. )
  210. return "\n".join(code)
  211. @classmethod
  212. def create(cls, *children, **props) -> Component:
  213. """Create the DataEditor component.
  214. Args:
  215. *children: The children of the data editor.
  216. **props: The props of the data editor.
  217. Raises:
  218. ValueError: invalid input.
  219. Returns:
  220. The DataEditor component.&
  221. """
  222. from reflex.el.elements import Div
  223. columns = props.get("columns", [])
  224. data = props.get("data", [])
  225. rows = props.get("rows", None)
  226. # If rows is not provided, determine from data.
  227. if rows is None:
  228. props["rows"] = (
  229. data.length() # BaseVar.create(value=f"{data}.length()", is_local=False)
  230. if isinstance(data, Var)
  231. else len(data)
  232. )
  233. if not isinstance(columns, Var) and len(columns):
  234. if (
  235. types.is_dataframe(type(data))
  236. or isinstance(data, Var)
  237. and types.is_dataframe(data._var_type)
  238. ):
  239. raise ValueError(
  240. "Cannot pass in both a pandas dataframe and columns to the data_editor component."
  241. )
  242. else:
  243. props["columns"] = [
  244. format.format_data_editor_column(col) for col in columns
  245. ]
  246. if "theme" in props:
  247. theme = props.get("theme")
  248. if isinstance(theme, Dict):
  249. props["theme"] = DataEditorTheme(**theme)
  250. # Allow by default to select a region of cells in the grid.
  251. props.setdefault("getCellForSelection", True)
  252. # Disable on_paste by default if not provided.
  253. props.setdefault("onPaste", False)
  254. if props.pop("getCellContent", None) is not None:
  255. console.warn(
  256. "getCellContent is not user configurable, the provided value will be discarded"
  257. )
  258. grid = super().create(*children, **props)
  259. return Div.create(
  260. grid,
  261. Div.create(id="portal"),
  262. width=props.pop("width", "100%"),
  263. height=props.pop("height", "100%"),
  264. )
  265. # def _render(self) -> Tag:
  266. # if isinstance(self.data, Var) and types.is_dataframe(self.data.type_):
  267. # self.columns = BaseVar(
  268. # name=f"{self.data.name}.columns",
  269. # type_=List[Any],
  270. # state=self.data.state,
  271. # )
  272. # self.data = BaseVar(
  273. # name=f"{self.data.name}.data",
  274. # type_=List[List[Any]],
  275. # state=self.data.state,
  276. # )
  277. # if types.is_dataframe(type(self.data)):
  278. # # If given a pandas df break up the data and columns
  279. # data = serialize(self.data)
  280. # assert isinstance(data, dict), "Serialized dataframe should be a dict."
  281. # self.columns = Var.create_safe(data["columns"])
  282. # self.data = Var.create_safe(data["data"])
  283. # # Render the table.
  284. # return super()._render()
  285. # try:
  286. # pass
  287. # # def format_dataframe_values(df: DataFrame) -> list[list[Any]]:
  288. # # """Format dataframe values to a list of lists.
  289. # # Args:
  290. # # df: The dataframe to format.
  291. # # Returns:
  292. # # The dataframe as a list of lists.
  293. # # """
  294. # # return [
  295. # # [str(d) if isinstance(d, (list, tuple)) else d for d in data]
  296. # # for data in list(df.values.tolist())
  297. # # ]
  298. # # ...
  299. # # @serializer
  300. # # def serialize_dataframe(df: DataFrame) -> dict:
  301. # # """Serialize a pandas dataframe.
  302. # # Args:
  303. # # df: The dataframe to serialize.
  304. # # Returns:
  305. # # The serialized dataframe.
  306. # # """
  307. # # return {
  308. # # "columns": df.columns.tolist(),
  309. # # "data": format_dataframe_values(df),
  310. # # }
  311. # except ImportError:
  312. # pass
  313. @serializer
  314. def serialize_dataeditortheme(theme: DataEditorTheme):
  315. """The serializer for the data editor theme.
  316. Args:
  317. theme: The theme to serialize.
  318. Returns:
  319. The serialized theme.
  320. """
  321. return format.json_dumps(
  322. {format.to_camel_case(k): v for k, v in theme.__dict__.items() if v is not None}
  323. )