Sfoglia il codice sorgente

load dependencies statically instead of during instantiation

Falko Schindler 3 anni fa
parent
commit
b09d9480da

+ 3 - 1
nicegui/elements/colors.py

@@ -1,10 +1,12 @@
 from .custom_view import CustomView
 from .element import Element
 
+CustomView.use(__file__)
+
 class ColorsView(CustomView):
 
     def __init__(self, primary, secondary, accent, positive, negative, info, warning):
-        super().__init__('colors', __file__,
+        super().__init__('colors',
                          primary=primary,
                          secondary=secondary,
                          accent=accent,

+ 3 - 1
nicegui/elements/custom_example.py

@@ -1,10 +1,12 @@
 from .custom_view import CustomView
 from .element import Element
 
+CustomView.use(__file__)
+
 class CustomExampleView(CustomView):
 
     def __init__(self, on_change):
-        super().__init__('custom_example', __file__, value=0)
+        super().__init__('custom_example', value=0)
 
         self.on_change = on_change
         self.allowed_events = ['onAdd']

+ 21 - 22
nicegui/elements/custom_view.py

@@ -1,15 +1,13 @@
 import justpy as jp
 import os.path
+from typing import List
 from starlette.routing import Route
 from starlette.responses import FileResponse
 
 class CustomView(jp.JustpyBaseComponent):
-    vue_dependencies = []
 
-    def __init__(self, vue_type, filepath, dependencies=[], **options):
+    def __init__(self, vue_type, **options):
         self.vue_type = vue_type
-        self.vue_filepath = os.path.realpath(filepath).replace('.py', '.js')
-        self.vue_dependencies = dependencies
 
         self.pages = {}
         self.classes = ''
@@ -18,24 +16,6 @@ class CustomView(jp.JustpyBaseComponent):
 
         super().__init__(temp=False)
 
-    def add_page(self, wp: jp.WebPage):
-        for dependency in self.vue_dependencies:
-            is_remote = dependency.startswith('http://') or dependency.startswith('https://')
-            src = dependency if is_remote else f'lib/{dependency}'
-            if src not in jp.component_file_list:
-                jp.component_file_list += [src]
-                if not is_remote:
-                    filepath = f'{os.path.dirname(self.vue_filepath)}/{src}'
-                    route = Route(f'/{src}', lambda _, filepath=filepath: FileResponse(filepath))
-                    jp.app.routes.insert(0, route)
-
-        if self.vue_filepath not in jp.component_file_list:
-            filename = os.path.basename(self.vue_filepath)
-            jp.app.routes.insert(0, Route(f'/{filename}', lambda _: FileResponse(self.vue_filepath)))
-            jp.component_file_list += [filename]
-
-        super().add_page(wp)
-
     def react(self, _):
         pass
 
@@ -48,3 +28,22 @@ class CustomView(jp.JustpyBaseComponent):
             'style': self.style,
             'options': self.options,
         }
+
+    @staticmethod
+    def use(py_filepath: str, dependencies: List[str] = []):
+        vue_filepath = os.path.realpath(py_filepath).replace('.py', '.js')
+
+        for dependency in dependencies:
+            is_remote = dependency.startswith('http://') or dependency.startswith('https://')
+            src = dependency if is_remote else f'lib/{dependency}'
+            if src not in jp.component_file_list:
+                jp.component_file_list += [src]
+                if not is_remote:
+                    filepath = f'{os.path.dirname(vue_filepath)}/{src}'
+                    route = Route(f'/{src}', lambda _, filepath=filepath: FileResponse(filepath))
+                    jp.app.routes.insert(0, route)
+
+        if vue_filepath not in jp.component_file_list:
+            filename = os.path.basename(vue_filepath)
+            jp.app.routes.insert(0, Route(f'/{filename}', lambda _: FileResponse(vue_filepath)))
+            jp.component_file_list += [filename]

+ 3 - 1
nicegui/elements/joystick.py

@@ -2,6 +2,8 @@ from typing import Callable, Dict, Optional
 from .custom_view import CustomView
 from .element import Element
 
+CustomView.use(__file__, ['nipplejs.min.js'])
+
 class JoystickView(CustomView):
 
     def __init__(self,
@@ -10,7 +12,7 @@ class JoystickView(CustomView):
                  on_end: Optional[Callable],
                  **options,
                  ):
-        super().__init__('joystick', __file__, ['nipplejs.min.js'], **options)
+        super().__init__('joystick', **options)
 
         self.on_start = on_start
         self.on_move = on_move

+ 3 - 1
nicegui/elements/keyboard.py

@@ -5,10 +5,12 @@ from ..events import KeyEventArguments, KeyboardAction, KeyboardKey, KeyboardMod
 from .custom_view import CustomView
 from .element import Element
 
+CustomView.use(__file__)
+
 class KeyboardView(CustomView):
 
     def __init__(self, on_key: Callable, repeating: bool):
-        super().__init__('keyboard', __file__, active_js_events=['keydown', 'keyup', 'keypress'], repeating=repeating)
+        super().__init__('keyboard', active_js_events=['keydown', 'keyup', 'keypress'], repeating=repeating)
         self.allowed_events = ['keyboardEvent']
         self.style = 'display: none'
         self.initialize(temp=False, on_keyboardEvent=on_key)

+ 3 - 1
nicegui/elements/log.py

@@ -9,10 +9,12 @@ from .custom_view import CustomView
 from .element import Element
 from ..task_logger import create_task
 
+CustomView.use(__file__)
+
 class LogView(CustomView):
 
     def __init__(self, lines: Deque[str], max_lines: int):
-        super().__init__('log', __file__, max_lines=max_lines)
+        super().__init__('log', max_lines=max_lines)
         self.lines = lines
         self.allowed_events = ['onConnect']
         self.initialize(onConnect=self.handle_connect)

+ 3 - 2
nicegui/elements/scene.py

@@ -8,11 +8,12 @@ from .scene_object3d import Object3D
 from ..globals import view_stack
 from ..events import handle_event
 
+CustomView.use(__file__, ['three.min.js', 'OrbitControls.js', 'STLLoader.js'])
+
 class SceneView(CustomView):
 
     def __init__(self, *, width: int, height: int, on_click: Union[Callable, Awaitable]):
-        dependencies = ['three.min.js', 'OrbitControls.js', 'STLLoader.js']
-        super().__init__('scene', __file__, dependencies, width=width, height=height)
+        super().__init__('scene', width=width, height=height)
         self.on_click = on_click
         self.allowed_events = ['onConnect', 'onClick']
         self.initialize(temp=False, onConnect=self.handle_connect, onClick=self.handle_click)