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

import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
import { AvailableFeature, SidePanelTab } from '~/types'

import type { TeamPublicType, TeamType } from '../../../types'
import { sidePanelContextLogic } from './sidePanelContextLogic'
import { sidePanelStateLogic } from './sidePanelStateLogic'
import type { SidePanelSceneContext } from './types'

const TABS_REQUIRING_A_TEAM = [
    SidePanelTab.Max,
    SidePanelTab.Notebooks,
    SidePanelTab.Activity,
    SidePanelTab.Discussion,
    SidePanelTab.AccessControl,
    SidePanelTab.Exports,
]

/**
 * Tabs whose content is not about the current page (an AI chat, a support ticket draft, a notebook),
 * so they stay open across navigation. Every other tab describes the object on screen and closes
 * when the user moves to a different scene.
 */
export const TABS_PERSISTED_ACROSS_NAVIGATION = [SidePanelTab.Max, SidePanelTab.Support, SidePanelTab.Notebooks]

/** The tabs a canvas scene shows instead of the general ones, in order. */
export const CANVAS_SIDE_PANEL_TABS = [SidePanelTab.CanvasChat, SidePanelTab.CanvasBlocks, SidePanelTab.CanvasTimeline]

/**
 * Closes the panel when the context it described goes away — a tab like activity logs or access
 * control left open after navigating elsewhere would otherwise stay up showing stale content and
 * cost an extra click to dismiss. Called on scene changes, and separately on settings section
 * changes, since all settings sections share one scene. Tabs in TABS_PERSISTED_ACROSS_NAVIGATION
 * and explicit #panel= deep links stay open.
 */
