event.py 59 KB

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