upload.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """A file upload component."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, List, Optional, Union
  4. from reflex import constants
  5. from reflex.components.component import Component
  6. from reflex.components.forms.input import Input
  7. from reflex.components.layout.box import Box
  8. from reflex.event import CallableEventSpec, EventChain, EventSpec, call_script
  9. from reflex.utils import imports
  10. from reflex.vars import BaseVar, CallableVar, ImportVar, Var
  11. DEFAULT_UPLOAD_ID: str = "default"
  12. @CallableVar
  13. def upload_file(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
  14. """Get the file upload drop trigger.
  15. This var is passed to the dropzone component to update the file list when a
  16. drop occurs.
  17. Args:
  18. id_: The id of the upload to get the drop trigger for.
  19. Returns:
  20. A var referencing the file upload drop trigger.
  21. """
  22. return BaseVar(
  23. _var_name=f"e => upload_files.{id_}[1]((files) => e)",
  24. _var_type=EventChain,
  25. )
  26. @CallableVar
  27. def selected_files(id_: str = DEFAULT_UPLOAD_ID) -> BaseVar:
  28. """Get the list of selected files.
  29. Args:
  30. id_: The id of the upload to get the selected files for.
  31. Returns:
  32. A var referencing the list of selected file paths.
  33. """
  34. return BaseVar(
  35. _var_name=f"(upload_files.{id_} ? upload_files.{id_}[0]?.map((f) => (f.path || f.name)) : [])",
  36. _var_type=List[str],
  37. )
  38. @CallableEventSpec
  39. def clear_selected_files(id_: str = DEFAULT_UPLOAD_ID) -> EventSpec:
  40. """Clear the list of selected files.
  41. Args:
  42. id_: The id of the upload to clear.
  43. Returns:
  44. An event spec that clears the list of selected files when triggered.
  45. """
  46. return call_script(f"upload_files.{id_}[1]((files) => [])")
  47. def cancel_upload(upload_id: str) -> EventSpec:
  48. """Cancel an upload.
  49. Args:
  50. upload_id: The id of the upload to cancel.
  51. Returns:
  52. An event spec that cancels the upload when triggered.
  53. """
  54. return call_script(f"upload_controllers[{upload_id!r}]?.abort()")
  55. class Upload(Component):
  56. """A file upload component."""
  57. library = "react-dropzone@14.2.3"
  58. tag = "ReactDropzone"
  59. is_default = True
  60. # The list of accepted file types. This should be a dictionary of MIME types as keys and array of file formats as
  61. # values.
  62. # supported MIME types: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  63. accept: Var[Optional[Dict[str, List]]]
  64. # Whether the dropzone is disabled.
  65. disabled: Var[bool]
  66. # The maximum number of files that can be uploaded.
  67. max_files: Var[int]
  68. # The maximum file size (bytes) that can be uploaded.
  69. max_size: Var[int]
  70. # The minimum file size (bytes) that can be uploaded.
  71. min_size: Var[int]
  72. # Whether to allow multiple files to be uploaded.
  73. multiple: Var[bool] = True # type: ignore
  74. # Whether to disable click to upload.
  75. no_click: Var[bool]
  76. # Whether to disable drag and drop.
  77. no_drag: Var[bool]
  78. # Whether to disable using the space/enter keys to upload.
  79. no_keyboard: Var[bool]
  80. @classmethod
  81. def create(cls, *children, **props) -> Component:
  82. """Create an upload component.
  83. Args:
  84. *children: The children of the component.
  85. **props: The properties of the component.
  86. Returns:
  87. The upload component.
  88. """
  89. # get only upload component props
  90. supported_props = cls.get_props()
  91. upload_props = {
  92. key: value for key, value in props.items() if key in supported_props
  93. }
  94. # The file input to use.
  95. upload = Input.create(type_="file")
  96. upload.special_props = {
  97. BaseVar(_var_name="{...getInputProps()}", _var_type=None)
  98. }
  99. # The dropzone to use.
  100. zone = Box.create(
  101. upload,
  102. *children,
  103. **{k: v for k, v in props.items() if k not in supported_props},
  104. )
  105. zone.special_props = {BaseVar(_var_name="{...getRootProps()}", _var_type=None)}
  106. # Create the component.
  107. upload_props["id"] = props.get("id", DEFAULT_UPLOAD_ID)
  108. return super().create(
  109. zone, on_drop=upload_file(upload_props["id"]), **upload_props
  110. )
  111. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  112. """Get the event triggers that pass the component's value to the handler.
  113. Returns:
  114. A dict mapping the event trigger to the var that is passed to the handler.
  115. """
  116. return {
  117. **super().get_event_triggers(),
  118. constants.EventTriggers.ON_DROP: lambda e0: [e0],
  119. }
  120. def _render(self):
  121. out = super()._render()
  122. out.args = ("getRootProps", "getInputProps")
  123. return out
  124. def _get_hooks(self) -> str | None:
  125. return (
  126. (super()._get_hooks() or "")
  127. + f"""
  128. upload_files.{self.id or DEFAULT_UPLOAD_ID} = useState([]);
  129. """
  130. )
  131. def _get_imports(self) -> imports.ImportDict:
  132. return {
  133. **super()._get_imports(),
  134. f"/{constants.Dirs.STATE_PATH}": [ImportVar(tag="upload_files")],
  135. }