event.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  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. List,
  16. Protocol,
  17. Sequence,
  18. Type,
  19. TypedDict,
  20. TypeVar,
  21. get_args,
  22. get_origin,
  23. get_type_hints,
  24. overload,
  25. )
  26. from typing_extensions import Self, TypeAliasType, TypeVarTuple, Unpack
  27. from reflex import constants
  28. from reflex.constants.compiler import CompileVars, Hooks, Imports
  29. from reflex.constants.state import FRONTEND_EVENT_STATE
  30. from reflex.utils import console, format
  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 = inspect.getfullargspec(self.fn).args[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 = inspect.getfullargspec(self.handler.fn).args[1 + len(self.args) :]
  257. fn_args = (Var(_js_expr=arg) for arg in fn_args)
  258. # Construct the payload.
  259. values = []
  260. arg = None
  261. try:
  262. for arg in args:
  263. values.append(LiteralVar.create(value=arg)) # noqa: PERF401, RUF100
  264. except TypeError as e:
  265. raise EventHandlerTypeError(
  266. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  267. ) from e
  268. new_payload = tuple(zip(fn_args, values, strict=False))
  269. return self.with_args(self.args + new_payload)
  270. @dataclasses.dataclass(
  271. frozen=True,
  272. )
  273. class CallableEventSpec(EventSpec):
  274. """Decorate an EventSpec-returning function to act as both a EventSpec and a function.
  275. This is used as a compatibility shim for replacing EventSpec objects in the
  276. API with functions that return a family of EventSpec.
  277. """
  278. fn: Callable[..., EventSpec] | None = None
  279. def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
  280. """Initialize a CallableEventSpec.
  281. Args:
  282. fn: The function to decorate.
  283. **kwargs: The kwargs to pass to pydantic initializer
  284. """
  285. if fn is not None:
  286. default_event_spec = fn()
  287. super().__init__(
  288. event_actions=default_event_spec.event_actions,
  289. client_handler_name=default_event_spec.client_handler_name,
  290. args=default_event_spec.args,
  291. handler=default_event_spec.handler,
  292. **kwargs,
  293. )
  294. object.__setattr__(self, "fn", fn)
  295. else:
  296. super().__init__(**kwargs)
  297. def __call__(self, *args, **kwargs) -> EventSpec:
  298. """Call the decorated function.
  299. Args:
  300. *args: The args to pass to the function.
  301. **kwargs: The kwargs to pass to the function.
  302. Returns:
  303. The EventSpec returned from calling the function.
  304. Raises:
  305. EventHandlerTypeError: If the CallableEventSpec has no associated function.
  306. """
  307. from reflex.utils.exceptions import EventHandlerTypeError
  308. if self.fn is None:
  309. raise EventHandlerTypeError("CallableEventSpec has no associated function.")
  310. return self.fn(*args, **kwargs)
  311. @dataclasses.dataclass(
  312. init=True,
  313. frozen=True,
  314. )
  315. class EventChain(EventActionsMixin):
  316. """Container for a chain of events that will be executed in order."""
  317. events: Sequence[EventSpec | EventVar | EventCallback] = dataclasses.field(
  318. default_factory=list
  319. )
  320. args_spec: Callable | Sequence[Callable] | None = dataclasses.field(default=None)
  321. invocation: Var | None = dataclasses.field(default=None)
  322. @classmethod
  323. def create(
  324. cls,
  325. value: EventType,
  326. args_spec: ArgsSpec | Sequence[ArgsSpec],
  327. key: str | None = None,
  328. **event_chain_kwargs,
  329. ) -> EventChain | Var:
  330. """Create an event chain from a variety of input types.
  331. Args:
  332. value: The value to create the event chain from.
  333. args_spec: The args_spec of the event trigger being bound.
  334. key: The key of the event trigger being bound.
  335. **event_chain_kwargs: Additional kwargs to pass to the EventChain constructor.
  336. Returns:
  337. The event chain.
  338. Raises:
  339. ValueError: If the value is not a valid event chain.
  340. """
  341. # If it's an event chain var, return it.
  342. if isinstance(value, Var):
  343. if isinstance(value, EventChainVar):
  344. return value
  345. elif isinstance(value, EventVar):
  346. value = [value]
  347. elif safe_issubclass(value._var_type, (EventChain, EventSpec)):
  348. return cls.create(
  349. value=value.guess_type(),
  350. args_spec=args_spec,
  351. key=key,
  352. **event_chain_kwargs,
  353. )
  354. else:
  355. raise ValueError(
  356. f"Invalid event chain: {value!s} of type {value._var_type}"
  357. )
  358. elif isinstance(value, EventChain):
  359. # Trust that the caller knows what they're doing passing an EventChain directly
  360. return value
  361. # If the input is a single event handler, wrap it in a list.
  362. if isinstance(value, (EventHandler, EventSpec)):
  363. value = [value]
  364. # If the input is a list of event handlers, create an event chain.
  365. if isinstance(value, List):
  366. events: list[EventSpec | EventVar] = []
  367. for v in value:
  368. if isinstance(v, (EventHandler, EventSpec)):
  369. # Call the event handler to get the event.
  370. events.append(call_event_handler(v, args_spec, key=key))
  371. elif isinstance(v, Callable):
  372. # Call the lambda to get the event chain.
  373. result = call_event_fn(v, args_spec, key=key)
  374. if isinstance(result, Var):
  375. raise ValueError(
  376. f"Invalid event chain: {v}. Cannot use a Var-returning "
  377. "lambda inside an EventChain list."
  378. )
  379. events.extend(result)
  380. elif isinstance(v, EventVar):
  381. events.append(v)
  382. else:
  383. raise ValueError(f"Invalid event: {v}")
  384. # If the input is a callable, create an event chain.
  385. elif isinstance(value, Callable):
  386. result = call_event_fn(value, args_spec, key=key)
  387. if isinstance(result, Var):
  388. # Recursively call this function if the lambda returned an EventChain Var.
  389. return cls.create(
  390. value=result, args_spec=args_spec, key=key, **event_chain_kwargs
  391. )
  392. events = [*result]
  393. # Otherwise, raise an error.
  394. else:
  395. raise ValueError(f"Invalid event chain: {value}")
  396. # Add args to the event specs if necessary.
  397. events = [
  398. (e.with_args(get_handler_args(e)) if isinstance(e, EventSpec) else e)
  399. for e in events
  400. ]
  401. # Return the event chain.
  402. return cls(
  403. events=events,
  404. args_spec=args_spec,
  405. **event_chain_kwargs,
  406. )
  407. @dataclasses.dataclass(
  408. init=True,
  409. frozen=True,
  410. )
  411. class JavascriptHTMLInputElement:
  412. """Interface for a Javascript HTMLInputElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement."""
  413. value: str = ""
  414. @dataclasses.dataclass(
  415. init=True,
  416. frozen=True,
  417. )
  418. class JavascriptInputEvent:
  419. """Interface for a Javascript InputEvent https://developer.mozilla.org/en-US/docs/Web/API/InputEvent."""
  420. target: JavascriptHTMLInputElement = JavascriptHTMLInputElement() # noqa: RUF009
  421. @dataclasses.dataclass(
  422. init=True,
  423. frozen=True,
  424. )
  425. class JavasciptKeyboardEvent:
  426. """Interface for a Javascript KeyboardEvent https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent."""
  427. key: str = ""
  428. altKey: bool = False # noqa: N815
  429. ctrlKey: bool = False # noqa: N815
  430. metaKey: bool = False # noqa: N815
  431. shiftKey: bool = False # noqa: N815
  432. def input_event(e: ObjectVar[JavascriptInputEvent]) -> tuple[Var[str]]:
  433. """Get the value from an input event.
  434. Args:
  435. e: The input event.
  436. Returns:
  437. The value from the input event.
  438. """
  439. return (e.target.value,)
  440. class KeyInputInfo(TypedDict):
  441. """Information about a key input event."""
  442. alt_key: bool
  443. ctrl_key: bool
  444. meta_key: bool
  445. shift_key: bool
  446. def key_event(
  447. e: ObjectVar[JavasciptKeyboardEvent],
  448. ) -> tuple[Var[str], Var[KeyInputInfo]]:
  449. """Get the key from a keyboard event.
  450. Args:
  451. e: The keyboard event.
  452. Returns:
  453. The key from the keyboard event.
  454. """
  455. return (
  456. e.key.to(str),
  457. Var.create(
  458. {
  459. "alt_key": e.altKey,
  460. "ctrl_key": e.ctrlKey,
  461. "meta_key": e.metaKey,
  462. "shift_key": e.shiftKey,
  463. },
  464. ).to(KeyInputInfo),
  465. )
  466. def no_args_event_spec() -> tuple[()]:
  467. """Empty event handler.
  468. Returns:
  469. An empty tuple.
  470. """
  471. return ()
  472. # These chains can be used for their side effects when no other events are desired.
  473. stop_propagation = EventChain(events=[], args_spec=no_args_event_spec).stop_propagation
  474. prevent_default = EventChain(events=[], args_spec=no_args_event_spec).prevent_default
  475. T = TypeVar("T")
  476. U = TypeVar("U")
  477. class IdentityEventReturn(Generic[T], Protocol):
  478. """Protocol for an identity event return."""
  479. def __call__(self, *values: Var[T]) -> tuple[Var[T], ...]:
  480. """Return the input values.
  481. Args:
  482. *values: The values to return.
  483. Returns:
  484. The input values.
  485. """
  486. return values
  487. @overload
  488. def passthrough_event_spec( # pyright: ignore [reportOverlappingOverload]
  489. event_type: Type[T], /
  490. ) -> Callable[[Var[T]], tuple[Var[T]]]: ...
  491. @overload
  492. def passthrough_event_spec(
  493. event_type_1: Type[T], event_type2: Type[U], /
  494. ) -> Callable[[Var[T], Var[U]], tuple[Var[T], Var[U]]]: ...
  495. @overload
  496. def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[T]: ...
  497. def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[T]: # pyright: ignore [reportInconsistentOverload]
  498. """A helper function that returns the input event as output.
  499. Args:
  500. *event_types: The types of the events.
  501. Returns:
  502. A function that returns the input event as output.
  503. """
  504. def inner(*values: Var[T]) -> tuple[Var[T], ...]:
  505. return values
  506. inner_type = tuple(Var[event_type] for event_type in event_types)
  507. return_annotation = tuple[inner_type]
  508. inner.__signature__ = inspect.signature(inner).replace( # pyright: ignore [reportFunctionMemberAccess]
  509. parameters=[
  510. inspect.Parameter(
  511. f"ev_{i}",
  512. kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
  513. annotation=Var[event_type],
  514. )
  515. for i, event_type in enumerate(event_types)
  516. ],
  517. return_annotation=return_annotation,
  518. )
  519. for i, event_type in enumerate(event_types):
  520. inner.__annotations__[f"ev_{i}"] = Var[event_type]
  521. inner.__annotations__["return"] = return_annotation
  522. return inner
  523. @dataclasses.dataclass(
  524. init=True,
  525. frozen=True,
  526. )
  527. class FileUpload:
  528. """Class to represent a file upload."""
  529. upload_id: str | None = None
  530. on_upload_progress: EventHandler | Callable | None = None
  531. @staticmethod
  532. def on_upload_progress_args_spec(_prog: Var[dict[str, int | float | bool]]):
  533. """Args spec for on_upload_progress event handler.
  534. Returns:
  535. The arg mapping passed to backend event handler
  536. """
  537. return [_prog]
  538. def as_event_spec(self, handler: EventHandler) -> EventSpec:
  539. """Get the EventSpec for the file upload.
  540. Args:
  541. handler: The event handler.
  542. Returns:
  543. The event spec for the handler.
  544. Raises:
  545. ValueError: If the on_upload_progress is not a valid event handler.
  546. """
  547. from reflex.components.core.upload import (
  548. DEFAULT_UPLOAD_ID,
  549. upload_files_context_var_data,
  550. )
  551. upload_id = self.upload_id or DEFAULT_UPLOAD_ID
  552. spec_args = [
  553. (
  554. Var(_js_expr="files"),
  555. Var(
  556. _js_expr="filesById",
  557. _var_type=dict[str, Any],
  558. _var_data=VarData.merge(upload_files_context_var_data),
  559. ).to(ObjectVar)[LiteralVar.create(upload_id)],
  560. ),
  561. (
  562. Var(_js_expr="upload_id"),
  563. LiteralVar.create(upload_id),
  564. ),
  565. ]
  566. if self.on_upload_progress is not None:
  567. on_upload_progress = self.on_upload_progress
  568. if isinstance(on_upload_progress, EventHandler):
  569. events = [
  570. call_event_handler(
  571. on_upload_progress,
  572. self.on_upload_progress_args_spec,
  573. ),
  574. ]
  575. elif isinstance(on_upload_progress, Callable):
  576. # Call the lambda to get the event chain.
  577. events = call_event_fn(
  578. on_upload_progress, self.on_upload_progress_args_spec
  579. )
  580. else:
  581. raise ValueError(f"{on_upload_progress} is not a valid event handler.")
  582. if isinstance(events, Var):
  583. raise ValueError(f"{on_upload_progress} cannot return a var {events}.")
  584. on_upload_progress_chain = EventChain(
  585. events=[*events],
  586. args_spec=self.on_upload_progress_args_spec,
  587. )
  588. formatted_chain = str(format.format_prop(on_upload_progress_chain))
  589. spec_args.append(
  590. (
  591. Var(_js_expr="on_upload_progress"),
  592. FunctionStringVar(
  593. formatted_chain.strip("{}"),
  594. ).to(FunctionVar, EventChain),
  595. ),
  596. )
  597. return EventSpec(
  598. handler=handler,
  599. client_handler_name="uploadFiles",
  600. args=tuple(spec_args),
  601. event_actions=handler.event_actions.copy(),
  602. )
  603. # Alias for rx.upload_files
  604. upload_files = FileUpload
  605. # Special server-side events.
  606. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  607. """A server-side event.
  608. Args:
  609. name: The name of the event.
  610. sig: The function signature of the event.
  611. **kwargs: The arguments to pass to the event.
  612. Returns:
  613. An event spec for a server-side event.
  614. """
  615. def fn():
  616. return None
  617. fn.__qualname__ = name
  618. fn.__signature__ = sig # pyright: ignore [reportFunctionMemberAccess]
  619. return EventSpec(
  620. handler=EventHandler(fn=fn, state_full_name=FRONTEND_EVENT_STATE),
  621. args=tuple(
  622. (
  623. Var(_js_expr=k),
  624. LiteralVar.create(v),
  625. )
  626. for k, v in kwargs.items()
  627. ),
  628. )
  629. def redirect(
  630. path: str | Var[str],
  631. is_external: bool = False,
  632. replace: bool = False,
  633. ) -> EventSpec:
  634. """Redirect to a new path.
  635. Args:
  636. path: The path to redirect to.
  637. is_external: Whether to open in new tab or not.
  638. replace: If True, the current page will not create a new history entry.
  639. Returns:
  640. An event to redirect to the path.
  641. """
  642. return server_side(
  643. "_redirect",
  644. get_fn_signature(redirect),
  645. path=path,
  646. external=is_external,
  647. replace=replace,
  648. )
  649. def console_log(message: str | Var[str]) -> EventSpec:
  650. """Do a console.log on the browser.
  651. Args:
  652. message: The message to log.
  653. Returns:
  654. An event to log the message.
  655. """
  656. return run_script(Var("console").to(dict).log.to(FunctionVar).call(message))
  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 = inspect.getfullargspec(event_callback.fn)
  1010. for event_spec_index, event_spec_return_type in enumerate(
  1011. event_spec_return_types
  1012. ):
  1013. args = get_args(event_spec_return_type)
  1014. args_types_without_vars = [
  1015. arg if get_origin(arg) is not Var else get_args(arg)[0] for arg in args
  1016. ]
  1017. # check that args of event handler are matching the spec if type hints are provided
  1018. for i, arg in enumerate(
  1019. event_callback_spec.args[1 : len(args_types_without_vars) + 1]
  1020. ):
  1021. if arg not in type_hints_of_provided_callback:
  1022. continue
  1023. type_match_found.setdefault(arg, False)
  1024. try:
  1025. compare_result = typehint_issubclass(
  1026. args_types_without_vars[i], type_hints_of_provided_callback[arg]
  1027. )
  1028. except TypeError as te:
  1029. raise TypeError(
  1030. 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}."
  1031. ) from te
  1032. if compare_result:
  1033. type_match_found[arg] = True
  1034. continue
  1035. else:
  1036. type_match_found[arg] = False
  1037. delayed_exceptions.append(
  1038. EventHandlerArgTypeMismatchError(
  1039. 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."
  1040. )
  1041. )
  1042. if all(type_match_found.values()):
  1043. delayed_exceptions.clear()
  1044. if event_spec_index:
  1045. args = get_args(event_spec_return_types[0])
  1046. args_types_without_vars = [
  1047. arg if get_origin(arg) is not Var else get_args(arg)[0]
  1048. for arg in args
  1049. ]
  1050. expect_string = ", ".join(
  1051. repr(arg) for arg in args_types_without_vars
  1052. ).replace("[", "\\[")
  1053. given_string = ", ".join(
  1054. repr(type_hints_of_provided_callback.get(arg, Any))
  1055. for arg in event_callback_spec.args[1:]
  1056. ).replace("[", "\\[")
  1057. console.warn(
  1058. f"Event handler {key} expects ({expect_string}) -> () but got ({given_string}) -> () as annotated in {event_callback.fn.__qualname__} instead. "
  1059. f"This may lead to unexpected behavior but is intentionally ignored for {key}."
  1060. )
  1061. break
  1062. if delayed_exceptions:
  1063. raise delayed_exceptions[0]
  1064. return event_callback(*event_spec_args)
  1065. def unwrap_var_annotation(annotation: GenericType):
  1066. """Unwrap a Var annotation or return it as is if it's not Var[X].
  1067. Args:
  1068. annotation: The annotation to unwrap.
  1069. Returns:
  1070. The unwrapped annotation.
  1071. """
  1072. if get_origin(annotation) in (Var, ObjectVar) and (args := get_args(annotation)):
  1073. return args[0]
  1074. return annotation
  1075. def resolve_annotation(annotations: dict[str, Any], arg_name: str, spec: ArgsSpec):
  1076. """Resolve the annotation for the given argument name.
  1077. Args:
  1078. annotations: The annotations.
  1079. arg_name: The argument name.
  1080. spec: The specs which the annotations come from.
  1081. Raises:
  1082. MissingAnnotationError: If the annotation is missing for non-lambda methods.
  1083. Returns:
  1084. The resolved annotation.
  1085. """
  1086. annotation = annotations.get(arg_name)
  1087. if annotation is None:
  1088. if not isinstance(spec, types.LambdaType):
  1089. raise MissingAnnotationError(var_name=arg_name)
  1090. else:
  1091. return dict[str, dict]
  1092. return annotation
  1093. def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]):
  1094. """Parse the args provided in the ArgsSpec of an event trigger.
  1095. Args:
  1096. arg_spec: The spec of the args.
  1097. Returns:
  1098. The parsed args.
  1099. """
  1100. # if there's multiple, the first is the default
  1101. arg_spec = arg_spec[0] if isinstance(arg_spec, Sequence) else arg_spec
  1102. spec = inspect.getfullargspec(arg_spec)
  1103. annotations = get_type_hints(arg_spec)
  1104. return list(
  1105. arg_spec(
  1106. *[
  1107. Var(f"_{l_arg}").to(
  1108. unwrap_var_annotation(
  1109. resolve_annotation(
  1110. annotations,
  1111. l_arg,
  1112. spec=arg_spec,
  1113. )
  1114. )
  1115. )
  1116. for l_arg in spec.args
  1117. ]
  1118. )
  1119. )
  1120. def check_fn_match_arg_spec(
  1121. user_func: Callable,
  1122. arg_spec: ArgsSpec | Sequence[ArgsSpec],
  1123. key: str | None = None,
  1124. number_of_bound_args: int = 0,
  1125. func_name: str | None = None,
  1126. ):
  1127. """Ensures that the function signature matches the passed argument specification
  1128. or raises an EventFnArgMismatchError if they do not.
  1129. Args:
  1130. user_func: The function to be validated.
  1131. arg_spec: The argument specification for the event trigger.
  1132. key: The key of the event trigger.
  1133. number_of_bound_args: The number of bound arguments to the function.
  1134. func_name: The name of the function to be validated.
  1135. Raises:
  1136. EventFnArgMismatchError: Raised if the number of mandatory arguments do not match
  1137. """
  1138. user_args = inspect.getfullargspec(user_func).args
  1139. # Drop the first argument if it's a bound method
  1140. if inspect.ismethod(user_func) and user_func.__self__ is not None:
  1141. user_args = user_args[1:]
  1142. user_default_args = inspect.getfullargspec(user_func).defaults
  1143. number_of_user_args = len(user_args) - number_of_bound_args
  1144. number_of_user_default_args = len(user_default_args) if user_default_args else 0
  1145. parsed_event_args = parse_args_spec(arg_spec)
  1146. number_of_event_args = len(parsed_event_args)
  1147. if number_of_user_args - number_of_user_default_args > number_of_event_args:
  1148. raise EventFnArgMismatchError(
  1149. f"Event {key} only provides {number_of_event_args} arguments, but "
  1150. f"{func_name or user_func} requires at least {number_of_user_args - number_of_user_default_args} "
  1151. "arguments to be passed to the event handler.\n"
  1152. "See https://reflex.dev/docs/events/event-arguments/"
  1153. )
  1154. def call_event_fn(
  1155. fn: Callable,
  1156. arg_spec: ArgsSpec | Sequence[ArgsSpec],
  1157. key: str | None = None,
  1158. ) -> list[EventSpec] | Var:
  1159. """Call a function to a list of event specs.
  1160. The function should return a single EventSpec, a list of EventSpecs, or a
  1161. single Var.
  1162. Args:
  1163. fn: The function to call.
  1164. arg_spec: The argument spec for the event trigger.
  1165. key: The key to pass to the event handler.
  1166. Returns:
  1167. The event specs from calling the function or a Var.
  1168. Raises:
  1169. EventHandlerValueError: If the lambda returns an unusable value.
  1170. """
  1171. # Import here to avoid circular imports.
  1172. from reflex.event import EventHandler, EventSpec
  1173. from reflex.utils.exceptions import EventHandlerValueError
  1174. # Check that fn signature matches arg_spec
  1175. check_fn_match_arg_spec(fn, arg_spec, key=key)
  1176. parsed_args = parse_args_spec(arg_spec)
  1177. number_of_fn_args = len(inspect.getfullargspec(fn).args)
  1178. # Call the function with the parsed args.
  1179. out = fn(*[*parsed_args][:number_of_fn_args])
  1180. # If the function returns a Var, assume it's an EventChain and render it directly.
  1181. if isinstance(out, Var):
  1182. return out
  1183. # Convert the output to a list.
  1184. if not isinstance(out, list):
  1185. out = [out]
  1186. # Convert any event specs to event specs.
  1187. events = []
  1188. for e in out:
  1189. if isinstance(e, EventHandler):
  1190. # An un-called EventHandler gets all of the args of the event trigger.
  1191. e = call_event_handler(e, arg_spec, key=key)
  1192. # Make sure the event spec is valid.
  1193. if not isinstance(e, EventSpec):
  1194. raise EventHandlerValueError(
  1195. f"Lambda {fn} returned an invalid event spec: {e}."
  1196. )
  1197. # Add the event spec to the chain.
  1198. events.append(e)
  1199. # Return the events.
  1200. return events
  1201. def get_handler_args(
  1202. event_spec: EventSpec,
  1203. ) -> tuple[tuple[Var, Var], ...]:
  1204. """Get the handler args for the given event spec.
  1205. Args:
  1206. event_spec: The event spec.
  1207. Returns:
  1208. The handler args.
  1209. """
  1210. args = inspect.getfullargspec(event_spec.handler.fn).args
  1211. return event_spec.args if len(args) > 1 else ()
  1212. def fix_events(
  1213. events: list[EventSpec | EventHandler] | None,
  1214. token: str,
  1215. router_data: dict[str, Any] | None = None,
  1216. ) -> list[Event]:
  1217. """Fix a list of events returned by an event handler.
  1218. Args:
  1219. events: The events to fix.
  1220. token: The user token.
  1221. router_data: The optional router data to set in the event.
  1222. Raises:
  1223. ValueError: If the event type is not what was expected.
  1224. Returns:
  1225. The fixed events.
  1226. """
  1227. # If the event handler returns nothing, return an empty list.
  1228. if events is None:
  1229. return []
  1230. # If the handler returns a single event, wrap it in a list.
  1231. if not isinstance(events, List):
  1232. events = [events]
  1233. # Fix the events created by the handler.
  1234. out = []
  1235. for e in events:
  1236. if isinstance(e, Event):
  1237. # If the event is already an event, append it to the list.
  1238. out.append(e)
  1239. continue
  1240. if not isinstance(e, (EventHandler, EventSpec)):
  1241. e = EventHandler(fn=e)
  1242. # Otherwise, create an event from the event spec.
  1243. if isinstance(e, EventHandler):
  1244. e = e()
  1245. if not isinstance(e, EventSpec):
  1246. raise ValueError(f"Unexpected event type, {type(e)}.")
  1247. name = format.format_event_handler(e.handler)
  1248. payload = {k._js_expr: v._decode() for k, v in e.args}
  1249. # Filter router_data to reduce payload size
  1250. event_router_data = {
  1251. k: v
  1252. for k, v in (router_data or {}).items()
  1253. if k in constants.route.ROUTER_DATA_INCLUDE
  1254. }
  1255. # Create an event and append it to the list.
  1256. out.append(
  1257. Event(
  1258. token=token,
  1259. name=name,
  1260. payload=payload,
  1261. router_data=event_router_data,
  1262. )
  1263. )
  1264. return out
  1265. def get_fn_signature(fn: Callable) -> inspect.Signature:
  1266. """Get the signature of a function.
  1267. Args:
  1268. fn: The function.
  1269. Returns:
  1270. The signature of the function.
  1271. """
  1272. signature = inspect.signature(fn)
  1273. new_param = inspect.Parameter(
  1274. FRONTEND_EVENT_STATE, inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  1275. )
  1276. return signature.replace(parameters=(new_param, *signature.parameters.values()))
  1277. class EventVar(ObjectVar, python_types=EventSpec):
  1278. """Base class for event vars."""
  1279. @dataclasses.dataclass(
  1280. eq=False,
  1281. frozen=True,
  1282. slots=True,
  1283. )
  1284. class LiteralEventVar(VarOperationCall, LiteralVar, EventVar):
  1285. """A literal event var."""
  1286. _var_value: EventSpec = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType]
  1287. def __hash__(self) -> int:
  1288. """Get the hash of the var.
  1289. Returns:
  1290. The hash of the var.
  1291. """
  1292. return hash((type(self).__name__, self._js_expr))
  1293. @classmethod
  1294. def create(
  1295. cls,
  1296. value: EventSpec,
  1297. _var_data: VarData | None = None,
  1298. ) -> LiteralEventVar:
  1299. """Create a new LiteralEventVar instance.
  1300. Args:
  1301. value: The value of the var.
  1302. _var_data: The data of the var.
  1303. Returns:
  1304. The created LiteralEventVar instance.
  1305. """
  1306. return cls(
  1307. _js_expr="",
  1308. _var_type=EventSpec,
  1309. _var_data=_var_data,
  1310. _var_value=value,
  1311. _func=FunctionStringVar("Event"),
  1312. _args=(
  1313. # event handler name
  1314. ".".join(
  1315. filter(
  1316. None,
  1317. format.get_event_handler_parts(value.handler),
  1318. )
  1319. ),
  1320. # event handler args
  1321. {str(name): value for name, value in value.args},
  1322. # event actions
  1323. value.event_actions,
  1324. # client handler name
  1325. *([value.client_handler_name] if value.client_handler_name else []),
  1326. ),
  1327. )
  1328. class EventChainVar(BuilderFunctionVar, python_types=EventChain):
  1329. """Base class for event chain vars."""
  1330. @dataclasses.dataclass(
  1331. eq=False,
  1332. frozen=True,
  1333. slots=True,
  1334. )
  1335. # Note: LiteralVar is second in the inheritance list allowing it act like a
  1336. # CachedVarOperation (ArgsFunctionOperation) and get the _js_expr from the
  1337. # _cached_var_name property.
  1338. class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainVar):
  1339. """A literal event chain var."""
  1340. _var_value: EventChain = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType]
  1341. def __hash__(self) -> int:
  1342. """Get the hash of the var.
  1343. Returns:
  1344. The hash of the var.
  1345. """
  1346. return hash((type(self).__name__, self._js_expr))
  1347. @classmethod
  1348. def create(
  1349. cls,
  1350. value: EventChain,
  1351. _var_data: VarData | None = None,
  1352. ) -> LiteralEventChainVar:
  1353. """Create a new LiteralEventChainVar instance.
  1354. Args:
  1355. value: The value of the var.
  1356. _var_data: The data of the var.
  1357. Returns:
  1358. The created LiteralEventChainVar instance.
  1359. Raises:
  1360. ValueError: If the invocation is not a FunctionVar.
  1361. """
  1362. arg_spec = (
  1363. value.args_spec[0]
  1364. if isinstance(value.args_spec, Sequence)
  1365. else value.args_spec
  1366. )
  1367. sig = inspect.signature(arg_spec) # pyright: ignore [reportArgumentType]
  1368. if sig.parameters:
  1369. arg_def = tuple((f"_{p}" for p in sig.parameters))
  1370. arg_def_expr = LiteralVar.create([Var(_js_expr=arg) for arg in arg_def])
  1371. else:
  1372. # add a default argument for addEvents if none were specified in value.args_spec
  1373. # used to trigger the preventDefault() on the event.
  1374. arg_def = ("...args",)
  1375. arg_def_expr = Var(_js_expr="args")
  1376. if value.invocation is None:
  1377. invocation = FunctionStringVar.create(
  1378. CompileVars.ADD_EVENTS,
  1379. _var_data=VarData(
  1380. imports=Imports.EVENTS,
  1381. hooks={Hooks.EVENTS: None},
  1382. ),
  1383. )
  1384. else:
  1385. invocation = value.invocation
  1386. if invocation is not None and not isinstance(invocation, FunctionVar):
  1387. raise ValueError(
  1388. f"EventChain invocation must be a FunctionVar, got {invocation!s} of type {invocation._var_type!s}."
  1389. )
  1390. return cls(
  1391. _js_expr="",
  1392. _var_type=EventChain,
  1393. _var_data=_var_data,
  1394. _args=FunctionArgs(arg_def),
  1395. _return_expr=invocation.call(
  1396. LiteralVar.create([LiteralVar.create(event) for event in value.events]),
  1397. arg_def_expr,
  1398. value.event_actions,
  1399. ),
  1400. _var_value=value,
  1401. )
  1402. P = TypeVarTuple("P")
  1403. Q = TypeVarTuple("Q")
  1404. T = TypeVar("T")
  1405. V = TypeVar("V")
  1406. V2 = TypeVar("V2")
  1407. V3 = TypeVar("V3")
  1408. V4 = TypeVar("V4")
  1409. V5 = TypeVar("V5")
  1410. class EventCallback(Generic[Unpack[P]], EventActionsMixin):
  1411. """A descriptor that wraps a function to be used as an event."""
  1412. def __init__(self, func: Callable[[Any, Unpack[P]], Any]):
  1413. """Initialize the descriptor with the function to be wrapped.
  1414. Args:
  1415. func: The function to be wrapped.
  1416. """
  1417. self.func = func
  1418. @overload
  1419. def __call__(
  1420. self: EventCallback[Unpack[Q]],
  1421. ) -> EventCallback[Unpack[Q]]: ...
  1422. @overload
  1423. def __call__(
  1424. self: EventCallback[V, Unpack[Q]], value: V | Var[V]
  1425. ) -> EventCallback[Unpack[Q]]: ...
  1426. @overload
  1427. def __call__(
  1428. self: EventCallback[V, V2, Unpack[Q]],
  1429. value: V | Var[V],
  1430. value2: V2 | Var[V2],
  1431. ) -> EventCallback[Unpack[Q]]: ...
  1432. @overload
  1433. def __call__(
  1434. self: EventCallback[V, V2, V3, Unpack[Q]],
  1435. value: V | Var[V],
  1436. value2: V2 | Var[V2],
  1437. value3: V3 | Var[V3],
  1438. ) -> EventCallback[Unpack[Q]]: ...
  1439. @overload
  1440. def __call__(
  1441. self: EventCallback[V, V2, V3, V4, Unpack[Q]],
  1442. value: V | Var[V],
  1443. value2: V2 | Var[V2],
  1444. value3: V3 | Var[V3],
  1445. value4: V4 | Var[V4],
  1446. ) -> EventCallback[Unpack[Q]]: ...
  1447. def __call__(self, *values) -> EventCallback: # pyright: ignore [reportInconsistentOverload]
  1448. """Call the function with the values.
  1449. Args:
  1450. *values: The values to call the function with.
  1451. Returns:
  1452. The function with the values.
  1453. """
  1454. return self.func(*values) # pyright: ignore [reportArgumentType]
  1455. @overload
  1456. def __get__(
  1457. self: EventCallback[Unpack[P]], instance: None, owner: Any
  1458. ) -> EventCallback[Unpack[P]]: ...
  1459. @overload
  1460. def __get__(self, instance: Any, owner: Any) -> Callable[[Unpack[P]]]: ...
  1461. def __get__(self, instance: Any, owner: Any) -> Callable:
  1462. """Get the function with the instance bound to it.
  1463. Args:
  1464. instance: The instance to bind to the function.
  1465. owner: The owner of the function.
  1466. Returns:
  1467. The function with the instance bound to it
  1468. """
  1469. if instance is None:
  1470. return self.func
  1471. return partial(self.func, instance)
  1472. class LambdaEventCallback(Protocol[Unpack[P]]):
  1473. """A protocol for a lambda event callback."""
  1474. @overload
  1475. def __call__(self: LambdaEventCallback[()]) -> Any: ...
  1476. @overload
  1477. def __call__(self: LambdaEventCallback[V], value: Var[V], /) -> Any: ...
  1478. @overload
  1479. def __call__(
  1480. self: LambdaEventCallback[V, V2], value: Var[V], value2: Var[V2], /
  1481. ) -> Any: ...
  1482. @overload
  1483. def __call__(
  1484. self: LambdaEventCallback[V, V2, V3],
  1485. value: Var[V],
  1486. value2: Var[V2],
  1487. value3: Var[V3],
  1488. /,
  1489. ) -> Any: ...
  1490. def __call__(self, *args: Var) -> Any:
  1491. """Call the lambda with the args.
  1492. Args:
  1493. *args: The args to call the lambda with.
  1494. """
  1495. ARGS = TypeVarTuple("ARGS")
  1496. LAMBDA_OR_STATE = TypeAliasType(
  1497. "LAMBDA_OR_STATE",
  1498. LambdaEventCallback[Unpack[ARGS]] | EventCallback[Unpack[ARGS]],
  1499. type_params=(ARGS,),
  1500. )
  1501. ItemOrList = V | list[V]
  1502. BASIC_EVENT_TYPES = TypeAliasType(
  1503. "BASIC_EVENT_TYPES", EventSpec | EventHandler | Var[Any], type_params=()
  1504. )
  1505. IndividualEventType = TypeAliasType(
  1506. "IndividualEventType",
  1507. LAMBDA_OR_STATE[Unpack[ARGS]] | BASIC_EVENT_TYPES,
  1508. type_params=(ARGS,),
  1509. )
  1510. EventType = TypeAliasType(
  1511. "EventType", ItemOrList[IndividualEventType[Unpack[ARGS]]], type_params=(ARGS,)
  1512. )
  1513. if TYPE_CHECKING:
  1514. from reflex.state import BaseState
  1515. BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
  1516. else:
  1517. BASE_STATE = TypeVar("BASE_STATE")
  1518. class EventNamespace(types.SimpleNamespace):
  1519. """A namespace for event related classes."""
  1520. Event = Event
  1521. EventHandler = EventHandler
  1522. EventSpec = EventSpec
  1523. CallableEventSpec = CallableEventSpec
  1524. EventChain = EventChain
  1525. EventVar = EventVar
  1526. LiteralEventVar = LiteralEventVar
  1527. EventChainVar = EventChainVar
  1528. LiteralEventChainVar = LiteralEventChainVar
  1529. EventType = EventType
  1530. EventCallback = EventCallback
  1531. @overload
  1532. @staticmethod
  1533. def __call__(
  1534. func: None = None, *, background: bool | None = None
  1535. ) -> Callable[
  1536. [Callable[[BASE_STATE, Unpack[P]], Any]], EventCallback[Unpack[P]] # pyright: ignore [reportInvalidTypeVarUse]
  1537. ]: ...
  1538. @overload
  1539. @staticmethod
  1540. def __call__(
  1541. func: Callable[[BASE_STATE, Unpack[P]], Any],
  1542. *,
  1543. background: bool | None = None,
  1544. ) -> EventCallback[Unpack[P]]: ...
  1545. @staticmethod
  1546. def __call__(
  1547. func: Callable[[BASE_STATE, Unpack[P]], Any] | None = None,
  1548. *,
  1549. background: bool | None = None,
  1550. ) -> (
  1551. EventCallback[Unpack[P]]
  1552. | Callable[[Callable[[BASE_STATE, Unpack[P]], Any]], EventCallback[Unpack[P]]]
  1553. ):
  1554. """Wrap a function to be used as an event.
  1555. Args:
  1556. func: The function to wrap.
  1557. background: Whether the event should be run in the background. Defaults to False.
  1558. Raises:
  1559. TypeError: If background is True and the function is not a coroutine or async generator. # noqa: DAR402
  1560. Returns:
  1561. The wrapped function.
  1562. """
  1563. def wrapper(
  1564. func: Callable[[BASE_STATE, Unpack[P]], T],
  1565. ) -> EventCallback[Unpack[P]]:
  1566. if background is True:
  1567. if not inspect.iscoroutinefunction(
  1568. func
  1569. ) and not inspect.isasyncgenfunction(func):
  1570. raise TypeError(
  1571. "Background task must be async function or generator."
  1572. )
  1573. setattr(func, BACKGROUND_TASK_MARKER, True)
  1574. return func # pyright: ignore [reportReturnType]
  1575. if func is not None:
  1576. return wrapper(func)
  1577. return wrapper
  1578. get_event = staticmethod(get_event)
  1579. get_hydrate_event = staticmethod(get_hydrate_event)
  1580. fix_events = staticmethod(fix_events)
  1581. call_event_handler = staticmethod(call_event_handler)
  1582. call_event_fn = staticmethod(call_event_fn)
  1583. get_handler_args = staticmethod(get_handler_args)
  1584. check_fn_match_arg_spec = staticmethod(check_fn_match_arg_spec)
  1585. resolve_annotation = staticmethod(resolve_annotation)
  1586. parse_args_spec = staticmethod(parse_args_spec)
  1587. passthrough_event_spec = staticmethod(passthrough_event_spec)
  1588. input_event = staticmethod(input_event)
  1589. key_event = staticmethod(key_event)
  1590. no_args_event_spec = staticmethod(no_args_event_spec)
  1591. server_side = staticmethod(server_side)
  1592. redirect = staticmethod(redirect)
  1593. console_log = staticmethod(console_log)
  1594. noop = staticmethod(noop)
  1595. back = staticmethod(back)
  1596. window_alert = staticmethod(window_alert)
  1597. set_focus = staticmethod(set_focus)
  1598. scroll_to = staticmethod(scroll_to)
  1599. set_value = staticmethod(set_value)
  1600. remove_cookie = staticmethod(remove_cookie)
  1601. clear_local_storage = staticmethod(clear_local_storage)
  1602. remove_local_storage = staticmethod(remove_local_storage)
  1603. clear_session_storage = staticmethod(clear_session_storage)
  1604. remove_session_storage = staticmethod(remove_session_storage)
  1605. set_clipboard = staticmethod(set_clipboard)
  1606. download = staticmethod(download)
  1607. call_script = staticmethod(call_script)
  1608. call_function = staticmethod(call_function)
  1609. run_script = staticmethod(run_script)
  1610. event = EventNamespace()