Files
wibosim/server/public/js/util.js
T
db9979andClaude Opus 5.5 95f09321ea Client neu für Sprint A–E: Auktionen, Ordertypen, Parlament, Battles, Ligen, Community, Admin
Behebt außerdem den Startwert des Index-Bots in Battle-Modi mit eigenem Konto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-03 14:22:23 +00:00

124 lines
6.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Hilfsfunktionen: Escaping, Zahlen- und Zeitformate, DOM-Helfer.
/** HTML-Escaping für alle Texte vom Server oder von Spielern */
export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
/** Nur http(s)-Links zulassen, sonst null */
export function safeUrl(u) {
try { const url = new URL(String(u)); return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null; } catch { return null; }
}
export const $ = (s, root = document) => root.querySelector(s);
export const $$ = (s, root = document) => [...root.querySelectorAll(s)];
const nf = new Map();
function numFmt(min, max) {
const k = `${min}|${max}`;
if (!nf.has(k)) nf.set(k, new Intl.NumberFormat('de-DE', { minimumFractionDigits: min, maximumFractionDigits: max }));
return nf.get(k);
}
/** Zahl mit festen Nachkommastellen */
export const num = (x, d = 2) => (x === null || x === undefined || !Number.isFinite(Number(x)) ? '–' : numFmt(d, d).format(Number(x)));
/** Ganzzahl mit Tausenderpunkt */
export const int = (x) => num(x, 0);
/** Euro-Betrag */
export const eur = (x, d = 2) => (x === null || x === undefined || !Number.isFinite(Number(x)) ? '–' : `${num(x, d)} €`);
/** Kompakte Beträge (Mio./Mrd.) */
export function compact(x) {
if (!Number.isFinite(x)) return '–';
const a = Math.abs(x);
if (a >= 1e9) return `${num(x / 1e9, 1)} Mrd.`;
if (a >= 1e6) return `${num(x / 1e6, 1)} Mio.`;
if (a >= 1e4) return `${num(x / 1e3, 1)} Tsd.`;
return int(x);
}
/** Prozentwert (Eingabe bereits in Prozent) mit Vorzeichen */
export const pct = (x, d = 2) => (Number.isFinite(x) ? `${x > 0 ? '+' : x < 0 ? '−' : '±'}${num(Math.abs(x), d)} %` : '–');
/** Anteil (0–1) als Prozent ohne Vorzeichen */
export const frac = (x, d = 1) => (Number.isFinite(x) ? `${num(x * 100, d)} %` : '–');
/** Richtung als Klasse + Pfeil (nie nur Farbe) */
export const dirCls = (x) => (x > 0 ? 'up' : x < 0 ? 'down' : 'flat');
export const arrow = (x) => (x > 0 ? '▲' : x < 0 ? '▼' : '■');
/** Prozentänderung mit Pfeil, Farbe und Vorzeichen */
export const chg = (x, d = 2) => `<span class="${dirCls(x)}"><span aria-hidden="true">${arrow(x)}</span> ${pct(x, d)}</span>`;
/** Betrag mit Pfeil */
export const chgEur = (x) => `<span class="${dirCls(x)}"><span aria-hidden="true">${arrow(x)}</span> ${x > 0 ? '+' : ''}${eur(x)}</span>`;
// ---------------------------------------------------------------- Zeit
let clockOffset = 0;
/** Serverzeit-Abgleich (market.serverTime) */
export function syncClock(serverTime) { if (Number.isFinite(serverTime)) clockOffset = serverTime - Date.now(); }
export const now = () => Date.now() + clockOffset;
const WD = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
const pad = (n) => String(n).padStart(2, '0');
export const time = (ts) => { const d = new Date(ts); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; };
export const timeS = (ts) => { const d = new Date(ts); return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; };
export const date = (ts) => { const d = new Date(ts); return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.`; };
export const dateY = (ts) => { const d = new Date(ts); return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`; };
export const wdDate = (ts) => { const d = new Date(ts); return `${WD[d.getDay()]} ${date(ts)}`; };
/** „heute 14:15“ / „morgen 09:00“ / „Do 12.03. 09:00“ */
export function when(ts) {
const d = new Date(ts), n = new Date(now());
const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
const diff = Math.round((day(d) - day(n)) / 86_400_000);
const t = time(ts);
if (diff === 0) return `heute ${t}`;
if (diff === 1) return `morgen ${t}`;
if (diff === -1) return `gestern ${t}`;
return `${wdDate(ts)} ${t}`;
}
/** Restzeit „2 h 14 min“ / „4:05“ */
export function countdown(ms) {
if (!Number.isFinite(ms)) return '–';
ms = Math.max(0, ms);
const s = Math.floor(ms / 1000);
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
if (d > 0) return `${d} T ${h} h`;
if (h > 0) return `${h} h ${pad(m)} min`;
return `${m}:${pad(sec)}`;
}
/** „vor 5 min“ */
export function ago(ts) {
const s = Math.max(0, Math.floor((now() - ts) / 1000));
if (s < 60) return 'gerade eben';
if (s < 3600) return `vor ${Math.floor(s / 60)} min`;
if (s < 86400) return `vor ${Math.floor(s / 3600)} h`;
return `vor ${Math.floor(s / 86400)} T`;
}
/** Spielername als klickbarer Link zum öffentlichen Profil */
export const player = (name) => (name ? `<button type="button" class="plink" data-act="profile" data-name="${esc(name)}">${esc(name)}</button>` : '–');
/** Fortschrittsbalken (0–1) mit ARIA */
export function meter(v, { label = '', cls = '' } = {}) {
const p = Math.max(0, Math.min(1, Number(v) || 0));
return `<div class="meter ${cls}" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(p * 100)}"${label ? ` aria-label="${esc(label)}"` : ''}><div style="width:${(p * 100).toFixed(1)}%"></div></div>`;
}
/**
* Inhalt nur ersetzen, wenn er sich geändert hat; Fokus (per data-k oder id) bleibt erhalten.
* @param {Element|null} el @param {string} html
*/
export function patch(el, html) {
if (!el || el._html === html) return false;
const a = document.activeElement;
const key = a && el.contains(a) ? (a.dataset?.k ?? (a.id ? `#${a.id}` : null)) : null;
el.innerHTML = html;
el._html = html;
if (key) {
const t = key.startsWith('#') ? el.querySelector(key) : el.querySelector(`[data-k="${CSS.escape(key)}"]`);
t?.focus({ preventScroll: true });
}
return true;
}
export const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
export const store = {
get(k, d = null) { try { const v = localStorage.getItem(`wibo.${k}`); return v === null ? d : JSON.parse(v); } catch { return d; } },
set(k, v) { try { localStorage.setItem(`wibo.${k}`, JSON.stringify(v)); } catch { /* egal */ } },
del(k) { try { localStorage.removeItem(`wibo.${k}`); } catch { /* egal */ } },
};