<!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>
|