瀏覽代碼

code review

Falko Schindler 1 年之前
父節點
當前提交
70af4ca56a

+ 1 - 1
main.py

@@ -402,7 +402,7 @@ def documentation_page() -> None:
 
 @ui.page('/documentation/{name}')
 async def documentation_page_more(name: str, client: Client) -> None:
-    if name in {'ag_grid', 'e_chart', 'j_s_o_n_editor'}:
+    if name in {'ag_grid', 'e_chart'}:
         name = name.replace('_', '')  # NOTE: "AG Grid" leads to anchor name "ag_grid", but class is `ui.aggrid`
     module = importlib.import_module(f'website.more_documentation.{name}_documentation')
     more = getattr(module, 'more', None)

+ 43 - 0
nicegui/elements/json_editor.js

@@ -0,0 +1,43 @@
+import { JSONEditor } from "index";
+
+export default {
+  template: "<div></div>",
+  mounted() {
+    this.properties.onChange = (updatedContent, previousContent, { contentErrors, patchResult }) => {
+      this.$emit("change", { content: updatedContent, errors: contentErrors });
+    };
+    this.properties.onSelect = (selection) => {
+      if (selection.type === "text") {
+        this.$emit("select_text", { main: selection.main, ranges: selection.ranges, type: selection.type });
+      }
+      if (selection.type === "key" || selection.type === "value") {
+        this.$emit("select_json", { edit: selection.edit, path: selection.path, type: selection.type });
+      }
+    };
+    this.editor = new JSONEditor({
+      target: this.$el,
+      props: this.properties,
+    });
+  },
+  beforeDestroy() {
+    this.destroyEditor();
+  },
+  beforeUnmount() {
+    this.destroyEditor();
+  },
+  methods: {
+    update_editor() {
+      if (this.editor) {
+        this.editor.updateProps(this.properties);
+      }
+    },
+    destroyEditor() {
+      if (this.editor) {
+        this.editor.dispose();
+      }
+    },
+  },
+  props: {
+    properties: Object,
+  },
+};

+ 55 - 0
nicegui/elements/json_editor.py

@@ -0,0 +1,55 @@
+from typing import Callable, Dict, Optional
+
+from ..element import Element
+from ..events import (GenericEventArguments, JsonEditorChangeEventArguments, JsonEditorSelectJsonEventArguments,
+                      JsonEditorSelectTextEventArguments, handle_event)
+
+
+class JsonEditor(Element, component='json_editor.js', exposed_libraries=['lib/vanilla-jsoneditor/index.js']):
+
+    def __init__(self,
+                 properties: Dict, *,
+                 on_select_json: Optional[Callable] = None,
+                 on_select_text: Optional[Callable] = None,
+                 on_change: Optional[Callable] = None,
+                 ) -> None:
+        """JSONEditor
+
+        An element to create a JSON editor using `JSONEditor <https://github.com/josdejong/svelte-jsoneditor>`_.
+        Updates can be pushed to the editor by changing the `properties` property.
+        After data has changed, call the `update` method to refresh the editor.
+
+        :param properties: dictionary of JSONEditor properties
+        :param on_select_json: callback function that is called when a JSON path is selected
+        :param on_select_text: callback function that is called when text is selected
+        :param on_change: callback function that is called when the editor's content has changed
+        """
+        super().__init__()
+        self._props['properties'] = properties
+        self._classes = ['nicegui-json-editor']
+
+        if on_select_json:
+            def handle_select_json(e: GenericEventArguments) -> None:
+                handle_event(on_select_json,
+                             JsonEditorSelectJsonEventArguments(sender=self, client=self.client, **e.args))
+            self.on('select_json', handle_select_json, ['edit', 'path', 'type'])
+
+        if on_select_text:
+            def handle_on_select_text(e: GenericEventArguments) -> None:
+                handle_event(on_select_text,
+                             JsonEditorSelectTextEventArguments(sender=self, client=self.client, **e.args))
+            self.on('select_text', handle_on_select_text, ['main', 'ranges', 'type'])
+
+        if on_change:
+            def handle_on_change(e: GenericEventArguments) -> None:
+                handle_event(on_change,
+                             JsonEditorChangeEventArguments(sender=self, client=self.client, **e.args))
+            self.on('change', handle_on_change, ['content', 'errors'])
+
+    @property
+    def properties(self) -> Dict:
+        return self._props['properties']
+
+    def update(self) -> None:
+        super().update()
+        self.run_method('update_editor')

