"use client"; import { useReducedMotion } from "motion/react"; import { useEffect, useLayoutEffect, useMemo, useRef } from "react"; import { encode } from "uqr"; import { useMessages } from "@/lib/i18n"; import { cn } from "@/lib/utils"; export type QrCodeVariant = "swarm" | "ripple" | "scan" | "smoke"; export const qrCodeMessages = { label: "QR code for {value}", }; export type QrCodeMessages = typeof qrCodeMessages; export interface QrCodeOrigin { /** Horizontal position as a fraction of the canvas width, 0 is the left edge. */ x: number; /** Vertical position as a fraction of the canvas height, 0 is the top edge. */ y: number; } export interface AnimatedQrCodeProps { /** Text or URL the code encodes. */ value: string; /** Whether the code is drawn. Turning it on builds the code; turning it off plays the build backwards from wherever it is. */ shown: boolean; /** How the code builds: every piece flies in on a curved path, pops in place behind a spreading ring, drops into place behind a bar sweeping down, or rises as smoke and condenses from the bottom row up. Default: "swarm" */ variant?: QrCodeVariant; /** Side of the square canvas, in px, quiet zone included. Default: 296 */ size?: number; /** Where swarm pieces fly from and where the ripple ring starts. Scan and smoke ignore it. Default: bottom centre for swarm, centre for ripple */ origin?: QrCodeOrigin; /** Dot colour, any CSS colour. Default: "#0a0a0a" */ ink?: string; /** Background colour, any CSS colour. Keep it light so cameras can read the code. Default: "#ffffff" */ paper?: string; /** Called when a build or teardown finishes, with the `shown` value it ended on. */ onSettled?: (shown: boolean) => void; /** Translated strings, merged over the English defaults. */ labels?: Partial; /** Classes merged onto the canvas. */ className?: string; } /** Empty modules kept around the code on every side. */ const QUIET = 2; /** Gap between the first and the last piece starting, in ms. */ const SPREAD = 600; /** One piece's own arrival, in ms. */ const PIECE_IN = 500; const TOTAL = SPREAD + PIECE_IN; /** Taking the code down runs this much faster than building it. */ const EXIT_RATE = 1.6; /** Time constant for the clock turning around after a press mid-run, in ms. */ const TURN_MS = 90; /** Reduced motion keeps only an opacity fade of this length, in ms. */ const REDUCED_MS = 200; /** Random offset added to each swarm piece's start, in ms, so the order is not mechanical. */ const JITTER = 70; /** How far a swarm path bows outward, as a share of its length; each piece adds up to BEND_SPREAD more. */ const BEND = 0.14; const BEND_SPREAD = 0.12; /** Extra length of a piece at top speed on the longest flight, as a share of its size. Width shrinks to keep its area. */ const STRETCH = 1.3; /** Share of that stretch an eye takes. */ const EYE_STRETCH = 0.2; /** How far a scan piece drops into place, in modules. */ const DROP = 1.6; /** Height of the soft trail behind the scan bar, in px. */ const SCAN_TRAIL = 28; /** Soft puffs in the smoke plume. */ const PUFFS = 90; /** Life of one puff, in ms. Puffs are released over SMOKE_EMIT so the last fades out as the build ends. */ const PUFF_LIFE = 560; const SMOKE_EMIT = SPREAD * 0.9; /** Width of the band puffs rise from, as a share of the canvas. */ const SMOKE_BAND = 0.75; /** A puff's radius at birth and at the end of its life, in modules. */ const PUFF_START = 1.4; const PUFF_END = 3.6; /** Peak opacity of one puff. Overlap builds the density. Fewer, smaller puffs keep the fill cost near 3ms a frame. */ const PUFF_ALPHA = 0.22; /** How far a condensing piece drifts up into place, in modules. */ const SMOKE_DRIFT = 1; const TAU = Math.PI * 2; /** * One soft puff: a radial falloff tinted with the ink colour, drawn scaled * per puff. A sprite is far cheaper than a gradient or a blur per draw, and * blur filters would re-render every frame. */ const puffSprites = new Map(); function puffSprite(ink: string) { const cached = puffSprites.get(ink); if (cached) return cached; const s = 96; const sprite = document.createElement("canvas"); sprite.width = s; sprite.height = s; const g = sprite.getContext("2d"); if (g) { const fall = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); fall.addColorStop(0, "rgba(0,0,0,1)"); fall.addColorStop(0.45, "rgba(0,0,0,0.55)"); fall.addColorStop(1, "rgba(0,0,0,0)"); g.fillStyle = fall; g.fillRect(0, 0, s, s); g.globalCompositeOperation = "source-in"; g.fillStyle = ink; g.fillRect(0, 0, s, s); } puffSprites.set(ink, sprite); return sprite; } /** * Smoke is soft, so it is drawn at half the canvas resolution in CSS px (a * quarter of the device pixels on a 2x screen) and scaled up in one draw. * The puffs overlap heavily, and filling them at full resolution cost * several ms a frame. */ const SMOKE_RES = 0.5; const smokeLayers = new Map(); function smokeLayer(size: number) { if (!smokeLayers.has(size)) { const layer = document.createElement("canvas"); layer.width = Math.ceil(size * SMOKE_RES); layer.height = layer.width; const lctx = layer.getContext("2d"); lctx?.scale(SMOKE_RES, SMOKE_RES); smokeLayers.set(size, lctx); } return smokeLayers.get(size) ?? null; } function drawSmoke(ctx: CanvasRenderingContext2D, layout: Layout, clock: number, ink: string) { const { size, cell, pieces } = layout; const lctx = smokeLayer(size); if (!lctx) return; const sprite = puffSprite(ink); lctx.clearRect(0, 0, size, size); // A soft haze where each condensing piece is gathering. for (const p of pieces) { const t = (clock - pieceStart(p, "smoke", size)) / PIECE_IN; if (t <= 0 || t >= 1) continue; const k = settle(t); const half = p.side / 2; const haze = (p.eye ? half * 1.3 : cell * 1.6) * (1.4 - k); lctx.globalAlpha = 0.35 * Math.min(1, t * 4) * (1 - k); lctx.drawImage(sprite, p.x + half - haze, p.y + half - haze + (1 - k) * cell * SMOKE_DRIFT, haze * 2, haze * 2); } for (let i = 0; i < PUFFS; i++) { const age = clock - (i / PUFFS) * SMOKE_EMIT; const u = age / PUFF_LIFE; if (u <= 0 || u >= 1) continue; const h1 = hash(i * 3 + 1); const h2 = hash(i * 3 + 2); const h3 = hash(i * 3 + 3); // Rises fast, then slows and spreads as it cools. const rise = size * (0.55 + 0.6 * h2) * (1 - (1 - u) ** 2); const curl = Math.sin(h3 * TAU + u * 4) * cell * 2.4 * u; const x = size / 2 + (h1 - 0.5) * size * SMOKE_BAND + curl; const y = size + cell * 2 - rise; const r = cell * (PUFF_START + (PUFF_END - PUFF_START) * u); lctx.globalAlpha = PUFF_ALPHA * Math.min(1, u * 6) * (1 - u) ** 1.5; lctx.drawImage(sprite, x - r, y - r, r * 2, r * 2); } ctx.globalAlpha = 1; ctx.drawImage(lctx.canvas, 0, 0, size, size); } const QUARTER = Math.PI / 2; /** * Each piece moves like a critically damped spring pulled to its cell: it * leaves at rest, speeds up, and eases in with no overshoot. An ease-out * curve would start at full speed, which reads as a jolt at launch. The * curve is scaled to land exactly at t = 1. Local because it has to run per * piece on a canvas, where the shared motion tokens cannot. */ const OMEGA = 7; const SETTLE_END = 1 - (1 + OMEGA) * Math.exp(-OMEGA); const settle = (t: number) => (1 - (1 + OMEGA * t) * Math.exp(-OMEGA * t)) / SETTLE_END; /** Speed of `settle` at t, 0 to 1, peaking at t = 1 / OMEGA. */ const speedAt = (t: number) => OMEGA * t * Math.exp(1 - OMEGA * t); const DEFAULT_ORIGIN: Record<"swarm" | "ripple", QrCodeOrigin> = { swarm: { x: 0.5, y: 1 }, ripple: { x: 0.5, y: 0.5 }, }; const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v); function hash(n: number) { let t = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b); t ^= t >>> 13; t = Math.imul(t, 0xc2b2ae35); return ((t ^ (t >>> 16)) >>> 0) / 4294967296; } /** One thing that arrives: a data dot, or a whole finder eye. */ interface Piece { eye: boolean; /** Top-left corner, in px. */ x: number; y: number; /** Side, in px. */ side: number; /** Distance of its centre from the origin, 0 to 1. */ d: number; /** Small per-piece random value, 0 to 1. */ r: number; } interface Layout { cell: number; dot: number; radius: number; pieces: Piece[]; /** Largest origin distance, in px, so the ripple ring meets each piece as it starts. */ reach: number; ox: number; oy: number; size: number; } function isEye(x: number, y: number, n: number) { return (x < 7 && y < 7) || (x >= n - 7 && y < 7) || (x < 7 && y >= n - 7); } function buildLayout(value: string, size: number, origin: QrCodeOrigin): Layout { const { data, size: n } = encode(value || " ", { ecc: "M", border: 0 }); const cell = Math.max(2, Math.floor(size / (n + QUIET * 2))); const gap = Math.max(1, Math.round(cell * 0.12)); const dot = cell - gap; const start = Math.round((size - n * cell) / 2); const ox = origin.x * size; const oy = origin.y * size; const pieces: Piece[] = []; const add = (eye: boolean, x: number, y: number, side: number, seed: number) => { pieces.push({ eye, x, y, side, d: Math.hypot(x + side / 2 - ox, y + side / 2 - oy), r: hash(seed) }); }; const eyeSide = cell * 7 - gap; const far = start + (n - 7) * cell; add(true, start, start, eyeSide, -1); add(true, far, start, eyeSide, -2); add(true, start, far, eyeSide, -3); data.forEach((row, y) => { row.forEach((dark, x) => { if (dark && !isEye(x, y, n)) add(false, start + x * cell, start + y * cell, dot, y * n + x); }); }); const reach = Math.max(1, ...pieces.map((p) => p.d)); for (const p of pieces) p.d /= reach; return { cell, dot, radius: dot * 0.32, pieces, reach, ox, oy, size }; } /** A finder eye: a rounded ring and a rounded core, radii concentric. */ function drawEye(ctx: CanvasRenderingContext2D, x: number, y: number, side: number, cell: number, radius: number) { const r = cell * 2; ctx.beginPath(); ctx.roundRect(x, y, side, side, r); ctx.roundRect(x + cell, y + cell, side - cell * 2, side - cell * 2, r - cell); ctx.fill("evenodd"); ctx.beginPath(); ctx.roundRect(x + cell * 2, y + cell * 2, side - cell * 4, side - cell * 4, Math.max(radius, r - cell * 2)); ctx.fill(); } function pieceStart(p: Piece, variant: QrCodeVariant, size: number) { if (variant === "scan") return clamp01((p.y + p.side / 2) / size) * SPREAD; if (variant === "smoke") return (1 - clamp01((p.y + p.side / 2) / size)) * (SPREAD - JITTER) + p.r * JITTER; if (variant === "ripple") return p.d * SPREAD; return p.d * (SPREAD - JITTER) + p.r * JITTER; } function draw( ctx: CanvasRenderingContext2D, layout: Layout, clock: number, variant: QrCodeVariant, reduce: boolean, ink: string, paper: string, ) { const { cell, dot, radius, pieces, reach, ox, oy, size } = layout; ctx.globalAlpha = 1; ctx.fillStyle = paper; ctx.fillRect(0, 0, size, size); ctx.fillStyle = ink; if (reduce) { ctx.globalAlpha = clock / TOTAL; ctx.beginPath(); for (const p of pieces) if (!p.eye) ctx.roundRect(p.x, p.y, dot, dot, radius); ctx.fill(); for (const p of pieces) if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius); ctx.globalAlpha = 1; return; } // Landed pieces sit on whole pixels with no transform. Dots share one fill. ctx.beginPath(); for (const p of pieces) { if (!p.eye && clock - pieceStart(p, variant, size) >= PIECE_IN) ctx.roundRect(p.x, p.y, dot, dot, radius); } ctx.fill(); for (const p of pieces) { if (p.eye && clock - pieceStart(p, variant, size) >= PIECE_IN) drawEye(ctx, p.x, p.y, p.side, cell, radius); } // The wavefront each piece waits for, drawn faintly while it moves. const q = clock / SPREAD; if (q > 0 && q < 1 && (variant === "ripple" || variant === "scan")) { ctx.save(); const fade = Math.sin(Math.PI * q); if (variant === "ripple") { ctx.strokeStyle = ink; ctx.lineWidth = 1.5; ctx.globalAlpha = 0.22 * fade; ctx.beginPath(); ctx.arc(ox, oy, q * reach, 0, Math.PI * 2); ctx.stroke(); } else { const y = q * size; const trail = ctx.createLinearGradient(0, y - SCAN_TRAIL, 0, y); trail.addColorStop(0, "transparent"); trail.addColorStop(1, ink); ctx.globalAlpha = 0.08 * fade; ctx.fillStyle = trail; ctx.fillRect(0, y - SCAN_TRAIL, size, SCAN_TRAIL); ctx.globalAlpha = 0.3 * fade; ctx.fillStyle = ink; ctx.fillRect(0, y - 1, size, 1.5); } ctx.restore(); } for (const p of pieces) { const t = (clock - pieceStart(p, variant, size)) / PIECE_IN; if (t <= 0 || t >= 1) continue; const k = settle(t); const half = p.side / 2; const cx = p.x + half; const cy = p.y + half; ctx.save(); if (variant === "ripple") { // Pops in place from a round seed. ctx.globalAlpha = Math.min(1, t * 4); ctx.translate(cx, cy); if (p.eye) { ctx.scale(k, k); drawEye(ctx, -half, -half, p.side, cell, radius); } else { const s = dot * k; ctx.beginPath(); ctx.roundRect(-s / 2, -s / 2, s, s, s / 2 + (radius - s / 2) * k); ctx.fill(); } } else if (variant === "smoke") { // Condenses out of the plume: the solid piece firms up as it drifts up // into place, under a haze drawn with the smoke layer. ctx.globalAlpha = k ** 1.4; ctx.translate(0, (1 - k) * cell * SMOKE_DRIFT); if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius); else { ctx.beginPath(); ctx.roundRect(p.x, p.y, dot, dot, radius); ctx.fill(); } } else if (variant === "scan") { // Drops a little way into place as the bar passes over it. ctx.globalAlpha = Math.min(1, t * 3); ctx.translate(0, -(1 - k) * cell * DROP); if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius); else { ctx.beginPath(); ctx.roundRect(p.x, p.y, dot, dot, radius); ctx.fill(); } } else { // Swarm: a curved flight from the origin, bowing away from the centre // line so the paths fan out like a fountain instead of crossing. const dx = cx - ox; const dy = cy - oy; const side = dx < 0 ? 1 : -1; const bend = (BEND + BEND_SPREAD * p.r) * side; const qx = ox + dx / 2 + dy * bend; const qy = oy + dy / 2 - dx * bend; const u = 1 - k; const x = u * u * ox + 2 * u * k * qx + k * k * cx; const y = u * u * oy + 2 * u * k * qy + k * k * cy; const angle = Math.atan2(u * (qy - oy) + k * (cy - qy), u * (qx - ox) + k * (cx - qx)); const rest = Math.round(angle / QUARTER) * QUARTER; // Real speed along the curve, so it stretches most where it moves // fastest, and longer flights move faster. 0 at launch and on landing. const v = speedAt(t) * p.d; // Eyes are seven modules wide, so the same stretch would turn them into long bars. const along = 1 + STRETCH * v * (p.eye ? EYE_STRETCH : 1); const across = 1 / along; ctx.globalAlpha = Math.min(1, t * 6); ctx.translate(x, y); // Faces its heading in flight and turns square as it settles. ctx.rotate(rest + (angle - rest) * (1 - k) ** 2); if (p.eye) { ctx.scale(along, across); drawEye(ctx, -half, -half, p.side, cell, radius); } else { const l = dot * along; const w = dot * across; ctx.beginPath(); ctx.roundRect(-l / 2, -w / 2, l, w, Math.min(w / 2, radius + (w / 2 - radius) * Math.min(1, v * 2))); ctx.fill(); } } ctx.restore(); } // The plume drifts over the code, so the dots seem to come out of it. if (variant === "smoke") drawSmoke(ctx, layout, clock, ink); ctx.globalAlpha = 1; } /** * A QR code drawn on a canvas that builds itself piece by piece: the dots and * the three finder eyes fly in on curved paths, pop in behind a spreading * ring, or drop in behind a bar sweeping down. One reversible clock runs it, * so hiding plays the build backwards and a press mid-run turns around from * where it is. */ export function AnimatedQrCode({ value, shown, variant = "swarm", size = 296, origin, ink = "#0a0a0a", paper = "#ffffff", onSettled, labels, className, }: AnimatedQrCodeProps) { const t = useMessages("AnimatedQrCode", qrCodeMessages, labels); const reduce = useReducedMotion() ?? false; const canvasRef = useRef(null); const ctxRef = useRef(null); // Read from the first render only. The clock must never be reset by a // change of `shown`, or a press would skip straight to the end. const clockRef = useRef(shown ? TOTAL : 0); /** Clock ms per real ms, signed. Eased toward its goal on a turnaround. */ const rateRef = useRef(0); const fallback = DEFAULT_ORIGIN[variant === "ripple" ? "ripple" : "swarm"]; const ox = origin?.x ?? fallback.x; const oy = origin?.y ?? fallback.y; const layout = useMemo(() => buildLayout(value, size, { x: ox, y: oy }), [value, size, ox, oy]); const live = useRef({ layout, variant, reduce, ink, paper, onSettled }); useLayoutEffect(() => { live.current = { layout, variant, reduce, ink, paper, onSettled }; }); // Backing store at device resolution, scaled once. Draws only push and pop // their own transforms, so the scale is never lost. useLayoutEffect(() => { const canvas = canvasRef.current; if (!canvas) return; const dpr = Math.max(1, window.devicePixelRatio || 1); canvas.width = Math.round(size * dpr); canvas.height = Math.round(size * dpr); const ctx = canvas.getContext("2d"); if (!ctx) return; ctx.scale(dpr, dpr); ctxRef.current = ctx; }, [size]); // Repaint at the current time when the look changes, without moving it. useLayoutEffect(() => { const ctx = ctxRef.current; if (ctx) draw(ctx, layout, clockRef.current, variant, reduce, ink, paper); }, [layout, variant, reduce, ink, paper]); // Run the clock toward the end `shown` asks for, from wherever it is. useEffect(() => { const target = shown ? TOTAL : 0; if (clockRef.current === target) return; // From rest, start at full rate: each piece already eases out of rest. if (clockRef.current === 0 || clockRef.current === TOTAL) rateRef.current = shown ? 1 : -EXIT_RATE; let frame = 0; let last = performance.now(); const tick = (now: number) => { // Real time, so slow frames drop instead of slowing the build. The cap // only stops a long stall, like a background tab, from skipping to the end. const dt = Math.min(250, now - last); last = now; const cur = live.current; // A press mid-run eases the clock's rate into the new direction // instead of flipping it, so every piece slows, stops and turns back. const goal = shown ? 1 : -EXIT_RATE; rateRef.current += (goal - rateRef.current) * (1 - Math.exp(-dt / TURN_MS)); const scale = cur.reduce ? TOTAL / REDUCED_MS : 1; const next = Math.min(TOTAL, Math.max(0, clockRef.current + dt * rateRef.current * scale)); clockRef.current = next; const ctx = ctxRef.current; if (ctx) draw(ctx, cur.layout, next, cur.variant, cur.reduce, cur.ink, cur.paper); if (next === target) { cur.onSettled?.(shown); return; } frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }, [shown]); return ( ); }