/** * WordPress dependencies */ import { useSelect, useDispatch } from '@safe-wordpress/data'; import { useMemo } from '@safe-wordpress/element'; /** * External dependencies */ import { filter, map, min } from 'lodash'; import { getCharLimitInNetwork, getMessageLength, getMinCharLimit, } from '@nelio-content/networks'; import { computeSocialMessageText } from '@nelio-content/utils'; /** * Internal dependencies */ import { store as NC_SOCIAL_EDITOR } from '../store'; export const useText = (): [ string, ( text: string ) => void ] => { const text = useSelect( ( select ) => select( NC_SOCIAL_EDITOR ).getText(), [] ); const { setText } = useDispatch( NC_SOCIAL_EDITOR ); return [ text, setText ]; }; export const useTextComputed = (): string => { const limit = useMaxChars(); const { post, text } = useSelect( ( select ) => { const editor = select( NC_SOCIAL_EDITOR ); return { post: editor.getPost(), text: editor.getText(), }; }, [] ); return useMemo( () => computeSocialMessageText( limit, post, text ), [ limit, post, text ] ); }; export const useCharCount = (): number => getMessageLength( useTextComputed() ); export const useMaxChars = (): number => { const { active, selected } = useSelect( ( select ) => { const s = select( NC_SOCIAL_EDITOR ); return { active: s.getActiveSocialNetwork(), selected: s.getSelectedSocialNetworks(), }; }, [] ); return useMemo( () => { const networks = filter( [ active, ...selected ] ); return ( min( map( networks, getCharLimitInNetwork ) ) || getMinCharLimit() ); }, [ active, selected ] ); };