๐Ÿ“ฆ Akryum / guijs

๐Ÿ“„ PackageLogo.vue ยท 77 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77<script>
import { ref, watch } from '@vue/composition-api'
import genericLogo from '@/assets/package.png'
import { proxy } from '@/util/proxy'

const cache = {}

export default {
  props: {
    pkg: {
      type: Object,
      required: true,
    },
  },

  setup (props) {
    const src = ref(null)

    watch(() => props.pkg.id, async id => {
      if (cache[id] !== undefined) {
        src.value = cache[id]
      } else {
        src.value = null
        await tryLogo(id, 'logo.svg')
        await tryLogo(id, 'logo.png')
      }
    })

    function tryLogo (id, filename) {
      return new Promise(resolve => {
        const checkId = () => id === props.pkg.id

        if (!checkId()) {
          return resolve(false)
        }

        const img = new Image()
        img.onload = () => {
          if (!checkId()) {
            resolve(false)
          } else {
            src.value = cache[id] = img.src
          }
        }
        img.onerror = () => {
          cache[id] = null
          resolve(false)
        }
        img.src = `https://unpkg.com/${props.pkg.id}/${filename}`
      })
    }

    function onError () {
      src.value = genericLogo
    }

    return {
      src,
      genericLogo,
      onError,
      proxy,
    }
  },
}
</script>

<template>
  <div>
    <img
      :src="src || pkg.defaultLogo ? proxy(src || pkg.defaultLogo) : genericLogo"
      :alt="`${pkg.id} logo`"
      class="w-full h-full rounded overflow-hidden text-transparent"
      @error="onError()"
    >
  </div>
</template>