11import { Controller } from 'stimulus' ;
22import CodeMirror from 'codemirror' ;
3- import 'codemirror/mode/ruby/ruby.js'
43// import 'codemirror/theme/duotone-dark.css'
54
65export default class extends Controller {
76 static targets = [ "wrapper" , "mirror" , "body" , "description" ] ;
87 static values = {
8+ modes : Array ,
99 code : String ,
10+ mode : String ,
1011 initialized : Boolean ,
1112 readOnly : Boolean
1213 }
1314
1415 connect ( ) {
16+ console . log ( 'l' , this . modesValue )
1517 if ( this . shouldInitialize ( ) ) {
1618 this . initializeCodeMirror ( )
1719 this . setCodeMirrorValue ( )
20+ if ( this . hasModeValue ) { this . importMode ( this . modeValue ) }
1821 this . addEventListeners ( )
1922 }
2023 }
2124
2225 initializeCodeMirror ( ) {
2326 this . codeMirror = CodeMirror . fromTextArea ( this . mirrorTarget , {
2427 theme : 'one-light' ,
25- mode : 'ruby ' ,
28+ mode : 'javascript ' ,
2629 readOnly : this . readOnlyValue ? 'nocursor' : false
2730 } ) ;
2831
2932 this . initializedValue = true
3033 }
3134
3235 setCodeMirrorValue ( ) {
33- const value = this . hasCodeValue ? this . codeValue : ''
36+ const value = this . hasCodeValue ? this . codeValue : "updateMode(event) {\n const modeId = event.target.value\n const mode = this.modeFromId(modeId)\n const hasMode = Object.keys(CodeMirror.modes).includes(mode)\n\n !hasMode ? this.importMode(mode) : this.setMode(mode)\n}\n\nsetMode(mode) {\n this.codeMirror.setOption(\"mode\", mode);\n}"
3437 this . codeMirror . setValue ( value )
3538 }
3639
40+ updateMode ( event ) {
41+ const modeId = event . target . value
42+ const mode = this . modeFromId ( modeId )
43+ const hasMode = Object . keys ( CodeMirror . modes ) . includes ( mode )
44+
45+ ! hasMode ? this . importMode ( mode ) : this . setMode ( mode )
46+ }
47+
3748 shouldInitialize ( ) {
3849 return ! this . initializedValue
3950 }
@@ -45,4 +56,20 @@ export default class extends Controller {
4556 event . stopPropagation ( )
4657 } )
4758 }
59+
60+ importMode ( mode ) {
61+ import ( `codemirror/mode/${ mode } /${ mode } .js` )
62+ . then ( ( ) => this . setMode ( mode ) )
63+ . catch ( console . error )
64+ }
65+
66+ setMode ( mode ) {
67+ this . codeMirror . setOption ( "mode" , mode ) ;
68+ }
69+
70+ modeFromId ( modeId ) {
71+ return this . modesValue . find ( mode => {
72+ return Number ( mode . id ) === Number ( modeId )
73+ } ) . slug
74+ }
4875}
0 commit comments