"use client"; import { CSSProperties, ReactNode, useRef, useState } from "react"; import styles from "@/css/ChargedButton.module.css"; interface ChargedButtonProps { children?: ReactNode; style?: CSSProperties; className?: string; /** Time in milliseconds needed to fully charge by continuous hold. */ holdDuration?: number; /** Runs exactly once, when the button is fully charged at 100%. */ onAction?: () => void; disabled?: boolean; }; export default function ChargedButton({ children, style, className, holdDuration = 500, onAction, disabled = false, }: ChargedButtonProps) { const [progress, setProgress] = useState(0); const [isCharging, setIsCharging] = useState(false); const [isDischarging, setIsDischarging] = useState(false); const rafRef = useRef(0); const startTimeRef = useRef(0); const dischargingRef = useRef(false); const cancelRaf = () => { if (rafRef.current) { cancelAnimationFrame(rafRef.current); rafRef.current = 0; } }; const onPointerDown = () => { if (disabled || dischargingRef.current) return; cancelRaf(); startTimeRef.current = performance.now(); setIsCharging(true); dischargingRef.current = false; setIsDischarging(false); rafRef.current = requestAnimationFrame(updateProgress); }; const onPointerUp = () => { if (disabled || dischargingRef.current) return; cancelRaf(); setIsCharging(false); setProgress(0); }; const updateProgress = () => { const elapsed = performance.now() - startTimeRef.current; const discharging = dischargingRef.current ?? false; if (!discharging) { const fraction = Math.min(1, elapsed / holdDuration); setProgress(fraction); if (fraction >= 1) { setProgress(1); setIsCharging(false); dischargingRef.current = true; setIsDischarging(true); startTimeRef.current = performance.now(); onAction?.(); } } else { const fraction = Math.min(1, elapsed / Math.max(holdDuration * 0.05, 150)); setProgress(1.0 - fraction); if (fraction >= 1) { setProgress(0); cancelRaf(); dischargingRef.current = false; setIsDischarging(false); return; } } rafRef.current = requestAnimationFrame(updateProgress); }; return ( ); }