File size: 10,004 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import config from '@automattic/calypso-config';
import { SimplifiedSegmentedControl, StatsCard } from '@automattic/components';
import { postList } from '@wordpress/icons';
import { useTranslate } from 'i18n-calypso';
import { useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import QuerySiteStats from 'calypso/components/data/query-site-stats';
import InlineSupportLink from 'calypso/components/inline-support-link';
import StatsInfoArea from 'calypso/my-sites/stats/features/modules/shared/stats-info-area';
import { trackStatsAnalyticsEvent } from 'calypso/my-sites/stats/utils';
import { isJetpackSite } from 'calypso/state/sites/selectors';
import getEnvStatsFeatureSupportChecks from 'calypso/state/sites/selectors/get-env-stats-feature-supports';
import {
	isRequestingSiteStatsForQuery,
	getSiteStatsNormalizedData,
} from 'calypso/state/stats/lists/selectors';
import { getSelectedSiteId } from 'calypso/state/ui/selectors';
import EmptyModuleCard from '../../../components/empty-module-card/empty-module-card';
import { useShouldGateStats } from '../../../hooks/use-should-gate-stats';
import StatsModule from '../../../stats-module';
import { StatsEmptyActionAI, StatsEmptyActionSocial } from '../shared';
import StatsCardSkeleton from '../shared/stats-card-skeleton';
import useOptionLabels, {
	MAIN_STAT_TYPE,
	SUB_STAT_TYPE,
	StatType,
	StatsModulePostsProps,
	getValidQueryViewType,
} from './use-option-labels';
import type { StatsStateProps } from '../types';

type StatTypeOptionType = {
	value: StatType;
	label: string;
	mainItemLabel: string;
	analyticsId: string;
	disabled?: boolean;
};

const StatsTopPosts: React.FC< StatsModulePostsProps > = ( {
	period,
	query: queryFromProps,
	moduleStrings,
	className,
	summaryUrl,
	summary,
	listItemClassName,
	isRealTime = false,
} ) => {
	const translate = useTranslate();
	const siteId = useSelector( getSelectedSiteId ) as number;
	const { supportsArchiveStats } = useSelector( ( state: object ) =>
		getEnvStatsFeatureSupportChecks( state, siteId )
	);

	const isArchiveBreakdownEnabled: boolean =
		config.isEnabled( 'stats/archive-breakdown' ) && supportsArchiveStats;

	const isSiteJetpackNotAtomic = useSelector( ( state ) =>
		isJetpackSite( state, siteId, { treatAtomicAsJetpackSite: false } )
	);
	const supportContext = isSiteJetpackNotAtomic
		? 'stats-top-posts-and-pages-analyze-content-performance-jetpack'
		: 'stats-top-posts-and-pages-analyze-content-performance';

	const query = useMemo( () => {
		return {
			...queryFromProps,
			skip_archives: isArchiveBreakdownEnabled ? '1' : '0',
		};
	}, [ queryFromProps, isArchiveBreakdownEnabled ] );

	const mainStatType = MAIN_STAT_TYPE;
	const subStatType = SUB_STAT_TYPE;

	const [ localStatType, setLocalStatType ] = useState< StatType | null >( null );
	const onStatTypeChange = ( option: StatTypeOptionType ) => {
		trackStatsAnalyticsEvent( 'stats_posts_module_menu_clicked', {
			stat_type: option.analyticsId,
		} );

		setLocalStatType( option.value );
	};
	// Reset the localStatType when the query changes from page navigation.
	useEffect( () => {
		setLocalStatType( null );
	}, [ query ] );

	const isRequestingTopPostsData = useSelector( ( state: StatsStateProps ) =>
		isRequestingSiteStatsForQuery( state, siteId, mainStatType, query )
	);
	const postsAndPagesData = useSelector( ( state ) =>
		getSiteStatsNormalizedData( state, siteId, mainStatType, query )
	) as Array< { id: number; label: string } >;

	const isRequestingArchivesData = useSelector( ( state: StatsStateProps ) =>
		isRequestingSiteStatsForQuery( state, siteId, subStatType, query )
	);
	// Get the archives data to check if we should disable the archives option.
	const archivesData = useSelector( ( state ) =>
		getSiteStatsNormalizedData( state, siteId, subStatType, query )
	) as Array< { id: number; label: string } >;

	const isRequestingData = isArchiveBreakdownEnabled
		? isRequestingTopPostsData || isRequestingArchivesData
		: isRequestingTopPostsData;

	const optionLabels = useOptionLabels();
	const options: StatTypeOptionType[] = useMemo(
		() =>
			Object.entries( optionLabels ).map( ( [ key, item ] ) => {
				return {
					value: key as StatType,
					label: item.tabLabel,
					mainItemLabel: item.mainItemLabel,
					analyticsId: item.analyticsId,
					// TODO: This is a temporary solution to disable the archives option when the archives data is not available.
					disabled:
						isArchiveBreakdownEnabled &&
						( ( key === subStatType && ! isRequestingArchivesData && ! archivesData.length ) ||
							( key === mainStatType &&
								! isRequestingTopPostsData &&
								! postsAndPagesData.length ) ),
				};
			} ),
		[
			optionLabels,
			isArchiveBreakdownEnabled,
			subStatType,
			isRequestingArchivesData,
			archivesData.length,
			mainStatType,
			isRequestingTopPostsData,
			postsAndPagesData.length,
		]
	);

	const availableStatTypes = options.filter( ( option ) => ! option.disabled );
	const defaultStatType =
		availableStatTypes.length === 1 ? availableStatTypes[ 0 ].value : mainStatType;
	const statType =
		localStatType ||
		getValidQueryViewType( query.viewType || defaultStatType, supportsArchiveStats );

	const data = statType === subStatType ? archivesData : postsAndPagesData;

	// Use StatsModule to display paywall upsell.
	const shouldGateStatsModule = useShouldGateStats( mainStatType );

	const hasData = !! data?.length;
	// TODO: Is there a way to show the Skeleton loader for real-time data?
	// We don't want it to show every time a rquest is being run for real-time data so it's disabled for now.
	const presentLoadingUI = isRealTime
		? isRequestingData && ! hasData && false
		: isRequestingData && ! shouldGateStatsModule;
	const presentModuleUI = isRealTime
		? hasData && ! presentLoadingUI
		: ( ! isRequestingData && hasData ) || shouldGateStatsModule;
	const presentEmptyUI = isRealTime
		? ! hasData && ! presentLoadingUI
		: ! isRequestingData && ! hasData && ! shouldGateStatsModule;

	// Query both statTypes for the Traffic page module card to avoid loading when switching between controls.
	// Only query one statType at a time to avoid loading plenty of data for the summary mode.
	const shouldQueryMainStatType = ! summary || statType === mainStatType;
	const shouldQuerySubStatType = ! summary || statType === subStatType;

	return (
		<>
			{ ! shouldGateStatsModule && siteId && shouldQueryMainStatType && (
				<QuerySiteStats statType={ mainStatType } siteId={ siteId } query={ query } />
			) }

			{ ! shouldGateStatsModule &&
				siteId &&
				isArchiveBreakdownEnabled &&
				shouldQuerySubStatType && (
					<QuerySiteStats statType={ subStatType } siteId={ siteId } query={ query } />
				) }

			{ presentLoadingUI && (
				<StatsCardSkeleton
					isLoading={ isRequestingData }
					className={ className }
					title={ moduleStrings.title }
					type={ 1 }
				/>
			) }
			{ presentModuleUI && (
				// show data or an overlay
				<StatsModule
					path="posts"
					titleNodes={
						<StatsInfoArea>
							{ isArchiveBreakdownEnabled
								? translate(
										'Most viewed {{link}}posts, pages and archive{{/link}}. Learn about what content resonates the most.',
										{
											comment: '{{link}} links to support documentation.',
											components: {
												link: (
													<InlineSupportLink supportContext={ supportContext } showIcon={ false } />
												),
											},
											context:
												'Stats: Link in a popover for the Posts & Pages when the module has data',
										}
								  )
								: translate(
										'{{link}}Posts and pages{{/link}} sorted by most visited. Learn about what content resonates the most.',
										{
											comment: '{{link}} links to support documentation.',
											components: {
												link: (
													<InlineSupportLink supportContext={ supportContext } showIcon={ false } />
												),
											},
											context:
												'Stats: Link in a popover for the Posts & Pages when the module has data',
										}
								  ) }
						</StatsInfoArea>
					}
					moduleStrings={ moduleStrings }
					period={ period }
					query={ query }
					statType={ statType }
					showSummaryLink={ !! summary }
					summaryLinkModifier={ ( link: string ) => `${ link }&viewType=${ statType }` }
					className={ className }
					summary={ summary }
					listItemClassName={ listItemClassName }
					skipQuery
					isRealTime={ isRealTime }
					toggleControl={
						isArchiveBreakdownEnabled &&
						! summary && (
							<SimplifiedSegmentedControl
								options={ options }
								initialSelected={ statType }
								onSelect={ onStatTypeChange }
							/>
						)
					}
					mainItemLabel={
						isArchiveBreakdownEnabled &&
						options.find( ( option ) => option.value === statType )?.mainItemLabel
					}
				/>
			) }
			{ presentEmptyUI && (
				// show empty state
				<StatsCard
					className={ className }
					title={ moduleStrings.title }
					isEmpty
					emptyMessage={
						<EmptyModuleCard
							icon={ postList }
							description={ translate(
								'Your top {{link}}posts and pages{{/link}} will display here to learn what content resonates the most. Start creating and sharing!',
								{
									comment: '{{link}} links to support documentation.',
									components: {
										link: (
											<InlineSupportLink supportContext={ supportContext } showIcon={ false } />
										),
									},
									context: 'Stats: Info box label when the Posts & Pages module is empty',
								}
							) }
							cards={
								<>
									<StatsEmptyActionAI from="module_top_posts" />
									<StatsEmptyActionSocial from="module_top_posts" />
								</>
							}
						/>
					}
					footerAction={
						summaryUrl
							? {
									url: summaryUrl,
									label: translate( 'View more' ),
							  }
							: undefined
					}
				/>
			) }
		</>
	);
};

export default StatsTopPosts;