event.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. """Define event classes to connect the frontend and backend."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import inspect
  5. import sys
  6. import types
  7. import urllib.parse
  8. from base64 import b64encode
  9. from functools import partial
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. Dict,
  15. Generic,
  16. List,
  17. Optional,
  18. Sequence,
  19. Tuple,
  20. Type,
  21. Union,
  22. get_type_hints,
  23. overload,
  24. )
  25. from typing_extensions import (
  26. Concatenate,
  27. ParamSpec,
  28. Protocol,
  29. TypeAliasType,
  30. TypedDict,
  31. TypeVar,
  32. get_args,
  33. get_origin,
  34. )
  35. from reflex import constants
  36. from reflex.constants.state import FRONTEND_EVENT_STATE
  37. from reflex.utils import console, format
  38. from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgTypeMismatch
  39. from reflex.utils.types import ArgsSpec, GenericType, typehint_issubclass
  40. from reflex.vars import VarData
  41. from reflex.vars.base import LiteralVar, Var
  42. from reflex.vars.function import (
  43. ArgsFunctionOperation,
  44. ArgsFunctionOperationBuilder,
  45. BuilderFunctionVar,
  46. FunctionArgs,
  47. FunctionStringVar,
  48. FunctionVar,
  49. VarOperationCall,
  50. )
  51. from reflex.vars.object import ObjectVar
  52. try:
  53. from typing import Annotated
  54. except ImportError:
  55. from typing_extensions import Annotated
  56. @dataclasses.dataclass(
  57. init=True,
  58. frozen=True,
  59. )
  60. class Event:
  61. """An event that describes any state change in the app."""
  62. # The token to specify the client that the event is for.
  63. token: str
  64. # The event name.
  65. name: str
  66. # The routing data where event occurred
  67. router_data: Dict[str, Any] = dataclasses.field(default_factory=dict)
  68. # The event payload.
  69. payload: Dict[str, Any] = dataclasses.field(default_factory=dict)
  70. @property
  71. def substate_token(self) -> str:
  72. """Get the substate token for the event.
  73. Returns:
  74. The substate token.
  75. """
  76. substate = self.name.rpartition(".")[0]
  77. return f"{self.token}_{substate}"
  78. BACKGROUND_TASK_MARKER = "_reflex_background_task"
  79. def background(fn, *, __internal_reflex_call: bool = False):
  80. """Decorator to mark event handler as running in the background.
  81. Args:
  82. fn: The function to decorate.
  83. Returns:
  84. The same function, but with a marker set.
  85. Raises:
  86. TypeError: If the function is not a coroutine function or async generator.
  87. """
  88. if not __internal_reflex_call:
  89. console.deprecate(
  90. "background-decorator",
  91. "Use `rx.event(background=True)` instead.",
  92. "0.6.5",
  93. "0.7.0",
  94. )
  95. if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
  96. raise TypeError("Background task must be async function or generator.")
  97. setattr(fn, BACKGROUND_TASK_MARKER, True)
  98. return fn
  99. @dataclasses.dataclass(
  100. init=True,
  101. frozen=True,
  102. )
  103. class EventActionsMixin:
  104. """Mixin for DOM event actions."""
  105. # Whether to `preventDefault` or `stopPropagation` on the event.
  106. event_actions: Dict[str, Union[bool, int]] = dataclasses.field(default_factory=dict)
  107. @property
  108. def stop_propagation(self):
  109. """Stop the event from bubbling up the DOM tree.
  110. Returns:
  111. New EventHandler-like with stopPropagation set to True.
  112. """
  113. return dataclasses.replace(
  114. self,
  115. event_actions={"stopPropagation": True, **self.event_actions},
  116. )
  117. @property
  118. def prevent_default(self):
  119. """Prevent the default behavior of the event.
  120. Returns:
  121. New EventHandler-like with preventDefault set to True.
  122. """
  123. return dataclasses.replace(
  124. self,
  125. event_actions={"preventDefault": True, **self.event_actions},
  126. )
  127. def throttle(self, limit_ms: int):
  128. """Throttle the event handler.
  129. Args:
  130. limit_ms: The time in milliseconds to throttle the event handler.
  131. Returns:
  132. New EventHandler-like with throttle set to limit_ms.
  133. """
  134. return dataclasses.replace(
  135. self,
  136. event_actions={"throttle": limit_ms, **self.event_actions},
  137. )
  138. def debounce(self, delay_ms: int):
  139. """Debounce the event handler.
  140. Args:
  141. delay_ms: The time in milliseconds to debounce the event handler.
  142. Returns:
  143. New EventHandler-like with debounce set to delay_ms.
  144. """
  145. return dataclasses.replace(
  146. self,
  147. event_actions={"debounce": delay_ms, **self.event_actions},
  148. )
  149. @property
  150. def temporal(self):
  151. """Do not queue the event if the backend is down.
  152. Returns:
  153. New EventHandler-like with temporal set to True.
  154. """
  155. return dataclasses.replace(
  156. self,
  157. event_actions={"temporal": True, **self.event_actions},
  158. )
  159. @dataclasses.dataclass(
  160. init=True,
  161. frozen=True,
  162. )
  163. class EventHandler(EventActionsMixin):
  164. """An event handler responds to an event to update the state."""
  165. # The function to call in response to the event.
  166. fn: Any = dataclasses.field(default=None)
  167. # The full name of the state class this event handler is attached to.
  168. # Empty string means this event handler is a server side event.
  169. state_full_name: str = dataclasses.field(default="")
  170. @classmethod
  171. def __class_getitem__(cls, args_spec: str) -> Annotated:
  172. """Get a typed EventHandler.
  173. Args:
  174. args_spec: The args_spec of the EventHandler.
  175. Returns:
  176. The EventHandler class item.
  177. """
  178. return Annotated[cls, args_spec]
  179. @property
  180. def is_background(self) -> bool:
  181. """Whether the event handler is a background task.
  182. Returns:
  183. True if the event handler is marked as a background task.
  184. """
  185. return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
  186. def __call__(self, *args: Any) -> EventSpec:
  187. """Pass arguments to the handler to get an event spec.
  188. This method configures event handlers that take in arguments.
  189. Args:
  190. *args: The arguments to pass to the handler.
  191. Returns:
  192. The event spec, containing both the function and args.
  193. Raises:
  194. EventHandlerTypeError: If the arguments are invalid.
  195. """
  196. from reflex.utils.exceptions import EventHandlerTypeError
  197. # Get the function args.
  198. fn_args = inspect.getfullargspec(self.fn).args[1:]
  199. fn_args = (Var(_js_expr=arg) for arg in fn_args)
  200. # Construct the payload.
  201. values = []
  202. for arg in args:
  203. # Special case for file uploads.
  204. if isinstance(arg, FileUpload):
  205. return arg.as_event_spec(handler=self)
  206. # Otherwise, convert to JSON.
  207. try:
  208. values.append(LiteralVar.create(arg))
  209. except TypeError as e:
  210. raise EventHandlerTypeError(
  211. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  212. ) from e
  213. payload = tuple(zip(fn_args, values))
  214. # Return the event spec.
  215. return EventSpec(
  216. handler=self, args=payload, event_actions=self.event_actions.copy()
  217. )
  218. @dataclasses.dataclass(
  219. init=True,
  220. frozen=True,
  221. )
  222. class EventSpec(EventActionsMixin):
  223. """An event specification.
  224. Whereas an Event object is passed during runtime, a spec is used
  225. during compile time to outline the structure of an event.
  226. """
  227. # The event handler.
  228. handler: EventHandler = dataclasses.field(default=None) # type: ignore
  229. # The handler on the client to process event.
  230. client_handler_name: str = dataclasses.field(default="")
  231. # The arguments to pass to the function.
  232. args: Tuple[Tuple[Var, Var], ...] = dataclasses.field(default_factory=tuple)
  233. def __init__(
  234. self,
  235. handler: EventHandler,
  236. event_actions: Dict[str, Union[bool, int]] | None = None,
  237. client_handler_name: str = "",
  238. args: Tuple[Tuple[Var, Var], ...] = tuple(),
  239. ):
  240. """Initialize an EventSpec.
  241. Args:
  242. event_actions: The event actions.
  243. handler: The event handler.
  244. client_handler_name: The client handler name.
  245. args: The arguments to pass to the function.
  246. """
  247. if event_actions is None:
  248. event_actions = {}
  249. object.__setattr__(self, "event_actions", event_actions)
  250. object.__setattr__(self, "handler", handler)
  251. object.__setattr__(self, "client_handler_name", client_handler_name)
  252. object.__setattr__(self, "args", args or tuple())
  253. def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
  254. """Copy the event spec, with updated args.
  255. Args:
  256. args: The new args to pass to the function.
  257. Returns:
  258. A copy of the event spec, with the new args.
  259. """
  260. return type(self)(
  261. handler=self.handler,
  262. client_handler_name=self.client_handler_name,
  263. args=args,
  264. event_actions=self.event_actions.copy(),
  265. )
  266. def add_args(self, *args: Var) -> EventSpec:
  267. """Add arguments to the event spec.
  268. Args:
  269. *args: The arguments to add positionally.
  270. Returns:
  271. The event spec with the new arguments.
  272. Raises:
  273. EventHandlerTypeError: If the arguments are invalid.
  274. """
  275. from reflex.utils.exceptions import EventHandlerTypeError
  276. # Get the remaining unfilled function args.
  277. fn_args = inspect.getfullargspec(self.handler.fn).args[1 + len(self.args) :]
  278. fn_args = (Var(_js_expr=arg) for arg in fn_args)
  279. # Construct the payload.
  280. values = []
  281. for arg in args:
  282. try:
  283. values.append(LiteralVar.create(arg))
  284. except TypeError as e:
  285. raise EventHandlerTypeError(
  286. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  287. ) from e
  288. new_payload = tuple(zip(fn_args, values))
  289. return self.with_args(self.args + new_payload)
  290. @dataclasses.dataclass(
  291. frozen=True,
  292. )
  293. class CallableEventSpec(EventSpec):
  294. """Decorate an EventSpec-returning function to act as both a EventSpec and a function.
  295. This is used as a compatibility shim for replacing EventSpec objects in the
  296. API with functions that return a family of EventSpec.
  297. """
  298. fn: Optional[Callable[..., EventSpec]] = None
  299. def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
  300. """Initialize a CallableEventSpec.
  301. Args:
  302. fn: The function to decorate.
  303. **kwargs: The kwargs to pass to pydantic initializer
  304. """
  305. if fn is not None:
  306. default_event_spec = fn()
  307. super().__init__(
  308. event_actions=default_event_spec.event_actions,
  309. client_handler_name=default_event_spec.client_handler_name,
  310. args=default_event_spec.args,
  311. handler=default_event_spec.handler,
  312. **kwargs,
  313. )
  314. object.__setattr__(self, "fn", fn)
  315. else:
  316. super().__init__(**kwargs)
  317. def __call__(self, *args, **kwargs) -> EventSpec:
  318. """Call the decorated function.
  319. Args:
  320. *args: The args to pass to the function.
  321. **kwargs: The kwargs to pass to the function.
  322. Returns:
  323. The EventSpec returned from calling the function.
  324. Raises:
  325. EventHandlerTypeError: If the CallableEventSpec has no associated function.
  326. """
  327. from reflex.utils.exceptions import EventHandlerTypeError
  328. if self.fn is None:
  329. raise EventHandlerTypeError("CallableEventSpec has no associated function.")
  330. return self.fn(*args, **kwargs)
  331. @dataclasses.dataclass(
  332. init=True,
  333. frozen=True,
  334. )
  335. class EventChain(EventActionsMixin):
  336. """Container for a chain of events that will be executed in order."""
  337. events: Sequence[Union[EventSpec, EventVar, EventCallback]] = dataclasses.field(
  338. default_factory=list
  339. )
  340. args_spec: Optional[Union[Callable, Sequence[Callable]]] = dataclasses.field(
  341. default=None
  342. )
  343. invocation: Optional[Var] = dataclasses.field(default=None)
  344. @dataclasses.dataclass(
  345. init=True,
  346. frozen=True,
  347. )
  348. class JavascriptHTMLInputElement:
  349. """Interface for a Javascript HTMLInputElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement."""
  350. value: str = ""
  351. @dataclasses.dataclass(
  352. init=True,
  353. frozen=True,
  354. )
  355. class JavascriptInputEvent:
  356. """Interface for a Javascript InputEvent https://developer.mozilla.org/en-US/docs/Web/API/InputEvent."""
  357. target: JavascriptHTMLInputElement = JavascriptHTMLInputElement()
  358. @dataclasses.dataclass(
  359. init=True,
  360. frozen=True,
  361. )
  362. class JavasciptKeyboardEvent:
  363. """Interface for a Javascript KeyboardEvent https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent."""
  364. key: str = ""
  365. altKey: bool = False
  366. ctrlKey: bool = False
  367. metaKey: bool = False
  368. shiftKey: bool = False
  369. def input_event(e: Var[JavascriptInputEvent]) -> Tuple[Var[str]]:
  370. """Get the value from an input event.
  371. Args:
  372. e: The input event.
  373. Returns:
  374. The value from the input event.
  375. """
  376. return (e.target.value,)
  377. class KeyInputInfo(TypedDict):
  378. """Information about a key input event."""
  379. alt_key: bool
  380. ctrl_key: bool
  381. meta_key: bool
  382. shift_key: bool
  383. def key_event(e: Var[JavasciptKeyboardEvent]) -> Tuple[Var[str], Var[KeyInputInfo]]:
  384. """Get the key from a keyboard event.
  385. Args:
  386. e: The keyboard event.
  387. Returns:
  388. The key from the keyboard event.
  389. """
  390. return (
  391. e.key,
  392. Var.create(
  393. {
  394. "alt_key": e.altKey,
  395. "ctrl_key": e.ctrlKey,
  396. "meta_key": e.metaKey,
  397. "shift_key": e.shiftKey,
  398. },
  399. ),
  400. )
  401. def no_args_event_spec() -> Tuple[()]:
  402. """Empty event handler.
  403. Returns:
  404. An empty tuple.
  405. """
  406. return tuple() # type: ignore
  407. # These chains can be used for their side effects when no other events are desired.
  408. stop_propagation = EventChain(events=[], args_spec=no_args_event_spec).stop_propagation
  409. prevent_default = EventChain(events=[], args_spec=no_args_event_spec).prevent_default
  410. T = TypeVar("T")
  411. U = TypeVar("U")
  412. class IdentityEventReturn(Generic[T], Protocol):
  413. """Protocol for an identity event return."""
  414. def __call__(self, *values: Var[T]) -> Tuple[Var[T], ...]:
  415. """Return the input values.
  416. Args:
  417. *values: The values to return.
  418. Returns:
  419. The input values.
  420. """
  421. return values
  422. @overload
  423. def passthrough_event_spec(
  424. event_type: Type[T], /
  425. ) -> Callable[[Var[T]], Tuple[Var[T]]]: ... # type: ignore
  426. @overload
  427. def passthrough_event_spec(
  428. event_type_1: Type[T], event_type2: Type[U], /
  429. ) -> Callable[[Var[T], Var[U]], Tuple[Var[T], Var[U]]]: ...
  430. @overload
  431. def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[T]: ...
  432. def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[T]: # type: ignore
  433. """A helper function that returns the input event as output.
  434. Args:
  435. *event_types: The types of the events.
  436. Returns:
  437. A function that returns the input event as output.
  438. """
  439. def inner(*values: Var[T]) -> Tuple[Var[T], ...]:
  440. return values
  441. inner_type = tuple(Var[event_type] for event_type in event_types)
  442. return_annotation = Tuple[inner_type] # type: ignore
  443. inner.__signature__ = inspect.signature(inner).replace( # type: ignore
  444. parameters=[
  445. inspect.Parameter(
  446. f"ev_{i}",
  447. kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
  448. annotation=Var[event_type],
  449. )
  450. for i, event_type in enumerate(event_types)
  451. ],
  452. return_annotation=return_annotation,
  453. )
  454. for i, event_type in enumerate(event_types):
  455. inner.__annotations__[f"ev_{i}"] = Var[event_type]
  456. inner.__annotations__["return"] = return_annotation
  457. return inner
  458. @dataclasses.dataclass(
  459. init=True,
  460. frozen=True,
  461. )
  462. class FileUpload:
  463. """Class to represent a file upload."""
  464. upload_id: Optional[str] = None
  465. on_upload_progress: Optional[Union[EventHandler, Callable]] = None
  466. @staticmethod
  467. def on_upload_progress_args_spec(_prog: Var[Dict[str, Union[int, float, bool]]]):
  468. """Args spec for on_upload_progress event handler.
  469. Returns:
  470. The arg mapping passed to backend event handler
  471. """
  472. return [_prog]
  473. def as_event_spec(self, handler: EventHandler) -> EventSpec:
  474. """Get the EventSpec for the file upload.
  475. Args:
  476. handler: The event handler.
  477. Returns:
  478. The event spec for the handler.
  479. Raises:
  480. ValueError: If the on_upload_progress is not a valid event handler.
  481. """
  482. from reflex.components.core.upload import (
  483. DEFAULT_UPLOAD_ID,
  484. upload_files_context_var_data,
  485. )
  486. upload_id = self.upload_id or DEFAULT_UPLOAD_ID
  487. spec_args = [
  488. (
  489. Var(_js_expr="files"),
  490. Var(
  491. _js_expr="filesById",
  492. _var_type=Dict[str, Any],
  493. _var_data=VarData.merge(upload_files_context_var_data),
  494. ).to(ObjectVar)[LiteralVar.create(upload_id)],
  495. ),
  496. (
  497. Var(_js_expr="upload_id"),
  498. LiteralVar.create(upload_id),
  499. ),
  500. ]
  501. if self.on_upload_progress is not None:
  502. on_upload_progress = self.on_upload_progress
  503. if isinstance(on_upload_progress, EventHandler):
  504. events = [
  505. call_event_handler(
  506. on_upload_progress,
  507. self.on_upload_progress_args_spec,
  508. ),
  509. ]
  510. elif isinstance(on_upload_progress, Callable):
  511. # Call the lambda to get the event chain.
  512. events = call_event_fn(
  513. on_upload_progress, self.on_upload_progress_args_spec
  514. ) # type: ignore
  515. else:
  516. raise ValueError(f"{on_upload_progress} is not a valid event handler.")
  517. if isinstance(events, Var):
  518. raise ValueError(f"{on_upload_progress} cannot return a var {events}.")
  519. on_upload_progress_chain = EventChain(
  520. events=[*events],
  521. args_spec=self.on_upload_progress_args_spec,
  522. )
  523. formatted_chain = str(format.format_prop(on_upload_progress_chain))
  524. spec_args.append(
  525. (
  526. Var(_js_expr="on_upload_progress"),
  527. FunctionStringVar(
  528. formatted_chain.strip("{}"),
  529. ).to(FunctionVar, EventChain),
  530. ),
  531. )
  532. return EventSpec(
  533. handler=handler,
  534. client_handler_name="uploadFiles",
  535. args=tuple(spec_args),
  536. event_actions=handler.event_actions.copy(),
  537. )
  538. # Alias for rx.upload_files
  539. upload_files = FileUpload
  540. # Special server-side events.
  541. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  542. """A server-side event.
  543. Args:
  544. name: The name of the event.
  545. sig: The function signature of the event.
  546. **kwargs: The arguments to pass to the event.
  547. Returns:
  548. An event spec for a server-side event.
  549. """
  550. def fn():
  551. return None
  552. fn.__qualname__ = name
  553. fn.__signature__ = sig
  554. return EventSpec(
  555. handler=EventHandler(fn=fn, state_full_name=FRONTEND_EVENT_STATE),
  556. args=tuple(
  557. (
  558. Var(_js_expr=k),
  559. LiteralVar.create(v),
  560. )
  561. for k, v in kwargs.items()
  562. ),
  563. )
  564. def redirect(
  565. path: str | Var[str],
  566. external: Optional[bool] = False,
  567. replace: Optional[bool] = False,
  568. ) -> EventSpec:
  569. """Redirect to a new path.
  570. Args:
  571. path: The path to redirect to.
  572. external: Whether to open in new tab or not.
  573. replace: If True, the current page will not create a new history entry.
  574. Returns:
  575. An event to redirect to the path.
  576. """
  577. return server_side(
  578. "_redirect",
  579. get_fn_signature(redirect),
  580. path=path,
  581. external=external,
  582. replace=replace,
  583. )
  584. def console_log(message: str | Var[str]) -> EventSpec:
  585. """Do a console.log on the browser.
  586. Args:
  587. message: The message to log.
  588. Returns:
  589. An event to log the message.
  590. """
  591. return run_script(Var("console").to(dict).log.to(FunctionVar).call(message))
  592. def noop() -> EventSpec:
  593. """Do nothing.
  594. Returns:
  595. An event to do nothing.
  596. """
  597. return run_script(Var.create(None))
  598. def back() -> EventSpec:
  599. """Do a history.back on the browser.
  600. Returns:
  601. An event to go back one page.
  602. """
  603. return run_script(
  604. Var("window").to(dict).history.to(dict).back.to(FunctionVar).call()
  605. )
  606. def window_alert(message: str | Var[str]) -> EventSpec:
  607. """Create a window alert on the browser.
  608. Args:
  609. message: The message to alert.
  610. Returns:
  611. An event to alert the message.
  612. """
  613. return run_script(Var("window").to(dict).alert.to(FunctionVar).call(message))
  614. def set_focus(ref: str) -> EventSpec:
  615. """Set focus to specified ref.
  616. Args:
  617. ref: The ref.
  618. Returns:
  619. An event to set focus on the ref
  620. """
  621. return server_side(
  622. "_set_focus",
  623. get_fn_signature(set_focus),
  624. ref=LiteralVar.create(format.format_ref(ref)),
  625. )
  626. def scroll_to(elem_id: str, align_to_top: bool | Var[bool] = True) -> EventSpec:
  627. """Select the id of a html element for scrolling into view.
  628. Args:
  629. elem_id: The id of the element to scroll to.
  630. align_to_top: Whether to scroll to the top (True) or bottom (False) of the element.
  631. Returns:
  632. An EventSpec to scroll the page to the selected element.
  633. """
  634. get_element_by_id = FunctionStringVar.create("document.getElementById")
  635. return run_script(
  636. get_element_by_id.call(elem_id)
  637. .to(ObjectVar)
  638. .scrollIntoView.to(FunctionVar)
  639. .call(align_to_top),
  640. )
  641. def set_value(ref: str, value: Any) -> EventSpec:
  642. """Set the value of a ref.
  643. Args:
  644. ref: The ref.
  645. value: The value to set.
  646. Returns:
  647. An event to set the ref.
  648. """
  649. return server_side(
  650. "_set_value",
  651. get_fn_signature(set_value),
  652. ref=LiteralVar.create(format.format_ref(ref)),
  653. value=value,
  654. )
  655. def remove_cookie(key: str, options: dict[str, Any] | None = None) -> EventSpec:
  656. """Remove a cookie on the frontend.
  657. Args:
  658. key: The key identifying the cookie to be removed.
  659. options: Support all the cookie options from RFC 6265
  660. Returns:
  661. EventSpec: An event to remove a cookie.
  662. """
  663. options = options or {}
  664. options["path"] = options.get("path", "/")
  665. return server_side(
  666. "_remove_cookie",
  667. get_fn_signature(remove_cookie),
  668. key=key,
  669. options=options,
  670. )
  671. def clear_local_storage() -> EventSpec:
  672. """Set a value in the local storage on the frontend.
  673. Returns:
  674. EventSpec: An event to clear the local storage.
  675. """
  676. return server_side(
  677. "_clear_local_storage",
  678. get_fn_signature(clear_local_storage),
  679. )
  680. def remove_local_storage(key: str) -> EventSpec:
  681. """Set a value in the local storage on the frontend.
  682. Args:
  683. key: The key identifying the variable in the local storage to remove.
  684. Returns:
  685. EventSpec: An event to remove an item based on the provided key in local storage.
  686. """
  687. return server_side(
  688. "_remove_local_storage",
  689. get_fn_signature(remove_local_storage),
  690. key=key,
  691. )
  692. def clear_session_storage() -> EventSpec:
  693. """Set a value in the session storage on the frontend.
  694. Returns:
  695. EventSpec: An event to clear the session storage.
  696. """
  697. return server_side(
  698. "_clear_session_storage",
  699. get_fn_signature(clear_session_storage),
  700. )
  701. def remove_session_storage(key: str) -> EventSpec:
  702. """Set a value in the session storage on the frontend.
  703. Args:
  704. key: The key identifying the variable in the session storage to remove.
  705. Returns:
  706. EventSpec: An event to remove an item based on the provided key in session storage.
  707. """
  708. return server_side(
  709. "_remove_session_storage",
  710. get_fn_signature(remove_session_storage),
  711. key=key,
  712. )
  713. def set_clipboard(content: Union[str, Var[str]]) -> EventSpec:
  714. """Set the text in content in the clipboard.
  715. Args:
  716. content: The text to add to clipboard.
  717. Returns:
  718. EventSpec: An event to set some content in the clipboard.
  719. """
  720. return run_script(
  721. Var("navigator")
  722. .to(dict)
  723. .clipboard.to(dict)
  724. .writeText.to(FunctionVar)
  725. .call(content)
  726. )
  727. def download(
  728. url: str | Var | None = None,
  729. filename: Optional[str | Var] = None,
  730. data: str | bytes | Var | None = None,
  731. ) -> EventSpec:
  732. """Download the file at a given path or with the specified data.
  733. Args:
  734. url: The URL to the file to download.
  735. filename: The name that the file should be saved as after download.
  736. data: The data to download.
  737. Raises:
  738. ValueError: If the URL provided is invalid, both URL and data are provided,
  739. or the data is not an expected type.
  740. Returns:
  741. EventSpec: An event to download the associated file.
  742. """
  743. from reflex.components.core.cond import cond
  744. if isinstance(url, str):
  745. if not url.startswith("/"):
  746. raise ValueError("The URL argument should start with a /")
  747. # if filename is not provided, infer it from url
  748. if filename is None:
  749. filename = url.rpartition("/")[-1]
  750. if filename is None:
  751. filename = ""
  752. if data is not None:
  753. if url is not None:
  754. raise ValueError("Cannot provide both URL and data to download.")
  755. if isinstance(data, str):
  756. # Caller provided a plain text string to download.
  757. url = "data:text/plain," + urllib.parse.quote(data)
  758. elif isinstance(data, Var):
  759. # Need to check on the frontend if the Var already looks like a data: URI.
  760. is_data_url = (data.js_type() == "string") & (
  761. data.to(str).startswith("data:")
  762. ) # type: ignore
  763. # If it's a data: URI, use it as is, otherwise convert the Var to JSON in a data: URI.
  764. url = cond( # type: ignore
  765. is_data_url,
  766. data.to(str),
  767. "data:text/plain," + data.to_string(), # type: ignore
  768. )
  769. elif isinstance(data, bytes):
  770. # Caller provided bytes, so base64 encode it as a data: URI.
  771. b64_data = b64encode(data).decode("utf-8")
  772. url = "data:application/octet-stream;base64," + b64_data
  773. else:
  774. raise ValueError(
  775. f"Invalid data type {type(data)} for download. Use `str` or `bytes`."
  776. )
  777. return server_side(
  778. "_download",
  779. get_fn_signature(download),
  780. url=url,
  781. filename=filename,
  782. )
  783. def _callback_arg_spec(eval_result):
  784. """ArgSpec for call_script callback function.
  785. Args:
  786. eval_result: The result of the javascript execution.
  787. Returns:
  788. Args for the callback function
  789. """
  790. return [eval_result]
  791. def call_script(
  792. javascript_code: str | Var[str],
  793. callback: EventType | None = None,
  794. ) -> EventSpec:
  795. """Create an event handler that executes arbitrary javascript code.
  796. Args:
  797. javascript_code: The code to execute.
  798. callback: EventHandler that will receive the result of evaluating the javascript code.
  799. Returns:
  800. EventSpec: An event that will execute the client side javascript.
  801. """
  802. callback_kwargs = {}
  803. if callback is not None:
  804. callback_kwargs = {
  805. "callback": format.format_queue_events(
  806. callback,
  807. args_spec=lambda result: [result],
  808. )._js_expr,
  809. }
  810. if isinstance(javascript_code, str):
  811. # When there is VarData, include it and eval the JS code inline on the client.
  812. javascript_code, original_code = (
  813. LiteralVar.create(javascript_code),
  814. javascript_code,
  815. )
  816. if not javascript_code._get_all_var_data():
  817. # Without VarData, cast to string and eval the code in the event loop.
  818. javascript_code = str(Var(_js_expr=original_code))
  819. return server_side(
  820. "_call_script",
  821. get_fn_signature(call_script),
  822. javascript_code=javascript_code,
  823. **callback_kwargs,
  824. )
  825. def call_function(
  826. javascript_code: str | Var,
  827. callback: EventType | None = None,
  828. ) -> EventSpec:
  829. """Create an event handler that executes arbitrary javascript code.
  830. Args:
  831. javascript_code: The code to execute.
  832. callback: EventHandler that will receive the result of evaluating the javascript code.
  833. Returns:
  834. EventSpec: An event that will execute the client side javascript.
  835. """
  836. callback_kwargs = {}
  837. if callback is not None:
  838. callback_kwargs = {
  839. "callback": format.format_queue_events(
  840. callback,
  841. args_spec=lambda result: [result],
  842. ),
  843. }
  844. javascript_code = (
  845. Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
  846. )
  847. return server_side(
  848. "_call_function",
  849. get_fn_signature(call_function),
  850. function=javascript_code,
  851. **callback_kwargs,
  852. )
  853. def run_script(
  854. javascript_code: str | Var,
  855. callback: EventType | None = None,
  856. ) -> EventSpec:
  857. """Create an event handler that executes arbitrary javascript code.
  858. Args:
  859. javascript_code: The code to execute.
  860. callback: EventHandler that will receive the result of evaluating the javascript code.
  861. Returns:
  862. EventSpec: An event that will execute the client side javascript.
  863. """
  864. javascript_code = (
  865. Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
  866. )
  867. return call_function(
  868. ArgsFunctionOperation.create(tuple(), javascript_code), callback
  869. )
  870. def get_event(state, event):
  871. """Get the event from the given state.
  872. Args:
  873. state: The state.
  874. event: The event.
  875. Returns:
  876. The event.
  877. """
  878. return f"{state.get_name()}.{event}"
  879. def get_hydrate_event(state) -> str:
  880. """Get the name of the hydrate event for the state.
  881. Args:
  882. state: The state.
  883. Returns:
  884. The name of the hydrate event.
  885. """
  886. return get_event(state, constants.CompileVars.HYDRATE)
  887. def call_event_handler(
  888. event_callback: EventHandler | EventSpec,
  889. event_spec: ArgsSpec | Sequence[ArgsSpec],
  890. key: Optional[str] = None,
  891. ) -> EventSpec:
  892. """Call an event handler to get the event spec.
  893. This function will inspect the function signature of the event handler.
  894. If it takes in an arg, the arg will be passed to the event handler.
  895. Otherwise, the event handler will be called with no args.
  896. Args:
  897. event_callback: The event handler.
  898. event_spec: The lambda that define the argument(s) to pass to the event handler.
  899. key: The key to pass to the event handler.
  900. Returns:
  901. The event spec from calling the event handler.
  902. # noqa: DAR401 failure
  903. """
  904. event_spec_args = parse_args_spec(event_spec) # type: ignore
  905. if isinstance(event_callback, EventSpec):
  906. check_fn_match_arg_spec(
  907. event_callback.handler.fn,
  908. event_spec,
  909. key,
  910. bool(event_callback.handler.state_full_name) + len(event_callback.args),
  911. event_callback.handler.fn.__qualname__,
  912. )
  913. # Handle partial application of EventSpec args
  914. return event_callback.add_args(*event_spec_args)
  915. check_fn_match_arg_spec(
  916. event_callback.fn,
  917. event_spec,
  918. key,
  919. bool(event_callback.state_full_name),
  920. event_callback.fn.__qualname__,
  921. )
  922. all_acceptable_specs = (
  923. [event_spec] if not isinstance(event_spec, Sequence) else event_spec
  924. )
  925. event_spec_return_types = list(
  926. filter(
  927. lambda event_spec_return_type: event_spec_return_type is not None
  928. and get_origin(event_spec_return_type) is tuple,
  929. (
  930. get_type_hints(arg_spec).get("return", None)
  931. for arg_spec in all_acceptable_specs
  932. ),
  933. )
  934. )
  935. if event_spec_return_types:
  936. failures = []
  937. event_callback_spec = inspect.getfullargspec(event_callback.fn)
  938. for event_spec_index, event_spec_return_type in enumerate(
  939. event_spec_return_types
  940. ):
  941. args = get_args(event_spec_return_type)
  942. args_types_without_vars = [
  943. arg if get_origin(arg) is not Var else get_args(arg)[0] for arg in args
  944. ]
  945. try:
  946. type_hints_of_provided_callback = get_type_hints(event_callback.fn)
  947. except NameError:
  948. type_hints_of_provided_callback = {}
  949. failed_type_check = False
  950. # check that args of event handler are matching the spec if type hints are provided
  951. for i, arg in enumerate(event_callback_spec.args[1:]):
  952. if arg not in type_hints_of_provided_callback:
  953. continue
  954. try:
  955. compare_result = typehint_issubclass(
  956. args_types_without_vars[i], type_hints_of_provided_callback[arg]
  957. )
  958. except TypeError:
  959. # TODO: In 0.7.0, remove this block and raise the exception
  960. # raise TypeError(
  961. # f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}."
  962. # ) from e
  963. console.warn(
  964. f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_callback.fn.__qualname__} provided for {key}."
  965. )
  966. compare_result = False
  967. if compare_result:
  968. continue
  969. else:
  970. failure = EventHandlerArgTypeMismatch(
  971. f"Event handler {key} expects {args_types_without_vars[i]} for argument {arg} but got {type_hints_of_provided_callback[arg]} as annotated in {event_callback.fn.__qualname__} instead."
  972. )
  973. failures.append(failure)
  974. failed_type_check = True
  975. break
  976. if not failed_type_check:
  977. if event_spec_index:
  978. args = get_args(event_spec_return_types[0])
  979. args_types_without_vars = [
  980. arg if get_origin(arg) is not Var else get_args(arg)[0]
  981. for arg in args
  982. ]
  983. expect_string = ", ".join(
  984. repr(arg) for arg in args_types_without_vars
  985. ).replace("[", "\\[")
  986. given_string = ", ".join(
  987. repr(type_hints_of_provided_callback.get(arg, Any))
  988. for arg in event_callback_spec.args[1:]
  989. ).replace("[", "\\[")
  990. console.warn(
  991. f"Event handler {key} expects ({expect_string}) -> () but got ({given_string}) -> () as annotated in {event_callback.fn.__qualname__} instead. "
  992. f"This may lead to unexpected behavior but is intentionally ignored for {key}."
  993. )
  994. return event_callback(*event_spec_args)
  995. if failures:
  996. console.deprecate(
  997. "Mismatched event handler argument types",
  998. "\n".join([str(f) for f in failures]),
  999. "0.6.5",
  1000. "0.7.0",
  1001. )
  1002. return event_callback(*event_spec_args) # type: ignore
  1003. def unwrap_var_annotation(annotation: GenericType):
  1004. """Unwrap a Var annotation or return it as is if it's not Var[X].
  1005. Args:
  1006. annotation: The annotation to unwrap.
  1007. Returns:
  1008. The unwrapped annotation.
  1009. """
  1010. if get_origin(annotation) is Var and (args := get_args(annotation)):
  1011. return args[0]
  1012. return annotation
  1013. def resolve_annotation(annotations: dict[str, Any], arg_name: str):
  1014. """Resolve the annotation for the given argument name.
  1015. Args:
  1016. annotations: The annotations.
  1017. arg_name: The argument name.
  1018. Returns:
  1019. The resolved annotation.
  1020. """
  1021. annotation = annotations.get(arg_name)
  1022. if annotation is None:
  1023. console.deprecate(
  1024. feature_name="Unannotated event handler arguments",
  1025. reason="Provide type annotations for event handler arguments.",
  1026. deprecation_version="0.6.3",
  1027. removal_version="0.7.0",
  1028. )
  1029. # Allow arbitrary attribute access two levels deep until removed.
  1030. return Dict[str, dict]
  1031. return annotation
  1032. def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]):
  1033. """Parse the args provided in the ArgsSpec of an event trigger.
  1034. Args:
  1035. arg_spec: The spec of the args.
  1036. Returns:
  1037. The parsed args.
  1038. """
  1039. # if there's multiple, the first is the default
  1040. arg_spec = arg_spec[0] if isinstance(arg_spec, Sequence) else arg_spec
  1041. spec = inspect.getfullargspec(arg_spec)
  1042. annotations = get_type_hints(arg_spec)
  1043. return list(
  1044. arg_spec(
  1045. *[
  1046. Var(f"_{l_arg}").to(
  1047. unwrap_var_annotation(resolve_annotation(annotations, l_arg))
  1048. )
  1049. for l_arg in spec.args
  1050. ]
  1051. )
  1052. )
  1053. def check_fn_match_arg_spec(
  1054. user_func: Callable,
  1055. arg_spec: ArgsSpec | Sequence[ArgsSpec],
  1056. key: str | None = None,
  1057. number_of_bound_args: int = 0,
  1058. func_name: str | None = None,
  1059. ):
  1060. """Ensures that the function signature matches the passed argument specification
  1061. or raises an EventFnArgMismatch if they do not.
  1062. Args:
  1063. user_func: The function to be validated.
  1064. arg_spec: The argument specification for the event trigger.
  1065. key: The key of the event trigger.
  1066. number_of_bound_args: The number of bound arguments to the function.
  1067. func_name: The name of the function to be validated.
  1068. Raises:
  1069. EventFnArgMismatch: Raised if the number of mandatory arguments do not match
  1070. """
  1071. user_args = inspect.getfullargspec(user_func).args
  1072. # Drop the first argument if it's a bound method
  1073. if inspect.ismethod(user_func) and user_func.__self__ is not None:
  1074. user_args = user_args[1:]
  1075. user_default_args = inspect.getfullargspec(user_func).defaults
  1076. number_of_user_args = len(user_args) - number_of_bound_args
  1077. number_of_user_default_args = len(user_default_args) if user_default_args else 0
  1078. parsed_event_args = parse_args_spec(arg_spec)
  1079. number_of_event_args = len(parsed_event_args)
  1080. if number_of_user_args - number_of_user_default_args > number_of_event_args:
  1081. raise EventFnArgMismatch(
  1082. f"Event {key} only provides {number_of_event_args} arguments, but "
  1083. f"{func_name or user_func} requires at least {number_of_user_args - number_of_user_default_args} "
  1084. "arguments to be passed to the event handler.\n"
  1085. "See https://reflex.dev/docs/events/event-arguments/"
  1086. )
  1087. def call_event_fn(
  1088. fn: Callable,
  1089. arg_spec: ArgsSpec | Sequence[ArgsSpec],
  1090. key: Optional[str] = None,
  1091. ) -> list[EventSpec] | Var:
  1092. """Call a function to a list of event specs.
  1093. The function should return a single EventSpec, a list of EventSpecs, or a
  1094. single Var.
  1095. Args:
  1096. fn: The function to call.
  1097. arg_spec: The argument spec for the event trigger.
  1098. key: The key to pass to the event handler.
  1099. Returns:
  1100. The event specs from calling the function or a Var.
  1101. Raises:
  1102. EventHandlerValueError: If the lambda returns an unusable value.
  1103. """
  1104. # Import here to avoid circular imports.
  1105. from reflex.event import EventHandler, EventSpec
  1106. from reflex.utils.exceptions import EventHandlerValueError
  1107. # Check that fn signature matches arg_spec
  1108. check_fn_match_arg_spec(fn, arg_spec, key=key)
  1109. parsed_args = parse_args_spec(arg_spec)
  1110. number_of_fn_args = len(inspect.getfullargspec(fn).args)
  1111. # Call the function with the parsed args.
  1112. out = fn(*[*parsed_args][:number_of_fn_args])
  1113. # If the function returns a Var, assume it's an EventChain and render it directly.
  1114. if isinstance(out, Var):
  1115. return out
  1116. # Convert the output to a list.
  1117. if not isinstance(out, list):
  1118. out = [out]
  1119. # Convert any event specs to event specs.
  1120. events = []
  1121. for e in out:
  1122. if isinstance(e, EventHandler):
  1123. # An un-called EventHandler gets all of the args of the event trigger.
  1124. e = call_event_handler(e, arg_spec, key=key)
  1125. # Make sure the event spec is valid.
  1126. if not isinstance(e, EventSpec):
  1127. raise EventHandlerValueError(
  1128. f"Lambda {fn} returned an invalid event spec: {e}."
  1129. )
  1130. # Add the event spec to the chain.
  1131. events.append(e)
  1132. # Return the events.
  1133. return events
  1134. def get_handler_args(
  1135. event_spec: EventSpec,
  1136. ) -> tuple[tuple[Var, Var], ...]:
  1137. """Get the handler args for the given event spec.
  1138. Args:
  1139. event_spec: The event spec.
  1140. Returns:
  1141. The handler args.
  1142. """
  1143. args = inspect.getfullargspec(event_spec.handler.fn).args
  1144. return event_spec.args if len(args) > 1 else tuple()
  1145. def fix_events(
  1146. events: list[EventHandler | EventSpec] | None,
  1147. token: str,
  1148. router_data: dict[str, Any] | None = None,
  1149. ) -> list[Event]:
  1150. """Fix a list of events returned by an event handler.
  1151. Args:
  1152. events: The events to fix.
  1153. token: The user token.
  1154. router_data: The optional router data to set in the event.
  1155. Raises:
  1156. ValueError: If the event type is not what was expected.
  1157. Returns:
  1158. The fixed events.
  1159. """
  1160. # If the event handler returns nothing, return an empty list.
  1161. if events is None:
  1162. return []
  1163. # If the handler returns a single event, wrap it in a list.
  1164. if not isinstance(events, List):
  1165. events = [events]
  1166. # Fix the events created by the handler.
  1167. out = []
  1168. for e in events:
  1169. if isinstance(e, Event):
  1170. # If the event is already an event, append it to the list.
  1171. out.append(e)
  1172. continue
  1173. if not isinstance(e, (EventHandler, EventSpec)):
  1174. e = EventHandler(fn=e)
  1175. # Otherwise, create an event from the event spec.
  1176. if isinstance(e, EventHandler):
  1177. e = e()
  1178. if not isinstance(e, EventSpec):
  1179. raise ValueError(f"Unexpected event type, {type(e)}.")
  1180. name = format.format_event_handler(e.handler)
  1181. payload = {k._js_expr: v._decode() for k, v in e.args} # type: ignore
  1182. # Filter router_data to reduce payload size
  1183. event_router_data = {
  1184. k: v
  1185. for k, v in (router_data or {}).items()
  1186. if k in constants.route.ROUTER_DATA_INCLUDE
  1187. }
  1188. # Create an event and append it to the list.
  1189. out.append(
  1190. Event(
  1191. token=token,
  1192. name=name,
  1193. payload=payload,
  1194. router_data=event_router_data,
  1195. )
  1196. )
  1197. return out
  1198. def get_fn_signature(fn: Callable) -> inspect.Signature:
  1199. """Get the signature of a function.
  1200. Args:
  1201. fn: The function.
  1202. Returns:
  1203. The signature of the function.
  1204. """
  1205. signature = inspect.signature(fn)
  1206. new_param = inspect.Parameter(
  1207. FRONTEND_EVENT_STATE, inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  1208. )
  1209. return signature.replace(parameters=(new_param, *signature.parameters.values()))
  1210. class EventVar(ObjectVar, python_types=EventSpec):
  1211. """Base class for event vars."""
  1212. @dataclasses.dataclass(
  1213. eq=False,
  1214. frozen=True,
  1215. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1216. )
  1217. class LiteralEventVar(VarOperationCall, LiteralVar, EventVar):
  1218. """A literal event var."""
  1219. _var_value: EventSpec = dataclasses.field(default=None) # type: ignore
  1220. def __hash__(self) -> int:
  1221. """Get the hash of the var.
  1222. Returns:
  1223. The hash of the var.
  1224. """
  1225. return hash((self.__class__.__name__, self._js_expr))
  1226. @classmethod
  1227. def create(
  1228. cls,
  1229. value: EventSpec,
  1230. _var_data: VarData | None = None,
  1231. ) -> LiteralEventVar:
  1232. """Create a new LiteralEventVar instance.
  1233. Args:
  1234. value: The value of the var.
  1235. _var_data: The data of the var.
  1236. Returns:
  1237. The created LiteralEventVar instance.
  1238. """
  1239. return cls(
  1240. _js_expr="",
  1241. _var_type=EventSpec,
  1242. _var_data=_var_data,
  1243. _var_value=value,
  1244. _func=FunctionStringVar("Event"),
  1245. _args=(
  1246. # event handler name
  1247. ".".join(
  1248. filter(
  1249. None,
  1250. format.get_event_handler_parts(value.handler),
  1251. )
  1252. ),
  1253. # event handler args
  1254. {str(name): value for name, value in value.args},
  1255. # event actions
  1256. value.event_actions,
  1257. # client handler name
  1258. *([value.client_handler_name] if value.client_handler_name else []),
  1259. ),
  1260. )
  1261. class EventChainVar(BuilderFunctionVar, python_types=EventChain):
  1262. """Base class for event chain vars."""
  1263. @dataclasses.dataclass(
  1264. eq=False,
  1265. frozen=True,
  1266. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1267. )
  1268. # Note: LiteralVar is second in the inheritance list allowing it act like a
  1269. # CachedVarOperation (ArgsFunctionOperation) and get the _js_expr from the
  1270. # _cached_var_name property.
  1271. class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainVar):
  1272. """A literal event chain var."""
  1273. _var_value: EventChain = dataclasses.field(default=None) # type: ignore
  1274. def __hash__(self) -> int:
  1275. """Get the hash of the var.
  1276. Returns:
  1277. The hash of the var.
  1278. """
  1279. return hash((self.__class__.__name__, self._js_expr))
  1280. @classmethod
  1281. def create(
  1282. cls,
  1283. value: EventChain,
  1284. _var_data: VarData | None = None,
  1285. ) -> LiteralEventChainVar:
  1286. """Create a new LiteralEventChainVar instance.
  1287. Args:
  1288. value: The value of the var.
  1289. _var_data: The data of the var.
  1290. Returns:
  1291. The created LiteralEventChainVar instance.
  1292. """
  1293. arg_spec = (
  1294. value.args_spec[0]
  1295. if isinstance(value.args_spec, Sequence)
  1296. else value.args_spec
  1297. )
  1298. sig = inspect.signature(arg_spec) # type: ignore
  1299. if sig.parameters:
  1300. arg_def = tuple((f"_{p}" for p in sig.parameters))
  1301. arg_def_expr = LiteralVar.create([Var(_js_expr=arg) for arg in arg_def])
  1302. else:
  1303. # add a default argument for addEvents if none were specified in value.args_spec
  1304. # used to trigger the preventDefault() on the event.
  1305. arg_def = ("...args",)
  1306. arg_def_expr = Var(_js_expr="args")
  1307. if value.invocation is None:
  1308. invocation = FunctionStringVar.create("addEvents")
  1309. else:
  1310. invocation = value.invocation
  1311. return cls(
  1312. _js_expr="",
  1313. _var_type=EventChain,
  1314. _var_data=_var_data,
  1315. _args=FunctionArgs(arg_def),
  1316. _return_expr=invocation.call(
  1317. LiteralVar.create([LiteralVar.create(event) for event in value.events]),
  1318. arg_def_expr,
  1319. value.event_actions,
  1320. ),
  1321. _var_value=value,
  1322. )
  1323. P = ParamSpec("P")
  1324. Q = ParamSpec("Q")
  1325. T = TypeVar("T")
  1326. V = TypeVar("V")
  1327. V2 = TypeVar("V2")
  1328. V3 = TypeVar("V3")
  1329. V4 = TypeVar("V4")
  1330. V5 = TypeVar("V5")
  1331. background_event_decorator = background
  1332. class EventCallback(Generic[P, T]):
  1333. """A descriptor that wraps a function to be used as an event."""
  1334. def __init__(self, func: Callable[Concatenate[Any, P], T]):
  1335. """Initialize the descriptor with the function to be wrapped.
  1336. Args:
  1337. func: The function to be wrapped.
  1338. """
  1339. self.func = func
  1340. @property
  1341. def prevent_default(self):
  1342. """Prevent default behavior.
  1343. Returns:
  1344. The event callback with prevent default behavior.
  1345. """
  1346. return self
  1347. @property
  1348. def stop_propagation(self):
  1349. """Stop event propagation.
  1350. Returns:
  1351. The event callback with stop propagation behavior.
  1352. """
  1353. return self
  1354. @overload
  1355. def __call__(
  1356. self: EventCallback[Q, T],
  1357. ) -> EventCallback[Q, T]: ...
  1358. @overload
  1359. def __call__(
  1360. self: EventCallback[Concatenate[V, Q], T], value: V | Var[V]
  1361. ) -> EventCallback[Q, T]: ...
  1362. @overload
  1363. def __call__(
  1364. self: EventCallback[Concatenate[V, V2, Q], T],
  1365. value: V | Var[V],
  1366. value2: V2 | Var[V2],
  1367. ) -> EventCallback[Q, T]: ...
  1368. @overload
  1369. def __call__(
  1370. self: EventCallback[Concatenate[V, V2, V3, Q], T],
  1371. value: V | Var[V],
  1372. value2: V2 | Var[V2],
  1373. value3: V3 | Var[V3],
  1374. ) -> EventCallback[Q, T]: ...
  1375. @overload
  1376. def __call__(
  1377. self: EventCallback[Concatenate[V, V2, V3, V4, Q], T],
  1378. value: V | Var[V],
  1379. value2: V2 | Var[V2],
  1380. value3: V3 | Var[V3],
  1381. value4: V4 | Var[V4],
  1382. ) -> EventCallback[Q, T]: ...
  1383. def __call__(self, *values) -> EventCallback: # type: ignore
  1384. """Call the function with the values.
  1385. Args:
  1386. *values: The values to call the function with.
  1387. Returns:
  1388. The function with the values.
  1389. """
  1390. return self.func(*values) # type: ignore
  1391. @overload
  1392. def __get__(
  1393. self: EventCallback[P, T], instance: None, owner
  1394. ) -> EventCallback[P, T]: ...
  1395. @overload
  1396. def __get__(self, instance, owner) -> Callable[P, T]: ...
  1397. def __get__(self, instance, owner) -> Callable: # type: ignore
  1398. """Get the function with the instance bound to it.
  1399. Args:
  1400. instance: The instance to bind to the function.
  1401. owner: The owner of the function.
  1402. Returns:
  1403. The function with the instance bound to it
  1404. """
  1405. if instance is None:
  1406. return self.func # type: ignore
  1407. return partial(self.func, instance) # type: ignore
  1408. G = ParamSpec("G")
  1409. if TYPE_CHECKING:
  1410. from reflex.state import BaseState
  1411. BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
  1412. else:
  1413. BASE_STATE = TypeVar("BASE_STATE")
  1414. StateCallable = TypeAliasType(
  1415. "StateCallable",
  1416. Callable[Concatenate[BASE_STATE, G], Any],
  1417. type_params=(G, BASE_STATE),
  1418. )
  1419. IndividualEventType = Union[
  1420. EventSpec,
  1421. EventHandler,
  1422. Callable[G, Any],
  1423. StateCallable[G, BASE_STATE],
  1424. EventCallback[G, Any],
  1425. Var[Any],
  1426. ]
  1427. ItemOrList = Union[V, List[V]]
  1428. EventType = ItemOrList[IndividualEventType[G, BASE_STATE]]
  1429. class EventNamespace(types.SimpleNamespace):
  1430. """A namespace for event related classes."""
  1431. Event = Event
  1432. EventHandler = EventHandler
  1433. EventSpec = EventSpec
  1434. CallableEventSpec = CallableEventSpec
  1435. EventChain = EventChain
  1436. EventVar = EventVar
  1437. LiteralEventVar = LiteralEventVar
  1438. EventChainVar = EventChainVar
  1439. LiteralEventChainVar = LiteralEventChainVar
  1440. EventType = EventType
  1441. EventCallback = EventCallback
  1442. @overload
  1443. @staticmethod
  1444. def __call__(
  1445. func: None = None, *, background: bool | None = None
  1446. ) -> Callable[[Callable[Concatenate[BASE_STATE, P], T]], EventCallback[P, T]]: ...
  1447. @overload
  1448. @staticmethod
  1449. def __call__(
  1450. func: Callable[Concatenate[BASE_STATE, P], T],
  1451. *,
  1452. background: bool | None = None,
  1453. ) -> EventCallback[P, T]: ...
  1454. @staticmethod
  1455. def __call__(
  1456. func: Callable[Concatenate[BASE_STATE, P], T] | None = None,
  1457. *,
  1458. background: bool | None = None,
  1459. ) -> Union[
  1460. EventCallback[P, T],
  1461. Callable[[Callable[Concatenate[BASE_STATE, P], T]], EventCallback[P, T]],
  1462. ]:
  1463. """Wrap a function to be used as an event.
  1464. Args:
  1465. func: The function to wrap.
  1466. background: Whether the event should be run in the background. Defaults to False.
  1467. Returns:
  1468. The wrapped function.
  1469. """
  1470. def wrapper(
  1471. func: Callable[Concatenate[BASE_STATE, P], T],
  1472. ) -> EventCallback[P, T]:
  1473. if background is True:
  1474. return background_event_decorator(func, __internal_reflex_call=True) # type: ignore
  1475. return func # type: ignore
  1476. if func is not None:
  1477. return wrapper(func)
  1478. return wrapper
  1479. get_event = staticmethod(get_event)
  1480. get_hydrate_event = staticmethod(get_hydrate_event)
  1481. fix_events = staticmethod(fix_events)
  1482. call_event_handler = staticmethod(call_event_handler)
  1483. call_event_fn = staticmethod(call_event_fn)
  1484. get_handler_args = staticmethod(get_handler_args)
  1485. check_fn_match_arg_spec = staticmethod(check_fn_match_arg_spec)
  1486. resolve_annotation = staticmethod(resolve_annotation)
  1487. parse_args_spec = staticmethod(parse_args_spec)
  1488. passthrough_event_spec = staticmethod(passthrough_event_spec)
  1489. input_event = staticmethod(input_event)
  1490. key_event = staticmethod(key_event)
  1491. no_args_event_spec = staticmethod(no_args_event_spec)
  1492. server_side = staticmethod(server_side)
  1493. redirect = staticmethod(redirect)
  1494. console_log = staticmethod(console_log)
  1495. noop = staticmethod(noop)
  1496. back = staticmethod(back)
  1497. window_alert = staticmethod(window_alert)
  1498. set_focus = staticmethod(set_focus)
  1499. scroll_to = staticmethod(scroll_to)
  1500. set_value = staticmethod(set_value)
  1501. remove_cookie = staticmethod(remove_cookie)
  1502. clear_local_storage = staticmethod(clear_local_storage)
  1503. remove_local_storage = staticmethod(remove_local_storage)
  1504. clear_session_storage = staticmethod(clear_session_storage)
  1505. remove_session_storage = staticmethod(remove_session_storage)
  1506. set_clipboard = staticmethod(set_clipboard)
  1507. download = staticmethod(download)
  1508. call_script = staticmethod(call_script)
  1509. call_function = staticmethod(call_function)
  1510. run_script = staticmethod(run_script)
  1511. event = EventNamespace()