dataeditor.py 14 KB

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