+ 0 - 44
nicegui/elements/jsoneditor.js

@@ -1,44 +0,0 @@
-import { JSONEditor } from "index";
-
-export default {
-  template: "<div></div>",
-  mounted() {
-    setTimeout(() => {
-      this.properties.onChange = (updatedContent, previousContent, { contentErrors, patchResult }) => {
-        this.$emit("change", { content: updatedContent, errors: contentErrors });
-      };
-      this.properties.onSelect = (selection) => {
-        if (selection.type === "text") {
-          this.$emit("select_text", { main: selection.main, ranges: selection.ranges, type: selection.type });
-        } else {
-          this.$emit("select_json", { edit: selection.edit, path: selection.path, type: selection.type });
-        }
-      };
-      this.editor = new JSONEditor({
-        target: this.$el,
-        props: this.properties,
-      });
-    }, 0); // NOTE: wait for window.path_prefix to be set in app.mounted()
-  },
-  beforeDestroy() {
-    this.destroyEditor();
-  },
-  beforeUnmount() {
-    this.destroyEditor();
-  },
-  methods: {
-    update_editor() {
-      if (this.editor) {
-        this.editor.updateProps(this.properties);
-      }
-    },
-    destroyEditor() {
-      if (this.editor) {
-        this.editor.dispose();
-      }
-    },
-  },
-  props: {
-    properties: Object,
-  },
-};

+ 0 - 64
nicegui/elements/jsoneditor.py

@@ -1,64 +0,0 @@
-from typing import Callable, Dict, List, Optional
-
-from ..element import Element
-from ..events import (GenericEventArguments, JSONEditorOnChangeEventArguments, JSONEditorOnSelectJSONEventArguments,
-                      JSONEditorOnSelectTextEventArguments, handle_event)
-
-
-class JSONEditor(Element, component='jsoneditor.js', exposed_libraries=['lib/vanilla-jsoneditor/index.js']):
-    def __init__(
-            self, properties: Dict, on_select: Optional[Callable] = None, on_change: Optional[Callable] = None) -> None:
-        """JSONEditor
-
-        An element to create a JSON editor using `JSONEditor <https://github.com/josdejong/svelte-jsoneditor>`_.
-        Updates can be pushed to the editor by changing the `properties` property.
-        After data has changed, call the `update` method to refresh the editor.
-
-        :param properties: dictionary of JSONEditor properties
-        :param on_select: callback function that is called when the editor's content has been selected
-        :param on_change: callback function that is called when the editor's content has changed
-        """
-        super().__init__()
-        self._props['properties'] = properties
-        self._classes = ['nicegui-jsoneditor']
-
-        if on_select:
-            def handle_on_select_json(e: GenericEventArguments) -> None:
-                handle_event(on_select, JSONEditorOnSelectJSONEventArguments(
-                    sender=self,
-                    client=self.client,
-                    event_type='select',
-                    edit=e.args['edit'],
-                    path=e.args['path'],
-                    type=e.args['type']
-                ))
-            self.on('select_json', handle_on_select_json, ['edit', 'path', 'type'])
-
-            def handle_on_select_text(e: GenericEventArguments) -> None:
-                handle_event(on_select, JSONEditorOnSelectTextEventArguments(
-                    sender=self,
-                    client=self.client,
-                    event_type='select',
-                    main=e.args['main'],
-                    ranges=e.args['ranges'],
-                    type=e.args['type']
-                ))
-            self.on('select_text', handle_on_select_text, ['main', 'ranges', 'type'])
-        if on_change:
-            def handle_on_change(e: GenericEventArguments) -> None:
-                handle_event(on_change, JSONEditorOnChangeEventArguments(
-                    sender=self,
-                    client=self.client,
-                    event_type='change',
-                    content=e.args['content'],
-                    errors=e.args['errors']
-                ))
-            self.on('change', handle_on_change, ['content', 'errors'])
-
-    @property
-    def properties(self) -> Dict:
-        return self._props['properties']
-
-    def update(self) -> None:
-        super().update()
-        self.run_method('update_editor')

