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.

22.0 KB
Raw Blame
import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, events, kea, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { getSingularType } from 'lib/components/DefinitionPopover/utils'
import { resolvePropertyDefinitionId } from 'lib/components/PropertyFilters/utils'
import { getDataWarehouseItemWithFieldDefaults } from 'lib/components/TaxonomicFilter/dataWarehouseItemUtils'
import { TaxonomicDefinitionTypes, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { actionsModel } from '~/models/actionsModel'
import { cohortsModel, getReferencedCohortIds, isIndividualInsightPath } from '~/models/cohortsModel'
import { propertyDefinitionsModel, updatePropertyDefinitions } from '~/models/propertyDefinitionsModel'
import { ActionType, CohortType, EventDefinition, PropertyDefinition } from '~/types'

import { DataWarehouseTableForInsight } from 'products/data_warehouse/frontend/types'

import type { PropertyDefinitionType } from '../../../types'
import type { TaxonomicFilterValue } from '../TaxonomicFilter/types'

const IS_TEST_MODE = process.env.NODE_ENV === 'test'

export enum DefinitionPopoverState {
    Edit = 'edit',
    View = 'view',
}

export interface DefinitionPopoverLogicProps {
    /* String type accounts for types with `TaxonomicFilterGroupType.GroupsPrefix` prefix */
    type: TaxonomicFilterGroupType | string
    selectedItemMeta?: Record<string, any> | null
    /* Callback to update specific item in in-memory list */
    updateRemoteItem?: (item: TaxonomicDefinitionTypes) => void
    onCancel?: () => void
    onSave?: () => void
    hideView?: boolean
    hideEdit?: boolean
    openDetailInNewTab?: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionPopoverLogicValues {
    getPropertyDefinition: (
        s: TaxonomicFilterValue,
        type: PropertyDefinitionType,
        groupTypeIndex?: number
    ) => PropertyDefinition | null // propertyDefinitionsModel
    currentProjectId: number | string // teamLogic
    definition: Partial<TaxonomicDefinitionTypes>
    definitionLoading: boolean
    dirty: boolean
    hasSentAs: any
    hideEdit: any
    hideView: any
    isAction: boolean
    isCohort: boolean
    isDataWarehouse: boolean
    isDataWarehousePersonProperty: boolean
    isEvent: boolean
    isProperty: any
    isViewable: boolean
    isVirtual: boolean | undefined
    localDefinition: Partial<TaxonomicDefinitionTypes>
    mediaPreviews: string[]
    openDetailInNewTab: any
    resolvedDefinition: Partial<TaxonomicDefinitionTypes>
    singularType: string
    state: DefinitionPopoverState
    type: any
    viewFullDetailUrl: string | undefined
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionPopoverLogicActions {
    handleCancel: () => {
        value: true
    }
    handleSave: (_: any) => any
    handleSaveFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    handleSaveSuccess: (
        definition: Partial<TaxonomicDefinitionTypes>,
        payload?: any
    ) => {
        definition: Partial<TaxonomicDefinitionTypes>
        payload?: any
    }
    recordHoverActivity: () => {
        value: true
    }
    setDefinition: (item: Partial<TaxonomicDefinitionTypes>) => {
        isDataWarehouse: boolean
        item: Partial<TaxonomicDefinitionTypes>
        selectedItemMeta: Record<string, any> | null | undefined
    }
    setDefinitionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setDefinitionSuccess: (
        definition: TaxonomicDefinitionTypes,
        payload?: {
            isDataWarehouse: boolean
            item: Partial<TaxonomicDefinitionTypes>
            selectedItemMeta: Record<string, any> | null | undefined
        }
    ) => {
        definition: TaxonomicDefinitionTypes
        payload?: {
            isDataWarehouse: boolean
            item: Partial<TaxonomicDefinitionTypes>
            selectedItemMeta: Record<string, any> | null | undefined
        }
    }
    setLocalDefinition: (item: Partial<TaxonomicDefinitionTypes>) => {
        item: Partial<TaxonomicDefinitionTypes>
    }
    setPopoverState: (state: DefinitionPopoverState) => {
        state: DefinitionPopoverState
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface definitionPopoverLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        type: (arg: any) => any
        hideView: (arg: any) => any
        hideEdit: (arg: any) => any
        openDetailInNewTab: (arg: any) => any
        singularType: (type: any) => string
        mediaPreviews: (definition: Partial<TaxonomicDefinitionTypes>) => string[]
        dirty: (
            state: DefinitionPopoverState,
            definition: Partial<TaxonomicDefinitionTypes>,
            localDefinition: Partial<TaxonomicDefinitionTypes>
        ) => boolean
        isViewable: (type: any) => boolean
        isAction: (type: any) => boolean
        isEvent: (type: any) => boolean
        isProperty: (type: any) => any
        isVirtual: (definition: Partial<TaxonomicDefinitionTypes>) => boolean | undefined
        hasSentAs: (type: any, isProperty: any, isEvent: boolean, isVirtual: boolean | undefined) => any
        isCohort: (type: any) => boolean
        isDataWarehouse: (type: any) => boolean
        isDataWarehousePersonProperty: (type: any) => boolean
        resolvedDefinition: (
            definition: Partial<TaxonomicDefinitionTypes>,
            isProperty: any,
            type: any,
            getPropertyDefinition: (
                s: TaxonomicFilterValue,
                type: PropertyDefinitionType,
                groupTypeIndex?: number
            ) => PropertyDefinition | null
        ) => Partial<TaxonomicDefinitionTypes>
        viewFullDetailUrl: (
            resolvedDefinition: Partial<TaxonomicDefinitionTypes>,
            isAction: boolean,
            isEvent: boolean,
            isProperty: any,
            isCohort: boolean
        ) => string | undefined
    }
}

export type definitionPopoverLogicType = MakeLogicType<
    definitionPopoverLogicValues,
    definitionPopoverLogicActions,
    DefinitionPopoverLogicProps,
    definitionPopoverLogicMeta
>

export const definitionPopoverLogic = kea<definitionPopoverLogicType>([
    props({} as DefinitionPopoverLogicProps),
    path(['lib', 'components', 'DefinitionPanel', 'definitionPopoverLogic']),
    connect(() => ({
        values: [teamLogic, ['currentProjectId'], propertyDefinitionsModel, ['getPropertyDefinition']],
    })),
    actions(({ values, props }) => ({
        setDefinition: (item: Partial<TaxonomicDefinitionTypes>) => ({
            item,
            isDataWarehouse: values.isDataWarehouse,
            selectedItemMeta: props.selectedItemMeta,
        }),
        setLocalDefinition: (item: Partial<TaxonomicDefinitionTypes>) => ({ item }),
        setPopoverState: (state: DefinitionPopoverState) => ({ state }),
        handleCancel: true,
        recordHoverActivity: true,
    })),
    loaders(({ values, props, cache }) => ({
        definition: [
            {} as Partial<TaxonomicDefinitionTypes>,
            {
                setDefinition: ({ item }) => item as TaxonomicDefinitionTypes,
                handleSave: async (_, breakpoint) => {
                    if (!values.definition) {
                        return {}
                    }

                    // resolvedDefinition carries the recovered id for name-only pinned/default
                    // property items, so Save PATCHes the real definition instead of /undefined.
                    let definition = {
                        ...values.resolvedDefinition,
                        ...values.localDefinition,
                    } as TaxonomicDefinitionTypes
                    cache.startTime = performance.now()
                    try {
                        if (values.isAction) {
                            // Action Definitions
                            const _action = definition as ActionType
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use actionsPartialUpdate() from 'products/actions/frontend/generated/api' instead.
                            definition = await api.update(
                                `api/projects/${values.currentProjectId}/actions/${_action.id}`,
                                _action
                            )
                            actionsModel.findMounted()?.actions.updateAction(definition as ActionType)
                        } else if (values.isEvent) {
                            // Event Definitions
                            const _event = definition as EventDefinition
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use eventDefinitionsPartialUpdate() from 'products/event_definitions/frontend/generated/api' instead.
                            definition = await api.update(
                                `api/projects/${values.currentProjectId}/event_definitions/${_event.id}`,
                                {
                                    ..._event,
                                    owner: _event.owner?.id ?? null,
                                    verified: !!_event.verified,
                                }
                            )
                        } else if (
                            values.type === TaxonomicFilterGroupType.EventProperties ||
                            values.type === TaxonomicFilterGroupType.EventFeatureFlags
                        ) {
                            // Event Property Definitions
                            const _eventProperty = definition as PropertyDefinition
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use propertyDefinitionsPartialUpdate() from '~/generated/core/api' instead.
                            definition = await api.update(
                                `api/projects/${values.currentProjectId}/property_definitions/${_eventProperty.id}`,
                                _eventProperty
                            )
                            updatePropertyDefinitions({
                                [`event/${definition.name}`]: definition as PropertyDefinition,
                            })
                        } else if (values.type === TaxonomicFilterGroupType.Cohorts) {
                            // Cohort
                            const _cohort = definition as CohortType
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use cohortsPartialUpdate() from 'products/cohorts/frontend/generated/api' instead.
                            definition = await api.update(
                                `api/projects/${values.currentProjectId}/cohorts/${_cohort.id}`,
                                { description: _cohort.description }
                            )
                            cohortsModel.findMounted()?.actions.updateCohort(definition as CohortType)
                        }
                    } catch (error: any) {
                        lemonToast.error(error.message)
                    }
                    breakpoint()
                    // Disregard save attempts for any other types of taxonomy groups
                    lemonToast.success(`${capitalizeFirstLetter(values.singularType)} definition saved`)
                    // Update item in infinite list
                    props.updateRemoteItem?.(definition)
                    return definition
                },
            },
        ],
    })),
    reducers(() => ({
        state: [
            DefinitionPopoverState.View as DefinitionPopoverState,
            {
                setPopoverState: (_, { state }) => state,
            },
        ],
        localDefinition: [
            {} as Partial<TaxonomicDefinitionTypes>,
            {
                setDefinition: (_, { item, isDataWarehouse, selectedItemMeta }) => {
                    if (isDataWarehouse && 'fields' in item) {
                        return getDataWarehouseItemWithFieldDefaults(
                            item as DataWarehouseTableForInsight,
                            selectedItemMeta
                        )
                    }

                    return item
                },
                setLocalDefinition: (state, { item }) =>
                    ({
                        ...state,
                        ...item,
                    }) as Partial<TaxonomicDefinitionTypes>,
            },
        ],
    })),
    selectors({
        type: [() => [(_, props) => props.type], (type) => type],
        hideView: [() => [(_, props) => props.hideView], (hideView) => hideView ?? false],
        hideEdit: [() => [(_, props) => props.hideEdit], (hideEdit) => hideEdit ?? false],
        openDetailInNewTab: [
            () => [(_, props) => props.openDetailInNewTab],
            (openDetailInNewTab) => openDetailInNewTab ?? true,
        ],
        singularType: [(s) => [s.type], (type) => getSingularType(type)],
        mediaPreviews: [
            (s) => [s.definition],
            (definition: Partial<TaxonomicDefinitionTypes>): string[] =>
                (definition as EventDefinition)?.media_preview_urls ?? [],
        ],
        dirty: [
            (s) => [s.state, s.definition, s.localDefinition],
            (
                state: DefinitionPopoverState,
                definition: Partial<TaxonomicDefinitionTypes>,
                localDefinition: Partial<TaxonomicDefinitionTypes>
            ) => state === DefinitionPopoverState.Edit && !equal(definition, localDefinition),
        ],
        isViewable: [
            (s) => [s.type],
            (type) => {
                if (
                    type === TaxonomicFilterGroupType.PersonProperties ||
                    type.startsWith(TaxonomicFilterGroupType.GroupsPrefix)
                ) {
                    return true
                }

                return [
                    TaxonomicFilterGroupType.Actions,
                    TaxonomicFilterGroupType.Events,
                    TaxonomicFilterGroupType.CustomEvents,
                    TaxonomicFilterGroupType.Cohorts,
                    TaxonomicFilterGroupType.EventProperties,
                    TaxonomicFilterGroupType.EventFeatureFlags,
                ].includes(type)
            },
        ],
        isAction: [(s) => [s.type], (type) => type === TaxonomicFilterGroupType.Actions],
        isEvent: [
            (s) => [s.type],
            (type) => [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.CustomEvents].includes(type),
        ],
        isProperty: [
            (s) => [s.type],
            (type) =>
                [
                    TaxonomicFilterGroupType.PersonProperties,
                    TaxonomicFilterGroupType.EventProperties,
                    TaxonomicFilterGroupType.SessionProperties,
                    TaxonomicFilterGroupType.EventFeatureFlags,
                    TaxonomicFilterGroupType.NumericalEventProperties,
                    TaxonomicFilterGroupType.Metadata,
                    TaxonomicFilterGroupType.DataWarehousePersonProperties,
                    TaxonomicFilterGroupType.RevenueAnalyticsProperties,
                    TaxonomicFilterGroupType.AccountCustomProperties,
                    TaxonomicFilterGroupType.ErrorTrackingProperties,
                ].includes(type) || type.startsWith(TaxonomicFilterGroupType.GroupsPrefix),
        ],
        isVirtual: [
            (s) => [s.definition],
            (definition: Partial<TaxonomicDefinitionTypes>) => {
                return 'virtual' in definition && definition.virtual
            },
        ],
        hasSentAs: [
            (s) => [s.type, s.isProperty, s.isEvent, s.isVirtual],
            (type, isProperty, isEvent: boolean, isVirtual: boolean | undefined) =>
                isEvent || (isProperty && !isVirtual && type !== TaxonomicFilterGroupType.SessionProperties),
        ],
        isCohort: [(s) => [s.type], (type) => type === TaxonomicFilterGroupType.Cohorts],
        isDataWarehouse: [(s) => [s.type], (type) => type === TaxonomicFilterGroupType.DataWarehouse],
        isDataWarehousePersonProperty: [
            (s) => [s.type],
            (type) => type === TaxonomicFilterGroupType.DataWarehousePersonProperties,
        ],
        resolvedDefinition: [
            (s) => [s.definition, s.isProperty, s.type, s.getPropertyDefinition],
            (
                definition: Partial<TaxonomicDefinitionTypes>,
                isProperty,
                type,
                getPropertyDefinition: (
                    s: import('lib/components/TaxonomicFilter/types').TaxonomicFilterValue,
                    type: import('~/types').PropertyDefinitionType,
                    groupTypeIndex?: number
                ) => PropertyDefinition | null
            ): Partial<TaxonomicDefinitionTypes> => {
                // Pinned/default property items are stored as { name } only. Hydrate them with the
                // saved definition id recovered from propertyDefinitionsModel so View, Edit and Save
                // all operate on a complete definition (and self-heal as the model loads) rather
                // than hitting /data-management/properties/undefined.
                if (isProperty && definition && !(definition as PropertyDefinition).id) {
                    const id = resolvePropertyDefinitionId(
                        definition as PropertyDefinition,
                        type as TaxonomicFilterGroupType,
                        getPropertyDefinition
                    )
                    if (id) {
                        // Cast because the union has numeric-id members (ActionType/CohortType);
                        // this branch only runs for property definitions (string id).
                        return { ...definition, id } as Partial<TaxonomicDefinitionTypes>
                    }
                }
                return definition
            },
        ],
        viewFullDetailUrl: [
            (s) => [s.resolvedDefinition, s.isAction, s.isEvent, s.isProperty, s.isCohort],
            (
                resolvedDefinition: Partial<TaxonomicDefinitionTypes>,
                isAction: boolean,
                isEvent: boolean,
                isProperty,
                isCohort: boolean
            ) => {
                if (isAction) {
                    const id = (resolvedDefinition as ActionType).id
                    return id != null ? urls.action(id) : undefined
                } else if (isEvent) {
                    const id = (resolvedDefinition as EventDefinition).id
                    return id ? urls.eventDefinition(id) : undefined
                } else if (isProperty) {
                    const id = (resolvedDefinition as PropertyDefinition).id
                    return id ? urls.propertyDefinition(id) : undefined
                } else if (isCohort) {
                    const id = (resolvedDefinition as CohortType).id
                    return id != null ? urls.cohort(id) : undefined
                }
                return undefined
            },
        ],
    }),
    listeners(({ actions, selectors, values, props, cache }) => ({
        setDefinition: ({ item }, __, ___, previousState) => {
            if (values.isCohort && isIndividualInsightPath(router.values.location.pathname)) {
                const ids = getReferencedCohortIds((item as Partial<CohortType>).filters)
                if (ids.length) {
                    cohortsModel.findMounted()?.actions.loadCohortsByIds({ ids })
                }
            }
            // Reset definition popover to view mode if context is switched
            if (
                selectors.definition(previousState)?.name &&
                values.definition?.name !== selectors.definition(previousState).name
            ) {
                actions.setPopoverState(DefinitionPopoverState.View)
                actions.recordHoverActivity()
            }
        },
        handleSave: () => {
            actions.setPopoverState(DefinitionPopoverState.View)
            props?.onSave?.()
        },
        handleSaveSuccess: () => {
            if (cache.startTime !== undefined) {
                posthog.capture('definition save succeeded', {
                    type: values.type,
                    load_time: performance.now() - cache.startTime,
                })
                cache.startTime = undefined
            }
        },
        handleSaveFailure: ({ error }) => {
            if (cache.startTime !== undefined) {
                posthog.capture('definition save failed', {
                    type: values.type,
                    load_time: performance.now() - cache.startTime,
                    error: error,
                })
                cache.startTime = undefined
            }
        },
        handleCancel: () => {
            actions.setPopoverState(DefinitionPopoverState.View)
            actions.setLocalDefinition(values.definition)
            props?.onCancel?.()
            posthog.capture('definition cancelled', { type: values.type })
        },
        recordHoverActivity: async (_, breakpoint) => {
            await breakpoint(IS_TEST_MODE ? 1 : 1000) // Tests will wait for all breakpoints to finish
            posthog.capture('definition hovered', {
                type: values.type,
                media_preview_count: values.mediaPreviews.length ?? 0,
            })
        },
    })),
    events(({ actions }) => ({
        afterMount: () => {
            actions.recordHoverActivity()
        },
    })),
])