page.py 2.6 KB

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