-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathKnockGuideProvider.tsx
More file actions
96 lines (85 loc) · 2.48 KB
/
KnockGuideProvider.tsx
File metadata and controls
96 lines (85 loc) · 2.48 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
import Knock, {
KnockGuideClient,
KnockGuideTargetParams,
} from "@knocklabs/client";
import * as React from "react";
import { useKnockClient, useStableOptions } from "../../core";
import { ColorMode } from "../../core/constants";
type KnockGuideProviderValue = {
client: KnockGuideClient;
colorMode: ColorMode;
};
export const KnockGuideContext = React.createContext<
KnockGuideProviderValue | undefined
>(undefined);
export type KnockGuideProviderProps = {
channelId: string;
readyToTarget: boolean;
listenForUpdates?: boolean;
colorMode?: ColorMode;
targetParams?: KnockGuideTargetParams;
trackLocationFromWindow?: boolean;
trackDebugParams?: boolean;
orderResolutionDuration?: number; // in milliseconds
throttleCheckInterval?: number; // in milliseconds
};
export const KnockGuideProvider: React.FC<
React.PropsWithChildren<KnockGuideProviderProps>
> = ({
channelId,
readyToTarget,
listenForUpdates = true,
colorMode = "light",
targetParams = {},
trackLocationFromWindow = true,
// Whether the guide client should look for debug params in url/local storage
// to launch guide toolbar. Set to true if using toolbar v1.
// TODO(KNO-11523): Remove this once we ship v2.
trackDebugParams = false,
// Default to 0 which works well for react apps as this "yields" to react for
// one render cyle first and close the group stage.
orderResolutionDuration = 0,
throttleCheckInterval,
children,
}) => {
let knock: Knock;
try {
knock = useKnockClient();
} catch (_) {
throw new Error("KnockGuideProvider must be used within a KnockProvider");
}
const stableTargetParams = useStableOptions(targetParams);
const knockGuideClient = React.useMemo(() => {
return new KnockGuideClient(knock, channelId, stableTargetParams, {
trackLocationFromWindow,
trackDebugParams,
orderResolutionDuration,
throttleCheckInterval,
});
}, [
knock,
channelId,
stableTargetParams,
trackLocationFromWindow,
trackDebugParams,
orderResolutionDuration,
throttleCheckInterval,
]);
React.useEffect(() => {
if (readyToTarget) {
knockGuideClient.fetch();
if (listenForUpdates) knockGuideClient.subscribe();
}
return () => knockGuideClient.cleanup();
}, [readyToTarget, listenForUpdates, knockGuideClient]);
return (
<KnockGuideContext.Provider
value={{
client: knockGuideClient,
colorMode,
}}
>
{children}
</KnockGuideContext.Provider>
);
};