Line data Source code
1 16 : <template>
2 : <!-- eslint-disable-next-line vue/no-v-html -->
3 76 : <span v-if="as === 'span'" v-bind="$attrs" v-html="sanitizedHtml" />
4 : <!-- eslint-disable-next-line vue/no-v-html -->
5 : <div v-else v-bind="$attrs" v-html="sanitizedHtml" />
6 : </template>
7 :
8 : <script setup lang="ts">
9 : import { default as createDOMPurify } from 'dompurify'
10 : import { computed } from 'vue'
11 :
12 75 : const purifier = createDOMPurify(window)
13 :
14 : defineOptions({ inheritAttrs: false })
15 :
16 : const {
17 : html,
18 : as = 'div',
19 : profile = 'default'
20 : } = defineProps<{
21 : html: string
22 : as?: 'div' | 'span'
23 : profile?: 'default' | 'highlighted-code'
24 : }>()
25 :
26 75 : purifier.addHook('uponSanitizeAttribute', (node, data) => {
27 185 : if (data.attrName !== 'style') return
28 185 : if (profile !== 'highlighted-code' || !(node instanceof HTMLSpanElement)) {
29 0 : data.keepAttr = false
30 0 : return
31 : }
32 :
33 0 : const source = document.createElement('span').style
34 0 : const allowed = document.createElement('span').style
35 0 : source.cssText = data.attrValue
36 0 : for (const property of ['color', 'font-style', 'font-weight']) {
37 0 : allowed.setProperty(property, source.getPropertyValue(property))
38 : }
39 0 : data.attrValue = allowed.cssText
40 0 : data.keepAttr = data.attrValue.length > 0
41 : })
42 :
43 75 : const sanitizedHtml = computed(() =>
44 : purifier.sanitize(html, {
45 : ADD_TAGS: ['video', 'source'],
46 : ADD_ATTR: [
47 : 'controls',
48 : 'autoplay',
49 : 'loop',
50 : 'muted',
51 : 'preload',
52 : 'poster',
53 : 'target',
54 : 'rel'
55 : ],
56 : FORBID_TAGS: ['form', 'input', 'button'],
57 : FORBID_ATTR: profile === 'highlighted-code' ? [] : ['style']
58 : })
59 : )
60 : </script>
|