-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
NpsSurvey.tsx
408 lines (363 loc) 路 13.4 KB
/
NpsSurvey.tsx
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import * as React from 'react';
import {
Box,
Flex,
IconButton,
Button,
Typography,
Textarea,
Portal,
Field,
FieldLabel,
FieldInput,
VisuallyHidden,
} from '@strapi/design-system';
import { useNotification, useAppInfo, usePersistentState } from '@strapi/helper-plugin';
import { Cross } from '@strapi/icons';
import { Formik, Form } from 'formik';
import { useIntl } from 'react-intl';
import styled, { useTheme } from 'styled-components';
import * as yup from 'yup';
import { useAuth } from '../features/Auth';
const FieldWrapper = styled(Field)`
height: ${32 / 16}rem;
width: ${32 / 16}rem;
> label,
~ input {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
> label {
color: inherit;
cursor: pointer;
padding: ${({ theme }) => theme.spaces[2]};
text-align: center;
vertical-align: middle;
}
&:hover,
&:focus-within {
background-color: ${({ theme }) => theme.colors.neutral0};
}
&:active,
&.selected {
color: ${({ theme }) => theme.colors.primary700};
background-color: ${({ theme }) => theme.colors.neutral0};
border-color: ${({ theme }) => theme.colors.primary700};
}
`;
const delays = {
postResponse: 90 * 24 * 60 * 60 * 1000, // 90 days in ms
postFirstDismissal: 14 * 24 * 60 * 60 * 1000, // 14 days in ms
postSubsequentDismissal: 90 * 24 * 60 * 60 * 1000, // 90 days in ms
display: 10 * 60 * 60 * 1000, // 10 hours in ms
};
const ratingArray = [...Array(11).keys()];
const checkIfShouldShowSurvey = (settings: NpsSurveySettings) => {
const { enabled, lastResponseDate, firstDismissalDate, lastDismissalDate } = settings;
// This function goes through all the cases where we'd want to not show the survey:
// 1. If the survey is disabled by strapi, abort mission, don't bother checking the other settings.
// 2. If the survey is disabled by user, abort mission, don't bother checking the other settings.
// 3. If the user has already responded to the survey, check if enough time has passed since the last response.
// 4. If the user has dismissed the survey twice or more before, check if enough time has passed since the last dismissal.
// 5. If the user has only dismissed the survey once before, check if enough time has passed since the first dismissal.
// If none of these cases check out, then we show the survey.
// Note that submitting a response resets the dismissal counts.
// Checks 4 and 5 should not be reversed, since the first dismissal will also exist if the user has dismissed the survey twice or more before.
// For users who had created an account before the NPS feature was introduced,
// we assume that they would have enabled the NPS feature if they had the chance.
// Global strapi disable for NSP.
if (window.strapi.flags.nps === false) {
return false;
}
// User chose not to enable the NPS feature when signing up
if (enabled === false) {
return false;
}
// The user has already responded to the survey
if (lastResponseDate) {
const timeSinceLastResponse = Date.now() - new Date(lastResponseDate).getTime();
if (timeSinceLastResponse >= delays.postResponse) {
return true;
}
return false;
}
// The user has dismissed the survey twice or more before
if (lastDismissalDate) {
const timeSinceLastDismissal = Date.now() - new Date(lastDismissalDate).getTime();
if (timeSinceLastDismissal >= delays.postSubsequentDismissal) {
return true;
}
return false;
}
// The user has only dismissed the survey once before
if (firstDismissalDate) {
const timeSinceFirstDismissal = Date.now() - new Date(firstDismissalDate).getTime();
if (timeSinceFirstDismissal >= delays.postFirstDismissal) {
return true;
}
return false;
}
// The user has not interacted with the survey before
return true;
};
const NpsSurvey = () => {
const theme = useTheme();
const { formatMessage } = useIntl();
const { npsSurveySettings, setNpsSurveySettings } = useNpsSurveySettings();
const [isFeedbackResponse, setIsFeedbackResponse] = React.useState(false);
const toggleNotification = useNotification();
const { currentEnvironment, strapiVersion } = useAppInfo();
interface NpsSurveyMutationBody {
email: string;
rating: number | null;
comment: string;
environment?: string;
version?: string;
license: 'Enterprise' | 'Community';
}
// Only check on first render if the survey should be shown
const [surveyIsShown, setSurveyIsShown] = React.useState(
checkIfShouldShowSurvey(npsSurveySettings)
);
// Set a cooldown to show the survey when session begins
const [displaySurvey, setDisplaySurvey] = React.useState(false);
React.useEffect(() => {
const displayTime = setTimeout(() => {
setDisplaySurvey(true);
}, delays.display);
return () => {
clearTimeout(displayTime);
};
}, []);
const { user } = useAuth('NpsSurvey');
if (!displaySurvey) {
return null;
}
if (!surveyIsShown) {
return null;
}
const handleSubmitResponse = async ({
npsSurveyRating,
npsSurveyFeedback,
}: {
npsSurveyRating: NpsSurveyMutationBody['rating'];
npsSurveyFeedback: NpsSurveyMutationBody['comment'];
}) => {
try {
const body = {
email: typeof user === 'object' && user.email ? user.email : '',
rating: npsSurveyRating,
comment: npsSurveyFeedback,
environment: currentEnvironment,
version: strapiVersion ?? undefined,
license: window.strapi.projectType,
};
const res = await fetch('https://analytics.strapi.io/submit-nps', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if (!res.ok) {
throw new Error('Failed to submit NPS survey');
}
setNpsSurveySettings((settings) => ({
...settings,
lastResponseDate: new Date().toString(),
firstDismissalDate: null,
lastDismissalDate: null,
}));
setIsFeedbackResponse(true);
// Thank you message displayed in the banner should disappear after few seconds.
setTimeout(() => {
setSurveyIsShown(false);
}, 3000);
} catch (err) {
toggleNotification({
type: 'warning',
message: formatMessage({ id: 'notification.error', defaultMessage: 'An error occurred' }),
});
}
};
const handleDismiss = () => {
setNpsSurveySettings((settings) => {
const nextSettings = {
...settings,
lastResponseDate: null,
};
if (settings.firstDismissalDate) {
// If the user dismisses the survey for the second time
nextSettings.lastDismissalDate = new Date().toString();
} else {
// If the user dismisses the survey for the first time
nextSettings.firstDismissalDate = new Date().toString();
}
return nextSettings;
});
setSurveyIsShown(false);
};
return (
<Portal>
<Formik
initialValues={{ npsSurveyFeedback: '', npsSurveyRating: null }}
onSubmit={handleSubmitResponse}
validationSchema={yup.object({
npsSurveyFeedback: yup.string(),
npsSurveyRating: yup.number().required(),
})}
>
{({ values, handleChange, setFieldValue, isSubmitting }) => (
<Form name="npsSurveyForm">
<Flex
hasRadius
direction="column"
padding={4}
borderColor="primary200"
background="neutral0"
shadow="popupShadow"
position="fixed"
bottom={0}
left="50%"
transform="translateX(-50%)"
zIndex={theme.zIndices[2]}
width="50%"
>
{isFeedbackResponse ? (
<Typography fontWeight="semiBold">
{formatMessage({
id: 'app.components.NpsSurvey.feedback-response',
defaultMessage: 'Thank you very much for your feedback!',
})}
</Typography>
) : (
<Box as="fieldset" width="100%">
<Flex justifyContent="space-between" width="100%">
<Box marginLeft="auto" marginRight="auto">
<Typography fontWeight="semiBold" as="legend">
{formatMessage({
id: 'app.components.NpsSurvey.banner-title',
defaultMessage:
'How likely are you to recommend Strapi to a friend or colleague?',
})}
</Typography>
</Box>
<IconButton
onClick={handleDismiss}
aria-label={formatMessage({
id: 'app.components.NpsSurvey.dismiss-survey-label',
defaultMessage: 'Dismiss survey',
})}
icon={<Cross />}
/>
</Flex>
<Flex gap={2} marginTop={2} marginBottom={2} justifyContent="center">
<Typography variant="pi" textColor="neutral600">
{formatMessage({
id: 'app.components.NpsSurvey.no-recommendation',
defaultMessage: 'Not at all likely',
})}
</Typography>
{ratingArray.map((number) => {
return (
<FieldWrapper
key={number}
className={values.npsSurveyRating === number ? 'selected' : undefined} // "selected" class added when child radio button is checked
hasRadius
background="primary100"
borderColor="primary200"
color="primary600"
position="relative"
cursor="pointer"
>
<FieldLabel htmlFor={`nps-survey-rating-${number}-input`}>
<VisuallyHidden>
<FieldInput
type="radio"
id={`nps-survey-rating-${number}-input`}
name="npsSurveyRating"
checked={values.npsSurveyRating === number}
onChange={(e) =>
setFieldValue('npsSurveyRating', parseInt(e.target.value, 10))
}
value={number}
/>
</VisuallyHidden>
{number}
</FieldLabel>
</FieldWrapper>
);
})}
<Typography variant="pi" textColor="neutral600">
{formatMessage({
id: 'app.components.NpsSurvey.happy-to-recommend',
defaultMessage: 'Extremely likely',
})}
</Typography>
</Flex>
{values.npsSurveyRating !== null && (
<Flex direction="column">
<Box marginTop={2}>
<FieldLabel htmlFor="npsSurveyFeedback" fontWeight="semiBold" fontSize={2}>
{formatMessage({
id: 'app.components.NpsSurvey.feedback-question',
defaultMessage: 'Do you have any suggestion for improvements?',
})}
</FieldLabel>
</Box>
<Box width="62%" marginTop={3} marginBottom={4}>
<Textarea
id="npsSurveyFeedback" // formik element attribute "id" should be same as the values key to work
width="100%"
onChange={handleChange}
>
{values.npsSurveyFeedback}
</Textarea>
</Box>
<Button marginBottom={2} type="submit" loading={isSubmitting}>
{formatMessage({
id: 'app.components.NpsSurvey.submit-feedback',
defaultMessage: 'Submit Feedback',
})}
</Button>
</Flex>
)}
</Box>
)}
</Flex>
</Form>
)}
</Formik>
</Portal>
);
};
interface NpsSurveySettings {
enabled: boolean;
lastResponseDate: string | null;
firstDismissalDate: string | null;
lastDismissalDate: string | null;
}
/**
* We exported to make it available during admin user registration.
* Because we only enable the NPS for users who subscribe to the newsletter when signing up
*/
function useNpsSurveySettings() {
const [npsSurveySettings, setNpsSurveySettings] = usePersistentState<NpsSurveySettings>(
'STRAPI_NPS_SURVEY_SETTINGS',
{
enabled: true,
lastResponseDate: null,
firstDismissalDate: null,
lastDismissalDate: null,
}
);
/**
* TODO: should this just be an array so we can alias the `usePersistentState` hook?
*/
return { npsSurveySettings, setNpsSurveySettings };
}
export { NpsSurvey, useNpsSurveySettings };