Unified Professor Oak Tracker hub (ORAS and Luminescent Platinum) with Docker and Unraid setup

This commit is contained in:
FaroeGames committed 2026-11-17 15:14:41 -07:00
commit f86f5d8bef
61 files changed
+58805

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Luminescent Platinum (v2.1) — Professor Oak Challenge Tracker
Standalone interactive web tracker for **Pokémon Luminescent Platinum v2.1**, modeled on the *Copy of Luminescent 2.1 Professor Oak Tracker* workbook and backed by Team Luminescent v2.0/2.1 gamedata.
## Features
- **10 Chronological Badge-Capped Checkpoints**: Sections follow Luminescent Platinum's story gates and Gym Leader / Boss level caps (`Roark Lv. 16` → `Gardenia Lv. 26` → `Fantina Lv. 33` → `Maylene Lv. 39` → `Wake Lv. 44` → `Byron Lv. 53` → `Candice Lv. 56` → `Volkner Lv. 62` → `Cynthia Lv. 78` → `Stark Mountain Lv. 85` / `Post-Game Lv. 100`).
- **Complete 547 Excel Pokédex (+ Optional 3 Special Forms = 550)**:
- All 105 Sinnoh routes/areas from the workbook with `Morning`, `Day`, `Night`, `Poké Radar`, `Honey Tree`, `Any Incense`, `Any Incense Surf`, `Surf`, `Old/Good/Super Rod`, `Gift`, `Gift Egg`, `Trade`, `Static`, and `Quest` tables.
- Pre-Badge evolution checklists obey each upcoming Gym Leader's level cap, Luminescent's Lv. 36 trade-evo replacements, held-item stone conversions, Moss Rock / Magnetic Field / Ice Rock / Move Reminder gates, and Solaceon Nursery `Manaphy + Ditto → Phione` breeding.
- **Jubilife Gift Egg (Only 1)** lets you pick 1 early baby bonus without locking the remaining 17 babies out of later wild/gift routes.
- **Special Forms (+3)** optional header toggle counts `Crystal Onix`, `Stitched Gengar`, and `Spiky-Eared Pichu` cleanly alongside the base 547 Pokédex.
- **Collapsible Route-Level Trainer & Boss Battles**: Includes regular route trainers, rivals (`Barry`, `Dawn`, `Lucas`, `Cedric`), Team Galactic commanders & HQ, `[Team 1–4]` randomized Gym Leader / Elite Four / Cynthia rosters with team-variant switcher pills, Johto Time Portals, Type Masters, and held items / abilities / natures / moves.
- **Global Caught Sync, Save Profiles & Movedex**:
- Checking any Pokémon highlights it **mint green** across Routes & Pokédex.
- Independent `Save 1`+ profiles with Create / Rename / Delete and JSON Export / Import (`localStorage` isolated under `lumi-poc-tracker:v1:`).
- Species detail modal with Regular & ★ Shiny Luminescent sprites, abilities, base stats, evolution tree, locations, complete Luminescent v2.1 **Movedex** (`Level-Up`, `TM/HM`, `Tutor`, `Egg`, `All`), and external links menu (`Team Luminescent Pokédex`, `Serebii`, `Bulbapedia`, `Pokémon Database`).
## Running Locally
```bash
cd luminescent-platinum
npm start
```
Open `http://127.0.0.1:4174` (override port with `PORT=4175 npm start`).
## Running Tests
```bash
cd luminescent-platinum
npm test
```
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Luminescent Platinum v2.1 — Professor Oak Challenge Tracker</title>
<link rel="stylesheet" href="./src/styles/main.css" />
</head>
<body>
<div id="app"></div>
<script type="module" src="./src/app.js"></script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
{
"name": "professor-oak-tracker-luminescent-platinum",
"version": "1.0.0",
"private": true,
"description": "Standalone Professor Oak Challenge tracker webapp for Pokémon Luminescent Platinum (v2.1), built with the complete Luminescent 2.1 Pokédex, route encounter tables, level caps, trainers, movedex, and save profiles.",
"type": "module",
"scripts": {
"start": "node server.mjs",
"test": "node --test tests/*.test.mjs"
},
"engines": {
"node": ">=20.0.0"
}
}
+80
View File
@@ -0,0 +1,80 @@
import http from 'node:http';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 4174);
const HOST = process.env.HOST || '127.0.0.1';
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
};
export function createStaticServer(rootDir = __dirname) {
const resolvedRoot = path.resolve(rootDir);
return http.createServer(async (req, res) => {
try {
const rawPath = (req.url || '/').split('?')[0];
const decodedRaw = decodeURIComponent(rawPath);
if (decodedRaw.split(/[\\/]/).includes('..')) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
const reqUrl = new URL(req.url || '/', 'http://localhost');
let relPath = decodeURIComponent(reqUrl.pathname);
if (relPath === '/api/assets-status') {
const localSpritesDir = path.join(resolvedRoot, 'assets', 'sprites', 'pkm');
const dirStat = await fs.stat(localSpritesDir).catch(() => null);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache' });
res.end(JSON.stringify({ hasLocalSprites: Boolean(dirStat?.isDirectory()) }));
return;
}
if (relPath === '/') relPath = '/index.html';
const targetPath = path.resolve(resolvedRoot, '.' + relPath);
if (targetPath !== resolvedRoot && !targetPath.startsWith(resolvedRoot + path.sep)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
const stat = await fs.stat(targetPath).catch(() => null);
if (!stat || !stat.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
const ext = path.extname(targetPath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
const content = await fs.readFile(targetPath);
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache',
});
res.end(content);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Server error: ${err.message}`);
}
});
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const server = createStaticServer();
server.listen(PORT, HOST, () => {
console.log(`Luminescent Platinum POC Tracker running at http://${HOST}:${PORT}`);
});
}
+426
View File
@@ -0,0 +1,426 @@
import { createTrackerStore, computeGameProgress } from './state/tracker-store.js';
import { renderHeader } from './ui/header.js';
import { renderSidebar } from './ui/sidebar.js';
import { renderRoutesView } from './ui/routes-view.js';
import { renderPokedexView } from './ui/pokedex-view.js';
import { renderGuideView } from './ui/guide-view.js';
import { renderProfileModal, renderSpeciesModal } from './ui/modal.js';
import { setSpriteBaseUrl } from './ui/sprites.js';
export function mountApp(rootEl, store = createTrackerStore()) {
let toastTimeout = null;
function showToast(message) {
let toast = document.getElementById('poc-toast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'poc-toast';
toast.className = 'poc-toast';
document.body.appendChild(toast);
}
toast.textContent = message;
toast.classList.add('visible');
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => toast.classList.remove('visible'), 2600);
}
function positionExternalMenu(openMenu) {
if (!openMenu) return;
const trigger = rootEl.querySelector(
`[data-open-ext-menu="${openMenu.speciesId}"][data-ext-context="${openMenu.context}"]`,
);
const menu = rootEl.querySelector(
`[data-ext-menu-panel="${openMenu.speciesId}"][data-ext-context="${openMenu.context}"]`,
);
if (!trigger || !menu) return;
const rect = trigger.getBoundingClientRect();
const menuWidth = menu.offsetWidth || 244;
const menuHeight = menu.offsetHeight || 228;
const margin = 8;
let top = rect.bottom + 4;
if (top + menuHeight > window.innerHeight - margin && rect.top - menuHeight - 4 > margin) {
top = rect.top - menuHeight - 4;
}
let left = rect.right - menuWidth;
if (left < margin) left = rect.left;
left = Math.max(margin, Math.min(left, window.innerWidth - menuWidth - margin));
menu.style.position = 'fixed';
menu.style.top = `${Math.round(top)}px`;
menu.style.left = `${Math.round(left)}px`;
}
function render() {
const activeEl = document.activeElement;
const focusedSearchId =
activeEl && (activeEl.id === 'global-search' || activeEl.id === 'movedex-search')
? activeEl.id
: null;
const selStart = focusedSearchId ? activeEl.selectionStart : null;
const selEnd = focusedSearchId ? activeEl.selectionEnd : null;
const state = store.getState();
const game = store.getGame();
const progress = computeGameProgress(game, state.caught, state.ruleset, {
includeSpecialForms: state.includeSpecialForms,
});
const profiles = store.getProfilesWithCounts();
let mainHtml = '';
if (state.activeTab === 'routes') {
mainHtml = renderRoutesView(game, state, progress);
} else if (state.activeTab === 'pokedex') {
mainHtml = renderPokedexView(store, state);
} else {
mainHtml = renderGuideView(game, state);
}
rootEl.innerHTML = `
<div class="app-shell">
${renderHeader(game, state, progress, profiles)}
<div class="workspace-grid ${state.activeTab === 'guide' ? 'no-rail' : ''}">
${state.activeTab === 'guide' ? '' : renderSidebar(game, state, progress)}
<main class="main-pane" id="main-pane">${mainHtml}</main>
</div>
${renderSpeciesModal(game, state)}
${renderProfileModal(game, state)}
</div>
`;
positionExternalMenu(state.openExternalMenu);
if (state.profileModal) {
const profileInput = rootEl.querySelector('#profile-name-input');
if (profileInput) {
profileInput.focus();
profileInput.select();
}
return;
}
if (focusedSearchId) {
const nextInput = rootEl.querySelector(`#${focusedSearchId}`);
if (nextInput) {
nextInput.focus();
if (selStart !== null && selEnd !== null) {
nextInput.setSelectionRange(selStart, selEnd);
}
}
}
}
function triggerJsonDownload(filename, text) {
const blob = new Blob([text], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
function openImportPicker() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json,application/json';
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
try {
const text = await file.text();
const count = store.importJson(text);
showToast(`Imported ${count} caught Pokémon.`);
} catch (err) {
showToast(err?.message || 'Could not import JSON file.');
}
});
input.click();
}
rootEl.addEventListener('click', (e) => {
const extItemEl = e.target.closest('.ext-links-item');
if (extItemEl) {
setTimeout(() => store.closeExternalMenu(), 0);
return;
}
const extTriggerEl = e.target.closest('[data-open-ext-menu]');
if (extTriggerEl) {
e.preventDefault();
e.stopPropagation();
store.toggleExternalMenu(
extTriggerEl.dataset.openExtMenu,
extTriggerEl.dataset.extContext || 'pokedex',
);
return;
}
if (store.getState().openExternalMenu && !e.target.closest('.ext-links-menu')) {
store.closeExternalMenu();
}
const movedexTabEl = e.target.closest('[data-movedex-tab]');
if (movedexTabEl) {
store.setMovedexTab(movedexTabEl.dataset.movedexTab);
return;
}
const teamVariantEl = e.target.closest('[data-select-team-variant]');
if (teamVariantEl) {
store.setSelectedTeamVariant(teamVariantEl.dataset.selectTeamVariant);
return;
}
const eggPickEl = e.target.closest('[data-pick-jubilife-egg]');
if (eggPickEl) {
store.toggleJubilifeEggPick(eggPickEl.dataset.pickJubilifeEgg);
return;
}
const starterPickEl = e.target.closest('[data-pick-starter]');
if (starterPickEl) {
store.pickStarter(starterPickEl.dataset.pickStarter);
return;
}
const switchGameEl = e.target.closest('[data-switch-game]');
if (switchGameEl) {
store.switchGame(switchGameEl.dataset.switchGame);
showToast(`Loaded ${store.getGame().title}`);
return;
}
const tabEl = e.target.closest('[data-tab]');
if (tabEl) {
store.setActiveTab(tabEl.dataset.tab);
return;
}
const jumpTabEl = e.target.closest('[data-jump-tab]');
if (jumpTabEl) {
store.setActiveTab(jumpTabEl.dataset.jumpTab);
return;
}
const sectionEl = e.target.closest('[data-section-id]');
if (sectionEl) {
store.setActiveSectionId(sectionEl.dataset.sectionId);
return;
}
const jumpSecEl = e.target.closest('[data-jump-section]');
if (jumpSecEl) {
store.setActiveSectionId(jumpSecEl.dataset.jumpSection);
store.setActiveTab('routes');
return;
}
const areaTrainersBtn = e.target.closest('[data-toggle-area-trainers]');
if (areaTrainersBtn) {
store.toggleAreaTrainersExpanded(areaTrainersBtn.dataset.toggleAreaTrainers);
return;
}
const areaBtn = e.target.closest('[data-toggle-area]');
if (areaBtn) {
store.toggleAreaCollapsed(areaBtn.dataset.toggleArea);
return;
}
const inspectEl = e.target.closest('[data-inspect-species]');
if (inspectEl) {
store.setSelectedSpeciesId(inspectEl.dataset.inspectSpecies);
return;
}
const caughtBtn = e.target.closest('[data-toggle-species-btn]');
if (caughtBtn) {
store.toggleCaught(caughtBtn.dataset.toggleSpeciesBtn);
return;
}
const dexFilterBtn = e.target.closest('[data-dex-filter]');
if (dexFilterBtn) {
store.setPokedexFilter(dexFilterBtn.dataset.dexFilter);
return;
}
const sortBtn = e.target.closest('[data-sort-col]');
if (sortBtn) {
store.setPokedexSort(sortBtn.dataset.sortCol);
return;
}
const actionEl = e.target.closest('[data-action]');
if (actionEl) {
const action = actionEl.dataset.action;
if (action === 'clear-search') {
store.setSearchQuery('');
} else if (action === 'clear-movedex-search') {
store.setMovedexSearch('');
} else if (action === 'expand-all') {
store.setAllAreasCollapsed(false);
} else if (action === 'collapse-all') {
store.setAllAreasCollapsed(true);
} else if (action === 'clear-filters') {
store.setSearchQuery('');
store.setMethodFilter('all');
store.setUncaughtOnly(false);
} else if (action === 'new-profile') {
store.setProfileModal({ mode: 'create' });
} else if (action === 'rename-profile') {
store.setProfileModal({ mode: 'rename', profileId: store.getState().profileId });
} else if (action === 'delete-profile') {
const profiles = store.getState().profiles || [];
if (profiles.length <= 1) {
showToast('At least one save profile must remain.');
return;
}
const active = store.getActiveProfile();
if (window.confirm(`Delete save profile "${active.name}" and its progress?`)) {
store.deleteProfile(active.id);
showToast(`Deleted "${active.name}"`);
}
} else if (action === 'close-profile-modal') {
if (e.target === actionEl || !actionEl.classList.contains('modal-backdrop')) {
store.setProfileModal(null);
}
} else if (action === 'close-modal') {
if (e.target === actionEl || !actionEl.classList.contains('modal-backdrop')) {
store.setSelectedSpeciesId(null);
}
} else if (action === 'export-json') {
const json = store.exportJson();
const active = store.getActiveProfile();
const safeName = (active?.name || 'save').toLowerCase().replace(/[^a-z0-9]+/g, '-');
const dateStamp = new Date().toISOString().slice(0, 10);
triggerJsonDownload(`${store.getGame().id}-${safeName}-${dateStamp}.json`, json);
showToast('Exported save JSON backup.');
} else if (action === 'import-json') {
openImportPicker();
} else if (action === 'reset-progress') {
const active = store.getActiveProfile();
if (window.confirm(`Reset caught progress and trainers in "${active?.name || 'Save 1'}"?`)) {
store.resetProgress();
showToast(`Cleared progress for ${active?.name || 'Save 1'}.`);
}
}
}
});
rootEl.addEventListener('submit', (e) => {
if (e.target.id === 'profile-modal-form') {
e.preventDefault();
const mode = e.target.dataset.profileMode;
const profileId = e.target.dataset.profileId;
const input = e.target.querySelector('#profile-name-input');
const value = input?.value?.trim();
if (!value) return;
if (mode === 'rename') {
store.renameProfile(profileId, value);
showToast(`Renamed save to "${value}"`);
} else {
const created = store.createProfile(value);
showToast(`Created save "${created.name}"`);
}
}
});
rootEl.addEventListener('input', (e) => {
if (e.target.id === 'global-search') {
store.setSearchQuery(e.target.value);
} else if (e.target.id === 'movedex-search') {
store.setMovedexSearch(e.target.value);
}
});
rootEl.addEventListener('change', (e) => {
if (e.target.dataset.toggleSpecies) {
store.toggleCaught(e.target.dataset.toggleSpecies);
} else if (e.target.dataset.toggleTrainer) {
store.toggleTrainerDefeated(e.target.dataset.toggleTrainer);
} else if (e.target.id === 'profile-select') {
store.switchProfile(e.target.value);
} else if (e.target.id === 'uncaught-only-toggle') {
store.setUncaughtOnly(e.target.checked);
} else if (e.target.id === 'special-forms-toggle') {
store.setIncludeSpecialForms(e.target.checked);
} else if (e.target.id === 'incense-burner-toggle' || e.target.matches('[data-toggle-incense]')) {
store.setIncenseActive(e.target.checked);
showToast(
e.target.checked
? 'Special Forms enabled (+Crystal Onix, Stitched Gengar, Spiky-Eared Pichu = 550)'
: 'Strict 547 Excel Pokédex count active',
);
} else if (e.target.id === 'method-filter') {
store.setMethodFilter(e.target.value);
} else if (e.target.id === 'starter-select') {
store.setChosenStarter(e.target.value || null);
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const current = store.getState();
if (current.openExternalMenu) {
store.closeExternalMenu();
} else if (current.profileModal) {
store.setProfileModal(null);
} else if (current.selectedSpeciesId) {
store.setSelectedSpeciesId(null);
}
}
});
document.addEventListener(
'scroll',
(e) => {
if (!store.getState().openExternalMenu) return;
if (e.target instanceof Element && e.target.closest('.ext-links-menu')) return;
store.closeExternalMenu();
},
true,
);
rootEl.addEventListener(
'error',
(e) => {
const img = e.target;
if (typeof HTMLImageElement === 'undefined' || !(img instanceof HTMLImageElement)) return;
const fallback = img.dataset.fallbackSrc;
if (fallback && img.src !== fallback) {
img.dataset.fallbackSrc = '';
img.src = fallback;
} else {
img.classList.add('sprite-broken');
}
},
true,
);
store.subscribe(render);
render();
if (typeof fetch === 'function') {
fetch('./api/assets-status')
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data?.hasLocalSprites) {
setSpriteBaseUrl('./assets/sprites');
render();
}
})
.catch(() => {});
}
return store;
}
if (typeof document !== 'undefined') {
const root = document.getElementById('app');
if (root) mountApp(root);
}
@@ -0,0 +1,15 @@
import { LUMINESCENT_PLATINUM } from './luminescent-platinum.js';
export const GAMES = {
'luminescent-platinum': LUMINESCENT_PLATINUM,
};
export const DEFAULT_GAME_ID = 'luminescent-platinum';
export function getGame(gameId = DEFAULT_GAME_ID) {
return GAMES[gameId] || GAMES[DEFAULT_GAME_ID];
}
export function listGames() {
return Object.values(GAMES);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
// Auto-generated from Team Luminescent v2.0/2.1 Mapper_Trainer_Output.json
export const LUMI_TRAINER_BUCKETS = {"route-201":[{"id":"rt201-s-1","name":"Single Battle Pokémon Trainer Barry","role":"Rival","location":"Route 201","format":"Single","starterTeams":{"piplup":[{"speciesId":"turtwig","pid":387,"natId":387,"name":"Turtwig","spriteFile":"pm0387_00_00_00_L.webp","level":5,"types":["Grass"],"moves":["Tackle","Withdraw"]}],"turtwig":[{"speciesId":"chimchar","pid":390,"natId":390,"name":"Chimchar","spriteFile":"pm0390_00_00_00_L.webp","level":5,"types":["Fire"],"moves":["Scratch","Leer"]}],"chimchar":[{"speciesId":"piplup","pid":393,"natId":393,"name":"Piplup","spriteFile":"pm0393_00_00_00_L.webp","level":5,"types":["Water"],"moves":["Pound","Growl"]}]}},{"id":"rt201-1-2","name":"Single Battle Youngster Tristan","role":"Rival","location":"Route 201","format":"Single","team":[{"speciesId":"hoothoot","pid":163,"natId":163,"name":"Hoothoot","spriteFile":"pm0163_00_00_00_L.webp","level":7,"types":["Normal","Flying"],"moves":["Peck","Tackle","Echoed Voice","Hypnosis"]},{"speciesId":"starly","pid":396,"natId":396,"name":"Starly","spriteFile":"pm0396_00_00_00_L.webp","level":7,"types":["Normal","Flying"],"moves":["Growl","Tackle","Quick Attack"]}]},{"id":"rt201-2-3","name":"Single Battle Youngster Logan","role":"Rival","location":"Route 201","format":"Single","team":[{"speciesId":"growlithe","pid":58,"natId":58,"name":"Growlithe","spriteFile":"pm0058_00_00_00_L.webp","level":7,"types":["Fire"],"moves":["Roar","Bite","Howl","Ember"]},{"speciesId":"burmy","pid":412,"natId":412,"name":"Burmy","spriteFile":"pm0412_00_00_00_L.webp","level":7,"types":["Bug"],"moves":["Tackle","Bug Bite","Hidden Power","Protect"]},{"speciesId":"zigzagoon","pid":263,"natId":263,"name":"Zigzagoon","spriteFile":"pm0263_00_00_00_L.webp","level":7,"types":["Normal"],"moves":["Tackle","Tail Whip","Sand Attack","Covet"]}]},{"id":"rt201-3-4","name":"Single Battle Lass Natalie","role":"Rival","location":"Route 201","format":"Single","team":[{"speciesId":"sentret","pid":161,"natId":161,"name":"Sentret","spriteFile":"pm0161_00_00_00_L.webp","level":7,"types":["Normal"],"moves":["Scratch","Defense Curl","Quick Attack","Fury Swipes"]},{"speciesId":"bidoof","pid":399,"natId":399,"name":"Bidoof","spriteFile":"pm0399_00_00_00_L.webp","level":7,"types":["Normal"],"moves":["Growl","Tackle","Defense Curl"]}]}],"route-202":[{"id":"rt202-s-1","name":"Single Battle Pokémon Trainer Lucas","role":"Rival","location":"Route 202","format":"Single","starterTeams":{"piplup":[{"speciesId":"piplup","pid":393,"natId":393,"name":"Piplup","spriteFile":"pm0393_00_00_00_L.webp","level":9,"types":["Water"],"moves":["Pound","Growl","Water Gun","Bubble"]}],"turtwig":[{"speciesId":"turtwig","pid":387,"natId":387,"name":"Turtwig","spriteFile":"pm0387_00_00_00_L.webp","level":9,"types":["Grass"],"moves":["Withdraw","Absorb","Leafage","Razor Leaf"]}],"chimchar":[{"speciesId":"chimchar","pid":390,"natId":390,"name":"Chimchar","spriteFile":"pm0390_00_00_00_L.webp","level":9,"types":["Fire"],"moves":["Leer","Scratch","Ember","Taunt"]}]}},{"id":"rt202-s-2","name":"Single Battle Pokémon Trainer Dawn","role":"Rival","location":"Route 202","format":"Single","starterTeams":{"piplup":[{"speciesId":"piplup","pid":393,"natId":393,"name":"Piplup","spriteFile":"pm0393_00_00_00_L.webp","level":9,"types":["Water"],"moves":["Pound","Growl","Water Gun","Bubble"]}],"turtwig":[{"speciesId":"turtwig","pid":387,"natId":387,"name":"Turtwig","spriteFile":"pm0387_00_00_00_L.webp","level":9,"types":["Grass"],"moves":["Withdraw","Absorb","Leafage","Razor Leaf"]}],"chimchar":[{"speciesId":"chimchar","pid":390,"natId":390,"name":"Chimchar","spriteFile":"pm0390_00_00_00_L.webp","level":9,"types":["Fire"],"moves":["Leer","Scratch","Ember","Taunt"]}]}}],"jubilife-city":[{"id":"jubilife-s-1","name":"Multi Battle Partner Pokémon Trainer Lucas","role":"Rival","location":"Jubilife City","format":"Single","starterTeams":{"piplup":[{"speciesId":"snubbull","pid":209,"natId":209,"name":"Snubbull","spriteFile":"pm0209_00_00_00_L.webp","level":13,"types":["Fairy"],"moves":["Bite","Fire Fang","Thunder Fang","Ice Fang"]},{"speciesId":"turtwig","pid":387,"natId":387,"name":"Turtwig","spriteFile":"pm0387_00_00_00_L.webp","level":14,"types":["Grass"],"moves":["Bullet Seed","Curse","Withdraw","Tackle"]}],"turtwig":[{"speciesId":"snubbull","pid":209,"natId":209,"name":"Snubbull","spriteFile":"pm0209_00_00_00_L.webp","level":13,"types":["Fairy"],"moves":["Bite","Fire Fang","Thunder Fang","Ice Fang"]},{"speciesId":"chimchar","pid":390,"natId":390,"name":"Chimchar","spriteFile":"pm0390_00_00_00_L.webp","level":14,"types":["Fire"],"moves":["Flame Wheel","Taunt","Leer","Scratch"]}],"chimchar":[{"speciesId":"snubbull","pid":209,"natId":209,"name":"Snubbull","spriteFile":"pm0209_00_00_00_L.webp","level":13,"types":["Fairy"],"moves":["Bite","Fire Fang","Thunder Fang","Ice Fang"]},{"speciesId":"piplup","pid":393,"natId":393,"name":"Piplup","spriteFile":"pm0393_00_00_00_L.webp","level":14,"types":["WateLine truncated
+34
View File
@@ -0,0 +1,34 @@
// Auto-generated from Team Luminescent v2.0/2.1 gamedata (WazaOboeTable, ItemTable, TamagoWazaTable, tutorMoves, WazaTable)
import { SPECIES_BY_ID } from './species.js';
export const MOVES_CATALOG = {"1":{"id":1,"name":"Pound","type":"Normal","category":"Physical","power":40,"accuracy":100,"pp":35},"2":{"id":2,"name":"Karate Chop","type":"Fighting","category":"Physical","power":50,"accuracy":100,"pp":25},"3":{"id":3,"name":"Double Slap","type":"Normal","category":"Physical","power":15,"accuracy":85,"pp":10},"4":{"id":4,"name":"Comet Punch","type":"Normal","category":"Physical","power":18,"accuracy":85,"pp":15},"5":{"id":5,"name":"Mega Punch","type":"Normal","category":"Physical","power":80,"accuracy":85,"pp":20},"6":{"id":6,"name":"Pay Day","type":"Normal","category":"Physical","power":40,"accuracy":100,"pp":20},"7":{"id":7,"name":"Fire Punch","type":"Fire","category":"Physical","power":75,"accuracy":100,"pp":15},"8":{"id":8,"name":"Ice Punch","type":"Ice","category":"Physical","power":75,"accuracy":100,"pp":15},"9":{"id":9,"name":"Thunder Punch","type":"Electric","category":"Physical","power":75,"accuracy":100,"pp":15},"10":{"id":10,"name":"Scratch","type":"Normal","category":"Physical","power":40,"accuracy":100,"pp":35},"11":{"id":11,"name":"Vise Grip","type":"Normal","category":"Physical","power":55,"accuracy":100,"pp":30},"12":{"id":12,"name":"Guillotine","type":"Normal","category":"Physical","power":1,"accuracy":30,"pp":5},"13":{"id":13,"name":"Razor Wind","type":"Normal","category":"Special","power":80,"accuracy":100,"pp":10},"14":{"id":14,"name":"Swords Dance","type":"Normal","category":"Status","power":null,"accuracy":null,"pp":20},"15":{"id":15,"name":"Cut","type":"Grass","category":"Physical","power":60,"accuracy":100,"pp":25},"16":{"id":16,"name":"Gust","type":"Flying","category":"Special","power":40,"accuracy":100,"pp":35},"17":{"id":17,"name":"Wing Attack","type":"Flying","category":"Physical","power":60,"accuracy":100,"pp":35},"18":{"id":18,"name":"Whirlwind","type":"Normal","category":"Status","power":null,"accuracy":null,"pp":20},"19":{"id":19,"name":"Fly","type":"Flying","category":"Physical","power":100,"accuracy":100,"pp":15},"20":{"id":20,"name":"Bind","type":"Normal","category":"Physical","power":15,"accuracy":85,"pp":20},"21":{"id":21,"name":"Slam","type":"Normal","category":"Physical","power":80,"accuracy":75,"pp":20},"22":{"id":22,"name":"Vine Whip","type":"Grass","category":"Physical","power":45,"accuracy":100,"pp":25},"23":{"id":23,"name":"Stomp","type":"Normal","category":"Physical","power":65,"accuracy":100,"pp":20},"24":{"id":24,"name":"Double Kick","type":"Fighting","category":"Physical","power":30,"accuracy":100,"pp":30},"25":{"id":25,"name":"Mega Kick","type":"Normal","category":"Physical","power":120,"accuracy":75,"pp":5},"26":{"id":26,"name":"Jump Kick","type":"Fighting","category":"Physical","power":100,"accuracy":95,"pp":10},"27":{"id":27,"name":"Rolling Kick","type":"Fighting","category":"Physical","power":60,"accuracy":85,"pp":15},"28":{"id":28,"name":"Sand Attack","type":"Ground","category":"Status","power":null,"accuracy":100,"pp":15},"29":{"id":29,"name":"Headbutt","type":"Normal","category":"Physical","power":70,"accuracy":100,"pp":15},"30":{"id":30,"name":"Horn Attack","type":"Normal","category":"Physical","power":65,"accuracy":100,"pp":25},"31":{"id":31,"name":"Fury Attack","type":"Normal","category":"Physical","power":15,"accuracy":85,"pp":20},"32":{"id":32,"name":"Horn Drill","type":"Normal","category":"Physical","power":1,"accuracy":30,"pp":5},"33":{"id":33,"name":"Tackle","type":"Normal","category":"Physical","power":40,"accuracy":100,"pp":35},"34":{"id":34,"name":"Body Slam","type":"Normal","category":"Physical","power":85,"accuracy":100,"pp":15},"35":{"id":35,"name":"Wrap","type":"Normal","category":"Physical","power":15,"accuracy":90,"pp":20},"36":{"id":36,"name":"Take Down","type":"Normal","category":"Physical","power":90,"accuracy":85,"pp":20},"37":{"id":37,"name":"Thrash","type":"Normal","category":"Physical","power":120,"accuracy":100,"pp":10},"38":{"id":38,"name":"Double-Edge","type":"Normal","category":"Physical","power":120,"accuracy":100,"pp":15},"39":{"id":39,"name":"Tail Whip","type":"Normal","category":"Status","power":null,"accuracy":100,"pp":30},"40":{"id":40,"name":"Poison Sting","type":"Poison","category":"Physical","power":15,"accuracy":100,"pp":35},"41":{"id":41,"name":"Twineedle","type":"Bug","category":"Physical","power":25,"accuracy":100,"pp":20},"42":{"id":42,"name":"Pin Missile","type":"Bug","category":"Physical","power":25,"accuracy":95,"pp":20},"43":{"id":43,"name":"Leer","type":"Normal","category":"Status","power":null,"accuracy":100,"pp":30},"44":{"id":44,"name":"Bite","type":"Dark","category":"Physical","power":60,"accuracy":100,"pp":25},"45":{"id":45,"name":"Growl","type":"Normal","category":"Status","power":null,"accuracy":100,"pp":40},"46":{"id":46,"name":"Roar","type":"Normal","category":"Status","power":null,"accuracy":null,"pp":20},"47":{"id":47,"name":"Sing","type":"Normal","category":"Status","power":null,"accuracy":55,"pp":15},"48":{"id":48,"name":"Supersonic","type":"Normal","category":Line truncated
export const SPECIES_MOVESETS = {"bulbasaur":{"levelUp":[[1,45],[1,33],[5,22],[8,73],[11,75],[14,77],[14,79],[17,124],[20,36],[23,230],[26,188],[29,74],[32,388],[35,38],[36,76],[38,235],[41,402],[44,437]],"machine":[["TM06",92],["TM09",331],["TM10",237],["TM104",526],["TM11",241],["TM16",113],["TM17",182],["TM19",202],["TM20",219],["TM22",76],["TM32",104],["TM36",188],["TM42",263],["TM44",156],["TM45",213],["TM53",412],["TM54",206],["TM58",203],["TM70",148],["TM75",14],["TM82",214],["TM86",447],["TM87",207],["TM90",164],["TM93",15],["TM96",70],["TM98",249]],"tutor":[173,20,270,388,189,210,235,402,282],"egg":[130,80,174,275,267,204,345,133,437,438,124,580,320,13]},"ivysaur":{"levelUp":[[1,74],[1,22],[1,45],[1,33],[5,22],[8,73],[11,75],[14,77],[14,79],[16,345],[18,124],[20,402],[22,36],[26,230],[30,188],[34,74],[38,388],[42,38],[46,235],[50,76],[54,437]],"machine":[["TM06",92],["TM09",331],["TM10",237],["TM104",526],["TM11",241],["TM16",113],["TM17",182],["TM19",202],["TM20",219],["TM22",76],["TM32",104],["TM36",188],["TM42",263],["TM44",156],["TM45",213],["TM53",412],["TM54",206],["TM58",203],["TM70",148],["TM75",14],["TM82",214],["TM86",447],["TM87",207],["TM90",164],["TM93",15],["TM96",70],["TM98",249]],"tutor":[173,20,270,388,189,210,235,402,282],"egg":[130,80,174,275,267,204,345,133,437,438,124,580,320,13]},"venusaur":{"levelUp":[[0,572],[1,74],[1,22],[1,45],[1,33],[1,80],[1,438],[1,414],[5,22],[8,73],[11,75],[14,77],[14,79],[16,345],[18,124],[20,402],[22,36],[26,230],[30,188],[32,80],[35,74],[40,388],[45,38],[50,235],[55,76],[60,437]],"machine":[["TM05",46],["TM06",92],["TM09",331],["TM10",237],["TM100",431],["TM102",523],["TM104",526],["TM11",241],["TM15",63],["TM16",113],["TM17",182],["TM19",202],["TM20",219],["TM22",76],["TM26",89],["TM32",104],["TM36",188],["TM42",263],["TM44",156],["TM45",213],["TM53",412],["TM54",206],["TM58",203],["TM68",416],["TM70",148],["TM75",14],["TM82",214],["TM86",447],["TM87",207],["TM90",164],["TM93",15],["TM96",70],["TM98",249]],"tutor":[173,20,270,523,388,189,335,210,707,235,402,282,200,414],"egg":[130,80,174,275,267,204,345,133,437,438,124,580,320,13]},"charmander":{"levelUp":[[1,45],[1,10],[5,52],[8,108],[11,232],[12,225],[14,44],[20,424],[23,163],[26,53],[29,184],[32,242],[35,406],[36,517],[38,83],[41,187],[44,394]],"machine":[["TM01",264],["TM02",337],["TM06",92],["TM10",237],["TM104",526],["TM11",241],["TM17",182],["TM23",231],["TM28",91],["TM31",280],["TM32",104],["TM35",53],["TM38",126],["TM39",317],["TM40",332],["TM42",263],["TM44",156],["TM45",213],["TM50",315],["TM54",206],["TM56",374],["TM58",203],["TM59",406],["TM61",261],["TM65",421],["TM75",14],["TM80",157],["TM82",214],["TM87",207],["TM90",164],["TM93",15],["TM96",70],["TM98",249]],"tutor":[173,270,189,210,7,9,69,129,612,257,200],"egg":[187,246,44,407,232,68,17,525,200,251,349,242,394,314]},"charmeleon":{"levelUp":[[1,45],[1,10],[5,52],[8,108],[11,232],[14,44],[16,225],[22,424],[26,163],[30,53],[34,184],[38,242],[42,406],[46,83],[48,517],[50,187],[54,394]],"machine":[["TM01",264],["TM02",337],["TM06",92],["TM10",237],["TM104",526],["TM11",241],["TM17",182],["TM23",231],["TM28",91],["TM31",280],["TM32",104],["TM35",53],["TM38",126],["TM39",317],["TM40",332],["TM42",263],["TM44",156],["TM45",213],["TM50",315],["TM54",206],["TM56",374],["TM58",203],["TM59",406],["TM61",261],["TM65",421],["TM75",14],["TM80",157],["TM82",214],["TM87",207],["TM90",164],["TM93",15],["TM96",70],["TM98",249]],"tutor":[173,270,189,210,7,9,69,129,612,257,200],"egg":[187,246,44,407,232,68,17,525,200,251,349,242,394,314]},"charizard":{"levelUp":[[0,403],[1,337],[1,421],[1,45],[1,10],[1,257],[1,17],[1,403],[5,52],[8,108],[11,232],[14,44],[16,225],[22,424],[26,163],[30,53],[34,184],[36,403],[39,242],[44,406],[49,83],[54,187],[54,517],[59,394]],"machine":[["TM01",264],["TM02",337],["TM05",46],["TM06",92],["TM10",237],["TM102",523],["TM103",365],["TM104",526],["TM11",241],["TM15",63],["TM17",182],["TM22",76],["TM23",231],["TM26",89],["TM28",91],["TM31",280],["TM32",104],["TM35",53],["TM38",126],["TM39",317],["TM40",332],["TM42",263],["TM44",156],["TM45",213],["TM47",211],["TM50",315],["TM51",355],["TM52",411],["TM54",206],["TM56",374],["TM58",203],["TM59",406],["TM61",261],["TM65",421],["TM68",416],["TM75",14],["TM80",157],["TM82",214],["TM87",207],["TM88",542],["TM90",164],["TM93",15],["TM94",19],["TM96",70],["TM98",249]],"tutor":[173,270,523,314,189,814,210,466,7,9,69,366,129,815,612,257,200,239],"egg":[187,246,44,407,232,68,17,525,200,251,349,242,394,314]},"squirtle":{"levelUp":[[1,39],[1,33],[5,55],[8,110],[11,145],[14,44],[17,229],[20,352],[23,182],[26,330],[27,504],[29,334],[32,130],[35,401],[38,240],[41,56],[44,323]],"machine":[["TM01",264],["TM03",352],["TM06",92],["TM07",258],["TM10",237],["TM104",526],["TM13",58],["TM14",59],["TM17",182],["TM18",240],["TM23",231],["TM28",91],["TM31",280],["TM32",104],["TM39",317],["TM42",263],["TM44",156],["TM45",213],["TM49",362],["TM54",206],["TM55",503],["TM56",374],["TM58",203],["TM59",406Line truncated
const EMPTY_MOVESET = Object.freeze({ levelUp: [], machine: [], tutor: [], egg: [] });
function resolveMoveEntry(id, extra = {}) {
const base = MOVES_CATALOG[id];
if (!base) {
return { id, name: `Move #${id}`, type: 'Normal', category: 'Status', power: null, accuracy: null, pp: null, ...extra };
}
return { ...base, ...extra };
}
export function getPokemonMoveset(speciesOrId) {
const key = typeof speciesOrId === 'string'
? speciesOrId
: speciesOrId?.id;
let raw = key ? SPECIES_MOVESETS[key] : null;
if (!raw && typeof speciesOrId === 'number') {
const match = Object.values(SPECIES_BY_ID).find((s) => s.natId === speciesOrId);
if (match) raw = SPECIES_MOVESETS[match.id];
}
if (!raw) return EMPTY_MOVESET;
return {
levelUp: raw.levelUp.map(([level, id]) => resolveMoveEntry(id, { level })),
machine: raw.machine.map(([machine, id]) => resolveMoveEntry(id, { machine })),
tutor: raw.tutor.map((id) => resolveMoveEntry(id)),
egg: raw.egg.map((id) => resolveMoveEntry(id)),
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,821 @@
import { SPECIES_LIST, SPECIES_BY_ID } from '../data/species.js';
import { GAMES, getGame, DEFAULT_GAME_ID } from '../data/games/index.js';
const STORAGE_PREFIX = 'lumi-poc-tracker:v1:';
const META_STORAGE_KEY = `${STORAGE_PREFIX}app-meta`;
function computeValidTrainerIds(game) {
return new Set(
(game?.sections || []).flatMap((section) => [
...(section.trainers || []).map((trainer) => trainer.id),
...(section.areas || []).flatMap((area) =>
(area.trainers || []).map((trainer) => trainer.id),
),
]),
);
}
/**
* Indexes earliest milestone and all locations for every species in the active ruleset.
* Entries tagged `earlyBonusGroup` (Jubilife Gift Egg 1-of-18) do NOT claim `earliestBySpecies`
* when the species has a guaranteed later unlock so the Pokédex always sums cleanly without
* double-counting or locking out the remaining 17 babies.
*/
export function indexGameSpecies(game, { includeSpecialForms = false } = {}) {
const earliestBySpecies = new Map();
const locationsBySpecies = new Map();
for (const section of game.sections) {
for (const area of section.areas) {
for (const group of area.groups || []) {
for (const entry of group.entries || []) {
const sp = SPECIES_BY_ID[entry.speciesId];
if (!sp) continue;
if (!includeSpecialForms && sp.isSpecialForm) continue;
if (!entry.earlyBonusGroup && !earliestBySpecies.has(entry.speciesId)) {
earliestBySpecies.set(entry.speciesId, {
sectionId: section.id,
badgeNumber: section.badgeNumber,
shortName: section.shortName,
title: section.title,
areaId: area.id,
areaName: area.name,
method: group.method,
});
}
if (!locationsBySpecies.has(entry.speciesId)) {
locationsBySpecies.set(entry.speciesId, []);
}
locationsBySpecies.get(entry.speciesId).push({
sectionId: section.id,
sectionShortName: section.shortName,
areaId: area.id,
areaName: area.name,
method: group.method,
rate: entry.rate,
levels: entry.levels,
notes: entry.notes || '',
earlyBonusGroup: entry.earlyBonusGroup || null,
});
}
}
}
}
return { earliestBySpecies, locationsBySpecies };
}
/**
* Computes per-section unique new unlocks, cumulative POC totals, and overall progress.
* Returns exact 547 total when `includeSpecialForms` is false, or 550 when true.
*/
export function computeGameProgress(
game,
caughtSet,
ruleset = 'solo',
{ includeSpecialForms = false } = {},
) {
const { earliestBySpecies } = indexGameSpecies(game, { includeSpecialForms });
const uniqueNewBySection = new Map(game.sections.map((s) => [s.id, []]));
for (const [speciesId, earliest] of earliestBySpecies.entries()) {
const sp = SPECIES_BY_ID[speciesId];
if (!sp) continue;
if (!includeSpecialForms && sp.isSpecialForm) continue;
if (ruleset === 'solo' && sp.availability !== 'all') continue;
const list = uniqueNewBySection.get(earliest.sectionId);
if (list) list.push(speciesId);
}
let cumulativeTotal = 0;
let cumulativeCaught = 0;
const sections = game.sections.map((section) => {
const newIds = uniqueNewBySection.get(section.id) || [];
let newCaught = 0;
for (const id of newIds) {
if (caughtSet.has(id)) newCaught++;
}
cumulativeTotal += newIds.length;
cumulativeCaught += newCaught;
const presentIds = new Set();
for (const area of section.areas) {
for (const group of area.groups || []) {
for (const entry of group.entries || []) {
const sp = SPECIES_BY_ID[entry.speciesId];
if (!sp) continue;
if (!includeSpecialForms && sp.isSpecialForm) continue;
presentIds.add(entry.speciesId);
}
}
}
let presentCaught = 0;
for (const id of presentIds) {
if (caughtSet.has(id)) presentCaught++;
}
return {
id: section.id,
badgeNumber: section.badgeNumber,
shortName: section.shortName,
levelCap: section.levelCap ?? null,
capBoss: section.capBoss ?? '',
newTotal: newIds.length,
newCaught,
newRemaining: newIds.length - newCaught,
cumulativeTotal,
cumulativeCaught,
presentTotal: presentIds.size,
presentCaught,
};
});
return {
totalObtainable: cumulativeTotal,
totalCaught: cumulativeCaught,
totalRemaining: cumulativeTotal - cumulativeCaught,
percent: cumulativeTotal > 0 ? Math.round((cumulativeCaught / cumulativeTotal) * 1000) / 10 : 0,
sections,
};
}
export function createTrackerStore({
gameId: initialGameId = null,
profileId: initialProfileId = null,
storage = typeof globalThis.localStorage !== 'undefined' ? globalThis.localStorage : null,
} = {}) {
function defaultMeta(preferredGameId) {
return {
activeGameId: preferredGameId || DEFAULT_GAME_ID,
profilesByGame: {},
};
}
let meta = defaultMeta(initialGameId ? getGame(initialGameId).id : DEFAULT_GAME_ID);
if (storage) {
try {
const rawMeta = storage.getItem(META_STORAGE_KEY);
if (rawMeta) {
const parsed = JSON.parse(rawMeta);
if (!initialGameId && parsed?.activeGameId && GAMES[parsed.activeGameId]) {
meta.activeGameId = parsed.activeGameId;
}
if (parsed?.profilesByGame && typeof parsed.profilesByGame === 'object') {
meta.profilesByGame = parsed.profilesByGame;
}
}
} catch {
// Ignore corrupt app metadata cleanly
}
}
function ensureGameProfiles(targetGameId) {
const existing = meta.profilesByGame[targetGameId];
const validList = Array.isArray(existing?.profiles)
? existing.profiles.filter((p) => p && typeof p.id === 'string' && typeof p.name === 'string')
: [];
if (validList.length === 0) {
validList.push({
id: 'default',
name: 'Save 1',
createdAt: new Date().toISOString(),
});
}
const activeOk = validList.some((p) => p.id === existing?.activeProfileId);
meta.profilesByGame[targetGameId] = {
activeProfileId: activeOk ? existing.activeProfileId : validList[0].id,
profiles: validList,
};
return meta.profilesByGame[targetGameId];
}
function getSaveKey(targetGameId, targetProfileId) {
return targetProfileId === 'default'
? `${STORAGE_PREFIX}${targetGameId}`
: `${STORAGE_PREFIX}${targetGameId}:${targetProfileId}`;
}
function saveMeta() {
if (!storage) return;
try {
storage.setItem(META_STORAGE_KEY, JSON.stringify(meta));
} catch {
// Ignore storage quota errors
}
}
const initialEntry = ensureGameProfiles(meta.activeGameId);
if (initialProfileId && initialEntry.profiles.some((p) => p.id === initialProfileId)) {
initialEntry.activeProfileId = initialProfileId;
}
let validTrainerIds = computeValidTrainerIds(getGame(meta.activeGameId));
const state = {
gameId: meta.activeGameId,
profileId: initialEntry.activeProfileId,
profiles: initialEntry.profiles.map((p) => ({ ...p })),
caught: new Set(),
ruleset: 'solo', // 'solo' | 'all'
includeSpecialForms: false, // false = exact 547 Excel Pokédex; true = 550 (+Crystal Onix / Stitched Gengar / Spiky-Eared Pichu)
incenseActive: false, // true = Incense Burner Key Item ON (activates Any Incense & adjusts overwritten Ground/Surf slot rates)
jubilifeEggPick: null, // null | speciesId picked in Jubilife Trainer School 1-of-18 pool
chosenStarter: null, // null | 'turtwig' | 'chimchar' | 'piplup'
selectedTeamVariant: 'all', // 'all' | 'Team 1' | 'Team 2' | 'Team 3' | 'Team 4'
activeTab: 'routes', // 'routes' | 'pokedex' | 'guide'
activeSectionId: 'all',
searchQuery: '',
uncaughtOnly: false,
methodFilter: 'all',
collapsedAreas: new Set(),
collapsedGroups: new Set(),
defeatedTrainers: new Set(),
expandedTrainerAreas: new Set(),
pokedexFilter: 'all', // 'all' | 'regional' | 'national' | 'legendary' | 'special'
pokedexSort: { column: 'excelIndex', direction: 'asc' },
selectedSpeciesId: null,
movedexTab: 'levelUp', // 'levelUp' | 'machine' | 'tutor' | 'egg' | 'all'
movedexSearch: '',
openExternalMenu: null, // null | { speciesId, context }
profileModal: null, // null | { mode: 'create' | 'rename', profileId? }
};
const listeners = new Set();
function syncProfilesToState() {
const entry = ensureGameProfiles(state.gameId);
state.profileId = entry.activeProfileId;
state.profiles = entry.profiles.map((p) => ({ ...p }));
}
function loadActiveSave() {
const currentGame = getGame(state.gameId);
validTrainerIds = computeValidTrainerIds(currentGame);
if (
state.activeSectionId !== 'all' &&
!currentGame.sections.some((s) => s.id === state.activeSectionId)
) {
state.activeSectionId = 'all';
}
state.caught = new Set();
state.ruleset = 'solo';
state.includeSpecialForms = false;
state.incenseActive = false;
state.jubilifeEggPick = null;
state.chosenStarter = null;
state.selectedTeamVariant = 'all';
state.collapsedAreas = new Set();
state.collapsedGroups = new Set();
state.defeatedTrainers = new Set();
state.expandedTrainerAreas = new Set();
state.selectedSpeciesId = null;
state.openExternalMenu = null;
state.movedexSearch = '';
if (!storage) return;
try {
const raw = storage.getItem(getSaveKey(state.gameId, state.profileId));
if (!raw) return;
const parsed = JSON.parse(raw);
if (Array.isArray(parsed.caught)) {
state.caught = new Set(parsed.caught.filter((id) => Boolean(SPECIES_BY_ID[id])));
}
if (parsed.ruleset === 'solo' || parsed.ruleset === 'all') {
state.ruleset = parsed.ruleset;
}
if (typeof parsed.includeSpecialForms === 'boolean') {
state.includeSpecialForms = parsed.includeSpecialForms;
}
if (typeof parsed.incenseActive === 'boolean') {
state.incenseActive = parsed.incenseActive;
}
if (parsed.jubilifeEggPick && SPECIES_BY_ID[parsed.jubilifeEggPick]) {
state.jubilifeEggPick = parsed.jubilifeEggPick;
}
if (['turtwig', 'chimchar', 'piplup'].includes(parsed.chosenStarter)) {
state.chosenStarter = parsed.chosenStarter;
}
if (['all', 'Team 1', 'Team 2', 'Team 3', 'Team 4'].includes(parsed.selectedTeamVariant)) {
state.selectedTeamVariant = parsed.selectedTeamVariant;
}
if (Array.isArray(parsed.collapsedAreas)) {
state.collapsedAreas = new Set(parsed.collapsedAreas);
}
if (Array.isArray(parsed.collapsedGroups)) {
state.collapsedGroups = new Set(parsed.collapsedGroups);
}
if (Array.isArray(parsed.defeatedTrainers)) {
state.defeatedTrainers = new Set(
parsed.defeatedTrainers.filter(
(id) => typeof id === 'string' && (!validTrainerIds.size || validTrainerIds.has(id)),
),
);
}
if (Array.isArray(parsed.expandedTrainerAreas)) {
state.expandedTrainerAreas = new Set(parsed.expandedTrainerAreas);
}
} catch {
// Ignore corrupt storage silently and keep defaults
}
}
function save() {
if (!storage) return;
try {
storage.setItem(
getSaveKey(state.gameId, state.profileId),
JSON.stringify({
caught: [...state.caught],
ruleset: state.ruleset,
includeSpecialForms: state.includeSpecialForms,
incenseActive: state.incenseActive,
jubilifeEggPick: state.jubilifeEggPick,
chosenStarter: state.chosenStarter,
selectedTeamVariant: state.selectedTeamVariant,
collapsedAreas: [...state.collapsedAreas],
collapsedGroups: [...state.collapsedGroups],
defeatedTrainers: [...state.defeatedTrainers],
expandedTrainerAreas: [...state.expandedTrainerAreas],
updatedAt: new Date().toISOString(),
}),
);
saveMeta();
} catch {
// Ignore storage quota errors cleanly
}
}
function notify() {
for (const listener of listeners) {
listener(this?.getState ? this.getState() : state);
}
}
loadActiveSave();
return {
subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
},
getGame() {
return getGame(state.gameId);
},
getState() {
return {
...state,
caught: new Set(state.caught),
collapsedAreas: new Set(state.collapsedAreas),
collapsedGroups: new Set(state.collapsedGroups),
defeatedTrainers: new Set(state.defeatedTrainers),
expandedTrainerAreas: new Set(state.expandedTrainerAreas),
profiles: state.profiles.map((p) => ({ ...p })),
openExternalMenu: state.openExternalMenu ? { ...state.openExternalMenu } : null,
profileModal: state.profileModal ? { ...state.profileModal } : null,
};
},
getProfilesWithCounts() {
const entry = ensureGameProfiles(state.gameId);
return entry.profiles.map((p) => {
if (p.id === state.profileId) {
return { ...p, caughtCount: state.caught.size };
}
let caughtCount = 0;
if (storage) {
try {
const raw = storage.getItem(getSaveKey(state.gameId, p.id));
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed?.caught)) {
caughtCount = parsed.caught.filter((id) => Boolean(SPECIES_BY_ID[id])).length;
}
}
} catch {
caughtCount = 0;
}
}
return { ...p, caughtCount };
});
},
getActiveProfile() {
return state.profiles.find((p) => p.id === state.profileId) || state.profiles[0];
},
createProfile(name) {
const cleanName = String(name || '').trim().slice(0, 36);
if (!cleanName) throw new Error('Profile name cannot be empty.');
save();
const entry = ensureGameProfiles(state.gameId);
const id = `save-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const profile = { id, name: cleanName, createdAt: new Date().toISOString() };
entry.profiles.push(profile);
entry.activeProfileId = id;
saveMeta();
syncProfilesToState();
loadActiveSave();
save();
state.profileModal = null;
notify();
return profile;
},
switchProfile(profileId) {
const entry = ensureGameProfiles(state.gameId);
if (!entry.profiles.some((p) => p.id === profileId)) return false;
if (profileId === state.profileId) return true;
save();
entry.activeProfileId = profileId;
saveMeta();
syncProfilesToState();
loadActiveSave();
notify();
return true;
},
renameProfile(profileId, newName) {
const cleanName = String(newName || '').trim().slice(0, 36);
if (!cleanName) throw new Error('Profile name cannot be empty.');
const entry = ensureGameProfiles(state.gameId);
const target = entry.profiles.find((p) => p.id === profileId);
if (!target) return false;
target.name = cleanName;
saveMeta();
syncProfilesToState();
state.profileModal = null;
notify();
return true;
},
deleteProfile(profileId) {
const entry = ensureGameProfiles(state.gameId);
if (entry.profiles.length <= 1) return false;
const idx = entry.profiles.findIndex((p) => p.id === profileId);
if (idx === -1) return false;
entry.profiles.splice(idx, 1);
if (storage) {
try {
storage.removeItem(getSaveKey(state.gameId, profileId));
} catch {
// Ignore removal failures
}
}
if (entry.activeProfileId === profileId) {
entry.activeProfileId = entry.profiles[Math.max(0, idx - 1)].id;
}
saveMeta();
syncProfilesToState();
loadActiveSave();
notify();
return true;
},
setProfileModal(modal) {
state.profileModal = modal;
notify();
},
switchGame(gameId) {
if (!GAMES[gameId] || gameId === state.gameId) return;
save();
meta.activeGameId = gameId;
state.gameId = gameId;
syncProfilesToState();
saveMeta();
loadActiveSave();
notify();
},
isCaught(speciesId) {
return state.caught.has(speciesId);
},
toggleCaught(speciesId, forcedValue = null) {
if (!SPECIES_BY_ID[speciesId]) return;
const shouldCatch = forcedValue !== null ? Boolean(forcedValue) : !state.caught.has(speciesId);
if (shouldCatch) {
state.caught.add(speciesId);
} else {
state.caught.delete(speciesId);
}
save();
notify();
},
toggleJubilifeEggPick(speciesId) {
if (!SPECIES_BY_ID[speciesId]) return;
if (state.jubilifeEggPick === speciesId) {
state.jubilifeEggPick = null;
} else {
state.jubilifeEggPick = speciesId;
state.caught.add(speciesId);
}
save();
notify();
},
setChosenStarter(starterId) {
state.chosenStarter = ['turtwig', 'chimchar', 'piplup'].includes(starterId) ? starterId : null;
save();
notify();
},
pickStarter(starterId) {
if (!['turtwig', 'chimchar', 'piplup'].includes(starterId)) return;
if (state.chosenStarter === starterId) {
state.chosenStarter = null;
} else {
state.chosenStarter = starterId;
state.caught.add(starterId);
}
save();
notify();
},
setSelectedTeamVariant(variant) {
if (['all', 'Team 1', 'Team 2', 'Team 3', 'Team 4'].includes(variant)) {
state.selectedTeamVariant = variant;
save();
notify();
}
},
setIncludeSpecialForms(enabled) {
state.includeSpecialForms = Boolean(enabled);
save();
notify();
},
setIncenseActive(enabled) {
state.incenseActive = Boolean(enabled);
save();
notify();
},
isTrainerDefeated(trainerId) {
return state.defeatedTrainers.has(trainerId);
},
toggleTrainerDefeated(trainerId, forcedValue = null) {
if (!trainerId) return;
const shouldMark =
forcedValue !== null ? Boolean(forcedValue) : !state.defeatedTrainers.has(trainerId);
if (shouldMark) {
state.defeatedTrainers.add(trainerId);
} else {
state.defeatedTrainers.delete(trainerId);
}
save();
notify();
},
toggleAreaTrainersExpanded(areaId) {
if (state.expandedTrainerAreas.has(areaId)) {
state.expandedTrainerAreas.delete(areaId);
} else {
state.expandedTrainerAreas.add(areaId);
}
save();
notify();
},
markGroupCaught(speciesIds, caught = true) {
for (const id of speciesIds) {
if (!SPECIES_BY_ID[id]) continue;
if (caught) state.caught.add(id);
else state.caught.delete(id);
}
save();
notify();
},
setActiveTab(tab) {
state.activeTab = tab;
state.openExternalMenu = null;
notify();
},
setActiveSectionId(sectionId) {
state.activeSectionId = sectionId;
state.openExternalMenu = null;
notify();
},
setSearchQuery(query) {
state.searchQuery = query;
notify();
},
setUncaughtOnly(enabled) {
state.uncaughtOnly = Boolean(enabled);
notify();
},
setMethodFilter(method) {
state.methodFilter = method;
notify();
},
setRuleset(ruleset) {
state.ruleset = ruleset === 'all' ? 'all' : 'solo';
save();
notify();
},
toggleAreaCollapsed(areaId) {
if (state.collapsedAreas.has(areaId)) {
state.collapsedAreas.delete(areaId);
} else {
state.collapsedAreas.add(areaId);
}
save();
notify();
},
setAllAreasCollapsed(collapsed) {
const currentGame = this.getGame();
if (collapsed) {
for (const section of currentGame.sections) {
for (const area of section.areas) {
state.collapsedAreas.add(area.id);
}
}
} else {
state.collapsedAreas.clear();
}
save();
notify();
},
setPokedexFilter(filter) {
state.pokedexFilter = filter;
notify();
},
setPokedexSort(column) {
if (state.pokedexSort.column === column) {
state.pokedexSort = {
column,
direction: state.pokedexSort.direction === 'asc' ? 'desc' : 'asc',
};
} else {
state.pokedexSort = { column, direction: 'asc' };
}
notify();
},
setSelectedSpeciesId(speciesId) {
state.selectedSpeciesId = speciesId || null;
state.movedexSearch = '';
state.openExternalMenu = null;
notify();
},
setMovedexTab(tab) {
if (['levelUp', 'machine', 'tutor', 'egg', 'all'].includes(tab)) {
state.movedexTab = tab;
notify();
}
},
setMovedexSearch(query) {
state.movedexSearch = query;
notify();
},
toggleExternalMenu(speciesId, context = 'pokedex') {
if (!speciesId || !SPECIES_BY_ID[speciesId]) {
state.openExternalMenu = null;
} else if (
state.openExternalMenu &&
state.openExternalMenu.speciesId === speciesId &&
state.openExternalMenu.context === context
) {
state.openExternalMenu = null;
} else {
state.openExternalMenu = { speciesId, context };
}
notify();
},
closeExternalMenu() {
if (!state.openExternalMenu) return;
state.openExternalMenu = null;
notify();
},
resetProgress() {
state.caught.clear();
state.defeatedTrainers.clear();
state.jubilifeEggPick = null;
save();
notify();
},
exportJson() {
const activeProfile = this.getActiveProfile();
return JSON.stringify(
{
app: 'professor-oak-tracker-luminescent-platinum',
version: 1,
gameId: state.gameId,
profileId: state.profileId,
profileName: activeProfile?.name || 'Save 1',
ruleset: state.ruleset,
includeSpecialForms: state.includeSpecialForms,
incenseActive: state.incenseActive,
jubilifeEggPick: state.jubilifeEggPick,
chosenStarter: state.chosenStarter,
caught: [...state.caught],
defeatedTrainers: [...state.defeatedTrainers],
exportedAt: new Date().toISOString(),
},
null,
2,
);
},
importJson(rawJson) {
const parsed = JSON.parse(rawJson);
if (!parsed || !Array.isArray(parsed.caught)) {
throw new Error('Invalid backup format: missing "caught" array.');
}
if (parsed.gameId && GAMES[parsed.gameId] && parsed.gameId !== state.gameId) {
throw new Error(`Backup is for ${GAMES[parsed.gameId].title}.`);
}
const validIds = parsed.caught.filter((id) => Boolean(SPECIES_BY_ID[id]));
state.caught = new Set(validIds);
state.defeatedTrainers = new Set(
Array.isArray(parsed.defeatedTrainers)
? parsed.defeatedTrainers.filter(
(id) => typeof id === 'string' && (!validTrainerIds.size || validTrainerIds.has(id)),
)
: [],
);
if (parsed.ruleset === 'solo' || parsed.ruleset === 'all') {
state.ruleset = parsed.ruleset;
}
state.includeSpecialForms =
typeof parsed.includeSpecialForms === 'boolean' ? parsed.includeSpecialForms : false;
state.incenseActive =
typeof parsed.incenseActive === 'boolean' ? parsed.incenseActive : false;
state.jubilifeEggPick =
parsed.jubilifeEggPick && SPECIES_BY_ID[parsed.jubilifeEggPick] ? parsed.jubilifeEggPick : null;
state.chosenStarter = ['turtwig', 'chimchar', 'piplup'].includes(parsed.chosenStarter)
? parsed.chosenStarter
: null;
save();
notify();
return validIds.length;
},
getPokedexRows() {
const currentGame = this.getGame();
const { earliestBySpecies, locationsBySpecies } = indexGameSpecies(currentGame, {
includeSpecialForms: state.includeSpecialForms,
});
const q = state.searchQuery.trim().toLowerCase();
const rows = SPECIES_LIST.filter((sp) => {
if (!state.includeSpecialForms && sp.isSpecialForm) return false;
return true;
})
.map((sp) => {
const earliest = earliestBySpecies.get(sp.id) || null;
const locations = locationsBySpecies.get(sp.id) || [];
const soloValid = earliest !== null;
const isForm = Boolean(sp.formLabel || sp.isSpecialForm);
const isLegend = locations.some((l) => l.method === 'Legendaries' || l.method === 'Quest');
return {
...sp,
caught: state.caught.has(sp.id),
earliest,
locations,
soloValid,
isForm,
isLegend,
};
})
.filter((row) => {
if (state.pokedexFilter === 'forms' && !row.isForm) return false;
if (state.pokedexFilter === 'legendary' && !row.isLegend) return false;
if (state.uncaughtOnly && row.caught) return false;
if (state.activeSectionId !== 'all') {
if (!row.earliest || row.earliest.sectionId !== state.activeSectionId) return false;
}
if (q) {
const hay = [
row.name,
String(row.natId),
String(row.excelIndex),
row.evolutionMethod || '',
row.formLabel || '',
row.earliest?.shortName || '',
...row.types,
...row.locations.map((l) => `${l.areaName} ${l.method}`),
]
.join(' ')
.toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
const { column, direction } = state.pokedexSort;
const dir = direction === 'desc' ? -1 : 1;
rows.sort((a, b) => {
let cmp = 0;
if (column === 'excelIndex') {
cmp = a.excelIndex - b.excelIndex;
} else if (column === 'natId') {
cmp = a.natId - b.natId || a.excelIndex - b.excelIndex;
} else if (column === 'name') {
cmp = a.name.localeCompare(b.name);
} else if (column === 'milestone') {
const am = a.earliest?.badgeNumber ?? 99;
const bm = b.earliest?.badgeNumber ?? 99;
cmp = am - bm || a.excelIndex - b.excelIndex;
} else if (column === 'caught') {
cmp = Number(b.caught) - Number(a.caught) || a.excelIndex - b.excelIndex;
} else if (column === 'evolutionMethod') {
cmp = (a.evolutionMethod || 'Base / Wild').localeCompare(
b.evolutionMethod || 'Base / Wild',
);
}
return cmp * dir;
});
return rows;
},
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,135 @@
import { escapeHtml, padDex } from './formatters.js';
function getBaseName(species) {
let base = String(species?.name || '').trim();
if (base === 'Crystal Onix') return 'Onix';
if (base === 'Stitched Gengar') return 'Gengar';
if (base === 'Spiky-Eared Pichu') return 'Pichu';
return base.replace(/-(A|G|H)$/i, '').trim();
}
function toWikiSlug(name) {
return String(name || '')
.trim()
.replace(/ /g, '_');
}
function toDbSlug(species) {
const base = getBaseName(species);
if (base === 'Nidoran♀') return 'nidoran-f';
if (base === 'Nidoran♂') return 'nidoran-m';
return base
.toLowerCase()
.replace(/['’.]/g, '')
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '');
}
/**
* Returns external Pokédex links tailored for Luminescent Platinum (v2.1).
*/
export function getExternalLinksForSpecies(species) {
if (!species) return [];
const baseName = getBaseName(species);
const wikiTitle = `${encodeURIComponent(toWikiSlug(baseName))}_(Pok%C3%A9mon)`;
const dbSlug = toDbSlug(species);
const serebiiSlug = dbSlug.replace(/-/g, '');
const lumiSlug = species.lumiSlug || dbSlug;
return [
{
id: 'luminescent',
label: 'Team Luminescent Pokédex',
description: 'Official Lumi v2.1 stats, moves & locations',
url: `https://luminescent.team/pokedex/${encodeURIComponent(lumiSlug)}`,
},
{
id: 'serebii',
label: 'Serebii Pokédex',
description: 'Stats, forms & generation data',
url: `https://www.serebii.net/pokedex-sv/${encodeURIComponent(serebiiSlug)}/`,
},
{
id: 'bulbapedia',
label: 'Bulbapedia',
description: 'Full encyclopedia & Sinnoh lore',
url: `https://bulbapedia.bulbagarden.net/wiki/${wikiTitle}`,
},
{
id: 'pokemondb',
label: 'Pokémon Database',
description: 'Base stats, type chart & BDSP moves',
url: `https://pokemondb.net/pokedex/${encodeURIComponent(dbSlug)}`,
},
];
}
const EXTERNAL_ARROW_SVG = `
<svg class="ext-arrow-icon" width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path d="M9.5 2.5H13.5V6.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M13.2 2.8L7.2 8.8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
<path d="M7 3.5H4C3.17 3.5 2.5 4.17 2.5 5V12C2.5 12.83 3.17 13.5 4 13.5H11C11.83 13.5 12.5 12.83 12.5 12V9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
`;
export function renderExternalLinksControl(species, state, context = 'pokedex') {
if (!species) return '';
const activeMenu = state?.openExternalMenu;
const isOpen = Boolean(
activeMenu && activeMenu.speciesId === species.id && activeMenu.context === context,
);
const links = isOpen ? getExternalLinksForSpecies(species) : [];
const menuHtml = isOpen
? `
<div
class="ext-links-menu"
role="menu"
aria-label="External links for ${escapeHtml(species.name)}"
data-ext-menu-panel="${escapeHtml(species.id)}"
data-ext-context="${escapeHtml(context)}"
>
<div class="ext-links-header">
<span>${escapeHtml(species.name)} Guides</span>
<span class="mono">#${padDex(species.natId)}</span>
</div>
${links
.map(
(link) => `
<a
class="ext-links-item"
role="menuitem"
href="${escapeHtml(link.url)}"
target="_blank"
rel="noopener noreferrer"
data-ext-site="${escapeHtml(link.id)}"
>
<span class="ext-links-item-main">
<span class="ext-links-item-label">${escapeHtml(link.label)}</span>
<span class="ext-links-item-desc">${escapeHtml(link.description)}</span>
</span>
<span class="ext-links-item-arrow" aria-hidden="true">↗</span>
</a>
`,
)
.join('')}
</div>
`
: '';
return `
<span class="ext-links-wrap">
<button
type="button"
class="ext-link-trigger ${isOpen ? 'active' : ''}"
data-open-ext-menu="${escapeHtml(species.id)}"
data-ext-context="${escapeHtml(context)}"
aria-haspopup="menu"
aria-expanded="${isOpen}"
title="External links (Luminescent.team, Serebii, Bulbapedia, PokémonDB)"
aria-label="Open external links menu for ${escapeHtml(species.name)}"
>${EXTERNAL_ARROW_SVG}</button>
${menuHtml}
</span>
`;
}
+92
View File
@@ -0,0 +1,92 @@
import { SPECIES_LIST, SPECIES_BY_ID } from '../data/species.js';
export function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function padDex(num, width = 3) {
return String(num).padStart(width, '0');
}
export function getMethodClass(method) {
switch (method) {
case 'Morning':
case 'Day':
case 'Night':
return 'method-tod';
case 'Old Rod':
case 'Good Rod':
case 'Super Rod':
case 'Surf':
return 'method-water';
case 'Poké Radar':
case 'Honey Tree':
case 'Any Incense':
case 'Any Incense Surf':
return 'method-special';
case 'Starter':
case 'Gift':
case 'Gift Egg':
case 'Gift Egg (Only 1)':
case 'Trade':
case 'Static':
case 'Quest':
case 'Legendaries':
return 'method-event';
case 'Breeding':
case 'Evolution':
return 'method-evo';
default:
return 'method-special';
}
}
export function getTypeBadgeHtml(type) {
const slug = String(type || 'normal').toLowerCase();
return `<span class="type-pill type-${escapeHtml(slug)}">${escapeHtml(type)}</span>`;
}
/**
* Returns ordered evolution tree starting from root ancestor for any speciesId.
* Handles regional/custom branches so e.g. Rattata shows both Raticate and Raticate-A,
* or Raichu-A walks cleanly back to Pichu -> Pikachu -> Raichu / Raichu-A.
*/
export function getEvolutionFamily(speciesId) {
const target = SPECIES_BY_ID[speciesId];
if (!target) return [];
let root = target;
const visited = new Set([root.id]);
while (root.evolvesFrom && SPECIES_BY_ID[root.evolvesFrom] && !visited.has(root.evolvesFrom)) {
root = SPECIES_BY_ID[root.evolvesFrom];
visited.add(root.id);
}
const childrenMap = new Map();
for (const sp of SPECIES_LIST) {
if (sp.evolvesFrom) {
if (!childrenMap.has(sp.evolvesFrom)) childrenMap.set(sp.evolvesFrom, []);
childrenMap.get(sp.evolvesFrom).push(sp);
}
}
const family = [];
const queue = [{ species: root, depth: 0 }];
const seen = new Set();
while (queue.length > 0) {
const { species, depth } = queue.shift();
if (seen.has(species.id)) continue;
seen.add(species.id);
family.push({ species, depth });
const kids = childrenMap.get(species.id) || [];
for (const kid of kids) {
queue.push({ species: kid, depth: depth + 1 });
}
}
return family;
}
+110
View File
@@ -0,0 +1,110 @@
import { escapeHtml } from './formatters.js';
import { LUMI_IMG_CDN, renderItemIconsHtml } from './sprites.js';
export function renderGuideView(game, state) {
const { guide } = game;
const specialEnabled = Boolean(state?.includeSpecialForms);
const levelCapRows = (guide?.levelCaps || [])
.map(
(row) => `
<tr>
<td><strong>${escapeHtml(row.section)}</strong></td>
<td>${escapeHtml(row.boss)}</td>
<td class="mono"><span class="cap-badge">Lv. ${escapeHtml(row.cap)}</span></td>
</tr>
`,
)
.join('');
const itemRows = (guide?.evolutionItems || [])
.map(
(row) => `
<tr>
<td>
<span class="evo-cell-wrap">
${renderItemIconsHtml(row.item, { size: 22 })}
<strong class="amber-inline">${escapeHtml(row.item)}</strong>
</span>
</td>
<td><span class="milestone-tag tag-earlier">${escapeHtml(row.earliest)}</span></td>
<td>${escapeHtml(row.source)}</td>
<td>${escapeHtml(row.usedFor)}</td>
</tr>
`,
)
.join('');
const tipsCards = (guide?.grindingTips || [])
.map(
(tip) => `
<article class="guide-card">
<h3 class="guide-card-title">${escapeHtml(tip.title)}</h3>
<p class="guide-card-body">${escapeHtml(tip.detail)}</p>
</article>
`,
)
.join('');
return `
<div class="guide-view">
<section class="guide-section">
<h2 class="guide-heading">Luminescent Platinum (v2.1) — Official Boss Level Caps</h2>
<p class="guide-lead">
Every Pre-Badge Evolution Checklist automatically restricts evolutions to moves, items, and levels strictly at or below the upcoming Gym Leader or Champion level cap.
</p>
<div class="dex-table-wrap">
<table class="dex-table">
<thead>
<tr>
<th>Checkpoint</th>
<th>Boss / Milestone</th>
<th>Level Cap</th>
</tr>
</thead>
<tbody>${levelCapRows}</tbody>
</table>
</div>
</section>
<section class="guide-section">
<h2 class="guide-heading">Evolution Stones &amp; Former Held-Trade Item Locations</h2>
<p class="guide-lead">
In Luminescent Platinum, link-trade evolutions without items (Alakazam, Machamp, Golem, Golem-A, Gengar) evolve at <strong>Level 36</strong>, while item-trade items (Metal Coat, King's Rock, Protector, Upgrade, Electirizer, etc.) work directly like evolution stones. Veilstone Dept Store 3F sells all 11 evolution stones (Pre-Badge 4), and Snowpoint City sells every former held-trade item (Pre-Badge 7).
</p>
<div class="dex-table-wrap">
<table class="dex-table">
<thead>
<tr>
<th>Evolution Item</th>
<th>Earliest Section</th>
<th>Locations &amp; Shops</th>
<th>Used For</th>
</tr>
</thead>
<tbody>${itemRows}</tbody>
</table>
</div>
</section>
<section class="guide-section">
<h2 class="guide-heading">POC Strategy &amp; Luminescent Mechanics</h2>
<p class="guide-lead">
Special Forms (+3) toggle is currently <strong>${specialEnabled ? 'ON (550 Dex incl. Crystal Onix, Stitched Gengar & Spiky-Eared Pichu)' : 'OFF (547 exact Excel Pokédex)'}</strong>.
</p>
<div class="guide-grid">${tipsCards}</div>
</section>
<section class="guide-section">
<h2 class="guide-heading">Sprites &amp; Item Icons (External Assets / Offline Optional)</h2>
<article class="guide-card">
<p class="guide-card-body">
Regular &amp; Shiny Luminescent sprites and item icons load automatically from
<a class="ext-link" href="https://github.com/TeamLumi/luminescent-team" target="_blank" rel="noopener noreferrer">TeamLumi/luminescent-team</a>
(<code>${escapeHtml(LUMI_IMG_CDN)}</code>). For 100% offline sprites, copy <code>static/img/{pkm,shinypkm,items}</code> into <code>luminescent-platinum/assets/sprites/</code>.
</p>
</article>
</section>
</div>
`;
}
+185
View File
@@ -0,0 +1,185 @@
import { listGames } from '../data/games/index.js';
import { escapeHtml } from './formatters.js';
const ALL_METHODS = [
'all',
'Starter',
'Morning',
'Day',
'Night',
'Poké Radar',
'Honey Tree',
'Any Incense',
'Any Incense Surf',
'Old Rod',
'Good Rod',
'Super Rod',
'Surf',
'Gift',
'Gift Egg',
'Gift Egg (Only 1)',
'Trade',
'Static',
'Quest',
'Legendaries',
'Breeding',
'Evolution',
];
export function renderHeader(game, state, progress, profilesWithCounts = null) {
const methodOptions = ALL_METHODS.map((m) => {
const label = m === 'all' ? 'All Methods' : m;
return `<option value="${escapeHtml(m)}" ${state.methodFilter === m ? 'selected' : ''}>${escapeHtml(label)}</option>`;
}).join('');
const versionPills = listGames()
.map((g) => {
const isActive = g.id === game.id;
return `
<button
type="button"
class="version-switch-btn ${escapeHtml(g.themeClass || 'version-plat')} ${isActive ? 'active' : ''}"
data-switch-game="${escapeHtml(g.id)}"
aria-pressed="${isActive}"
>${escapeHtml(g.title)}</button>
`;
})
.join('');
const profileList =
profilesWithCounts ||
(state.profiles || [{ id: 'default', name: 'Save 1', caughtCount: state.caught?.size || 0 }]);
const profileOptions = profileList
.map((p) => {
const countText = Number.isInteger(p.caughtCount) ? ` (${p.caughtCount})` : '';
return `<option value="${escapeHtml(p.id)}" ${p.id === state.profileId ? 'selected' : ''}>${escapeHtml(p.name)}${escapeHtml(countText)}</option>`;
})
.join('');
const starterOptions = [
{ id: '', label: 'Rival Starter: Show All' },
...(game.starters || []).map((s) => ({ id: s.id, label: `Starter: ${s.label}` })),
]
.map(
(opt) =>
`<option value="${escapeHtml(opt.id)}" ${(state.chosenStarter || '') === opt.id ? 'selected' : ''}>${escapeHtml(opt.label)}</option>`,
)
.join('');
return `
<header class="app-header ${escapeHtml(game.themeClass || 'version-plat')}">
<div class="header-top">
<div class="brand-block">
<div class="brand-badges">
<a class="hub-home-link" href="../" title="Back to Professor Oak Tracker Hub">← Hub</a>
<div class="version-switcher" role="group" aria-label="Game Version">
${versionPills}
</div>
<span class="platform-pill">${escapeHtml(game.platform)}</span>
</div>
<h1 class="app-title">Luminescent Platinum — Professor Oak Challenge Tracker</h1>
<p class="app-subtitle">
Complete v2.1 Tracker — check any Pokémon <span class="mint-inline">Caught</span> to sync across Areas &amp; Pokédex. Built for Luminescent’s exact Gym Leader level caps, no-trade evolutions, Incense regional spawns, and randomized [Team 1–4] boss battles.
</p>
</div>
<div class="progress-panel">
<div class="profile-bar">
<label class="profile-label" for="profile-select">Save</label>
<select class="select-input select-sm profile-select" id="profile-select" aria-label="Active save profile">
${profileOptions}
</select>
<button type="button" class="btn-ghost btn-xs" data-action="new-profile" title="Create a new save profile">+ New</button>
<button type="button" class="btn-ghost btn-xs" data-action="rename-profile" title="Rename active save profile">Rename</button>
${
profileList.length > 1
? '<button type="button" class="btn-ghost btn-xs btn-danger" data-action="delete-profile" title="Delete active save profile">Del</button>'
: ''
}
</div>
<div class="progress-stats-row">
<div>
<span class="progress-count">${progress.totalCaught}</span>
<span class="progress-sep">/</span>
<span class="progress-total">${progress.totalObtainable}</span>
<span class="progress-caption">${state.includeSpecialForms ? 'Dex + Special Forms' : 'Luminescent 2.1 Dex'}</span>
</div>
<span class="progress-pct">${progress.percent}%</span>
</div>
<div class="progress-track" role="progressbar" aria-valuenow="${progress.percent}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-fill" style="width: ${progress.percent}%"></div>
</div>
<div class="progress-meta-row">
<span>Remaining: <strong>${progress.totalRemaining}</strong></span>
<div class="header-actions">
<button type="button" class="btn-ghost btn-sm" data-action="export-json">Export Save</button>
<button type="button" class="btn-ghost btn-sm" data-action="import-json">Import</button>
<button type="button" class="btn-ghost btn-sm btn-danger" data-action="reset-progress">Reset</button>
</div>
</div>
</div>
</div>
<div class="header-toolbar">
<nav class="tab-nav" aria-label="Tracker views">
<button type="button" class="tab-btn ${state.activeTab === 'routes' ? 'active' : ''}" data-tab="routes">
Areas &amp; Routes
</button>
<button type="button" class="tab-btn ${state.activeTab === 'pokedex' ? 'active' : ''}" data-tab="pokedex">
Pokédex &amp; Evolution Methods
</button>
<button type="button" class="tab-btn ${state.activeTab === 'guide' ? 'active' : ''}" data-tab="guide">
Level Caps, Items &amp; Tips
</button>
</nav>
<div class="filter-controls">
<div class="search-wrap">
<input
type="search"
id="global-search"
class="search-input"
placeholder="Search Pokémon, trainer, item..."
value="${escapeHtml(state.searchQuery)}"
autocomplete="off"
/>
${state.searchQuery ? '<button type="button" class="search-clear" data-action="clear-search" title="Clear search">×</button>' : ''}
</div>
${
state.activeTab === 'routes'
? `<select class="select-input" id="method-filter" aria-label="Filter encounter method">${methodOptions}</select>`
: ''
}
<select class="select-input" id="starter-select" aria-label="Filter rival battles by chosen starter">
${starterOptions}
</select>
<label class="toggle-chip ${state.uncaughtOnly ? 'active' : ''}">
<input type="checkbox" id="uncaught-only-toggle" ${state.uncaughtOnly ? 'checked' : ''} />
<span>Uncaught Only</span>
</label>
<label
class="toggle-chip ${state.includeSpecialForms ? 'active' : ''}"
title="Optional: count Crystal Onix, Stitched Gengar, and Spiky-Eared Pichu separately (547 → 550)"
>
<input type="checkbox" id="special-forms-toggle" ${state.includeSpecialForms ? 'checked' : ''} />
<span>Special Forms (+3)</span>
</label>
<label
class="toggle-chip toggle-incense ${state.incenseActive ? 'active' : ''}"
for="incense-burner-toggle"
title="Simulates turning the Incense Burner Key Item ON/OFF in-game: activates Any Incense spawns and shows exact overwritten Ground (slots 4–5 & 10–11) and Surf (30% slot) rates"
>
<input type="checkbox" id="incense-burner-toggle" ${state.incenseActive ? 'checked' : ''} />
<span>Incense Burner${state.incenseActive ? ' (ON)' : ''}</span>
</label>
</div>
</div>
</header>
`;
}
+380
View File
@@ -0,0 +1,380 @@
import { SPECIES_BY_ID } from '../data/species.js';
import { getPokemonMoveset } from '../data/movesets.js';
import { indexGameSpecies } from '../state/tracker-store.js';
import { renderExternalLinksControl } from './external-links.js';
import { escapeHtml, getEvolutionFamily, getTypeBadgeHtml, padDex } from './formatters.js';
import { renderItemIconsHtml, renderPokemonSpriteImg } from './sprites.js';
function getCategoryBadgeHtml(category) {
const slug = String(category || 'Status').toLowerCase();
return `<span class="move-cat-pill cat-${escapeHtml(slug)}">${escapeHtml(category)}</span>`;
}
function renderBaseStatsHtml(species) {
const st = species.baseStats;
if (!st) return '';
const bars = [
['HP', st.hp, '#ef4444'],
['Atk', st.atk, '#f97316'],
['Def', st.def, '#eab308'],
['SpA', st.spa, '#3b82f6'],
['SpD', st.spd, '#22c55e'],
['Spe', st.spe, '#ec4899'],
];
return `
<div class="modal-section">
<div class="stats-header-row">
<h3 class="modal-subtitle">Base Stats (BST ${st.total})</h3>
${
species.abilities?.length
? `<div class="abilities-inline">Abilities: ${species.abilities
.map((ab, i) => `<span class="ability-pill">${escapeHtml(ab)}${i === 2 && species.abilities.length === 3 ? ' (HA)' : ''}</span>`)
.join('')}</div>`
: ''
}
</div>
<div class="stat-bars-grid">
${bars
.map(([label, val, color]) => {
const pct = Math.min(100, Math.round((val / 180) * 100));
return `
<div class="stat-bar-row">
<span class="stat-bar-label">${label}</span>
<span class="stat-bar-val mono">${val}</span>
<div class="stat-bar-track">
<div class="stat-bar-fill" style="width: ${pct}%; background: ${color}"></div>
</div>
</div>
`;
})
.join('')}
</div>
</div>
`;
}
function buildMovedexRows(moveset) {
const levelRows = moveset.levelUp.map((m) => ({
...m,
unlockLabel: m.level === 0 ? 'Evo' : `Lv. ${m.level}`,
badgeClass: 'unlock-level',
searchMethod: 'level up evo',
}));
const machineRows = moveset.machine.map((m) => ({
...m,
unlockLabel: m.machine || 'TM',
badgeClass: 'unlock-tm',
searchMethod: 'tm hm machine',
}));
const tutorRows = moveset.tutor.map((m) => ({
...m,
unlockLabel: 'Tutor',
badgeClass: 'unlock-tutor',
searchMethod: 'move tutor',
}));
const eggRows = moveset.egg.map((m) => ({
...m,
unlockLabel: 'Egg',
badgeClass: 'unlock-egg',
searchMethod: 'egg breed',
}));
const uniqueCount = new Set(
[...levelRows, ...machineRows, ...tutorRows, ...eggRows].map((m) => m.id),
).size;
return {
uniqueCount,
levelUp: levelRows,
machine: machineRows,
tutor: tutorRows,
egg: eggRows,
all: [...levelRows, ...machineRows, ...tutorRows, ...eggRows],
};
}
function matchesMoveQuery(row, q) {
if (!q) return true;
return `${row.name} ${row.type} ${row.category} ${row.unlockLabel} ${row.searchMethod}`
.toLowerCase()
.includes(q);
}
function renderMovedexSection(species, state) {
const moveset = getPokemonMoveset(species);
const rowsByTab = buildMovedexRows(moveset);
const activeTab = rowsByTab[state.movedexTab] ? state.movedexTab : 'levelUp';
const query = (state.movedexSearch || '').trim().toLowerCase();
const tabs = [
{ id: 'levelUp', label: 'Level-Up', count: rowsByTab.levelUp.length },
{ id: 'machine', label: 'TM / HM', count: rowsByTab.machine.length },
{ id: 'tutor', label: 'Tutor', count: rowsByTab.tutor.length },
{ id: 'egg', label: 'Egg', count: rowsByTab.egg.length },
{ id: 'all', label: 'All', count: rowsByTab.all.length },
];
const filteredRows = rowsByTab[activeTab].filter((row) => matchesMoveQuery(row, query));
const allMatchCount =
query && filteredRows.length === 0 && activeTab !== 'all'
? rowsByTab.all.filter((row) => matchesMoveQuery(row, query)).length
: 0;
const tabsHtml = tabs
.map(
(t) => `
<button
type="button"
class="movedex-tab-btn ${activeTab === t.id ? 'active' : ''}"
data-movedex-tab="${t.id}"
>${escapeHtml(t.label)} <span class="movedex-tab-count">(${t.count})</span></button>
`,
)
.join('');
const rowsHtml =
filteredRows.length > 0
? filteredRows
.map(
(m) => `
<tr class="movedex-row">
<td class="mono move-unlock-col">
<span class="move-method-pill ${escapeHtml(m.badgeClass)}">${escapeHtml(m.unlockLabel)}</span>
</td>
<td class="move-name-col">
<strong>${escapeHtml(m.name)}</strong>
</td>
<td>${getTypeBadgeHtml(m.type)}</td>
<td>${getCategoryBadgeHtml(m.category)}</td>
<td class="mono move-stat-col">${m.power ?? '—'}</td>
<td class="mono move-stat-col">${m.accuracy !== null && m.accuracy !== undefined ? `${m.accuracy}%` : '—'}</td>
<td class="mono move-stat-col">${m.pp ?? '—'}</td>
</tr>
`,
)
.join('')
: `
<tr>
<td colspan="7" class="empty-cell">
${
query
? allMatchCount > 0
? `No matches in this tab. <button type="button" class="inline-jump-link" data-movedex-tab="all">View ${allMatchCount} match${allMatchCount === 1 ? '' : 'es'} in All Moves</button>`
: `No Luminescent moves match "${escapeHtml(state.movedexSearch.trim())}".`
: `No ${escapeHtml(tabs.find((t) => t.id === activeTab)?.label || '')} moves recorded for ${escapeHtml(species.name)}.`
}
</td>
</tr>
`;
return `
<div class="modal-section movedex-section">
<div class="movedex-head-row">
<h3 class="modal-subtitle">Luminescent Platinum Movedex (${rowsByTab.uniqueCount} moves)</h3>
<div class="movedex-search-wrap">
<input
type="search"
id="movedex-search"
class="movedex-search-input"
placeholder="Filter moves, type, TM..."
value="${escapeHtml(state.movedexSearch || '')}"
autocomplete="off"
/>
${state.movedexSearch ? '<button type="button" class="search-clear" data-action="clear-movedex-search" title="Clear move filter">×</button>' : ''}
</div>
</div>
<div class="movedex-tabs" role="tablist" aria-label="Move learn methods">
${tabsHtml}
</div>
<div class="movedex-table-wrap">
<table class="movedex-table">
<thead>
<tr>
<th>Learn</th>
<th>Move</th>
<th>Type</th>
<th>Cat.</th>
<th class="move-stat-head">Pwr</th>
<th class="move-stat-head">Acc</th>
<th class="move-stat-head">PP</th>
</tr>
</thead>
<tbody>${rowsHtml}</tbody>
</table>
</div>
</div>
`;
}
export function renderSpeciesModal(game, state) {
if (!state.selectedSpeciesId) return '';
const species = SPECIES_BY_ID[state.selectedSpeciesId];
if (!species) return '';
const { locationsBySpecies } = indexGameSpecies(game, {
includeSpecialForms: Boolean(state.includeSpecialForms),
});
const locations = locationsBySpecies.get(species.id) || [];
const family = getEvolutionFamily(species.id);
const isCaught = state.caught.has(species.id);
const familyHtml = family
.map(({ species: member, depth }) => {
const memberCaught = state.caught.has(member.id);
const isCurrent = member.id === species.id;
const memberItemIcons = renderItemIconsHtml(member.evolutionMethod, { size: 18 });
return `
<div class="family-node ${isCurrent ? 'current' : ''} ${memberCaught ? 'is-caught' : ''}" style="--depth: ${depth}">
<input
type="checkbox"
class="caught-checkbox"
data-toggle-species="${escapeHtml(member.id)}"
${memberCaught ? 'checked' : ''}
aria-label="Mark ${escapeHtml(member.name)} caught"
/>
${renderPokemonSpriteImg(member, {
shiny: false,
className: 'pkmn-mini-sprite',
size: 36,
})}
<button type="button" class="species-link" data-inspect-species="${escapeHtml(member.id)}">
<strong>${escapeHtml(member.name)}</strong>
</button>
<span class="family-evo">
${memberItemIcons}
<span>${escapeHtml(member.evolutionMethod || 'Base')}</span>
</span>
</div>
`;
})
.join('');
const locHtml = locations.length
? locations
.map(
(loc) => `
<div class="modal-loc-row">
<div>
<span class="milestone-tag tag-earlier">${escapeHtml(loc.sectionShortName)}</span>
<strong>${escapeHtml(loc.areaName)}</strong>
<span class="amber-inline">[${escapeHtml(loc.method)}]</span>
${loc.notes ? `<span class="encounter-note">${escapeHtml(loc.notes)}</span>` : ''}
</div>
<div class="encounter-meta">
<span class="rate-pill">${escapeHtml(loc.rate)}</span>
<span class="level-pill">${escapeHtml(loc.levels)}</span>
</div>
</div>
`,
)
.join('')
: `<p class="muted-text">Obtained via evolution${species.evolutionMethod ? ` (${escapeHtml(species.evolutionMethod)})` : ''}.</p>`;
return `
<div class="modal-backdrop" data-action="close-modal" role="dialog" aria-modal="true" aria-label="${escapeHtml(species.name)} details">
<div class="modal-card">
<div class="modal-header">
<div>
<div class="modal-dex-nums">
Lumi #${padDex(species.excelIndex)} · National #${padDex(species.natId)}${species.formLabel ? ` · ${escapeHtml(species.formLabel)}` : ''}
</div>
<h2 class="modal-title">${escapeHtml(species.name)}</h2>
<div class="modal-types">${species.types.map(getTypeBadgeHtml).join('')}</div>
</div>
<div class="modal-header-actions">
${renderExternalLinksControl(species, state, 'modal')}
<button
type="button"
class="btn-caught-lg ${isCaught ? 'checked' : ''}"
data-toggle-species-btn="${escapeHtml(species.id)}"
>
${isCaught ? '✓ Caught' : 'Mark Caught'}
</button>
<button type="button" class="btn-ghost" data-action="close-modal" aria-label="Close">×</button>
</div>
</div>
<div class="modal-body">
<div class="sprite-showcase">
<div class="sprite-card">
<div class="sprite-frame">
${renderPokemonSpriteImg(species, { shiny: false, className: 'pkmn-sprite', size: 96 })}
</div>
<span class="sprite-label">Regular</span>
</div>
<div class="sprite-card sprite-card-shiny">
<div class="sprite-frame">
${renderPokemonSpriteImg(species, { shiny: true, className: 'pkmn-sprite', size: 96 })}
</div>
<span class="sprite-label shiny-label">★ Shiny</span>
</div>
</div>
${renderBaseStatsHtml(species)}
<div class="modal-section">
<h3 class="modal-subtitle">Evolution Family</h3>
<div class="family-list">${familyHtml}</div>
</div>
<div class="modal-section">
<h3 class="modal-subtitle">Sinnoh Locations &amp; Methods (${locations.length})</h3>
<div class="modal-locs">${locHtml}</div>
</div>
${renderMovedexSection(species, state)}
</div>
</div>
</div>
`;
}
export function renderProfileModal(game, state) {
const modal = state.profileModal;
if (!modal) return '';
const isRename = modal.mode === 'rename';
const target = isRename
? (state.profiles || []).find((p) => p.id === (modal.profileId || state.profileId))
: null;
const defaultVal = isRename
? target?.name || 'Save 1'
: `Save ${(state.profiles?.length || 1) + 1}`;
const heading = isRename
? `Rename ${game.shortTitle} Save Profile`
: `New ${game.shortTitle} Save Profile`;
return `
<div class="modal-backdrop" data-action="close-profile-modal" role="dialog" aria-modal="true" aria-label="${escapeHtml(heading)}">
<div class="modal-card modal-card-sm">
<div class="modal-header">
<div>
<div class="modal-dex-nums">${escapeHtml(game.title)}</div>
<h2 class="modal-title">${escapeHtml(heading)}</h2>
</div>
<button type="button" class="btn-ghost" data-action="close-profile-modal" aria-label="Close">×</button>
</div>
<div class="modal-body">
<form id="profile-modal-form" class="profile-form" data-profile-mode="${escapeHtml(modal.mode)}" data-profile-id="${escapeHtml(target?.id || '')}">
<label class="profile-form-label" for="profile-name-input">Profile Name</label>
<input
type="text"
id="profile-name-input"
class="text-input"
value="${escapeHtml(defaultVal)}"
maxlength="36"
required
autocomplete="off"
/>
<div class="profile-form-actions">
<button type="button" class="btn-ghost" data-action="close-profile-modal">Cancel</button>
<button type="submit" class="btn-primary">${isRename ? 'Save Name' : 'Create Save'}</button>
</div>
</form>
</div>
</div>
</div>
`;
}
+134
View File
@@ -0,0 +1,134 @@
import { escapeHtml, padDex, getTypeBadgeHtml } from './formatters.js';
import { renderExternalLinksControl } from './external-links.js';
import { renderItemIconsHtml, renderPokemonSpriteImg } from './sprites.js';
function sortIndicator(sortState, column) {
if (sortState.column !== column) return '<span class="sort-arrow muted">⇅</span>';
return `<span class="sort-arrow active">${sortState.direction === 'asc' ? '▲' : '▼'}</span>`;
}
export function renderPokedexView(store, state) {
const rows = store.getPokedexRows();
const caughtInView = rows.filter((r) => r.caught).length;
const tableRowsHtml = rows
.map((row) => {
const lumiLabel = `#${padDex(row.excelIndex)}`;
const natLabel = `#${padDex(row.natId)}`;
const milestoneLabel = row.earliest ? row.earliest.shortName : 'Optional Special Form';
const evoText = row.evolutionMethod || 'Base / Wild Encounter';
const typesHtml = row.types.map(getTypeBadgeHtml).join('');
const itemIconsHtml = renderItemIconsHtml(evoText, { size: 18 });
return `
<tr class="dex-row ${row.caught ? 'is-caught' : ''} ${row.isSpecialForm ? 'is-special-form' : ''}">
<td class="col-num mono">${escapeHtml(lumiLabel)}</td>
<td class="col-num mono">${escapeHtml(natLabel)}</td>
<td class="col-name">
<div class="dex-name-cell">
${renderPokemonSpriteImg(row, { shiny: false, className: 'pkmn-table-sprite', size: 28 })}
<button type="button" class="species-link" data-inspect-species="${escapeHtml(row.id)}">
${escapeHtml(row.name)}
</button>
<span class="inline-types">${typesHtml}</span>
${row.formLabel ? `<span class="form-pill">${escapeHtml(row.formLabel)}</span>` : ''}
${renderExternalLinksControl(row, state, 'pokedex')}
</div>
</td>
<td class="col-caught">
<input
type="checkbox"
class="caught-checkbox"
data-toggle-species="${escapeHtml(row.id)}"
${row.caught ? 'checked' : ''}
aria-label="Mark ${escapeHtml(row.name)} caught"
title="${row.caught ? 'Caught everywhere' : 'Mark caught everywhere'}"
/>
</td>
<td class="col-milestone">
${
row.earliest
? `<button type="button" class="milestone-jump-pill" data-jump-section="${escapeHtml(row.earliest.sectionId)}">${escapeHtml(milestoneLabel)}</button>`
: `<span class="muted-text">${escapeHtml(milestoneLabel)}</span>`
}
</td>
<td class="col-evo">
<span class="evo-cell-wrap">
${itemIconsHtml}
<span>${escapeHtml(evoText)}</span>
</span>
</td>
</tr>
`;
})
.join('');
return `
<div class="pokedex-view">
<div class="view-utility-bar">
<div class="dex-filter-pills">
<button type="button" class="pill-btn ${state.pokedexFilter === 'all' ? 'active' : ''}" data-dex-filter="all">
All (${rows.length})
</button>
<button type="button" class="pill-btn ${state.pokedexFilter === 'forms' ? 'active' : ''}" data-dex-filter="forms">
Regional &amp; Special Forms
</button>
<button type="button" class="pill-btn ${state.pokedexFilter === 'legendary' ? 'active' : ''}" data-dex-filter="legendary">
Quests &amp; Legendaries
</button>
</div>
<div class="utility-right">
<span class="dex-count-summary">Showing <strong>${rows.length}</strong> · Caught: <strong class="mint-inline">${caughtInView}</strong></span>
<button type="button" class="btn-ghost btn-sm" data-jump-tab="routes">↑ Back to Routes</button>
</div>
</div>
<div class="dex-table-wrap">
<table class="dex-table">
<thead>
<tr>
<th>
<button type="button" class="sort-btn" data-sort-col="excelIndex">
Lumi # ${sortIndicator(state.pokedexSort, 'excelIndex')}
</button>
</th>
<th>
<button type="button" class="sort-btn" data-sort-col="natId">
Nat # ${sortIndicator(state.pokedexSort, 'natId')}
</button>
</th>
<th>
<button type="button" class="sort-btn" data-sort-col="name">
Pokémon Name ${sortIndicator(state.pokedexSort, 'name')}
</button>
</th>
<th class="col-caught-head">
<button type="button" class="sort-btn" data-sort-col="caught">
Caught ${sortIndicator(state.pokedexSort, 'caught')}
</button>
</th>
<th>
<button type="button" class="sort-btn" data-sort-col="milestone">
Earliest Milestone ${sortIndicator(state.pokedexSort, 'milestone')}
</button>
</th>
<th>
<button type="button" class="sort-btn" data-sort-col="evolutionMethod">
Evolution / Obtain Method ${sortIndicator(state.pokedexSort, 'evolutionMethod')}
</button>
</th>
</tr>
</thead>
<tbody>
${
rows.length > 0
? tableRowsHtml
: `<tr><td colspan="6" class="empty-cell">No Pokédex entries match your current filter.</td></tr>`
}
</tbody>
</table>
</div>
</div>
`;
}
+644
View File
@@ -0,0 +1,644 @@
import { SPECIES_BY_ID } from '../data/species.js';
import { indexGameSpecies } from '../state/tracker-store.js';
import { escapeHtml, getMethodClass, getTypeBadgeHtml, padDex } from './formatters.js';
import { renderItemIconsHtml, renderPokemonSpriteImg } from './sprites.js';
const STARTER_LABELS = {
turtwig: 'Turtwig',
chimchar: 'Chimchar',
piplup: 'Piplup',
};
const TEAM_VARIANTS = ['Team 1', 'Team 2', 'Team 3', 'Team 4'];
function getTrainerRoleClass(role) {
switch (role) {
case 'Gym Leader':
return 'role-gym';
case 'Rival':
return 'role-rival';
case 'Team Galactic':
return 'role-galactic';
case 'Elite Four':
return 'role-e4';
case 'Champion':
return 'role-champion';
case 'Johto Time Portal':
return 'role-johto';
case 'Type Master (Plate)':
case 'Post-Game Boss':
case 'Boss / Quest':
return 'role-boss';
case 'Tag Partner':
return 'role-partner';
case 'Lv. 100 Rematch':
return 'role-rematch';
default:
return 'role-trainer';
}
}
function getTrainerAllMons(trainer) {
if (Array.isArray(trainer.team)) return trainer.team;
if (trainer.teamVariants) return Object.values(trainer.teamVariants).flat();
if (trainer.starterTeams) return Object.values(trainer.starterTeams).flat();
if (trainer.starterTeamVariants) {
return Object.values(trainer.starterTeamVariants).flatMap((vMap) => Object.values(vMap).flat());
}
return [];
}
function trainerMatchesSearch(trainer, area, section, q) {
if (!q) return true;
const hay = [
trainer.name,
trainer.role,
trainer.location,
trainer.format || '',
trainer.note || '',
area.name,
section.title,
]
.join(' ')
.toLowerCase();
if (hay.includes(q)) return true;
const monsText = getTrainerAllMons(trainer)
.map((mon) => `${mon.name} ${mon.item || ''} ${mon.ability || ''} ${(mon.types || []).join(' ')} ${(mon.moves || []).join(' ')}`)
.join(' ')
.toLowerCase();
return monsText.includes(q);
}
function renderTeamMonChipsHtml(team) {
return (team || [])
.map(
(mon) => `
<div class="team-mon-chip">
${renderPokemonSpriteImg(
{ natId: mon.natId, spriteFile: mon.spriteFile, name: mon.name },
{ className: 'pkmn-mini-sprite', size: 30 },
)}
<div class="team-mon-info">
<div class="team-mon-top">
<span class="team-mon-name">${escapeHtml(mon.name)}</span>
<span class="team-mon-level mono">Lv.${escapeHtml(mon.level)}</span>
${mon.item ? `<span class="team-mon-item">@ ${escapeHtml(mon.item)}</span>` : ''}
</div>
<div class="team-mon-sub">
<span class="team-mon-types">${(mon.types || []).map(getTypeBadgeHtml).join('')}</span>
${mon.ability ? `<span class="team-mon-meta">${escapeHtml(mon.ability)}</span>` : ''}
${mon.nature ? `<span class="team-mon-meta">${escapeHtml(mon.nature)}</span>` : ''}
</div>
${
mon.moves?.length
? `<div class="team-mon-moves">${mon.moves
.map((mv) => `<span class="move-chip">${escapeHtml(mv)}</span>`)
.join('')}</div>`
: ''
}
</div>
</div>
`,
)
.join('');
}
function renderTeamVariantEntries(variantsMap, selectedTeamVariant) {
const keysToShow =
selectedTeamVariant && selectedTeamVariant !== 'all' && variantsMap[selectedTeamVariant]
? [selectedTeamVariant]
: Object.keys(variantsMap);
return keysToShow
.map(
(vKey) => `
<div class="trainer-variant-group">
<span class="trainer-variant-label">${escapeHtml(vKey)}:</span>
<div class="trainer-team-row">${renderTeamMonChipsHtml(variantsMap[vKey])}</div>
</div>
`,
)
.join('');
}
function renderTrainerTeamHtml(trainer, state) {
const chosenStarter = state.chosenStarter || null;
const selectedVariant = state.selectedTeamVariant || 'all';
if (trainer.starterTeamVariants) {
if (chosenStarter && trainer.starterTeamVariants[chosenStarter]) {
const sLabel = STARTER_LABELS[chosenStarter] || chosenStarter;
return `
<div class="trainer-team-context">If you chose <strong>${escapeHtml(sLabel)}</strong> (4 possible Lumi teams):</div>
<div class="trainer-team-variants">${renderTeamVariantEntries(trainer.starterTeamVariants[chosenStarter], selectedVariant)}</div>
`;
}
return `<div class="trainer-team-variants">
${Object.entries(trainer.starterTeamVariants)
.map(
([sKey, vMap]) => `
<div class="trainer-starter-block">
<div class="trainer-team-context">Starter <strong>${escapeHtml(STARTER_LABELS[sKey] || sKey)}</strong>:</div>
${renderTeamVariantEntries(vMap, selectedVariant)}
</div>
`,
)
.join('')}
</div>`;
}
if (trainer.teamVariants) {
return `<div class="trainer-team-variants">${renderTeamVariantEntries(trainer.teamVariants, selectedVariant)}</div>`;
}
if (trainer.starterTeams) {
if (chosenStarter && trainer.starterTeams[chosenStarter]) {
const label = STARTER_LABELS[chosenStarter] || chosenStarter;
return `
<div class="trainer-team-context">Team for your <strong>${escapeHtml(label)}</strong> starter:</div>
<div class="trainer-team-row">${renderTeamMonChipsHtml(trainer.starterTeams[chosenStarter])}</div>
`;
}
const variantsHtml = Object.entries(trainer.starterTeams)
.map(([starterKey, team]) => {
const label = STARTER_LABELS[starterKey] || starterKey;
return `
<div class="trainer-variant-group">
<span class="trainer-variant-label">If ${escapeHtml(label)}:</span>
<div class="trainer-team-row">${renderTeamMonChipsHtml(team)}</div>
</div>
`;
})
.join('');
return `<div class="trainer-team-variants">${variantsHtml}</div>`;
}
return `<div class="trainer-team-row">${renderTeamMonChipsHtml(trainer.team || [])}</div>`;
}
function renderTrainerCardsGrid(trainers, state) {
const hasVariants = trainers.some((t) => Boolean(t.teamVariants || t.starterTeamVariants));
const curVar = state.selectedTeamVariant || 'all';
const variantBarHtml = hasVariants
? `
<div class="team-variant-bar">
<span class="team-variant-label">Boss Team Variant:</span>
<div class="team-variant-pills">
${['all', ...TEAM_VARIANTS]
.map(
(v) => `
<button
type="button"
class="pill-btn btn-xs ${curVar === v ? 'active' : ''}"
data-select-team-variant="${escapeHtml(v)}"
>${v === 'all' ? 'All 4 Teams' : escapeHtml(v)}</button>
`,
)
.join('')}
</div>
</div>
`
: '';
return `
${variantBarHtml}
<div class="trainers-grid">
${trainers
.map((trainer) => {
const isDefeated = state.defeatedTrainers.has(trainer.id);
const checkboxId = `trainer-check-${trainer.id}`;
return `
<article class="trainer-battle-card ${isDefeated ? 'is-defeated' : ''}">
<div class="trainer-card-header">
<input
type="checkbox"
class="caught-checkbox trainer-defeat-checkbox"
id="${escapeHtml(checkboxId)}"
data-toggle-trainer="${escapeHtml(trainer.id)}"
aria-label="Mark ${escapeHtml(trainer.name)} defeated"
${isDefeated ? 'checked' : ''}
/>
<label class="trainer-card-title-group" for="${escapeHtml(checkboxId)}">
<span class="role-pill ${getTrainerRoleClass(trainer.role)}">${escapeHtml(trainer.role)}</span>
<span class="trainer-name">${escapeHtml(trainer.name)}</span>
${trainer.format && trainer.format !== 'Single' ? `<span class="format-pill">${escapeHtml(trainer.format)}</span>` : ''}
${isDefeated ? '<span class="defeated-pill">Defeated</span>' : ''}
</label>
<span class="trainer-location">${escapeHtml(trainer.location)}</span>
</div>
${renderTrainerTeamHtml(trainer, state)}
</article>
`;
})
.join('')}
</div>
`;
}
function renderAreaTrainersDrawer(area, visibleTrainers, totalTrainersCount, state, isExpanded) {
const allTrainers = area.trainers || [];
const defeatedCount = allTrainers.filter((t) => state.defeatedTrainers.has(t.id)).length;
const allDefeated = totalTrainersCount > 0 && defeatedCount === totalTrainersCount;
const countLabel =
visibleTrainers.length < totalTrainersCount
? `${visibleTrainers.length} of ${totalTrainersCount} battles`
: visibleTrainers.length === 1
? '1 battle'
: `${visibleTrainers.length} battles`;
return `
<div class="trainers-panel area-trainers-drawer ${allDefeated ? 'all-defeated' : ''} ${isExpanded ? 'is-expanded' : ''}">
<button
type="button"
class="trainers-toggle-btn"
data-toggle-area-trainers="${escapeHtml(area.id)}"
aria-expanded="${isExpanded}"
>
<span class="trainers-toggle-left">
<span class="area-chevron">${isExpanded ? '▾' : '▸'}</span>
<span class="trainers-toggle-title">Trainer &amp; Boss Battles</span>
<span class="trainers-toggle-sub">${countLabel}${!isExpanded ? ' · Click to view teams, items & moves' : ''}</span>
</span>
<span class="area-status ${allDefeated ? 'done' : ''}">
${allDefeated ? `✓ All ${totalTrainersCount} defeated` : `${defeatedCount} / ${totalTrainersCount} defeated`}
</span>
</button>
${isExpanded ? renderTrainerCardsGrid(visibleTrainers, state) : ''}
</div>
`;
}
function entryMatchesSearch(entry, species, area, section, method, q) {
if (!q) return true;
const hay = [
species?.name || '',
species?.evolutionMethod || '',
String(species?.natId || ''),
species?.excelIndex ? String(species.excelIndex) : '',
entry.notes || '',
entry.rate || '',
entry.levels || '',
method,
area.name,
area.sublabel || '',
section.title,
]
.join(' ')
.toLowerCase();
return hay.includes(q);
}
function renderInlineIncenseToggle(isIncenseActive, extraClass = '') {
return `
<label
class="inline-incense-toggle ${isIncenseActive ? 'active' : ''} ${extraClass}"
title="Toggle Luminescent Platinum's Incense Burner Key Item ON/OFF (syncs across header and all sections)"
>
<input
type="checkbox"
class="inline-incense-checkbox"
data-toggle-incense
${isIncenseActive ? 'checked' : ''}
/>
<span>Incense Burner${isIncenseActive ? ' ON' : ''}</span>
</label>
`;
}
export function renderRoutesView(game, state, progress) {
const q = state.searchQuery.trim().toLowerCase();
const includeSpecialForms = Boolean(state.includeSpecialForms);
const { earliestBySpecies } = indexGameSpecies(game, { includeSpecialForms });
const progressBySection = new Map(progress.sections.map((s) => [s.id, s]));
const visibleSections = game.sections.filter(
(s) => state.activeSectionId === 'all' || s.id === state.activeSectionId,
);
let renderedSectionsCount = 0;
const sectionsHtml = visibleSections
.map((section) => {
const secProg = progressBySection.get(section.id);
const areasHtml = section.areas
.map((area) => {
const areaSpeciesIds = new Set();
let areaTargetCount = 0;
let areaCaughtCount = 0;
const groupsHtml = (area.groups || [])
.map((group) => {
const isJubilifePool = group.method === 'Gift Egg (Only 1)';
const isStarterPick = group.method === 'Starter';
const isIncenseGroup =
group.method === 'Any Incense' || group.method === 'Any Incense Surf';
const isIncenseActive = Boolean(state.incenseActive);
const hasIncenseShift = group.entries.some((e) => Boolean(e.incenseRate));
for (const entry of group.entries) {
const sp = SPECIES_BY_ID[entry.speciesId];
if (!sp) continue;
if (!includeSpecialForms && sp.isSpecialForm) continue;
if (isJubilifePool || isStarterPick) continue;
if (!areaSpeciesIds.has(entry.speciesId)) {
areaSpeciesIds.add(entry.speciesId);
areaTargetCount++;
if (state.caught.has(entry.speciesId)) areaCaughtCount++;
}
}
if (state.methodFilter !== 'all' && group.method !== state.methodFilter) {
return '';
}
const rowsHtml = group.entries
.map((entry) => {
const species = SPECIES_BY_ID[entry.speciesId];
if (!species) return '';
const isCaught = state.caught.has(entry.speciesId);
const isExcludedSpecial = !includeSpecialForms && species.isSpecialForm;
const earliest = earliestBySpecies.get(entry.speciesId);
const isFirstHere =
earliest && earliest.sectionId === section.id && earliest.areaId === area.id;
const jubilifePicked = state.jubilifeEggPick;
const isThisEggPick = isJubilifePool && jubilifePicked === entry.speciesId;
const isOtherEggPicked =
isJubilifePool && Boolean(jubilifePicked) && jubilifePicked !== entry.speciesId;
const chosenStarter = state.chosenStarter;
const isThisStarterPick = isStarterPick && chosenStarter === entry.speciesId;
const isOtherStarterPicked =
isStarterPick && Boolean(chosenStarter) && chosenStarter !== entry.speciesId;
if (state.uncaughtOnly && isCaught) return '';
if (state.uncaughtOnly && isExcludedSpecial) return '';
if (!entryMatchesSearch(entry, species, area, section, group.method, q)) {
return '';
}
const noteParts = [];
if (entry.notes) noteParts.push(entry.notes);
if (species.evolutionMethod && group.method === 'Evolution') {
// Already concise in notes
} else if (species.evolutionMethod) {
noteParts.push(`Evo: ${species.evolutionMethod}`);
}
const combinedNote = noteParts.join(' · ');
const evoIconHtml = renderItemIconsHtml(combinedNote, { size: 16 });
let statusTag = '';
if (isExcludedSpecial) {
statusTag = '<span class="milestone-tag tag-special">Special Form (Optional)</span>';
} else if (isJubilifePool) {
statusTag = isThisEggPick
? '<span class="milestone-tag tag-new">Picked in Jubilife</span>'
: isOtherEggPicked
? '<span class="milestone-tag tag-earlier">Other Egg Picked · Wild Later</span>'
: '<span class="milestone-tag tag-new">1-of-18 Early Egg</span>';
} else if (isStarterPick) {
statusTag = isThisStarterPick
? '<span class="milestone-tag tag-new">Starter Picked</span>'
: isOtherStarterPicked
? '<span class="milestone-tag tag-earlier">Other Picked · Claim in Sandgem</span>'
: '<span class="milestone-tag tag-new">Pick 1 Initial Starter</span>';
} else if (isFirstHere) {
statusTag = '<span class="milestone-tag tag-new">New</span>';
} else if (earliest) {
statusTag = `<span class="milestone-tag tag-earlier">${escapeHtml(earliest.shortName)}</span>`;
}
const eggPickBtn = isJubilifePool
? `<button type="button" class="btn-egg-pick ${isThisEggPick ? 'picked' : ''}" data-pick-jubilife-egg="${escapeHtml(entry.speciesId)}">${isThisEggPick ? '★ Picked' : 'Pick Egg'}</button>`
: isStarterPick
? `<button type="button" class="btn-egg-pick ${isThisStarterPick ? 'picked' : ''}" data-pick-starter="${escapeHtml(entry.speciesId)}">${isThisStarterPick ? '★ Starter' : 'Choose Starter'}</button>`
: '';
const isIncenseOffRow = isIncenseGroup && !isIncenseActive;
const hasShiftedRate = Boolean(entry.incenseRate && isIncenseActive);
const isReplacedByIncense = hasShiftedRate && entry.incenseRate === '0%';
const incenseBadgeHtml = isReplacedByIncense
? `<span class="milestone-tag tag-replaced" title="Overwritten to 0% while Incense Burner is ON — turn Incense Burner OFF to spawn">Replaced by Incense</span>`
: isIncenseOffRow
? `<span class="milestone-tag tag-incense-off" title="Activate the Incense Burner in the header (and Key Items in-game) to spawn">Incense OFF</span>`
: '';
const rateHtml = isIncenseOffRow
? `<span class="rate-zero">0%</span> <span class="rate-was-pill" title="Spawns at ${escapeHtml(entry.rate)} when Incense Burner is ON">ON: ${escapeHtml(entry.rate)}</span>`
: hasShiftedRate
? `<span class="${isReplacedByIncense ? 'rate-zero' : 'rate-reduced'}">${escapeHtml(entry.incenseRate)}</span> <span class="rate-was-pill" title="Incense overrides this slot (normal rate: ${escapeHtml(entry.rate)})">was ${escapeHtml(entry.rate)}</span>`
: isIncenseGroup && isIncenseActive
? `<span class="rate-boosted">${escapeHtml(entry.rate)}</span>`
: escapeHtml(entry.rate);
return `
<tr class="encounter-row ${isCaught ? 'is-caught' : ''} ${isOtherEggPicked || isOtherStarterPicked ? 'is-pool-other' : ''} ${isIncenseOffRow ? 'is-incense-inactive' : ''} ${isReplacedByIncense ? 'is-incense-replaced' : ''}" data-species-id="${escapeHtml(entry.speciesId)}">
<td class="col-check">
<input
type="checkbox"
class="caught-checkbox"
data-toggle-species="${escapeHtml(entry.speciesId)}"
${isCaught ? 'checked' : ''}
aria-label="Mark ${escapeHtml(species.name)} caught"
title="${isCaught ? 'Caught (synced globally)' : 'Mark caught'}"
/>
</td>
<td class="col-dex mono">#${padDex(species.natId)}</td>
<td class="col-pokemon">
<div class="pkmn-cell">
${renderPokemonSpriteImg(species, {
shiny: false,
className: 'pkmn-mini-sprite',
size: 28,
})}
<button type="button" class="species-link" data-inspect-species="${escapeHtml(entry.speciesId)}">
${escapeHtml(species.name)}
</button>
<span class="inline-types">${species.types.map(getTypeBadgeHtml).join('')}</span>
${statusTag}
${incenseBadgeHtml}
${eggPickBtn}
</div>
</td>
<td class="col-rate mono">${rateHtml}</td>
<td class="col-levels mono">${escapeHtml(entry.levels)}</td>
<td class="col-notes">
<span class="evo-cell-wrap">
${evoIconHtml}
<span>${escapeHtml(combinedNote)}</span>
</span>
</td>
</tr>
`;
})
.join('');
if (!rowsHtml.trim()) return '';
return `
<div class="method-group">
<div class="method-header">
<span class="method-badge ${getMethodClass(group.method)}">${escapeHtml(group.method)}</span>
${
isJubilifePool
? `<span class="egg-pool-status mono">${state.jubilifeEggPick ? `1/1 Egg: ${escapeHtml(SPECIES_BY_ID[state.jubilifeEggPick]?.name || '')}` : '0/1 Egg Picked'}</span>`
: isStarterPick
? `<span class="egg-pool-status mono">${state.chosenStarter ? `Starter: ${escapeHtml(SPECIES_BY_ID[state.chosenStarter]?.name || '')}` : '0/1 Starter Picked'}</span>`
: isIncenseGroup
? `${renderInlineIncenseToggle(isIncenseActive)}<span class="incense-status-pill ${isIncenseActive ? 'is-on' : 'is-off'}">${isIncenseActive ? 'Spawning' : '0% until ON'}</span>`
: hasIncenseShift && isIncenseActive
? `${renderInlineIncenseToggle(isIncenseActive)}<span class="incense-status-pill is-shifted">Slot Rates Adjusted</span>`
: ''
}
${group.note ? `<span class="method-note">${escapeHtml(group.note)}</span>` : ''}
</div>
<div class="encounter-table-wrap">
<table class="encounter-table">
<thead>
<tr>
<th class="col-check">Caught</th>
<th class="col-dex">Dex #</th>
<th>Pokémon</th>
<th class="col-rate">Rate</th>
<th class="col-levels">Levels</th>
<th>Notes / Evolution</th>
</tr>
</thead>
<tbody>${rowsHtml}</tbody>
</table>
</div>
</div>
`;
})
.filter(Boolean)
.join('');
const allAreaTrainers = area.trainers || [];
const visibleAreaTrainers = allAreaTrainers.filter((t) =>
trainerMatchesSearch(t, area, section, q),
);
const hasMatchingTrainers = visibleAreaTrainers.length > 0 && state.methodFilter === 'all';
if (!groupsHtml && !hasMatchingTrainers) return '';
const isCollapsed = state.collapsedAreas.has(area.id) && !q;
const isTrainersExpanded =
state.expandedTrainerAreas.has(area.id) || (Boolean(q) && visibleAreaTrainers.length > 0);
const allCaught = areaTargetCount > 0 && areaCaughtCount === areaTargetCount;
const trainersDrawerHtml =
allAreaTrainers.length > 0 && state.methodFilter === 'all'
? visibleAreaTrainers.length > 0
? renderAreaTrainersDrawer(
area,
visibleAreaTrainers,
allAreaTrainers.length,
state,
isTrainersExpanded,
)
: ''
: '';
const statusText =
areaTargetCount > 0
? allCaught
? `✓ All ${areaTargetCount} caught`
: `${areaCaughtCount} / ${areaTargetCount} caught`
: `${allAreaTrainers.length} battles`;
return `
<article class="area-card ${allCaught ? 'area-complete' : ''} ${isCollapsed ? 'is-collapsed' : ''}" id="${escapeHtml(area.id)}">
<button
type="button"
class="area-header"
data-toggle-area="${escapeHtml(area.id)}"
aria-expanded="${!isCollapsed}"
>
<div class="area-title-wrap">
<span class="area-chevron">${isCollapsed ? '▸' : '▾'}</span>
<div>
<h3 class="area-title">${escapeHtml(area.name)}</h3>
<p class="area-subtitle">${escapeHtml(area.sublabel || '')}</p>
</div>
</div>
<span class="area-status ${allCaught ? 'done' : ''}">${statusText}</span>
</button>
<div class="area-body">
${groupsHtml}
${trainersDrawerHtml}
</div>
</article>
`;
})
.filter(Boolean)
.join('');
if (!areasHtml) return '';
renderedSectionsCount++;
const secDone = secProg && secProg.newTotal > 0 && secProg.newRemaining === 0;
const sectionHasIncense = section.areas.some((a) =>
(a.groups || []).some(
(g) => g.method === 'Any Incense' || g.method === 'Any Incense Surf',
),
);
return `
<section class="milestone-section ${secDone ? 'section-done' : ''}" id="sec-${escapeHtml(section.id)}">
<div class="section-banner">
<div>
<div class="section-eyebrow">
<span>${section.badgeNumber === 0 ? 'START · CAP LV. 16' : `AFTER ${section.badgeNumber} BADGE${section.badgeNumber > 1 ? 'S' : ''} · CAP LV. ${section.levelCap}`}</span>
<span class="cap-badge-inline">${escapeHtml(section.capBoss || '')}</span>
</div>
<h2 class="section-title">${escapeHtml(section.title)}</h2>
<p class="section-summary">${escapeHtml(section.summary)}</p>
</div>
<div class="section-counters">
${sectionHasIncense ? renderInlineIncenseToggle(Boolean(state.incenseActive), 'section-incense-toggle') : ''}
<div class="counter-box">
<span class="counter-label">New This Section</span>
<span class="counter-val">${secProg ? `${secProg.newCaught} / ${secProg.newTotal}` : '—'}</span>
</div>
<div class="counter-box">
<span class="counter-label">Cumulative POC</span>
<span class="counter-val mint-inline">${secProg ? `${secProg.cumulativeCaught} / ${secProg.cumulativeTotal}` : '—'}</span>
</div>
</div>
</div>
<div class="areas-stack">${areasHtml}</div>
</section>
`;
})
.filter(Boolean)
.join('');
return `
<div class="routes-view">
<div class="view-utility-bar">
<span class="view-hint">
Check any row to highlight it <span class="mint-inline">mint green</span> everywhere. Click any Pokémon name for base stats, Shiny sprites, locations &amp; Luminescent Movedex.
</span>
<div class="utility-actions">
<button type="button" class="btn-ghost btn-sm" data-action="expand-all">Expand All Areas</button>
<button type="button" class="btn-ghost btn-sm" data-action="collapse-all">Collapse All Areas</button>
</div>
</div>
${
renderedSectionsCount > 0
? sectionsHtml
: `
<div class="empty-state">
<h3>No routes or encounters match your filters</h3>
<p>Try clearing your search, switching method filter back to All Methods, or unchecking Uncaught Only.</p>
<button type="button" class="btn-primary" data-action="clear-filters">Reset View Filters</button>
</div>
`
}
</div>
`;
}
+54
View File
@@ -0,0 +1,54 @@
import { escapeHtml } from './formatters.js';
export function renderSidebar(game, state, progress) {
const sectionButtons = progress.sections
.map((sec) => {
const active = state.activeSectionId === sec.id;
const done = sec.newTotal > 0 && sec.newRemaining === 0;
return `
<button
type="button"
class="milestone-btn ${active ? 'active' : ''} ${done ? 'done' : ''}"
data-section-id="${escapeHtml(sec.id)}"
>
<div class="milestone-top">
<span class="milestone-name">${done ? '✓ ' : ''}${escapeHtml(sec.shortName)}</span>
<span class="milestone-count">${sec.newCaught}/${sec.newTotal}</span>
</div>
<div class="milestone-sub">
<span>${sec.levelCap ? `Cap Lv.${sec.levelCap} · ` : ''}New: ${sec.newTotal}</span>
<span>Cumul: ${sec.cumulativeCaught}/${sec.cumulativeTotal}</span>
</div>
<div class="mini-bar">
<div class="mini-bar-fill" style="width: ${sec.newTotal ? Math.round((sec.newCaught / sec.newTotal) * 100) : 0}%"></div>
</div>
</button>
`;
})
.join('');
return `
<aside class="milestone-rail" aria-label="Badge Checkpoints">
<div class="rail-header">
<span class="rail-title">Badge Checkpoints</span>
<button type="button" class="btn-link" data-section-id="all">Show All</button>
</div>
<div class="milestone-list">
<button
type="button"
class="milestone-btn ${state.activeSectionId === 'all' ? 'active' : ''}"
data-section-id="all"
>
<div class="milestone-top">
<span class="milestone-name">All Sections</span>
<span class="milestone-count">${progress.totalCaught}/${progress.totalObtainable}</span>
</div>
<div class="milestone-sub">
<span>Complete ${escapeHtml(game.shortTitle)} POC</span>
</div>
</button>
${sectionButtons}
</div>
</aside>
`;
}
+120
View File
@@ -0,0 +1,120 @@
import { escapeHtml } from './formatters.js';
export const LUMI_IMG_CDN =
'https://raw.githubusercontent.com/TeamLumi/luminescent-team/main/static/img';
export const POKEAPI_FALLBACK_CDN =
'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites';
let spriteBaseUrl = LUMI_IMG_CDN;
export function setSpriteBaseUrl(baseUrl) {
spriteBaseUrl = String(baseUrl || LUMI_IMG_CDN).replace(/\/+$/, '');
}
export function getSpriteBaseUrl() {
return spriteBaseUrl;
}
const ITEM_PATTERNS = [
{ regex: /water stone/i, file: 'items/Item_Water_Stone.webp', label: 'Water Stone' },
{ regex: /fire stone/i, file: 'items/Item_Fire_Stone.webp', label: 'Fire Stone' },
{ regex: /thunder stone/i, file: 'items/Item_Thunder_Stone.webp', label: 'Thunder Stone' },
{ regex: /leaf stone/i, file: 'items/Item_Leaf_Stone.webp', label: 'Leaf Stone' },
{ regex: /moon stone/i, file: 'items/Item_Moon_Stone.webp', label: 'Moon Stone' },
{ regex: /sun stone/i, file: 'items/Item_Sun_Stone.webp', label: 'Sun Stone' },
{ regex: /shiny stone/i, file: 'items/Item_Shiny_Stone.webp', label: 'Shiny Stone' },
{ regex: /dusk stone/i, file: 'items/Item_Dusk_Stone.webp', label: 'Dusk Stone' },
{ regex: /dawn stone/i, file: 'items/Item_Dawn_Stone.webp', label: 'Dawn Stone' },
{ regex: /ice stone/i, file: 'items/Item_Ice_Stone.webp', label: 'Ice Stone' },
{ regex: /oval stone/i, file: 'items/Item_Oval_Stone.webp', label: 'Oval Stone' },
{ regex: /king['’]?s rock/i, file: 'items/Item_Kings_Rock.webp', label: "King's Rock" },
{ regex: /metal coat/i, file: 'items/Item_Metal_Coat.webp', label: 'Metal Coat' },
{ regex: /dragon scale/i, file: 'items/Item_Dragon_Scale.webp', label: 'Dragon Scale' },
{ regex: /deep sea tooth/i, file: 'items/Item_Deep_Sea_Tooth.webp', label: 'Deep Sea Tooth' },
{ regex: /deep sea scale/i, file: 'items/Item_Deep_Sea_Scale.webp', label: 'Deep Sea Scale' },
{ regex: /protector/i, file: 'items/Item_Protector.webp', label: 'Protector' },
{ regex: /reaper cloth/i, file: 'items/Item_Reaper_Cloth.webp', label: 'Reaper Cloth' },
{ regex: /electirizer/i, file: 'items/Item_Electirizer.webp', label: 'Electirizer' },
{ regex: /magmarizer/i, file: 'items/Item_Magmarizer.webp', label: 'Magmarizer' },
{ regex: /\bup-?grade\b/i, file: 'items/Item_Upgrade.webp', label: 'Upgrade' },
{ regex: /dubious disc/i, file: 'items/Item_Dubious_Disc.webp', label: 'Dubious Disc' },
{ regex: /prism scale/i, file: 'items/Item_Prism_Scale.webp', label: 'Prism Scale' },
{ regex: /razor claw/i, file: 'items/Item_Razor_Claw.webp', label: 'Razor Claw' },
{ regex: /razor fang/i, file: 'items/Item_Razor_Fang.webp', label: 'Razor Fang' },
{ regex: /soothe bell/i, file: 'items/Item_Soothe_Bell.webp', label: 'Soothe Bell' },
{ regex: /moss rock/i, file: 'Moss%20Rock.webp', label: 'Moss Rock' },
{ regex: /ice rock/i, file: 'Ice%20Rock.webp', label: 'Ice Rock' },
{ regex: /incense/i, file: 'Incense.webp', label: 'Incense' },
{ regex: /honey/i, file: 'items/Item_Honey.webp', label: 'Honey' },
{ regex: /pok[eé] ball/i, file: 'items/Item_Poke_Ball.webp', label: 'Poké Ball' },
];
export function getPokemonSpriteUrls(species, { shiny = false } = {}) {
const base = getSpriteBaseUrl();
const natId = species?.natId || 1;
const padded = String(natId).padStart(4, '0');
const regFile = species?.spriteFile || `pm${padded}_00_00_L.webp`;
const shnFile = species?.shinySpriteFile || `pm${padded}_00_01_L.webp`;
const primary = shiny
? `${base}/shinypkm/${shnFile}`
: `${base}/pkm/${regFile}`;
const fallback = shiny
? `${POKEAPI_FALLBACK_CDN}/pokemon/shiny/${natId}.png`
: `${POKEAPI_FALLBACK_CDN}/pokemon/${natId}.png`;
return { primary, fallback };
}
export function getItemSpriteUrl(file) {
return `${getSpriteBaseUrl()}/${file}`;
}
export function extractItemsFromText(text) {
if (!text) return [];
const matches = [];
const seen = new Set();
for (const item of ITEM_PATTERNS) {
if (item.regex.test(text) && !seen.has(item.file)) {
seen.add(item.file);
matches.push({
file: item.file,
label: item.label,
url: getItemSpriteUrl(item.file),
});
}
}
return matches;
}
export function renderPokemonSpriteImg(species, { shiny = false, className = 'pkmn-sprite', size = 96 } = {}) {
const { primary, fallback } = getPokemonSpriteUrls(species, { shiny });
const alt = `${species?.name || 'Pokémon'}${shiny ? ' (Shiny)' : ''} sprite`;
return `<img
class="${escapeHtml(className)}"
src="${escapeHtml(primary)}"
data-fallback-src="${escapeHtml(fallback)}"
alt="${escapeHtml(alt)}"
width="${size}"
height="${size}"
loading="lazy"
/>`;
}
export function renderItemIconsHtml(text, { size = 20 } = {}) {
const items = extractItemsFromText(text);
if (items.length === 0) return '';
return items
.map(
(item) => `<img
class="evo-item-icon"
src="${escapeHtml(item.url)}"
alt="${escapeHtml(item.label)}"
title="${escapeHtml(item.label)}"
width="${size}"
height="${size}"
loading="lazy"
/>`,
)
.join('');
}
+438
View File
@@ -0,0 +1,438 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SPECIES_LIST, SPECIES_BY_ID } from '../src/data/species.js';
import { getPokemonMoveset } from '../src/data/movesets.js';
import { getGame } from '../src/data/games/index.js';
import {
computeGameProgress,
createTrackerStore,
indexGameSpecies,
} from '../src/state/tracker-store.js';
import { getExternalLinksForSpecies, renderExternalLinksControl } from '../src/ui/external-links.js';
import { renderRoutesView } from '../src/ui/routes-view.js';
import { renderHeader } from '../src/ui/header.js';
import { renderPokedexView } from '../src/ui/pokedex-view.js';
import { renderSpeciesModal } from '../src/ui/modal.js';
import { getPokemonSpriteUrls } from '../src/ui/sprites.js';
import { createStaticServer } from '../server.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, '..');
function makeMemoryStorage() {
const map = new Map();
return {
getItem(k) {
return map.has(k) ? map.get(k) : null;
},
setItem(k, v) {
map.set(k, String(v));
},
removeItem(k) {
map.delete(k);
},
keys() {
return [...map.keys()];
},
};
}
test('Pokédex totals equal exact 547 default and 550 with Special Forms enabled', () => {
const baseSpecies = SPECIES_LIST.filter((s) => !s.isSpecialForm);
const specialSpecies = SPECIES_LIST.filter((s) => s.isSpecialForm);
assert.equal(baseSpecies.length, 547);
assert.equal(specialSpecies.length, 3);
assert.equal(SPECIES_LIST.length, 550);
const game = getGame('luminescent-platinum');
const progBase = computeGameProgress(game, new Set(), 'solo', { includeSpecialForms: false });
assert.equal(progBase.totalObtainable, 547);
assert.equal(progBase.sections.at(-1).cumulativeTotal, 547);
assert.equal(progBase.sections.length, 10);
const progFull = computeGameProgress(game, new Set(), 'solo', { includeSpecialForms: true });
assert.equal(progFull.totalObtainable, 550);
assert.equal(progFull.sections.at(-1).cumulativeTotal, 550);
// Marking all 547 caught gives 100% completion
const allBaseCaught = new Set(baseSpecies.map((s) => s.id));
const doneBase = computeGameProgress(game, allBaseCaught, 'solo', { includeSpecialForms: false });
assert.equal(doneBase.totalCaught, 547);
assert.equal(doneBase.percent, 100);
});
test('Level caps and item/story gates match Luminescent Platinum v2.1 rules', () => {
const game = getGame('luminescent-platinum');
const { earliestBySpecies } = indexGameSpecies(game, { includeSpecialForms: true });
const secOf = (id) => earliestBySpecies.get(id)?.sectionId;
// Section 1: Roark Lv. 16 cap
assert.equal(secOf('kadabra'), 'pre-badge-1');
assert.equal(secOf('ivysaur'), 'pre-badge-1');
assert.equal(secOf('mewth-alola') || secOf('meowth-alola'), 'pre-badge-1');
assert.equal(secOf('persian-alola'), 'pre-badge-1'); // Friendship evo!
// Section 2: Gardenia Lv. 26 cap (Floaroma/Eterna/Windworks/Coronet 211/Rt 216 early + Mining stones)
assert.equal(secOf('lucario'), 'pre-badge-2'); // Aura Sphere Lv. 26
assert.equal(secOf('mr-mime'), 'pre-badge-2'); // Mime Jr. Route 205S + Mimic Lv. 18
assert.equal(secOf('stitched-gengar'), 'pre-badge-2'); // Old Chateau Static
assert.equal(secOf('leafeon'), 'pre-badge-2');
assert.equal(secOf('glaceon'), 'pre-badge-2');
// Section 3: Fantina Lv. 33 cap (Cut, Wayward Cave, Magnetic Field, High Beauty)
assert.equal(secOf('magnezone'), 'pre-badge-3');
assert.equal(secOf('milotic'), 'pre-badge-3'); // High Beauty Hearthome
assert.equal(secOf('mismagius'), 'pre-badge-3'); // Dusk Stone Wayward Cave
assert.equal(secOf('steelix'), 'pre-badge-3'); // Metal Coat Route 207
// Section 4: Maylene Lv. 39 cap (Bonsly Rt 209, Lv. 36 trade replacements, Veilstone Dept Store, Nursery)
assert.equal(secOf('sudowoodo'), 'pre-badge-4'); // Bonsly first wild spawn Route 209
assert.equal(secOf('alakazam'), 'pre-badge-4');
assert.equal(secOf('machamp'), 'pre-badge-4');
assert.equal(secOf('golem'), 'pre-badge-4');
assert.equal(secOf('manaphy'), 'pre-badge-4');
assert.equal(secOf('phione'), 'pre-badge-4'); // Manaphy + Ditto Solaceon Nursery
assert.equal(secOf('weavile'), 'pre-badge-4'); // Razor Claw Rt 215
assert.equal(secOf('gliscor'), 'pre-badge-4'); // Razor Fang Rt 215
assert.equal(secOf('kleavor'), 'pre-badge-4'); // Scyther Rt 209 + King's Rock
// Section 5: Wake Lv. 44 cap (Move Reminder Ancient Power, Jirachi Lv. 42)
assert.equal(secOf('mamoswine'), 'pre-badge-5');
assert.equal(secOf('jirachi'), 'pre-badge-5');
// Section 6: Byron Lv. 53 cap (Surf, Protector Iron Island, Quests Mew/Celebi/Crystal Onix/Spiky Pichu)
assert.equal(secOf('rhyperior'), 'pre-badge-6');
assert.equal(secOf('ursaluna'), 'pre-badge-6'); // Lv. 48 Night
assert.equal(secOf('mew'), 'pre-badge-6');
assert.equal(secOf('celebi'), 'pre-badge-6');
assert.equal(secOf('crystal-onix'), 'pre-badge-6');
assert.equal(secOf('spiky-eared-pichu'), 'pre-badge-6');
// Section 7: Candice Lv. 56 cap (Super Rod & Snowpoint Held-Trade Vendor)
assert.equal(secOf('lapras'), 'pre-badge-7');
assert.equal(secOf('dragonite'), 'pre-badge-7'); // Lv. 55
assert.equal(secOf('porygon-z'), 'pre-badge-7');
assert.equal(secOf('electivire'), 'pre-badge-7');
// Section 8: Volkner Lv. 62 cap (Post-Distortion World Rowan Quests Lv. 60)
assert.equal(secOf('uxie'), 'pre-badge-8');
assert.equal(secOf('articuno'), 'pre-badge-8');
assert.equal(secOf('raikou'), 'pre-badge-8');
// Section 9: Cynthia Lv. 78 cap (Waterfall Victory Road Moltres Lv. 60)
assert.equal(secOf('moltres'), 'pre-champion');
// Section 10: Post-Game
assert.equal(secOf('heatran'), 'post-game');
assert.equal(secOf('giratina'), 'post-game');
assert.equal(secOf('arceus'), 'post-game');
// Every Pre-Badge Evolution Checklist obeys its section's Gym Leader level cap
for (const sec of game.sections) {
const evoArea = sec.areas.find((a) => a.id.startsWith('evolutions-'));
if (!evoArea) continue;
for (const grp of evoArea.groups) {
for (const entry of grp.entries) {
const m = String(entry.levels || '').match(/Lv\.?\s*(\d+)|Level\s+(\d+)/i);
if (m) {
const lv = Number(m[1] || m[2]);
assert.ok(
lv <= sec.levelCap,
`${entry.speciesId} in ${sec.id} requires Lv.${lv} > cap ${sec.levelCap}`,
);
}
}
}
}
});
test('Jubilife Gift Egg (Only 1) picks early bonus without double counting or locking later spawns', () => {
const storage = makeMemoryStorage();
const store = createTrackerStore({ storage });
store.toggleJubilifeEggPick('elekid');
let st = store.getState();
assert.equal(st.jubilifeEggPick, 'elekid');
assert.equal(st.caught.has('elekid'), true);
// Total obtainable remains strictly 547
const prog = computeGameProgress(store.getGame(), st.caught, 'solo', { includeSpecialForms: false });
assert.equal(prog.totalObtainable, 547);
// Other babies like magby and togepi remain catchable/checkable in later routes!
store.toggleCaught('magby', true);
assert.equal(store.getState().caught.has('magby'), true);
// Toggling Jubilife egg pick again clears pick label
store.toggleJubilifeEggPick('elekid');
assert.equal(store.getState().jubilifeEggPick, null);
});
test('Every species has a valid Luminescent Movedex, forms are distinct, and Crystal Onix has Rock/Ice', () => {
const empty = [];
for (const sp of SPECIES_LIST) {
const ms = getPokemonMoveset(sp);
const total = ms.levelUp.length + ms.machine.length + ms.tutor.length + ms.egg.length;
if (total === 0) empty.push(sp.id);
}
assert.deepEqual(empty, []);
const crystalOnix = SPECIES_BY_ID['crystal-onix'];
assert.deepEqual(crystalOnix.types, ['Rock', 'Ice']);
assert.equal(crystalOnix.spriteFile, 'pm0095_01_00_00_L.webp');
assert.equal(crystalOnix.shinySpriteFile, 'pm0095_01_01_L.webp');
const charizardMoves = getPokemonMoveset('charizard');
assert.ok(charizardMoves.levelUp.some((m) => m.level === 0 && m.name === 'Air Slash'));
assert.ok(charizardMoves.machine.some((m) => /^TM\d{2}$/.test(m.machine)));
// Distinct regional moveset check: Raichu vs Raichu-A
const rBase = getPokemonMoveset('raichu');
const rAlola = getPokemonMoveset('raichu-alola');
assert.ok(rAlola.levelUp.some((m) => /Psychic/i.test(m.name)));
assert.notEqual(
JSON.stringify(rBase.levelUp.slice(0, 5)),
JSON.stringify(rAlola.levelUp.slice(0, 5)),
);
});
test('Routes trainer drawers, Boss [Team 1-4] variants, Starter filtering, and Pokedex/Movedex render cleanly', () => {
const storage = makeMemoryStorage();
const store = createTrackerStore({ storage });
const game = store.getGame();
// Route 201 has Barry starter variants; Oreburgh City has Roark Team 1..4 variants
const sec1 = game.sections[0];
const rt201 = sec1.areas.find((a) => a.name.includes('Route 201'));
const oreburgh = sec1.areas.find((a) => a.name.includes('Oreburgh City'));
assert.ok(rt201?.trainers?.length > 0);
assert.ok(oreburgh?.trainers?.some((t) => t.teamVariants && Object.keys(t.teamVariants).length === 4));
// Expand Oreburgh trainers and switch team variant to Team 3
store.toggleAreaTrainersExpanded(oreburgh.id);
store.setSelectedTeamVariant('Team 3');
store.setChosenStarter('chimchar');
const html = renderRoutesView(
game,
store.getState(),
computeGameProgress(game, store.getState().caught, 'solo'),
);
assert.ok(html.includes('Gym Leader Roark'));
assert.ok(html.includes('Team 3:'));
assert.ok(!html.includes('Team 2:'));
assert.ok(html.includes('Trainer Battles') || html.includes('Trainer &amp; Boss Battles'));
// Pokedex table renders Search/Links/Movedex
const dexHtml = renderPokedexView(store, store.getState());
assert.ok(dexHtml.includes('Bulbasaur'));
assert.ok(dexHtml.includes('Tinkaton'));
store.setSelectedSpeciesId('tinkaton');
store.toggleExternalMenu('tinkaton', 'modal');
const modalHtml = renderSpeciesModal(game, store.getState());
assert.ok(modalHtml.includes('Luminescent Platinum Movedex'));
assert.ok(modalHtml.includes('https://luminescent.team/pokedex/tinkaton'));
assert.ok(modalHtml.includes('https://www.serebii.net/pokedex-sv/tinkaton/'));
});
test('External links and sprites resolve cleanly for standard, regional, and special form Pokémon', () => {
const alolaVulpix = SPECIES_BY_ID['vulpix-alola'];
const links = getExternalLinksForSpecies(alolaVulpix);
assert.equal(links[0].url, 'https://luminescent.team/pokedex/alola-vulpix');
assert.equal(links[1].url, 'https://www.serebii.net/pokedex-sv/vulpix/');
assert.equal(links[2].url, 'https://bulbapedia.bulbagarden.net/wiki/Vulpix_(Pok%C3%A9mon)');
const spUrl = getPokemonSpriteUrls(SPECIES_BY_ID['spiky-eared-pichu'], { shiny: true });
assert.ok(spUrl.primary.endsWith('/shinypkm/pm0172_01_11_L.webp'));
const rotomUrl = getPokemonSpriteUrls(SPECIES_BY_ID['rotom'], { shiny: true });
assert.ok(rotomUrl.primary.endsWith('/shinypkm/pm0479_00_21_L.webp'));
const extHtml = renderExternalLinksControl(alolaVulpix, { openExternalMenu: { speciesId: 'vulpix-alola', context: 'pokedex' } }, 'pokedex');
assert.ok(extHtml.includes('Team Luminescent Pokédex'));
});
test('Save profiles, isolated storage prefix, and JSON export/import round-trip accurately', () => {
const storage = makeMemoryStorage();
const store = createTrackerStore({ storage });
store.toggleCaught('bulbasaur', true);
store.toggleJubilifeEggPick('magby');
store.setIncludeSpecialForms(true);
const p2 = store.createProfile('Nuzlocke Run');
assert.equal(store.getState().caught.size, 0);
store.toggleCaught('piplup', true);
store.switchProfile('default');
assert.equal(store.getState().caught.has('bulbasaur'), true);
assert.equal(store.getState().caught.has('piplup'), false);
assert.equal(store.getState().includeSpecialForms, true);
const exported = store.exportJson();
assert.ok(storage.keys().every((k) => k.startsWith('lumi-poc-tracker:v1:')));
store.switchProfile(p2.id);
store.importJson(exported);
assert.equal(store.getState().caught.has('bulbasaur'), true);
assert.equal(store.getState().jubilifeEggPick, 'magby');
store.renameProfile(p2.id, 'Main Lumi');
assert.equal(store.getActiveProfile().name, 'Main Lumi');
assert.equal(store.deleteProfile(p2.id), true);
assert.equal(store.deleteProfile('default'), false);
});
test('Static HTTP server serves Luminescent app assets and rejects directory traversal', async () => {
const server = createStaticServer(ROOT_DIR);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
try {
const htmlRes = await fetch(`http://127.0.0.1:${port}/`);
assert.equal(htmlRes.status, 200);
const html = await htmlRes.text();
assert.ok(html.includes('Luminescent Platinum'));
const statusRes = await fetch(`http://127.0.0.1:${port}/api/assets-status`);
assert.equal(statusRes.status, 200);
const statusJson = await statusRes.json();
assert.equal(typeof statusJson.hasLocalSprites, 'boolean');
const badStatus = await new Promise((resolve, reject) => {
const req = http.request(
{ hostname: '127.0.0.1', port, path: '/../package.json', method: 'GET' },
(res) => {
res.resume();
resolve(res.statusCode);
},
);
req.on('error', reject);
req.end();
});
assert.equal(badStatus, 403);
} finally {
await new Promise((resolve) => server.close(resolve));
}
});
test('Method levels never leak Surfing labels onto Old Rod/Gifts and Old Rod backtracks order after Jubilife Gatehouse', () => {
const game = getGame('luminescent-platinum');
const sec1 = game.sections[0];
const areaIds = sec1.areas.map((a) => a.id);
// Twinleaf initial card has only Gift (Eevee Lv. 5), no premature Old Rod and no (Surfing)
const twinleafInit = sec1.areas.find((a) => a.id === 'area-1');
assert.ok(twinleafInit);
assert.equal(twinleafInit.groups.length, 1);
assert.equal(twinleafInit.groups[0].method, 'Gift');
assert.equal(twinleafInit.groups[0].entries[0].speciesId, 'eevee');
assert.equal(twinleafInit.groups[0].entries[0].levels, 'Lv. 5');
assert.ok(!/Surfing/i.test(twinleafInit.sublabel));
// Old Rod backtracks (Twinleaf, Lake Verity, Route 219) come chronologically after Jubilife City & Route 218 Gatehouse
const jubilifeIdx = areaIds.indexOf('area-7');
const route218Idx = areaIds.indexOf('area-8');
const twinleafRodIdx = areaIds.indexOf('area-1-oldrod');
const verityRodIdx = areaIds.indexOf('area-3-oldrod');
const route219Idx = areaIds.indexOf('area-5');
assert.ok(jubilifeIdx > -1 && route218Idx > jubilifeIdx);
assert.ok(twinleafRodIdx > route218Idx);
assert.ok(verityRodIdx > route218Idx);
assert.ok(route219Idx > route218Idx);
assert.equal(sec1.areas[twinleafRodIdx].groups[0].entries[0].levels, 'Lv. 10');
// Across the entire game, no non-Surf group or card without Surf ever displays "(Surfing)"
for (const sec of game.sections) {
for (const area of sec.areas) {
const hasSurf = area.groups.some((g) => g.method === 'Surf' || g.method === 'Any Incense Surf');
if (!hasSurf) {
assert.ok(!/Surfing/i.test(area.sublabel), `Sublabel leaked Surfing on ${area.name}`);
}
for (const g of area.groups) {
for (const e of g.entries) {
assert.ok(Boolean(e.levels), `Empty levels on ${area.name} -> ${g.method} -> ${e.speciesId}`);
if (g.method !== 'Surf' && g.method !== 'Any Incense Surf') {
assert.ok(!/Surfing/i.test(e.levels), `Entry ${e.speciesId} (${g.method} @ ${area.name}) leaked Surfing: ${e.levels}`);
}
}
}
}
}
});
test('Route 201 includes initial Sinnoh Starter options synced with store.pickStarter and UI rendering', () => {
const storage = makeMemoryStorage();
const store = createTrackerStore({ storage });
const game = store.getGame();
const route201 = game.sections[0].areas.find((a) => a.id === 'area-2');
assert.ok(route201);
const starterGroup = route201.groups.find((g) => g.method === 'Starter');
assert.ok(starterGroup);
assert.deepEqual(
starterGroup.entries.map((e) => e.speciesId),
['turtwig', 'chimchar', 'piplup'],
);
assert.ok(starterGroup.entries.every((e) => e.levels === 'Lv. 5'));
store.pickStarter('chimchar');
assert.equal(store.getState().chosenStarter, 'chimchar');
assert.equal(store.getState().caught.has('chimchar'), true);
// Remaining starters stay claimable in Sandgem Town and total obtainable stays 547
const prog = computeGameProgress(game, store.getState().caught, 'solo', { includeSpecialForms: false });
assert.equal(prog.totalObtainable, 547);
const html = renderRoutesView(game, store.getState(), prog);
assert.ok(html.includes('data-pick-starter="chimchar"'));
assert.ok(html.includes('Starter: Chimchar'));
assert.ok(html.includes('Starter Picked'));
assert.ok(html.includes('Other Picked'));
});
test('Incense Burner toggle persists per profile and dynamically updates overwritten Grass & Surf rates', () => {
const storage = makeMemoryStorage();
const store = createTrackerStore({ storage });
const game = store.getGame();
// Off by default: normal rates shown on Morning/Surf, Any Incense shows 0% (ON: 20%)
assert.equal(store.getState().incenseActive, false);
const prog = computeGameProgress(game, store.getState().caught, 'solo', { includeSpecialForms: false });
let htmlOff = renderRoutesView(game, store.getState(), prog);
assert.ok(htmlOff.includes('0% until ON'));
assert.ok(htmlOff.includes('data-toggle-incense'));
assert.ok(htmlOff.includes('section-incense-toggle'));
assert.ok(!htmlOff.includes('Replaced by Incense'));
// Toggle ON: Any Incense becomes active and Grass/Surf slot shifts + inline checkboxes update
store.setIncenseActive(true);
assert.equal(store.getState().incenseActive, true);
const hdrHtml = renderHeader(game, store.getState(), prog);
assert.ok(hdrHtml.includes('id="incense-burner-toggle"'));
assert.ok(hdrHtml.includes('Incense Burner (ON)'));
let htmlOn = renderRoutesView(game, store.getState(), prog);
assert.ok(htmlOn.includes('Spawning'));
assert.ok(htmlOn.includes('Slot Rates Adjusted'));
assert.ok(htmlOn.includes('Incense Burner ON'));
assert.ok(htmlOn.includes('was 30%'));
// Jump to Sec 6 (Canalave Surf) where Shellos 30% is completely overwritten to 0%
store.setActiveSectionId('pre-badge-6');
const sec6Html = renderRoutesView(game, store.getState(), prog);
assert.ok(sec6Html.includes('Replaced by Incense'));
assert.ok(sec6Html.includes('was 30%'));
// Persists across JSON backup round-trip
const backup = store.exportJson();
store.setIncenseActive(false);
assert.equal(store.getState().incenseActive, false);
store.importJson(backup);
assert.equal(store.getState().incenseActive, true);
});