"use client"; /** * yarn.tsx — a chunky hand-knit patch with a loose end. * Hover and the loose end dangles and sways; click to pull it: the stitches unravel into a ball that rolls away, then the patch knits itself back. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, type ButtonHTMLAttributes, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from "react"; type Palette = { yarn: string; light: string; dark: string; label: string }; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; palette?: Palette; }; const W = 236; const H = 84; const R = H / 2; const PL = 40; const PT = 40; const CW = W + PL + 140; const CH = H + PT + 160; const COLS = 13; const ROWS = 6; const COLW = W / COLS; const ROWH = H / ROWS; const FLOOR = H + 120; // ball bottom rests here (body coords) const ANCHOR_X = W * 0.62; const N = 40; // rope points const T_START = 80; const T_UNRAVEL = 600; const T_KNIT = 2200; const T_POP0 = 2600; const T_POP_SPAN = 1050; const T_END = 4300; const DEFAULT_PALETTE: Palette = { yarn: "#4a78a3", light: "#7292aa", dark: "#1d364d", label: "#ece4d2" }; type Stitch = { x: number; y: number; row: number; col: number; v: number; mode: 0 | 1 | 2 | 3; t: number }; const mulberry = (seed: number) => () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n)); const capDist = (x: number, y: number) => Math.hypot(x - clamp(x, R, W - R), y - R); // Stitch grid, unravel order and fuzz hairs are the same for every instance. const GRID: { x: number; y: number; row: number; col: number; v: number; edge: boolean }[] = []; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { const x = (c + 0.5) * COLW; const y = (r + 0.5) * ROWH; const d = capDist(x, y); if (d <= R + 2.5) GRID.push({ x, y, row: r, col: c, v: (r * 7 + c * 3) % 5 === 0 ? 1 : 0, edge: d > R - 7 }); } } const pick = (row: number, from: number, to: number, desc: boolean) => { const ids = GRID.map((g, i) => ({ g, i })).filter(({ g }) => g.row === row && g.col >= from && g.col <= to).map(({ i }) => i); return desc ? ids.reverse() : ids; }; const ORDER = [...pick(5, 0, COLS, true), ...pick(4, 0, COLS, false), ...pick(3, 11, COLS, true)]; const K = ORDER.length; const HAIRS = (() => { const r = mulberry(21); const out: { x0: number; y0: number; x1: number; y1: number; cx: number; cy: number; s: number }[] = []; for (let i = 0; i < 260; i++) { const t = r(); const per = 2 * (W - 2 * R) + 2 * Math.PI * R; let d = t * per; let x: number; let y: number; let nx: number; let ny: number; const seg = W - 2 * R; if (d < seg) { x = R + d; y = 0; nx = 0; ny = -1; } else if ((d -= seg) < Math.PI * R) { const a = -Math.PI / 2 + d / R; x = W - R + Math.cos(a) * R; y = R + Math.sin(a) * R; nx = Math.cos(a); ny = Math.sin(a); } else if ((d -= Math.PI * R) < seg) { x = W - R - d; y = H; nx = 0; ny = 1; } else { d -= seg; const a = Math.PI / 2 + d / R; x = R + Math.cos(a) * R; y = R + Math.sin(a) * R; nx = Math.cos(a); ny = Math.sin(a); } const len = 1.2 + r() * 1.8; const j = (r() - 0.5) * 2.2; const dx = nx * Math.cos(j) - ny * Math.sin(j); const dy = nx * Math.sin(j) + ny * Math.cos(j); const sx = x - nx * 1.0, sy = y - ny * 1.0; if (Math.abs(y - R) < 4 && (x < 4 || x > W - 4)) continue; let best = 0; let bd = Infinity; GRID.forEach((g, gi) => { const dd = Math.hypot(g.x - x, g.y - y); if (dd < bd) { bd = dd; best = gi; } }); out.push({ x0: sx, y0: sy, x1: x + dx * len, y1: y + dy * len, cx: x + dx * len * 0.5 - ny * 1.2, cy: y + dy * len * 0.5 + nx * 1.2, s: best }); } return out; })(); const ABOVE = GRID.map((g) => GRID.findIndex((o) => o.col === g.col && o.row === g.row - 1)); export function YarnButton({ children = "knit", palette = DEFAULT_PALETTE, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); const wrapRef = useRef(null); const canvasRef = useRef(null); const labelRef = useRef(null); const dimRef = useRef(null); const play = useRef<() => void>(() => {}); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const btn = btnRef.current; const wrap = wrapRef.current; const canvas = canvasRef.current; const label = labelRef.current; const dim = dimRef.current; if (!btn || !wrap || !canvas || !label || !dim) return; const ctx = canvas.getContext("2d"); if (!ctx) return; const media = window.matchMedia("(prefers-reduced-motion: reduce)"); let epoch = 0; let raf = 0; let last = 0; let visible = true; let hovering = false; let rect: DOMRect | null = null; let curX = ANCHOR_X; let simT = 0; let phase: "idle" | "play" | "knit" = "idle"; let t0 = 0; let nextOut = 0; let nextPop = 0; let gone = 0; let squash = 1; let L = 0; let ax = ANCHOR_X; let ay = H; let swayOff = 0; let kink = 0; let ballOn = false; let bx = 0, by = 0, bvx = 0, bvy = 0, br = 0, bang = 0, bhit = false, bShadow = 1; let knitFrom = { x: 0, y: 0 }; const px = new Float64Array(N), py = new Float64Array(N), ox = new Float64Array(N), oy = new Float64Array(N); const stitches: Stitch[] = GRID.map((g) => ({ x: g.x, y: g.y, row: g.row, col: g.col, v: g.v, mode: 0, t: 0 })); let sprites: HTMLCanvasElement[] = []; let ballSprite: HTMLCanvasElement | null = null; let bevelSprite: HTMLCanvasElement | null = null; let shadowSprite: HTMLCanvasElement | null = null; let edgeShade: HTMLCanvasElement | null = null; const colBot = new Float64Array(COLS); const colCut = new Uint8Array(COLS); const timers = new Set(); const anims = new Set(); const later = (fn: () => void, ms: number) => { const my = epoch; const id = window.setTimeout(() => { timers.delete(id); if (my === epoch) fn(); }, ms); timers.add(id); }; const allowed = () => !disabled && !btn.matches(":disabled") && visible && !document.hidden && !media.matches; const resetRope = () => { for (let i = 0; i < N; i++) { px[i] = ox[i] = ax; py[i] = oy[i] = ay; } }; resetRope(); const mk = (w: number, h: number, dpr: number, fn: (g: CanvasRenderingContext2D) => void) => { const c = document.createElement("canvas"); c.width = Math.ceil(w * dpr); c.height = Math.ceil(h * dpr); const g = c.getContext("2d"); if (g) { g.scale(dpr, dpr); fn(g); } return c; }; const buildSprites = (dpr: number) => { const loop = (g: CanvasRenderingContext2D, sgn: number, kind: number, shadowOnly = false) => { g.save(); g.translate(14 + sgn * 4.4, 12.5); if (kind === 3) { g.rotate(sgn * 0.62); g.lineCap = "round"; g.lineJoin = "round"; const wav = () => { g.beginPath(); g.moveTo(0, -11.2); for (let k = 0; k < 4; k++) g.quadraticCurveTo(k % 2 ? 1.3 : -1.3, -11.2 + k * 5.6 + 2.8, 0, -11.2 + (k + 1) * 5.6); }; g.lineWidth = 6.0; g.strokeStyle = palette.dark; wav(); g.stroke(); g.lineWidth = 4.4; g.strokeStyle = palette.yarn; wav(); g.stroke(); g.globalAlpha = 0.45; g.lineWidth = 1.0; g.strokeStyle = palette.light; wav(); g.stroke(); g.globalAlpha = 1; } else { g.rotate(sgn * 0.62); const el = () => { g.beginPath(); g.moveTo(0, -10); g.bezierCurveTo(5.2, -6.5, 5.2, 5.5, 0, 10); g.bezierCurveTo(-5.2, 6.5, -5.2, -5.5, 0, -10); g.closePath(); }; if (shadowOnly) { el(); g.fillStyle = palette.dark; g.fill(); g.restore(); return; } el(); g.fillStyle = palette.yarn; g.fill(); let gr = g.createLinearGradient(-4.2, 0, 4.2, 0); gr.addColorStop(0, "rgba(0,0,0,.50)"); gr.addColorStop(0.3, "rgba(0,0,0,0)"); gr.addColorStop(0.55, "rgba(255,255,255,.16)"); gr.addColorStop(0.78, "rgba(255,255,255,0)"); gr.addColorStop(1, "rgba(0,0,0,.34)"); g.fillStyle = gr; g.fill(); gr = g.createLinearGradient(0, -10, 0, 10); gr.addColorStop(0, "rgba(255,255,255,.12)"); gr.addColorStop(0.5, "rgba(255,255,255,0)"); gr.addColorStop(1, "rgba(0,0,0,.28)"); g.fillStyle = gr; g.fill(); if (kind === 1) { g.fillStyle = "rgba(255,255,255,.06)"; g.fill(); } g.beginPath(); g.ellipse(0.6, -4.6, 1.3, 3.2, 0, 0, Math.PI * 2); g.fillStyle = "rgba(255,255,255,.08)"; g.fill(); g.save(); el(); g.clip(); for (let k = 0; k < 5; k++) { const y = -9 + k * 4.4; g.beginPath(); g.moveTo(-4.4, y + 2.2); g.quadraticCurveTo(0, y + 0.6, 4.4, y - 2.6); g.strokeStyle = palette.dark; g.globalAlpha = .42; g.lineWidth = 1.3; g.stroke(); g.beginPath(); g.moveTo(-4.4, y + 3.8); g.quadraticCurveTo(0, y + 2.2, 4.4, y - 1.0); g.strokeStyle = palette.light; g.globalAlpha = .30; g.lineWidth = 1.1; g.stroke(); } g.restore(); g.globalAlpha = .35; el(); g.lineWidth = 0.6; g.strokeStyle = palette.dark; g.stroke(); g.globalAlpha = 1; } g.restore(); }; sprites = [0, 1, 3].map((kind) => mk(28, 28, dpr, (g) => { if (kind === 3) { loop(g, -1, kind); loop(g, 1, kind); return; } g.save(); g.shadowColor = "rgba(4,12,22,.6)"; g.shadowBlur = 3 * dpr; g.shadowOffsetY = 2.4 * dpr; loop(g, -1, kind, true); loop(g, 1, kind, true); g.restore(); loop(g, -1, kind); loop(g, 1, kind); })); bevelSprite = mk(W, H, dpr, (g) => { g.clip(lumpy); const ring = new Path2D(); ring.rect(-60, -60, W + 120, H + 120); ring.addPath(lumpy); g.fillStyle = "#000"; g.shadowColor = "rgba(4,14,24,.75)"; g.shadowBlur = 12 * dpr; g.shadowOffsetY = -2 * dpr; g.fill(ring, "evenodd"); g.shadowColor = "transparent"; g.shadowBlur = 0; g.shadowOffsetY = 0; const gr = g.createLinearGradient(0, 0, 0, H); gr.addColorStop(0, "rgba(255,255,255,.12)"); gr.addColorStop(0.38, "rgba(255,255,255,0)"); gr.addColorStop(0.72, "rgba(0,0,0,0)"); gr.addColorStop(1, "rgba(0,0,0,.30)"); g.fillStyle = gr; g.fill(lumpy); }); shadowSprite = mk(W + 80, H + 80, dpr, (g) => { g.translate(40, 40); g.fillStyle = "#000"; for (const [blur, oy, col] of [[18, 8, "rgba(0,0,0,.42)"], [4, 2, "rgba(0,0,0,.38)"]] as [number, number, string][]) { g.save(); g.translate(-10000, 0); g.shadowOffsetX = 10000 * dpr; g.shadowOffsetY = oy * dpr; g.shadowBlur = blur * dpr; g.shadowColor = col; g.fill(lumpy); g.restore(); } }); edgeShade = mk(4, 14, dpr, (g) => { const gr = g.createLinearGradient(0, 0, 0, 14); gr.addColorStop(0, "rgba(0,0,0,.55)"); gr.addColorStop(1, "rgba(0,0,0,0)"); g.fillStyle = gr; g.fillRect(0, 0, 4, 14); }); ballSprite = mk(64, 64, dpr, (g) => { g.translate(32, 32); g.save(); g.beginPath(); g.arc(0, 0, 30, 0, Math.PI * 2); g.clip(); g.fillStyle = palette.yarn; g.fillRect(-32, -32, 64, 64); g.lineCap = "round"; for (const rot of [0.3, 1.25, 2.2, 2.9]) { g.save(); g.rotate(rot); for (let k = 0; k < 4; k++) { const path = (dy: number) => { g.beginPath(); g.ellipse(0, -8 + k * 5.6 + dy, 30, 10 + k * 4, 0, 0, Math.PI); }; g.globalAlpha = 0.8; g.lineWidth = 5.6; g.strokeStyle = palette.dark; path(0); g.stroke(); g.globalAlpha = 1; g.lineWidth = 4.2; g.strokeStyle = palette.yarn; path(0); g.stroke(); g.globalAlpha = 0.45; g.lineWidth = 1.2; g.strokeStyle = palette.light; path(-1.0); g.stroke(); } g.restore(); } g.restore(); g.globalAlpha = 0.35; g.strokeStyle = palette.light; g.lineWidth = 0.5; g.beginPath(); for (let i = 0; i < 24; i++) { const a = (i / 24) * Math.PI * 2 + (i % 3) * 0.1, l = 1.5 + (i % 4) * 0.5; g.moveTo(Math.cos(a) * 29.5, Math.sin(a) * 29.5); g.lineTo(Math.cos(a) * (29.5 + l), Math.sin(a) * (29.5 + l)); } g.stroke(); g.globalAlpha = 1; }); }; const setup = () => { const r = btn.getBoundingClientRect(); const scale = r.width / (btn.offsetWidth || 1) || 1; const dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); canvas.width = Math.round(CW * dpr); canvas.height = Math.round(CH * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); buildSprites(dpr); rect = null; if (!raf) draw(); }; const lumpy = (() => { const p = new Path2D(); const seg = W - 2 * R, per = 2 * seg + 2 * Math.PI * R, n = 380; for (let i = 0; i <= n; i++) { let d = (i / n) * per; let x: number, y: number, nx: number, ny: number; if (d < seg) { x = R + d; y = 0; nx = 0; ny = -1; } else if ((d -= seg) < Math.PI * R) { const a = -Math.PI / 2 + d / R; x = W - R + Math.cos(a) * R; y = R + Math.sin(a) * R; nx = Math.cos(a); ny = Math.sin(a); } else if ((d -= Math.PI * R) < seg) { x = W - R - d; y = H; nx = 0; ny = 1; } else { d -= seg; const a = Math.PI / 2 + d / R; x = R + Math.cos(a) * R; y = R + Math.sin(a) * R; nx = Math.cos(a); ny = Math.sin(a); } const o = 1.6 * Math.abs(Math.sin((Math.PI * ((i / n) * per)) / (COLW / 2))) - 0.6; if (i) p.lineTo(x + nx * o, y + ny * o); else p.moveTo(x + nx * o, y + ny * o); } p.closePath(); return p; })(); function draw() { ctx.clearRect(0, 0, CW, CH); ctx.save(); ctx.translate(PL, PT); // rope if (L > 1) { const pts: [number, number][] = []; for (let i = 0; i < N; i++) { const a = Math.max(0, i - 1), b = Math.min(N - 1, i + 1); let tx = px[b] - px[a], ty = py[b] - py[a]; const tl = Math.hypot(tx, ty) || 1; tx /= tl; ty /= tl; const o = Math.sin(i * 0.45 + 0.6 + (phase === "idle" ? simT * 0.003 : 0)) * kink * (i === 0 ? 0 : phase === "idle" ? i / N : 1) + (!ballOn && i > N - 7 ? (i - (N - 7)) * 1.6 : 0); pts.push([px[i] - ty * o, py[i] + tx * o]); } let end = N; if (ballOn && br > 0.5) { for (let i = 1; i < N; i++) if (Math.hypot(pts[i][0] - bx, pts[i][1] - by) < br * 0.85) { end = i + 1; break; } } const path = () => { ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < end - 1; i++) ctx.quadraticCurveTo(pts[i][0], pts[i][1], (pts[i][0] + pts[i + 1][0]) / 2, (pts[i][1] + pts[i + 1][1]) / 2); ctx.lineTo(pts[end - 1][0], pts[end - 1][1]); }; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.strokeStyle = palette.dark; ctx.lineWidth = 9.5; path(); ctx.stroke(); ctx.strokeStyle = palette.yarn; ctx.lineWidth = 7.6; path(); ctx.stroke(); ctx.globalAlpha = 0.16; ctx.strokeStyle = palette.light; ctx.lineWidth = 2.4; path(); ctx.stroke(); const marks = (off: number) => { ctx.beginPath(); let s0 = 0, next = 1.7 + off; for (let i = 0; i < end - 1; i++) { const dx = pts[i + 1][0] - pts[i][0], dy = pts[i + 1][1] - pts[i][1]; const sl = Math.hypot(dx, dy); if (sl < 1e-4) continue; const tx = dx / sl, ty = dy / sl, nx = -ty, ny = tx; while (next <= s0 + sl) { const f = next - s0; const qx = pts[i][0] + tx * f, qy = pts[i][1] + ty * f; ctx.moveTo(qx - nx * 3.4 - tx * 2.4, qy - ny * 3.4 - ty * 2.4); ctx.quadraticCurveTo(qx + tx * 1.0, qy + ty * 1.0, qx + nx * 3.4 + tx * 2.4, qy + ny * 3.4 + ty * 2.4); next += 4.6; } s0 += sl; } }; ctx.lineCap = "round"; ctx.globalAlpha = 0.45; ctx.strokeStyle = palette.dark; ctx.lineWidth = 2.0; marks(0); ctx.stroke(); ctx.globalAlpha = 0.35; ctx.strokeStyle = palette.light; ctx.lineWidth = 1.2; marks(2.3); ctx.stroke(); ctx.globalAlpha = 1; if (!ballOn) { const [qx, qy] = pts[N - 1], [rx, ry] = pts[N - 3]; const ang = Math.atan2(qy - ry, qx - rx); ctx.beginPath(); for (const d of [-0.5, 0, 0.5]) { ctx.moveTo(qx, qy); ctx.lineTo(qx + Math.cos(ang + d) * 4, qy + Math.sin(ang + d) * 4); } ctx.strokeStyle = palette.light; ctx.globalAlpha = 0.7; ctx.lineWidth = 1; ctx.stroke(); ctx.globalAlpha = 1; } } colBot.fill(-1); colCut.fill(0); for (const s of stitches) { if (s.mode === 2) colCut[s.col] = 1; else colBot[s.col] = Math.max(colBot[s.col], s.y + ROWH / 2); } const keepPath = () => { ctx.beginPath(); for (let c = 0; c < COLS; c++) { const x0 = c === 0 ? -40 : c * COLW, x1 = c === COLS - 1 ? W + 40 : (c + 1) * COLW + 0.5; const b = colCut[c] ? colBot[c] : H + 40; if (b > 0) ctx.rect(x0, -40, x1 - x0, b + 40); } }; ctx.save(); ctx.translate(0, H); ctx.scale(1, squash); ctx.translate(0, -H); ctx.clip(lumpy); ctx.beginPath(); for (const s of stitches) if (s.mode === 0 || s.mode === 3) ctx.rect(s.x - COLW / 2, s.y - ROWH / 2 - 0.2, COLW, ROWH + 0.4); ctx.fillStyle = palette.dark; ctx.fill(); for (let i = stitches.length - 1; i >= 0; i--) { const s = stitches[i]; if (s.mode === 2) continue; const spr = sprites[s.mode === 1 ? 2 : s.v]; if (!spr) continue; if (s.mode === 3) { const p = clamp((simT - s.t) / 120, 0, 1); const sc = p < 0.6 ? 0.6 + (0.45 * p) / 0.6 : 1.05 - 0.05 * ((p - 0.6) / 0.4); ctx.save(); ctx.translate(s.x, s.y); ctx.scale(sc, sc); ctx.drawImage(spr, -14, -12.5, 28, 28); ctx.restore(); } else ctx.drawImage(spr, s.x - 14, s.y - 12.5, 28, 28); } // dangling frogged loops on the ragged edge if (gone > 0) { ctx.beginPath(); let any = false; for (let i = 0; i < stitches.length; i++) { const s = stitches[i]; if (s.mode !== 2 || ABOVE[i] < 0) continue; const am = stitches[ABOVE[i]].mode; if (am !== 0 && am !== 1) continue; const hv = ((s.col * 37 + s.row * 11) % 7) / 6; const rr = 3.6 + 1.6 * hv, cy0 = s.y - ROWH / 2 + 1.0 + 2.6 * hv, tilt = (hv - 0.5) * 0.5; const a0 = 0.08 * Math.PI + tilt, a1 = 0.92 * Math.PI + tilt; ctx.moveTo(s.x + rr * Math.cos(a0), cy0 + rr * Math.sin(a0)); ctx.arc(s.x, cy0, rr, a0, a1); any = true; } if (any) { ctx.lineCap = "round"; ctx.strokeStyle = palette.dark; ctx.lineWidth = 5.0; ctx.stroke(); ctx.strokeStyle = palette.yarn; ctx.lineWidth = 3.6; ctx.stroke(); ctx.strokeStyle = palette.light; ctx.lineWidth = 1.0; ctx.globalAlpha = 0.5; ctx.stroke(); ctx.globalAlpha = 1; } } if (bevelSprite) { if (gone > 0) { ctx.save(); keepPath(); ctx.clip(); } ctx.globalCompositeOperation = "source-atop"; ctx.drawImage(bevelSprite, 0, 0, W, H); ctx.globalCompositeOperation = "source-over"; if (gone > 0) ctx.restore(); } ctx.restore(); // shadows behind everything ctx.globalCompositeOperation = "destination-over"; if (ballOn && br > 0.5) { ctx.save(); ctx.translate(bx, FLOOR); ctx.scale(1, 0.24 * (0.6 + 0.4 * bShadow)); const sg = ctx.createRadialGradient(0, 0, 0, 0, 0, br * 1.35); sg.addColorStop(0, `rgba(0,0,0,${0.6 * bShadow})`); sg.addColorStop(0.6, `rgba(0,0,0,${0.28 * bShadow})`); sg.addColorStop(1, "rgba(0,0,0,0)"); ctx.fillStyle = sg; ctx.beginPath(); ctx.arc(0, 0, br * 1.35, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } if (shadowSprite) { ctx.save(); if (gone > 0) { let top = H + 40; for (let c = 0; c < COLS; c++) if (colCut[c]) top = Math.min(top, colBot[c]); ctx.beginPath(); ctx.rect(-40, -40, W + 80, top + 38); ctx.clip(); } ctx.drawImage(shadowSprite, -40, -40, W + 80, H + 80); ctx.restore(); } if (edgeShade && gone > 0) for (let c = 0; c < COLS; c++) if (colBot[c] > 0) ctx.drawImage(edgeShade, c * COLW - 0.5, colBot[c] - 3, COLW + 1, 14); ctx.globalCompositeOperation = "source-over"; // fuzz halo ctx.save(); if (gone > 0) { keepPath(); ctx.clip(); } ctx.strokeStyle = palette.light; ctx.lineWidth = 3; ctx.globalAlpha = 0.10; ctx.stroke(lumpy); ctx.globalAlpha = 0.28; ctx.lineWidth = 0.5; ctx.lineCap = "round"; ctx.beginPath(); for (const h of HAIRS) { if (stitches[h.s].mode === 2) continue; ctx.moveTo(h.x0, h.y0); ctx.quadraticCurveTo(h.cx, h.cy, h.x1, h.y1); } ctx.stroke(); ctx.globalAlpha = 1; ctx.restore(); if (ballOn && br > 0.5 && ballSprite) { ctx.save(); ctx.translate(bx, by); ctx.save(); ctx.rotate(bang); ctx.drawImage(ballSprite, -br * (32 / 30), -br * (32 / 30), br * (64 / 30), br * (64 / 30)); ctx.restore(); const g = ctx.createRadialGradient(-br * 0.45, -br * 0.5, 0, 0, 0, br * 1.1); g.addColorStop(0, "rgba(255,255,255,.30)"); g.addColorStop(0.32, "rgba(255,255,255,0)"); g.addColorStop(0.72, "rgba(0,0,0,.2)"); g.addColorStop(1, "rgba(0,0,0,.62)"); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, br, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } ctx.restore(); } const setMode = (i: number, m: 0 | 1 | 2 | 3) => { stitches[i].mode = m; stitches[i].t = simT; }; const resetStitches = () => { stitches.forEach((s) => { s.mode = 0; }); gone = 0; nextOut = 0; nextPop = 0; }; const stitchAnchor = (): [number, number] => { if (gone <= 0) return [ANCHOR_X, H - 6]; const s = stitches[ORDER[Math.min(gone, K) - 1]]; return [s.x, s.y - 6]; }; const step = (dt: number) => { simT += dt * 1000; const el = simT - t0; if (phase === "play") { while (nextOut < K && el >= T_START + (nextOut * T_UNRAVEL) / K) { setMode(ORDER[nextOut], 1); nextOut++; } for (let j = 0; j < nextOut; j++) { const s = stitches[ORDER[j]]; if (s.mode === 1 && simT - s.t >= 60) { s.mode = 2; gone++; } } if (el >= T_KNIT) { phase = "knit"; knitFrom = { x: bx, y: by }; } } if (phase === "knit") { const k = el - T_POP0; while (nextPop < K && k >= (nextPop * T_POP_SPAN) / K) { const idx = ORDER[K - 1 - nextPop]; if (stitches[idx].mode === 2) gone--; setMode(idx, 3); nextPop++; } for (const s of stitches) if (s.mode === 3 && simT - s.t >= 120) s.mode = 0; if (el >= T_END && gone <= 0) { phase = "idle"; ballOn = false; br = 0; kink = 0; wrap.dataset.tbState = "idle"; } } // squash and tug let tug = 0; if (phase !== "idle" && el < 230) { const e = el / 80; tug = el < 80 ? 12 * Math.sin((e * Math.PI) / 2) : 12 * Math.max(0, 1 - (el - 80) / 150); squash = 1 - 0.03 * (el < 80 ? e : Math.max(0, 1 - (el - 80) / 150)); } else squash = 1; label.style.transform = squash === 1 ? "" : `scaleY(${squash.toFixed(3)})`; if (phase === "idle") kink += ((hovering && !disabled ? 3.2 : 0) - kink) * (1 - Math.exp(-dt / 0.3)); else kink += (0.5 - kink) * (1 - Math.exp(-dt / 1.2)); // rope length target let Lt = 0; const bendy = phase !== "idle" && gone > 0; if (phase === "idle") Lt = hovering && !disabled ? 65 : 0; else Lt = bendy ? 65 + (130 * gone) / K : hovering ? 65 : phase === "knit" && el > T_POP0 + 400 ? 0 : 65; const wasZero = L < 1; L += (Lt - L) * (1 - Math.exp(-dt / (phase === "knit" ? 0.1 : 0.06))); if (wasZero && L >= 1 && phase === "idle") for (let i = 0; i < N; i++) ox[i] = px[i] - (50 / 60) * (i / N); const seg = L / (N - 1); // anchor let [tx, ty] = stitchAnchor(); if (phase === "idle") { tx = ANCHOR_X; ty = H - 6; } ty += tug; const ka = 1 - Math.exp(-dt / 0.03); ax += (tx - ax) * ka; ay += (ty - ay) * ka; swayOff += ((hovering ? clamp(curX - ANCHOR_X, -10, 10) : 0) - swayOff) * (1 - Math.exp(-dt / 0.15)); // ball if (phase === "play" && !ballOn && el >= T_START) { ballOn = true; bx = ANCHOR_X; by = H + 28; bvx = bvy = 0; bhit = false; bang = 0; } if (ballOn) { const target = phase === "knit" ? (gone > 0 ? 8 + 28 * Math.sqrt(gone / K) : 0) : 8 + 28 * Math.sqrt(gone / K); br += (target - br) * (1 - Math.exp(-dt / (phase === "knit" ? 0.08 : 0.04))); if (phase === "play") { bvy += 1200 * dt; let nx = bx + bvx * dt; let ny = by + bvy * dt; const fl = FLOOR - br; let onFloor = false; if (ny >= fl) { ny = fl; if (!bhit) { bhit = true; bvx = 160; } if (bvy > 40) bvy = -bvy * 0.35; else { bvy = 0; onFloor = true; } bShadow = 0.6; } if (onFloor || ny >= fl - 0.5) bvx = Math.max(0, bvx - 120 * dt); const ddx = nx - ax, ddy = ny - ay; const d = Math.hypot(ddx, ddy); const Lmax = Math.max(8, L); if (d > Lmax) { const nxn = ddx / d, nyn = ddy / d; nx = ax + nxn * Lmax; ny = ay + nyn * Lmax; const vn = bvx * nxn + bvy * nyn; if (vn > 0) { bvx -= vn * nxn; bvy -= vn * nyn; } } nx = clamp(nx, -PL + br + 2, W + 140 - br - 2); bang += (nx - bx) / Math.max(br, 4); bx = nx; by = ny; bShadow = clamp(1 - (FLOOR - br - by) / 120, 0.3, 1); } else { const k = clamp((el - T_KNIT) / 600, 0, 1); const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; const tgx = gone > 0 ? stitchAnchor()[0] + 10 : ANCHOR_X; const tgy = gone > 0 ? stitchAnchor()[1] + 30 : H + 28; const nx = knitFrom.x + (tgx - knitFrom.x) * e; bang += (nx - bx) / Math.max(br, 4); bx = nx; by = knitFrom.y + (tgy - knitFrom.y) * e; if (gone === 0) br = Math.max(0, br - 40 * dt); bShadow = 1; } } // rope verlet const sub = 2; const h = dt / sub; for (let s = 0; s < sub; s++) { for (let i = 1; i < N; i++) { const vx = (px[i] - ox[i]) * 0.985, vy = (py[i] - oy[i]) * 0.985; ox[i] = px[i]; oy[i] = py[i]; px[i] += vx; py[i] += vy + 1200 * h * h; if (hovering && phase === "idle") px[i] += (ANCHOR_X + swayOff * (i / N) - px[i]) * 0.02 * (i / N); } px[0] = ax; py[0] = ay; const pinEnd = ballOn && br > 0.5; for (let it = 0; it < 6; it++) { for (let i = 0; i < N - 1; i++) { let dx = px[i + 1] - px[i], dy = py[i + 1] - py[i]; let d = Math.hypot(dx, dy); if (d < 1e-4) { dx = 0; dy = 1; d = 1; } const diff = (d - seg) / d; const wi = i === 0 ? 0 : 1; const wj = i + 1 === N - 1 && pinEnd ? 0 : 1; const wsum = wi + wj; if (!wsum) continue; px[i] += (dx * diff * wi) / wsum; py[i] += (dy * diff * wi) / wsum; px[i + 1] -= (dx * diff * wj) / wsum; py[i + 1] -= (dy * diff * wj) / wsum; } px[0] = ax; py[0] = ay; if (pinEnd) { px[N - 1] = bx; py[N - 1] = by; } } } }; const needLoop = () => phase !== "idle" || L > 0.5 || hovering; const tick = (now: number) => { raf = 0; if (!allowed()) { last = 0; return; } const dt = last ? Math.min(0.048, (now - last) / 1000) : 0.016; last = now; step(dt); draw(); if (needLoop()) raf = requestAnimationFrame(tick); else { last = 0; L = 0; } }; const wake = () => { if (!raf && allowed()) raf = requestAnimationFrame(tick); }; const locate = (e: PointerEvent) => { if (!rect) rect = btn.getBoundingClientRect(); const scale = rect.width / (btn.offsetWidth || 1) || 1; curX = (e.clientX - rect.left) / scale; }; const enter = (e: PointerEvent) => { if (disabled || media.matches) return; hovering = true; rect = btn.getBoundingClientRect(); locate(e); wake(); }; const move = (e: PointerEvent) => { if (hovering) locate(e); }; const leave = () => { hovering = false; wake(); }; const invalidate = () => { rect = null; }; play.current = () => { if (disabled) return; if (media.matches) { wrap.dataset.tbState = "reduced"; const a = dim.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 150, fill: "forwards" }); anims.add(a); later(() => { const b = dim.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200, fill: "forwards" }); anims.add(b); later(() => { anims.forEach((x) => x.cancel()); anims.clear(); wrap.dataset.tbState = "idle"; }, 220); }, 2200); return; } if (!allowed() || phase !== "idle") return; resetStitches(); phase = "play"; kink = 1.8; t0 = simT; wrap.dataset.tbState = "playing"; wake(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; wrap.dataset.tbPaused = String(!visible); if (visible) { last = 0; wake(); } }); const mq = () => { if (media.matches) { cancelAnimationFrame(raf); raf = 0; phase = "idle"; hovering = false; ballOn = false; L = 0; resetStitches(); label.style.transform = ""; resetRope(); draw(); } }; setup(); io?.observe(wrap); btn.addEventListener("pointerenter", enter); btn.addEventListener("pointermove", move, { passive: true }); btn.addEventListener("pointerleave", leave); window.addEventListener("resize", setup); window.addEventListener("scroll", invalidate, true); media.addEventListener("change", mq); draw(); return () => { epoch++; play.current = () => {}; cancelAnimationFrame(raf); timers.forEach((id) => window.clearTimeout(id)); timers.clear(); anims.forEach((a) => a.cancel()); anims.clear(); io?.disconnect(); btn.removeEventListener("pointerenter", enter); btn.removeEventListener("pointermove", move); btn.removeEventListener("pointerleave", leave); window.removeEventListener("resize", setup); window.removeEventListener("scroll", invalidate, true); media.removeEventListener("change", mq); }; }, [disabled, palette]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; play.current(); }; return ( ); } export default YarnButton; const css = ` .tb-yarn-wrap{display:inline-flex;position:relative;vertical-align:middle} .tb-yarn-btn{position:relative;display:block;box-sizing:border-box;width:${W}px;height:${H}px;padding:0;border:0;border-radius:${R}px;background:transparent; overflow:visible;cursor:pointer;-webkit-tap-highlight-color:transparent;transform-origin:50% 100%; transition:transform 240ms cubic-bezier(.34,1.56,.64,1);font:900 40px/1 ui-rounded,"SF Pro Rounded","Arial Rounded MT Bold","Nunito","Segoe UI Black","Segoe UI",system-ui,sans-serif} .tb-yarn-btn:hover:not(:disabled){transform:translateY(-2px) scale(1.025)} .tb-yarn-btn:active:not(:disabled){transform:translateY(0) scale(.99);transition-duration:90ms} .tb-yarn-btn:focus-visible{outline:3px solid #8fc1ee;outline-offset:6px} .tb-yarn-btn:disabled{cursor:default;opacity:.6;filter:saturate(.5)} .tb-yarn-canvas{position:absolute;left:-${PL}px;top:-${PT}px;width:${CW}px;height:${CH}px;pointer-events:none} .tb-yarn-dim{position:absolute;inset:0;border-radius:${R}px;overflow:hidden;pointer-events:none} .tb-yarn-dim>span{position:absolute;left:0;right:0;top:${ROWH * 4}px;bottom:0;background:rgba(14,24,34,.62);opacity:0} .tb-yarn-label{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;transform-origin:50% 100%} .tb-yarn-label>span{display:block;text-transform:uppercase;letter-spacing:.06em;padding-left:.06em;white-space:nowrap; background:linear-gradient(180deg,rgba(255,255,255,.30) 0,rgba(255,255,255,0) 40%,rgba(84,62,30,.30) 100%),repeating-linear-gradient(-52deg,rgba(255,255,255,0) 0,rgba(255,255,255,.26) 1.6px,rgba(255,255,255,0) 3.2px,rgba(96,72,40,.34) 5.2px,rgba(96,72,40,0) 7px),var(--tb-yarn-label,#ece4d2);-webkit-background-clip:text;background-clip:text;color:transparent; -webkit-text-stroke:1px rgba(112,88,54,.62); filter:drop-shadow(0 0 .7px rgba(236,228,210,.6)) drop-shadow(0 2.5px 1.5px rgba(4,12,22,.72)) drop-shadow(0 0 1px rgba(4,12,22,.6))} .tb-yarn-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-yarn-wrap *,.tb-yarn-wrap *::before,.tb-yarn-wrap *::after{animation:none!important;transition:none!important}} `;