Files
wibosim/server/public/js/charts.js
T
db9979andClaude Opus 5.5 9544fe6911 Client: Hell- und Dunkelmodus, Begründung unter Nachrichten, Probeauswertung im Admin
- Farbschema System/Hell/Dunkel (Knopf in der Kopfleiste und in den Einstellungen), ohne Aufblitzen beim Laden
- Alle Farben als Variablen, Diagramme lesen die Farben beim Zeichnen und folgen dem Schema
- Nachrichten: Themen mit Pfeil, Eilmeldung, Folgemeldung, KI-Analyse und „Warum?“ mit bewegten Werten
- Admin: Schlagzeile mit Regelwerk und Sprachmodell testen, Status der KI-Auswertung

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

352 lines
18 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.
// Eigene Canvas-Diagramme (ohne Bibliotheken): Kerzenchart mit Volumen und Fadenkreuz, Linienchart für Battles.
import { num, int, time, date } from './util.js';
const css = (name, fb) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fb;
/** Farbangabe auflösen: „var(--name)“ wird zur Zeichenzeit aus dem aktuellen Farbschema gelesen */
const paintColor = (c, fb) => {
const m = /^var\((--[\w-]+)\)$/.exec(String(c ?? '').trim());
return m ? css(m[1], fb) : (c ?? fb);
};
// Alle Diagramme merken, um sie beim Wechsel des Farbschemas (Ereignis „wibo:theme“ aus theme.js) neu zu zeichnen.
const charts = new Set();
document.addEventListener('wibo:theme', () => {
for (const ch of charts) {
if (!ch.c.isConnected) { charts.delete(ch); continue; }
try { ch.draw(); } catch (e) { console.error('[chart]', e); }
}
});
class Base {
/** @param {HTMLCanvasElement} canvas */
constructor(canvas) {
this.c = canvas;
this.ctx = canvas.getContext('2d');
this.hover = null;
charts.add(this);
this.ro = new ResizeObserver(() => this.draw());
this.ro.observe(canvas.parentElement ?? canvas);
canvas.addEventListener('mousemove', (e) => { const r = canvas.getBoundingClientRect(); this.hover = { x: e.clientX - r.left, y: e.clientY - r.top }; this.draw(); });
canvas.addEventListener('mouseleave', () => { this.hover = null; this.draw(); });
}
size() {
const r = this.c.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const w = Math.max(10, Math.round(r.width)), h = Math.max(10, Math.round(r.height));
if (this.c.width !== w * dpr || this.c.height !== h * dpr) { this.c.width = w * dpr; this.c.height = h * dpr; }
this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
return { w, h };
}
colors() {
return { up: css('--up', '#22c55e'), down: css('--down', '#ef4444'), text: css('--muted', '#8b97ad'), line: css('--line', '#222c42'), accent: css('--accent', '#3b82f6'), gold: css('--gold', '#f5b942'), fg: css('--text', '#dfe6f3'), bg: css('--panel', '#121826'), onSignal: css('--on-signal', '#0b0f17'), tip: css('--tip-bg', '#0d1422') };
}
}
/** „schöne“ Achsenschritte */
function niceStep(range, n) {
const raw = range / Math.max(1, n);
const p = 10 ** Math.floor(Math.log10(raw));
const m = raw / p;
return (m < 1.5 ? 1 : m < 3 ? 2 : m < 7 ? 5 : 10) * p;
}
export class CandleChart extends Base {
constructor(canvas) { super(canvas); this.bars = []; this.opt = {}; }
/** @param {{t:number,o:number,h:number,l:number,c:number,v:number}[]} bars @param {{daily?: boolean, last?: number, indicative?: number|null, prevClose?: number, empty?: string}} opt */
set(bars, opt = {}) { this.bars = bars ?? []; this.opt = opt; this.draw(); }
draw() {
const { w, h } = this.size();
const ctx = this.ctx, col = this.colors();
ctx.clearRect(0, 0, w, h);
ctx.font = '12px system-ui, sans-serif';
const axisW = 64, padT = 10, timeH = 18;
const volH = Math.max(28, Math.round(h * 0.16));
const plotW = w - axisW - 6, priceH = h - padT - timeH - volH - 6;
const maxBars = Math.max(10, Math.floor(plotW / 7));
const bars = this.bars.slice(-maxBars);
if (!bars.length) {
ctx.fillStyle = col.text;
ctx.textAlign = 'center';
ctx.fillText(this.opt.empty ?? 'Noch keine Kursdaten', w / 2, h / 2);
return;
}
let lo = Infinity, hi = -Infinity, vmax = 1;
for (const b of bars) { lo = Math.min(lo, b.l); hi = Math.max(hi, b.h); vmax = Math.max(vmax, b.v ?? 0); }
for (const extra of [this.opt.indicative, this.opt.prevClose]) if (Number.isFinite(extra)) { lo = Math.min(lo, extra); hi = Math.max(hi, extra); }
if (hi - lo < hi * 0.002) { hi += hi * 0.002; lo -= lo * 0.002; }
const padP = (hi - lo) * 0.06; hi += padP; lo -= padP;
const y = (p) => padT + (hi - p) / (hi - lo) * priceH;
const slot = plotW / maxBars;
const x0 = plotW - bars.length * slot;
const bw = Math.max(1, Math.min(12, slot * 0.7));
// Raster + Preisachse
ctx.strokeStyle = col.line; ctx.fillStyle = col.text; ctx.lineWidth = 1; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
const step = niceStep(hi - lo, 5);
const dec = step < 0.1 ? 2 : step < 1 ? 2 : step < 10 ? 1 : 0;
for (let p = Math.ceil(lo / step) * step; p <= hi; p += step) {
const yy = Math.round(y(p)) + 0.5;
ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(plotW, yy); ctx.stroke();
ctx.fillText(num(p, dec), plotW + 6, yy);
}
// Vortagesschluss
if (Number.isFinite(this.opt.prevClose) && !this.opt.daily) {
ctx.setLineDash([2, 4]); ctx.strokeStyle = col.text;
const yy = Math.round(y(this.opt.prevClose)) + 0.5;
ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(plotW, yy); ctx.stroke();
ctx.setLineDash([]);
}
// Kerzen + Volumen
const volTop = padT + priceH + 6;
bars.forEach((b, i) => {
const cx = x0 + i * slot + slot / 2;
const up = b.c >= b.o;
ctx.strokeStyle = ctx.fillStyle = up ? col.up : col.down;
ctx.beginPath(); ctx.moveTo(Math.round(cx) + 0.5, y(b.h)); ctx.lineTo(Math.round(cx) + 0.5, y(b.l)); ctx.stroke();
const top = y(Math.max(b.o, b.c)), bh = Math.max(1, Math.abs(y(b.o) - y(b.c)));
if (up) { ctx.lineWidth = 1; ctx.strokeRect(Math.round(cx - bw / 2) + 0.5, Math.round(top) + 0.5, Math.round(bw) - 1 || 1, Math.round(bh)); ctx.globalAlpha = 0.35; ctx.fillRect(Math.round(cx - bw / 2), Math.round(top), Math.round(bw), Math.round(bh)); ctx.globalAlpha = 1; }
else ctx.fillRect(Math.round(cx - bw / 2), Math.round(top), Math.round(bw), Math.round(bh));
const vh = ((b.v ?? 0) / vmax) * volH;
ctx.globalAlpha = 0.45;
ctx.fillRect(Math.round(cx - bw / 2), volTop + volH - vh, Math.round(bw), vh);
ctx.globalAlpha = 1;
});
// Zeitachse
ctx.fillStyle = col.text; ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
const every = Math.max(1, Math.ceil(80 / slot));
for (let i = bars.length - 1; i >= 0; i -= every) {
const cx = x0 + i * slot + slot / 2;
if (cx < 24) break;
ctx.fillText(this.opt.daily ? (bars[i].label ?? date(bars[i].t)) : time(bars[i].t), cx, h - 4);
}
// letzter Kurs / indikativer Preis
const mark = (p, color, label) => {
if (!Number.isFinite(p)) return;
const yy = Math.round(y(p)) + 0.5;
ctx.strokeStyle = color; ctx.setLineDash([4, 3]);
ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(plotW, yy); ctx.stroke(); ctx.setLineDash([]);
ctx.fillStyle = color; ctx.fillRect(plotW + 2, yy - 9, axisW - 2, 18);
ctx.fillStyle = col.onSignal; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(label ?? num(p, 2), plotW + 5, yy);
};
const lastBar = bars[bars.length - 1];
if (!this.opt.daily) mark(this.opt.last ?? lastBar.c, lastBar.c >= (bars[0].o) ? col.up : col.down);
if (Number.isFinite(this.opt.indicative)) mark(this.opt.indicative, col.gold, `≈${num(this.opt.indicative, 2)}`);
// Fadenkreuz mit OHLC
if (this.hover && this.hover.x < plotW) {
const i = Math.floor((this.hover.x - x0) / slot);
const b = bars[i];
if (b) {
const cx = Math.round(x0 + i * slot + slot / 2) + 0.5;
ctx.strokeStyle = col.text; ctx.setLineDash([3, 3]);
ctx.beginPath(); ctx.moveTo(cx, padT); ctx.lineTo(cx, volTop + volH); ctx.stroke();
ctx.beginPath(); ctx.moveTo(0, Math.round(this.hover.y) + 0.5); ctx.lineTo(plotW, Math.round(this.hover.y) + 0.5); ctx.stroke();
ctx.setLineDash([]);
const txt = `${this.opt.daily ? (b.label ?? date(b.t)) : time(b.t)} E ${num(b.o)} H ${num(b.h)} T ${num(b.l)} S ${num(b.c)} Vol ${int(b.v ?? 0)}`;
ctx.font = '12px ui-monospace, monospace';
const tw = ctx.measureText(txt).width + 12;
ctx.fillStyle = col.tip; ctx.globalAlpha = 0.9; ctx.fillRect(4, 2, tw, 18); ctx.globalAlpha = 1;
ctx.fillStyle = col.fg; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(txt, 10, 11);
}
}
}
}
// ================================================================ Kleine Diagramme mit Zeichenfunktion
/** Canvas mit austauschbarer Zeichenfunktion – überlebt Neuzeichnen bei Größenänderung */
class FnChart extends Base {
constructor(canvas) { super(canvas); this.fn = null; }
set(fn) { this.fn = fn; this.draw(); }
draw() {
if (!this.c.isConnected) { this.ro.disconnect(); return; }
const { w, h } = this.size();
this.ctx.clearRect(0, 0, w, h);
this.ctx.font = '12px system-ui, sans-serif';
this.ctx.setLineDash([]);
this.fn?.(this.ctx, w, h, this.colors(), this.hover);
}
}
const fnCharts = new WeakMap();
/** Zeichenfunktion an ein Canvas hängen (wiederverwendbar nach patch()) */
export function paint(canvas, fn) {
if (!canvas) return;
let c = fnCharts.get(canvas);
if (!c) { c = new FnChart(canvas); fnCharts.set(canvas, c); }
c.set(fn);
}
/**
* XY-Linien: series [{name, color, dash?, points [{x, y}]}]
* opt: {yFmt, xFmt, xTicks [x], xScale (x→x'), hlines [{y, label, color}], marks [{x, y, label, color}], yMin, yMax, legend, empty}
*/
export function lineChart(series, opt = {}) {
return (ctx, w, h, col, hover) => {
const pts = series.flatMap((s) => s.points);
if (!pts.length) { ctx.fillStyle = col.text; ctx.textAlign = 'center'; ctx.fillText(opt.empty ?? 'Noch keine Daten', w / 2, h / 2); return; }
const xs = opt.xScale ?? ((x) => x);
const axisW = 46, padT = opt.legend ? 22 : 8, padB = 18, plotW = w - axisW - 8, plotH = h - padT - padB;
let lo = Math.min(...pts.map((p) => p.y), ...(opt.hlines ?? []).map((l) => l.y)), hi = Math.max(...pts.map((p) => p.y), ...(opt.hlines ?? []).map((l) => l.y));
if (opt.yMin !== undefined) lo = Math.min(lo, opt.yMin);
if (opt.yMax !== undefined) hi = Math.max(hi, opt.yMax);
if (hi - lo < 1e-6) { hi += 0.5; lo -= 0.5; }
const pad = (hi - lo) * 0.08; hi += pad; lo -= pad;
const x0 = Math.min(...pts.map((p) => xs(p.x))), x1 = Math.max(...pts.map((p) => xs(p.x)));
const X = (x) => axisW + (x1 === x0 ? plotW / 2 : ((xs(x) - x0) / (x1 - x0)) * plotW);
const Y = (y) => padT + ((hi - y) / (hi - lo)) * plotH;
const yFmt = opt.yFmt ?? ((v) => num(v, 1));
ctx.strokeStyle = col.line; ctx.fillStyle = col.text; ctx.lineWidth = 1; ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
const step = niceStep(hi - lo, 4);
for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) {
const yy = Math.round(Y(v)) + 0.5;
ctx.beginPath(); ctx.moveTo(axisW, yy); ctx.lineTo(axisW + plotW, yy); ctx.stroke();
ctx.fillText(yFmt(v, step), axisW - 6, yy);
}
ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
const xFmt = opt.xFmt ?? ((x) => String(x));
const ticks = opt.xTicks ?? [pts[0].x, pts[pts.length - 1].x];
for (const t of ticks) ctx.fillText(xFmt(t), Math.min(w - 20, Math.max(axisW + 14, X(t))), h - 4);
for (const l of opt.hlines ?? []) {
const yy = Math.round(Y(l.y)) + 0.5;
const lc = paintColor(l.color, col.text);
ctx.strokeStyle = lc; ctx.setLineDash([4, 4]);
ctx.beginPath(); ctx.moveTo(axisW, yy); ctx.lineTo(axisW + plotW, yy); ctx.stroke(); ctx.setLineDash([]);
if (l.label) { ctx.fillStyle = lc; ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'; ctx.fillText(l.label, axisW + 4, yy - 2); }
}
const palette = [col.accent, col.gold, col.up, col.down];
let lx = axisW;
series.forEach((s, i) => {
const c = paintColor(s.color, palette[i % palette.length]);
ctx.strokeStyle = c; ctx.fillStyle = c; ctx.lineWidth = 2; ctx.setLineDash(s.dash ?? []);
ctx.beginPath();
s.points.forEach((p, j) => (j ? ctx.lineTo(X(p.x), Y(p.y)) : ctx.moveTo(X(p.x), Y(p.y))));
ctx.stroke(); ctx.setLineDash([]); ctx.lineWidth = 1;
if (s.points.length <= 12) for (const p of s.points) { ctx.beginPath(); ctx.arc(X(p.x), Y(p.y), 2.5, 0, 7); ctx.fill(); }
if (opt.legend) {
ctx.fillRect(lx, 8, 12, 3);
ctx.fillStyle = col.fg; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(s.name, lx + 16, 10);
lx += ctx.measureText(s.name).width + 30;
}
});
for (const m of opt.marks ?? []) {
const xx = X(m.x), yy = Y(m.y);
ctx.fillStyle = paintColor(m.color, col.gold); ctx.strokeStyle = col.bg; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(xx, yy, 5, 0, 7); ctx.fill(); ctx.stroke(); ctx.lineWidth = 1;
ctx.fillStyle = col.fg; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom';
ctx.fillText(m.label, Math.min(w - 30, Math.max(axisW + 30, xx)), yy - 8);
}
if (hover && hover.x > axisW && opt.hoverFmt) {
let best = null, bd = Infinity;
for (const p of pts) { const d = Math.abs(X(p.x) - hover.x); if (d < bd) { bd = d; best = p; } }
if (best) {
const txt = opt.hoverFmt(best);
ctx.font = '12px ui-monospace, monospace';
const tw = ctx.measureText(txt).width + 12;
const bx = Math.min(w - tw - 2, Math.max(2, X(best.x) - tw / 2));
ctx.fillStyle = col.tip; ctx.globalAlpha = 0.9; ctx.fillRect(bx, padT, tw, 18); ctx.globalAlpha = 1;
ctx.fillStyle = col.fg; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText(txt, bx + 6, padT + 9);
}
}
};
}
/** Halbkreis-Sitzverteilung: parties [{short, color, seats, coalition}] in Reihenfolge links → rechts */
export function hemicycle(parties, total) {
return (ctx, w, h, col) => {
const cx = w / 2, cy = h - 6;
const R = Math.min(w / 2 - 6, h - 12), r0 = R * 0.38;
const rows = Math.max(4, Math.round(Math.sqrt(total / 3.2)));
const radii = Array.from({ length: rows }, (_, i) => r0 + ((R - r0) * (i + 0.5)) / rows);
const sumR = radii.reduce((a, x) => a + x, 0);
const spots = [];
let left = total;
radii.forEach((r, i) => {
const n = i === rows - 1 ? left : Math.round((total * r) / sumR);
left -= n;
for (let k = 0; k < n; k++) {
const a = Math.PI - (Math.PI * (k + 0.5)) / n;
spots.push({ a, x: cx + r * Math.cos(a), y: cy - r * Math.sin(a) });
}
});
spots.sort((p, q) => q.a - p.a);
const dot = Math.max(1.5, Math.min(7, ((R - r0) / rows) * 0.38));
let i = 0;
for (const p of parties) {
for (let k = 0; k < p.seats && i < spots.length; k++, i++) {
const s = spots[i];
ctx.fillStyle = paintColor(p.color, col.text);
ctx.beginPath(); ctx.arc(s.x, s.y, dot, 0, 7); ctx.fill();
if (p.coalition) { ctx.strokeStyle = col.fg; ctx.lineWidth = 1; ctx.stroke(); }
}
}
ctx.fillStyle = col.fg; ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
ctx.font = 'bold 18px system-ui, sans-serif';
ctx.fillText(String(total), cx, cy - 18);
ctx.font = '12px system-ui, sans-serif'; ctx.fillStyle = col.text;
ctx.fillText(`Mehrheit ab ${Math.floor(total / 2) + 1}`, cx, cy - 2);
};
}
/** Linienchart (z. B. Battle-Verlauf in %) */
export class LineChart extends Base {
constructor(canvas) { super(canvas); this.series = []; this.opt = {}; }
/** @param {{name: string, color?: string, points: {t:number, v:number}[]}[]} series */
set(series, opt = {}) { this.series = series ?? []; this.opt = opt; this.draw(); }
draw() {
const { w, h } = this.size();
const ctx = this.ctx, col = this.colors();
ctx.clearRect(0, 0, w, h);
ctx.font = '12px system-ui, sans-serif';
const pts = this.series.flatMap((s) => s.points);
if (pts.length < 1) { ctx.fillStyle = col.text; ctx.textAlign = 'center'; ctx.fillText(this.opt.empty ?? 'Verlauf erscheint nach den ersten Messpunkten', w / 2, h / 2); return; }
const axisW = 56, padT = 22, padB = 18, plotW = w - axisW - 4, plotH = h - padT - padB;
let lo = Math.min(0, ...pts.map((p) => p.v)), hi = Math.max(0, ...pts.map((p) => p.v));
if (hi - lo < 0.2) { hi += 0.1; lo -= 0.1; }
const t0 = Math.min(...pts.map((p) => p.t)), t1 = Math.max(this.opt.tEnd ?? 0, ...pts.map((p) => p.t));
const x = (t) => (t1 === t0 ? plotW / 2 : ((t - t0) / (t1 - t0)) * plotW);
const y = (v) => padT + ((hi - v) / (hi - lo)) * plotH;
ctx.strokeStyle = col.line; ctx.fillStyle = col.text; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
const step = niceStep(hi - lo, 4);
for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) {
const yy = Math.round(y(v)) + 0.5;
ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(plotW, yy); ctx.stroke();
ctx.fillText(`${num(v, step < 0.1 ? 2 : step < 1 ? 1 : 0)} %`, plotW + 6, yy);
}
ctx.strokeStyle = col.text; ctx.beginPath(); ctx.moveTo(0, Math.round(y(0)) + 0.5); ctx.lineTo(plotW, Math.round(y(0)) + 0.5); ctx.stroke();
const palette = [col.accent, col.gold, col.up, col.down];
let lx = 6;
this.series.forEach((s, i) => {
const c = paintColor(s.color, palette[i % palette.length]);
ctx.strokeStyle = c; ctx.lineWidth = 2; ctx.setLineDash(i === 1 ? [6, 3] : []);
ctx.beginPath();
s.points.forEach((p, j) => (j ? ctx.lineTo(x(p.t), y(p.v)) : ctx.moveTo(x(p.t), y(p.v))));
if (s.points.length === 1) ctx.arc(x(s.points[0].t), y(s.points[0].v), 2, 0, 7);
ctx.stroke(); ctx.setLineDash([]); ctx.lineWidth = 1;
// Legende (Linienstil unterscheidet zusätzlich zur Farbe)
ctx.fillStyle = c; ctx.fillRect(lx, 8, 14, 3);
ctx.fillStyle = col.fg; ctx.textBaseline = 'middle';
const lab = `${s.name}${s.points.length ? ` ${num(s.points[s.points.length - 1].v, 2)} %` : ''}`;
ctx.fillText(lab, lx + 18, 10);
lx += ctx.measureText(lab).width + 40;
});
ctx.fillStyle = col.text; ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
ctx.fillText(time(t0), 20, h - 3);
ctx.fillText(time(t1), plotW - 20, h - 3);
}
}
/** Zinskurve mit Markierungen bei 2 und 10 Jahren */
export function curveChart(cv) {
if (!cv?.points?.length) return lineChart([], { empty: 'Keine Zinskurve' });
const tf = (T) => (T < 1 ? `${Math.round(T * 12)} M` : `${T} J`);
return lineChart([{ name: 'Rendite', points: cv.points.map((p) => ({ x: p.T, y: p.y })) }], {
xScale: Math.sqrt, xTicks: [0.25, 2, 5, 10, 30].filter((T) => cv.points.some((p) => p.T === T)), xFmt: tf,
yFmt: (v, step) => `${num(v, step < 0.1 ? 2 : 1)} %`,
marks: [{ x: 2, y: cv.y2, label: `2 J. ${num(cv.y2, 2)} %` }, { x: 10, y: cv.y10, label: `10 J. ${num(cv.y10, 2)} %` }],
hoverFmt: (p) => `${tf(p.x)}: ${num(p.y, 2)} %`,
});
}