style.py 9.4 KB

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