format.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. """Formatting operations."""
  2. from __future__ import annotations
  3. import inspect
  4. import json
  5. import os
  6. import re
  7. import sys
  8. from typing import TYPE_CHECKING, Any, Union
  9. from reflex import constants
  10. from reflex.utils import exceptions, serializers, types
  11. from reflex.utils.serializers import serialize
  12. from reflex.vars import Var
  13. if TYPE_CHECKING:
  14. from reflex.components.component import ComponentStyle
  15. from reflex.event import EventChain, EventHandler, EventSpec
  16. WRAP_MAP = {
  17. "{": "}",
  18. "(": ")",
  19. "[": "]",
  20. "<": ">",
  21. '"': '"',
  22. "'": "'",
  23. "`": "`",
  24. }
  25. def get_close_char(open: str, close: str | None = None) -> str:
  26. """Check if the given character is a valid brace.
  27. Args:
  28. open: The open character.
  29. close: The close character if provided.
  30. Returns:
  31. The close character.
  32. Raises:
  33. ValueError: If the open character is not a valid brace.
  34. """
  35. if close is not None:
  36. return close
  37. if open not in WRAP_MAP:
  38. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  39. return WRAP_MAP[open]
  40. def is_wrapped(text: str, open: str, close: str | None = None) -> bool:
  41. """Check if the given text is wrapped in the given open and close characters.
  42. Args:
  43. text: The text to check.
  44. open: The open character.
  45. close: The close character.
  46. Returns:
  47. Whether the text is wrapped.
  48. """
  49. close = get_close_char(open, close)
  50. return text.startswith(open) and text.endswith(close)
  51. def wrap(
  52. text: str,
  53. open: str,
  54. close: str | None = None,
  55. check_first: bool = True,
  56. num: int = 1,
  57. ) -> str:
  58. """Wrap the given text in the given open and close characters.
  59. Args:
  60. text: The text to wrap.
  61. open: The open character.
  62. close: The close character.
  63. check_first: Whether to check if the text is already wrapped.
  64. num: The number of times to wrap the text.
  65. Returns:
  66. The wrapped text.
  67. """
  68. close = get_close_char(open, close)
  69. # If desired, check if the text is already wrapped in braces.
  70. if check_first and is_wrapped(text=text, open=open, close=close):
  71. return text
  72. # Wrap the text in braces.
  73. return f"{open * num}{text}{close * num}"
  74. def indent(text: str, indent_level: int = 2) -> str:
  75. """Indent the given text by the given indent level.
  76. Args:
  77. text: The text to indent.
  78. indent_level: The indent level.
  79. Returns:
  80. The indented text.
  81. """
  82. lines = text.splitlines()
  83. if len(lines) < 2:
  84. return text
  85. return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep
  86. def to_snake_case(text: str) -> str:
  87. """Convert a string to snake case.
  88. The words in the text are converted to lowercase and
  89. separated by underscores.
  90. Args:
  91. text: The string to convert.
  92. Returns:
  93. The snake case string.
  94. """
  95. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  96. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
  97. def to_camel_case(text: str) -> str:
  98. """Convert a string to camel case.
  99. The first word in the text is converted to lowercase and
  100. the rest of the words are converted to title case, removing underscores.
  101. Args:
  102. text: The string to convert.
  103. Returns:
  104. The camel case string.
  105. """
  106. if "_" not in text:
  107. return text
  108. camel = "".join(
  109. word.capitalize() if i > 0 else word.lower()
  110. for i, word in enumerate(text.lstrip("_").split("_"))
  111. )
  112. prefix = "_" if text.startswith("_") else ""
  113. return prefix + camel
  114. def to_title_case(text: str) -> str:
  115. """Convert a string from snake case to title case.
  116. Args:
  117. text: The string to convert.
  118. Returns:
  119. The title case string.
  120. """
  121. return "".join(word.capitalize() for word in text.split("_"))
  122. def to_kebab_case(text: str) -> str:
  123. """Convert a string to kebab case.
  124. The words in the text are converted to lowercase and
  125. separated by hyphens.
  126. Args:
  127. text: The string to convert.
  128. Returns:
  129. The title case string.
  130. """
  131. return to_snake_case(text).replace("_", "-")
  132. def format_string(string: str) -> str:
  133. """Format the given string as a JS string literal..
  134. Args:
  135. string: The string to format.
  136. Returns:
  137. The formatted string.
  138. """
  139. # Escape backticks.
  140. string = string.replace(r"\`", "`")
  141. string = string.replace("`", r"\`")
  142. # Wrap the string so it looks like {`string`}.
  143. string = wrap(string, "`")
  144. string = wrap(string, "{")
  145. return string
  146. def format_var(var: Var) -> str:
  147. """Format the given Var as a javascript value.
  148. Args:
  149. var: The Var to format.
  150. Returns:
  151. The formatted Var.
  152. """
  153. if not var._var_is_local or var._var_is_string:
  154. return str(var)
  155. if types._issubclass(var._var_type, str):
  156. return format_string(var._var_full_name)
  157. if is_wrapped(var._var_full_name, "{"):
  158. return var._var_full_name
  159. return json_dumps(var._var_full_name)
  160. def format_route(route: str, format_case=True) -> str:
  161. """Format the given route.
  162. Args:
  163. route: The route to format.
  164. format_case: whether to format case to kebab case.
  165. Returns:
  166. The formatted route.
  167. """
  168. route = route.strip("/")
  169. # Strip the route and format casing.
  170. if format_case:
  171. route = to_kebab_case(route)
  172. # If the route is empty, return the index route.
  173. if route == "":
  174. return constants.PageNames.INDEX_ROUTE
  175. return route
  176. def format_cond(
  177. cond: str,
  178. true_value: str,
  179. false_value: str = '""',
  180. is_prop=False,
  181. ) -> str:
  182. """Format a conditional expression.
  183. Args:
  184. cond: The cond.
  185. true_value: The value to return if the cond is true.
  186. false_value: The value to return if the cond is false.
  187. is_prop: Whether the cond is a prop
  188. Returns:
  189. The formatted conditional expression.
  190. """
  191. # Import here to avoid circular imports.
  192. from reflex.vars import Var
  193. # Use Python truthiness.
  194. cond = f"isTrue({cond})"
  195. # Format prop conds.
  196. if is_prop:
  197. prop1 = Var.create_safe(
  198. true_value,
  199. _var_is_string=type(true_value) is str,
  200. )
  201. prop1._var_is_local = True
  202. prop2 = Var.create_safe(
  203. false_value,
  204. _var_is_string=type(false_value) is str,
  205. )
  206. prop2._var_is_local = True
  207. return f"{cond} ? {prop1} : {prop2}".replace("{", "").replace("}", "")
  208. # Format component conds.
  209. return wrap(f"{cond} ? {true_value} : {false_value}", "{")
  210. def format_prop(
  211. prop: Union[Var, EventChain, ComponentStyle, str],
  212. ) -> Union[int, float, str]:
  213. """Format a prop.
  214. Args:
  215. prop: The prop to format.
  216. Returns:
  217. The formatted prop to display within a tag.
  218. Raises:
  219. exceptions.InvalidStylePropError: If the style prop value is not a valid type.
  220. TypeError: If the prop is not valid.
  221. """
  222. # import here to avoid circular import.
  223. from reflex.event import EVENT_ARG, EventChain
  224. try:
  225. # Handle var props.
  226. if isinstance(prop, Var):
  227. if not prop._var_is_local or prop._var_is_string:
  228. return str(prop)
  229. if types._issubclass(prop._var_type, str):
  230. return format_string(prop._var_full_name)
  231. prop = prop._var_full_name
  232. # Handle event props.
  233. elif isinstance(prop, EventChain):
  234. if prop.args_spec is None:
  235. arg_def = f"{EVENT_ARG}"
  236. else:
  237. sig = inspect.signature(prop.args_spec)
  238. if sig.parameters:
  239. arg_def = ",".join(f"_{p}" for p in sig.parameters)
  240. arg_def = f"({arg_def})"
  241. else:
  242. # add a default argument for addEvents if none were specified in prop.args_spec
  243. # used to trigger the preventDefault() on the event.
  244. arg_def = "(_e)"
  245. chain = ",".join([format_event(event) for event in prop.events])
  246. event = f"addEvents([{chain}], {arg_def})"
  247. prop = f"{arg_def} => {event}"
  248. # Handle other types.
  249. elif isinstance(prop, str):
  250. if is_wrapped(prop, "{"):
  251. return prop
  252. return json_dumps(prop)
  253. # For dictionaries, convert any properties to strings.
  254. elif isinstance(prop, dict):
  255. prop = serializers.serialize_dict(prop) # type: ignore
  256. else:
  257. # Dump the prop as JSON.
  258. prop = json_dumps(prop)
  259. except exceptions.InvalidStylePropError:
  260. raise
  261. except TypeError as e:
  262. raise TypeError(f"Could not format prop: {prop} of type {type(prop)}") from e
  263. # Wrap the variable in braces.
  264. assert isinstance(prop, str), "The prop must be a string."
  265. return wrap(prop, "{", check_first=False)
  266. def format_props(*single_props, **key_value_props) -> list[str]:
  267. """Format the tag's props.
  268. Args:
  269. single_props: Props that are not key-value pairs.
  270. key_value_props: Props that are key-value pairs.
  271. Returns:
  272. The formatted props list.
  273. """
  274. # Format all the props.
  275. return [
  276. f"{name}={format_prop(prop)}"
  277. for name, prop in sorted(key_value_props.items())
  278. if prop is not None
  279. ] + [str(prop) for prop in single_props]
  280. def get_event_handler_parts(handler: EventHandler) -> tuple[str, str]:
  281. """Get the state and function name of an event handler.
  282. Args:
  283. handler: The event handler to get the parts of.
  284. Returns:
  285. The state and function name.
  286. """
  287. # Get the class that defines the event handler.
  288. parts = handler.fn.__qualname__.split(".")
  289. # If there's no enclosing class, just return the function name.
  290. if len(parts) == 1:
  291. return ("", parts[-1])
  292. # Get the state and the function name.
  293. state_name, name = parts[-2:]
  294. # Construct the full event handler name.
  295. try:
  296. # Try to get the state from the module.
  297. state = vars(sys.modules[handler.fn.__module__])[state_name]
  298. except Exception:
  299. # If the state isn't in the module, just return the function name.
  300. return ("", to_snake_case(handler.fn.__qualname__))
  301. return (state.get_full_name(), name)
  302. def format_event_handler(handler: EventHandler) -> str:
  303. """Format an event handler.
  304. Args:
  305. handler: The event handler to format.
  306. Returns:
  307. The formatted function.
  308. """
  309. state, name = get_event_handler_parts(handler)
  310. if state == "":
  311. return name
  312. return f"{state}.{name}"
  313. def format_event(event_spec: EventSpec) -> str:
  314. """Format an event.
  315. Args:
  316. event_spec: The event to format.
  317. Returns:
  318. The compiled event.
  319. """
  320. args = ",".join(
  321. [
  322. ":".join(
  323. (
  324. name._var_name,
  325. wrap(json.dumps(val._var_name).strip('"'), "`")
  326. if val._var_is_string
  327. else val._var_full_name,
  328. )
  329. )
  330. for name, val in event_spec.args
  331. ]
  332. )
  333. event_args = [
  334. wrap(format_event_handler(event_spec.handler), '"'),
  335. ]
  336. event_args.append(wrap(args, "{"))
  337. if event_spec.client_handler_name:
  338. event_args.append(wrap(event_spec.client_handler_name, '"'))
  339. return f"Event({', '.join(event_args)})"
  340. def format_event_chain(
  341. event_chain: EventChain | Var[EventChain],
  342. event_arg: Var | None = None,
  343. ) -> str:
  344. """Format an event chain as a javascript invocation.
  345. Args:
  346. event_chain: The event chain to queue on the frontend.
  347. event_arg: The browser-native event (only used to preventDefault).
  348. Returns:
  349. Compiled javascript code to queue the given event chain on the frontend.
  350. Raises:
  351. ValueError: When the given event chain is not a valid event chain.
  352. """
  353. if isinstance(event_chain, Var):
  354. from reflex.event import EventChain
  355. if event_chain._var_type is not EventChain:
  356. raise ValueError(f"Invalid event chain: {event_chain}")
  357. return "".join(
  358. [
  359. "(() => {",
  360. format_var(event_chain),
  361. f"; preventDefault({format_var(event_arg)})" if event_arg else "",
  362. "})()",
  363. ]
  364. )
  365. chain = ",".join([format_event(event) for event in event_chain.events])
  366. return "".join(
  367. [
  368. f"addEvents([{chain}]",
  369. f", {format_var(event_arg)}" if event_arg else "",
  370. ")",
  371. ]
  372. )
  373. def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
  374. """Convert back query params name to python-friendly case.
  375. Args:
  376. router_data: the router_data dict containing the query params
  377. Returns:
  378. The reformatted query params
  379. """
  380. params = router_data[constants.RouteVar.QUERY]
  381. return {k.replace("-", "_"): v for k, v in params.items()}
  382. def format_state(value: Any) -> Any:
  383. """Recursively format values in the given state.
  384. Args:
  385. value: The state to format.
  386. Returns:
  387. The formatted state.
  388. Raises:
  389. TypeError: If the given value is not a valid state.
  390. """
  391. # Handle dicts.
  392. if isinstance(value, dict):
  393. return {k: format_state(v) for k, v in value.items()}
  394. # Handle lists, sets, typles.
  395. if isinstance(value, types.StateIterBases):
  396. return [format_state(v) for v in value]
  397. # Return state vars as is.
  398. if isinstance(value, types.StateBases):
  399. return value
  400. # Serialize the value.
  401. serialized = serialize(value)
  402. if serialized is not None:
  403. return serialized
  404. raise TypeError(f"No JSON serializer found for var {value} of type {type(value)}.")
  405. def format_ref(ref: str) -> str:
  406. """Format a ref.
  407. Args:
  408. ref: The ref to format.
  409. Returns:
  410. The formatted ref.
  411. """
  412. # Replace all non-word characters with underscores.
  413. clean_ref = re.sub(r"[^\w]+", "_", ref)
  414. return f"ref_{clean_ref}"
  415. def format_array_ref(refs: str, idx: Var | None) -> str:
  416. """Format a ref accessed by array.
  417. Args:
  418. refs : The ref array to access.
  419. idx : The index of the ref in the array.
  420. Returns:
  421. The formatted ref.
  422. """
  423. clean_ref = re.sub(r"[^\w]+", "_", refs)
  424. if idx is not None:
  425. idx._var_is_local = True
  426. return f"refs_{clean_ref}[{idx}]"
  427. return f"refs_{clean_ref}"
  428. def format_breadcrumbs(route: str) -> list[tuple[str, str]]:
  429. """Take a route and return a list of tuple for use in breadcrumb.
  430. Args:
  431. route: The route to transform.
  432. Returns:
  433. list[tuple[str, str]]: the list of tuples for the breadcrumb.
  434. """
  435. route_parts = route.lstrip("/").split("/")
  436. # create and return breadcrumbs
  437. return [
  438. (part, "/".join(["", *route_parts[: i + 1]]))
  439. for i, part in enumerate(route_parts)
  440. ]
  441. def format_library_name(library_fullname: str):
  442. """Format the name of a library.
  443. Args:
  444. library_fullname: The fullname of the library.
  445. Returns:
  446. The name without the @version if it was part of the name
  447. """
  448. lib, at, version = library_fullname.rpartition("@")
  449. if not lib:
  450. lib = at + version
  451. return lib
  452. def json_dumps(obj: Any) -> str:
  453. """Takes an object and returns a jsonified string.
  454. Args:
  455. obj: The object to be serialized.
  456. Returns:
  457. A string
  458. """
  459. return json.dumps(obj, ensure_ascii=False, default=serialize)
  460. def unwrap_vars(value: str) -> str:
  461. """Unwrap var values from a JSON string.
  462. For example, "{var}" will be unwrapped to "var".
  463. Args:
  464. value: The JSON string to unwrap.
  465. Returns:
  466. The unwrapped JSON string.
  467. """
  468. def unescape_double_quotes_in_var(m: re.Match) -> str:
  469. # Since the outer quotes are removed, the inner escaped quotes must be unescaped.
  470. return re.sub('\\\\"', '"', m.group(1))
  471. # This substitution is necessary to unwrap var values.
  472. return re.sub(
  473. pattern=r"""
  474. (?<!\\) # must NOT start with a backslash
  475. " # match opening double quote of JSON value
  476. {(.*?)} # extract the value between curly braces (non-greedy)
  477. " # match must end with an unescaped double quote
  478. """,
  479. repl=unescape_double_quotes_in_var,
  480. string=value,
  481. flags=re.VERBOSE,
  482. )