event.py 31 KB

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