upload.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. """A file upload component."""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple
  5. from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
  6. from reflex.components.el.elements.forms import Input
  7. from reflex.components.radix.themes.layout.box import Box
  8. from reflex.config import environment
  9. from reflex.constants import Dirs
  10. from reflex.event import (
  11. CallableEventSpec,
  12. EventChain,
  13. EventHandler,
  14. EventSpec,
  15. call_event_fn,
  16. call_script,
  17. parse_args_spec,
  18. )
  19. from reflex.utils.imports import ImportVar
  20. from reflex.vars import VarData
  21. from reflex.vars.base import CallableVar, LiteralVar, Var
  22. from reflex.vars.sequence import LiteralStringVar
  23. DEFAULT_UPLOAD_ID: str = "default"
  24. upload_files_context_var_data: VarData = VarData(
  25. imports={
  26. "react": "useContext",
  27. f"/{Dirs.CONTEXTS_PATH}": "UploadFilesContext",
  28. },
  29. hooks={
  30. "const [filesById, setFilesById] = useContext(UploadFilesContext);": None,
  31. },
  32. )
  33. @CallableVar
  34. def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> Var:
  35. """Get the file upload drop trigger.
  36. This var is passed to the dropzone component to update the file list when a
  37. drop occurs.
  38. Args:
  39. id_: The id of the upload to get the drop trigger for.
  40. Returns:
  41. A var referencing the file upload drop trigger.
  42. """
  43. id_var = LiteralStringVar.create(id_)
  44. var_name = f"""e => setFilesById(filesById => {{
  45. const updatedFilesById = Object.assign({{}}, filesById);
  46. updatedFilesById[{str(id_var)}] = e;
  47. return updatedFilesById;
  48. }})
  49. """
  50. return Var(
  51. _js_expr=var_name,
  52. _var_type=EventChain,
  53. _var_data=VarData.merge(
  54. upload_files_context_var_data, id_var._get_all_var_data()
  55. ),
  56. )
  57. @CallableVar
  58. def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> Var:
  59. """Get the list of selected files.
  60. Args:
  61. id_: The id of the upload to get the selected files for.
  62. Returns:
  63. A var referencing the list of selected file paths.
  64. """
  65. id_var = LiteralStringVar.create(id_)
  66. return Var(
  67. _js_expr=f"(filesById[{str(id_var)}] ? filesById[{str(id_var)}].map((f) => (f.path || f.name)) : [])",
  68. _var_type=List[str],
  69. _var_data=VarData.merge(
  70. upload_files_context_var_data, id_var._get_all_var_data()
  71. ),
  72. ).guess_type()
  73. @CallableEventSpec
  74. def clear_selected_files(id_: str = DEFAULT_UPLOAD_ID) -> EventSpec:
  75. """Clear the list of selected files.
  76. Args:
  77. id_: The id of the upload to clear.
  78. Returns:
  79. An event spec that clears the list of selected files when triggered.
  80. """
  81. # UploadFilesProvider assigns a special function to clear selected files
  82. # into the shared global refs object to make it accessible outside a React
  83. # component via `call_script` (otherwise backend could never clear files).
  84. return call_script(f"refs['__clear_selected_files']({id_!r})")
  85. def cancel_upload(upload_id: str) -> EventSpec:
  86. """Cancel an upload.
  87. Args:
  88. upload_id: The id of the upload to cancel.
  89. Returns:
  90. An event spec that cancels the upload when triggered.
  91. """
  92. return call_script(
  93. f"upload_controllers[{str(LiteralVar.create(upload_id))}]?.abort()"
  94. )
  95. def get_upload_dir() -> Path:
  96. """Get the directory where uploaded files are stored.
  97. Returns:
  98. The directory where uploaded files are stored.
  99. """
  100. Upload.is_used = True
  101. uploaded_files_dir = environment.REFLEX_UPLOADED_FILES_DIR
  102. uploaded_files_dir.mkdir(parents=True, exist_ok=True)
  103. return uploaded_files_dir
  104. uploaded_files_url_prefix = Var(
  105. _js_expr="getBackendURL(env.UPLOAD)",
  106. _var_data=VarData(
  107. imports={
  108. f"/{Dirs.STATE_PATH}": "getBackendURL",
  109. "/env.json": ImportVar(tag="env", is_default=True),
  110. }
  111. ),
  112. ).to(str)
  113. def get_upload_url(file_path: str) -> Var[str]:
  114. """Get the URL of an uploaded file.
  115. Args:
  116. file_path: The path of the uploaded file.
  117. Returns:
  118. The URL of the uploaded file to be rendered from the frontend (as a str-encoded Var).
  119. """
  120. Upload.is_used = True
  121. return uploaded_files_url_prefix + "/" + file_path
  122. def _on_drop_spec(files: Var) -> Tuple[Var[Any]]:
  123. """Args spec for the on_drop event trigger.
  124. Args:
  125. files: The files to upload.
  126. Returns:
  127. Signature for on_drop handler including the files to upload.
  128. """
  129. return (files,)
  130. class UploadFilesProvider(Component):
  131. """AppWrap component that provides a dict of selected files by ID via useContext."""
  132. library = f"/{Dirs.CONTEXTS_PATH}"
  133. tag = "UploadFilesProvider"
  134. class Upload(MemoizationLeaf):
  135. """A file upload component."""
  136. library = "react-dropzone@14.2.10"
  137. tag = "ReactDropzone"
  138. is_default = True
  139. # The list of accepted file types. This should be a dictionary of MIME types as keys and array of file formats as
  140. # values.
  141. # supported MIME types: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  142. accept: Var[Optional[Dict[str, List]]]
  143. # Whether the dropzone is disabled.
  144. disabled: Var[bool]
  145. # The maximum number of files that can be uploaded.
  146. max_files: Var[int]
  147. # The maximum file size (bytes) that can be uploaded.
  148. max_size: Var[int]
  149. # The minimum file size (bytes) that can be uploaded.
  150. min_size: Var[int]
  151. # Whether to allow multiple files to be uploaded.
  152. multiple: Var[bool] = True # type: ignore
  153. # Whether to disable click to upload.
  154. no_click: Var[bool]
  155. # Whether to disable drag and drop.
  156. no_drag: Var[bool]
  157. # Whether to disable using the space/enter keys to upload.
  158. no_keyboard: Var[bool]
  159. # Marked True when any Upload component is created.
  160. is_used: ClassVar[bool] = False
  161. # Fired when files are dropped.
  162. on_drop: EventHandler[_on_drop_spec]
  163. @classmethod
  164. def create(cls, *children, **props) -> Component:
  165. """Create an upload component.
  166. Args:
  167. *children: The children of the component.
  168. **props: The properties of the component.
  169. Returns:
  170. The upload component.
  171. """
  172. # Mark the Upload component as used in the app.
  173. cls.is_used = True
  174. # Apply the default classname
  175. given_class_name = props.pop("class_name", [])
  176. if isinstance(given_class_name, str):
  177. given_class_name = [given_class_name]
  178. props["class_name"] = ["rx-Upload", *given_class_name]
  179. # get only upload component props
  180. supported_props = cls.get_props().union({"on_drop"})
  181. upload_props = {
  182. key: value for key, value in props.items() if key in supported_props
  183. }
  184. # The file input to use.
  185. upload = Input.create(type="file")
  186. upload.special_props = [Var(_js_expr="{...getInputProps()}", _var_type=None)]
  187. # The dropzone to use.
  188. zone = Box.create(
  189. upload,
  190. *children,
  191. **{k: v for k, v in props.items() if k not in supported_props},
  192. )
  193. zone.special_props = [Var(_js_expr="{...getRootProps()}", _var_type=None)]
  194. # Create the component.
  195. upload_props["id"] = props.get("id", DEFAULT_UPLOAD_ID)
  196. if upload_props.get("on_drop") is None:
  197. # If on_drop is not provided, save files to be uploaded later.
  198. upload_props["on_drop"] = upload_file(upload_props["id"])
  199. else:
  200. on_drop = upload_props["on_drop"]
  201. if isinstance(on_drop, Callable):
  202. # Call the lambda to get the event chain.
  203. on_drop = call_event_fn(on_drop, _on_drop_spec) # type: ignore
  204. if isinstance(on_drop, EventSpec):
  205. # Update the provided args for direct use with on_drop.
  206. on_drop = on_drop.with_args(
  207. args=tuple(
  208. cls._update_arg_tuple_for_on_drop(arg_value)
  209. for arg_value in on_drop.args
  210. ),
  211. )
  212. upload_props["on_drop"] = on_drop
  213. return super().create(
  214. zone,
  215. **upload_props,
  216. )
  217. @classmethod
  218. def _update_arg_tuple_for_on_drop(cls, arg_value: tuple[Var, Var]):
  219. """Helper to update caller-provided EventSpec args for direct use with on_drop.
  220. Args:
  221. arg_value: The arg tuple to update (if necessary).
  222. Returns:
  223. The updated arg_value tuple when arg is "files", otherwise the original arg_value.
  224. """
  225. if arg_value[0]._js_expr == "files":
  226. placeholder = parse_args_spec(_on_drop_spec)[0]
  227. return (arg_value[0], placeholder)
  228. return arg_value
  229. def _render(self):
  230. out = super()._render()
  231. out.args = ("getRootProps", "getInputProps")
  232. return out
  233. @staticmethod
  234. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  235. return {
  236. (5, "UploadFilesProvider"): UploadFilesProvider.create(),
  237. }
  238. class StyledUpload(Upload):
  239. """The styled Upload Component."""
  240. @classmethod
  241. def create(cls, *children, **props) -> Component:
  242. """Create the styled upload component.
  243. Args:
  244. *children: The children of the component.
  245. **props: The properties of the component.
  246. Returns:
  247. The styled upload component.
  248. """
  249. # Set default props.
  250. props.setdefault("border", "1px dashed var(--accent-12)")
  251. props.setdefault("padding", "5em")
  252. props.setdefault("textAlign", "center")
  253. # Mark the Upload component as used in the app.
  254. Upload.is_used = True
  255. return super().create(
  256. *children,
  257. **props,
  258. )
  259. class UploadNamespace(ComponentNamespace):
  260. """Upload component namespace."""
  261. root = Upload.create
  262. __call__ = StyledUpload.create
  263. upload = UploadNamespace()