script.py 2.4 KB

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