style.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. """Handle styling."""
  2. from __future__ import annotations
  3. from typing import Any, Literal, Tuple, Type
  4. from reflex import constants
  5. from reflex.components.core.breakpoints import Breakpoints, breakpoints_values
  6. from reflex.event import EventChain, EventHandler
  7. from reflex.utils import format
  8. from reflex.utils.exceptions import ReflexError
  9. from reflex.utils.imports import ImportVar
  10. from reflex.vars import VarData
  11. from reflex.vars.base import CallableVar, LiteralVar, Var
  12. from reflex.vars.function import FunctionVar
  13. SYSTEM_COLOR_MODE: str = "system"
  14. LIGHT_COLOR_MODE: str = "light"
  15. DARK_COLOR_MODE: str = "dark"
  16. LiteralColorMode = Literal["system", "light", "dark"]
  17. # Reference the global ColorModeContext
  18. color_mode_imports = {
  19. f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="ColorModeContext")],
  20. "react": [ImportVar(tag="useContext")],
  21. }
  22. def _color_mode_var(_js_expr: str, _var_type: Type = str) -> Var:
  23. """Create a Var that destructs the _js_expr from ColorModeContext.
  24. Args:
  25. _js_expr: The name of the variable to get from ColorModeContext.
  26. _var_type: The type of the Var.
  27. Returns:
  28. The Var that resolves to the color mode.
  29. """
  30. return Var(
  31. _js_expr=_js_expr,
  32. _var_type=_var_type,
  33. _var_data=VarData(
  34. imports=color_mode_imports,
  35. hooks={f"const {{ {_js_expr} }} = useContext(ColorModeContext)": None},
  36. ),
  37. ).guess_type()
  38. @CallableVar
  39. def set_color_mode(
  40. new_color_mode: LiteralColorMode | Var[LiteralColorMode] | None = None,
  41. ) -> Var[EventChain]:
  42. """Create an EventChain Var that sets the color mode to a specific value.
  43. Note: `set_color_mode` is not a real event and cannot be triggered from a
  44. backend event handler.
  45. Args:
  46. new_color_mode: The color mode to set.
  47. Returns:
  48. The EventChain Var that can be passed to an event trigger.
  49. """
  50. base_setter = _color_mode_var(
  51. _js_expr=constants.ColorMode.SET,
  52. _var_type=EventChain,
  53. )
  54. if new_color_mode is None:
  55. return base_setter
  56. if not isinstance(new_color_mode, Var):
  57. new_color_mode = LiteralVar.create(new_color_mode)
  58. return Var(
  59. f"() => {str(base_setter)}({str(new_color_mode)})",
  60. _var_data=VarData.merge(
  61. base_setter._get_all_var_data(), new_color_mode._get_all_var_data()
  62. ),
  63. ).to(FunctionVar, EventChain) # type: ignore
  64. # Var resolves to the current color mode for the app ("light", "dark" or "system")
  65. color_mode = _color_mode_var(_js_expr=constants.ColorMode.NAME)
  66. # Var resolves to the resolved color mode for the app ("light" or "dark")
  67. resolved_color_mode = _color_mode_var(_js_expr=constants.ColorMode.RESOLVED_NAME)
  68. # Var resolves to a function invocation that toggles the color mode
  69. toggle_color_mode = _color_mode_var(
  70. _js_expr=constants.ColorMode.TOGGLE,
  71. _var_type=EventChain,
  72. )
  73. STYLE_PROP_SHORTHAND_MAPPING = {
  74. "paddingX": ("paddingInlineStart", "paddingInlineEnd"),
  75. "paddingY": ("paddingTop", "paddingBottom"),
  76. "marginX": ("marginInlineStart", "marginInlineEnd"),
  77. "marginY": ("marginTop", "marginBottom"),
  78. "bg": ("background",),
  79. "bgColor": ("backgroundColor",),
  80. # Radix components derive their font from this CSS var, not inherited from body or class.
  81. "fontFamily": ("fontFamily", "--default-font-family"),
  82. }
  83. def media_query(breakpoint_expr: str):
  84. """Create a media query selector.
  85. Args:
  86. breakpoint_expr: The CSS expression representing the breakpoint.
  87. Returns:
  88. The media query selector used as a key in emotion css dict.
  89. """
  90. return f"@media screen and (min-width: {breakpoint_expr})"
  91. def convert_item(
  92. style_item: int | str | Var,
  93. ) -> tuple[str | Var, VarData | None]:
  94. """Format a single value in a style dictionary.
  95. Args:
  96. style_item: The style item to format.
  97. Returns:
  98. The formatted style item and any associated VarData.
  99. Raises:
  100. ReflexError: If an EventHandler is used as a style value
  101. """
  102. if isinstance(style_item, EventHandler):
  103. raise ReflexError(
  104. "EventHandlers cannot be used as style values. "
  105. "Please use a Var or a literal value."
  106. )
  107. if isinstance(style_item, Var):
  108. return style_item, style_item._get_all_var_data()
  109. # if isinstance(style_item, str) and REFLEX_VAR_OPENING_TAG not in style_item:
  110. # return style_item, None
  111. # Otherwise, convert to Var to collapse VarData encoded in f-string.
  112. new_var = LiteralVar.create(style_item)
  113. var_data = new_var._get_all_var_data() if new_var is not None else None
  114. return new_var, var_data
  115. def convert_list(
  116. responsive_list: list[str | dict | Var],
  117. ) -> tuple[list[str | dict[str, Var | list | dict]], VarData | None]:
  118. """Format a responsive value list.
  119. Args:
  120. responsive_list: The raw responsive value list (one value per breakpoint).
  121. Returns:
  122. The recursively converted responsive value list and any associated VarData.
  123. """
  124. converted_value = []
  125. item_var_datas = []
  126. for responsive_item in responsive_list:
  127. if isinstance(responsive_item, dict):
  128. # Recursively format nested style dictionaries.
  129. item, item_var_data = convert(responsive_item)
  130. else:
  131. item, item_var_data = convert_item(responsive_item)
  132. converted_value.append(item)
  133. item_var_datas.append(item_var_data)
  134. return converted_value, VarData.merge(*item_var_datas)
  135. def convert(
  136. style_dict: dict[str, Var | dict | list | str],
  137. ) -> tuple[dict[str, str | list | dict], VarData | None]:
  138. """Format a style dictionary.
  139. Args:
  140. style_dict: The style dictionary to format.
  141. Returns:
  142. The formatted style dictionary.
  143. """
  144. var_data = None # Track import/hook data from any Vars in the style dict.
  145. out = {}
  146. def update_out_dict(return_value, keys_to_update):
  147. for k in keys_to_update:
  148. out[k] = return_value
  149. for key, value in style_dict.items():
  150. keys = format_style_key(key)
  151. if isinstance(value, Var):
  152. return_val = value
  153. new_var_data = value._get_all_var_data()
  154. update_out_dict(return_val, keys)
  155. elif isinstance(value, dict):
  156. # Recursively format nested style dictionaries.
  157. return_val, new_var_data = convert(value)
  158. update_out_dict(return_val, keys)
  159. elif isinstance(value, list):
  160. # Responsive value is a list of dict or value
  161. return_val, new_var_data = convert_list(value)
  162. update_out_dict(return_val, keys)
  163. else:
  164. return_val, new_var_data = convert_item(value)
  165. update_out_dict(return_val, keys)
  166. # Combine all the collected VarData instances.
  167. var_data = VarData.merge(var_data, new_var_data)
  168. if isinstance(style_dict, Breakpoints):
  169. out = Breakpoints(out).factorize()
  170. return out, var_data
  171. def format_style_key(key: str) -> Tuple[str, ...]:
  172. """Convert style keys to camel case and convert shorthand
  173. styles names to their corresponding css names.
  174. Args:
  175. key: The style key to convert.
  176. Returns:
  177. Tuple of css style names corresponding to the key provided.
  178. """
  179. key = format.to_camel_case(key, allow_hyphens=True)
  180. return STYLE_PROP_SHORTHAND_MAPPING.get(key, (key,))
  181. class Style(dict):
  182. """A style dictionary."""
  183. def __init__(self, style_dict: dict | None = None, **kwargs):
  184. """Initialize the style.
  185. Args:
  186. style_dict: The style dictionary.
  187. kwargs: Other key value pairs to apply to the dict update.
  188. """
  189. if style_dict:
  190. style_dict.update(kwargs)
  191. else:
  192. style_dict = kwargs
  193. style_dict, self._var_data = convert(style_dict or {})
  194. super().__init__(style_dict)
  195. def update(self, style_dict: dict | None, **kwargs):
  196. """Update the style.
  197. Args:
  198. style_dict: The style dictionary.
  199. kwargs: Other key value pairs to apply to the dict update.
  200. """
  201. if not isinstance(style_dict, Style):
  202. converted_dict = type(self)(style_dict)
  203. else:
  204. converted_dict = style_dict
  205. if kwargs:
  206. if converted_dict is None:
  207. converted_dict = type(self)(kwargs)
  208. else:
  209. converted_dict.update(kwargs)
  210. # Combine our VarData with that of any Vars in the style_dict that was passed.
  211. self._var_data = VarData.merge(self._var_data, converted_dict._var_data)
  212. super().update(converted_dict)
  213. def __setitem__(self, key: str, value: Any):
  214. """Set an item in the style.
  215. Args:
  216. key: The key to set.
  217. value: The value to set.
  218. """
  219. # Create a Var to collapse VarData encoded in f-string.
  220. _var = LiteralVar.create(value)
  221. if _var is not None:
  222. # Carry the imports/hooks when setting a Var as a value.
  223. self._var_data = VarData.merge(self._var_data, _var._get_all_var_data())
  224. super().__setitem__(key, value)
  225. def _format_emotion_style_pseudo_selector(key: str) -> str:
  226. """Format a pseudo selector for emotion CSS-in-JS.
  227. Args:
  228. key: Underscore-prefixed or colon-prefixed pseudo selector key (_hover).
  229. Returns:
  230. A self-referential pseudo selector key (&:hover).
  231. """
  232. prefix = None
  233. if key.startswith("_"):
  234. prefix = "&:"
  235. key = key[1:]
  236. if key.startswith(":"):
  237. # Handle pseudo selectors and elements in native format.
  238. prefix = "&"
  239. if prefix is not None:
  240. return prefix + format.to_kebab_case(key)
  241. return key
  242. def format_as_emotion(style_dict: dict[str, Any]) -> Style | None:
  243. """Convert the style to an emotion-compatible CSS-in-JS dict.
  244. Args:
  245. style_dict: The style dict to convert.
  246. Returns:
  247. The emotion style dict.
  248. """
  249. _var_data = style_dict._var_data if isinstance(style_dict, Style) else None
  250. emotion_style = Style()
  251. for orig_key, value in style_dict.items():
  252. key = _format_emotion_style_pseudo_selector(orig_key)
  253. if isinstance(value, (Breakpoints, list)):
  254. if isinstance(value, Breakpoints):
  255. mbps = {
  256. media_query(bp): (
  257. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  258. )
  259. for bp, bp_value in value.items()
  260. }
  261. else:
  262. # Apply media queries from responsive value list.
  263. mbps = {
  264. media_query([0, *breakpoints_values][bp]): (
  265. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  266. )
  267. for bp, bp_value in enumerate(value)
  268. }
  269. if key.startswith("&:"):
  270. emotion_style[key] = mbps
  271. else:
  272. for mq, style_sub_dict in mbps.items():
  273. emotion_style.setdefault(mq, {}).update(style_sub_dict)
  274. elif isinstance(value, dict):
  275. # Recursively format nested style dictionaries.
  276. emotion_style[key] = format_as_emotion(value)
  277. else:
  278. emotion_style[key] = value
  279. if emotion_style:
  280. if _var_data is not None:
  281. emotion_style._var_data = VarData.merge(emotion_style._var_data, _var_data)
  282. return emotion_style
  283. def convert_dict_to_style_and_format_emotion(
  284. raw_dict: dict[str, Any],
  285. ) -> dict[str, Any] | None:
  286. """Convert a dict to a style dict and then format as emotion.
  287. Args:
  288. raw_dict: The dict to convert.
  289. Returns:
  290. The emotion dict.
  291. """
  292. return format_as_emotion(Style(raw_dict))
  293. STACK_CHILDREN_FULL_WIDTH = {
  294. "& :where(.rx-Stack)": {
  295. "width": "100%",
  296. },
  297. "& :where(.rx-Stack) > :where( "
  298. "div:not(.rt-Box, .rx-Upload, .rx-Html),"
  299. "input, select, textarea, table"
  300. ")": {
  301. "width": "100%",
  302. "flex_shrink": "1",
  303. },
  304. }