1
0
mirror of https://github.com/sahadev/vue-component-creater-ui.git synced 2025-09-28 07:13:21 +08:00

Merge branch 'master' into vue3

This commit is contained in:
shangbin
2021-12-09 14:22:52 +08:00
13 changed files with 1195 additions and 1226 deletions

View File

@@ -1,7 +1,7 @@
<template>
<div class="top-tools-bar">
<el-row :gutter="20">
<el-row :gutter="22">
<el-col :span="3">
<div class="edit">
<el-tooltip class="item" effect="dark" content="ctrl + z" placement="bottom-start">
@@ -24,9 +24,14 @@
<el-link type="primary" @click="$emit('structureVisible')">Inspect Components
Structure</el-link>
</el-col>
<el-col :span="3">
<a class="github-button" href="https://github.com/sahadev/vue-component-creater-ui" data-icon="octicon-star"
data-show-count="true" aria-label="Star sahadev/vue-component-creater-ui on GitHub">Star</a>
</el-col>
</el-row>
<a href="https://github.com/sahadev/vue-component-creater-ui" class="github-corner" aria-label="View source on GitHub">
<a href="https://github.com/sahadev/vue-component-creater-ui" class="github-corner"
aria-label="View source on GitHub">
<svg width="40" height="40" viewBox="0 0 250 250"
style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
@@ -44,7 +49,7 @@
<script>
export default {
props: [],
components: {},
components: { },
data() {
return {
previewMode: false,

View File

@@ -1,125 +0,0 @@
<template>
<preview :value="preview" class="panel"></preview>
</template>
<script>
import Preview from '@/components/Preview';
import { parseComponent } from 'vue-template-compiler/browser';
import getImports from '@/utils/get-imports';
import getPkgs from '@/utils/get-pkgs';
import isAbsouteUrl from 'is-absolute-url';
import * as params from '@/utils/params';
export default {
props: ['code'],
components: {
Preview
},
data: () => ({
preview: '',
}),
watch: {
code: {
handler: function (newValue) {
this.compile(newValue);
},
immediate: true
}
},
methods: {
async compile(code) {
if (!code) {
return;
}
const imports = [];
const { template, script, styles, customBlocks } = parseComponent(code);
let config;
if ((config = customBlocks.find(n => n.type === 'config'))) {
params.clear();
params.parse(config.content);
}
let compiled;
const pkgs = [];
let scriptContent = 'exports = { default: {} }';
if (script) {
try {
compiled = window.Babel.transform(script.content, {
presets: ['es2015', 'es2016', 'es2017', 'stage-0'],
plugins: [[getImports, { imports }]]
}).code;
} catch (e) {
this.preview = `<pre style="color: red">${e.message}</pre>`;
return;
}
scriptContent = await getPkgs(compiled, imports, pkgs);
}
const heads = this.genHeads();
const scripts = [];
pkgs.forEach(pkg => {
scripts.push(
`<script src=//packd.now.sh/${pkg.module}${pkg.path}?name=${pkg.name
}><\/script>`
);
});
styles.forEach(style => {
heads.push(`<style>${style.content}</style>`);
});
scripts.push(`
<script>
var exports = {};
${scriptContent}
var component = exports.default;
component.template = component.template || ${JSON.stringify(
template.content
)}
new Vue(component).$mount('#app')
<\/script>`);
this.preview = {
head: heads.join('\n'),
body: '<div lc_id="app"></div>' + scripts.join('\n')
};
},
genHeads() {
let heads = [];
const { pkgs, css } = params.get();
return [].concat(
[]
.concat(pkgs)
.map(
pkg =>
`<script src="${isAbsouteUrl(pkg) ? '' : prefix}${pkg}"><\/script>`
),
css.map(
item =>
`<link rel=stylesheet href="${isAbsouteUrl(item) ? '' : prefix
}${item}">`
)
);
},
}
};
</script>
<style src="modern-normalize"></style>
<style scoped>
.panel {
background-color: white;
}
</style>

View File

@@ -11,6 +11,7 @@ import { getRawComponentContent, getRawComponentKey, isObject } from '@/utils/co
import { createNewCodeGenerator } from "@/libs/code-generator-factory";
import EventEmitter from 'eventemitter3'
import { cloneDeep } from 'lodash-es';
import scope from 'css-scoped';
/**
* 主控制面板辅助类,用于代码的生成与绘制
@@ -44,8 +45,6 @@ export class MainPanelProvider {
console.groupCollapsed('---> for code generator warn <---');
const readyForMoutedElement = this.createMountedElement();
// 生成原始代码
let code = this.codeGenerator.outputVueCodeWithJsonObj(rawDataStructure);
@@ -61,6 +60,8 @@ export class MainPanelProvider {
const { template, script, styles, customBlocks } = parseComponent(code);
this.loadStyle(styles);
let newScript = script.content.replace(/\s*export default\s*/, "")
const componentOptions = (new Function(`return ${newScript}`))();
@@ -69,6 +70,7 @@ export class MainPanelProvider {
if (this.editMode) {
// 渲染当前代码
const readyForMoutedElement = this.createMountedElement();
createBaseApp(componentOptions).mount(readyForMoutedElement);
// 拍平数据结构
@@ -99,6 +101,21 @@ export class MainPanelProvider {
this.reRender();
}
loadStyle(styles) {
if (styles.length > 0) {
const scopedStyle = styles[0];
this.styleNodeName = `cssScoped${Date.now()}`;
const scopedCss = scope(scopedStyle.content.replace(/::v-deep/g, ''), this.styleNodeName);
const styleNode = document.createElement('style');
styleNode.innerText = scopedCss;
// 这个会导致越来越卡
document.head.appendChild(styleNode);
}
}
/**
* 初始化代码编译
*/
@@ -122,6 +139,10 @@ export class MainPanelProvider {
*/
createMountedElement() {
const renderControlPanel = this.getControlPanelRoot();
if (this.styleNodeName) {
renderControlPanel.setAttribute('class', this.styleNodeName);
}
return renderControlPanel;
}

View File

@@ -95,12 +95,22 @@ function convert2Map(jsonObj) {
}
}
function findProperty(properties, findWhoStructure) {
return properties.find(item=>{
if(item.key.name === findWhoStructure){
return true;
}
})
}
// 对JS代码进行编译
function compileJsCode(code, onEncounterDuplicateDeclared = () => { }) {
const ast = espree.parse(code, { ecmaVersion: 6, sourceType: "module" });
// 提取data中返回的对象结构, 如果文件引入了其它文件, 则body[0]为import语句。
if (ast.body[0].declaration) {
const dataAst = ast.body[0].declaration.properties[0].value.body.body[0].argument;
const properties = ast.body[0].declaration.properties;
const dataProperty = findProperty(properties, 'data');
const dataAst = dataProperty.value.body.body[0].argument;
const newCode = escodegen.generate(dataAst);
// 这里编译的组件内部应当只包含data和method不应该包含其它属性

View File

@@ -1,18 +0,0 @@
export default function(code, { imports }) {
return {
name: 'get-imports',
visitor: {
ImportDeclaration(path) {
imports.push({
variables: path.node.specifiers.map(spec => ({
local: spec.local.name,
imported: spec.imported ? spec.imported.name : 'default'
})),
module: path.node.source.value
});
path.remove();
}
}
};
}

View File

@@ -1,40 +0,0 @@
import parsePackageName from 'parse-package-name';
export default async function(code, imports, scripts) {
const replacements = [];
for (const [index, item] of imports.entries()) {
const moduleName = `__npm_module_${index}`;
const pkg = parsePackageName(item.module);
const version = pkg.version || 'latest';
scripts.push({
path: pkg.path ? `/${pkg.path}` : '',
name: moduleName,
module:
pkg.name === 'vue' && !pkg.path
? `vue@${version}/dist/vue.esm.js`
: `${pkg.name}@${version}`
});
let replacement = '\n';
for (const variable of item.variables) {
if (variable.imported === 'default') {
replacement += `var ${
variable.local
} = ${moduleName}.default || ${moduleName};\n`;
} else {
replacement += `var ${variable.local} = ${moduleName}.${
variable.imported
};\n`;
}
}
if (replacement) {
replacements.push(replacement);
}
}
if (replacements.length > 0) {
code = replacements.join('\n') + code;
}
return code;
}

View File

@@ -1,59 +0,0 @@
/**
* From: https://github.com/egoist/codepan/blob/2c22bb3d7a7a4e31fd99fc640d320f7ec24d2951/src/utils/iframe.js
*/
import { Loading } from 'element-ui';
class Iframe {
constructor({ container, el, sandboxAttributes = [] }) {
if (!el) {
throw new Error('Expect "el" to mount iframe to!');
}
this.$container = container;
this.$el = el;
this.sandboxAttributes = sandboxAttributes;
}
setHTML(obj) {
let html;
if (typeof obj === 'string') {
html = obj;
} else {
const { head = '', body = '' } = obj;
html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
}
// 关闭上一个实例引起的loading
if (this.loadingInstance) {
this.loadingInstance.close();
}
this.loadingInstance = Loading.service({
target: this.$container,
text: '渲染中,请稍后...'
});
const iframe = this.createIframe();
iframe.addEventListener('load', () => {
this.loadingInstance.close();
})
this.$el.parentNode.replaceChild(iframe, this.$el);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
this.$el = iframe;
}
createIframe() {
const iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', this.sandboxAttributes.join(' '));
iframe.setAttribute('scrolling', 'yes');
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = '0';
return iframe;
}
}
export default (...args) => new Iframe(...args);

View File

@@ -1,55 +0,0 @@
import qs from 'query-string';
import deepmerge from 'deepmerge';
const DEFAULT_PARAMS = {
pkgs: ['https://static.imonkey.xueersi.com/vue-code-creater/resource/vue.js', 'https://static.imonkey.xueersi.com/vue-code-creater/resource/element-ui/index.js'],
css: ['https://static.imonkey.xueersi.com/vue-code-creater/resource/element-ui/index.css'],
};
let params = DEFAULT_PARAMS;
function getArr(str) {
if (Array.isArray(str)) {
return str;
}
if (typeof str === 'string') {
return str.split(',');
}
return [];
}
export function clear() {
params = DEFAULT_PARAMS;
}
export function parse(str) {
try {
merge(JSON.parse(str));
} catch (e) {
console.error('error', e.message);
}
}
export function queryParse(str) {
const query = qs.parse(str);
const pkgs = getArr(query.pkg);
const css = getArr(query.css);
const options = { pkgs, css };
if (query.cdn) {
options.cdn = query.cdn;
}
if (query.vue) {
options.vue = query.vue;
}
merge(options);
}
export function get() {
return deepmerge(DEFAULT_PARAMS, params);
}
export function merge(opts) {
params = deepmerge(params, opts);
}