"use client";
import { useEffect, useRef, useState } from "react";
/**
* Glass Bubble — an original take inspired by bencho.dev's "Glass bubble".
* A drop of glass you can drag across a photo. One fragment shader does the
* lens: it magnifies the middle, squeezes the rim, splits the colours a
* little at the edge, and stretches the drop along the way it's moving.
* Without WebGL you get the plain photo.
*/
const VERT = `
attribute vec2 a;
void main() { gl_Position = vec4(a, 0.0, 1.0); }
`;
const FRAG = `
precision highp float;
uniform sampler2D img;
uniform vec2 res; // canvas size, css px
uniform float pad; // margin around the photo, css px
uniform vec2 box; // photo size, css px
uniform float corner; // photo corner radius
uniform vec2 c; // bubble centre, canvas css px
uniform float R; // bubble radius
uniform vec2 vel; // smoothed velocity, px/s
uniform float mag; // 0..1 magnification strength
uniform float ab; // 0..1 colour split
uniform float dpr;
float rbox(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
// photo coverage at canvas point p (0 outside, 1 inside, soft edge)
float cover(vec2 p) {
float d = rbox(p - pad - box * 0.5, box * 0.5, corner);
return clamp(0.5 - d * dpr, 0.0, 1.0);
}
vec3 photo(vec2 p) {
vec2 uv = clamp((p - pad) / box, 0.0, 1.0);
return texture2D(img, uv).rgb;
}
void main() {
vec2 p = vec2(gl_FragCoord.x, res.y * dpr - gl_FragCoord.y) / dpr;
// stretch the drop along its velocity, keep its area
float sp = length(vel);
vec2 dir = sp > 1.0 ? vel / sp : vec2(1.0, 0.0);
float s = 1.0 + min(sp / 2600.0, 0.22);
vec2 d = p - c;
vec2 dl = vec2(dot(d, dir) / s, dot(d, vec2(-dir.y, dir.x)) * s);
float r = length(dl) / R;
vec4 base = vec4(photo(p) * cover(p), cover(p));
// soft contact shadow just outside the rim
float sh = smoothstep(1.28, 1.0, r) * (1.0 - step(1.0, 1.0 - (r - 1.0)));
base.rgb *= 1.0 - 0.28 * sh * smoothstep(0.98, 1.02, r);
if (r < 1.0) {
// lens: a sphere-ish profile. Small r reads from closer in (magnified),
// near the rim it reaches further out (compressed).
float k = mix(1.0, 0.70, mag);
float m = k + (1.04 - k) * pow(r, 3.2);
float split = ab * 0.06 * pow(r, 2.0);
vec2 q = d;
vec3 col;
col.r = photo(c + q * (m + split)).r;
col.g = photo(c + q * m).g;
col.b = photo(c + q * (m - split)).b;
float cv = cover(c + q * m);
// glass catches a touch of light, bottom-right a touch of shade
vec2 n = d / R;
float lit = 0.10 * smoothstep(0.2, 1.0, r) * clamp(-n.x * 0.6 - n.y * 0.8, 0.0, 1.0);
col = col * (1.0 - 0.10 * smoothstep(0.6, 1.0, r) * clamp(n.y + n.x, 0.0, 1.0)) + lit;
// thin bright rim
float rim = smoothstep(0.955, 0.985, r) * (1.0 - smoothstep(0.985, 1.0, r));
float a = max(cv, 0.0);
vec4 glass = vec4(col * a, a);
// edge band always visible, even off the photo
float band = smoothstep(0.90, 1.0, r);
glass = mix(glass, vec4(vec3(1.0) * 0.08, 0.08), band * (1.0 - a));
glass.rgb += vec3(1.0) * rim * 0.7;
glass.a = max(glass.a, rim * 0.7);
float edge = clamp((1.0 - r) * R * dpr, 0.0, 1.0);
gl_FragColor = mix(base, glass, edge);
} else {
gl_FragColor = base;
}
}
`;
export function GlassBubble({
src = "/bencho/meadow.webp",
alt = "A misty green hillside with grazing animals",
width = 260,
size = 104,
magnify = 60,
aberration = 50,
corner = 14,
}: {
src?: string;
alt?: string;
/** Photo edge length in px (square). */
width?: number;
/** Bubble diameter in px. */
size?: number;
/** 0–100 magnification in the middle of the drop. */
magnify?: number;
/** 0–100 colour fringe at the rim. */
aberration?: number;
corner?: number;
}) {
const PAD = Math.ceil(size * 0.62);
const canvas = useRef<HTMLCanvasElement>(null);
const [ready, setReady] = useState(false);
const st = useRef({
x: width / 2 + 36,
y: width / 2 - 30,
tx: width / 2 + 36,
ty: width / 2 - 30,
vx: 0,
vy: 0,
svx: 0,
svy: 0,
grab: null as null | { dx: number; dy: number },
});
const props = useRef({ size, magnify, aberration, corner, width });
props.current = { size, magnify, aberration, corner, width };
useEffect(() => {
const cv = canvas.current;
if (!cv) return;
const gl = cv.getContext("webgl", { premultipliedAlpha: true, alpha: true, antialias: false });
if (!gl) return;
const sh = (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, sh(gl.VERTEX_SHADER, VERT));
gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FRAG));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return;
gl.useProgram(prog);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
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);
const U = (n: string) => gl.getUniformLocation(prog, n);
const u = { res: U("res"), pad: U("pad"), box: U("box"), corner: U("corner"), c: U("c"), R: U("R"), vel: U("vel"), mag: U("mag"), ab: U("ab"), dpr: U("dpr") };
const tex = gl.createTexture();
let alive = true;
let raf = 0;
const im = new Image();
im.decoding = "async";
im.onload = () => {
if (!alive) return;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, im);
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);
setReady(true);
let last = performance.now();
const frame = (now: number) => {
const dt = Math.min(0.033, (now - last) / 1000);
last = now;
const P = props.current;
const pad = Math.ceil(P.size * 0.62);
const cssW = P.width + pad * 2;
const dpr = Math.min(3, (window.devicePixelRatio || 1) * 1.25);
if (cv.width !== Math.round(cssW * dpr)) {
cv.width = cv.height = Math.round(cssW * dpr);
}
const s = st.current;
// spring the drop towards where it's being held
const k = 520;
const damp = 2 * 0.72 * Math.sqrt(k);
s.vx += (k * (s.tx - s.x) - damp * s.vx) * dt;
s.vy += (k * (s.ty - s.y) - damp * s.vy) * dt;
s.x += s.vx * dt;
s.y += s.vy * dt;
s.svx += (s.vx - s.svx) * Math.min(1, dt * 14);
s.svy += (s.vy - s.svy) * Math.min(1, dt * 14);
gl.viewport(0, 0, cv.width, cv.height);
gl.uniform2f(u.res, cssW, cssW);
gl.uniform1f(u.pad, pad);
gl.uniform2f(u.box, P.width, P.width);
gl.uniform1f(u.corner, P.corner);
gl.uniform2f(u.c, s.x + pad, s.y + pad);
gl.uniform1f(u.R, P.size / 2);
gl.uniform2f(u.vel, s.svx, s.svy);
gl.uniform1f(u.mag, P.magnify / 100);
gl.uniform1f(u.ab, P.aberration / 100);
gl.uniform1f(u.dpr, dpr);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
raf = requestAnimationFrame(frame);
};
raf = requestAnimationFrame(frame);
};
im.src = src;
return () => {
alive = false;
cancelAnimationFrame(raf);
};
}, [src]);
// pointer → photo-space coordinates (works under any CSS scale)
const local = (e: React.PointerEvent) => {
const el = e.currentTarget as HTMLElement;
const r = el.getBoundingClientRect();
const k = r.width / el.offsetWidth || 1;
return { x: (e.clientX - r.left) / k - PAD, y: (e.clientY - r.top) / k - PAD };
};
const clampC = (v: number) => Math.max(0, Math.min(width, v));
return (
<div
tabIndex={0}
role="img"
aria-label={`${alt}. A glass lens magnifies part of the photo; drag it, or use the arrow keys to move it.`}
onKeyDown={(e) => {
const step = e.shiftKey ? 30 : 10;
const s = st.current;
const m: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
const d = m[e.key];
if (!d) return;
e.preventDefault();
s.tx = clampC(s.tx + d[0]);
s.ty = clampC(s.ty + d[1]);
}}
onPointerDown={(e) => {
const p = local(e);
const s = st.current;
const inside = Math.hypot(p.x - s.x, p.y - s.y) < size / 2;
if (!inside && (p.x < 0 || p.y < 0 || p.x > width || p.y > width)) return;
e.currentTarget.setPointerCapture(e.pointerId);
s.grab = inside ? { dx: s.x - p.x, dy: s.y - p.y } : { dx: 0, dy: 0 };
s.tx = clampC(p.x + s.grab.dx);
s.ty = clampC(p.y + s.grab.dy);
}}
onPointerMove={(e) => {
const s = st.current;
if (!s.grab) return;
const p = local(e);
s.tx = clampC(p.x + s.grab.dx);
s.ty = clampC(p.y + s.grab.dy);
}}
onPointerUp={() => (st.current.grab = null)}
onPointerCancel={() => (st.current.grab = null)}
className="relative cursor-grab touch-none select-none rounded-[24px] outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/30 active:cursor-grabbing"
style={{ width: width + PAD * 2, height: width + PAD * 2, margin: -PAD }}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={src}
alt=""
draggable={false}
className="absolute object-cover"
style={{ left: PAD, top: PAD, width, height: width, borderRadius: corner, opacity: ready ? 0 : 1 }}
/>
<canvas ref={canvas} className="absolute inset-0 h-full w-full" />
</div>
);
}