event.py 59 KB

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