Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

8.1 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'
import { urls } from 'scenes/urls'

import { ProductKey } from '~/queries/schema/schema-general'
import type { AvailableOnboardingProducts, OnboardingProduct } from '~/types'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import { loadWelcomeEmptyState } from './welcomeEmptyState'

export interface WelcomeProduct {
    key: ProductKey
    product: OnboardingProduct
}

export type WelcomeSelection = 'ai' | ProductKey

const isWelcomeProductKey = (key: unknown): key is keyof AvailableOnboardingProducts =>
    typeof key === 'string' && Object.hasOwn(availableOnboardingProducts, key)

export const WELCOME_PRODUCTS: WelcomeProduct[] = Object.entries(availableOnboardingProducts).map(([key, product]) => ({
    key: key as ProductKey,
    product,
}))

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface onboardingWelcomeLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    aiPrompt: string
    celebratedProductKeys: ProductKey[]
    emptyStates: Partial<Record<ProductKey, SceneProductEmptyState | null>>
    selectedEmptyState: SceneProductEmptyState | null | undefined
    selectedProduct: WelcomeProduct | null
    selectedProductKey: ProductKey | null
    selection: WelcomeSelection
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface onboardingWelcomeLogicActions {
    loadEmptyState: (productKey: ProductKey) => {
        productKey: ProductKey
    }
    markCelebrated: (productKey: ProductKey) => {
        productKey: ProductKey
    }
    selectAi: () => {
        value: true
    }
    selectProduct: (
        productKey: ProductKey,
        fromUrl?: boolean
    ) => {
        fromUrl: boolean
        productKey: ProductKey
    }
    setAiPrompt: (aiPrompt: string) => {
        aiPrompt: string
    }
    setEmptyState: (
        productKey: ProductKey,
        emptyState: SceneProductEmptyState | null
    ) => {
        emptyState: SceneProductEmptyState | null
        productKey: ProductKey
    }
    submitAiPrompt: (
        prompt: string,
        fromSuggestion?: boolean
    ) => {
        fromSuggestion: boolean
        prompt: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface onboardingWelcomeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        selectedProductKey: (selection: WelcomeSelection) => ProductKey | null
        selectedProduct: (selectedProductKey: ProductKey | null) => WelcomeProduct | null
        selectedEmptyState: (
            emptyStates: Partial<Record<ProductKey, SceneProductEmptyState | null>>,
            selectedProductKey: ProductKey | null
        ) => SceneProductEmptyState | null | undefined
    }
}

export type onboardingWelcomeLogicType = MakeLogicType<
    onboardingWelcomeLogicValues,
    onboardingWelcomeLogicActions,
    Record<string, any>,
    onboardingWelcomeLogicMeta
>

export const onboardingWelcomeLogic = kea<onboardingWelcomeLogicType>([
    path(['scenes', 'onboarding', 'welcome', 'onboardingWelcomeLogic']),
    connect(() => ({
        values: [featureFlagLogic, ['featureFlags']],
    })),
    actions({
        selectAi: true,
        selectProduct: (productKey: ProductKey, fromUrl: boolean = false) => ({ productKey, fromUrl }),
        loadEmptyState: (productKey: ProductKey) => ({ productKey }),
        setEmptyState: (productKey: ProductKey, emptyState: SceneProductEmptyState | null) => ({
            productKey,
            emptyState,
        }),
        setAiPrompt: (aiPrompt: string) => ({ aiPrompt }),
        submitAiPrompt: (prompt: string, fromSuggestion: boolean = false) => ({ prompt, fromSuggestion }),
        markCelebrated: (productKey: ProductKey) => ({ productKey }),
    }),
    reducers({
        selection: [
            'ai' as WelcomeSelection,
            {
                selectAi: () => 'ai',
                selectProduct: (_, { productKey }) => productKey,
            },
        ],
        emptyStates: [
            {} as Partial<Record<ProductKey, SceneProductEmptyState | null>>,
            {
                setEmptyState: (state, { productKey, emptyState }) => ({ ...state, [productKey]: emptyState }),
            },
        ],
        aiPrompt: [
            '',
            {
                setAiPrompt: (_, { aiPrompt }) => aiPrompt,
            },
        ],
        celebratedProductKeys: [
            [] as ProductKey[],
            {
                markCelebrated: (state, { productKey }) =>
                    state.includes(productKey) ? state : [...state, productKey],
            },
        ],
    }),
    selectors({
        selectedProductKey: [
            (s) => [s.selection],
            (selection: WelcomeSelection): ProductKey | null => (selection === 'ai' ? null : selection),
        ],
        selectedProduct: [
            (s) => [s.selectedProductKey],
            (selectedProductKey: ProductKey | null): WelcomeProduct | null =>
                WELCOME_PRODUCTS.find(({ key }) => key === selectedProductKey) ?? null,
        ],
        // `undefined` while the product's setup screen loads, `null` when it has none.
        selectedEmptyState: [
            (s) => [s.emptyStates, s.selectedProductKey],
            (
                emptyStates: Partial<Record<ProductKey, SceneProductEmptyState | null>>,
                selectedProductKey: ProductKey | null
            ): SceneProductEmptyState | null | undefined =>
                selectedProductKey ? emptyStates[selectedProductKey] : undefined,
        ],
    }),
    listeners(({ actions, values }) => ({
        loadEmptyState: async ({ productKey }) => {
            // `null` can be a failed download, so only a loaded setup screen skips the next attempt.
            if (values.emptyStates[productKey]) {
                return
            }
            const emptyState = isWelcomeProductKey(productKey)
                ? await loadWelcomeEmptyState(
                      productKey,
                      availableOnboardingProducts[productKey].scene,
                      values.featureFlags
                  )
                : null
            actions.setEmptyState(productKey, emptyState)
        },
        selectProduct: ({ productKey, fromUrl }) => {
            actions.loadEmptyState(productKey)
            if (fromUrl) {
                return
            }
            // pinned: analytics event name and properties, dashboards read them
            posthog.capture('onboarding welcome product selected', { product_key: productKey })
        },
        submitAiPrompt: ({ prompt, fromSuggestion }) => {
            const trimmed = prompt.trim()
            if (!trimmed) {
                return
            }
            // pinned: analytics event name and properties, dashboards read them. The prompt itself
            // stays out of the event.
            posthog.capture('onboarding welcome ai prompt submitted', {
                from_suggestion: fromSuggestion,
                prompt_length: trimmed.length,
            })
            router.actions.push(urls.ai(undefined, trimmed))
        },
    })),
    actionToUrl(() => ({
        selectProduct: ({ productKey }) => [
            urls.onboardingWelcome(),
            { product: productKey },
            undefined,
            { replace: true },
        ],
        selectAi: () => [urls.onboardingWelcome(), {}, undefined, { replace: true }],
    })),
    urlToAction(({ actions, values }) => ({
        [urls.onboardingWelcome()]: (_, { product }) => {
            if (isWelcomeProductKey(product)) {
                if (product !== values.selection) {
                    actions.selectProduct(product, true)
                }
                return
            }
            if (values.selection !== 'ai') {
                actions.selectAi()
            }
        },
    })),
])