1
0

templates.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Templates to use in the reflex compiler."""
  2. from __future__ import annotations
  3. from jinja2 import Environment, FileSystemLoader, Template
  4. from reflex import constants
  5. from reflex.constants import Hooks
  6. from reflex.utils.format import format_state_name, json_dumps
  7. from reflex.vars.base import VarData
  8. def _sort_hooks(hooks: dict[str, VarData | None]):
  9. """Sort the hooks by their position.
  10. Args:
  11. hooks: The hooks to sort.
  12. Returns:
  13. The sorted hooks.
  14. """
  15. sorted_hooks = {
  16. Hooks.HookPosition.INTERNAL: [],
  17. Hooks.HookPosition.PRE_TRIGGER: [],
  18. Hooks.HookPosition.POST_TRIGGER: [],
  19. }
  20. for hook, data in hooks.items():
  21. if data and data.position and data.position == Hooks.HookPosition.INTERNAL:
  22. sorted_hooks[Hooks.HookPosition.INTERNAL].append((hook, data))
  23. elif not data or (
  24. not data.position
  25. or data.position == constants.Hooks.HookPosition.PRE_TRIGGER
  26. ):
  27. sorted_hooks[Hooks.HookPosition.PRE_TRIGGER].append((hook, data))
  28. elif (
  29. data
  30. and data.position
  31. and data.position == constants.Hooks.HookPosition.POST_TRIGGER
  32. ):
  33. sorted_hooks[Hooks.HookPosition.POST_TRIGGER].append((hook, data))
  34. return sorted_hooks
  35. class ReflexJinjaEnvironment(Environment):
  36. """The template class for jinja environment."""
  37. def __init__(self) -> None:
  38. """Set default environment."""
  39. super().__init__(
  40. trim_blocks=True,
  41. lstrip_blocks=True,
  42. auto_reload=False,
  43. )
  44. self.filters["json_dumps"] = json_dumps
  45. self.filters["react_setter"] = lambda state: f"set{state.capitalize()}"
  46. self.filters["var_name"] = format_state_name
  47. self.loader = FileSystemLoader(constants.Templates.Dirs.JINJA_TEMPLATE)
  48. self.globals["const"] = {
  49. "socket": constants.CompileVars.SOCKET,
  50. "result": constants.CompileVars.RESULT,
  51. "router": constants.CompileVars.ROUTER,
  52. "event_endpoint": constants.Endpoint.EVENT.name,
  53. "events": constants.CompileVars.EVENTS,
  54. "state": constants.CompileVars.STATE,
  55. "final": constants.CompileVars.FINAL,
  56. "processing": constants.CompileVars.PROCESSING,
  57. "initial_result": {
  58. constants.CompileVars.STATE: None,
  59. constants.CompileVars.EVENTS: [],
  60. constants.CompileVars.FINAL: True,
  61. constants.CompileVars.PROCESSING: False,
  62. },
  63. "color_mode": constants.ColorMode.NAME,
  64. "resolved_color_mode": constants.ColorMode.RESOLVED_NAME,
  65. "toggle_color_mode": constants.ColorMode.TOGGLE,
  66. "set_color_mode": constants.ColorMode.SET,
  67. "use_color_mode": constants.ColorMode.USE,
  68. "hydrate": constants.CompileVars.HYDRATE,
  69. "on_load_internal": constants.CompileVars.ON_LOAD_INTERNAL,
  70. "update_vars_internal": constants.CompileVars.UPDATE_VARS_INTERNAL,
  71. "frontend_exception_state": constants.CompileVars.FRONTEND_EXCEPTION_STATE_FULL,
  72. "hook_position": constants.Hooks.HookPosition,
  73. }
  74. self.globals["sort_hooks"] = _sort_hooks
  75. def get_template(name: str) -> Template:
  76. """Get render function that work with a template.
  77. Args:
  78. name: The template name. "/" is used as the path separator.
  79. Returns:
  80. A render function.
  81. """
  82. return ReflexJinjaEnvironment().get_template(name=name)
  83. # Template for the Reflex config file.
  84. RXCONFIG = get_template("app/rxconfig.py.jinja2")
  85. # Code to render a NextJS Document root.
  86. DOCUMENT_ROOT = get_template("web/pages/_document.js.jinja2")
  87. # Code to render NextJS App root.
  88. APP_ROOT = get_template("web/pages/_app.js.jinja2")
  89. # Template for the theme file.
  90. THEME = get_template("web/utils/theme.js.jinja2")
  91. # Template for the context file.
  92. CONTEXT = get_template("web/utils/context.js.jinja2")
  93. # Template for Tailwind config.
  94. TAILWIND_CONFIG = get_template("web/tailwind.config.js.jinja2")
  95. # Template to render a component tag.
  96. COMPONENT = get_template("web/pages/component.js.jinja2")
  97. # Code to render a single NextJS page.
  98. PAGE = get_template("web/pages/index.js.jinja2")
  99. # Code to render the custom components page.
  100. COMPONENTS = get_template("web/pages/custom_component.js.jinja2")
  101. # Code to render Component instances as part of StatefulComponent
  102. STATEFUL_COMPONENT = get_template("web/pages/stateful_component.js.jinja2")
  103. # Code to render StatefulComponent to an external file to be shared
  104. STATEFUL_COMPONENTS = get_template("web/pages/stateful_components.js.jinja2")
  105. # Sitemap config file.
  106. SITEMAP_CONFIG = "module.exports = {config}".format
  107. # Code to render the root stylesheet.
  108. STYLE = get_template("web/styles/styles.css.jinja2")
  109. # Code that generate the package json file
  110. PACKAGE_JSON = get_template("web/package.json.jinja2")
  111. # Template containing some macros used in the web pages.
  112. MACROS = get_template("web/pages/macros.js.jinja2")
  113. # Code that generate the pyproject.toml file for custom components.
  114. CUSTOM_COMPONENTS_PYPROJECT_TOML = get_template(
  115. "custom_components/pyproject.toml.jinja2"
  116. )
  117. # Code that generates the README file for custom components.
  118. CUSTOM_COMPONENTS_README = get_template("custom_components/README.md.jinja2")
  119. # Code that generates the source file for custom components.
  120. CUSTOM_COMPONENTS_SOURCE = get_template("custom_components/src.py.jinja2")
  121. # Code that generates the init file for custom components.
  122. CUSTOM_COMPONENTS_INIT_FILE = get_template("custom_components/__init__.py.jinja2")
  123. # Code that generates the demo app main py file for testing custom components.
  124. CUSTOM_COMPONENTS_DEMO_APP = get_template("custom_components/demo_app.py.jinja2")