44 lines
1.6 KiB
Vue
44 lines
1.6 KiB
Vue
<script setup lang="ts">
|
||
import { computed } from 'vue'
|
||
|
||
const props = defineProps<{ text: string }>()
|
||
const emit = defineEmits<{ error: [message: string] }>()
|
||
const internalBrowser = window.xhchat?.openBrowser
|
||
|
||
const parts = computed(() => {
|
||
const text = props.text
|
||
const segments: { text: string; url?: string }[] = []
|
||
let offset = 0
|
||
for (const match of text.matchAll(/https?:\/\/[^\s<>"']+/giu)) {
|
||
const label = match[0].replace(/[.,!?;:,。!?;:、))\]】]+$/u, '')
|
||
if (label.length > 4096) continue
|
||
try {
|
||
const url = new URL(label)
|
||
if (url.username || url.password ||
|
||
(url.protocol !== 'https:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) continue
|
||
if (match.index > offset) segments.push({ text: text.slice(offset, match.index) })
|
||
segments.push({ text: label, url: url.href })
|
||
offset = match.index + label.length
|
||
} catch {
|
||
continue
|
||
}
|
||
}
|
||
if (offset < text.length) segments.push({ text: text.slice(offset) })
|
||
return segments
|
||
})
|
||
|
||
async function open(url: string) {
|
||
try {
|
||
await internalBrowser?.(url)
|
||
} catch (cause) {
|
||
emit('error', cause instanceof Error ? cause.message : '无法打开网页链接')
|
||
}
|
||
}
|
||
</script>
|
||
|
||
<template>
|
||
<span><template v-for="(part, index) in parts" :key="index"><button v-if="part.url && internalBrowser"
|
||
type="button" class="chat-link" @click="open(part.url)">{{ part.text }}</button><a v-else-if="part.url"
|
||
class="chat-link" :href="part.url" target="_blank" rel="noopener noreferrer">{{ part.text }}</a><template v-else>{{ part.text }}</template></template></span>
|
||
</template>
|