-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathindex.tsx
More file actions
279 lines (253 loc) · 9.13 KB
/
Copy pathindex.tsx
File metadata and controls
279 lines (253 loc) · 9.13 KB
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
import config from '@automattic/calypso-config';
import page from '@automattic/calypso-router';
import { translate } from 'i18n-calypso';
import { Moment } from 'moment';
import qs from 'qs';
import { findShortcutForRange } from 'calypso/components/date-range/use-shortcuts';
import { useLocalizedMoment } from 'calypso/components/localized-moment';
import { recordTracksEvent } from 'calypso/lib/analytics/tracks';
import { useMomentInSite } from 'calypso/my-sites/stats/hooks/use-moment-site-zone';
import { useSelector } from 'calypso/state';
import getSiteId from 'calypso/state/sites/selectors/get-site-id';
import DateControl from '../date-control';
import { DateRangePickerShortcut } from '../date-range/shortcuts';
import type { JSX } from 'react';
type DateRange = {
// Absent for shortcuts without a fixed range (e.g. "All time").
chartStart?: string;
chartEnd?: string;
daysInRange: number;
shortcutId?: string;
};
interface StatsDateControlProps {
slug: string;
// Either a raw query string or an already-parsed query object; both are accepted by `qs.parse`.
queryParams: string | Record< string, string >;
period: 'day' | 'week' | 'month' | 'year';
dateRange: DateRange;
shortcutList: DateRangePickerShortcut[];
overlay?: JSX.Element;
// Optional module segment used by summary pages so links resolve to
// `/stats/{period}/{module}/{slug}` instead of the Traffic `/stats/{period}/{slug}`.
module?: string;
onGatedHandler: (
events: { name: string; params?: object }[],
event_from: string,
stat_type: string
) => void;
}
// Define the event name keys for tracking events
type EventNameKey =
| 'today'
| 'last_7_days'
| 'last_30_days'
| 'month_to_date'
| 'last_12_months'
| 'year_to_date'
| 'last_3_years'
| 'all_time'
| 'custom_date_range'
| 'apply_button'
| 'trigger_button';
// Define the structure for tracking event names
interface EventNames {
jetpack_odyssey: Record< EventNameKey, string >;
calypso: Record< EventNameKey, string >;
}
// Define the tracking event names object. Hardcoding event names ensures consistency, searchability, and prevents errors per Tracks naming conventions.
const eventNames: EventNames = {
jetpack_odyssey: {
today: 'jetpack_odyssey_stats_date_picker_shortcut_today_clicked',
last_7_days: 'jetpack_odyssey_stats_date_picker_shortcut_last_7_days_clicked',
last_30_days: 'jetpack_odyssey_stats_date_picker_shortcut_last_30_days_clicked',
month_to_date: 'jetpack_odyssey_stats_date_picker_shortcut_month_to_date_clicked',
last_12_months: 'jetpack_odyssey_stats_date_picker_shortcut_last_12_months_clicked',
year_to_date: 'jetpack_odyssey_stats_date_picker_shortcut_year_to_date_clicked',
last_3_years: 'jetpack_odyssey_stats_date_picker_shortcut_last_3_years_clicked',
all_time: 'jetpack_odyssey_stats_date_picker_shortcut_all_time_clicked',
custom_date_range: 'jetpack_odyssey_stats_date_picker_shortcut_custom_date_range_clicked',
apply_button: 'jetpack_odyssey_stats_date_picker_apply_button_clicked',
trigger_button: 'jetpack_odyssey_stats_date_picker_opened',
},
calypso: {
today: 'calypso_stats_date_picker_shortcut_today_clicked',
last_7_days: 'calypso_stats_date_picker_shortcut_last_7_days_clicked',
last_30_days: 'calypso_stats_date_picker_shortcut_last_30_days_clicked',
month_to_date: 'calypso_stats_date_picker_shortcut_month_to_date_clicked',
last_12_months: 'calypso_stats_date_picker_shortcut_last_12_months_clicked',
year_to_date: 'calypso_stats_date_picker_shortcut_year_to_date_clicked',
last_3_years: 'calypso_stats_date_picker_shortcut_last_3_years_clicked',
all_time: 'calypso_stats_date_picker_shortcut_all_time_clicked',
custom_date_range: 'calypso_stats_date_picker_shortcut_custom_date_range_clicked',
apply_button: 'calypso_stats_date_picker_apply_button_clicked',
trigger_button: 'calypso_stats_date_picker_opened',
},
};
const StatsDateControl = ( {
slug,
queryParams,
dateRange,
shortcutList,
overlay,
module,
onGatedHandler,
}: StatsDateControlProps ) => {
// ToDo: Consider removing period from shortcuts.
// We could use the bestPeriodForDays() helper and keep the shortcuts
// consistent with the custom ranges.
const moment = useLocalizedMoment();
const isOdysseyStats = config.isEnabled( 'is_running_in_jetpack_site' );
const siteId = useSelector( ( state ) => getSiteId( state, slug ) );
const momentInSite = useMomentInSite( siteId );
// Drop params that belong to the legacy summary date contract so it can't
// coexist with the modern `chartStart`/`chartEnd` one in the same URL.
const removeLegacyRangeParams = ( queryParamsObject: Record< string, unknown > ): void => {
[
'startDate',
'endDate',
'num',
'summarize',
'customRangeStart',
'customRangeEnd',
'shortcut',
'navigation',
].forEach( ( key ) => delete queryParamsObject[ key ] );
};
const basePath = ( period: string ) =>
module ? `/stats/${ period }/${ module }/${ slug }` : `/stats/${ period }/${ slug }`;
// Shared link generation helper.
const generateNewLink = (
period: string,
startDate: string,
endDate: string,
shortcutId?: string
) => {
const queryParamsObject = qs.parse( queryParams );
removeLegacyRangeParams( queryParamsObject );
const dateRangeParams = Object.assign( {}, queryParamsObject, {
chartStart: startDate,
chartEnd: endDate,
} );
if ( shortcutId ) {
dateRangeParams.shortcut = shortcutId;
}
const newRangeQuery = qs.stringify( dateRangeParams, {
addQueryPrefix: true,
} );
return `${ basePath( period ) }${ newRangeQuery }`;
};
// "All time" keeps the legacy `num=-1&summarize=1` contract so the existing
// query/label logic keeps working instead of a synthetic huge chart range.
const generateAllTimeLink = () => {
const queryParamsObject = qs.parse( queryParams );
removeLegacyRangeParams( queryParamsObject );
delete queryParamsObject.chartStart;
delete queryParamsObject.chartEnd;
const allTimeParams = Object.assign( {}, queryParamsObject, {
startDate: momentInSite().format( 'YYYY-MM-DD' ),
summarize: 1,
num: -1,
} );
const newRangeQuery = qs.stringify( allTimeParams, {
addQueryPrefix: true,
} );
return `${ basePath( 'day' ) }${ newRangeQuery }`;
};
// Determine period based on number of days in date range.
const bestPeriodForDays = ( days: number ): string => {
// 30 bars, one day is one bar
if ( days <= 30 ) {
return 'day';
}
// 25 bars, 7 days one bar
if ( days <= 7 * 25 ) {
return 'week';
}
// 25 bars, 30 days one bar
if ( days <= 30 * 25 ) {
return 'month';
}
return 'year';
};
// Handler for Apply button.
const onApplyButtonHandler = (
startDate: string,
endDate: string,
selectedShortcutId?: string
) => {
// Determine period based on date range.
const rangeInDays = Math.abs( moment( endDate ).diff( moment( startDate ), 'days' ) );
let period = bestPeriodForDays( rangeInDays );
const event_from = isOdysseyStats ? 'jetpack_odyssey' : 'calypso';
recordTracksEvent( eventNames[ event_from ][ 'apply_button' ], { blog_id: siteId } );
const appliedShortcut = findShortcutForRange( shortcutList, {
chartStart: startDate,
chartEnd: endDate,
shortcutId: selectedShortcutId,
} );
if ( appliedShortcut && appliedShortcut.id ) {
localStorage.setItem(
`jetpack_stats_stored_date_range_shortcut_id_${ siteId }`,
appliedShortcut.id
);
// Remove legacy item key.
localStorage.removeItem( 'jetpack_stats_stored_date_range_shortcut_id' );
// Apply the period from the found shortcut.
period = appliedShortcut.period;
}
// Update chart via routing.
setTimeout(
() => page( generateNewLink( period, startDate, endDate, selectedShortcutId ) ),
250
);
};
// handler for shortcut clicks
const onShortcutClickHandler = (
shortcut: DateRangePickerShortcut,
closePopoverAndCommit: () => void,
closePopover: () => void
) => {
const event_from = isOdysseyStats ? 'jetpack_odyssey' : 'calypso';
if ( shortcut.isGated ) {
if ( onGatedHandler ) {
onGatedHandler(
[ { name: eventNames[ event_from ][ shortcut.id as EventNameKey ] } ],
event_from,
shortcut.statType ?? shortcut.id
);
}
} else {
recordTracksEvent( eventNames[ event_from ][ shortcut.id as EventNameKey ], {
blog_id: siteId,
} );
if ( shortcut.id === 'all_time' ) {
closePopover();
setTimeout( () => page( generateAllTimeLink() ), 250 );
} else if ( shortcut.id !== 'custom_date_range' ) {
// Prevent the unclickable shortcut from being applied.
closePopoverAndCommit();
}
}
};
return (
<DateControl
dateRange={ dateRange }
onApplyButtonClick={ ( startDate: Moment, endDate: Moment, selectedShortcutId?: string ) =>
onApplyButtonHandler(
startDate.format( 'YYYY-MM-DD' ),
endDate.format( 'YYYY-MM-DD' ),
selectedShortcutId
)
}
onShortcutClick={ onShortcutClickHandler }
onDateControlClick={ () => {
const event_from = isOdysseyStats ? 'jetpack_odyssey' : 'calypso';
recordTracksEvent( eventNames[ event_from ][ 'trigger_button' ], { blog_id: siteId } );
} }
tooltip={ translate( 'Filter all data by date' ) }
overlay={ overlay }
shortcutList={ shortcutList }
/>
);
};
export { StatsDateControl as default, StatsDateControl };