dataeditor.py 13 KB

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