M2-M3: tile loader and album viewer

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5.5 committed 2026-11-04 04:22:20 -08:00
1 parent 18a397653a
commit 6d39dc1713
24 files changed
+2687 -16

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
export interface CachedTile {
bitmap: ImageBitmap;
bytes: number;
at: number;
}
interface NavigatorWithMemory extends Navigator {
deviceMemory?: number;
}
export function cacheBudget(): number {
const mb = 1024 * 1024;
const memory = (navigator as NavigatorWithMemory).deviceMemory;
const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
const smallScreen = Math.min(screen.width, screen.height) <= 820;
if ((memory !== undefined && memory <= 4) || (coarse && smallScreen)) {
return 120 * mb;
}
return 250 * mb;
}
export class TileCache {
private readonly entries = new Map<string, CachedTile>();
private used = 0;
constructor(private readonly budget: number) {}
get(id: string): CachedTile | undefined {
const entry = this.entries.get(id);
if (entry) {
this.entries.delete(id);
this.entries.set(id, entry);
}
return entry;
}
has(id: string): boolean {
return this.entries.has(id);
}
put(id: string, bitmap: ImageBitmap): void {
const existing = this.entries.get(id);
if (existing) {
if (existing.bitmap !== bitmap) {
bitmap.close();
}
return;
}
const bytes = bitmap.width * bitmap.height * 4;
this.entries.set(id, { bitmap, bytes, at: performance.now() });
this.used += bytes;
this.evict();
}
private evict(): void {
while (this.used > this.budget && this.entries.size > 1) {
const oldest = this.entries.keys().next();
if (oldest.done) {
return;
}
const entry = this.entries.get(oldest.value);
this.entries.delete(oldest.value);
if (entry) {
this.used -= entry.bytes;
entry.bitmap.close();
}
}
}
}