feat: Bestenliste für jedes Türchen-Minispiel
- Zeitmessung startet beim Öffnen des Türchens, endet bei der ersten Server-Antwort mit solved:true (z. B. Codewort abgeschickt) - Pflichtfeld Name am Spielende, Eintrag via POST /api/door/:token/leaderboard - Extra Link /leaderboard zeigt alle Bestenlisten (JSON: /api/leaderboard) - Speicher: data/leaderboard.json, per Compose-Volume persistent Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
1 parent
2d6f3fd0c7
commit
37e70eddb6
8 files changed
+657
-1
No files matched your search
@@ -7,3 +7,7 @@ qr-codes/
|
||||
*.log
|
||||
*.tmp
|
||||
temp.txt
|
||||
|
||||
# Bestenlisten-Daten (Spielereinträge)
|
||||
data/*
|
||||
!data/.gitkeep
|
||||
Whitespace-only changes.
@@ -13,6 +13,7 @@ services:
|
||||
DOORS_OVERRIDE_DIR: /app/content-override
|
||||
volumes:
|
||||
- /mnt/Jannik-Cloud-Volume-01/adventskalender:/app/content-override:ro
|
||||
- /mnt/Jannik-Cloud-Volume-01/adventskalender-leaderboard:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"]
|
||||
interval: 30s
|
||||
|
||||
@@ -11,6 +11,8 @@ services:
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"]
|
||||
interval: 30s
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* Bestenlisten-Speicher für jedes Türchen/Minispiel.
|
||||
*
|
||||
* - Start: Öffnen des Türchens (misst der Client, siehe views/leaderboard.ts)
|
||||
* - Ende: Lösung abgeschickt (erste Server-Antwort mit solved: true)
|
||||
* - Pro Eintrag wird ein Name gespeichert (Pflichtfeld am Spielende).
|
||||
*
|
||||
* Ablage: data/leaderboard.json (per Env LEADERBOARD_FILE überschreibbar).
|
||||
*/
|
||||
|
||||
export interface LeaderboardEntry {
|
||||
/** Anzeigename der Spielerin / des Spielers (Pflichtfeld, 1–24 Zeichen) */
|
||||
name: string;
|
||||
/** Gemessene Spielzeit in Millisekunden (Start = Türchen geöffnet) */
|
||||
durationMs: number;
|
||||
/** Zeitpunkt des Eintrags (ISO) */
|
||||
dateIso: string;
|
||||
}
|
||||
|
||||
interface DoorLeaderboard {
|
||||
entries: LeaderboardEntry[];
|
||||
}
|
||||
|
||||
interface LeaderboardData {
|
||||
doors: Record<string, DoorLeaderboard>;
|
||||
}
|
||||
|
||||
export interface AddEntryResult {
|
||||
rank: number;
|
||||
total: number;
|
||||
top10: LeaderboardEntry[];
|
||||
}
|
||||
|
||||
const MIN_DURATION_MS = 500;
|
||||
const MAX_DURATION_MS = 24 * 60 * 60 * 1000; // 24 h
|
||||
const MAX_NAME_LENGTH = 24;
|
||||
const MAX_ENTRIES_PER_DOOR = 200;
|
||||
|
||||
function getStoragePath(): string {
|
||||
const configured = process.env.LEADERBOARD_FILE?.trim();
|
||||
if (configured) {
|
||||
return path.resolve(configured);
|
||||
}
|
||||
return path.resolve(process.cwd(), 'data', 'leaderboard.json');
|
||||
}
|
||||
|
||||
function isDoorIdValid(doorId: string): boolean {
|
||||
return /^\d{2}$/.test(doorId);
|
||||
}
|
||||
|
||||
function createEmptyData(): LeaderboardData {
|
||||
return { doors: {} };
|
||||
}
|
||||
|
||||
function loadLeaderboard(): LeaderboardData {
|
||||
const filePath = getStoragePath();
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, 'utf-8');
|
||||
const parsed = JSON.parse(raw) as Partial<LeaderboardData>;
|
||||
if (!parsed.doors || typeof parsed.doors !== 'object') {
|
||||
return createEmptyData();
|
||||
}
|
||||
return parsed as LeaderboardData;
|
||||
} catch {
|
||||
return createEmptyData();
|
||||
}
|
||||
}
|
||||
|
||||
function saveLeaderboard(data: LeaderboardData): void {
|
||||
const filePath = getStoragePath();
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
const tempPath = `${filePath}.tmp`;
|
||||
fs.writeFileSync(tempPath, JSON.stringify(data, null, 2), 'utf-8');
|
||||
fs.renameSync(tempPath, filePath);
|
||||
}
|
||||
|
||||
function sortedEntries(door: DoorLeaderboard): LeaderboardEntry[] {
|
||||
return [...door.entries].sort((a, b) => a.durationMs - b.durationMs);
|
||||
}
|
||||
|
||||
/** Top-Liste eines Türchens (aufsteigend nach Zeit). */
|
||||
export function getLeaderboardForDoor(doorId: string): LeaderboardEntry[] {
|
||||
const data = loadLeaderboard();
|
||||
const door = data.doors[doorId];
|
||||
if (!door || !Array.isArray(door.entries)) {
|
||||
return [];
|
||||
}
|
||||
return sortedEntries(door);
|
||||
}
|
||||
|
||||
/** Alle Bestenlisten (nur Türchen mit Einträgen), nach Tür-ID sortiert. */
|
||||
export function getAllLeaderboards(): { doorId: string; entries: LeaderboardEntry[] }[] {
|
||||
const data = loadLeaderboard();
|
||||
return Object.keys(data.doors)
|
||||
.filter((doorId) => isDoorIdValid(doorId))
|
||||
.filter((doorId) => (data.doors[doorId]?.entries ?? []).length > 0)
|
||||
.sort()
|
||||
.map((doorId) => ({
|
||||
doorId,
|
||||
entries: sortedEntries(data.doors[doorId]),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Neuen Eintrag speichern und Platzierung zurückgeben.
|
||||
* Wirft einen Error mit sprechender Meldung, wenn die Eingabe ungültig ist.
|
||||
*/
|
||||
export function addLeaderboardEntry(
|
||||
doorId: string,
|
||||
rawName: string,
|
||||
rawDurationMs: number,
|
||||
): AddEntryResult {
|
||||
if (!isDoorIdValid(doorId)) {
|
||||
throw new Error('Ungültige Türchen-ID.');
|
||||
}
|
||||
|
||||
const name = rawName.trim().replace(/\s+/g, ' ');
|
||||
if (name.length < 1 || name.length > MAX_NAME_LENGTH) {
|
||||
throw new Error(`Bitte einen Namen mit 1–${MAX_NAME_LENGTH} Zeichen eingeben.`);
|
||||
}
|
||||
|
||||
const durationMs = Math.round(rawDurationMs);
|
||||
if (!Number.isFinite(durationMs) || durationMs < MIN_DURATION_MS || durationMs > MAX_DURATION_MS) {
|
||||
throw new Error('Ungültige Spielzeit.');
|
||||
}
|
||||
|
||||
const data = loadLeaderboard();
|
||||
if (!data.doors[doorId]) {
|
||||
data.doors[doorId] = { entries: [] };
|
||||
}
|
||||
|
||||
const entry: LeaderboardEntry = {
|
||||
name,
|
||||
durationMs,
|
||||
dateIso: new Date().toISOString(),
|
||||
};
|
||||
data.doors[doorId].entries.push(entry);
|
||||
|
||||
if (data.doors[doorId].entries.length > MAX_ENTRIES_PER_DOOR) {
|
||||
// Bei sehr langen Listen nur die schnellsten behalten, damit die Datei klein bleibt.
|
||||
data.doors[doorId].entries = sortedEntries(data.doors[doorId]).slice(0, MAX_ENTRIES_PER_DOOR);
|
||||
}
|
||||
|
||||
saveLeaderboard(data);
|
||||
|
||||
const all = sortedEntries(data.doors[doorId]);
|
||||
const rank = all.findIndex((item) => item === entry) + 1;
|
||||
return {
|
||||
rank,
|
||||
total: all.length,
|
||||
top10: all.slice(0, 10),
|
||||
};
|
||||
}
|
||||
@@ -8,8 +8,19 @@ import {
|
||||
verifyBypassToken,
|
||||
} from './doors';
|
||||
import { executeDoorAction } from './doors/actions';
|
||||
import { loadDoorMeta } from './doors';
|
||||
import { registerAiJailbreakDoor } from './doors/index';
|
||||
import { renderWichtelWidget } from './doors/wichtel';
|
||||
import {
|
||||
addLeaderboardEntry,
|
||||
getAllLeaderboards,
|
||||
getLeaderboardForDoor,
|
||||
} from './doors/leaderboard';
|
||||
import {
|
||||
renderLeaderboardPage,
|
||||
renderLeaderboardRuntimeScript,
|
||||
type LeaderboardPageDoor,
|
||||
} from './views/leaderboard';
|
||||
import { IpRateLimiter, sleep } from './security/rateLimiter';
|
||||
import {
|
||||
renderForbiddenBypassPage,
|
||||
@@ -123,6 +134,87 @@ app.get('/health', (_req: Request, res: Response) => {
|
||||
res.json({ status: 'ok' });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bestenlisten: Aufrufbar über den extra Link /leaderboard
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
app.get('/leaderboard', (_req: Request, res: Response) => {
|
||||
const doors: LeaderboardPageDoor[] = getAllLeaderboards().map(({ doorId, entries }) => {
|
||||
const door = loadDoorMeta(doorId, Number.parseInt(doorId, 10));
|
||||
return { doorId, day: door.day, title: door.title, entries };
|
||||
});
|
||||
res.type('html').send(renderLeaderboardPage(doors));
|
||||
});
|
||||
|
||||
app.get('/api/leaderboard', (_req: Request, res: Response) => {
|
||||
res.json({ doors: getAllLeaderboards() });
|
||||
});
|
||||
|
||||
app.get('/api/door/:token/leaderboard', (req: Request, res: Response) => {
|
||||
if (!ensureNotBlocked(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
const door = findDoorByToken(extractParam(req.params.token));
|
||||
if (!door) {
|
||||
res.status(404).json({ error: 'Türchen nicht gefunden' });
|
||||
return;
|
||||
}
|
||||
res.json({ doorId: door.id, top: getLeaderboardForDoor(door.id).slice(0, 10) });
|
||||
});
|
||||
|
||||
app.post('/api/door/:token/leaderboard', async (req: Request, res: Response) => {
|
||||
if (!ensureNotBlocked(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const door = findDoorByToken(extractParam(req.params.token));
|
||||
if (!door) {
|
||||
await handleAuthFailure(req, res, 404, 'Türchen nicht gefunden', renderNotFoundPage, true);
|
||||
return;
|
||||
}
|
||||
|
||||
const bypassCandidate = extractBypassCandidate(req);
|
||||
let isBypassValid = false;
|
||||
if (bypassCandidate !== undefined) {
|
||||
isBypassValid = verifyBypassToken(bypassCandidate);
|
||||
if (!isBypassValid) {
|
||||
await handleAuthFailure(req, res, 403, 'Ungültiges Vorschau-Passwort', renderForbiddenBypassPage, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const unlockState = getUnlockState(door.day, isBypassValid);
|
||||
if (!unlockState.isUnlocked) {
|
||||
res.status(403).json({
|
||||
error: `${door.title} ist noch verschlossen.`,
|
||||
unlockDateIso: unlockState.unlockDateIso,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const payload =
|
||||
req.body && typeof req.body === 'object' && !Array.isArray(req.body)
|
||||
? (req.body as Record<string, unknown>)
|
||||
: {};
|
||||
const name = typeof payload.name === 'string' ? payload.name : '';
|
||||
const durationMs = typeof payload.durationMs === 'number' ? payload.durationMs : Number.NaN;
|
||||
|
||||
try {
|
||||
const result = addLeaderboardEntry(door.id, name, durationMs);
|
||||
res.json({
|
||||
ok: true,
|
||||
doorId: door.id,
|
||||
rank: result.rank,
|
||||
total: result.total,
|
||||
top10: result.top10,
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: error instanceof Error ? error.message : 'Eintrag konnte nicht gespeichert werden.',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/', (_req: Request, res: Response) => {
|
||||
res.type('html').send(renderHomePage());
|
||||
});
|
||||
|
||||
+5
-1
@@ -8,6 +8,7 @@ import {
|
||||
renderWinterBackdropSvg,
|
||||
} from './views/assets';
|
||||
import { renderInteractiveScript } from './views/interactiveScript';
|
||||
import { renderLeaderboardRuntimeScript } from './views/leaderboard';
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
@@ -1227,5 +1228,8 @@ export function renderUnlockedDoorPage(
|
||||
})();
|
||||
</script>`;
|
||||
|
||||
return renderLayout(door.title, body, script);
|
||||
// Bestenlisten-Timer + Namensdialog (Start = Öffnen, Ende = solved:true)
|
||||
const leaderboardScript = renderLeaderboardRuntimeScript(token.trim(), door.id, bypassQuery);
|
||||
|
||||
return renderLayout(door.title, body, script + leaderboardScript);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
/**
|
||||
* Leaderboard-Ansichten.
|
||||
*
|
||||
* 1. renderLeaderboardRuntimeScript: muss auf jeder Türchen-Seite geladen werden.
|
||||
* - Start der Zeitmessung: Öffnen des Türchens (Inhalt wird gemountet),
|
||||
* gemerkt in localStorage, damit ein Reload die Zeit nicht nullt.
|
||||
* - Ende: erste Server-Antwort einer Türchen-Aktion mit solved: true
|
||||
* (z. B. Codewort abgeschickt). Danach erscheint der Namens-Dialog.
|
||||
*
|
||||
* 2. renderLeaderboardPage: eigenständige Bestenlisten-Seite unter /leaderboard.
|
||||
*/
|
||||
|
||||
function escapeHtmlValue(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function formatDurationMs(durationMs: number): string {
|
||||
const totalSeconds = Math.floor(durationMs / 1000);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return hours > 0
|
||||
? `${hours}:${pad(minutes)}:${pad(seconds)}`
|
||||
: `${minutes}:${pad(seconds)}`;
|
||||
}
|
||||
|
||||
export interface LeaderboardPageDoor {
|
||||
doorId: string;
|
||||
day: number;
|
||||
title: string;
|
||||
entries: { name: string; durationMs: number; dateIso: string }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Laufzeit-Skript für Türchen-Seiten: Timer, fetch-Abo auf solved:true,
|
||||
* Namensdialog und Eintrag per POST /api/door/:token/leaderboard.
|
||||
*/
|
||||
export function renderLeaderboardRuntimeScript(token: string, doorId: string, bypassQuery: string): string {
|
||||
return `<script>
|
||||
(function () {
|
||||
var TOKEN = ${JSON.stringify(token)};
|
||||
var DOOR_ID = ${JSON.stringify(doorId)};
|
||||
var LS_START = 'advent-timer-start-' + DOOR_ID;
|
||||
var LS_NAME = 'advent-player-name';
|
||||
var SUBMIT_URL = '/api/door/' + encodeURIComponent(TOKEN) + '/leaderboard' + ${JSON.stringify(bypassQuery)};
|
||||
|
||||
var startMs = null;
|
||||
var finished = false;
|
||||
var disabled = false;
|
||||
var badgeEl = null;
|
||||
var badgeTimeEl = null;
|
||||
var modalEl = null;
|
||||
var lastElapsedMs = null;
|
||||
|
||||
function storeSet(key, value) { try { localStorage.setItem(key, value); } catch (e) {} }
|
||||
function storeGet(key) { try { return localStorage.getItem(key); } catch (e) { return null; } }
|
||||
|
||||
function formatMs(ms) {
|
||||
var totalSeconds = Math.floor(ms / 1000);
|
||||
var hours = Math.floor(totalSeconds / 3600);
|
||||
var minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
var seconds = totalSeconds % 60;
|
||||
var pad = function (n) { return String(n).padStart(2, '0'); };
|
||||
return hours > 0 ? hours + ':' + pad(minutes) + ':' + pad(seconds) : minutes + ':' + pad(seconds);
|
||||
}
|
||||
|
||||
function createBadge() {
|
||||
if (badgeEl) return;
|
||||
badgeEl = document.createElement('button');
|
||||
badgeEl.type = 'button';
|
||||
badgeEl.setAttribute('aria-label', 'Bestenliste: Zeit eintragen');
|
||||
badgeEl.style.cssText = 'position:fixed;right:14px;bottom:14px;z-index:6000;display:none;align-items:center;gap:8px;' +
|
||||
'padding:10px 14px;border-radius:999px;border:1px solid rgba(235,194,110,0.55);cursor:pointer;' +
|
||||
'background:rgba(7,15,24,0.85);color:#faf5e8;font-size:0.9rem;font-weight:600;' +
|
||||
'box-shadow:0 10px 26px rgba(0,0,0,0.45);backdrop-filter:blur(6px);';
|
||||
var label = document.createElement('span');
|
||||
label.textContent = '⏱️';
|
||||
badgeTimeEl = document.createElement('span');
|
||||
badgeTimeEl.textContent = '0:00';
|
||||
badgeEl.appendChild(label);
|
||||
badgeEl.appendChild(badgeTimeEl);
|
||||
badgeEl.addEventListener('click', function () {
|
||||
if (lastElapsedMs !== null) showNameModal(lastElapsedMs);
|
||||
});
|
||||
document.body.appendChild(badgeEl);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
if (startMs === null || finished) return;
|
||||
if (badgeTimeEl) badgeTimeEl.textContent = formatMs(Date.now() - startMs);
|
||||
}
|
||||
|
||||
function ensureStart() {
|
||||
if (startMs !== null) return startMs;
|
||||
var stored = Number(storeGet(LS_START));
|
||||
startMs = (Number.isFinite(stored) && stored > 0 && stored <= Date.now()) ? stored : Date.now();
|
||||
storeSet(LS_START, String(startMs));
|
||||
createBadge();
|
||||
if (!finished) badgeEl.style.display = 'inline-flex';
|
||||
tick();
|
||||
return startMs;
|
||||
}
|
||||
|
||||
function resetTimer(newRun) {
|
||||
if (!newRun) return;
|
||||
// Neues Spiel (z. B. Reset im Minispiel): Zeit neu starten.
|
||||
finished = false;
|
||||
lastElapsedMs = null;
|
||||
startMs = Date.now();
|
||||
storeSet(LS_START, String(startMs));
|
||||
if (badgeEl && !disabled) {
|
||||
badgeEl.style.display = 'inline-flex';
|
||||
tick();
|
||||
}
|
||||
}
|
||||
|
||||
// Start = öffnen des Türchens: sobald der Inhalt gemountet wird, läuft die Uhr.
|
||||
var mount = document.getElementById('doorContentMount');
|
||||
if (mount) {
|
||||
var observer = new MutationObserver(function (mutations) {
|
||||
for (var i = 0; i < mutations.length; i++) {
|
||||
if (mutations[i].addedNodes.length > 0) { ensureStart(); return; }
|
||||
}
|
||||
});
|
||||
observer.observe(mount, { childList: true });
|
||||
}
|
||||
|
||||
// Ende = Lösung abgeschickt: Wir lauschen auf die Türchen-Aktionen und
|
||||
// fangen die erste Antwort mit solved:true ab – ganz ohne Änderungen an
|
||||
// den einzelnen Minispielen.
|
||||
var origFetch = window.fetch;
|
||||
window.fetch = function (input, init) {
|
||||
var url = typeof input === 'string' ? input : (input && input.url) || '';
|
||||
var isAction = url.indexOf('/action') !== -1;
|
||||
var promise = origFetch.apply(this, arguments);
|
||||
if (isAction && !disabled) {
|
||||
var payload = null;
|
||||
try {
|
||||
if (init && typeof init.body === 'string') payload = JSON.parse(init.body);
|
||||
} catch (e) {}
|
||||
if (payload && payload.action === 'reset') {
|
||||
// Spieler hat eine neue Runde gestartet – Uhr neu aufziehen.
|
||||
promise.then(function () { resetTimer(finished); }).catch(function () {});
|
||||
} else if (!finished) {
|
||||
promise.then(function (response) {
|
||||
response.clone().json().then(function (data) {
|
||||
if (data && data.solved === true && !finished) {
|
||||
finished = true;
|
||||
showNameModal(Math.max(800, Date.now() - (startMs === null ? ensureStart() : startMs)));
|
||||
}
|
||||
}).catch(function () {});
|
||||
}).catch(function () {});
|
||||
}
|
||||
}
|
||||
return promise;
|
||||
};
|
||||
|
||||
function showNameModal(elapsedMs) {
|
||||
lastElapsedMs = elapsedMs;
|
||||
if (disabled) return;
|
||||
destroyModal();
|
||||
if (badgeEl) { badgeTimeEl.textContent = formatMs(elapsedMs); }
|
||||
|
||||
modalEl = document.createElement('div');
|
||||
modalEl.style.cssText = 'position:fixed;inset:0;z-index:7000;display:flex;align-items:center;justify-content:center;' +
|
||||
'background:rgba(4,10,16,0.72);backdrop-filter:blur(4px);padding:20px;';
|
||||
|
||||
var inner = document.createElement('form');
|
||||
inner.style.cssText = 'width:100%;max-width:380px;background:linear-gradient(168deg, rgba(19,43,35,0.97), rgba(36,17,24,0.97));' +
|
||||
'border:1px solid rgba(235,194,110,0.5);border-radius:16px;padding:22px;color:#faf5e8;text-align:center;' +
|
||||
'box-shadow:0 24px 60px rgba(0,0,0,0.6);';
|
||||
inner.innerHTML =
|
||||
'<h2 style="margin:0 0 6px;color:#efc774;font-family:Georgia,serif;font-size:1.25rem;">🎉 Gelöst!</h2>' +
|
||||
'<p style="margin:0 0 14px;font-size:0.95rem;">Deine Zeit: <strong style="color:#ffd08a;">' + formatMs(elapsedMs) + '</strong></p>' +
|
||||
'<label for="lbNameInput" style="display:block;font-size:0.85rem;margin-bottom:6px;">Wie heißt du?</label>' +
|
||||
'<input id="lbNameInput" maxlength="24" autocomplete="off" placeholder="Name" style="width:100%;padding:10px 12px;border-radius:10px;' +
|
||||
'border:1px solid rgba(235,194,110,0.4);background:rgba(0,0,0,0.3);color:#faf5e8;font-size:1rem;text-align:center;" />' +
|
||||
'<p id="lbError" style="display:none;color:#ff9e9e;font-size:0.82rem;margin:8px 0 0;"></p>' +
|
||||
'<button type="submit" style="margin-top:14px;width:100%;padding:11px 16px;border:0;border-radius:10px;cursor:pointer;' +
|
||||
'background:linear-gradient(160deg,#b0512b,#94192b);color:#faf5e8;font-size:1rem;font-weight:700;">In Bestenliste eintragen</button>' +
|
||||
'<button type="button" id="lbSkip" style="margin-top:8px;background:none;border:0;cursor:pointer;color:#d2c8ba;font-size:0.82rem;text-decoration:underline;">Später eintragen</button>';
|
||||
|
||||
modalEl.appendChild(inner);
|
||||
document.body.appendChild(modalEl);
|
||||
modalEl.addEventListener('click', function (event) { if (event.target === modalEl) destroyModal(); });
|
||||
|
||||
var nameInput = inner.querySelector('#lbNameInput');
|
||||
var errorEl = inner.querySelector('#lbError');
|
||||
nameInput.value = storeGet(LS_NAME) || '';
|
||||
setTimeout(function () { nameInput.focus(); }, 60);
|
||||
|
||||
inner.querySelector('#lbSkip').addEventListener('click', destroyModal);
|
||||
|
||||
inner.addEventListener('submit', async function (event) {
|
||||
event.preventDefault();
|
||||
var name = nameInput.value.trim().replace(/\\s+/g, ' ');
|
||||
if (!name) {
|
||||
errorEl.textContent = 'Bitte gib einen Namen ein.';
|
||||
errorEl.style.display = 'block';
|
||||
nameInput.focus();
|
||||
return;
|
||||
}
|
||||
errorEl.style.display = 'none';
|
||||
storeSet(LS_NAME, name);
|
||||
var submitBtn = inner.querySelector('button[type="submit"]');
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Speichere…';
|
||||
try {
|
||||
var response = await origFetch(SUBMIT_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name, durationMs: elapsedMs })
|
||||
});
|
||||
var data = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof data.error === 'string' ? data.error : 'Speichern fehlgeschlagen.');
|
||||
}
|
||||
storeSet(LS_START, '');
|
||||
startMs = null;
|
||||
if (badgeEl) badgeEl.style.display = 'none';
|
||||
disabled = true;
|
||||
var rankLine = 'Platz ' + data.rank + ' von ' + data.total + ' 🏆';
|
||||
inner.innerHTML =
|
||||
'<h2 style="margin:0 0 6px;color:#efc774;font-family:Georgia,serif;font-size:1.25rem;">Eingetragen!</h2>' +
|
||||
'<p style="margin:0 0 14px;font-size:0.95rem;">' + formatMs(elapsedMs) + ' · <strong style="color:#ffd08a;">' + rankLine + '</strong></p>' +
|
||||
'<a href="/leaderboard" style="display:inline-block;padding:11px 18px;border-radius:10px;text-decoration:none;' +
|
||||
'background:linear-gradient(160deg,#b0512b,#94192b);color:#faf5e8;font-size:0.95rem;font-weight:700;">Bestenliste ansehen</a>' +
|
||||
'<br /><button type="button" id="lbClose" style="margin-top:10px;background:none;border:0;cursor:pointer;color:#d2c8ba;font-size:0.82rem;text-decoration:underline;">Schließen</button>';
|
||||
inner.querySelector('#lbClose').addEventListener('click', destroyModal);
|
||||
} catch (err) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'In Bestenliste eintragen';
|
||||
errorEl.textContent = (err && err.message) ? err.message : 'Speichern fehlgeschlagen.';
|
||||
errorEl.style.display = 'block';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function destroyModal() {
|
||||
if (modalEl) { modalEl.remove(); modalEl = null; }
|
||||
}
|
||||
|
||||
// Falls das Türchen schon offen war (z. B. Reload), Uhr direkt weiterticken lassen.
|
||||
setInterval(tick, 1000);
|
||||
tick();
|
||||
})();
|
||||
</script>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eigenständige Bestenlisten-Seite (Link /leaderboard).
|
||||
*/
|
||||
export function renderLeaderboardPage(doors: LeaderboardPageDoor[]): string {
|
||||
const sections = doors.length
|
||||
? doors.map((door) => {
|
||||
const rows = door.entries.slice(0, 10).map((entry, index) => {
|
||||
const rank = index + 1;
|
||||
const medal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : String(rank);
|
||||
const dateLabel = escapeHtmlValue(
|
||||
new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' })
|
||||
.format(new Date(entry.dateIso)),
|
||||
);
|
||||
return `
|
||||
<tr>
|
||||
<td class="lb-rank">${medal}</td>
|
||||
<td class="lb-time">${formatDurationMs(entry.durationMs)}</td>
|
||||
<td class="lb-name">${escapeHtmlValue(entry.name)}</td>
|
||||
<td class="lb-date">${dateLabel}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<section class="lb-card">
|
||||
<h2><span class="lb-door-day">${door.day}</span> ${escapeHtmlValue(door.title)}</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>#</th><th>Zeit</th><th>Name</th><th>Datum</th></tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</section>`;
|
||||
}).join('')
|
||||
: `
|
||||
<section class="lb-card">
|
||||
<h2>Noch keine Einträge</h2>
|
||||
<p>Sobald ein Minispiel gelöst ist, erscheinen hier die besten Zeiten.</p>
|
||||
</section>`;
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<title>Bestenlisten – Adventskalender</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg-top: #07131d; --bg-mid: #10252a; --bg-warm: #24171c;
|
||||
--card-border: rgba(235, 194, 110, 0.45);
|
||||
--gold: #efc774;
|
||||
--text: #faf5e8;
|
||||
--text-muted: #d2c8ba;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
min-height: 100dvh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(circle at 50% 30%, rgba(239, 180, 88, 0.14) 0%, transparent 50%),
|
||||
linear-gradient(180deg, var(--bg-top) 0%, var(--bg-mid) 58%, var(--bg-warm) 100%);
|
||||
padding: 28px 16px 60px;
|
||||
}
|
||||
.lb-wrap { max-width: 560px; margin: 0 auto; }
|
||||
.lb-header { text-align: center; margin-bottom: 26px; }
|
||||
.lb-header h1 {
|
||||
font-family: Georgia, "Times New Roman", serif;
|
||||
font-size: 1.9rem;
|
||||
color: var(--gold);
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.lb-header p { color: var(--text-muted); margin-top: 6px; font-size: 0.95rem; }
|
||||
.lb-card {
|
||||
background: linear-gradient(168deg, rgba(19, 43, 35, 0.93) 0%, rgba(36, 17, 24, 0.95) 100%);
|
||||
border: 1px solid var(--card-border);
|
||||
border-radius: 18px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.lb-card h2 {
|
||||
font-family: Georgia, "Times New Roman", serif;
|
||||
font-size: 1.15rem;
|
||||
color: var(--gold);
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.lb-door-day {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle at 32% 28%, #b0512b, #741221);
|
||||
border: 2px solid #efc774;
|
||||
color: #f7ecd2;
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
table { width: 100%; border-collapse: collapse; font-size: 0.93rem; }
|
||||
th {
|
||||
text-align: left;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid rgba(235, 194, 110, 0.25);
|
||||
}
|
||||
td { padding: 8px; border-bottom: 1px solid rgba(235, 194, 110, 0.12); }
|
||||
tr:last-child td { border-bottom: 0; }
|
||||
.lb-rank { width: 44px; text-align: left; }
|
||||
.lb-time { width: 76px; font-variant-numeric: tabular-nums; color: #ffd08a; font-weight: 700; }
|
||||
.lb-name { word-break: break-word; }
|
||||
.lb-date { width: 86px; color: var(--text-muted); font-size: 0.8rem; text-align: right; }
|
||||
.lb-footer { text-align: center; color: var(--text-muted); font-size: 0.85rem; }
|
||||
.lb-footer a {
|
||||
color: var(--gold);
|
||||
text-decoration: none;
|
||||
border: 1px solid rgba(235, 194, 110, 0.4);
|
||||
border-radius: 999px;
|
||||
padding: 8px 16px;
|
||||
display: inline-block;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="lb-wrap">
|
||||
<header class="lb-header">
|
||||
<h1>🏆 Bestenlisten</h1>
|
||||
<p>Die schnellsten Runden durch die Türchen – Start ab dem Öffnen bis zur richtigen Lösung.</p>
|
||||
</header>
|
||||
${sections}
|
||||
<p class="lb-footer"><a href="/">← Zum Adventskalender</a></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
Reference in new issue
Block a user