page.py 2.3 KB

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