Files
wibosim/server/public/js/chartzoom.js
T

247 lines
11 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.
// Bedienung für zoombare Canvas-Diagramme (Maus, Trackpad, Finger, Tastatur) – wiederverwendbar.
// Der Ausschnitt ist ein Bereich in Balken-Indizes (chartview.js). Das Diagramm (host) liefert Anzahl und Zeichenbreite
// und zeichnet bei Änderungen neu:
// host.count() Anzahl Balken
// host.plot() {w (Breite des Zeichenbereichs), axis (x ab der die Preisachse beginnt) }
// host.redraw() neu zeichnen (gebündelt per requestAnimationFrame)
// host.hover(pt|null) Fadenkreuz an Punkt {x, y} bzw. aus
// host.yScale(f) / host.yReset() senkrechte Streckung (Ziehen an der Preisachse)
// host.announce(text) optional: Text für Screenreader nach Tastaturbedienung
// Seite scrollt weiter, wenn senkrecht gewischt wird („touch-action: pan-y“); waagerechtes Wischen verschiebt,
// zwei Finger zoomen um ihre Mitte, langes Drücken zeigt das Fadenkreuz, doppeltes Tippen zeigt wieder alles.
import { clampView, zoomAt, panBy, pinchView, fullView, isFull, followData, defaultView } from './chartview.js';
const LONG_MS = 420; // langes Drücken → Fadenkreuz
const MOVE_PX = 7; // ab dieser Bewegung ist es kein Tippen mehr
const DOUBLE_MS = 320;
const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
// Ein per Finger gezeigtes Fadenkreuz bleibt stehen, bis woanders hingetippt wird
const touchedCtl = new Set();
if (typeof document !== 'undefined') {
document.addEventListener('pointerdown', (e) => {
for (const c of touchedCtl) if (e.target !== c.el) { touchedCtl.delete(c); c.host.hover(null); }
}, { capture: true, passive: true });
}
export class ZoomCtl {
/** @param {HTMLElement} el @param {object} host @param {{fit?: boolean}} [opt] */
constructor(el, host, opt = {}) {
this.el = el; this.host = host;
this.view = fullView(1);
this.mode = 'auto'; // auto = Standardansicht folgt den Daten; user = vom Spieler gewählt
this.fit = opt.fit ?? true;
this.pts = new Map();
this.g = null; // laufende Geste
this.inertia = 0;
this.lastTap = null;
this.ac = new AbortController();
const sig = { signal: this.ac.signal };
el.style.touchAction = 'pan-y';
el.addEventListener('pointerdown', (e) => this.down(e), sig);
el.addEventListener('pointermove', (e) => this.move(e), sig);
el.addEventListener('pointerup', (e) => this.up(e, false), sig);
el.addEventListener('pointercancel', (e) => this.up(e, true), sig);
el.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && !this.g) host.hover(null); }, sig);
el.addEventListener('dblclick', (e) => { e.preventDefault(); if (this.onAxis(this.pos(e).x)) host.yReset(); else this.reset(); }, sig);
el.addEventListener('wheel', (e) => this.wheel(e), { ...sig, passive: false });
// Safari: eigene Zoom-Gesten und Seitenbewegung unterbinden, solange der Chart die Geste bearbeitet
el.addEventListener('touchmove', (e) => { if (e.touches.length > 1 || (this.g && this.g.kind !== 'tap')) e.preventDefault(); }, { ...sig, passive: false });
el.addEventListener('gesturestart', (e) => e.preventDefault(), { ...sig, passive: false });
el.addEventListener('contextmenu', (e) => { if (this.g?.touch) e.preventDefault(); }, sig);
el.addEventListener('keydown', (e) => this.key(e), sig);
}
destroy() { this.ac.abort(); cancelAnimationFrame(this.inertia); touchedCtl.delete(this); }
// ---------------------------------------------------------------- Ausschnitt
n() { return Math.max(0, this.host.count()); }
/** Aktueller Ausschnitt (Standardansicht, solange der Spieler nichts verändert hat) */
get() {
if (this.mode === 'auto') this.view = defaultView(this.n(), this.host.plot().w, { fit: this.fit });
return this.view;
}
set(v) { this.view = clampView(v, this.n()); this.mode = 'user'; this.host.redraw(); }
zoomed() { return this.mode === 'user' && !isFull(this.view, this.n()); }
reset() { this.stop(); this.view = fullView(this.n()); this.mode = 'user'; this.host.yReset(); this.host.redraw(); }
/** Neue Daten: Ausschnitt fortschreiben (dropped = vorn weggefallene Balken, -1 = andere Daten → Standardansicht) */
data(oldN, newN, dropped) {
if (this.mode === 'auto') return;
if (dropped < 0) { this.mode = 'auto'; this.stop(); return; }
this.view = followData(this.view, oldN, newN, dropped);
}
/** Andere Daten (Wertpapier/Zeitraum): zurück zur Standardansicht */
restart(fit = this.fit) { this.fit = fit; this.mode = 'auto'; this.stop(); }
// ---------------------------------------------------------------- Zeiger
pos(e) { const r = this.el.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; }
onAxis(x) { return x >= this.host.plot().axis; }
stop() { if (this.inertia) { cancelAnimationFrame(this.inertia); this.inertia = 0; } }
down(e) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
this.stop();
const p = this.pos(e);
this.pts.set(e.pointerId, { ...p, x0: p.x, y0: p.y });
const touch = e.pointerType !== 'mouse';
try { this.el.setPointerCapture(e.pointerId); } catch { /* egal */ }
if (this.pts.size === 1) {
const v = this.get();
if (this.onAxis(p.x)) { this.g = { kind: 'yscale', y: p.y, touch }; return; }
this.g = { kind: touch ? 'tap' : 'pan', touch, v0: { ...v }, x0: p.x, t0: performance.now(), samples: [[performance.now(), v.a]] };
if (touch) {
clearTimeout(this.longT);
this.longT = setTimeout(() => {
if (this.g?.kind !== 'tap') return;
this.g.kind = 'cross';
touchedCtl.add(this);
this.host.hover(p);
}, LONG_MS);
}
} else if (this.pts.size === 2) {
clearTimeout(this.longT);
const [a, b] = [...this.pts.values()];
const v = this.get();
this.g = { kind: 'pinch', touch, v0: { ...v }, d0: Math.hypot(a.x - b.x, a.y - b.y), m0: (a.x + b.x) / 2 };
this.host.hover(null);
}
}
move(e) {
const p = this.pos(e);
if (!this.pts.has(e.pointerId)) {
if (e.pointerType === 'mouse' && !this.g) this.host.hover(p.x < this.host.plot().axis ? p : null);
return;
}
const q = this.pts.get(e.pointerId);
q.x = p.x; q.y = p.y;
const g = this.g;
if (!g) return;
const w = Math.max(1, this.host.plot().w), n = this.n();
if (g.kind === 'tap' && Math.hypot(p.x - q.x0, p.y - q.y0) > MOVE_PX) {
clearTimeout(this.longT);
// klar senkrecht: der Seite überlassen (sie scrollt), waagerecht: Chart verschieben
if (Math.abs(p.y - q.y0) > Math.abs(p.x - q.x0) * 1.2) { this.g = null; this.pts.delete(e.pointerId); return; }
g.kind = 'pan';
}
if (g.kind === 'pan') {
const span = g.v0.b - g.v0.a;
this.view = panBy(g.v0, -((p.x - g.x0) / w) * span, n);
this.mode = 'user';
const t = performance.now();
g.samples.push([t, this.view.a]);
while (g.samples.length > 2 && t - g.samples[0][0] > 100) g.samples.shift();
if (e.pointerType === 'mouse') this.host.hover(p);
this.host.redraw();
} else if (g.kind === 'cross') {
this.host.hover(p);
} else if (g.kind === 'pinch' && this.pts.size >= 2) {
const [a, b] = [...this.pts.values()];
const d = Math.hypot(a.x - b.x, a.y - b.y), m = (a.x + b.x) / 2;
this.view = pinchView(g.v0, g.d0, d, g.m0, m, w, n);
this.mode = 'user';
this.host.redraw();
} else if (g.kind === 'yscale') {
const dy = p.y - g.y;
g.y = p.y;
if (dy) this.host.yScale(Math.exp(dy * 0.006));
}
}
up(e, cancel) {
if (!this.pts.has(e.pointerId)) return;
this.pts.delete(e.pointerId);
clearTimeout(this.longT);
const g = this.g;
if (!g) return;
if (g.kind === 'pinch') {
// ein Finger bleibt liegen → nahtlos weiter verschieben
const rest = [...this.pts.values()][0];
this.g = rest ? { kind: 'pan', touch: true, v0: { ...this.view }, x0: rest.x, t0: performance.now(), samples: [[performance.now(), this.view.a]] } : null;
return;
}
if (this.pts.size) return;
this.g = null;
if (cancel) { if (g.touch && g.kind !== 'cross') this.host.hover(null); return; }
if (g.kind === 'tap') {
const p = this.pos(e), t = performance.now();
const lt = this.lastTap;
if (lt && t - lt.t < DOUBLE_MS && Math.hypot(p.x - lt.x, p.y - lt.y) < 30) {
this.lastTap = null; touchedCtl.delete(this); this.host.hover(null); this.reset(); return;
}
this.lastTap = { t, x: p.x, y: p.y };
touchedCtl.add(this);
this.host.hover(p);
} else if (g.kind === 'pan') this.fling(g);
}
/** Trägheit: nach dem Loslassen dezent auslaufen lassen (nicht bei „Bewegung reduzieren“) */
fling(g) {
if (reduced() || g.samples.length < 2) return;
const [t0, a0] = g.samples[0], [t1, a1] = g.samples[g.samples.length - 1];
if (performance.now() - t1 > 60 || t1 - t0 < 8) return;
let vel = (a1 - a0) / (t1 - t0); // Balken je ms
const w = Math.max(1, this.host.plot().w);
const pxPerBar = w / (this.view.b - this.view.a);
if (Math.abs(vel * pxPerBar) < 0.25) return; // langsames Ziehen läuft nicht nach
let last = performance.now();
const step = (t) => {
const dt = Math.min(48, t - last); last = t;
const before = this.view.a;
this.view = panBy(this.view, vel * dt, this.n());
vel *= Math.exp(-dt * 0.0045);
this.host.redraw();
if (Math.abs(vel * pxPerBar) < 0.02 || this.view.a === before) { this.inertia = 0; return; }
this.inertia = requestAnimationFrame(step);
};
this.inertia = requestAnimationFrame(step);
}
wheel(e) {
const n = this.n();
if (n < 2) return;
e.preventDefault();
this.stop();
const p = this.pos(e);
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1;
const dx = e.deltaX * unit, dy = e.deltaY * unit;
const { w } = this.host.plot();
if (this.onAxis(p.x) && !e.ctrlKey) { this.host.yScale(Math.exp(dy * 0.0015)); return; }
const v = this.get();
if (!e.ctrlKey && (Math.abs(dx) > Math.abs(dy) || e.shiftKey)) {
const d = Math.abs(dx) > Math.abs(dy) ? dx : dy;
this.view = panBy(v, (d / Math.max(1, w)) * (v.b - v.a), n);
} else {
// Mausrad: ein Raster ≈ 12 % Zoom; Trackpad (Strg + Pinch) feiner
const k = e.ctrlKey ? 0.01 : 0.0012;
this.view = zoomAt(v, Math.exp(Math.max(-0.5, Math.min(0.5, dy * k))), p.x / Math.max(1, w), n);
}
this.mode = 'user';
this.host.hover(p.x < this.host.plot().axis ? p : null);
this.host.redraw();
}
key(e) {
if (e.altKey || e.metaKey || e.ctrlKey) return;
const n = this.n();
const v = this.get(), span = v.b - v.a;
let next = null, msg = '';
switch (e.key) {
case 'ArrowLeft': next = panBy(v, -Math.max(1, span * (e.shiftKey ? 0.5 : 0.1)), n); msg = 'verschoben'; break;
case 'ArrowRight': next = panBy(v, Math.max(1, span * (e.shiftKey ? 0.5 : 0.1)), n); msg = 'verschoben'; break;
case '+': case '=': next = zoomAt(v, 0.8, 0.5, n); msg = 'vergrößert'; break;
case '-': case '_': next = zoomAt(v, 1.25, 0.5, n); msg = 'verkleinert'; break;
case 'End': next = panBy(v, n, n); msg = 'neueste Kurse'; break;
case 'Home': next = panBy(v, -n, n); msg = 'älteste Kurse'; break;
case '0': this.reset(); this.host.announce?.('Ganzer Zeitraum'); e.preventDefault(); return;
default: return;
}
e.preventDefault();
this.stop();
this.view = next; this.mode = 'user';
this.host.redraw();
this.host.announce?.(msg);
}
}