Line data Source code
1 : <template>
2 3 : <div class="wrap-break-word">
3 : <div v-if="!hasMarkdown" v-text="text" />
4 : <div v-else>
5 0 : <template v-for="(segment, index) in parsedSegments" :key="index">
6 : <a
7 : v-if="segment.type === 'link' && 'url' in segment"
8 : :href="segment.url"
9 : target="_blank"
10 : rel="noopener noreferrer"
11 : class="hover:underline"
12 : >
13 : <span class="text-blue-600">{{ segment.text }}</span>
14 : </a>
15 : <strong v-else-if="segment.type === 'bold'">{{ segment.text }}</strong>
16 : <em v-else-if="segment.type === 'italic'">{{ segment.text }}</em>
17 : <code
18 : v-else-if="segment.type === 'code'"
19 : class="rounded-sm px-1 py-0.5 text-xs"
20 : >{{ segment.text }}</code
21 : >
22 : <span v-else>{{ segment.text }}</span>
23 : </template>
24 : </div>
25 : </div>
26 : </template>
27 :
28 : <script setup lang="ts">
29 : import { computed } from 'vue'
30 :
31 : const { text } = defineProps<{
32 : text: string
33 : }>()
34 :
35 : type MarkdownSegment = {
36 : type: 'text' | 'link' | 'bold' | 'italic' | 'code'
37 : text: string
38 : url?: string
39 : }
40 :
41 3 : const hasMarkdown = computed(() => {
42 : const hasMarkdown =
43 : /(\[.*?\]\(.*?\)|(\*\*|__)(.*?)(\*\*|__)|(\*|_)(.*?)(\*|_)|`(.*?)`)/.test(
44 : text
45 : )
46 3 : return hasMarkdown
47 : })
48 :
49 3 : const parsedSegments = computed(() => {
50 0 : if (!hasMarkdown.value) return [{ type: 'text', text }]
51 :
52 0 : const segments: MarkdownSegment[] = []
53 0 : const remainingText = text
54 0 : let lastIndex: number = 0
55 :
56 0 : const linkRegex = /\[(.*?)\]\((.*?)\)/g
57 0 : let linkMatch: RegExpExecArray | null
58 :
59 0 : while ((linkMatch = linkRegex.exec(remainingText)) !== null) {
60 0 : if (linkMatch.index > lastIndex) {
61 0 : segments.push({
62 : type: 'text',
63 : text: remainingText.substring(lastIndex, linkMatch.index)
64 : })
65 : }
66 :
67 0 : segments.push({
68 : type: 'link',
69 : text: linkMatch[1],
70 : url: linkMatch[2]
71 : })
72 :
73 0 : lastIndex = linkMatch.index + linkMatch[0].length
74 : }
75 :
76 0 : if (lastIndex < remainingText.length) {
77 0 : let rest = remainingText.substring(lastIndex)
78 :
79 0 : rest = rest.replace(/(\*\*|__)(.*?)(\*\*|__)/g, (_, __, p2) => {
80 0 : segments.push({ type: 'bold', text: p2 })
81 0 : return ''
82 : })
83 :
84 0 : rest = rest.replace(/(\*|_)(.*?)(\*|_)/g, (_, __, p2) => {
85 0 : segments.push({ type: 'italic', text: p2 })
86 0 : return ''
87 : })
88 :
89 0 : rest = rest.replace(/`(.*?)`/g, (_, p1) => {
90 0 : segments.push({ type: 'code', text: p1 })
91 0 : return ''
92 : })
93 :
94 0 : if (rest) {
95 0 : segments.push({ type: 'text', text: rest })
96 : }
97 : }
98 :
99 0 : return segments
100 : })
101 : </script>
|