GO is back in the game list and in Move to HOME (it sends to HOME through GO Transporter). Its logo is saved for offline again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2450 lines
112 KiB
JavaScript
2450 lines
112 KiB
JavaScript
'use strict';
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Config. These Firebase values are public by design: the security rules in
|
||
// firestore.rules limit every request to the signed-in user's own records.
|
||
// ---------------------------------------------------------------------------
|
||
const FIREBASE_CONFIG = {
|
||
apiKey: 'AIzaSyBBYo2uN1nfQMBHMb_C_XXTSnex6tp99dE',
|
||
authDomain: 'pokemon-tracker-8d5ac.firebaseapp.com',
|
||
projectId: 'pokemon-tracker-8d5ac',
|
||
storageBucket: 'pokemon-tracker-8d5ac.firebasestorage.app',
|
||
messagingSenderId: '869525751786',
|
||
appId: '1:869525751786:web:2ec719a2da6bc79d47d493',
|
||
};
|
||
// Sync talks to Firestore over its REST API (same calls as the Mac app's CloudClient),
|
||
// so only the Firebase Auth library is loaded, and only after the first render.
|
||
const FIRESTORE_DOCS = `projects/${FIREBASE_CONFIG.projectId}/databases/(default)/documents`;
|
||
const FIRESTORE_URL = `https://firestore.googleapis.com/v1/${FIRESTORE_DOCS}`;
|
||
let auth = null; // firebase.auth(), set by startFirebase()
|
||
const POLL_MS = 60000; // also syncs on every edit and whenever the app comes back to the front
|
||
const PULL_OVERLAP_MS = 120000;
|
||
const LEGACY_CACHE_KEY = 'pt-cache-v2'; // localStorage copy from before IndexedDB; moved over on first run
|
||
const PREFS_KEY = 'pt-prefs-v1';
|
||
try { localStorage.removeItem('pt-cache-v1'); } catch { /* ignore */ }
|
||
|
||
// Must match HuntMethod raw values in the Mac app.
|
||
const METHODS = ['Full Odds', 'Masuda Method', 'SOS Chain', 'Mass Outbreak',
|
||
'Sparkling Power Sandwich', 'Dynamax Adventure', 'Chain Fishing', 'Other'];
|
||
|
||
const CHAIN_LABELS = { 'SOS Chain': 'SOS Chain', 'Mass Outbreak': 'KOs in Outbreak', 'Chain Fishing': 'Fishing Chain' };
|
||
|
||
const $ = (sel) => document.querySelector(sel);
|
||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
|
||
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
const uuid = () => crypto.randomUUID().toUpperCase();
|
||
const nowISO = () => new Date().toISOString();
|
||
|
||
function readJSON(key) {
|
||
try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch { return null; }
|
||
}
|
||
function writeJSON(key, value) {
|
||
try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* storage full or blocked */ }
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Static data
|
||
// ---------------------------------------------------------------------------
|
||
let SPECIES = [];
|
||
let SPECIES_BY_ID = new Map();
|
||
// The games the app shows: HOME, GO and the games on Switch / Switch 2. The older
|
||
// games stay in data/games.json, and their catches, badges and playthroughs
|
||
// stay in the account and in backups, just out of sight. Add an id to bring one back.
|
||
const SHOWN_GAMES = new Set(['home', 'pogo', 'frlg', 'letsgo', 'swsh', 'bdsp', 'legendsarceus', 'sv', 'legendsza']);
|
||
const GAME_KINDS = new Set(['catch', 'badge', 'playthrough']); // records that belong to one game
|
||
let GAMES = [];
|
||
// Extra HOME forms (data/forms.json, from scripts/fetch_forms.py): forms that
|
||
// stay in HOME (Unown letters, Vivillon patterns, Alcremie...) and the females
|
||
// of species with a gender difference. They are always in SPECIES_BY_ID, so a
|
||
// catch of one has a name everywhere; Settings → HOME forms decides whether
|
||
// HOME's dex lists them (applyHomeForms).
|
||
let FORMS = [];
|
||
let BASE_NAMES = {}; // species id -> its plain entry's name beside its forms ("Unown A")
|
||
let HOME_SPECIES = []; // HOME's list without the extras
|
||
let HAS_FEMALE = new Set();
|
||
let BADGES = {};
|
||
// gameId -> Map(speciesId -> version id) of version exclusives (data/exclusives.json,
|
||
// generated by the Mac project's scripts/fetch_exclusives.py).
|
||
let EXCLUSIVES = {};
|
||
// gameId -> {dexes, short, nums: {id: [dexIndex, number]}}: each game's own Pokédex
|
||
// numbers (data/dexnums.json, from scripts/fetch_dex_numbers.py).
|
||
let DEX_NUMS = {};
|
||
const exclusiveTo = (gameId, speciesId) => EXCLUSIVES[gameId]?.get(speciesId) || null;
|
||
// Outlined tag ("Scarlet only") so it reads differently from the filled "caught in" tags.
|
||
function exclusiveTag(gameId, speciesId) {
|
||
const vid = exclusiveTo(gameId, speciesId);
|
||
const v = vid && versionsOf(gameId).find((x) => x.id === vid);
|
||
if (!v) return '';
|
||
const short = versionsOf(gameId).some((x) => x.label.length > 8) ? VERSION_SHORT[vid] || v.label : v.label;
|
||
return `<span class="xtag" style="--vc:${v.color}" title="Only in ${esc(v.label)}">${esc(short)} only</span>`;
|
||
} // game id -> [{id, name, type, category}] (from the Mac app's GymData)
|
||
const BADGE_CATEGORIES = ['Gym', 'Trial', 'Kahuna', 'Titan', 'Team Star', 'Noble'];
|
||
|
||
// Versions within paired games, for marking which copy a catch is in. Ids match
|
||
// the Mac app's exclusives.json (PokéAPI version names). Catch records carry
|
||
// them as data.versions: string[] (absent/empty = not specified).
|
||
const VERSIONS = {
|
||
gsc: [['gold', 'Gold', '#c9a227'], ['silver', 'Silver', '#8e9aa8'], ['crystal', 'Crystal', '#3fb6c9']],
|
||
rse: [['ruby', 'Ruby', '#d33a3a'], ['sapphire', 'Sapphire', '#2f6fd6'], ['emerald', 'Emerald', '#2e9d58']],
|
||
frlg: [['firered', 'FireRed', '#e2532d'], ['leafgreen', 'LeafGreen', '#4caf50']],
|
||
dpp: [['diamond', 'Diamond', '#3b7bd8'], ['pearl', 'Pearl', '#d8669a'], ['platinum', 'Platinum', '#8e8e9a']],
|
||
hgss: [['heartgold', 'HeartGold', '#e0952b'], ['soulsilver', 'SoulSilver', '#8e9aa8']],
|
||
bw: [['black', 'Black', '#3b3f6b'], ['white', 'White', '#7aa7a4']],
|
||
b2w2: [['black-2', 'Black 2', '#2f8f8f'], ['white-2', 'White 2', '#55b59a']],
|
||
xy: [['x', 'X', '#2f6fd6'], ['y', 'Y', '#d33a3a']],
|
||
oras: [['omega-ruby', 'Omega Ruby', '#d33a3a'], ['alpha-sapphire', 'Alpha Sapphire', '#2f6fd6']],
|
||
sumo: [['sun', 'Sun', '#e8892b'], ['moon', 'Moon', '#4b4fb0']],
|
||
usum: [['ultra-sun', 'Ultra Sun', '#e8892b'], ['ultra-moon', 'Ultra Moon', '#4b4fb0']],
|
||
letsgo: [['lets-go-pikachu', 'Pikachu', '#d9b400'], ['lets-go-eevee', 'Eevee', '#9b6b43']],
|
||
swsh: [['sword', 'Sword', '#2ba8d6'], ['shield', 'Shield', '#d6457a']],
|
||
bdsp: [['brilliant-diamond', 'Brilliant Diamond', '#3b7bd8'], ['shining-pearl', 'Shining Pearl', '#d8669a']],
|
||
sv: [['scarlet', 'Scarlet', '#d33a3a'], ['violet', 'Violet', '#8e44c9']],
|
||
};
|
||
const versionsOf = (gameId) => (VERSIONS[gameId] || []).map(([id, label, color]) => ({ id, label, color }));
|
||
// Version tag text that fits a dex cell.
|
||
const VERSION_SHORT = { 'omega-ruby': 'OR', 'alpha-sapphire': 'AS', 'ultra-sun': 'US', 'ultra-moon': 'UM',
|
||
'brilliant-diamond': 'BD', 'shining-pearl': 'SP', firered: 'FR', leafgreen: 'LG', heartgold: 'HG',
|
||
soulsilver: 'SS', 'black-2': 'B2', 'white-2': 'W2', platinum: 'Plat', sapphire: 'Sapph', diamond: 'Dia' };
|
||
function versionTag(gameId, vid, short = true) {
|
||
const v = versionsOf(gameId).find((x) => x.id === vid);
|
||
if (!v) return '';
|
||
return `<span class="vtag" style="background:${v.color}">${esc(short ? VERSION_SHORT[vid] || v.label : v.label)}</span>`;
|
||
}
|
||
// The version new taps mark in the current game (remembered per game).
|
||
function activeVersion(gameId) {
|
||
const vs = versionsOf(gameId);
|
||
if (!vs.length) return null;
|
||
const v = (prefs.versionByGame || {})[gameId];
|
||
return vs.some((x) => x.id === v) ? v : vs[0].id;
|
||
}
|
||
|
||
// Official game logos in logos/{game}-{n}.webp (one per version of paired games).
|
||
const GAME_LOGOS = { home: 1, pogo: 1, gsc: 2, rse: 2, frlg: 2, dpp: 2, hgss: 2, bw: 2, b2w2: 2, xy: 2, oras: 2, sumo: 2, usum: 2, letsgo: 2, swsh: 2, bdsp: 2, legendsarceus: 1, sv: 2, legendsza: 1 };
|
||
const gameLogos = (gameId, cls = '') => Array.from({ length: GAME_LOGOS[gameId] || 0 },
|
||
(_, i) => `<img class="${cls}" src="logos/${gameId}-${i}.webp" alt="" loading="lazy" decoding="async">`).join('');
|
||
|
||
// Best-odds suggestions for a new hunt (port of MethodRecommender.swift).
|
||
const METHODS_BY_GAME = {
|
||
gsc: ['Full Odds'], rse: ['Full Odds'], frlg: ['Full Odds'],
|
||
dpp: ['Full Odds', 'Masuda Method'], hgss: ['Full Odds', 'Masuda Method'],
|
||
bw: ['Full Odds', 'Masuda Method'], b2w2: ['Full Odds', 'Masuda Method'],
|
||
xy: ['Full Odds', 'Masuda Method', 'Chain Fishing'], oras: ['Full Odds', 'Masuda Method', 'Chain Fishing'],
|
||
sumo: ['Full Odds', 'Masuda Method', 'SOS Chain'], usum: ['Full Odds', 'Masuda Method', 'SOS Chain'],
|
||
letsgo: ['Full Odds'], swsh: ['Full Odds', 'Masuda Method', 'Mass Outbreak', 'Dynamax Adventure'],
|
||
bdsp: ['Full Odds', 'Masuda Method'], legendsarceus: ['Full Odds', 'Mass Outbreak'],
|
||
sv: ['Full Odds', 'Masuda Method', 'Mass Outbreak', 'Sparkling Power Sandwich'], legendsza: ['Full Odds'],
|
||
};
|
||
const CHARM_GAMES = new Set(['b2w2', 'xy', 'oras', 'sumo', 'usum', 'letsgo', 'swsh', 'bdsp', 'legendsarceus', 'sv', 'legendsza']);
|
||
const BEST_MODIFIERS = {
|
||
'Sparkling Power Sandwich': { sandwichLevel: 3, label: 'Sparkling Power Lv. 3' },
|
||
'SOS Chain': { chainCount: 31, label: 'Chain ≥ 31' },
|
||
'Mass Outbreak': { chainCount: 60, label: '60 KOs' },
|
||
'Chain Fishing': { chainCount: 20, label: 'Chain ≥ 20' },
|
||
};
|
||
|
||
function recommendMethods(speciesId, limit = 5) {
|
||
const out = [];
|
||
for (const g of GAMES) {
|
||
if (!g.species.includes(speciesId)) continue;
|
||
for (const method of METHODS_BY_GAME[g.id] || []) {
|
||
const mods = BEST_MODIFIERS[method] || {};
|
||
const charm = CHARM_GAMES.has(g.id);
|
||
const odds = huntOdds({ method, shinyCharm: charm, sandwichLevel: mods.sandwichLevel || 0, chainCount: mods.chainCount || 0 });
|
||
const parts = [charm && 'Shiny Charm', mods.label].filter(Boolean);
|
||
out.push({ game: g, method, charm, mods, odds, summary: [method, ...parts].join(' · ') });
|
||
}
|
||
}
|
||
return out.sort((a, b) => b.odds.rolls - a.odds.rolls || a.summary.localeCompare(b.summary)).slice(0, limit);
|
||
}
|
||
|
||
const SPRITE_CDN = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/';
|
||
// PokéAPI's file name for a sprite: the id, or for extra forms "201-b" / "female/3".
|
||
const spriteKey = (id) => SPECIES_BY_ID.get(id)?.sprite ?? id;
|
||
const pixelSpriteURL = (id, shiny) => `${SPRITE_CDN}${shiny ? 'shiny/' : ''}${spriteKey(id)}.png`;
|
||
// HOME 3D renders: 144px copies ship with the app (sprites/home) for grids and
|
||
// lists; `large` loads PokéAPI's full-size render for the detail sheet. Any
|
||
// HOME image that fails to load falls back to the pixel sprite (see boot()).
|
||
function spriteURL(id, shiny, large = false) {
|
||
if (prefs.spriteStyle === 'pixel') return pixelSpriteURL(id, shiny);
|
||
return large ? `${SPRITE_CDN}other/home/${shiny ? 'shiny/' : ''}${spriteKey(id)}.png`
|
||
: `sprites/home/${shiny ? 's' : 'r'}-${id}.webp`;
|
||
}
|
||
// Sprites from the CDN load with CORS (crossorigin) so the service worker caches
|
||
// them at their real size; without it each one counts as several MB of storage.
|
||
const spriteImg = (id, shiny, attrs = '', large = false) => {
|
||
const src = spriteURL(id, shiny, large);
|
||
// A form with no sprite of its own ends up on its species' pixel sprite (see boot()).
|
||
const base = SPECIES_BY_ID.get(id)?.baseSpeciesId ?? id;
|
||
const last = base !== id ? ` data-base="${SPRITE_CDN}${shiny ? 'shiny/' : ''}${base}.png"` : '';
|
||
return `<img ${attrs} alt="" draggable="false"${src.startsWith(SPRITE_CDN) ? ' crossorigin="anonymous"' : ''} src="${src}" data-fallback="${pixelSpriteURL(id, shiny)}"${last}>`;
|
||
};
|
||
// One-line message above the tab bar, with an optional action button. With an
|
||
// action it stays until tapped unless a timeout is given; without one it fades.
|
||
let toastTimer = null;
|
||
function showToast(text, action = null, onAction = null, timeout = action ? 0 : 8000) {
|
||
const el = $('#toast');
|
||
if (!el) return;
|
||
clearTimeout(toastTimer);
|
||
// An open dialog makes everything outside it untappable, so the toast moves inside it.
|
||
const host = [...document.querySelectorAll('dialog:modal')].pop() || document.body;
|
||
if (el.parentNode !== host) host.append(el);
|
||
el.innerHTML = `<span>${esc(text)}</span>` + (action ? `<button type="button">${esc(action)}</button>` : '');
|
||
el.hidden = false;
|
||
if (action) el.querySelector('button').addEventListener('click', () => { hideToast(); onAction(); });
|
||
if (timeout) toastTimer = setTimeout(hideToast, timeout);
|
||
}
|
||
function hideToast() {
|
||
clearTimeout(toastTimer);
|
||
$('#toast').hidden = true;
|
||
}
|
||
|
||
// ---- Dialogs ---------------------------------------------------------------
|
||
// Every sheet and dialog opens through openDialog, which adds a history entry so
|
||
// the Back button (or the back swipe) closes it instead of leaving the app.
|
||
// Closing it any other way removes that entry again.
|
||
const dialogStack = []; // open dialogs, oldest first
|
||
const closedByBack = new Set();
|
||
let popsToIgnore = 0; // history.back() calls of our own still on their way
|
||
|
||
// `modal: false` opens it beside the page instead of over it (the docked details panel).
|
||
function openDialog(dlg, modal = true) {
|
||
if (dlg.open) return;
|
||
if (modal) {
|
||
dlg.showModal();
|
||
} else {
|
||
const focused = document.activeElement;
|
||
dlg.show();
|
||
focused?.focus?.({ preventScroll: true }); // show() moves focus into the panel; keep it in the grid
|
||
}
|
||
dialogStack.push(dlg);
|
||
history.pushState({ ptDialogs: dialogStack.length }, '');
|
||
}
|
||
|
||
function watchDialogs() {
|
||
document.querySelectorAll('dialog').forEach((dlg) => dlg.addEventListener('close', () => {
|
||
const i = dialogStack.lastIndexOf(dlg);
|
||
if (i < 0) return;
|
||
dialogStack.splice(i, 1);
|
||
if (closedByBack.delete(dlg)) return;
|
||
popsToIgnore++;
|
||
history.back();
|
||
}));
|
||
window.addEventListener('popstate', () => {
|
||
if (popsToIgnore > 0) { popsToIgnore--; return; }
|
||
const top = dialogStack[dialogStack.length - 1];
|
||
if (!top) return;
|
||
closedByBack.add(top);
|
||
top.close();
|
||
});
|
||
// Reloaded with a dialog's entry still in the history: step back past it.
|
||
const stale = history.state?.ptDialogs;
|
||
if (stale) { popsToIgnore++; history.go(-stale); }
|
||
}
|
||
|
||
// In-app replacement for confirm() and prompt(). Resolves true/false, or with
|
||
// `input` the trimmed text (null when cancelled).
|
||
let askDone = null;
|
||
function ask({ title, body = '', ok = 'OK', input = null }) {
|
||
const dlg = $('#ask-dlg');
|
||
if (askDone) askDone(input ? null : false);
|
||
$('#ask-title').textContent = title;
|
||
$('#ask-body').textContent = body;
|
||
$('#ask-body').hidden = !body;
|
||
$('#ask-ok').textContent = ok;
|
||
const field = $('#ask-input');
|
||
$('#ask-field').hidden = !input;
|
||
field.required = !!input;
|
||
field.value = input?.value || '';
|
||
field.placeholder = input?.placeholder || '';
|
||
$('#ask-label').textContent = input?.label || '';
|
||
dlg.returnValue = '';
|
||
openDialog(dlg);
|
||
if (input) { field.focus(); field.select(); }
|
||
return new Promise((resolve) => {
|
||
askDone = (value) => { askDone = null; resolve(value); };
|
||
dlg.addEventListener('close', () => {
|
||
if (!askDone) return;
|
||
const yes = dlg.returnValue === 'ok';
|
||
askDone(input ? (yes ? field.value.trim() || null : null) : yes);
|
||
}, { once: true });
|
||
});
|
||
}
|
||
|
||
// Skip the DOM write when the markup hasn't changed.
|
||
function setHTML(el, html) {
|
||
if (el._html === html) return;
|
||
el.innerHTML = html;
|
||
el._html = html;
|
||
}
|
||
|
||
// Update a list in place from [{key, html}]: unchanged items keep their node,
|
||
// changed ones are rebuilt but keep their already-loaded sprites (and open
|
||
// <details>), so tapping a cell doesn't make the whole list blink.
|
||
function morphChildren(container, items) {
|
||
const old = new Map();
|
||
for (const el of container.children) if (el._key != null) old.set(el._key, el);
|
||
const tpl = document.createElement('template');
|
||
const next = items.map(({ key, html }) => {
|
||
const prev = old.get(key);
|
||
if (prev && prev._html === html) return prev;
|
||
tpl.innerHTML = html;
|
||
const el = tpl.content.firstElementChild;
|
||
el._key = key;
|
||
el._html = html;
|
||
if (prev) {
|
||
const imgs = new Map([...prev.querySelectorAll('img')].map((i) => [i.dataset.src || i.getAttribute('src'), i]));
|
||
for (const img of el.querySelectorAll('img')) {
|
||
const keep = imgs.get(img.getAttribute('src'));
|
||
if (keep) { imgs.delete(img.getAttribute('src')); img.replaceWith(keep); }
|
||
}
|
||
const wasOpen = [...prev.querySelectorAll('details'), prev].filter((d) => d.tagName === 'DETAILS').map((d) => d.open);
|
||
[...el.querySelectorAll('details'), el].filter((d) => d.tagName === 'DETAILS').forEach((d, i) => { if (wasOpen[i]) d.open = true; });
|
||
}
|
||
return el;
|
||
});
|
||
const kids = [...container.children];
|
||
if (kids.length === next.length && next.every((el, i) => kids[i] === el || !el.isConnected)) {
|
||
next.forEach((el, i) => { if (kids[i] !== el) kids[i].replaceWith(el); });
|
||
} else {
|
||
container.replaceChildren(...next);
|
||
}
|
||
}
|
||
|
||
const dexNum = (sp) => '#' + String(sp.baseSpeciesId ?? sp.id).padStart(4, '0');
|
||
// The number a game's own Pokédex gives a species: "#074", plus the sub-dex when
|
||
// the game has more than one ("Kitakami #036"). Home, GO and species off the
|
||
// regional dex use the national number. `full` always names the dex ("Paldea #074").
|
||
function gameDexNum(gameId, sp, full = false) {
|
||
const g = DEX_NUMS[gameId];
|
||
const hit = g?.nums[sp.id];
|
||
if (!hit) return dexNum(sp);
|
||
const [dex, n] = hit;
|
||
const label = full ? g.dexes[dex] : g.short[dex];
|
||
return `${label ? `${label} ` : ''}#${String(n).padStart(3, '0')}`;
|
||
}
|
||
const speciesName = (id) => SPECIES_BY_ID.get(id)?.name ?? `#${id}`;
|
||
|
||
// ---- HOME forms --------------------------------------------------------------
|
||
// prefs.homeForms: 'off' | 'forms' | 'all' (forms and females). Rebuilds HOME's
|
||
// list with each extra right after its species: female first, then its forms.
|
||
function applyHomeForms() {
|
||
const home = GAMES.find((g) => g.id === 'home');
|
||
if (!home) return;
|
||
const extra = new Map();
|
||
const want = (f) => prefs.homeForms === 'all' || (prefs.homeForms === 'forms' && f.kind === 'form');
|
||
for (const f of [...FORMS.filter((x) => x.kind === 'female'), ...FORMS.filter((x) => x.kind !== 'female')]) {
|
||
if (!want(f)) continue;
|
||
if (!extra.has(f.baseSpeciesId)) extra.set(f.baseSpeciesId, []);
|
||
extra.get(f.baseSpeciesId).push(f.id);
|
||
}
|
||
home.species = HOME_SPECIES.flatMap((id) => [id, ...(extra.get(id) || [])]);
|
||
}
|
||
// The extra forms HOME is listing right now.
|
||
const shownForms = () => (prefs.homeForms === 'off' ? [] : FORMS.filter((f) => prefs.homeForms === 'all' || f.kind === 'form'));
|
||
// A Pokémon's name in a game's dex. With HOME forms on, the plain entry says
|
||
// which form it is: "Unown A", "Meadow Vivillon", "Venusaur ♂".
|
||
function dexName(gameId, sp) {
|
||
if (gameId !== 'home' || prefs.homeForms === 'off') return sp.name;
|
||
if (BASE_NAMES[sp.id]) return BASE_NAMES[sp.id];
|
||
return prefs.homeForms === 'all' && HAS_FEMALE.has(sp.id) ? `${sp.name} ♂` : sp.name;
|
||
}
|
||
const gameGroup = (g) => (g.releaseGen === 'cross' ? 'Cross-Game' : `Gen ${g.releaseGen}`);
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Sync store: every record is a row {id, kind, data, deleted, updated_at}.
|
||
// In Firestore each one is users/{uid}/records/{id} = {kind, json, deleted,
|
||
// updatedAt}, the same documents the Mac app reads and writes.
|
||
// updated_at here is "seconds.nanoseconds" so it compares as a string.
|
||
// Local writes go into `pending` and are flushed in the background; pulls
|
||
// skip rows with unsent local edits so a tap is never overwritten.
|
||
// Deleted records stay on the server as tombstones (deleted: true); on this
|
||
// device a row is dropped once its deletion has been uploaded.
|
||
// ---------------------------------------------------------------------------
|
||
const store = {
|
||
userId: null, // whose data this is; kept while signed out so unsent edits survive
|
||
email: '',
|
||
rows: new Map(),
|
||
pending: new Map(),
|
||
cursor: null,
|
||
status: 'idle', // idle | busy | error
|
||
error: '',
|
||
lastSync: null,
|
||
};
|
||
|
||
// ---- Local copy (IndexedDB) -------------------------------------------------
|
||
// Database "poketracker": `rows` and `pending` keyed by record id, and
|
||
// meta['session'] = {userId, email, cursor}. Each change saves only the rows it
|
||
// touched. Every krburchel.github.io app shares one origin, hence the specific name.
|
||
let localDB = null;
|
||
let localBroken = false;
|
||
|
||
function openLocalDB() {
|
||
return new Promise((resolve, reject) => {
|
||
const req = indexedDB.open('poketracker', 1);
|
||
req.onupgradeneeded = () => {
|
||
req.result.createObjectStore('rows', { keyPath: 'id' });
|
||
req.result.createObjectStore('pending', { keyPath: 'id' });
|
||
req.result.createObjectStore('meta');
|
||
};
|
||
req.onsuccess = () => resolve(req.result);
|
||
req.onerror = () => reject(req.error);
|
||
});
|
||
}
|
||
|
||
// Saving failed (storage full or blocked, some private windows): say so once
|
||
// rather than failing silently. Edits still upload while the app stays open.
|
||
function localFailed(e) {
|
||
console.warn('PokéTracker: saving on this device failed', e);
|
||
if (!localBroken) {
|
||
localBroken = true;
|
||
showToast("Can't save on this device (storage is full or blocked). Keep the app open until the sync dot turns green.");
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// Runs fn(rows, pending, meta) in one transaction; resolves true once it has committed.
|
||
function localTx(fn) {
|
||
if (!localDB) return Promise.resolve(false);
|
||
return new Promise((resolve, reject) => {
|
||
const tx = localDB.transaction(['rows', 'pending', 'meta'], 'readwrite');
|
||
tx.oncomplete = () => resolve(true);
|
||
tx.onabort = tx.onerror = () => reject(tx.error || new Error('Local save failed'));
|
||
fn(tx.objectStore('rows'), tx.objectStore('pending'), tx.objectStore('meta'));
|
||
}).catch(localFailed);
|
||
}
|
||
|
||
function readLocal() {
|
||
return new Promise((resolve, reject) => {
|
||
const tx = localDB.transaction(['rows', 'pending', 'meta'], 'readonly');
|
||
const session = tx.objectStore('meta').get('session');
|
||
const rows = tx.objectStore('rows').getAll();
|
||
const pending = tx.objectStore('pending').getAll();
|
||
tx.oncomplete = () => resolve({ session: session.result || null, rows: rows.result, pending: pending.result });
|
||
tx.onabort = tx.onerror = () => reject(tx.error || new Error('Local read failed'));
|
||
});
|
||
}
|
||
|
||
const saveSession = () => localTx((rows, pending, meta) =>
|
||
meta.put({ userId: store.userId, email: store.email || '', cursor: store.cursor }, 'session'));
|
||
|
||
// Loads this device's saved data into `store`. Returns true when there is a
|
||
// saved account, so the app can be shown before sign-in has been checked.
|
||
async function loadLocal() {
|
||
const legacy = readJSON(LEGACY_CACHE_KEY);
|
||
let saved = { session: null, rows: [], pending: [] };
|
||
try {
|
||
localDB = await openLocalDB();
|
||
localDB.onversionchange = () => { localDB.close(); localDB = null; };
|
||
saved = await readLocal();
|
||
} catch (e) {
|
||
localDB = null;
|
||
localFailed(e);
|
||
}
|
||
if (legacy?.userId) {
|
||
if (localDB) {
|
||
// Move the old localStorage copy over. If IndexedDB already holds this
|
||
// account, only the old copy's unsent edits are still needed.
|
||
const sameUser = saved.session?.userId === legacy.userId;
|
||
const moved = await localTx((rows, pending, meta) => {
|
||
if (!sameUser) {
|
||
rows.clear();
|
||
pending.clear();
|
||
for (const r of legacy.rows || []) rows.put(r);
|
||
meta.put({ userId: legacy.userId, email: '', cursor: legacy.cursor || null }, 'session');
|
||
}
|
||
for (const r of legacy.pending || []) {
|
||
pending.put(r);
|
||
if (sameUser) rows.put({ ...r, updated_at: '' });
|
||
}
|
||
});
|
||
if (moved) {
|
||
try { localStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* ignore */ }
|
||
saved = await readLocal().catch(() => saved);
|
||
}
|
||
} else {
|
||
saved = { session: { userId: legacy.userId, email: '', cursor: legacy.cursor || null },
|
||
rows: legacy.rows || [], pending: legacy.pending || [] };
|
||
}
|
||
}
|
||
if (!saved.session?.userId) return false;
|
||
store.userId = saved.session.userId;
|
||
store.email = saved.session.email || '';
|
||
store.cursor = saved.session.cursor || null;
|
||
store.pending = new Map(saved.pending.map((r) => [r.id, r]));
|
||
store.rows = new Map();
|
||
const uploaded = []; // deletions the server already has
|
||
for (const r of saved.rows) {
|
||
if (r.deleted && !store.pending.has(r.id)) uploaded.push(r.id);
|
||
else store.rows.set(r.id, r);
|
||
}
|
||
for (const r of saved.pending) if (!store.rows.has(r.id)) store.rows.set(r.id, { ...r, updated_at: '' });
|
||
if (uploaded.length) localTx((rows) => uploaded.forEach((id) => rows.delete(id)));
|
||
return true;
|
||
}
|
||
|
||
// Starts this device's copy over for `user` (a different account signed in),
|
||
// or wipes it on sign-out (user = null).
|
||
function resetLocal(user) {
|
||
store.userId = user ? user.uid : null;
|
||
store.email = user?.email || '';
|
||
store.rows = new Map();
|
||
store.pending = new Map();
|
||
store.cursor = null;
|
||
store.lastSync = null;
|
||
try { localStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* ignore */ }
|
||
return localTx((rows, pending, meta) => {
|
||
rows.clear();
|
||
pending.clear();
|
||
if (user) meta.put({ userId: store.userId, email: store.email, cursor: null }, 'session');
|
||
else meta.delete('session');
|
||
});
|
||
}
|
||
|
||
// ---- Firestore (REST) ---------------------------------------------------------
|
||
const signedIn = () => !!auth?.currentUser && auth.currentUser.uid === store.userId;
|
||
const docName = (id) => `${FIRESTORE_DOCS}/users/${store.userId}/records/${id}`;
|
||
// "2026-10-08T12:34:56.123456Z" -> "1791462896.123456000"
|
||
function stamp(ts) {
|
||
const frac = (/\.(\d+)/.exec(ts)?.[1] || '').padEnd(9, '0').slice(0, 9);
|
||
return `${Math.floor(Date.parse(`${ts.slice(0, 19)}Z`) / 1000)}.${frac}`;
|
||
}
|
||
|
||
async function firestorePost(path, body) {
|
||
const token = await auth.currentUser.getIdToken();
|
||
const payload = JSON.stringify(body);
|
||
const res = await fetch(FIRESTORE_URL + path, {
|
||
method: 'POST',
|
||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||
body: payload,
|
||
// Lets a small upload finish even if the app is closed right after a tap.
|
||
keepalive: payload.length < 50000,
|
||
});
|
||
if (!res.ok) {
|
||
let detail = null;
|
||
try {
|
||
const json = await res.json();
|
||
detail = (Array.isArray(json) ? json[0] : json)?.error;
|
||
} catch { /* not JSON */ }
|
||
throw new Error(detail?.message || `Sync server error (${res.status})`);
|
||
}
|
||
return res.json();
|
||
}
|
||
|
||
async function pull() {
|
||
const pageSize = 1000;
|
||
const uid = store.userId;
|
||
let changed = false;
|
||
let newest = store.cursor;
|
||
let after = null;
|
||
for (;;) {
|
||
const query = {
|
||
from: [{ collectionId: 'records' }],
|
||
orderBy: [
|
||
{ field: { fieldPath: 'updatedAt' }, direction: 'ASCENDING' },
|
||
{ field: { fieldPath: '__name__' }, direction: 'ASCENDING' },
|
||
],
|
||
limit: pageSize,
|
||
};
|
||
if (store.cursor) {
|
||
const since = Number(store.cursor.split('.')[0]) * 1000 - PULL_OVERLAP_MS;
|
||
query.where = { fieldFilter: {
|
||
field: { fieldPath: 'updatedAt' }, op: 'GREATER_THAN',
|
||
value: { timestampValue: new Date(since).toISOString() },
|
||
} };
|
||
}
|
||
if (after) {
|
||
query.startAt = { before: false, values: [{ timestampValue: after.time }, { referenceValue: after.name }] };
|
||
}
|
||
const results = await firestorePost(`/users/${uid}:runQuery`, { structuredQuery: query });
|
||
if (store.userId !== uid) return false; // signed out or switched account meanwhile
|
||
const puts = [];
|
||
const drops = [];
|
||
let count = 0;
|
||
for (const { document: doc } of Array.isArray(results) ? results : []) {
|
||
const f = doc?.fields;
|
||
const time = f?.updatedAt?.timestampValue;
|
||
if (!time) continue;
|
||
count++;
|
||
after = { time, name: doc.name };
|
||
const id = doc.name.slice(doc.name.lastIndexOf('/') + 1);
|
||
const updated = stamp(time);
|
||
if (!newest || updated > newest) newest = updated;
|
||
if (store.pending.has(id)) continue;
|
||
const cur = store.rows.get(id);
|
||
if (f.deleted?.booleanValue) {
|
||
if (cur) {
|
||
store.rows.delete(id);
|
||
drops.push(id);
|
||
if (!cur.deleted) changed = true;
|
||
}
|
||
continue;
|
||
}
|
||
if (cur && cur.updated_at === updated) continue;
|
||
let data;
|
||
try { data = JSON.parse(f.json.stringValue); } catch { continue; }
|
||
const row = { id, kind: f.kind?.stringValue, data, deleted: false, updated_at: updated };
|
||
store.rows.set(id, row);
|
||
puts.push(row);
|
||
changed = true;
|
||
}
|
||
// Save each page as it arrives; the cursor only moves once every page is in.
|
||
if (puts.length || drops.length) {
|
||
localTx((rows) => { puts.forEach((r) => rows.put(r)); drops.forEach((id) => rows.delete(id)); });
|
||
}
|
||
if (count < pageSize) break;
|
||
}
|
||
if (newest !== store.cursor) {
|
||
store.cursor = newest;
|
||
saveSession();
|
||
}
|
||
return changed;
|
||
}
|
||
|
||
// Edits upload shortly after the last one. Hunt counting is `lazy`: taps collect
|
||
// and go up together every COUNT_FLUSH_MS, so a long hunt isn't one upload per
|
||
// tap. Either way the change is already saved on this device.
|
||
const COUNT_FLUSH_MS = 5000;
|
||
let flushTimer = null;
|
||
let flushing = false;
|
||
function scheduleFlush(delay = 600, lazy = false) {
|
||
if (lazy && flushTimer) return; // an upload is already on its way
|
||
clearTimeout(flushTimer);
|
||
flushTimer = setTimeout(flush, lazy ? COUNT_FLUSH_MS : delay);
|
||
}
|
||
|
||
async function flush() {
|
||
clearTimeout(flushTimer);
|
||
flushTimer = null;
|
||
if (flushing || !store.pending.size || !signedIn()) return;
|
||
flushing = true;
|
||
const uid = store.userId;
|
||
const batch = [...store.pending.values()];
|
||
setStatus('busy');
|
||
try {
|
||
for (let i = 0; i < batch.length; i += 500) {
|
||
await firestorePost(':commit', { writes: batch.slice(i, i + 500).map((r) => ({
|
||
update: {
|
||
name: docName(r.id),
|
||
fields: {
|
||
kind: { stringValue: r.kind },
|
||
json: { stringValue: JSON.stringify(r.data) },
|
||
deleted: { booleanValue: !!r.deleted },
|
||
},
|
||
},
|
||
updateTransforms: [{ fieldPath: 'updatedAt', setToServerValue: 'REQUEST_TIME' }],
|
||
})) });
|
||
}
|
||
} catch (e) {
|
||
flushing = false;
|
||
if (store.userId !== uid) return;
|
||
setStatus('error', describeError(e));
|
||
scheduleFlush(10000);
|
||
return;
|
||
}
|
||
flushing = false;
|
||
if (store.userId !== uid) return;
|
||
// Only clear entries that weren't edited again while the request was in flight.
|
||
const sent = batch.filter((r) => store.pending.get(r.id) === r);
|
||
for (const r of sent) store.pending.delete(r.id);
|
||
localTx((rows, pending) => sent.forEach((r) => pending.delete(r.id)));
|
||
// Edited again mid-upload: keep the timer that edit set, or start one if it already ran out.
|
||
if (store.pending.size) { if (!flushTimer) scheduleFlush(); }
|
||
else syncNow();
|
||
}
|
||
|
||
let syncing = false;
|
||
async function syncNow() {
|
||
if (syncing || !signedIn()) return;
|
||
syncing = true;
|
||
setStatus('busy');
|
||
try {
|
||
if (store.pending.size) await flush();
|
||
const changed = await pull();
|
||
store.lastSync = new Date();
|
||
setStatus('idle');
|
||
if (changed) render();
|
||
} catch (e) {
|
||
setStatus('error', describeError(e));
|
||
} finally {
|
||
syncing = false;
|
||
}
|
||
}
|
||
|
||
function describeError(e) {
|
||
if (!navigator.onLine) return 'Offline — changes are saved on this device and will sync when you reconnect.';
|
||
const msg = e?.message || String(e);
|
||
if (/unavailable|network|offline|Failed to (get|fetch)|Load failed/i.test(msg)) return "Can't reach the sync server. Changes are saved on this device and will sync once it's reachable.";
|
||
return msg;
|
||
}
|
||
|
||
// A sync problem is announced once, not on every retry, until a sync gets through.
|
||
let errorToasted = false;
|
||
function setStatus(status, error = '') {
|
||
if (status === 'error' && !errorToasted && !$('#app').hidden) {
|
||
errorToasted = true;
|
||
showToast(error);
|
||
} else if (status === 'idle' && !store.pending.size) {
|
||
errorToasted = false;
|
||
}
|
||
store.status = status;
|
||
store.error = error;
|
||
const dot = $('#sync-dot');
|
||
dot.className = 'dot' + (status === 'busy' ? ' busy' : status === 'error' ? ' err' : '');
|
||
if ($('#account-dlg').open) renderAccount();
|
||
}
|
||
|
||
function write(kind, id, data, deleted = false, lazy = false) {
|
||
writeMany([{ kind, id, data, deleted }], lazy);
|
||
}
|
||
|
||
// Several writes in one save (a restore can be thousands of rows).
|
||
function writeMany(list, lazy = false) {
|
||
const saved = [];
|
||
for (const { kind, id, data, deleted = false } of list) {
|
||
const row = { id, kind, data, deleted };
|
||
const full = { ...row, updated_at: store.rows.get(id)?.updated_at ?? '' };
|
||
store.rows.set(id, full);
|
||
store.pending.set(id, row);
|
||
saved.push([full, row]);
|
||
}
|
||
localTx((rows, pending) => { for (const [full, row] of saved) { rows.put(full); pending.put(row); } });
|
||
scheduleFlush(600, lazy);
|
||
}
|
||
|
||
const live = (kind) => [...store.rows.values()].filter((r) => r.kind === kind && !r.deleted
|
||
&& (!GAME_KINDS.has(kind) || SHOWN_GAMES.has(r.data.gameId)));
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Derived data
|
||
// ---------------------------------------------------------------------------
|
||
const catchKey = (d) => `${d.speciesId}|${d.gameId}|${d.isShiny ? 1 : 0}|${d.playthroughId || ''}`;
|
||
|
||
function catchIndex() {
|
||
const byKey = new Map();
|
||
for (const r of live('catch')) {
|
||
const k = catchKey(r.data);
|
||
if (!byKey.has(k)) byKey.set(k, []);
|
||
byKey.get(k).push(r);
|
||
}
|
||
return byKey;
|
||
}
|
||
|
||
// The writes for one tap. Without `version`: caught ⇄ not caught. With `version`
|
||
// (paired games): toggles just that copy — adding it to an existing catch, or
|
||
// deleting the catch when it was the last copy marked. `added` says which way it went.
|
||
function catchToggleWrites(speciesId, gameId, isShiny, playthroughId, index, version = null) {
|
||
const key = catchKey({ speciesId, gameId, isShiny, playthroughId });
|
||
const existing = index.get(key);
|
||
const del = (r) => ({ kind: 'catch', id: r.id, data: r.data, deleted: true });
|
||
if (existing?.length) {
|
||
if (version) {
|
||
const first = existing[0];
|
||
const versions = first.data.versions || [];
|
||
if (!versions.includes(version)) {
|
||
return { added: true, writes: [{ kind: 'catch', id: first.id, data: { ...first.data, versions: [...versions, version] } }] };
|
||
}
|
||
const left = versions.filter((v) => v !== version);
|
||
if (left.length) return { added: false, writes: [{ kind: 'catch', id: first.id, data: { ...first.data, versions: left } }] };
|
||
}
|
||
return { added: false, writes: existing.map(del) };
|
||
}
|
||
return { added: true, writes: [{ kind: 'catch', id: uuid(), data: {
|
||
speciesId, gameId, isShiny, playthroughId: playthroughId || null,
|
||
notes: '', tagsRaw: '', caughtAt: nowISO(), ...(version ? { versions: [version] } : {}),
|
||
} }] };
|
||
}
|
||
|
||
function toggleCatch(...args) {
|
||
const { added, writes } = catchToggleWrites(...args);
|
||
writeMany(writes);
|
||
return added;
|
||
}
|
||
|
||
// Makes `writes` and offers Undo, which puts every touched record back as it is now.
|
||
function writeWithUndo(writes, message, timeout = 6000) {
|
||
const undo = writes.map((w) => {
|
||
const prev = store.rows.get(w.id);
|
||
return prev && !prev.deleted ? { kind: prev.kind, id: prev.id, data: prev.data, deleted: false }
|
||
: { kind: w.kind, id: w.id, data: w.data, deleted: true };
|
||
});
|
||
writeMany(writes);
|
||
showToast(message, 'Undo', () => { writeMany(undo); render(); }, timeout);
|
||
}
|
||
|
||
// A tap on the dex or a detail-sheet pill. Removing a catch also removes its
|
||
// notes, tags and date, so that direction gets an Undo.
|
||
function tapCatch(speciesId, gameId, isShiny, playthroughId, version = null) {
|
||
const { added, writes } = catchToggleWrites(speciesId, gameId, isShiny, playthroughId, catchIndex(), version);
|
||
if (added) { writeMany(writes); return true; }
|
||
const onlyVersion = version && !writes.some((w) => w.deleted);
|
||
const label = versionsOf(gameId).find((v) => v.id === version)?.label;
|
||
writeWithUndo(writes, `Removed ${isShiny ? 'shiny ' : ''}${speciesName(speciesId)}${onlyVersion ? ` from ${label}` : ''}`);
|
||
return false;
|
||
}
|
||
|
||
// Port of OddsCalculator.swift.
|
||
function huntOdds(h) {
|
||
let rolls = 1;
|
||
switch (h.method) {
|
||
case 'Masuda Method': rolls = 6; break;
|
||
case 'SOS Chain':
|
||
if (h.chainCount >= 31) rolls += 12;
|
||
else if (h.chainCount >= 21) rolls += 8;
|
||
else if (h.chainCount >= 11) rolls += 4;
|
||
break;
|
||
case 'Mass Outbreak':
|
||
if (h.chainCount >= 60) rolls += 3;
|
||
else if (h.chainCount >= 30) rolls += 2;
|
||
else if (h.chainCount >= 1) rolls += 1;
|
||
break;
|
||
case 'Sparkling Power Sandwich': rolls += Math.max(0, Math.min(3, h.sandwichLevel || 0)); break;
|
||
case 'Dynamax Adventure': rolls = 13; break;
|
||
case 'Chain Fishing': rolls = 1 + 2 * Math.max(0, Math.min(20, h.chainCount || 0)); break;
|
||
}
|
||
if (h.shinyCharm) rolls += 2;
|
||
const p = rolls / 4096;
|
||
const cumulative = 1 - Math.pow(1 - p, Math.max(0, h.encounters || 0));
|
||
return { rolls, oneIn: Math.round(1 / p), cumulative };
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// UI state
|
||
// ---------------------------------------------------------------------------
|
||
const prefs = Object.assign({
|
||
tab: 'dex', gameId: 'home', playthroughId: '', mode: 'regular',
|
||
gen: 'all', type: 'all', status: 'all', tag: 'all', excl: 'all', lastCaughtGame: 'sv', versionByGame: {},
|
||
reviewYear: null, badgesExpanded: false, spriteStyle: 'home', hintSeen: false, lastBackupAt: null, view: 'grid',
|
||
density: 'large', // dex grid size on this device: large | compact
|
||
savedFilters: [], // [{id, name, f: {status, excl, gen, type, tag}}], kept on this device
|
||
homeForms: 'off', // extra forms in HOME's dex on this device: off | forms | all
|
||
}, readJSON(PREFS_KEY) || {});
|
||
const savePrefs = () => writeJSON(PREFS_KEY, prefs);
|
||
let search = '';
|
||
|
||
function render() {
|
||
if (!store.userId) return;
|
||
if (prefs.tab === 'dex') renderDex();
|
||
else if (prefs.tab === 'hunts') renderHunts();
|
||
else if (prefs.tab === 'timeline') renderTimeline();
|
||
else renderStats();
|
||
refreshDetailIfOpen();
|
||
if ($('#compare-dlg').open) renderCompare();
|
||
if ($('#tohome-dlg').open) renderToHome();
|
||
}
|
||
|
||
// ---- Tabs -----------------------------------------------------------------
|
||
const TITLES = { dex: 'Living Dex', hunts: 'Shiny Hunts', timeline: 'Timeline', stats: 'Stats' };
|
||
const TABS = Object.keys(TITLES);
|
||
function showTab(tab) {
|
||
prefs.tab = tab;
|
||
savePrefs();
|
||
if (!TABS.includes(tab)) tab = prefs.tab = 'dex';
|
||
if (tab === 'timeline') timelineShown = TIMELINE_PAGE;
|
||
if (tab !== 'dex') closeDockedDetail();
|
||
for (const t of TABS) $(`#tab-${t}`).hidden = t !== tab;
|
||
$('#app').dataset.tab = tab;
|
||
document.querySelectorAll('.tabbar button').forEach((b) => b.classList.toggle('on', b.dataset.tab === tab));
|
||
$('#title').textContent = TITLES[tab];
|
||
render();
|
||
updateWake();
|
||
window.scrollTo(0, 0);
|
||
}
|
||
|
||
// ---- Dex ------------------------------------------------------------------
|
||
function currentGame() {
|
||
return GAMES.find((g) => g.id === prefs.gameId) || GAMES[0];
|
||
}
|
||
|
||
function renderGameButton() {
|
||
const game = currentGame();
|
||
setHTML($('#game-btn'), `<span class="game-logos">${gameLogos(game.id)}</span>` +
|
||
`<span class="game-name">${esc(game.name)}</span><span class="caret">▾</span>`);
|
||
$('#game-btn').setAttribute('aria-label', `Game: ${game.name}. Change game`);
|
||
}
|
||
|
||
function openGamePicker() {
|
||
// Progress counts distinct species caught (regular) in each game, any playthrough.
|
||
const caughtBy = new Map();
|
||
for (const r of live('catch')) {
|
||
if (r.data.isShiny) continue;
|
||
if (!caughtBy.has(r.data.gameId)) caughtBy.set(r.data.gameId, new Set());
|
||
caughtBy.get(r.data.gameId).add(r.data.speciesId);
|
||
}
|
||
const groups = [];
|
||
for (const g of GAMES) {
|
||
const label = gameGroup(g);
|
||
let grp = groups.find((x) => x.label === label);
|
||
if (!grp) groups.push(grp = { label, games: [] });
|
||
grp.games.push(g);
|
||
}
|
||
$('#game-grid').innerHTML = groups.map((grp) => `<h3 class="game-group">${grp.label}</h3><div class="game-tiles">` +
|
||
grp.games.map((g) => {
|
||
const dex = new Set(g.species);
|
||
const n = [...(caughtBy.get(g.id) || [])].filter((id) => dex.has(id)).length;
|
||
const pct = g.species.length ? (n / g.species.length) * 100 : 0;
|
||
return `<button class="game-tile ${g.id === prefs.gameId ? 'on' : ''}" data-game="${g.id}">` +
|
||
`<span class="tile-logos n${GAME_LOGOS[g.id] || 0}">${gameLogos(g.id)}</span>` +
|
||
`<span class="tile-name">${esc(g.name)}</span>` +
|
||
`<span class="tile-progress">${n} / ${g.species.length}</span><span class="bar"><i style="width:${pct.toFixed(1)}%"></i></span></button>`;
|
||
}).join('') + '</div>').join('');
|
||
openDialog($('#game-dlg'));
|
||
$('#game-grid .game-tile.on')?.scrollIntoView({ block: 'center' });
|
||
}
|
||
|
||
function renderDexControls() {
|
||
const game = currentGame();
|
||
renderGameButton();
|
||
|
||
const pts = live('playthrough').filter((r) => r.data.gameId === game.id)
|
||
.sort((a, b) => a.data.createdAt.localeCompare(b.data.createdAt));
|
||
if (prefs.playthroughId && !pts.some((r) => r.id === prefs.playthroughId)) prefs.playthroughId = '';
|
||
setHTML($('#pt-select'), '<option value="">Main</option>' +
|
||
pts.map((r) => `<option value="${esc(r.id)}">${esc(r.data.name)}</option>`).join('') +
|
||
'<option value="__new">+ New playthrough…</option>');
|
||
$('#pt-select').value = prefs.playthroughId;
|
||
|
||
// Filter choices for this game (shown in the Filters sheet).
|
||
const opts = filterOptions(game);
|
||
for (const [key, list] of Object.entries(opts)) {
|
||
if (prefs[key] !== 'all' && !list.some(([v]) => String(v) === String(prefs[key]))) prefs[key] = 'all';
|
||
}
|
||
const active = ['gen', 'type', 'status', 'tag', 'excl'].filter((k) => prefs[k] !== 'all').length;
|
||
$('#filter-count').hidden = !active;
|
||
$('#filter-count').textContent = active;
|
||
$('#filter-btn').classList.toggle('active', active > 0);
|
||
$('#filter-btn').setAttribute('aria-label', active ? `Filters, ${active} on` : 'Filters');
|
||
if ($('#filter-dlg').open) renderFilterSheet();
|
||
|
||
// Mode buttons: icon only, plus a label on the active one.
|
||
const MODES = { regular: ['caught', 'Caught'], shiny: ['shiny', 'Shiny'], info: ['info', 'Info'] };
|
||
document.querySelectorAll('.iconseg button').forEach((b) => {
|
||
const [ic, label] = MODES[b.dataset.mode];
|
||
const on = b.dataset.mode === prefs.mode;
|
||
b.classList.toggle('on', on);
|
||
b.setAttribute('aria-pressed', on);
|
||
setHTML(b, icon(ic) + (on ? `<span>${label}</span>` : ''));
|
||
});
|
||
|
||
// "In:" version picker for paired games.
|
||
const vs = versionsOf(game.id);
|
||
const activeV = activeVersion(game.id);
|
||
// Long names (Brilliant Diamond, LeafGreen…) use initials for every version in that game.
|
||
const shortLabels = vs.some((v) => v.label.length > 8);
|
||
$('#version-row').hidden = !vs.length || prefs.mode === 'info';
|
||
setHTML($('#version-row'), vs.length ? '<span class="muted">In</span>' + vs.map((v) =>
|
||
`<button data-version="${v.id}" class="${v.id === activeV ? 'on' : ''}" style="--vc:${v.color}" aria-pressed="${v.id === activeV}" title="${esc(v.label)}">${esc(shortLabels ? VERSION_SHORT[v.id] || v.label : v.label)}</button>`).join('') : '');
|
||
}
|
||
|
||
// Choices per filter group for a game: [value, label][] each.
|
||
function filterOptions(game) {
|
||
const dexSpecies = game.species.map((id) => SPECIES_BY_ID.get(id)).filter(Boolean);
|
||
const pt = prefs.playthroughId || '';
|
||
const vs = versionsOf(game.id);
|
||
const tags = [...new Set(live('catch')
|
||
.filter((r) => r.data.gameId === game.id && (r.data.playthroughId || '') === pt)
|
||
.flatMap((r) => tagsOf(r.data.tagsRaw)))].sort();
|
||
return {
|
||
status: [['missing', 'Missing'], ['caught', 'Caught'],
|
||
...vs.flatMap((v) => [[`missing:${v.id}`, `Missing in ${v.label}`], [`caught:${v.id}`, `In ${v.label}`]])],
|
||
excl: EXCLUSIVES[game.id] ? vs.filter((v) => [...EXCLUSIVES[game.id].values()].includes(v.id))
|
||
.map((v) => [v.id, `${v.label} only`]).concat([['none', 'In every version']]) : [],
|
||
gen: [...new Set(dexSpecies.map((s) => s.generation))].sort((a, b) => a - b).map((g) => [g, `Gen ${g}`]),
|
||
type: [...new Set(dexSpecies.flatMap((s) => s.types))].sort().map((t) => [t, t[0].toUpperCase() + t.slice(1)]),
|
||
tag: tags.map((t) => [t, `#${t}`]),
|
||
};
|
||
}
|
||
|
||
const FILTER_TITLES = { status: 'Status', excl: 'Exclusive to', gen: 'Generation', type: 'Type', tag: 'Tag' };
|
||
const FILTER_KEYS = Object.keys(FILTER_TITLES);
|
||
const NO_FILTERS = Object.fromEntries(FILTER_KEYS.map((k) => [k, 'all']));
|
||
|
||
// ---- Saved filter sets ---------------------------------------------------------
|
||
// A named combination of the filter choices, kept on this device (in prefs). A
|
||
// set only shows for games that have every choice in it, so "Missing in
|
||
// Scarlet" doesn't appear on HOME.
|
||
const filterIsOn = (f) => FILTER_KEYS.every((k) => String(prefs[k]) === String(f[k] ?? 'all'));
|
||
const filterFits = (f, opts) => FILTER_KEYS.every((k) => (f[k] ?? 'all') === 'all' || opts[k].some(([v]) => String(v) === String(f[k])));
|
||
// "Missing · Gen 9 · Fire": what the filters on right now are called.
|
||
function currentFilterName(opts) {
|
||
return FILTER_KEYS.filter((k) => prefs[k] !== 'all')
|
||
.map((k) => opts[k].find(([v]) => String(v) === String(prefs[k]))?.[1]).filter(Boolean).join(' · ');
|
||
}
|
||
|
||
function savedFiltersHTML(opts) {
|
||
const saved = (prefs.savedFilters || []).filter((s) => filterFits(s.f, opts));
|
||
const anyOn = FILTER_KEYS.some((k) => prefs[k] !== 'all');
|
||
const alreadySaved = saved.some((s) => filterIsOn(s.f));
|
||
if (!saved.length && !anyOn) return '';
|
||
return `<section class="filter-group"><h3>Saved</h3><div class="choice">` +
|
||
saved.map((s) => `<span class="saved-chip"><button data-saved="${esc(s.id)}" aria-pressed="${filterIsOn(s.f)}">${esc(s.name)}</button>` +
|
||
`<button data-unsave="${esc(s.id)}" aria-label="Delete saved filter ${esc(s.name)}">✕</button></span>`).join('') +
|
||
(anyOn && !alreadySaved ? '<button data-save-filter class="save-filter">+ Save these filters</button>' : '') +
|
||
'</div></section>';
|
||
}
|
||
|
||
async function onSavedFilterTap(e) {
|
||
const btn = e.target.closest('[data-saved], [data-unsave], [data-save-filter]');
|
||
if (!btn) return false;
|
||
const list = prefs.savedFilters || [];
|
||
if (btn.dataset.saved) {
|
||
const s = list.find((x) => x.id === btn.dataset.saved);
|
||
if (!s) return true;
|
||
// Tapping the one that's on turns every filter off, like the other chips.
|
||
Object.assign(prefs, NO_FILTERS, filterIsOn(s.f) ? {} : s.f);
|
||
} else if (btn.dataset.unsave) {
|
||
const s = list.find((x) => x.id === btn.dataset.unsave);
|
||
if (!s || !await ask({ title: `Delete the saved filter “${s.name}”?`, ok: 'Delete' })) return true;
|
||
prefs.savedFilters = list.filter((x) => x !== s);
|
||
} else {
|
||
const f = Object.fromEntries(FILTER_KEYS.map((k) => [k, prefs[k]]));
|
||
const name = await ask({ title: 'Save these filters', ok: 'Save',
|
||
input: { label: 'Name', value: currentFilterName(filterOptions(currentGame())).slice(0, 60) } });
|
||
if (!name) return true;
|
||
// Saving under a name that's already used replaces that set.
|
||
prefs.savedFilters = [...list.filter((x) => x.name.toLowerCase() !== name.toLowerCase()), { id: uuid(), name, f }];
|
||
}
|
||
savePrefs();
|
||
renderFilterSheet();
|
||
renderDex();
|
||
showDexStart();
|
||
return true;
|
||
}
|
||
|
||
function renderFilterSheet() {
|
||
const opts = filterOptions(currentGame());
|
||
$('#filter-groups').innerHTML = savedFiltersHTML(opts) + Object.entries(opts).filter(([, list]) => list.length).map(([key, list]) =>
|
||
`<section class="filter-group"><h3>${FILTER_TITLES[key]}</h3><div class="choice" data-key="${key}">` +
|
||
`<button data-v="all" aria-pressed="${prefs[key] === 'all'}">${key === 'tag' ? 'Any tag' : 'All'}</button>` +
|
||
list.map(([v, label]) => {
|
||
const on = String(prefs[key]) === String(v);
|
||
const style = key === 'type' ? ` style="--tc:${TYPE_COLORS[v]}"` : '';
|
||
return `<button class="${key === 'type' ? 'tchip' : ''}" data-v="${esc(v)}" aria-pressed="${on}"${style}>${esc(label)}</button>`;
|
||
}).join('') + '</div></section>').join('');
|
||
}
|
||
|
||
// Gym badges / trials / titans for the selected game + playthrough: a count
|
||
// pill next to the progress line that expands the full list.
|
||
function renderBadges() {
|
||
const game = currentGame();
|
||
const list = BADGES[game.id] || [];
|
||
const pill = $('#badge-pill');
|
||
const el = $('#badge-strip');
|
||
pill.hidden = !list.length;
|
||
el.hidden = !list.length || !prefs.badgesExpanded;
|
||
if (!list.length) return;
|
||
const pt = prefs.playthroughId || '';
|
||
const earned = new Set(live('badge').filter((r) => r.data.gameId === game.id && (r.data.playthroughId || '') === pt)
|
||
.map((r) => r.data.badgeId));
|
||
const count = list.filter((b) => earned.has(b.id)).length;
|
||
setHTML(pill, `${icon('badge')}${count} / ${list.length}`);
|
||
pill.setAttribute('aria-expanded', prefs.badgesExpanded);
|
||
pill.setAttribute('aria-label', `Badges: ${count} of ${list.length}. ${prefs.badgesExpanded ? 'Hide' : 'Show'} badges`);
|
||
if (el.hidden) return;
|
||
const groups = BADGE_CATEGORIES.map((cat) => [cat, list.filter((b) => (b.category || 'Gym') === cat)]).filter(([, l]) => l.length);
|
||
setHTML(el, groups.map(([cat, l]) => `<div class="badge-group">${groups.length > 1 ? `<span class="badge-cat">${cat}</span>` : ''}` +
|
||
l.map((b) => {
|
||
const on = earned.has(b.id);
|
||
return `<button class="gym ${on ? 'on' : ''}" data-badge="${esc(b.id)}" aria-pressed="${on}"` +
|
||
`${on ? ` style="background:${TYPE_COLORS[b.type] || '#888'}"` : ''} title="${esc(b.name)} (${b.type})">${esc(b.name)}</button>`;
|
||
}).join('') + '</div>').join(''));
|
||
}
|
||
|
||
function toggleBadge(badgeId) {
|
||
const game = currentGame();
|
||
const pt = prefs.playthroughId || null;
|
||
const matches = live('badge').filter((r) => r.data.gameId === game.id && (r.data.playthroughId || null) === pt && r.data.badgeId === badgeId);
|
||
if (matches.length) for (const r of matches) write('badge', r.id, r.data, true);
|
||
else write('badge', uuid(), { gameId: game.id, playthroughId: pt, badgeId, earnedAt: nowISO() });
|
||
renderBadges();
|
||
}
|
||
|
||
// ---- Boxes -------------------------------------------------------------------
|
||
// Box view lays the dex out the way it's stored in the game: 30 to a box, six
|
||
// across (Gen 2: 20, five across). GO and Let's Go have no boxes.
|
||
function boxLayout(gameId) {
|
||
if (gameId === 'pogo' || gameId === 'letsgo') return null;
|
||
return gameId === 'gsc' ? { size: 20, cols: 5 } : { size: 30, cols: 6 };
|
||
}
|
||
|
||
// A game's boxes in order: [{n, species}], filled in the game's dex order, the
|
||
// same order as the grid. Regional forms sit right after their base Pokémon
|
||
// (HOME too: Alolan Rattata follows Rattata).
|
||
function boxesOf(game) {
|
||
const layout = boxLayout(game.id);
|
||
if (!layout) return [];
|
||
const all = game.species.map((id) => SPECIES_BY_ID.get(id)).filter(Boolean);
|
||
const out = [];
|
||
for (let i = 0; i < all.length; i += layout.size) out.push({ n: out.length + 1, species: all.slice(i, i + layout.size) });
|
||
return out;
|
||
}
|
||
|
||
function boxPosition(gameId, speciesId) {
|
||
const game = GAMES.find((g) => g.id === gameId);
|
||
const layout = game && boxLayout(gameId);
|
||
if (!layout) return null;
|
||
for (const box of boxesOf(game)) {
|
||
const i = box.species.findIndex((sp) => sp.id === speciesId);
|
||
if (i >= 0) return { box: box.n, row: Math.floor(i / layout.cols) + 1, slot: (i % layout.cols) + 1 };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// ---- Mark or unmark everything shown -------------------------------------------
|
||
let dexShown = []; // the Pokémon the dex is showing after filters and search
|
||
|
||
// What marking (or unmarking) every shown Pokémon would write, in the current
|
||
// mode (caught / shiny) and, for paired games, the selected version.
|
||
function bulkPlan(mark) {
|
||
const game = currentGame();
|
||
const pt = prefs.playthroughId || null;
|
||
const shiny = prefs.mode === 'shiny';
|
||
const version = activeVersion(game.id);
|
||
const index = catchIndex();
|
||
const writes = [];
|
||
let n = 0;
|
||
for (const sp of dexShown) {
|
||
const recs = index.get(catchKey({ speciesId: sp.id, gameId: game.id, isShiny: shiny, playthroughId: pt }));
|
||
const owned = version ? !!recs?.[0]?.data.versions?.includes(version) : !!recs?.length;
|
||
if (owned === mark) continue;
|
||
writes.push(...catchToggleWrites(sp.id, game.id, shiny, pt, index, version).writes);
|
||
n++;
|
||
}
|
||
const label = versionsOf(game.id).find((v) => v.id === version)?.label;
|
||
return { n, writes, what: `${shiny ? 'shiny' : 'caught'}${label ? ` in ${label}` : ''}` };
|
||
}
|
||
|
||
function renderBulk() {
|
||
const mark = bulkPlan(true);
|
||
const clear = bulkPlan(false);
|
||
setHTML($('#filter-bulk'), `<h3>All ${dexShown.length.toLocaleString()} shown</h3><div class="bulk-actions">` +
|
||
`<button type="button" data-bulk="mark" ${mark.n ? '' : 'disabled'}>Mark ${mark.n.toLocaleString()} ${esc(mark.what)}</button>` +
|
||
`<button type="button" data-bulk="clear" ${clear.n ? '' : 'disabled'}>Unmark ${clear.n.toLocaleString()}</button></div>`);
|
||
}
|
||
|
||
async function onBulkTap(e) {
|
||
const btn = e.target.closest('[data-bulk]');
|
||
if (!btn) return;
|
||
const mark = btn.dataset.bulk === 'mark';
|
||
const plan = bulkPlan(mark);
|
||
if (!plan.n) return;
|
||
const count = `${plan.n.toLocaleString()} Pokémon`;
|
||
const yes = await ask(mark ? { title: `Mark ${count} as ${plan.what}?`, ok: 'Mark' }
|
||
: { title: `Unmark ${count}?`, body: `Removes them as ${plan.what}, along with their notes, tags and catch dates.`, ok: 'Unmark' });
|
||
if (!yes) return;
|
||
$('#filter-dlg').close(); // so the result, and the Undo, are in view
|
||
writeWithUndo(plan.writes, mark ? `Marked ${count} as ${plan.what}` : `Unmarked ${count}`, 15000);
|
||
renderDex();
|
||
}
|
||
|
||
function renderDex() {
|
||
renderDexControls();
|
||
renderBadges();
|
||
const game = currentGame();
|
||
const pt = prefs.playthroughId || '';
|
||
const index = catchIndex();
|
||
const has = (id, shiny) => index.has(catchKey({ speciesId: id, gameId: game.id, isShiny: shiny, playthroughId: pt }));
|
||
const vs = versionsOf(game.id);
|
||
// Which copies a species' catch is marked in (regular or shiny record).
|
||
const versionsFor = (id, shiny) => index.get(catchKey({ speciesId: id, gameId: game.id, isShiny: shiny, playthroughId: pt }))?.[0]?.data.versions || [];
|
||
|
||
const dexSpecies = game.species.map((id) => SPECIES_BY_ID.get(id)).filter(Boolean);
|
||
const caughtCount = dexSpecies.filter((s) => has(s.id, false)).length;
|
||
const shinyCount = dexSpecies.filter((s) => has(s.id, true)).length;
|
||
const pct = dexSpecies.length ? Math.round((caughtCount / dexSpecies.length) * 100) : 0;
|
||
const perVersion = vs.map((v) => `${dexSpecies.filter((s) => versionsFor(s.id, false).includes(v.id)).length} ${esc(v.label)}`).join(' · ');
|
||
setHTML($('#dex-progress'),
|
||
`${caughtCount} / ${dexSpecies.length} caught (${pct}%) · ${shinyCount} shiny` +
|
||
(vs.length ? `<span class="per-version">${perVersion}</span>` : '') +
|
||
`<div class="bar"><i style="width:${pct}%"></i></div>`);
|
||
|
||
const q = search.trim().toLowerCase();
|
||
const qNum = /^#?\d+$/.test(q) ? Number(q.replace('#', '')) : null;
|
||
const target = prefs.mode === 'shiny';
|
||
// Notes/tags per species for this game + playthrough.
|
||
const recs = new Map();
|
||
for (const r of live('catch')) {
|
||
const d = r.data;
|
||
if (d.gameId !== game.id || (d.playthroughId || '') !== pt) continue;
|
||
const cur = recs.get(d.speciesId) || { notes: false, tags: [] };
|
||
cur.notes = cur.notes || !!(d.notes || '').trim();
|
||
cur.tags.push(...tagsOf(d.tagsRaw));
|
||
recs.set(d.speciesId, cur);
|
||
}
|
||
const list = dexSpecies.filter((s) => {
|
||
if (prefs.gen !== 'all' && s.generation !== Number(prefs.gen)) return false;
|
||
if (prefs.type !== 'all' && !s.types.includes(prefs.type)) return false;
|
||
if (prefs.tag !== 'all' && !recs.get(s.id)?.tags.includes(prefs.tag)) return false;
|
||
if (prefs.excl !== 'all') {
|
||
const x = exclusiveTo(game.id, s.id);
|
||
if (prefs.excl === 'none' ? x : x !== prefs.excl) return false;
|
||
}
|
||
if (prefs.status !== 'all') {
|
||
const [want, version] = prefs.status.split(':');
|
||
const owned = version ? versionsFor(s.id, target).includes(version) : has(s.id, target);
|
||
if (want === 'caught' ? !owned : owned) return false;
|
||
}
|
||
if (q) {
|
||
// "74" / "#74": that number in this game's dex (any sub-dex) or the national dex.
|
||
const hit = qNum != null
|
||
? DEX_NUMS[game.id]?.nums[s.id]?.[1] === qNum || (s.baseSpeciesId ?? s.id) === qNum
|
||
: dexName(game.id, s).toLowerCase().includes(q) || gameDexNum(game.id, s).toLowerCase().includes(q);
|
||
if (!hit) return false;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
dexShown = list;
|
||
if ($('#filter-dlg').open) renderBulk();
|
||
const layout = boxLayout(game.id);
|
||
const boxed = prefs.view === 'boxes' && !!layout;
|
||
const viewBtn = $('#view-btn');
|
||
viewBtn.hidden = !layout;
|
||
viewBtn.classList.toggle('active', boxed);
|
||
viewBtn.setAttribute('aria-pressed', boxed);
|
||
const grid = $('#dex-grid');
|
||
const compact = prefs.density === 'compact' && !boxed;
|
||
grid.classList.toggle('boxes', boxed);
|
||
grid.classList.toggle('compact', compact);
|
||
const nothing = [{ key: 'empty', html: '<p class="empty">Nothing matches these filters.</p>' }];
|
||
|
||
if (boxed) {
|
||
// Every Pokémon keeps its slot; ones the filters hide are faded, and boxes with no match are left out.
|
||
const match = new Set(list.map((s) => s.id));
|
||
const items = [];
|
||
for (const box of boxesOf(game)) {
|
||
if (!box.species.some((s) => match.has(s.id))) continue;
|
||
const got = box.species.filter((s) => has(s.id, target)).length;
|
||
const range = `${gameDexNum(game.id, box.species[0])} – ${gameDexNum(game.id, box.species[box.species.length - 1])}`;
|
||
items.push({ key: `box-${box.n}`, html: `<section class="box${got === box.species.length ? ' full' : ''}">` +
|
||
`<header><b>Box ${box.n}</b><span>${esc(range)}</span><span class="box-count">${got} / ${box.species.length}</span></header>` +
|
||
`<div class="box-grid" style="--cols:${layout.cols}">` + box.species.map((s) => {
|
||
const caught = has(s.id, false);
|
||
const shiny = has(s.id, true);
|
||
const cls = ['cell', 'bcell', caught && 'caught', shiny && 'shiny', !match.has(s.id) && 'off'].filter(Boolean).join(' ');
|
||
const name = dexName(game.id, s);
|
||
return `<button class="${cls}" data-id="${s.id}" aria-pressed="${target ? shiny : caught}" aria-label="${esc(name)}" title="${esc(name)} ${gameDexNum(game.id, s)}">` +
|
||
`${shiny ? `<span class="badge">${icon('shiny')}</span>` : ''}` +
|
||
spriteImg(s.id, shiny, 'loading="lazy" decoding="async"') + '</button>';
|
||
}).join('') + '</div></section>' });
|
||
}
|
||
morphChildren(grid, items.length ? items : nothing);
|
||
markDetailCell();
|
||
return;
|
||
}
|
||
|
||
morphChildren(grid, list.length ? list.map((s) => {
|
||
const caught = has(s.id, false);
|
||
const shiny = has(s.id, true);
|
||
const cls = ['cell', caught && 'caught', shiny && 'shiny'].filter(Boolean).join(' ');
|
||
// Compact: sprite and number only, with a dot per version it's marked in.
|
||
if (compact) {
|
||
const num = gameDexNum(game.id, s);
|
||
const dots = versionsFor(s.id, target).map((vid) => vs.find((v) => v.id === vid)).filter(Boolean)
|
||
.map((v) => `<i style="background:${v.color}" title="${esc(v.label)}"></i>`).join('');
|
||
const name = dexName(game.id, s);
|
||
return { key: s.id, html: `<button class="${cls}" data-id="${s.id}" aria-pressed="${target ? shiny : caught}" aria-label="${esc(name)}" title="${esc(name)} ${esc(num)}">` +
|
||
`${shiny ? `<span class="badge" title="Shiny owned">${icon('shiny')}</span>` : ''}` +
|
||
`${dots ? `<span class="vdots">${dots}</span>` : ''}` +
|
||
spriteImg(s.id, shiny, 'loading="lazy" decoding="async"') +
|
||
`<span class="num">${esc(num.slice(num.lastIndexOf('#')))}</span></button>` };
|
||
}
|
||
return { key: s.id, html: `<button class="${cls}" data-id="${s.id}" aria-pressed="${target ? shiny : caught}">` +
|
||
`${shiny ? `<span class="badge" title="Shiny owned">${icon('shiny')}</span>` : ''}` +
|
||
`${recs.get(s.id)?.notes ? `<span class="note-dot" title="Has notes">${icon('note')}</span>` : ''}` +
|
||
spriteImg(s.id, shiny, 'loading="lazy" decoding="async"') +
|
||
`<span class="num">${gameDexNum(game.id, s)}</span><span class="name">${esc(dexName(game.id, s))}</span>` +
|
||
(vs.length ? `<span class="vtags">${exclusiveTag(game.id, s.id)}${versionsFor(s.id, target).map((v) => versionTag(game.id, v)).join('')}</span>` : '') +
|
||
`</button>` };
|
||
}) : nothing);
|
||
markDetailCell();
|
||
}
|
||
|
||
// ---- Wide screens: details panel beside the dex, arrow keys in the grid ---------
|
||
// On a wide window the detail sheet docks to the right of the dex instead of
|
||
// covering it, so the grid stays usable. It shows the Pokémon last opened, and
|
||
// follows the arrow keys.
|
||
const WIDE = matchMedia('(min-width: 1100px)');
|
||
const detailDocks = () => WIDE.matches && prefs.tab === 'dex' && !document.querySelector('dialog:modal');
|
||
const detailDocked = () => $('#detail-dlg').open && $('#detail-dlg').classList.contains('docked');
|
||
function closeDockedDetail() {
|
||
if (detailDocked()) $('#detail-dlg').close();
|
||
}
|
||
// Outlines the cell whose details are in the docked panel.
|
||
function markDetailCell() {
|
||
const id = detailDocked() ? String(detailState.id) : null;
|
||
for (const el of document.querySelectorAll('#dex-grid .cell.sel')) if (el.dataset.id !== id) el.classList.remove('sel');
|
||
if (id) $(`#dex-grid .cell[data-id="${id}"]`)?.classList.add('sel');
|
||
}
|
||
|
||
// Arrow keys move between Pokémon (Home / End jump to the ends); Enter or Space
|
||
// marks the focused one as a tap would, and I opens its details.
|
||
let followTimer = null;
|
||
function onDexKey(e) {
|
||
const cell = e.target.closest?.('.cell');
|
||
if (!cell || e.ctrlKey || e.metaKey || e.altKey) return;
|
||
if (e.key === 'i' || e.key === 'I') {
|
||
e.preventDefault();
|
||
openDetail(Number(cell.dataset.id));
|
||
return;
|
||
}
|
||
if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(e.key)) return;
|
||
const cells = [...document.querySelectorAll('#dex-grid .cell')];
|
||
const i = cells.indexOf(cell);
|
||
let next = null;
|
||
if (e.key === 'ArrowLeft') next = cells[i - 1];
|
||
else if (e.key === 'ArrowRight') next = cells[i + 1];
|
||
else if (e.key === 'Home') next = cells[0];
|
||
else if (e.key === 'End') next = cells[cells.length - 1];
|
||
else {
|
||
// Up / Down: the nearest row that way, then the closest cell across (works for box view too).
|
||
const from = cell.getBoundingClientRect();
|
||
const dir = e.key === 'ArrowDown' ? 1 : -1;
|
||
let best = Infinity;
|
||
for (const c of cells) {
|
||
const r = c.getBoundingClientRect();
|
||
const dy = (r.top - from.top) * dir;
|
||
if (dy < 2) continue;
|
||
const score = dy * 10000 + Math.abs(r.left + r.width / 2 - (from.left + from.width / 2));
|
||
if (score < best) { best = score; next = c; }
|
||
}
|
||
}
|
||
e.preventDefault();
|
||
if (!next || next === cell) return;
|
||
next.focus({ preventScroll: true });
|
||
next.scrollIntoView({ block: 'nearest' });
|
||
if (detailDocked()) {
|
||
clearTimeout(followTimer);
|
||
const id = Number(next.dataset.id);
|
||
followTimer = setTimeout(() => { if (detailDocked() && detailState.id !== id) openDetail(id); }, 180);
|
||
}
|
||
}
|
||
|
||
// After a search or filter changes the list: if its start has scrolled up out of
|
||
// view, bring it back to just under the pinned bar.
|
||
function showDexStart() {
|
||
const bar = $('.pinbar').getBoundingClientRect();
|
||
const top = $('#dex-grid').getBoundingClientRect().top;
|
||
if (top < bar.bottom) window.scrollBy(0, top - bar.bottom);
|
||
}
|
||
|
||
// Long-press (touch) or right-click (mouse) on a cell opens its detail sheet.
|
||
let pressTimer = null;
|
||
let pressStart = null;
|
||
let suppressClick = false;
|
||
function onDexPointerDown(e) {
|
||
const cell = e.target.closest('.cell');
|
||
if (!cell || e.button > 0) return;
|
||
pressStart = { x: e.clientX, y: e.clientY };
|
||
clearTimeout(pressTimer);
|
||
pressTimer = setTimeout(() => {
|
||
suppressClick = true;
|
||
openDetail(Number(cell.dataset.id));
|
||
}, 450);
|
||
}
|
||
function onDexPointerMove(e) {
|
||
if (pressStart && Math.hypot(e.clientX - pressStart.x, e.clientY - pressStart.y) > 10) cancelPress();
|
||
}
|
||
function cancelPress() { clearTimeout(pressTimer); pressStart = null; }
|
||
|
||
function onDexTap(e) {
|
||
const cell = e.target.closest('.cell');
|
||
if (!cell) return;
|
||
if (suppressClick) { suppressClick = false; return; }
|
||
const id = Number(cell.dataset.id);
|
||
if (prefs.mode === 'info') { openDetail(id); return; }
|
||
const game = currentGame();
|
||
const focused = document.activeElement === cell;
|
||
const added = tapCatch(id, game.id, prefs.mode === 'shiny', prefs.playthroughId || null, activeVersion(game.id));
|
||
renderDex();
|
||
// The cell is rebuilt when its state changes: keep the keyboard on it.
|
||
if (focused) $(`#dex-grid .cell[data-id="${id}"]`)?.focus({ preventScroll: true });
|
||
if (added) {
|
||
const fresh = $(`#dex-grid .cell[data-id="${id}"]`);
|
||
fresh?.classList.add('pop');
|
||
fresh?.addEventListener('animationend', () => fresh.classList.remove('pop'), { once: true });
|
||
}
|
||
}
|
||
|
||
// ---- Hunts ----------------------------------------------------------------
|
||
const activeHunts = () => live('hunt').filter((h) => !h.data.completedAt && !h.data.abandonedAt)
|
||
.sort((a, b) => b.data.startedAt.localeCompare(a.data.startedAt));
|
||
|
||
// With a keyboard, Space adds +1 to one hunt: the last one clicked, else the top one.
|
||
const hasKeyboard = matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||
let keyHuntId = null;
|
||
function keyHunt() {
|
||
const active = activeHunts();
|
||
return active.find((h) => h.id === keyHuntId) || active[0] || null;
|
||
}
|
||
|
||
function bumpHunt(id, step = 1) {
|
||
const row = store.rows.get(id);
|
||
if (!row) return;
|
||
write('hunt', id, { ...row.data, encounters: Math.max(0, (row.data.encounters || 0) + step) }, false, true);
|
||
renderHunts();
|
||
keepAwake();
|
||
}
|
||
|
||
function onHuntKey(e) {
|
||
if (e.code !== 'Space' || e.repeat || prefs.tab !== 'hunts' || $('#app').hidden) return;
|
||
if (document.querySelector('dialog:modal')) return;
|
||
if (e.target.closest?.('button, input, select, textarea, summary, a')) return;
|
||
const hunt = keyHunt();
|
||
if (!hunt) return;
|
||
e.preventDefault();
|
||
bumpHunt(hunt.id);
|
||
}
|
||
|
||
// Counting keeps the screen on: the lock is held on the Hunts tab while there's
|
||
// an active hunt, and let go after ten minutes without a tap.
|
||
let wakeLock = null;
|
||
let wakeTimer = null;
|
||
async function keepAwake() {
|
||
clearTimeout(wakeTimer);
|
||
wakeTimer = setTimeout(releaseWake, 600000);
|
||
if (wakeLock || !navigator.wakeLock || document.visibilityState !== 'visible') return;
|
||
try {
|
||
const lock = await navigator.wakeLock.request('screen');
|
||
if (prefs.tab !== 'hunts') { lock.release().catch(() => {}); return; }
|
||
wakeLock = lock;
|
||
lock.addEventListener('release', () => { if (wakeLock === lock) wakeLock = null; });
|
||
} catch { /* low battery or not allowed: the screen just follows its usual timeout */ }
|
||
}
|
||
function releaseWake() {
|
||
clearTimeout(wakeTimer);
|
||
wakeLock?.release().catch(() => {});
|
||
wakeLock = null;
|
||
}
|
||
function updateWake() {
|
||
if (prefs.tab === 'hunts' && !$('#app').hidden && activeHunts().length) keepAwake();
|
||
else releaseWake();
|
||
}
|
||
|
||
function renderHunts() {
|
||
const hunts = live('hunt');
|
||
const phases = live('phase');
|
||
const active = activeHunts();
|
||
const keyed = hasKeyboard && active.length > 1 ? keyHunt()?.id : null;
|
||
const hint = $('#hunt-hint');
|
||
hint.hidden = !hasKeyboard || !active.length;
|
||
hint.textContent = active.length > 1 ? 'Tip: Space adds +1 to the outlined hunt. Click a hunt to pick it.' : 'Tip: press Space to add +1.';
|
||
const done = hunts.filter((h) => h.data.completedAt)
|
||
.sort((a, b) => b.data.completedAt.localeCompare(a.data.completedAt));
|
||
const abandoned = hunts.filter((h) => !h.data.completedAt && h.data.abandonedAt);
|
||
|
||
const card = (h) => {
|
||
const d = h.data;
|
||
const odds = huntOdds(d);
|
||
const myPhases = phases.filter((p) => p.data.huntId === h.id)
|
||
.sort((a, b) => b.data.endedAt.localeCompare(a.data.endedAt));
|
||
const nPhases = myPhases.length;
|
||
const sincePhase = nPhases ? (d.encounters || 0) - Math.max(...myPhases.map((p) => p.data.encountersAtPhase || 0)) : null;
|
||
return `<article class="hunt${h.id === keyed ? ' keyed' : ''}" data-id="${esc(h.id)}">
|
||
<div class="hunt-head">
|
||
${spriteImg(d.speciesId, true)}
|
||
<div class="meta">
|
||
<h3>${esc(speciesName(d.speciesId))}</h3>
|
||
<div class="sub">${huntGame(d) ? `${esc(huntGame(d).shortName)} · ` : ''}${esc(d.method)}${d.shinyCharm ? ' · Shiny Charm' : ''}${nPhases ? ` · ${nPhases} phase${nPhases > 1 ? 's' : ''}` : ''}</div>
|
||
</div>
|
||
</div>
|
||
<div class="counter">
|
||
<button class="minus" data-act="minus" aria-label="Minus one">−</button>
|
||
<button class="count" data-act="set" aria-label="Set encounters">${(d.encounters || 0).toLocaleString()}</button>
|
||
<span style="width:56px"></span>
|
||
</div>
|
||
<button class="plus" data-act="plus">+1</button>
|
||
${modifierRow(d)}
|
||
<div class="odds">1/${odds.oneIn.toLocaleString()} odds · ${(odds.cumulative * 100).toFixed(1)}% chance of a shiny by now` +
|
||
`${sincePhase != null ? ` · ${sincePhase.toLocaleString()} since last phase` : ''}</div>
|
||
${d.notes ? `<p class="hunt-notes">${esc(d.notes)}</p>` : ''}
|
||
<div class="hunt-actions">
|
||
<button class="caught-btn" data-act="caught">${icon('shiny')}Caught it!</button>
|
||
<button data-act="phase">Phase</button>
|
||
<button data-act="notes">Notes</button>
|
||
<button data-act="charm">${d.shinyCharm ? '− Charm' : '+ Charm'}</button>
|
||
<button data-act="abandon">Abandon</button>
|
||
</div>
|
||
${nPhases ? `<details class="phases"><summary>Phases (${nPhases})</summary>${myPhases.map(phaseRow).join('')}</details>` : ''}
|
||
</article>`;
|
||
};
|
||
|
||
const phaseRow = (p) => `<div class="phase" data-phase="${esc(p.id)}">
|
||
${spriteImg(p.data.speciesId, true, 'loading="lazy"')}
|
||
<div class="meta"><b>${esc(speciesName(p.data.speciesId))}</b>
|
||
<small>at encounter ${(p.data.encountersAtPhase || 0).toLocaleString()} · ${new Date(p.data.endedAt).toLocaleDateString()}</small>
|
||
${p.data.notes ? `<small>${esc(p.data.notes)}</small>` : ''}</div>
|
||
<button class="ghost" data-act="del-phase" aria-label="Delete phase">✕</button>
|
||
</div>`;
|
||
|
||
// Same method-specific modifiers the Mac's HuntDetailView exposes.
|
||
const modifierRow = (d) => {
|
||
let label, value;
|
||
if (d.method === 'Sparkling Power Sandwich') { label = 'Sparkling Power Lv'; value = d.sandwichLevel || 0; }
|
||
else if (CHAIN_LABELS[d.method]) { label = CHAIN_LABELS[d.method]; value = d.chainCount || 0; }
|
||
else return '';
|
||
return `<div class="modifier"><span>${label}</span>` +
|
||
`<button data-act="mod-minus" aria-label="Decrease">−</button><b>${value}</b>` +
|
||
`<button data-act="mod-plus" aria-label="Increase">+</button></div>`;
|
||
};
|
||
|
||
const mini = (h, button) => `<div class="mini" data-id="${esc(h.id)}">
|
||
${spriteImg(h.data.speciesId, true, 'loading="lazy"')}
|
||
<div class="meta">${esc(speciesName(h.data.speciesId))}
|
||
<small>${(h.data.encounters || 0).toLocaleString()} encounters · ${esc(h.data.method)}${huntGame(h.data) ? ` · ${esc(huntGame(h.data).shortName)}` : ''}</small></div>
|
||
${button}
|
||
</div>`;
|
||
|
||
morphChildren($('#hunt-list'), [
|
||
...(active.length ? active.map((h) => ({ key: h.id, html: card(h) })) : [{ key: 'empty', html: '<p class="empty">No active hunts. Start one above.</p>' }]),
|
||
...(done.length ? [{ key: 'done', html: `<details class="archive"><summary>Caught (${done.length})</summary>${done.map((h) => mini(h, '')).join('')}</details>` }] : []),
|
||
...(abandoned.length ? [{ key: 'abandoned', html: `<details class="archive"><summary>Abandoned (${abandoned.length})</summary>${abandoned.map((h) => mini(h, '<button data-act="resurrect">Resurrect</button>')).join('')}</details>` }] : []),
|
||
]);
|
||
}
|
||
|
||
// The game a hunt is being done in (hunts started before this was saved have none).
|
||
const huntGame = (d) => (d.gameId && GAMES.find((g) => g.id === d.gameId)) || null;
|
||
|
||
let countHuntId = null;
|
||
let caughtHuntId = null;
|
||
let phaseHuntId = null;
|
||
let notesHuntId = null;
|
||
|
||
function onHuntTap(e) {
|
||
// Clicking anywhere on an active hunt makes it the one Space counts for.
|
||
const card = e.target.closest('article.hunt');
|
||
if (card && card.dataset.id !== keyHuntId) {
|
||
keyHuntId = card.dataset.id;
|
||
if (!e.target.closest('[data-act]')) renderHunts();
|
||
}
|
||
const btn = e.target.closest('[data-act]');
|
||
if (!btn) return;
|
||
const id = btn.closest('article[data-id], .mini[data-id]').dataset.id;
|
||
const row = store.rows.get(id);
|
||
if (!row) return;
|
||
const d = { ...row.data };
|
||
switch (btn.dataset.act) {
|
||
case 'plus': bumpHunt(id, 1); return;
|
||
case 'minus': bumpHunt(id, -1); return;
|
||
case 'charm': d.shinyCharm = !d.shinyCharm; break;
|
||
case 'mod-minus':
|
||
case 'mod-plus': {
|
||
const step = btn.dataset.act === 'mod-plus' ? 1 : -1;
|
||
if (d.method === 'Sparkling Power Sandwich') d.sandwichLevel = Math.max(0, Math.min(3, (d.sandwichLevel || 0) + step));
|
||
else d.chainCount = Math.max(0, (d.chainCount || 0) + step);
|
||
write('hunt', id, d, false, true);
|
||
renderHunts();
|
||
return;
|
||
}
|
||
case 'abandon':
|
||
ask({ title: `Abandon the ${speciesName(d.speciesId)} hunt?`, body: 'You can resurrect it later from the Abandoned list.', ok: 'Abandon' }).then((yes) => {
|
||
const cur = store.rows.get(id);
|
||
if (!yes || !cur) return;
|
||
write('hunt', id, { ...cur.data, abandonedAt: nowISO() });
|
||
renderHunts();
|
||
});
|
||
return;
|
||
case 'resurrect': d.abandonedAt = null; break;
|
||
case 'set':
|
||
countHuntId = id;
|
||
$('#count-input').value = d.encounters || 0;
|
||
openDialog($('#count-dlg'));
|
||
$('#count-input').select();
|
||
return;
|
||
case 'phase':
|
||
phaseHuntId = id;
|
||
phasePicker.reset();
|
||
$('#phase-notes').value = '';
|
||
$('#phase-sub').textContent = `Log a non-target shiny found during your ${speciesName(d.speciesId)} hunt. It's recorded at encounter ${(d.encounters || 0).toLocaleString()}; the count keeps running.`;
|
||
openDialog($('#phase-dlg'));
|
||
return;
|
||
case 'del-phase': {
|
||
const pid = btn.closest('[data-phase]').dataset.phase;
|
||
const prow = store.rows.get(pid);
|
||
if (!prow) return;
|
||
ask({ title: `Delete the ${speciesName(prow.data.speciesId)} phase?`, ok: 'Delete' }).then((yes) => {
|
||
if (!yes) return;
|
||
write('phase', pid, prow.data, true);
|
||
renderHunts();
|
||
});
|
||
return;
|
||
}
|
||
case 'notes':
|
||
notesHuntId = id;
|
||
$('#notes-input').value = d.notes || '';
|
||
openDialog($('#notes-dlg'));
|
||
return;
|
||
case 'caught':
|
||
caughtHuntId = id;
|
||
$('#caught-name').textContent = `${speciesName(d.speciesId)} after ${(d.encounters || 0).toLocaleString()} encounters`;
|
||
$('#caught-game').value = huntGame(d)?.id || prefs.lastCaughtGame;
|
||
caughtVersion = null;
|
||
renderCaughtVersions();
|
||
openDialog($('#caught-dlg'));
|
||
return;
|
||
}
|
||
write('hunt', id, d);
|
||
renderHunts();
|
||
}
|
||
|
||
// Species search box + result list, used by the New Hunt and Phase dialogs.
|
||
function makeSpeciesPicker(input, results, onPick = () => {}) {
|
||
const picker = {
|
||
picked: null,
|
||
reset() { picker.picked = null; input.value = ''; results.innerHTML = ''; onPick(null); },
|
||
render() {
|
||
const q = input.value.trim().toLowerCase();
|
||
if (!q || (picker.picked && speciesName(picker.picked).toLowerCase() === q)) { results.innerHTML = ''; return; }
|
||
const matches = SPECIES.filter((s) => s.name.toLowerCase().includes(q) || String(s.id) === q).slice(0, 20);
|
||
results.innerHTML = matches.map((s) =>
|
||
`<button type="button" data-id="${s.id}" class="${s.id === picker.picked ? 'on' : ''}">` +
|
||
`${spriteImg(s.id, true, 'loading="lazy"')}${esc(s.name)} <span class="muted">${dexNum(s)}</span></button>`).join('')
|
||
|| '<p class="muted">No Pokémon by that name.</p>';
|
||
},
|
||
// Accept an exact typed name even if no result was tapped.
|
||
resolve() {
|
||
if (picker.picked) return picker.picked;
|
||
const exact = SPECIES.find((s) => s.name.toLowerCase() === input.value.trim().toLowerCase());
|
||
return exact ? exact.id : null;
|
||
},
|
||
};
|
||
input.addEventListener('input', () => { picker.picked = null; onPick(null); picker.render(); });
|
||
results.addEventListener('click', (e) => {
|
||
const b = e.target.closest('button[data-id]');
|
||
if (!b) return;
|
||
picker.picked = Number(b.dataset.id);
|
||
input.value = speciesName(picker.picked);
|
||
picker.render();
|
||
onPick(picker.picked);
|
||
});
|
||
return picker;
|
||
}
|
||
|
||
// "Shiny caught!" dialog: which copy of a paired game it's in. Starts on the
|
||
// version the dex is marking for that game.
|
||
let caughtVersion = null;
|
||
function renderCaughtVersions() {
|
||
const gameId = $('#caught-game').value;
|
||
const vs = versionsOf(gameId);
|
||
if (!vs.some((v) => v.id === caughtVersion)) caughtVersion = activeVersion(gameId);
|
||
$('#caught-version-field').hidden = !vs.length;
|
||
$('#caught-versions').innerHTML = vs.map((v) =>
|
||
`<button type="button" class="vbtn ${v.id === caughtVersion ? 'on' : ''}" style="--vc:${v.color}" data-version="${v.id}" aria-pressed="${v.id === caughtVersion}">${esc(v.label)}</button>`).join('');
|
||
}
|
||
|
||
let huntPicker = null;
|
||
let phasePicker = null;
|
||
let huntMods = {}; // sandwich/chain values from a tapped recommendation
|
||
|
||
function renderRecommendations(speciesId) {
|
||
const el = $('#hunt-recs');
|
||
huntMods = {};
|
||
if (!speciesId) { el.innerHTML = ''; return; }
|
||
const recs = recommendMethods(speciesId);
|
||
el.innerHTML = recs.length
|
||
? `<p class="muted">Best odds for ${esc(speciesName(speciesId))} — tap one to use it:</p>` + recs.map((r, i) =>
|
||
`<button type="button" class="rec" data-rec="${i}"><b>${esc(r.game.shortName)}</b>` +
|
||
`<span>${esc(r.summary)}</span><em>1/${r.odds.oneIn.toLocaleString()}</em></button>`).join('')
|
||
: `<p class="muted">${esc(speciesName(speciesId))} can't be shiny hunted in the tracked mainline games.</p>`;
|
||
el.onclick = (e) => {
|
||
const b = e.target.closest('[data-rec]');
|
||
if (!b) return;
|
||
const r = recs[Number(b.dataset.rec)];
|
||
$('#hunt-game').value = r.game.id;
|
||
$('#hunt-method').value = r.method;
|
||
$('#hunt-charm').checked = r.charm;
|
||
huntMods = { sandwichLevel: r.mods.sandwichLevel || 0, chainCount: r.mods.chainCount || 0 };
|
||
el.querySelectorAll('.rec').forEach((x) => x.classList.toggle('on', x === b));
|
||
};
|
||
}
|
||
|
||
// ---- Stats ----------------------------------------------------------------
|
||
const ALMOST_DONE = 12; // a game with this few left gets its missing Pokémon listed
|
||
|
||
function renderStats() {
|
||
const catches = live('catch').map((r) => r.data);
|
||
const regular = catches.filter((c) => !c.isShiny);
|
||
const shiny = catches.filter((c) => c.isShiny);
|
||
const hunts = live('hunt').map((r) => r.data);
|
||
const doneHunts = hunts.filter((h) => h.completedAt);
|
||
const activeCount = hunts.filter((h) => !h.completedAt && !h.abandonedAt).length;
|
||
const avg = doneHunts.length
|
||
? Math.round(doneHunts.reduce((n, h) => n + (h.encounters || 0), 0) / doneHunts.length) : 0;
|
||
|
||
const toHome = toHomeData(false).total;
|
||
|
||
const tile = (n, label) => `<div class="tile"><b>${n.toLocaleString()}</b><span>${label}</span></div>`;
|
||
const bar = (name, n, total) => `<div class="game-row"><div class="line"><span>${esc(name)}</span>` +
|
||
`<span>${n} / ${total}</span></div><div class="bar"><i style="width:${(total ? (n / total) * 100 : 0).toFixed(1)}%"></i></div></div>`;
|
||
|
||
const byGame = new Map();
|
||
for (const c of regular) {
|
||
if (!byGame.has(c.gameId)) byGame.set(c.gameId, new Set());
|
||
byGame.get(c.gameId).add(c.speciesId);
|
||
}
|
||
const games = GAMES.map((g) => {
|
||
const have = byGame.get(g.id) || new Set();
|
||
const missing = g.species.filter((id) => !have.has(id));
|
||
return { g, caught: g.species.length - missing.length, missing };
|
||
});
|
||
const started = games.filter((x) => x.caught > 0);
|
||
const idle = games.filter((x) => x.caught === 0);
|
||
|
||
// Games within reach of a full dex, closest first, with what's still missing.
|
||
const almost = started.filter((x) => x.missing.length > 0 && x.missing.length <= ALMOST_DONE)
|
||
.sort((a, b) => a.missing.length - b.missing.length);
|
||
const almostCard = almost.length ? `<div class="card"><h2>Almost complete</h2>` + almost.map(({ g, missing }) =>
|
||
`<div class="game-row"><div class="line"><span>${esc(g.name)}</span><span>${missing.length} to go</span></div>` +
|
||
`<div class="missing">${missing.map((id) => `<button data-id="${id}" title="${esc(speciesName(id))}" aria-label="${esc(speciesName(id))}">` +
|
||
`${spriteImg(id, false, 'loading="lazy"')}</button>`).join('')}</div></div>`).join('') + '</div>' : '';
|
||
|
||
// National Dex by generation: species caught in any game (regional forms not counted).
|
||
const haveAny = new Set(regular.map((c) => SPECIES_BY_ID.get(c.speciesId)?.baseSpeciesId ?? c.speciesId));
|
||
const gens = new Map();
|
||
for (const sp of SPECIES) {
|
||
if ((sp.baseSpeciesId ?? sp.id) !== sp.id) continue;
|
||
const cur = gens.get(sp.generation) || { n: 0, total: 0 };
|
||
cur.total++;
|
||
if (haveAny.has(sp.id)) cur.n++;
|
||
gens.set(sp.generation, cur);
|
||
}
|
||
const genRows = [...gens.entries()].sort((a, b) => a[0] - b[0]).map(([gen, x]) => bar(`Gen ${gen}`, x.n, x.total)).join('');
|
||
|
||
setHTML($('#stats'), `<div class="tiles">
|
||
${tile(new Set(regular.map((c) => c.speciesId)).size, 'unique species caught')}
|
||
${tile(new Set(shiny.map((c) => c.speciesId)).size, 'unique shinies')}
|
||
${tile(catches.length, 'catch records')}
|
||
${tile(activeCount, 'active hunts')}
|
||
${tile(doneHunts.length, 'shinies from hunts')}
|
||
${tile(avg, 'avg encounters per shiny')}
|
||
</div>
|
||
<button class="card link-card" data-act="compare"><span>Compare two games</span><span class="muted">What one has that the other doesn't ›</span></button>
|
||
<button class="card link-card" data-act="tohome"><span>Move to HOME</span><span class="muted">${toHome
|
||
? `${toHome.toLocaleString()} caught in your games ${toHome === 1 ? "isn't" : "aren't"} in HOME yet ›` : "What's caught in a game but not in HOME ›"}</span></button>
|
||
${almostCard}
|
||
<div class="card"><h2>Progress by game</h2>
|
||
${started.map((x) => bar(x.g.name, x.caught, x.g.species.length)).join('') || '<p class="muted">Nothing caught yet.</p>'}
|
||
${idle.length && started.length ? `<details class="idle-games"><summary>Not started (${idle.length})</summary>` +
|
||
`${idle.map((x) => bar(x.g.name, 0, x.g.species.length)).join('')}</details>` : ''}
|
||
</div>
|
||
<div class="card"><h2>National Dex by generation</h2>${genRows}</div>`);
|
||
}
|
||
|
||
// ---- Account --------------------------------------------------------------
|
||
// ---- Backup ---------------------------------------------------------------
|
||
// A backup is every live record as JSON: {app, format, exportedAt, records:[{id, kind, data}]}.
|
||
// Restoring merges: records from the file are added back or reset to the
|
||
// backup's version; anything created since the backup is left alone.
|
||
const BACKUP_FORMAT = 1;
|
||
const BACKUP_CHECKS = {
|
||
catch: (d) => Number.isInteger(d.speciesId) && typeof d.gameId === 'string',
|
||
hunt: (d) => Number.isInteger(d.speciesId) && typeof d.startedAt === 'string',
|
||
phase: (d) => typeof d.huntId === 'string' && Number.isInteger(d.speciesId),
|
||
playthrough: (d) => typeof d.name === 'string' && typeof d.gameId === 'string',
|
||
badge: (d) => typeof d.gameId === 'string' && typeof d.badgeId === 'string',
|
||
};
|
||
const BACKUP_LABELS = [['catch', 'catch', 'catches'], ['hunt', 'hunt', 'hunts'], ['phase', 'phase', 'phases'],
|
||
['playthrough', 'playthrough', 'playthroughs'], ['badge', 'badge', 'badges']];
|
||
|
||
function describeRecords(records) {
|
||
const parts = BACKUP_LABELS.map(([kind, one, many]) => {
|
||
const n = records.filter((r) => r.kind === kind).length;
|
||
return n ? `${n.toLocaleString()} ${n === 1 ? one : many}` : '';
|
||
}).filter(Boolean);
|
||
return parts.length ? parts.join(', ') : 'nothing yet';
|
||
}
|
||
|
||
function renderBackup() {
|
||
const last = prefs.lastBackupAt ? new Date(prefs.lastBackupAt) : null;
|
||
const days = last ? Math.floor((Date.now() - last) / 86400000) : null;
|
||
$('#backup-status').textContent = !last ? 'No backup downloaded on this device yet'
|
||
: `Last downloaded ${days === 0 ? 'today' : days === 1 ? 'yesterday' : last.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' })}` +
|
||
(days >= 30 ? ' · time for a fresh one' : '');
|
||
}
|
||
|
||
function backupMessage(text, ok = true) {
|
||
const msg = $('#backup-msg');
|
||
msg.textContent = text;
|
||
msg.classList.toggle('ok', ok);
|
||
}
|
||
|
||
// Hands a file to the user. Phones: the share sheet (Save to Files / Drive).
|
||
// Computers: a normal download. False when the share sheet was dismissed.
|
||
async function saveFile(file) {
|
||
if (matchMedia('(pointer: coarse)').matches && navigator.canShare?.({ files: [file] })) {
|
||
try {
|
||
await navigator.share({ files: [file], title: file.name });
|
||
} catch (e) {
|
||
if (e.name === 'AbortError') return false;
|
||
throw e;
|
||
}
|
||
} else {
|
||
const url = URL.createObjectURL(file);
|
||
const a = Object.assign(document.createElement('a'), { href: url, download: file.name });
|
||
document.body.append(a);
|
||
a.click();
|
||
a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// ---- CSV export -------------------------------------------------------------
|
||
// Every catch as a spreadsheet row. Same columns as the Mac app's export, plus
|
||
// `versions` (which copy of a paired game). For reading in a spreadsheet only:
|
||
// the JSON backup is the one that can be restored.
|
||
const CSV_COLUMNS = ['species_id', 'species_name', 'game_id', 'game_name', 'is_shiny', 'playthrough_id',
|
||
'playthrough_name', 'versions', 'notes', 'tags', 'caught_at'];
|
||
const csvCell = (value) => {
|
||
const text = String(value ?? '');
|
||
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
||
};
|
||
|
||
// Rows in game order, then playthrough, then each game's dex order, regular before shiny.
|
||
function buildCatchesCSV() {
|
||
const gameAt = new Map(GAMES.map((g, i) => [g.id, i]));
|
||
const dexAt = new Map(GAMES.map((g) => [g.id, new Map(g.species.map((id, i) => [id, i]))]));
|
||
const place = (d) => [gameAt.get(d.gameId) ?? 999, d.playthroughId || '', dexAt.get(d.gameId)?.get(d.speciesId) ?? 99999, d.isShiny ? 1 : 0];
|
||
const catches = live('catch').map((r) => r.data).sort((a, b) => {
|
||
const p = place(a), q = place(b);
|
||
return p[0] - q[0] || String(p[1]).localeCompare(String(q[1])) || p[2] - q[2] || p[3] - q[3];
|
||
});
|
||
const lines = catches.map((d) => {
|
||
const game = GAMES.find((g) => g.id === d.gameId);
|
||
const labels = (d.versions || []).map((vid) => versionsOf(d.gameId).find((v) => v.id === vid)?.label || vid);
|
||
return [d.speciesId, speciesName(d.speciesId), d.gameId, game?.name || d.gameId, d.isShiny ? 'true' : 'false',
|
||
d.playthroughId || '', d.playthroughId ? store.rows.get(d.playthroughId)?.data.name || '' : 'Main',
|
||
labels.join('; '), d.notes || '', tagsOf(d.tagsRaw).join(', '), d.caughtAt || ''].map(csvCell).join(',');
|
||
});
|
||
return { count: catches.length, text: [CSV_COLUMNS.join(','), ...lines].join('\r\n') + '\r\n' };
|
||
}
|
||
|
||
// Returns what to tell the user, or '' when the share sheet was dismissed.
|
||
async function exportCSV() {
|
||
const { count, text } = buildCatchesCSV();
|
||
if (!count) return 'No catches to export yet.';
|
||
const name = `poketracker-catches-${localDate(nowISO())}.csv`;
|
||
// The leading BOM makes Excel read names like Flabébé as UTF-8.
|
||
if (!await saveFile(new File(['\uFEFF', text], name, { type: 'text/csv' }))) return '';
|
||
return `Saved ${name} (${count.toLocaleString()} catch${count === 1 ? '' : 'es'}).`;
|
||
}
|
||
|
||
async function exportBackup() {
|
||
const records = [...store.rows.values()].filter((r) => !r.deleted && BACKUP_CHECKS[r.kind])
|
||
.map(({ id, kind, data }) => ({ id, kind, data }));
|
||
const now = new Date();
|
||
const json = JSON.stringify({ app: 'PokéTracker', format: BACKUP_FORMAT, exportedAt: now.toISOString(), records }, null, 1);
|
||
const name = `poketracker-backup-${localDate(now.toISOString())}.json`;
|
||
if (!await saveFile(new File([json], name, { type: 'application/json' }))) return;
|
||
prefs.lastBackupAt = now.toISOString();
|
||
savePrefs();
|
||
renderBackup();
|
||
backupMessage(`Saved ${name} (${describeRecords(records)}).`);
|
||
}
|
||
|
||
async function importBackup(file) {
|
||
let parsed;
|
||
try { parsed = JSON.parse(await file.text()); } catch { parsed = null; }
|
||
if (!parsed || !Array.isArray(parsed.records) || parsed.format !== BACKUP_FORMAT) {
|
||
throw new Error("That file isn't a PokéTracker backup.");
|
||
}
|
||
const okId = (id) => typeof id === 'string' && /^[^/]{1,200}$/.test(id) && !/^\.\.?$|^__.*__$/.test(id);
|
||
const records = parsed.records.filter((r) => r && okId(r.id) && BACKUP_CHECKS[r.kind]
|
||
&& r.data && typeof r.data === 'object' && !Array.isArray(r.data) && BACKUP_CHECKS[r.kind](r.data));
|
||
const skipped = parsed.records.length - records.length;
|
||
const restore = [];
|
||
let same = 0;
|
||
for (const r of records) {
|
||
const cur = store.rows.get(r.id);
|
||
if (cur && cur.kind !== r.kind) continue;
|
||
if (cur && !cur.deleted && JSON.stringify(cur.data) === JSON.stringify(r.data)) { same++; continue; }
|
||
restore.push({ ...r, isNew: !cur || cur.deleted });
|
||
}
|
||
const when = new Date(parsed.exportedAt);
|
||
const from = Number.isNaN(when.getTime()) ? 'this backup' : `the ${when.toLocaleDateString([], { month: 'short', day: 'numeric', year: 'numeric' })} backup`;
|
||
if (!restore.length) {
|
||
backupMessage(`Everything in ${from} is already here (${describeRecords(records)}).`);
|
||
return;
|
||
}
|
||
const added = restore.filter((r) => r.isNew);
|
||
const changed = restore.filter((r) => !r.isNew);
|
||
const lines = [
|
||
added.length ? `• Add back ${describeRecords(added)}` : '',
|
||
changed.length ? `• Reset ${describeRecords(changed)} to the backup's version` : '',
|
||
same ? `• ${same.toLocaleString()} already match` : '',
|
||
skipped ? `• ${skipped.toLocaleString()} unreadable entr${skipped === 1 ? 'y' : 'ies'} will be skipped` : '',
|
||
].filter(Boolean).join('\n');
|
||
if (!await ask({ title: `Restore from ${from}?`, body: `${lines}\n\nAnything added since the backup stays.`, ok: 'Restore' })) return;
|
||
writeMany(restore.map(({ id, kind, data }) => ({ id, kind, data })));
|
||
render();
|
||
backupMessage(`Restored ${describeRecords(restore)}. Uploading to your account…`);
|
||
}
|
||
|
||
function renderAccount() {
|
||
$('#account-email').textContent = `Signed in as ${store.email || ''}`;
|
||
let s;
|
||
if (store.status === 'error') s = store.error;
|
||
else if (store.status === 'busy') s = signedIn() ? 'Syncing…' : 'Connecting…';
|
||
else s = store.lastSync ? `Up to date · last synced ${store.lastSync.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}` : 'Waiting to sync…';
|
||
if (store.pending.size) s += ` · ${store.pending.size} change${store.pending.size > 1 ? 's' : ''} waiting to upload`;
|
||
$('#account-status').textContent = s;
|
||
$('#account-status').classList.toggle('err', store.status === 'error');
|
||
renderBackup();
|
||
}
|
||
|
||
function authMessage(err) {
|
||
switch (err?.code) {
|
||
case 'auth/invalid-credential':
|
||
case 'auth/wrong-password':
|
||
case 'auth/user-not-found': return 'Wrong email or password.';
|
||
case 'auth/email-already-in-use': return 'That email already has an account. Sign in instead (or use Continue with Google if you made it that way).';
|
||
case 'auth/weak-password': return 'Password must be at least 6 characters.';
|
||
case 'auth/invalid-email': return "That doesn't look like an email address.";
|
||
case 'auth/too-many-requests': return 'Too many attempts. Try again in a few minutes.';
|
||
case 'auth/popup-blocked': return 'The Google sign-in window was blocked. Allow pop-ups for this site, or use email and password.';
|
||
default: return err?.message || String(err);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Auth + boot
|
||
// ---------------------------------------------------------------------------
|
||
let pollTimer = null;
|
||
|
||
function showApp() {
|
||
$('#auth').hidden = true;
|
||
$('#app').hidden = false;
|
||
showTab(prefs.tab);
|
||
}
|
||
|
||
// Sign-in confirmed. The app may already be on screen from this device's saved
|
||
// copy (see boot); a different account starts from an empty copy.
|
||
function enterApp(user) {
|
||
const switched = store.userId !== user.uid;
|
||
if (switched) {
|
||
resetLocal(user);
|
||
} else if (store.email !== (user.email || '')) {
|
||
store.email = user.email || '';
|
||
saveSession();
|
||
}
|
||
if ($('#app').hidden) showApp();
|
||
else if (switched) render();
|
||
syncNow();
|
||
clearInterval(pollTimer);
|
||
pollTimer = setInterval(() => { if (document.visibilityState === 'visible') syncNow(); }, POLL_MS);
|
||
}
|
||
|
||
// Signed out. This device's copy is kept, so unsent edits upload if the same
|
||
// account signs back in; the Sign Out button wipes it first.
|
||
function leaveApp() {
|
||
clearInterval(pollTimer);
|
||
$('#app').hidden = true;
|
||
$('#auth').hidden = false;
|
||
}
|
||
|
||
// ---- Firebase Auth, loaded after the first render -----------------------------
|
||
function loadScript(src) {
|
||
return new Promise((resolve, reject) => {
|
||
const el = document.createElement('script');
|
||
el.src = src;
|
||
el.onload = resolve;
|
||
el.onerror = () => { el.remove(); reject(new Error(`Couldn't load ${src}`)); };
|
||
document.head.append(el);
|
||
});
|
||
}
|
||
|
||
let firebaseStarting = null;
|
||
function startFirebase() {
|
||
if (auth) return Promise.resolve();
|
||
if (!firebaseStarting) {
|
||
firebaseStarting = (async () => {
|
||
if (!window.firebase) await loadScript('vendor/firebase/firebase-app-compat.js');
|
||
if (!window.firebase.auth) await loadScript('vendor/firebase/firebase-auth-compat.js');
|
||
if (!firebase.apps.length) firebase.initializeApp(FIREBASE_CONFIG);
|
||
auth = firebase.auth();
|
||
$('#auth-msg').textContent = '';
|
||
auth.onAuthStateChanged((user) => { if (user) enterApp(user); else leaveApp(); });
|
||
})().catch((e) => {
|
||
// Retried when the connection comes back or the app is reopened.
|
||
firebaseStarting = null;
|
||
const msg = "Can't reach the sign-in service. Check your connection.";
|
||
if ($('#app').hidden) { leaveApp(); $('#auth-msg').textContent = msg; }
|
||
else setStatus('error', `${msg} Changes are saved on this device.`);
|
||
throw e;
|
||
});
|
||
}
|
||
return firebaseStarting;
|
||
}
|
||
|
||
function wireEvents() {
|
||
// Auth form
|
||
let authMode = 'signin';
|
||
document.querySelectorAll('#auth-form button').forEach((b) =>
|
||
b.addEventListener('click', () => { authMode = b.dataset.mode; }));
|
||
$('#auth-form').addEventListener('submit', async (e) => {
|
||
e.preventDefault();
|
||
const email = $('#auth-email').value.trim();
|
||
const password = $('#auth-password').value;
|
||
const msg = $('#auth-msg');
|
||
msg.textContent = '';
|
||
try {
|
||
await startFirebase();
|
||
if (authMode === 'signup') await auth.createUserWithEmailAndPassword(email, password);
|
||
else await auth.signInWithEmailAndPassword(email, password);
|
||
} catch (err) {
|
||
msg.textContent = authMessage(err);
|
||
}
|
||
});
|
||
$('#google-signin').addEventListener('click', async () => {
|
||
$('#auth-msg').textContent = '';
|
||
try {
|
||
await startFirebase();
|
||
await auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
|
||
} catch (err) {
|
||
if (err.code !== 'auth/popup-closed-by-user') $('#auth-msg').textContent = authMessage(err);
|
||
}
|
||
});
|
||
|
||
// Tabs
|
||
document.querySelectorAll('.tabbar button').forEach((b) =>
|
||
b.addEventListener('click', () => showTab(b.dataset.tab)));
|
||
|
||
// Dex controls
|
||
$('#game-btn').addEventListener('click', openGamePicker);
|
||
$('#version-row').addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-version]');
|
||
if (!b) return;
|
||
prefs.versionByGame = { ...(prefs.versionByGame || {}), [currentGame().id]: b.dataset.version };
|
||
savePrefs();
|
||
renderDex();
|
||
});
|
||
$('#game-grid').addEventListener('click', (e) => {
|
||
const tile = e.target.closest('[data-game]');
|
||
if (!tile) return;
|
||
$('#game-dlg').close();
|
||
if (tile.dataset.game === prefs.gameId) return;
|
||
prefs.gameId = tile.dataset.game;
|
||
prefs.playthroughId = '';
|
||
savePrefs();
|
||
renderDex();
|
||
window.scrollTo(0, 0);
|
||
});
|
||
$('#game-dlg').addEventListener('click', (e) => { if (e.target === e.currentTarget) e.currentTarget.close(); });
|
||
$('#pt-select').addEventListener('change', async (e) => {
|
||
if (e.target.value === '__new') {
|
||
e.target.value = prefs.playthroughId; // show the current one again while asking
|
||
const game = currentGame();
|
||
const name = await ask({ title: 'New playthrough', body: `A separate dex for ${game.name}.`, ok: 'Create',
|
||
input: { label: 'Name', placeholder: 'e.g. Nuzlocke' } });
|
||
if (name) {
|
||
const id = uuid();
|
||
write('playthrough', id, { name, gameId: game.id, createdAt: nowISO() });
|
||
prefs.playthroughId = id;
|
||
}
|
||
} else {
|
||
prefs.playthroughId = e.target.value;
|
||
}
|
||
savePrefs();
|
||
renderDex();
|
||
});
|
||
document.querySelectorAll('.iconseg button').forEach((b) => b.addEventListener('click', () => {
|
||
prefs.mode = b.dataset.mode;
|
||
savePrefs();
|
||
renderDex();
|
||
}));
|
||
// Filters sheet
|
||
$('#filter-btn').addEventListener('click', () => { renderFilterSheet(); renderBulk(); openDialog($('#filter-dlg')); });
|
||
$('#filter-bulk').addEventListener('click', onBulkTap);
|
||
$('#view-btn').addEventListener('click', () => {
|
||
prefs.view = prefs.view === 'boxes' ? 'grid' : 'boxes';
|
||
savePrefs();
|
||
renderDex();
|
||
window.scrollTo(0, 0);
|
||
});
|
||
$('#filter-groups').addEventListener('click', (e) => {
|
||
if (e.target.closest('[data-saved], [data-unsave], [data-save-filter]')) { onSavedFilterTap(e); return; }
|
||
const b = e.target.closest('button[data-v]');
|
||
if (!b) return;
|
||
const key = b.closest('[data-key]').dataset.key;
|
||
// Tapping the selected choice again goes back to All.
|
||
prefs[key] = b.dataset.v === String(prefs[key]) ? 'all' : (key === 'gen' && b.dataset.v !== 'all' ? Number(b.dataset.v) : b.dataset.v);
|
||
savePrefs();
|
||
renderFilterSheet();
|
||
renderDex();
|
||
showDexStart();
|
||
});
|
||
$('#filter-reset').addEventListener('click', () => {
|
||
Object.assign(prefs, NO_FILTERS);
|
||
savePrefs();
|
||
renderFilterSheet();
|
||
renderDex();
|
||
showDexStart();
|
||
});
|
||
$('#filter-done').addEventListener('click', () => $('#filter-dlg').close());
|
||
$('#filter-dlg').addEventListener('click', (e) => { if (e.target === e.currentTarget) e.currentTarget.close(); });
|
||
$('#dex-search').addEventListener('input', (e) => { search = e.target.value; renderDex(); showDexStart(); });
|
||
const grid = $('#dex-grid');
|
||
grid.addEventListener('click', onDexTap);
|
||
grid.addEventListener('keydown', onDexKey);
|
||
// The docked panel: tidy up when it closes, Esc closes it, and a window made
|
||
// narrow turns it back into the usual sheet.
|
||
$('#detail-dlg').addEventListener('close', () => {
|
||
$('#detail-dlg').classList.remove('docked');
|
||
$('#app').classList.remove('with-panel');
|
||
markDetailCell();
|
||
});
|
||
document.addEventListener('keydown', (e) => {
|
||
if (e.key !== 'Escape' || !detailDocked() || document.querySelector('dialog:modal')) return;
|
||
if (e.target.closest?.('input, textarea, select')) return;
|
||
closeDockedDetail();
|
||
});
|
||
WIDE.addEventListener('change', () => {
|
||
if (!detailDocked() || WIDE.matches) return;
|
||
const id = detailState.id;
|
||
$('#detail-dlg').close();
|
||
openDetail(id);
|
||
});
|
||
grid.addEventListener('pointerdown', onDexPointerDown);
|
||
grid.addEventListener('pointermove', onDexPointerMove);
|
||
for (const ev of ['pointerup', 'pointercancel', 'pointerleave']) grid.addEventListener(ev, cancelPress);
|
||
grid.addEventListener('contextmenu', (e) => {
|
||
const cell = e.target.closest('.cell');
|
||
if (!cell) return;
|
||
e.preventDefault();
|
||
cancelPress();
|
||
// A long-press may already have opened it.
|
||
if (!$('#detail-dlg').open || detailDocked()) openDetail(Number(cell.dataset.id));
|
||
});
|
||
$('#badge-strip').addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-badge]');
|
||
if (b) toggleBadge(b.dataset.badge);
|
||
});
|
||
$('#badge-pill').addEventListener('click', () => {
|
||
prefs.badgesExpanded = !prefs.badgesExpanded;
|
||
savePrefs();
|
||
renderBadges();
|
||
});
|
||
|
||
// Detail sheet
|
||
$('#detail-body').addEventListener('click', onDetailClick);
|
||
$('#detail-body').addEventListener('change', onDetailChange);
|
||
$('#detail-dlg').addEventListener('click', (e) => { if (e.target === e.currentTarget) e.currentTarget.close(); });
|
||
|
||
// Stats: a missing Pokémon opens its details
|
||
$('#stats').addEventListener('click', (e) => {
|
||
if (e.target.closest('[data-act="compare"]')) { openCompare(); return; }
|
||
if (e.target.closest('[data-act="tohome"]')) { openToHome(); return; }
|
||
const b = e.target.closest('.missing [data-id]');
|
||
if (b) openDetail(Number(b.dataset.id));
|
||
});
|
||
$('#compare-body').addEventListener('click', onCompareClick);
|
||
$('#compare-body').addEventListener('change', onCompareChange);
|
||
$('#compare-dlg').addEventListener('click', (e) => { if (e.target === e.currentTarget) e.currentTarget.close(); });
|
||
wireToHome();
|
||
|
||
// Timeline
|
||
$('#timeline').addEventListener('change', (e) => {
|
||
if (e.target.id !== 'review-year') return;
|
||
prefs.reviewYear = Number(e.target.value);
|
||
savePrefs();
|
||
renderTimeline();
|
||
});
|
||
$('#timeline').addEventListener('click', (e) => {
|
||
if (e.target.id !== 'timeline-more') return;
|
||
timelineShown += TIMELINE_PAGE;
|
||
renderTimeline();
|
||
});
|
||
|
||
// Hunts
|
||
$('#hunt-list').addEventListener('click', onHuntTap);
|
||
document.addEventListener('keydown', onHuntKey);
|
||
huntPicker = makeSpeciesPicker($('#hunt-species'), $('#hunt-species-results'), renderRecommendations);
|
||
phasePicker = makeSpeciesPicker($('#phase-species'), $('#phase-species-results'));
|
||
$('#new-hunt').addEventListener('click', () => {
|
||
$('#hunt-form').reset();
|
||
huntPicker.reset();
|
||
openDialog($('#hunt-dlg'));
|
||
$('#hunt-species').focus();
|
||
});
|
||
// Changing game or method by hand drops a tapped recommendation's modifiers.
|
||
for (const id of ['#hunt-method', '#hunt-game']) $(id).addEventListener('change', () => {
|
||
huntMods = {};
|
||
$('#hunt-recs').querySelectorAll('.rec').forEach((x) => x.classList.remove('on'));
|
||
});
|
||
$('#hunt-form').addEventListener('submit', (e) => {
|
||
const speciesId = huntPicker.resolve();
|
||
if (!speciesId) { e.preventDefault(); $('#hunt-species').focus(); return; }
|
||
write('hunt', uuid(), {
|
||
speciesId,
|
||
gameId: $('#hunt-game').value || null,
|
||
method: $('#hunt-method').value,
|
||
encounters: Math.max(0, parseInt($('#hunt-start').value, 10) || 0),
|
||
startedAt: nowISO(),
|
||
completedAt: null,
|
||
abandonedAt: null,
|
||
notes: '',
|
||
shinyCharm: $('#hunt-charm').checked,
|
||
sandwichLevel: huntMods.sandwichLevel || 0,
|
||
chainCount: huntMods.chainCount || 0,
|
||
maxMilestoneNotified: 0,
|
||
});
|
||
renderHunts();
|
||
});
|
||
$('#phase-form').addEventListener('submit', (e) => {
|
||
const speciesId = phasePicker.resolve();
|
||
const hunt = store.rows.get(phaseHuntId);
|
||
if (!speciesId || !hunt) { e.preventDefault(); $('#phase-species').focus(); return; }
|
||
write('phase', uuid(), {
|
||
huntId: hunt.id,
|
||
speciesId,
|
||
encountersAtPhase: hunt.data.encounters || 0,
|
||
endedAt: nowISO(),
|
||
notes: $('#phase-notes').value.trim(),
|
||
});
|
||
renderHunts();
|
||
});
|
||
$('#notes-form').addEventListener('submit', () => {
|
||
const row = store.rows.get(notesHuntId);
|
||
if (!row) return;
|
||
write('hunt', row.id, { ...row.data, notes: $('#notes-input').value.trim() });
|
||
renderHunts();
|
||
});
|
||
$('#count-form').addEventListener('submit', () => {
|
||
const row = store.rows.get(countHuntId);
|
||
const n = parseInt($('#count-input').value, 10);
|
||
if (row && Number.isFinite(n) && n >= 0) {
|
||
write('hunt', row.id, { ...row.data, encounters: n });
|
||
renderHunts();
|
||
}
|
||
});
|
||
$('#caught-form').addEventListener('submit', () => {
|
||
const row = store.rows.get(caughtHuntId);
|
||
if (!row) return;
|
||
const gameId = $('#caught-game').value;
|
||
const version = versionsOf(gameId).some((v) => v.id === caughtVersion) ? caughtVersion : null;
|
||
prefs.lastCaughtGame = gameId;
|
||
if (version) prefs.versionByGame = { ...(prefs.versionByGame || {}), [gameId]: version };
|
||
savePrefs();
|
||
write('hunt', row.id, { ...row.data, gameId, completedAt: nowISO() });
|
||
// Add the shiny to that game's dex (Main), in that version. One already
|
||
// there is kept, and gains the version if it didn't have it.
|
||
const index = catchIndex();
|
||
const have = index.get(catchKey({ speciesId: row.data.speciesId, gameId, isShiny: true, playthroughId: null }))?.[0];
|
||
if (!have || (version && !(have.data.versions || []).includes(version))) {
|
||
toggleCatch(row.data.speciesId, gameId, true, null, index, version);
|
||
}
|
||
renderHunts();
|
||
});
|
||
$('#caught-game').addEventListener('change', renderCaughtVersions);
|
||
$('#caught-versions').addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-version]');
|
||
if (!b) return;
|
||
caughtVersion = b.dataset.version;
|
||
renderCaughtVersions();
|
||
});
|
||
watchDialogs();
|
||
wirePalette();
|
||
document.querySelectorAll('dialog [data-close]').forEach((b) =>
|
||
b.addEventListener('click', () => b.closest('dialog').close()));
|
||
|
||
// Account
|
||
$('#sync-btn').addEventListener('click', () => { renderAccount(); openDialog($('#account-dlg')); });
|
||
$('#sync-now').addEventListener('click', () => syncNow());
|
||
$('#backup-export').addEventListener('click', () => {
|
||
backupMessage('');
|
||
exportBackup().catch((e) => backupMessage(`Couldn't save the backup: ${e.message || e}`, false));
|
||
});
|
||
$('#backup-import').addEventListener('click', () => { backupMessage(''); $('#backup-file').click(); });
|
||
$('#csv-export').addEventListener('click', () => {
|
||
backupMessage('');
|
||
exportCSV().then((said) => backupMessage(said), (e) => backupMessage(`Couldn't export: ${e.message || e}`, false));
|
||
});
|
||
$('#backup-file').addEventListener('change', (e) => {
|
||
const file = e.target.files[0];
|
||
e.target.value = '';
|
||
if (file) importBackup(file).catch((err) => backupMessage(err.message || String(err), false));
|
||
});
|
||
document.querySelectorAll('[data-sprites]').forEach((b) => b.addEventListener('click', () => {
|
||
prefs.spriteStyle = b.dataset.sprites;
|
||
savePrefs();
|
||
applySpriteStyle();
|
||
render();
|
||
}));
|
||
document.querySelectorAll('[data-density]').forEach((b) => b.addEventListener('click', () => setDensity(b.dataset.density)));
|
||
document.querySelectorAll('[data-forms]').forEach((b) => b.addEventListener('click', () => {
|
||
prefs.homeForms = b.dataset.forms;
|
||
savePrefs();
|
||
applyForms();
|
||
render();
|
||
}));
|
||
$('#sign-out').addEventListener('click', async () => {
|
||
if (store.pending.size) await flush().catch(() => {});
|
||
if (store.pending.size && !await ask({ title: 'Sign out with unsent changes?',
|
||
body: "Some changes haven't uploaded yet and will be lost.", ok: 'Sign out' })) return;
|
||
$('#account-dlg').close();
|
||
try { await startFirebase(); } catch { return; }
|
||
await resetLocal(null);
|
||
await auth.signOut();
|
||
});
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (document.visibilityState === 'visible') { reconnect(); checkForUpdate(); updateWake(); }
|
||
else if (store.pending.size) flush();
|
||
});
|
||
window.addEventListener('online', reconnect);
|
||
}
|
||
|
||
function applySpriteStyle() {
|
||
document.body.dataset.sprites = prefs.spriteStyle;
|
||
document.querySelectorAll('[data-sprites]').forEach((b) => {
|
||
if (b.tagName !== 'BUTTON') return;
|
||
b.classList.toggle('on', b.dataset.sprites === prefs.spriteStyle);
|
||
b.setAttribute('aria-pressed', b.dataset.sprites === prefs.spriteStyle);
|
||
});
|
||
}
|
||
|
||
function applyDensity() {
|
||
document.querySelectorAll('[data-density]').forEach((b) => {
|
||
b.classList.toggle('on', b.dataset.density === prefs.density);
|
||
b.setAttribute('aria-pressed', b.dataset.density === prefs.density);
|
||
});
|
||
}
|
||
function applyForms() {
|
||
if (!['off', 'forms', 'all'].includes(prefs.homeForms)) prefs.homeForms = 'off';
|
||
applyHomeForms();
|
||
document.querySelectorAll('[data-forms]').forEach((b) => {
|
||
b.classList.toggle('on', b.dataset.forms === prefs.homeForms);
|
||
b.setAttribute('aria-pressed', b.dataset.forms === prefs.homeForms);
|
||
});
|
||
}
|
||
function setDensity(density) {
|
||
prefs.density = density === 'compact' ? 'compact' : 'large';
|
||
savePrefs();
|
||
applyDensity();
|
||
if (prefs.tab === 'dex') renderDex();
|
||
}
|
||
|
||
function fillStaticSelects() {
|
||
const groups = [];
|
||
for (const g of GAMES) {
|
||
const label = gameGroup(g);
|
||
let grp = groups.find((x) => x.label === label);
|
||
if (!grp) groups.push(grp = { label, games: [] });
|
||
grp.games.push(g);
|
||
}
|
||
const options = groups.map((grp) => `<optgroup label="${grp.label}">` +
|
||
grp.games.map((g) => `<option value="${g.id}">${esc(g.name)}</option>`).join('') + '</optgroup>').join('');
|
||
$('#caught-game').innerHTML = options;
|
||
$('#hunt-game').innerHTML = '<option value="">Not decided yet</option>' + options;
|
||
const methods = METHODS.filter((m) => m === 'Other' || GAMES.some((g) => METHODS_BY_GAME[g.id]?.includes(m)));
|
||
$('#hunt-method').innerHTML = methods.map((m) => `<option>${m}</option>`).join('');
|
||
}
|
||
|
||
async function boot() {
|
||
const [species, games, badges, exclusives, dexNums, forms, hasSaved] = await Promise.all([
|
||
fetch('data/species.json').then((r) => r.json()),
|
||
fetch('data/games.json').then((r) => r.json()),
|
||
fetch('data/badges.json').then((r) => r.json()),
|
||
fetch('data/exclusives.json').then((r) => r.json()),
|
||
fetch('data/dexnums.json').then((r) => r.json()),
|
||
fetch('data/forms.json').then((r) => r.json()).catch(() => ({ forms: [], baseNames: {} })),
|
||
loadLocal().catch(() => false),
|
||
]);
|
||
BADGES = badges;
|
||
DEX_NUMS = dexNums;
|
||
EXCLUSIVES = Object.fromEntries(Object.entries(exclusives).map(([gid, byVersion]) =>
|
||
[gid, new Map(Object.entries(byVersion).flatMap(([vid, ids]) => ids.map((id) => [id, vid])))]));
|
||
SPECIES = species;
|
||
FORMS = forms.forms || [];
|
||
BASE_NAMES = forms.baseNames || {};
|
||
HAS_FEMALE = new Set(FORMS.filter((f) => f.kind === 'female').map((f) => f.baseSpeciesId));
|
||
SPECIES_BY_ID = new Map([...species, ...FORMS].map((s) => [s.id, s]));
|
||
GAMES = games.filter((g) => SHOWN_GAMES.has(g.id));
|
||
// Saved choices that point at a hidden game.
|
||
if (!SHOWN_GAMES.has(prefs.gameId)) Object.assign(prefs, { gameId: 'home', playthroughId: '' });
|
||
if (!SHOWN_GAMES.has(prefs.lastCaughtGame)) prefs.lastCaughtGame = 'sv';
|
||
HOME_SPECIES = games.find((g) => g.id === 'home')?.species || [];
|
||
fillStaticSelects();
|
||
wireEvents();
|
||
applySpriteStyle();
|
||
applyDensity();
|
||
applyForms();
|
||
// The pinned dex bar sits just under the top bar, whatever height that is.
|
||
const topbar = $('.topbar');
|
||
const setTop = () => document.documentElement.style.setProperty('--topbar-h', `${topbar.offsetHeight}px`);
|
||
if (window.ResizeObserver) new ResizeObserver(setTop).observe(topbar);
|
||
setTop();
|
||
document.querySelectorAll('.tabbar [data-icon]').forEach((b) => b.insertAdjacentHTML('afterbegin', icon(b.dataset.icon)));
|
||
$('#search-icon').innerHTML = icon('search');
|
||
$('#filter-icon').innerHTML = icon('filter');
|
||
$('#view-btn').innerHTML = icon('boxes');
|
||
$('#settings-icon').innerHTML = icon('gear');
|
||
$('#palette-btn').innerHTML = icon('jump');
|
||
// The long-press tip shows on the first visit only.
|
||
$('#dex-hint').hidden = !!prefs.hintSeen;
|
||
if (!prefs.hintSeen) { prefs.hintSeen = true; savePrefs(); }
|
||
// A HOME sprite that's missing (some forms) falls back to the pixel sprite.
|
||
document.addEventListener('error', (e) => {
|
||
const img = e.target;
|
||
if (img.tagName !== 'IMG' || !img.dataset.fallback) return;
|
||
// Next in line: the pixel sprite, then (for a form) its species' pixel sprite.
|
||
const next = [img.dataset.fallback, img.dataset.base].find((url) => url && !(img.dataset.tried || '').includes(url) && img.src !== url);
|
||
if (!next) return;
|
||
if (!img.dataset.src) img.dataset.src = img.getAttribute('src');
|
||
img.dataset.tried = `${img.dataset.tried || ''} ${next}`;
|
||
img.crossOrigin = 'anonymous';
|
||
img.src = next;
|
||
img.classList.add('pixel');
|
||
}, true);
|
||
|
||
// A saved account shows straight away from this device's copy. Sign-in is
|
||
// checked, and sync starts, once that first screen has been painted.
|
||
if (hasSaved) {
|
||
showApp();
|
||
setStatus('busy');
|
||
let started = false;
|
||
const start = () => { if (!started) { started = true; reconnect(); } };
|
||
requestAnimationFrame(() => setTimeout(start, 0));
|
||
setTimeout(start, 1500); // no frames are drawn while the tab is in the background
|
||
} else {
|
||
reconnect();
|
||
}
|
||
watchForUpdates();
|
||
}
|
||
|
||
// Loads sign-in if it isn't up yet (first run, or an earlier attempt failed), then syncs.
|
||
function reconnect() {
|
||
if (auth) syncNow();
|
||
else startFirebase().catch(() => {});
|
||
}
|
||
|
||
// ---- App updates ------------------------------------------------------------
|
||
// The service worker serves the app from its saved copy and installs a new
|
||
// version in the background. When one takes over, reload if the app was just
|
||
// opened and hasn't been touched; otherwise offer a Reload button.
|
||
let swRegistration = null;
|
||
let lastUpdateCheck = Date.now();
|
||
function watchForUpdates() {
|
||
if (!('serviceWorker' in navigator)) return;
|
||
const sw = navigator.serviceWorker;
|
||
const hadVersion = !!sw.controller;
|
||
let touched = false;
|
||
let reloading = false;
|
||
for (const ev of ['pointerdown', 'keydown']) addEventListener(ev, () => { touched = true; }, { capture: true, passive: true });
|
||
sw.addEventListener('controllerchange', () => {
|
||
if (!hadVersion || reloading) return; // first install: nothing to refresh
|
||
const reload = () => { reloading = true; location.reload(); };
|
||
if (!touched) reload();
|
||
else showToast('A new version is ready.', 'Reload', reload);
|
||
});
|
||
sw.register('sw.js').then((reg) => { swRegistration = reg; }).catch(() => {});
|
||
}
|
||
|
||
// An installed app can stay open for days, so look for a new version when it
|
||
// comes back to the foreground (at most every 10 minutes).
|
||
function checkForUpdate() {
|
||
if (!swRegistration || Date.now() - lastUpdateCheck < 600000) return;
|
||
lastUpdateCheck = Date.now();
|
||
swRegistration.update().catch(() => {});
|
||
}
|
||
|
||
boot();
|