event.py 32 KB

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