/** * WordPress dependencies */ import { Dashicon, Tooltip } from '@safe-wordpress/components'; import { useSelect } from '@safe-wordpress/data'; import { _x } from '@safe-wordpress/i18n'; /** * External dependencies */ import { 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 PostPageviewsAnalyticsProps = { readonly className?: string; readonly postId: PostId; readonly statistics?: Post[ 'statistics' ]; }; export const PostPageviewsAnalytics = ( { className = '', postId, statistics, }: PostPageviewsAnalyticsProps ): JSX.Element | null => { const isVisible = useIsVisible(); const pageviews = usePageViews( postId, statistics ); const metrics = useMetrics( postId, statistics ); if ( ! isVisible ) { return null; } return (
{ _x( 'Pageviews', 'text', 'nelio-content' ) }
{ pageviews }
{ metrics.map( ( [ network, metric ] ) => (
{ metric }
) ) }
); }; // ===== // HOOKS // ===== const useIsVisible = () => useSelect( ( select ) => select( NC_DATA ).isGAConnected(), [] ); const usePageViews = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => useSelect( ( select ) => statistics?.pageviews.total ?? select( NC_DATA ).getPost( postId )?.statistics.pageviews.total ?? '–', [ postId, statistics ] ); const useMetrics = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => { const post = usePost( postId ); const networks = getSupportedNetworks(); const metrics = statistics?.pageviews || post?.statistics.pageviews || {}; const pairs = filter( toPairs( metrics ), < V, >( pair: [ 'total' | SocialNetworkName, Maybe< V > ] ): pair is [ SocialNetworkName, V ] => pair[ 0 ] !== 'total' && pair[ 1 ] !== undefined && pair[ 1 ] !== null // && // parseFloat( pair[ 1 ] as string ) > 0 ); return filter( pairs, ( [ network ] ) => networks.includes( network ) ); };