+ 7 - 12
nicegui/events.py

@@ -352,28 +352,23 @@ class ScrollEventArguments(UiEventArguments):
 
 
 @dataclass(**KWONLY_SLOTS)
-class JSONEditorEventArguments(UiEventArguments):
-    event_type: str
-
-
-@dataclass(**KWONLY_SLOTS)
-class JSONEditorOnSelectJSONEventArguments(JSONEditorEventArguments):
+class JsonEditorSelectJsonEventArguments(UiEventArguments):
     edit: bool
-    path: dict
+    path: Dict
     type: str
 
 
 @dataclass(**KWONLY_SLOTS)
-class JSONEditorOnSelectTextEventArguments(JSONEditorEventArguments):
+class JsonEditorSelectTextEventArguments(UiEventArguments):
     main: int
-    ranges: dict
+    ranges: Dict
     type: str
 
 
 @dataclass(**KWONLY_SLOTS)
-class JSONEditorOnChangeEventArguments(JSONEditorEventArguments):
-    content: dict
-    errors: dict
+class JsonEditorChangeEventArguments(UiEventArguments):
+    content: Dict
+    errors: Dict
 
 
 def handle_event(handler: Optional[Callable[..., Any]], arguments: EventArguments) -> None:

+ 1 - 1
nicegui/static/nicegui.css

@@ -68,7 +68,7 @@
   width: 100%;
   height: 16rem;
 }
-.nicegui-jsoneditor {
+.nicegui-json-editor {
   width: 100%;
   height: 16rem;
 }

+ 2 - 2
nicegui/ui.py

@@ -29,7 +29,7 @@ __all__ = [
     'input',
     'interactive_image',
     'joystick',
-    'jsoneditor',
+    'json_editor',
     'keyboard',
     'knob',
     'label',
@@ -122,7 +122,7 @@ from .elements.image import Image as image
 from .elements.input import Input as input
 from .elements.interactive_image import InteractiveImage as interactive_image
 from .elements.joystick import Joystick as joystick
-from .elements.jsoneditor import JSONEditor as jsoneditor
+from .elements.json_editor import JsonEditor as json_editor
 from .elements.keyboard import Keyboard as keyboard
 from .elements.knob import Knob as knob
 from .elements.label import Label as label

+ 1 - 1
website/documentation.py

@@ -143,7 +143,7 @@ def create_full() -> None:
     load_demo(ui.scene)
     load_demo(ui.tree)
     load_demo(ui.log)
-    load_demo(ui.jsoneditor)
+    load_demo(ui.json_editor)
 
     heading('Layout')
 

+ 18 - 0
website/more_documentation/json_editor_documentation.py

@@ -0,0 +1,18 @@
+from nicegui import ui
+
+
+def main_demo() -> None:
+    json = {
+        'array': [1, 2, 3],
+        'boolean': True,
+        'color': '#82b92c',
+        None: None,
+        'number': 123,
+        'object': {'a': 'b', 'c': 'd'},
+        'time': 1575599819000,
+        'string': 'Hello World'
+    }
+    ui.json_editor({'content': {'json': json}},
+                   on_select_json=lambda e: ui.notify(f'Select JSON: {e}'),
+                   on_select_text=lambda e: ui.notify(f'Select text: {e}'),
+                   on_change=lambda e: ui.notify(f'Change: {e}')).classes('h-80')

+ 0 - 17
website/more_documentation/jsoneditor_documentation.py

@@ -1,17 +0,0 @@
-from nicegui import ui
-
-
-def main_demo() -> None:
-    ui.jsoneditor(properties={'content': {
-        'json': {
-            'array': [1, 2, 3],
-            'boolean': True,
-            'color': '#82b92c',
-            None: None,
-            'number': 123,
-            'object': {'a': 'b', 'c': 'd'},
-            'time': 1575599819000,
-            'string': 'Hello World'
-        }}},
-        on_select=lambda e: ui.notify(f'Select: {e}'),
-        on_change=lambda e: ui.notify(f'Change: {e}'))