77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import { releaseImage, type TileImage } from "./scheduler";
|
|
|
|
export interface CachedTile {
|
|
bitmap: TileImage;
|
|
bytes: number;
|
|
at: number;
|
|
}
|
|
|
|
interface NavigatorWithMemory extends Navigator {
|
|
deviceMemory?: number;
|
|
}
|
|
|
|
const mb = 1024 * 1024;
|
|
|
|
export function isConstrainedDevice(): boolean {
|
|
const memory = (navigator as NavigatorWithMemory).deviceMemory;
|
|
if (typeof memory === "number" && memory <= 4) {
|
|
return true;
|
|
}
|
|
const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
|
|
const shortSide = Math.min(screen.width, screen.height);
|
|
return coarse && shortSide <= 820;
|
|
}
|
|
|
|
export function cacheBudget(): number {
|
|
return isConstrainedDevice() ? 120 * mb : 250 * mb;
|
|
}
|
|
|
|
export class TileCache {
|
|
private readonly entries = new Map<string, CachedTile>();
|
|
private used = 0;
|
|
|
|
constructor(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: TileImage): void {
|
|
const existing = this.entries.get(id);
|
|
if (existing) {
|
|
if (existing.bitmap !== bitmap) {
|
|
releaseImage(bitmap);
|
|
}
|
|
return;
|
|
}
|
|
const bytes = bitmap.width * bitmap.height * 4;
|
|
this.entries.set(id, { bitmap, bytes, at: performance.now() });
|
|
this.used += bytes;
|
|
this.trim(this.budget);
|
|
}
|
|
|
|
trim(limit: number): void {
|
|
while (this.used > limit && this.entries.size > 0) {
|
|
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;
|
|
releaseImage(entry.bitmap);
|
|
}
|
|
}
|
|
}
|
|
}
|