FormDrawer.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <template>
  2. <div>
  3. <el-drawer
  4. v-bind="$attrs"
  5. v-on="$listeners"
  6. @opened="onOpen"
  7. @close="onClose"
  8. >
  9. <div style="height: 100%">
  10. <el-row style="height: 100%; overflow: auto">
  11. <el-col :md="24" :lg="12" class="left-editor">
  12. <div class="setting" title="资源引用" @click="showResource">
  13. <el-badge :is-dot="!!resources.length" class="item">
  14. <i class="el-icon-setting" />
  15. </el-badge>
  16. </div>
  17. <el-tabs v-model="activeTab" type="card" class="editor-tabs">
  18. <el-tab-pane name="html">
  19. <span slot="label">
  20. <i v-if="activeTab === 'html'" class="el-icon-edit" />
  21. <i v-else class="el-icon-document" />
  22. template
  23. </span>
  24. </el-tab-pane>
  25. <el-tab-pane name="js">
  26. <span slot="label">
  27. <i v-if="activeTab === 'js'" class="el-icon-edit" />
  28. <i v-else class="el-icon-document" />
  29. script
  30. </span>
  31. </el-tab-pane>
  32. <el-tab-pane name="css">
  33. <span slot="label">
  34. <i v-if="activeTab === 'css'" class="el-icon-edit" />
  35. <i v-else class="el-icon-document" />
  36. css
  37. </span>
  38. </el-tab-pane>
  39. </el-tabs>
  40. <div
  41. v-show="activeTab === 'html'"
  42. id="editorHtml"
  43. class="tab-editor"
  44. />
  45. <div v-show="activeTab === 'js'" id="editorJs" class="tab-editor" />
  46. <div
  47. v-show="activeTab === 'css'"
  48. id="editorCss"
  49. class="tab-editor"
  50. />
  51. </el-col>
  52. <el-col :md="24" :lg="12" class="right-preview">
  53. <div class="action-bar" :style="{ 'text-align': 'left' }">
  54. <span class="bar-btn" @click="runCode">
  55. <i class="el-icon-refresh" />
  56. 刷新
  57. </span>
  58. <span class="bar-btn" @click="exportFile">
  59. <i class="el-icon-download" />
  60. 导出vue文件
  61. </span>
  62. <span ref="copyBtn" class="bar-btn copy-btn">
  63. <i class="el-icon-document-copy" />
  64. 复制代码
  65. </span>
  66. <span
  67. class="bar-btn delete-btn"
  68. @click="$emit('update:visible', false)"
  69. >
  70. <i class="el-icon-circle-close" />
  71. 关闭
  72. </span>
  73. </div>
  74. <iframe
  75. v-show="isIframeLoaded"
  76. ref="previewPage"
  77. class="result-wrapper"
  78. frameborder="0"
  79. src="preview.html"
  80. @load="iframeLoad"
  81. />
  82. <div
  83. v-show="!isIframeLoaded"
  84. v-loading="true"
  85. class="result-wrapper"
  86. />
  87. </el-col>
  88. </el-row>
  89. </div>
  90. </el-drawer>
  91. <resource-dialog
  92. :visible.sync="resourceVisible"
  93. :origin-resource="resources"
  94. @save="setResource"
  95. />
  96. </div>
  97. </template>
  98. <script>
  99. import { parse } from '@babel/parser';
  100. import ClipboardJS from 'clipboard';
  101. // import { saveAs } from 'file-saver'
  102. import {
  103. makeUpHtml,
  104. vueTemplate,
  105. vueScript,
  106. cssStyle
  107. } from '@/components/FormGenerator/components/generator/html';
  108. import { makeUpJs } from '@/components/FormGenerator/components/generator/js';
  109. import { makeUpCss } from '@/components/FormGenerator/components/generator/css';
  110. import {
  111. exportDefault,
  112. beautifierConf,
  113. titleCase
  114. } from '@/components/FormGenerator/utils/index';
  115. import ResourceDialog from './ResourceDialog';
  116. import loadMonaco from '@/components/FormGenerator/utils/loadMonaco';
  117. import loadBeautifier from '@/components/FormGenerator/utils/loadBeautifier';
  118. const editorObj = {
  119. html: null,
  120. js: null,
  121. css: null
  122. };
  123. const mode = {
  124. html: 'html',
  125. js: 'javascript',
  126. css: 'css'
  127. };
  128. let beautifier;
  129. let monaco;
  130. export default {
  131. components: { ResourceDialog },
  132. props: ['formData', 'generateConf'],
  133. data() {
  134. return {
  135. activeTab: 'html',
  136. htmlCode: '',
  137. jsCode: '',
  138. cssCode: '',
  139. codeFrame: '',
  140. isIframeLoaded: false,
  141. isInitcode: false, // 保证open后两个异步只执行一次runcode
  142. isRefreshCode: false, // 每次打开都需要重新刷新代码
  143. resourceVisible: false,
  144. scripts: [],
  145. links: [],
  146. monaco: null
  147. };
  148. },
  149. computed: {
  150. resources() {
  151. return this.scripts.concat(this.links);
  152. }
  153. },
  154. watch: {},
  155. created() {},
  156. mounted() {
  157. window.addEventListener('keydown', this.preventDefaultSave);
  158. const clipboard = new ClipboardJS('.copy-btn', {
  159. text: (trigger) => {
  160. const codeStr = this.generateCode();
  161. this.$notify({
  162. title: '成功',
  163. message: '代码已复制到剪切板,可粘贴。',
  164. type: 'success'
  165. });
  166. return codeStr;
  167. }
  168. });
  169. clipboard.on('error', (e) => {
  170. this.$message.error('代码复制失败');
  171. });
  172. },
  173. beforeDestroy() {
  174. window.removeEventListener('keydown', this.preventDefaultSave);
  175. },
  176. methods: {
  177. preventDefaultSave(e) {
  178. if (e.key === 's' && (e.metaKey || e.ctrlKey)) {
  179. e.preventDefault();
  180. }
  181. },
  182. onOpen() {
  183. const { type } = this.generateConf;
  184. this.htmlCode = makeUpHtml(this.formData, type);
  185. this.jsCode = makeUpJs(this.formData, type);
  186. this.cssCode = makeUpCss(this.formData);
  187. loadBeautifier((btf) => {
  188. beautifier = btf;
  189. this.htmlCode = beautifier.html(this.htmlCode, beautifierConf.html);
  190. this.jsCode = beautifier.js(this.jsCode, beautifierConf.js);
  191. this.cssCode = beautifier.css(this.cssCode, beautifierConf.html);
  192. loadMonaco((val) => {
  193. monaco = val;
  194. this.setEditorValue('editorHtml', 'html', this.htmlCode);
  195. this.setEditorValue('editorJs', 'js', this.jsCode);
  196. this.setEditorValue('editorCss', 'css', this.cssCode);
  197. if (!this.isInitcode) {
  198. this.isRefreshCode = true;
  199. this.isIframeLoaded && (this.isInitcode = true) && this.runCode();
  200. }
  201. });
  202. });
  203. },
  204. onClose() {
  205. this.isInitcode = false;
  206. this.isRefreshCode = false;
  207. },
  208. iframeLoad() {
  209. if (!this.isInitcode) {
  210. this.isIframeLoaded = true;
  211. this.isRefreshCode && (this.isInitcode = true) && this.runCode();
  212. }
  213. },
  214. setEditorValue(id, type, codeStr) {
  215. if (editorObj[type]) {
  216. editorObj[type].setValue(codeStr);
  217. } else {
  218. editorObj[type] = monaco.editor.create(document.getElementById(id), {
  219. value: codeStr,
  220. theme: 'vs-dark',
  221. language: mode[type],
  222. automaticLayout: true
  223. });
  224. }
  225. // ctrl + s 刷新
  226. editorObj[type].onKeyDown((e) => {
  227. if (e.keyCode === 49 && (e.metaKey || e.ctrlKey)) {
  228. this.runCode();
  229. }
  230. });
  231. },
  232. runCode() {
  233. const jsCodeStr = editorObj.js.getValue();
  234. try {
  235. const ast = parse(jsCodeStr, { sourceType: 'module' });
  236. const astBody = ast.program.body;
  237. if (astBody.length > 1) {
  238. this.$confirm(
  239. 'js格式不能识别,仅支持修改export default的对象内容',
  240. '提示',
  241. {
  242. type: 'warning'
  243. }
  244. );
  245. return;
  246. }
  247. if (astBody[0].type === 'ExportDefaultDeclaration') {
  248. const postData = {
  249. type: 'refreshFrame',
  250. data: {
  251. generateConf: this.generateConf,
  252. html: editorObj.html.getValue(),
  253. js: jsCodeStr.replace(exportDefault, ''),
  254. css: editorObj.css.getValue(),
  255. scripts: this.scripts,
  256. links: this.links
  257. }
  258. };
  259. this.$refs.previewPage.contentWindow.postMessage(
  260. postData,
  261. location.origin
  262. );
  263. } else {
  264. this.$message.error('请使用export default');
  265. }
  266. } catch (err) {
  267. this.$message.error(`js错误:${err}`);
  268. console.error(err);
  269. }
  270. },
  271. generateCode() {
  272. const html = vueTemplate(editorObj.html.getValue());
  273. const script = vueScript(editorObj.js.getValue());
  274. const css = cssStyle(editorObj.css.getValue());
  275. return beautifier.html(html + script + css, beautifierConf.html);
  276. },
  277. exportFile() {
  278. this.$prompt('文件名:', '导出文件', {
  279. inputValue: `${+new Date()}.vue`,
  280. closeOnClickModal: false,
  281. inputPlaceholder: '请输入文件名'
  282. }).then(({ value }) => {
  283. if (!value) value = `${+new Date()}.vue`;
  284. const codeStr = this.generateCode();
  285. const blob = new Blob([codeStr], {
  286. type: 'text/plain;charset=utf-8'
  287. });
  288. // saveAs(blob, value)
  289. });
  290. },
  291. showResource() {
  292. this.resourceVisible = true;
  293. },
  294. setResource(arr) {
  295. const scripts = [];
  296. const links = [];
  297. if (Array.isArray(arr)) {
  298. arr.forEach((item) => {
  299. if (item.endsWith('.css')) {
  300. links.push(item);
  301. } else {
  302. scripts.push(item);
  303. }
  304. });
  305. this.scripts = scripts;
  306. this.links = links;
  307. } else {
  308. this.scripts = [];
  309. this.links = [];
  310. }
  311. }
  312. }
  313. };
  314. </script>
  315. <style lang="scss" scoped>
  316. @import '@/components/FormGenerator/styles/mixin.scss';
  317. .tab-editor {
  318. position: absolute;
  319. top: 33px;
  320. bottom: 0;
  321. left: 0;
  322. right: 0;
  323. font-size: 14px;
  324. }
  325. .left-editor {
  326. position: relative;
  327. height: 100%;
  328. background: #1e1e1e;
  329. overflow: hidden;
  330. }
  331. .setting {
  332. position: absolute;
  333. right: 15px;
  334. top: 3px;
  335. color: #a9f122;
  336. font-size: 18px;
  337. cursor: pointer;
  338. z-index: 1;
  339. }
  340. .right-preview {
  341. height: 100%;
  342. .result-wrapper {
  343. height: calc(100vh - 33px);
  344. width: 100%;
  345. overflow: auto;
  346. padding: 12px;
  347. box-sizing: border-box;
  348. }
  349. }
  350. @include action-bar;
  351. :deep(.el-drawer__header) {
  352. display: none;
  353. }
  354. </style>