Specification
- Catalogue
- No. 107 of 110
- Section
- Buttons and toggles
- Interaction
- Press, Drag
- Element
- Button
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
A round arrow button you can pull back. A band stretches from its resting place to the button as you drag, and when you let go past a short distance it springs back, overshoots once, and the arrow shoots out of the top corner while a new one slides in.
The band is one capsule: as long as the pull plus the button, turned to the pull's angle, with its origin on the rest point. The return is a spring stepped per frame (stiffness 0.085, damping 0.2, in sixtieths of a second) so a long pull overshoots further. Enter or Space fires it from the keyboard. Under reduced motion it returns at once.
Code
React and plain CSS"use client";
import { useEffect, useRef, useState, type PointerEvent } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { useReducedMotion } from "@/lib/client/hooks";
import styles from "./slingshot-button.module.css";
type Vec = { x: number; y: number };
/** How far the button can be pulled, and the pull that counts as a shot. */
const MAX_PULL = 110;
const FIRE_AT = 40;
/** Spring per sixtieth of a second: stiffness and damping, underdamped so it overshoots the rest point once. */
const K = 0.085;
const C = 0.2;
const DEMO_PULL: Vec = { x: -72, y: 62 };
function clampPull(v: Vec): Vec {
const len = Math.hypot(v.x, v.y);
if (len <= MAX_PULL) return v;
return { x: (v.x / len) * MAX_PULL, y: (v.y / len) * MAX_PULL };
}
export default function SlingshotButton({ active, context }: LivePreviewProps) {
const card = context === "card";
const reduced = useReducedMotion();
const rootRef = useRef<HTMLDivElement>(null);
const pos = useRef<Vec>({ x: 0, y: 0 });
const vel = useRef<Vec>({ x: 0, y: 0 });
const drag = useRef<{ start: Vec; scale: number } | null>(null);
const raf = useRef(0);
const [shots, setShots] = useState(0);
/** Writes the pull into CSS variables: the button's offset and the band from the rest point to it. */
const paint = () => {
const root = rootRef.current;
if (!root) return;
const { x, y } = pos.current;
root.style.setProperty("--x", `${x.toFixed(2)}px`);
root.style.setProperty("--y", `${y.toFixed(2)}px`);
root.style.setProperty("--len", `${Math.hypot(x, y).toFixed(2)}px`);
root.style.setProperty("--angle", `${Math.atan2(y, x).toFixed(4)}rad`);
};
const springBack = () => {
cancelAnimationFrame(raf.current);
if (reduced) {
pos.current = { x: 0, y: 0 };
paint();
return;
}
let last = performance.now();
const step = (now: number) => {
const dt = Math.min(2.5, (now - last) / (1000 / 60));
last = now;
const p = pos.current;
const v = vel.current;
v.x += (-K * p.x - C * v.x) * dt;
v.y += (-K * p.y - C * v.y) * dt;
p.x += v.x * dt;
p.y += v.y * dt;
paint();
if (Math.hypot(p.x, p.y) < 0.2 && Math.hypot(v.x, v.y) < 0.05) {
pos.current = { x: 0, y: 0 };
paint();
return;
}
raf.current = requestAnimationFrame(step);
};
raf.current = requestAnimationFrame(step);
};
const release = () => {
const pulled = Math.hypot(pos.current.x, pos.current.y);
vel.current = { x: 0, y: 0 };
if (pulled >= FIRE_AT) setShots((s) => s + 1);
springBack();
};
useEffect(() => () => cancelAnimationFrame(raf.current), []);
// The card demo draws the button back toward the lower left, lets go, and waits.
const demo = card && active;
useEffect(() => {
if (!demo) {
cancelAnimationFrame(raf.current);
pos.current = { x: 0, y: 0 };
vel.current = { x: 0, y: 0 };
paint();
return;
}
let timer = 0;
let frame = 0;
const pull = () => {
const start = performance.now();
const tick = (now: number) => {
const t = Math.min(1, (now - start) / 620);
const e = 1 - Math.pow(1 - t, 3);
pos.current = { x: DEMO_PULL.x * e, y: DEMO_PULL.y * e };
paint();
if (t < 1) frame = requestAnimationFrame(tick);
else timer = window.setTimeout(() => {
release();
timer = window.setTimeout(pull, 1500);
}, 260);
};
frame = requestAnimationFrame(tick);
};
timer = window.setTimeout(pull, 400);
return () => {
window.clearTimeout(timer);
cancelAnimationFrame(frame);
};
// paint and release only touch refs and a state setter.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [demo]);
function onDown(event: PointerEvent<HTMLButtonElement>) {
if (card) return;
const root = rootRef.current;
if (!root) return;
cancelAnimationFrame(raf.current);
event.currentTarget.setPointerCapture(event.pointerId);
const rect = root.getBoundingClientRect();
drag.current = { start: { x: event.clientX - pos.current.x, y: event.clientY - pos.current.y }, scale: rect.width / root.offsetWidth || 1 };
}
function onMove(event: PointerEvent<HTMLButtonElement>) {
const d = drag.current;
if (!d) return;
// A little give at first, then the band takes the strain.
pos.current = clampPull({ x: ((event.clientX - d.start.x) / d.scale) * 0.85, y: ((event.clientY - d.start.y) / d.scale) * 0.85 });
paint();
}
function onUp() {
if (!drag.current) return;
drag.current = null;
release();
}
return (
<div ref={rootRef} className={styles.area}>
<span className={styles.band} aria-hidden="true" />
<button
type="button"
className={styles.button}
tabIndex={card ? -1 : 0}
aria-label="Launch. Drag back and let go, or press Enter"
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
onKeyDown={(e) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
pos.current = { x: DEMO_PULL.x * 0.8, y: DEMO_PULL.y * 0.8 };
release();
}}
>
<span key={shots} className={styles.arrow} data-fired={shots > 0 || undefined}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M7 17 17 7M8 7h9v9" />
</svg>
</span>
</button>
<p className="visually-hidden" role="status">
{shots > 0 ? `Launched ${shots} ${shots === 1 ? "time" : "times"}.` : ""}
</p>
</div>
);
}