fix: remediate branch review findings

This commit is contained in:
Josh Creek
2026-09-14 11:47:58 +01:00
parent 4af33709a3
commit 86f1c21e4d
38 changed files with 65833 additions and 58545 deletions
+92
View File
@@ -0,0 +1,92 @@
const META_CACHE = 'livingdex-offline-meta-v1';
const META_URL = '/__offline/current';
function element(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function statusText(record) {
if (!record) return 'Not caught';
const values = [];
if (record.caught) values.push('Caught');
if (record.haveToEvolve) values.push('Needs evolution');
if (record.inHome) values.push('In HOME');
return values.join(' · ') || 'Not caught';
}
function renderSnapshot(snapshot) {
const content = document.querySelector('#offline-content');
for (const { pokedex, entries } of snapshot.pokedexes) {
const section = element('section', 'card bg-base-100 mb-6 shadow');
const body = element('div', 'card-body');
body.append(element('h2', 'card-title text-2xl', pokedex.name));
body.append(element('p', 'text-sm opacity-70', `${entries.length} entries`));
const grid = element(
'div',
'grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-6'
);
for (const { pokedexEntry: entry, catchRecord } of entries) {
const card = element('article', 'rounded border border-base-300 p-2');
const image = element('img', 'mx-auto h-20 w-20 object-contain');
image.alt = `${entry.pokemon}${entry.form ? `${entry.form}` : ''}`;
image.src = entry.offlineSpriteUrl ?? '/placeholder-bulb.png';
image.addEventListener(
'error',
() => {
image.src = '/placeholder-bulb.png';
},
{ once: true }
);
card.append(image);
card.append(element('h3', 'font-semibold', `#${entry.pokedexNumber} ${entry.pokemon}`));
if (entry.form) card.append(element('p', 'text-xs opacity-70', entry.form));
card.append(element('p', 'text-sm', statusText(catchRecord)));
if (catchRecord?.personalNotes)
card.append(element('p', 'mt-1 whitespace-pre-wrap text-xs', catchRecord.personalNotes));
grid.append(card);
}
body.append(grid);
section.append(body);
content.append(section);
}
}
async function load() {
const status = document.querySelector('#offline-status');
try {
const meta = await (await (await caches.open(META_CACHE)).match(META_URL))?.json();
if (!meta?.userId) throw new Error('No collection has been synchronized on this device.');
if (!meta.dataCache) throw new Error('The saved collection metadata is incomplete.');
const dataCache = await caches.open(meta.dataCache);
const response = await dataCache.match(
`/__offline/snapshot/${encodeURIComponent(meta.userId)}`
);
if (!response)
throw new Error('The saved collection is incomplete. Reconnect and synchronize again.');
const snapshot = await response.json();
if (snapshot.version !== 1 || snapshot.userId !== meta.userId)
throw new Error('The saved collection is incompatible with this app version.');
status.textContent = `Saved ${new Date(snapshot.generatedAt).toLocaleString()}.`;
renderSnapshot(snapshot);
} catch (error) {
status.className = 'alert alert-warning';
status.textContent = error instanceof Error ? error.message : String(error);
}
}
void load();
navigator.serviceWorker?.addEventListener('message', (event) => {
if (event.data?.type !== 'OFFLINE_DATA_CLEARED') return;
const content = document.querySelector('#offline-content');
if (content) content.replaceChildren();
const status = document.querySelector('#offline-status');
if (status) {
status.className = 'alert alert-warning';
status.textContent =
'The saved collection was removed because the account changed or signed out.';
}
});
+207
View File
@@ -0,0 +1,207 @@
const OFFLINE_CACHE_PREFIX = 'livingdex-offline-';
const OFFLINE_META_CACHE = `${OFFLINE_CACHE_PREFIX}meta-v1`;
const OFFLINE_META_URL = '/__offline/current';
let offlineEpoch = 0;
let offlineOperation = Promise.resolve();
function queueOfflineOperation(operation) {
const result = offlineOperation.then(operation, operation);
offlineOperation = result.catch(() => undefined);
return result;
}
function dataCacheName(userId, generation) {
return `${OFFLINE_CACHE_PREFIX}data-v1-${userId}-${generation}`;
}
function artworkCacheName(userId, generation) {
return `${OFFLINE_CACHE_PREFIX}art-v1-${userId}-${generation}`;
}
async function currentOfflineMeta() {
const response = await (await caches.open(OFFLINE_META_CACHE)).match(OFFLINE_META_URL);
if (!response) return null;
const data = await response.json().catch(() => null);
return typeof data?.userId === 'string' ? data : null;
}
async function clearOfflineData() {
const names = await caches.keys();
await Promise.all(
names.filter((name) => name.startsWith(OFFLINE_CACHE_PREFIX)).map((name) => caches.delete(name))
);
}
async function notifyOfflineDataCleared() {
const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const client of windows) client.postMessage({ type: 'OFFLINE_DATA_CLEARED' });
}
async function cacheArtwork(cache, urls) {
let next = 0;
let failed = 0;
const workers = Array.from({ length: Math.min(6, urls.length) }, async () => {
for (;;) {
const index = next++;
if (index >= urls.length) return;
const url = urls[index];
try {
const response = await fetch(url, {
mode: url.startsWith(self.location.origin) ? 'same-origin' : 'no-cors'
});
if (!response.ok && response.type !== 'opaque') throw new Error(`HTTP ${response.status}`);
await cache.put(url, response);
} catch {
failed++;
}
}
});
await Promise.all(workers);
return failed;
}
self.addEventListener('message', (event) => {
const reply = (value) => event.ports[0]?.postMessage(value);
if (event.data?.type === 'CLEAR_OFFLINE_DATA') {
offlineEpoch++;
event.waitUntil(
queueOfflineOperation(async () => {
await clearOfflineData();
await notifyOfflineDataCleared();
})
.then(() => reply({ ok: true }))
.catch((error) => reply({ ok: false, error: String(error) }))
);
return;
}
if (event.data?.type === 'CLAIM_OFFLINE_USER') {
offlineEpoch++;
event.waitUntil(
queueOfflineOperation(async () => {
if (typeof event.data.userId !== 'string') throw new Error('Invalid offline cache owner');
const meta = await currentOfflineMeta();
if (meta?.userId && meta.userId !== event.data.userId) {
await clearOfflineData();
await notifyOfflineDataCleared();
}
reply({ ok: true });
}).catch((error) => reply({ ok: false, error: String(error) }))
);
return;
}
if (event.data?.type !== 'SYNC_OFFLINE_SNAPSHOT') return;
const syncEpoch = offlineEpoch;
event.waitUntil(
queueOfflineOperation(async () => {
let nextData;
let nextArtwork;
try {
const snapshot = event.data.snapshot;
if (!snapshot || snapshot.version !== 1 || typeof snapshot.userId !== 'string') {
throw new Error('Unsupported offline snapshot');
}
const previousMeta = await currentOfflineMeta();
if (previousMeta?.userId && previousMeta.userId !== snapshot.userId)
await clearOfflineData();
const timestamp = String(snapshot.generatedAt).replace(/[^0-9]/g, '');
const generation = `${timestamp}-${crypto.randomUUID()}`;
nextData = dataCacheName(snapshot.userId, generation);
const dataCache = await caches.open(nextData);
await dataCache.put(
`/__offline/snapshot/${encodeURIComponent(snapshot.userId)}`,
new Response(JSON.stringify(snapshot), {
headers: { 'Content-Type': 'application/json' }
})
);
nextArtwork = artworkCacheName(snapshot.userId, generation);
const artworkCache = await caches.open(nextArtwork);
const failedArtwork = await cacheArtwork(
artworkCache,
Array.from(new Set(event.data.artworkUrls ?? []))
);
if (syncEpoch !== offlineEpoch) {
await Promise.all([caches.delete(nextData), caches.delete(nextArtwork)]);
throw new Error('Offline synchronization was superseded by an account change');
}
const metaCache = await caches.open(OFFLINE_META_CACHE);
await metaCache.put(
OFFLINE_META_URL,
new Response(
JSON.stringify({
userId: snapshot.userId,
generatedAt: snapshot.generatedAt,
dataCache: nextData,
artworkCache: nextArtwork
}),
{
headers: { 'Content-Type': 'application/json' }
}
)
);
if (syncEpoch !== offlineEpoch) {
const current = await currentOfflineMeta();
if (current?.dataCache === nextData) await metaCache.delete(OFFLINE_META_URL);
await Promise.all([caches.delete(nextData), caches.delete(nextArtwork)]);
throw new Error('Offline synchronization was superseded by an account change');
}
if (previousMeta?.artworkCache && previousMeta.artworkCache !== nextArtwork) {
await caches.delete(previousMeta.artworkCache);
}
if (previousMeta?.dataCache && previousMeta.dataCache !== nextData) {
await caches.delete(previousMeta.dataCache);
}
const currentCaches = await caches.keys();
await Promise.all(
currentCaches
.filter(
(name) =>
name.startsWith(OFFLINE_CACHE_PREFIX) &&
![OFFLINE_META_CACHE, nextData, nextArtwork].includes(name)
)
.map((name) => caches.delete(name))
);
reply({ ok: true, failedArtwork });
} catch (error) {
await Promise.allSettled(
[nextData, nextArtwork].filter(Boolean).map((name) => caches.delete(name))
);
reply({ ok: false, error: error instanceof Error ? error.message : String(error) });
}
})
);
});
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.mode === 'navigate' && !['/offline', '/offline.html'].includes(url.pathname)) {
const fallback = async () =>
(await caches.match('/offline', { ignoreSearch: true })) ??
(await caches.match('/offline.html', { ignoreSearch: true })) ??
Response.error();
event.respondWith(
self.navigator.onLine
? fetch(new Request(event.request, { cache: 'no-store' })).catch(fallback)
: fallback()
);
return;
}
if (event.request.destination !== 'image') return;
event.respondWith(
(async () => {
const meta = await currentOfflineMeta();
if (meta?.artworkCache) {
const cached = await (
await caches.open(meta.artworkCache)
).match(event.request, {
ignoreSearch: true
});
if (cached) return cached;
}
return fetch(event.request);
})()
);
});
+28
View File
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#f00000" />
<title>Living Dex Tracker — Offline</title>
<link rel="stylesheet" href="/output.css" />
<script type="module" src="/offline-viewer.js"></script>
</head>
<body class="min-h-screen bg-base-200 text-base-content">
<header class="navbar bg-primary text-primary-content">
<div class="mx-auto w-full max-w-screen-2xl px-4 text-xl font-semibold">
Living Dex Tracker
</div>
</header>
<main class="mx-auto max-w-screen-2xl p-4">
<div class="alert mb-4" role="status">
<span
>You are offline. This is a read-only copy; changes, exports, and account actions are
disabled.</span
>
</div>
<p id="offline-status" class="mb-4">Loading the saved collection…</p>
<div id="offline-content"></div>
</main>
</body>
</html>