"use client";
import { useEffect, useRef, useState } from "react";
/**
* Heat Map — an original take inspired by bencho.dev's "Heat map".
* A grey shape drawn as a soft field. Moving over it leaves heat behind;
* heat lowers the field's threshold so nearby blobs melt into each other,
* and colours it from cool to hot as heat builds, with a hot rim.
* Press to morph into the next shape. Heat fades on its own.
*/
type Shape = "dots" | "asterisk" | "word";
type Tone = "neon" | "fire" | "sea" | "pop";
const SHAPES: Shape[] = ["dots", "asterisk", "word"];
// colour stops from hottest (0) to coolest (1)
const TONES: Record<Tone, [number, string][]> = {
neon: [[0, "#ff3ca0"], [0.12, "#ff3b3b"], [0.26, "#ffd54a"], [0.42, "#9bd8ff"], [0.62, "#3b8bff"], [1, "#1c2c8f"]],
fire: [[0, "#7a0d2e"], [0.15, "#e2262c"], [0.35, "#ff8a1e"], [0.6, "#ffd34d"], [1, "#fff6d8"]],
sea: [[0, "#5a2bd9"], [0.18, "#2b6be6"], [0.4, "#1fc1d6"], [0.65, "#8ff0d8"], [1, "#f2fffb"]],
pop: [[0, "#ff4fa3"], [0.2, "#ff9a3c"], [0.42, "#ffe25a"], [0.66, "#5fe3b0"], [1, "#6a5cff"]],
};
const W = 300;
const H = 160;
const GW = 60; // heat grid
const GH = 32;
function lut(stops: [number, string][]) {
const c = document.createElement("canvas");
c.width = 256;
c.height = 1;
const g = c.getContext("2d")!;
const grad = g.createLinearGradient(0, 0, 256, 0);
stops.forEach(([o, col]) => grad.addColorStop(o, col));
g.fillStyle = grad;
g.fillRect(0, 0, 256, 1);
return c;
}
/** Paint a shape's soft field (white on black) into a W×H canvas. */
function paint(shape: Shape, word: string) {
const c = document.createElement("canvas");
c.width = W;
c.height = H;
const g = c.getContext("2d")!;
g.fillStyle = "#000";
g.fillRect(0, 0, W, H);
g.filter = "blur(7px)";
g.fillStyle = "#fff";
g.strokeStyle = "#fff";
if (shape === "dots") {
// a 7×3 matrix of big, uneven dots that already nearly touch
const cols = 7, rows = 3, gx = 38, gy = 38;
const x0 = W / 2 - ((cols - 1) * gx) / 2;
const y0 = H / 2 - ((rows - 1) * gy) / 2;
for (let r = 0; r < rows; r++)
for (let q = 0; q < cols; q++) {
const k = Math.sin(q * 12.9898 + r * 78.233) * 43758.5453;
const f = k - Math.floor(k);
const rad = f < 0.3 ? 13.5 : f < 0.7 ? 16.5 : 20;
g.beginPath();
g.arc(x0 + q * gx, y0 + r * gy, rad, 0, Math.PI * 2);
g.fill();
}
} else if (shape === "asterisk") {
g.lineCap = "round";
g.lineWidth = 26;
for (let i = 0; i < 3; i++) {
const a = (i * Math.PI) / 3 + Math.PI / 2 + 0.22;
g.beginPath();
g.moveTo(W / 2 - Math.cos(a) * 66, H / 2 - Math.sin(a) * 66);
g.lineTo(W / 2 + Math.cos(a) * 66, H / 2 + Math.sin(a) * 66);
g.stroke();
}
} else {
g.font = `800 ${word.length > 5 ? 56 : 76}px ui-sans-serif, system-ui, -apple-system, sans-serif`;
g.textAlign = "center";
g.textBaseline = "middle";
g.lineJoin = "round";
g.lineWidth = 6;
g.strokeText(word, W / 2, H / 2 + 4);
g.fillText(word, W / 2, H / 2 + 4);
}
return c;
}
const VERT = `attribute vec2 a; varying vec2 uv; void main(){ uv = vec2(a.x*0.5+0.5, 0.5-a.y*0.5); gl_Position = vec4(a,0.,1.); }`;
const FRAG = `
precision mediump float;
varying vec2 uv;
uniform sampler2D fa, fb, heat, pal;
uniform float t, melt;
uniform vec3 cold;
void main(){
float f = mix(texture2D(fa, uv).r, texture2D(fb, uv).r, t);
float h = clamp(texture2D(heat, uv).r * 1.6, 0.0, 1.0);
float th = 0.5 - melt * 0.22 * h;
float a = smoothstep(th - 0.03, th + 0.03, f);
float depth = clamp((f - th) / (1.0 - th) * 1.6, 0.0, 1.0);
// more heat walks the colour from the cool end of the ramp to the hot end;
// the shape's own edge is pushed hot too, so every heated blob gets a rim
float idx = 0.2 + (1.0 - h) * 0.72;
idx = mix(0.0, idx, smoothstep(0.0, 0.55, depth));
vec3 hot = texture2D(pal, vec2(idx, 0.5)).rgb;
float warm = smoothstep(0.04, 0.45, h);
vec3 col = mix(cold, hot, warm);
// hot rims glow a little past the edge
vec3 rimC = texture2D(pal, vec2(0.0, 0.5)).rgb;
float halo = smoothstep(th - 0.14, th, f) * (1.0 - a) * warm * 0.85;
vec3 outc = col * a + rimC * halo;
float outa = a + halo;
gl_FragColor = vec4(outc, outa);
}`;
export function HeatMap({
tone = "neon",
defaultShape = "dots",
word = "HEAT",
brush = 50,
melt = 60,
fade = 50,
}: {
tone?: Tone;
defaultShape?: Shape;
/** Text used by the "word" shape. */
word?: string;
/** 0–100: size of the heat brush. */
brush?: number;
/** 0–100: how much heat lets blobs merge. */
melt?: number;
/** 0–100: how quickly heat cools. */
fade?: number;
}) {
const canvas = useRef<HTMLCanvasElement>(null);
const [shape, setShape] = useState<Shape>(defaultShape);
const [noGL, setNoGL] = useState(false);
const api = useRef<{ morphTo: (s: Shape) => void; setTone: (t: Tone) => void; repaint: () => void } | null>(null);
const hand = useRef<{ x: number; y: number; on: boolean; key: boolean }>({ x: W / 2, y: H / 2, on: false, key: false });
const opts = useRef({ brush, melt, fade, word });
opts.current = { brush, melt, fade, word };
const shapeRef = useRef(shape);
shapeRef.current = shape;
useEffect(() => {
const cv = canvas.current;
if (!cv) return;
const gl = cv.getContext("webgl", { premultipliedAlpha: false, alpha: true });
if (!gl) {
setNoGL(true);
return;
}
const dpr = Math.min(2.5, (window.devicePixelRatio || 1) * 1.25);
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
const mk = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
return s;
};
const prog = gl.createProgram()!;
gl.attachShader(prog, mk(gl.VERTEX_SHADER, VERT));
gl.attachShader(prog, mk(gl.FRAGMENT_SHADER, FRAG));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
setNoGL(true);
return;
}
gl.useProgram(prog);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(prog, "a");
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
const texs = [0, 1, 2, 3].map((unit) => {
const tx = gl.createTexture()!;
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, tx);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return tx;
});
const upload = (unit: number, src: TexImageSource) => {
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, texs[unit]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src);
};
["fa", "fb", "heat", "pal"].forEach((n, i) => gl.uniform1i(gl.getUniformLocation(prog, n), i));
const uT = gl.getUniformLocation(prog, "t");
const uMelt = gl.getUniformLocation(prog, "melt");
const uCold = gl.getUniformLocation(prog, "cold");
let from = shapeRef.current;
let morph = 1;
upload(0, paint(from, opts.current.word));
upload(1, paint(from, opts.current.word));
const heat = new Float32Array(GW * GH);
const heatBytes = new Uint8Array(GW * GH * 4);
api.current = {
morphTo: (s) => {
upload(0, paint(from, opts.current.word));
upload(1, paint(s, opts.current.word));
from = s;
morph = 0;
},
setTone: (t) => upload(3, lut(TONES[t])),
repaint: () => {
upload(0, paint(from, opts.current.word));
upload(1, paint(from, opts.current.word));
},
};
api.current.setTone(tone);
let raf = 0;
let last = performance.now();
const frame = (now: number) => {
const dt = Math.min(0.033, (now - last) / 1000);
last = now;
const o = opts.current;
// cool everything, then warm a gaussian around the hand
const keep = Math.pow(0.5, dt / (0.35 + (1 - o.fade / 100) * 1.6));
for (let i = 0; i < heat.length; i++) heat[i] *= keep;
const hd = hand.current;
if (hd.on) {
const rad = 3 + (o.brush / 100) * 9; // grid cells
const cx = (hd.x / W) * GW;
const cy = (hd.y / H) * GH;
for (let y = Math.max(0, Math.floor(cy - rad * 2)); y < Math.min(GH, cy + rad * 2); y++)
for (let x = Math.max(0, Math.floor(cx - rad * 2)); x < Math.min(GW, cx + rad * 2); x++) {
const d2 = (x + 0.5 - cx) ** 2 + (y + 0.5 - cy) ** 2;
const i = y * GW + x;
heat[i] = Math.min(1, heat[i] + Math.exp(-d2 / (rad * rad)) * dt * 3.2);
}
}
for (let i = 0; i < heat.length; i++) {
const v = Math.round(heat[i] * 255);
heatBytes[i * 4] = heatBytes[i * 4 + 1] = heatBytes[i * 4 + 2] = v;
heatBytes[i * 4 + 3] = 255;
}
gl.activeTexture(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, texs[2]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, GW, GH, 0, gl.RGBA, gl.UNSIGNED_BYTE, heatBytes);
morph = Math.min(1, morph + dt / 0.5);
const e = morph < 0.5 ? 4 * morph ** 3 : 1 - (-2 * morph + 2) ** 3 / 2;
const dark = document.documentElement.classList.contains("dark");
gl.uniform1f(uT, e);
gl.uniform1f(uMelt, o.melt / 100);
if (dark) gl.uniform3f(uCold, 0.6, 0.6, 0.62);
else gl.uniform3f(uCold, 0.62, 0.62, 0.65);
gl.viewport(0, 0, cv.width, cv.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
raf = requestAnimationFrame(frame);
};
raf = requestAnimationFrame(frame);
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => api.current?.setTone(tone), [tone]);
useEffect(() => api.current?.repaint(), [word]);
useEffect(() => {
setShape(defaultShape);
api.current?.morphTo(defaultShape);
}, [defaultShape]);
const next = () => {
const s = SHAPES[(SHAPES.indexOf(shapeRef.current) + 1) % SHAPES.length];
setShape(s);
api.current?.morphTo(s);
};
const local = (e: React.PointerEvent) => {
const el = e.currentTarget as HTMLElement;
const r = el.getBoundingClientRect();
return { x: ((e.clientX - r.left) / r.width) * W, y: ((e.clientY - r.top) / r.height) * H };
};
return (
<div
tabIndex={0}
role="button"
aria-label={`Heat map showing ${shape === "word" ? `the word ${word}` : shape}. Press to change shape; arrow keys move a warm hand over it.`}
onPointerMove={(e) => {
hand.current = { ...local(e), on: true, key: false };
}}
onPointerLeave={() => (hand.current.on = false)}
onClick={next}
onKeyDown={(e) => {
const hd = hand.current;
const step = 14;
const m: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
next();
return;
}
if (e.key === "Escape") {
hd.on = false;
return;
}
const d = m[e.key];
if (!d) return;
e.preventDefault();
if (!hd.key) hand.current = { x: W / 2, y: H / 2, on: true, key: true };
hand.current.x = Math.max(0, Math.min(W, hand.current.x + d[0]));
hand.current.y = Math.max(0, Math.min(H, hand.current.y + d[1]));
hand.current.on = true;
}}
onBlur={() => hand.current.key && (hand.current.on = false)}
className="relative cursor-pointer rounded-[20px] outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/30"
style={{ width: W, height: H }}
>
<canvas ref={canvas} className="h-full w-full" />
{noGL && (
<span className="absolute inset-0 flex items-center justify-center text-[56px] font-extrabold text-[var(--b-fg-muted)]">{word}</span>
)}
</div>
);
}