All files / repo/src/shared/utils imageCache.ts

70.45% Statements 31/44
77.77% Branches 7/9
42.85% Functions 3/7
70.45% Lines 31/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 531x   1x 1x 1x 1x 1x 1x   1x         1x 1x 1x 1x   2x 2x 2x   2x 2x 1x 1x             1x 1x 1x 1x   1x   1x 1x         1x 2x 2x   2x 2x  
export const preloadedImages: Record<string, HTMLImageElement> = {};
 
export function preloadImagesSync(paths: string[]) {
  paths.forEach((path) => {
    const lowerPath = path.toLowerCase();
    if (!preloadedImages[lowerPath]) {
      const img = new Image();
      img.src = path;
 
      img.onerror = () => {
        console.warn(`Image preload failed: ${path}`);
        delete preloadedImages[lowerPath];
      };
 
      preloadedImages[lowerPath] = img;
    }
  });
}
 
export async function preloadImagesWithAwait(paths: string[]) {
  const promises = paths.map((path) => {
    const lowerPath = path.toLowerCase();
 
    return new Promise<void>((resolve) => {
      if (preloadedImages[lowerPath]) {
        const img = preloadedImages[lowerPath];
        if (img.complete) return resolve();
        img.onload = () => resolve();
        img.onerror = () => {
          console.warn(`Image preload failed: ${path}`);
          delete preloadedImages[lowerPath];
          resolve();
        };
      } else {
        const img = new Image();
        img.src = path;
        preloadedImages[lowerPath] = img;
 
        if (img.complete) return resolve();
 
        img.onload = () => resolve();
        img.onerror = () => {
          console.warn(`Image preload failed: ${path}`);
          delete preloadedImages[lowerPath];
          resolve();
        };
      }
    });
  });
 
  await Promise.all(promises);
}