templates.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. )
  10. """
  11. # Javascript formatting.
  12. CONST = "const {name} = {value}".format
  13. PROP = "{object}.{property}".format
  14. IMPORT_LIB = 'import "{lib}"'.format
  15. IMPORT_FIELDS = 'import {default}{others} from "{lib}"'.format
  16. def format_import(lib: str, default: str = "", rest: Optional[Set[str]] = None) -> str:
  17. """Format an import statement.
  18. Args:
  19. lib: The library to import from.
  20. default: The default field to import.
  21. rest: The set of fields to import from the library.
  22. Returns:
  23. The compiled import statement.
  24. """
  25. # Handle the case of direct imports with no libraries.
  26. if lib == "":
  27. assert default == "", "No default field allowed for empty library."
  28. assert rest is not None and len(rest) > 0, "No fields to import."
  29. return join([IMPORT_LIB(lib=lib) for lib in sorted(rest)])
  30. # Handle importing from a library.
  31. rest = rest or set()
  32. if len(default) == 0 and len(rest) == 0:
  33. # Handle the case of importing a library with no fields.
  34. return IMPORT_LIB(lib=lib)
  35. else:
  36. # Handle importing specific fields from a library.
  37. others = f'{{{", ".join(sorted(rest))}}}' if len(rest) > 0 else ""
  38. if len(default) > 0 and len(rest) > 0:
  39. default += ", "
  40. return IMPORT_FIELDS(default=default, others=others, lib=lib)
  41. # Code to render a NextJS Document root.
  42. DOCUMENT_ROOT = join(
  43. [
  44. "{imports}",
  45. "export default function Document() {{",
  46. "return (",
  47. "{document}",
  48. ")",
  49. "}}",
  50. ]
  51. ).format
  52. # Template for the theme file.
  53. THEME = "export default {theme}".format
  54. # Code to render a single NextJS component.
  55. COMPONENT = join(
  56. [
  57. "{imports}",
  58. "{custom_code}",
  59. "{constants}",
  60. "export default function Component() {{",
  61. "{state}",
  62. "{events}",
  63. "{effects}",
  64. "return (",
  65. "{render}",
  66. ")",
  67. "}}",
  68. ]
  69. ).format
  70. # React state declarations.
  71. USE_STATE = CONST(
  72. name="[{state}, {set_state}]", value="useState({initial_state})"
  73. ).format
  74. def format_state_setter(state: str) -> str:
  75. """Format a state setter.
  76. Args:
  77. state: The name of the state variable.
  78. Returns:
  79. The compiled state setter.
  80. """
  81. return f"set{state[0].upper() + state[1:]}"
  82. def format_state(
  83. state: str,
  84. initial_state: str,
  85. ) -> str:
  86. """Format a state declaration.
  87. Args:
  88. state: The name of the state variable.
  89. initial_state: The initial state of the state variable.
  90. Returns:
  91. The compiled state declaration.
  92. """
  93. set_state = format_state_setter(state)
  94. return USE_STATE(state=state, set_state=set_state, initial_state=initial_state)
  95. # Events.
  96. EVENT_ENDPOINT = constants.Endpoint.EVENT.name
  97. EVENT_FN = join(
  98. [
  99. "const Event = events => {set_state}({{",
  100. " ...{state},",
  101. " events: [...{state}.events, ...events],",
  102. "}})",
  103. ]
  104. ).format
  105. # Effects.
  106. ROUTER = constants.ROUTER
  107. RESULT = constants.RESULT
  108. PROCESSING = constants.PROCESSING
  109. STATE = constants.STATE
  110. EVENTS = constants.EVENTS
  111. SET_RESULT = format_state_setter(RESULT)
  112. USE_EFFECT = join(
  113. [
  114. "useEffect(() => {{",
  115. " const update = async () => {{",
  116. f" if ({RESULT}.{STATE} != null) {{{{",
  117. f" {{set_state}}({{{{",
  118. f" ...{RESULT}.{STATE},",
  119. f" events: [...{{state}}.{EVENTS}, ...{RESULT}.{EVENTS}],",
  120. " }})",
  121. f" {SET_RESULT}({{{{",
  122. f" {STATE}: null,",
  123. f" {EVENTS}: [],",
  124. f" {PROCESSING}: false,",
  125. " }})",
  126. " }}",
  127. f" await updateState({{state}}, {RESULT}, {SET_RESULT}, {EVENT_ENDPOINT}, {ROUTER})",
  128. " }}",
  129. " update()",
  130. "}})",
  131. ]
  132. ).format
  133. # Routing
  134. ROUTER = f"const {constants.ROUTER} = useRouter()"