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.

2.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'

import { onFirstSceneRendered } from 'lib/utils/bootTiming'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

// Longer than the 99th percentile time from `app_ready` to `scene_rendered`.
export const SCENE_RENDERED_MAX_WAIT_MS = 10000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneRenderedLogicValues {
    sceneHasRendered: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneRenderedLogicActions {
    sceneRendered: () => {
        value: true
    }
}

export type sceneRenderedLogicType = MakeLogicType<sceneRenderedLogicValues, sceneRenderedLogicActions>

/**
 * Lets a request the first paint does not need wait for the first scene. A consumer listens for `sceneRendered`
 * and checks `sceneHasRendered` in `afterMount`. A page with no scene fires it after the maximum wait.
 */
export const sceneRenderedLogic = kea<sceneRenderedLogicType>([
    path(['lib', 'logic', 'sceneRenderedLogic']),
    actions({
        sceneRendered: true,
    }),
    reducers({
        sceneHasRendered: [
            false,
            {
                sceneRendered: () => true,
            },
        ],
    }),
    afterMount(({ actions, values, cache }) => {
        const markRendered = (): void => {
            if (!values.sceneHasRendered) {
                actions.sceneRendered()
            }
        }
        // A hidden tab must not pause these, or a consumer in a background tab would wait until the tab shows.
        cache.disposables.add(() => onFirstSceneRendered(markRendered), 'firstSceneRendered', {
            pauseOnPageHidden: false,
        })
        cache.disposables.add(
            () => {
                const timer = window.setTimeout(markRendered, SCENE_RENDERED_MAX_WAIT_MS)
                return () => clearTimeout(timer)
            },
            'sceneRenderedFallback',
            { pauseOnPageHidden: false }
        )
    }),
    permanentlyMount(),
])