返回 slidev
usePreloadImages.ts
根目录 / packages / client / composables / usePreloadImages.ts
1 import type { SlideRoute } from '@slidev/types'
2 import type { ComputedRef, Ref } from 'vue'
3 import { computed, ref, watchEffect } from 'vue'
4 import configs from '#slidev/configs'
5
6 const loaded = new Set<string>()
7 const loading = new Set<string>()
8 const RE_TRAILING_SLASH = /\/$/
9
10 function resolveUrl(url: string): string {
11 if (url.startsWith('http') || url.startsWith('//'))
12 return url
13 const base = (import.meta.env.BASE_URL || '/').replace(RE_TRAILING_SLASH, '')
14 return `${base}${url.startsWith('/')
15 ? url
16 : `/${url}`}`
17 }
18
19 const RETRY_LIMIT = 2
20 const retries = new Map<string, number>()
21
22 const preloadedCount = ref(0)
23 const totalImagesCount = ref(0)
24
25 /**
26 * Progress of slide-image preloading, from 0 to 1 (1 when every preloadable
27 * image in the deck has loaded, or when the deck has no images).
28 */
29 export const preloadProgress = computed(() =>
30 totalImagesCount.value === 0
31 ? 1
32 : preloadedCount.value / totalImagesCount.value,
33 )
34
35 /** Whether all preloadable slide images have finished loading. */
36 export const preloadComplete = computed(() => preloadProgress.value >= 1)
37
38 function preloadImage(url: string): void {
39 const resolved = resolveUrl(url)
40 if (loaded.has(resolved) || loading.has(resolved))
41 return
42 loading.add(resolved)
43 const img = new Image()
44 img.onload = () => {
45 loading.delete(resolved)
46 loaded.add(resolved)
47 retries.delete(resolved)
48 preloadedCount.value = loaded.size
49 }
50 img.onerror = () => {
51 loading.delete(resolved)
52 // Retry transient preload failures (e.g. flaky network) instead of silently
53 // giving up; bounded so genuinely-missing assets aren't hammered.
54 const attempts = retries.get(resolved) ?? 0
55 if (attempts < RETRY_LIMIT) {
56 retries.set(resolved, attempts + 1)
57 setTimeout(preloadImage, 1000 * (attempts + 1), url)
58 }
59 }
60 img.src = resolved
61 }
62
63 function preloadSlideImages(route: SlideRoute): void {
64 const images = route.meta?.slide?.images
65 if (images?.length) {
66 for (const url of images)
67 preloadImage(url)
68 }
69 }
70
71 export function usePreloadImages(
72 currentRoute: ComputedRef<SlideRoute>,
73 prevRoute: ComputedRef<SlideRoute>,
74 nextRoute: ComputedRef<SlideRoute>,
75 slides: Ref<SlideRoute[]>,
76 ): void {
77 const config = configs.preloadImages
78 if (config === false)
79 return
80
81 const ahead = (typeof config === 'object' && config?.ahead) || 3
82
83 // Track total preloadable images across the deck for progress reporting
84 watchEffect(() => {
85 const all = slides.value
86 if (!all?.length)
87 return
88 const urls = new Set<string>()
89 for (const route of all) {
90 for (const url of route.meta?.slide?.images ?? [])
91 urls.add(resolveUrl(url))
92 }
93 totalImagesCount.value = urls.size
94 })
95
96 // Preload current + prev + next + look-ahead window
97 watchEffect(() => {
98 const current = currentRoute.value
99 const all = slides.value
100 if (!current || !all?.length)
101 return
102
103 preloadSlideImages(current)
104 preloadSlideImages(prevRoute.value)
105 preloadSlideImages(nextRoute.value)
106
107 // Preload ahead window
108 const currentIdx = current.no - 1
109 for (let i = 1; i <= ahead; i++) {
110 const idx = currentIdx + i
111 if (idx < all.length)
112 preloadSlideImages(all[idx])
113 }
114 })
115
116 // Preload all remaining slides after 3s
117 watchEffect((onCleanup) => {
118 const all = slides.value
119 const timeout = setTimeout(() => {
120 if (all?.length) {
121 for (const route of all)
122 preloadSlideImages(route)
123 }
124 }, 3000)
125 onCleanup(() => clearTimeout(timeout))
126 })
127 }
128
128 lines TYPESCRIPT