upload.py 12 KB

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