style.py 13 KB

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