A personal Are.na browser you handle, not scroll
Everything I save on Are.na ends up as the same grid. I wanted to pull a channel off a shelf like a record and handle what's inside.
Story
For years, Are.na has been my notebook for the internet: favourite sites, design references, music, odd corners of culture. Everything I save lands in the same grid of thumbnails, so a channel of animal-shaped breads looks exactly like a channel of type references.
Wordminders is the interface I wanted for those collections. References are things you handle, not rows in a feed. Ten channels sit on a shelf as CDs: my own Wordminders channel, and nine from curators I keep going back to, like Persona, Masks and Animal shaped breads. Pick one and its blocks tile an endless canvas, or roll past as a film strip you can scrub.
Loading preview…
Show code
"use client";
import { useEffect, useId, useRef, type ReactNode } from "react";
import { prefetchPrioritized } from "@/components/wordminders/disc-picker/disc-art";
import { registerDisc, type DiscHandle } from "@/components/wordminders/disc-picker/disc-gl";
import { cn } from "@/lib/utils";
// A channel picker where every channel is a spinning CD. Each disc's label is
// a slideshow of the channel's own images, cross-fading every 3.8s, under a
// groove shader with a travelling glint. Hover or focus a disc and it stops,
// the way a finger stops a record, so the art you're reading holds still.
export type DiscChannel = {
id: string;
title: string;
/** Image URLs for the label slideshow, in order. Cross-origin art needs CORS. */
slides: string[];
/** ISO date, shown as "Updated Mar. 4, 2026". */
updatedAt?: string;
};
const MONTHS = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."];
function formatUpdated(iso?: string) {
if (!iso) return "";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "";
return `Updated ${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
}
function prefersReducedMotion() {
return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function Disc({
channel,
index,
active,
paused,
onSelect,
renderMeta,
}: {
channel: DiscChannel;
index: number;
active: boolean;
paused: boolean;
onSelect?: (id: string) => void;
renderMeta?: (channel: DiscChannel, active: boolean) => ReactNode;
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const handleRef = useRef<DiscHandle | null>(null);
const pausedRef = useRef(paused);
const updated = formatUpdated(channel.updatedAt);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const handle: DiscHandle = {
canvas,
title: channel.title,
slides: channel.slides,
index,
held: false,
still: pausedRef.current || prefersReducedMotion(),
visible: false,
};
handleRef.current = handle;
const unregister = registerDisc(handle);
// Offscreen discs cost nothing: the shared loop skips them.
const io = new IntersectionObserver(([entry]) => {
handle.visible = entry?.isIntersecting ?? false;
});
io.observe(canvas);
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
const onMotion = () => {
handle.still = pausedRef.current || motion.matches;
};
motion.addEventListener("change", onMotion);
return () => {
io.disconnect();
motion.removeEventListener("change", onMotion);
unregister();
handleRef.current = null;
};
}, [channel.title, channel.slides, index]);
// Pausing freezes the disc where it is; it doesn't re-register or reset.
useEffect(() => {
pausedRef.current = paused;
if (handleRef.current) handleRef.current.still = paused || prefersReducedMotion();
}, [paused]);
const hold = (held: boolean) => {
if (handleRef.current) handleRef.current.held = held;
};
return (
<div className="group flex min-w-0 flex-col">
<button
type="button"
aria-label={`Open ${channel.title}`}
aria-current={active || undefined}
onPointerEnter={() => hold(true)}
onPointerLeave={() => hold(false)}
onFocus={() => hold(true)}
onBlur={() => hold(false)}
onClick={() => onSelect?.(channel.id)}
className="relative aspect-square w-full cursor-pointer touch-manipulation rounded-xl outline-none transition-transform duration-150 ease-out active:scale-[0.96] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-reduce:active:scale-100"
>
<canvas ref={canvasRef} aria-hidden className="block size-full" />
</button>
<div className="flex flex-col px-2 pt-2 pb-3">
{renderMeta ? (
renderMeta(channel, active)
) : (
<>
<p className="flex min-w-0 items-center gap-1 text-sm text-foreground">
<span className="line-clamp-1 min-w-0 break-words">{channel.title}</span>
<svg
viewBox="0 0 24 24"
fill="none"
aria-hidden
className="size-3.5 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"
>
<path d="M7 17 17 7M17 7H9M17 7v8" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
</svg>
</p>
{active ? (
<p className="text-sm text-muted-foreground">Now playing</p>
) : updated ? (
<p className="text-sm text-muted-foreground">{updated}</p>
) : null}
</>
)}
</div>
</div>
);
}
export function DiscPicker({
channels,
activeId,
onSelect,
title = "Select a disk",
description,
paused = false,
hideTitle = false,
renderMeta,
className,
}: {
channels: DiscChannel[];
/** The playing channel; marked with aria-current and "Now playing". */
activeId?: string;
onSelect?: (id: string) => void;
title?: string;
description?: string;
/** Freeze every disc on its current frame (e.g. while the panel is hidden). */
paused?: boolean;
/** Keep the title for screen readers only (it still names the section). */
hideTitle?: boolean;
/** Replace the title / updated line under each disc. */
renderMeta?: (channel: DiscChannel, active: boolean) => ReactNode;
className?: string;
}) {
const titleId = useId();
// Warm every disc's first slide before any second slide.
useEffect(() => {
void prefetchPrioritized(channels.map((c) => c.slides));
}, [channels]);
return (
<section
aria-labelledby={titleId}
className={cn(
"flex w-full flex-col rounded-3xl bg-background p-6 motion-safe:animate-[disc-picker-in_280ms_cubic-bezier(0.16,1,0.3,1)_both]",
className,
)}
>
<header className={hideTitle ? "sr-only" : "pb-10"}>
<h2 id={titleId} className="m-0 flex flex-col text-lg leading-snug font-semibold sm:text-xl">
<span className="text-foreground">{title}</span>
{description ? <span className="text-muted-foreground">{description}</span> : null}
</h2>
</header>
<div className="grid grid-cols-2 gap-6">
{channels.map((channel, i) => (
<Disc
key={channel.id}
channel={channel}
index={i}
active={channel.id === activeId}
paused={paused}
onSelect={onSelect}
renderMeta={renderMeta}
/>
))}
</div>
</section>
);
}// One WebGL context for every disc on the page. Each disc owns a shader
// material and an art texture; a shared renderer draws them one at a time
// into a scissored corner of its buffer, and each disc copies that corner
// into its own 2D canvas. Ten pickers still cost one GPU context.
import * as THREE from "three";
import { artKey, createArtTexture, createScratch, paintArt, uploadScratch } from "./disc-art";
export const DISC_DEFAULTS = {
/** Resting tilt, degrees. */
rotation: 13,
/** Radians per second while not held. */
spinSpeed: 1,
glistenSpeed: 1.55,
glistenIntensity: 1.5,
rainbowAmount: 0,
highlightSharpness: 96,
};
const vertex = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
// Ported from the production CD shader; logo decal and dim/fade passes removed.
const fragment = /* glsl */ `
precision highp float;
varying vec2 vUv;
#define TWO_PI 6.28318530718
uniform sampler2D uArt;
uniform float uTime;
uniform float uGlistenIntensity;
uniform float uRainbowAmount;
uniform float uSharpness;
uniform float uDiskPx;
vec3 hsv2rgb(vec3 c) {
vec4 K = vec4(1.0, 2.0/3.0, 1.0/3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
float hash12(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
}
void main() {
vec2 centered = vUv - 0.5;
float r = length(centered) * 2.0;
float angle = atan(centered.y, centered.x);
if (r > 1.0) discard;
vec3 art = texture2D(uArt, vUv).rgb;
// Groove ripple on the printed art, strongest across the data area.
float pr = 378.0 * r * r + 99.0 * r + 12.0 * sin(angle * 2.62 + uTime * 0.056) + uTime * 0.36;
float beatp = sin(pr) * sin(pr * 1.049 + 0.9);
float irisE = smoothstep(0.33, 0.48, r) * smoothstep(0.76, 0.58, r);
float rimE = smoothstep(0.74, 0.985, r);
float ge = irisE * (1.0 - rimE * 0.9);
art *= 1.0 + (0.5 * sin(pr)) * 0.072 * ge + beatp * 0.035 * ge;
float lum = dot(art, vec3(0.299, 0.587, 0.114));
art = mix(vec3(lum), art, 0.81);
art = pow(max(art, vec3(0.001)), vec3(0.93));
vec2 gCell = floor(vUv * vec2(1600.0));
float gn = hash12(gCell) * 0.65 + hash12(gCell + vec2(31.0, 17.0)) * 0.35;
vec3 color = clamp(art + (gn - 0.5) * 0.062, 0.0, 1.0);
// Aluminium lift at the rim and hub.
vec3 aluminum = vec3(0.86, 0.88, 0.92);
float irisMid = irisE;
float rimW = rimE;
vec3 radialMetal = mix(aluminum, vec3(0.78, 0.80, 0.86), rimW * 0.95);
color = mix(color, radialMetal, clamp(rimW * 0.34 + (1.0 - irisMid) * 0.24, 0.0, 1.0) * 0.74);
// Concentric groove grating with a slight chromatic split.
float angNorm = fract(angle / TWO_PI + 0.5);
float kR = 385.0 + 18.0 * sin(angNorm * TWO_PI * 2.0 + uTime * 0.07);
float ph = kR * r * r + 102.0 * r + 14.0 * sin(angle * 2.65 + uTime * 0.056) + uTime * 0.38;
float s1 = sin(ph);
float s2 = sin(ph * 1.051 + 2.15 + 0.35 * sin(angle * 1.9));
float h2 = 0.5 + 0.5 * sin(ph * 2.04 + 0.55);
float beat = 0.5 + 0.5 * (s1 * s2);
float visBeat = pow(max(beat, 0.0), 0.78);
float grateRegion = irisMid * (1.0 - rimW * 0.88);
float rib = s1;
float ribFine = (h2 - 0.5) * 2.0;
float gStr = grateRegion * (0.72 + 0.28 * visBeat);
color *= 1.0 + rib * 0.1 * gStr + ribFine * 0.038 * gStr;
vec3 cChrom = color;
float chrom = rib * 0.062 * gStr;
cChrom.r = clamp(cChrom.r + chrom, 0.0, 1.0);
cChrom.g = clamp(cChrom.g + chrom * 0.28, 0.0, 1.0);
cChrom.b = clamp(cChrom.b - chrom * 1.02, 0.0, 1.0);
color = mix(color, cChrom, 0.44);
color *= 0.982 + 0.055 * mix(beat, visBeat, 0.5) * grateRegion;
// Optional iridescent zones (off by default).
float cellCoord = angNorm * 6.0 + uTime * 0.0072;
float cellF = fract(cellCoord);
float dwell = pow(max(smoothstep(0.0, 0.32, cellF) * smoothstep(1.0, 0.68, cellF), 1e-4), 0.82);
float arcMask = smoothstep(0.35, 0.95, 0.55 + 0.45 * cos((angNorm - 0.5) * TWO_PI * 1.15 + uTime * 0.055));
float zi = mod(floor(cellCoord), 3.0);
float hueAnchor = mix(0.17, mix(0.48, 0.76, step(2.0, zi)), step(1.0, zi));
float phHue = fract(0.09 + ph * 0.0098 + angNorm * 0.2 + sin(ph * 0.031) * 0.11 + uTime * 0.004);
float hue = fract(mix(hueAnchor, phHue, 0.62) + 0.04 * rib * grateRegion + 0.018 * sin(cellF * TWO_PI));
float speckle = clamp(0.42 * pow(max(abs(s1), 0.08), 0.65) + 0.28 * abs(h2 - 0.5) * 2.0 + 0.35 * visBeat, 0.0, 1.1);
float zoneSat = 0.62 * speckle * dwell * arcMask * grateRegion;
float iridMix = min(1.0, zoneSat * uRainbowAmount * (0.16 + 0.84 * smoothstep(0.08, 0.55, dwell)) * uGlistenIntensity);
color = mix(color, mix(radialMetal, hsv2rgb(vec3(hue, 0.76, 1.0)), 0.58), iridMix);
// Soft bloom that drifts around the data area.
float spread = mix(0.42, 0.78, clamp(uSharpness / 128.0, 0.0, 1.0));
float bloom = (cos((angle * spread + uTime * 0.62) * 1.15) * 0.5 + 0.5) * 0.52
+ (sin(angle * 0.65 + uTime * 0.28) * 0.5 + 0.5) * 0.48;
bloom = smoothstep(0.18, 0.96, pow(max(bloom, 0.0), 1.35));
float bloomMask = (irisMid * 0.92 + 0.05 * (1.0 - rimW) * irisMid)
* smoothstep(0.1, 0.26, r) * (1.0 - smoothstep(0.65, 0.94, r));
color = clamp(color + vec3(1.0, 0.994, 0.99) * bloom * bloomMask * 0.11 * uGlistenIntensity, 0.0, 1.0);
// The specular sweep: the glint that reads as "a CD catching the light".
float specN = clamp(uSharpness * 0.5 + 40.0, 52.0, 120.0);
float ht = angle * 1.72 + uTime * 0.98;
float cs = cos(ht);
float spec = pow(max(cs, 0.0), specN) + pow(max(-cs, 0.0), specN * 0.8) * 0.42
+ pow(max(cos(ht + 0.67), 0.0), specN * 1.02) * 0.36;
float specZone = irisMid * (0.58 + 0.32 * (1.0 - rimW * 0.95)) * (1.0 - smoothstep(0.76, 0.96, r));
vec3 specTint = mix(vec3(1.0, 0.996, 0.992), vec3(0.78, 0.84, 0.96), 0.22);
color = clamp(color + specTint * spec * specZone * 0.62 * uGlistenIntensity, 0.0, 1.0);
// A 1px rim stroke, measured in screen pixels.
float dr = 2.0 / max(uDiskPx, 1.0);
float aa = max(dr * 0.55, 0.00035);
float strokeMask = smoothstep(1.0 - dr - aa, 1.0 - aa * 0.3, r) * step(r, 1.001);
vec3 strokeRgb = mix(vec3(0.0), vec3(0.17, 0.17, 0.18), clamp(vUv.x * 0.68 + vUv.y * 0.32, 0.0, 1.0));
color = mix(color, strokeRgb, strokeMask);
gl_FragColor = vec4(color, smoothstep(1.008, 0.988, r));
}
`;
export type DiscHandle = {
canvas: HTMLCanvasElement;
title: string;
slides: string[];
index: number;
/** True while hovered or focused: the disc stops, like a finger on a record. */
held: boolean;
/** Frozen: no spin, no slideshow, no glisten drift (reduced motion, paused). */
still: boolean;
visible: boolean;
};
type Entry = {
handle: DiscHandle;
material: THREE.ShaderMaterial;
art: THREE.DataTexture;
scratch: HTMLCanvasElement;
rotation: number;
time: number;
lastKey: string | null;
lastDrawKey: string | null;
};
type Shared = {
renderer: THREE.WebGLRenderer;
scene: THREE.Scene;
camera: THREE.OrthographicCamera;
mesh: THREE.Mesh<THREE.PlaneGeometry, THREE.ShaderMaterial>;
entries: Set<Entry>;
raf: number;
last: number;
bufW: number;
bufH: number;
};
/** Seconds of slideshow offset between neighbouring discs. */
const SLIDE_STAGGER_SEC = 0.12;
const MAX_DPR = 2;
let shared: Shared | null = null;
function createShared(): Shared {
const renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: false,
premultipliedAlpha: false,
powerPreference: "high-performance",
});
renderer.setClearColor(0x000000, 0);
renderer.setScissorTest(true);
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(0, 1, 1, 0, -10, 10);
camera.position.z = 1;
const placeholder = new THREE.ShaderMaterial();
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), placeholder);
scene.add(mesh);
return { renderer, scene, camera, mesh, entries: new Set(), raf: 0, last: 0, bufW: 0, bufH: 0 };
}
function frame(now: number) {
const s = shared;
if (!s) return;
const dt = s.last ? Math.min((now - s.last) / 1000, 0.05) : 0;
s.last = now;
const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);
for (const e of s.entries) {
const h = e.handle;
if (!h.visible) continue;
const w = Math.max(1, h.canvas.clientWidth);
const hh = Math.max(1, h.canvas.clientHeight);
if (!h.still) {
e.time += dt;
if (!h.held) e.rotation += dt * DISC_DEFAULTS.spinSpeed;
}
const key = artKey(h.title, h.slides, e.time + h.index * SLIDE_STAGGER_SEC);
if (key !== e.lastKey) {
e.lastKey = key;
paintArt(e.scratch, h.title, h.slides, e.time + h.index * SLIDE_STAGGER_SEC);
uploadScratch(e.scratch, e.art);
}
// A still disc only redraws when its art or size changes.
const drawKey = h.still ? `${key}|${w}x${hh}|${dpr}` : null;
if (drawKey && drawKey === e.lastDrawKey) continue;
e.lastDrawKey = drawKey;
// Grow-only shared buffer, sized to the largest disc on the page.
if (w > s.bufW || hh > s.bufH || s.renderer.getPixelRatio() !== dpr) {
s.bufW = Math.max(s.bufW, w);
s.bufH = Math.max(s.bufH, hh);
s.renderer.setPixelRatio(dpr);
s.renderer.setSize(s.bufW, s.bufH, false);
}
const size = Math.min(w, hh) * 0.92;
const u = e.material.uniforms;
u.uTime.value = e.time * DISC_DEFAULTS.glistenSpeed + h.index * 1.37;
u.uDiskPx.value = size * dpr;
s.mesh.material = e.material;
s.mesh.position.set(w / 2, hh / 2, 0);
s.mesh.scale.set(size, size, 1);
s.mesh.rotation.z = (DISC_DEFAULTS.rotation * Math.PI) / 180 + e.rotation;
s.camera.right = w;
s.camera.top = hh;
s.camera.updateProjectionMatrix();
s.renderer.setViewport(0, 0, w, hh);
s.renderer.setScissor(0, 0, w, hh);
s.renderer.clear();
s.renderer.render(s.scene, s.camera);
// Copy the bottom-left corner (GL origin) into the disc's own canvas.
const pw = Math.round(w * dpr);
const ph = Math.round(hh * dpr);
if (h.canvas.width !== pw || h.canvas.height !== ph) {
h.canvas.width = pw;
h.canvas.height = ph;
}
const ctx = h.canvas.getContext("2d");
if (!ctx) continue;
const src = s.renderer.domElement;
ctx.clearRect(0, 0, pw, ph);
ctx.drawImage(src, 0, src.height - ph, pw, ph, 0, 0, pw, ph);
}
s.raf = requestAnimationFrame(frame);
}
/** Register a disc with the shared renderer; returns an unregister function. */
export function registerDisc(handle: DiscHandle): () => void {
shared ??= createShared();
const s = shared;
const art = createArtTexture();
const material = new THREE.ShaderMaterial({
vertexShader: vertex,
fragmentShader: fragment,
transparent: true,
depthTest: false,
depthWrite: false,
uniforms: {
uArt: { value: art },
uTime: { value: 0 },
uGlistenIntensity: { value: DISC_DEFAULTS.glistenIntensity },
uRainbowAmount: { value: DISC_DEFAULTS.rainbowAmount },
uSharpness: { value: DISC_DEFAULTS.highlightSharpness },
uDiskPx: { value: 256 },
},
});
const entry: Entry = {
handle,
material,
art,
scratch: createScratch(),
rotation: 0,
time: 0,
lastKey: null,
lastDrawKey: null,
};
s.entries.add(entry);
if (!s.raf) {
s.last = 0;
s.raf = requestAnimationFrame(frame);
}
return () => {
s.entries.delete(entry);
material.dispose();
art.dispose();
if (s.entries.size === 0) {
cancelAnimationFrame(s.raf);
s.mesh.geometry.dispose();
s.renderer.dispose();
shared = null;
}
};
}// Slideshow artwork for one disc: hold on a frame, cross-fade to the next,
// painted into a 512² scratch canvas and copied into a DataTexture. Bitmaps
// load into one shared cache, first frame of every disc before the rest, so
// every disc shows art before any disc gets its second slide.
import * as THREE from "three";
export const ART_SIZE = 512;
export const SLIDE_HOLD_SEC = 2.8;
export const SLIDE_CROSS_SEC = 1.0;
export type BitmapCache = Map<string, ImageBitmap | null>;
/** One cache per page, so remounting a picker reuses warmed bitmaps. */
export const bitmapCache: BitmapCache = new Map();
/** Deterministic neutral grey for discs with no art, or while their art loads. */
export function fallbackGrey(str: string, offset = 0): string {
let h = 0;
for (let i = 0; i < str.length; i++) h = str.charCodeAt(i) + ((h << 5) - h);
return `hsl(0 0% ${22 + (((h + offset * 7) % 8) + 8) % 8}%)`;
}
/**
* Strict CORS: the scratch canvas is read back with getImageData, so a
* tainted image would throw. Cross-origin art must be served with CORS.
*/
function loadBitmap(url: string): Promise<ImageBitmap | null> {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
createImageBitmap(img).then(resolve, () => resolve(null));
};
img.onerror = () => resolve(null);
img.src = url;
});
}
export async function prefetchBitmaps(urls: string[], cache = bitmapCache, concurrency = 16) {
const pending = [...new Set(urls)].filter((u) => !cache.has(u));
if (pending.length === 0) return;
let cursor = 0;
async function worker() {
while (cursor < pending.length) {
const url = pending[cursor++]!;
cache.set(url, await loadBitmap(url));
}
}
await Promise.all(Array.from({ length: Math.min(concurrency, pending.length) }, worker));
}
/** First frame of every disc, then everything else. */
export async function prefetchPrioritized(slides: string[][], cache = bitmapCache) {
const primaries = [...new Set(slides.map((s) => s[0]).filter(Boolean) as string[])];
await prefetchBitmaps(primaries, cache);
void prefetchBitmaps(slides.flat(), cache);
}
export function createArtTexture(): THREE.DataTexture {
const tex = new THREE.DataTexture(
new Uint8Array(ART_SIZE * ART_SIZE * 4),
ART_SIZE,
ART_SIZE,
THREE.RGBAFormat,
THREE.UnsignedByteType,
);
// No colour-space decode: the shader writes straight to an sRGB canvas, so
// decoding here would show every label darker than its source image.
tex.colorSpace = THREE.NoColorSpace;
tex.magFilter = THREE.LinearFilter;
tex.minFilter = THREE.LinearFilter;
tex.flipY = true;
tex.generateMipmaps = false;
tex.needsUpdate = true;
return tex;
}
export function createScratch(): HTMLCanvasElement {
const c = document.createElement("canvas");
c.width = ART_SIZE;
c.height = ART_SIZE;
return c;
}
export function uploadScratch(scratch: HTMLCanvasElement, tex: THREE.DataTexture) {
const ctx = scratch.getContext("2d", { willReadFrequently: true });
const dst = tex.image.data as Uint8Array | null;
if (!ctx || !dst) return;
dst.set(ctx.getImageData(0, 0, ART_SIZE, ART_SIZE).data);
tex.needsUpdate = true;
}
function drawCover(ctx: CanvasRenderingContext2D, bmp: ImageBitmap) {
const s = Math.max(ART_SIZE / bmp.width, ART_SIZE / bmp.height);
const w = bmp.width * s;
const h = bmp.height * s;
ctx.drawImage(bmp, (ART_SIZE - w) / 2, (ART_SIZE - h) / 2, w, h);
}
/** Which slide pair is on screen at time t, and how far the cross-fade is. */
function slideAt(n: number, t: number) {
const seg = SLIDE_HOLD_SEC + SLIDE_CROSS_SEC;
const cyc = Math.max(0, t) % (n * seg);
const idx = Math.floor(cyc / seg);
const local = cyc - idx * seg;
const blend = local >= SLIDE_HOLD_SEC ? Math.min(1, (local - SLIDE_HOLD_SEC) / SLIDE_CROSS_SEC) : 0;
return { from: idx % n, to: (idx + 1) % n, blend };
}
/**
* Changes exactly when the painted pixels would: slide pair, blend, or a
* bitmap arriving. Comparing it per frame means a disc on hold re-uploads
* nothing, and art that loads late appears on the next frame.
*/
export function artKey(title: string, urls: string[], t: number, cache = bitmapCache): string {
let loaded = "";
for (const u of urls) loaded += !cache.has(u) ? "m" : cache.get(u) ? "1" : "0";
if (urls.length === 0) return `q:${title}`;
if (urls.length === 1) return `1:${loaded}`;
const { from, to, blend } = slideAt(urls.length, t);
return `${from}|${to}|${blend}|${loaded}`;
}
export function paintArt(
scratch: HTMLCanvasElement,
title: string,
urls: string[],
t: number,
cache = bitmapCache,
) {
const ctx = scratch.getContext("2d", { willReadFrequently: true });
if (!ctx) return;
const half = ART_SIZE / 2;
if (urls.length === 0) {
for (let i = 0; i < 4; i++) {
ctx.fillStyle = fallbackGrey(title, i);
ctx.fillRect(i % 2 ? half : 0, i < 2 ? 0 : half, half, half);
}
return;
}
const { from, to, blend } = urls.length === 1 ? { from: 0, to: 0, blend: 0 } : slideAt(urls.length, t);
const a = cache.get(urls[from]!) ?? null;
const b = cache.get(urls[to]!) ?? null;
ctx.globalAlpha = 1;
ctx.clearRect(0, 0, ART_SIZE, ART_SIZE);
if (a) drawCover(ctx, a);
else {
ctx.fillStyle = fallbackGrey(title, from);
ctx.fillRect(0, 0, ART_SIZE, ART_SIZE);
}
if (blend > 0 && b) {
ctx.globalAlpha = blend;
drawCover(ctx, b);
ctx.globalAlpha = 1;
}
}The first version switched channels from a dropdown of names in the breadcrumb. A name says nothing about what's inside, so nine days in, the list became a shelf of discs whose labels play the channel back to you.
It stays small on purpose. Ten channels are allowlisted in code, nothing is written back to Are.na, and there's no search or login. Blocks arrive in the order each curator arranged them by hand, and a channel saved inside another channel stays a block until you open it.
Gray until you point at it
A dense field of full-colour references is loud, and nothing stands out from it. On the canvas, every tile renders gray, and only the one under the pointer gets its colour back. It's gray or colour, never halfway: a fade would flicker as the pointer crosses tiles.
Loading preview…
Show code
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { cn } from "@/lib/utils";
// An endless field of image tiles you pan in any direction. Tiles sit in rows
// of their natural widths, each row phase-shifted so columns never line up,
// and the whole pool wraps on a torus: a fixed set of meshes, repositioned
// every frame, covers an infinite plane. Idle tiles render grayscale; the one
// under the pointer gets its colour back. The frame goes through a barrel
// lens with a hair of chromatic split, then a vignette.
export type CanvasTile = {
id: string;
src: string;
/** Width / height; used until the image loads and reports its own. */
aspect?: number;
title?: string;
};
export type TileFieldParams = {
/** Row height in CSS px. Changing it rebuilds the tile pool. */
tileHeight: number;
/** Gap between tiles in CSS px. Changing it rebuilds the tile pool. */
tileGap: number;
vignetteStrength: number;
vignetteSize: number;
/** Velocity kept per 60Hz frame after a fling (0 = none). */
inertiaFriction: number;
/** How much of the remaining distance is left per 60Hz frame (lower = snappier). */
panEase: number;
/** Barrel distortion amount; also drives the chromatic split. */
barrel: number;
/** Colour tiles under the pointer; off keeps everything grayscale. */
hover: boolean;
};
export const TILE_FIELD_DEFAULTS: TileFieldParams = {
tileHeight: 220,
tileGap: 4,
vignetteStrength: 0.29,
vignetteSize: 1.25,
inertiaFriction: 0.5,
panEase: 0.8,
barrel: 0.04,
hover: true,
};
const CORNER_PX = 4;
const PICK_Z_EPS = 1e-4;
const KEY_STEP = 18;
const quadVert = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
// Rounded-rect SDF mask; luminance grayscale unless hovered.
const tileFrag = /* glsl */ `
varying vec2 vUv;
uniform sampler2D uTex;
uniform float uHover;
uniform vec2 uSizePx;
uniform float uCornerPx;
void main() {
vec2 p = (vUv - 0.5) * uSizePx;
vec2 q = abs(p) - (uSizePx * 0.5 - vec2(uCornerPx)) + uCornerPx;
float d = min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - uCornerPx;
if (d > max(fwidth(d), 1e-5)) discard;
vec4 c = texture2D(uTex, vUv);
vec3 gray = vec3(dot(c.rgb, vec3(0.299, 0.587, 0.114)));
gl_FragColor = vec4(uHover > 0.5 ? c.rgb : gray, 1.0);
}
`;
const screenVert = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}
`;
const vignetteFrag = /* glsl */ `
varying vec2 vUv;
uniform float uVigStrength;
uniform float uVigSize;
void main() {
float v = smoothstep(0.35, 0.95, length(vUv - 0.5) * uVigSize);
gl_FragColor = vec4(0.0, 0.0, 0.0, v * uVigStrength);
}
`;
const barrelFrag = /* glsl */ `
varying vec2 vUv;
uniform sampler2D uScene;
uniform float uBarrel;
uniform vec3 uBg;
void main() {
vec2 p = vUv - 0.5;
float r2 = dot(p, p);
vec2 distorted = p * (1.0 + uBarrel * r2 + uBarrel * 0.5 * r2 * r2) + 0.5;
vec3 color;
if (distorted.x < 0.0 || distorted.x > 1.0 || distorted.y < 0.0 || distorted.y > 1.0) {
color = uBg;
} else {
float ca = uBarrel * 0.015;
color = vec3(
texture2D(uScene, p * (1.0 + uBarrel * r2 + ca) + 0.5).r,
texture2D(uScene, distorted).g,
texture2D(uScene, p * (1.0 + uBarrel * r2 - ca) + 0.5).b
);
}
gl_FragColor = vec4(color, 1.0);
// Encode for the sRGB canvas; without it every image showed darker than its source.
#include <colorspace_fragment>
}
`;
const mod = (a: number, n: number) => ((a % n) + n) % n;
/** prefix[phase][k] = summed widths of the k tiles before slot k in a row shifted by `phase`. */
function prefixByPhase(widths: number[]) {
const n = widths.length;
return Array.from({ length: n }, (_, phase) => {
const ps = [0];
for (let k = 1; k < n; k++) ps.push(ps[k - 1]! + widths[(k - 1 + phase) % n]!);
return ps;
});
}
function placeholderTexture(): THREE.Texture {
const t = new THREE.DataTexture(new Uint8Array([26, 26, 26, 255]), 1, 1);
t.colorSpace = THREE.SRGBColorSpace;
t.needsUpdate = true;
return t;
}
function prefersReducedMotion() {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
export function TileField({
tiles,
params,
onTileOpen,
wheel = "always",
background = "#000000",
className,
label = "Image canvas",
}: {
tiles: CanvasTile[];
params?: Partial<TileFieldParams>;
onTileOpen?: (tile: CanvasTile) => void;
/**
* "always" takes every wheel event over the canvas (full-screen use).
* "engaged" lets the page scroll until the canvas is clicked or focused,
* so an inline canvas never traps a reader mid-scroll.
*/
wheel?: "always" | "engaged";
/** Clear colour, any CSS colour three.js can parse (hex, rgb, hsl). */
background?: string;
className?: string;
label?: string;
}) {
const wrapRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const P = useMemo(() => ({ ...TILE_FIELD_DEFAULTS, ...params }), [params]);
const paramsRef = useRef(P);
const bgRef = useRef(background);
const openRef = useRef(onTileOpen);
const engagedRef = useRef(wheel === "always");
const [engaged, setEngaged] = useState(wheel === "always");
const [announce, setAnnounce] = useState("");
useEffect(() => {
paramsRef.current = P;
bgRef.current = background;
openRef.current = onTileOpen;
});
useEffect(() => {
engagedRef.current = wheel === "always" ? true : engaged;
}, [wheel, engaged]);
const tilesKey = tiles.map((t) => `${t.id}:${t.src.length}`).join(",");
useEffect(() => {
const root = wrapRef.current;
const canvas = canvasRef.current;
if (!root || !canvas) return;
let disposed = false;
const items = tiles.length ? tiles : [{ id: "empty", src: "" }];
const TILE_H = P.tileHeight;
const GAP = Math.max(0, P.tileGap);
const size = () => ({ w: Math.max(1, root.clientWidth), h: Math.max(1, root.clientHeight) });
// Renderer, scene pass into a render target, then lens + vignette.
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.autoClear = false;
const { w: w0, h: h0 } = size();
renderer.setSize(w0, h0, false);
const buf = renderer.getDrawingBufferSize(new THREE.Vector2());
const target = new THREE.WebGLRenderTarget(buf.x, buf.y, {
magFilter: THREE.LinearFilter,
minFilter: THREE.LinearFilter,
});
const scene = new THREE.Scene();
const bg = new THREE.Color(bgRef.current);
scene.background = bg;
const camera = new THREE.OrthographicCamera(-w0 / 2, w0 / 2, h0 / 2, -h0 / 2, -100, 100);
camera.position.z = 10;
const vignetteMat = new THREE.ShaderMaterial({
vertexShader: screenVert,
fragmentShader: vignetteFrag,
transparent: true,
depthTest: false,
depthWrite: false,
uniforms: { uVigStrength: { value: 0 }, uVigSize: { value: 1 } },
});
const barrelMat = new THREE.ShaderMaterial({
vertexShader: screenVert,
fragmentShader: barrelFrag,
uniforms: { uScene: { value: target.texture }, uBarrel: { value: 0 }, uBg: { value: new THREE.Vector3() } },
});
const screenGeom = new THREE.PlaneGeometry(2, 2);
const vignetteScene = new THREE.Scene().add(new THREE.Mesh(screenGeom, vignetteMat));
const barrelScene = new THREE.Scene().add(new THREE.Mesh(screenGeom, barrelMat));
const screenCam = new THREE.Camera();
// Tile pool: enough rows and strip repeats to cover the frame plus a margin.
let aspects = items.map((t) => Math.min(4, Math.max(0.25, t.aspect ?? 1)));
let widths = aspects.map((a) => TILE_H * a);
let stripW0 = widths.reduce((s, w) => s + w, 0) || TILE_H;
let prefix = prefixByPhase(widths);
const n = items.length;
const stripPool = stripW0 + n * GAP;
const repeats = Math.ceil(w0 / stripPool) + 2;
const rows = Math.ceil(h0 / (TILE_H + GAP)) + 3;
const spanX = repeats * stripPool;
const spanY = rows * (TILE_H + GAP);
const textures = items.map(() => placeholderTexture());
const geom = new THREE.PlaneGeometry(1, 1);
const meshes: THREE.Mesh<THREE.PlaneGeometry, THREE.ShaderMaterial>[] = [];
let index = 0;
for (let j = 0; j < rows; j++) {
const rowPhase = (j * 3) % n;
for (let r = 0; r < repeats; r++) {
for (let k = 0; k < n; k++) {
const texIdx = (k + rowPhase) % n;
const tw = widths[texIdx]!;
const mat = new THREE.ShaderMaterial({
vertexShader: quadVert,
fragmentShader: tileFrag,
uniforms: {
uTex: { value: textures[texIdx] },
uHover: { value: 0 },
uSizePx: { value: new THREE.Vector2(tw, TILE_H) },
uCornerPx: { value: Math.min(CORNER_PX, Math.max(0, Math.min(tw, TILE_H) / 2 - 0.5)) },
},
});
const mesh = new THREE.Mesh(geom, mat);
mesh.scale.set(tw, TILE_H, 1);
mesh.userData = { r, k, j, rowPhase, texIdx, index: index++, tw };
scene.add(mesh);
meshes.push(mesh);
}
}
}
const applyAspects = () => {
widths = aspects.map((a) => TILE_H * a);
stripW0 = widths.reduce((s, w) => s + w, 0) || TILE_H;
prefix = prefixByPhase(widths);
for (const m of meshes) {
const tw = widths[m.userData.texIdx as number]!;
m.scale.set(tw, TILE_H, 1);
m.userData.tw = tw;
m.material.uniforms.uSizePx.value.set(tw, TILE_H);
m.material.uniforms.uCornerPx.value = Math.min(CORNER_PX, Math.max(0, Math.min(tw, TILE_H) / 2 - 0.5));
}
};
// Textures stream in; a tile whose real aspect differs reflows the rows.
const loader = new THREE.TextureLoader();
loader.setCrossOrigin("anonymous");
const loaded: THREE.Texture[] = [];
items.forEach((tile, i) => {
if (!tile.src) return;
loader.load(tile.src, (tex) => {
if (disposed) return tex.dispose();
tex.colorSpace = THREE.SRGBColorSpace;
tex.minFilter = THREE.LinearFilter;
loaded.push(tex);
const img = tex.image as { width?: number; height?: number };
const a = Math.min(4, Math.max(0.25, (img.width || 1) / (img.height || 1)));
if (Math.abs(a - aspects[i]!) > 0.02) {
aspects = aspects.map((v, k) => (k === i ? a : v));
applyAspects();
}
for (const m of meshes) if (m.userData.texIdx === i) m.material.uniforms.uTex.value = tex;
});
});
// Pan state: wheel / drag / keys move the target; offset eases toward it.
let offsetX = 0;
let offsetY = 0;
let targetX = 0;
let targetY = 0;
let velX = 0;
let velY = 0;
let pointerX = 0;
let pointerY = 0;
let pointerInside = false;
let keyboardMode = false;
let hovered = -1;
let lastCentered = -1;
let drag: {
id: number;
lastX: number;
lastY: number;
lastT: number;
startX: number;
startY: number;
moved: boolean;
vx: number;
vy: number;
} | null = null;
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
let raf = 0;
let frameCount = 0;
let lastT = performance.now();
// Match the buffer to on-screen pixels: a CSS-scaled canvas (docs
// previews scale it down) shouldn't render more than it shows.
const pixelRatio = () => {
const rect = canvas.getBoundingClientRect();
const k = canvas.clientWidth ? Math.min(1, rect.width / canvas.clientWidth) : 1;
return Math.min(window.devicePixelRatio, 2) * k;
};
const syncSize = () => {
const { w, h } = size();
camera.left = -w / 2;
camera.right = w / 2;
camera.top = h / 2;
camera.bottom = -h / 2;
camera.updateProjectionMatrix();
renderer.setPixelRatio(pixelRatio());
renderer.setSize(w, h, false);
const b = renderer.getDrawingBufferSize(new THREE.Vector2());
target.setSize(b.x, b.y);
};
const tileAt = (idx: number) => {
const m = meshes.find((mesh) => mesh.userData.index === idx);
return m ? items[m.userData.texIdx as number] : undefined;
};
const draw = () => {
if (disposed) return;
const p = paramsRef.current;
// The preview's CSS scale can settle after mount; re-check twice a second.
if (++frameCount % 30 === 0 && Math.abs(pixelRatio() - renderer.getPixelRatio()) > 0.01) syncSize();
const reduced = prefersReducedMotion();
const now = performance.now();
const dt = Math.min(now - lastT, 50);
lastT = now;
const { w, h } = size();
const frames = dt / 16.67;
bg.set(bgRef.current);
targetX += velX;
targetY += velY;
const friction = reduced ? 0 : p.inertiaFriction;
velX *= Math.pow(friction, frames);
velY *= Math.pow(friction, frames);
if (Math.abs(velX) < 0.01) velX = 0;
if (Math.abs(velY) < 0.01) velY = 0;
const ease = reduced ? 1 : 1 - Math.pow(p.panEase, frames);
offsetX += (targetX - offsetX) * ease;
offsetY += (targetY - offsetY) * ease;
// Torus wrap. The period never drops below the pool's span, or two
// meshes would land on the same spot.
const stripW = stripW0 + n * GAP;
const cellH = TILE_H + GAP;
const totalW = Math.max(stripW, w + stripW);
const totalH = (Math.ceil(h / cellH) + 3) * cellH;
const periodX = Math.max(stripW * Math.ceil(totalW / stripW), spanX);
const periodY = Math.max(totalH, spanY);
for (const m of meshes) {
const u = m.userData as { r: number; k: number; j: number; rowPhase: number; tw: number; index: number };
const bx = u.r * stripW + prefix[u.rowPhase]![u.k]! + u.k * GAP + u.tw / 2;
const by = u.j * cellH;
const x = mod(bx - totalW / 2 + offsetX + totalW / 2, periodX) - totalW / 2;
const y = mod(by - totalH / 2 + offsetY + totalH / 2, periodY) - totalH / 2;
m.position.set(x, y, -u.index * PICK_Z_EPS);
}
// Pick under the pointer, or under the centre while using the keyboard.
hovered = -1;
if (p.hover && (pointerInside || keyboardMode)) {
ndc.set(keyboardMode ? 0 : (pointerX / w) * 2 - 1, keyboardMode ? 0 : -(pointerY / h) * 2 + 1);
raycaster.setFromCamera(ndc, camera);
const hit = raycaster.intersectObjects(meshes, false)[0];
if (hit) hovered = hit.object.userData.index as number;
}
for (const m of meshes) m.material.uniforms.uHover.value = m.userData.index === hovered ? 1 : 0;
if (keyboardMode && hovered !== lastCentered) {
lastCentered = hovered;
const t = tileAt(hovered);
if (t?.title) setAnnounce(t.title);
}
vignetteMat.uniforms.uVigStrength.value = p.vignetteStrength;
vignetteMat.uniforms.uVigSize.value = p.vignetteSize;
barrelMat.uniforms.uBarrel.value = p.barrel;
barrelMat.uniforms.uBg.value.set(bg.r, bg.g, bg.b);
renderer.setRenderTarget(target);
renderer.clear();
renderer.render(scene, camera);
renderer.render(vignetteScene, screenCam);
renderer.setRenderTarget(null);
renderer.clear();
renderer.render(barrelScene, screenCam);
raf = requestAnimationFrame(draw);
};
// Pointer position in layout px. The canvas may be CSS-scaled (a docs
// preview scales it down from its native width), so divide the scale out.
const local = (e: { clientX: number; clientY: number }) => {
const rect = canvas.getBoundingClientRect();
const k = rect.width ? canvas.clientWidth / rect.width : 1;
pointerX = (e.clientX - rect.left) * k;
pointerY = (e.clientY - rect.top) * k;
};
const open = () => {
const t = tileAt(hovered);
if (t && t.src) openRef.current?.(t);
};
const onPointerMove = (e: PointerEvent) => {
pointerInside = true;
keyboardMode = false;
local(e);
if (!drag || drag.id !== e.pointerId) return;
const dx = pointerX - drag.lastX;
const dy = pointerY - drag.lastY;
const now = performance.now();
const frames = Math.max((now - drag.lastT) / 16.67, 0.25);
drag.lastX = pointerX;
drag.lastY = pointerY;
drag.lastT = now;
// 1:1 under the hand: move the offset itself, not just the eased target.
targetX += dx;
targetY -= dy;
offsetX += dx;
offsetY -= dy;
drag.vx = dx / frames;
drag.vy = -dy / frames;
if (Math.hypot(pointerX - drag.startX, pointerY - drag.startY) > 6) drag.moved = true;
};
const onPointerDown = (e: PointerEvent) => {
if (e.pointerType === "mouse" && e.button !== 0) return;
local(e);
pointerInside = true;
setEngaged(true);
velX = 0;
velY = 0;
targetX = offsetX;
targetY = offsetY;
drag = {
id: e.pointerId,
lastX: pointerX,
lastY: pointerY,
lastT: performance.now(),
startX: pointerX,
startY: pointerY,
moved: false,
vx: 0,
vy: 0,
};
try {
canvas.setPointerCapture(e.pointerId);
} catch {}
};
const onPointerUp = (e: PointerEvent) => {
if (!drag || drag.id !== e.pointerId) return;
const { moved, vx, vy, lastT } = drag;
drag = null;
// Release momentum: carry the last pointer velocity unless the hand had stopped.
if (moved && performance.now() - lastT < 80 && !prefersReducedMotion()) {
velX = vx;
velY = vy;
}
try {
canvas.releasePointerCapture(e.pointerId);
} catch {}
if (!moved) open();
};
const onPointerCancel = () => {
drag = null;
};
const onPointerLeave = () => {
pointerInside = false;
if (wheel === "engaged") setEngaged(false);
};
const onWheel = (e: WheelEvent) => {
if (!engagedRef.current) return;
e.preventDefault();
pointerInside = true;
keyboardMode = false;
local(e);
targetX -= e.deltaX || 0;
targetY += e.deltaY || 0;
};
const onKeyDown = (e: KeyboardEvent) => {
const step = KEY_STEP * (e.shiftKey ? 3 : 1);
const moves: Record<string, [number, number]> = {
ArrowLeft: [step, 0],
ArrowRight: [-step, 0],
ArrowUp: [0, -step],
ArrowDown: [0, step],
};
const mv = moves[e.key];
if (mv) {
e.preventDefault();
keyboardMode = true;
velX = mv[0];
velY = mv[1];
} else if (e.key === "Enter" && keyboardMode) {
e.preventDefault();
open();
}
};
canvas.addEventListener("wheel", onWheel, { passive: false });
canvas.addEventListener("pointerdown", onPointerDown);
canvas.addEventListener("pointermove", onPointerMove);
canvas.addEventListener("pointerup", onPointerUp);
canvas.addEventListener("pointercancel", onPointerCancel);
canvas.addEventListener("pointerleave", onPointerLeave);
root.addEventListener("keydown", onKeyDown);
const ro = new ResizeObserver(syncSize);
ro.observe(root);
window.addEventListener("resize", syncSize);
syncSize();
draw();
return () => {
disposed = true;
cancelAnimationFrame(raf);
ro.disconnect();
window.removeEventListener("resize", syncSize);
canvas.removeEventListener("wheel", onWheel);
canvas.removeEventListener("pointerdown", onPointerDown);
canvas.removeEventListener("pointermove", onPointerMove);
canvas.removeEventListener("pointerup", onPointerUp);
canvas.removeEventListener("pointercancel", onPointerCancel);
canvas.removeEventListener("pointerleave", onPointerLeave);
root.removeEventListener("keydown", onKeyDown);
for (const m of meshes) m.material.dispose();
geom.dispose();
screenGeom.dispose();
vignetteMat.dispose();
barrelMat.dispose();
textures.forEach((t) => t.dispose());
loaded.forEach((t) => t.dispose());
target.dispose();
renderer.dispose();
};
// Rebuild only when the tiles or the pool geometry change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tilesKey, P.tileHeight, P.tileGap, wheel]);
return (
<div
ref={wrapRef}
role="group"
aria-roledescription="canvas"
aria-label={`${label}. Drag or use arrow keys to pan; Enter opens the centred tile.`}
tabIndex={0}
onFocus={() => setEngaged(true)}
onBlur={() => wheel === "engaged" && setEngaged(false)}
className={cn(
"relative isolate overflow-hidden rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring",
className,
)}
>
<canvas ref={canvasRef} aria-hidden className="block size-full cursor-grab touch-none active:cursor-grabbing" />
<p aria-live="polite" className="sr-only">
{announce}
</p>
</div>
);
}Tiles keep their real proportions, clamped between 1:4 and 4:1 so one panorama can't take over a row. Each row starts three tiles later than the one above, so identical tiles never line up into columns. On the live site, a mouse pans with the wheel only, so a click always opens a tile; the embed adds drag, because inline on a page you need a way to pan without scrolling it.
Speed you can see
The wave view is a strip that loops forever. Scrolling moves a target, the strip chases it, and the speed of that chase bends every plane with a sine wave. A strip that only slides reads as a carousel; one that bends reads as something you're pulling.
Loading preview…
Show code
"use client";
import { Canvas, useFrame, useLoader, useThree } from "@react-three/fiber";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import * as THREE from "three";
import { cn } from "@/lib/utils";
// A horizontal film strip of images that loops forever. It always has content
// past both edges, so both edges always fade (a fixed 24px mask, the same
// size as the registry's scroll fade, with no scroll position to track).
// Scroll, drag or arrow keys move a target; the strip lerps toward it, and the speed of that
// chase bends every plane with a sine wave in its vertex shader, so a fast
// scrub ripples the reel like cloth and it flattens as it comes to rest.
export type ReelItem = {
id: string;
src: string;
/** Width / height. */
aspect?: number;
title?: string;
};
export type WaveReelParams = {
/** World units added per wheel pixel, relative to 0.01. */
scrollSpeed: number;
/** Fraction of the remaining distance covered per 60Hz frame. */
lerp: number;
waveFrequency: number;
waveAmplitude: number;
planeHeight: number;
planeGap: number;
};
export const WAVE_REEL_DEFAULTS: WaveReelParams = {
scrollSpeed: 0.01,
lerp: 0.01,
waveFrequency: 1.1,
waveAmplitude: 0.003,
planeHeight: 2,
planeGap: 0.05,
};
/** The strip repeats until it is at least this wide, so the loop never shows a gap. */
const MIN_STRIP_WIDTH = 24;
const vertexShader = /* glsl */ `
uniform float uVelocity;
uniform float uWaveFreq;
uniform float uWaveAmp;
varying vec2 vUv;
void main() {
vUv = uv;
vec4 worldPos = modelMatrix * vec4(position, 1.0);
float wave = sin(worldPos.x * uWaveFreq) * uVelocity * uWaveAmp;
vec3 pos = position;
pos.y += wave;
pos.z += wave;
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(pos, 1.0);
}
`;
const fragmentShader = /* glsl */ `
uniform sampler2D uTexture;
varying vec2 vUv;
void main() {
gl_FragColor = texture2D(uTexture, vUv);
// Encode for the sRGB canvas; without it every image showed darker than its source.
#include <colorspace_fragment>
}
`;
const mod = (a: number, n: number) => ((a % n) + n) % n;
/** Frame-rate independent version of `x += (target - x) * k` at 60Hz. */
const lerpAlpha = (k: number, dtMs: number) => 1 - Math.pow(1 - k, dtMs / 16.67);
type Plane = { item: ReelItem; key: string; baseX: number; w: number };
type ReelMesh = THREE.Mesh<THREE.PlaneGeometry, THREE.ShaderMaterial>;
function layout(items: ReelItem[], h: number, gap: number) {
const planes: Plane[] = [];
let x = 0;
for (let rep = 0; items.length && (rep === 0 || x < MIN_STRIP_WIDTH); rep++) {
for (const item of items) {
const w = h * (item.aspect ?? 1);
planes.push({ item, key: `${rep}:${item.id}`, baseX: x + w / 2, w });
x += w + gap;
}
}
return { planes, total: x };
}
function usePlaceholder() {
const tex = useMemo(() => {
const t = new THREE.DataTexture(new Uint8Array([200, 200, 200, 255]), 1, 1);
t.needsUpdate = true;
return t;
}, []);
useEffect(() => () => tex.dispose(), [tex]);
return tex;
}
function PlaneMesh({
plane,
height,
texture,
register,
}: {
plane: Plane;
height: number;
texture: THREE.Texture;
register: (key: string, mesh: ReelMesh | null) => void;
}) {
const materialRef = useRef<THREE.ShaderMaterial>(null);
// Built once; texture swaps go through the material ref, not a rebuild.
const [uniforms] = useState(() => ({
uTexture: { value: texture },
uVelocity: { value: 0 },
uWaveFreq: { value: WAVE_REEL_DEFAULTS.waveFrequency },
uWaveAmp: { value: WAVE_REEL_DEFAULTS.waveAmplitude },
}));
useEffect(() => {
if (materialRef.current) materialRef.current.uniforms.uTexture.value = texture;
}, [texture]);
return (
<mesh
ref={(m: ReelMesh | null) => {
if (m) m.userData = { baseX: plane.baseX, w: plane.w, item: plane.item };
register(plane.key, m);
}}
position={[plane.baseX, 0, 0]}
>
<planeGeometry args={[plane.w, height, 30, 30]} />
<shaderMaterial ref={materialRef} uniforms={uniforms} vertexShader={vertexShader} fragmentShader={fragmentShader} />
</mesh>
);
}
function TexturedPlane(props: { plane: Plane; height: number; register: (key: string, mesh: ReelMesh | null) => void }) {
const loaded = useLoader(THREE.TextureLoader, props.plane.item.src);
const texture = useMemo(() => {
const t = loaded.clone();
t.colorSpace = THREE.SRGBColorSpace;
t.needsUpdate = true;
return t;
}, [loaded]);
useEffect(() => () => texture.dispose(), [texture]);
return <PlaneMesh {...props} texture={texture} />;
}
function FallbackPlane(props: { plane: Plane; height: number; register: (key: string, mesh: ReelMesh | null) => void }) {
return <PlaneMesh {...props} texture={usePlaceholder()} />;
}
type Input = {
target: number;
arrow: number;
paused: boolean;
reduced: boolean;
/** While dragging, the strip sits exactly on the target: no chase, no lag. */
direct: boolean;
};
/** What the scene hands back to the DOM layer for picking and 1:1 drags. */
type Bridge = {
pick: (x: number, y: number) => ReelItem | undefined;
/** World units per on-screen pixel, so a drag tracks the hand exactly. */
unitsPerPx: () => number;
/** The target value that matches where the strip is drawn right now. */
position: () => number;
};
function Reel({
planes,
total,
params,
input,
onBridge,
background,
}: {
planes: Plane[];
total: number;
params: WaveReelParams;
input: RefObject<Input>;
onBridge: (bridge: Bridge | null) => void;
background: string;
}) {
const { camera, gl } = useThree();
const meshes = useRef(new Map<string, ReelMesh>());
const scroll = useRef(0);
const last = useRef(0);
/** Distance travelled by held arrow keys, added on top of the input target. */
const arrowShift = useRef(0);
const raycaster = useMemo(() => new THREE.Raycaster(), []);
const register = useMemo(
() => (key: string, mesh: ReelMesh | null) => {
if (mesh) meshes.current.set(key, mesh);
else meshes.current.delete(key);
},
[],
);
useEffect(() => {
onBridge({
pick: (cx, cy) => {
const rect = gl.domElement.getBoundingClientRect();
if (!rect.width || !rect.height) return undefined;
raycaster.setFromCamera(
new THREE.Vector2(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1),
camera,
);
return raycaster.intersectObjects([...meshes.current.values()], false)[0]?.object.userData.item as
| ReelItem
| undefined;
},
unitsPerPx: () => {
const cam = camera as THREE.PerspectiveCamera;
const viewW = 2 * Math.tan((cam.fov * Math.PI) / 360) * cam.position.z * cam.aspect;
// Screen rect, so a CSS-scaled reel still tracks the pointer exactly.
return viewW / Math.max(1, gl.domElement.getBoundingClientRect().width);
},
position: () => scroll.current - arrowShift.current,
});
return () => onBridge(null);
}, [camera, gl, raycaster, onBridge]);
useFrame((_, delta) => {
const inp = input.current;
if (!inp || planes.length === 0) return;
const dt = Math.min(delta * 1000, 50);
if (!inp.paused) arrowShift.current += inp.arrow * dt * params.scrollSpeed;
// Reduced motion: a quick, flat chase instead of a slow, rippling one.
const k = inp.reduced ? Math.max(params.lerp, 0.25) : params.lerp;
const goal = inp.target + arrowShift.current;
scroll.current = inp.direct ? goal : scroll.current + (goal - scroll.current) * lerpAlpha(k, dt);
const velocity = (scroll.current - last.current) / Math.max(dt / 1000, 1e-4);
last.current = scroll.current;
const cam = camera as THREE.PerspectiveCamera;
const viewH = 2 * Math.tan((cam.fov * Math.PI) / 360) * cam.position.z;
const half = (viewH * cam.aspect) / 2;
const amp = inp.reduced ? 0 : params.waveAmplitude;
for (const mesh of meshes.current.values()) {
const { baseX, w } = mesh.userData as { baseX: number; w: number };
mesh.position.x = mod(baseX - scroll.current + half + w, total) - half - w;
const u = mesh.material.uniforms;
u.uVelocity.value += (velocity - u.uVelocity.value) * lerpAlpha(k, dt);
u.uWaveFreq.value = params.waveFrequency;
u.uWaveAmp.value = amp;
}
});
return (
<>
<color attach="background" args={[background]} />
{planes.map((plane) => (
<Suspense key={plane.key} fallback={<FallbackPlane plane={plane} height={params.planeHeight} register={register} />}>
{plane.item.src ? (
<TexturedPlane plane={plane} height={params.planeHeight} register={register} />
) : (
<FallbackPlane plane={plane} height={params.planeHeight} register={register} />
)}
</Suspense>
))}
</>
);
}
export function WaveReel({
items,
params,
onItemOpen,
paused = false,
wheel = "always",
background = "#ffffff",
className,
label = "Image reel",
}: {
items: ReelItem[];
params?: Partial<WaveReelParams>;
onItemOpen?: (item: ReelItem) => void;
/** Ignore wheel, drag and keys (e.g. while a menu covers the reel). */
paused?: boolean;
/**
* "always" takes every wheel event over the reel (full-screen use).
* "engaged" lets the page scroll until the reel is clicked or focused.
*/
wheel?: "always" | "engaged";
/** Clear colour, any CSS colour three.js can parse. */
background?: string;
className?: string;
label?: string;
}) {
const P = useMemo(() => ({ ...WAVE_REEL_DEFAULTS, ...params }), [params]);
const { planes, total } = useMemo(() => layout(items, P.planeHeight, P.planeGap), [items, P.planeHeight, P.planeGap]);
const rootRef = useRef<HTMLDivElement>(null);
const input = useRef<Input>({ target: 0, arrow: 0, paused, reduced: false, direct: false });
const bridgeRef = useRef<Bridge | null>(null);
const setBridge = useCallback((bridge: Bridge | null) => {
bridgeRef.current = bridge;
}, []);
const drag = useRef<{
id: number;
lastX: number;
lastT: number;
startX: number;
startY: number;
moved: boolean;
/** World units per second at the last move. */
v: number;
} | null>(null);
const [engaged, setEngaged] = useState(wheel === "always");
const engagedRef = useRef(engaged);
const [visible, setVisible] = useState(false);
// Device pixels per CSS pixel actually on screen (a scaled-down preview
// shouldn't render at full native resolution).
const [dpr, setDpr] = useState(1);
useEffect(() => {
input.current.paused = paused;
engagedRef.current = wheel === "always" || engaged;
}, [paused, wheel, engaged]);
useEffect(() => {
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
const sync = () => {
input.current.reduced = motion.matches;
};
sync();
motion.addEventListener("change", sync);
return () => motion.removeEventListener("change", sync);
}, []);
// Wheel on the reel only (production listened on window), and no frames
// while the reel is offscreen.
useEffect(() => {
const el = rootRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (input.current.paused || !engagedRef.current) return;
e.preventDefault();
const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
input.current.target += d * 0.002 * (P.scrollSpeed / 0.01);
};
el.addEventListener("wheel", onWheel, { passive: false });
const io = new IntersectionObserver(([entry]) => setVisible(entry?.isIntersecting ?? false));
io.observe(el);
const syncDpr = () => {
const k = el.clientWidth ? Math.min(1, el.getBoundingClientRect().width / el.clientWidth) : 1;
setDpr(Math.max(0.5, Math.min(window.devicePixelRatio || 1, 2) * k));
};
syncDpr();
// The preview's CSS scale can settle a frame or two after mount.
const settle = window.setTimeout(syncDpr, 250);
window.addEventListener("resize", syncDpr);
return () => {
el.removeEventListener("wheel", onWheel);
io.disconnect();
window.clearTimeout(settle);
window.removeEventListener("resize", syncDpr);
};
}, [P.scrollSpeed]);
return (
<div
ref={rootRef}
role="group"
aria-roledescription="carousel"
aria-label={`${label}. Drag, scroll or use the arrow keys to move.`}
tabIndex={0}
onFocus={() => setEngaged(true)}
onBlur={() => {
input.current.arrow = 0;
if (wheel === "engaged") setEngaged(false);
}}
onKeyDown={(e) => {
if (paused) return;
if (e.key === "ArrowRight") input.current.arrow = 1;
else if (e.key === "ArrowLeft") input.current.arrow = -1;
else return;
e.preventDefault();
}}
onKeyUp={(e) => {
if ((e.key === "ArrowRight" && input.current.arrow === 1) || (e.key === "ArrowLeft" && input.current.arrow === -1))
input.current.arrow = 0;
}}
onPointerDown={(e) => {
if (paused || (e.pointerType === "mouse" && e.button !== 0)) return;
setEngaged(true);
// Catch the strip where it is drawn, then hold it there under the hand.
const at = bridgeRef.current?.position();
if (at !== undefined) input.current.target = at;
input.current.direct = true;
drag.current = {
id: e.pointerId,
lastX: e.clientX,
lastT: performance.now(),
startX: e.clientX,
startY: e.clientY,
moved: false,
v: 0,
};
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
if (Math.hypot(e.clientX - d.startX, e.clientY - d.startY) > 8) d.moved = true;
const now = performance.now();
const du = -(e.clientX - d.lastX) * (bridgeRef.current?.unitsPerPx() ?? 0);
input.current.target += du;
d.v = du / Math.max((now - d.lastT) / 1000, 1 / 240);
d.lastX = e.clientX;
d.lastT = now;
}}
onPointerUp={(e) => {
const d = drag.current;
drag.current = null;
input.current.direct = false;
if (!d || d.id !== e.pointerId) return;
// Release momentum: project a short glide from the last velocity.
if (d.moved && performance.now() - d.lastT < 80 && !input.current.reduced) input.current.target += d.v * 0.35;
if (d.moved || !onItemOpen) return;
const item = bridgeRef.current?.pick(e.clientX, e.clientY);
if (item) onItemOpen(item);
}}
onPointerCancel={() => {
drag.current = null;
input.current.direct = false;
}}
onPointerLeave={() => {
if (wheel === "engaged" && !drag.current) setEngaged(false);
}}
className={cn(
"relative isolate cursor-grab touch-pan-y overflow-hidden rounded-xl [mask-image:linear-gradient(to_right,transparent,#000_24px,#000_calc(100%-24px),transparent)] outline-none select-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
className,
)}
style={{ background }}
>
<Canvas
camera={{ position: [0, 0, 4.5], fov: 45, near: 0.1, far: 100 }}
gl={{ alpha: false, antialias: true }}
dpr={dpr}
// Measure layout size, not the transformed box, so a CSS-scaled reel fills its frame.
resize={{ offsetSize: true }}
frameloop={visible ? "always" : "never"}
aria-hidden
>
<Reel planes={planes} total={total} params={P} input={input} onBridge={setBridge} background={background} />
</Canvas>
</div>
);
}The chase is frame-rate independent, so the glide feels the same at 60, 120 and 144Hz.
One request first
The plan broke on the API, not the graphics. Without a token, Are.na allows about 30 requests a minute. Fetching every channel at once blew through that, and the API answered with a 65-second wait. A cold page could hang for more than 80 seconds.
So the server now renders only the channel you're looking at, in one request that used to be two. The other nine load after the page is up, and their discs fill in as the art arrives. Without a token, those requests go one at a time, 2.2 seconds apart. Every response is cached by ETag, so a channel that hasn't changed costs a 304, not a download.
Outcome
I built Wordminders between April 27 and May 25, 2026, and it's still live at wordminders.space. I open it most days when I'm looking for references.
The cost is weight. Each view is its own WebGL scene, and three.js loads with the first view on every visit. The wave view loads only when you switch to it, and the picker's code and art load in the background once the page is up.
The rule I'd pass on: when an API rations you, spend the first request on what's on screen, and let everything else arrive behind it. It's how I build now. I load what's on screen first and let the rest stream in, and I design around an API's limits instead of its happy path.
The embeds here run on placeholder art instead of other people's Are.na images. With reduced motion on, nothing spins, ripples or glides.
Interactions
npx shadcn@latest add \
https://benjaminuribe.com/r/disc-picker.json \
https://benjaminuribe.com/r/tile-field.json \
https://benjaminuribe.com/r/wave-reel.jsonA portfolio you wander, for a portrait photographer in New York
Most portfolios make you pick a project before you've seen a photo. Nuvany's opens on all of them at once.
