"use client"; /** * vinyl.tsx — a record half out of its sleeve, with a tone arm that swings in on click. * Hover and it slides out and spins up; click and the needle drops with a scratch, then the arm lifts away. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useId, useImperativeHandle, useRef, type ButtonHTMLAttributes, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from "react"; type Palette = { sleeve: string; artA: string; artB: string; label: string }; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; palette?: Palette; }; const W = 250; const H = 150; const PADR = 70; const PADV = 50; const CW = W + PADR; const CH = H + PADV * 2; const SLEEVE = 150; const REC_D = 140; const REC_X = 110; // record left edge; centre at 180 const REC_CY = 75; const PIVOT = { x: 240, y: 8 + PADV }; const STYLUS = { x: 222, y: 120 + PADV }; const PARK = -38; const DEFAULT_PALETTE: Palette = { sleeve: "#d7c8b0", artA: "#c4512f", artB: "#26343f", label: "#c4512f" }; const INK = "#e8dcc8"; const WAVE_LEN = 90; const WAVE_N = 36; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); const tidy = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, ""); export function VinylButton({ children = "play", palette = DEFAULT_PALETTE, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const uid = `tb-vinyl-${tidy(useId())}`; const btnRef = useRef(null); const wrapRef = useRef(null); const recRef = useRef(null); const dipRef = useRef(null); const armRef = useRef(null); const headRef = useRef(null); const canvasRef = useRef(null); const playRef = useRef<() => void>(() => {}); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const btn = btnRef.current, wrap = wrapRef.current, rec = recRef.current, dip = dipRef.current; const arm = armRef.current, head = headRef.current, cv = canvasRef.current; if (!btn || !wrap || !rec || !dip || !arm || !head || !cv) return; const ctx = cv.getContext("2d"); if (!ctx) return; const media = window.matchMedia("(prefers-reduced-motion: reduce)"); let reduced = media.matches; let visible = true, hovering = false; let frame = 0, last = 0; let angle = 0, omega = 0; let t0 = 0; // click start (performance.now), 0 when idle let scratched = false; let epoch = 0; const timers = new Set(); const anims = new Set(); const running = () => !disabled && !btn.matches(":disabled") && visible && !document.hidden && !reduced; const later = (fn: () => void, ms: number) => { const e = epoch; const id = window.setTimeout(() => { timers.delete(id); if (e === epoch) fn(); }, ms); timers.add(id); }; const animate = (el: Element, frames: Keyframe[], opts: KeyframeAnimationOptions) => { const a = el.animate(frames, opts); anims.add(a); a.onfinish = () => { if (opts.fill !== "forwards") anims.delete(a); }; return a; }; const clearWork = () => { epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); anims.forEach((a) => a.cancel()); anims.clear(); }; const setup = () => { const scale = btn.getBoundingClientRect().width / (btn.offsetWidth || 1) || 1; const dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); cv.width = Math.round(CW * dpr); cv.height = Math.round(CH * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }; const clear = () => ctx.clearRect(0, 0, CW, CH); const setAngle = () => rec.style.setProperty("--tb-vinyl-a", `${(angle % 360).toFixed(2)}deg`); const drawWave = (tw: number, amp: number) => { clear(); if (amp <= 0.01) return; ctx.beginPath(); for (let i = 0; i < WAVE_N; i++) { const u = i / (WAVE_N - 1); const x = STYLUS.x + u * WAVE_LEN; const p = (u * WAVE_LEN - 120 * tw) / WAVE_LEN; let y: number; if (tw < 0.12) { const noise = Math.sin(i * 12.9898 + tw * 400) * 43758.5453; y = (noise - Math.floor(noise) - 0.5) * 2 * 18 * (1 - u * 0.6); } else { const env = 9 + 3 * Math.sin(tw * 5); const sv = 0.55 * Math.sin(p * 6.2832 * 3) + 0.3 * Math.sin(p * 6.2832 * 5.3 + 1.1) + 0.2 * Math.sin(p * 6.2832 * 9 + 2.3); y = (i % 2 ? 1 : -1) * env * (0.3 + 0.7 * Math.abs(sv)) * (1 - u * 0.35); } y *= Math.min(1, u / 0.12); const px = x, py = STYLUS.y + y * amp; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.lineJoin = "miter"; ctx.miterLimit = 4; ctx.strokeStyle = "rgba(12,10,9,.55)"; ctx.lineWidth = 3.2; ctx.stroke(); const g = ctx.createLinearGradient(STYLUS.x, 0, STYLUS.x + WAVE_LEN, 0); g.addColorStop(0, "rgba(232,220,200,.9)"); g.addColorStop(0.77, "rgba(232,220,200,.9)"); g.addColorStop(1, "rgba(232,220,200,0)"); ctx.strokeStyle = g; ctx.lineWidth = 1.5; ctx.stroke(); ctx.lineJoin = "round"; if (tw < 0.16) { const k = tw / 0.16; ctx.beginPath(); for (const a of [-150, -120, -95, -70, -45, -20, 10]) { const rad = (a * Math.PI) / 180, c = Math.cos(rad), sn = Math.sin(rad); ctx.moveTo(STYLUS.x + c * (4 + 10 * k), STYLUS.y + sn * (4 + 10 * k)); ctx.lineTo(STYLUS.x + c * (9 + 14 * k), STYLUS.y + sn * (9 + 14 * k)); } ctx.lineCap = "round"; ctx.strokeStyle = "rgba(12,10,9,.5)"; ctx.lineWidth = 2.6; ctx.stroke(); ctx.strokeStyle = `rgba(240,230,212,${((1 - k) * 0.95).toFixed(3)})`; ctx.lineWidth = 1.2; ctx.stroke(); ctx.lineCap = "butt"; } }; const tick = (now: number) => { frame = 0; if (!running()) { last = 0; return; } const dt = last ? Math.min(48, now - last) : 16; last = now; const base = hovering ? 200 : 0; let target = base; let tau = base > omega ? 450 : 1400; let amp = 0, tw = 0; let playing = false; if (t0) { const ct = now - t0; playing = true; if (ct < 400) { target = 360; tau = 300; } else if (ct < 520) { if (!scratched) { scratched = true; omega = Math.min(omega, 60); } target = 60; tau = 60; } else if (ct < 2100) { target = 360; tau = 200; } if (ct >= 400 && ct < 1900) { tw = (ct - 400) / 1000; amp = ct < 1600 ? 1 : clamp(1 - (ct - 1600) / 300); } if (ct >= 3400) { t0 = 0; playing = false; scratched = false; } } omega += (target - omega) * (1 - Math.exp(-dt / tau)); if (target === 0) { omega = Math.max(0, omega - 160 * dt / 1000); if (omega < 3) omega = 0; } angle += omega * (dt / 1000); setAngle(); if (playing && amp > 0) drawWave(tw, amp); else if (cv.dataset.on === "1") { clear(); cv.dataset.on = "0"; } if (amp > 0) cv.dataset.on = "1"; if (playing || hovering || omega > 0.5) frame = requestAnimationFrame(tick); else { omega = 0; last = 0; } }; const wake = () => { if (!frame && running()) { last = 0; frame = requestAnimationFrame(tick); } }; const staticWave = () => { clear(); ctx.beginPath(); const pts = [0, 0, -8, 12, -16, 6, 14, -5, -3, 0]; for (let i = 0; i < 31; i++) { const u = i / 30; const peak = Math.exp(-Math.pow((u - 0.25) / 0.06, 2)) * -9 + Math.exp(-Math.pow((u - 0.5) / 0.06, 2)) * 15 + Math.exp(-Math.pow((u - 0.74) / 0.06, 2)) * -11; const y = STYLUS.y + peak + (pts[i % pts.length] || 0) * 0.15; const x = STYLUS.x + u * WAVE_LEN; if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } ctx.lineJoin = "round"; ctx.strokeStyle = "rgba(12,10,9,.55)"; ctx.lineWidth = 3.5; ctx.stroke(); ctx.strokeStyle = INK; ctx.lineWidth = 1.6; ctx.stroke(); }; const refresh = () => { wrap.dataset.tbPaused = String(disabled || !visible || document.hidden); if (running()) { hovering = hovering && btn.matches(":hover"); wake(); } else { cancelAnimationFrame(frame); frame = 0; last = 0; omega = 0; t0 = 0; scratched = false; if (!reduced) { clearWork(); clear(); } } }; const enter = () => { hovering = true; wake(); }; const leave = () => { hovering = false; wake(); }; const mediaChange = () => { reduced = media.matches; clearWork(); clear(); delete wrap.dataset.tbArm; refresh(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; refresh(); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => setup()); setup(); setAngle(); io?.observe(wrap); ro?.observe(btn); window.addEventListener("resize", setup); btn.addEventListener("pointerenter", enter); btn.addEventListener("pointerleave", leave); document.addEventListener("visibilitychange", refresh); media.addEventListener("change", mediaChange); const lift = () => { animate(arm, [ { transform: "rotate(0deg)", opacity: 1 }, { transform: `rotate(${PARK}deg)`, opacity: 1, offset: 0.8 }, { transform: `rotate(${PARK}deg)`, opacity: 0 }, ], { duration: 500, easing: "ease-in-out", fill: "forwards" }); }; playRef.current = () => { if (disabled || btn.matches(":disabled")) return; if (reduced) { clearWork(); wrap.dataset.tbArm = "show"; staticWave(); later(() => { delete wrap.dataset.tbArm; clear(); }, 900); return; } const now = performance.now(); const ct = t0 ? now - t0 : -1; if (ct >= 0 && ct < 400) return; // arm is still swinging in if (ct >= 400 && ct < 1600) { // restart the scratch beat, no new arm swing t0 = now - 400; scratched = false; epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); later(lift, 1200); later(() => { t0 = 0; }, 3000); wake(); return; } clearWork(); t0 = now; scratched = false; animate(arm, [ { transform: `rotate(${PARK}deg)`, opacity: 0 }, { transform: `rotate(${PARK * 0.8}deg)`, opacity: 1, offset: 0.25 }, { transform: "rotate(0deg)", opacity: 1 }, ], { duration: 380, easing: "cubic-bezier(.3,0,.2,1)", fill: "forwards" }); animate(head, [{ transform: "scale(1.06)" }, { transform: "scale(1.06)", offset: 0.85 }, { transform: "scale(1)" }], { duration: 460, fill: "forwards" }); animate(dip, [ { transform: "translateY(0) scaleY(1)" }, { transform: "translateY(0) scaleY(.985)", offset: 0.27 }, { transform: "translateY(1.5px) scaleY(1)", offset: 0.45 }, { transform: "translateY(-.4px) scaleY(1)", offset: 0.75 }, { transform: "translateY(0) scaleY(1)" }, ], { duration: 300, delay: 380 }); later(lift, 1600); later(() => { anims.forEach((a) => a.cancel()); anims.clear(); }, 2200); later(() => { t0 = 0; }, 3400); wake(); }; refresh(); return () => { playRef.current = () => {}; cancelAnimationFrame(frame); clearWork(); io?.disconnect(); ro?.disconnect(); window.removeEventListener("resize", setup); btn.removeEventListener("pointerenter", enter); btn.removeEventListener("pointerleave", leave); document.removeEventListener("visibilitychange", refresh); media.removeEventListener("change", mediaChange); }; }, [disabled]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; playRef.current(); }; const grooves = Array.from({ length: 17 }, (_, i) => 26.5 + i * 2.35); const vars = { "--tb-vinyl-sleeve": palette.sleeve, "--tb-vinyl-label": palette.label, } as CSSProperties; return ( ); } export default VinylButton; const css = ` .tb-vinyl-wrap{position:relative;display:inline-block;width:${W}px;height:${H}px;vertical-align:middle} .tb-vinyl-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;margin:0;border:0;border-radius:6px;background:transparent; overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent; font:700 20px ui-sans-serif,system-ui,"Segoe UI",sans-serif} .tb-vinyl-btn:focus-visible{outline:3px solid #e0643a;outline-offset:5px} .tb-vinyl-btn:disabled{cursor:default;opacity:.6;filter:saturate(.5)} .tb-vinyl-slide{position:absolute;left:${REC_X}px;top:${REC_CY - REC_D / 2}px;width:${REC_D}px;height:${REC_D}px;pointer-events:none; transition:transform .4s cubic-bezier(.2,.8,.2,1)} .tb-vinyl-btn:hover .tb-vinyl-slide{transform:translateX(28px);transition:transform 360ms cubic-bezier(.34,1.4,.5,1)} .tb-vinyl-sleeve{transition:transform .4s cubic-bezier(.2,.8,.2,1)} .tb-vinyl-btn:hover .tb-vinyl-sleeve{transform:translateX(-4px);transition:transform 360ms cubic-bezier(.34,1.4,.5,1)} .tb-vinyl-btn:disabled .tb-vinyl-sleeve{transform:none} .tb-vinyl-cast{position:absolute;inset:0;display:block;border-radius:50%;box-shadow:0 1px 2px rgba(0,0,0,.45),0 8px 16px -2px rgba(0,0,0,.45)} .tb-vinyl-btn:disabled .tb-vinyl-slide{transform:none} .tb-vinyl-dip,.tb-vinyl-rec,.tb-vinyl-spin{position:absolute;inset:0;display:block} .tb-vinyl-spin{transform:rotate(var(--tb-vinyl-a,0deg))} .tb-vinyl-spin svg{display:block} .tb-vinyl-spec{position:absolute;inset:0;border-radius:50%; background:radial-gradient(circle at 34% 26%,rgba(255,255,255,.05),transparent 55%),conic-gradient(from 0deg,transparent 0 4deg,rgba(255,255,255,.04) 12deg,rgba(255,255,255,.13) 22deg,rgba(255,255,255,.26) 30deg,rgba(255,255,255,.13) 38deg,rgba(255,255,255,.04) 48deg,transparent 58deg 184deg,rgba(255,255,255,.03) 192deg,rgba(255,255,255,.10) 202deg,rgba(255,255,255,.19) 210deg,rgba(255,255,255,.10) 218deg,rgba(255,255,255,.03) 228deg,transparent 238deg); -webkit-mask:radial-gradient(circle,rgba(0,0,0,.3) 0 22px,rgba(0,0,0,.55) 27px,#000 50px,rgba(0,0,0,.7) 68px,transparent 70px);mask:radial-gradient(circle,rgba(0,0,0,.3) 0 22px,rgba(0,0,0,.55) 27px,#000 50px,rgba(0,0,0,.7) 68px,transparent 70px); box-shadow:inset 1px 1.5px 0 rgba(255,255,255,.13),inset -1px -2px 3px rgba(0,0,0,.6)} .tb-vinyl-clip{position:absolute;inset:0;display:block;border-radius:50%;overflow:hidden;pointer-events:none} .tb-vinyl-shade{position:absolute;left:${SLEEVE - REC_X}px;top:0;width:14px;height:${REC_D}px;display:block; background:linear-gradient(90deg,rgba(0,0,0,.6),rgba(0,0,0,.2) 45%,rgba(0,0,0,0));transition:transform .4s cubic-bezier(.2,.8,.2,1)} .tb-vinyl-btn:hover .tb-vinyl-shade{transform:translateX(-32px);transition:transform 360ms cubic-bezier(.34,1.4,.5,1)} .tb-vinyl-btn:disabled .tb-vinyl-shade{transform:none} .tb-vinyl-sleeve{position:absolute;left:0;top:0;width:${SLEEVE}px;height:${SLEEVE}px;pointer-events:none;border-radius:2px;box-shadow:0 1px 1px rgba(0,0,0,.22),0 3px 6px rgba(0,0,0,.22),0 12px 22px -6px rgba(0,0,0,.45)} .tb-vinyl-sleeve svg{display:block} .tb-vinyl-pill{position:absolute;left:22px;top:55px;width:120px;height:40px;box-sizing:border-box;border-radius:20px;pointer-events:none; display:flex;align-items:center;justify-content:center;background:radial-gradient(90% 75% at 50% 0%,rgba(255,255,255,.09),rgba(255,255,255,0) 70%),linear-gradient(180deg,#2b2927 0%,#1e1d1b 48%,#171615 100%); box-shadow:inset 0 1px 0 rgba(255,255,255,.12),inset 0 -1px 0 rgba(0,0,0,.55),0 0 0 1px rgba(0,0,0,.55),0 2px 3px rgba(0,0,0,.35),0 8px 16px -4px rgba(0,0,0,.5); transition:transform 140ms cubic-bezier(.3,.7,.4,1),box-shadow 140ms} .tb-vinyl-btn:hover .tb-vinyl-pill{transform:translate(-4px,-1px);transition:transform 360ms cubic-bezier(.34,1.4,.5,1),box-shadow 140ms} .tb-vinyl-btn:hover .tb-vinyl-label{color:#fff3df} .tb-vinyl-btn:active .tb-vinyl-pill{transform:translateY(1.5px) scale(.97);transition-duration:60ms;box-shadow:inset 0 1px 0 rgba(255,255,255,.06),inset 0 1px 3px rgba(0,0,0,.6),0 0 0 1px rgba(0,0,0,.55),0 1px 2px rgba(0,0,0,.4)} .tb-vinyl-btn:hover:active .tb-vinyl-pill{transform:translate(-4px,1.5px) scale(.97)} .tb-vinyl-btn:disabled .tb-vinyl-pill{transform:none} .tb-vinyl-label{position:relative;font:600 17px ui-sans-serif,system-ui,"Segoe UI",sans-serif;color:#eadfcb;text-shadow:0 -1px 0 rgba(0,0,0,.55);transition:color 140ms;padding-left:.14em;letter-spacing:.14em;text-transform:uppercase;line-height:1;white-space:nowrap} .tb-vinyl-arm{position:absolute;left:0;top:-${PADV}px;width:${CW}px;height:${CH}px;pointer-events:none;opacity:0; transform-origin:${PIVOT.x}px ${PIVOT.y}px;transform:rotate(${PARK}deg)} .tb-vinyl-arm svg{display:block;filter:drop-shadow(1px 3px 2px rgba(0,0,0,.45))} .tb-vinyl-wave{position:absolute;left:0;top:-${PADV}px;width:${CW}px;height:${CH}px;pointer-events:none} .tb-vinyl-wrap[data-tb-arm=show] .tb-vinyl-arm{opacity:1;transform:none;transition:opacity .15s} .tb-vinyl-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-vinyl-wrap *,.tb-vinyl-wrap *::before,.tb-vinyl-wrap *::after{animation:none!important;transition:none!important} .tb-vinyl-wrap .tb-vinyl-slide{transform:none!important} .tb-vinyl-wrap .tb-vinyl-sleeve,.tb-vinyl-wrap .tb-vinyl-shade,.tb-vinyl-wrap .tb-vinyl-pill{transform:none!important}} `;