jsoneditor.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from typing import Callable, Dict, List, Optional
  2. from ..element import Element
  3. from ..events import (GenericEventArguments, JSONEditorOnChangeEventArguments, JSONEditorOnSelectJSONEventArguments,
  4. JSONEditorOnSelectTextEventArguments, handle_event)
  5. class JSONEditor(Element, component='jsoneditor.js', exposed_libraries=['lib/vanilla-jsoneditor/index.js']):
  6. def __init__(
  7. self, properties: Dict, on_select: Optional[Callable] = None, on_change: Optional[Callable] = None) -> None:
  8. """JSONEditor
  9. An element to create a JSON editor using `JSONEditor <https://github.com/josdejong/svelte-jsoneditor>`_.
  10. Updates can be pushed to the editor by changing the `properties` property.
  11. After data has changed, call the `update` method to refresh the editor.
  12. :param properties: dictionary of JSONEditor properties
  13. :param on_select: callback function that is called when the editor's content has been selected
  14. :param on_change: callback function that is called when the editor's content has changed
  15. """
  16. super().__init__()
  17. self._props['properties'] = properties
  18. self._classes = ['nicegui-jsoneditor']
  19. if on_select:
  20. def handle_on_select_json(e: GenericEventArguments) -> None:
  21. handle_event(on_select, JSONEditorOnSelectJSONEventArguments(
  22. sender=self,
  23. client=self.client,
  24. event_type='select',
  25. edit=e.args['edit'],
  26. path=e.args['path'],
  27. type=e.args['type']
  28. ))
  29. self.on('select_json', handle_on_select_json, ['edit', 'path', 'type'])
  30. def handle_on_select_text(e: GenericEventArguments) -> None:
  31. handle_event(on_select, JSONEditorOnSelectTextEventArguments(
  32. sender=self,
  33. client=self.client,
  34. event_type='select',
  35. main=e.args['main'],
  36. ranges=e.args['ranges'],
  37. type=e.args['type']
  38. ))
  39. self.on('select_text', handle_on_select_text, ['main', 'ranges', 'type'])
  40. if on_change:
  41. def handle_on_change(e: GenericEventArguments) -> None:
  42. handle_event(on_change, JSONEditorOnChangeEventArguments(
  43. sender=self,
  44. client=self.client,
  45. event_type='change',
  46. content=e.args['content'],
  47. errors=e.args['errors']
  48. ))
  49. self.on('change', handle_on_change, ['content', 'errors'])
  50. @property
  51. def properties(self) -> Dict:
  52. return self._props['properties']
  53. def update(self) -> None:
  54. super().update()
  55. self.run_method('update_editor')