Files
outdoor-tour-pwa/src/components/ChargedButton.tsx
T
2026-09-17 01:46:13 +02:00

108 lines
3.0 KiB
TypeScript

"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 (
<button
type="button"
className={styles["charged-button"] + ((disabled) ? " " + styles["button-disabled"] : "") + (className ? " " + className : "")}
style={style}
onPointerDown={onPointerDown}
onTouchStart={onPointerDown}
onPointerUp={onPointerUp}
onTouchEnd={onPointerUp}
onPointerCancel={onPointerUp}
onTouchCancel={onPointerUp}
>
<span className={styles["charged-button-label"]}>{children}</span>
<span
className={styles["charged-button-fill"]}
aria-hidden="true"
style={{
clipPath: `inset(0 ${100 - progress * 100}% 0 0)`,
}}
/>
</button>
);
}