templates.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """Templates to use in the pynecone compiler."""
  2. from typing import Optional, Set
  3. from pynecone import constants
  4. from pynecone.utils import join
  5. # Template for the Pynecone config file.
  6. PCCONFIG = f"""import pynecone as pc
  7. config = pc.Config(
  8. app_name="{{app_name}}",
  9. db_url="{constants.DB_URL}",
  10. env=pc.Env.DEV,
  11. )
  12. """
  13. # Javascript formatting.
  14. CONST = "const {name} = {value}".format
  15. PROP = "{object}.{property}".format
  16. IMPORT_LIB = 'import "{lib}"'.format
  17. IMPORT_FIELDS = 'import {default}{others} from "{lib}"'.format
  18. def format_import(lib: str, default: str = "", rest: Optional[Set[str]] = None) -> str:
  19. """Format an import statement.
  20. Args:
  21. lib: The library to import from.
  22. default: The default field to import.
  23. rest: The set of fields to import from the library.
  24. Returns:
  25. The compiled import statement.
  26. """
  27. # Handle the case of direct imports with no libraries.
  28. if lib == "":
  29. assert default == "", "No default field allowed for empty library."
  30. assert rest is not None and len(rest) > 0, "No fields to import."
  31. return join([IMPORT_LIB(lib=lib) for lib in sorted(rest)])
  32. # Handle importing from a library.
  33. rest = rest or set()
  34. if len(default) == 0 and len(rest) == 0:
  35. # Handle the case of importing a library with no fields.
  36. return IMPORT_LIB(lib=lib)
  37. else:
  38. # Handle importing specific fields from a library.
  39. others = f'{{{", ".join(sorted(rest))}}}' if len(rest) > 0 else ""
  40. if len(default) > 0 and len(rest) > 0:
  41. default += ", "
  42. return IMPORT_FIELDS(default=default, others=others, lib=lib)
  43. # Code to render a NextJS Document root.
  44. DOCUMENT_ROOT = join(
  45. [
  46. "{imports}",
  47. "export default function Document() {{",
  48. "return (",
  49. "{document}",
  50. ")",
  51. "}}",
  52. ]
  53. ).format
  54. # Template for the theme file.
  55. THEME = "export default {theme}".format
  56. # Code to render a single NextJS page.
  57. PAGE = join(
  58. [
  59. "{imports}",
  60. "{custom_code}",
  61. "{constants}",
  62. "export default function Component() {{",
  63. "{state}",
  64. "{events}",
  65. "{effects}",
  66. "return (",
  67. "{render}",
  68. ")",
  69. "}}",
  70. ]
  71. ).format
  72. # Code to render a single exported custom component.
  73. COMPONENT = join(
  74. [
  75. "export const {name} = memo(({{{props}}}) => (",
  76. "{render}",
  77. "))",
  78. ]
  79. ).format
  80. # Code to render the custom components page.
  81. COMPONENTS = join(
  82. [
  83. "{imports}",
  84. "{components}",
  85. ]
  86. ).format
  87. # React state declarations.
  88. USE_STATE = CONST(
  89. name="[{state}, {set_state}]", value="useState({initial_state})"
  90. ).format
  91. def format_state_setter(state: str) -> str:
  92. """Format a state setter.
  93. Args:
  94. state: The name of the state variable.
  95. Returns:
  96. The compiled state setter.
  97. """
  98. return f"set{state[0].upper() + state[1:]}"
  99. def format_state(
  100. state: str,
  101. initial_state: str,
  102. ) -> str:
  103. """Format a state declaration.
  104. Args:
  105. state: The name of the state variable.
  106. initial_state: The initial state of the state variable.
  107. Returns:
  108. The compiled state declaration.
  109. """
  110. set_state = format_state_setter(state)
  111. return USE_STATE(state=state, set_state=set_state, initial_state=initial_state)
  112. # Events.
  113. EVENT_ENDPOINT = constants.Endpoint.EVENT.name
  114. EVENT_FN = join(
  115. [
  116. "const Event = events => {set_state}({{",
  117. " ...{state},",
  118. " events: [...{state}.events, ...events],",
  119. "}})",
  120. ]
  121. ).format
  122. # Effects.
  123. ROUTER = constants.ROUTER
  124. RESULT = constants.RESULT
  125. PROCESSING = constants.PROCESSING
  126. SOCKET = constants.SOCKET
  127. STATE = constants.STATE
  128. EVENTS = constants.EVENTS
  129. SET_RESULT = format_state_setter(RESULT)
  130. READY = f"const {{ isReady }} = {ROUTER};"
  131. USE_EFFECT = join(
  132. [
  133. "useEffect(() => {{",
  134. " if(!isReady)",
  135. f" return;",
  136. f" if (!{SOCKET}.current) {{{{",
  137. f" connect({SOCKET}, {{state}}, {RESULT}, {SET_RESULT}, {ROUTER}, {EVENT_ENDPOINT})",
  138. " }}",
  139. " const update = async () => {{",
  140. f" if ({RESULT}.{STATE} != null) {{{{",
  141. f" {{set_state}}({{{{",
  142. f" ...{RESULT}.{STATE},",
  143. f" events: [...{{state}}.{EVENTS}, ...{RESULT}.{EVENTS}],",
  144. " }})",
  145. f" {SET_RESULT}({{{{",
  146. f" {STATE}: null,",
  147. f" {EVENTS}: [],",
  148. f" {PROCESSING}: false,",
  149. " }})",
  150. " }}",
  151. f" await updateState({{state}}, {RESULT}, {SET_RESULT}, {ROUTER}, {SOCKET}.current)",
  152. " }}",
  153. " update()",
  154. "}})",
  155. ]
  156. ).format
  157. # Routing
  158. ROUTER = f"const {constants.ROUTER} = useRouter()"
  159. # Sockets.
  160. SOCKET = "const socket = useRef(null)"