page.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """The page decorator and associated variables and functions."""
  2. from __future__ import annotations
  3. from typing import Any
  4. DECORATED_PAGES = []
  5. def page(
  6. route: str | None = None,
  7. title: str | None = None,
  8. image: str | None = None,
  9. description: str | None = None,
  10. meta: str | None = None,
  11. script_tags: list[Any] | None = None,
  12. on_load: Any | list[Any] | None = None,
  13. ):
  14. """Decorate a function as a page.
  15. rx.App() will automatically call add_page() for any method decorated with page
  16. when App.compile is called.
  17. All defaults are None because they will use the one from add_page().
  18. Note: the decorated functions still need to be imported.
  19. Args:
  20. route: The route to reach the page.
  21. title: The title of the page.
  22. image: The favicon of the page.
  23. description: The description of the page.
  24. meta: Additionnal meta to add to the page.
  25. on_load: The event handler(s) called when the page load.
  26. script_tags: scripts to attach to the page
  27. Returns:
  28. The decorated function.
  29. """
  30. def decorator(render_fn):
  31. kwargs = {}
  32. if route:
  33. kwargs["route"] = route
  34. if title:
  35. kwargs["title"] = title
  36. if image:
  37. kwargs["image"] = image
  38. if description:
  39. kwargs["description"] = description
  40. if meta:
  41. kwargs["meta"] = meta
  42. if script_tags:
  43. kwargs["script_tags"] = script_tags
  44. if on_load:
  45. kwargs["on_load"] = on_load
  46. DECORATED_PAGES.append((render_fn, kwargs))
  47. return render_fn
  48. return decorator
  49. def get_decorated_pages() -> list[dict]:
  50. """Get the decorated pages.
  51. Returns:
  52. The decorated pages.
  53. """
  54. return sorted(
  55. [page_data for render_fn, page_data in DECORATED_PAGES],
  56. key=lambda x: x["route"],
  57. )