event.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. """Define event classes to connect the frontend and backend."""
  2. from __future__ import annotations
  3. import inspect
  4. from types import FunctionType
  5. from typing import (
  6. TYPE_CHECKING,
  7. Any,
  8. Callable,
  9. Dict,
  10. List,
  11. Optional,
  12. Tuple,
  13. Type,
  14. Union,
  15. )
  16. from reflex import constants
  17. from reflex.base import Base
  18. from reflex.utils import console, format
  19. from reflex.utils.types import ArgsSpec
  20. from reflex.vars import BaseVar, Var
  21. if TYPE_CHECKING:
  22. from reflex.state import State
  23. class Event(Base):
  24. """An event that describes any state change in the app."""
  25. # The token to specify the client that the event is for.
  26. token: str
  27. # The event name.
  28. name: str
  29. # The routing data where event occurred
  30. router_data: Dict[str, Any] = {}
  31. # The event payload.
  32. payload: Dict[str, Any] = {}
  33. BACKGROUND_TASK_MARKER = "_reflex_background_task"
  34. def background(fn):
  35. """Decorator to mark event handler as running in the background.
  36. Args:
  37. fn: The function to decorate.
  38. Returns:
  39. The same function, but with a marker set.
  40. Raises:
  41. TypeError: If the function is not a coroutine function or async generator.
  42. """
  43. if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
  44. raise TypeError("Background task must be async function or generator.")
  45. setattr(fn, BACKGROUND_TASK_MARKER, True)
  46. return fn
  47. def _no_chain_background_task(
  48. state_cls: Type["State"], name: str, fn: Callable
  49. ) -> Callable:
  50. """Protect against directly chaining a background task from another event handler.
  51. Args:
  52. state_cls: The state class that the event handler is in.
  53. name: The name of the background task.
  54. fn: The background task coroutine function / generator.
  55. Returns:
  56. A compatible coroutine function / generator that raises a runtime error.
  57. Raises:
  58. TypeError: If the background task is not async.
  59. """
  60. call = f"{state_cls.__name__}.{name}"
  61. message = (
  62. f"Cannot directly call background task {name!r}, use "
  63. f"`yield {call}` or `return {call}` instead."
  64. )
  65. if inspect.iscoroutinefunction(fn):
  66. async def _no_chain_background_task_co(*args, **kwargs):
  67. raise RuntimeError(message)
  68. return _no_chain_background_task_co
  69. if inspect.isasyncgenfunction(fn):
  70. async def _no_chain_background_task_gen(*args, **kwargs):
  71. yield
  72. raise RuntimeError(message)
  73. return _no_chain_background_task_gen
  74. raise TypeError(f"{fn} is marked as a background task, but is not async.")
  75. class EventHandler(Base):
  76. """An event handler responds to an event to update the state."""
  77. # The function to call in response to the event.
  78. fn: Any
  79. class Config:
  80. """The Pydantic config."""
  81. # Needed to allow serialization of Callable.
  82. frozen = True
  83. @property
  84. def is_background(self) -> bool:
  85. """Whether the event handler is a background task.
  86. Returns:
  87. True if the event handler is marked as a background task.
  88. """
  89. return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
  90. def __call__(self, *args: Var) -> EventSpec:
  91. """Pass arguments to the handler to get an event spec.
  92. This method configures event handlers that take in arguments.
  93. Args:
  94. *args: The arguments to pass to the handler.
  95. Returns:
  96. The event spec, containing both the function and args.
  97. Raises:
  98. TypeError: If the arguments are invalid.
  99. """
  100. # Get the function args.
  101. fn_args = inspect.getfullargspec(self.fn).args[1:]
  102. fn_args = (Var.create_safe(arg) for arg in fn_args)
  103. # Construct the payload.
  104. values = []
  105. for arg in args:
  106. # Special case for file uploads.
  107. if isinstance(arg, FileUpload):
  108. return EventSpec(
  109. handler=self,
  110. client_handler_name="uploadFiles",
  111. # `files` is defined in the Upload component's _use_hooks
  112. args=((Var.create_safe("files"), Var.create_safe("files")),),
  113. )
  114. # Otherwise, convert to JSON.
  115. try:
  116. values.append(Var.create(arg, _var_is_string=type(arg) is str))
  117. except TypeError as e:
  118. raise TypeError(
  119. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  120. ) from e
  121. payload = tuple(zip(fn_args, values))
  122. # Return the event spec.
  123. return EventSpec(handler=self, args=payload)
  124. class EventSpec(Base):
  125. """An event specification.
  126. Whereas an Event object is passed during runtime, a spec is used
  127. during compile time to outline the structure of an event.
  128. """
  129. # The event handler.
  130. handler: EventHandler
  131. # The handler on the client to process event.
  132. client_handler_name: str = ""
  133. # The arguments to pass to the function.
  134. args: Tuple[Tuple[Var, Var], ...] = ()
  135. class Config:
  136. """The Pydantic config."""
  137. # Required to allow tuple fields.
  138. frozen = True
  139. class EventChain(Base):
  140. """Container for a chain of events that will be executed in order."""
  141. events: List[EventSpec]
  142. args_spec: Optional[Callable]
  143. class Target(Base):
  144. """A Javascript event target."""
  145. checked: bool = False
  146. value: Any = None
  147. class FrontendEvent(Base):
  148. """A Javascript event."""
  149. target: Target = Target()
  150. key: str = ""
  151. value: Any = None
  152. class FileUpload(Base):
  153. """Class to represent a file upload."""
  154. pass
  155. # Special server-side events.
  156. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  157. """A server-side event.
  158. Args:
  159. name: The name of the event.
  160. sig: The function signature of the event.
  161. **kwargs: The arguments to pass to the event.
  162. Returns:
  163. An event spec for a server-side event.
  164. """
  165. def fn():
  166. return None
  167. fn.__qualname__ = name
  168. fn.__signature__ = sig
  169. return EventSpec(
  170. handler=EventHandler(fn=fn),
  171. args=tuple(
  172. (Var.create_safe(k), Var.create_safe(v, _var_is_string=type(v) is str))
  173. for k, v in kwargs.items()
  174. ),
  175. )
  176. def redirect(path: str | Var[str], external: Optional[bool] = False) -> EventSpec:
  177. """Redirect to a new path.
  178. Args:
  179. path: The path to redirect to.
  180. external: Whether to open in new tab or not.
  181. Returns:
  182. An event to redirect to the path.
  183. """
  184. return server_side(
  185. "_redirect", get_fn_signature(redirect), path=path, external=external
  186. )
  187. def console_log(message: str | Var[str]) -> EventSpec:
  188. """Do a console.log on the browser.
  189. Args:
  190. message: The message to log.
  191. Returns:
  192. An event to log the message.
  193. """
  194. return server_side("_console", get_fn_signature(console_log), message=message)
  195. def window_alert(message: str | Var[str]) -> EventSpec:
  196. """Create a window alert on the browser.
  197. Args:
  198. message: The message to alert.
  199. Returns:
  200. An event to alert the message.
  201. """
  202. return server_side("_alert", get_fn_signature(window_alert), message=message)
  203. def set_focus(ref: str) -> EventSpec:
  204. """Set focus to specified ref.
  205. Args:
  206. ref: The ref.
  207. Returns:
  208. An event to set focus on the ref
  209. """
  210. return server_side(
  211. "_set_focus",
  212. get_fn_signature(set_focus),
  213. ref=Var.create_safe(format.format_ref(ref)),
  214. )
  215. def set_value(ref: str, value: Any) -> EventSpec:
  216. """Set the value of a ref.
  217. Args:
  218. ref: The ref.
  219. value: The value to set.
  220. Returns:
  221. An event to set the ref.
  222. """
  223. return server_side(
  224. "_set_value",
  225. get_fn_signature(set_value),
  226. ref=Var.create_safe(format.format_ref(ref)),
  227. value=value,
  228. )
  229. def remove_cookie(key: str, options: dict[str, Any] | None = None) -> EventSpec:
  230. """Remove a cookie on the frontend.
  231. Args:
  232. key: The key identifying the cookie to be removed.
  233. options: Support all the cookie options from RFC 6265
  234. Returns:
  235. EventSpec: An event to remove a cookie.
  236. """
  237. options = options or {}
  238. options["path"] = options.get("path", "/")
  239. return server_side(
  240. "_remove_cookie",
  241. get_fn_signature(remove_cookie),
  242. key=key,
  243. options=options,
  244. )
  245. def clear_local_storage() -> EventSpec:
  246. """Set a value in the local storage on the frontend.
  247. Returns:
  248. EventSpec: An event to clear the local storage.
  249. """
  250. return server_side(
  251. "_clear_local_storage",
  252. get_fn_signature(clear_local_storage),
  253. )
  254. def remove_local_storage(key: str) -> EventSpec:
  255. """Set a value in the local storage on the frontend.
  256. Args:
  257. key: The key identifying the variable in the local storage to remove.
  258. Returns:
  259. EventSpec: An event to remove an item based on the provided key in local storage.
  260. """
  261. return server_side(
  262. "_remove_local_storage",
  263. get_fn_signature(remove_local_storage),
  264. key=key,
  265. )
  266. def set_clipboard(content: str) -> EventSpec:
  267. """Set the text in content in the clipboard.
  268. Args:
  269. content: The text to add to clipboard.
  270. Returns:
  271. EventSpec: An event to set some content in the clipboard.
  272. """
  273. return server_side(
  274. "_set_clipboard",
  275. get_fn_signature(set_clipboard),
  276. content=content,
  277. )
  278. def download(url: str, filename: Optional[str] = None) -> EventSpec:
  279. """Download the file at a given path.
  280. Args:
  281. url : The URL to the file to download.
  282. filename : The name that the file should be saved as after download.
  283. Raises:
  284. ValueError: If the URL provided is invalid.
  285. Returns:
  286. EventSpec: An event to download the associated file.
  287. """
  288. if not url.startswith("/"):
  289. raise ValueError("The URL argument should start with a /")
  290. # if filename is not provided, infer it from url
  291. if filename is None:
  292. filename = url.rpartition("/")[-1]
  293. return server_side(
  294. "_download",
  295. get_fn_signature(download),
  296. url=url,
  297. filename=filename,
  298. )
  299. def _callback_arg_spec(eval_result):
  300. """ArgSpec for call_script callback function.
  301. Args:
  302. eval_result: The result of the javascript execution.
  303. Returns:
  304. Args for the callback function
  305. """
  306. return [eval_result]
  307. def call_script(
  308. javascript_code: str,
  309. callback: EventHandler | Callable | None = None,
  310. ) -> EventSpec:
  311. """Create an event handler that executes arbitrary javascript code.
  312. Args:
  313. javascript_code: The code to execute.
  314. callback: EventHandler that will receive the result of evaluating the javascript code.
  315. Returns:
  316. EventSpec: An event that will execute the client side javascript.
  317. Raises:
  318. ValueError: If the callback is not a valid event handler.
  319. """
  320. callback_kwargs = {}
  321. if callback is not None:
  322. arg_name = parse_args_spec(_callback_arg_spec)[0]._var_name
  323. if isinstance(callback, EventHandler):
  324. event_spec = call_event_handler(callback, _callback_arg_spec)
  325. elif isinstance(callback, FunctionType):
  326. event_spec = call_event_fn(callback, _callback_arg_spec)[0]
  327. else:
  328. raise ValueError("Cannot use {callback!r} as a call_script callback.")
  329. callback_kwargs = {
  330. "callback": f"({arg_name}) => queueEvents([{format.format_event(event_spec)}], {constants.CompileVars.SOCKET})"
  331. }
  332. return server_side(
  333. "_call_script",
  334. get_fn_signature(call_script),
  335. javascript_code=javascript_code,
  336. **callback_kwargs,
  337. )
  338. def get_event(state, event):
  339. """Get the event from the given state.
  340. Args:
  341. state: The state.
  342. event: The event.
  343. Returns:
  344. The event.
  345. """
  346. return f"{state.get_name()}.{event}"
  347. def get_hydrate_event(state) -> str:
  348. """Get the name of the hydrate event for the state.
  349. Args:
  350. state: The state.
  351. Returns:
  352. The name of the hydrate event.
  353. """
  354. return get_event(state, constants.CompileVars.HYDRATE)
  355. def call_event_handler(
  356. event_handler: EventHandler, arg_spec: Union[Var, ArgsSpec]
  357. ) -> EventSpec:
  358. """Call an event handler to get the event spec.
  359. This function will inspect the function signature of the event handler.
  360. If it takes in an arg, the arg will be passed to the event handler.
  361. Otherwise, the event handler will be called with no args.
  362. Args:
  363. event_handler: The event handler.
  364. arg_spec: The lambda that define the argument(s) to pass to the event handler.
  365. Raises:
  366. ValueError: if number of arguments expected by event_handler doesn't match the spec.
  367. Returns:
  368. The event spec from calling the event handler.
  369. """
  370. args = inspect.getfullargspec(event_handler.fn).args
  371. # handle new API using lambda to define triggers
  372. if isinstance(arg_spec, ArgsSpec):
  373. parsed_args = parse_args_spec(arg_spec) # type: ignore
  374. if len(args) == len(["self", *parsed_args]):
  375. return event_handler(*parsed_args) # type: ignore
  376. else:
  377. source = inspect.getsource(arg_spec) # type: ignore
  378. raise ValueError(
  379. f"number of arguments in {event_handler.fn.__qualname__} "
  380. f"doesn't match the definition of the event trigger '{source.strip().strip(',')}'"
  381. )
  382. else:
  383. console.deprecate(
  384. feature_name="EVENT_ARG API for triggers",
  385. reason="Replaced by new API using lambda allow arbitrary number of args",
  386. deprecation_version="0.2.8",
  387. removal_version="0.3.0",
  388. )
  389. if len(args) == 1:
  390. return event_handler()
  391. assert (
  392. len(args) == 2
  393. ), f"Event handler {event_handler.fn} must have 1 or 2 arguments."
  394. return event_handler(arg_spec) # type: ignore
  395. def parse_args_spec(arg_spec: ArgsSpec):
  396. """Parse the args provided in the ArgsSpec of an event trigger.
  397. Args:
  398. arg_spec: The spec of the args.
  399. Returns:
  400. The parsed args.
  401. """
  402. spec = inspect.getfullargspec(arg_spec)
  403. return arg_spec(
  404. *[
  405. BaseVar(
  406. _var_name=f"_{l_arg}",
  407. _var_type=spec.annotations.get(l_arg, FrontendEvent),
  408. _var_is_local=True,
  409. )
  410. for l_arg in spec.args
  411. ]
  412. )
  413. def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
  414. """Call a function to a list of event specs.
  415. The function should return either a single EventSpec or a list of EventSpecs.
  416. If the function takes in an arg, the arg will be passed to the function.
  417. Otherwise, the function will be called with no args.
  418. Args:
  419. fn: The function to call.
  420. arg: The argument to pass to the function.
  421. Returns:
  422. The event specs from calling the function.
  423. Raises:
  424. ValueError: If the lambda has an invalid signature.
  425. """
  426. # Import here to avoid circular imports.
  427. from reflex.event import EventHandler, EventSpec
  428. # Get the args of the lambda.
  429. args = inspect.getfullargspec(fn).args
  430. if isinstance(arg, ArgsSpec):
  431. out = fn(*parse_args_spec(arg)) # type: ignore
  432. else:
  433. # Call the lambda.
  434. if len(args) == 0:
  435. out = fn()
  436. elif len(args) == 1:
  437. out = fn(arg)
  438. else:
  439. raise ValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  440. # Convert the output to a list.
  441. if not isinstance(out, List):
  442. out = [out]
  443. # Convert any event specs to event specs.
  444. events = []
  445. for e in out:
  446. # Convert handlers to event specs.
  447. if isinstance(e, EventHandler):
  448. if len(args) == 0:
  449. e = e()
  450. elif len(args) == 1:
  451. e = e(arg) # type: ignore
  452. # Make sure the event spec is valid.
  453. if not isinstance(e, EventSpec):
  454. raise ValueError(f"Lambda {fn} returned an invalid event spec: {e}.")
  455. # Add the event spec to the chain.
  456. events.append(e)
  457. # Return the events.
  458. return events
  459. def get_handler_args(event_spec: EventSpec) -> tuple[tuple[Var, Var], ...]:
  460. """Get the handler args for the given event spec.
  461. Args:
  462. event_spec: The event spec.
  463. Returns:
  464. The handler args.
  465. """
  466. args = inspect.getfullargspec(event_spec.handler.fn).args
  467. return event_spec.args if len(args) > 1 else tuple()
  468. def fix_events(
  469. events: list[EventHandler | EventSpec] | None,
  470. token: str,
  471. router_data: dict[str, Any] | None = None,
  472. ) -> list[Event]:
  473. """Fix a list of events returned by an event handler.
  474. Args:
  475. events: The events to fix.
  476. token: The user token.
  477. router_data: The optional router data to set in the event.
  478. Returns:
  479. The fixed events.
  480. """
  481. # If the event handler returns nothing, return an empty list.
  482. if events is None:
  483. return []
  484. # If the handler returns a single event, wrap it in a list.
  485. if not isinstance(events, List):
  486. events = [events]
  487. # Fix the events created by the handler.
  488. out = []
  489. for e in events:
  490. if not isinstance(e, (EventHandler, EventSpec)):
  491. e = EventHandler(fn=e)
  492. # Otherwise, create an event from the event spec.
  493. if isinstance(e, EventHandler):
  494. e = e()
  495. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  496. name = format.format_event_handler(e.handler)
  497. payload = {k._var_name: v._decode() for k, v in e.args} # type: ignore
  498. # Create an event and append it to the list.
  499. out.append(
  500. Event(
  501. token=token,
  502. name=name,
  503. payload=payload,
  504. router_data=router_data or {},
  505. )
  506. )
  507. return out
  508. def get_fn_signature(fn: Callable) -> inspect.Signature:
  509. """Get the signature of a function.
  510. Args:
  511. fn: The function.
  512. Returns:
  513. The signature of the function.
  514. """
  515. signature = inspect.signature(fn)
  516. new_param = inspect.Parameter(
  517. "state", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  518. )
  519. return signature.replace(parameters=(new_param, *signature.parameters.values()))