Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support icon by svg tag #3847

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 37 additions & 8 deletions src/client/theme-default/components/VPImage.vue
Original file line number Diff line number Diff line change
@@ -1,24 +1,53 @@
<script setup lang="ts">
import type { DefaultTheme } from 'vitepress/theme'
import { withBase } from 'vitepress'
import { computed, ref, useAttrs, watch } from 'vue'

defineProps<{
const props = defineProps<{
image: DefaultTheme.ThemeableImage
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 })
</script>

<template>
<template v-if="image">
<img
v-if="typeof image === 'string' || 'src' in image"
class="VPImage"
v-bind="typeof image === 'string' ? $attrs : { ...image, ...$attrs }"
:src="withBase(typeof image === 'string' ? image : image.src)"
:alt="alt ?? (typeof image === 'string' ? '' : image.alt || '')"
/>
<template v-if="typeof image === 'string' || 'src' in image">
<div v-if="computedSrc.endsWith('.svg')" ref="svgWrapperEl" class="VPImage" />
<img
v-else
class="VPImage"
v-bind="elAttrs"
:src="computedSrc"
:alt="alt ?? (typeof image === 'string' ? '' : image.alt || '')"
/>
</template>
<template v-else>
<VPImage
class="dark"
Expand Down