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.1 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'

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

import {
    AnalyticsItem,
    fileSystemBaseType,
    fileSystemEntryName,
    fileSystemEntryToAnalytics,
    isSpacePath,
} from './analyticsUtils'

export interface PinTarget {
    type: string
    ref: string
    name: string
    href?: string
}

export type PinnedAnalytics =
    | { kind: 'item'; key: string; shortcutId: string; item: AnalyticsItem }
    | { kind: 'collection'; key: string; shortcutId: string; path: string; name: string }

/** One key per pinnable thing. `insight/trends` and `insight` share a key, since the shortcut keeps whichever it was given. */
export function pinKey(type: string, ref: string): string {
    return `${fileSystemBaseType(type)}:${ref}`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsPinnedLogicValues {
    shortcutData: FileSystemEntry[] // projectTreeDataLogic
    shortcutDataLoading: boolean // projectTreeDataLogic
    pinnedAnalytics: PinnedAnalytics[]
    pinnedCollectionPaths: Set<string>
    pinnedShortcutIds: Map<string, string>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsPinnedLogicActions {
    addShortcutItem: (
        item: FileSystemEntry,
        successMessage?: string | undefined
    ) => {
        item: FileSystemEntry
        successMessage: string | undefined
    } // projectTreeDataLogic
    deleteShortcut: (
        id: string,
        successMessage?: string | undefined
    ) => {
        id: string
        successMessage: string | undefined
    } // projectTreeDataLogic
    togglePinned: (target: PinTarget) => {
        target: PinTarget
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface analyticsPinnedLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        pinnedAnalytics: (shortcutData: FileSystemEntry[]) => PinnedAnalytics[]
        pinnedShortcutIds: (pinnedAnalytics: PinnedAnalytics[]) => Map<string, string>
        pinnedCollectionPaths: (pinnedAnalytics: PinnedAnalytics[]) => Set<string>
    }
}

export type analyticsPinnedLogicType = MakeLogicType<
    analyticsPinnedLogicValues,
    analyticsPinnedLogicActions,
    Record<string, any>,
    analyticsPinnedLogicMeta
>

/**
 * The analytics items and collections a person pinned. Pins are the project tree's shortcuts, which the
 * classic navigation lists as Starred, so a pin made here shows in every other place that lists them, and the reverse.
 */
export const analyticsPinnedLogic = kea<analyticsPinnedLogicType>([
    path(['scenes', 'analytics', 'analyticsPinnedLogic']),
    connect(() => ({
        values: [projectTreeDataLogic, ['shortcutData', 'shortcutDataLoading']],
        actions: [projectTreeDataLogic, ['addShortcutItem', 'deleteShortcut']],
    })),
    actions({
        togglePinned: (target: PinTarget) => ({ target }),
    }),
    selectors({
        pinnedAnalytics: [
            (s) => [s.shortcutData],
            (shortcutData: FileSystemEntry[]): PinnedAnalytics[] =>
                shortcutData.flatMap((shortcut): PinnedAnalytics[] => {
                    if (!shortcut.id || !shortcut.ref) {
                        return []
                    }
                    // A folder shortcut's `path` is its display name; `ref` holds the folder it points at.
                    if (shortcut.type === 'folder') {
                        return isSpacePath(shortcut.ref)
                            ? [
                                  {
                                      kind: 'collection',
                                      key: pinKey('folder', shortcut.ref),
                                      shortcutId: shortcut.id,
                                      path: shortcut.ref,
                                      name: fileSystemEntryName({ path: shortcut.ref }),
                                  },
                              ]
                            : []
                    }
                    const item = fileSystemEntryToAnalytics(shortcut)
                    return item
                        ? [{ kind: 'item', key: pinKey(item.type, item.id), shortcutId: shortcut.id, item }]
                        : []
                }),
        ],
        pinnedShortcutIds: [
            (s) => [s.pinnedAnalytics],
            (pinnedAnalytics: PinnedAnalytics[]): Map<string, string> =>
                new Map(pinnedAnalytics.map((pinned) => [pinned.key, pinned.shortcutId])),
        ],
        pinnedCollectionPaths: [
            (s) => [s.pinnedAnalytics],
            (pinnedAnalytics: PinnedAnalytics[]): Set<string> =>
                new Set(pinnedAnalytics.flatMap((pinned) => (pinned.kind === 'collection' ? [pinned.path] : []))),
        ],
    }),
    listeners(({ actions, values }) => ({
        togglePinned: ({ target }) => {
            // Every pin control is disabled while a change saves. This also stops a repeated dispatch.
            if (values.shortcutDataLoading) {
                return
            }
            const shortcutId = values.pinnedShortcutIds.get(pinKey(target.type, target.ref))
            if (shortcutId) {
                actions.deleteShortcut(shortcutId, 'Unpinned from sidebar')
            } else if (target.type === 'folder') {
                // A folder shortcut keeps its path as ref, so a rename moves the pin with the folder.
                actions.addShortcutItem({ path: target.ref, type: 'folder' } as FileSystemEntry, 'Pinned to sidebar')
            } else {
                actions.addShortcutItem(
                    {
                        path: escapePath(target.name),
                        type: target.type,
                        ref: target.ref,
                        href: target.href,
                    } as FileSystemEntry,
                    'Pinned to sidebar'
                )
            }
        },
    })),
])