1
0

drawer.py 9.0 KB

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