format.py 11 KB

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