11import { Controller } from 'stimulus' ;
22import CodeMirror from 'codemirror' ;
3- // import 'codemirror/theme/duotone-dark.css '
3+ import 'codemirror/mode/meta.js '
44
55export default class extends Controller {
66 static targets = [ "wrapper" , "mirror" , "body" , "description" ] ;
77 static values = {
88 modes : Array ,
99 code : String ,
10- mode : String ,
10+ modeId : String ,
1111 initialized : Boolean ,
1212 readOnly : Boolean
1313 }
@@ -16,7 +16,11 @@ export default class extends Controller {
1616 if ( this . shouldInitialize ( ) ) {
1717 this . initializeCodeMirror ( )
1818 this . setCodeMirrorValue ( )
19- if ( this . hasModeValue ) { this . importMode ( this . modeValue ) }
19+
20+ if ( this . hasModeIdValue ) {
21+ this . importModeFromId ( this . modeIdValue )
22+ }
23+
2024 this . addEventListeners ( )
2125 }
2226 }
@@ -38,37 +42,48 @@ export default class extends Controller {
3842
3943 updateMode ( event ) {
4044 const modeId = event . target . value
45+
46+ this . importModeFromId ( modeId )
47+ }
48+
49+ importModeFromId ( modeId ) {
4150 const mode = this . modeFromId ( modeId )
4251 const hasMode = Object . keys ( CodeMirror . modes ) . includes ( mode )
4352
4453 ! hasMode ? this . importMode ( mode ) : this . setMode ( mode )
4554 }
4655
47- shouldInitialize ( ) {
48- return ! this . initializedValue
49- }
50-
51- addEventListeners ( ) {
52- var editor = document . querySelector ( '.CodeMirror' ) ;
53-
54- editor . addEventListener ( "click" , ( event ) => {
55- event . stopPropagation ( )
56- } )
57- }
58-
5956 importMode ( mode ) {
60- import ( `codemirror/mode/${ mode } /${ mode } .js` )
57+ const path = mode . mode
58+
59+ import ( `codemirror/mode/${ path } /${ path } .js` )
6160 . then ( ( ) => this . setMode ( mode ) )
6261 . catch ( console . error )
6362 }
6463
6564 setMode ( mode ) {
66- this . codeMirror . setOption ( "mode" , mode ) ;
65+ this . codeMirror . setOption ( "mode" , mode . mime ) ;
6766 }
6867
6968 modeFromId ( modeId ) {
70- return this . modesValue . find ( mode => {
69+ const dbMode = this . modesValue . find ( mode => {
7170 return Number ( mode . id ) === Number ( modeId )
72- } ) . mode
71+ } )
72+
73+ return CodeMirror . modeInfo . find ( mode => {
74+ return mode . name === dbMode . name
75+ } )
76+ }
77+
78+ shouldInitialize ( ) {
79+ return ! this . initializedValue
80+ }
81+
82+ addEventListeners ( ) {
83+ var editor = document . querySelector ( '.CodeMirror' ) ;
84+
85+ editor . addEventListener ( "click" , ( event ) => {
86+ event . stopPropagation ( )
87+ } )
7388 }
7489}
0 commit comments