1
0

page.py 2.3 KB

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