style.py 12 KB

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