-
Notifications
You must be signed in to change notification settings - Fork 24
/
Preview.vue
289 lines (275 loc) · 8.09 KB
/
Preview.vue
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
<template>
<pre v-if="debug">{{ compiledCodeForDebug }}</pre>
<pre class="VueLive-error" v-if="error">{{ error }}</pre>
<component v-else-if="previewedComponent" :is="previewedComponent" :key="iteration">
<template v-for="(_, name) in $slots" v-slot:[name]="slotData">
<slot :name="name" v-bind="slotData" />
</template>
</component>
</template>
<script lang="ts">
import { markRaw, h, defineComponent } from "vue";
import * as Vue from "vue";
import {
compile as compileScript,
isCodeVueSfc,
addScopedStyle,
adaptCreateElement,
concatenate,
compileTemplateForEval
} from "vue-inbrowser-compiler-sucrase";
import checkTemplate, {
VueLiveParseTemplateError,
} from "./utils/checkTemplate";
import evalInContext from "./utils/evalInContext";
import requireAtRuntime from "./utils/requireAtRuntime";
export default defineComponent({
name: "VueLivePreviewComponent",
emits: ["error", "success", "detect-language"],
components: {},
errorCaptured(err) {
this.handleError(err);
},
props: {
debug: {
type: Boolean,
default: false
},
/**
* code rendered
*/
code: {
type: String,
required: true,
},
/**
* Hashtable of auto-registered components
* @example { DatePicker: VueDatePicker }
* @example { VueDatePicker }
*/
components: {
type: Object,
default: () => { },
},
/**
* Hashtable of auto-registered directives
* @example { Tooltip: VueTooltip }
* @example { VueTooltip }
*/
directives: {
type: Object,
default: () => { },
},
/**
* Hashtable of modules available in require and import statements
* in the code prop
* @example { lodash: require("lodash") }
* @example { moment: require("moment") }
*/
requires: {
type: Object,
default: () => { },
},
jsx: {
type: Boolean,
default: false,
},
/**
* Outside data to the preview
* @example { count: 1 }
*/
dataScope: {
type: Object,
default: () => { },
},
/**
* Avoid checking variables for availability it template
*/
checkVariableAvailability: {
type: Boolean,
default: true,
},
},
data() {
return {
scope: this.generateScope(),
previewedComponent: markRaw(defineComponent({
render: () => h("div"),
})),
iteration: 0,
error: false,
removeScopedStyle: () => { },
compiledCodeForDebug: "",
};
},
computed: {
requiresPlusVue(): Record<string, any> {
return { vue: Vue, ...this.requires };
},
},
created() {
this.renderComponent(this.code.trim());
},
destroyed() {
this.removeStyle();
},
watch: {
code(value) {
this.renderComponent(value.trim());
},
},
methods: {
/**
* Generates the Scope Id attribute value. It will be added to each
* tag if a style is applied to scope the style only to this example
*/
generateScope() {
return "v-xxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
},
handleError(e: any) {
/**
* Emitted every time the component rendered throws an error
* Catches runtime and compilation errors
* @event
* @property { Error } - the error thrown
*/
if (e.constructor === VueLiveParseTemplateError) {
e.message = `Cannot parse template expression: ${JSON.stringify(
(e.expression as any).content || e.expression
)}\n\n${e.message}`;
}
this.$emit("error", e);
this.error = e.message;
},
removeStyle() {
if (this.removeScopedStyle) {
this.removeScopedStyle();
}
},
async renderComponent(code: string) {
let options = defineComponent({});
let style;
const scopeAttribute = `data-${this.scope}`
try {
const renderedComponent = compileScript(
code,
this.jsx
? {
jsxPragma: "__pragma__(h)",
} : {},
scopeAttribute
);
if(this.debug){
this.compiledCodeForDebug = Object.entries(renderedComponent).map(([key, code]) => typeof code === 'string' ? `<${key}>\n${code}\n</${key}>` : '').join("\n\n")
}
style = renderedComponent.style;
if (renderedComponent.script) {
// if the compiled code contains a script it might be "just" a script
// if so, change scheme used by editor
// NOTE: vsg is a superset of JavaScript allowing
// the template to add javascript code above the template without fluff, very useful for examples
// NOTE2: vsg stands for vue-styleguidist
this.$emit("detect-language", isCodeVueSfc(code) ? "vue" : "vsg");
// compile and execute the script
// it can be:
// - a script setting up variables => we set up the data property of renderedComponent
// - a `new Vue()` script that will return a full config object
const calcOptions = async () => {
const script = renderedComponent.script;
const requires: typeof this.requires = {}
await Promise.allSettled(Object.keys(this.requiresPlusVue).map(async (key) => {
requires[key] = this.requiresPlusVue[key] instanceof Promise ? (await this.requiresPlusVue[key]).default : this.requiresPlusVue[key]
}))
options = defineComponent((evalInContext(
script,
(filepath) => requireAtRuntime(requires, filepath),
adaptCreateElement,
concatenate,
h
) || {}));
options.name = "VueLiveCompiledExample";
};
await calcOptions();
// In case the template is inlined in the script,
// we need to compile it
if (typeof options.template === "string") {
renderedComponent.template = options.template;
compileTemplateForEval(renderedComponent);
await calcOptions();
checkTemplate({
...(options as any),
template: options.template,
},
this.checkVariableAvailability);
delete options.template;
}
if (this.dataScope) {
const mergeData = { ...(options as any)?.data(), ...this.dataScope };
options.data = () => mergeData;
}
}
const template = renderedComponent.raw.template
if (template) {
checkTemplate({
...(options as any),
template,
},
this.checkVariableAvailability
);
}
} catch (e) {
this.handleError(e);
return;
}
if (this.components) {
if (!options.components) {
options.components = this.components;
} else {
options.components = { ...options.components, ...this.components };
}
}
if (this.directives) {
if (!options.directives) {
options.directives = this.directives;
} else {
options.directives = { ...options.directives, ...this.directives };
}
}
this.removeStyle();
if (style) {
// To add the scope id attribute to each item in the html
// this way when we add the scoped style sheet it will be applied
options.__scopeId = scopeAttribute;
this.removeScopedStyle = addScopedStyle(style, this.scope);
}
if (!options.render) {
this.handleError({
message:
"[Vue Live] no template or render function specified. Example cannot be rendered.",
});
return;
}
options.errorCaptured = (e: any) => {
this.handleError(e);
return false;
};
this.previewedComponent = markRaw(options);
this.iteration = this.iteration + 1;
this.error = false;
this.$emit("success");
},
},
});
</script>
<style>
.VueLive-error {
color: red;
text-align: left;
overflow: auto;
white-space: pre-wrap;
}
</style>