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.

14.6 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'

import { FEATURE_FLAGS } from 'lib/constants'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { userLogic } from 'scenes/userLogic'

import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
import {
    SettingsVisibilityGates,
    isSettingVisible,
    matchesFlagDefinition,
    visibleSettingsSections,
} from '~/scenes/settings/flagGating'
import { getTitleText } from '~/scenes/settings/settingsSearch'
import type { SettingSection } from '~/scenes/settings/types'
import { IntegrationType, OrganizationType, PreflightStatus, TeamPublicType, TeamType, UserType } from '~/types'

import { SearchItem } from './searchItems'
import {
    CommandKSettingsSection,
    SettingsSectionSummary,
    commandKSettingsSearchItems,
    actionSearchItems,
    dataManagementSearchItems,
    healthSearchItems,
    newSearchItems,
    peopleSearchItems,
    productSearchItems,
    settingsSearchItems,
    starredSearchItems,
} from './searchListItems'

const summarizeSettingsSection = (section: SettingSection): SettingsSectionSummary => ({
    id: section.id,
    level: section.level,
    titleString: getTitleText(section.title) || null,
    hideFromNavigation: section.hideFromNavigation,
    flag: section.flag,
    to: section.to,
    keywords: section.keywords,
    settings: section.settings.map((setting) => ({
        id: setting.id,
        // A setting can render a title that getTitleText cannot read, such as a whole
        // component, and it must stay findable via its id token.
        // hasTitle preserves that distinction.
        hasTitle: !!setting.title,
        titleString: getTitleText(setting.title) || null,
        descriptionString:
            setting.searchDescription ?? (typeof setting.description === 'string' ? setting.description : null),
        keywords: setting.keywords,
        flag: setting.flag,
    })),
})

const summarizeCommandKSettingsSections = (
    sections: SettingSection[],
    gates: SettingsVisibilityGates
): CommandKSettingsSection[] =>
    visibleSettingsSections(sections, gates)
        .filter((section) => !section.hideFromNavigation)
        .map((section) => ({
            id: section.id,
            level: section.level === 'environment' ? 'project' : section.level,
            titleString: getTitleText(section.title) || null,
            to: section.to,
            keywords: section.keywords,
            settings: section.settings
                .filter((setting) => !!setting.title && isSettingVisible(setting, gates))
                .map((setting) => ({
                    id: setting.id,
                    titleString: getTitleText(setting.title) || null,
                    descriptionString:
                        setting.searchDescription ??
                        (typeof setting.description === 'string' ? setting.description : null),
                    keywords: setting.keywords,
                })),
        }))

