script.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, no_args_event_spec
  8. from reflex.vars.base import LiteralVar, 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 (defer-like behavior) | beforeInteractive | lazyOnload (async-like behavior)
  22. strategy: Var[Literal["afterInteractive", "beforeInteractive", "lazyOnload"]] = (
  23. LiteralVar.create("afterInteractive")
  24. )
  25. # Triggered when the script is loading
  26. on_load: EventHandler[no_args_event_spec]
  27. # Triggered when the script has loaded
  28. on_ready: EventHandler[no_args_event_spec]
  29. # Triggered when the script has errored
  30. on_error: EventHandler[no_args_event_spec]
  31. @classmethod
  32. def create(cls, *children, **props) -> Component:
  33. """Create an inline or user-defined script.
  34. If a string is provided as the first child, it will be rendered as an inline script
  35. otherwise the `src` prop must be provided.
  36. The following event triggers are provided:
  37. on_load: Execute code after the script has finished loading.
  38. on_ready: Execute code after the script has finished loading and every
  39. time the component is mounted.
  40. on_error: Execute code if the script fails to load.
  41. Args:
  42. *children: The children of the component.
  43. **props: The props of the component.
  44. Returns:
  45. The component.
  46. Raises:
  47. ValueError: when neither children nor `src` are specified.
  48. """
  49. if not children and not props.get("src"):
  50. raise ValueError("Must provide inline script or `src` prop.")
  51. return super().create(*children, **props)
  52. script = Script.create