dataeditor.py 13 KB

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