event.py 65 KB

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