Bipes-Blockly项目二次开发/代码预览(二)
代码预览功能,使用Bipes原先用的插件codemirror,codemirror这个插件也是有局限的,有一些功能需要自己去改源码,对于代码预览已经足够了 项目地址:maxuecan.github.io/Bipes/index…
html引用
资源引用:
<script src="core/codemirror/codemirror.js"></script>
<script src="core/codemirror/mode/python/python.js"></script>
<link rel="stylesheet" href="core/codemirror/codemirror.css">
页面初始化内容
<!-- 代码预览 -->
<div class="code-preview">
<textarea name="code" id="code-preview"></textarea>
</div>
js引用
第一:目录ui/components/code-preview.js文件,定义代码预览组件
export default class CodePreview {
constructor() {
this.watch_timer = null // 定时器,监听积木区变动
this.state = false // 控制预览区是否显示
this.code = CodeMirror.fromTextArea(document.getElementById('code-preview'), {
mode: 'python', // 代码模式
lineNumbers: true, // 显示行号
readOnly: true // 只读模式
}) // 初始化CodeMirror
this.initEvent() // 初始化事件
}
initEvent() {
$('#codePreviewButton').on('click', () => {
this.codePreviewChange(!this.state)
})
}
// 显示隐藏预览区
codePreviewChange(state) {
$('.code-preview').css('visibility', (state ? 'visible' : 'hidden'))
if (state) {
$('.CodeMirror').eq(0).css('height', `calc(100vh - 3.5rem)`)
this.code.setValue(Code.generateCode()) // 通过Code.generateCode()加载代码内容
this.watchCodeChange() // 开启监听
} else {
clearTimeout(this.watch_timer)
this.code.setValue('')
}
this.state = state
}
// 监听积木区变动
watchCodeChange() {
this.watch_timer = setTimeout(() => {
let code = Code.generateCode()
let old_code = this.code.getValue()
if (code !== old_code) {
this.code.setValue(code)
}
this.watchCodeChange()
}, 500)
}
}
总结
代码预览功能代码不多,难点在于对codemirror插件使用,以及功能操作逻辑构建