json_editor.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from typing import Callable, Dict, Optional
  2. from ..awaitable_response import AwaitableResponse
  3. from ..element import Element
  4. from ..events import GenericEventArguments, JsonEditorChangeEventArguments, JsonEditorSelectEventArguments, handle_event
  5. class JsonEditor(Element, component='json_editor.js', exposed_libraries=['lib/vanilla-jsoneditor/index.js']):
  6. def __init__(self,
  7. properties: Dict, *,
  8. on_select: Optional[Callable] = None,
  9. on_change: Optional[Callable] = None,
  10. ) -> None:
  11. """JSONEditor
  12. An element to create a JSON editor using `JSONEditor <https://github.com/josdejong/svelte-jsoneditor>`_.
  13. Updates can be pushed to the editor by changing the `properties` property.
  14. After data has changed, call the `update` method to refresh the editor.
  15. :param properties: dictionary of JSONEditor properties
  16. :param on_select: callback function that is called when some of the content has been selected
  17. :param on_change: callback function that is called when the content has changed
  18. """
  19. super().__init__()
  20. self._props['properties'] = properties
  21. if on_select:
  22. def handle_on_select(e: GenericEventArguments) -> None:
  23. handle_event(on_select, JsonEditorSelectEventArguments(sender=self, client=self.client, **e.args))
  24. self.on('select', handle_on_select, ['selection'])
  25. if on_change:
  26. def handle_on_change(e: GenericEventArguments) -> None:
  27. handle_event(on_change, JsonEditorChangeEventArguments(sender=self, client=self.client, **e.args))
  28. self.on('change', handle_on_change, ['content', 'errors'])
  29. @property
  30. def properties(self) -> Dict:
  31. """The property dictionary."""
  32. return self._props['properties']
  33. def update(self) -> None:
  34. super().update()
  35. self.run_method('update_editor')
  36. def run_editor_method(self, name: str, *args, timeout: float = 1,
  37. check_interval: float = 0.01) -> AwaitableResponse:
  38. """Run a method of the JSONEditor instance.
  39. See the `JSONEditor README <https://github.com/josdejong/svelte-jsoneditor/>`_ for a list of methods.
  40. If the function is awaited, the result of the method call is returned.
  41. Otherwise, the method is executed without waiting for a response.
  42. :param name: name of the method
  43. :param args: arguments to pass to the method
  44. :param timeout: timeout in seconds (default: 1 second)
  45. :param check_interval: interval in seconds to check for a response (default: 0.01 seconds)
  46. :return: AwaitableResponse that can be awaited to get the result of the method call
  47. """
  48. return self.run_method('run_editor_method', name, *args, timeout=timeout, check_interval=check_interval)