-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary.js
More file actions
432 lines (360 loc) · 13.6 KB
/
Copy pathlibrary.js
File metadata and controls
432 lines (360 loc) · 13.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
/**
* The library and pre-game setup.
*
* The library is the home screen: every saved game, with import, export, and
* the storage-health readout. Setup is the screen between choosing a game and
* playing it — team names, a warning summary, and the photo wall.
*/
import {
$, el, clear, showScreen, toast, confirmDialog,
downloadFile, pickFile, relativeTime, formatMoney
} from './ui.js';
import * as sound from './sound.js';
import * as pack from './pack.js';
import * as storage from './storage.js';
let onPlay = null; // (gameId) => void
let onEdit = null; // (gameId) => void
/** The game chosen on the setup screen. */
let staged = null; // { id, pack, media }
/* ============================================================
LIBRARY SCREEN
============================================================ */
export async function showLibrary() {
showScreen('library-screen');
sound.playTheme();
await renderLibrary();
}
async function renderLibrary() {
const host = clear($('library-list'));
let games = [];
try {
games = await storage.listGames();
} catch (e) {
host.appendChild(el('p', 'library-empty', 'Could not open local storage. Private browsing can block it.'));
return;
}
$('library-count').textContent = games.length
? `${games.length} game${games.length === 1 ? '' : 's'}`
: '';
if (games.length === 0) {
const empty = el('div', 'library-empty');
empty.appendChild(el('p', null, 'No games yet.'));
empty.appendChild(el('p', 'muted', 'Build one from scratch, import a pack, or try the demo.'));
host.appendChild(empty);
}
for (const game of games) {
host.appendChild(renderGameCard(game));
}
renderStorageHealth();
}
function renderGameCard(game) {
const card = el('div', 'game-card');
const head = el('div', 'game-card-head');
head.appendChild(el('h3', 'game-card-title', game.title));
const meta = [];
meta.push(`${game.roundCount} round${game.roundCount === 1 ? '' : 's'}`);
if (game.photoCount) meta.push(`${game.photoCount} photo${game.photoCount === 1 ? '' : 's'}`);
meta.push(`edited ${relativeTime(game.updatedAt)}`);
head.appendChild(el('div', 'game-card-meta', meta.join(' · ')));
// The browser is the only copy until this game has been exported, so say so.
if (!game.exportedAt || game.exportedAt < game.updatedAt) {
const warn = el('div', 'game-card-warn');
warn.textContent = game.exportedAt
? 'Changed since last export — export to keep a backup'
: 'Never exported — this game only exists in this browser';
head.appendChild(warn);
}
card.appendChild(head);
const actions = el('div', 'game-card-actions');
const play = el('button', 'btn btn-gold', 'Play');
const edit = el('button', 'btn btn-ghost', 'Edit');
const exportBtn = el('button', 'btn btn-ghost', 'Export');
const del = el('button', 'btn btn-ghost btn-danger', 'Delete');
play.addEventListener('click', () => onPlay(game.id));
edit.addEventListener('click', () => onEdit(game.id));
exportBtn.addEventListener('click', () => exportGame(game.id, exportBtn));
del.addEventListener('click', () => deleteGame(game));
actions.append(play, edit, exportBtn, del);
card.appendChild(actions);
return card;
}
async function renderStorageHealth() {
const node = $('storage-health');
if (!node) return;
const [estimate, persisted] = await Promise.all([storage.storageEstimate(), storage.isPersisted()]);
clear(node);
if (estimate.supported) {
node.appendChild(el('span', null, `${storage.formatBytes(estimate.usage)} used`));
}
const badge = el('span', 'storage-badge');
if (persisted) {
badge.classList.add('ok');
badge.textContent = 'storage protected';
badge.title = 'This browser has been asked not to evict your games.';
} else {
badge.classList.add('warn');
badge.textContent = 'storage not protected';
badge.title = 'Browsers can clear unprotected site data — Safari does so after seven days without a visit. Export your games to be safe.';
}
node.appendChild(badge);
}
/* ============================================================
LIBRARY ACTIONS
============================================================ */
async function exportGame(id, button) {
const label = button ? button.textContent : null;
try {
if (button) { button.disabled = true; button.textContent = 'Exporting…'; }
const row = await storage.getGame(id);
if (!row) throw new Error('That game is gone.');
const media = await storage.getAllMedia(id);
const bytes = await pack.toZip(row.pack, media);
downloadFile(bytes, pack.packFilename(row.pack), 'application/zip');
await storage.markExported(id);
toast(`Exported ${pack.packFilename(row.pack)} (${storage.formatBytes(bytes.length)})`, 'ok');
await renderLibrary();
} catch (e) {
toast(`Export failed: ${e.message}`, 'error');
} finally {
if (button) { button.disabled = false; button.textContent = label; }
}
}
async function deleteGame(game) {
const neverExported = !game.exportedAt;
const ok = await confirmDialog(
neverExported
? `Delete "${game.title}"? It has never been exported, so this cannot be undone.`
: `Delete "${game.title}"?`,
{ confirmText: 'Delete', danger: true }
);
if (!ok) return;
try {
await storage.deleteGame(game.id);
toast(`Deleted "${game.title}"`, 'info');
await renderLibrary();
} catch (e) {
toast(`Could not delete: ${e.message}`, 'error');
}
}
async function importPackFile() {
const file = await pickFile('.jeopardy,.zip,application/zip');
if (!file) return;
try {
const bytes = new Uint8Array(await file.arrayBuffer());
const { pack: imported, media, warnings } = await pack.fromZip(bytes);
const id = storage.newGameId();
await storage.saveGame(id, imported, { exported: true }); // it came from a file, so a copy exists
await storage.putAllMedia(id, media);
await afterFirstSave();
for (const w of warnings) toast(w, 'warn', 7000);
toast(`Imported "${imported.title}"`, 'ok');
await renderLibrary();
} catch (e) {
toast(`Could not import that file: ${e.message}`, 'error', 8000);
}
}
async function importCSVFile() {
const file = await pickFile('.csv,text/csv');
if (!file) return;
try {
const text = await file.text();
const title = file.name.replace(/\.csv$/i, '') || 'Imported Game';
const { pack: imported, warnings } = pack.fromCSV(text, title);
const id = storage.newGameId();
await storage.saveGame(id, imported);
await afterFirstSave();
for (const w of warnings) toast(w, 'warn', 7000);
toast(`Imported ${imported.rounds.length} rounds from ${file.name}. Add photos in the editor.`, 'ok', 6000);
await renderLibrary();
onEdit(id);
} catch (e) {
toast(`Could not read that CSV: ${e.message}`, 'error', 8000);
}
}
async function loadDemoGame() {
try {
const text = await fetch('sample.csv').then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.text();
});
const { pack: demo } = pack.fromCSV(text, 'Demo Game');
const id = storage.newGameId();
await storage.saveGame(id, demo);
await afterFirstSave();
toast('Demo game added to your library.', 'ok');
await renderLibrary();
} catch (e) {
toast(`Could not load the demo: ${e.message}`, 'error');
}
}
async function createNewGame() {
const id = storage.newGameId();
await storage.saveGame(id, pack.createEmptyPack('Untitled Game'));
await afterFirstSave();
onEdit(id);
}
/**
* Ask for persistent storage the first time real work exists — not on page
* load. Firefox prompts for this, and a prompt shown to someone who has not
* created anything yet earns a "no" that cannot be asked again.
*/
let persistenceAsked = false;
async function afterFirstSave() {
if (persistenceAsked) return;
persistenceAsked = true;
const { supported, persisted } = await storage.requestPersistence();
if (supported && !persisted) {
toast('This browser may clear saved games. Export anything you care about.', 'warn', 7000);
}
}
/* ============================================================
SETUP SCREEN
============================================================ */
export async function showSetup(gameId) {
const row = await storage.getGame(gameId);
if (!row) { toast('That game could not be found.', 'error'); return showLibrary(); }
const media = await storage.getAllMedia(gameId);
staged = { id: gameId, pack: row.pack, media };
showScreen('setup-screen');
sound.playTheme();
$('setup-title').textContent = row.pack.title;
renderSetupIssues(row.pack);
renderTeamInputs(row.pack);
requestAnimationFrame(() => restartPhotoWall(row.pack, media));
}
function renderSetupIssues(game) {
const host = clear($('setup-issues'));
const issues = pack.validate(game);
const blocking = issues.filter(i => i.level === 'error');
const warnings = issues.filter(i => i.level === 'warning');
$('start-btn').disabled = blocking.length > 0;
for (const issue of blocking) {
host.appendChild(el('div', 'issue error', issue.message));
}
if (warnings.length) {
const summary = el('details', 'issue warn');
const label = el('summary', null,
`${warnings.length} thing${warnings.length === 1 ? '' : 's'} to know — the game still plays`);
summary.appendChild(label);
const list = el('ul');
for (const w of warnings) list.appendChild(el('li', null, w.message));
summary.appendChild(list);
host.appendChild(summary);
}
}
function renderTeamInputs(game) {
const host = clear($('team-inputs'));
const count = game.settings.teamCount;
for (let i = 0; i < count; i++) {
const input = el('input');
input.type = 'text';
input.id = `team-name-${i}`;
input.maxLength = 30;
input.placeholder = game.settings.teamNames[i] || `Team ${i + 1}`;
input.value = game.settings.teamNames[i] || '';
input.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
e.preventDefault();
const next = $(`team-name-${i + 1}`);
if (next) next.focus(); else $('start-btn').click();
});
host.appendChild(input);
}
$('team-count-note').textContent = count === 1
? 'Solo play — one score to beat.'
: `${count} teams. Change this in the editor.`;
}
function readTeamNames(game) {
const names = [];
for (let i = 0; i < game.settings.teamCount; i++) {
const input = $(`team-name-${i}`);
names.push((input && input.value.trim()) || game.settings.teamNames[i] || `Team ${i + 1}`);
}
return names;
}
export function stagedGame() {
if (!staged) return null;
return { ...staged, teamNames: readTeamNames(staged.pack) };
}
/* ============================================================
PHOTO WALL
============================================================ */
const wallURLs = [];
function shuffled(arr) {
const a = arr.slice();
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function releaseWall() {
for (const url of wallURLs.splice(0)) URL.revokeObjectURL(url);
}
function buildPhotoWall(game, media) {
const wall = $('photo-wall');
if (!wall) return false;
releaseWall();
clear(wall);
const sources = (game.attract || [])
.map(id => media.get(id))
.filter(Boolean)
.map(blob => {
const url = URL.createObjectURL(blob);
wallURLs.push(url);
return url;
});
if (sources.length === 0) return false;
const w = wall.clientWidth || window.innerWidth;
const h = wall.clientHeight || window.innerHeight;
// ~190px tiles on desktop, smaller on phones so cells stay legible.
const target = w < 600 ? 130 : 190;
const cols = Math.max(3, Math.round(w / target));
const rows = Math.max(3, Math.round(h / target));
wall.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
wall.style.gridTemplateRows = `repeat(${rows}, 1fr)`;
const pool = shuffled(sources);
const fillSeconds = 8;
for (let i = 0; i < cols * rows; i++) {
const tile = el('div', 'photo-wall-tile');
tile.style.backgroundImage = `url("${pool[i % pool.length]}")`;
// Random delays so the mosaic emerges rather than sweeping in rows.
tile.style.setProperty('--tile-delay', (Math.random() * fillSeconds).toFixed(2) + 's');
wall.appendChild(tile);
}
return true;
}
function restartPhotoWall(game, media) {
const wall = $('photo-wall');
const screen = $('setup-screen');
if (!wall) return;
wall.classList.remove('active');
screen.classList.remove('wall-active');
if (!buildPhotoWall(game, media)) return;
// Force a reflow so the opacity:0 start state registers before .active goes
// back on — otherwise the transition does not replay.
void wall.offsetWidth;
requestAnimationFrame(() => {
wall.classList.add('active');
screen.classList.add('wall-active');
});
}
/* ============================================================
WIRING
============================================================ */
export function initLibrary(handlers) {
onPlay = handlers.onPlay;
onEdit = handlers.onEdit;
$('new-game-btn').addEventListener('click', createNewGame);
$('import-pack-btn').addEventListener('click', importPackFile);
$('import-csv-btn').addEventListener('click', importCSVFile);
$('demo-game-btn').addEventListener('click', loadDemoGame);
$('setup-back-btn').addEventListener('click', () => { releaseWall(); showLibrary(); });
$('setup-edit-btn').addEventListener('click', () => { if (staged) onEdit(staged.id); });
$('start-btn').addEventListener('click', () => {
if (!staged) return;
releaseWall();
handlers.onStart(stagedGame());
});
}
export { renderLibrary };