-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathhooks.ts
399 lines (361 loc) · 14.1 KB
/
hooks.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
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
/**
* Copyright 2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useCallback, useContext, useEffect, useState, useRef } from 'react';
import { UserAttributes, OptimizelyDecideOption } from '@optimizely/optimizely-sdk';
import { getLogger, LoggerFacade } from '@optimizely/js-sdk-logging';
import { setupAutoUpdateListeners } from './autoUpdate';
import { ReactSDKClient, VariableValuesObject, OnReadyResult } from './client';
import { OptimizelyContext } from './Context';
import { areAttributesEqual, OptimizelyDecision, createFailedDecision } from './utils';
const hooksLogger: LoggerFacade = getLogger('ReactSDK');
enum HookType {
EXPERIMENT = 'Experiment',
FEATURE = 'Feature',
}
type HookOptions = {
autoUpdate?: boolean;
timeout?: number;
};
type DecideHooksOptions = HookOptions & { decideOptions?: OptimizelyDecideOption[] };
type HookOverrides = {
overrideUserId?: string;
overrideAttributes?: UserAttributes;
};
type ClientReady = boolean;
type DidTimeout = boolean;
interface InitializationState {
clientReady: ClientReady;
didTimeout: DidTimeout;
}
// TODO - Get these from the core SDK once it's typed
interface ExperimentDecisionValues {
variation: string | null;
}
// TODO - Get these from the core SDK once it's typed
interface FeatureDecisionValues {
isEnabled: boolean;
variables: VariableValuesObject;
}
interface UseExperiment {
(experimentKey: string, options?: HookOptions, overrides?: HookOverrides): [
ExperimentDecisionValues['variation'],
ClientReady,
DidTimeout
];
}
interface UseFeature {
(featureKey: string, options?: HookOptions, overrides?: HookOverrides): [
FeatureDecisionValues['isEnabled'],
FeatureDecisionValues['variables'],
ClientReady,
DidTimeout
];
}
interface UseDecision {
(featureKey: string, options?: DecideHooksOptions, overrides?: HookOverrides): [
OptimizelyDecision,
ClientReady,
DidTimeout
];
}
interface DecisionInputs {
entityKey: string;
overrideUserId?: string;
overrideAttributes?: UserAttributes;
}
/**
* Equality check applied to decision inputs passed into hooks (experiment/feature keys, override user IDs, and override user attributes).
* Used to determine when we need to recompute a decision because different inputs were passed into a hook.
* @param {DecisionInputs} oldDecisionInputs
* @param {DecisionInput} newDecisionInputs
* @returns boolean
*/
function areDecisionInputsEqual(oldDecisionInputs: DecisionInputs, newDecisionInputs: DecisionInputs): boolean {
return (
oldDecisionInputs.entityKey === newDecisionInputs.entityKey &&
oldDecisionInputs.overrideUserId === newDecisionInputs.overrideUserId &&
areAttributesEqual(oldDecisionInputs.overrideAttributes, newDecisionInputs.overrideAttributes)
);
}
/**
* Subscribe to changes in initialization state of the argument client. onInitStateChange callback
* is called on the following events:
* - optimizely successfully becomes ready
* - timeout is reached prior to optimizely becoming ready
* - optimizely becomes ready after the timeout has already passed
* @param {ReactSDKClient} optimizely
* @param {number|undefined} timeout
* @param {Function} onInitStateChange
*/
function subscribeToInitialization(
optimizely: ReactSDKClient,
timeout: number | undefined,
onInitStateChange: (initState: InitializationState) => void
): void {
optimizely
.onReady({ timeout })
.then((res: OnReadyResult) => {
if (res.success) {
hooksLogger.info('Client became ready');
onInitStateChange({
clientReady: true,
didTimeout: false,
});
return;
}
hooksLogger.info(`Client did not become ready before timeout of ${timeout}ms, reason="${res.reason || ''}"`);
onInitStateChange({
clientReady: false,
didTimeout: true,
});
res.dataReadyPromise!.then(() => {
hooksLogger.info('Client became ready after timeout already elapsed');
onInitStateChange({
clientReady: true,
didTimeout: true,
});
});
})
.catch(() => {
hooksLogger.error(`Error initializing client. The core client or user promise(s) rejected.`);
});
}
function useCompareAttrsMemoize(value: UserAttributes | undefined): UserAttributes | undefined {
const ref = useRef<UserAttributes | undefined>();
if (!areAttributesEqual(value, ref.current)) {
ref.current = value;
}
return ref.current;
}
/**
* A React Hook that retrieves the variation for an experiment, optionally
* auto updating that value based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useExperiment: UseExperiment = (experimentKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => ExperimentDecisionValues = useCallback(
() => ({
variation: optimizely.activate(experimentKey, overrides.overrideUserId, overrideAttrs),
}),
[optimizely, experimentKey, overrides.overrideUserId, overrideAttrs]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<ExperimentDecisionValues & InitializationState>(() => {
const decisionState = isClientReady ? getCurrentDecision() : { variation: null };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: experimentKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrideAttrs,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
useEffect(() => {
if (options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.EXPERIMENT, experimentKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, experimentKey, getCurrentDecision]);
useEffect(
() =>
optimizely.onForcedVariationsUpdate(() => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}),
[getCurrentDecision, optimizely]
);
return [state.variation, state.clientReady, state.didTimeout];
};
/**
* A React Hook that retrieves the status of a feature flag and its variables, optionally
* auto updating those values based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useFeature: UseFeature = (featureKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => FeatureDecisionValues = useCallback(
() => ({
isEnabled: optimizely.isFeatureEnabled(featureKey, overrides.overrideUserId, overrideAttrs),
variables: optimizely.getFeatureVariables(featureKey, overrides.overrideUserId, overrideAttrs),
}),
[optimizely, featureKey, overrides.overrideUserId, overrideAttrs]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<FeatureDecisionValues & InitializationState>(() => {
const decisionState = isClientReady ? getCurrentDecision() : { isEnabled: false, variables: {} };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: featureKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrides.overrideAttributes,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
useEffect(() => {
if (options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, featureKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, featureKey, getCurrentDecision]);
return [state.isEnabled, state.variables, state.clientReady, state.didTimeout];
};
/**
* A React Hook that retrieves the flag decision, optionally
* auto updating those values based on underlying user or datafile changes.
*
* Note: The react client can become ready AFTER the timeout period.
* ClientReady and DidTimeout provide signals to handle this scenario.
*/
export const useDecision: UseDecision = (flagKey, options = {}, overrides = {}) => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
if (!optimizely) {
throw new Error('optimizely prop must be supplied via a parent <OptimizelyProvider>');
}
const overrideAttrs = useCompareAttrsMemoize(overrides.overrideAttributes);
const getCurrentDecision: () => { decision: OptimizelyDecision } = useCallback(
() => ({
decision: optimizely.decide(flagKey, options.decideOptions, overrides.overrideUserId, overrideAttrs)
}),
[optimizely, flagKey, overrides.overrideUserId, overrideAttrs, options.decideOptions]
);
const isClientReady = isServerSide || optimizely.isReady();
const [state, setState] = useState<{ decision: OptimizelyDecision } & InitializationState>(() => {
const decisionState = isClientReady? getCurrentDecision()
: { decision: createFailedDecision(flagKey, 'Optimizely SDK not configured properly yet.', { id: overrides.overrideUserId || null, attributes: overrideAttrs}) };
return {
...decisionState,
clientReady: isClientReady,
didTimeout: false,
};
});
// Decision state is derived from entityKey and overrides arguments.
// Track the previous value of those arguments, and update state when they change.
// This is an instance of the derived state pattern recommended here:
// https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
const currentDecisionInputs: DecisionInputs = {
entityKey: flagKey,
overrideUserId: overrides.overrideUserId,
overrideAttributes: overrides.overrideAttributes,
};
const [prevDecisionInputs, setPrevDecisionInputs] = useState<DecisionInputs>(currentDecisionInputs);
if (!areDecisionInputsEqual(prevDecisionInputs, currentDecisionInputs)) {
setPrevDecisionInputs(currentDecisionInputs);
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}
const finalReadyTimeout = options.timeout !== undefined ? options.timeout : timeout;
useEffect(() => {
if (!isClientReady) {
subscribeToInitialization(optimizely, finalReadyTimeout, initState => {
setState({
...getCurrentDecision(),
...initState,
});
});
}
}, [isClientReady, finalReadyTimeout, getCurrentDecision, optimizely]);
useEffect(() => {
if (options.autoUpdate) {
return setupAutoUpdateListeners(optimizely, HookType.FEATURE, flagKey, hooksLogger, () => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
});
}
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, flagKey, getCurrentDecision]);
return [state.decision, state.clientReady, state.didTimeout];
};