Files
wibosim/server/public/js/util.js
T
db9979andClaude Opus 5.5 b8a3c9d429 Chartfluss 4: Kursraster nach Preis
Eine Tabelle (public/js/ticksize.js) für Server und Client: unter 10 € Schritte
von 0,001 €, 10 bis unter 50 € 0,005 €, ab 50 € 0,01 €. Gilt für Orderbuch,
Matching, Limitprüfung (Server und Orderticket gleich, Meldung nennt die
Schrittweite, Knopf „Auf … setzen“), Abendhandel, Auktionen, Market Maker,
Arbitrage, Rivalen, Stopps/Bracket/OCO (Auslöser werden gerundet), Dividenden-
und Split-Anpassung, Abfindung beim Börsenrückzug, Anzeige (Nachkommastellen nach
Raster in Kursliste, Kopf, Orderbuch, Umsätzen, Orders, Chart) und MCP
(Beschreibung, get_quote mit Raster). Hebelprodukte behalten ihr Raster 0,001 €.
Alte Cent-Limits liegen auf jedem Raster; beim Laden werden Limits und Auslöser
idempotent aufs Raster gelegt. Tests: Rundung/Grenzen/Schritte ohne Drift,
Spiel über mehrere Handelstage mit Invarianten (Geld, Bestände, Gebühren), Buch
nie gekreuzt, alle Kurse auf dem Raster, Neustart. Vergleichswerte des Spielteils
in prt2-before.json neu erzeugt (feinere Schritte ändern den Kursverlauf).

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

