custom_view.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import justpy as jp
  2. import os.path
  3. from starlette.routing import Route
  4. from starlette.responses import FileResponse
  5. class CustomView(jp.JustpyBaseComponent):
  6. vue_dependencies = []
  7. def __init__(self, vue_type, filepath, dependencies=[], **options):
  8. self.vue_type = vue_type
  9. self.vue_filepath = os.path.realpath(filepath).replace('.py', '.js')
  10. self.vue_dependencies = dependencies
  11. self.pages = {}
  12. self.classes = ''
  13. self.options = jp.Dict(**options)
  14. super().__init__(temp=False)
  15. def add_page(self, wp: jp.WebPage):
  16. marker = '<!--' + self.__module__ + '-->\n'
  17. if marker not in wp.head_html:
  18. wp.head_html += marker
  19. for dependency in self.vue_dependencies:
  20. if dependency.startswith('http://') or dependency.startswith('https://'):
  21. wp.head_html += f'<script src="{dependency}"></script>\n'
  22. else:
  23. wp.head_html += f'<script src="lib/{dependency}"></script>\n'
  24. filepath = f'{os.path.dirname(self.vue_filepath)}/lib/{dependency}'
  25. route = Route(f'/lib/{dependency}', lambda _, filepath=filepath: FileResponse(filepath))
  26. jp.app.routes.insert(0, route)
  27. if self.vue_filepath not in jp.component_file_list:
  28. filename = os.path.basename(self.vue_filepath)
  29. jp.app.routes.insert(0, Route(f'/{filename}', lambda _: FileResponse(self.vue_filepath)))
  30. jp.component_file_list += [filename]
  31. super().add_page(wp)
  32. def react(self, _):
  33. pass
  34. def convert_object_to_dict(self):
  35. return {
  36. 'vue_type': self.vue_type,
  37. 'id': self.id,
  38. 'show': True,
  39. 'options': self.options,
  40. }