"use client";
import { AnimatePresence, motion } from "motion/react";
import { useCallback, useEffect, useRef, useState } from "react";
/**
* Signature Pad — an original take inspired by bencho.dev's "Signature pad".
* Ink is drawn as short quadratic segments whose width follows pen speed
* (slow = full nib, fast = hairline). Clear rewinds the ink stroke by stroke;
* leaving the pad alone settles the ink and folds the card into a "Signed" pill.
*/
const W = 300;
const H = 180;
type Pt = { x: number; y: number; t: number };
type Seg = { d: string; w: number };
type Stroke = Seg[];
type Phase = "idle" | "drawing" | "settling" | "signed" | "rewinding";
export type SignaturePadProps = {
/** Ink colour. Defaults to the theme's foreground. */
ink?: "auto" | "blue";
/** 0–100 — how much the pointer path is smoothed. */
smoothing?: number;
/** 0–100 — nib size. */
pen?: number;
/** ms of stillness before the ink settles and the pad folds. 0 disables. */
commitDelay?: number;
onSigned?: () => void;
};
const f = (n: number) => n.toFixed(1);
export function SignaturePad({
ink = "auto",
smoothing = 50,
pen = 50,
commitDelay = 380,
onSigned,
}: SignaturePadProps) {
const [strokes, setStrokes] = useState<Stroke[]>([]);
const [live, setLive] = useState<Stroke | null>(null);
const [phase, setPhase] = useState<Phase>("idle");
const [visible, setVisible] = useState<number>(Infinity); // segments shown while rewinding
const svgRef = useRef<SVGSVGElement>(null);
const pts = useRef<Pt[]>([]);
const width = useRef(0);
const smooth = useRef<{ x: number; y: number } | null>(null);
const timers = useRef<number[]>([]);
const raf = useRef(0);
const maxW = 2.6 + (pen / 100) * 4.1; // pen 50 → ~4.65
const minW = Math.max(0.9, maxW * 0.3);
const lerp = 1 - (smoothing / 100) * 0.75; // smoothing 50 → 0.625
const clearTimers = () => {
timers.current.forEach((t) => window.clearTimeout(t));
timers.current = [];
};
useEffect(() => () => {
clearTimers();
cancelAnimationFrame(raf.current);
}, []);
const toLocal = (e: React.PointerEvent) => {
const r = svgRef.current!.getBoundingClientRect();
return {
x: ((e.clientX - r.left) / r.width) * W,
y: ((e.clientY - r.top) / r.height) * H,
};
};
const scheduleCommit = useCallback(() => {
clearTimers();
if (!commitDelay) return;
timers.current.push(
window.setTimeout(() => {
setPhase("settling");
timers.current.push(
window.setTimeout(() => {
setPhase("signed");
onSigned?.();
}, 1150)
);
}, commitDelay)
);
}, [commitDelay, onSigned]);
const onDown = (e: React.PointerEvent<SVGSVGElement>) => {
if (phase === "signed" || phase === "rewinding") return;
clearTimers();
e.currentTarget.setPointerCapture(e.pointerId);
const p = toLocal(e);
smooth.current = p;
pts.current = [{ ...p, t: performance.now() }];
width.current = maxW * 0.74; // nib lands a little thin, then swells
setLive([{ d: `M${f(p.x)} ${f(p.y)}L${f(p.x)} ${f(p.y + 0.01)}`, w: width.current }]);
setPhase("drawing");
};
const onMove = (e: React.PointerEvent<SVGSVGElement>) => {
if (phase !== "drawing" || !smooth.current) return;
const events = e.nativeEvent.getCoalescedEvents?.() ?? [e.nativeEvent];
const segs: Seg[] = [];
for (const ev of events) {
const r = svgRef.current!.getBoundingClientRect();
const raw = { x: ((ev.clientX - r.left) / r.width) * W, y: ((ev.clientY - r.top) / r.height) * H };
const s = smooth.current!;
s.x += (raw.x - s.x) * lerp;
s.y += (raw.y - s.y) * lerp;
const now = performance.now();
const list = pts.current;
const last = list[list.length - 1];
const dist = Math.hypot(s.x - last.x, s.y - last.y);
if (dist < 0.8) continue;
const dt = Math.max(1, now - last.t);
const v = dist / dt; // px per ms in pad units
const target = Math.max(minW, Math.min(maxW, maxW - (v - 0.12) * 2.1));
width.current += (target - width.current) * 0.22;
list.push({ x: s.x, y: s.y, t: now });
const n = list.length;
const a = list[n - 3] ?? list[0];
const b = list[n - 2];
const c = list[n - 1];
const m1 = n >= 3 ? { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } : b;
const m2 = { x: (b.x + c.x) / 2, y: (b.y + c.y) / 2 };
segs.push({ d: `M${f(m1.x)} ${f(m1.y)}Q${f(b.x)} ${f(b.y)} ${f(m2.x)} ${f(m2.y)}`, w: width.current });
}
if (segs.length) setLive((prev) => (prev ? [...prev, ...segs] : segs));
};
const onUp = () => {
if (phase !== "drawing") return;
const list = pts.current;
const seg: Seg[] = [];
if (list.length >= 2) {
// Lift-off: taper the last stretch so the tail flicks out thin.
const b = list[list.length - 2];
const c = list[list.length - 1];
seg.push({ d: `M${f((b.x + c.x) / 2)} ${f((b.y + c.y) / 2)}L${f(c.x)} ${f(c.y)}`, w: width.current * 0.7 });
}
setStrokes((s) => [...s, [...(live ?? []), ...seg]]);
setLive(null);
smooth.current = null;
setPhase("idle");
scheduleCommit();
};
const total = strokes.reduce((n, s) => n + s.length, 0);
const hasInk = total > 0 || !!live;
const rewind = () => {
if (!total) return;
clearTimers();
setPhase("rewinding");
const dur = Math.min(720, 260 + total * 1.1);
const t0 = performance.now();
const step = (now: number) => {
const p = Math.min(1, (now - t0) / dur);
const eased = p * p * (3 - 2 * p);
setVisible(Math.round(total * (1 - eased)));
if (p < 1) raf.current = requestAnimationFrame(step);
else {
setStrokes([]);
setVisible(Infinity);
setPhase("idle");
}
};
raf.current = requestAnimationFrame(step);
};
const reopen = () => {
clearTimers();
setStrokes([]);
setVisible(Infinity);
setPhase("idle");
};
// Flatten for rendering; when rewinding only the first `visible` segments show,
// so the newest stroke retracts first, tail to head.
let budget = visible;
const rendered: { key: string; seg: Seg }[] = [];
strokes.forEach((s, si) =>
s.forEach((seg, gi) => {
if (budget-- > 0) rendered.push({ key: `${si}-${gi}`, seg });
})
);
const signed = phase === "signed";
const settled = phase === "settling" || signed;
const color = ink === "blue" ? "#2f6bff" : "var(--b-ink)";
return (
<div className="relative flex h-[180px] w-[300px] items-center justify-center">
<motion.div
initial={false}
animate={
signed
? { width: 104, height: 34, borderRadius: 17 }
: { width: W, height: H, borderRadius: 20 }
}
transition={{ type: "spring", stiffness: 420, damping: 36, mass: 0.9 }}
className="relative overflow-hidden bg-[var(--b-surface)] shadow-[var(--b-shadow)]"
onClick={signed ? reopen : undefined}
role={signed ? "button" : undefined}
tabIndex={signed ? 0 : undefined}
aria-label={signed ? "Signed — tap to sign again" : undefined}
onKeyDown={
signed
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
reopen();
}
}
: undefined
}
style={{ cursor: signed ? "pointer" : "default" }}
>
<AnimatePresence initial={false}>
{!signed && (
<motion.div
key="pad"
className="absolute left-1/2 top-1/2 h-[180px] w-[300px] -translate-x-1/2 -translate-y-1/2"
initial={{ opacity: 0, scale: 0.94 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.36, transition: { duration: 0.26, ease: [0.4, 0, 0.2, 1] } }}
transition={{ duration: 0.22, ease: [0.2, 0, 0, 1] }}
>
<span aria-hidden className="pointer-events-none absolute bottom-[51px] left-[28px] right-[28px] h-px bg-[var(--b-fg)] opacity-[0.16]" />
<motion.span
aria-hidden
className="pointer-events-none absolute bottom-[21px] left-0 right-0 text-center text-[12px] leading-[18px] text-[var(--b-fg)]"
animate={{ opacity: hasInk && phase !== "rewinding" ? 0 : 0.38, y: hasInk && phase !== "rewinding" ? 2 : 0 }}
transition={{ duration: 0.18 }}
>
Sign here
</motion.span>
<motion.svg
ref={svgRef}
viewBox={`0 0 ${W} ${H}`}
width={W}
height={H}
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
className="absolute inset-0 touch-none select-none"
style={{ cursor: "crosshair" }}
role="img"
aria-label={hasInk ? "Signature" : "Empty signature pad"}
animate={{ opacity: settled ? 0.42 : 1 }}
transition={{ duration: 0.22 }}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
>
{rendered.map(({ key, seg }) => (
<path key={key} d={seg.d} strokeWidth={seg.w.toFixed(2)} />
))}
{live?.map((seg, i) => (
<path key={`l${i}`} d={seg.d} strokeWidth={seg.w.toFixed(2)} />
))}
</motion.svg>
<AnimatePresence>
{hasInk && !settled && phase !== "rewinding" && (
<motion.button
key="clear"
type="button"
onClick={rewind}
className="absolute right-[11px] top-[11px] h-[26px] rounded-[10px] bg-[color-mix(in_srgb,var(--b-fg)_7%,transparent)] px-[11px] text-[12px] font-medium text-[var(--b-fg)] transition-colors hover:bg-[color-mix(in_srgb,var(--b-fg)_12%,transparent)] active:scale-[0.96]"
initial={{ opacity: 0, scale: 0.9, filter: "blur(2px)" }}
animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: 0.9, filter: "blur(2px)" }}
transition={{ duration: 0.16 }}
>
Clear
</motion.button>
)}
</AnimatePresence>
</motion.div>
)}
</AnimatePresence>
<AnimatePresence>
{signed && (
<motion.span
key="pill"
className="absolute inset-0 flex items-center justify-center gap-[6px] text-[12px] font-medium text-[var(--b-fg)]"
initial={{ opacity: 0, filter: "blur(3px)" }}
animate={{ opacity: 1, filter: "blur(0px)", transition: { delay: 0.14, duration: 0.22 } }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#34c759" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<motion.path
d="M20 6 9 17l-5-5"
initial={{ pathLength: 0 }}
animate={{ pathLength: 1, transition: { delay: 0.2, duration: 0.3, ease: "easeOut" } }}
/>
</svg>
Signed
</motion.span>
)}
</AnimatePresence>
</motion.div>
<span aria-live="polite" className="sr-only">
{signed ? "Signed" : ""}
</span>
</div>
);
}
"use client";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/**
* Neutral stage the Bencho Originals sit on. The block renders at its
* natural size and is scaled as a whole (like a device preview), so
* strokes, radii and type keep their proportions at any stage size.
*/
export function BenchoStage({
children,
scale = 1.25,
className,
}: {
children: ReactNode;
scale?: number;
className?: string;
}) {
return (
<div
className={cn(
"bencho bencho-font relative flex items-center justify-center overflow-hidden rounded-2xl text-[var(--b-fg)]",
"bg-[var(--b-stage)]",
className
)}
>
<div style={{ transform: `scale(${scale})` }} className="origin-center">
{children}
</div>
</div>
);
}
/* Bencho Originals — shared surface tokens (light / dark). */
.bencho {
--b-stage: #f1f1f1;
--b-surface: #ffffff;
--b-surface-2: #f1f1f1;
--b-fg: #171717;
--b-fg-muted: rgb(23 23 23 / 0.5);
--b-ink: #171717;
--b-invert: #171717;
--b-invert-fg: #ffffff;
--b-line: rgb(0 0 0 / 0.06);
--b-shadow: 0 1px 2px rgb(0 0 0 / 0.04), 0 0 0 1px rgb(0 0 0 / 0.04);
}
.dark .bencho {
--b-stage: #171717;
--b-surface: #262626;
--b-surface-2: #333333;
--b-fg: #ffffff;
--b-fg-muted: rgb(255 255 255 / 0.55);
--b-ink: #ffffff;
--b-invert: #ffffff;
--b-invert-fg: #262626;
--b-line: rgb(255 255 255 / 0.06);
--b-shadow: none;
}
.bencho-font {
font-family: var(--font-bencho-inter), var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
font-feature-settings: "cv11", "ss01";
-webkit-font-smoothing: antialiased;
}
.bencho-tabular { font-variant-numeric: tabular-nums; }
/* Code panel: Shiki dual-theme output, with line numbers */
.bencho-code pre.shiki { background: transparent !important; margin: 0; }
.bencho-code .shiki span { color: var(--shiki-light); }
.dark .bencho-code .shiki span { color: var(--shiki-dark); }
.bencho-code .shiki code { counter-reset: line; display: block; }
.bencho-code .shiki .line::before {
counter-increment: line;
content: counter(line);
display: inline-block;
width: 2.2em;
margin-right: 1.1em;
text-align: right;
opacity: 0.32;
}