1 | <template>
|
2 | <section class="sandbox">
|
3 | <div ref="monaco" class="sandbox-monaco" :style="monacoStyle"></div>
|
4 | </section>
|
5 | </template>
|
6 |
|
7 | <script>
|
8 | import * as monaco from 'monaco-editor';
|
9 |
|
10 | import loadTheme from './sandboxTheme.js';
|
11 | import { mapState } from 'vuex';
|
12 | export default {
|
13 | props: {
|
14 | language: {
|
15 | require: true,
|
16 | type: String
|
17 | },
|
18 | value: {
|
19 | type: String,
|
20 | default: ''
|
21 | },
|
22 | isFolded: {
|
23 | type: Boolean,
|
24 | default: false
|
25 | },
|
26 | editorHook: {
|
27 | type: Function,
|
28 | default: null
|
29 | }
|
30 | },
|
31 | watch: {
|
32 | value(val) {
|
33 | if (val) this.monacoEditor.setValue(val);
|
34 | }
|
35 | },
|
36 | computed: {
|
37 | ...mapState(['config']),
|
38 | monacoStyle() {
|
39 | if (this.config.editorViewMode === 'waterfall') {
|
40 | return {
|
41 | height: this.isFolded ? 0 : `${this.editorLineCount * 18}px`
|
42 | };
|
43 | }
|
44 | return {};
|
45 | }
|
46 | },
|
47 | data() {
|
48 | return {
|
49 | showPartial: true,
|
50 | monacoEditor: null,
|
51 | editorLineCount: 1
|
52 | };
|
53 | },
|
54 | mounted() {
|
55 | this.initMonaco();
|
56 | },
|
57 | destroyed() {
|
58 | if (this.monacoEditor) {
|
59 | this.monacoEditor.getModel().dispose();
|
60 | this.monacoEditor.dispose();
|
61 | }
|
62 | },
|
63 | methods: {
|
64 | initMonaco() {
|
65 | let model;
|
66 | if (this.editorHook) {
|
67 | model = this.editorHook(monaco, this.value, this.language);
|
68 | }
|
69 |
|
70 |
|
71 | loadTheme(monaco);
|
72 |
|
73 | this.monacoEditor = monaco.editor.create(
|
74 | this.$refs.monaco,
|
75 | Object.assign(
|
76 | {
|
77 | language: this.language,
|
78 | automaticLayout: true,
|
79 | theme: this.config.boxTheme,
|
80 | minimap: {
|
81 | enabled: false
|
82 | },
|
83 | smoothScrolling: true,
|
84 | scrollBeyondLastLine: false
|
85 | },
|
86 | this.config.editorOptions
|
87 | )
|
88 | );
|
89 | this.monacoEditor.onDidChangeModelContent(() => {
|
90 | this.editorLineCount = this.monacoEditor.getModel().getLineCount();
|
91 | });
|
92 |
|
93 | if (model) {
|
94 | this.monacoEditor.setModel(model);
|
95 | } else {
|
96 | this.monacoEditor.setValue(this.value);
|
97 | }
|
98 |
|
99 | this.bindContentChangeListener();
|
100 | },
|
101 | bindContentChangeListener() {
|
102 | if (!this.monacoEditor) throw new Error('editor is not mounted');
|
103 | this.monacoEditor.onDidChangeModelContent(() => {
|
104 | const value = this.monacoEditor.getValue();
|
105 | this.$emit('input', value);
|
106 | });
|
107 | }
|
108 | }
|
109 | };
|
110 | </script>
|
111 |
|
112 | <style lang="scss">
|
113 | @import '@/css/index.scss';
|
114 | .sandbox {
|
115 | &-monaco {
|
116 | height: 100%;
|
117 | overflow: hidden;
|
118 | transition: 300ms all ease-out;
|
119 | }
|
120 | }
|
121 | </style>
|