event.py 46 KB

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