format.py 16 KB

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