1
0

event.py 59 KB

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