CodeEditorElement.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { Element, LoaderLib } from 'flow';
  2. export class CodeEditorElement extends Element {
  3. constructor( source = '' ) {
  4. super();
  5. this.updateInterval = 500;
  6. this._source = source;
  7. this.dom.style[ 'z-index' ] = - 1;
  8. this.dom.classList.add( 'no-zoom' );
  9. this.setHeight( 500 );
  10. const editorDOM = document.createElement( 'div' );
  11. editorDOM.style.width = '100%';
  12. editorDOM.style.height = '100%';
  13. this.dom.appendChild( editorDOM );
  14. this.editor = null; // async
  15. window.require.config( { paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.48.0/min/vs' } } );
  16. require( [ 'vs/editor/editor.main' ], () => {
  17. this.editor = window.monaco.editor.create( editorDOM, {
  18. value: this.source,
  19. language: 'javascript',
  20. theme: 'vs-dark',
  21. automaticLayout: true,
  22. minimap: { enabled: false }
  23. } );
  24. let timeout = null;
  25. this.editor.getModel().onDidChangeContent( () => {
  26. this._source = this.editor.getValue();
  27. if ( timeout ) clearTimeout( timeout );
  28. timeout = setTimeout( () => {
  29. this.dispatchEvent( new Event( 'change' ) );
  30. }, this.updateInterval );
  31. } );
  32. } );
  33. }
  34. set source( value ) {
  35. if ( this._source === value ) return;
  36. this._source = value;
  37. if ( this.editor ) this.editor.setValue( value );
  38. this.dispatchEvent( new Event( 'change' ) );
  39. }
  40. get source() {
  41. return this._source;
  42. }
  43. focus() {
  44. if ( this.editor ) this.editor.focus();
  45. }
  46. serialize( data ) {
  47. super.serialize( data );
  48. data.source = this.source;
  49. }
  50. deserialize( data ) {
  51. super.deserialize( data );
  52. this.source = data.source || '';
  53. }
  54. }
  55. LoaderLib[ 'CodeEditorElement' ] = CodeEditorElement;