This repository was archived by the owner on Jun 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
333 lines (301 loc) · 8.7 KB
/
index.js
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
import React from 'react'
/**
* Check if we're running in a browser.
*
* @return {!boolean}
*/
const isBrowser = () =>
typeof window !== 'undefined'
/**
* Check if the Optimizely API is present.
*
* @return {!boolean}
*/
const isOptimizelyLoaded = () =>
isBrowser() && window['optimizely']
/**
* Shorthand helper to get a given key from `window['optimizely']`
*
* @param {?string} [key=null]
* An optional key to get on the Optimizely client
* @return {*}
* Returns the key from the Optimizely client, or the Optimizely client itself
*/
const optimizely = (key = null) => {
if (!isOptimizelyLoaded()) {
throw Error('Optimizely JS API not found.')
}
return key
? window['optimizely'][key]
: window['optimizely']
}
/**
* Get all registered Optimizely experiments.
*
* @return {Object.<string, Object>}
* A hash-map-like object in the form `<id, experiment>`
*/
const getAllExperiments = () =>
(isOptimizelyLoaded() ? optimizely('allExperiments') || {} : {})
/**
* Get the activated experiments for the current visitor.
*
* @return {string[]}
* An array containing the IDs of the activated experiments.
*/
const getActiveExperiments = () =>
(isOptimizelyLoaded() ? optimizely('activeExperiments') || [] : [])
/**
* Get the variation map.
*
* @return {Object}
* This is a hash table whose keys are the experiment ids of
* experiments running for the visitor (including inactive
* experiments for which the user has been bucketed), and whose
* values are the variation indexes for those experiments.
*/
const getVariationMap = () =>
(isOptimizelyLoaded() ? optimizely('variationMap') || {} : {})
/**
* Trigger an API call through the Optimizely client.
*
* @param {!string} method
* The method to call (i.e. `trackEvent`)
* @param {...*} [args]
* A variable number of arguments to pass to the call.
* @return {undefined}
*/
const call = (method, ...args) => {
window['optimizely'] = window['optimizely'] || []
try {
window['optimizely'].push([method, ...args])
} catch (err) {
console.error(`react-optimizely`, err)
}
}
/**
* Activate an experiment by ID for the current user.
*
* @param {!string} experimentId
* @return {undefined}
*/
const activateExperiment = (experimentId) => {
call('activate', experimentId)
}
/**
* Get the possible experiment IDs for a given experiment name.
*
* @param {!string} experimentName
* @return {string[]}
*/
const getPossibleIds = (experimentName) => {
let allExperiments = getAllExperiments()
return Object.keys(allExperiments).filter((key) => {
return allExperiments[key].name === experimentName
})
}
/**
* Get an experiment's ID from their name.
*
* @param {!string} experimentName
* @return {?string}
* The ID of the experiment or `null` if the
* experiment was not found.
*/
const getExperimentId = (experimentName) => {
let id = getPossibleIds(experimentName).pop()
return id || null
}
/**
* Get an experiment by their ID.
*
* @param {!string} experimentId
* @return {?Object}
* The experiment or `null` if it was not found.
*/
const getExperimentById = (experimentId) => {
const allExperiments = getAllExperiments()
const experiment = allExperiments[experimentId]
return experiment || null
}
/**
* Get an experiment by name.
*
* @param {!string} experimentName
* @return {?Object}
* The experiment or `null` if it was not found.
*/
const getExperimentByName = (experimentName) => {
return getExperimentById(getExperimentId(experimentName))
}
/**
* Check if an experiment is enabled.
*
* Please note that this flag does _not_ constitute
* whether or not the experiment is **active**.
*
* @param {!string} experimentName
* @return {!boolean}
*/
const isEnabled = (experimentName) => {
let experiment = getExperimentByName(experimentName)
return (experiment && experiment.enabled)
}
/**
* Check if an experiment's name is unique.
*
* @param {!string} experimentName
* @return {!boolean}
* Returns `false` if the experiment name could resolve
* to more than 1 experiment ID.
*/
const isNameUnique = (experimentName) => {
return getPossibleIds(experimentName).length <= 1
}
/**
* Check whether or not an experiment is active.
*
* @param {!string} experimentName
* @return {!boolean}
*/
const isActive = (experimentName) => {
const experimentId = getExperimentId(experimentName)
const activateExperiments = getActiveExperiments()
return activateExperiments
.filter((id) => id === experimentId).length > 0
}
/**
* Activate an experiment.
*
* @param {!string} experimentName
* The name of the experiment to activate.
* @return {!boolean}
* Returns `true` if the experiment is active, `false` otherwise
*/
export const activate = (experimentName) => {
// Can't activate experiments that are unidentifiable
// by name, or experiments that are disabled
if (isOptimizelyLoaded() &&
!isNameUnique(experimentName) ||
!isEnabled(experimentName)) {
return false
}
const experimentId = getExperimentId(experimentName)
// Activate the experiment if it is not already
if (!isActive(experimentName) && experimentId) {
activateExperiment(experimentId)
}
return isActive(experimentName)
}
/**
* Get the current variant for the current user and a given experiment.
*
* @param {!string} experimentName The experiment name
* @return {?Object}
* The current variant, or `null` if the experiment is
* not activated, not enabled or the experiment name
* could not be resolved to a singular experiment ID.
*/
export const getVariant = (experimentName) => {
const variationMap = getVariationMap()
if (isOptimizelyLoaded() &&
isNameUnique(experimentName) &&
isEnabled(experimentName) &&
isActive(experimentName)) {
return variationMap[getExperimentId(experimentName)]
}
return null
}
/**
* Add custom tags to this session.
*
* @param {...Object} rawTags
* A variable number of tags as key-value pairs,
* e.g. ``{ user: 1 }, { foo: 'bar', bar: 'baz' }``
* @return {undefined}
*/
export const tag = (...rawTags) => {
let tags = {}
rawTags.forEach((tag) => {
if (typeof tag !== 'object') throw Error(`Expected tag to be an object, got ${typeof tag}`)
tags = Object.assign(tags, tag)
})
call('customTag', tags)
}
/**
* Track a custom event.
*
* @param {!string} event
* The event to track.
* @param {?number} [revenue=null]
* An optional amount of revenue for this event (in cents)
* @return {undefined}
*/
export const track = (event, revenue = null) => {
let metadata = {}
if (revenue !== null) {
metadata.revenue = revenue
}
call('trackEvent', event, metadata)
}
/**
* A helper to variate between different results based on
* the current experiment variant.
*
* @param {object} variantToResultMap
* An object whose keys are variant names and values
* are the results for the given variant. The values
* can either be strings or functions.
* @return {*}
* The result for the given variant, or the default
* result if a result for the current variant was
* not found.
*/
export const variate = (variantToResultMap, variant) => {
let result = variantToResultMap['default']
if (variant !== undefined &&
variantToResultMap.hasOwnProperty(variant.name)) {
result = variantToResultMap[variant.name]
}
if (typeof result === 'function') {
return result()
}
return result
}
/**
* Wrap a React component in an Optimizely experiment.
*
* The wrapped component is passed a prop, `optimizely`,
* that is an object with three keys:
*
* - `experiment` (?object): The Optimizely experiment
* - `variant` (?object): The current experiment variant
* - `isActive` (!boolean): Whether or not the experiment is active
*
* If the experiment could not be activated (see {@link activate}),
* then `isActive` is set to `false` and both the `experiment`
* and `variant` props are nulled.
*
* @param {!string} experimentName
* The experiment name
* @return {Function}
* A function to wrap your component in.
*/
export default (experimentName) =>
/**
* @param {React.Component} Component
* The component to wrap
* @return {Function}
* The wrapped component
*/
(Component) =>
(props) => {
// Activate the experiment
const isActive = activate(experimentName)
// Get experiment and variant information
const experiment = getExperimentByName(experimentName)
const variant = getVariant(experimentName)
return <Component
{...props}
optimizely={{ experiment, variant, isActive }} />
}