feat: support icon by svg tag

pull/3847/head
GweesinChan 1 year ago
parent 0048787206
commit a78426fa6e

@ -1,24 +1,53 @@
<script setup lang="ts"> <script setup lang="ts">
import type { DefaultTheme } from 'vitepress/theme' import type { DefaultTheme } from 'vitepress/theme'
import { withBase } from 'vitepress' import { withBase } from 'vitepress'
import { computed, ref, useAttrs, watch } from 'vue'
defineProps<{ const props = defineProps<{
image: DefaultTheme.ThemeableImage image: DefaultTheme.ThemeableImage
alt?: string alt?: string
}>() }>()
const $attrs = useAttrs()
const elAttrs = computed(() => typeof props.image === 'string' ? $attrs : { ...props.image, ...$attrs })
const computedSrc = computed(() => withBase(typeof props.image === 'string' ? props.image : props.image.src))
const svgWrapperEl = ref<HTMLElement | null>(null)
watch(computedSrc, async () => {
if (!computedSrc.value.endsWith('.svg')) {
return
}
fetch(computedSrc.value)
.then((res) => res.text())
.then((data) => {
svgWrapperEl.value!.innerHTML = data
const svgEl = svgWrapperEl.value!.querySelector('svg')
// iterate over all attributes and set them on the svg element
for (const [key, value] of Object.entries(elAttrs.value)) {
svgEl!.setAttribute(key, value as string)
}
})
}, { immediate: true })
defineOptions({ inheritAttrs: false }) defineOptions({ inheritAttrs: false })
</script> </script>
<template> <template>
<template v-if="image"> <template v-if="image">
<img <template v-if="typeof image === 'string' || 'src' in image">
v-if="typeof image === 'string' || 'src' in image" <div v-if="computedSrc.endsWith('.svg')" ref="svgWrapperEl" class="VPImage" />
class="VPImage" <img
v-bind="typeof image === 'string' ? $attrs : { ...image, ...$attrs }" v-else
:src="withBase(typeof image === 'string' ? image : image.src)" class="VPImage"
:alt="alt ?? (typeof image === 'string' ? '' : image.alt || '')" v-bind="elAttrs"
/> :src="computedSrc"
:alt="alt ?? (typeof image === 'string' ? '' : image.alt || '')"
/>
</template>
<template v-else> <template v-else>
<VPImage <VPImage
class="dark" class="dark"

Loading…
Cancel
Save