dataeditor.py 12 KB

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