File size: 10,899 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import config from '@automattic/calypso-config';
import clsx from 'clsx';
import { localize } from 'i18n-calypso';
import { includes, isEqual } from 'lodash';
import moment from 'moment';
import PropTypes from 'prop-types';
import { Component } from 'react';
import { connect } from 'react-redux';
import QuerySiteStats from 'calypso/components/data/query-site-stats';
import { getSiteSlug } from 'calypso/state/sites/selectors';
import {
	isRequestingSiteStatsForQuery,
	getSiteStatsNormalizedData,
} from 'calypso/state/stats/lists/selectors';
import { getSelectedSiteId } from 'calypso/state/ui/selectors';
import { STATS_FEATURE_DOWNLOAD_CSV } from '../constants';
import Geochart from '../geochart';
import { shouldGateStats } from '../hooks/use-should-gate-stats';
import StatsCardUpsell from '../stats-card-upsell';
import DatePicker from '../stats-date-picker';
import ErrorPanel from '../stats-error';
import StatsListCard from '../stats-list/stats-list-card';
import StatsModulePlaceholder from './placeholder';

import './style.scss';
import '../stats-list/style.scss'; // TODO: limit included CSS and remove this import.

class StatsModule extends Component {
	static propTypes = {
		summary: PropTypes.bool,
		moduleStrings: PropTypes.object,
		period: PropTypes.object,
		path: PropTypes.string,
		siteSlug: PropTypes.string,
		siteId: PropTypes.number,
		data: PropTypes.array,
		query: PropTypes.object,
		statType: PropTypes.string,
		showSummaryLink: PropTypes.bool,
		summaryLinkModifier: PropTypes.func,
		translate: PropTypes.func,
		metricLabel: PropTypes.string,
		mainItemLabel: PropTypes.string,
		additionalColumns: PropTypes.object,
		toggleControl: PropTypes.node,
		listItemClassName: PropTypes.string,
		gateStats: PropTypes.bool,
		gateDownloads: PropTypes.bool,
		hasNoBackground: PropTypes.bool,
		skipQuery: PropTypes.bool,
		valueField: PropTypes.string,
		formatValue: PropTypes.func,
		minutesLimit: PropTypes.number,
		isRealTime: PropTypes.bool,
	};

	static defaultProps = {
		showSummaryLink: false,
		query: {},
		valueField: 'value',
		minutesLimit: 30,
		isRealTime: false,
		summaryLinkModifier: ( link ) => link,
	};

	state = {
		loaded: false,
		diffData: [],
		dataHistory: [],
		lastUpdated: null,
	};

	componentDidUpdate( prevProps ) {
		const { data, isRealTime, query, requesting, statType } = this.props;
		if ( ! requesting && prevProps.requesting ) {
			// eslint-disable-next-line react/no-did-update-set-state
			this.setState( { loaded: true } );
		}

		if ( ! isEqual( query, prevProps.query ) ) {
			// eslint-disable-next-line react/no-did-update-set-state
			this.setState( { loaded: false } );
		}

		if ( ! isRealTime ) {
			return;
		}

		// Limit data processing to avoid spurious updates.
		const { dataHistory, lastUpdated } = this.state;
		const UPDATE_THRESHOLD_IN_SECONDS = 15;
		const now = moment();

		if ( ! lastUpdated || now.diff( lastUpdated, 'seconds' ) >= UPDATE_THRESHOLD_IN_SECONDS ) {
			const updatedHistory = this.updateHistory( dataHistory, data );
			const diffData = this.calculateDiff( updatedHistory, statType );
			// eslint-disable-next-line react/no-did-update-set-state
			this.setState( {
				diffData,
				dataHistory: updatedHistory,
				lastUpdated: now,
			} );
		}
	}

