forked from BigDonRob/Retro-Game-Guides-Legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguide_engine.js
More file actions
728 lines (644 loc) · 31.6 KB
/
guide_engine.js
File metadata and controls
728 lines (644 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
/* ═══════════════════════════════════════════════════════════════════════
guide_engine.js — Viewer Logic
Boots on ?game=raId. Exits immediately if ?edit is present.
URL params (all 1-based for user-facing URLs):
?game=2919 load guide for game ID 2919
?game=2919&tab=3 open at tab 3
?game=2919&tab=3&panel=2 open at tab 3, scroll to panel 2
═══════════════════════════════════════════════════════════════════════ */
(function () {
'use strict';
const params = new URLSearchParams(location.search);
// Yield to builder if in edit mode
if (params.get('edit') !== null) return;
const raId = parseInt(params.get('game') || '0', 10);
// ── URL PARAMS (1-based, converted to 0-based on use) ────────────────
const tabParam = params.get('tab');
const panelParam = params.get('panel');
const startTabNum = tabParam ? parseInt(tabParam, 10) : 1;
const startPanelNum = panelParam ? parseInt(panelParam, 10) : null;
// ── CONSTANTS ─────────────────────────────────────────────────────────
const OVERRIDE_THEME_KEY = 'bdr_user_theme';
const OVERRIDE_PALETTE_KEY = 'bdr_user_palette';
const FILTER_KEY = 'bdr_palette_filters'; // JSON {modes:[...], hues:[...]}
const A11Y_DYSLEXIA_KEY = 'bdr_a11y_dyslexia'; // '1'/'0', global preference
const ROYGBIV = ['red','orange','yellow','green','blue','violet','neutral'];
// ── PATH HELPER ──────────────────────────────────────────────────────
function getGamePath(id) {
const topEnd = Math.ceil(id / 5000) * 5000, topStart = topEnd - 4999;
const subEnd = Math.ceil(id / 200) * 200, subStart = subEnd - 199;
return `games/${topStart}-${topEnd}/${subStart}-${subEnd}/${id}`;
}
// ── DOM REFERENCES ───────────────────────────────────────────────────
const $icon = document.getElementById('guide-icon');
const $title = document.getElementById('guide-title');
const $meta = document.getElementById('guide-meta');
const $tabBar = document.getElementById('tab-bar');
const $content = document.getElementById('tab-content');
if (!$icon || !$title || !$meta || !$tabBar || !$content) {
console.error('guide_engine: Required DOM elements not found.');
return;
}
// ── MUTABLE STATE ─────────────────────────────────────────────────────
let allTabs = [];
let activeTabIndex = -1;
let storagePrefix = raId ? `${raId}_` : '';
let guideThemeKey = '';
let guidePaletteKey = '';
let allThemes = {};
let allPalettes = {};
const tabCache = {};
// ── STORAGE CONTEXT ──────────────────────────────────────────────────
const ctx = {
preview: false,
save(id, val) {
try { localStorage.setItem(storagePrefix + id, val ? '1' : '0'); } catch (_) {}
},
load(id) {
try { return localStorage.getItem(storagePrefix + id) === '1'; } catch (_) { return false; }
}
};
// ── BOOT ─────────────────────────────────────────────────────────────
async function boot() {
if (!raId) { panic('Missing ?game= parameter in URL.'); return; }
let config, themes, palettes, index;
try {
const GAME_PATH = getGamePath(raId) + '/';
[config, themes, palettes, index] = await Promise.all([
fetchJSON(`${GAME_PATH}${raId}_00.json`),
fetchJSON('./themes.json').catch(() => ({})),
fetchJSON('./palettes.json').catch(() => ({})),
fetchJSON('./games_index.json').catch(() => ({ systems: {}, series: {}, themes: [], palettes: [], games: [] })),
]);
} catch (e) {
panic(`Failed to load guide: ${e.message}`); return;
}
// theme/palette/series/altSystems are canonical in games_index.json only
const indexEntry = Array.isArray(index.games) ? index.games.find(e => e.raId === raId) : null;
allThemes = themes;
allPalettes = palettes;
guideThemeKey = (index.themes || [])[indexEntry?.theme] || '';
guidePaletteKey = (index.palettes || [])[indexEntry?.palette] || '';
if (config.storagePrefix) storagePrefix = config.storagePrefix;
applyThemePalette(guideThemeKey, guidePaletteKey, themes, palettes);
applyUserOverride(themes, palettes);
initA11y();
// Header — display fields from _00.json; series/altSystems decoded from index entry
$icon.textContent = config.icon || '🎮';
$title.textContent = config.primaryName || 'Guide';
document.title = `${config.primaryName || 'Guide'} — Game Guide`;
const altSystemNames = (indexEntry?.altSystems || [])
.map(id => (index.systems || {})[id])
.filter(Boolean);
const seriesName = indexEntry?.series != null
? (index.series || {})[indexEntry.series] || null
: null;
const metaParts = [
config.primarySystem,
...altSystemNames,
config.year ? String(config.year) : null,
seriesName,
].filter(Boolean);
$meta.textContent = metaParts.join(' · ');
// Subtitle
$content.innerHTML = '';
if (config.subtitle) {
const sub = document.createElement('div');
sub.id = 'guide-subtitle';
sub.textContent = config.subtitle;
$content.appendChild(sub);
}
// Storage badge + filter btn
document.getElementById('storage-badge').style.display = '';
document.getElementById('filter-btn').style.display = '';
// Tab bar — tabs now live in _00.json
allTabs = config.tabs || [];
if (!allTabs.length) { panic('No tabs defined for this guide.'); return; }
allTabs.forEach((tab, i) => {
const btn = document.createElement('button');
btn.className = 'tab-btn';
btn.textContent = tab.label;
btn.setAttribute('role', 'tab');
btn.setAttribute('aria-selected', 'false');
btn.addEventListener('click', () => activateTab(i));
$tabBar.appendChild(btn);
});
// Keyboard navigation
document.addEventListener('keydown', e => {
if (e.target.matches('input,textarea,select,[contenteditable]')) return;
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
e.preventDefault();
const next = Math.max(0, Math.min(allTabs.length - 1,
activeTabIndex + (e.key === 'ArrowRight' ? 1 : -1)));
if (next !== activeTabIndex) activateTab(next);
});
// Internal link handler (delegated, 1-based tab/panel → 0-based index)
document.addEventListener('click', e => {
const link = e.target.closest('.gr-internal-link');
if (!link) return;
const tabNum = parseInt(link.getAttribute('tab'), 10); // 1-based
const panelAttr = link.getAttribute('panel');
const panelNum = panelAttr === 'none' ? null : parseInt(panelAttr, 10); // 1-based or null
const tabIdx = tabNum - 1;
if (tabIdx < 0 || tabIdx >= allTabs.length) {
console.warn('Internal link: tab', tabNum, 'not found');
return;
}
const panelIdx = panelNum !== null ? panelNum - 1 : null;
// Update URL (keep 1-based for human-readable URLs)
const url = new URL(window.location);
url.searchParams.set('tab', tabNum);
if (panelNum !== null) url.searchParams.set('panel', panelNum);
else url.searchParams.delete('panel');
history.replaceState({}, '', url);
activateTab(tabIdx, panelIdx);
});
// Box toggle handler (delegated — works across tab switches)
document.addEventListener('click', e => {
const header = e.target.closest('.gr-box-header');
if (header) header.closest('.gr-box')?.classList.toggle('gr-collapsed');
});
initOverrideSheet(themes, palettes);
initFilterBtn();
initClearBtn();
// Activate initial tab from URL params (1-based → 0-based)
let startTabIdx = startTabNum - 1;
if (startTabIdx < 0 || startTabIdx >= allTabs.length) startTabIdx = 0;
const startPanelIdx = startPanelNum !== null ? startPanelNum - 1 : null;
setTimeout(async () => {
await activateTab(startTabIdx, startPanelIdx);
}, 50);
}
// ── TAB ACTIVATION ───────────────────────────────────────────────────
async function activateTab(index, panelIdx = null) {
// Same tab — just scroll to panel if specified
if (index === activeTabIndex) {
if (panelIdx !== null) scrollToPanel(panelIdx);
return;
}
activeTabIndex = index;
[...$tabBar.querySelectorAll('.tab-btn')].forEach((btn, i) => {
const active = i === index;
btn.classList.toggle('active', active);
btn.setAttribute('aria-selected', active ? 'true' : 'false');
if (active) btn.scrollIntoView({ inline: 'nearest', behavior: 'smooth' });
});
const num = allTabs[index]?.num;
if (!num) return;
if (tabCache[num]) {
mountTab(tabCache[num]);
if (panelIdx !== null) setTimeout(() => scrollToPanel(panelIdx), 50);
return;
}
mountLoading();
let tabDef;
try {
tabDef = await fetchJSON(`${getGamePath(raId)}/${raId}_${num}.json`);
} catch (e) {
mountError(`Could not load ${raId}_${num}.json — ${e.message}`); return;
}
const frag = buildTabContent(tabDef);
tabCache[num] = frag;
mountTab(frag);
if (panelIdx !== null && tabDef.panels?.[panelIdx]) {
setTimeout(() => scrollToPanel(panelIdx), 50);
}
}
// ── SCROLL / EXPAND / COLLAPSE ────────────────────────────────────────
function scrollToPanel(index) {
const panels = $content.querySelectorAll('.gr-panel-wrap');
const panelWrap = panels[index];
if (!panelWrap) return;
// Expand if collapsed
const card = panelWrap.querySelector('.gr-card');
if (card?.classList.contains('gr-collapsed')) expandPanel(index);
// Offset accounts for all sticky headers (works in both viewer and editor mode)
const editorHeader = document.getElementById('editor-header');
const guideHeader = document.getElementById('guide-header');
const tabBar = document.getElementById('tab-bar');
const offset = (editorHeader?.offsetHeight || 0) +
(guideHeader?.offsetHeight || 0) +
(tabBar?.offsetHeight || 0) + 8;
const top = panelWrap.getBoundingClientRect().top + window.scrollY - offset;
window.scrollTo({ top, behavior: 'smooth' });
}
function expandPanel(index) {
const panelWrap = $content.querySelectorAll('.gr-panel-wrap')[index];
if (!panelWrap) return;
const card = panelWrap.querySelector('.gr-card');
if (!card) return;
card.classList.remove('gr-collapsed');
ctx.save(colKeyFor(panelWrap, index), true);
}
function collapsePanel(index) {
const panelWrap = $content.querySelectorAll('.gr-panel-wrap')[index];
if (!panelWrap) return;
const card = panelWrap.querySelector('.gr-card');
if (!card) return;
card.classList.add('gr-collapsed');
ctx.save(colKeyFor(panelWrap, index), false);
}
// Storage key: prefer stable panel ID, fall back to positional index
function colKeyFor(panelWrap, index) {
return panelWrap.dataset.panelId
? '__c_' + panelWrap.dataset.panelId
: '__c_idx_' + index;
}
// ── TAB CONTENT BUILDERS ─────────────────────────────────────────────
function buildTabContent(tabDef) {
const frag = document.createDocumentFragment();
const panels = tabDef.panels || [];
if (!panels.length) {
const empty = document.createElement('div');
empty.className = 'empty-tab';
empty.textContent = 'This tab has no content yet.';
frag.appendChild(empty);
return frag;
}
panels.forEach(panelDef => {
try {
frag.appendChild(GuideRender.panel(panelDef, ctx));
} catch (e) {
const err = document.createElement('div');
err.className = 'error-state';
err.textContent = `Panel error (${panelDef.panelType || '?'}): ${e.message}`;
frag.appendChild(err);
}
});
return frag;
}
// ── MOUNT HELPERS ────────────────────────────────────────────────────
function clearContent() {
[...$content.children].forEach(c => { if (c.id !== 'guide-subtitle') c.remove(); });
}
function mountTab(frag) {
clearContent();
$content.appendChild(frag.cloneNode(true));
rebindChecklists();
rebindPanelToggles();
}
function mountLoading() {
clearContent();
const d = document.createElement('div');
d.className = 'loading-state';
d.innerHTML = 'Loading<span class="loading-dot">.</span><span class="loading-dot">.</span><span class="loading-dot">.</span>';
$content.appendChild(d);
}
function mountError(msg) {
clearContent();
const d = document.createElement('div');
d.className = 'error-state';
d.textContent = `⚠️ ${msg}`;
$content.appendChild(d);
}
// ── CHECKLIST REBINDING ──────────────────────────────────────────────
function rebindChecklists() {
$content.querySelectorAll('.gr-check-row').forEach(tr => {
const itemId = tr.dataset.itemId;
if (!itemId) return;
const checked = ctx.load(itemId);
tr.classList.toggle('gr-checked', checked);
const cb = tr.querySelector('.gr-checkbox');
if (cb) { cb.classList.toggle('gr-checked', checked); cb.textContent = checked ? '✓' : ''; }
tr.addEventListener('click', (e) => {
e.stopPropagation();
const now = tr.classList.toggle('gr-checked');
if (cb) { cb.classList.toggle('gr-checked', now); cb.textContent = now ? '✓' : ''; }
ctx.save(itemId, now);
updateProgress(tr);
});
});
}
// ── PANEL TOGGLE REBINDING ────────────────────────────────────────────
function rebindPanelToggles() {
$content.querySelectorAll('.gr-panel-wrap').forEach((panelWrap, index) => {
const card = panelWrap.querySelector('.gr-card');
const header = panelWrap.querySelector('.gr-card-header');
if (!card || !header) return;
// Restore collapse state from storage (panelId-based key, stable across reorders)
const colKey = colKeyFor(panelWrap, index);
const isExpanded = ctx.load(colKey);
if (!isExpanded) card.classList.add('gr-collapsed');
header.addEventListener('click', (e) => {
e.preventDefault();
if (card.classList.contains('gr-collapsed')) {
expandPanel(index);
} else {
collapsePanel(index);
}
});
});
}
function updateProgress(tr) {
const body = tr.closest('.gr-card-body');
if (!body) return;
const total = body.querySelectorAll('.gr-check-row').length;
const done = body.querySelectorAll('.gr-check-row.gr-checked').length;
const fill = body.querySelector('.gr-progress-fill');
const count = body.querySelector('.gr-progress-count');
if (fill) fill.style.width = Math.round(done / total * 100) + '%';
if (count) count.textContent = done;
}
// ── THEME / PALETTE ───────────────────────────────────────────────────
function applyThemePalette(themeKey, palKey, themes, palettes) {
const theme = themes[themeKey] || {};
const pal = palettes[palKey] || {};
const root = document.documentElement;
Object.entries(theme.vars || {}).forEach(([k, v]) => root.style.setProperty(k, v));
Object.entries(pal.vars || {}).forEach(([k, v]) => root.style.setProperty(k, v));
if (theme.fonts) {
root.style.setProperty('--font-body', theme.fonts.body || '');
root.style.setProperty('--font-display', theme.fonts.display || '');
root.style.setProperty('--font-mono', theme.fonts.mono || '');
if (theme.fonts.googleFonts) {
let link = document.getElementById('bdr-fonts');
if (!link) {
link = document.createElement('link');
link.id = 'bdr-fonts'; link.rel = 'stylesheet';
document.head.prepend(link);
}
link.href = theme.fonts.googleFonts;
}
}
}
function applyUserOverride(themes, palettes) {
const ot = localStorage.getItem(OVERRIDE_THEME_KEY) || '';
const op = localStorage.getItem(OVERRIDE_PALETTE_KEY) || '';
if (ot || op) {
applyThemePalette(ot || guideThemeKey, op || guidePaletteKey, themes, palettes);
}
updateOverrideIndicator();
}
function updateOverrideIndicator() {
const ot = localStorage.getItem(OVERRIDE_THEME_KEY) || '';
const op = localStorage.getItem(OVERRIDE_PALETTE_KEY) || '';
const btn = document.getElementById('display-btn');
if (btn) btn.classList.toggle('overriding', !!(ot || op));
}
// ── FILTER BUTTON ─────────────────────────────────────────────────────
function initFilterBtn() {
const btn = document.getElementById('filter-btn');
if (!btn) return;
const REMAINING_KEY = storagePrefix + 'show_remaining';
const iconEl = btn.querySelector('.btn-icon');
const labelEl = btn.querySelector('.btn-label');
function applyFilter(active) {
document.body.classList.toggle('show-remaining', active);
btn.classList.toggle('filter-active', active);
if (iconEl) iconEl.textContent = active ? '☑' : '☐';
if (labelEl) labelEl.textContent = active ? ' Show all' : ' Show remaining';
try { localStorage.setItem(REMAINING_KEY, active ? '1' : '0'); } catch (_) {}
}
const stored = (() => {
try { return localStorage.getItem(REMAINING_KEY) === '1'; } catch (_) { return false; }
})();
applyFilter(stored);
btn.addEventListener('click', () => applyFilter(!document.body.classList.contains('show-remaining')));
}
// ── CLEAR PROGRESS ────────────────────────────────────────────────────
function initClearBtn() {
const clearBtn = document.getElementById('clear-btn');
const clearCancel = document.getElementById('clear-cancel');
const clearConfirm = document.getElementById('clear-confirm');
const clearBackdrop = document.getElementById('clear-backdrop');
clearBtn?.addEventListener('click', showClearConfirm);
clearCancel?.addEventListener('click', hideClearConfirm);
clearConfirm?.addEventListener('click', clearProgress);
clearBackdrop?.addEventListener('click', e => {
if (e.target === e.currentTarget) hideClearConfirm();
});
}
function showClearConfirm() {
document.getElementById('clear-backdrop')?.classList.add('open');
}
function hideClearConfirm() {
document.getElementById('clear-backdrop')?.classList.remove('open');
}
function clearProgress() {
const keysToRemove = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key?.startsWith(storagePrefix)) keysToRemove.push(key);
}
keysToRemove.forEach(key => localStorage.removeItem(key));
// Rebuild current tab to show cleared state
if (activeTabIndex >= 0 && allTabs.length > 0) {
const currentNum = allTabs[activeTabIndex].num;
delete tabCache[currentNum];
const prev = activeTabIndex;
activeTabIndex = -1;
activateTab(prev);
}
// Brief feedback on storage badge
const badge = document.getElementById('storage-badge');
if (badge) {
badge.textContent = '● cleared';
badge.style.display = 'inline-block';
setTimeout(() => { badge.style.display = ''; }, 2000);
}
hideClearConfirm();
}
// ── A11Y — runs on boot before first paint ────────────────────────────
function initA11y() {
if (localStorage.getItem(A11Y_DYSLEXIA_KEY) === '1') {
document.body.classList.add('a11y-dyslexia');
injectLexendFont();
}
}
function injectLexendFont() {
if (!document.getElementById('bdr-a11y-fonts')) {
const link = document.createElement('link');
link.id = 'bdr-a11y-fonts';
link.rel = 'stylesheet';
link.href = 'https://fonts.googleapis.com/css2?family=Lexend:wght@400;600;700&display=swap';
document.head.appendChild(link);
}
}
// ── OVERRIDE SHEET ────────────────────────────────────────────────────
function initOverrideSheet(themes, palettes) {
const backdrop = document.getElementById('do-backdrop');
const sheet = document.getElementById('do-sheet');
const closeBtn = document.getElementById('do-sheet-close');
const resetBtn = document.getElementById('do-reset-btn');
const openBtn = document.getElementById('display-btn');
const themeGrid = document.getElementById('do-theme-grid');
const palGrid = document.getElementById('do-palette-grid');
const filterRow = document.getElementById('do-palette-filters');
const currentEl = document.getElementById('do-current');
const defaultEl = document.getElementById('do-guide-default');
const dyslexiaBtn = document.getElementById('do-dyslexia-toggle');
if (!backdrop || !sheet) return;
function esc2(s) { return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
const gThemeLabel = themes[guideThemeKey]?.label || guideThemeKey;
const gPalLabel = palettes[guidePaletteKey]?.label || guidePaletteKey;
defaultEl.innerHTML = `Guide default: <strong>${esc2(gThemeLabel)}</strong> + <strong>${esc2(gPalLabel)}</strong>`;
function getActiveTheme() { return localStorage.getItem(OVERRIDE_THEME_KEY) || guideThemeKey; }
function getActivePalette() { return localStorage.getItem(OVERRIDE_PALETTE_KEY) || guidePaletteKey; }
function refreshCurrent() {
const ot = localStorage.getItem(OVERRIDE_THEME_KEY) || '';
const op = localStorage.getItem(OVERRIDE_PALETTE_KEY) || '';
if (!ot && !op) { currentEl.textContent = 'guide default'; return; }
const tLabel = themes[ot || guideThemeKey]?.label || ot || guideThemeKey;
const pLabel = palettes[op || guidePaletteKey]?.label || op || guidePaletteKey;
currentEl.textContent = `${tLabel} + ${pLabel}`;
}
function refreshActiveCards() {
const at = getActiveTheme(), ap = getActivePalette();
themeGrid.querySelectorAll('.do-card').forEach(c => c.classList.toggle('active', c.dataset.key === at));
palGrid.querySelectorAll('.do-card').forEach(c => c.classList.toggle('active', c.dataset.key === ap));
}
// ── PALETTE FILTER CHIPS ─────────────────────────────────────────
const availableHues = ROYGBIV.filter(hue =>
Object.values(palettes).some(p => p.hue === hue && !p.hc)
);
const hasHC = Object.values(palettes).some(p => p.hc);
// Load or derive default filter state
let filterState = null;
try { const r = localStorage.getItem(FILTER_KEY); if (r) filterState = JSON.parse(r); } catch (_) {}
if (!filterState) {
const firstDarkHue = ROYGBIV.find(hue =>
Object.values(palettes).some(p => p.hue === hue && p.dark && !p.hc)
);
filterState = { modes: ['dark'], hues: firstDarkHue ? [firstDarkHue] : [] };
}
let activeModes = new Set(filterState.modes || []);
let activeHues = new Set(filterState.hues || []);
function saveFilters() {
try { localStorage.setItem(FILTER_KEY, JSON.stringify({ modes: [...activeModes], hues: [...activeHues] })); } catch (_) {}
}
function paletteVisible(pal) {
if (!pal) return true;
let modeMatch = false;
if (activeModes.has('dark') && pal.dark && !pal.hc) modeMatch = true;
if (activeModes.has('light') && !pal.dark && !pal.hc) modeMatch = true;
if (activeModes.has('hc') && pal.hc) modeMatch = true;
if (activeModes.size === 0) modeMatch = true;
if (!modeMatch) return false;
if (activeHues.size === 0) return true;
return activeHues.has(pal.hue);
}
function refreshPaletteVisibility() {
palGrid.querySelectorAll('.do-card').forEach(c => {
c.style.display = paletteVisible(palettes[c.dataset.key]) ? '' : 'none';
});
}
if (filterRow) {
// Mode chips: Dark | Light | (High Contrast if present)
const modeChipDefs = [
{ key: 'dark', label: 'Dark' },
{ key: 'light', label: 'Light' },
...(hasHC ? [{ key: 'hc', label: 'High Contrast' }] : []),
];
modeChipDefs.forEach(({ key, label }) => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'do-chip' + (activeModes.has(key) ? ' active' : '');
chip.textContent = label;
chip.addEventListener('click', () => {
activeModes.has(key) ? activeModes.delete(key) : activeModes.add(key);
chip.classList.toggle('active', activeModes.has(key));
saveFilters(); refreshPaletteVisibility();
});
filterRow.appendChild(chip);
});
// Separator before hue chips
if (availableHues.length) {
const sep = document.createElement('span');
sep.className = 'do-chip-sep'; sep.textContent = '|';
filterRow.appendChild(sep);
}
// Hue chips in ROYGBIV order, only hues that exist in this palette set
availableHues.forEach(hue => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'do-chip' + (activeHues.has(hue) ? ' active' : '');
chip.textContent = hue.charAt(0).toUpperCase() + hue.slice(1);
chip.addEventListener('click', () => {
activeHues.has(hue) ? activeHues.delete(hue) : activeHues.add(hue);
chip.classList.toggle('active', activeHues.has(hue));
saveFilters(); refreshPaletteVisibility();
});
filterRow.appendChild(chip);
});
}
// ── DYSLEXIA TOGGLE ──────────────────────────────────────────────
let dyslexiaOn = localStorage.getItem(A11Y_DYSLEXIA_KEY) === '1';
function applyDyslexia(on) {
dyslexiaOn = on;
document.body.classList.toggle('a11y-dyslexia', on);
if (dyslexiaBtn) {
dyslexiaBtn.setAttribute('aria-checked', on ? 'true' : 'false');
dyslexiaBtn.textContent = on ? 'On' : 'Off';
}
if (on) injectLexendFont();
try { localStorage.setItem(A11Y_DYSLEXIA_KEY, on ? '1' : '0'); } catch (_) {}
}
if (dyslexiaBtn) {
dyslexiaBtn.setAttribute('aria-checked', dyslexiaOn ? 'true' : 'false');
dyslexiaBtn.textContent = dyslexiaOn ? 'On' : 'Off';
dyslexiaBtn.addEventListener('click', () => applyDyslexia(!dyslexiaOn));
}
// ── THEME CARDS ──────────────────────────────────────────────────
Object.entries(themes).forEach(([key, th]) => {
const card = document.createElement('div');
card.className = 'do-card'; card.dataset.key = key;
card.innerHTML = `<div class="do-card-name">${esc2(th.label)}</div><div class="do-card-desc">${esc2(th.description || '')}</div>`;
card.addEventListener('click', () => {
localStorage.setItem(OVERRIDE_THEME_KEY, key);
applyThemePalette(key, getActivePalette(), themes, palettes);
updateOverrideIndicator(); refreshCurrent(); refreshActiveCards();
});
themeGrid.appendChild(card);
});
// ── PALETTE CARDS ─────────────────────────────────────────────────
Object.entries(palettes).forEach(([key, pal]) => {
const card = document.createElement('div');
card.className = 'do-card'; card.dataset.key = key;
const dots = [
{ color: pal.vars['--bg'] || '#888', border: true },
{ color: pal.vars['--emphasis'] || '#888', border: false },
{ color: pal.vars['--positive'] || '#888', border: false },
{ color: pal.vars['--text'] || '#888', border: true },
].map(d => `<div class="do-dot" style="background:${d.color};${d.border ? 'border:1px solid rgba(128,128,128,0.3)' : ''}"></div>`).join('');
card.innerHTML = `<div class="do-card-dots">${dots}</div><div class="do-card-name">${esc2(pal.label)}</div>`;
card.addEventListener('click', () => {
localStorage.setItem(OVERRIDE_PALETTE_KEY, key);
applyThemePalette(getActiveTheme(), key, themes, palettes);
updateOverrideIndicator(); refreshCurrent(); refreshActiveCards();
});
palGrid.appendChild(card);
});
// Apply initial filter visibility
refreshPaletteVisibility();
resetBtn.addEventListener('click', () => {
localStorage.removeItem(OVERRIDE_THEME_KEY);
localStorage.removeItem(OVERRIDE_PALETTE_KEY);
applyThemePalette(guideThemeKey, guidePaletteKey, themes, palettes);
updateOverrideIndicator(); refreshCurrent(); refreshActiveCards();
});
const openSheet = () => { refreshCurrent(); refreshActiveCards(); backdrop.classList.add('open'); sheet.classList.add('open'); };
const closeSheet = () => { backdrop.classList.remove('open'); sheet.classList.remove('open'); };
openBtn?.addEventListener('click', openSheet);
closeBtn?.addEventListener('click', closeSheet);
backdrop.addEventListener('click', closeSheet);
refreshCurrent(); refreshActiveCards();
}
// ── UTILITIES ─────────────────────────────────────────────────────────
async function fetchJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} — ${url}`);
return res.json();
}
function esc(s) {
return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
}
function panic(msg) {
$content.innerHTML = `<div class="error-state">⚠️ Engine error: ${esc(msg)}</div>`;
}
// ── INIT ─────────────────────────────────────────────────────────────
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => boot().catch(e => panic(e.message)));
} else {
boot().catch(e => panic(e.message));
}
})();