1
0

event.py 54 KB

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