script.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """Next.js script wrappers and inline script functionality.
  2. from typing import Optional
  3. https://nextjs.org/docs/app/api-reference/components/script.
  4. """
  5. from __future__ import annotations
  6. from typing import Any, Optional, Union
  7. from reflex.components.component import Component
  8. from reflex.vars import 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: Optional[Var[str]] = None
  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. }