CodeEditorElement.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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@latest/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. } );
  23. let timeout = null;
  24. this.editor.getModel().onDidChangeContent( () => {
  25. this._source = this.editor.getValue();
  26. if ( timeout ) clearTimeout( timeout );
  27. timeout = setTimeout( () => {
  28. this.dispatchEvent( new Event( 'change' ) );
  29. }, this.updateInterval );
  30. } );
  31. } );
  32. }
  33. set source( value ) {
  34. if ( this._source === value ) return;
  35. this._source = value;
  36. if ( this.editor ) this.editor.setValue( value );
  37. this.dispatchEvent( new Event( 'change' ) );
  38. }
  39. get source() {
  40. return this._source;
  41. }
  42. focus() {
  43. if ( this.editor ) this.editor.focus();
  44. }
  45. serialize( data ) {
  46. super.serialize( data );
  47. data.source = this.source;
  48. }
  49. deserialize( data ) {
  50. super.deserialize( data );
  51. this.source = data.source || '';
  52. }
  53. }
  54. LoaderLib[ 'CodeEditorElement' ] = CodeEditorElement;