/* eslint-disable camelcase */ /* eslint-disable @typescript-eslint/no-explicit-any */ import React, { FC, useState, useRef, useMemo, } from 'react'; import { Editor } from '@tinymce/tinymce-react'; import AUTinyMCEBuilder from '../lib/tinymce'; import { replace } from '../lib/helpers'; type Translation = IGenericTranslation['generics']['forms']; type CounterType = 'recommended' | 'allowed'; type Props = { lang: string; id: string; initialValue: string; textareaName: string; showCounter?: boolean; counterType?: CounterType; maxChars?: number; translations: Translation; onEditorChange: (value: string) => void; disabled?: boolean; }; const onKeyUp = ( editor: any, parent: HTMLDivElement, maxChars: number, counterType: string, setOverflow: React.Dispatch>, ): void => { const container = editor.getContainer(); const numChars = editor.plugins.wordcount.body.getCharacterCount(); let isActive = false; if (numChars >= maxChars) { isActive = true; parent.setAttribute(`data-${counterType}-length`, maxChars.toString()); } if (isActive) { container.classList.add('info-active'); } else { container.classList.remove('info-active'); parent.removeAttribute(`data-${counterType}-length`); } const overflow = numChars - maxChars; if (overflow > 0) { parent.classList.add('form__field__character-count--overflow'); } else { parent.classList.remove('form__field__character-count--overflow'); } setOverflow(overflow); }; const AUEditorComponent: FC = ({ lang, id, initialValue, textareaName, showCounter = false, counterType = 'recommended', maxChars = 0, translations, onEditorChange, disabled = false, }) => { const [overflow, setOverflow] = useState(0); const parentRef = useRef(null); // Capture initialValue on first render only. // Passing a changing initialValue to TinyMCE's // causes it to call setContent() on every update, // which resets the cursor to position 0. const stableInitialValue = useRef(initialValue); const tiny = useMemo(() => new AUTinyMCEBuilder( lang, showCounter as boolean, (editor: any) => onKeyUp( editor, parentRef.current as HTMLDivElement, maxChars as number, counterType as string, setOverflow, ), ), [lang, showCounter, maxChars, counterType]); const tinyConfig = useMemo(() => tiny.tinyGeneralConfig(), [tiny]); const { character_count } = translations; return (
{ (typeof showCounter !== 'undefined' && typeof counterType !== 'undefined' && typeof maxChars !== 'undefined') && (
{`${replace(character_count.overflow.message[counterType], ['maxchars'], [maxChars.toString()])}`} {' '} {`${replace(character_count.overflow.count[counterType][overflow === 1 ? 'one' : 'other'], ['overflow'], [overflow.toString()])}`}
) }
); }; AUEditorComponent.displayName = 'AUEditorComponent'; export default AUEditorComponent;