templates.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 component.
  57. COMPONENT = 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. # React state declarations.
  73. USE_STATE = CONST(
  74. name="[{state}, {set_state}]", value="useState({initial_state})"
  75. ).format
  76. def format_state_setter(state: str) -> str:
  77. """Format a state setter.
  78. Args:
  79. state: The name of the state variable.
  80. Returns:
  81. The compiled state setter.
  82. """
  83. return f"set{state[0].upper() + state[1:]}"
  84. def format_state(
  85. state: str,
  86. initial_state: str,
  87. ) -> str:
  88. """Format a state declaration.
  89. Args:
  90. state: The name of the state variable.
  91. initial_state: The initial state of the state variable.
  92. Returns:
  93. The compiled state declaration.
  94. """
  95. set_state = format_state_setter(state)
  96. return USE_STATE(state=state, set_state=set_state, initial_state=initial_state)
  97. # Events.
  98. EVENT_ENDPOINT = constants.Endpoint.EVENT.name
  99. EVENT_FN = join(
  100. [
  101. "const Event = events => {set_state}({{",
  102. " ...{state},",
  103. " events: [...{state}.events, ...events],",
  104. "}})",
  105. ]
  106. ).format
  107. # Effects.
  108. ROUTER = constants.ROUTER
  109. RESULT = constants.RESULT
  110. PROCESSING = constants.PROCESSING
  111. STATE = constants.STATE
  112. EVENTS = constants.EVENTS
  113. SET_RESULT = format_state_setter(RESULT)
  114. USE_EFFECT = join(
  115. [
  116. "useEffect(() => {{",
  117. " const update = async () => {{",
  118. f" if ({RESULT}.{STATE} != null) {{{{",
  119. f" {{set_state}}({{{{",
  120. f" ...{RESULT}.{STATE},",
  121. f" events: [...{{state}}.{EVENTS}, ...{RESULT}.{EVENTS}],",
  122. " }})",
  123. f" {SET_RESULT}({{{{",
  124. f" {STATE}: null,",
  125. f" {EVENTS}: [],",
  126. f" {PROCESSING}: false,",
  127. " }})",
  128. " }}",
  129. f" await updateState({{state}}, {RESULT}, {SET_RESULT}, {EVENT_ENDPOINT}, {ROUTER})",
  130. " }}",
  131. " update()",
  132. "}})",
  133. ]
  134. ).format
  135. # Routing
  136. ROUTER = f"const {constants.ROUTER} = useRouter()"