script.py 2.2 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 reflex.components.component import Component
  6. from reflex.event import EventHandler
  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 = "Script"
  17. is_default = True
  18. # Required unless inline script is used
  19. src: Var[str]
  20. # When the script will execute: afterInteractive | beforeInteractive | lazyOnload
  21. strategy: Var[str] = "afterInteractive" # type: ignore
  22. # Triggered when the script is loading
  23. on_load: EventHandler[lambda: []]
  24. # Triggered when the script has loaded
  25. on_ready: EventHandler[lambda: []]
  26. # Triggered when the script has errored
  27. on_error: EventHandler[lambda: []]
  28. @classmethod
  29. def create(cls, *children, **props) -> Component:
  30. """Create an inline or user-defined script.
  31. If a string is provided as the first child, it will be rendered as an inline script
  32. otherwise the `src` prop must be provided.
  33. The following event triggers are provided:
  34. on_load: Execute code after the script has finished loading.
  35. on_ready: Execute code after the script has finished loading and every
  36. time the component is mounted.
  37. on_error: Execute code if the script fails to load.
  38. Args:
  39. *children: The children of the component.
  40. **props: The props of the component.
  41. Returns:
  42. The component.
  43. Raises:
  44. ValueError: when neither children nor `src` are specified.
  45. """
  46. if not children and not props.get("src"):
  47. raise ValueError("Must provide inline script or `src` prop.")
  48. return super().create(*children, **props)
  49. script = Script.create