upload.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """A file upload component."""
  2. from typing import Dict, List, Optional
  3. from pynecone.components.component import EVENT_ARG, Component
  4. from pynecone.components.forms.input import Input
  5. from pynecone.components.layout.box import Box
  6. from pynecone.event import EventChain
  7. from pynecone.var import BaseVar, Var
  8. upload_file = BaseVar(name="e => File(e)", type_=EventChain)
  9. class Upload(Component):
  10. """A file upload component."""
  11. library = "react-dropzone"
  12. tag = "ReactDropzone"
  13. # The list of accepted file types.
  14. accept: Var[Optional[List[str]]]
  15. # Whether the dropzone is disabled.
  16. disabled: Var[bool]
  17. # The maximum number of files that can be uploaded.
  18. max_files: Var[int]
  19. # The maximum file size (bytes) that can be uploaded.
  20. max_size: Var[int]
  21. # The minimum file size (bytes) that can be uploaded.
  22. min_size: Var[int]
  23. # Whether to allow multiple files to be uploaded.
  24. multiple: Var[bool] = True # type: ignore
  25. # Whether to disable click to upload.
  26. no_click: Var[bool]
  27. # Whether to disable drag and drop.
  28. no_drag: Var[bool]
  29. # Whether to disable using the space/enter keys to upload.
  30. no_keyboard: Var[bool]
  31. @classmethod
  32. def create(cls, *children, **props) -> Component:
  33. """Create an upload component.
  34. Args:
  35. children: The children of the component.
  36. props: The properties of the component.
  37. Returns:
  38. The upload component.
  39. """
  40. # get only upload component props
  41. supported_props = cls.get_props()
  42. upload_props = {
  43. key: value for key, value in props.items() if key in supported_props
  44. }
  45. # The file input to use.
  46. upload = Input.create(type_="file")
  47. upload.special_props = {BaseVar(name="{...getInputProps()}", type_=None)}
  48. # The dropzone to use.
  49. zone = Box.create(
  50. upload,
  51. *children,
  52. **{k: v for k, v in props.items() if k not in supported_props}
  53. )
  54. zone.special_props = {BaseVar(name="{...getRootProps()}", type_=None)}
  55. # Create the component.
  56. return super().create(zone, on_drop=upload_file, **upload_props)
  57. @classmethod
  58. def get_controlled_triggers(cls) -> Dict[str, Var]:
  59. """Get the event triggers that pass the component's value to the handler.
  60. Returns:
  61. A dict mapping the event trigger to the var that is passed to the handler.
  62. """
  63. return {
  64. "on_drop": EVENT_ARG,
  65. }
  66. def _render(self):
  67. out = super()._render()
  68. out.args = ("getRootProps", "getInputProps")
  69. return out