event.py 56 KB

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