event.py 60 KB

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