"use client"; import { ArrowUp, Check, Mic, Trash2 } from "lucide-react"; import { type AnimationPlaybackControls, animate, isMotionValue, type MotionValue, motion, useMotionTemplate, useMotionValue, useReducedMotion, } from "motion/react"; import { type ComponentProps, useEffect, useLayoutEffect, useRef, useState } from "react"; import { IconSwap } from "@/components/agents/icon-swap"; import { Tooltip } from "@/components/motion/tooltip"; import { EASE_OUT, SPRING_PRESS } from "@/lib/ease"; import { useMessages } from "@/lib/i18n"; import { cn } from "@/lib/utils"; /** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */ export const voiceNoteMessages = { record: "Record voice note", send: "Send voice note", discard: "Discard recording", recording: "Recording", sent: "Voice note sent", }; export type VoiceNoteMessages = typeof voiceNoteMessages; export interface VoiceNoteProps extends Omit, "children" | "onSubmit"> { /** Live input level from 0 to 1 while recording, as a number or a MotionValue. Without it the waveform idles softly. */ level?: number | MotionValue; /** Called when recording starts. Start your recorder here; the component never opens the microphone. */ onRecordStart?: () => void; /** Called when the recording is thrown away, from the discard button or Escape. */ onDiscard?: () => void; /** Called with the recording's length in ms when it is sent. */ onSend?: (durationMs: number) => void; /** Stops recording and sends once it reaches this length, in seconds. Default: no limit */ maxDuration?: number; /** Blocks starting a recording. Default: false */ disabled?: boolean; /** Override any built-in string, e.g. for translation. */ labels?: Partial; } // Half the control's height: the mic's radius, and the bar's end caps. const RADIUS = 20; // Enough to fill a wide bar; the oldest fade out at the left. const BARS = 56; const SAMPLE_MS = 90; // One bar's width plus the gap after it, in px: how far the strip moves per sample. const BAR_STEP = 5; // How far each sample moves toward the new level (0–1); lower is smoother. const SMOOTHING = 0.6; // The newest bar grows to its height as it arrives. const BAR_IN = { duration: 0.14, ease: EASE_OUT } as const; type Sample = { id: number; value: number }; function emptyWave(): Sample[] { return Array.from({ length: BARS }, (_, id) => ({ id, value: 0 })); } const SENT_MS = 1200; // The bar's controls fade in as it opens and out as soon as it starts to close. const CONTENT_IN = { duration: 0.2, ease: EASE_OUT, delay: 0.08 } as const; const CONTENT_OUT = { duration: 0.1, ease: EASE_OUT } as const; // The mic's icon fades in at the bar's centre as it folds, so the bar lands as // the mic itself. const ICON_IN = { duration: 0.16, ease: EASE_OUT, delay: 0.06 } as const; // A visible bounce both ways, local because only this morph wants it. // Opening overshoots about 6% (~11px a side on a 384px bar, inside OVERSHOOT). const OPEN_BOUNCE = { type: "spring", duration: 0.55, bounce: 0.34 } as const; // Closing squeezes past the mic's circle and pops back. Gentler than opening: // the same bounce would pinch the 40px circle to a sliver. const CLOSE_BOUNCE = { type: "spring", duration: 0.5, bounce: 0.25 } as const; // Room (px) on each side for the open bounce to overshoot into: the bar rests // this far inside a frame that is wider than the control. const OVERSHOOT = 16; function clock(ms: number) { const seconds = Math.floor(ms / 1000); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; } /** * A mic button that opens into a recording bar: discard, a timer, a live * waveform and send. The bar springs out of the mic's circle to both sides at * once and folds back into the centre on send or discard, where the mic * briefly shows a check. Recording itself is the app's: start it in * `onRecordStart` and pass the input level in, so the waveform moves with the * voice. */ export function VoiceNote({ level, onRecordStart, onDiscard, onSend, maxDuration, disabled = false, labels, className, ...props }: VoiceNoteProps) { const t = useMessages("voiceNote", voiceNoteMessages, labels); const reduce = useReducedMotion() ?? false; const [recording, setRecording] = useState(false); // The bar stays mounted while it folds away, after recording has stopped. const [barShown, setBarShown] = useState(false); const [sent, setSent] = useState(false); const [elapsed, setElapsed] = useState(0); // Each sample keeps its id for life, so its bar keeps its height and moves // with the strip instead of taking on its neighbour's height every tick. const [samples, setSamples] = useState(emptyWave); const sampleId = useRef(BARS); const smoothed = useRef(0); // The strip slides left by one bar per sample, linearly, so the waveform // scrolls continuously rather than stepping. const scroll = useMotionValue(0); const startedAt = useRef(0); const rootRef = useRef(null); const micRef = useRef(null); const sendRef = useRef(null); const morph = useRef(undefined); const latest = useRef({ level, onSend, maxDuration }); useLayoutEffect(() => { latest.current = { level, onSend, maxDuration }; }); // How far (px) the bar is clipped in from each side. At half the width less // the radius it is exactly the mic's circle; at 0 it is the full bar. One // spring drives it, so the bar opens to both sides at once without its // width ever being animated. const inset = useMotionValue(10_000); const frameClip = useMotionTemplate`inset(0 ${inset}px round ${RADIUS}px)`; // The surface sits 1px inside the frame, so the same inset leaves a 1px ring // of the frame showing: the border travels with the ends as they move. const surfaceClip = useMotionTemplate`inset(0 ${inset}px round ${RADIUS - 1}px)`; // The frame is OVERSHOOT wider than the control on each side: open rests at // OVERSHOOT, and closed is the mic's circle in the middle. const closed = () => Math.max(0, (rootRef.current?.offsetWidth ?? 0) / 2 + OVERSHOOT - RADIUS); const start = () => { if (disabled || recording) return; startedAt.current = performance.now(); setElapsed(0); setSamples(emptyWave()); smoothed.current = 0; setSent(false); setRecording(true); setBarShown(true); onRecordStart?.(); morph.current?.stop(); if (reduce) { inset.set(OVERSHOOT); } else { if (!barShown) inset.set(closed()); morph.current = animate(inset, OVERSHOOT, OPEN_BOUNCE); } }; const fold = () => { morph.current?.stop(); if (reduce) { inset.set(closed()); setBarShown(false); return; } morph.current = animate(inset, closed(), { ...CLOSE_BOUNCE, // Settled on the mic's circle with the mic's icon in it: swap in the // real button, which looks the same. onComplete: () => setBarShown(false), }); }; const stop = (send: boolean) => { if (!recording) return; setRecording(false); fold(); if (send) { latest.current.onSend?.(performance.now() - startedAt.current); setSent(true); } else { onDiscard?.(); } }; // The timer reads the current stop through a ref, so it never acts on the // state of the render that started it. const stopRef = useRef(stop); useLayoutEffect(() => { stopRef.current = stop; }); // Sample the level into a rolling waveform and run the timer. useEffect(() => { if (!recording) return; const timer = window.setInterval(() => { const { level: input, maxDuration: limit } = latest.current; const raw = input === undefined ? 0.12 + Math.random() * 0.14 : isMotionValue(input) ? input.get() : input; // A little smoothing, so neighbouring bars rise and fall together // instead of spiking. smoothed.current += (Math.max(0, Math.min(1, raw)) - smoothed.current) * SMOOTHING; const id = sampleId.current++; setSamples((current) => [...current.slice(1), { id, value: smoothed.current }]); // The new bar pushes the strip left by one slot: start it one slot to // the right and slide it home over the next sample's time. if (!reduce) { scroll.set(BAR_STEP); animate(scroll, 0, { duration: SAMPLE_MS / 1000, ease: "linear" }); } const now = performance.now() - startedAt.current; setElapsed(now); // Reaching the limit sends, exactly as the send button would. if (limit !== undefined && now >= limit * 1000) stopRef.current(true); }, SAMPLE_MS); return () => window.clearInterval(timer); }, [recording, reduce, scroll]); // Focus follows the control that took the mic's place, and comes back. useEffect(() => { if (recording) sendRef.current?.focus({ preventScroll: true }); }, [recording]); // Focus goes back once the bar has landed and the mic is a button again. const wasShown = useRef(false); useEffect(() => { if (wasShown.current && !barShown) micRef.current?.focus({ preventScroll: true }); wasShown.current = barShown; }, [barShown]); useEffect(() => { if (!sent) return; const timer = window.setTimeout(() => setSent(false), SENT_MS); return () => window.clearTimeout(timer); }, [sent]); useEffect(() => () => morph.current?.stop(), []); return (
{recording ? t("recording") : sent ? t("sent") : ""} {sent ? : } {barShown ? ( { if (event.key !== "Escape") return; event.preventDefault(); stop(false); }} // Wider than the control by OVERSHOOT each side, so the open bounce // has room to swing past full width. className="absolute inset-y-0 -inset-x-4 bg-border p-px" > {/* Folding, the bar becomes the mic: its icon fades in at the centre. */} stop(false)} whileTap={reduce ? undefined : { scale: 0.95 }} transition={SPRING_PRESS} className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-rose-500 focus-visible:ring-2 focus-visible:ring-ring" > {/* Newest sample on the right. The strip scrolls left as a whole and each bar keeps its height; only the newest bar grows in. Bars scale, they never resize, and the oldest fade out at the left edge instead of being cut off. */} stop(true)} whileTap={reduce ? undefined : { scale: 0.95 }} transition={SPRING_PRESS} className="grid size-8 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground outline-none transition-colors hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" > ) : null}
); }