script.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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, Optional, Union
  6. from reflex.components.component import Component
  7. from reflex.vars import Var
  8. class Script(Component):
  9. """Next.js script component.
  10. Note that this component differs from reflex.components.base.document.NextScript
  11. in that it is intended for use with custom and user-defined scripts.
  12. It also differs from reflex.components.base.link.ScriptTag, which is the plain
  13. HTML <script> tag which does not work when rendering a component.
  14. """
  15. library = "next/script"
  16. tag: str = "Script"
  17. is_default: bool = True
  18. # Required unless inline script is used
  19. src: Optional[Var[str]] = None
  20. # When the script will execute: afterInteractive | beforeInteractive | lazyOnload
  21. strategy: Var[str] = "afterInteractive" # type: ignore
  22. @classmethod
  23. def create(cls, *children, **props) -> Component:
  24. """Create an inline or user-defined script.
  25. If a string is provided as the first child, it will be rendered as an inline script
  26. otherwise the `src` prop must be provided.
  27. The following event triggers are provided:
  28. on_load: Execute code after the script has finished loading.
  29. on_ready: Execute code after the script has finished loading and every
  30. time the component is mounted.
  31. on_error: Execute code if the script fails to load.
  32. Args:
  33. *children: The children of the component.
  34. **props: The props of the component.
  35. Returns:
  36. The component.
  37. Raises:
  38. ValueError: when neither children nor `src` are specified.
  39. """
  40. if not children and not props.get("src"):
  41. raise ValueError("Must provide inline script or `src` prop.")
  42. return super().create(*children, **props)
  43. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  44. """Get the event triggers for the component.
  45. Returns:
  46. The event triggers.
  47. """
  48. return {
  49. **super().get_event_triggers(),
  50. "on_load": lambda: [],
  51. "on_ready": lambda: [],
  52. "on_error": lambda: [],
  53. }