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.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import type { PostHog } from 'posthog-js/dist/module'

import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

import { WebVitalsMetric } from '~/queries/schema/schema-general'
import { toolbarApi } from '~/toolbar/shared/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'

// We're giving different meaning for `undefined` and `null` here.
// `undefined` means we don't have a value yet, while `null` means we didn't get a value from the server.
export type WebVitalsMetrics = Record<WebVitalsMetric, number | null | undefined>

// It returns this and much more, but we only care about the metrics
export type WebVitalsMetricsResponse = {
    results: {
        order: number
        data: [number, number] // We care about the second value, last one from the week
    }[]
}

// The series order of the `/web_vitals` query in `posthog/api/web_vitals.py`. Each row's `order` indexes it.
const WEB_VITALS_SERIES_ORDER: WebVitalsMetric[] = ['INP', 'LCP', 'CLS', 'FCP']

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webVitalsToolbarLogicValues {
    posthog: PostHog | null // toolbarConfigLogic
    localWebVitals: WebVitalsMetrics
    remoteWebVitals: WebVitalsMetrics
    remoteWebVitalsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webVitalsToolbarLogicActions {
    getWebVitals: () => {
        value: true
    }
    getWebVitalsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    getWebVitalsSuccess: (
        remoteWebVitals: WebVitalsMetrics,
        payload?: {
            value: true
        }
    ) => {
        remoteWebVitals: WebVitalsMetrics
        payload?: {
            value: true
        }
    }
    nullifyLocalWebVitals: () => {
        value: true
    }
    resetLocalWebVitals: () => {
        value: true
    }
    setLocalWebVital: (
        webVitalMetric: WebVitalsMetric,
        value: number | null
    ) => {
        value: number | null
        webVitalMetric: WebVitalsMetric
    }
}

export type webVitalsToolbarLogicType = MakeLogicType<webVitalsToolbarLogicValues, webVitalsToolbarLogicActions>

export const webVitalsToolbarLogic = kea<webVitalsToolbarLogicType>([
    path(['toolbar', 'web-vitals', 'webVitalsToolbarLogic']),
    connect(() => ({
        values: [toolbarConfigLogic, ['posthog']],
    })),
    actions({
        getWebVitals: true,
        setLocalWebVital: (webVitalMetric: WebVitalsMetric, value: number | null) => ({ webVitalMetric, value }),
        resetLocalWebVitals: true,
        nullifyLocalWebVitals: true,
    }),

    reducers({
        localWebVitals: [
            {} as WebVitalsMetrics,
            {
                setLocalWebVital: (state, { webVitalMetric, value }) => ({
                    ...state,
                    [webVitalMetric]: value,
                }),
                resetLocalWebVitals: () => ({}) as WebVitalsMetrics,
                nullifyLocalWebVitals: () =>
                    ({
                        LCP: null,
                        FCP: null,
                        CLS: null,
                        INP: null,
                    }) as WebVitalsMetrics,
            },
        ],
    }),

    loaders(({ values }) => ({
        remoteWebVitals: [
            {} as WebVitalsMetrics,
            {
                getWebVitals: async (_, breakpoint) => {
                    // If web vitals autocapture is disabled, we don't want to fetch the data
                    // because it's likely we won't have any data
                    if (
                        !values.posthog?.webVitalsAutocapture?.isEnabled &&
                        !inStorybook() &&
                        !inStorybookTestRunner()
                    ) {
                        return { LCP: null, FCP: null, CLS: null, INP: null } as WebVitalsMetrics
                    }

                    const result = await toolbarApi.webVitals.get<WebVitalsMetricsResponse>(
                        { pathname: window.location.pathname },
                        { context: 'load_web_vitals' }
                    )
                    breakpoint()

                    // The UI already handles null metrics — any failure degrades to "no data".
                    if (!result.ok) {
                        return { LCP: null, FCP: null, CLS: null, INP: null } as WebVitalsMetrics
                    }

                    const json = result.data
                    const metricValue = (metric: WebVitalsMetric): number | null =>
                        json.results.find((row) => row.order === WEB_VITALS_SERIES_ORDER.indexOf(metric))?.data[1] ??
                        null
                    return {
                        LCP: metricValue('LCP'),
                        FCP: metricValue('FCP'),
                        CLS: metricValue('CLS'),
                        INP: metricValue('INP'),
                    }
                },
            },
        ],
    })),

    urlToAction(({ actions, cache }) => ({
        '*': () => {
            const { pathname } = router.values.location
            if (!cache.previousURL || cache.previousURL !== pathname) {
                actions.resetLocalWebVitals()
                actions.getWebVitals()
                cache.previousURL = pathname
            }
        },
    })),

    afterMount(({ values, actions, cache }) => {
        if (!values.posthog?.webVitalsAutocapture?.isEnabled && !inStorybook() && !inStorybookTestRunner()) {
            actions.nullifyLocalWebVitals()
        } else {
            const METRICS_AND_PROPERTIES: Record<WebVitalsMetric, string> = {
                FCP: '$web_vitals_FCP_value',
                LCP: '$web_vitals_LCP_value',
                CLS: '$web_vitals_CLS_value',
                INP: '$web_vitals_INP_value',
            }

            cache.disposables.add(() => {
                return values.posthog?.on('eventCaptured', (event) => {
                    if (event.event === '$web_vitals') {
                        for (const [metric, property] of Object.entries(METRICS_AND_PROPERTIES)) {
                            const value = event.properties[property]
                            if (value !== undefined) {
                                actions.setLocalWebVital(metric as WebVitalsMetric, value)
                            }
                        }
                    }
                })
            }, 'posthogEventListener')
        }

        actions.getWebVitals()
    }),
    permanentlyMount(),
])