mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
298 lines
18 KiB
JavaScript
298 lines
18 KiB
JavaScript
// Startseite für Besucher ohne Anmeldung: bewegter Börsen-Hintergrund, Live-Indizes, Laufband und Anmeldekarte.
|
||
// Erscheint beim Öffnen ohne Konto und nach dem Abmelden. Zuschauen ohne Konto gibt es nicht: die Seite bleibt, bis man
|
||
// angemeldet ist. Ein Einladungslink öffnet direkt die Registrierung (auf dem Handy steht die Karte dann ganz oben).
|
||
import { art } from './art.js';
|
||
import { S, sub } from './state.js';
|
||
import { api, setToken, getToken } from './net.js';
|
||
import { esc, num, int, chg, patch } from './util.js';
|
||
import { icon } from './icons.js';
|
||
import { pendingInvite, inviteHeadHtml, afterRegister } from './invite.js';
|
||
|
||
const reduce = matchMedia('(prefers-reduced-motion: reduce)');
|
||
let el = null;
|
||
let onAuthed = async () => {};
|
||
let raf = 0;
|
||
let timers = [];
|
||
const spark = new Map(); // Index-ID → Werte für den Mini-Verlauf
|
||
let health = null;
|
||
|
||
export function initSplash({ authed }) { onAuthed = authed; }
|
||
|
||
const SIGNET = '<svg class="spl-signet" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><defs><linearGradient id="splG" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#4F8BFF"/><stop offset="1" stop-color="#1E40AF"/></linearGradient></defs><rect width="64" height="64" rx="15" fill="url(#splG)"/><path d="M12.5 21.5 21 44.5l10-17 10 17" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/><path d="M41 44.5 51 15.5M42.5 15.5H51v8.5" fill="none" stroke="#FCD34D" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
||
|
||
const indices = () => {
|
||
const m = S.market;
|
||
if (Array.isArray(m?.indices) && m.indices.length) return m.indices;
|
||
return m?.index ? [{ id: 'WIBO10', name: 'WIBO-10', ...m.index }] : [];
|
||
};
|
||
|
||
function sparkSvg(arr, up) {
|
||
if (arr.length < 2) return '<svg viewBox="0 0 140 28" preserveAspectRatio="none" aria-hidden="true"></svg>';
|
||
const min = Math.min(...arr), max = Math.max(...arr), w = 140, h = 28;
|
||
const pts = arr.map((v, i) => `${((i / (arr.length - 1)) * w).toFixed(1)},${(h - ((v - min) / (max - min || 1)) * (h - 4) - 2).toFixed(1)}`).join(' ');
|
||
return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" aria-hidden="true" class="${up ? 'up' : 'down'}"><polyline points="0,${h} ${pts} ${w},${h}" class="spl-area"/><polyline points="${pts}" class="spl-line"/></svg>`;
|
||
}
|
||
|
||
function tilesHtml() {
|
||
const list = indices();
|
||
if (!list.length) return '<p class="spl-muted">Kurse werden geladen …</p>';
|
||
return list.map((i) => {
|
||
const key = i.id ?? i.name;
|
||
const arr = spark.get(key) ?? [];
|
||
return `<div class="spl-tile"><small>${esc(i.name ?? key)}</small><b>${num(i.value, 0)}</b><span class="spl-c">${chg(i.change)}</span>${sparkSvg(arr, (i.change ?? 0) >= 0)}</div>`;
|
||
}).join('');
|
||
}
|
||
|
||
function liveHtml() {
|
||
const lbl = document.getElementById('phaseLabel')?.textContent?.trim() || 'Börse Wiborien';
|
||
const subTxt = document.getElementById('phaseSub')?.textContent?.trim() || '';
|
||
const on = health?.online;
|
||
const st = S.market?.phase === 'continuous' ? 'on' : S.market?.after ? 'eve' : S.market?.phase === 'closed' ? 'off' : 'auc';
|
||
return `<span class="spl-dot" data-st="${st}"></span><b>${esc(lbl)}</b><span class="spl-t">${on ? ` · ${int(on)} online` : ''}${subTxt ? ` · ${esc(subTxt)}` : ''}</span>`;
|
||
}
|
||
|
||
function tapeHtml() {
|
||
const parts = indices().map((i) => `<span><b class="spl-acc">${esc(i.name ?? i.id)}</b> ${num(i.value, 0)} ${chg(i.change)}</span>`);
|
||
for (const n of (S.news ?? []).slice(0, 8)) parts.push(`<span class="spl-news">${esc(n.title)}</span>`);
|
||
const st = (S.tickers ?? []).filter((t) => (t.kind ?? 'stock') === 'stock' && Number.isFinite(t.change));
|
||
for (const t of [...st].sort((a, b) => Math.abs(b.change) - Math.abs(a.change)).slice(0, 14)) parts.push(`<span><b>${esc(t.symbol)}</b> ${num(t.last)} ${chg(t.change)}</span>`);
|
||
const html = parts.join('<i class="spl-sep" aria-hidden="true"></i>');
|
||
return html ? `${html}<i class="spl-sep" aria-hidden="true"></i>${html}<i class="spl-sep" aria-hidden="true"></i>` : '';
|
||
}
|
||
|
||
function floatsHtml() {
|
||
const st = (S.tickers ?? []).filter((t) => (t.kind ?? 'stock') === 'stock').slice(0, 14);
|
||
return st.map((t, i) => `<div class="spl-float" style="left:${58 + ((i * 37) % 38)}%;top:${10 + ((i * 53) % 80)}%;animation-delay:${-i * 1.3}s;animation-duration:${12 + (i % 5) * 2}s"><b>${esc(t.symbol)}</b>${num(t.last)} <span class="${(t.change ?? 0) >= 0 ? 'up' : 'down'}">${(t.change ?? 0) >= 0 ? '+' : '−'}${num(Math.abs(t.change ?? 0))} %</span></div>`).join('');
|
||
}
|
||
|
||
function update() {
|
||
if (!el) return;
|
||
for (const i of indices()) {
|
||
const key = i.id ?? i.name;
|
||
const arr = spark.get(key) ?? [];
|
||
if (arr.at(-1) !== i.value && Number.isFinite(i.value)) { arr.push(i.value); if (arr.length > 60) arr.shift(); spark.set(key, arr); }
|
||
}
|
||
el.querySelector('#splIdx').innerHTML = tilesHtml();
|
||
patch(el.querySelector('#splLive'), liveHtml());
|
||
const fl = el.querySelector('#splFloats');
|
||
if (!fl.childElementCount) fl.innerHTML = floatsHtml();
|
||
const tape = el.querySelector('#splTape');
|
||
if (!tape.childElementCount || tape.dataset.n !== String((S.news ?? [])[0]?.id ?? '')) {
|
||
tape.innerHTML = tapeHtml();
|
||
tape.dataset.n = String((S.news ?? [])[0]?.id ?? '');
|
||
requestAnimationFrame(() => tape.style.setProperty('--spl-dur', `${Math.max(30, Math.round(tape.scrollWidth / 2 / 60))}s`));
|
||
}
|
||
}
|
||
|
||
/** Verlauf der Indizes für die Mini-Kurven vorladen (Tagesschlüsse) */
|
||
async function preloadSpark() {
|
||
for (const i of indices()) {
|
||
if (!i.id) continue;
|
||
try {
|
||
const d = await api(`/api/index/${encodeURIComponent(i.id)}`, { auth: false, feedback: false });
|
||
const vals = (d.hist ?? []).slice(-30).map((h) => h.v).filter(Number.isFinite);
|
||
if (vals.length) spark.set(i.id, [...vals, ...(spark.get(i.id) ?? [])].slice(-60));
|
||
} catch { /* egal */ }
|
||
}
|
||
update();
|
||
}
|
||
|
||
async function loadHealth() {
|
||
try { health = await (await fetch('/api/health')).json(); } catch { health = null; }
|
||
if (el) patch(el.querySelector('#splLive'), liveHtml());
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Hintergrund: Kerzen und Linie, wachsen langsam nach rechts
|
||
function startChart(cv) {
|
||
const ctx = cv.getContext('2d');
|
||
let W = 0, H = 0, prog = 0, last = 100;
|
||
const candles = [];
|
||
const add = () => {
|
||
const o = last, c = o * (1 + 0.0012 + (Math.random() - 0.5) * 0.036);
|
||
candles.push({ o, c, h: Math.max(o, c) * (1 + Math.random() * 0.008), l: Math.min(o, c) * (1 - Math.random() * 0.008) });
|
||
last = c;
|
||
if (candles.length > 90) candles.shift();
|
||
};
|
||
for (let i = 0; i < 90; i++) add();
|
||
const resize = () => { const r = devicePixelRatio || 1; W = cv.clientWidth; H = cv.clientHeight; cv.width = W * r; cv.height = H * r; ctx.setTransform(r, 0, 0, r, 0, 0); };
|
||
const frame = () => {
|
||
if (!el) return;
|
||
ctx.clearRect(0, 0, W, H);
|
||
const n = candles.length, cw = W / 80;
|
||
let min = Infinity, max = -Infinity;
|
||
for (const k of candles) { min = Math.min(min, k.l); max = Math.max(max, k.h); }
|
||
const y = (v) => H * 0.92 - ((v - min) / (max - min || 1)) * H * 0.62;
|
||
const x0 = -prog * cw;
|
||
ctx.globalAlpha = 0.16;
|
||
candles.forEach((k, i) => {
|
||
const x = x0 + i * cw;
|
||
ctx.strokeStyle = ctx.fillStyle = k.c >= k.o ? '#2bd36b' : '#ff5c5c';
|
||
ctx.beginPath(); ctx.moveTo(x + cw / 2, y(k.h)); ctx.lineTo(x + cw / 2, y(k.l)); ctx.stroke();
|
||
ctx.fillRect(x + cw * 0.2, Math.min(y(k.o), y(k.c)), cw * 0.6, Math.max(1, Math.abs(y(k.o) - y(k.c))));
|
||
});
|
||
ctx.globalAlpha = 1;
|
||
const g = ctx.createLinearGradient(0, 0, W, 0);
|
||
g.addColorStop(0, 'rgba(76,141,255,0)'); g.addColorStop(0.35, 'rgba(76,141,255,.55)'); g.addColorStop(1, 'rgba(43,211,107,.9)');
|
||
ctx.beginPath();
|
||
candles.forEach((k, i) => { const x = x0 + i * cw + cw / 2; if (i) ctx.lineTo(x, y(k.c)); else ctx.moveTo(x, y(k.c)); });
|
||
ctx.strokeStyle = g; ctx.lineWidth = 2.4; ctx.shadowColor = 'rgba(76,141,255,.6)'; ctx.shadowBlur = 16; ctx.stroke(); ctx.shadowBlur = 0;
|
||
const lx = x0 + (n - 1) * cw + cw / 2, ly = y(candles[n - 1].c);
|
||
ctx.lineTo(lx, H); ctx.lineTo(x0 + cw / 2, H); ctx.closePath();
|
||
const f = ctx.createLinearGradient(0, H * 0.3, 0, H);
|
||
f.addColorStop(0, 'rgba(76,141,255,.10)'); f.addColorStop(1, 'rgba(76,141,255,0)');
|
||
ctx.fillStyle = f; ctx.fill();
|
||
const t = performance.now() / 600;
|
||
ctx.beginPath(); ctx.arc(lx, ly, 5 + Math.sin(t) * 1.5, 0, 7); ctx.fillStyle = '#2bd36b'; ctx.shadowColor = '#2bd36b'; ctx.shadowBlur = 18; ctx.fill(); ctx.shadowBlur = 0;
|
||
prog += 0.012;
|
||
if (prog >= 1) { prog = 0; add(); }
|
||
if (!reduce.matches && !document.hidden) raf = requestAnimationFrame(frame);
|
||
};
|
||
resize();
|
||
addEventListener('resize', resize);
|
||
document.addEventListener('visibilitychange', () => { if (el && !document.hidden && !reduce.matches) { cancelAnimationFrame(raf); raf = requestAnimationFrame(frame); } });
|
||
frame();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Anmeldekarte
|
||
function cardHtml(invite) {
|
||
const inv = S.info?.invites ?? {};
|
||
const only = !!inv.inviteOnly;
|
||
const showCode = only || inv.enabled !== false;
|
||
const code = invite?.ok ? invite.code : pendingInvite();
|
||
const cash = S.info?.startCash ? `${int(S.info.startCash)} €` : '100.000 €';
|
||
return `${invite ? `<div class="spl-invite">${inviteHeadHtml(invite)}</div>` : ''}
|
||
<div class="spl-key">${art('briefcase', { cls: 'spl-key-art' })}</div>
|
||
<h2 id="splH">Dein Depot wartet.</h2>
|
||
<p class="spl-sub" id="splS">Konto in 20 Sekunden – kostenlos, nur Spielgeld.</p>
|
||
<div class="spl-seg" role="tablist" aria-label="Registrieren oder anmelden">
|
||
<button type="button" role="tab" data-sm="register" aria-selected="true">Registrieren</button>
|
||
<button type="button" role="tab" data-sm="login" aria-selected="false">Anmelden</button>
|
||
</div>
|
||
<form id="splForm" novalidate>
|
||
<div class="spl-f"><label for="splName">Spielername</label><input id="splName" autocomplete="username" required minlength="3" maxlength="20" placeholder="z. B. Bullenreiter"></div>
|
||
<div class="spl-f"><label for="splPw">Passwort <span id="splPwH">(mindestens 8 Zeichen)</span></label><input id="splPw" type="password" required minlength="8" autocomplete="new-password"></div>
|
||
<div class="spl-f" id="splMailF"><label for="splMail">E-Mail <span class="spl-opt">(optional)</span></label><input id="splMail" type="email" autocomplete="email" placeholder="für Tagesbericht und Benachrichtigungen"></div>
|
||
${showCode ? `<div class="spl-f" id="splInvF"><label for="splInv">Einladungscode ${only ? '<b class="gold-t">(Pflicht)</b>' : '<span class="spl-opt">(optional)</span>'}</label>
|
||
<input id="splInv" autocomplete="off" autocapitalize="characters" spellcheck="false" maxlength="40" value="${esc(code)}" ${only ? 'required aria-required="true"' : ''}>
|
||
${only ? `<small class="spl-muted">Registrierung derzeit nur mit Einladung – den Code bekommst du von Freunden oder der Spielleitung.${inv.setupOpen ? ' Erstes Konto auf diesem Server? Gib den Einrichtungscode aus dem Server-Log ein – damit wirst du Admin.' : ''}</small>` : ''}</div>` : ''}
|
||
<p class="spl-err" id="splErr" role="alert"></p>
|
||
<button type="submit" class="spl-go" id="splGo"><span>Mit ${esc(cash)} starten</span>${icon('go', { size: 18 })}</button>
|
||
</form>
|
||
<div class="spl-bonus" id="splBonus">${icon('check', { size: 18 })}<span><b>${esc(cash)}</b> Startkapital · Einführungstour · nur Spielgeld</span></div>`;
|
||
}
|
||
|
||
function setMode(m) {
|
||
const reg = m === 'register';
|
||
el.dataset.mode = m;
|
||
for (const b of el.querySelectorAll('[data-sm]')) b.setAttribute('aria-selected', String(b.dataset.sm === m));
|
||
el.querySelector('#splMailF').hidden = !reg;
|
||
const invF = el.querySelector('#splInvF'); if (invF) invF.hidden = !reg;
|
||
el.querySelector('#splBonus').hidden = !reg;
|
||
el.querySelector('#splPwH').hidden = !reg;
|
||
el.querySelector('#splPw').autocomplete = reg ? 'new-password' : 'current-password';
|
||
el.querySelector('#splH').textContent = reg ? 'Dein Depot wartet.' : 'Willkommen zurück.';
|
||
el.querySelector('#splS').textContent = reg ? 'Konto in 20 Sekunden – kostenlos, nur Spielgeld.' : 'Der Markt hat nicht auf dich gewartet – dein Depot schon.';
|
||
const cash = S.info?.startCash ? `${int(S.info.startCash)} €` : '100.000 €';
|
||
el.querySelector('#splGo span').textContent = reg ? `Mit ${cash} starten` : 'Anmelden';
|
||
el.querySelector('#splErr').textContent = '';
|
||
}
|
||
|
||
async function submit(e) {
|
||
e.preventDefault();
|
||
const m = el.dataset.mode;
|
||
const name = el.querySelector('#splName').value.trim();
|
||
const password = el.querySelector('#splPw').value;
|
||
const err = el.querySelector('#splErr');
|
||
err.textContent = '';
|
||
if (name.length < 3) { err.textContent = 'Name: mindestens 3 Zeichen.'; el.querySelector('#splName').focus(); return; }
|
||
if (m === 'register' && password.length < 8) { err.textContent = 'Passwort: mindestens 8 Zeichen.'; el.querySelector('#splPw').focus(); return; }
|
||
if (!password) { err.textContent = 'Bitte Passwort eingeben.'; el.querySelector('#splPw').focus(); return; }
|
||
const invite = el.querySelector('#splInv')?.value.trim() || undefined;
|
||
if (m === 'register' && S.info?.invites?.inviteOnly && !invite) { err.textContent = 'Bitte deinen Einladungscode eingeben – ohne Einladung ist die Registrierung derzeit nicht möglich.'; el.querySelector('#splInv').focus(); return; }
|
||
const btn = el.querySelector('#splGo');
|
||
btn.disabled = true;
|
||
try {
|
||
const body = m === 'register' ? { name, password, email: el.querySelector('#splMail').value.trim() || undefined, invite } : { name, password };
|
||
const r = await api(`/api/${m}`, { method: 'POST', body, auth: false });
|
||
setToken(r.token);
|
||
hideSplash();
|
||
await onAuthed(m === 'register');
|
||
if (m === 'register') afterRegister(r.invite);
|
||
} catch (ex) { err.textContent = ex.message; btn.disabled = false; }
|
||
}
|
||
|
||
/** Startseite zeigen. opt.invite: Ergebnis eines Einladungslinks (Willkommenskarte, Registrierung vorne), opt.mode: Start-Reiter */
|
||
export function showSplash(opt = {}) {
|
||
if (getToken()) return;
|
||
if (el) { if (opt.invite) { el.classList.add('spl-inv'); el.querySelector('.spl-card').innerHTML = cardHtml(opt.invite); setMode('register'); } return; }
|
||
el = document.createElement('div');
|
||
el.className = opt.invite ? 'spl spl-inv' : 'spl';
|
||
el.id = 'splash';
|
||
el.setAttribute('role', 'dialog');
|
||
el.setAttribute('aria-modal', 'true');
|
||
el.setAttribute('aria-label', 'Willkommen bei WiBoSim – anmelden oder registrieren');
|
||
el.innerHTML = `<div class="spl-bg" aria-hidden="true"><div class="spl-grid"></div><canvas class="spl-chart"></canvas><div id="splFloats"></div></div>
|
||
<header class="spl-top"><div class="spl-brand">${SIGNET}<span>Wi<em>Bo</em>Sim</span></div><div class="spl-live" id="splLive"></div></header>
|
||
<main class="spl-main">
|
||
<section class="spl-hero">
|
||
<span class="spl-kicker">${icon('chart-up', { size: 14 })}Die Börse von Wiborien · live</span>
|
||
<h1>Kaufen. Verkaufen.<br><span class="spl-grad">Mitregieren.</span></h1>
|
||
<p class="spl-lead">${int(S.tickers?.filter((t) => (t.kind ?? 'stock') === 'stock').length || 60)} Aktien, echte Auktionen, Orderbuch und Optionsscheine – mit Spielgeld. Nachrichten aus aller Welt bewegen die Kurse, und im Parlament stimmst du über Gesetze ab, die ganze Branchen treffen.</p>
|
||
</section>
|
||
<section class="spl-more">
|
||
<div class="spl-idx" id="splIdx"></div>
|
||
<div class="spl-feats">
|
||
<div class="spl-feat"><i>${art('chart', { cls: 'spl-art' })}</i><div><b>Echter Börsenalltag</b><span>Eröffnungsauktion, Limit-Orders, Leerverkauf, Abendhandel.</span></div></div>
|
||
<div class="spl-feat"><i>${art('parliament', { cls: 'spl-art' })}</i><div><b>Politik bewegt Kurse</b><span>Parteien, Abstimmungen, Haushalt – und Rivalen, die mitbieten.</span></div></div>
|
||
<div class="spl-feat"><i>${art('trophy', { cls: 'spl-art' })}</i><div><b>Battles & Ligen</b><span>Duelle, Clans, Turniere und eine Saison-Rangliste.</span></div></div>
|
||
</div>
|
||
</section>
|
||
<aside class="spl-card" aria-label="Registrieren oder anmelden">${cardHtml(opt.invite)}</aside>
|
||
</main>
|
||
<div class="spl-tape" aria-hidden="true"><div class="spl-lbl"><i></i>Live</div><div class="spl-vp"><div class="spl-run" id="splTape"></div></div></div>`;
|
||
document.body.appendChild(el);
|
||
document.documentElement.classList.add('splash-open');
|
||
el.addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-sm]');
|
||
if (b) setMode(b.dataset.sm);
|
||
});
|
||
el.addEventListener('submit', (e) => { if (e.target.id === 'splForm') submit(e); });
|
||
// Dialog: Tab bleibt im Begrüßungsfenster; ohne Konto lässt es sich nicht schließen (auch nicht mit Escape)
|
||
el.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Escape' && !document.querySelector('.modal-bg')) { e.preventDefault(); return; }
|
||
if (e.key !== 'Tab') return;
|
||
const f = [...el.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')].filter((x) => x.offsetParent !== null);
|
||
if (!f.length) return;
|
||
const i = f.indexOf(document.activeElement);
|
||
if (i < 0) { e.preventDefault(); f[e.shiftKey ? f.length - 1 : 0].focus(); }
|
||
else if (e.shiftKey && i === 0) { e.preventDefault(); f[f.length - 1].focus(); }
|
||
else if (!e.shiftKey && i === f.length - 1) { e.preventDefault(); f[0].focus(); }
|
||
});
|
||
setMode(opt.invite ? 'register' : opt.mode ?? 'register');
|
||
startChart(el.querySelector('.spl-chart'));
|
||
update();
|
||
preloadSpark();
|
||
loadHealth();
|
||
timers = [setInterval(() => { if (el) patch(el.querySelector('#splLive'), liveHtml()); }, 1000), setInterval(loadHealth, 30_000)];
|
||
if (!matchMedia('(pointer: coarse)').matches) setTimeout(() => el?.querySelector('#splName')?.focus({ preventScroll: true }), 50);
|
||
else if (opt.invite) setTimeout(() => el?.querySelector('.spl-card')?.scrollIntoView({ block: 'start' }), 50);
|
||
}
|
||
|
||
export function hideSplash() {
|
||
if (!el) return;
|
||
cancelAnimationFrame(raf);
|
||
for (const t of timers) clearInterval(t);
|
||
timers = [];
|
||
el.classList.add('spl-out');
|
||
const old = el;
|
||
el = null;
|
||
document.documentElement.classList.remove('splash-open');
|
||
setTimeout(() => old.remove(), reduce.matches ? 0 : 350);
|
||
}
|
||
|
||
/** Nach dem Abmelden wieder zeigen (Reiter „Anmelden“) */
|
||
export function splashAfterLogout() { showSplash({ mode: 'login' }); }
|
||
|
||
sub('market', () => update());
|
||
sub('news', () => update());
|