drawer.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """Drawer components based on Radix primitives."""
  2. # Based on Vaul: https://github.com/emilkowalski/vaul
  3. # Style based on https://ui.shadcn.com/docs/components/drawer
  4. from __future__ import annotations
  5. from typing import Any, List, Literal, Optional, Union
  6. from reflex.components.component import Component, ComponentNamespace
  7. from reflex.components.radix.primitives.base import RadixPrimitiveComponent
  8. from reflex.components.radix.themes.base import Theme
  9. from reflex.components.radix.themes.layout.flex import Flex
  10. from reflex.constants.compiler import MemoizationMode
  11. from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec
  12. from reflex.vars.base import Var
  13. class DrawerComponent(RadixPrimitiveComponent):
  14. """A Drawer component."""
  15. library = "vaul"
  16. lib_dependencies: List[str] = ["@radix-ui/react-dialog@^1.0.5"]
  17. LiteralDirectionType = Literal["top", "bottom", "left", "right"]
  18. class DrawerRoot(DrawerComponent):
  19. """The Root component of a Drawer, contains all parts of a drawer."""
  20. tag = "Drawer.Root"
  21. alias = "Vaul" + tag
  22. # The open state of the drawer when it is initially rendered. Use when you do not need to control its open state.
  23. default_open: Var[bool]
  24. # Whether the drawer is open or not.
  25. open: Var[bool]
  26. # Fires when the drawer is opened or closed.
  27. on_open_change: EventHandler[passthrough_event_spec(bool)]
  28. # When `False`, it allows interaction with elements outside of the drawer without closing it. Defaults to `True`.
  29. modal: Var[bool]
  30. # Direction of the drawer. This adjusts the animations and the drag direction. Defaults to `"bottom"`
  31. direction: Var[LiteralDirectionType]
  32. # Gets triggered after the open or close animation ends, it receives an open argument with the open state of the drawer by the time the function was triggered.
  33. on_animation_end: EventHandler[passthrough_event_spec(bool)]
  34. # When `False`, dragging, clicking outside, pressing esc, etc. will not close the drawer. Use this in combination with the open prop, otherwise you won't be able to open/close the drawer.
  35. dismissible: Var[bool]
  36. # When `True`, dragging will only be possible by the handle.
  37. handle_only: Var[bool]
  38. # Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Also Accept px values, which doesn't take screen height into account.
  39. snap_points: Optional[List[Union[str, float]]]
  40. # Index of a snapPoint from which the overlay fade should be applied. Defaults to the last snap point.
  41. fade_from_index: Var[int]
  42. # Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms
  43. scroll_lock_timeout: Var[int]
  44. # When `True`, it prevents scroll restoration. Defaults to `True`.
  45. prevent_scroll_restoration: Var[bool]
  46. # Enable background scaling, it requires container element with `vaul-drawer-wrapper` attribute to scale its background.
  47. should_scale_background: Var[bool]
  48. # Number between 0 and 1 that determines when the drawer should be closed.
  49. close_threshold: Var[float]
  50. class DrawerTrigger(DrawerComponent):
  51. """The button that opens the dialog."""
  52. tag = "Drawer.Trigger"
  53. alias = "Vaul" + tag
  54. # Defaults to true, if the first child acts as the trigger.
  55. as_child: Var[bool] = Var.create(True)
  56. _memoization_mode = MemoizationMode(recursive=False)
  57. @classmethod
  58. def create(cls, *children: Any, **props: Any) -> Component:
  59. """Create a new DrawerTrigger instance.
  60. Args:
  61. *children: The children of the element.
  62. **props: The properties of the element.
  63. Returns:
  64. The new DrawerTrigger instance.
  65. """
  66. for child in children:
  67. if "on_click" in getattr(child, "event_triggers", {}):
  68. children = (Flex.create(*children),)
  69. break
  70. return super().create(*children, **props)
  71. class DrawerPortal(DrawerComponent):
  72. """Portals your drawer into the body."""
  73. tag = "Drawer.Portal"
  74. alias = "Vaul" + tag
  75. # Based on https://www.radix-ui.com/primitives/docs/components/dialog#content
  76. class DrawerContent(DrawerComponent):
  77. """Content that should be rendered in the drawer."""
  78. tag = "Drawer.Content"
  79. alias = "Vaul" + tag
  80. # Style set partially based on the source code at https://ui.shadcn.com/docs/components/drawer
  81. def _get_style(self) -> dict:
  82. """Get the style for the component.
  83. Returns:
  84. The dictionary of the component style as value and the style notation as key.
  85. """
  86. base_style = {
  87. "left": "0",
  88. "right": "0",
  89. "bottom": "0",
  90. "top": "0",
  91. "position": "fixed",
  92. "z_index": 50,
  93. "display": "flex",
  94. }
  95. style = self.style or {}
  96. base_style.update(style)
  97. return {"css": base_style}
  98. # Fired when the drawer content is opened.
  99. on_open_auto_focus: EventHandler[no_args_event_spec]
  100. # Fired when the drawer content is closed.
  101. on_close_auto_focus: EventHandler[no_args_event_spec]
  102. # Fired when the escape key is pressed.
  103. on_escape_key_down: EventHandler[no_args_event_spec]
  104. # Fired when the pointer is down outside the drawer content.
  105. on_pointer_down_outside: EventHandler[no_args_event_spec]
  106. # Fired when interacting outside the drawer content.
  107. on_interact_outside: EventHandler[no_args_event_spec]
  108. @classmethod
  109. def create(cls, *children, **props):
  110. """Create a Drawer Content.
  111. We wrap the Drawer content in an `rx.theme` to make radix themes definitions available to
  112. rendered div in the DOM. This is because Vaul Drawer injects the Drawer overlay content in a sibling
  113. div to the root div rendered by radix which contains styling definitions. Wrapping in `rx.theme`
  114. makes the styling available to the overlay.
  115. Args:
  116. *children: The list of children to use.
  117. **props: Additional properties to apply to the drawer content.
  118. Returns:
  119. The drawer content.
  120. """
  121. comp = super().create(*children, **props)
  122. return Theme.create(comp)
  123. class DrawerOverlay(DrawerComponent):
  124. """A layer that covers the inert portion of the view when the dialog is open."""
  125. tag = "Drawer.Overlay"
  126. alias = "Vaul" + tag
  127. # Style set based on the source code at https://ui.shadcn.com/docs/components/drawer
  128. def _get_style(self) -> dict:
  129. """Get the style for the component.
  130. Returns:
  131. The dictionary of the component style as value and the style notation as key.
  132. """
  133. base_style = {
  134. "position": "fixed",
  135. "left": "0",
  136. "right": "0",
  137. "bottom": "0",
  138. "top": "0",
  139. "z_index": 50,
  140. "background": "rgba(0, 0, 0, 0.5)",
  141. }
  142. style = self.style or {}
  143. base_style.update(style)
  144. return {"css": base_style}
  145. class DrawerClose(DrawerTrigger):
  146. """A button that closes the drawer."""
  147. tag = "Drawer.Close"
  148. alias = "Vaul" + tag
  149. class DrawerTitle(DrawerComponent):
  150. """A title for the drawer."""
  151. tag = "Drawer.Title"
  152. alias = "Vaul" + tag
  153. # Style set based on the source code at https://ui.shadcn.com/docs/components/drawer
  154. def _get_style(self) -> dict:
  155. """Get the style for the component.
  156. Returns:
  157. The dictionary of the component style as value and the style notation as key.
  158. """
  159. base_style = {
  160. "font-size": "1.125rem",
  161. "font-weight": "600",
  162. "line-weight": "1",
  163. "letter-spacing": "-0.05em",
  164. }
  165. style = self.style or {}
  166. base_style.update(style)
  167. return {"css": base_style}
  168. class DrawerDescription(DrawerComponent):
  169. """A description for the drawer."""
  170. tag = "Drawer.Description"
  171. alias = "Vaul" + tag
  172. # Style set based on the source code at https://ui.shadcn.com/docs/components/drawer
  173. def _get_style(self) -> dict:
  174. """Get the style for the component.
  175. Returns:
  176. The dictionary of the component style as value and the style notation as key.
  177. """
  178. base_style = {
  179. "font-size": "0.875rem",
  180. }
  181. style = self.style or {}
  182. base_style.update(style)
  183. return {"css": base_style}
  184. class DrawerHandle(DrawerComponent):
  185. """A description for the drawer."""
  186. tag = "Drawer.Handle"
  187. alias = "Vaul" + tag
  188. class Drawer(ComponentNamespace):
  189. """A namespace for Drawer components."""
  190. root = __call__ = staticmethod(DrawerRoot.create)
  191. trigger = staticmethod(DrawerTrigger.create)
  192. portal = staticmethod(DrawerPortal.create)
  193. content = staticmethod(DrawerContent.create)
  194. overlay = staticmethod(DrawerOverlay.create)
  195. close = staticmethod(DrawerClose.create)
  196. title = staticmethod(DrawerTitle.create)
  197. description = staticmethod(DrawerDescription.create)
  198. handle = staticmethod(DrawerHandle.create)
  199. drawer = Drawer()