/** * WordPress dependencies */ import { useSelect, useDispatch } from '@safe-wordpress/data'; import { useEffect, useState } from '@safe-wordpress/element'; import { _x } from '@safe-wordpress/i18n'; /** * External dependencies */ import clsx from 'clsx'; import moment from 'moment'; import { AuthorIcon, DeleteButton } from '@nelio-content/components'; import { useAuthorName, store as NC_DATA } from '@nelio-content/data'; import { dateI18n, getSettings } from '@nelio-content/date'; import type { Uuid } from '@nelio-content/types'; /** * Internal dependencies */ import './style.scss'; import { store as NC_EDIT_POST } from '../../../store'; export type CommentProps = { readonly commentId: Uuid; }; export const Comment = ( { commentId }: CommentProps ): JSX.Element => { const comment = useComment( commentId ); const authorName = useAuthorName( comment?.authorId ); const isBeingDeleted = useSelect( ( select ) => select( NC_EDIT_POST ).isDeletingEditorialComment( commentId ), [ commentId ] ); const isBeingSynched = useSelect( ( select ) => select( NC_EDIT_POST ).isSynchingEditorialComment( commentId ), [ commentId ] ); const isCurrentUsers = useIsCurrentUsers( commentId ); const canBeDeleted = useCanBeDeleted( commentId ); const { deleteEditorialComment } = useDispatch( NC_EDIT_POST ); return (
{ ! isCurrentUsers && (
) }
{ comment?.comment || '' }
{ isBeingSynched && _x( 'Sending…', 'text', 'nelio-content' ) } { ! isBeingSynched && ! isCurrentUsers && (
{ authorName }
) } { ! isBeingSynched && (
{ dateI18n( getSettings().formats.datetime, comment?.date ) }
) }
{ ( isBeingDeleted || canBeDeleted ) && ! isBeingSynched && (
void deleteEditorialComment( commentId ) } />
) }
); }; // ===== // HOOKS // ===== const useComment = ( commentId: Uuid ) => useSelect( ( select ) => select( NC_DATA ).getComment( commentId ), [ commentId ] ); const useIsCurrentUsers = ( commentId: Uuid ) => { const comment = useComment( commentId ); return useSelect( ( select ) => select( NC_DATA ).getCurrentUserId() === comment?.authorId, [ comment?.authorId ] ); }; const useCanBeDeleted = ( commentId: Uuid ) => { const date = useComment( commentId )?.date; const isCurrentUsers = useIsCurrentUsers( commentId ); const diff = date ? moment().diff( date, 'minutes' ) : 0; const isFresh = Math.abs( diff ) < 5; const [ tick, setTick ] = useState( 0 ); useEffect( () => { if ( ! isFresh ) { return; } setTimeout( () => setTick( tick + 1 ), 30000 ); }, [ tick, isFresh ] ); return isCurrentUsers && isFresh; };