Detect detect file type in codemirror mode

Created: 3 Feb 2022,Updated: 4 Feb 2022,(0) fork,(0) stars,(0) comments,
const loadMode = (editor, filename: string) => {
    if (!editor) return;
    const CodeMirror = window.CodeMirror;
    // @ts-ignore
    window.CodeMirror.modeURL = scriptCfg.baseUrl + "mode/%N/%N.min.js";
    var val = filename,
      m: any[],
      mode: string,
      spec: string | CodeMirror.ModeSpec<CodeMirror.ModeSpecOptions>;
    try {
      if ((m = /.+\.([^.]+)$/.exec(val))) {
        // @ts-ignore
        var info = CodeMirror.findModeByExtension(m[1]);
        if (info) {
          mode = info.mode;
          spec = info.mime;
        }
      } else if (/\//.test(val)) {
        // @ts-ignore
        var info = CodeMirror.findModeByMIME(val);
        if (info) {
          mode = info.mode;
          spec = val;
        }
      }
      // else {
      //   mode = spec = val;
      // }
      if (mode) {
        if (mode !== editor.getMode()?.name) {
          editor.setOption("mode", spec);
          // @ts-ignore
          CodeMirror.autoLoadMode(editor, mode);
        }
        //console.log(mode, spec);
      } else {
        if (!!filename) alert("Could not find a mode corresponding to " + val);
        editor.setOption("mode", "null");
      }
    } catch (e) {
      console.error(e);
    }
  };