-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathposthog-surveys.ts
337 lines (286 loc) · 13.5 KB
/
posthog-surveys.ts
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
import { SURVEYS } from './constants'
import { getSurveySeenStorageKeys } from './extensions/surveys/surveys-utils'
import { PostHog } from './posthog-core'
import {
Survey,
SurveyCallback,
SurveyQuestionBranchingType,
SurveyQuestionType,
SurveyUrlMatchType,
} from './posthog-surveys-types'
import { RemoteConfig } from './types'
import { assignableWindow, document, window } from './utils/globals'
import { createLogger } from './utils/logger'
import { isUrlMatchingRegex } from './utils/request-utils'
import { SurveyEventReceiver } from './utils/survey-event-receiver'
import { isNullish } from './utils/type-utils'
const logger = createLogger('[Surveys]')
export const surveyUrlValidationMap: Record<SurveyUrlMatchType, (conditionsUrl: string) => boolean> = {
icontains: (conditionsUrl) =>
!!window && window.location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) > -1,
not_icontains: (conditionsUrl) =>
!!window && window.location.href.toLowerCase().indexOf(conditionsUrl.toLowerCase()) === -1,
regex: (conditionsUrl) => !!window && isUrlMatchingRegex(window.location.href, conditionsUrl),
not_regex: (conditionsUrl) => !!window && !isUrlMatchingRegex(window.location.href, conditionsUrl),
exact: (conditionsUrl) => window?.location.href === conditionsUrl,
is_not: (conditionsUrl) => window?.location.href !== conditionsUrl,
}
function getRatingBucketForResponseValue(responseValue: number, scale: number) {
if (scale === 3) {
if (responseValue < 1 || responseValue > 3) {
throw new Error('The response must be in range 1-3')
}
return responseValue === 1 ? 'negative' : responseValue === 2 ? 'neutral' : 'positive'
} else if (scale === 5) {
if (responseValue < 1 || responseValue > 5) {
throw new Error('The response must be in range 1-5')
}
return responseValue <= 2 ? 'negative' : responseValue === 3 ? 'neutral' : 'positive'
} else if (scale === 7) {
if (responseValue < 1 || responseValue > 7) {
throw new Error('The response must be in range 1-7')
}
return responseValue <= 3 ? 'negative' : responseValue === 4 ? 'neutral' : 'positive'
} else if (scale === 10) {
if (responseValue < 0 || responseValue > 10) {
throw new Error('The response must be in range 0-10')
}
return responseValue <= 6 ? 'detractors' : responseValue <= 8 ? 'passives' : 'promoters'
}
throw new Error('The scale must be one of: 3, 5, 7, 10')
}
export function getNextSurveyStep(
survey: Survey,
currentQuestionIndex: number,
response: string | string[] | number | null
) {
const question = survey.questions[currentQuestionIndex]
const nextQuestionIndex = currentQuestionIndex + 1
if (!question.branching?.type) {
if (currentQuestionIndex === survey.questions.length - 1) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
if (question.branching.type === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
} else if (question.branching.type === SurveyQuestionBranchingType.SpecificQuestion) {
if (Number.isInteger(question.branching.index)) {
return question.branching.index
}
} else if (question.branching.type === SurveyQuestionBranchingType.ResponseBased) {
// Single choice
if (question.type === SurveyQuestionType.SingleChoice) {
// :KLUDGE: for now, look up the choiceIndex based on the response
// TODO: once QuestionTypes.MultipleChoiceQuestion is refactored, pass the selected choiceIndex into this method
const selectedChoiceIndex = question.choices.indexOf(`${response}`)
if (question.branching?.responseValues?.hasOwnProperty(selectedChoiceIndex)) {
const nextStep = question.branching.responseValues[selectedChoiceIndex]
// Specific question
if (Number.isInteger(nextStep)) {
return nextStep
}
if (nextStep === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
} else if (question.type === SurveyQuestionType.Rating) {
if (typeof response !== 'number' || !Number.isInteger(response)) {
throw new Error('The response type must be an integer')
}
const ratingBucket = getRatingBucketForResponseValue(response, question.scale)
if (question.branching?.responseValues?.hasOwnProperty(ratingBucket)) {
const nextStep = question.branching.responseValues[ratingBucket]
// Specific question
if (Number.isInteger(nextStep)) {
return nextStep
}
if (nextStep === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
}
return nextQuestionIndex
}
logger.warn('Falling back to next question index due to unexpected branching type')
return nextQuestionIndex
}
export class PostHogSurveys {
private _decideServerResponse?: boolean
public _surveyEventReceiver: SurveyEventReceiver | null
private _surveyManager: any
constructor(private readonly instance: PostHog) {
// we set this to undefined here because we need the persistence storage for this type
// but that's not initialized until loadIfEnabled is called.
this._surveyEventReceiver = null
}
onRemoteConfig(response: RemoteConfig) {
this._decideServerResponse = !!response['surveys']
this.loadIfEnabled()
}
reset(): void {
localStorage.removeItem('lastSeenSurveyDate')
const surveyKeys = getSurveySeenStorageKeys()
surveyKeys.forEach((key) => localStorage.removeItem(key))
}
loadIfEnabled() {
const surveysGenerator = assignableWindow?.__PosthogExtensions__?.generateSurveys
if (!this.instance.config.disable_surveys && this._decideServerResponse && !surveysGenerator) {
if (this._surveyEventReceiver == null) {
this._surveyEventReceiver = new SurveyEventReceiver(this.instance)
}
assignableWindow.__PosthogExtensions__?.loadExternalDependency?.(this.instance, 'surveys', (err) => {
if (err) {
return logger.error('Could not load surveys script', err)
}
this._surveyManager = assignableWindow.__PosthogExtensions__?.generateSurveys?.(this.instance)
})
}
}
getSurveys(callback: SurveyCallback, forceReload = false) {
// In case we manage to load the surveys script, but config says not to load surveys
// then we shouldn't return survey data
if (this.instance.config.disable_surveys) {
return callback([])
}
if (this._surveyEventReceiver == null) {
this._surveyEventReceiver = new SurveyEventReceiver(this.instance)
}
const existingSurveys = this.instance.get_property(SURVEYS)
if (!existingSurveys || forceReload) {
this.instance._send_request({
url: this.instance.requestRouter.endpointFor(
'api',
`/api/surveys/?token=${this.instance.config.token}`
),
method: 'GET',
callback: (response) => {
if (response.statusCode !== 200 || !response.json) {
return callback([])
}
const surveys = response.json.surveys || []
const eventOrActionBasedSurveys = surveys.filter(
(survey: Survey) =>
(survey.conditions?.events &&
survey.conditions?.events?.values &&
survey.conditions?.events?.values?.length > 0) ||
(survey.conditions?.actions &&
survey.conditions?.actions?.values &&
survey.conditions?.actions?.values?.length > 0)
)
if (eventOrActionBasedSurveys.length > 0) {
this._surveyEventReceiver?.register(eventOrActionBasedSurveys)
}
this.instance.persistence?.register({ [SURVEYS]: surveys })
return callback(surveys)
},
})
} else {
return callback(existingSurveys)
}
}
getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {
this.getSurveys((surveys) => {
const activeSurveys = surveys.filter((survey) => {
return !!(survey.start_date && !survey.end_date)
})
const conditionMatchedSurveys = activeSurveys.filter((survey) => {
if (!survey.conditions) {
return true
}
// use urlMatchType to validate url condition, fallback to contains for backwards compatibility
const urlCheck = survey.conditions?.url
? surveyUrlValidationMap[survey.conditions?.urlMatchType ?? 'icontains'](survey.conditions.url)
: true
const selectorCheck = survey.conditions?.selector
? document?.querySelector(survey.conditions.selector)
: true
return urlCheck && selectorCheck
})
// get all the surveys that have been activated so far with user actions.
const activatedSurveys: string[] | undefined = this._surveyEventReceiver?.getSurveys()
const targetingMatchedSurveys = conditionMatchedSurveys.filter((survey) => {
if (
!survey.linked_flag_key &&
!survey.targeting_flag_key &&
!survey.internal_targeting_flag_key &&
!survey.feature_flag_keys?.length
) {
return true
}
const linkedFlagCheck = survey.linked_flag_key
? this.instance.featureFlags.isFeatureEnabled(survey.linked_flag_key)
: true
const targetingFlagCheck = survey.targeting_flag_key
? this.instance.featureFlags.isFeatureEnabled(survey.targeting_flag_key)
: true
const hasEvents =
survey.conditions?.events &&
survey.conditions?.events?.values &&
survey.conditions?.events?.values.length > 0
const hasActions =
survey.conditions?.actions &&
survey.conditions?.actions?.values &&
survey.conditions?.actions?.values.length > 0
const eventBasedTargetingFlagCheck =
hasEvents || hasActions ? activatedSurveys?.includes(survey.id) : true
const overrideInternalTargetingFlagCheck = this._canActivateRepeatedly(survey)
const internalTargetingFlagCheck =
survey.internal_targeting_flag_key && !overrideInternalTargetingFlagCheck
? this.instance.featureFlags.isFeatureEnabled(survey.internal_targeting_flag_key)
: true
const flagsCheck = this.checkFlags(survey)
return (
linkedFlagCheck &&
targetingFlagCheck &&
internalTargetingFlagCheck &&
eventBasedTargetingFlagCheck &&
flagsCheck
)
})
return callback(targetingMatchedSurveys)
}, forceReload)
}
checkFlags(survey: Survey): boolean {
if (!survey.feature_flag_keys?.length) {
return true
}
return survey.feature_flag_keys.every(({ key, value }) => {
if (!key || !value) {
return true
}
return this.instance.featureFlags.isFeatureEnabled(value)
})
}
getNextSurveyStep = getNextSurveyStep
// this method is lazily loaded onto the window to avoid loading preact and other dependencies if surveys is not enabled
private _canActivateRepeatedly(survey: Survey) {
if (isNullish(assignableWindow.__PosthogExtensions__?.canActivateRepeatedly)) {
logger.warn('init was not called')
return false // TODO does it make sense to have a default here?
}
return assignableWindow.__PosthogExtensions__.canActivateRepeatedly(survey)
}
canRenderSurvey(surveyId: string) {
if (isNullish(this._surveyManager)) {
logger.warn('init was not called')
return
}
this.getSurveys((surveys) => {
const survey = surveys.filter((x) => x.id === surveyId)[0]
this._surveyManager.canRenderSurvey(survey)
})
}
renderSurvey(surveyId: string, selector: string) {
if (isNullish(this._surveyManager)) {
logger.warn('init was not called')
return
}
this.getSurveys((surveys) => {
const survey = surveys.filter((x) => x.id === surveyId)[0]
this._surveyManager.renderSurvey(survey, document?.querySelector(selector))
})
}
}