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.

13.0 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'

import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { todayAnalyticsLogic } from '~/layout/today/todayAnalyticsLogic'
import { FileSystemEntry } from '~/queries/schema/schema-general'

import { ANALYTICS_FEED_PAGE_SIZE, fileSystemTypeParams } from './analyticsFeed'
import { analyticsPinnedLogic, pinKey } from './analyticsPinnedLogic'
import { ANALYTICS_TYPES, AnalyticsType, fileSystemEntryName, isSpacePath } from './analyticsUtils'

export interface AnalyticsSpace {
    path: string
    name: string
    /** How many rows of each analytics type the space holds, from the API's own counts. */
    counts: Record<AnalyticsType, number>
    total: number
    /** When something was last added, from the newest row. */
    lastAddedAt: string | null
}

type SpacesPagination = { offset: number; hasMore: boolean }

/** One request per type reads the count and the newest row, so a big space costs four small calls. */
export async function loadSpace(folder: FileSystemEntry, signal?: AbortSignal): Promise<AnalyticsSpace> {
    const pages = await Promise.all(
        ANALYTICS_TYPES.map((info) =>
            api.fileSystem.list({
                parent: folder.path,
                ...fileSystemTypeParams(info.type),
                orderBy: '-created_at',
                limit: 1,
                signal,
            })
        )
    )
    const counts = Object.fromEntries(
        ANALYTICS_TYPES.map((info, index) => [info.type, pages[index].count ?? pages[index].results.length])
    ) as Record<AnalyticsType, number>
    const lastAddedAt = pages
        .map((page) => page.results[0]?.created_at ?? null)
        .filter((value): value is string => !!value)
        .sort()
        .at(-1)
    return {
        path: folder.path,
        name: fileSystemEntryName(folder),
        counts,
        total: Object.values(counts).reduce((sum, count) => sum + count, 0),
        lastAddedAt: lastAddedAt ?? null,
    }
}

