@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.
- package/LICENSE +21 -0
- package/README.md +198 -0
- package/dist/esm/index.js +426 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/surveys/index.js +98 -0
- package/dist/esm/surveys/index.js.map +1 -0
- package/dist/types/index.d.ts +96 -0
- package/dist/types/surveys/index.d.ts +19 -0
- package/dist/umd/index.js +449 -0
- package/dist/umd/index.js.map +1 -0
- package/dist/umd/surveys/index.js +107 -0
- package/dist/umd/surveys/index.js.map +1 -0
- package/package.json +64 -0
- package/src/components/PostHogCaptureOnViewed.tsx +126 -0
- package/src/components/PostHogErrorBoundary.tsx +89 -0
- package/src/components/PostHogFeature.tsx +91 -0
- package/src/components/__tests__/PostHogCaptureOnViewed.test.tsx +110 -0
- package/src/components/__tests__/PostHogErrorBoundary.test.tsx +110 -0
- package/src/components/__tests__/PostHogFeature.test.tsx +291 -0
- package/src/components/index.ts +7 -0
- package/src/components/internal/VisibilityAndClickTracker.tsx +49 -0
- package/src/components/internal/VisibilityAndClickTrackers.tsx +60 -0
- package/src/context/PostHogContext.ts +9 -0
- package/src/context/PostHogProvider.tsx +136 -0
- package/src/context/__tests__/PostHogContext.test.tsx +35 -0
- package/src/context/__tests__/PostHogProvider.test.tsx +131 -0
- package/src/context/index.ts +2 -0
- package/src/helpers/error-helpers.ts +15 -0
- package/src/helpers/index.ts +1 -0
- package/src/hooks/__tests__/featureFlags.test.tsx +273 -0
- package/src/hooks/__tests__/usePostHog.test.tsx +19 -0
- package/src/hooks/__tests__/useThumbSurvey.test.tsx +105 -0
- package/src/hooks/index.ts +6 -0
- package/src/hooks/useActiveFeatureFlags.ts +21 -0
- package/src/hooks/useFeatureFlagEnabled.ts +24 -0
- package/src/hooks/useFeatureFlagPayload.ts +22 -0
- package/src/hooks/useFeatureFlagResult.ts +31 -0
- package/src/hooks/useFeatureFlagVariantKey.ts +22 -0
- package/src/hooks/usePostHog.ts +7 -0
- package/src/hooks/useThumbSurvey.ts +146 -0
- package/src/index.ts +4 -0
- package/src/surveys/index.ts +1 -0
- package/src/utils/__tests__/object-utils.test.ts +42 -0
- package/src/utils/object-utils.ts +36 -0
- package/src/utils/type-utils.ts +16 -0
- package/surveys/package.json +7 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../../node_modules/.pnpm/@rollup+plugin-typescript@12.1.4_rollup@4.53.3_tslib@2.8.1_typescript@5.8.2/node_modules/tslib/tslib.es6.js","../../../src/context/PostHogContext.ts","../../../src/hooks/usePostHog.ts","../../../src/hooks/useThumbSurvey.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nvar ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n};\r\n",null,null,null],"names":["createContext","posthogJs","useContext","SurveyPosition","useState","useMemo","useRef","useCallback","SurveyEventName","SurveyEventProperties","useEffect","DisplaySurveyType"],"mappings":";;;;;;;;;;IAAA;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AAiBA;IACO,IAAI,QAAQ,GAAG,WAAW;IACjC,IAAI,QAAQ,GAAG,MAAM,CAAC,MAAM,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE;IACrD,QAAQ,KAAK,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IAC7D,YAAY,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;IAC7B,YAAY,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACzF,SAAS;IACT,QAAQ,OAAO,CAAC,CAAC;IACjB,MAAK;IACL,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IAC3C,EAAC;AA+RD;IACuB,OAAO,eAAe,KAAK,UAAU,GAAG,eAAe,GAAG,UAAU,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE;IACvH,IA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,EAAE,YAAY,CAAC,CAC7E,CAAA;IAED,IAAA,OAAA,QAAA,CAAA,EACI,OAAO,EAAA,OAAA,EACP,QAAQ,EAAE,SAAS,EACnB,UAAU,EAAA,UAAA,EACP,GAAC,wBAAwB,IAAI,EAAE,UAAU,EAAA,UAAA,EAAE,EACjD,CAAA;IACL;;;;;;;;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hanzo/insights-react",
|
|
3
|
+
"version": "1.8.1",
|
|
4
|
+
"description": "Provides components and hooks for React integrations of PostHog.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/PostHog/posthog-js.git",
|
|
8
|
+
"directory": "packages/react"
|
|
9
|
+
},
|
|
10
|
+
"author": "hey@posthog.com",
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"homepage": "https://posthog.com/docs/libraries/react",
|
|
13
|
+
"main": "dist/umd/index.js",
|
|
14
|
+
"module": "dist/esm/index.js",
|
|
15
|
+
"types": "dist/types/index.d.ts",
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src",
|
|
19
|
+
"surveys"
|
|
20
|
+
],
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@types/react": ">=16.8.0",
|
|
23
|
+
"@hanzo/insights": ">=1.257.2",
|
|
24
|
+
"react": ">=16.8.0"
|
|
25
|
+
},
|
|
26
|
+
"peerDependenciesMeta": {
|
|
27
|
+
"@types/react": {
|
|
28
|
+
"optional": true
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@babel/preset-env": "^7.27.1",
|
|
33
|
+
"@babel/preset-react": "^7.27.1",
|
|
34
|
+
"@babel/preset-typescript": "^7.27.1",
|
|
35
|
+
"@rollup/plugin-inject": "^4.0.2",
|
|
36
|
+
"@rollup/plugin-replace": "^2.3.4",
|
|
37
|
+
"@testing-library/dom": "^10.4.1",
|
|
38
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
39
|
+
"@testing-library/react": "^16.3.0",
|
|
40
|
+
"@types/react": "^19.2.7",
|
|
41
|
+
"@types/jest": "^29.5.14",
|
|
42
|
+
"cross-env": "^7.0.3",
|
|
43
|
+
"jest": "29.7.0",
|
|
44
|
+
"jest-environment-jsdom": "^29.7.0",
|
|
45
|
+
"react": "^19.2.1",
|
|
46
|
+
"react-dom": "^19.2.1",
|
|
47
|
+
"react-test-renderer": "^19.2.1",
|
|
48
|
+
"rollup": "^2.35.1",
|
|
49
|
+
"rollup-plugin-copy": "^3.5.0",
|
|
50
|
+
"tslib": "^2.5.0",
|
|
51
|
+
"typescript": "5.8.2",
|
|
52
|
+
"@hanzo/insights-tooling-rollup-utils": "1.1.1",
|
|
53
|
+
"@hanzo/insights": "1.357.1"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"clean": "rimraf dist",
|
|
57
|
+
"build": "rollup -c",
|
|
58
|
+
"dev": "rollup -cw",
|
|
59
|
+
"test:unit": "jest",
|
|
60
|
+
"lint": "eslint src",
|
|
61
|
+
"test:debug": "jest --runInBand",
|
|
62
|
+
"package": "pnpm pack --out $PACKAGE_DEST/%s.tgz"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import React, { Children, useCallback, useRef, JSX } from 'react'
|
|
2
|
+
import { usePostHog } from '../hooks'
|
|
3
|
+
import { VisibilityAndClickTracker } from './internal/VisibilityAndClickTracker'
|
|
4
|
+
|
|
5
|
+
export type PostHogCaptureOnViewedProps = React.HTMLProps<HTMLDivElement> & {
|
|
6
|
+
name?: string
|
|
7
|
+
properties?: Record<string, any>
|
|
8
|
+
observerOptions?: IntersectionObserverInit
|
|
9
|
+
trackAllChildren?: boolean
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function TrackedChild({
|
|
13
|
+
child,
|
|
14
|
+
index,
|
|
15
|
+
name,
|
|
16
|
+
properties,
|
|
17
|
+
observerOptions,
|
|
18
|
+
}: {
|
|
19
|
+
child: React.ReactNode
|
|
20
|
+
index: number
|
|
21
|
+
name?: string
|
|
22
|
+
properties?: Record<string, any>
|
|
23
|
+
observerOptions?: IntersectionObserverInit
|
|
24
|
+
}): JSX.Element {
|
|
25
|
+
const trackedRef = useRef(false)
|
|
26
|
+
const posthog = usePostHog()
|
|
27
|
+
|
|
28
|
+
const onIntersect = useCallback(
|
|
29
|
+
(entry: IntersectionObserverEntry) => {
|
|
30
|
+
if (entry.isIntersecting && !trackedRef.current) {
|
|
31
|
+
posthog.capture('$element_viewed', {
|
|
32
|
+
element_name: name,
|
|
33
|
+
child_index: index,
|
|
34
|
+
...properties,
|
|
35
|
+
})
|
|
36
|
+
trackedRef.current = true
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
[posthog, name, index, properties]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
return (
|
|
43
|
+
<VisibilityAndClickTracker onIntersect={onIntersect} trackView={true} options={observerOptions}>
|
|
44
|
+
{child}
|
|
45
|
+
</VisibilityAndClickTracker>
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* PostHogCaptureOnViewed - Track when elements are scrolled into view
|
|
51
|
+
*
|
|
52
|
+
* Wraps any children and automatically sends a `$element_viewed` event to PostHog
|
|
53
|
+
* when the element comes into the viewport. Only fires once per component instance.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```tsx
|
|
57
|
+
* <PostHogCaptureOnViewed name="hero-banner">
|
|
58
|
+
* <div>Important content here</div>
|
|
59
|
+
* </PostHogCaptureOnViewed>
|
|
60
|
+
*
|
|
61
|
+
* // With custom properties
|
|
62
|
+
* <PostHogCaptureOnViewed
|
|
63
|
+
* name="product-card"
|
|
64
|
+
* properties={{ product_id: '123', category: 'electronics' }}
|
|
65
|
+
* >
|
|
66
|
+
* <ProductCard />
|
|
67
|
+
* </PostHogCaptureOnViewed>
|
|
68
|
+
*
|
|
69
|
+
* // With custom intersection observer options
|
|
70
|
+
* <PostHogCaptureOnViewed
|
|
71
|
+
* name="footer"
|
|
72
|
+
* observerOptions={{ threshold: 0.5 }}
|
|
73
|
+
* >
|
|
74
|
+
* <Footer />
|
|
75
|
+
* </PostHogCaptureOnViewed>
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export function PostHogCaptureOnViewed({
|
|
79
|
+
name,
|
|
80
|
+
properties,
|
|
81
|
+
observerOptions,
|
|
82
|
+
trackAllChildren,
|
|
83
|
+
children,
|
|
84
|
+
...props
|
|
85
|
+
}: PostHogCaptureOnViewedProps): JSX.Element {
|
|
86
|
+
const trackedRef = useRef(false)
|
|
87
|
+
const posthog = usePostHog()
|
|
88
|
+
|
|
89
|
+
const onIntersect = useCallback(
|
|
90
|
+
(entry: IntersectionObserverEntry) => {
|
|
91
|
+
if (entry.isIntersecting && !trackedRef.current) {
|
|
92
|
+
posthog.capture('$element_viewed', {
|
|
93
|
+
element_name: name,
|
|
94
|
+
...properties,
|
|
95
|
+
})
|
|
96
|
+
trackedRef.current = true
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
[posthog, name, properties]
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
// If trackAllChildren is enabled, wrap each child individually
|
|
103
|
+
if (trackAllChildren) {
|
|
104
|
+
const trackedChildren = Children.map(children, (child, index) => {
|
|
105
|
+
return (
|
|
106
|
+
<TrackedChild
|
|
107
|
+
key={index}
|
|
108
|
+
child={child}
|
|
109
|
+
index={index}
|
|
110
|
+
name={name}
|
|
111
|
+
properties={properties}
|
|
112
|
+
observerOptions={observerOptions}
|
|
113
|
+
/>
|
|
114
|
+
)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
return <div {...props}>{trackedChildren}</div>
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Default behavior: track the container as a single element
|
|
121
|
+
return (
|
|
122
|
+
<VisibilityAndClickTracker onIntersect={onIntersect} trackView={true} options={observerOptions} {...props}>
|
|
123
|
+
{children}
|
|
124
|
+
</VisibilityAndClickTracker>
|
|
125
|
+
)
|
|
126
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import React, { FunctionComponent } from 'react'
|
|
2
|
+
import { PostHogContext } from '../context'
|
|
3
|
+
import { isFunction } from '../utils/type-utils'
|
|
4
|
+
|
|
5
|
+
export type Properties = Record<string, any>
|
|
6
|
+
|
|
7
|
+
export type PostHogErrorBoundaryFallbackProps = {
|
|
8
|
+
error: unknown
|
|
9
|
+
exceptionEvent: unknown
|
|
10
|
+
componentStack: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type PostHogErrorBoundaryProps = {
|
|
14
|
+
children?: React.ReactNode | (() => React.ReactNode)
|
|
15
|
+
fallback?: React.ReactNode | FunctionComponent<PostHogErrorBoundaryFallbackProps>
|
|
16
|
+
additionalProperties?: Properties | ((error: unknown) => Properties)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type PostHogErrorBoundaryState = {
|
|
20
|
+
componentStack: string | null
|
|
21
|
+
exceptionEvent: unknown
|
|
22
|
+
error: unknown
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const INITIAL_STATE: PostHogErrorBoundaryState = {
|
|
26
|
+
componentStack: null,
|
|
27
|
+
exceptionEvent: null,
|
|
28
|
+
error: null,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const __POSTHOG_ERROR_MESSAGES = {
|
|
32
|
+
INVALID_FALLBACK:
|
|
33
|
+
'[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element.',
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class PostHogErrorBoundary extends React.Component<PostHogErrorBoundaryProps, PostHogErrorBoundaryState> {
|
|
37
|
+
static contextType = PostHogContext
|
|
38
|
+
declare context: React.ContextType<typeof PostHogContext>
|
|
39
|
+
|
|
40
|
+
constructor(props: PostHogErrorBoundaryProps) {
|
|
41
|
+
super(props)
|
|
42
|
+
this.state = INITIAL_STATE
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
componentDidCatch(error: unknown, errorInfo: React.ErrorInfo) {
|
|
46
|
+
//eslint-disable-next-line react/prop-types
|
|
47
|
+
const { additionalProperties } = this.props
|
|
48
|
+
let currentProperties
|
|
49
|
+
if (isFunction(additionalProperties)) {
|
|
50
|
+
currentProperties = additionalProperties(error)
|
|
51
|
+
} else if (typeof additionalProperties === 'object') {
|
|
52
|
+
currentProperties = additionalProperties
|
|
53
|
+
}
|
|
54
|
+
const { client } = this.context
|
|
55
|
+
const exceptionEvent = client.captureException(error, currentProperties)
|
|
56
|
+
|
|
57
|
+
const { componentStack } = errorInfo
|
|
58
|
+
this.setState({
|
|
59
|
+
error,
|
|
60
|
+
componentStack: componentStack ?? null,
|
|
61
|
+
exceptionEvent,
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
public render(): React.ReactNode {
|
|
66
|
+
//eslint-disable-next-line react/prop-types
|
|
67
|
+
const { children, fallback } = this.props
|
|
68
|
+
const state = this.state
|
|
69
|
+
|
|
70
|
+
if (state.componentStack == null) {
|
|
71
|
+
return isFunction(children) ? children() : children
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const element = isFunction(fallback)
|
|
75
|
+
? (React.createElement(fallback, {
|
|
76
|
+
error: state.error,
|
|
77
|
+
componentStack: state.componentStack,
|
|
78
|
+
exceptionEvent: state.exceptionEvent,
|
|
79
|
+
}) as React.ReactNode)
|
|
80
|
+
: fallback
|
|
81
|
+
|
|
82
|
+
if (React.isValidElement(element)) {
|
|
83
|
+
return element as React.ReactElement
|
|
84
|
+
}
|
|
85
|
+
//eslint-disable-next-line no-console
|
|
86
|
+
console.warn(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK)
|
|
87
|
+
return <></>
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { useFeatureFlagPayload, useFeatureFlagVariantKey, usePostHog } from '../hooks'
|
|
2
|
+
import React, { JSX } from 'react'
|
|
3
|
+
import { PostHog } from '../context'
|
|
4
|
+
import { isFunction, isUndefined } from '../utils/type-utils'
|
|
5
|
+
import { VisibilityAndClickTrackers } from './internal/VisibilityAndClickTrackers'
|
|
6
|
+
|
|
7
|
+
export type PostHogFeatureProps = Omit<React.HTMLProps<HTMLDivElement>, 'children'> & {
|
|
8
|
+
flag: string
|
|
9
|
+
children: React.ReactNode | ((payload: any) => React.ReactNode)
|
|
10
|
+
fallback?: React.ReactNode
|
|
11
|
+
match?: string | boolean
|
|
12
|
+
visibilityObserverOptions?: IntersectionObserverInit
|
|
13
|
+
trackInteraction?: boolean
|
|
14
|
+
trackView?: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function PostHogFeature({
|
|
18
|
+
flag,
|
|
19
|
+
match,
|
|
20
|
+
children,
|
|
21
|
+
fallback,
|
|
22
|
+
visibilityObserverOptions,
|
|
23
|
+
trackInteraction,
|
|
24
|
+
trackView,
|
|
25
|
+
...props
|
|
26
|
+
}: PostHogFeatureProps): JSX.Element | null {
|
|
27
|
+
const payload = useFeatureFlagPayload(flag)
|
|
28
|
+
const variant = useFeatureFlagVariantKey(flag)
|
|
29
|
+
const posthog = usePostHog()
|
|
30
|
+
|
|
31
|
+
const shouldTrackInteraction = trackInteraction ?? true
|
|
32
|
+
const shouldTrackView = trackView ?? true
|
|
33
|
+
|
|
34
|
+
if (!isUndefined(variant)) {
|
|
35
|
+
if (isUndefined(match) || variant === match) {
|
|
36
|
+
const childNode: React.ReactNode = isFunction(children) ? children(payload) : children
|
|
37
|
+
return (
|
|
38
|
+
<VisibilityAndClickTrackers
|
|
39
|
+
flag={flag}
|
|
40
|
+
options={visibilityObserverOptions}
|
|
41
|
+
trackInteraction={shouldTrackInteraction}
|
|
42
|
+
trackView={shouldTrackView}
|
|
43
|
+
onInteract={() => captureFeatureInteraction({ flag, posthog, flagVariant: variant })}
|
|
44
|
+
onView={() => captureFeatureView({ flag, posthog, flagVariant: variant })}
|
|
45
|
+
{...props}
|
|
46
|
+
>
|
|
47
|
+
{childNode}
|
|
48
|
+
</VisibilityAndClickTrackers>
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return <>{fallback}</>
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function captureFeatureInteraction({
|
|
56
|
+
flag,
|
|
57
|
+
posthog,
|
|
58
|
+
flagVariant,
|
|
59
|
+
}: {
|
|
60
|
+
flag: string
|
|
61
|
+
posthog: PostHog
|
|
62
|
+
flagVariant?: string | boolean
|
|
63
|
+
}) {
|
|
64
|
+
const properties: Record<string, any> = {
|
|
65
|
+
feature_flag: flag,
|
|
66
|
+
$set: { [`$feature_interaction/${flag}`]: flagVariant ?? true },
|
|
67
|
+
}
|
|
68
|
+
if (typeof flagVariant === 'string') {
|
|
69
|
+
properties.feature_flag_variant = flagVariant
|
|
70
|
+
}
|
|
71
|
+
posthog.capture('$feature_interaction', properties)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function captureFeatureView({
|
|
75
|
+
flag,
|
|
76
|
+
posthog,
|
|
77
|
+
flagVariant,
|
|
78
|
+
}: {
|
|
79
|
+
flag: string
|
|
80
|
+
posthog: PostHog
|
|
81
|
+
flagVariant?: string | boolean
|
|
82
|
+
}) {
|
|
83
|
+
const properties: Record<string, any> = {
|
|
84
|
+
feature_flag: flag,
|
|
85
|
+
$set: { [`$feature_view/${flag}`]: flagVariant ?? true },
|
|
86
|
+
}
|
|
87
|
+
if (typeof flagVariant === 'string') {
|
|
88
|
+
properties.feature_flag_variant = flagVariant
|
|
89
|
+
}
|
|
90
|
+
posthog.capture('$feature_view', properties)
|
|
91
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import * as React from 'react'
|
|
2
|
+
import { render, screen } from '@testing-library/react'
|
|
3
|
+
import { PostHog, PostHogProvider } from '../../context'
|
|
4
|
+
import { PostHogCaptureOnViewed } from '../'
|
|
5
|
+
import '@testing-library/jest-dom'
|
|
6
|
+
|
|
7
|
+
describe('PostHogCaptureOnViewed component', () => {
|
|
8
|
+
let mockObserverCallback: any = null
|
|
9
|
+
|
|
10
|
+
let fakePosthog: PostHog
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
fakePosthog = {
|
|
14
|
+
capture: jest.fn(),
|
|
15
|
+
} as unknown as PostHog
|
|
16
|
+
|
|
17
|
+
const mockIntersectionObserver = jest.fn((callback) => {
|
|
18
|
+
mockObserverCallback = callback
|
|
19
|
+
return {
|
|
20
|
+
observe: jest.fn(),
|
|
21
|
+
unobserve: jest.fn(),
|
|
22
|
+
disconnect: jest.fn(),
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
mockIntersectionObserver.prototype = {}
|
|
27
|
+
// eslint-disable-next-line compat/compat
|
|
28
|
+
window.IntersectionObserver = mockIntersectionObserver as unknown as typeof IntersectionObserver
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('should render children', () => {
|
|
32
|
+
render(
|
|
33
|
+
<PostHogProvider client={fakePosthog}>
|
|
34
|
+
<PostHogCaptureOnViewed name="test-element">
|
|
35
|
+
<div data-testid="child">Hello</div>
|
|
36
|
+
</PostHogCaptureOnViewed>
|
|
37
|
+
</PostHogProvider>
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
expect(screen.getByTestId('child')).toBeInTheDocument()
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('should track when element comes into view', () => {
|
|
44
|
+
render(
|
|
45
|
+
<PostHogProvider client={fakePosthog}>
|
|
46
|
+
<PostHogCaptureOnViewed name="test-element">
|
|
47
|
+
<div data-testid="child">Hello</div>
|
|
48
|
+
</PostHogCaptureOnViewed>
|
|
49
|
+
</PostHogProvider>
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
expect(fakePosthog.capture).not.toHaveBeenCalled()
|
|
53
|
+
|
|
54
|
+
mockObserverCallback([{ isIntersecting: true }])
|
|
55
|
+
|
|
56
|
+
expect(fakePosthog.capture).toHaveBeenCalledWith('$element_viewed', {
|
|
57
|
+
element_name: 'test-element',
|
|
58
|
+
})
|
|
59
|
+
expect(fakePosthog.capture).toHaveBeenCalledTimes(1)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('should only track visibility once', () => {
|
|
63
|
+
render(
|
|
64
|
+
<PostHogProvider client={fakePosthog}>
|
|
65
|
+
<PostHogCaptureOnViewed name="test-element">
|
|
66
|
+
<div data-testid="child">Hello</div>
|
|
67
|
+
</PostHogCaptureOnViewed>
|
|
68
|
+
</PostHogProvider>
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
mockObserverCallback([{ isIntersecting: true }])
|
|
72
|
+
expect(fakePosthog.capture).toHaveBeenCalledTimes(1)
|
|
73
|
+
|
|
74
|
+
mockObserverCallback([{ isIntersecting: true }])
|
|
75
|
+
mockObserverCallback([{ isIntersecting: true }])
|
|
76
|
+
expect(fakePosthog.capture).toHaveBeenCalledTimes(1)
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('should include custom properties', () => {
|
|
80
|
+
render(
|
|
81
|
+
<PostHogProvider client={fakePosthog}>
|
|
82
|
+
<PostHogCaptureOnViewed name="test-element" properties={{ category: 'hero', priority: 'high' }}>
|
|
83
|
+
<div data-testid="child">Hello</div>
|
|
84
|
+
</PostHogCaptureOnViewed>
|
|
85
|
+
</PostHogProvider>
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
mockObserverCallback([{ isIntersecting: true }])
|
|
89
|
+
|
|
90
|
+
expect(fakePosthog.capture).toHaveBeenCalledWith('$element_viewed', {
|
|
91
|
+
element_name: 'test-element',
|
|
92
|
+
category: 'hero',
|
|
93
|
+
priority: 'high',
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('should not track when element is not intersecting', () => {
|
|
98
|
+
render(
|
|
99
|
+
<PostHogProvider client={fakePosthog}>
|
|
100
|
+
<PostHogCaptureOnViewed name="test-element">
|
|
101
|
+
<div data-testid="child">Hello</div>
|
|
102
|
+
</PostHogCaptureOnViewed>
|
|
103
|
+
</PostHogProvider>
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
mockObserverCallback([{ isIntersecting: false }])
|
|
107
|
+
|
|
108
|
+
expect(fakePosthog.capture).not.toHaveBeenCalled()
|
|
109
|
+
})
|
|
110
|
+
})
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/* eslint-disable no-console */
|
|
2
|
+
|
|
3
|
+
import * as React from 'react'
|
|
4
|
+
import { render } from '@testing-library/react'
|
|
5
|
+
import { __POSTHOG_ERROR_MESSAGES, PostHogErrorBoundary } from '../PostHogErrorBoundary'
|
|
6
|
+
import posthog from '@hanzo/insights'
|
|
7
|
+
|
|
8
|
+
describe('PostHogErrorBoundary component', () => {
|
|
9
|
+
mockFunction(console, 'error')
|
|
10
|
+
mockFunction(console, 'warn')
|
|
11
|
+
mockFunction(posthog, 'captureException')
|
|
12
|
+
|
|
13
|
+
const renderWithError = (props: any) => render(<RenderWithError {...props} />)
|
|
14
|
+
const renderWithoutError = (props?: any) => render(<RenderWithoutError {...props} />)
|
|
15
|
+
|
|
16
|
+
it('should call captureException with error message', () => {
|
|
17
|
+
const { container } = renderWithError({ message: 'Test error', fallback: <div></div> })
|
|
18
|
+
expect(posthog.captureException).toHaveBeenCalledWith(new Error('Test error'), undefined)
|
|
19
|
+
expect(container.innerHTML).toBe('<div></div>')
|
|
20
|
+
expect(console.error).toHaveBeenCalledTimes(1)
|
|
21
|
+
expect((console.error as any).mock.calls[0][1].message).toEqual('Test error')
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('should warn user when fallback is null', () => {
|
|
25
|
+
const { container } = renderWithError({ fallback: null })
|
|
26
|
+
expect(posthog.captureException).toHaveBeenCalledWith(new Error('Error'), undefined)
|
|
27
|
+
expect(container.innerHTML).toBe('')
|
|
28
|
+
expect(console.warn).toHaveBeenCalledWith(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('should warn user when fallback is a string', () => {
|
|
32
|
+
const { container } = renderWithError({ fallback: 'hello' })
|
|
33
|
+
expect(posthog.captureException).toHaveBeenCalledWith(new Error('Error'), undefined)
|
|
34
|
+
expect(container.innerHTML).toBe('')
|
|
35
|
+
expect(console.warn).toHaveBeenCalledWith(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('should add additional properties before sending event (as object)', () => {
|
|
39
|
+
const props = { team_id: '1234' }
|
|
40
|
+
renderWithError({ message: 'Kaboom', additionalProperties: props })
|
|
41
|
+
expect(posthog.captureException).toHaveBeenCalledWith(new Error('Kaboom'), props)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('should add additional properties before sending event (as function)', () => {
|
|
45
|
+
const props = { team_id: '1234' }
|
|
46
|
+
renderWithError({
|
|
47
|
+
message: 'Kaboom',
|
|
48
|
+
additionalProperties: (err: Error) => {
|
|
49
|
+
expect(err.message).toBe('Kaboom')
|
|
50
|
+
return props
|
|
51
|
+
},
|
|
52
|
+
})
|
|
53
|
+
expect(posthog.captureException).toHaveBeenCalledWith(new Error('Kaboom'), props)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('should render children without errors', () => {
|
|
57
|
+
const { container } = renderWithoutError()
|
|
58
|
+
expect(container.innerHTML).toBe('<div>Amazing content</div>')
|
|
59
|
+
})
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
describe('captureException processing', () => {
|
|
63
|
+
mockFunction(console, 'error')
|
|
64
|
+
mockFunction(console, 'warn')
|
|
65
|
+
mockFunction(posthog, 'capture')
|
|
66
|
+
|
|
67
|
+
const renderWithError = (props: any) => render(<RenderWithError {...props} />)
|
|
68
|
+
|
|
69
|
+
it('should call capture with a stacktrace', () => {
|
|
70
|
+
renderWithError({ message: 'Kaboom', fallback: <div></div>, additionalProperties: {} })
|
|
71
|
+
const captureCalls = (posthog.capture as jest.Mock).mock.calls
|
|
72
|
+
expect(captureCalls.length).toBe(1)
|
|
73
|
+
const exceptionList = captureCalls[0][1].$exception_list
|
|
74
|
+
expect(exceptionList.length).toBe(1)
|
|
75
|
+
const stacktrace = exceptionList[0].stacktrace
|
|
76
|
+
expect(stacktrace.frames.length).toBeGreaterThan(20)
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
function mockFunction(object: any, funcName: string) {
|
|
81
|
+
const originalFunc = object[funcName]
|
|
82
|
+
|
|
83
|
+
beforeEach(() => {
|
|
84
|
+
object[funcName] = jest.fn()
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
afterEach(() => {
|
|
88
|
+
object[funcName] = originalFunc
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function ComponentWithError({ message }: { message: string }): React.ReactElement {
|
|
93
|
+
throw new Error(message)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function RenderWithError({ message = 'Error', fallback, additionalProperties }: any) {
|
|
97
|
+
return (
|
|
98
|
+
<PostHogErrorBoundary fallback={fallback} additionalProperties={additionalProperties}>
|
|
99
|
+
<ComponentWithError message={message} />
|
|
100
|
+
</PostHogErrorBoundary>
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function RenderWithoutError({ additionalProperties }: any) {
|
|
105
|
+
return (
|
|
106
|
+
<PostHogErrorBoundary fallback={<div></div>} additionalProperties={additionalProperties}>
|
|
107
|
+
<div>Amazing content</div>
|
|
108
|
+
</PostHogErrorBoundary>
|
|
109
|
+
)
|
|
110
|
+
}
|