infoalloggi-monorepo/apps/infoalloggi/src/lib/useIsTyping.ts
2025-08-29 16:18:32 +02:00

46 lines
950 B
TypeScript

import { useEffect, useState } from "react";
export default function useIsTyping() {
const [isTyping, setIsTyping] = useState(false);
const [isKeyPressed, setIsKeyPressed] = useState(false);
const [countdown, setCountdown] = useState(5);
const startTyping = () => {
setIsKeyPressed(true);
setCountdown(5);
setIsTyping(true);
};
const stopTyping = () => {
setIsKeyPressed(false);
};
const cancelTyping = () => {
setCountdown(0);
};
useEffect(() => {
let interval: NodeJS.Timeout | undefined;
if (!isKeyPressed) {
interval = setInterval(() => {
setCountdown((c) => c - 1);
}, 1000);
} else if (isKeyPressed || countdown === 0) {
if (interval) {
clearInterval(interval);
}
}
if (countdown === 0) {
setIsTyping(false);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isKeyPressed, countdown]);
return { cancelTyping, isTyping, startTyping, stopTyping };
}