style.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. """Handle styling."""
  2. from __future__ import annotations
  3. from typing import Any, Literal, Mapping, Type
  4. from reflex import constants
  5. from reflex.components.core.breakpoints import Breakpoints, breakpoints_values
  6. from reflex.event import EventChain, EventHandler, EventSpec, run_script
  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 typehint_issubclass
  11. from reflex.vars import VarData
  12. from reflex.vars.base import 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. def set_color_mode(
  41. new_color_mode: LiteralColorMode | Var[LiteralColorMode],
  42. ) -> EventSpec:
  43. """Create an EventSpec Var that sets the color mode to a specific value.
  44. Note: `set_color_mode` is not a real event and cannot be triggered from a
  45. backend event handler.
  46. Args:
  47. new_color_mode: The color mode to set.
  48. Returns:
  49. The EventSpec Var that can be passed to an event trigger.
  50. """
  51. base_setter = _color_mode_var(
  52. _js_expr=constants.ColorMode.SET,
  53. ).to(FunctionVar)
  54. return run_script(
  55. base_setter.call(new_color_mode),
  56. )
  57. # Var resolves to the current color mode for the app ("light", "dark" or "system")
  58. color_mode = _color_mode_var(_js_expr=constants.ColorMode.NAME)
  59. # Var resolves to the resolved color mode for the app ("light" or "dark")
  60. resolved_color_mode = _color_mode_var(_js_expr=constants.ColorMode.RESOLVED_NAME)
  61. # Var resolves to a function invocation that toggles the color mode
  62. toggle_color_mode = _color_mode_var(
  63. _js_expr=constants.ColorMode.TOGGLE,
  64. _var_type=EventChain,
  65. )
  66. STYLE_PROP_SHORTHAND_MAPPING = {
  67. "paddingX": ("paddingInlineStart", "paddingInlineEnd"),
  68. "paddingY": ("paddingTop", "paddingBottom"),
  69. "marginX": ("marginInlineStart", "marginInlineEnd"),
  70. "marginY": ("marginTop", "marginBottom"),
  71. "bg": ("background",),
  72. "bgColor": ("backgroundColor",),
  73. # Radix components derive their font from this CSS var, not inherited from body or class.
  74. "fontFamily": ("fontFamily", "--default-font-family"),
  75. }
  76. def media_query(breakpoint_expr: str):
  77. """Create a media query selector.
  78. Args:
  79. breakpoint_expr: The CSS expression representing the breakpoint.
  80. Returns:
  81. The media query selector used as a key in emotion css dict.
  82. """
  83. return f"@media screen and (min-width: {breakpoint_expr})"
  84. def convert_item(
  85. style_item: int | str | Var,
  86. ) -> tuple[str | Var, VarData | None]:
  87. """Format a single value in a style dictionary.
  88. Args:
  89. style_item: The style item to format.
  90. Returns:
  91. The formatted style item and any associated VarData.
  92. Raises:
  93. ReflexError: If an EventHandler is used as a style value
  94. """
  95. if isinstance(style_item, EventHandler):
  96. raise ReflexError(
  97. "EventHandlers cannot be used as style values. "
  98. "Please use a Var or a literal value."
  99. )
  100. if isinstance(style_item, Var):
  101. return style_item, style_item._get_all_var_data()
  102. # Otherwise, convert to Var to collapse VarData encoded in f-string.
  103. new_var = LiteralVar.create(style_item)
  104. var_data = new_var._get_all_var_data() if new_var is not None else None
  105. return new_var, var_data
  106. def convert_list(
  107. responsive_list: list[str | dict | Var],
  108. ) -> tuple[list[str | dict[str, Var | list | dict]], VarData | None]:
  109. """Format a responsive value list.
  110. Args:
  111. responsive_list: The raw responsive value list (one value per breakpoint).
  112. Returns:
  113. The recursively converted responsive value list and any associated VarData.
  114. """
  115. converted_value = []
  116. item_var_datas = []
  117. for responsive_item in responsive_list:
  118. if isinstance(responsive_item, dict):
  119. # Recursively format nested style dictionaries.
  120. item, item_var_data = convert(responsive_item)
  121. else:
  122. item, item_var_data = convert_item(responsive_item)
  123. converted_value.append(item)
  124. item_var_datas.append(item_var_data)
  125. return converted_value, VarData.merge(*item_var_datas)
  126. def convert(
  127. style_dict: dict[str, Var | dict | list | str],
  128. ) -> tuple[dict[str, str | list | dict], VarData | None]:
  129. """Format a style dictionary.
  130. Args:
  131. style_dict: The style dictionary to format.
  132. Returns:
  133. The formatted style dictionary.
  134. """
  135. var_data = None # Track import/hook data from any Vars in the style dict.
  136. out = {}
  137. def update_out_dict(
  138. return_value: Var | dict | list | str, keys_to_update: tuple[str, ...]
  139. ):
  140. for k in keys_to_update:
  141. out[k] = return_value
  142. for key, value in style_dict.items():
  143. keys = (
  144. format_style_key(key)
  145. if not isinstance(value, (dict, ObjectVar, list))
  146. or (
  147. isinstance(value, Breakpoints)
  148. and all(not isinstance(v, dict) for v in value.values())
  149. )
  150. or (isinstance(value, list) and all(not isinstance(v, dict) for v in value))
  151. or (
  152. isinstance(value, ObjectVar)
  153. and not typehint_issubclass(value._var_type, Mapping)
  154. )
  155. else (key,)
  156. )
  157. if isinstance(value, Var):
  158. return_val = value
  159. new_var_data = value._get_all_var_data()
  160. update_out_dict(return_val, keys)
  161. elif isinstance(value, dict):
  162. # Recursively format nested style dictionaries.
  163. return_val, new_var_data = convert(value)
  164. update_out_dict(return_val, keys)
  165. elif isinstance(value, list):
  166. # Responsive value is a list of dict or value
  167. return_val, new_var_data = convert_list(value)
  168. update_out_dict(return_val, keys)
  169. else:
  170. return_val, new_var_data = convert_item(value)
  171. update_out_dict(return_val, keys)
  172. # Combine all the collected VarData instances.
  173. var_data = VarData.merge(var_data, new_var_data)
  174. if isinstance(style_dict, Breakpoints):
  175. out = Breakpoints(out).factorize()
  176. return out, var_data
  177. def format_style_key(key: str) -> tuple[str, ...]:
  178. """Convert style keys to camel case and convert shorthand
  179. styles names to their corresponding css names.
  180. Args:
  181. key: The style key to convert.
  182. Returns:
  183. Tuple of css style names corresponding to the key provided.
  184. """
  185. if key.startswith("--"):
  186. return (key,)
  187. key = format.to_camel_case(key)
  188. return STYLE_PROP_SHORTHAND_MAPPING.get(key, (key,))
  189. EMPTY_VAR_DATA = VarData()
  190. class Style(dict[str, Any]):
  191. """A style dictionary."""
  192. def __init__(self, style_dict: dict[str, Any] | None = None, **kwargs):
  193. """Initialize the style.
  194. Args:
  195. style_dict: The style dictionary.
  196. kwargs: Other key value pairs to apply to the dict update.
  197. """
  198. if style_dict:
  199. style_dict.update(kwargs)
  200. else:
  201. style_dict = kwargs
  202. if style_dict:
  203. style_dict, self._var_data = convert(style_dict)
  204. else:
  205. self._var_data = EMPTY_VAR_DATA
  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(
  236. getattr(self, "_var_data", None), _var._get_all_var_data()
  237. )
  238. super().__setitem__(key, value)
  239. def __or__(self, other: Style | dict) -> Style:
  240. """Combine two styles.
  241. Args:
  242. other: The other style to combine.
  243. Returns:
  244. The combined style.
  245. """
  246. other_var_data = None
  247. if not isinstance(other, Style):
  248. other_dict, other_var_data = convert(other)
  249. else:
  250. other_dict, other_var_data = other, other._var_data
  251. new_style = Style(super().__or__(other_dict))
  252. if self._var_data or other_var_data:
  253. new_style._var_data = VarData.merge(self._var_data, other_var_data)
  254. return new_style
  255. def _format_emotion_style_pseudo_selector(key: str) -> str:
  256. """Format a pseudo selector for emotion CSS-in-JS.
  257. Args:
  258. key: Underscore-prefixed or colon-prefixed pseudo selector key (_hover/:hover).
  259. Returns:
  260. A self-referential pseudo selector key (&:hover).
  261. """
  262. prefix = None
  263. if key.startswith("_"):
  264. prefix = "&:"
  265. key = key[1:]
  266. if key.startswith(":"):
  267. # Handle pseudo selectors and elements in native format.
  268. prefix = "&"
  269. if prefix is not None:
  270. return prefix + format.to_kebab_case(key)
  271. return key
  272. def format_as_emotion(style_dict: dict[str, Any]) -> Style | None:
  273. """Convert the style to an emotion-compatible CSS-in-JS dict.
  274. Args:
  275. style_dict: The style dict to convert.
  276. Returns:
  277. The emotion style dict.
  278. """
  279. _var_data = style_dict._var_data if isinstance(style_dict, Style) else None
  280. emotion_style = Style()
  281. for orig_key, value in style_dict.items():
  282. key = _format_emotion_style_pseudo_selector(orig_key)
  283. if isinstance(value, (Breakpoints, list)):
  284. if isinstance(value, Breakpoints):
  285. mbps = {
  286. media_query(bp): (
  287. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  288. )
  289. for bp, bp_value in value.items()
  290. }
  291. else:
  292. # Apply media queries from responsive value list.
  293. mbps = {
  294. media_query([0, *breakpoints_values][bp]): (
  295. bp_value if isinstance(bp_value, dict) else {key: bp_value}
  296. )
  297. for bp, bp_value in enumerate(value)
  298. }
  299. if key.startswith("&:"):
  300. emotion_style[key] = mbps
  301. else:
  302. for mq, style_sub_dict in mbps.items():
  303. emotion_style.setdefault(mq, {}).update(style_sub_dict)
  304. elif isinstance(value, dict):
  305. # Recursively format nested style dictionaries.
  306. emotion_style[key] = format_as_emotion(value)
  307. else:
  308. emotion_style[key] = value
  309. if emotion_style:
  310. if _var_data is not None:
  311. emotion_style._var_data = VarData.merge(emotion_style._var_data, _var_data)
  312. return emotion_style
  313. def convert_dict_to_style_and_format_emotion(
  314. raw_dict: dict[str, Any],
  315. ) -> dict[str, Any] | None:
  316. """Convert a dict to a style dict and then format as emotion.
  317. Args:
  318. raw_dict: The dict to convert.
  319. Returns:
  320. The emotion dict.
  321. """
  322. return format_as_emotion(Style(raw_dict))
  323. STACK_CHILDREN_FULL_WIDTH = {
  324. "& :where(.rx-Stack)": {
  325. "width": "100%",
  326. },
  327. "& :where(.rx-Stack) > :where( "
  328. "div:not(.rt-Box, .rx-Upload, .rx-Html),"
  329. "input, select, textarea, table"
  330. ")": {
  331. "width": "100%",
  332. "flex_shrink": "1",
  333. },
  334. }