import type { PhotoRecord } from '../types'; import { getAsset, putAsset } from './db'; const CACHE_LIMIT = 6; const cache = new Map(); /** * Grid/filmstrip thumbnail URL. The version stamp changes when the saved edit is * re-rendered, so the browser does not keep showing the pre-edit thumbnail. */ export function thumbSrc(photo: PhotoRecord): string { if (!photo.thumbUrl) return photo.thumb; return photo.thumbVersion ? `${photo.thumbUrl}?v=${photo.thumbVersion}` : photo.thumbUrl; } /** Where to fetch the original (or raw proxy) when it is not cached on this device. */ export function remoteAssetUrl(photo: PhotoRecord): string { if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`; return `/api/photos/${encodeURIComponent(photo.id)}/original`; } async function fetchRemote(photo: PhotoRecord): Promise { try { const res = await fetch(remoteAssetUrl(photo), { credentials: 'same-origin' }); if (!res.ok) return null; const blob = await res.blob(); // Cache it locally so the photo keeps working offline after the first look. await putAsset(photo.id, blob).catch(() => undefined); return blob; } catch { return null; } } export async function getBitmap(photo: PhotoRecord): Promise { const hit = cache.get(photo.id); if (hit) { cache.delete(photo.id); cache.set(photo.id, hit); return hit; } let blob = await getAsset(photo.id); if (!blob) blob = (await fetchRemote(photo)) ?? undefined; if (!blob) { throw new Error( photo.raw ? 'This raw file has no editable proxy yet. Sign in to the server and sync to fetch it.' : 'Original image data is missing from browser storage', ); } // Apply EXIF orientation so the pixels the editor works on are upright. const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' }); cache.set(photo.id, bitmap); while (cache.size > CACHE_LIMIT) { const first = cache.keys().next(); if (first.done) break; const old = cache.get(first.value); cache.delete(first.value); old?.close(); } return bitmap; } export function evictBitmap(photoId: string) { const bmp = cache.get(photoId); if (!bmp) return; cache.delete(photoId); bmp.close(); } export function clearBitmapCache() { for (const bmp of cache.values()) bmp.close(); cache.clear(); }