event.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. """Define event classes to connect the frontend and backend."""
  2. from __future__ import annotations
  3. import inspect
  4. from base64 import b64encode
  5. from typing import (
  6. Any,
  7. Callable,
  8. Dict,
  9. List,
  10. Optional,
  11. Tuple,
  12. Union,
  13. get_type_hints,
  14. )
  15. from reflex import constants
  16. from reflex.base import Base
  17. from reflex.utils import format
  18. from reflex.utils.types import ArgsSpec
  19. from reflex.vars import BaseVar, Var
  20. try:
  21. from typing import Annotated
  22. except ImportError:
  23. from typing_extensions import Annotated
  24. class Event(Base):
  25. """An event that describes any state change in the app."""
  26. # The token to specify the client that the event is for.
  27. token: str
  28. # The event name.
  29. name: str
  30. # The routing data where event occurred
  31. router_data: Dict[str, Any] = {}
  32. # The event payload.
  33. payload: Dict[str, Any] = {}
  34. @property
  35. def substate_token(self) -> str:
  36. """Get the substate token for the event.
  37. Returns:
  38. The substate token.
  39. """
  40. substate = self.name.rpartition(".")[0]
  41. return f"{self.token}_{substate}"
  42. BACKGROUND_TASK_MARKER = "_reflex_background_task"
  43. def background(fn):
  44. """Decorator to mark event handler as running in the background.
  45. Args:
  46. fn: The function to decorate.
  47. Returns:
  48. The same function, but with a marker set.
  49. Raises:
  50. TypeError: If the function is not a coroutine function or async generator.
  51. """
  52. if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
  53. raise TypeError("Background task must be async function or generator.")
  54. setattr(fn, BACKGROUND_TASK_MARKER, True)
  55. return fn
  56. class EventActionsMixin(Base):
  57. """Mixin for DOM event actions."""
  58. # Whether to `preventDefault` or `stopPropagation` on the event.
  59. event_actions: Dict[str, Union[bool, int]] = {}
  60. @property
  61. def stop_propagation(self):
  62. """Stop the event from bubbling up the DOM tree.
  63. Returns:
  64. New EventHandler-like with stopPropagation set to True.
  65. """
  66. return self.copy(
  67. update={"event_actions": {"stopPropagation": True, **self.event_actions}},
  68. )
  69. @property
  70. def prevent_default(self):
  71. """Prevent the default behavior of the event.
  72. Returns:
  73. New EventHandler-like with preventDefault set to True.
  74. """
  75. return self.copy(
  76. update={"event_actions": {"preventDefault": True, **self.event_actions}},
  77. )
  78. def throttle(self, limit_ms: int):
  79. """Throttle the event handler.
  80. Args:
  81. limit_ms: The time in milliseconds to throttle the event handler.
  82. Returns:
  83. New EventHandler-like with throttle set to limit_ms.
  84. """
  85. return self.copy(
  86. update={"event_actions": {"throttle": limit_ms, **self.event_actions}},
  87. )
  88. def debounce(self, delay_ms: int):
  89. """Debounce the event handler.
  90. Args:
  91. delay_ms: The time in milliseconds to debounce the event handler.
  92. Returns:
  93. New EventHandler-like with debounce set to delay_ms.
  94. """
  95. return self.copy(
  96. update={"event_actions": {"debounce": delay_ms, **self.event_actions}},
  97. )
  98. class EventHandler(EventActionsMixin):
  99. """An event handler responds to an event to update the state."""
  100. # The function to call in response to the event.
  101. fn: Any
  102. # The full name of the state class this event handler is attached to.
  103. # Empty string means this event handler is a server side event.
  104. state_full_name: str = ""
  105. class Config:
  106. """The Pydantic config."""
  107. # Needed to allow serialization of Callable.
  108. frozen = True
  109. @classmethod
  110. def __class_getitem__(cls, args_spec: str) -> Annotated:
  111. """Get a typed EventHandler.
  112. Args:
  113. args_spec: The args_spec of the EventHandler.
  114. Returns:
  115. The EventHandler class item.
  116. """
  117. return Annotated[cls, args_spec]
  118. @property
  119. def is_background(self) -> bool:
  120. """Whether the event handler is a background task.
  121. Returns:
  122. True if the event handler is marked as a background task.
  123. """
  124. return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
  125. def __call__(self, *args: Any) -> EventSpec:
  126. """Pass arguments to the handler to get an event spec.
  127. This method configures event handlers that take in arguments.
  128. Args:
  129. *args: The arguments to pass to the handler.
  130. Returns:
  131. The event spec, containing both the function and args.
  132. Raises:
  133. EventHandlerTypeError: If the arguments are invalid.
  134. """
  135. from reflex.utils.exceptions import EventHandlerTypeError
  136. # Get the function args.
  137. fn_args = inspect.getfullargspec(self.fn).args[1:]
  138. fn_args = (Var.create_safe(arg) for arg in fn_args)
  139. # Construct the payload.
  140. values = []
  141. for arg in args:
  142. # Special case for file uploads.
  143. if isinstance(arg, FileUpload):
  144. return arg.as_event_spec(handler=self)
  145. # Otherwise, convert to JSON.
  146. try:
  147. values.append(Var.create(arg, _var_is_string=isinstance(arg, str)))
  148. except TypeError as e:
  149. raise EventHandlerTypeError(
  150. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  151. ) from e
  152. payload = tuple(zip(fn_args, values))
  153. # Return the event spec.
  154. return EventSpec(
  155. handler=self, args=payload, event_actions=self.event_actions.copy()
  156. )
  157. class EventSpec(EventActionsMixin):
  158. """An event specification.
  159. Whereas an Event object is passed during runtime, a spec is used
  160. during compile time to outline the structure of an event.
  161. """
  162. # The event handler.
  163. handler: EventHandler
  164. # The handler on the client to process event.
  165. client_handler_name: str = ""
  166. # The arguments to pass to the function.
  167. args: Tuple[Tuple[Var, Var], ...] = ()
  168. class Config:
  169. """The Pydantic config."""
  170. # Required to allow tuple fields.
  171. frozen = True
  172. def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
  173. """Copy the event spec, with updated args.
  174. Args:
  175. args: The new args to pass to the function.
  176. Returns:
  177. A copy of the event spec, with the new args.
  178. """
  179. return type(self)(
  180. handler=self.handler,
  181. client_handler_name=self.client_handler_name,
  182. args=args,
  183. event_actions=self.event_actions.copy(),
  184. )
  185. def add_args(self, *args: Var) -> EventSpec:
  186. """Add arguments to the event spec.
  187. Args:
  188. *args: The arguments to add positionally.
  189. Returns:
  190. The event spec with the new arguments.
  191. Raises:
  192. EventHandlerTypeError: If the arguments are invalid.
  193. """
  194. from reflex.utils.exceptions import EventHandlerTypeError
  195. # Get the remaining unfilled function args.
  196. fn_args = inspect.getfullargspec(self.handler.fn).args[1 + len(self.args) :]
  197. fn_args = (Var.create_safe(arg) for arg in fn_args)
  198. # Construct the payload.
  199. values = []
  200. for arg in args:
  201. try:
  202. values.append(Var.create(arg, _var_is_string=isinstance(arg, str)))
  203. except TypeError as e:
  204. raise EventHandlerTypeError(
  205. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  206. ) from e
  207. new_payload = tuple(zip(fn_args, values))
  208. return self.with_args(self.args + new_payload)
  209. class CallableEventSpec(EventSpec):
  210. """Decorate an EventSpec-returning function to act as both a EventSpec and a function.
  211. This is used as a compatibility shim for replacing EventSpec objects in the
  212. API with functions that return a family of EventSpec.
  213. """
  214. fn: Optional[Callable[..., EventSpec]] = None
  215. def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
  216. """Initialize a CallableEventSpec.
  217. Args:
  218. fn: The function to decorate.
  219. **kwargs: The kwargs to pass to pydantic initializer
  220. """
  221. if fn is not None:
  222. default_event_spec = fn()
  223. super().__init__(
  224. fn=fn, # type: ignore
  225. **default_event_spec.dict(),
  226. **kwargs,
  227. )
  228. else:
  229. super().__init__(**kwargs)
  230. def __call__(self, *args, **kwargs) -> EventSpec:
  231. """Call the decorated function.
  232. Args:
  233. *args: The args to pass to the function.
  234. **kwargs: The kwargs to pass to the function.
  235. Returns:
  236. The EventSpec returned from calling the function.
  237. Raises:
  238. EventHandlerTypeError: If the CallableEventSpec has no associated function.
  239. """
  240. from reflex.utils.exceptions import EventHandlerTypeError
  241. if self.fn is None:
  242. raise EventHandlerTypeError("CallableEventSpec has no associated function.")
  243. return self.fn(*args, **kwargs)
  244. class EventChain(EventActionsMixin):
  245. """Container for a chain of events that will be executed in order."""
  246. events: List[EventSpec]
  247. args_spec: Optional[Callable]
  248. # These chains can be used for their side effects when no other events are desired.
  249. stop_propagation = EventChain(events=[], args_spec=lambda: []).stop_propagation
  250. prevent_default = EventChain(events=[], args_spec=lambda: []).prevent_default
  251. class Target(Base):
  252. """A Javascript event target."""
  253. checked: bool = False
  254. value: Any = None
  255. class FrontendEvent(Base):
  256. """A Javascript event."""
  257. target: Target = Target()
  258. key: str = ""
  259. value: Any = None
  260. class FileUpload(Base):
  261. """Class to represent a file upload."""
  262. upload_id: Optional[str] = None
  263. on_upload_progress: Optional[Union[EventHandler, Callable]] = None
  264. @staticmethod
  265. def on_upload_progress_args_spec(_prog: Dict[str, Union[int, float, bool]]):
  266. """Args spec for on_upload_progress event handler.
  267. Returns:
  268. The arg mapping passed to backend event handler
  269. """
  270. return [_prog]
  271. def as_event_spec(self, handler: EventHandler) -> EventSpec:
  272. """Get the EventSpec for the file upload.
  273. Args:
  274. handler: The event handler.
  275. Returns:
  276. The event spec for the handler.
  277. Raises:
  278. ValueError: If the on_upload_progress is not a valid event handler.
  279. """
  280. from reflex.components.core.upload import (
  281. DEFAULT_UPLOAD_ID,
  282. upload_files_context_var_data,
  283. )
  284. upload_id = self.upload_id or DEFAULT_UPLOAD_ID
  285. spec_args = [
  286. (
  287. Var.create_safe("files"),
  288. Var.create_safe(f"filesById.{upload_id}")._replace(
  289. _var_data=upload_files_context_var_data
  290. ),
  291. ),
  292. (
  293. Var.create_safe("upload_id"),
  294. Var.create_safe(upload_id, _var_is_string=True),
  295. ),
  296. ]
  297. if self.on_upload_progress is not None:
  298. on_upload_progress = self.on_upload_progress
  299. if isinstance(on_upload_progress, EventHandler):
  300. events = [
  301. call_event_handler(
  302. on_upload_progress,
  303. self.on_upload_progress_args_spec,
  304. ),
  305. ]
  306. elif isinstance(on_upload_progress, Callable):
  307. # Call the lambda to get the event chain.
  308. events = call_event_fn(
  309. on_upload_progress, self.on_upload_progress_args_spec
  310. ) # type: ignore
  311. else:
  312. raise ValueError(f"{on_upload_progress} is not a valid event handler.")
  313. on_upload_progress_chain = EventChain(
  314. events=events,
  315. args_spec=self.on_upload_progress_args_spec,
  316. )
  317. formatted_chain = str(format.format_prop(on_upload_progress_chain))
  318. spec_args.append(
  319. (
  320. Var.create_safe("on_upload_progress"),
  321. BaseVar(
  322. _var_name=formatted_chain.strip("{}"),
  323. _var_type=EventChain,
  324. ),
  325. ),
  326. )
  327. return EventSpec(
  328. handler=handler,
  329. client_handler_name="uploadFiles",
  330. args=tuple(spec_args),
  331. event_actions=handler.event_actions.copy(),
  332. )
  333. # Alias for rx.upload_files
  334. upload_files = FileUpload
  335. # Special server-side events.
  336. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  337. """A server-side event.
  338. Args:
  339. name: The name of the event.
  340. sig: The function signature of the event.
  341. **kwargs: The arguments to pass to the event.
  342. Returns:
  343. An event spec for a server-side event.
  344. """
  345. def fn():
  346. return None
  347. fn.__qualname__ = name
  348. fn.__signature__ = sig
  349. return EventSpec(
  350. handler=EventHandler(fn=fn),
  351. args=tuple(
  352. (Var.create_safe(k), Var.create_safe(v, _var_is_string=isinstance(v, str)))
  353. for k, v in kwargs.items()
  354. ),
  355. )
  356. def redirect(
  357. path: str | Var[str],
  358. external: Optional[bool] = False,
  359. replace: Optional[bool] = False,
  360. ) -> EventSpec:
  361. """Redirect to a new path.
  362. Args:
  363. path: The path to redirect to.
  364. external: Whether to open in new tab or not.
  365. replace: If True, the current page will not create a new history entry.
  366. Returns:
  367. An event to redirect to the path.
  368. """
  369. return server_side(
  370. "_redirect",
  371. get_fn_signature(redirect),
  372. path=path,
  373. external=external,
  374. replace=replace,
  375. )
  376. def console_log(message: str | Var[str]) -> EventSpec:
  377. """Do a console.log on the browser.
  378. Args:
  379. message: The message to log.
  380. Returns:
  381. An event to log the message.
  382. """
  383. return server_side("_console", get_fn_signature(console_log), message=message)
  384. def window_alert(message: str | Var[str]) -> EventSpec:
  385. """Create a window alert on the browser.
  386. Args:
  387. message: The message to alert.
  388. Returns:
  389. An event to alert the message.
  390. """
  391. return server_side("_alert", get_fn_signature(window_alert), message=message)
  392. def set_focus(ref: str) -> EventSpec:
  393. """Set focus to specified ref.
  394. Args:
  395. ref: The ref.
  396. Returns:
  397. An event to set focus on the ref
  398. """
  399. return server_side(
  400. "_set_focus",
  401. get_fn_signature(set_focus),
  402. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  403. )
  404. def scroll_to(elem_id: str) -> EventSpec:
  405. """Select the id of a html element for scrolling into view.
  406. Args:
  407. elem_id: the id of the element
  408. Returns:
  409. An EventSpec to scroll the page to the selected element.
  410. """
  411. js_code = f"document.getElementById('{elem_id}').scrollIntoView();"
  412. return call_script(js_code)
  413. def set_value(ref: str, value: Any) -> EventSpec:
  414. """Set the value of a ref.
  415. Args:
  416. ref: The ref.
  417. value: The value to set.
  418. Returns:
  419. An event to set the ref.
  420. """
  421. return server_side(
  422. "_set_value",
  423. get_fn_signature(set_value),
  424. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  425. value=value,
  426. )
  427. def remove_cookie(key: str, options: dict[str, Any] | None = None) -> EventSpec:
  428. """Remove a cookie on the frontend.
  429. Args:
  430. key: The key identifying the cookie to be removed.
  431. options: Support all the cookie options from RFC 6265
  432. Returns:
  433. EventSpec: An event to remove a cookie.
  434. """
  435. options = options or {}
  436. options["path"] = options.get("path", "/")
  437. return server_side(
  438. "_remove_cookie",
  439. get_fn_signature(remove_cookie),
  440. key=key,
  441. options=options,
  442. )
  443. def clear_local_storage() -> EventSpec:
  444. """Set a value in the local storage on the frontend.
  445. Returns:
  446. EventSpec: An event to clear the local storage.
  447. """
  448. return server_side(
  449. "_clear_local_storage",
  450. get_fn_signature(clear_local_storage),
  451. )
  452. def remove_local_storage(key: str) -> EventSpec:
  453. """Set a value in the local storage on the frontend.
  454. Args:
  455. key: The key identifying the variable in the local storage to remove.
  456. Returns:
  457. EventSpec: An event to remove an item based on the provided key in local storage.
  458. """
  459. return server_side(
  460. "_remove_local_storage",
  461. get_fn_signature(remove_local_storage),
  462. key=key,
  463. )
  464. def set_clipboard(content: str) -> EventSpec:
  465. """Set the text in content in the clipboard.
  466. Args:
  467. content: The text to add to clipboard.
  468. Returns:
  469. EventSpec: An event to set some content in the clipboard.
  470. """
  471. return server_side(
  472. "_set_clipboard",
  473. get_fn_signature(set_clipboard),
  474. content=content,
  475. )
  476. def download(
  477. url: str | Var | None = None,
  478. filename: Optional[str | Var] = None,
  479. data: str | bytes | Var | None = None,
  480. ) -> EventSpec:
  481. """Download the file at a given path or with the specified data.
  482. Args:
  483. url: The URL to the file to download.
  484. filename: The name that the file should be saved as after download.
  485. data: The data to download.
  486. Raises:
  487. ValueError: If the URL provided is invalid, both URL and data are provided,
  488. or the data is not an expected type.
  489. Returns:
  490. EventSpec: An event to download the associated file.
  491. """
  492. from reflex.components.core.cond import cond
  493. if isinstance(url, str):
  494. if not url.startswith("/"):
  495. raise ValueError("The URL argument should start with a /")
  496. # if filename is not provided, infer it from url
  497. if filename is None:
  498. filename = url.rpartition("/")[-1]
  499. if filename is None:
  500. filename = ""
  501. if data is not None:
  502. if url is not None:
  503. raise ValueError("Cannot provide both URL and data to download.")
  504. if isinstance(data, str):
  505. # Caller provided a plain text string to download.
  506. url = "data:text/plain," + data
  507. elif isinstance(data, Var):
  508. # Need to check on the frontend if the Var already looks like a data: URI.
  509. is_data_url = data._replace(
  510. _var_name=(
  511. f"typeof {data._var_full_name} == 'string' && "
  512. f"{data._var_full_name}.startsWith('data:')"
  513. ),
  514. _var_type=bool,
  515. _var_is_string=False,
  516. _var_full_name_needs_state_prefix=False,
  517. )
  518. # If it's a data: URI, use it as is, otherwise convert the Var to JSON in a data: URI.
  519. url = cond( # type: ignore
  520. is_data_url,
  521. data,
  522. "data:text/plain," + data.to_string(), # type: ignore
  523. )
  524. elif isinstance(data, bytes):
  525. # Caller provided bytes, so base64 encode it as a data: URI.
  526. b64_data = b64encode(data).decode("utf-8")
  527. url = "data:application/octet-stream;base64," + b64_data
  528. else:
  529. raise ValueError(
  530. f"Invalid data type {type(data)} for download. Use `str` or `bytes`."
  531. )
  532. return server_side(
  533. "_download",
  534. get_fn_signature(download),
  535. url=url,
  536. filename=filename,
  537. )
  538. def _callback_arg_spec(eval_result):
  539. """ArgSpec for call_script callback function.
  540. Args:
  541. eval_result: The result of the javascript execution.
  542. Returns:
  543. Args for the callback function
  544. """
  545. return [eval_result]
  546. def call_script(
  547. javascript_code: str,
  548. callback: EventSpec
  549. | EventHandler
  550. | Callable
  551. | List[EventSpec | EventHandler | Callable]
  552. | None = None,
  553. ) -> EventSpec:
  554. """Create an event handler that executes arbitrary javascript code.
  555. Args:
  556. javascript_code: The code to execute.
  557. callback: EventHandler that will receive the result of evaluating the javascript code.
  558. Returns:
  559. EventSpec: An event that will execute the client side javascript.
  560. """
  561. callback_kwargs = {}
  562. if callback is not None:
  563. callback_kwargs = {
  564. "callback": format.format_queue_events(
  565. callback,
  566. args_spec=lambda result: [result],
  567. )
  568. }
  569. return server_side(
  570. "_call_script",
  571. get_fn_signature(call_script),
  572. javascript_code=javascript_code,
  573. **callback_kwargs,
  574. )
  575. def get_event(state, event):
  576. """Get the event from the given state.
  577. Args:
  578. state: The state.
  579. event: The event.
  580. Returns:
  581. The event.
  582. """
  583. return f"{state.get_name()}.{event}"
  584. def get_hydrate_event(state) -> str:
  585. """Get the name of the hydrate event for the state.
  586. Args:
  587. state: The state.
  588. Returns:
  589. The name of the hydrate event.
  590. """
  591. return get_event(state, constants.CompileVars.HYDRATE)
  592. def call_event_handler(
  593. event_handler: EventHandler | EventSpec,
  594. arg_spec: ArgsSpec,
  595. ) -> EventSpec:
  596. """Call an event handler to get the event spec.
  597. This function will inspect the function signature of the event handler.
  598. If it takes in an arg, the arg will be passed to the event handler.
  599. Otherwise, the event handler will be called with no args.
  600. Args:
  601. event_handler: The event handler.
  602. arg_spec: The lambda that define the argument(s) to pass to the event handler.
  603. Raises:
  604. ValueError: if number of arguments expected by event_handler doesn't match the spec.
  605. Returns:
  606. The event spec from calling the event handler.
  607. """
  608. parsed_args = parse_args_spec(arg_spec) # type: ignore
  609. if isinstance(event_handler, EventSpec):
  610. # Handle partial application of EventSpec args
  611. return event_handler.add_args(*parsed_args)
  612. args = inspect.getfullargspec(event_handler.fn).args
  613. if len(args) == len(["self", *parsed_args]):
  614. return event_handler(*parsed_args) # type: ignore
  615. else:
  616. source = inspect.getsource(arg_spec) # type: ignore
  617. raise ValueError(
  618. f"number of arguments in {event_handler.fn.__qualname__} "
  619. f"doesn't match the definition of the event trigger '{source.strip().strip(',')}'"
  620. )
  621. def parse_args_spec(arg_spec: ArgsSpec):
  622. """Parse the args provided in the ArgsSpec of an event trigger.
  623. Args:
  624. arg_spec: The spec of the args.
  625. Returns:
  626. The parsed args.
  627. """
  628. spec = inspect.getfullargspec(arg_spec)
  629. annotations = get_type_hints(arg_spec)
  630. return arg_spec(
  631. *[
  632. BaseVar(
  633. _var_name=f"_{l_arg}",
  634. _var_type=annotations.get(l_arg, FrontendEvent),
  635. _var_is_local=True,
  636. )
  637. for l_arg in spec.args
  638. ]
  639. )
  640. def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
  641. """Call a function to a list of event specs.
  642. The function should return either a single EventSpec or a list of EventSpecs.
  643. If the function takes in an arg, the arg will be passed to the function.
  644. Otherwise, the function will be called with no args.
  645. Args:
  646. fn: The function to call.
  647. arg: The argument to pass to the function.
  648. Returns:
  649. The event specs from calling the function.
  650. Raises:
  651. EventHandlerValueError: If the lambda has an invalid signature.
  652. """
  653. # Import here to avoid circular imports.
  654. from reflex.event import EventHandler, EventSpec
  655. from reflex.utils.exceptions import EventHandlerValueError
  656. # Get the args of the lambda.
  657. args = inspect.getfullargspec(fn).args
  658. if isinstance(arg, ArgsSpec):
  659. out = fn(*parse_args_spec(arg)) # type: ignore
  660. else:
  661. # Call the lambda.
  662. if len(args) == 0:
  663. out = fn()
  664. elif len(args) == 1:
  665. out = fn(arg)
  666. else:
  667. raise EventHandlerValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  668. # Convert the output to a list.
  669. if not isinstance(out, List):
  670. out = [out]
  671. # Convert any event specs to event specs.
  672. events = []
  673. for e in out:
  674. # Convert handlers to event specs.
  675. if isinstance(e, EventHandler):
  676. if len(args) == 0:
  677. e = e()
  678. elif len(args) == 1:
  679. e = e(arg) # type: ignore
  680. # Make sure the event spec is valid.
  681. if not isinstance(e, EventSpec):
  682. raise EventHandlerValueError(
  683. f"Lambda {fn} returned an invalid event spec: {e}."
  684. )
  685. # Add the event spec to the chain.
  686. events.append(e)
  687. # Return the events.
  688. return events
  689. def get_handler_args(event_spec: EventSpec) -> tuple[tuple[Var, Var], ...]:
  690. """Get the handler args for the given event spec.
  691. Args:
  692. event_spec: The event spec.
  693. Returns:
  694. The handler args.
  695. """
  696. args = inspect.getfullargspec(event_spec.handler.fn).args
  697. return event_spec.args if len(args) > 1 else tuple()
  698. def fix_events(
  699. events: list[EventHandler | EventSpec] | None,
  700. token: str,
  701. router_data: dict[str, Any] | None = None,
  702. ) -> list[Event]:
  703. """Fix a list of events returned by an event handler.
  704. Args:
  705. events: The events to fix.
  706. token: The user token.
  707. router_data: The optional router data to set in the event.
  708. Returns:
  709. The fixed events.
  710. """
  711. # If the event handler returns nothing, return an empty list.
  712. if events is None:
  713. return []
  714. # If the handler returns a single event, wrap it in a list.
  715. if not isinstance(events, List):
  716. events = [events]
  717. # Fix the events created by the handler.
  718. out = []
  719. for e in events:
  720. if isinstance(e, Event):
  721. # If the event is already an event, append it to the list.
  722. out.append(e)
  723. continue
  724. if not isinstance(e, (EventHandler, EventSpec)):
  725. e = EventHandler(fn=e)
  726. # Otherwise, create an event from the event spec.
  727. if isinstance(e, EventHandler):
  728. e = e()
  729. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  730. name = format.format_event_handler(e.handler)
  731. payload = {k._var_name: v._decode() for k, v in e.args} # type: ignore
  732. # Filter router_data to reduce payload size
  733. event_router_data = {
  734. k: v
  735. for k, v in (router_data or {}).items()
  736. if k in constants.route.ROUTER_DATA_INCLUDE
  737. }
  738. # Create an event and append it to the list.
  739. out.append(
  740. Event(
  741. token=token,
  742. name=name,
  743. payload=payload,
  744. router_data=event_router_data,
  745. )
  746. )
  747. return out
  748. def get_fn_signature(fn: Callable) -> inspect.Signature:
  749. """Get the signature of a function.
  750. Args:
  751. fn: The function.
  752. Returns:
  753. The signature of the function.
  754. """
  755. signature = inspect.signature(fn)
  756. new_param = inspect.Parameter(
  757. "state", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  758. )
  759. return signature.replace(parameters=(new_param, *signature.parameters.values()))