style.py 8.6 KB

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