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.

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

import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'

import {
    getNavProductItems,
    groupNavProducts,
    navProductHrefForPath,
    pinnedNavProducts,
} from '~/layout/panel-layout/navbar/tabs/navProductItems'
import { ProductsItemGroup, productMatchesSearch } from '~/layout/panel-layout/navbar/tabs/productsCatalog'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { findProductShortcut } from '~/layout/panel-layout/ProjectTree/utils'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'

import { isPeopleListPath } from './todayPeople'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayProductsLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    shortcutData: FileSystemEntry[] // projectTreeDataLogic
    shortcutDataLoading: boolean // projectTreeDataLogic
    location: {
        pathname: string
        search: string
        hash: string
    } // router
    activeHref: string | null
    allProductsOpen: boolean
    pinnedProducts: FileSystemImport[]
    productCount: number
    productGroups: ProductsItemGroup[]
    products: FileSystemImport[]
    search: string
    starredHrefs: Set<string>
    starredOpen: boolean
    starredProducts: FileSystemImport[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayProductsLogicActions {
    addShortcutItem: (
        item: FileSystemEntry,
        successMessage?: string | undefined
    ) => {
        item: FileSystemEntry
        successMessage: string | undefined
    } // projectTreeDataLogic
    deleteShortcut: (
        id: string,
        successMessage?: string | undefined
    ) => {
        id: string
        successMessage: string | undefined
    } // projectTreeDataLogic
    setAllProductsOpen: (open: boolean) => {
        open: boolean
    }
    setSearch: (search: string) => {
        search: string
    }
    setStarredOpen: (open: boolean) => {
        open: boolean
    }
    toggleStarred: (item: FileSystemImport) => {
        item: FileSystemImport
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayProductsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        products: (featureFlags: FeatureFlagsSet) => FileSystemImport[]
        pinnedProducts: (products: FileSystemImport[], search: string) => FileSystemImport[]
        productGroups: (products: FileSystemImport[], search: string) => ProductsItemGroup[]
        productCount: (productGroups: ProductsItemGroup[]) => number
        activeHref: (
            location: {
                hash: string
                pathname: string
                search: string
            },
            products: FileSystemImport[]
        ) => string | null
        starredProducts: (
            shortcutData: FileSystemEntry[],
            products: FileSystemImport[],
            search: string
        ) => FileSystemImport[]
        starredHrefs: (shortcutData: FileSystemEntry[], products: FileSystemImport[]) => Set<string>
    }
}

export type todayProductsLogicType = MakeLogicType<
    todayProductsLogicValues,
    todayProductsLogicActions,
    Record<string, any>,
    todayProductsLogicMeta
>

/** The products behind the product stars, in saved order. A star made before a rename still finds its product by href. */
export function resolveStarredProducts(
    shortcuts: FileSystemEntry[],
    candidates: FileSystemImport[]
): FileSystemImport[] {
    const seen = new Set<string>()
    return shortcuts.flatMap((shortcut) => {
        const item = candidates.find((candidate) => !!candidate.href && findProductShortcut(candidate, [shortcut]))
        if (!item?.href || seen.has(item.href)) {
            return []
        }
        seen.add(item.href)
        return [item]
    })
}

function peoplePaneListsProduct(item: FileSystemImport): boolean {
    const href = item.href?.split(/[?#]/)[0]
    return !!href && isPeopleListPath(href)
}

export const todayProductsLogic = kea<todayProductsLogicType>([
    path(['layout', 'today', 'todayProductsLogic']),
    connect(() => ({
        values: [
            projectTreeDataLogic,
            ['shortcutData', 'shortcutDataLoading'],
            featureFlagLogic,
            ['featureFlags'],
            router,
            ['location'],
        ],
        actions: [projectTreeDataLogic, ['addShortcutItem', 'deleteShortcut']],
    })),
    actions({
        setSearch: (search: string) => ({ search }),
        setStarredOpen: (open: boolean) => ({ open }),
        setAllProductsOpen: (open: boolean) => ({ open }),
        toggleStarred: (item: FileSystemImport) => ({ item }),
    }),
    reducers({
        search: ['', { setSearch: (_, { search }) => search }],
        // pinned: storage keys for persisted state. Renaming them resets everyone's sections.
        starredOpen: [true, { persist: true }, { setStarredOpen: (_, { open }) => open }],
        allProductsOpen: [
            inStorybook() || inStorybookTestRunner(),
            { persist: true },
            { setAllProductsOpen: (_, { open }) => open },
        ],
    }),
    selectors({
        // The same list as the Products tab of the current navigation. Home and People have their own rail items.
        products: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): FileSystemImport[] =>
                getNavProductItems(featureFlags).filter(
                    (item) =>
                        item.href !== urls.projectRoot() &&
                        !getProductAccessDisabledReason(item) &&
                        !peoplePaneListsProduct(item)
                ),
        ],
        pinnedProducts: [
            (s) => [s.products, s.search],
            (products: FileSystemImport[], search: string): FileSystemImport[] => pinnedNavProducts(products, search),
        ],
        productGroups: [
            (s) => [s.products, s.search],
            (products: FileSystemImport[], search: string): ProductsItemGroup[] => groupNavProducts(products, search),
        ],
        productCount: [
            (s) => [s.productGroups],
            (groups: ProductsItemGroup[]): number => groups.reduce((count, group) => count + group.items.length, 0),
        ],
        // Every row, starred ones too, is in the product list, so the best match there is the only active row.
        activeHref: [
            (s) => [s.location, s.products],
            (location: { pathname: string }, products: FileSystemImport[]): string | null =>
                navProductHrefForPath(removeProjectIdIfPresent(location.pathname), products),
        ],
        starredProducts: [
            (s) => [s.shortcutData, s.products, s.search],
            (shortcuts: FileSystemEntry[], products: FileSystemImport[], search: string): FileSystemImport[] =>
                resolveStarredProducts(shortcuts, products).filter((item) => productMatchesSearch(item, search)),
        ],
        starredHrefs: [
            (s) => [s.shortcutData, s.products],
            (shortcuts: FileSystemEntry[], products: FileSystemImport[]): Set<string> =>
                new Set(resolveStarredProducts(shortcuts, products).map((item) => item.href ?? '')),
        ],
    }),
    listeners(({ actions, values }) => ({
        toggleStarred: ({ item }) => {
            // The star buttons are disabled while a change saves. This also stops a repeated dispatch.
            if (values.shortcutDataLoading) {
                return
            }
            const shortcut = findProductShortcut(item, values.shortcutData)
            if (shortcut?.id) {
                actions.deleteShortcut(shortcut.id)
            } else {
                actions.addShortcutItem(item as FileSystemEntry)
            }
        },
    })),
])