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.

6.9 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import { FacetOption } from 'lib/components/FacetRail/Facet'

import { metricsAttributeValuesRetrieve } from '../../generated/api'
import { canViewMetrics } from '../../metricsAccess'
import { metricsViewerLogic, resolveDate } from '../metricsViewerLogic'
import { MetricFacetConfig } from './facets'
import { metricsFacetRailLogic } from './metricsFacetRailLogic'

const FACET_VALUES_LIMIT = 50

export interface MetricsFacetValuesLogicProps {
    facet: MetricFacetConfig
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetValuesLogicValues {
    collapsedFacetKeys: string[] // metricsFacetRailLogic
    currentTeamId: number | null // metricsViewerLogic
    dateFrom: string | null // metricsViewerLogic
    dateTo: string | null // metricsViewerLogic
    metricName: string // metricsViewerLogic
    timezone: string // metricsViewerLogic
    collapsed: boolean
    facetSearch: string
    facetValues: FacetOption[]
    facetValuesLoading: boolean
    fetchFailed: boolean
    fetchScope: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetValuesLogicActions {
    liveRefreshTick: () => {
        value: true
    } // metricsViewerLogic
    loadFacetValues: (_: any) => any
    loadFacetValuesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadFacetValuesSuccess: (
        facetValues:
            | FacetOption[]
            | {
                  count: number
                  label: string
                  value: string
              }[],
        payload?: any
    ) => {
        facetValues:
            | FacetOption[]
            | {
                  count: number
                  label: string
                  value: string
              }[]
        payload?: any
    }
    retryFacetValues: () => {
        value: true
    }
    setFacetSearch: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetValuesLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        collapsed: (collapsedFacetKeys: string[], facet: MetricFacetConfig) => boolean
        fetchScope: (
            collapsed: boolean,
            metricName: string,
            dateFrom: string | null,
            dateTo: string | null,
            currentTeamId: number | null,
            facetSearch: string
        ) => string | null
    }
}

export type metricsFacetValuesLogicType = MakeLogicType<
    metricsFacetValuesLogicValues,
    metricsFacetValuesLogicActions,
    MetricsFacetValuesLogicProps,
    metricsFacetValuesLogicMeta
>

/**
 * One facet's values and data point counts for the active metric. A collapsed facet does not fetch,
 * so a metric with many attributes costs one query per facet the user opens.
 */
export const metricsFacetValuesLogic = kea<metricsFacetValuesLogicType>([
    props({} as MetricsFacetValuesLogicProps),
    key((props) => props.facet.key),
    path((key) => ['products', 'metrics', 'frontend', 'components', 'FacetRail', 'metricsFacetValuesLogic', key]),
    connect(() => ({
        values: [
            metricsViewerLogic,
            ['metricName', 'dateFrom', 'dateTo', 'timezone', 'currentTeamId'],
            metricsFacetRailLogic,
            ['collapsedFacetKeys'],
        ],
        actions: [metricsViewerLogic, ['liveRefreshTick']],
    })),
    actions({
        setFacetSearch: (search: string) => ({ search }),
        retryFacetValues: true,
    }),
    reducers({
        facetSearch: ['', { setFacetSearch: (_, { search }) => search }],
        fetchFailed: [
            false,
            {
                loadFacetValues: () => false,
                loadFacetValuesSuccess: () => false,
                loadFacetValuesFailure: () => true,
            },
        ],
    }),
    loaders(({ props, values }) => ({
        facetValues: [
            [] as FacetOption[],
            {
                loadFacetValues: async (_, breakpoint) => {
                    if (!canViewMetrics() || !values.currentTeamId) {
                        return []
                    }
                    await breakpoint(300)
                    // Collapsed while this was still debouncing: nobody can see the list, so skip the request.
                    if (values.collapsed) {
                        return values.facetValues
                    }
                    const dateFrom = resolveDate(values.dateFrom, values.timezone)
                    const dateTo = resolveDate(values.dateTo, values.timezone)
                    const response = await metricsAttributeValuesRetrieve(String(values.currentTeamId), {
                        key: props.facet.attributeKey,
                        ...(values.metricName.trim() ? { metricName: values.metricName.trim() } : {}),
                        ...(values.facetSearch.trim() ? { value: values.facetSearch.trim() } : {}),
                        ...(dateFrom ? { dateFrom } : {}),
                        ...(dateTo ? { dateTo } : {}),
                        limit: FACET_VALUES_LIMIT,
                    })
                    breakpoint()
                    return response.results.map((row) => ({ value: row.name, label: row.name, count: row.count }))
                },
            },
        ],
    })),
    selectors({
        collapsed: [
            (s, p) => [s.collapsedFacetKeys, p.facet],
            (collapsedFacetKeys: string[], facet: MetricFacetConfig): boolean => collapsedFacetKeys.includes(facet.key),
        ],
        // Null while collapsed, so opening a facet fetches and closing one does not.
        fetchScope: [
            (s) => [s.collapsed, s.metricName, s.dateFrom, s.dateTo, s.currentTeamId, s.facetSearch],
            (
                collapsed: boolean,
                metricName: string,
                dateFrom: string | null,
                dateTo: string | null,
                teamId: number | null,
                facetSearch: string
            ): string | null =>
                collapsed ? null : JSON.stringify([metricName.trim(), dateFrom, dateTo, teamId, facetSearch.trim()]),
        ],
    }),
    subscriptions(({ actions }) => ({
        fetchScope: (scope: string | null) => {
            if (scope !== null) {
                actions.loadFacetValues({})
            }
        },
    })),
    listeners(({ actions, values }) => ({
        retryFacetValues: () => actions.loadFacetValues({}),
        // A load still in flight is left to finish, because a restart would discard its result.
        liveRefreshTick: () => {
            if (!values.collapsed && !values.facetValuesLoading) {
                actions.loadFacetValues({})
            }
        },
    })),
])