UNPKG

solid-posthog

Version:

Allows you to PostHog within SolidJS

100 lines (95 loc) 3.22 kB
import posthog2 from 'posthog-js'; import { createContext, createSignal, createMemo, onMount, useContext } from 'solid-js'; import { createComponent } from 'solid-js/web'; // src/context/PostHogContext.ts var PostHogContext = createContext({ client: posthog2 }); // src/utils/object-utils.ts function isDeepEqual(obj1, obj2, visited = /* @__PURE__ */ new WeakMap()) { if (obj1 === obj2) { return true; } if (typeof obj1 !== "object" || obj1 === null || typeof obj2 !== "object" || obj2 === null) { return false; } if (visited.has(obj1) && visited.get(obj1) === obj2) { return true; } visited.set(obj1, obj2); const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) { return false; } for (const key of keys1) { if (!keys2.includes(key)) { return false; } if (!isDeepEqual(obj1[key], obj2[key], visited)) { return false; } } return true; } // src/context/PostHogProvider.tsx function PostHogProvider({ children, client, apiKey, options }) { const [previousInitialization, setPreviousInitialization] = createSignal(null); const postHogJs = createMemo(() => { if (client) { if (apiKey) { console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."); } if (options) { console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."); return client; } } if (apiKey) { return posthog2; } 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."); return posthog2; }, [client, apiKey, JSON.stringify(options)]); onMount(() => { if (client) return; const prev = previousInitialization(); if (!prev) { if (posthog2.__loaded) { console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."); } posthog2.init(apiKey, options); setPreviousInitialization({ apiKey, options: options ?? {} }); } else { if (apiKey !== prev.apiKey) { 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."); } if (options && !isDeepEqual(options, prev.options)) { posthog2.set_config(options); } setPreviousInitialization({ apiKey, options: options ?? {} }); } }); return createComponent(PostHogContext.Provider, { get value() { return { client: postHogJs() }; }, children }); } var usePostHog = () => { const { client } = useContext(PostHogContext); return client; }; export { PostHogContext, PostHogProvider, usePostHog };