UNPKG

posthog-tours

Version:

A TypeScript package for creating guided tours in PostHog

64 lines (63 loc) 2.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PostHogTours = void 0; const posthog_js_1 = __importDefault(require("posthog-js")); const types_1 = require("./types"); class PostHogTours { constructor(options) { this.observers = new Map(); this.posthog = options.posthogInstance || posthog_js_1.default; this.tours = options.tours; // Check if PostHog is initialized if (!this.posthog.__loaded) { throw new types_1.PostHogNotInitializedError(); } // Validate that all provided feature flags exist this.validateFeatureFlags(); // Start monitoring first steps of all tours this.startMonitoringFirstSteps(); } validateFeatureFlags() { const missingFlags = Object.keys(this.tours).filter(flag => !this.posthog.isFeatureEnabled(flag)); if (missingFlags.length > 0) { throw new types_1.PostHogFeatureFlagsNotConfiguredError(missingFlags); } } startMonitoringFirstSteps() { Object.entries(this.tours).forEach(([flagKey, tour]) => { const firstStep = tour.steps[0]; if (firstStep === null || firstStep === void 0 ? void 0 : firstStep.target) { this.monitorElement(flagKey, firstStep.target); } }); } monitorElement(flagKey, selector) { // Check if element already exists const element = document.querySelector(selector); if (element) { console.log(`First step target found for tour "${flagKey}":`, selector); return; } // Set up observer to watch for the element const observer = new MutationObserver((mutations, obs) => { const element = document.querySelector(selector); if (element) { console.log(`First step target found for tour "${flagKey}":`, selector); obs.disconnect(); this.observers.delete(flagKey); } }); observer.observe(document.body, { childList: true, subtree: true }); this.observers.set(flagKey, observer); } getTourConfig(flagKey) { return this.tours[flagKey]; } } exports.PostHogTours = PostHogTours;