| 1 |
import type Swup from '../Swup.js'; |
| 2 |
import { Location } from '../helpers.js'; |
| 3 |
import { type PageData } from './fetchPage.js'; |
| 4 |
|
| 5 |
export interface CacheData extends PageData {} |
| 6 |
|
| 7 |
/** |
| 8 |
* In-memory page cache. |
| 9 |
*/ |
| 10 |
export class Cache { |
| 11 |
/** Swup instance this cache belongs to */ |
| 12 |
protected swup: Swup; |
| 13 |
|
| 14 |
/** Cached pages, indexed by URL */ |
| 15 |
protected pages: Map<string, CacheData> = new Map(); |
| 16 |
|
| 17 |
constructor(swup: Swup) { |
| 18 |
this.swup = swup; |
| 19 |
} |
| 20 |
|
| 21 |
/** Number of cached pages in memory. */ |
| 22 |
get size(): number { |
| 23 |
return this.pages.size; |
| 24 |
} |
| 25 |
|
| 26 |
/** All cached pages. */ |
| 27 |
get all() { |
| 28 |
const copy = new Map(); |
| 29 |
this.pages.forEach((page, key) => { |
| 30 |
copy.set(key, { ...page }); |
| 31 |
}); |
| 32 |
return copy; |
| 33 |
} |
| 34 |
|
| 35 |
/** Check if the given URL has been cached. */ |
| 36 |
has(url: string): boolean { |
| 37 |
return this.pages.has(this.resolve(url)); |
| 38 |
} |
| 39 |
|
| 40 |
/** Return a shallow copy of the cached page object if available. */ |
| 41 |
get(url: string): CacheData | undefined { |
| 42 |
const result = this.pages.get(this.resolve(url)); |
| 43 |
if (!result) return result; |
| 44 |
return { ...result }; |
| 45 |
} |
| 46 |
|
| 47 |
/** Create a cache record for the specified URL. */ |
| 48 |
set(url: string, page: CacheData) { |
| 49 |
url = this.resolve(url); |
| 50 |
page = { ...page, url }; |
| 51 |
this.pages.set(url, page); |
| 52 |
this.swup.hooks.callSync('cache:set', undefined, { page }); |
| 53 |
} |
| 54 |
|
| 55 |
/** Update a cache record, overwriting or adding custom data. */ |
| 56 |
update(url: string, payload: object) { |
| 57 |
url = this.resolve(url); |
| 58 |
const page = { ...this.get(url), ...payload, url } as CacheData; |
| 59 |
this.pages.set(url, page); |
| 60 |
} |
| 61 |
|
| 62 |
/** Delete a cache record. */ |
| 63 |
delete(url: string): void { |
| 64 |
this.pages.delete(this.resolve(url)); |
| 65 |
} |
| 66 |
|
| 67 |
/** Empty the cache. */ |
| 68 |
clear(): void { |
| 69 |
this.pages.clear(); |
| 70 |
this.swup.hooks.callSync('cache:clear', undefined, undefined); |
| 71 |
} |
| 72 |
|
| 73 |
/** Remove all cache entries that return true for a given predicate function. */ |
| 74 |
prune(predicate: (url: string, page: CacheData) => boolean): void { |
| 75 |
this.pages.forEach((page, url) => { |
| 76 |
if (predicate(url, page)) { |
| 77 |
this.delete(url); |
| 78 |
} |
| 79 |
}); |
| 80 |
} |
| 81 |
|
| 82 |
/** Resolve URLs by making them local and letting swup resolve them. */ |
| 83 |
protected resolve(urlToResolve: string): string { |
| 84 |
const { url } = Location.fromUrl(urlToResolve); |
| 85 |
return this.swup.resolveUrl(url); |
| 86 |
} |
| 87 |
} |