	updateHistory( history, data ) {
		// Timestamp the new data snapshot.
		const now = moment();
		const newSnapshot = {
			timestamp: now,
			data: data,
		};

		// Filter out snapshots older than minutesLimit prop.
		// This determines the baseline for the diff calculation.
		const { minutesLimit } = this.props;
		const filteredHistory = [ ...history, newSnapshot ].filter(
			( snapshot ) => now.diff( snapshot.timestamp, 'minutes' ) <= minutesLimit
		);

		return this.compactHistory( filteredHistory );
	}

	compactHistory( history ) {
		const MAX_HISTORY_LENGTH = 35;

		if ( history.length > MAX_HISTORY_LENGTH ) {
			// Keep every other entry to keep memory usage low.
			return history.filter( ( _, index ) => index % 2 === 0 );
		}

		return history;
	}

	calculateDiff( history, statType ) {
		const key = this.getKeyForStatType( statType );
		const baselineMap = this.createBaselineLookupMap( history, key );
		const lastSnapshot = history[ history.length - 1 ].data;

		return lastSnapshot.map( ( item ) => {
			const baselineItem = baselineMap.get( item[ key ] ) || { value: 0 };
			return {
				...item,
				diffValue: item.value - baselineItem.value,
			};
		} );
	}

	createBaselineLookupMap( history, key = 'id' ) {
		const lookup = new Map();

		history.forEach( ( snapshot ) => {
			snapshot.data.forEach( ( item ) => {
				if ( ! lookup.has( item[ key ] ) ) {
					lookup.set( item[ key ], item );
				}
			} );
		} );

		return lookup;
	}

	getKeyForStatType( statType ) {
		// Provided data is not consistent across modules.
		// Ideally we'd have an interface with some common properties.
		// For now we can't assume an 'id' for all stats types.
		// Use this function to find the best available key for unique identification.
		const keys = {
			statsTopPosts: 'id',
			statsReferrers: 'label',
			statsCountryViews: 'countryCode',
		};
		return keys[ statType ] || 'id';
	}

	getModuleLabel() {
		if ( ! this.props.summary ) {
			return this.props.moduleStrings.title;
		}
		const { period, startOf } = this.props.period;
		const { path, query } = this.props;

		return <DatePicker period={ period } date={ startOf } path={ path } query={ query } summary />;
	}

	getSummaryLink() {
		const { summary, period, path, siteSlug, query, summaryLinkModifier } = this.props;
		if ( summary ) {
			return;
		}

		const paramsValid = period?.period && path && siteSlug;
		if ( ! paramsValid ) {
			return undefined;
		}

		let url = `/stats/${ period.period }/${ path }/${ siteSlug }`;

		if ( query?.start_date ) {
			url += `?startDate=${ query.start_date }&endDate=${ query.date }`;
		} else {
			url += `?startDate=${ period.endOf.format( 'YYYY-MM-DD' ) }`;
		}

		return summaryLinkModifier( url );
	}

	isAllTimeList() {
		const { summary, statType } = this.props;
		const summarizedTypes = [
			'statsSearchTerms',
			'statsClicks',
			'statsReferrers',
			'statsTopAuthors',
			'statsFileDownloads',
			// statsEmailsOpen and statsEmailsClick are not used. statsEmailsSummary are used at the moment,
			// besides this, email page uses separate summary component: <StatsEmailSummary />
			'statsEmailsOpen',
			'statsEmailsClick',
		];

		// TODO: Remove this once the archive breakdown is enabled by default.
		if ( ! config.isEnabled( 'stats/archive-breakdown' ) ) {
			summarizedTypes.push( 'statsTopPosts' );
		}

		return summary && includes( summarizedTypes, statType );
	}