export interface SearchListsLogicProps {
    /** The command palette runs `onSelect` items, so it gets rows other search surfaces cannot use. */
    commandPalette: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchListsLogicValues {
    billingEntryUrl: string | null // billingLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    organizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogic
    currentOrganization: OrganizationType | null // organizationLogic
    isAdminOrOwner: boolean | null // organizationLogic
    isCloudOrDev: boolean | undefined // preflightLogic
    isDev: boolean | undefined // preflightLogic
    preflight: PreflightStatus | null // preflightLogic
    cachedStarred: FileSystemEntry[] // projectTreeDataLogic
    treeGroupItems: FileSystemImport[] // projectTreeDataLogic
    sceneLogViewsByRef: Record<string, string> // recentItemsModel
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    user: UserType | null // userLogic
    actionItems: SearchItem[]
    commandKSettingsItems: SearchItem[]
    dataManagementItems: SearchItem[]
    hasOrganizationIntegrations: boolean
    healthItems: SearchItem[]
    newItems: SearchItem[]
    peopleItems: SearchItem[]
    productsItems: SearchItem[]
    settingsItems: SearchItem[]
    settingsMap: SettingSection[]
    settingsSections: SettingsSectionSummary[]
    showTerminal: boolean
    showUnreleased: boolean
    starredItems: SearchItem[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchListsLogicActions {
    toggleTerminal: () => {
        value: true
    } // terminalDockLogic
    setSettingsMap: (sections: SettingSection[]) => {
        sections: SettingSection[]
    }
    setSettingsSections: (sections: SettingsSectionSummary[]) => {
        sections: SettingsSectionSummary[]
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchListsLogicMeta {
    key: 'command-palette' | 'page'
    __keaTypeGenInternalSelectorTypes: {
        showUnreleased: (isDev: boolean | undefined, user: UserType | null) => boolean
        showTerminal: (featureFlags: FeatureFlagsSet, arg: boolean) => boolean
        hasOrganizationIntegrations: (organizationIntegrations: IntegrationType[] | null) => boolean
        starredItems: (cachedStarred: FileSystemEntry[]) => SearchItem[]
        productsItems: (
            featureFlags: FeatureFlagsSet,
            showUnreleased: boolean,
            sceneLogViewsByRef: Record<string, string>
        ) => SearchItem[]
        dataManagementItems: (
            featureFlags: FeatureFlagsSet,
            showUnreleased: boolean,
            sceneLogViewsByRef: Record<string, string>
        ) => SearchItem[]
        newItems: (featureFlags: FeatureFlagsSet, showUnreleased: boolean, arg: boolean) => SearchItem[]
        peopleItems: (treeGroupItems: FileSystemImport[], sceneLogViewsByRef: Record<string, string>) => SearchItem[]
        healthItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]
        actionItems: (showTerminal: boolean) => SearchItem[]
        settingsItems: (
            settingsSections: SettingsSectionSummary[],
            featureFlags: FeatureFlagsSet,
            hasOrganizationIntegrations: boolean,
            billingEntryUrl: string | null
        ) => SearchItem[]
        commandKSettingsItems: (
            settingsMap: SettingSection[],
            featureFlags: FeatureFlagsSet,
            isCloudOrDev: boolean | undefined,
            preflight: PreflightStatus | null,
            currentTeam: TeamPublicType | TeamType | null,
            currentOrganization: OrganizationType | null,
            hasOrganizationIntegrations: boolean,
            billingEntryUrl: string | null,
            isAdminOrOwner: boolean | null,
            user: UserType | null
        ) => SearchItem[]
    }
}

export type searchListsLogicType = MakeLogicType<
    searchListsLogicValues,
    searchListsLogicActions,
    SearchListsLogicProps,
    searchListsLogicMeta
>

/**
 * The search lists that need no request: products, starred items, settings, and the other fixed
 * destinations. Both the current palette and Command K search filter these in memory.
 */
export const searchListsLogic = kea<searchListsLogicType>([
    props({} as SearchListsLogicProps),
    key((props) => (props.commandPalette ? 'command-palette' : 'page')),
    path((key) => ['lib', 'components', 'Search', 'searchListsLogic', key]),
    connect(() => ({
        // Keeps the terminal dock mounted for the "Toggle terminal" row's onSelect.
        actions: [terminalDockLogic, ['toggleTerminal']],
        values: [
            featureFlagLogic,
            ['featureFlags'],
            preflightLogic,
            ['isDev', 'isCloudOrDev', 'preflight'],
            teamLogic,
            ['currentTeam'],
            organizationLogic,
            ['currentOrganization', 'isAdminOrOwner'],
            userLogic,
            ['user'],
            recentItemsModel,
            ['sceneLogViewsByRef'],
            projectTreeDataLogic,
            ['shortcutData as cachedStarred', 'groupItems as treeGroupItems'],
            organizationIntegrationsLogic,
            ['organizationIntegrations'],
            billingLogic,
            ['billingEntryUrl'],
        ],
    })),
    actions({
        setSettingsSections: (sections: SettingsSectionSummary[]) => ({ sections }),
        setSettingsMap: (sections: SettingSection[]) => ({ sections }),
    }),
    reducers({
        settingsSections: [
            [] as SettingsSectionSummary[],
            {
                setSettingsSections: (_, { sections }) => sections,
            },
        ],
        settingsMap: [
            [] as SettingSection[],
            {
                setSettingsMap: (_, { sections }) => sections,
            },
        ],
    }),
    selectors({
        showUnreleased: [
            (s) => [s.isDev, s.user],
            (isDev: boolean | undefined, user: UserType | null): boolean => !!isDev || !!user?.is_staff,
        ],
        showTerminal: [
            (s) => [s.featureFlags, (_, props: SearchListsLogicProps) => props.commandPalette],
            (featureFlags: FeatureFlagsSet, commandPalette: boolean): boolean =>
                commandPalette && !!featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL],
        ],
        hasOrganizationIntegrations: [
            (s) => [s.organizationIntegrations],
            (organizationIntegrations: IntegrationType[] | null): boolean => !!organizationIntegrations?.length,
        ],
        starredItems: [
            (s) => [s.cachedStarred],
            (cachedStarred: FileSystemEntry[]): SearchItem[] => starredSearchItems(cachedStarred),
        ],
        productsItems: [
            (s) => [s.featureFlags, s.showUnreleased, s.sceneLogViewsByRef],
            (
                featureFlags: FeatureFlagsSet,
                showUnreleased: boolean,
                sceneLogViewsByRef: Record<string, string>
            ): SearchItem[] => productSearchItems(featureFlags, showUnreleased, sceneLogViewsByRef),
        ],
        dataManagementItems: [
            (s) => [s.featureFlags, s.showUnreleased, s.sceneLogViewsByRef],
            (
                featureFlags: FeatureFlagsSet,
                showUnreleased: boolean,
                sceneLogViewsByRef: Record<string, string>
            ): SearchItem[] => dataManagementSearchItems(featureFlags, showUnreleased, sceneLogViewsByRef),
        ],
        newItems: [
            (s) => [s.featureFlags, s.showUnreleased, (_, props: SearchListsLogicProps) => props.commandPalette],
            (featureFlags: FeatureFlagsSet, showUnreleased: boolean, commandPalette: boolean): SearchItem[] =>
                newSearchItems(featureFlags, showUnreleased, commandPalette),
        ],
        peopleItems: [
            (s) => [s.treeGroupItems, s.sceneLogViewsByRef],
            (treeGroupItems: FileSystemImport[], sceneLogViewsByRef: Record<string, string>): SearchItem[] =>
                peopleSearchItems(treeGroupItems, sceneLogViewsByRef),
        ],
        healthItems: [
            (s) => [s.sceneLogViewsByRef],
            (sceneLogViewsByRef: Record<string, string>): SearchItem[] => healthSearchItems(sceneLogViewsByRef),
        ],
        actionItems: [
            (s) => [s.showTerminal],
            (showTerminal: boolean): SearchItem[] =>
                actionSearchItems(showTerminal ? () => terminalDockLogic.actions.toggleTerminal() : null),
        ],
        settingsItems: [
            (s) => [s.settingsSections, s.featureFlags, s.hasOrganizationIntegrations, s.billingEntryUrl],
            (
                settingsSections: SettingsSectionSummary[],
                featureFlags: FeatureFlagsSet,
                hasOrganizationIntegrations: boolean,
                billingEntryUrl: string | null
            ): SearchItem[] =>
                settingsSearchItems(settingsSections, {
                    isFlagEnabled: (flag) => matchesFlagDefinition(flag, featureFlags),
                    hasOrganizationIntegrations,
                    billingEntryUrl,
                }),
        ],
        commandKSettingsItems: [
            (s) => [
                s.settingsMap,
                s.featureFlags,
                s.isCloudOrDev,
                s.preflight,
                s.currentTeam,
                s.currentOrganization,
                s.hasOrganizationIntegrations,
                s.billingEntryUrl,
                s.isAdminOrOwner,
                s.user,
            ],
            (
                settingsMap: SettingSection[],
                featureFlags: FeatureFlagsSet,
                isCloudOrDev: boolean | undefined,
                preflight: PreflightStatus | null,
                currentTeam: TeamType | TeamPublicType | null,
                currentOrganization: OrganizationType | null,
                hasOrganizationIntegrations: boolean,
                billingEntryUrl: string | null,
                isAdminOrOwner: boolean | null,
                user: UserType | null
            ): SearchItem[] =>
                commandKSettingsSearchItems(
                    summarizeCommandKSettingsSections(settingsMap, {
                        featureFlags,
                        isCloudOrDev,
                        realm: preflight?.realm,
                        currentTeam,
                        currentOrganization,
                        hasOrganizationIntegrations,
                        billingEntryUrl,
                        isAdminOrOwner,
                        isStaff: !!user?.is_staff,
                    }),
                    billingEntryUrl
                ),
        ],
    }),
    afterMount(({ actions }) => {
        import('~/scenes/settings/SettingsMap')
            .then(({ SETTINGS_MAP }) => {
                actions.setSettingsSections(SETTINGS_MAP.map(summarizeSettingsSection))
                actions.setSettingsMap(SETTINGS_MAP)
            })
            .catch((error) => {
                console.error('Failed to load SETTINGS_MAP for settings search:', error)
            })
    }),
])