274 lines
14 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.
import { avatar } from './avatar.js';
import { tickDec } from './ticksize.js';
/** 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 */
/** Kurs mit den Nachkommastellen seines Kursrasters (ticksize.js): unter 50 € drei, sonst zwei */
export const kurs = (x) => num(x, tickDec(x));
export const eur = (x, d = 2) => (x === null || x === undefined || !Number.isFinite(Number(x)) ? '–' : `${num(x, d)}\u00a0€`);
/** 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)}\u00a0%` : '–');
/** Anteil (0–1) als Prozent ohne Vorzeichen */
export const frac = (x, d = 1) => (Number.isFinite(x) ? `${num(x * 100, d)}\u00a0%` : '–');
/** 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>\u00a0${pct(x, d)}</span>`;
/** Betrag mit Pfeil */
export const chgEur = (x) => `<span class="${dirCls(x)}"><span aria-hidden="true">${arrow(x)}</span>\u00a0${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 */
/** Namen der computergesteuerten Rivalen (aus „hello“) – werden überall mit „KI“ gekennzeichnet */
export const rivalNames = new Set();
export function setRivals(list) { rivalNames.clear(); for (const n of list ?? []) rivalNames.add(n); }
export const kiBadge = '<span class="ki-badge" title="Computergesteuerter Rivale">KI</span>';
/** opt.av = Avatargröße in px (0 = ohne Avatar), opt.badge = Abzeichen für den Avatar (siehe avatar.js) */
export const player = (name, { av = 0, badge } = {}) => (name ? `<button type="button" class="plink${av ? ' has-av' : ''}" data-act="profile" data-name="${esc(name)}">${av ? `${avatar(name, { size: av, badge })}<span class="pl-n">${esc(name)}</span>` : esc(name)}</button>${rivalNames.has(name) ? ` ${kiBadge}` : ''}` : '–');
/** 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>`;
}
// Laufende Kennungen für SVG-Verläufe, Masken und Beschnitte: Jedes Zeichnen braucht neue, damit sie im
// Dokument eindeutig bleiben. Sie haben die feste Form „_g<zahl>_“ und werden beim Vergleich in patch()
// ausgeblendet – sonst sähe jedes Neuzeichnen wie eine Änderung aus und der ganze Bereich würde ersetzt.
let uidN = 0;
const UID_RE = /_g[0-9a-z]+_/g;
/** Neue, im Dokument eindeutige Kennung (Präfix wählbar), z. B. `ar_g1f_` */
export const uid = (prefix = '') => `${prefix}_g${(++uidN).toString(36)}_`;
/** HTML ohne die laufenden Kennungen aus uid() – Vergleichsschlüssel für patch() */
export const idFree = (html) => (html.includes('_g') ? html.replace(UID_RE, '_g_') : html);
/**
* Inhalt nur ersetzen, wenn er sich geändert hat; Fokus (per data-k oder id) bleibt erhalten.
* @param {Element|null} el @param {string} html
*/
// Aufklappbare Blöcke (<details>): Die Wahl des Spielers (auf/zu) überlebt das Neuzeichnen.
// Erkannt wird ein Block an data-k, id oder Klasse + Position unter Blöcken gleicher Klasse.
const detKey = (root, d) => d.dataset.k || d.id || `${d.className}:${[...root.querySelectorAll('details')].filter((x) => x.className === d.className).indexOf(d)}`;
// Hat der Bereich eine id, wird die Wahl auch über das Neuladen hinaus gespeichert (localStorage „wibo.details“).
const DET_STORE = 'details';
function watchDetails(el) {
if (el._det) return;
el._det = new Map();
if (el.id) for (const [k, v] of Object.entries(store.get(DET_STORE, {}) ?? {})) if (k.startsWith(`${el.id}|`)) el._det.set(k.slice(el.id.length + 1), !!v);
el.addEventListener('click', (e) => {
const sum = e.target.closest?.('summary');
if (!sum || !el.contains(sum) || e.target.closest('button, a, input, select')) return;
const d = sum.parentElement;
if (d?.tagName !== 'DETAILS') return;
const k = detKey(el, d), open = !d.open; // Zustand nach dem Umschalten
el._det.set(k, open);
if (el.id) {
const all = store.get(DET_STORE, {}) ?? {};
delete all[`${el.id}|${k}`];
all[`${el.id}|${k}`] = open;
const keys = Object.keys(all);
for (const x of keys.slice(0, Math.max(0, keys.length - 100))) delete all[x]; // höchstens 100 merken
store.set(DET_STORE, all);
}
});
}
/**
* Kinder von `from` an die von `to` angleichen, ohne Unverändertes anzufassen: Gleiche Knoten (gleicher Typ
* und Name an gleicher Stelle) bleiben erhalten, nur Texte und Attribute werden nachgezogen; Abweichendes
* wird ersetzt. So laufen Animationen weiter, Bilder blinken nicht und Fokus/Markierung bleiben stehen.
* Der Zustand „aufgeklappt“ von <details>, eingesetzte Fremdknoten (data-inj) und Eingaben, in denen gerade getippt wird, bleiben unberührt.
* @param {Node} from lebender Knoten @param {Node} to frisch erzeugter Knoten (wird dabei geleert)
* @returns {number} Zahl der geänderten Stellen
*/
// Von anderen Bausteinen nachträglich eingesetzte Knoten (data-inj, z. B. die „?“-Hilfeknöpfe an Überschriften)
// und deren Merker-Attribute überspringt morph(), sonst würden sie bei jedem Abgleich entfernt und neu gesetzt.
const KEEP_ATTR = new Set(['data-hq']);
export function morph(from, to) {
let n = 0;
const a = [...from.childNodes].filter((x) => !(x.nodeType === 1 && x.hasAttribute('data-inj'))), b = [...to.childNodes];
for (let i = 0; i < b.length; i++) {
const x = a[i], y = b[i];
if (!x) { from.appendChild(y); n++; continue; }
if (x.nodeType !== y.nodeType || x.nodeName !== y.nodeName) { x.replaceWith(y); n++; continue; }
if (x.nodeType !== 1) { if (x.data !== y.data) { x.data = y.data; n++; } continue; }
const typing = (x.nodeName === 'INPUT' || x.nodeName === 'TEXTAREA' || x.nodeName === 'SELECT') && x.ownerDocument?.activeElement === x;
for (const { name, value } of [...y.attributes]) {
if (x.getAttribute(name) !== value && !(typing && name === 'value')) { x.setAttribute(name, value); n++; }
}
for (const { name } of [...x.attributes]) {
if (!y.hasAttribute(name) && !KEEP_ATTR.has(name) && !(name === 'open' && x.nodeName === 'DETAILS')) { x.removeAttribute(name); n++; }
}
n += morph(x, y);
}
for (let i = b.length; i < a.length; i++) { a[i].remove(); n++; }
return n;
}
/**
* @param {Element|null} el @param {string} html
* @param {{morph?: boolean}} [o] morph: nur Geändertes im vorhandenen DOM nachziehen (für Ansichten, die
* laufend mit neuen Kursen gezeichnet werden), statt den ganzen Bereich zu ersetzen
*/
export function patch(el, html, { morph: soft = false } = {}) {
if (!el) return false;
const same = idFree(html);
if (el._html === same) return false;
watchDetails(el);
const a = document.activeElement;
const key = a && el.contains(a) ? (a.dataset?.k ?? (a.id ? `#${a.id}` : null)) : null;
if (soft && el._html) {
const t = document.createElement('template');
t.innerHTML = html;
morph(el, t.content);
} else el.innerHTML = html;
el._html = same;
if (el._det.size) for (const d of el.querySelectorAll('details')) { const o = el._det.get(detKey(el, d)); if (o !== undefined) d.open = o; }
if (key) {
const t = key.startsWith('#') ? el.querySelector(key) : el.querySelector(`[data-k="${CSS.escape(key)}"]`);
t?.focus({ preventScroll: true });
}
return true;
}
/** Text nur setzen, wenn er sich ändert (jede Zuweisung ersetzt sonst den Textknoten und erzwingt ein neues Layout) */
export function setText(el, s) {
if (el && el.textContent !== s) el.textContent = s;
}
/**
* Welche Zeilen einer Liste müssen neu? null = alles neu aufbauen (andere Zeilen, Reihenfolge oder Köpfe),
* sonst die Indizes der Zeilen, deren Endzellen (`tail`) sich geändert haben.
* @param {{k: string, head: string, tail: string}[]|undefined} prev @param {{k: string, head: string, tail: string}[]} items
* @returns {number[]|null}
*/
export function rowPlan(prev, items) {
if (!prev || prev.length !== items.length) return null;
const out = [];
for (let i = 0; i < items.length; i++) {
const a = prev[i], b = items[i];
if (a.k !== b.k || a.head !== b.head) return null;
if (a.tail !== b.tail) { if (!a.tail || !b.tail) return null; out.push(i); }
}
return out;
}
/**
* Tabellenkörper aus Zeilen {k, head, tail} (head: `<tr …><td>…</td>`, tail: die übrigen Zellen) zeichnen.
* Bleiben Schlüssel und Köpfe gleich (laufende Kursänderungen), werden nur die Endzellen der geänderten
* Zeilen ersetzt statt der ganzen Liste – wichtig für lange Listen, die jede Sekunde aktualisiert werden.
* @param {HTMLElement|null} el @param {{k: string, head: string, tail: string}[]} items
*/
export function patchRows(el, items) {
if (!el) return false;
const plan = el.children.length === (el._rows?.length ?? -1) ? rowPlan(el._rows, items) : null;
const html = items.map((r) => `${r.head}${r.tail}${r.tail ? '</tr>' : ''}`).join('');
if (!plan) { el._rows = items; return patch(el, html); }
if (!plan.length) return false;
const cells = (h) => { const t = document.createElement('tr'); t.innerHTML = h; return [...t.cells]; };
for (const i of plan) {
const tr = el.children[i];
// Endzellen enthalten nur Text (Kurs, Veränderung) – keine Bedienelemente, deren Fokus verloren ginge
for (let m = cells(el._rows[i].tail).length; m > 0 && tr.cells.length; m--) tr.deleteCell(-1);
tr.append(...cells(items[i].tail));
}
el._rows = items;
el._html = idFree(html);
return true;
}
/**
* Höhe eines Bereichs halten, der sich laufend ändert (Hinweise, Orderbuch …): Er darf wachsen,
* schrumpft aber nicht zurück, solange `key` gleich bleibt – so hüpft darunter nichts mehr.
* Ein neuer key (anderes Wertpapier, andere Ordertyp …) setzt die Höhe zurück.
* @param {HTMLElement|null} el @param {string} key
*/
export function keepHeight(el, key) {
if (!el) return;
if (el._khKey !== key) { el._khKey = key; el._khMax = 0; el.style.minHeight = ''; }
const h = el.offsetHeight;
if (h > el._khMax) { el._khMax = h; el.style.minHeight = `${h}px`; }
}
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 */ } },
};