aboutsummaryrefslogtreecommitdiffstats
path: root/apps/updatenotification/src/composables/useMarkdown.ts
blob: 71b496a10b366534d878e9cf2c92a0e727fd1900 (plain)
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
/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
import type { Ref } from 'vue'

import { marked } from 'marked'
import { computed } from 'vue'
import dompurify from 'dompurify'

export const useMarkdown = (text: Ref<string|undefined|null>, minHeadingLevel: Ref<number|undefined>) => {
	const minHeading = computed(() => Math.min(Math.max(minHeadingLevel.value ?? 1, 1), 6))
	const renderer = new marked.Renderer()

	renderer.link = function(href, title, text) {
		let out = `<a href="${href}" rel="noreferrer noopener" target="_blank"`
		if (title) {
			out += ' title="' + title + '"'
		}
		out += '>' + text + '</a>'
		return out
	}

	renderer.image = function(href, title, text) {
		if (text) {
			return text
		}
		return title ?? ''
	}

	renderer.heading = (text: string, level: number) => {
		const headingLevel = Math.max(minHeading.value, level)
		return `<h${headingLevel}>${text}</h${headingLevel}>`
	}

	const html = computed(() => dompurify.sanitize(
		marked((text.value ?? '').trim(), {
			renderer,
			gfm: false,
			breaks: false,
			pedantic: false,
		}),
		{
			SAFE_FOR_JQUERY: true,
			ALLOWED_TAGS: [
				'h1',
				'h2',
				'h3',
				'h4',
				'h5',
				'h6',
				'strong',
				'p',
				'a',
				'ul',
				'ol',
				'li',
				'em',
				'del',
				'blockquote',
			],
		},
	))

	return { html }
}