event.py 59 KB

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