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.

9.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import type { UniversalFiltersGroup } from '../../../../../frontend/src/types'
import { metricsAttributesRetrieve } from '../../generated/api'
import { canViewMetrics } from '../../metricsAccess'
import { SERVICE_NAME_KEY } from '../../metricsAttributes'
import { metricsViewerLogic, resolveDate } from '../metricsViewerLogic'
import { MetricFacetConfig, buildMetricFacets, cycleMetricFacetFilter } from './facets'

// A metric can carry dozens of attributes, and each expanded facet runs its own values query,
// so only the top-ranked facets start expanded.
export const DEFAULT_EXPANDED_FACETS = 5
const ATTRIBUTE_KEYS_LIMIT = 50

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetRailLogicValues {
    currentTeamId: number | null // metricsViewerLogic
    dateFrom: string | null // metricsViewerLogic
    dateTo: string | null // metricsViewerLogic
    filterGroup: UniversalFiltersGroup // metricsViewerLogic
    liveRefresh: boolean // metricsViewerLogic
    metricName: string // metricsViewerLogic
    timezone: string // metricsViewerLogic
    attributeKeys: string[]
    attributeKeysFailed: boolean
    attributeKeysLoading: boolean
    attributeKeysScope: string
    collapseOverrides: Record<string, boolean>
    collapsedFacetKeys: string[]
    facetNameSearch: string
    loadedAttributeKeysScope: string | null
    railCollapsed: boolean
    visibleFacets: MetricFacetConfig[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetRailLogicActions {
    liveRefreshTick: () => {
        value: true
    } // metricsViewerLogic
    setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
        filterGroup: UniversalFiltersGroup
    } // metricsViewerLogic
    loadAttributeKeys: (_scope: string) => string
    loadAttributeKeysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAttributeKeysSuccess: (
        attributeKeys: string[],
        payload?: string
    ) => {
        attributeKeys: string[]
        payload?: string
    }
    retryAttributeKeys: () => {
        value: true
    }
    setFacetCollapsed: (
        facetKey: string,
        collapsed: boolean
    ) => {
        collapsed: boolean
        facetKey: string
    }
    setFacetNameSearch: (search: string) => {
        search: string
    }
    setRailCollapsed: (railCollapsed: boolean) => {
        railCollapsed: boolean
    }
    toggleFacetCollapsed: (facetKey: string) => {
        facetKey: string
    }
    toggleFacetValue: (
        attributeKey: string,
        value: string
    ) => {
        attributeKey: string
        value: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsFacetRailLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        visibleFacets: (
            attributeKeys: string[],
            loadedAttributeKeysScope: string | null,
            attributeKeysScope: string
        ) => MetricFacetConfig[]
        collapsedFacetKeys: (visibleFacets: MetricFacetConfig[], collapseOverrides: Record<string, boolean>) => string[]
        attributeKeysScope: (
            metricName: string,
            dateFrom: string | null,
            dateTo: string | null,
            currentTeamId: number | null
        ) => string
    }
}

export type metricsFacetRailLogicType = MakeLogicType<
    metricsFacetRailLogicValues,
    metricsFacetRailLogicActions,
    Record<string, any>,
    metricsFacetRailLogicMeta
>

/** The metrics viewer's facet rail: which facets render, which are collapsed, and value toggles. */
export const metricsFacetRailLogic = kea<metricsFacetRailLogicType>([
    path(['products', 'metrics', 'frontend', 'components', 'FacetRail', 'metricsFacetRailLogic']),
    connect(() => ({
        values: [
            metricsViewerLogic,
            ['metricName', 'dateFrom', 'dateTo', 'timezone', 'currentTeamId', 'filterGroup', 'liveRefresh'],
        ],
        actions: [metricsViewerLogic, ['setFilterGroup', 'liveRefreshTick']],
    })),
    actions({
        retryAttributeKeys: true,
        toggleFacetValue: (attributeKey: string, value: string) => ({ attributeKey, value }),
        toggleFacetCollapsed: (facetKey: string) => ({ facetKey }),
        setFacetCollapsed: (facetKey: string, collapsed: boolean) => ({ facetKey, collapsed }),
        setFacetNameSearch: (search: string) => ({ search }),
        setRailCollapsed: (railCollapsed: boolean) => ({ railCollapsed }),
    }),
    reducers({
        facetNameSearch: ['', { setFacetNameSearch: (_, { search }) => search }],
        railCollapsed: [false, { persist: true }, { setRailCollapsed: (_, { railCollapsed }) => railCollapsed }],
        // Only the user's own toggles. The default depends on the facet's rank, which changes with the metric.
        collapseOverrides: [
            {} as Record<string, boolean>,
            { persist: true },
            {
                setFacetCollapsed: (state, { facetKey, collapsed }) => ({ ...state, [facetKey]: collapsed }),
            },
        ],
        // The scope the loaded keys belong to. Until it matches the current scope, the keys are another
        // metric's, and their facets would query the new metric for nothing.
        loadedAttributeKeysScope: [
            null as string | null,
            { loadAttributeKeysSuccess: (_, { payload }) => payload ?? null },
        ],
        attributeKeysFailed: [
            false,
            {
                loadAttributeKeysSuccess: () => false,
                loadAttributeKeysFailure: () => true,
            },
        ],
    }),
    loaders(({ values }) => ({
        attributeKeys: [
            [] as string[],
            {
                // The scope is unused here, but it rides on the success action to loadedAttributeKeysScope.
                loadAttributeKeys: async (_scope: string, breakpoint) => {
                    if (!canViewMetrics() || !values.currentTeamId) {
                        return []
                    }
                    await breakpoint(300)
                    const dateFrom = resolveDate(values.dateFrom, values.timezone)
                    const dateTo = resolveDate(values.dateTo, values.timezone)
                    const response = await metricsAttributesRetrieve(String(values.currentTeamId), {
                        ...(values.metricName.trim() ? { metricName: values.metricName.trim() } : {}),
                        ...(dateFrom ? { dateFrom } : {}),
                        ...(dateTo ? { dateTo } : {}),
                        limit: ATTRIBUTE_KEYS_LIMIT,
                    })
                    breakpoint()
                    return response.results.map((result) => result.name)
                },
            },
        ],
    })),
    selectors({
        visibleFacets: [
            (s) => [s.attributeKeys, s.loadedAttributeKeysScope, s.attributeKeysScope],
            (attributeKeys: string[], loadedScope: string | null, scope: string): MetricFacetConfig[] =>
                buildMetricFacets(loadedScope === scope ? attributeKeys : []),
        ],
        collapsedFacetKeys: [
            (s) => [s.visibleFacets, s.collapseOverrides],
            (facets: MetricFacetConfig[], overrides: Record<string, boolean>): string[] =>
                facets
                    .filter((facet, index) => overrides[facet.key] ?? index >= DEFAULT_EXPANDED_FACETS)
                    .map((facet) => facet.key),
        ],
        attributeKeysScope: [
            (s) => [s.metricName, s.dateFrom, s.dateTo, s.currentTeamId],
            (metricName: string, dateFrom: string | null, dateTo: string | null, teamId: number | null): string =>
                JSON.stringify([metricName.trim(), dateFrom, dateTo, teamId]),
        ],
    }),
    listeners(({ actions, values }) => ({
        toggleFacetValue: ({ attributeKey, value }) => {
            actions.setFilterGroup(cycleMetricFacetFilter(values.filterGroup, attributeKey, value))
            // Attribute keys are the customer's own names, so the event only says whether it was the service facet.
            posthog.capture('metrics facet rail value toggled', { is_service_facet: attributeKey === SERVICE_NAME_KEY })
        },
        toggleFacetCollapsed: ({ facetKey }) => {
            actions.setFacetCollapsed(facetKey, !values.collapsedFacetKeys.includes(facetKey))
        },
        retryAttributeKeys: () => actions.loadAttributeKeys(values.attributeKeysScope),
        // A rolling range moves with each refresh, so new attributes can appear in it. A load still in
        // flight is left to finish, because a restart would discard its result. A hidden rail does not
        // poll, because the toggle keeps this logic mounted.
        liveRefreshTick: () => {
            if (!values.railCollapsed && !values.attributeKeysLoading) {
                actions.loadAttributeKeys(values.attributeKeysScope)
            }
        },
        // Reopening catches up on the ticks the hidden rail skipped.
        setRailCollapsed: ({ railCollapsed }) => {
            if (!railCollapsed && values.liveRefresh && !values.attributeKeysLoading) {
                actions.loadAttributeKeys(values.attributeKeysScope)
            }
        },
    })),
    subscriptions(({ actions }) => ({
        attributeKeysScope: (scope: string) => actions.loadAttributeKeys(scope),
    })),
])