script.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Next.js script wrappers and inline script functionality.
  2. https://nextjs.org/docs/app/api-reference/components/script
  3. """
  4. from __future__ import annotations
  5. from typing import Any, Union
  6. from reflex.components.component import Component
  7. from reflex.event import EventChain
  8. from reflex.vars import BaseVar, Var
  9. class Script(Component):
  10. """Next.js script component.
  11. Note that this component differs from reflex.components.base.document.NextScript
  12. in that it is intended for use with custom and user-defined scripts.
  13. It also differs from reflex.components.base.link.ScriptTag, which is the plain
  14. HTML <script> tag which does not work when rendering a component.
  15. """
  16. library = "next/script"
  17. tag = "Script"
  18. is_default = True
  19. # Required unless inline script is used
  20. src: Var[str]
  21. # When the script will execute: afterInteractive | beforeInteractive | lazyOnload
  22. strategy: Var[str] = "afterInteractive" # type: ignore
  23. @classmethod
  24. def create(cls, *children, **props) -> Component:
  25. """Create an inline or user-defined script.
  26. If a string is provided as the first child, it will be rendered as an inline script
  27. otherwise the `src` prop must be provided.
  28. The following event triggers are provided:
  29. on_load: Execute code after the script has finished loading.
  30. on_ready: Execute code after the script has finished loading and every
  31. time the component is mounted.
  32. on_error: Execute code if the script fails to load.
  33. Args:
  34. *children: The children of the component.
  35. **props: The props of the component.
  36. Returns:
  37. The component.
  38. Raises:
  39. ValueError: when neither children nor `src` are specified.
  40. """
  41. if not children and not props.get("src"):
  42. raise ValueError("Must provide inline script or `src` prop.")
  43. return super().create(*children, **props)
  44. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  45. """Get the event triggers for the component.
  46. Returns:
  47. The event triggers.
  48. """
  49. return {
  50. **super().get_event_triggers(),
  51. "on_load": lambda: [],
  52. "on_ready": lambda: [],
  53. "on_error": lambda: [],
  54. }
  55. def client_side(javascript_code) -> Var[EventChain]:
  56. """Create an event handler that executes arbitrary javascript code.
  57. The provided code will have access to `args`, which come from the event itself.
  58. The code may call functions or reference variables defined in a previously
  59. included rx.script function.
  60. Args:
  61. javascript_code: The code to execute.
  62. Returns:
  63. An EventChain, passable to any component, that will execute the client side javascript
  64. when triggered.
  65. """
  66. return BaseVar(name=f"...args => {{{javascript_code}}}", type_=EventChain)