docs/.vitepress/theme/components/extrepo/LazyIcon.vue

97 lines · 2088 bytes

 1<script setup lang="ts">
 2import { onBeforeUnmount, onMounted, ref } from 'vue'
 3import { iconResultCache, observeIcon } from './iconObserver'
 4import { scheduleIconLoad } from './iconQueue'
 5
 6const props = defineProps<{
 7  src?: string
 8  alt: string
 9}>()
10
11const rootRef = ref<HTMLElement>()
12const loaded = ref(false)
13const failed = ref(false)
14let unobserve: (() => void) | undefined
15let cancelLoad: (() => void) | undefined
16
17function startLoad() {
18  if (!props.src) return
19  const cached = iconResultCache.get(props.src)
20  if (cached !== undefined) {
21    if (cached) loaded.value = true
22    else failed.value = true
23    return
24  }
25  cancelLoad = scheduleIconLoad(() =>
26    new Promise<void>((resolve) => {
27      const img = new Image()
28      img.onload = () => {
29        loaded.value = true
30        iconResultCache.set(props.src!, true)
31        resolve()
32      }
33      img.onerror = () => {
34        failed.value = true
35        iconResultCache.set(props.src!, false)
36        resolve()
37      }
38      img.src = props.src!
39    })
40  )
41}
42
43onMounted(() => {
44  const el = rootRef.value
45  if (!el) return
46  if (!props.src) return
47  unobserve = observeIcon(el, () => {
48    startLoad()
49  })
50})
51
52onBeforeUnmount(() => {
53  unobserve?.()
54  cancelLoad?.()
55})
56</script>
57
58<template>
59  <span ref="rootRef" class="ext-site-icon-slot">
60    <img v-if="loaded" :src="src" :alt="alt" loading="lazy" decoding="async" />
61    <span
62      v-else
63      class="ext-site-icon-fallback"
64      :class="{
65        'i-lucide:globe': !src || failed,
66        'ext-site-icon-loading': src && !failed
67      }"
68    />
69  </span>
70</template>
71
72<style scoped>
73.ext-site-icon-slot {
74  width: 18px;
75  height: 18px;
76  flex-shrink: 0;
77  display: inline-flex;
78}
79.ext-site-icon-slot img {
80  width: 18px;
81  height: 18px;
82  border-radius: 4px;
83  object-fit: contain;
84}
85.ext-site-icon-fallback {
86  display: flex;
87  align-items: center;
88  justify-content: center;
89  color: var(--vp-c-text-3);
90  width: 18px;
91  height: 18px;
92}
93.ext-site-icon-loading {
94  background-color: var(--vp-c-bg-mute, var(--vp-c-bg-soft));
95  border-radius: 4px;
96}
97</style>