"use client"; /** * candle.tsx — a frosted cake button with a living candle. * The flame leans away from your cursor. Click to blow it out and make a wish. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useId, useRef, useState, useImperativeHandle, type ButtonHTMLAttributes, type Ref, type RefObject, type MouseEvent, type ReactNode, } from "react"; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; /** ms before the candle relights itself */ relightAfter?: number; }; const DRIPS: [x: number, w: number, len: number][] = [ [204, 11, 14], [176, 9, 8], [150, 14, 17], [121, 9, 9], [95, 13, 15], [66, 9, 8], [40, 12, 13], [15, 9, 7], ]; const FROSTING = (() => { const base = 11; let d = `M0 0H220V${base}`; for (const [x, w, len] of DRIPS) { d += `L${x + w / 2} ${base}C${x + w / 2} ${base + len} ${x - w / 2} ${base + len} ${x - w / 2} ${base}`; } return `${d}L0 ${base}Z`; })(); const SPRINKLES = [ { x: 9, y: 4, r: 28, c: "#7cc6f2" }, { x: 19, y: 7, r: -40, c: "#ffd166" }, { x: 31, y: 3, r: 70, c: "#9be3b0" }, { x: 44, y: 6, r: -15, c: "#c3a6ff" }, { x: 58, y: 3, r: 50, c: "#ffd166" }, { x: 69, y: 7, r: -60, c: "#7cc6f2" }, { x: 80, y: 4, r: 20, c: "#f47aa6" }, { x: 91, y: 6, r: -35, c: "#9be3b0" }, ]; const SPARKS = [ { x: -9, y: 30, s: 22, d: 0, c: "#ffc94d" }, { x: 108, y: 14, s: 18, d: 60, c: "#ff8fbf" }, { x: 16, y: -45, s: 15, d: 120, c: "#8fcbff" }, { x: 86, y: -60, s: 20, d: 40, c: "#ffc94d" }, { x: 104, y: 92, s: 13, d: 160, c: "#b39bff" }, { x: -5, y: 98, s: 15, d: 100, c: "#ff8fbf" }, { x: 62, y: -95, s: 12, d: 200, c: "#7fdba0" }, { x: 34, y: -90, s: 10, d: 240, c: "#ffc94d" }, { x: 40, y: 125, s: 11, d: 180, c: "#8fcbff" }, { x: 75, y: 128, s: 9, d: 260, c: "#ffc94d" }, ]; export function CandleButton({ children = "make a wish", relightAfter = 2600, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const [lit, setLit] = useState(true); const [wishes, setWishes] = useState(0); const leanRef = useRef(null); const flameRef = useRef(null); const busy = useRef(false); const lean = useRef(0); const work = useWork(disabled, () => { busy.current = false; setLit(true); }); const uid = `tbc-${useId()}`; // The candle sits 38px above the button; keep its resting anchor stable. const wake = usePointerMotion(btnRef, disabled, (r, x, y, _hover, scale) => { if (!lit) return true; const dx = x - (r.left + r.width / 2); const dy = y - (r.top - 38 * scale); const dist = Math.hypot(dx, dy) || 1; const reach = Math.max(0, 1 - dist / 340); const target = (-dx / dist) * Math.sqrt(reach) * 40; lean.current += (target - lean.current) * 0.08; if (leanRef.current) leanRef.current.style.transform = `rotate(${lean.current.toFixed(2)}deg) scale(${(1 - reach * 0.06).toFixed(3)},${(1 + reach * 0.22).toFixed(3)})`; return Math.abs(target - lean.current) < 0.01; }); useEffect(() => { wake.current(); }, [lit, wake]); const blow = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; if (busy.current || !lit) return; busy.current = true; wake.current(); const fr = flameRef.current?.getBoundingClientRect(); // which way the breath pushes the flame (away from the cursor) const dir = !fr || e.detail === 0 ? 1 : e.clientX > fr.left + fr.width / 2 ? -1 : 1; const out = () => { setLit(false); setWishes((w) => w + 1); work.later(() => { setLit(true); busy.current = false; }, relightAfter); }; if (work.reduced()) { out(); return; } work.animate(flameRef.current, [ { transform: "skewX(0deg) scale(1, 1)", opacity: 1 }, { transform: `skewX(${-dir * 40}deg) scale(1.3, .7)`, opacity: 1, offset: 0.45 }, { transform: `skewX(${-dir * 58}deg) scale(.15, .05)`, opacity: 0 }, ], { duration: 420, easing: "cubic-bezier(.5,0,.75,0)", fill: "forwards" }, out, ); }; return ( ); } export default CandleButton; // Each file stays copyable: all animation ownership lives with this instance. function useWork(disabled: boolean, reset: () => void) { const state = useRef({ epoch: 0, active: false, timers: new Set(), animations: new Map() }); const resetRef = useRef(reset); resetRef.current = reset; useEffect(() => { const s = state.current; const clear = () => { s.epoch++; s.timers.forEach((id) => window.clearTimeout(id)); s.timers.clear(); s.animations.forEach(({ el, remove }, a) => { a.cancel(); if (remove) el.remove(); }); s.animations.clear(); }; s.active = !disabled; if (disabled) resetRef.current(); const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const change = () => { clear(); resetRef.current(); }; media.addEventListener("change", change); return () => { s.active = false; clear(); media.removeEventListener("change", change); }; }, [disabled]); const later = (done: () => void, ms: number) => { const s = state.current; const epoch = s.epoch; const id = window.setTimeout(() => { s.timers.delete(id); if (s.active && s.epoch === epoch) done(); }, ms); s.timers.add(id); return id; }; const animate = (el: Element | null, frames: Keyframe[], timing: KeyframeAnimationOptions, done?: () => void, remove = false) => { const s = state.current; if (!s.active) return; s.animations.forEach((entry, a) => { if (entry.el === el) { a.cancel(); s.animations.delete(a); } }); if (!el) { done?.(); return; } const epoch = s.epoch; const a = el.animate(frames, timing); s.animations.set(a, { el, remove }); const finish = () => { if (remove) { el.remove(); a.cancel(); } if (remove || done || (timing.fill !== "forwards" && timing.fill !== "both")) s.animations.delete(a); }; a.finished.then(() => { finish(); if (s.active && s.epoch === epoch) done?.(); if (done) a.cancel(); }, () => { if (remove) el.remove(); s.animations.delete(a); }); }; const cancelAnimations = (el: Element) => { state.current.animations.forEach((entry, a) => { if (entry.el === el) { a.cancel(); if (entry.remove) el.remove(); state.current.animations.delete(a); } }); }; return { later, animate, cancelAnimations, cancel: (id: number) => { window.clearTimeout(id); state.current.timers.delete(id); }, reduced: () => window.matchMedia("(prefers-reduced-motion: reduce)").matches, }; } // Cache geometry until layout changes; stop the spring once it settles. function usePointerMotion( ref: RefObject, disabled: boolean, step: (r: DOMRect, x: number, y: number, hover: boolean, scale: number) => boolean, ) { const stepRef = useRef(step); stepRef.current = step; const wake = useRef(() => {}); useEffect(() => { const button = ref.current; const wrap = button?.parentElement; if (!button || !wrap) return; let raf = 0, dirty = true, visible = true, hover = button.matches(":hover"); let x = -1e4, y = -1e4, scale = 1, wasNear = false; let rect: DOMRect | undefined; const media = window.matchMedia("(prefers-reduced-motion: reduce)"); const allowed = () => !disabled && !button.matches(":disabled") && visible && !document.hidden && !media.matches; const tick = () => { raf = 0; if (!allowed()) return; if (dirty) { rect = button.getBoundingClientRect(); scale = rect.width / (button.offsetWidth || 1); dirty = false; } if (!stepRef.current(rect!, x, y, hover, scale)) raf = requestAnimationFrame(tick); }; const start = () => { if (!raf && allowed()) raf = requestAnimationFrame(tick); }; wake.current = start; const pause = () => { wrap.dataset.tbPaused = String(disabled || !visible || document.hidden); if (!allowed()) { cancelAnimationFrame(raf); raf = 0; } else { dirty = true; start(); } }; const invalidate = () => { dirty = true; start(); }; const move = (e: PointerEvent) => { x = e.clientX; y = e.clientY; const near = hover || !rect || (x >= rect.left - 400 && x <= rect.right + 400 && y >= rect.top - 400 && y <= rect.bottom + 400); if (near || wasNear) start(); wasNear = near; }; const enter = (e: PointerEvent) => { hover = true; dirty = true; move(e); }; const leave = () => { hover = false; start(); }; const gone = () => { x = y = -1e4; hover = false; start(); }; const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; pause(); }); observer?.observe(wrap); const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(invalidate); resize?.observe(button); window.addEventListener("pointermove", move, { passive: true }); window.addEventListener("resize", invalidate); window.addEventListener("scroll", invalidate, true); document.documentElement.addEventListener("pointerleave", gone); document.addEventListener("visibilitychange", pause); button.addEventListener("pointerenter", enter); button.addEventListener("pointerleave", leave); button.addEventListener("transitionend", invalidate); media.addEventListener("change", pause); pause(); return () => { wake.current = () => {}; cancelAnimationFrame(raf); observer?.disconnect(); resize?.disconnect(); window.removeEventListener("pointermove", move); window.removeEventListener("resize", invalidate); window.removeEventListener("scroll", invalidate, true); document.documentElement.removeEventListener("pointerleave", gone); document.removeEventListener("visibilitychange", pause); button.removeEventListener("pointerenter", enter); button.removeEventListener("pointerleave", leave); button.removeEventListener("transitionend", invalidate); media.removeEventListener("change", pause); }; }, [disabled, ref]); return wake; } const css = ` .tbc-wrap{display:inline-flex;padding-top:64px} .tbc-btn{position:relative;display:inline-flex;align-items:center;justify-content:center;width:220px;height:62px; padding:12px 0 0;border:0;border-radius:16px;cursor:pointer;color:#fff;-webkit-tap-highlight-color:transparent; font:700 17px/1 ui-rounded,"SF Pro Rounded","Nunito","Segoe UI",system-ui,sans-serif;letter-spacing:.01em; background:linear-gradient(180deg,#fab6cf 0%,#f492b7 55%,#e9779f 100%); box-shadow:inset 0 -5px 0 rgba(150,30,80,.12),0 12px 26px -10px rgba(214,80,130,.6),0 2px 4px rgba(0,0,0,.08); transition:transform .25s cubic-bezier(.3,1.6,.5,1)} .tbc-btn:enabled:hover{transform:translateY(-2px)} .tbc-btn:enabled:active{transform:translateY(1px) scale(.98)} .tbc-btn:focus-visible{outline:3px solid #f492b7;outline-offset:4px} .tbc-cake{position:absolute;inset:0;border-radius:inherit;overflow:hidden;pointer-events:none} .tbc-frost{position:absolute;left:0;top:0;width:100%;height:30px;filter:drop-shadow(0 2px 1px rgba(170,40,95,.28))} .tbc-sprinkle{position:absolute;width:7px;height:2.6px;border-radius:2px} .tbc-label{position:relative;text-shadow:0 1px 0 rgba(170,40,90,.35)} .tbc-candle{position:absolute;left:50%;bottom:calc(100% - 7px);width:11px;height:40px;margin-left:-5.5px; border-radius:3px 3px 2px 2px;pointer-events:none; background:repeating-linear-gradient(135deg,#fff 0 5px,#7cc6f2 5px 10px);box-shadow:inset -3px 0 0 rgba(0,0,0,.07)} .tbc-wick{position:absolute;left:50%;top:-7px;width:2px;height:8px;margin-left:-1px;border-radius:1px;background:linear-gradient(#1d1410,#4a3426)} .tbc-wick.is-out::after{content:"";position:absolute;left:-1px;top:-1px;width:4px;height:4px;border-radius:50%; background:#ff7a1a;box-shadow:0 0 6px 2px rgba(255,120,30,.7);animation:tbc-ember 1.8s ease-out forwards} .tbc-lean{position:absolute;left:50%;bottom:calc(100% + 1px);width:20px;height:36px;margin-left:-10px;transform-origin:50% 89%} .tbc-layer{position:absolute;inset:0;transform-origin:50% 89%} .tbc-flicker{animation:tbc-flicker .9s ease-in-out infinite} .tbc-ignite{animation:tbc-ignite .45s cubic-bezier(.3,1.5,.5,1) both} .tbc-flame{position:absolute;inset:0;width:100%;height:100%;overflow:visible;animation:tbc-flicker2 1.3s ease-in-out infinite;transform-origin:50% 89%} .tbc-glow{position:absolute;left:50%;top:62%;width:120px;height:120px;margin:-60px 0 0 -60px;border-radius:50%; background:radial-gradient(closest-side,rgba(255,196,90,.5),rgba(255,160,60,.16) 55%,transparent);animation:tbc-glow 2.2s ease-in-out infinite} .tbc-smoke{position:absolute;left:50%;bottom:calc(100% + 4px);width:40px;height:100px;margin-left:-20px;overflow:visible} .tbc-smoke path{fill:none;stroke:#a3a8b0;stroke-width:3;stroke-linecap:round;stroke-dasharray:160;stroke-dashoffset:160; filter:blur(1.2px);opacity:0;animation:tbc-smoke 1.9s ease-out forwards} .tbc-sparks{position:absolute;inset:0;pointer-events:none} .tbc-spark{position:absolute;transform:translate(-50%,-50%) scale(0);animation:tbc-spark .9s cubic-bezier(.3,1.4,.5,1) both} @keyframes tbc-flicker{0%,100%{transform:scale(1,1) skewX(0)}20%{transform:scale(.95,1.05) skewX(2deg)}40%{transform:scale(1.03,.96) skewX(-1deg)} 60%{transform:scale(.97,1.07) skewX(1deg)}80%{transform:scale(1.02,.98) skewX(-2deg)}} @keyframes tbc-flicker2{0%,100%{transform:scaleY(1)}33%{transform:scaleY(1.06)}66%{transform:scaleY(.95)}} @keyframes tbc-glow{0%,100%{opacity:.85;transform:scale(1)}50%{opacity:1;transform:scale(1.08)}} @keyframes tbc-ignite{0%{transform:scale(0)}55%{transform:scale(1.3,1.45)}100%{transform:scale(1)}} @keyframes tbc-ember{0%{opacity:1}100%{opacity:0}} @keyframes tbc-smoke{0%{stroke-dashoffset:160;opacity:0;transform:translateY(0)}15%{opacity:.8} 100%{stroke-dashoffset:0;opacity:0;transform:translateY(-36px) scaleX(1.5)}} @keyframes tbc-spark{0%{transform:translate(-50%,-50%) scale(0) rotate(0);opacity:1}45%{transform:translate(-50%,-50%) scale(1) rotate(90deg);opacity:1} 100%{transform:translate(-50%,-50%) scale(0) rotate(180deg);opacity:0}} @media (prefers-reduced-motion:reduce){.tbc-flicker,.tbc-flame,.tbc-glow{animation:none}} .tbc-btn:disabled{cursor:default;transition:none} .tbc-wrap[data-tb-paused=true] *{animation-play-state:paused!important} .tbc-btn:disabled *{transition:none!important;animation:none!important} @media (prefers-reduced-motion:reduce){.tbc-wrap *, .tbc-wrap *::before, .tbc-wrap *::after{animation:none!important;transition:none!important}} .tbc-btn:disabled .tbc-lean{transform:none!important} @media (prefers-reduced-motion:reduce){.tbc-lean{transform:none!important}} `;