export async function listSpaceFolders(signal?: AbortSignal): Promise<FileSystemEntry[]> {
    const folders: FileSystemEntry[] = []
    for (let offset = 0; ; offset += 200) {
        const page = await api.fileSystem.list({
            depth: 1,
            type: 'folder',
            limit: 200,
            offset,
            orderBy: 'path',
            signal,
        })
        folders.push(...page.results.filter((folder) => isSpacePath(folder.path)))
        if (!page.next || !page.results.length) {
            return folders
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsSpacesLogicValues {
    pinnedCollectionPaths: Set<string> // analyticsPinnedLogic
    pinnedShortcutIds: Map<string, string> // analyticsPinnedLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    pagination: SpacesPagination
    search: string
    spaces: AnalyticsSpace[]
    spacesFailed: boolean
    spacesLoading: boolean
    visibleSpaces: AnalyticsSpace[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsSpacesLogicActions {
    deleteSavedItem: (savedItem: FileSystemEntry) => {
        savedItem: FileSystemEntry
    } // projectTreeDataLogic
    loadShortcuts: () => {
        value: true
    } // projectTreeDataLogic
    folderCreated: () => {
        value: true
    } // todayAnalyticsLogic
    loadMore: () => {
        value: true
    }
    loadSpaces: (append?: boolean) => boolean
    loadSpacesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSpacesSuccess: (
        spaces: AnalyticsSpace[],
        payload?: boolean
    ) => {
        spaces: AnalyticsSpace[]
        payload?: boolean
    }
    refreshSpaces: () => {
        value: true
    }
    setPagination: (
        offset: number,
        hasMore: boolean
    ) => {
        hasMore: boolean
        offset: number
    }
    setSearch: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsSpacesLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        visibleSpaces: (
            spaces: AnalyticsSpace[],
            pinnedCollectionPaths: Set<string>,
            search: string
        ) => AnalyticsSpace[]
    }
}

export type analyticsSpacesLogicType = MakeLogicType<
    analyticsSpacesLogicValues,
    analyticsSpacesLogicActions,
    Record<string, any>,
    analyticsSpacesLogicMeta
>

/** The project's spaces: its top-level folders, with what each one holds. */
export const analyticsSpacesLogic = kea<analyticsSpacesLogicType>([
    path(['scenes', 'analytics', 'analyticsSpacesLogic']),
    connect(() => ({
        values: [
            featureFlagLogic,
            ['featureFlags'],
            analyticsPinnedLogic,
            ['pinnedCollectionPaths', 'pinnedShortcutIds'],
        ],
        actions: [todayAnalyticsLogic, ['folderCreated'], projectTreeDataLogic, ['deleteSavedItem', 'loadShortcuts']],
    })),
    actions({
        setSearch: (search: string) => ({ search }),
        loadMore: true,
        refreshSpaces: true,
        setPagination: (offset: number, hasMore: boolean) => ({ offset, hasMore }),
    }),
    loaders(({ actions, values, cache }) => ({
        spaces: [
            [] as AnalyticsSpace[],
            {
                loadSpaces: async (append: boolean = false, breakpoint): Promise<AnalyticsSpace[]> => {
                    const controller = new AbortController()
                    cache.disposables.add(() => () => controller.abort(), 'spacesRequest', { pauseOnPageHidden: false })
                    const metadata: Map<string, AnalyticsSpace> = (cache.metadata ??= new Map())
                    let folders: FileSystemEntry[] | undefined = cache.folders
                    if (!folders) {
                        folders = await listSpaceFolders(controller.signal)
                        breakpoint()
                        cache.folders = folders
                    }
                    const pinned = values.pinnedCollectionPaths
                    const needle = values.search.trim().toLowerCase()
                    const matches = folders
                        .filter(
                            (folder) =>
                                isSpacePath(folder.path) && fileSystemEntryName(folder).toLowerCase().includes(needle)
                        )
                        .sort((first, second) => {
                            const pinnedFirst = Number(pinned.has(second.path)) - Number(pinned.has(first.path))
                            return pinnedFirst || first.path.localeCompare(second.path)
                        })
                    const offset = append ? values.pagination.offset : 0
                    const page = matches.slice(offset, offset + ANALYTICS_FEED_PAGE_SIZE)
                    const spaces = await Promise.all(
                        page.map(async (folder) => {
                            const existing = metadata.get(folder.path)
                            if (existing) {
                                return existing
                            }
                            const space = await loadSpace(folder, controller.signal)
                            metadata.set(folder.path, space)
                            return space
                        })
                    )
                    breakpoint()
                    cache.loaded = true
                    actions.setPagination(offset + page.length, offset + page.length < matches.length)
                    const combined = append ? [...values.spaces, ...spaces] : spaces
                    return combined.sort((first, second) => first.name.localeCompare(second.name))
                },
            },
        ],
    })),
    reducers({
        pagination: [
            { offset: 0, hasMore: false } as SpacesPagination,
            {
                setPagination: (_, { offset, hasMore }) => ({ offset, hasMore }),
                setSearch: (): SpacesPagination => ({ offset: 0, hasMore: false }),
            },
        ],
        spacesFailed: [
            false,
            { loadSpaces: () => false, loadSpacesSuccess: () => false, loadSpacesFailure: () => true },
        ],
        search: ['', { setSearch: (_, { search }) => search }],
    }),
    selectors({
        // Pinned spaces lead, then the rest alphabetically; a search narrows both by name.
        visibleSpaces: [
            (s) => [s.spaces, s.pinnedCollectionPaths, s.search],
            (spaces: AnalyticsSpace[], pinnedCollectionPaths: Set<string>, search: string): AnalyticsSpace[] => {
                const needle = search.trim().toLowerCase()
                return spaces
                    .filter((space) => !needle || space.name.toLowerCase().includes(needle))
                    .sort((first, second) => {
                        const pinnedFirst =
                            Number(pinnedCollectionPaths.has(second.path)) -
                            Number(pinnedCollectionPaths.has(first.path))
                        return pinnedFirst || first.name.localeCompare(second.name)
                    })
            },
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        refreshSpaces: () => {
            cache.folders = undefined
            cache.metadata = new Map<string, AnalyticsSpace>()
            actions.loadSpaces()
        },
        loadMore: () => {
            if (!values.spacesLoading && values.pagination.hasMore) {
                actions.loadSpaces(true)
            }
        },
        setSearch: async (_, breakpoint) => {
            await breakpoint(200)
            actions.loadSpaces()
        },
    })),
    listeners(({ actions, values, cache }) => ({
        // Flags can arrive after the mount, so a mount that skipped the load must load now.
        [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
            if (!values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] || cache.flagSeen) {
                return
            }
            cache.flagSeen = true
            if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
                actions.refreshSpaces()
            }
        },
        // A space made from the dialog shows up without a reload.
        folderCreated: () => {
            if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
                actions.refreshSpaces()
            }
        },
        // A collection is deleted like any folder, through the project tree. The server keeps its pin, so it goes here.
        deleteSavedItem: async ({ savedItem }) => {
            if (savedItem.type !== 'folder' || !isSpacePath(savedItem.path)) {
                return
            }
            const shortcutId = values.pinnedShortcutIds.get(pinKey('folder', savedItem.path))
            if (shortcutId) {
                await api.fileSystemShortcuts.delete(shortcutId).catch(() => null)
            }
            // pinned: analytics event name. Renaming it breaks dashboards.
            posthog.capture('analytics collection deleted')
            actions.loadShortcuts()
            if (removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()) {
                actions.refreshSpaces()
            }
        },
    })),
    subscriptions(({ actions, cache }) => ({
        // Pinned spaces page first, so a change to the pins changes which spaces each page holds. Paging on from the
        // old order would skip some spaces and repeat others, so the list loads again from the first page.
        pinnedCollectionPaths: (paths: Set<string>, previous: Set<string> | undefined) => {
            const unchanged =
                !!previous && paths.size === previous.size && [...paths].every((path) => previous.has(path))
            if (
                !unchanged &&
                cache.loaded &&
                removeProjectIdIfPresent(router.values.location.pathname) === urls.analyticsSpaces()
            ) {
                actions.loadSpaces()
            }
        },
    })),
    // The sidebar mounts this logic for the pins alone; counting every space is for the Spaces page.
    urlToAction(({ actions, values }) => ({
        [urls.analyticsSpaces()]: () => {
            if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
                actions.refreshSpaces()
            }
        },
    })),
    afterMount(({ values, cache }) => {
        if (values.featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
            cache.flagSeen = true
        }
    }),
])