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.

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

import { toast } from '@posthog/quill'

import api from 'lib/api'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { analyticsPinnedLogic, pinKey } from 'scenes/analytics/analyticsPinnedLogic'
import {
    AnalyticsItem,
    FromPostHogItem,
    fileSystemEntryToAnalytics,
    fromPostHogItems,
} from 'scenes/analytics/analyticsUtils'

import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { escapePath } from '~/layout/panel-layout/ProjectTree/utils'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'

import { newestByName } from './todayNewestByName'
import { matchesPaneQuery } from './todayPaneSearch'
import { TODAY_USER_PERSIST_OPTIONS } from './todayUserPersistOptions'

// pinned: persisted section ids and the `section` property of `analytics section toggled`.
export type TodayAnalyticsSection = 'pinned' | 'recents' | 'monitor' | 'by-posthog'

export const DEFAULT_COLLAPSED_SECTIONS: TodayAnalyticsSection[] = []

export const TODAY_ANALYTICS_RECENTS_LIMIT = 3

// The last Recents list stays in the browser so it shows on first paint.

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAnalyticsLogicValues {
    pinnedShortcutIds: Map<string, string> // analyticsPinnedLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    recents: FileSystemEntry[] // recentItemsModel
    recentsHasLoaded: boolean // recentItemsModel
    collapsedSections: TodayAnalyticsSection[]
    creatingFolder: boolean
    freshRecentAnalytics: AnalyticsItem[]
    fromPostHog: FromPostHogItem[]
    isSectionOpen: (section: TodayAnalyticsSection) => boolean
    matchesSearch: (label: string) => boolean
    newFolderDialogOpen: boolean
    newFolderParent: string | null
    recentAnalytics: AnalyticsItem[]
    savedRecentAnalytics: AnalyticsItem[]
    searchQuery: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAnalyticsLogicActions {
    createSavedItem: (savedItem: FileSystemEntry) => {
        savedItem: FileSystemEntry
    } // projectTreeDataLogic
    createFolder: (name: string) => {
        name: string
    }
    folderCreated: () => {
        value: true
    }
    folderCreationFailed: () => {
        value: true
    }
    setNewFolderDialogOpen: (
        open: boolean,
        parent?: string | null
    ) => {
        open: boolean
        parent: string | null
    }
    setSearchQuery: (searchQuery: string) => {
        searchQuery: string
    }
    storeRecentAnalytics: (items: AnalyticsItem[]) => {
        items: AnalyticsItem[]
    }
    toggleSection: (section: TodayAnalyticsSection) => {
        section: TodayAnalyticsSection
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAnalyticsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        matchesSearch: (searchQuery: string) => (label: string) => boolean
        isSectionOpen: (
            collapsedSections: TodayAnalyticsSection[],
            searchQuery: string
        ) => (section: TodayAnalyticsSection) => boolean
        fromPostHog: (featureFlags: FeatureFlagsSet) => FromPostHogItem[]
        freshRecentAnalytics: (recents: FileSystemEntry[], pinnedShortcutIds: Map<string, string>) => AnalyticsItem[]
        recentAnalytics: (
            recentsHasLoaded: boolean,
            freshRecentAnalytics: AnalyticsItem[],
            savedRecentAnalytics: AnalyticsItem[],
            pinnedShortcutIds: Map<string, string>
        ) => AnalyticsItem[]
    }
}

export type todayAnalyticsLogicType = MakeLogicType<
    todayAnalyticsLogicValues,
    todayAnalyticsLogicActions,
    Record<string, any>,
    todayAnalyticsLogicMeta
>

export const todayAnalyticsLogic = kea<todayAnalyticsLogicType>([
    path(['layout', 'today', 'todayAnalyticsLogic']),
    connect(() => ({
        values: [
            featureFlagLogic,
            ['featureFlags'],
            recentItemsModel,
            ['recents', 'recentsHasLoaded'],
            analyticsPinnedLogic,
            ['pinnedShortcutIds'],
        ],
        actions: [projectTreeDataLogic, ['createSavedItem']],
    })),
    actions({
        toggleSection: (section: TodayAnalyticsSection) => ({ section }),
        setSearchQuery: (searchQuery: string) => ({ searchQuery }),
        storeRecentAnalytics: (items: AnalyticsItem[]) => ({ items }),
        setNewFolderDialogOpen: (open: boolean, parent: string | null = null) => ({ open, parent }),
        createFolder: (name: string) => ({ name }),
        folderCreated: true,
        folderCreationFailed: true,
    }),
    reducers({
        // pinned: storage key for the saved Recents list. Renaming it makes everyone's Recents pop in once more.
        savedRecentAnalytics: [
            [] as AnalyticsItem[],
            TODAY_USER_PERSIST_OPTIONS,
            { storeRecentAnalytics: (_, { items }) => items },
        ],
        searchQuery: ['', { setSearchQuery: (_, { searchQuery }) => searchQuery }],
        // pinned: storage key for the persisted sections. Renaming it reopens everyone's sections.
        collapsedSections: [
            DEFAULT_COLLAPSED_SECTIONS,
            { persist: true },
            {
                toggleSection: (state, { section }) =>
                    state.includes(section) ? state.filter((id) => id !== section) : [...state, section],
            },
        ],
        // The collection a folder is created in, or null for a new top-level collection.
        newFolderParent: [null as string | null, { setNewFolderDialogOpen: (_, { parent }) => parent }],
        newFolderDialogOpen: [
            false,
            {
                setNewFolderDialogOpen: (_, { open }) => open,
                folderCreated: () => false,
            },
        ],
        creatingFolder: [
            false,
            {
                createFolder: () => true,
                folderCreated: () => false,
                folderCreationFailed: () => false,
            },
        ],
    }),
    selectors({
        /** Whether a row's label matches the pane search. Every row matches while the search is empty. */
        matchesSearch: [
            (s) => [s.searchQuery],
            (searchQuery: string) =>
                (label: string): boolean =>
                    matchesPaneQuery(label, searchQuery),
        ],
        /** A search opens every section, so no match hides in a collapsed one. */
        isSectionOpen: [
            (s) => [s.collapsedSections, s.searchQuery],
            (collapsedSections: TodayAnalyticsSection[], searchQuery: string) =>
                (section: TodayAnalyticsSection): boolean =>
                    searchQuery.trim() !== '' || !collapsedSections.includes(section),
        ],
        fromPostHog: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): FromPostHogItem[] => fromPostHogItems(featureFlags),
        ],
        // The app loads recently viewed items once and keeps them, so this section needs no request of its own.
        // Pinned items already show in the Pinned section, so Recents leaves them out before it applies the limit.
        freshRecentAnalytics: [
            (s) => [s.recents, s.pinnedShortcutIds],
            (recents: FileSystemEntry[], pinnedShortcutIds: Map<string, string>): AnalyticsItem[] =>
                newestByName(
                    recents.flatMap((entry) => {
                        const item = fileSystemEntryToAnalytics(entry)
                        return item && !pinnedShortcutIds.has(pinKey(item.type, item.id)) ? [item] : []
                    }),
                    (item) => item.name,
                    (item) => pinKey(item.type, item.id),
                    TODAY_ANALYTICS_RECENTS_LIMIT
                ),
        ],
        // The saved list covers only the wait for the shared list. Once it has loaded, even empty, it is the answer.
        recentAnalytics: [
            (s) => [s.recentsHasLoaded, s.freshRecentAnalytics, s.savedRecentAnalytics, s.pinnedShortcutIds],
            (
                recentsHasLoaded: boolean,
                fresh: AnalyticsItem[],
                saved: AnalyticsItem[],
                pinnedShortcutIds: Map<string, string>
            ): AnalyticsItem[] =>
                recentsHasLoaded ? fresh : saved.filter((item) => !pinnedShortcutIds.has(pinKey(item.type, item.id))),
        ],
    }),
    listeners(({ actions, values }) => ({
        toggleSection: ({ section }) => {
            // pinned: analytics event name and properties. Renaming them breaks dashboards.
            posthog.capture('analytics section toggled', {
                section,
                open: !values.collapsedSections.includes(section),
            })
        },
        createFolder: async ({ name }) => {
            const parent = values.newFolderParent
            // One name is one segment: a slash in it must not create a nested folder.
            const path = parent ? `${parent}/${escapePath(name.trim())}` : escapePath(name.trim())
            if (!name.trim()) {
                actions.folderCreationFailed()
                return
            }
            try {
                // The project tree keeps the rows, so the new folder shows wherever the tree is open.
                const entry = await api.fileSystem.create({ path, type: 'folder' } as FileSystemEntry)
                actions.createSavedItem(entry)
                actions.folderCreated()
                // pinned: analytics event name. Renaming it breaks dashboards.
                posthog.capture('analytics folder created', { nested: parent !== null })
                toast.success({ title: parent ? 'Folder created' : 'Collection created' })
            } catch {
                actions.folderCreationFailed()
                toast.error({
                    title: parent
                        ? 'Couldn’t create the folder. Try again.'
                        : 'Couldn’t create the collection. Try again.',
                })
            }
        },
    })),
    subscriptions(({ actions, values }) => ({
        // Saves what the section shows, so the next page load starts from it. Before the shared list loads, the
        // section shows a filtered copy of the saved list, and saving that copy would start the subscription again.
        recentAnalytics: (items: AnalyticsItem[]) => {
            if (values.recentsHasLoaded) {
                actions.storeRecentAnalytics(items)
            }
        },
    })),
])