function closeContextBoundTab(
    values: { sidePanelOpen: boolean; selectedTab: SidePanelTab | null },
    actions: { closeSidePanel: () => void }
): void {
    if (!values.sidePanelOpen) {
        return
    }
    // An explicit #panel= hash on the destination URL (deep link) wins over closing
    if (router.values.hashParams['panel']) {
        return
    }
    if (values.selectedTab && TABS_PERSISTED_ACROSS_NAVIGATION.includes(values.selectedTab)) {
        return
    }
    actions.closeSidePanel()
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidePanelLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    isCloudOrDev: boolean | undefined // preflightLogic
    location: {
        pathname: string
        search: string
        hash: string
    } // router
    scenePanelIsPresent: boolean // sceneLayoutLogic
    sceneSidePanelContext: SidePanelSceneContext // sidePanelContextLogic
    selectedTab: SidePanelTab | null // sidePanelStateLogic
    sidePanelOpen: boolean // sidePanelStateLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    defaultTab: SidePanelTab
    deprecatedTabs: SidePanelTab[]
    enabledTabs: SidePanelTab[]
    isAccessControlSettings: boolean
    visibleTabs: SidePanelTab[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidePanelLogicActions {
    closeSidePanel: (tab?: SidePanelTab | undefined) => {
        tab: SidePanelTab | undefined
    } // sidePanelStateLogic
    openSidePanel: (
        tab: SidePanelTab,
        options?: string | undefined
    ) => {
        options: string | undefined
        tab: SidePanelTab
    } // sidePanelStateLogic
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidePanelLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isAccessControlSettings: (
            location: { hash: string; pathname: string; search: string },
            featureFlags: FeatureFlagsSet
        ) => boolean
        enabledTabs: (
            sceneSidePanelContext: SidePanelSceneContext,
            currentTeam: TeamPublicType | TeamType | null,
            scenePanelIsPresent: boolean,
            isCloudOrDev: boolean | undefined,
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean, // userLogic
            isAccessControlSettings: boolean
        ) => SidePanelTab[]
        deprecatedTabs: (featureFlags: FeatureFlagsSet) => SidePanelTab[]
        defaultTab: (scenePanelIsPresent: boolean, deprecatedTabs: SidePanelTab[]) => SidePanelTab
        visibleTabs: (
            enabledTabs: SidePanelTab[],
            sceneSidePanelContext: SidePanelSceneContext,
            featureFlags: FeatureFlagsSet,
            deprecatedTabs: SidePanelTab[]
        ) => SidePanelTab[]
    }
}

export type sidePanelLogicType = MakeLogicType<
    sidePanelLogicValues,
    sidePanelLogicActions,
    Record<string, any>,
    sidePanelLogicMeta
>

export const sidePanelLogic = kea<sidePanelLogicType>([
    path(['scenes', 'navigation', 'sidepanel', 'sidePanelLogic']),
    connect(() => ({
        values: [
            sidePanelStateLogic,
            ['selectedTab', 'sidePanelOpen'],
            sidePanelContextLogic,
            ['sceneSidePanelContext'],
            teamLogic,
            ['currentTeam'],
            sceneLayoutLogic,
            ['scenePanelIsPresent'],
            preflightLogic,
            ['isCloudOrDev'],
            userLogic,
            ['hasAvailableFeature'],
            featureFlagLogic,
            ['featureFlags'],
            router,
            ['location'],
        ],
        actions: [sidePanelStateLogic, ['closeSidePanel', 'openSidePanel']],
    })),

    selectors({
        /** The access control settings page shows member/role access in the side panel */
        isAccessControlSettings: [
            (s) => [s.location, s.featureFlags],
            (location: { hash: string; pathname: string; search: string }, featureFlags: FeatureFlagsSet): boolean =>
                !!featureFlags[FEATURE_FLAGS.ACCESS_CONTROL_DETAIL_PANEL] &&
                /\/settings\/(environment|project)-access-control$/.test(location.pathname),
        ],

        enabledTabs: [
            (s) => [
                s.sceneSidePanelContext,
                s.currentTeam,
                s.scenePanelIsPresent,
                s.isCloudOrDev,
                s.hasAvailableFeature,
                s.isAccessControlSettings,
            ],
            (
                sceneSidePanelContext: import('./types').SidePanelSceneContext,
                currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
                scenePanelIsPresent: boolean,
                isCloudOrDev: boolean | undefined,
                hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean,
                isAccessControlSettings: boolean
            ) => {
                if (sceneSidePanelContext.canvas_id && currentTeam) {
                    // Support stays openable from the help menu, but the canvas tabs take the bar.
                    return [
                        ...CANVAS_SIDE_PANEL_TABS.filter(
                            (tab) => tab !== SidePanelTab.CanvasBlocks || sceneSidePanelContext.canvas_blocks
                        ),
                        SidePanelTab.Exports,
                        ...(isCloudOrDev ? [SidePanelTab.Support] : []),
                    ]
                }

                const tabs: SidePanelTab[] = []

                if (scenePanelIsPresent) {
                    tabs.push(SidePanelTab.Info)
                }

                tabs.push(SidePanelTab.Max)
                tabs.push(SidePanelTab.Notebooks)

                // Activity entries and comments are both stored against the scene's activity scope. A
                // scene that declares none has nothing to show, and the discussion panel can only
                // render its "not supported here" state.
                if (sceneSidePanelContext?.activity_scope) {
                    if (hasAvailableFeature(AvailableFeature.AUDIT_LOGS)) {
                        tabs.push(SidePanelTab.Activity)
                    }
                    tabs.push(SidePanelTab.Discussion)
                }

                if (sceneSidePanelContext.access_control_resource && sceneSidePanelContext.access_control_resource_id) {
                    tabs.push(SidePanelTab.AccessControl)
                }

                if (isAccessControlSettings) {
                    tabs.push(SidePanelTab.AccessDetail)
                }

                // Exports and Support are openable programmatically but not shown in the nav bar
                tabs.push(SidePanelTab.Exports)

                if (isCloudOrDev) {
                    tabs.push(SidePanelTab.Support)
                }

                // Notebooks and discussions attach to a specific object, so they have nothing to show on the
                // access control settings page and would only render their "not supported here" state.
                const notApplicable: SidePanelTab[] = isAccessControlSettings
                    ? [SidePanelTab.Notebooks, SidePanelTab.Discussion]
                    : []
                const applicableTabs = tabs.filter((tab) => !notApplicable.includes(tab))

                if (!currentTeam) {
                    return applicableTabs.filter((tab) => !TABS_REQUIRING_A_TEAM.includes(tab))
                }

                return applicableTabs
            },
        ],

        /** Tabs on their way out. They stay usable, but sit at the end of the bar and never open by default. */
        deprecatedTabs: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): SidePanelTab[] =>
                featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] ? [SidePanelTab.Info] : [],
        ],
        defaultTab: [
            (s) => [s.scenePanelIsPresent, s.deprecatedTabs],
            (scenePanelIsPresent: boolean, deprecatedTabs: SidePanelTab[]): SidePanelTab =>
                scenePanelIsPresent && !deprecatedTabs.includes(SidePanelTab.Info)
                    ? SidePanelTab.Info
                    : SidePanelTab.Max,
        ],
        /** Tabs shown in the navigation bar */
        visibleTabs: [
            (s) => [s.enabledTabs, s.sceneSidePanelContext, s.featureFlags, s.deprecatedTabs],
            (
                enabledTabs: SidePanelTab[],
                sceneSidePanelContext: SidePanelSceneContext,
                featureFlags: FeatureFlagsSet,
                deprecatedTabs: SidePanelTab[]
            ): SidePanelTab[] => {
                // Some tabs are openable programmatically but not shown in the nav bar
                const hiddenTabs: SidePanelTab[] = sceneSidePanelContext.canvas_id
                    ? [SidePanelTab.Exports, SidePanelTab.Support]
                    : [SidePanelTab.Exports]
                // The Today layout has no home for these tabs yet. They stay openable from their entry points.
                if (featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {
                    hiddenTabs.push(SidePanelTab.Discussion, SidePanelTab.Notebooks)
                }
                const tabs = enabledTabs.filter((tab) => !hiddenTabs.includes(tab))
                return [
                    ...tabs.filter((tab) => !deprecatedTabs.includes(tab)),
                    ...tabs.filter((tab) => deprecatedTabs.includes(tab)),
                ]
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        // Close context-bound tabs when the user moves to a different scene: their content describes
        // the page being left. Comparing scenes (not URLs) keeps the panel open across in-page tab
        // switches, filter changes, and search params. Tabs in TABS_PERSISTED_ACROSS_NAVIGATION hold
        // cross-page state and survive.
        [sceneLogic.actionTypes.setScene]: ({ sceneId }: { sceneId: string }, _: any, __: any, previousState: any) => {
            // Not the sceneId selector: setExportedScene already wrote the new sceneId before setScene fires
            const previousSceneId = sceneLogic.selectors.lastSetScenePayload(previousState)?.sceneId
            if (!previousSceneId || previousSceneId === sceneId) {
                return
            }
            closeContextBoundTab(values, actions)
        },
    })),
    urlToAction(({ actions, values, cache }) => {
        return {
            // All settings sections share one scene, so the setScene listener above never fires between
            // them — but each section is its own context, so apply the same close rules on section change.
            // The section lives in the pathname, keeping search-param changes (tabs, filters) from closing.
            '/settings/:section': ({ section }): void => {
                const previousSection = cache.lastSettingsSection
                cache.lastSettingsSection = section
                if (previousSection && previousSection !== section) {
                    closeContextBoundTab(values, actions)
                }
            },
            '/': (_, _searchParams, hashParams): void => {
                // Redirect old feature preview side panel links to new settings page
                if (hashParams.panel?.startsWith('feature-previews')) {
                    // it will be encoded as %3A, so we need to split on :
                    const parts = hashParams.panel.split(':')
                    // from: ${url}/#panel=feature-previews
                    // to:   ${url}/settings/user-feature-previews
                    if (parts.length > 1) {
                        // from: ${url}/#panel=feature-previews%3A${flagKey} or ${url}/#panel=feature-previews:${flagKey}
                        // to:   ${url}/settings/user-feature-previews#${flagKey}
                        router.actions.replace(combineUrl(urls.settings('user-feature-previews'), {}, parts[1]).url)
                    } else {
                        router.actions.replace(urls.settings('user-feature-previews'))
                    }
                }
            },
        }
    }),
])