format.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. """Formatting operations."""
  2. from __future__ import annotations
  3. import base64
  4. import io
  5. import json
  6. import os
  7. import os.path as op
  8. import re
  9. import sys
  10. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type
  11. import plotly.graph_objects as go
  12. from plotly.io import to_json
  13. from reflex import constants
  14. from reflex.utils import types
  15. if TYPE_CHECKING:
  16. from reflex.components.component import ComponentStyle
  17. from reflex.event import EventChain, EventHandler, EventSpec
  18. WRAP_MAP = {
  19. "{": "}",
  20. "(": ")",
  21. "[": "]",
  22. "<": ">",
  23. '"': '"',
  24. "'": "'",
  25. "`": "`",
  26. }
  27. def get_close_char(open: str, close: Optional[str] = None) -> str:
  28. """Check if the given character is a valid brace.
  29. Args:
  30. open: The open character.
  31. close: The close character if provided.
  32. Returns:
  33. The close character.
  34. Raises:
  35. ValueError: If the open character is not a valid brace.
  36. """
  37. if close is not None:
  38. return close
  39. if open not in WRAP_MAP:
  40. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  41. return WRAP_MAP[open]
  42. def is_wrapped(text: str, open: str, close: Optional[str] = None) -> bool:
  43. """Check if the given text is wrapped in the given open and close characters.
  44. Args:
  45. text: The text to check.
  46. open: The open character.
  47. close: The close character.
  48. Returns:
  49. Whether the text is wrapped.
  50. """
  51. close = get_close_char(open, close)
  52. return text.startswith(open) and text.endswith(close)
  53. def wrap(
  54. text: str,
  55. open: str,
  56. close: Optional[str] = None,
  57. check_first: bool = True,
  58. num: int = 1,
  59. ) -> str:
  60. """Wrap the given text in the given open and close characters.
  61. Args:
  62. text: The text to wrap.
  63. open: The open character.
  64. close: The close character.
  65. check_first: Whether to check if the text is already wrapped.
  66. num: The number of times to wrap the text.
  67. Returns:
  68. The wrapped text.
  69. """
  70. close = get_close_char(open, close)
  71. # If desired, check if the text is already wrapped in braces.
  72. if check_first and is_wrapped(text=text, open=open, close=close):
  73. return text
  74. # Wrap the text in braces.
  75. return f"{open * num}{text}{close * num}"
  76. def indent(text: str, indent_level: int = 2) -> str:
  77. """Indent the given text by the given indent level.
  78. Args:
  79. text: The text to indent.
  80. indent_level: The indent level.
  81. Returns:
  82. The indented text.
  83. """
  84. lines = text.splitlines()
  85. if len(lines) < 2:
  86. return text
  87. return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep
  88. def to_snake_case(text: str) -> str:
  89. """Convert a string to snake case.
  90. The words in the text are converted to lowercase and
  91. separated by underscores.
  92. Args:
  93. text: The string to convert.
  94. Returns:
  95. The snake case string.
  96. """
  97. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  98. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
  99. def to_camel_case(text: str) -> str:
  100. """Convert a string to camel case.
  101. The first word in the text is converted to lowercase and
  102. the rest of the words are converted to title case, removing underscores.
  103. Args:
  104. text: The string to convert.
  105. Returns:
  106. The camel case string.
  107. """
  108. if "_" not in text:
  109. return text
  110. camel = "".join(
  111. word.capitalize() if i > 0 else word.lower()
  112. for i, word in enumerate(text.lstrip("_").split("_"))
  113. )
  114. prefix = "_" if text.startswith("_") else ""
  115. return prefix + camel
  116. def to_title_case(text: str) -> str:
  117. """Convert a string from snake case to title case.
  118. Args:
  119. text: The string to convert.
  120. Returns:
  121. The title case string.
  122. """
  123. return "".join(word.capitalize() for word in text.split("_"))
  124. def format_string(string: str) -> str:
  125. """Format the given string as a JS string literal..
  126. Args:
  127. string: The string to format.
  128. Returns:
  129. The formatted string.
  130. """
  131. # Escape backticks.
  132. string = string.replace(r"\`", "`")
  133. string = string.replace("`", r"\`")
  134. # Wrap the string so it looks like {`string`}.
  135. string = wrap(string, "`")
  136. string = wrap(string, "{")
  137. return string
  138. def format_route(route: str) -> str:
  139. """Format the given route.
  140. Args:
  141. route: The route to format.
  142. Returns:
  143. The formatted route.
  144. """
  145. # Strip the route.
  146. route = route.strip("/")
  147. route = to_snake_case(route).replace("_", "-")
  148. # If the route is empty, return the index route.
  149. if route == "":
  150. return constants.INDEX_ROUTE
  151. return route
  152. def format_cond(
  153. cond: str,
  154. true_value: str,
  155. false_value: str = '""',
  156. is_prop=False,
  157. ) -> str:
  158. """Format a conditional expression.
  159. Args:
  160. cond: The cond.
  161. true_value: The value to return if the cond is true.
  162. false_value: The value to return if the cond is false.
  163. is_prop: Whether the cond is a prop
  164. Returns:
  165. The formatted conditional expression.
  166. """
  167. # Import here to avoid circular imports.
  168. from reflex.vars import Var
  169. # Use Python truthiness.
  170. cond = f"isTrue({cond})"
  171. # Format prop conds.
  172. if is_prop:
  173. prop1 = Var.create_safe(true_value, is_string=type(true_value) is str).set(
  174. is_local=True
  175. ) # type: ignore
  176. prop2 = Var.create_safe(false_value, is_string=type(false_value) is str).set(
  177. is_local=True
  178. ) # type: ignore
  179. return f"{cond} ? {prop1} : {prop2}".replace("{", "").replace("}", "")
  180. # Format component conds.
  181. return wrap(f"{cond} ? {true_value} : {false_value}", "{")
  182. def get_event_handler_parts(handler: EventHandler) -> Tuple[str, str]:
  183. """Get the state and function name of an event handler.
  184. Args:
  185. handler: The event handler to get the parts of.
  186. Returns:
  187. The state and function name.
  188. """
  189. # Get the class that defines the event handler.
  190. parts = handler.fn.__qualname__.split(".")
  191. # If there's no enclosing class, just return the function name.
  192. if len(parts) == 1:
  193. return ("", parts[-1])
  194. # Get the state and the function name.
  195. state_name, name = parts[-2:]
  196. # Construct the full event handler name.
  197. try:
  198. # Try to get the state from the module.
  199. state = vars(sys.modules[handler.fn.__module__])[state_name]
  200. except Exception:
  201. # If the state isn't in the module, just return the function name.
  202. return ("", handler.fn.__qualname__)
  203. return (state.get_full_name(), name)
  204. def format_event_handler(handler: EventHandler) -> str:
  205. """Format an event handler.
  206. Args:
  207. handler: The event handler to format.
  208. Returns:
  209. The formatted function.
  210. """
  211. state, name = get_event_handler_parts(handler)
  212. if state == "":
  213. return name
  214. return f"{state}.{name}"
  215. def format_event(event_spec: EventSpec) -> str:
  216. """Format an event.
  217. Args:
  218. event_spec: The event to format.
  219. Returns:
  220. The compiled event.
  221. """
  222. args = ",".join(
  223. [
  224. ":".join(
  225. (name.name, json.dumps(val.name) if val.is_string else val.full_name)
  226. )
  227. for name, val in event_spec.args
  228. ]
  229. )
  230. event_args = [
  231. wrap(format_event_handler(event_spec.handler), '"'),
  232. ]
  233. event_args.append(wrap(args, "{"))
  234. if event_spec.client_handler_name:
  235. event_args.append(wrap(event_spec.client_handler_name, '"'))
  236. return f"E({', '.join(event_args)})"
  237. def format_full_control_event(event_chain: EventChain) -> str:
  238. """Format a fully controlled input prop.
  239. Args:
  240. event_chain: The event chain for full controlled input.
  241. Returns:
  242. The compiled event.
  243. """
  244. from reflex.compiler import templates
  245. event_spec = event_chain.events[0]
  246. arg = event_spec.args[0][1] if event_spec.args else None
  247. state_name = event_chain.state_name
  248. chain = ",".join([format_event(event) for event in event_chain.events])
  249. event = templates.FULL_CONTROL(state_name=state_name, arg=arg, chain=chain)
  250. return event
  251. def format_query_params(router_data: Dict[str, Any]) -> Dict[str, str]:
  252. """Convert back query params name to python-friendly case.
  253. Args:
  254. router_data: the router_data dict containing the query params
  255. Returns:
  256. The reformatted query params
  257. """
  258. params = router_data[constants.RouteVar.QUERY]
  259. return {k.replace("-", "_"): v for k, v in params.items()}
  260. def format_dataframe_values(value: Type) -> List[Any]:
  261. """Format dataframe values.
  262. Args:
  263. value: The value to format.
  264. Returns:
  265. Format data
  266. """
  267. if not types.is_dataframe(type(value)):
  268. return value
  269. format_data = []
  270. for data in list(value.values.tolist()):
  271. element = []
  272. for d in data:
  273. element.append(str(d) if isinstance(d, (list, tuple)) else d)
  274. format_data.append(element)
  275. return format_data
  276. def format_image_data(value: Type) -> str:
  277. """Format image data.
  278. Args:
  279. value: The value to format.
  280. Returns:
  281. Format data
  282. """
  283. buff = io.BytesIO()
  284. value.save(buff, format="PNG")
  285. image_bytes = buff.getvalue()
  286. base64_image = base64.b64encode(image_bytes).decode("utf-8")
  287. return f"data:image/png;base64,{base64_image}"
  288. def format_state(value: Any) -> Dict:
  289. """Recursively format values in the given state.
  290. Args:
  291. value: The state to format.
  292. Returns:
  293. The formatted state.
  294. Raises:
  295. TypeError: If the given value is not a valid state.
  296. """
  297. # Handle dicts.
  298. if isinstance(value, dict):
  299. return {k: format_state(v) for k, v in value.items()}
  300. # Return state vars as is.
  301. if isinstance(value, types.StateBases):
  302. return value
  303. # Convert plotly figures to JSON.
  304. if isinstance(value, go.Figure):
  305. return json.loads(to_json(value))["data"] # type: ignore
  306. # Convert pandas dataframes to JSON.
  307. if types.is_dataframe(type(value)):
  308. return {
  309. "columns": value.columns.tolist(),
  310. "data": format_dataframe_values(value),
  311. }
  312. # Convert Image objects to base64.
  313. if types.is_image(type(value)):
  314. return format_image_data(value) # type: ignore
  315. raise TypeError(
  316. "State vars must be primitive Python types, "
  317. "or subclasses of rx.Base. "
  318. f"Got var of type {type(value)}."
  319. )
  320. def format_ref(ref: str) -> str:
  321. """Format a ref.
  322. Args:
  323. ref: The ref to format.
  324. Returns:
  325. The formatted ref.
  326. """
  327. # Replace all non-word characters with underscores.
  328. clean_ref = re.sub(r"[^\w]+", "_", ref)
  329. return f"ref_{clean_ref}"
  330. def format_array_ref(refs: str, idx) -> str:
  331. """Format a ref accessed by array.
  332. Args:
  333. refs : The ref array to access.
  334. idx : The index of the ref in the array.
  335. Returns:
  336. The formatted ref.
  337. """
  338. clean_ref = re.sub(r"[^\w]+", "_", refs)
  339. if idx:
  340. idx.is_local = True
  341. return f"refs_{clean_ref}[{idx}]"
  342. else:
  343. return f"refs_{clean_ref}"
  344. def format_dict(prop: ComponentStyle) -> str:
  345. """Format a dict with vars potentially as values.
  346. Args:
  347. prop: The dict to format.
  348. Returns:
  349. The formatted dict.
  350. """
  351. # Import here to avoid circular imports.
  352. from reflex.vars import Var
  353. # Convert any var keys to strings.
  354. prop = {key: str(val) if isinstance(val, Var) else val for key, val in prop.items()}
  355. # Dump the dict to a string.
  356. fprop = json_dumps(prop)
  357. def unescape_double_quotes_in_var(m: re.Match) -> str:
  358. # Since the outer quotes are removed, the inner escaped quotes must be unescaped.
  359. return re.sub('\\\\"', '"', m.group(1))
  360. # This substitution is necessary to unwrap var values.
  361. fprop = re.sub(
  362. pattern=r"""
  363. (?<!\\) # must NOT start with a backslash
  364. " # match opening double quote of JSON value
  365. {(.*?)} # extract the value between curly braces (non-greedy)
  366. " # match must end with an unescaped double quote
  367. """,
  368. repl=unescape_double_quotes_in_var,
  369. string=fprop,
  370. flags=re.VERBOSE,
  371. )
  372. # Return the formatted dict.
  373. return fprop
  374. def format_breadcrumbs(route: str) -> list[tuple[str, str]]:
  375. """Take a route and return a list of tuple for use in breadcrumb.
  376. Args:
  377. route: The route to transform.
  378. Returns:
  379. list[tuple[str, str]]: the list of tuples for the breadcrumb.
  380. """
  381. route_parts = route.lstrip("/").split("/")
  382. # create and return breadcrumbs
  383. return [
  384. (part, op.join("/", *route_parts[: i + 1]))
  385. for i, part in enumerate(route_parts)
  386. ]
  387. def json_dumps(obj: Any) -> str:
  388. """Takes an object and returns a jsonified string.
  389. Args:
  390. obj: The object to be serialized.
  391. Returns:
  392. A string
  393. """
  394. return json.dumps(obj, ensure_ascii=False, default=list)