/** * WordPress dependencies */ import { Dashicon, Tooltip } from '@safe-wordpress/components'; import { useSelect } from '@safe-wordpress/data'; import { _x } from '@safe-wordpress/i18n'; /** * External dependencies */ import { map, filter, toPairs } from 'lodash'; import { store as NC_DATA, usePost } from '@nelio-content/data'; import { getSupportedNetworks } from '@nelio-content/networks'; import type { Maybe, Post, PostId, SocialNetworkName, } from '@nelio-content/types'; /** * Internal dependencies */ import './style.scss'; import { SocialNetworkIcon } from '../social-network-icon'; export type PostEngagementAnalyticsProps = { readonly className?: string; readonly postId: PostId; readonly statistics?: Post[ 'statistics' ]; }; export const PostEngagementAnalytics = ( { className = '', postId, statistics, }: PostEngagementAnalyticsProps ): JSX.Element => { const isSubscribed = useIsSubscribed(); const engagement = useEngagement( postId, statistics ); const metrics = useMetrics( postId, statistics ); const comments = useComments( postId, statistics ); return (
{ _x( 'Engagement', 'text', 'nelio-content' ) }
{ engagement }
{ map( metrics, ( [ network, metric ] ) => (
{ 'twitter' === network && ! isSubscribed ? _x( 'N/A', 'text', 'nelio-content' ) : metric }
) ) } { Number.parseFloat( `${ comments }` ) > 0 && (
{ comments }
) }
); }; // ===== // HOOKS // ===== const useIsSubscribed = () => useSelect( ( select ) => select( NC_DATA ).isSubscribed(), [] ); const useEngagement = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => { const post = usePost( postId ); return ( statistics?.engagement.total ?? post?.statistics.engagement.total ?? '–' ); }; const useComments = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => { const post = usePost( postId ); return ( statistics?.engagement.comments || post?.statistics.engagement.comments || 0 ); }; const useMetrics = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => { const post = usePost( postId ); const networks = getSupportedNetworks(); const metrics = statistics?.engagement || post?.statistics.engagement || {}; const pairs = filter( toPairs( metrics ), < V, >( pair: [ 'total' | 'comments' | SocialNetworkName, Maybe< V > ] ): pair is [ SocialNetworkName, V ] => pair[ 0 ] !== 'total' && pair[ 0 ] !== 'comments' && pair[ 1 ] !== undefined && pair[ 1 ] !== null && parseFloat( pair[ 1 ] as string ) > 0 ); return filter( pairs, ( [ network ] ) => networks.includes( network ) ); };