import React, { useEffect, useState } from "react"; import { BodyShort } from "../../typography"; import { debounce } from "../../utils-external"; import { cl } from "../../utils/helpers"; import { useI18n } from "../../utils/i18n/i18n.hooks"; import type { TextareaProps } from "./Textarea"; interface Props { maxLengthId: string; maxLength: number; currentLength: number; size: TextareaProps["size"]; i18n: TextareaProps["i18n"]; } const TextareaCounter = ({ maxLengthId, maxLength, currentLength, size, i18n, }: Props) => { const translate = useI18n("Textarea", { charsLeft: i18n?.counterLeft ? `{chars} ${i18n.counterLeft}` : undefined, charsTooMany: i18n?.counterTooMuch ? `{chars} ${i18n.counterTooMuch}` : undefined, }); const difference = maxLength - currentLength; const [debouncedDiff, setDebouncedDiff] = useState(difference); useEffect(() => { const debounceFunc = debounce(() => { setDebouncedDiff(difference); }, 2000); debounceFunc(); return () => { debounceFunc.clear(); }; }, [difference]); return ( <> {translate("maxLength", { maxLength })} {difference < 20 && ( {getCounterText(debouncedDiff, translate)} )} {getCounterText(difference, translate)} ); }; const getCounterText = ( difference: number, translate: ( key: "charsTooMany" | "charsLeft", replacements?: { chars: number }, ) => string, ) => difference < 0 ? translate("charsTooMany", { chars: Math.abs(difference) }) : translate("charsLeft", { chars: difference }); export default TextareaCounter;