MBO-Tech-IT-Webseite/components/AsciiField.tsx

258 lines
8.4 KiB
TypeScript
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.

"use client";
import { useEffect, useRef, useState } from "react";
import { Pause, Play } from "lucide-react";
/*
* Das ASCII-Feld des Hero (Theme Cobalt): ein Zeichenraster auf 8 × 16 px.
* Links bleibt es ruhig (dort steht der Text), in der Mitte rauscht ein ungeordnetes
* Netz, rechts laufen daraus geordnete Leitungen in die Stack-Labels (.hero__stack li).
* Läuft mit 30 fps, pausiert außerhalb des Sichtfelds, per Taste und bei reduzierter Bewegung.
*/
const CW = 8;
const CH = 16;
const RAMP = " .:-=+*#%@";
function hash(x: number, y: number) {
let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263)) | 0;
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967295;
}
function fade(t: number) {
return t * t * (3 - 2 * t);
}
function noise(x: number, y: number) {
const xi = Math.floor(x);
const yi = Math.floor(y);
const u = fade(x - xi);
const v = fade(y - yi);
const a = hash(xi, yi);
const b = hash(xi + 1, yi);
const c = hash(xi, yi + 1);
const d = hash(xi + 1, yi + 1);
return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
}
function smoothstep(e0: number, e1: number, x: number) {
const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));
return t * t * (3 - 2 * t);
}
type Line = { x: number; y: number; i: number };
export default function AsciiField() {
const wrapRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const heldRef = useRef(false);
const syncRef = useRef<() => void>(() => {});
const [live, setLive] = useState(false);
const [held, setHeld] = useState(false);
const [canPause, setCanPause] = useState(false);
useEffect(() => {
const wrap = wrapRef.current;
const canvas = canvasRef.current;
const hero = wrap?.parentElement;
if (!wrap || !canvas || !hero) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
const wide = window.matchMedia("(min-width: 60.01rem)");
const fine = window.matchMedia("(pointer: fine)");
let W = 0;
let H = 0;
let lines: Line[] = [];
let colors: string[] = [];
let family = "monospace";
let pointer: { x: number; y: number } | null = null;
let visible = true;
let raf = 0;
let last = 0;
let t0 = performance.now();
let tPaused = 0;
const readColors = () => {
const cs = getComputedStyle(document.documentElement);
colors = ["--color-glyph-1", "--color-glyph-2", "--color-glyph-3", "--color-glyph-4", "--color-accent-deep"].map((n) =>
cs.getPropertyValue(n).trim()
);
family = getComputedStyle(canvas).fontFamily || "monospace";
};
const measure = () => {
const r = hero.getBoundingClientRect();
W = r.width;
H = r.height;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
lines = [];
if (wide.matches) {
hero.querySelectorAll<HTMLElement>(".hero__stack li").forEach((li, i) => {
const b = li.getBoundingClientRect();
lines.push({ x: b.left - r.left - CW * 2, y: b.top - r.top + b.height / 2, i });
});
}
};
const draw = (t: number) => {
ctx.clearRect(0, 0, W, H);
ctx.font = `12px ${family}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const narrow = !wide.matches;
const cx = narrow ? W * 0.78 : W * 0.6;
const cy = narrow ? H * 0.07 : H * 0.47;
const rx = W * (narrow ? 0.28 : 0.15);
const ry = H * (narrow ? 0.08 : 0.33);
const lineStart = cx + rx * 0.35;
const calmEnd = W * (narrow ? 0.45 : 0.34);
const calmFull = W * (narrow ? 0.9 : 0.58);
const buckets: [string, number, number][][] = [[], [], [], [], []];
const cols = Math.ceil(W / CW);
const rows = Math.ceil(H / CH);
for (let r = 0; r < rows; r++) {
const py = r * CH + CH / 2;
let row: Line | null = null;
for (const L of lines) if (Math.abs(py - L.y) < CH / 2) row = L;
for (let c = 0; c < cols; c++) {
const px = c * CW + CW / 2;
const f = smoothstep(calmEnd, calmFull, px);
const lens = pointer ? Math.exp(-((px - pointer.x) ** 2 + (py - pointer.y) ** 2) / (2 * 64 * 64)) : 0;
if (f === 0 && lens < 0.05) continue;
let d = Math.pow(noise(px * 0.018 + t * 0.25, py * 0.03 - t * 0.1), 5) * 0.55 * f;
const dx = (px - cx) / rx;
const dy = (py - cy) / ry;
const g = Math.exp(-(dx * dx + dy * dy) * 1.6);
if (g > 0.01) d = Math.max(d, g * (0.3 + 0.9 * noise(px * 0.045 - t * 0.6, py * 0.06 + t * 0.3)));
let isLine = false;
if (row && px > lineStart && px < row.x) {
const along = (px - lineStart) / (row.x - lineStart);
const pulse = Math.max(0, Math.sin(px * 0.035 - t * 5 + row.i * 1.7));
d = Math.max(d, 0.42 + 0.12 * (1 - along) + 0.5 * Math.pow(pulse, 6));
isLine = true;
}
d = Math.min(0.999, d + lens * 0.55 * Math.max(f, 0.25));
if (d < 0.1) continue;
const ch = isLine ? (d > 0.8 ? "=" : "-") : RAMP[Math.floor(d * RAMP.length)];
if (ch === " ") continue;
const b = d < 0.3 ? 0 : d < 0.5 ? 1 : d < 0.68 ? 2 : d < 0.86 ? 3 : 4;
buckets[b].push([ch, px, py]);
}
}
buckets.forEach((cells, i) => {
if (!cells.length) return;
ctx.fillStyle = colors[i] || "currentColor";
for (const [ch, x, y] of cells) ctx.fillText(ch, x, y);
});
};
const running = () => visible && !heldRef.current && !reduced.matches;
const loop = (now: number) => {
raf = 0;
if (!running()) return;
if (now - last >= 33) {
last = now;
draw((now - t0) / 1000);
}
raf = requestAnimationFrame(loop);
};
const sync = () => {
if (running()) {
if (!raf) {
t0 = performance.now() - tPaused * 1000;
raf = requestAnimationFrame(loop);
}
} else {
if (raf) cancelAnimationFrame(raf);
raf = 0;
tPaused = (performance.now() - t0) / 1000;
draw(reduced.matches ? 2.4 : tPaused);
}
};
syncRef.current = sync;
readColors();
measure();
draw(reduced.matches ? 2.4 : 0);
setLive(true);
setCanPause(!reduced.matches);
sync();
const onResize = () => {
measure();
if (!running()) draw(reduced.matches ? 2.4 : tPaused);
};
const ro = new ResizeObserver(onResize);
ro.observe(hero);
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(hero);
const mo = new MutationObserver(() => {
readColors();
if (!running()) draw(reduced.matches ? 2.4 : tPaused);
});
mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
const onMove = (e: PointerEvent) => {
if (!fine.matches) return;
const r = hero.getBoundingClientRect();
pointer = { x: e.clientX - r.left, y: e.clientY - r.top };
};
const onLeave = () => {
pointer = null;
};
hero.addEventListener("pointermove", onMove);
hero.addEventListener("pointerleave", onLeave);
const onMotion = () => {
setCanPause(!reduced.matches);
sync();
};
reduced.addEventListener("change", onMotion);
return () => {
if (raf) cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
mo.disconnect();
hero.removeEventListener("pointermove", onMove);
hero.removeEventListener("pointerleave", onLeave);
reduced.removeEventListener("change", onMotion);
};
}, []);
const toggle = () => {
heldRef.current = !heldRef.current;
setHeld(heldRef.current);
syncRef.current();
};
return (
<>
<div ref={wrapRef} className={`hero__field${live ? " is-live" : ""}`} aria-hidden="true">
<canvas ref={canvasRef} className="font-mono" />
</div>
{canPause && (
<button type="button" className="hero__pause" onClick={toggle} aria-pressed={held}>
{held ? <Play className="icon--s" aria-hidden="true" /> : <Pause className="icon--s" aria-hidden="true" />}
{held ? "Animation fortsetzen" : "Animation anhalten"}
</button>
)}
</>
);
}