page.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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() -> list[dict]:
  52. """Get the decorated pages.
  53. Returns:
  54. The decorated pages.
  55. """
  56. return sorted(
  57. [page_data for _, page_data in DECORATED_PAGES[get_config().app_name]],
  58. key=lambda x: x["route"],
  59. )