event.py 54 KB

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