format.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. """Formatting operations."""
  2. from __future__ import annotations
  3. import inspect
  4. import json
  5. import re
  6. from typing import TYPE_CHECKING, Any, Optional, Union
  7. from reflex import constants
  8. from reflex.constants.state import FRONTEND_EVENT_STATE
  9. from reflex.utils import exceptions
  10. if TYPE_CHECKING:
  11. from reflex.components.component import ComponentStyle
  12. from reflex.event import ArgsSpec, EventChain, EventHandler, EventSpec, EventType
  13. WRAP_MAP = {
  14. "{": "}",
  15. "(": ")",
  16. "[": "]",
  17. "<": ">",
  18. '"': '"',
  19. "'": "'",
  20. "`": "`",
  21. }
  22. def length_of_largest_common_substring(str1: str, str2: str) -> int:
  23. """Find the length of the largest common substring between two strings.
  24. Args:
  25. str1: The first string.
  26. str2: The second string.
  27. Returns:
  28. The length of the largest common substring.
  29. """
  30. if not str1 or not str2:
  31. return 0
  32. # Create a matrix of size (len(str1) + 1) x (len(str2) + 1)
  33. dp = [[0] * (len(str2) + 1) for _ in range(len(str1) + 1)]
  34. # Variables to keep track of maximum length and ending position
  35. max_length = 0
  36. # Fill the dp matrix
  37. for i in range(1, len(str1) + 1):
  38. for j in range(1, len(str2) + 1):
  39. if str1[i - 1] == str2[j - 1]:
  40. dp[i][j] = dp[i - 1][j - 1] + 1
  41. if dp[i][j] > max_length:
  42. max_length = dp[i][j]
  43. return max_length
  44. def get_close_char(open: str, close: str | None = None) -> str:
  45. """Check if the given character is a valid brace.
  46. Args:
  47. open: The open character.
  48. close: The close character if provided.
  49. Returns:
  50. The close character.
  51. Raises:
  52. ValueError: If the open character is not a valid brace.
  53. """
  54. if close is not None:
  55. return close
  56. if open not in WRAP_MAP:
  57. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  58. return WRAP_MAP[open]
  59. def is_wrapped(text: str, open: str, close: str | None = None) -> bool:
  60. """Check if the given text is wrapped in the given open and close characters.
  61. "(a) + (b)" --> False
  62. "((abc))" --> True
  63. "(abc)" --> True
  64. Args:
  65. text: The text to check.
  66. open: The open character.
  67. close: The close character.
  68. Returns:
  69. Whether the text is wrapped.
  70. """
  71. close = get_close_char(open, close)
  72. if not (text.startswith(open) and text.endswith(close)):
  73. return False
  74. depth = 0
  75. for ch in text[:-1]:
  76. if ch == open:
  77. depth += 1
  78. if ch == close:
  79. depth -= 1
  80. if depth == 0: # it shouldn't close before the end
  81. return False
  82. return True
  83. def wrap(
  84. text: str,
  85. open: str,
  86. close: str | None = None,
  87. check_first: bool = True,
  88. num: int = 1,
  89. ) -> str:
  90. """Wrap the given text in the given open and close characters.
  91. Args:
  92. text: The text to wrap.
  93. open: The open character.
  94. close: The close character.
  95. check_first: Whether to check if the text is already wrapped.
  96. num: The number of times to wrap the text.
  97. Returns:
  98. The wrapped text.
  99. """
  100. close = get_close_char(open, close)
  101. # If desired, check if the text is already wrapped in braces.
  102. if check_first and is_wrapped(text=text, open=open, close=close):
  103. return text
  104. # Wrap the text in braces.
  105. return f"{open * num}{text}{close * num}"
  106. def to_snake_case(text: str) -> str:
  107. """Convert a string to snake case.
  108. The words in the text are converted to lowercase and
  109. separated by underscores.
  110. Args:
  111. text: The string to convert.
  112. Returns:
  113. The snake case string.
  114. """
  115. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  116. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower().replace("-", "_")
  117. def to_camel_case(text: str, allow_hyphens: bool = False) -> str:
  118. """Convert a string to camel case.
  119. The first word in the text is converted to lowercase and
  120. the rest of the words are converted to title case, removing underscores.
  121. Args:
  122. text: The string to convert.
  123. allow_hyphens: Whether to allow hyphens in the string.
  124. Returns:
  125. The camel case string.
  126. """
  127. char = "_" if allow_hyphens else "-_"
  128. words = re.split(f"[{char}]", text.lstrip(char))
  129. leading_underscores_or_hyphens = "".join(re.findall(rf"^[{char}]+", text))
  130. # Capitalize the first letter of each word except the first one
  131. converted_word = words[0] + "".join(x.capitalize() for x in words[1:])
  132. return leading_underscores_or_hyphens + converted_word
  133. def to_title_case(text: str, sep: str = "") -> str:
  134. """Convert a string from snake case to title case.
  135. Args:
  136. text: The string to convert.
  137. sep: The separator to use to join the words.
  138. Returns:
  139. The title case string.
  140. """
  141. return sep.join(word.title() for word in text.split("_"))
  142. def to_kebab_case(text: str) -> str:
  143. """Convert a string to kebab case.
  144. The words in the text are converted to lowercase and
  145. separated by hyphens.
  146. Args:
  147. text: The string to convert.
  148. Returns:
  149. The title case string.
  150. """
  151. return to_snake_case(text).replace("_", "-")
  152. def make_default_page_title(app_name: str, route: str) -> str:
  153. """Make a default page title from a route.
  154. Args:
  155. app_name: The name of the app owning the page.
  156. route: The route to make the title from.
  157. Returns:
  158. The default page title.
  159. """
  160. route_parts = [
  161. part
  162. for part in route.split("/")
  163. if part and not (part.startswith("[") and part.endswith("]"))
  164. ]
  165. title = constants.DefaultPage.TITLE.format(
  166. app_name, route_parts[-1] if route_parts else constants.PageNames.INDEX_ROUTE
  167. )
  168. return to_title_case(title)
  169. def format_route(route: str, format_case: bool = True) -> str:
  170. """Format the given route.
  171. Args:
  172. route: The route to format.
  173. format_case: whether to format case to kebab case.
  174. Returns:
  175. The formatted route.
  176. """
  177. route = route.strip("/")
  178. # Strip the route and format casing.
  179. if format_case:
  180. route = to_kebab_case(route)
  181. # If the route is empty, return the index route.
  182. if route == "":
  183. return constants.PageNames.INDEX_ROUTE
  184. return route
  185. def format_prop(
  186. prop: Union[Var, EventChain, ComponentStyle, str],
  187. ) -> Union[int, float, str]:
  188. """Format a prop.
  189. Args:
  190. prop: The prop to format.
  191. Returns:
  192. The formatted prop to display within a tag.
  193. Raises:
  194. exceptions.InvalidStylePropError: If the style prop value is not a valid type.
  195. TypeError: If the prop is not valid.
  196. ValueError: If the prop is not a string.
  197. """
  198. # import here to avoid circular import.
  199. from reflex.event import EventChain
  200. from reflex.utils import serializers
  201. from reflex.vars import Var
  202. try:
  203. # Handle var props.
  204. if isinstance(prop, Var):
  205. return str(prop)
  206. # Handle event props.
  207. if isinstance(prop, EventChain):
  208. return str(Var.create(prop))
  209. # Handle other types.
  210. elif isinstance(prop, str):
  211. if is_wrapped(prop, "{"):
  212. return prop
  213. return json_dumps(prop)
  214. # For dictionaries, convert any properties to strings.
  215. elif isinstance(prop, dict):
  216. prop = serializers.serialize_dict(prop) # pyright: ignore [reportAttributeAccessIssue]
  217. else:
  218. # Dump the prop as JSON.
  219. prop = json_dumps(prop)
  220. except exceptions.InvalidStylePropError:
  221. raise
  222. except TypeError as e:
  223. raise TypeError(f"Could not format prop: {prop} of type {type(prop)}") from e
  224. # Wrap the variable in braces.
  225. if not isinstance(prop, str):
  226. raise ValueError(f"Invalid prop: {prop}. Expected a string.")
  227. return wrap(prop, "{", check_first=False)
  228. def format_props(*single_props, **key_value_props) -> list[str]:
  229. """Format the tag's props.
  230. Args:
  231. single_props: Props that are not key-value pairs.
  232. key_value_props: Props that are key-value pairs.
  233. Returns:
  234. The formatted props list.
  235. """
  236. # Format all the props.
  237. from reflex.vars.base import LiteralVar, Var
  238. return [
  239. (
  240. f"{name}={{{format_prop(prop if isinstance(prop, Var) else LiteralVar.create(prop))}}}"
  241. )
  242. for name, prop in sorted(key_value_props.items())
  243. if prop is not None
  244. ] + [(f"{LiteralVar.create(prop)!s}") for prop in single_props]
  245. def get_event_handler_parts(handler: EventHandler) -> tuple[str, str]:
  246. """Get the state and function name of an event handler.
  247. Args:
  248. handler: The event handler to get the parts of.
  249. Returns:
  250. The state and function name.
  251. """
  252. # Get the class that defines the event handler.
  253. parts = handler.fn.__qualname__.split(".")
  254. # Get the state full name
  255. state_full_name = handler.state_full_name
  256. # If there's no enclosing class, just return the function name.
  257. if not state_full_name:
  258. return ("", parts[-1])
  259. # Get the function name
  260. name = parts[-1]
  261. from reflex.state import State
  262. if state_full_name == FRONTEND_EVENT_STATE and name not in State.__dict__:
  263. return ("", to_snake_case(handler.fn.__qualname__))
  264. return (state_full_name, name)
  265. def format_event_handler(handler: EventHandler) -> str:
  266. """Format an event handler.
  267. Args:
  268. handler: The event handler to format.
  269. Returns:
  270. The formatted function.
  271. """
  272. state, name = get_event_handler_parts(handler)
  273. if state == "":
  274. return name
  275. return f"{state}.{name}"
  276. def format_event(event_spec: EventSpec) -> str:
  277. """Format an event.
  278. Args:
  279. event_spec: The event to format.
  280. Returns:
  281. The compiled event.
  282. """
  283. args = ",".join(
  284. [
  285. ":".join(
  286. (
  287. name._js_expr,
  288. (
  289. wrap(
  290. json.dumps(val._js_expr).strip('"').replace("`", "\\`"),
  291. "`",
  292. )
  293. if val._var_is_string
  294. else str(val)
  295. ),
  296. )
  297. )
  298. for name, val in event_spec.args
  299. ]
  300. )
  301. event_args = [
  302. wrap(format_event_handler(event_spec.handler), '"'),
  303. ]
  304. event_args.append(wrap(args, "{"))
  305. if event_spec.client_handler_name:
  306. event_args.append(wrap(event_spec.client_handler_name, '"'))
  307. return f"Event({', '.join(event_args)})"
  308. if TYPE_CHECKING:
  309. from reflex.vars import Var
  310. def format_queue_events(
  311. events: EventType[Any] | None = None,
  312. args_spec: Optional[ArgsSpec] = None,
  313. ) -> Var[EventChain]:
  314. """Format a list of event handler / event spec as a javascript callback.
  315. The resulting code can be passed to interfaces that expect a callback
  316. function and when triggered it will directly call queueEvents.
  317. It is intended to be executed in the rx.call_script context, where some
  318. existing API needs a callback to trigger a backend event handler.
  319. Args:
  320. events: The events to queue.
  321. args_spec: The argument spec for the callback.
  322. Returns:
  323. The compiled javascript callback to queue the given events on the frontend.
  324. Raises:
  325. ValueError: If a lambda function is given which returns a Var.
  326. """
  327. from reflex.event import (
  328. EventChain,
  329. EventHandler,
  330. EventSpec,
  331. call_event_fn,
  332. call_event_handler,
  333. )
  334. from reflex.vars import FunctionVar, Var
  335. if not events:
  336. return Var("(() => null)").to(FunctionVar, EventChain)
  337. # If no spec is provided, the function will take no arguments.
  338. def _default_args_spec():
  339. return []
  340. # Construct the arguments that the function accepts.
  341. sig = inspect.signature(args_spec or _default_args_spec)
  342. if sig.parameters:
  343. arg_def = ",".join(f"_{p}" for p in sig.parameters)
  344. arg_def = f"({arg_def})"
  345. else:
  346. arg_def = "()"
  347. payloads = []
  348. if not isinstance(events, list):
  349. events = [events]
  350. # Process each event/spec/lambda (similar to Component._create_event_chain).
  351. for spec in events:
  352. specs: list[EventSpec] = []
  353. if isinstance(spec, (EventHandler, EventSpec)):
  354. specs = [call_event_handler(spec, args_spec or _default_args_spec)]
  355. elif isinstance(spec, type(lambda: None)):
  356. specs = call_event_fn(spec, args_spec or _default_args_spec) # pyright: ignore [reportAssignmentType, reportArgumentType]
  357. if isinstance(specs, Var):
  358. raise ValueError(
  359. f"Invalid event spec: {specs}. Expected a list of EventSpecs."
  360. )
  361. payloads.extend(format_event(s) for s in specs)
  362. # Return the final code snippet, expecting queueEvents, processEvent, and socket to be in scope.
  363. # Typically this snippet will _only_ run from within an rx.call_script eval context.
  364. return Var(
  365. f"{arg_def} => {{queueEvents([{','.join(payloads)}], {constants.CompileVars.SOCKET}); "
  366. f"processEvent({constants.CompileVars.SOCKET})}}",
  367. ).to(FunctionVar, EventChain)
  368. def format_query_params(router_data: dict[str, Any]) -> dict[str, str]:
  369. """Convert back query params name to python-friendly case.
  370. Args:
  371. router_data: the router_data dict containing the query params
  372. Returns:
  373. The reformatted query params
  374. """
  375. params = router_data[constants.RouteVar.QUERY]
  376. return {k.replace("-", "_"): v for k, v in params.items()}
  377. def format_state_name(state_name: str) -> str:
  378. """Format a state name, replacing dots with double underscore.
  379. This allows individual substates to be accessed independently as javascript vars
  380. without using dot notation.
  381. Args:
  382. state_name: The state name to format.
  383. Returns:
  384. The formatted state name.
  385. """
  386. return state_name.replace(".", "__")
  387. def format_ref(ref: str) -> str:
  388. """Format a ref.
  389. Args:
  390. ref: The ref to format.
  391. Returns:
  392. The formatted ref.
  393. """
  394. # Replace all non-word characters with underscores.
  395. clean_ref = re.sub(r"[^\w]+", "_", ref)
  396. return f"ref_{clean_ref}"
  397. def format_library_name(library_fullname: str):
  398. """Format the name of a library.
  399. Args:
  400. library_fullname: The fullname of the library.
  401. Returns:
  402. The name without the @version if it was part of the name
  403. """
  404. if library_fullname.startswith("https://"):
  405. return library_fullname
  406. lib, at, version = library_fullname.rpartition("@")
  407. if not lib:
  408. lib = at + version
  409. return lib
  410. def json_dumps(obj: Any, **kwargs) -> str:
  411. """Takes an object and returns a jsonified string.
  412. Args:
  413. obj: The object to be serialized.
  414. kwargs: Additional keyword arguments to pass to json.dumps.
  415. Returns:
  416. A string
  417. """
  418. from reflex.utils import serializers
  419. kwargs.setdefault("ensure_ascii", False)
  420. kwargs.setdefault("default", serializers.serialize)
  421. return json.dumps(obj, **kwargs)
  422. def collect_form_dict_names(form_dict: dict[str, Any]) -> dict[str, Any]:
  423. """Collapse keys with consecutive suffixes into a single list value.
  424. Separators dash and underscore are removed, unless this would overwrite an existing key.
  425. Args:
  426. form_dict: The dict to collapse.
  427. Returns:
  428. The collapsed dict.
  429. """
  430. ending_digit_regex = re.compile(r"^(.*?)[_-]?(\d+)$")
  431. collapsed = {}
  432. for k in sorted(form_dict):
  433. m = ending_digit_regex.match(k)
  434. if m:
  435. collapsed.setdefault(m.group(1), []).append(form_dict[k])
  436. # collapsing never overwrites valid data from the form_dict
  437. collapsed.update(form_dict)
  438. return collapsed
  439. def format_array_ref(refs: str, idx: Var | None) -> str:
  440. """Format a ref accessed by array.
  441. Args:
  442. refs : The ref array to access.
  443. idx : The index of the ref in the array.
  444. Returns:
  445. The formatted ref.
  446. """
  447. clean_ref = re.sub(r"[^\w]+", "_", refs)
  448. if idx is not None:
  449. return f"refs_{clean_ref}[{idx!s}]"
  450. return f"refs_{clean_ref}"
  451. def format_data_editor_column(col: str | dict):
  452. """Format a given column into the proper format.
  453. Args:
  454. col: The column.
  455. Raises:
  456. ValueError: invalid type provided for column.
  457. Returns:
  458. The formatted column.
  459. """
  460. from reflex.vars import Var
  461. if isinstance(col, str):
  462. return {"title": col, "id": col.lower(), "type": "str"}
  463. if isinstance(col, (dict,)):
  464. if "id" not in col:
  465. col["id"] = col["title"].lower()
  466. if "type" not in col:
  467. col["type"] = "str"
  468. if "overlayIcon" not in col:
  469. col["overlayIcon"] = None
  470. return col
  471. if isinstance(col, Var):
  472. return col
  473. raise ValueError(
  474. f"unexpected type ({(type(col).__name__)}: {col}) for column header in data_editor"
  475. )
  476. def format_data_editor_cell(cell: Any):
  477. """Format a given data into a renderable cell for data_editor.
  478. Args:
  479. cell: The data to format.
  480. Returns:
  481. The formatted cell.
  482. """
  483. from reflex.vars.base import Var
  484. return {
  485. "kind": Var(_js_expr="GridCellKind.Text"),
  486. "data": cell,
  487. }