docs/.vitepress/theme/components/LibrarySize.vue

53 lines · 1339 bytes

 1<script setup lang="ts">
 2
 3import { onMounted, ref } from 'vue'
 4
 5const props = defineProps<{ name: string }>()
 6
 7const LIBRARY_URL = 'https://library-sizes.duckling.workers.dev/'
 8
 9interface Entry {
10  size: string
11  updated: string
12}
13type Library = {
14  anime: Record<string, Entry>
15  manga: Record<string, Entry>
16  donghua: Record<string, Entry>
17  raw: Record<string, Entry>
18}
19
20// One shared request per page, regardless of how many markers are used.
21let pending: Promise<Library> | null = null
22
23function load(): Promise<Library> {
24  if (!pending) {
25    pending = fetch(LIBRARY_URL)
26      .then(res => (res.ok ? res.json() : Promise.reject(res.status)))
27      .catch(() => ({ anime: {}, manga: {}, donghua: {}, raw: {} }) as Library)
28  }
29  return pending
30}
31
32const normalize = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '')
33
34function lookup(lib: Library, name: string): string | undefined {
35  const wanted = normalize(name)
36  for (const section of [lib.raw, lib.manga, lib.anime, lib.donghua]) {
37    for (const [site, entry] of Object.entries(section ?? {})) {
38      if (normalize(site) === wanted) return entry.size
39    }
40  }
41  return undefined
42}
43
44const size = ref('')
45
46onMounted(async () => {
47  size.value = lookup(await load(), props.name) ?? ''
48})
49</script>
50
51<template>
52  <span class="library-size">{{ size }}</span>
53</template>