upload.py 13 KB

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