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

7b774cae81351666b54bdca55c379582beb10043
wotaku/docs/.vitepress/theme/components/extrepo/LazyIcon.vue
Duck sora05e19b07cd 4 months ago

49 lines · 1292 bytes

 1<script setup lang="ts">
 2import { onBeforeUnmount, onMounted, ref } from 'vue'
 3import { scheduleIconLoad } from './iconQueue'
 4
 5const props = defineProps<{
 6  src?: string
 7  alt: string
 8}>()
 9
10const rootRef = ref<HTMLElement>()
11const loaded = ref(false)
12const failed = ref(false)
13let observer: IntersectionObserver | undefined
14
15onMounted(() => {
16  const el = rootRef.value
17  if (!el || !props.src) return
18  // Preload a bit before the card is actually visible so it's ready by the time it scrolls in.
19  observer = new IntersectionObserver((entries) => {
20    if (!entries.some(entry => entry.isIntersecting)) return
21    observer?.disconnect()
22    scheduleIconLoad(() => new Promise<void>((resolve) => {
23      const img = new Image()
24      img.onload = () => {
25        loaded.value = true
26        resolve()
27      }
28      img.onerror = () => {
29        failed.value = true
30        resolve()
31      }
32      img.src = props.src!
33    }))
34  }, { rootMargin: '200px' })
35  observer.observe(el)
36})
37
38onBeforeUnmount(() => observer?.disconnect())
39</script>
40
41<template>
42  <img v-if="loaded" ref="rootRef" :src="src" :alt="alt" />
43  <span
44    v-else
45    ref="rootRef"
46    class="ext-site-icon-fallback"
47    :class="{ 'i-lucide:globe': !src || failed, 'ext-site-icon-loading': src && !failed }"
48  />
49</template>
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form