event.py 55 KB

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