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.

5.8 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { MaxContextInput } from 'scenes/max/maxTypes'
import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

import { Breadcrumb, InsightModel } from '~/types'

import type { Node } from '../../queries/schema/schema-general'
import { reportIdFromPath } from './today/todayLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectHomepageLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    receivedFeatureFlags: boolean // featureFlagLogic
    currentProjectId: number | null // projectLogic
    breadcrumbs: Breadcrumb[]
    expandedInsightIds: Set<string>
    maxContext: MaxContextInput[]
    recentInsights: InsightModel[]
    recentInsightsLoading: boolean
    todayHomeEnabled: boolean
    todayReportTitle: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectHomepageLogicActions {
    setFeatureFlags: (
        flags: string[],
        variants: Record<string, boolean | string>
    ) => {
        flags: string[]
        variants: Record<string, boolean | string>
    } // featureFlagLogic
    loadRecentInsights: () => any
    loadRecentInsightsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRecentInsightsSuccess: (
        recentInsights: InsightModel<Node<Record<string, any>>>[],
        payload?: any
    ) => {
        recentInsights: InsightModel<Node<Record<string, any>>>[]
        payload?: any
    }
    setTodayReportTitle: (title: string | null) => {
        title: string | null
    }
    toggleInsightExpanded: (insightShortId: string) => {
        insightShortId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectHomepageLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        todayHomeEnabled: (featureFlags: FeatureFlagsSet) => boolean
        breadcrumbs: (todayReportTitle: string | null) => Breadcrumb[]
    }
}

export type projectHomepageLogicType = MakeLogicType<
    projectHomepageLogicValues,
    projectHomepageLogicActions,
    Record<string, any>,
    projectHomepageLogicMeta
>

export const projectHomepageLogic = kea<projectHomepageLogicType>([
    path(['scenes', 'project-homepage', 'projectHomepageLogic']),
    connect(() => ({
        values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],
        actions: [featureFlagLogic, ['setFeatureFlags']],
    })),

    actions({
        toggleInsightExpanded: (insightShortId: string) => ({ insightShortId }),
        setTodayReportTitle: (title: string | null) => ({ title }),
    }),

    reducers({
        todayReportTitle: [null as string | null, { setTodayReportTitle: (_, { title }) => title }],
        expandedInsightIds: [
            new Set<string>(),
            {
                toggleInsightExpanded: (state, { insightShortId }) => {
                    const next = new Set(state)
                    next.has(insightShortId) ? next.delete(insightShortId) : next.add(insightShortId)
                    return next
                },
            },
        ],
    }),

    loaders(({ values }) => ({
        recentInsights: [
            [] as InsightModel[],
            {
                loadRecentInsights: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. insightsMyLastViewedRetrieve() from 'products/product_analytics/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    return await api.get<InsightModel[]>(
                        `api/projects/${values.currentProjectId}/insights/my_last_viewed`
                    )
                },
            },
        ],
    })),

    selectors({
        // Matches the condition that swaps in the Today rail, because Today has no way around without it.
        todayHomeEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV],
        ],
        maxContext: [
            () => [],
            // Context is only added explicitly via the @Context button.
            (): MaxContextInput[] => [],
        ],
        breadcrumbs: [
            (s) => [s.todayReportTitle],
            (todayReportTitle: string | null): Breadcrumb[] => [
                {
                    key: 'home',
                    name: 'Home',
                    iconType: 'home',
                    path: todayReportTitle ? urls.projectHomepage() : undefined,
                },
                ...(todayReportTitle ? [{ key: 'today-report', name: todayReportTitle }] : []),
            ],
        ],
    }),

    listeners(({ values }) => ({
        setFeatureFlags: () => {
            const reportId = reportIdFromPath(router.values.location.pathname)
            if (reportId && !values.todayHomeEnabled) {
                router.actions.replace(urls.inboxReport('reports', reportId))
            }
        },
    })),

    urlToAction(({ values }) => ({
        // A Today report link opened where Today is off lands on the same report in the Inbox.
        [urls.todayReport(':reportId')]: ({ reportId }) => {
            if (reportId && values.receivedFeatureFlags && !values.todayHomeEnabled) {
                router.actions.replace(urls.inboxReport('reports', reportId))
            }
        },
    })),
])