base.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. """Base classes for radix-themes components."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, Literal
  4. from reflex.components import Component
  5. from reflex.components.tags import Tag
  6. from reflex.config import get_config
  7. from reflex.ivars.base import ImmutableVar
  8. from reflex.utils.imports import ImportDict, ImportVar
  9. from reflex.vars import Var
  10. LiteralAlign = Literal["start", "center", "end", "baseline", "stretch"]
  11. LiteralJustify = Literal["start", "center", "end", "between"]
  12. LiteralSpacing = Literal["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  13. LiteralVariant = Literal["classic", "solid", "soft", "surface", "outline", "ghost"]
  14. LiteralAppearance = Literal["inherit", "light", "dark"]
  15. LiteralGrayColor = Literal["gray", "mauve", "slate", "sage", "olive", "sand", "auto"]
  16. LiteralPanelBackground = Literal["solid", "translucent"]
  17. LiteralRadius = Literal["none", "small", "medium", "large", "full"]
  18. LiteralScaling = Literal["90%", "95%", "100%", "105%", "110%"]
  19. LiteralAccentColor = Literal[
  20. "tomato",
  21. "red",
  22. "ruby",
  23. "crimson",
  24. "pink",
  25. "plum",
  26. "purple",
  27. "violet",
  28. "iris",
  29. "indigo",
  30. "blue",
  31. "cyan",
  32. "teal",
  33. "jade",
  34. "green",
  35. "grass",
  36. "brown",
  37. "orange",
  38. "sky",
  39. "mint",
  40. "lime",
  41. "yellow",
  42. "amber",
  43. "gold",
  44. "bronze",
  45. "gray",
  46. ]
  47. class CommonMarginProps(Component):
  48. """Many radix-themes elements accept shorthand margin props."""
  49. # Margin: "0" - "9"
  50. m: Var[LiteralSpacing]
  51. # Margin horizontal: "0" - "9"
  52. mx: Var[LiteralSpacing]
  53. # Margin vertical: "0" - "9"
  54. my: Var[LiteralSpacing]
  55. # Margin top: "0" - "9"
  56. mt: Var[LiteralSpacing]
  57. # Margin right: "0" - "9"
  58. mr: Var[LiteralSpacing]
  59. # Margin bottom: "0" - "9"
  60. mb: Var[LiteralSpacing]
  61. # Margin left: "0" - "9"
  62. ml: Var[LiteralSpacing]
  63. class RadixLoadingProp(Component):
  64. """Base class for components that can be in a loading state."""
  65. # If set, show an rx.spinner instead of the component children.
  66. loading: Var[bool]
  67. class RadixThemesComponent(Component):
  68. """Base class for all @radix-ui/themes components."""
  69. library = "@radix-ui/themes@^3.0.0"
  70. # "Fake" prop color_scheme is used to avoid shadowing CSS prop "color".
  71. _rename_props: Dict[str, str] = {"colorScheme": "color"}
  72. @classmethod
  73. def create(
  74. cls,
  75. *children,
  76. **props,
  77. ) -> Component:
  78. """Create a new component instance.
  79. Will prepend "RadixThemes" to the component tag to avoid conflicts with
  80. other UI libraries for common names, like Text and Button.
  81. Args:
  82. *children: Child components.
  83. **props: Component properties.
  84. Returns:
  85. A new component instance.
  86. """
  87. component = super().create(*children, **props)
  88. if component.library is None:
  89. component.library = RadixThemesComponent.__fields__["library"].default
  90. component.alias = "RadixThemes" + (
  91. component.tag or component.__class__.__name__
  92. )
  93. # value = props.get("value")
  94. # if value is not None and component.alias == "RadixThemesSelect.Root":
  95. # lv = LiteralVar.create(value)
  96. # print(repr(lv))
  97. # print(f"Warning: Value {value} is not used in {component.alias}.")
  98. return component
  99. @staticmethod
  100. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  101. return {
  102. (45, "RadixThemesColorModeProvider"): RadixThemesColorModeProvider.create(),
  103. }
  104. class RadixThemesTriggerComponent(RadixThemesComponent):
  105. """Base class for Trigger, Close, Cancel, and Accept components.
  106. These components trigger some action in an overlay component that depends on the
  107. on_click event, and thus if a child is provided and has on_click specified, it
  108. will overtake the internal action, unless it is wrapped in some inert component,
  109. in this case, a Flex.
  110. """
  111. @classmethod
  112. def create(cls, *children: Any, **props: Any) -> Component:
  113. """Create a new RadixThemesTriggerComponent instance.
  114. Args:
  115. children: The children of the component.
  116. props: The properties of the component.
  117. Returns:
  118. The new RadixThemesTriggerComponent instance.
  119. """
  120. from .layout.flex import Flex
  121. for child in children:
  122. if "on_click" in getattr(child, "event_triggers", {}):
  123. children = (Flex.create(*children),)
  124. break
  125. return super().create(*children, **props)
  126. class Theme(RadixThemesComponent):
  127. """A theme provider for radix components.
  128. This should be applied as `App.theme` to apply the theme to all radix
  129. components in the app with the given settings.
  130. It can also be used in a normal page to apply specified properties to all
  131. child elements as an override of the main theme.
  132. """
  133. tag = "Theme"
  134. # Whether to apply the themes background color to the theme node. Defaults to True.
  135. has_background: Var[bool]
  136. # Override light or dark mode theme: "inherit" | "light" | "dark". Defaults to "inherit".
  137. appearance: Var[LiteralAppearance]
  138. # The color used for default buttons, typography, backgrounds, etc
  139. accent_color: Var[LiteralAccentColor]
  140. # The shade of gray, defaults to "auto".
  141. gray_color: Var[LiteralGrayColor]
  142. # Whether panel backgrounds are translucent: "solid" | "translucent" (default)
  143. panel_background: Var[LiteralPanelBackground]
  144. # Element border radius: "none" | "small" | "medium" | "large" | "full". Defaults to "medium".
  145. radius: Var[LiteralRadius]
  146. # Scale of all theme items: "90%" | "95%" | "100%" | "105%" | "110%". Defaults to "100%"
  147. scaling: Var[LiteralScaling]
  148. @classmethod
  149. def create(
  150. cls,
  151. *children,
  152. color_mode: LiteralAppearance | None = None,
  153. theme_panel: bool = False,
  154. **props,
  155. ) -> Component:
  156. """Create a new Radix Theme specification.
  157. Args:
  158. *children: Child components.
  159. color_mode: Map to appearance prop.
  160. theme_panel: Whether to include a panel for editing the theme.
  161. **props: Component properties.
  162. Returns:
  163. A new component instance.
  164. """
  165. if color_mode is not None:
  166. props["appearance"] = color_mode
  167. if theme_panel:
  168. children = [ThemePanel.create(), *children]
  169. return super().create(*children, **props)
  170. def add_imports(self) -> ImportDict | list[ImportDict]:
  171. """Add imports for the Theme component.
  172. Returns:
  173. The import dict.
  174. """
  175. _imports: ImportDict = {
  176. "/utils/theme.js": [ImportVar(tag="theme", is_default=True)],
  177. }
  178. if get_config().tailwind is None:
  179. # When tailwind is disabled, import the radix-ui styles directly because they will
  180. # not be included in the tailwind.css file.
  181. _imports[""] = ImportVar(
  182. tag="@radix-ui/themes/styles.css",
  183. install=False,
  184. )
  185. return _imports
  186. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  187. tag = super()._render(props)
  188. tag.add_props(
  189. css=ImmutableVar.create(
  190. f"{{...theme.styles.global[':root'], ...theme.styles.global.body}}"
  191. ),
  192. )
  193. return tag
  194. class ThemePanel(RadixThemesComponent):
  195. """Visual editor for creating and editing themes.
  196. Include as a child component of Theme to use in your app.
  197. """
  198. tag = "ThemePanel"
  199. # Whether the panel is open. Defaults to False.
  200. default_open: Var[bool]
  201. def add_imports(self) -> dict[str, str]:
  202. """Add imports for the ThemePanel component.
  203. Returns:
  204. The import dict.
  205. """
  206. return {"react": "useEffect"}
  207. class RadixThemesColorModeProvider(Component):
  208. """Next-themes integration for radix themes components."""
  209. library = "/components/reflex/radix_themes_color_mode_provider.js"
  210. tag = "RadixThemesColorModeProvider"
  211. is_default = True
  212. theme = Theme.create
  213. theme_panel = ThemePanel.create