"use client"; /** * sticky.tsx — a sticky-note button. * The corner curls up as your cursor gets close. Click to peel it off; the next note is waiting underneath. * * Part of toy-buttons. MIT licensed. Only depends on React. */ import { useEffect, useRef, useState, useImperativeHandle, type ButtonHTMLAttributes, type Ref, type RefObject, type CSSProperties, type MouseEvent, type ReactNode, } from "react"; type Props = Omit, "children"> & { children?: ReactNode; ref?: Ref; /** paper colors, cycled as notes get peeled off */ papers?: { paper: string; edge: string }[]; }; const PAPERS = [ { paper: "#ffe56b", edge: "#f0c93a" }, { paper: "#ffb5c9", edge: "#f08aa8" }, { paper: "#a9dcff", edge: "#74bbef" }, { paper: "#c4f0a9", edge: "#90d475" }, ]; const tilt = (n: number) => [-2.2, 1.6, -0.8, 2.4][n % 4]; export function StickyButton({ children = "peel me", papers = PAPERS, onClick, className, type = "button", disabled = false, ref, ...rest }: Props) { const btnRef = useRef(null); useImperativeHandle(ref, () => btnRef.current!, []); const [n, setN] = useState(0); const noteRef = useRef(null); const curl = useRef(5); const peeling = useRef(false); const work = useWork(disabled, () => { if (peeling.current) setN((v) => v + 1); peeling.current = false; curl.current = 5; }); // The resting note geometry stays cached while the corner curls. const wake = usePointerMotion(btnRef, disabled, (r, x, y, hover) => { const d = Math.hypot(x - r.right, y - r.bottom); const target = peeling.current ? 58 : hover ? 15 + Math.max(0, 1 - d / 150) * 28 : 5; curl.current += (target - curl.current) * (peeling.current ? 0.3 : 0.16); noteRef.current?.style.setProperty("--tbs-c", `${curl.current.toFixed(2)}px`); return Math.abs(target - curl.current) < 0.01; }); const peel = (e: MouseEvent) => { if (disabled || e.currentTarget.matches(":disabled")) return; onClick?.(e); if (e.defaultPrevented) return; const el = noteRef.current; if (peeling.current || !el) return; if (work.reduced()) { setN((v) => v + 1); return; } peeling.current = true; wake.current(); const r = tilt(n); const at = (x: number, y: number, rot: number, rx: number, s: number) => `translate(${x}px,${y}px) rotate(${r + rot}deg) rotateX(${rx}deg) scale(${s})`; work.later(() => { work.animate(el, [ { transform: at(0, 0, 0, 0, 1), opacity: 1 }, { transform: at(5, -10, -5, 8, 1.06), opacity: 1, offset: 0.12 }, { transform: at(50, 34, 16, 34, 1.04), opacity: 1, offset: 0.32 }, { transform: at(16, 110, -12, -24, 1.02), opacity: 1, offset: 0.52 }, { transform: at(74, 190, 24, 38, 1), opacity: 0.9, offset: 0.74 }, { transform: at(40, 290, 6, 0, 0.98), opacity: 0 }, ], { duration: 1500, easing: "cubic-bezier(.3,.1,.5,1)", fill: "forwards" }, () => { curl.current = 5; peeling.current = false; setN((v) => v + 1); wake.current(); }); }, 170); }; // three notes deep: the top one, and the pad underneath const stack = [n + 2, n + 1, n]; return ( ); } export default StickyButton; // 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 - 0 && x <= rect.right + 0 && y >= rect.top - 0 && y <= rect.bottom + 0); 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 = ` .tbs-wrap{display:inline-flex} .tbs-btn{position:relative;width:210px;height:76px;padding:0;border:0;background:none;cursor:pointer;perspective:700px;-webkit-tap-highlight-color:transparent} .tbs-btn:focus-visible{outline:2px dashed #b8a24a;outline-offset:8px;border-radius:4px} .tbs-note{--tbs-c:5px;position:absolute;inset:0;transform-origin:30% 0; filter:drop-shadow(0 7px 6px rgba(60,50,20,.13)) drop-shadow(0 1px 1px rgba(60,50,20,.14))} .tbs-face{position:absolute;inset:0;display:flex;align-items:center;justify-content:center; clip-path:polygon(0 0,100% 0,100% calc(100% - var(--tbs-c)),calc(100% - var(--tbs-c)) 100%,0 100%); background:linear-gradient(180deg,rgba(0,0,0,.045) 0 13px,transparent 13px), linear-gradient(160deg,rgba(255,255,255,.4),rgba(255,255,255,0) 45%,rgba(0,0,0,.04)),var(--tbs-paper)} .tbs-label{color:#3a3122;transform:rotate(-1deg) translateY(3px); font:700 22px/1 "Segoe Print","Bradley Hand","Chalkboard SE","Marker Felt","Comic Sans MS",cursive} .tbs-flap-wrap{position:absolute;right:0;bottom:0;width:var(--tbs-c);height:var(--tbs-c);filter:drop-shadow(-2px -2px 2px rgba(60,40,10,.22))} .tbs-flap{position:absolute;inset:0;clip-path:polygon(0 0,100% 0,0 100%); background:linear-gradient(135deg,rgba(255,255,255,.55) 0%,rgba(255,255,255,.15) 34%,rgba(0,0,0,.1) 50%),var(--tbs-edge)} .tbs-btn:disabled{cursor:default;transition:none} .tbs-wrap[data-tb-paused=true] *{animation-play-state:paused!important} .tbs-btn:disabled *{transition:none!important;animation:none!important} @media (prefers-reduced-motion:reduce){.tbs-wrap *, .tbs-wrap *::before, .tbs-wrap *::after{animation:none!important;transition:none!important}} .tbs-btn:disabled .tbs-note{--tbs-c:5px!important} @media (prefers-reduced-motion:reduce){.tbs-note{--tbs-c:5px!important}} `;