Ldc
2024-04-07 0652600959e5e3b5796fb6e8da129704ca95347a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!doctype html>
 
<title>CodeMirror</title>
<meta charset="utf-8"/>
 
<link rel=stylesheet href="css/codemirror.css">
<script src="js/codemirror.js"></script>
<script src="js/yaml.js"></script>
<script src="js/js-yaml.min.js"></script>
<style type="text/css">
    .CodeMirror{
        height:500px;
    }
</style>
 
<body>
  <div id="yamlSource" style="width: 700px;height:500px;float: left;margin-right: 10px;border: 1px solid #ddd"></div>
  <div id="yamlResult" style="width: 600px;height:500px;float: left;border: 1px solid #ddd"></div>
<script>
  var yamlSourceCodeMirror = CodeMirror(document.getElementById('yamlSource'), {
    value: '',
    mode: 'yaml',
    lineNumbers: true,     // 显示行数
    indentUnit: 1,         // 缩进单位为2
    styleActiveLine: true, // 当前行背景高亮
    matchBrackets: true,   // 括号匹配
    lineWrapping: true,    // 自动换行
    tabSize: 2,
  });
 
  var yamlResultCodeMirror = CodeMirror(document.getElementById('yamlResult'), {
      value: '',
      mode: 'yaml',
      lineNumbers: true,     // 显示行数
      indentUnit: 1,         // 缩进单位为2
      styleActiveLine: true, // 当前行背景高亮
      matchBrackets: true,   // 括号匹配
      lineWrapping: true,    // 自动换行
      tabSize: 2,
  });
 
  // 监听输入值变化
  yamlSourceCodeMirror.on('change', (cm) => {
    var parseYaml=parseYamlFn(cm.doc.getValue())
    if(!!parseYaml.isYaml){
        var json = JSON.stringify(parseYaml.isYaml, null, 2);
        yamlResultCodeMirror.setValue(json);
    }else {
        console.log(parseYaml.errorMessage)
        yamlResultCodeMirror.setValue(parseYaml.errorMessage);
    }
  })
 
  const parseYamlFn = (str) => {
    let isYaml = false;
    let errorMessage = '';
    try {
      isYaml = jsyaml.load(str)
    } catch(e) {
      errorMessage = e && e.message;
    }
    return {
      isYaml, errorMessage
    };
  }
</script>
</body>