	remapData() {
		const { valueField, isRealTime } = this.props;
		const data = isRealTime ? this.state.diffData : this.props.data;

		// TODO: Handle items with children.
		// For now, we remove any children to avoid view counts out of context.

		if ( isRealTime ) {
			return data
				.filter( ( item ) => item.diffValue !== 0 )
				.sort( ( a, b ) => {
					// Primary sort: diffValue (high to low)
					if ( b.diffValue !== a.diffValue ) {
						return b.diffValue - a.diffValue;
					}
					// Secondary sort: label (alphabetically)
					return ( a.label || '' ).localeCompare( b.label || '' );
				} )
				.map( ( item ) => ( {
					...item,
					value: item.diffValue || 0,
					children: null,
				} ) );
		}

		if ( valueField && data ) {
			return data.map( ( item ) => ( {
				...item,
				value: item[ valueField ],
			} ) );
		}

		return [];
	}

	render() {
		const {
			className,
			summary,
			siteId,
			path,
			moduleStrings,
			statType,
			query,
			translate,
			useShortLabel,
			metricLabel,
			additionalColumns,
			toggleControl,
			mainItemLabel,
			listItemClassName,
			gateStats,
			hasNoBackground,
			skipQuery,
			titleNodes,
			formatValue,
			isRealTime,
		} = this.props;

		const data = this.remapData();

		// Only show loading indicators when nothing is in state tree, and request in-flight
		const isLoading = ! this.state.loaded && ! ( data && data.length );

		// TODO: Support error state in redux store
		const hasError = false;

		const summaryLink = ! this.props.hideSummaryLink && this.getSummaryLink();
		const displaySummaryLink = data && summaryLink;
		const isAllTime = this.isAllTimeList();

		const emptyMessage = isRealTime ? 'gathering info…' : moduleStrings.empty;
		// TODO: Translate empty message
		// But not yet as this is just a placeholder for now.

		return (
			<>
				{ ! skipQuery && siteId && statType && (
					<QuerySiteStats statType={ statType } siteId={ siteId } query={ query } />
				) }
				<StatsListCard
					className={ clsx( className, 'stats-module__card', path ) }
					moduleType={ path }
					data={ data }
					useShortLabel={ useShortLabel }
					title={ this.props.moduleStrings?.title }
					titleNodes={ titleNodes }
					emptyMessage={ emptyMessage }
					metricLabel={ metricLabel }
					showMore={
						displaySummaryLink && ! summary
							? {
									url: summaryLink,
									label:
										data.length >= 10
											? translate( 'View all', {
													context: 'Stats: Button link to show more detailed stats information',
											  } )
											: translate( 'View details', {
													context: 'Stats: Button label to see the detailed content of a panel',
											  } ),
							  }
							: undefined
					}
					error={ hasError && <ErrorPanel /> }
					loader={ isLoading && <StatsModulePlaceholder isLoading={ isLoading } /> }
					heroElement={
						path === 'countryviews' && (
							<Geochart query={ query } skipQuery={ skipQuery } isRealTime={ isRealTime } />
						)
					}
					additionalColumns={ additionalColumns }
					splitHeader={ !! toggleControl || !! additionalColumns || !! mainItemLabel }
					toggleControl={ toggleControl }
					multiHeader={ isAllTime }
					mainItemLabel={ mainItemLabel }
					showLeftIcon={ path === 'authors' }
					listItemClassName={ listItemClassName }
					hasNoBackground={ hasNoBackground }
					overlay={
						siteId &&
						statType &&
						gateStats && (
							<StatsCardUpsell
								className="stats-module__upsell"
								statType={ statType }
								siteId={ siteId }
							/>
						)
					}
					formatValue={ formatValue }
				/>
			</>
		);
	}
}

export default connect( ( state, ownProps ) => {
	const siteId = getSelectedSiteId( state );
	const siteSlug = getSiteSlug( state, siteId );
	const { statType, query } = ownProps;
	const gateStats = shouldGateStats( state, siteId, statType );
	const gateDownloads = shouldGateStats( state, siteId, STATS_FEATURE_DOWNLOAD_CSV );

	return {
		requesting: isRequestingSiteStatsForQuery( state, siteId, statType, query ),
		data: getSiteStatsNormalizedData( state, siteId, statType, query ),
		siteId,
		siteSlug,
		gateStats,
		gateDownloads,
	};
} )( localize( StatsModule ) );