Browse Source

hold content of log element and send it to newly connected clients

Falko Schindler 3 years ago
parent
commit
aa39ac172b
2 changed files with 33 additions and 6 deletions
  1. 14 0
      nicegui/elements/log.js
  2. 19 6
      nicegui/elements/log.py

+ 14 - 0
nicegui/elements/log.js

@@ -4,6 +4,20 @@ Vue.component("log", {
   template: `<textarea v-bind:id="jp_props.id" :class="jp_props.classes" :style="jp_props.style" disabled></textarea>`,
   mounted() {
     comp_dict[this.$props.jp_props.id] = this;
+
+    const sendConnectEvent = () => {
+      if (websocket_id === "") return;
+      const event = {
+        event_type: "onConnect",
+        vue_type: this.$props.jp_props.vue_type,
+        id: this.$props.jp_props.id,
+        page_id: page_id,
+        websocket_id: websocket_id,
+      };
+      send_to_server(event, "event");
+      clearInterval(connectInterval);
+    };
+    connectInterval = setInterval(sendConnectEvent, 10);
   },
   methods: {
     push(line) {

+ 19 - 6
nicegui/elements/log.py

@@ -1,13 +1,27 @@
 import asyncio
+import traceback
 import urllib
+from collections import deque
 from justpy.htmlcomponents import WebPage
 from .custom_view import CustomView
 from .element import Element
 
 class LogView(CustomView):
 
-    def __init__(self, max_lines: int):
+    def __init__(self, lines: deque[str], max_lines: int):
         super().__init__('log', __file__, max_lines=max_lines)
+        self.lines = lines
+        self.allowed_events = ['onConnect']
+        self.initialize(onConnect=self.handle_connect)
+
+    def handle_connect(self, msg):
+        try:
+            if self.lines:
+                content = '\n'.join(self.lines)
+                command = f'push("{urllib.parse.quote(content)}")'
+                asyncio.get_event_loop().create_task(self.run_method(command, msg.websocket))
+        except:
+            traceback.print_exc()
 
 class Log(Element):
 
@@ -18,16 +32,15 @@ class Log(Element):
 
         :param max_lines: maximum number of lines before dropping oldest ones (default: None)
         """
-        super().__init__(LogView(max_lines=max_lines))
-
+        self.lines = deque(maxlen=max_lines)
+        super().__init__(LogView(lines=self.lines, max_lines=max_lines))
         self.classes('border whitespace-pre font-mono').style('opacity: 1 !important; cursor: text !important')
 
     async def push_async(self, line: str):
-        if self.page.page_id not in WebPage.sockets:
-            return
+        self.lines.append(line)
         await asyncio.gather(*[
             self.view.run_method(f'push("{urllib.parse.quote(line)}")', socket)
-            for socket in WebPage.sockets[self.page.page_id].values()
+            for socket in WebPage.sockets.get(self.page.page_id, {}).values()
         ])
 
     def push(self, line: str):