(editor: Editor | null, setTextLength: (length: number) => void)
| 5 | import { useTranslation } from 'react-i18next' |
| 6 | |
| 7 | function useTextCounter(editor: Editor | null, setTextLength: (length: number) => void) { |
| 8 | const { t } = useTranslation() |
| 9 | const timeoutRef = useRef<NodeJS.Timeout | null>(null) |
| 10 | const hasShownToastRef = useRef(false) |
| 11 | |
| 12 | const handleTextChange = useCallback( |
| 13 | (currentEditor: Editor) => { |
| 14 | const currentText = currentEditor.getText() |
| 15 | const textLength = currentText.length |
| 16 | |
| 17 | if (textLength > MAX_CHARACTERS) { |
| 18 | const truncatedText = currentText.substring(0, MAX_CHARACTERS) |
| 19 | currentEditor.chain().focus().setContent(truncatedText).run() |
| 20 | if (!hasShownToastRef.current) { |
| 21 | hasShownToastRef.current = true |
| 22 | toaster.create({ |
| 23 | title: t('components.editorTextCounter.title'), |
| 24 | description: t('components.editorTextCounter.description'), |
| 25 | type: 'info', |
| 26 | }) |
| 27 | |
| 28 | timeoutRef.current = setTimeout(() => { |
| 29 | hasShownToastRef.current = false |
| 30 | }, 3000) |
| 31 | } |
| 32 | |
| 33 | setTextLength(MAX_CHARACTERS) |
| 34 | } else { |
| 35 | hasShownToastRef.current = false |
| 36 | setTextLength(textLength) |
| 37 | } |
| 38 | }, |
| 39 | [setTextLength, t], |
| 40 | ) |
| 41 | |
| 42 | useEffect(() => { |
| 43 | if (!editor) { |
| 44 | setTextLength(0) |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | const handleUpdate = ({ editor: currentEditor }: { editor: Editor }) => { |
| 49 | if (currentEditor && !currentEditor.isDestroyed) { |
| 50 | handleTextChange(currentEditor) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | editor.on('update', handleUpdate) |
| 55 | |
| 56 | handleTextChange(editor) |
| 57 | |
| 58 | return () => { |
| 59 | if (timeoutRef.current) { |
| 60 | clearTimeout(timeoutRef.current) |
| 61 | timeoutRef.current = null |
| 62 | } |
| 63 | |
| 64 | if (editor && !editor.isDestroyed) { |
no test coverage detected