"use client";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useRef, useState } from "react";
import { Mic, Pause, Play, X } from "lucide-react";
import { cn } from "@/lib/utils";
/**
* Voice Note — an original take inspired by bencho.dev's "Voice note".
* Hold to record: the pill opens into a scrolling waveform with a timer.
* Slide left to throw it away; let go and it becomes a clip you can play
* and scrub. The waveform is synthesised, so nothing asks for a microphone.
*/
type Phase = "idle" | "recording" | "clip";
const RED = "#ef4452";
const fmt = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
/** A voice-like level: bursts (syllables) riding a slow phrase envelope. */
function makeVoice(seed: number) {
let t = seed;
let syl = 0;
return () => {
t += 1;
if (syl <= 0 && Math.random() < 0.35) syl = 2 + Math.floor(Math.random() * 5);
const phrase = 0.65 + 0.35 * Math.sin(t / 7 + seed);
const v = syl-- > 0 ? (0.4 + Math.random() * 0.6) * phrase : 0.1 + Math.random() * 0.18;
return Math.max(0, Math.min(1, v));
};
}
export function VoiceNote({
sensitivity = 60,
bounce = 40,
bars = 28,
corner = 28,
outlined = false,
onSend,
}: {
/** 0–100: how tall the bars get for the same level. */
sensitivity?: number;
/** 0–100: overshoot when the pill opens and closes. */
bounce?: number;
/** Number of bars in the waveform (12–40). */
bars?: number;
/** Corner radius in px. 28 is a full pill. */
corner?: number;
outlined?: boolean;
/** Called with the clip's length in seconds when recording ends. */
onSend?: (seconds: number) => void;
}) {
const [phase, setPhase] = useState<Phase>("idle");
const [live, setLive] = useState<number[]>([]);
const [clip, setClip] = useState<number[]>([]);
const [elapsed, setElapsed] = useState(0);
const [dur, setDur] = useState(0);
const [pull, setPull] = useState(0);
const [prog, setProg] = useState(0);
const [playing, setPlaying] = useState(false);
const start = useRef(0);
const x0 = useRef(0);
const samples = useRef<number[]>([]);
const voice = useRef(makeVoice(1));
const n = Math.max(12, Math.min(40, Math.round(bars)));
const gain = 0.4 + (sensitivity / 100) * 1.2;
const spring = { type: "spring" as const, stiffness: 420, damping: 38 - bounce * 0.26 };
// recording loop: one sample every 70ms, the newest on the right
useEffect(() => {
if (phase !== "recording") return;
const id = window.setInterval(() => {
const v = voice.current();
samples.current.push(v);
setLive(samples.current.slice(-n));
setElapsed((performance.now() - start.current) / 1000);
}, 55);
return () => window.clearInterval(id);
}, [phase, n]);
// playback: progress is one number, every bar lights itself from it
useEffect(() => {
if (!playing) return;
let raf = 0;
const t0 = performance.now() - prog * dur * 1000;
const tick = (now: number) => {
const p = Math.min(1, (now - t0) / (dur * 1000));
setProg(p);
if (p >= 1) {
setPlaying(false);
window.setTimeout(() => setProg(0), 400);
return;
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [playing, dur]);
// while a pointer holds the record button, follow it anywhere on the page
const fin = useRef(() => {});
const can = useRef(() => {});
const pillRef = useRef<HTMLDivElement>(null);
const byPointer = useRef(false);
useEffect(() => {
if (phase !== "recording" || !byPointer.current) return;
const el = pillRef.current;
const scale = el && el.offsetWidth ? el.getBoundingClientRect().width / el.offsetWidth || 1 : 1;
const move = (e: PointerEvent) => {
const p = Math.max(0, Math.min(1, (x0.current - e.clientX) / scale / 90));
setPull(p);
if (p >= 1) can.current();
};
const up = () => fin.current();
const off = () => can.current();
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
window.addEventListener("pointercancel", off);
return () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("pointercancel", off);
};
}, [phase]);
const begin = (clientX: number) => {
samples.current = Array.from({ length: n }, () => 0);
voice.current = makeVoice(Math.random() * 10);
setLive(samples.current.slice());
start.current = performance.now();
x0.current = clientX;
setElapsed(0);
setPull(0);
setPhase("recording");
};
const cancel = () => {
setPhase("idle");
setPull(0);
};
const finish = () => {
const secs = (performance.now() - start.current) / 1000;
if (secs < 0.4) return cancel();
// squeeze the whole take into n bars (peak of each bucket)
const all = samples.current.slice(n);
const out = Array.from({ length: n }, (_, i) => {
const a = Math.floor((i / n) * all.length);
const b = Math.max(a + 1, Math.floor(((i + 1) / n) * all.length));
return Math.max(0.08, ...all.slice(a, b));
});
setClip(out);
setDur(Math.max(1, Math.round(secs)));
setProg(0);
setPull(0);
setPhase("clip");
onSend?.(secs);
};
fin.current = finish;
can.current = cancel;
const h = (v: number) => Math.max(4, Math.min(28, 3 + v * gain * 25));
const recW = 232 + n * 2.4;
return (
<div className="relative flex h-[120px] w-[340px] items-center justify-center">
<motion.div
ref={pillRef}
initial={false}
animate={{ width: phase === "idle" ? 216 : recW }}
transition={spring}
className={cn("relative flex h-[56px] items-center overflow-hidden bg-[var(--b-surface)] text-[var(--b-fg)] shadow-[var(--b-shadow)]", outlined && "ring-1 ring-[var(--b-line)]")}
style={{
borderRadius: corner,
opacity: phase === "recording" ? 1 - pull * 0.9 : 1,
}}
>
<AnimatePresence mode="popLayout" initial={false}>
{phase === "idle" && (
<motion.button
key="idle"
type="button"
initial={{ opacity: 0, filter: "blur(4px)" }}
animate={{ opacity: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: "blur(4px)" }}
transition={{ duration: 0.18 }}
onPointerDown={(e) => {
e.preventDefault();
byPointer.current = true;
begin(e.clientX);
}}
onKeyDown={(e) => {
if ((e.key === " " || e.key === "Enter") && !e.repeat) {
e.preventDefault();
byPointer.current = false;
begin(0);
}
}}
aria-label="Hold to record a voice note"
className="flex h-full w-full items-center justify-center gap-[10px] text-[16px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--b-fg)]/30"
style={{ borderRadius: corner, touchAction: "none" }}
>
<Mic className="size-[18px]" strokeWidth={2.2} />
Hold to record
</motion.button>
)}
{phase === "recording" && (
<motion.div
key="rec"
tabIndex={-1}
ref={(n) => n?.focus()}
initial={{ opacity: 0, filter: "blur(4px)" }}
animate={{ opacity: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: "blur(4px)" }}
transition={{ duration: 0.18 }}
className="flex h-full w-full items-center gap-[12px] pl-[22px] pr-[18px] outline-none"
onKeyUp={(e) => (e.key === " " || e.key === "Enter") && finish()}
onKeyDown={(e) => {
if (e.key === "Escape") cancel();
if (e.key === " " || e.key === "Enter") e.preventDefault();
}}
role="status"
aria-label={`Recording ${fmt(elapsed)}. Release to finish, slide left or press Escape to cancel.`}
>
<span className="flex items-center gap-[12px]" style={{ opacity: Math.max(0, 1 - pull * 1.6) }}>
<motion.span
className="size-[8px] shrink-0 rounded-full"
style={{ background: RED }}
animate={{ opacity: [1, 0.35, 1] }}
transition={{ duration: 1.1, repeat: Infinity }}
/>
<span className="bencho-tabular w-[34px] text-[16px] font-medium">{fmt(elapsed)}</span>
</span>
<div className="flex h-[28px] flex-1 items-center justify-end gap-[3px]">
{live.map((v, i) => (
<span
key={i}
className="w-[3px] shrink-0 rounded-full bg-[var(--b-fg)] transition-[height] duration-75"
style={{ height: h(v) }}
/>
))}
</div>
</motion.div>
)}
{phase === "clip" && (
<motion.div
key="clip"
initial={{ opacity: 0, filter: "blur(4px)" }}
animate={{ opacity: 1, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: "blur(4px)" }}
transition={{ duration: 0.2 }}
className="flex h-full w-full items-center gap-[12px] pl-[6px] pr-[12px]"
>
<motion.button
type="button"
whileTap={{ scale: 0.92 }}
onClick={() => setPlaying((p) => !p)}
aria-label={playing ? "Pause" : "Play voice note"}
className="flex size-[44px] shrink-0 items-center justify-center rounded-full bg-[var(--b-invert)] text-[var(--b-invert-fg)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/40"
>
{playing ? <Pause className="size-[16px] fill-current" /> : <Play className="ml-[2px] size-[16px] fill-current" />}
</motion.button>
<Scrub
values={clip}
prog={prog}
h={h}
dur={dur}
onSeek={(p) => setProg(p)}
/>
<span className="bencho-tabular w-[34px] text-[15px] text-[var(--b-fg-muted)]">{fmt(playing || prog > 0 ? prog * dur : dur)}</span>
<button
type="button"
onClick={() => {
setPlaying(false);
setPhase("idle");
}}
aria-label="Delete voice note"
className="flex size-[28px] shrink-0 items-center justify-center rounded-full text-[var(--b-fg-muted)] outline-none hover:text-[var(--b-fg)] focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/30"
>
<X className="size-[16px]" />
</button>
</motion.div>
)}
</AnimatePresence>
</motion.div>
<AnimatePresence>
{phase === "recording" && (
<motion.span
initial={{ opacity: 0, y: -4 }}
animate={{ opacity: Math.max(0, 1 - pull * 1.4), y: 0 }}
exit={{ opacity: 0 }}
className="pointer-events-none absolute left-1/2 top-[96px] -translate-x-1/2 whitespace-nowrap text-[13px] text-[var(--b-fg-muted)]"
>
‹ Slide to cancel
</motion.span>
)}
</AnimatePresence>
</div>
);
}
function Scrub({ values, prog, h, dur, onSeek }: { values: number[]; prog: number; h: (v: number) => number; dur: number; onSeek: (p: number) => void }) {
const ref = useRef<HTMLDivElement>(null);
const seek = (clientX: number) => {
const r = ref.current!.getBoundingClientRect();
onSeek(Math.max(0, Math.min(1, (clientX - r.left) / r.width)));
};
return (
<div
ref={ref}
role="slider"
tabIndex={0}
aria-label="Seek"
aria-valuemin={0}
aria-valuemax={dur}
aria-valuenow={Math.round(prog * dur)}
aria-valuetext={`${fmt(prog * dur)} of ${fmt(dur)}`}
onPointerDown={(e) => {
e.currentTarget.setPointerCapture(e.pointerId);
seek(e.clientX);
}}
onPointerMove={(e) => e.buttons && seek(e.clientX)}
onKeyDown={(e) => {
const d = e.key === "ArrowRight" ? 0.1 : e.key === "ArrowLeft" ? -0.1 : 0;
if (d) {
e.preventDefault();
onSeek(Math.max(0, Math.min(1, prog + d)));
}
if (e.key === "Home") onSeek(0);
if (e.key === "End") onSeek(1);
}}
className="flex h-[32px] flex-1 cursor-ew-resize items-center justify-between rounded-md outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/30"
style={{ touchAction: "none" }}
>
{values.map((v, i) => (
<span
key={i}
className="w-[3px] shrink-0 rounded-full bg-[var(--b-fg)]"
style={{ height: h(v), opacity: prog * values.length > i ? 1 : 0.38 }}
/>
))}
</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;
}