@hanzo/insights-react 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +198 -0
  3. package/dist/esm/index.js +426 -0
  4. package/dist/esm/index.js.map +1 -0
  5. package/dist/esm/surveys/index.js +98 -0
  6. package/dist/esm/surveys/index.js.map +1 -0
  7. package/dist/types/index.d.ts +96 -0
  8. package/dist/types/surveys/index.d.ts +19 -0
  9. package/dist/umd/index.js +449 -0
  10. package/dist/umd/index.js.map +1 -0
  11. package/dist/umd/surveys/index.js +107 -0
  12. package/dist/umd/surveys/index.js.map +1 -0
  13. package/package.json +64 -0
  14. package/src/components/PostHogCaptureOnViewed.tsx +126 -0
  15. package/src/components/PostHogErrorBoundary.tsx +89 -0
  16. package/src/components/PostHogFeature.tsx +91 -0
  17. package/src/components/__tests__/PostHogCaptureOnViewed.test.tsx +110 -0
  18. package/src/components/__tests__/PostHogErrorBoundary.test.tsx +110 -0
  19. package/src/components/__tests__/PostHogFeature.test.tsx +291 -0
  20. package/src/components/index.ts +7 -0
  21. package/src/components/internal/VisibilityAndClickTracker.tsx +49 -0
  22. package/src/components/internal/VisibilityAndClickTrackers.tsx +60 -0
  23. package/src/context/PostHogContext.ts +9 -0
  24. package/src/context/PostHogProvider.tsx +136 -0
  25. package/src/context/__tests__/PostHogContext.test.tsx +35 -0
  26. package/src/context/__tests__/PostHogProvider.test.tsx +131 -0
  27. package/src/context/index.ts +2 -0
  28. package/src/helpers/error-helpers.ts +15 -0
  29. package/src/helpers/index.ts +1 -0
  30. package/src/hooks/__tests__/featureFlags.test.tsx +273 -0
  31. package/src/hooks/__tests__/usePostHog.test.tsx +19 -0
  32. package/src/hooks/__tests__/useThumbSurvey.test.tsx +105 -0
  33. package/src/hooks/index.ts +6 -0
  34. package/src/hooks/useActiveFeatureFlags.ts +21 -0
  35. package/src/hooks/useFeatureFlagEnabled.ts +24 -0
  36. package/src/hooks/useFeatureFlagPayload.ts +22 -0
  37. package/src/hooks/useFeatureFlagResult.ts +31 -0
  38. package/src/hooks/useFeatureFlagVariantKey.ts +22 -0
  39. package/src/hooks/usePostHog.ts +7 -0
  40. package/src/hooks/useThumbSurvey.ts +146 -0
  41. package/src/index.ts +4 -0
  42. package/src/surveys/index.ts +1 -0
  43. package/src/utils/__tests__/object-utils.test.ts +42 -0
  44. package/src/utils/object-utils.ts +36 -0
  45. package/src/utils/type-utils.ts +16 -0
  46. package/surveys/package.json +7 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2025 PostHog, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # @posthog/react
