import { Component , Vue , Watch } from 'vue-property-decorator' ; @ Component export default class CodeViewMixin extends Vue { cmInstance = null ; isCodeViewMode = false ; @ Watch ( 'isCodeViewMode' ) onCodeViewModeChange ( val ) { if ( val ) { this . $nextTick ( ( ) => ! this . cmInstance && this . initCodemirror ( ) ) ; } else { if ( this . cmInstance ) { const content = this . cmInstance . getValue ( ) ; this . editor . setContent ( content , true ) ; this . destroyCodemirror ( ) ; } } } private initCodemirror ( ) { const codeView = this . extensions . find ( e => e . name === 'code_view' ) ; if ( codeView ) { const { codemirror , codemirrorOptions } = codeView . options ; if ( codemirror ) { const cmOptions = { ... codemirrorOptions , readOnly : this . readonly , spellcheck : this . spellcheckEnabled , } ; this . cmInstance = codemirror . fromTextArea ( this . $refs . cmTextArea , cmOptions ) ; this . cmInstance . setValue ( this . editor . getHTML ( ) ) ; this . formatCode ( ) ; } } } private destroyCodemirror ( ) { const element = this . cmInstance . doc . cm . getWrapperElement ( ) ; element && element . remove && element . remove ( ) ; this . cmInstance = null ; } private formatCode ( ) { const cm = this . cmInstance ; cm . execCommand ( 'selectAll' ) ; const selectedRange = { from : cm . getCursor ( true ) , to : cm . getCursor ( false ) , } ; cm . autoFormatRange ( selectedRange . from , selectedRange . to ) ; cm . setCursor ( 0 ) ; } }