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
|
<script>
import SafeHtml from '~/vue_shared/directives/safe_html';
import languageLoader from '~/content_editor/services/highlight_js_language_loader';
import CodeBlock from './code_block.vue';
export default {
name: 'CodeBlockHighlighted',
directives: {
SafeHtml,
},
components: {
CodeBlock,
},
props: {
code: {
type: String,
required: true,
},
language: {
type: String,
required: true,
},
maxHeight: {
type: String,
required: false,
default: 'initial',
},
},
data() {
return {
hljs: null,
languageLoaded: false,
};
},
computed: {
highlighted() {
if (this.hljs && this.languageLoaded) {
return this.hljs.highlight(this.code, { language: this.language }).value;
}
return this.code;
},
},
async mounted() {
this.hljs = await this.loadHighlightJS();
if (this.language) {
await this.loadLanguage();
}
},
methods: {
async loadLanguage() {
try {
const { default: languageDefinition } = await languageLoader[this.language]();
this.hljs.registerLanguage(this.language, languageDefinition);
this.languageLoaded = true;
} catch (e) {
this.$emit('error', e);
}
},
loadHighlightJS() {
return import('highlight.js/lib/core');
},
},
};
</script>
<template>
<code-block :max-height="maxHeight" class="highlight">
<span v-safe-html="highlighted"></span>
</code-block>
</template>
|