2
+
3
+ React components and hooks for PostHog analytics integration.
4
+
5
+ [SEE FULL DOCS](https://posthog.com/docs/libraries/react)
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @posthog/react posthog-js
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Setting up the Provider
16
+
17
+ Wrap your application with `PostHogProvider` to make the PostHog client available throughout your app:
18
+
19
+ ```tsx
20
+ import { PostHogProvider } from '@posthog/react'
21
+
22
+ function App() {
23
+ return (
24
+ <PostHogProvider apiKey="<YOUR_PROJECT_API_KEY>" options={{ api_host: 'https://us.i.posthog.com' }}>
25
+ <YourApp />
26
+ </PostHogProvider>
27
+ )
28
+ }
29
+ ```
30
+
31
+ Or pass an existing PostHog client instance:
32
+
33
+ ```tsx
34
+ import posthog from 'posthog-js'
35
+ import { PostHogProvider } from '@posthog/react'
36
+
37
+ // Initialize your client
38
+ posthog.init('<YOUR_PROJECT_API_KEY>', { api_host: 'https://us.i.posthog.com' })
39
+
40
+ function App() {
41
+ return (
42
+ <PostHogProvider client={posthog}>
43
+ <YourApp />
44
+ </PostHogProvider>
45
+ )
46
+ }
47
+ ```
48
+
49
+ ### Hooks
50
+
51
+ #### usePostHog
52
+
53
+ Access the PostHog client instance to capture events, identify users, etc.
54
+
55
+ ```tsx
56
+ import { usePostHog } from '@posthog/react'
57
+
58
+ function MyComponent() {
59
+ const posthog = usePostHog()
60
+
61
+ const handleClick = () => {
62
+ posthog.capture('button_clicked', { button_name: 'signup' })
63
+ }
64
+
65
+ return <button onClick={handleClick}>Sign Up</button>
66
+ }
67
+ ```
68
+
69
+ #### useFeatureFlagEnabled
70
+
71
+ Check if a feature flag is enabled for the current user.
72
+
73
+ ```tsx
74
+ import { useFeatureFlagEnabled } from '@posthog/react'
75
+
76
+ function MyComponent() {
77
+ const isEnabled = useFeatureFlagEnabled('new-feature')
78
+
79
+ if (isEnabled) {
80
+ return <NewFeature />
81
+ }
82
+ return <OldFeature />
83
+ }
84
+ ```
85
+
86
+ #### useFeatureFlagVariantKey
87
+
88
+ Get the variant key for a multivariate feature flag.
89
+
90
+ ```tsx
91
+ import { useFeatureFlagVariantKey } from '@posthog/react'
92
+
93
+ function MyComponent() {
94
+ const variant = useFeatureFlagVariantKey('experiment-flag')
95
+
96
+ if (variant === 'control') {
97
+ return <ControlVariant />
98
+ }
99
+ if (variant === 'test') {
100
+ return <TestVariant />
101
+ }
102
+ return null
103
+ }
104
+ ```
105
+
106
+ #### useFeatureFlagPayload
107
+
108
+ Get the payload associated with a feature flag.
109
+
110
+ ```tsx
111
+ import { useFeatureFlagPayload } from '@posthog/react'
112
+
113
+ function MyComponent() {
114
+ const payload = useFeatureFlagPayload('feature-with-payload')
115
+
116
+ return <div>Config: {JSON.stringify(payload)}</div>
117
+ }
118
+ ```
119
+
120
+ #### useActiveFeatureFlags
121
+
122
+ Get all active feature flags for the current user.
123
+
124
+ ```tsx
125
+ import { useActiveFeatureFlags } from '@posthog/react'
126
+
127
+ function MyComponent() {
128
+ const activeFlags = useActiveFeatureFlags()
129
+
130
+ return (
131
+ <ul>
132
+ {activeFlags?.map((flag) => (
133
+ <li key={flag}>{flag}</li>
134
+ ))}
135
+ </ul>
136
+ )
137
+ }
138
+ ```
139
+
140
+ ### Components
141
+
142
+ #### PostHogFeature
143
+
144
+ A component that renders content based on a feature flag's value. Automatically tracks feature views and interactions.
145
+
146
+ ```tsx
147
+ import { PostHogFeature } from '@posthog/react'
148
+
149
+ function MyComponent() {
150
+ return (
151
+ <PostHogFeature flag="new-cta" fallback={<OldButton />}>
152
+ <NewButton />
153
+ </PostHogFeature>
154
+ )
155
+ }
156
+
157
+ // With variant matching
158
+ function MyComponent() {
159
+ return (
160
+ <PostHogFeature flag="experiment" match="test" fallback={<ControlVersion />}>
161
+ <TestVersion />
162
+ </PostHogFeature>
163
+ )
164
+ }
165
+
166
+ // With payload as render function
167
+ function MyComponent() {
168
+ return (
169
+ <PostHogFeature flag="banner-config">
170
+ {(payload) => <Banner title={payload.title} color={payload.color} />}
171
+ </PostHogFeature>
172
+ )
173
+ }
174
+ ```
175
+
176
+ #### PostHogErrorBoundary
177
+
178
+ An error boundary that captures React errors and reports them to PostHog.
179
+
180
+ ```tsx
181
+ import { PostHogErrorBoundary } from '@posthog/react'
182
+
183
+ function App() {
184
+ return (
185
+ <PostHogProvider apiKey="<YOUR_PROJECT_API_KEY>">
186
+ <PostHogErrorBoundary>
187
+ <YourApp />
188
+ </PostHogErrorBoundary>
189
+ </PostHogProvider>
190
+ )
191
+ }
192
+ ```
193
+
194
+ Please see the main [PostHog docs](https://www.posthog.com/docs).
195
+
196
+ ## Questions?
197
+
198
+ ### [Check out our community page.](https://posthog.com/posts)
@@ -0,0 +1,426 @@
1
+ import posthogJs from '@hanzo/insights';
2
+ import React, { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback, Children } from 'react';
3
+
4
+ var PostHogContext = createContext({
5
+ client: posthogJs,
6
+ bootstrap: undefined,
7
+ });
8
+
9
+ function isDeepEqual(obj1, obj2, visited) {
10
+ if (visited === void 0) { visited = new WeakMap(); }
11
+ if (obj1 === obj2) {
12
+ return true;
13
+ }
14
+ if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
15
+ return false;
16
+ }
17
+ if (visited.has(obj1) && visited.get(obj1) === obj2) {
18
+ return true;
19
+ }
20
+ visited.set(obj1, obj2);
21
+ var keys1 = Object.keys(obj1);
22
+ var keys2 = Object.keys(obj2);
23
+ if (keys1.length !== keys2.length) {
24
+ return false;
25
+ }
26
+ for (var _i = 0, keys1_1 = keys1; _i < keys1_1.length; _i++) {
27
+ var key = keys1_1[_i];
28
+ if (!keys2.includes(key)) {
29
+ return false;
30
+ }
31
+ if (!isDeepEqual(obj1[key], obj2[key], visited)) {
32
+ return false;
33
+ }
34
+ }
35
+ return true;
36
+ }
37
+
38
+ function PostHogProvider(_a) {
39
+ var _b, _c;
40
+ var children = _a.children, client = _a.client, apiKey = _a.apiKey, options = _a.options;
41
+ var previousInitializationRef = useRef(null);
42
+ var posthog = useMemo(function () {
43
+ if (client) {
44
+ if (apiKey) {
45
+ console.warn('[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`.');
46
+ }
47
+ if (options) {
48
+ console.warn('[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`.');
49
+ }
50
+ return client;
51
+ }
52
+ if (apiKey) {
53
+ return posthogJs;
54
+ }
55
+ console.warn('[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior.');
56
+ return posthogJs;
57
+ }, [client, apiKey, JSON.stringify(options)]);
58
+ useEffect(function () {
59
+ if (client) {
60
+ return;
61
+ }
62
+ var previousInitialization = previousInitializationRef.current;
63
+ if (!previousInitialization) {
64
+ if (posthogJs.__loaded) {
65
+ console.warn('[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues.');
66
+ }
67
+ posthogJs.init(apiKey, options);
68
+ previousInitializationRef.current = {
69
+ apiKey: apiKey,
70
+ options: options !== null && options !== void 0 ? options : {},
71
+ };
72
+ }
73
+ else {
74
+ if (apiKey !== previousInitialization.apiKey) {
75
+ console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop.");
76
+ }
77
+ if (options && !isDeepEqual(options, previousInitialization.options)) {
78
+ posthogJs.set_config(options);
79
+ }
80
+ previousInitializationRef.current = {
81
+ apiKey: apiKey,
82
+ options: options !== null && options !== void 0 ? options : {},
83
+ };
84
+ }
85
+ }, [client, apiKey, JSON.stringify(options)]);
86
+ return (React.createElement(PostHogContext.Provider, { value: { client: posthog, bootstrap: (_b = options === null || options === void 0 ? void 0 : options.bootstrap) !== null && _b !== void 0 ? _b : (_c = client === null || client === void 0 ? void 0 : client.config) === null || _c === void 0 ? void 0 : _c.bootstrap } }, children));
87
+ }
88
+
89
+ var isFunction = function (f) {
90
+ return typeof f === 'function';
91
+ };
92
+ var isUndefined = function (x) {
93
+ return x === void 0;
94
+ };
95
+ var isNull = function (x) {
96
+ return x === null;
97
+ };
98
+
99
+ function useFeatureFlagEnabled(flag) {
100
+ var _a, _b;
101
+ var _c = useContext(PostHogContext), client = _c.client, bootstrap = _c.bootstrap;
102
+ var _d = useState(function () { return client.isFeatureEnabled(flag); }), featureEnabled = _d[0], setFeatureEnabled = _d[1];
103
+ useEffect(function () {
104
+ return client.onFeatureFlags(function () {
105
+ setFeatureEnabled(client.isFeatureEnabled(flag));
106
+ });
107
+ }, [client, flag]);
108
+ var bootstrapped = (_a = bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlags) === null || _a === void 0 ? void 0 : _a[flag];
109
+ if (!((_b = client === null || client === void 0 ? void 0 : client.featureFlags) === null || _b === void 0 ? void 0 : _b.hasLoadedFlags) && (bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlags)) {
110
+ return isUndefined(bootstrapped) ? undefined : !!bootstrapped;
111
+ }
112
+ return featureEnabled;
113
+ }
114
+
115
+ function useFeatureFlagPayload(flag) {
116
+ var _a;
117
+ var _b = useContext(PostHogContext), client = _b.client, bootstrap = _b.bootstrap;
118
+ var _c = useState(function () { return client.getFeatureFlagPayload(flag); }), featureFlagPayload = _c[0], setFeatureFlagPayload = _c[1];
119
+ useEffect(function () {
120
+ return client.onFeatureFlags(function () {
121
+ setFeatureFlagPayload(client.getFeatureFlagPayload(flag));
122
+ });
123
+ }, [client, flag]);
124
+ if (!((_a = client === null || client === void 0 ? void 0 : client.featureFlags) === null || _a === void 0 ? void 0 : _a.hasLoadedFlags) && (bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlagPayloads)) {
125
+ return bootstrap.featureFlagPayloads[flag];
126
+ }
127
+ return featureFlagPayload;
128
+ }
129
+
130
+ function useFeatureFlagResult(flag) {
131
+ var _a, _b;
132
+ var _c = useContext(PostHogContext), client = _c.client, bootstrap = _c.bootstrap;
133
+ var _d = useState(function () { return client.getFeatureFlagResult(flag); }), result = _d[0], setResult = _d[1];
134
+ useEffect(function () {
135
+ return client.onFeatureFlags(function () {
136
+ setResult(client.getFeatureFlagResult(flag));
137
+ });
138
+ }, [client, flag]);
139
+ if (!((_a = client === null || client === void 0 ? void 0 : client.featureFlags) === null || _a === void 0 ? void 0 : _a.hasLoadedFlags) && (bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlags)) {
140
+ var bootstrappedValue = bootstrap.featureFlags[flag];
141
+ if (isUndefined(bootstrappedValue)) {
142
+ return undefined;
143
+ }
144
+ return {
145
+ key: flag,
146
+ enabled: typeof bootstrappedValue === 'string' ? true : !!bootstrappedValue,
147
+ variant: typeof bootstrappedValue === 'string' ? bootstrappedValue : undefined,
148
+ payload: (_b = bootstrap.featureFlagPayloads) === null || _b === void 0 ? void 0 : _b[flag],
149
+ };
150
+ }
151
+ return result;
152
+ }
153
+
154
+ function useActiveFeatureFlags() {
155
+ var _a;
156
+ var _b = useContext(PostHogContext), client = _b.client, bootstrap = _b.bootstrap;
157
+ var _c = useState(function () { return client.featureFlags.getFlags(); }), featureFlags = _c[0], setFeatureFlags = _c[1];
158
+ useEffect(function () {
159
+ return client.onFeatureFlags(function (flags) {
160
+ setFeatureFlags(flags);
161
+ });
162
+ }, [client]);
163
+ if (!((_a = client === null || client === void 0 ? void 0 : client.featureFlags) === null || _a === void 0 ? void 0 : _a.hasLoadedFlags) && (bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlags)) {
164
+ return Object.keys(bootstrap.featureFlags);
165
+ }
166
+ return featureFlags;
167
+ }
168
+
169
+ function useFeatureFlagVariantKey(flag) {
170
+ var _a;
171
+ var _b = useContext(PostHogContext), client = _b.client, bootstrap = _b.bootstrap;
172
+ var _c = useState(function () {
173
+ return client.getFeatureFlag(flag);
174
+ }), featureFlagVariantKey = _c[0], setFeatureFlagVariantKey = _c[1];
175
+ useEffect(function () {
176
+ return client.onFeatureFlags(function () {
177
+ setFeatureFlagVariantKey(client.getFeatureFlag(flag));
178
+ });
179
+ }, [client, flag]);
180
+ if (!((_a = client === null || client === void 0 ? void 0 : client.featureFlags) === null || _a === void 0 ? void 0 : _a.hasLoadedFlags) && (bootstrap === null || bootstrap === void 0 ? void 0 : bootstrap.featureFlags)) {
181
+ return bootstrap.featureFlags[flag];
182
+ }
183
+ return featureFlagVariantKey;
184
+ }
185
+
186
+ var usePostHog = function () {
187
+ var client = useContext(PostHogContext).client;
188
+ return client;
189
+ };
190
+
191
+ /******************************************************************************
192
+ Copyright (c) Microsoft Corporation.
193
+
194
+ Permission to use, copy, modify, and/or distribute this software for any
195
+ purpose with or without fee is hereby granted.
196
+
197
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
198
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
199
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
200
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
201
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
202
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
203
+ PERFORMANCE OF THIS SOFTWARE.
204
+ ***************************************************************************** */
205
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
206
+
207
+ var extendStatics = function(d, b) {
208
+ extendStatics = Object.setPrototypeOf ||
209
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
210
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
211
+ return extendStatics(d, b);
212
+ };
213
+
214
+ function __extends(d, b) {
215
+ if (typeof b !== "function" && b !== null)
216
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
217
+ extendStatics(d, b);
218
+ function __() { this.constructor = d; }
219
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
220
+ }
221
+
222
+ var __assign = function() {
223
+ __assign = Object.assign || function __assign(t) {
224
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
225
+ s = arguments[i];
226
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
227
+ }
228
+ return t;
229
+ };
230
+ return __assign.apply(this, arguments);
231
+ };
232
+
233
+ function __rest(s, e) {
234
+ var t = {};
235
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
236
+ t[p] = s[p];
237
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
238
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
239
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
240
+ t[p[i]] = s[p[i]];
241
+ }
242
+ return t;
243
+ }
244
+
245
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
246
+ var e = new Error(message);
247
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
248
+ };
249
+
250
+ function VisibilityAndClickTracker(_a) {
251
+ var children = _a.children, onIntersect = _a.onIntersect, onClick = _a.onClick, trackView = _a.trackView, options = _a.options, props = __rest(_a, ["children", "onIntersect", "onClick", "trackView", "options"]);
252
+ var ref = useRef(null);
253
+ var observerOptions = useMemo(function () { return (__assign({ threshold: 0.1 }, options)); }, [options === null || options === void 0 ? void 0 : options.threshold, options === null || options === void 0 ? void 0 : options.root, options === null || options === void 0 ? void 0 : options.rootMargin]);
254
+ useEffect(function () {
255
+ if (isNull(ref.current) || !trackView)
256
+ return;
257
+ var observer = new IntersectionObserver(function (_a) {
258
+ var entry = _a[0];
259
+ return onIntersect(entry);
260
+ }, observerOptions);
261
+ observer.observe(ref.current);
262
+ return function () { return observer.disconnect(); };
263
+ }, [observerOptions, trackView, onIntersect]);
264
+ return (React.createElement("div", __assign({ ref: ref }, props, { onClick: onClick }), children));
265
+ }
266
+
267
+ function VisibilityAndClickTrackers(_a) {
268
+ var children = _a.children, trackInteraction = _a.trackInteraction, trackView = _a.trackView, options = _a.options, onInteract = _a.onInteract, onView = _a.onView, props = __rest(_a, ["children", "trackInteraction", "trackView", "options", "onInteract", "onView"]);
269
+ var clickTrackedRef = useRef(false);
270
+ var visibilityTrackedRef = useRef(false);
271
+ var cachedOnClick = useCallback(function () {
272
+ if (!clickTrackedRef.current && trackInteraction && onInteract) {
273
+ onInteract();
274
+ clickTrackedRef.current = true;
275
+ }
276
+ }, [trackInteraction, onInteract]);
277
+ var onIntersect = function (entry) {
278
+ if (!visibilityTrackedRef.current && entry.isIntersecting && onView) {
279
+ onView();
280
+ visibilityTrackedRef.current = true;
281
+ }
282
+ };
283
+ var trackedChildren = Children.map(children, function (child) {
284
+ return (React.createElement(VisibilityAndClickTracker, __assign({ onClick: cachedOnClick, onIntersect: onIntersect, trackView: trackView, options: options }, props), child));
285
+ });
286
+ return React.createElement(React.Fragment, null, trackedChildren);
287
+ }
288
+
289
+ function PostHogFeature(_a) {
290
+ var flag = _a.flag, match = _a.match, children = _a.children, fallback = _a.fallback, visibilityObserverOptions = _a.visibilityObserverOptions, trackInteraction = _a.trackInteraction, trackView = _a.trackView, props = __rest(_a, ["flag", "match", "children", "fallback", "visibilityObserverOptions", "trackInteraction", "trackView"]);
291
+ var payload = useFeatureFlagPayload(flag);
292
+ var variant = useFeatureFlagVariantKey(flag);
293
+ var posthog = usePostHog();
294
+ var shouldTrackInteraction = trackInteraction !== null && trackInteraction !== void 0 ? trackInteraction : true;
295
+ var shouldTrackView = trackView !== null && trackView !== void 0 ? trackView : true;
296
+ if (!isUndefined(variant)) {
297
+ if (isUndefined(match) || variant === match) {
298
+ var childNode = isFunction(children) ? children(payload) : children;
299
+ return (React.createElement(VisibilityAndClickTrackers, __assign({ flag: flag, options: visibilityObserverOptions, trackInteraction: shouldTrackInteraction, trackView: shouldTrackView, onInteract: function () { return captureFeatureInteraction({ flag: flag, posthog: posthog, flagVariant: variant }); }, onView: function () { return captureFeatureView({ flag: flag, posthog: posthog, flagVariant: variant }); } }, props), childNode));
300
+ }
301
+ }
302
+ return React.createElement(React.Fragment, null, fallback);
303
+ }
304
+ function captureFeatureInteraction(_a) {
305
+ var _b;
306
+ var flag = _a.flag, posthog = _a.posthog, flagVariant = _a.flagVariant;
307
+ var properties = {
308
+ feature_flag: flag,
309
+ $set: (_b = {}, _b["$feature_interaction/".concat(flag)] = flagVariant !== null && flagVariant !== void 0 ? flagVariant : true, _b),
310
+ };
311
+ if (typeof flagVariant === 'string') {
312
+ properties.feature_flag_variant = flagVariant;
313
+ }
314
+ posthog.capture('$feature_interaction', properties);
315
+ }
316
+ function captureFeatureView(_a) {
317
+ var _b;
318
+ var flag = _a.flag, posthog = _a.posthog, flagVariant = _a.flagVariant;
319
+ var properties = {
320
+ feature_flag: flag,
321
+ $set: (_b = {}, _b["$feature_view/".concat(flag)] = flagVariant !== null && flagVariant !== void 0 ? flagVariant : true, _b),
322
+ };
323
+ if (typeof flagVariant === 'string') {
324
+ properties.feature_flag_variant = flagVariant;
325
+ }
326
+ posthog.capture('$feature_view', properties);
327
+ }
328
+
329
+ function TrackedChild(_a) {
330
+ var child = _a.child, index = _a.index, name = _a.name, properties = _a.properties, observerOptions = _a.observerOptions;
331
+ var trackedRef = useRef(false);
332
+ var posthog = usePostHog();
333
+ var onIntersect = useCallback(function (entry) {
334
+ if (entry.isIntersecting && !trackedRef.current) {
335
+ posthog.capture('$element_viewed', __assign({ element_name: name, child_index: index }, properties));
336
+ trackedRef.current = true;
337
+ }
338
+ }, [posthog, name, index, properties]);
339
+ return (React.createElement(VisibilityAndClickTracker, { onIntersect: onIntersect, trackView: true, options: observerOptions }, child));
340
+ }
341
+ function PostHogCaptureOnViewed(_a) {
342
+ var name = _a.name, properties = _a.properties, observerOptions = _a.observerOptions, trackAllChildren = _a.trackAllChildren, children = _a.children, props = __rest(_a, ["name", "properties", "observerOptions", "trackAllChildren", "children"]);
343
+ var trackedRef = useRef(false);
344
+ var posthog = usePostHog();
345
+ var onIntersect = useCallback(function (entry) {
346
+ if (entry.isIntersecting && !trackedRef.current) {
347
+ posthog.capture('$element_viewed', __assign({ element_name: name }, properties));
348
+ trackedRef.current = true;
349
+ }
350
+ }, [posthog, name, properties]);
351
+ if (trackAllChildren) {
352
+ var trackedChildren = Children.map(children, function (child, index) {
353
+ return (React.createElement(TrackedChild, { key: index, child: child, index: index, name: name, properties: properties, observerOptions: observerOptions }));
354
+ });
355
+ return React.createElement("div", __assign({}, props), trackedChildren);
356
+ }
357
+ return (React.createElement(VisibilityAndClickTracker, __assign({ onIntersect: onIntersect, trackView: true, options: observerOptions }, props), children));
358
+ }
359
+
360
+ var INITIAL_STATE = {
361
+ componentStack: null,
362
+ exceptionEvent: null,
363
+ error: null,
364
+ };
365
+ var __POSTHOG_ERROR_MESSAGES = {
366
+ INVALID_FALLBACK: '[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element.',
367
+ };
368
+ var PostHogErrorBoundary = (function (_super) {
369
+ __extends(PostHogErrorBoundary, _super);
370
+ function PostHogErrorBoundary(props) {
371
+ var _this = _super.call(this, props) || this;
372
+ _this.state = INITIAL_STATE;
373
+ return _this;
374
+ }
375
+ PostHogErrorBoundary.prototype.componentDidCatch = function (error, errorInfo) {
376
+ var additionalProperties = this.props.additionalProperties;
377
+ var currentProperties;
378
+ if (isFunction(additionalProperties)) {
379
+ currentProperties = additionalProperties(error);
380
+ }
381
+ else if (typeof additionalProperties === 'object') {
382
+ currentProperties = additionalProperties;
383
+ }
384
+ var client = this.context.client;
385
+ var exceptionEvent = client.captureException(error, currentProperties);
386
+ var componentStack = errorInfo.componentStack;
387
+ this.setState({
388
+ error: error,
389
+ componentStack: componentStack !== null && componentStack !== void 0 ? componentStack : null,
390
+ exceptionEvent: exceptionEvent,
391
+ });
392
+ };
393
+ PostHogErrorBoundary.prototype.render = function () {
394
+ var _a = this.props, children = _a.children, fallback = _a.fallback;
395
+ var state = this.state;
396
+ if (state.componentStack == null) {
397
+ return isFunction(children) ? children() : children;
398
+ }
399
+ var element = isFunction(fallback)
400
+ ? React.createElement(fallback, {
401
+ error: state.error,
402
+ componentStack: state.componentStack,
403
+ exceptionEvent: state.exceptionEvent,
404
+ })
405
+ : fallback;
406
+ if (React.isValidElement(element)) {
407
+ return element;
408
+ }
409
+ console.warn(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK);
410
+ return React.createElement(React.Fragment, null);
411
+ };
412
+ PostHogErrorBoundary.contextType = PostHogContext;
413
+ return PostHogErrorBoundary;
414
+ }(React.Component));
415
+
416
+ var setupReactErrorHandler = function (client, callback) {
417
+ return function (error, errorInfo) {
418
+ var event = client.captureException(error);
419
+ if (callback) {
420
+ callback(event, error, errorInfo);
421
+ }
422
+ };
423
+ };
424
+
425
+ export { PostHogCaptureOnViewed, PostHogContext, PostHogErrorBoundary, PostHogFeature, PostHogProvider, captureFeatureInteraction, captureFeatureView, setupReactErrorHandler, useActiveFeatureFlags, useFeatureFlagEnabled, useFeatureFlagPayload, useFeatureFlagResult, useFeatureFlagVariantKey, usePostHog };
426
+ //# sourceMappingURL=index.js.map