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.4 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'

import * as api from 'products/signals/frontend/generated/api'
import type { InboxSummaryApi } from 'products/signals/frontend/generated/api.schemas'

import { captureInboxValueSummary } from '../inboxAnalytics'

export const INBOX_SUMMARY_DISMISS_MS = 7 * 24 * 60 * 60 * 1000
export const INBOX_SUMMARY_FRESH_MS = 5 * 60 * 1000

export interface InboxSummaryLogicProps {
    teamId: number
    userId: number
    visible: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxSummaryLogicValues {
    dismissed: boolean
    dismissedUntil: number
    failed: boolean
    hasBeenViewed: boolean
    loadedAt: number
    now: number
    pageVisible: boolean
    summary: InboxSummaryApi | null
    summaryLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxSummaryLogicActions {
    armDismissalExpiry: () => {
        value: true
    }
    dismissSummary: (until: number) => {
        until: number
    }
    loadInboxSummary: (_: void) => void
    loadInboxSummaryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInboxSummarySuccess: (
        summary: InboxSummaryApi,
        payload?: void
    ) => {
        summary: InboxSummaryApi
        payload?: void
    }
    refreshSummary: (force?: boolean) => {
        force: boolean
    }
    summaryViewed: () => {
        value: true
    }
    updateClock: (
        now: number,
        pageVisible: boolean
    ) => {
        now: number
        pageVisible: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxSummaryLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        dismissed: (dismissedUntil: number, now: number) => boolean
    }
}

export type inboxSummaryLogicType = MakeLogicType<
    inboxSummaryLogicValues,
    inboxSummaryLogicActions,
    InboxSummaryLogicProps,
    inboxSummaryLogicMeta
>

export const inboxSummaryLogic = kea<inboxSummaryLogicType>([
    props({} as InboxSummaryLogicProps),
    key(({ teamId, userId }) => `${userId}:${teamId}`),
    path((key) => ['products', 'signals', 'inbox', 'inboxSummaryLogic', key]),
    actions({
        refreshSummary: (force: boolean = false) => ({ force }),
        updateClock: (now: number, pageVisible: boolean) => ({ now, pageVisible }),
        dismissSummary: (until: number) => ({ until }),
        summaryViewed: true,
        armDismissalExpiry: true,
    }),
    loaders(({ props }) => ({
        summary: [
            null as InboxSummaryApi | null,
            {
                loadInboxSummary: async (_: void, breakpoint) => {
                    const summary = await api.signalsInboxSummaryList(String(props.teamId))
                    breakpoint()
                    return summary
                },
            },
        ],
    })),
    reducers({
        dismissedUntil: [0, { persist: true }, { dismissSummary: (_, { until }) => until }],
        now: [Date.now(), { updateClock: (_, { now }) => now }],
        pageVisible: [!document.hidden, { updateClock: (_, { pageVisible }) => pageVisible }],
        loadedAt: [
            0,
            {
                loadInboxSummarySuccess: () => Date.now(),
                loadInboxSummaryFailure: () => 0,
            },
        ],
        failed: [false, { loadInboxSummary: () => false, loadInboxSummaryFailure: () => true }],
        hasBeenViewed: [false, { summaryViewed: () => true }],
    }),
    selectors({
        dismissed: [
            (s) => [s.dismissedUntil, s.now],
            (until: number, now: number): boolean => Number.isFinite(until) && until > now,
        ],
    }),
    listeners(({ values, actions, props, cache }) => ({
        refreshSummary: ({ force }) => {
            actions.updateClock(Date.now(), !document.hidden)
            if (
                props.visible &&
                values.pageVisible &&
                !values.dismissed &&
                !values.summaryLoading &&
                (force || Date.now() - values.loadedAt >= INBOX_SUMMARY_FRESH_MS)
            ) {
                actions.loadInboxSummary()
            }
        },
        dismissSummary: () => {
            if (values.summary) {
                captureInboxValueSummary('dismissed', values.summary)
            }
            actions.armDismissalExpiry()
        },
        summaryViewed: () => {
            if (values.summary) {
                captureInboxValueSummary('viewed', values.summary)
            }
        },
        armDismissalExpiry: () => {
            cache.disposables.dispose('dismissal-expiry')
            if (Number.isFinite(values.dismissedUntil) && values.dismissedUntil > Date.now()) {
                cache.disposables.add(() => {
                    const timeout = window.setTimeout(
                        () => actions.refreshSummary(),
                        Math.max(0, values.dismissedUntil - Date.now())
                    )
                    return () => window.clearTimeout(timeout)
                }, 'dismissal-expiry')
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        cache.disposables.add(
            () => {
                actions.refreshSummary()
                const refresh = (): void => actions.refreshSummary()
                const visibilityChanged = (): void => {
                    actions.updateClock(Date.now(), !document.hidden)
                    if (!document.hidden) {
                        actions.refreshSummary()
                    }
                }
                window.addEventListener('focus', refresh)
                document.addEventListener('visibilitychange', visibilityChanged)
                return () => {
                    window.removeEventListener('focus', refresh)
                    document.removeEventListener('visibilitychange', visibilityChanged)
                }
            },
            'page-visibility',
            { pauseOnPageHidden: false }
        )
        actions.armDismissalExpiry()
    }),
    propsChanged(({ actions, props }, oldProps) => {
        if (props.visible && !oldProps.visible) {
            actions.refreshSummary()
        }
    }),
])