Line data Source code
1 : import { reactive } from 'vue'
2 :
3 : interface CachedMedia {
4 : src: string
5 : blob?: Blob
6 : objectUrl?: string
7 : error?: boolean
8 : isLoading: boolean
9 : lastAccessed: number
10 : }
11 :
12 : interface MediaCacheOptions {
13 : maxSize?: number
14 : maxAge?: number // in milliseconds
15 : preloadDistance?: number // pixels from viewport
16 : }
17 :
18 2355 : class MediaCacheService {
19 : public cache = reactive(new Map<string, CachedMedia>())
20 : private readonly maxSize: number
21 : private readonly maxAge: number
22 : private cleanupInterval: number | null = null
23 : private urlRefCount = new Map<string, number>()
24 : private readonly destroyOnUnload = () => this.destroy()
25 :
26 : constructor(options: MediaCacheOptions = {}) {
27 21 : this.maxSize = options.maxSize ?? 100
28 21 : this.maxAge = options.maxAge ?? 30 * 60 * 1000
29 21 : this.startCleanupInterval()
30 21 : window.addEventListener('beforeunload', this.destroyOnUnload)
31 : }
32 :
33 : private startCleanupInterval() {
34 : // Clean up every 5 minutes
35 21 : this.cleanupInterval = window.setInterval(
36 : () => {
37 0 : this.cleanup()
38 : },
39 : 5 * 60 * 1000
40 : )
41 : }
42 :
43 : private cleanup() {
44 0 : const now = Date.now()
45 0 : const keysToDelete: string[] = []
46 :
47 : // Find expired entries
48 0 : for (const [key, entry] of Array.from(this.cache.entries())) {
49 0 : if (now - entry.lastAccessed > this.maxAge) {
50 : // Only revoke object URL if no components are using it
51 0 : if (entry.objectUrl) {
52 0 : const refCount = this.urlRefCount.get(entry.objectUrl) || 0
53 : if (refCount === 0) {
54 0 : URL.revokeObjectURL(entry.objectUrl)
55 0 : this.urlRefCount.delete(entry.objectUrl)
56 0 : keysToDelete.push(key)
57 : }
58 : // Don't delete cache entry if URL is still in use
59 : } else {
60 0 : keysToDelete.push(key)
61 : }
62 : }
63 : }
64 :
65 : // Remove expired entries
66 0 : keysToDelete.forEach((key) => this.cache.delete(key))
67 :
68 : // If still over size limit, remove oldest entries that aren't in use
69 0 : if (this.cache.size > this.maxSize) {
70 0 : const entries = Array.from(this.cache.entries())
71 0 : entries.sort((a, b) => a[1].lastAccessed - b[1].lastAccessed)
72 :
73 0 : let removedCount = 0
74 0 : const targetRemoveCount = this.cache.size - this.maxSize
75 :
76 0 : for (const [key, entry] of entries) {
77 0 : if (removedCount >= targetRemoveCount) break
78 :
79 0 : if (entry.objectUrl) {
80 0 : const refCount = this.urlRefCount.get(entry.objectUrl) || 0
81 : if (refCount === 0) {
82 0 : URL.revokeObjectURL(entry.objectUrl)
83 0 : this.urlRefCount.delete(entry.objectUrl)
84 0 : this.cache.delete(key)
85 0 : removedCount++
86 : }
87 : } else {
88 0 : this.cache.delete(key)
89 0 : removedCount++
90 : }
91 : }
92 : }
93 : }
94 :
95 : async getCachedMedia(src: string): Promise<CachedMedia> {
96 162 : let entry = this.cache.get(src)
97 :
98 162 : if (entry) {
99 : // Update last accessed time
100 0 : entry.lastAccessed = Date.now()
101 0 : return entry
102 : }
103 :
104 : // Create new entry
105 162 : entry = {
106 : src,
107 : isLoading: true,
108 : lastAccessed: Date.now()
109 : }
110 :
111 : // Update cache with loading entry
112 162 : this.cache.set(src, entry)
113 :
114 162 : try {
115 : // Fetch the media
116 162 : const response = await fetch(src, { cache: 'force-cache' })
117 154 : if (!response.ok) {
118 0 : console.error(`Failed to fetch: ${response.status}`)
119 0 : const errorEntry: CachedMedia = {
120 : src,
121 : error: true,
122 : isLoading: false,
123 : lastAccessed: Date.now()
124 : }
125 0 : this.cache.set(src, errorEntry)
126 0 : return errorEntry
127 : }
128 :
129 152 : const blob = await response.blob()
130 : const objectUrl = URL.createObjectURL(blob)
131 :
132 : // Update entry with successful result
133 149 : const updatedEntry: CachedMedia = {
134 : src,
135 : blob,
136 : objectUrl,
137 : isLoading: false,
138 : lastAccessed: Date.now()
139 : }
140 :
141 149 : this.cache.set(src, updatedEntry)
142 149 : return updatedEntry
143 : } catch (error) {
144 0 : console.warn('Failed to cache media:', src, error)
145 :
146 : // Update entry with error
147 0 : const errorEntry: CachedMedia = {
148 : src,
149 : error: true,
150 : isLoading: false,
151 : lastAccessed: Date.now()
152 : }
153 :
154 0 : this.cache.set(src, errorEntry)
155 0 : return errorEntry
156 : }
157 : }
158 :
159 : acquireUrl(src: string): string | undefined {
160 149 : const entry = this.cache.get(src)
161 149 : if (entry?.objectUrl) {
162 149 : const currentCount = this.urlRefCount.get(entry.objectUrl) || 0
163 149 : this.urlRefCount.set(entry.objectUrl, currentCount + 1)
164 149 : return entry.objectUrl
165 : }
166 : return undefined
167 : }
168 :
169 : releaseUrl(src: string): void {
170 85 : const entry = this.cache.get(src)
171 85 : if (entry?.objectUrl) {
172 85 : const count = (this.urlRefCount.get(entry.objectUrl) || 1) - 1
173 85 : if (count <= 0) {
174 85 : URL.revokeObjectURL(entry.objectUrl)
175 85 : this.urlRefCount.delete(entry.objectUrl)
176 : // Remove from cache as well
177 85 : this.cache.delete(src)
178 : } else {
179 0 : this.urlRefCount.set(entry.objectUrl, count)
180 : }
181 : }
182 : }
183 :
184 : clearCache() {
185 : // Revoke all object URLs
186 0 : for (const entry of Array.from(this.cache.values())) {
187 0 : if (entry.objectUrl) {
188 0 : URL.revokeObjectURL(entry.objectUrl)
189 : }
190 : }
191 0 : this.cache.clear()
192 0 : this.urlRefCount.clear()
193 : }
194 :
195 : destroy() {
196 0 : window.removeEventListener('beforeunload', this.destroyOnUnload)
197 0 : if (this.cleanupInterval) {
198 0 : clearInterval(this.cleanupInterval)
199 0 : this.cleanupInterval = null
200 : }
201 0 : this.clearCache()
202 : }
203 : }
204 :
205 2355 : let mediaCacheInstance: MediaCacheService | null = null
206 :
207 : /** Destroys the shared media cache, releasing its unload listener and cleanup interval. */
208 : export function disposeMediaCache() {
209 : mediaCacheInstance?.destroy()
210 : mediaCacheInstance = null
211 : }
212 :
213 : import.meta.hot?.dispose(disposeMediaCache)
214 :
215 499 : export function useMediaCache(options?: MediaCacheOptions) {
216 499 : if (!mediaCacheInstance) {
217 21 : mediaCacheInstance = new MediaCacheService(options)
218 : }
219 :
220 499 : const getCachedMedia = (src: string) =>
221 : mediaCacheInstance!.getCachedMedia(src)
222 499 : const clearCache = () => mediaCacheInstance!.clearCache()
223 499 : const acquireUrl = (src: string) => mediaCacheInstance!.acquireUrl(src)
224 499 : const releaseUrl = (src: string) => mediaCacheInstance!.releaseUrl(src)
225 :
226 499 : return {
227 : getCachedMedia,
228 : clearCache,
229 : acquireUrl,
230 : releaseUrl,
231 : cache: mediaCacheInstance.cache
232 : }
233 : }
|