"use client"; /** * grass.tsx — a patch of lawn with tiny flowers and a mown label. * Brush it and the blades bend away; click and it blooms, a butterfly flies off, then it settles. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useImperativeHandle, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type Ref } from "react"; type Palette = { blades: string[]; soil: string; flowers: string[]; ink: string }; type Props = Omit, "children"> & { children?: string; // drawn on canvas ref?: Ref; palette?: Palette; }; const W = 260; const H = 92; const R = 46; const PADX = 40; const PADT = 150; const PADB = 24; const CW = W + 2 * PADX; const CH = H + PADT + PADB; const DEFAULT_PALETTE: Palette = { blades: ["#1d3305", "#2f5a0a", "#4a8a14", "#78b62a", "#b9dc55"], soil: "#17290a", flowers: ["#f7f4ea", "#f4c21c", "#7fb2e8", "#e889b3"], ink: "#efe3c2", }; const EDGE = "#0e1a03"; const BLOOM_EXTRA = ["#ff7eb6", "#ffd23f"]; const PETAL_COLORS = ["#ff9ec4", "#ffd23f", "#f7f4ea"]; const FONT_FAMILY = 'ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif'; const BLADES = 1500; const UNDERFUR = 450; const MASK_BLADES = 140; const REST_FLOWERS = 22; const BLOOM_FLOWERS = 26; const BIG_FLOWERS = 6; const REACH = 64; const SPRING_K = 120; const SPRING_C = 9; const TOTAL = 4300; // click effect length, ms const CLOSE_AT = 2800; const BF_X = W * 0.7; const clamp = (n: number, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, n)); const easeOut = (n: number) => 1 - Math.pow(1 - clamp(n), 3); const backOut = (n: number) => { const u = clamp(n) - 1; return 1 + 2.2 * u * u * u + 1.2 * u * u; }; function rng(seed: number) { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } const sdf = (x: number, y: number) => Math.hypot(x - clamp(x, R, W - R), y - R) - R; const pillPath = (g: CanvasRenderingContext2D) => { g.beginPath(); g.moveTo(R, 0); g.lineTo(W - R, 0); g.arc(W - R, R, R, -Math.PI / 2, Math.PI / 2); g.lineTo(R, H); g.arc(R, R, R, Math.PI / 2, Math.PI * 1.5); g.closePath(); }; type Flower = { x: number; y: number; r: number; col: string; cen: string; stem: number; rot: number; bloom: number; big: boolean }; type Scene = { n: number; x: Float32Array; y: Float32Array; len: Float32Array; th: Float32Array; curl: Float32Array; w: Float32Array; c: Uint8Array; under: { x: number; y: number; len: number; th: number; w: number }[]; tip: Uint8Array; flowers: Flower[]; fontPx: number; mask: Uint8Array; }; function buildScene(label: string, pal: Palette): Scene { const rand = rng(7); const rr = (a: number, b: number) => a + (b - a) * rand(); // label size + mask (fat text outline marks where blades stay short) const mc = document.createElement("canvas"); mc.width = W; mc.height = H; const mg = mc.getContext("2d"); let fontPx = 34; const mask = new Uint8Array(W * H); if (mg) { mg.font = `900 34px ${FONT_FAMILY}`; const tw = mg.measureText(label).width || 1; fontPx = Math.min(34, Math.floor((34 * 190) / tw)); mg.font = `900 ${fontPx}px ${FONT_FAMILY}`; mg.textAlign = "center"; mg.textBaseline = "middle"; mg.lineJoin = "round"; mg.lineWidth = 12; mg.fillStyle = "#000"; mg.strokeStyle = "#000"; mg.strokeText(label, W / 2, H / 2 + 1); mg.fillText(label, W / 2, H / 2 + 1); const d = mg.getImageData(0, 0, W, H).data; for (let i = 0; i < W * H; i++) mask[i] = d[i * 4 + 3] > 40 ? 1 : 0; } const inMask = (x: number, y: number) => { const ix = Math.round(x), iy = Math.round(y); return ix >= 0 && iy >= 0 && ix < W && iy < H && mask[iy * W + ix] === 1; }; type B = { x: number; y: number; len: number; th: number; curl: number; w: number; c: number; tip?: number }; const under: Scene["under"] = []; const list: B[] = []; const nc = Math.max(1, pal.blades.length); const pickColor = (x: number, y: number) => { const lx = (x - W * 0.42) / (W * 0.6), ly = (y - H * 0.22) / (H * 0.85); let light = clamp(1 - Math.hypot(lx, ly) * 0.85); light *= 0.55 + 0.45 * clamp(-sdf(x, y) / 14); if (sdf(x, y) > -7 && y < H * 0.45 && rand() < 0.5) return nc - 1; if (light > 0.45 && rand() < 0.08) return nc - 1; const cc = Math.min(nc - 2, Math.floor(clamp(light * 0.8 + rand() * 0.35) * (nc - 1))); return y > H * 0.8 ? Math.min(cc, 1) : cc; }; let guard0 = 0; while (under.length < UNDERFUR && guard0++ < 20000) { const x = rr(0, W), y = rr(0, H); if (sdf(x, y) >= -2 || inMask(x, y)) continue; under.push({ x, y, len: rr(4, 7), th: rr(-0.35, 0.35), w: 2.6 }); } let guard = 0; while (list.length < BLADES && guard++ < 20000) { const x = rr(-3, W + 3), y = rr(-3, H + 3); const sd = sdf(x, y); if (sd > 3) continue; const short = inMask(x, y); const rim = clamp((sd + 20) / 20); const ox = x - clamp(x, R, W - R), oy = y - R; const ol = Math.hypot(ox, oy) || 1; const dome = 0.65 + 0.35 * Math.sin(Math.PI * clamp(x / W)); let len = short ? rr(3, 5) : rr(6, 11) + rim * rr(4, 7) * dome; let vx = (ox / ol) * rim * 0.5 + rr(-0.2, 0.2); let vy = -0.95 + (oy / ol) * rim * 0.35; let c = pickColor(x, y); if (short) { vx = rr(-0.1, 0.1); vy = -1; len = rr(3, 5); } else if (oy / ol > 0.35 && rim > 0.4) { vy = -0.5; vx = (ox / ol) * 0.9 + Math.sign(x - W / 2) * 0.35; len *= 0.65; c = Math.min(c, 1); } len = Math.min(len, 16); list.push({ x, y, len, th: Math.atan2(vx, -vy), curl: rr(-0.32, 0.32), w: short ? 2.2 : (rand() < 0.3 ? rr(0.9, 1.3) : rr(1.3, 2)), c, tip: !short && rand() < 0.5 ? 1 : 0 }); } let more = 0; guard = 0; while (more < MASK_BLADES && guard++ < 20000) { const x = rr(30, W - 30), y = rr(18, H - 18); if (!inMask(x, y)) continue; list.push({ x, y, len: rr(3, 5), th: rr(-0.1, 0.1), curl: rr(-0.1, 0.1), w: 2.2, c: Math.floor(rand() * 2) }); more++; } list.sort((a, b) => a.y - b.y); const n = list.length; const s: Scene = { n, x: new Float32Array(n), y: new Float32Array(n), len: new Float32Array(n), th: new Float32Array(n), curl: new Float32Array(n), w: new Float32Array(n), c: new Uint8Array(n), under, tip: new Uint8Array(n), flowers: [], fontPx, mask, }; list.forEach((b, i) => { s.x[i] = b.x; s.y[i] = b.y; s.len[i] = b.len; s.th[i] = b.th; s.curl[i] = b.curl; s.w[i] = b.w; s.c[i] = b.c; s.tip[i] = b.tip ?? 0; }); // flowers: rest layout first, then bloom layout, no overlap with the label or each other const fcols = pal.flowers.length ? pal.flowers : DEFAULT_PALETTE.flowers; const cenFor = (col: string) => (col.toLowerCase() === "#f4c21c" ? "#c8790a" : "#f2c230"); const placed: { x: number; y: number }[] = []; const free = (x: number, y: number, h: number, gap: number) => { if (sdf(x, y) > -7) return false; for (let k = 0; k <= 4; k++) { const yy = y - (h * k) / 4; for (const dx of [-6, 0, 6]) if (inMask(x + dx, yy)) return false; } return placed.every((p) => Math.hypot(p.x - x, p.y - y) >= gap); }; const weights = [0.45, 0.7, 0.88, 1]; for (let i = 0; i < REST_FLOWERS; i++) { for (let t = 0; t < 300; t++) { const x = rr(6, W - 6), y = rr(4, H - 6); if (!free(x, y, 4, 15)) continue; const u = rand(); const col = fcols[Math.min(fcols.length - 1, weights.findIndex((wt) => u <= wt))] ?? fcols[0]; placed.push({ x, y }); s.flowers.push({ x, y, r: rr(3.2, 5), col, cen: cenFor(col), stem: 4, rot: rr(0, 6.28), bloom: -1, big: false }); break; } } const bcols = [...fcols, ...BLOOM_EXTRA]; for (let i = 0; i < BLOOM_FLOWERS; i++) { const big = i < BIG_FLOWERS; for (let t = 0; t < 500; t++) { const x = big ? 34 + ((i + rand() * 0.7) * (W - 68)) / BIG_FLOWERS : rr(8, W - 8); const y = big ? rr(6, 12) : rr(8, H - 6); const h = big ? rr(9, 14) : rr(6, 14); if (!free(x, y, h, big ? 20 : 12 - t / 120)) continue; const col = big ? (i % 2 === 0 ? "#f7f4ea" : "#ff7eb6") : bcols[Math.floor(rand() * bcols.length)]; placed.push({ x, y }); s.flowers.push({ x, y, r: big ? 6.5 : rr(3.8, 5.5), col, cen: cenFor(col), stem: h, rot: rr(0, 6.28), bloom: i, big }); break; } } s.flowers.sort((a, b) => a.y - b.y); return s; } export function GrassButton({ children = "grow", 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 playRef = useRef<(x: number) => void>(() => {}); const [playing, setPlaying] = useState(false); const label = String(children).toUpperCase(); const paletteKey = JSON.stringify(palette); useImperativeHandle(ref, () => btnRef.current!, []); useEffect(() => { const el = btnRef.current; const host = wrapRef.current; const cv = canvasRef.current; if (!el || !host || !cv) return; const ctx = cv.getContext("2d"); if (!ctx) return; const pal: Palette = JSON.parse(paletteKey); const sc = buildScene(label, pal); const n = sc.n; const F = sc.flowers; const nf = F.length; const bb = new Float32Array(n), bv = new Float32Array(n), bm = new Float32Array(n), bmu = new Float64Array(n); const fb = new Float32Array(nf), fv = new Float32Array(nf), fm = new Float32Array(nf), fmu = new Float64Array(nf); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const pr = rng(31); const petals = Array.from({ length: 16 }, (_, i) => { const fl = F.find((q) => q.bloom === i % 26) ?? F[0]; return { fl, t0: 20 + (i % 26) * 14 + 320, ph: i * 1.7, vx: (i % 2 ? 1 : -1) * (8 + 12 * pr()), w: 3.2 + 0.8 * pr(), h: 2 + 0.4 * pr(), col: PETAL_COLORS[i % 3], rot: i * 0.9, }; }); const cr = rng(53); const clips = Array.from({ length: 18 }, () => ({ ox: (cr() - 0.5) * 20, a: -Math.PI / 2 + (cr() - 0.5) * 2.4, sp: 90 + 80 * cr(), spin: (cr() - 0.5) * 16, r0: cr() * 6.28, })); let clipAt = -1, clipX = W / 2; let dpr = 1; let base: HTMLCanvasElement | null = null; let shadowCv: HTMLCanvasElement | null = null; let labelCv: HTMLCanvasElement | null = null; let lift = 0, liftV = 0, press = 0, pressV = 0, pressT = 0, pvx = 0; let raf = 0; let last = 0; let lastDraw = 0; let visible = true; let hovering = false; let px = -999, py = -999, lastMove = 0, lastPx = 0, lastPy = 0; let rect: DOMRect | undefined; let dirty = true; let clickAt = -1; let rmOn = false, rmB = 0, rmF = 0; let epoch = 0; const tipBuf = new Float32Array(n * 6); let volGrad: CanvasGradient | null = null; const timers = new Set(); const rmNow = () => media.matches; const canRun = () => !disabled && !el.matches(":disabled") && visible && !document.hidden && !rmNow(); const later = (fn: () => void, ms: number) => { const ep = epoch; const id = window.setTimeout(() => { timers.delete(id); if (ep === epoch) fn(); }, ms); timers.add(id); }; const clearTimers = () => { epoch++; timers.forEach((id) => window.clearTimeout(id)); timers.clear(); }; const makeBase = () => { const c = document.createElement("canvas"); c.width = Math.round(CW * dpr); c.height = Math.round(CH * dpr); const g = c.getContext("2d"); if (!g) return null; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.translate(PADX, PADT); const gr = g.createLinearGradient(0, 0, 0, H); gr.addColorStop(0, pal.soil); gr.addColorStop(1, EDGE); g.fillStyle = gr; pillPath(g); g.fill(); g.save(); pillPath(g); g.clip(); g.lineWidth = 12; g.strokeStyle = "rgba(6,12,0,.6)"; pillPath(g); g.stroke(); const sh = g.createLinearGradient(0, H * 0.55, 0, H); sh.addColorStop(0, "rgba(0,0,0,0)"); sh.addColorStop(1, "rgba(0,0,0,.55)"); g.fillStyle = sh; g.fillRect(0, 0, W, H); g.fillStyle = pal.blades[0]; g.beginPath(); for (const u of sc.under) { const tx = u.x + Math.sin(u.th) * u.len, ty = u.y - Math.cos(u.th) * u.len; const cx = u.x + Math.sin(u.th) * u.len * 0.55, cy = u.y - Math.cos(u.th) * u.len * 0.55; const ax = Math.cos(u.th) * u.w * 0.5, ay = Math.sin(u.th) * u.w * 0.5; g.moveTo(u.x - ax, u.y - ay); g.quadraticCurveTo(cx - ax * 0.5, cy - ay * 0.5, tx, ty); g.quadraticCurveTo(cx + ax * 0.5, cy + ay * 0.5, u.x + ax, u.y + ay); } g.fill(); g.restore(); return c; }; const makeShadow = () => { const c = document.createElement("canvas"); c.width = Math.round(CW * dpr); c.height = Math.round(CH * dpr); const g = c.getContext("2d"); if (!g) return null; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.translate(PADX, PADT); const pool = (cy: number, rx: number, ry: number, a: number) => { g.save(); g.translate(W / 2, cy); g.scale(1, ry / rx); const rg = g.createRadialGradient(0, 0, 0, 0, 0, rx); rg.addColorStop(0, `rgba(0,0,0,${a})`); rg.addColorStop(1, "rgba(0,0,0,0)"); g.fillStyle = rg; g.beginPath(); g.arc(0, 0, rx, 0, 6.2832); g.fill(); g.restore(); }; pool(H + 4, W * 0.52, 14, 0.5); pool(H - 1, W * 0.46, 5, 0.65); return c; }; const makeLabel = () => { const c = document.createElement("canvas"); c.width = Math.round(CW * dpr); c.height = Math.round(CH * dpr); const g = c.getContext("2d"); if (!g) return null; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.translate(PADX, PADT); const fp = sc.fontPx; g.font = `900 ${fp}px ${FONT_FAMILY}`; g.textAlign = "center"; g.textBaseline = "middle"; g.lineJoin = "round"; const lg = g as CanvasRenderingContext2D & { letterSpacing?: string }; if ("letterSpacing" in lg) lg.letterSpacing = "1.5px"; const cy = H / 2; const noSh = () => { g.shadowColor = "transparent"; g.shadowBlur = 0; g.shadowOffsetY = 0; }; g.strokeStyle = "rgba(8,16,0,.6)"; g.lineWidth = 12; g.shadowColor = "rgba(0,0,0,.6)"; g.shadowBlur = 8; g.strokeText(label, W / 2, cy + 2); noSh(); g.fillStyle = "#6e5f36"; g.shadowColor = "rgba(0,0,0,.55)"; g.shadowBlur = 5; g.shadowOffsetY = 3; g.fillText(label, W / 2, cy + 3.5); noSh(); g.fillStyle = "#8f7d4c"; g.fillText(label, W / 2, cy + 2.5); g.fillStyle = "#a8955f"; g.fillText(label, W / 2, cy + 1.5); g.fillStyle = "rgba(255,255,255,.6)"; g.fillText(label, W / 2, cy + 0.2); const fg = g.createLinearGradient(0, cy - fp * 0.45, 0, cy + fp * 0.45); fg.addColorStop(0, "#fff8e2"); fg.addColorStop(0.55, "#efe3c2"); fg.addColorStop(1, "#d9c79a"); g.fillStyle = fg; g.fillText(label, W / 2, cy + 1); g.lineWidth = 0.75; g.strokeStyle = "rgba(70,55,20,.45)"; g.strokeText(label, W / 2, cy + 1); return c; }; const setup = () => { const scale = el.getBoundingClientRect().width / (el.offsetWidth || 1) || 1; dpr = Math.min(2, (window.devicePixelRatio || 1) * scale); cv.width = Math.round(CW * dpr); cv.height = Math.round(CH * dpr); base = makeBase(); shadowCv = makeShadow(); labelCv = makeLabel(); ctx.setTransform(dpr, 0, 0, dpr, PADX * dpr, PADT * dpr); const vg = ctx.createLinearGradient(0, -14, 0, H + 8); vg.addColorStop(0, "rgba(235,255,170,.16)"); vg.addColorStop(0.35, "rgba(235,255,170,0)"); vg.addColorStop(0.62, "rgba(0,0,0,0)"); vg.addColorStop(1, "rgba(0,14,0,.42)"); volGrad = vg; dirty = true; }; const drawFlower = (f: Flower, i: number, now: number, k: number, pk: number, still: boolean) => { const bend = fb[i] + (still ? 0 : 0.05 * Math.sin(now * 0.0021 + f.rot * 3) + 0.06 * Math.sin(f.x * 0.03 + now * 0.0016) + 0.035 * Math.sin(f.x * 0.071 - now * 0.0027 + f.y * 0.05)); const h = f.stem * k; const hx = f.x + Math.sin(bend) * h, hy = f.y - Math.cos(bend) * h; if (h > 0.8) { ctx.strokeStyle = "#3f5f08"; ctx.lineWidth = 1.1; ctx.beginPath(); ctx.moveTo(f.x, f.y); ctx.quadraticCurveTo(f.x + Math.sin(bend * 0.4) * h * 0.6, f.y - h * 0.6, hx, hy); ctx.stroke(); } if (pk <= 0.02) return; const r = f.r * pk; const lc = f.col.toLowerCase(); ctx.fillStyle = "rgba(0,0,0,.3)"; ctx.beginPath(); ctx.ellipse(hx + 0.6, hy + 1.6, r * 1.1, r * 0.7, 0, 0, 6.2832); ctx.fill(); let np = 5, dist = 0.5, ra = 0.5, rb = 0.44; if (lc === "#f7f4ea") { np = 11; dist = 0.58; ra = 0.5; rb = 0.17; } else if (lc === "#7fb2e8") { np = 5; dist = 0.5; ra = 0.48; rb = 0.46; } else if (lc === "#e889b3" || lc === "#ff7eb6") { np = 6; dist = 0.55; ra = 0.5; rb = 0.3; } ctx.fillStyle = f.col; ctx.beginPath(); for (let j = 0; j < np; j++) { const a = f.rot + bend + (j * 6.2832) / np; ctx.moveTo(hx + Math.cos(a) * r * dist + Math.cos(a) * r * ra, hy + Math.sin(a) * r * dist + Math.sin(a) * r * ra); ctx.ellipse(hx + Math.cos(a) * r * dist, hy + Math.sin(a) * r * dist, r * ra, r * rb, a, 0, 6.2832); } ctx.fill(); ctx.lineWidth = 0.5; ctx.strokeStyle = "rgba(0,0,0,.18)"; ctx.stroke(); const disc = (col: string, rad: number) => { ctx.fillStyle = col; ctx.beginPath(); ctx.arc(hx, hy, r * rad, 0, 6.2832); ctx.fill(); }; if (lc === "#f7f4ea") { disc("#f2c230", 0.3); ctx.lineWidth = 0.6; ctx.strokeStyle = "#c8790a"; ctx.stroke(); } else if (lc === "#f4c21c" || lc === "#ffd23f") { disc("#ffe27a", 0.42); disc("#c8790a", 0.2); } else if (lc === "#7fb2e8") { disc("#ffffff", 0.3); disc("#f2c230", 0.14); } else if (lc === "#e889b3" || lc === "#ff7eb6") disc("#c8578a", 0.28); else disc(f.cen, 0.3); ctx.fillStyle = "rgba(255,255,255,.7)"; ctx.beginPath(); ctx.arc(hx - 0.3 * r, hy - 0.3 * r, 0.8, 0, 6.2832); ctx.fill(); }; const wing = (side: number, sx: number, hind: boolean) => { ctx.save(); ctx.scale(side * sx, 1); ctx.beginPath(); if (!hind) { ctx.moveTo(0.8, -1); ctx.bezierCurveTo(3, -9, 11, -13.5, 13.5, -10.5); ctx.bezierCurveTo(14.5, -7, 11, -2, 6.5, 1.5); ctx.lineTo(0.8, 1); } else { ctx.moveTo(0.8, 1); ctx.bezierCurveTo(6, 0, 11, 3, 10, 7); ctx.bezierCurveTo(9, 10.5, 4, 10.5, 1.5, 6.5); } ctx.closePath(); const wg = hind ? ctx.createLinearGradient(0, 1, 10, 8) : ctx.createLinearGradient(0, 0, 13, -10); wg.addColorStop(0, "#ffb54a"); wg.addColorStop(0.55, "#f08a1a"); wg.addColorStop(1, "#c9600a"); ctx.fillStyle = wg; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = "#1a1208"; ctx.lineJoin = "round"; ctx.stroke(); ctx.lineWidth = 0.6; ctx.beginPath(); if (!hind) { ctx.moveTo(1, -0.5); ctx.lineTo(11, -8.5); ctx.moveTo(1, 0); ctx.lineTo(12.5, -4); } else { ctx.moveTo(1, 2); ctx.lineTo(8, 7); } ctx.stroke(); ctx.fillStyle = "#fff"; ctx.beginPath(); if (!hind) { for (const [dx, dy, dr] of [[12, -9.8, 0.8], [13.4, -8, 0.7], [13.7, -6, 0.7], [12.9, -3.9, 0.6], [11.3, -2, 0.6]]) { ctx.moveTo(dx + dr, dy); ctx.arc(dx, dy, dr, 0, 6.2832); } } else { for (const [dx, dy] of [[9, 8], [6.6, 9.4], [3.6, 8.6]]) { ctx.moveTo(dx + 0.7, dy); ctx.arc(dx, dy, 0.7, 0, 6.2832); } } ctx.fill(); ctx.restore(); }; const butterfly = (x: number, y: number, alpha: number, open: number, flap: number, rot = 0) => { ctx.save(); ctx.globalAlpha = alpha; ctx.translate(x, y); ctx.rotate(rot); ctx.scale(1.55, 1.55); const fore = open * Math.max(0.12, Math.abs(Math.cos((flap * Math.PI * 2) / 180))); const hindS = open * Math.max(0.12, Math.abs(Math.cos(((flap - 40) * Math.PI * 2) / 180))); for (const side of [-1, 1]) { wing(side, hindS, true); wing(side, fore, false); } ctx.fillStyle = "#1a1208"; ctx.beginPath(); ctx.ellipse(0, 0, 1.6, 6.6, 0, 0, 6.2832); ctx.fill(); ctx.strokeStyle = "#1a1208"; ctx.lineWidth = 0.7; ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.arc(-0.6, -2, 0.5, 0, 6.2832); ctx.moveTo(1.1, -2); ctx.arc(0.6, -2, 0.5, 0, 6.2832); ctx.fill(); ctx.beginPath(); ctx.moveTo(-0.5, -6); ctx.quadraticCurveTo(-3, -10, -5, -10.5); ctx.moveTo(0.5, -6); ctx.quadraticCurveTo(3, -10, 5, -10.5); ctx.stroke(); ctx.restore(); }; const render = (now: number, t: number) => { const still = rmNow() || disabled; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, CW, CH); if (shadowCv) { ctx.globalAlpha = 1 - 0.28 * lift; ctx.drawImage(shadowCv, 0, 0, CW, CH); if (press > 0.01) { ctx.globalAlpha = 0.3 * press; ctx.drawImage(shadowCv, 0, 0, CW, CH); } ctx.globalAlpha = 1; } ctx.translate(PADX, PADT); ctx.translate(0, -4 * lift); ctx.translate(W / 2, H); ctx.scale(1 + 0.025 * press, 1 - 0.07 * press); ctx.translate(-W / 2, -H); ctx.translate(0, 2 * press); if (base) ctx.drawImage(base, -PADX, -PADT, CW, CH); // flowers, interleaved with blade bands const rmShow = rmOn; const flowerAt = (i: number) => { const f = F[i]; if (f.bloom < 0) { drawFlower(f, i, now, 1, 1, still); return; } let k = 0, pk = 0, a = 1; if (rmShow) { k = 1; pk = 1; a = rmB; } else if (t >= 0) { const t0 = 20 + f.bloom * 14; k = backOut((t - t0) / 200); if (t < t0) k = 0; const u = (t - t0 - 100) / 220; pk = u <= 0 ? 0 : u < 0.6 ? 1.15 * easeOut(u / 0.6) : u < 1 ? 1.15 - 0.15 * ((u - 0.6) / 0.4) : 1; const tc = (t - (CLOSE_AT + f.bloom * 25)) / 400; if (tc > 0) { const e = 1 - clamp(tc) * clamp(tc); k *= e; pk *= e; } } if (k <= 0.001 && pk <= 0.001) return; ctx.globalAlpha = a; drawFlower(f, i, now, k, pk, still); ctx.globalAlpha = 1; }; // blades, back to front in six depth bands, one path per colour const cols = pal.blades; const band = Math.ceil(n / 6); let fi = 0; for (let s0 = 0; s0 < n; s0 += band) { const s1 = Math.min(n, s0 + band); let tn = 0; for (let c = 0; c < cols.length; c++) { ctx.beginPath(); let any = false; for (let i = s0; i < s1; i++) { const ab = Math.abs(bb[i]); const ce = Math.min(cols.length - 1, sc.c[i] + (ab > 0.9 ? 2 : ab > 0.35 ? 1 : 0)); if (ce !== c) continue; any = true; const x = sc.x[i], y = sc.y[i]; const bend = bb[i] + (still ? 0 : 0.06 * Math.sin(x * 0.03 + now * 0.0016) + 0.035 * Math.sin(x * 0.071 - now * 0.0027 + y * 0.05)) + press * 0.25 * Math.sign(x - W / 2) * Math.abs(x - W / 2) / (W / 2); const m = Math.min(1, ab / 1.2); const L = sc.len[i] * (1 + (y < H * 0.5 ? 0.3 : 0.1) * m) * (1 + 0.05 * lift); const th = sc.th[i] + bend * 1.15 + sc.curl[i]; const tc = sc.th[i] + bend * 0.4 + sc.curl[i] * 0.35; const tx = x + Math.sin(th) * L, ty = y - Math.cos(th) * L; const cx = x + Math.sin(tc) * L * 0.55, cy = y - Math.cos(tc) * L * 0.55; const hw = sc.w[i] * 0.5; const ax = Math.cos(sc.th[i]) * hw, ay = Math.sin(sc.th[i]) * hw; ctx.moveTo(x - ax, y - ay); ctx.quadraticCurveTo(cx - ax * 0.5, cy - ay * 0.5, tx, ty); ctx.quadraticCurveTo(cx + ax * 0.5, cy + ay * 0.5, x + ax, y + ay); if (sc.tip[i]) { const sx = 0.2025 * x + 0.495 * cx + 0.3025 * tx, sy = 0.2025 * y + 0.495 * cy + 0.3025 * ty; tipBuf[tn++] = sx - ax * 0.45; tipBuf[tn++] = sy - ay * 0.45; tipBuf[tn++] = tx; tipBuf[tn++] = ty; tipBuf[tn++] = sx + ax * 0.45; tipBuf[tn++] = sy + ay * 0.45; } } if (any) { ctx.fillStyle = cols[c]; ctx.fill(); } } if (tn > 0) { ctx.beginPath(); for (let k = 0; k < tn; k += 6) { ctx.moveTo(tipBuf[k], tipBuf[k + 1]); ctx.lineTo(tipBuf[k + 2], tipBuf[k + 3]); ctx.lineTo(tipBuf[k + 4], tipBuf[k + 5]); } ctx.globalAlpha = 0.5; ctx.fillStyle = "#d4ef7a"; ctx.fill(); ctx.globalAlpha = 1; } while (fi < nf && F[fi].y <= sc.y[s1 - 1]) flowerAt(fi++); } while (fi < nf) flowerAt(fi++); if (lift > 0.01 && px > -900) { ctx.save(); ctx.globalCompositeOperation = "source-atop"; const lg = ctx.createRadialGradient(px, py, 0, px, py, 48); lg.addColorStop(0, `rgba(214,255,130,${0.22 * lift})`); lg.addColorStop(1, "rgba(214,255,130,0)"); ctx.fillStyle = lg; ctx.fillRect(px - 48, py - 48, 96, 96); ctx.restore(); } if (volGrad) { ctx.save(); ctx.globalCompositeOperation = "source-atop"; ctx.fillStyle = volGrad; ctx.fillRect(-PADX, -30, CW, H + 60); ctx.restore(); } // petals + butterfly if (t >= 0 && !rmShow) { for (const p of petals) { const age = t - p.t0; if (age < 0 || age > 1400) continue; const al = 1 - clamp((age - 1000) / 400); const sec = age / 1000; const px0 = p.fl.x + p.vx * sec + 10 * Math.sin(age * 0.006 + p.ph); const py0 = p.fl.y - p.fl.stem - 45 * sec + 35 * sec * sec; ctx.globalAlpha = al; ctx.fillStyle = p.col; ctx.beginPath(); ctx.ellipse(px0, py0, p.w, p.h * Math.max(0.25, Math.abs(Math.cos(age * 0.012 + p.ph))) * 1.2, p.rot + age * 0.002, 0, 6.2832); ctx.fill(); } ctx.globalAlpha = 1; drawClips(now); if (t >= 400 && t < CLOSE_AT) { const al = clamp((t - 400) / 100) * (1 - clamp((t - 2400) / 400)); if (t >= 400 && t < 1000) { const sa = 0.25 * (1 - clamp((t - 400) / 600)); const sx = t < 700 ? BF_X : BF_X + 22 * ((t - 700) / 1000) + 16 * Math.sin((2 * Math.PI * (t - 700)) / 900); ctx.fillStyle = `rgba(0,0,0,${sa})`; ctx.beginPath(); ctx.ellipse(sx, 6, 10, 3, 0, 0, 6.2832); ctx.fill(); } if (t < 700) { butterfly(BF_X, -2 - 8 * easeOut((t - 400) / 300), al, 0.12 + 0.88 * easeOut((t - 400) / 300), 0); } else { const s = (t - 700) / 1000; const ph = (2 * Math.PI * (t - 700)) / 900; const bx = BF_X + 22 * s + 16 * Math.sin(ph); const by = -10 - 50 * s + 2 * Math.sin((2 * Math.PI * (t - 700)) / 180); const vx = 22 + 16 * (2 * Math.PI / 0.9) * Math.cos(ph); butterfly(bx, by, al, 1, t - 700, 0.6 * Math.atan2(vx, 50) + 0.08 * Math.sin((t - 700) * 0.035)); } } } else if (rmShow && rmF > 0) { butterfly(BF_X, -6, rmF, 1, 0); } // label, drawn last so nothing covers it if (labelCv) ctx.drawImage(labelCv, -PADX, -PADT, CW, CH); }; const drawClips = (now: number) => { const age = now - clipAt; if (clipAt < 0 || age < 0 || age >= 650) return; const sec = age / 1000; ctx.globalAlpha = 1 - clamp((age - 400) / 250); const cc = ["#78b62a", "#b9dc55", "#4a8a14"]; for (let c = 0; c < 3; c++) { ctx.fillStyle = cc[c]; ctx.beginPath(); for (let i = c; i < clips.length; i += 3) { const p = clips[i]; const x = clipX + p.ox + Math.cos(p.a) * p.sp * sec; const y = 6 + Math.sin(p.a) * p.sp * sec + 0.5 * 420 * sec * sec; const r = p.r0 + p.spin * sec, co = Math.cos(r), si = Math.sin(r); const pt = (u: number, v: number): [number, number] => [x + u * co - v * si, y + u * si + v * co]; const q0 = pt(-2.5, 0), q1 = pt(0, -0.9), q2 = pt(2.5, 0), q3 = pt(0, 0.9); ctx.moveTo(q0[0], q0[1]); ctx.quadraticCurveTo(q1[0], q1[1], q2[0], q2[1]); ctx.quadraticCurveTo(q3[0], q3[1], q0[0], q0[1]); } ctx.fill(); } ctx.globalAlpha = 1; }; // physics: springs toward a hover target plus a fading footprint memory const springs = (dt: number, now: number) => { const sec = Math.min(dt, 48) / 1000; const steps = sec > 0.022 ? 2 : 1; const h = sec / steps; const decay = Math.exp(-dt / 600); let moving = false; const handle = (X: number, Y: number, b: Float32Array, v: Float32Array, m: Float32Array, mu: Float64Array, i: number, oy: number) => { let target = 0; if (hovering) { const dx = X - px, d = Math.hypot(dx, Y - oy - py); if (d < REACH) { const q = 1 - d / REACH; target = (dx >= 0 ? 1 : -1) * 1.45 * Math.pow(q, 1.4) + clamp(pvx / 600, -1, 1) * 0.6 * q; } } if (m[i] !== 0 && now > mu[i]) { m[i] *= decay; if (Math.abs(m[i]) < 0.002) m[i] = 0; } const goal = target + m[i]; for (let s = 0; s < steps; s++) { v[i] += (SPRING_K * (goal - b[i]) - SPRING_C * v[i]) * h; b[i] += v[i] * h; } if (Math.abs(goal - b[i]) > 0.002 || Math.abs(v[i]) > 0.01) moving = true; else { b[i] = goal; v[i] = 0; } }; for (let i = 0; i < n; i++) handle(sc.x[i], sc.y[i], bb, bv, bm, bmu, i, sc.len[i] * 0.5); for (let i = 0; i < nf; i++) handle(F[i].x, F[i].y, fb, fv, fm, fmu, i, 4); if (!hovering) pvx *= Math.exp(-dt / 120); const lt = hovering ? 1 : 0; for (let s = 0; s < steps; s++) { liftV += (170 * (lt - lift) - 16 * liftV) * h; lift += liftV * h; pressV += (400 * (pressT - press) - 22 * pressV) * h; press += pressV * h; } if (Math.abs(lt - lift) > 0.003 || Math.abs(liftV) > 0.01) moving = true; else { lift = lt; liftV = 0; } if (Math.abs(pressT - press) > 0.003 || Math.abs(pressV) > 0.01) moving = true; else { press = pressT; pressV = 0; } return moving; }; const tick = (now: number) => { raf = 0; if (!canRun()) return; const dt = last ? Math.min(48, now - last) : 16; last = now; const moving = springs(dt, now); let t = -1; if (clickAt >= 0) { t = now - clickAt; if (t >= TOTAL) { clickAt = -1; t = -1; setPlaying(false); } } if (moving || t >= 0 || now - lastDraw >= 33) { render(now, t); lastDraw = now; } raf = requestAnimationFrame(tick); }; const wake = () => { if (!raf && canRun()) { last = 0; raf = requestAnimationFrame(tick); } }; const still = () => { // static single frame for reduced motion, disabled or hidden states bb.fill(0); bv.fill(0); fb.fill(0); fv.fill(0); render(performance.now(), -1); }; const refresh = () => { host.dataset.tbPaused = String(disabled || !visible || document.hidden); cancelAnimationFrame(raf); raf = 0; if (canRun()) { wake(); } else if (!rmOn) { clickAt = -1; setPlaying(false); still(); } }; const local = (e: PointerEvent) => { if (dirty || !rect) { rect = el.getBoundingClientRect(); dirty = false; } const s = rect.width / (el.offsetWidth || 1) || 1; px = (e.clientX - rect.left) / s; py = (e.clientY - rect.top) / s; }; const ripple = (now: number, e: PointerEvent) => { const dtm = Math.max(1, e.timeStamp - lastMove); const speed = (Math.hypot(px - lastPx, py - lastPy) / dtm) * 1000; if (speed > 300) { for (let i = 0; i < n; i++) { const dx = sc.x[i] - px; if (Math.abs(dx) < 20 && Math.hypot(dx, sc.y[i] - sc.len[i] * 0.5 - py) < 20) { const dir = dx >= 0 ? 1 : -1; bv[i] += dir * 2.5; bm[i] = dir * 0.36; bmu[i] = now + 1200; } } } }; const enter = (e: PointerEvent) => { if (e.pointerType === "touch") return; hovering = true; dirty = true; local(e); lastPx = px; lastPy = py; lastMove = e.timeStamp; wake(); }; const move = (e: PointerEvent) => { if (e.pointerType === "touch" || !canRun()) return; hovering = true; const opx = px; local(e); { const dtm = Math.max(1, e.timeStamp - lastMove); const inst = ((px - (opx > -900 ? opx : px)) / dtm) * 1000; pvx += (inst - pvx) * (1 - Math.exp(-dtm / 80)); } ripple(performance.now(), e); lastPx = px; lastPy = py; lastMove = e.timeStamp; wake(); }; const leave = () => { hovering = false; pressT = 0; px = py = -999; wake(); }; const down = (e: PointerEvent) => { if (e.button !== 0 || !canRun()) return; pressT = 1; wake(); }; const up = () => { pressT = 0; wake(); }; const invalidate = () => { dirty = true; }; const resize = () => { setup(); refresh(); }; const io = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([en]) => { visible = en.isIntersecting; refresh(); }); const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); const mediaChange = () => { clearTimers(); rmOn = false; clickAt = -1; setPlaying(false); refresh(); }; playRef.current = (x: number) => { if (!canRun() && !rmNow()) return; if (rmNow()) { if (rmOn || disabled) return; rmOn = true; rmB = 0; rmF = 0; setPlaying(true); const step = (v: number) => { rmB = v; rmF = v; render(performance.now(), -1); }; [0, 50, 100, 150].forEach((ms, i) => later(() => step((i + 1) / 4), ms)); [1200, 1250, 1300, 1350].forEach((ms, i) => later(() => step(1 - (i + 1) / 4), ms)); later(() => { rmOn = false; rmB = rmF = 0; setPlaying(false); still(); }, 1420); return; } if (!hovering) { pressT = 1; later(() => { pressT = 0; wake(); }, 90); } // gust: every blade gets pushed away from the click point for (let i = 0; i < n; i++) bv[i] += (sc.x[i] >= x ? 1 : -1) * 7 * (0.75 + 0.25 * ((i * 37) % 10) / 10); for (let i = 0; i < nf; i++) fv[i] += (F[i].x >= x ? 1 : -1) * 5; clipAt = performance.now(); clipX = x; if (clickAt < 0) { clickAt = clipAt; setPlaying(true); } wake(); }; setup(); io?.observe(host); ro?.observe(el); window.addEventListener("resize", resize); window.addEventListener("scroll", invalidate, true); el.addEventListener("pointerenter", enter); el.addEventListener("pointermove", move); el.addEventListener("pointerleave", leave); el.addEventListener("pointerdown", down); el.addEventListener("pointerup", up); el.addEventListener("pointercancel", up); document.addEventListener("visibilitychange", refresh); media.addEventListener("change", mediaChange); refresh(); if (!canRun()) still(); return () => { playRef.current = () => {}; cancelAnimationFrame(raf); clearTimers(); io?.disconnect(); ro?.disconnect(); window.removeEventListener("resize", resize); window.removeEventListener("scroll", invalidate, true); el.removeEventListener("pointerenter", enter); el.removeEventListener("pointermove", move); el.removeEventListener("pointerleave", leave); el.removeEventListener("pointerdown", down); el.removeEventListener("pointerup", up); el.removeEventListener("pointercancel", up); document.removeEventListener("visibilitychange", refresh); media.removeEventListener("change", mediaChange); }; }, [disabled, label, paletteKey]); const click = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; const r = e.currentTarget.getBoundingClientRect(); const s = r.width / (e.currentTarget.offsetWidth || 1) || 1; playRef.current(e.detail > 0 ? (e.clientX - r.left) / s : W / 2); }; return ( ); } export default GrassButton; const css = ` .tb-grass-wrap{display:inline-flex;position:relative;vertical-align:middle} .tb-grass-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} .tb-grass-btn:focus-visible{outline:2px solid #c6ec5c;outline-offset:9px} .tb-grass-btn:disabled{cursor:not-allowed} .tb-grass-btn:disabled .tb-grass-canvas{opacity:.6;filter:saturate(.5)} .tb-grass-canvas{position:absolute;left:-${PADX}px;top:-${PADT}px;width:${CW}px;height:${CH}px;max-width:none;pointer-events:none} .tb-grass-wrap[data-tb-paused=true] *{animation-play-state:paused!important} @media (prefers-reduced-motion:reduce){.tb-grass-wrap *,.tb-grass-wrap *::before,.tb-grass-wrap *::after{animation:none!important;transition:none!important}} `;