style.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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"() => {str(base_setter)}({str(new_color_mode)})",
  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. # if isinstance(style_item, str) and REFLEX_VAR_OPENING_TAG not in style_item:
  112. # return style_item, None
  113. # Otherwise, convert to Var to collapse VarData encoded in f-string.
  114. new_var = LiteralVar.create(style_item)
  115. var_data = new_var._get_all_var_data() if new_var is not None else None
  116. return new_var, var_data
  117. def convert_list(
  118. responsive_list: list[str | dict | Var],
  119. ) -> tuple[list[str | dict[str, Var | list | dict]], VarData | None]:
  120. """Format a responsive value list.
  121. Args:
  122. responsive_list: The raw responsive value list (one value per breakpoint).
  123. Returns:
  124. The recursively converted responsive value list and any associated VarData.
  125. """
  126. converted_value = []
  127. item_var_datas = []
  128. for responsive_item in responsive_list:
  129. if isinstance(responsive_item, dict):
  130. # Recursively format nested style dictionaries.
  131. item, item_var_data = convert(responsive_item)
  132. else:
  133. item, item_var_data = convert_item(responsive_item)
  134. converted_value.append(item)
  135. item_var_datas.append(item_var_data)
  136. return converted_value, VarData.merge(*item_var_datas)
  137. def convert(
  138. style_dict: dict[str, Var | dict | list | str],
  139. ) -> tuple[dict[str, str | list | dict], VarData | None]:
  140. """Format a style dictionary.
  141. Args:
  142. style_dict: The style dictionary to format.
  143. Returns:
  144. The formatted style dictionary.
  145. """
  146. var_data = None # Track import/hook data from any Vars in the style dict.
  147. out = {}
  148. def update_out_dict(return_value, keys_to_update):
  149. for k in keys_to_update:
  150. out[k] = return_value
  151. for key, value in style_dict.items():
  152. keys = (
  153. format_style_key(key)
  154. if not isinstance(value, (dict, ObjectVar))
  155. or (
  156. isinstance(value, Breakpoints)
  157. and all(not isinstance(v, dict) for v in value.values())
  158. )
  159. or (
  160. isinstance(value, ObjectVar)
  161. and not issubclass(get_origin(value._var_type) or value._var_type, dict)
  162. )
  163. else (key,)
  164. )
  165. if isinstance(value, Var):
  166. return_val = value
  167. new_var_data = value._get_all_var_data()
  168. update_out_dict(return_val, keys)
  169. elif isinstance(value, dict):
  170. # Recursively format nested style dictionaries.
  171. return_val, new_var_data = convert(value)
  172. update_out_dict(return_val, keys)
  173. elif isinstance(value, list):
  174. # Responsive value is a list of dict or value
  175. return_val, new_var_data = convert_list(value)
  176. update_out_dict(return_val, keys)
  177. else:
  178. return_val, new_var_data = convert_item(value)
  179. update_out_dict(return_val, keys)
  180. # Combine all the collected VarData instances.
  181. var_data = VarData.merge(var_data, new_var_data)
  182. if isinstance(style_dict, Breakpoints):
  183. out = Breakpoints(out).factorize()
  184. return out, var_data
  185. def format_style_key(key: str) -> Tuple[str, ...]:
  186. """Convert style keys to camel case and convert shorthand
  187. styles names to their corresponding css names.
  188. Args:
  189. key: The style key to convert.
  190. Returns:
  191. Tuple of css style names corresponding to the key provided.
  192. """
  193. key = format.to_camel_case(key, allow_hyphens=True)
  194. return STYLE_PROP_SHORTHAND_MAPPING.get(key, (key,))
  195. class Style(dict):
  196. """A style dictionary."""
  197. def __init__(self, style_dict: dict | None = None, **kwargs):
  198. """Initialize the style.
  199. Args:
  200. style_dict: The style dictionary.
  201. kwargs: Other key value pairs to apply to the dict update.
  202. """
  203. if style_dict:
  204. style_dict.update(kwargs)
  205. else:
  206. style_dict = kwargs
  207. style_dict, self._var_data = convert(style_dict or {})
  208. super().__init__(style_dict)
  209. def update(self, style_dict: dict | None, **kwargs):
  210. """Update the style.
  211. Args:
  212. style_dict: The style dictionary.
  213. kwargs: Other key value pairs to apply to the dict update.
  214. """
  215. if not isinstance(style_dict, Style):
  216. converted_dict = type(self)(style_dict)
  217. else:
  218. converted_dict = style_dict
  219. if kwargs:
  220. if converted_dict is None:
  221. converted_dict = type(self)(kwargs)
  222. else:
  223. converted_dict.update(kwargs)
  224. # Combine our VarData with that of any Vars in the style_dict that was passed.
  225. self._var_data = VarData.merge(self._var_data, converted_dict._var_data)
  226. super().update(converted_dict)
  227. def __setitem__(self, key: str, value: Any):
  228. """Set an item in the style.
  229. Args:
  230. key: The key to set.
  231. value: The value to set.
  232. """
  233. # Create a Var to collapse VarData encoded in f-string.
  234. _var = LiteralVar.create(value)
  235. if _var is not None:
  236. # Carry the imports/hooks when setting a Var as a value.
  237. self._var_data = VarData.merge(self._var_data, _var._get_all_var_data())
  238. super().__setitem__(key, value)
  239. def _format_emotion_style_pseudo_selector(key: str) -> str:
  240. """Format a pseudo selector for emotion CSS-in-JS.
  241. Args:
  242. key: Underscore-prefixed or colon-prefixed pseudo selector key (_hover/:hover).
  243. Returns:
  244. A self-referential pseudo selector key (&:hover).
  245. """
  246. prefix = None
  247. if key.startswith("_"):
  248. prefix = "&:"
  249. key = key[1:]
  250. if key.startswith(":"):
  251. # Handle pseudo selectors and elements in native format.
  252. prefix = "&"
  253. if prefix is not None:
  254. return prefix + format.to_kebab_case(key)
  255. return key
  256. def format_as_emotion(style_dict: dict[str, Any]) -> Style | None:
  257. """Convert the style to an emotion-compatible CSS-in-JS dict.
  258. Args:
  259. style_dict: The style dict to convert.
  260. Returns:
  261. The emotion style dict.
  262. """
  263. _var_data = style_dict._var_data if isinstance(style_dict, Style) else None
  264. emotion_style = Style()
  265. for orig_key, value in style_dict.items():
  266. key = _format_emotion_style_pseudo_selector(orig_key)
  267. if isinstance(value, (Breakpoints, list)):
  268. if isinstance(value, Breakpoints):
  269. mbps = {
  270. media_query(bp): (
  271. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  272. )
  273. for bp, bp_value in value.items()
  274. }
  275. else:
  276. # Apply media queries from responsive value list.
  277. mbps = {
  278. media_query([0, *breakpoints_values][bp]): (
  279. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  280. )
  281. for bp, bp_value in enumerate(value)
  282. }
  283. if key.startswith("&:"):
  284. emotion_style[key] = mbps
  285. else:
  286. for mq, style_sub_dict in mbps.items():
  287. emotion_style.setdefault(mq, {}).update(style_sub_dict)
  288. elif isinstance(value, dict):
  289. # Recursively format nested style dictionaries.
  290. emotion_style[key] = format_as_emotion(value)
  291. else:
  292. emotion_style[key] = value
  293. if emotion_style:
  294. if _var_data is not None:
  295. emotion_style._var_data = VarData.merge(emotion_style._var_data, _var_data)
  296. return emotion_style
  297. def convert_dict_to_style_and_format_emotion(
  298. raw_dict: dict[str, Any],
  299. ) -> dict[str, Any] | None:
  300. """Convert a dict to a style dict and then format as emotion.
  301. Args:
  302. raw_dict: The dict to convert.
  303. Returns:
  304. The emotion dict.
  305. """
  306. return format_as_emotion(Style(raw_dict))
  307. STACK_CHILDREN_FULL_WIDTH = {
  308. "& :where(.rx-Stack)": {
  309. "width": "100%",
  310. },
  311. "& :where(.rx-Stack) > :where( "
  312. "div:not(.rt-Box, .rx-Upload, .rx-Html),"
  313. "input, select, textarea, table"
  314. ")": {
  315. "width": "100%",
  316. "flex_shrink": "1",
  317. },
  318. }