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.2 KB
Raw Blame
import FuseClass, { FuseResult } from 'fuse.js'
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { router } from 'kea-router'

import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { createFuse } from 'lib/utils/fuseSearch'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { dashboardsModel, nameCompareFunction } from '~/models/dashboardsModel'
import { DashboardBasicType, DashboardType, InsightLogicProps } from '~/types'

import type { Node } from '../../../queries/schema/schema-general'
import type { InsightModel, UserType } from '../../../types'

// Helping kea-typegen navigate the exported default class for Fuse
export interface Fuse extends FuseClass<any> {}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addToDashboardModalLogicValues {
    insight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic
    user: UserType | null // userLogic
    _dashboardToNavigateTo: number | null
    availableDashboards: DashboardBasicType[]
    currentDashboards: DashboardBasicType[]
    dashboardWithActiveAPICall: number | null
    dashboardsFuse: Fuse
    filteredDashboards: DashboardBasicType[]
    orderedDashboards: DashboardBasicType[]
    scrollIndex: number
    searchQuery: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addToDashboardModalLogicActions {
    reportCreatedDashboardFromModal: () => {
        value: true
    } // eventUsageLogic
    reportRemovedInsightFromDashboard: (
        insight: Partial<InsightModel<Node<Record<string, any>>>> | null,
        dashboardId: number | null
    ) => {
        dashboardId: number | null
        insight: Partial<InsightModel<Node<Record<string, any>>>> | null
    } // eventUsageLogic
    reportSavedInsightToDashboard: (
        insight: Partial<InsightModel<Node<Record<string, any>>>> | null,
        dashboardId: number | null
    ) => {
        dashboardId: number | null
        insight: Partial<InsightModel<Node<Record<string, any>>>> | null
    } // eventUsageLogic
    addInsightToDashboard: (
        dashboardId: number,
        callback?: (() => void) | undefined
    ) => {
        callback: (() => void) | undefined
        dashboardId: number
    } // insightLogic
    addInsightToDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // insightLogic
    addInsightToDashboardSuccess: (
        insight: InsightModel<Node<Record<string, any>>>,
        payload?:
            | {
                  callback: (() => void) | undefined
                  dashboardId: number
              }
            | undefined
    ) => {
        insight: InsightModel<Node<Record<string, any>>>
        payload?: {
            callback: (() => void) | undefined
            dashboardId: number
        }
    } // insightLogic
    removeInsightFromDashboard: (
        dashboardId: number,
        callback?: (() => void) | undefined
    ) => {
        callback: (() => void) | undefined
        dashboardId: number
    } // insightLogic
    removeInsightFromDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // insightLogic
    removeInsightFromDashboardSuccess: (
        insight: InsightModel<Node<Record<string, any>>>,
        payload?:
            | {
                  callback: (() => void) | undefined
                  dashboardId: number
              }
            | undefined
    ) => {
        insight: InsightModel<Node<Record<string, any>>>
        payload?: {
            callback: (() => void) | undefined
            dashboardId: number
        }
    } // insightLogic
    showNewDashboardModal: () => {
        value: true
    } // newDashboardLogic
    addNewDashboard: () => {
        value: true
    }
    addToDashboard: (dashboardId: number) => {
        dashboardId: number
    }
    removeFromDashboard: (dashboardId: number) => {
        dashboardId: number
    }
    setDashboardToNavigateTo: (dashboardId: number | null) => {
        dashboardId: number | null
    }
    setScrollIndex: (index: number) => {
        index: number
    }
    setSearchQuery: (query: string) => {
        query: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addToDashboardModalLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        dashboardsFuse: (nameSortedDashboards: (DashboardBasicType | DashboardType)[]) => Fuse
        filteredDashboards: (
            searchQuery: string,
            dashboardsFuse: Fuse,
            nameSortedDashboards: (DashboardBasicType | DashboardType)[]
        ) => DashboardBasicType[]
        currentDashboards: (
            filteredDashboards: DashboardBasicType[],
            insight: Partial<InsightModel<Node<Record<string, any>>>>
        ) => DashboardBasicType[]
        availableDashboards: (
            filteredDashboards: DashboardBasicType[],
            currentDashboards: DashboardBasicType[]
        ) => DashboardBasicType[]
        orderedDashboards: (
            currentDashboards: DashboardBasicType[],
            availableDashboards: DashboardBasicType[],
            user: UserType | null
        ) => DashboardBasicType[]
    }
}

export type addToDashboardModalLogicType = MakeLogicType<
    addToDashboardModalLogicValues,
    addToDashboardModalLogicActions,
    InsightLogicProps,
    addToDashboardModalLogicMeta
>

function showDashboardUpdateError(errorObject: unknown): void {
    // Surface hard rejections (e.g. the target dashboard is publicly shared and the
    // editor lacks access to this insight's tables) - the modal otherwise fails silently.
    const detail = (errorObject as { detail?: unknown } | null)?.detail
    lemonToast.error(typeof detail === 'string' ? detail : 'Could not update dashboards')
}

export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
    props({} as InsightLogicProps),
    key(keyForInsightLogicProps('new')),
    path((key) => ['lib', 'components', 'AddToDashboard', 'saveToDashboardModalLogic', key]),
    connect((props: InsightLogicProps) => ({
        values: [insightLogic(props), ['insight'], userLogic, ['user']],
        actions: [
            insightLogic(props),
            [
                'addInsightToDashboard',
                'addInsightToDashboardSuccess',
                'addInsightToDashboardFailure',
                'removeInsightFromDashboard',
                'removeInsightFromDashboardSuccess',
                'removeInsightFromDashboardFailure',
            ],
            eventUsageLogic,
            ['reportSavedInsightToDashboard', 'reportRemovedInsightFromDashboard', 'reportCreatedDashboardFromModal'],
            newDashboardLogic,
            ['showNewDashboardModal'],
        ],
    })),
    actions({
        addNewDashboard: true,
        setSearchQuery: (query: string) => ({ query }),
        setScrollIndex: (index: number) => ({ index }),
        addToDashboard: (dashboardId: number) => ({ dashboardId }),
        removeFromDashboard: (dashboardId: number) => ({ dashboardId }),
        setDashboardToNavigateTo: (dashboardId: number | null) => ({ dashboardId }),
    }),
    reducers({
        searchQuery: ['', { setSearchQuery: (_, { query }) => query }],
        scrollIndex: [-1 as number, { setScrollIndex: (_, { index }) => index }],
        dashboardWithActiveAPICall: [
            null as number | null,
            {
                addToDashboard: (_, { dashboardId }) => dashboardId,
                removeFromDashboard: (_, { dashboardId }) => dashboardId,
                addInsightToDashboardSuccess: () => null,
                addInsightToDashboardFailure: () => null,
                removeInsightFromDashboardSuccess: () => null,
                removeInsightFromDashboardFailure: () => null,
            },
        ],
        _dashboardToNavigateTo: [
            null as number | null,
            {
                setDashboardToNavigateTo: (_, { dashboardId }) => dashboardId,
            },
        ],
    }),
    selectors({
        dashboardsFuse: [
            () => [dashboardsModel.selectors.nameSortedDashboards],
            (nameSortedDashboards: (DashboardBasicType | DashboardType)[]): Fuse => {
                return createFuse(nameSortedDashboards || [], {
                    keys: ['name', 'description', 'tags'],
                })
            },
        ],
        filteredDashboards: [
            (s) => [s.searchQuery, s.dashboardsFuse, dashboardsModel.selectors.nameSortedDashboards],
            (
                searchQuery: string,
                dashboardsFuse: Fuse,
                nameSortedDashboards: (DashboardBasicType | DashboardType)[]
            ): DashboardBasicType[] =>
                searchQuery.length
                    ? dashboardsFuse.search(searchQuery).map((r: FuseResult<DashboardType>) => r.item)
                    : nameSortedDashboards,
        ],
        currentDashboards: [
            (s) => [s.filteredDashboards, s.insight],
            (
                filteredDashboards: DashboardBasicType[],
                insight: Partial<
                    import('~/types').InsightModel<import('../../../queries/schema').Node<Record<string, any>>>
                >
            ): DashboardBasicType[] =>
                filteredDashboards.filter((d) => liveDashboardIds(insight.dashboard_tiles).includes(d.id)),
        ],
        availableDashboards: [
            (s) => [s.filteredDashboards, s.currentDashboards],
            (filteredDashboards: DashboardBasicType[], currentDashboards: DashboardBasicType[]): DashboardBasicType[] =>
                filteredDashboards.filter((d) => !currentDashboards?.map((cd) => cd.id).includes(d.id)),
        ],
        orderedDashboards: [
            (s) => [s.currentDashboards, s.availableDashboards, userLogic.selectors.user],
            (
                currentDashboards: DashboardBasicType[],
                availableDashboards: DashboardBasicType[],
                user: null | import('~/types').UserType
            ): DashboardBasicType[] => {
                const myUuid = user?.uuid ?? null
                const currentSorted = [...currentDashboards].sort(nameCompareFunction)
                const isMine = (d: DashboardBasicType): boolean => myUuid !== null && d.created_by?.uuid === myUuid
                const mineAvailable = availableDashboards.filter(isMine).sort(nameCompareFunction)
                const othersPinnedAvailable = availableDashboards
                    .filter((d) => d.pinned && !isMine(d))
                    .sort(nameCompareFunction)
                const othersUnpinnedAvailable = availableDashboards
                    .filter((d) => !d.pinned && !isMine(d))
                    .sort(nameCompareFunction)
                return [...currentSorted, ...mineAvailable, ...othersPinnedAvailable, ...othersUnpinnedAvailable]
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        addNewDashboard: async () => {
            actions.showNewDashboardModal()
            newDashboardLogic.actions.setRedirectAfterCreation(false)
        },

        [dashboardsModel.actionTypes.addDashboardSuccess]: async ({ dashboard }) => {
            actions.reportCreatedDashboardFromModal()
            actions.setDashboardToNavigateTo(dashboard.id)
            actions.addToDashboard(dashboard.id)
            actions.setScrollIndex(values.orderedDashboards.findIndex((d) => d.id === dashboard.id))
        },

        addInsightToDashboardFailure: ({ errorObject }) => {
            showDashboardUpdateError(errorObject)
        },
        removeInsightFromDashboardFailure: ({ errorObject }) => {
            showDashboardUpdateError(errorObject)
        },
        addToDashboard: async ({ dashboardId }) => {
            actions.addInsightToDashboard(dashboardId, () => {
                actions.reportSavedInsightToDashboard(values.insight, dashboardId)
                dashboardsModel.actions.tileAddedToDashboard(dashboardId)
                if (values._dashboardToNavigateTo === dashboardId) {
                    actions.setDashboardToNavigateTo(null)
                    router.actions.push(urls.dashboard(dashboardId))
                } else {
                    lemonToast.success('Insight added to dashboard', {
                        button: {
                            label: 'View dashboard',
                            action: () => router.actions.push(urls.dashboard(dashboardId)),
                        },
                    })
                }
            })
        },
        removeFromDashboard: async ({ dashboardId }): Promise<void> => {
            actions.removeInsightFromDashboard(dashboardId, () => {
                actions.reportRemovedInsightFromDashboard(values.insight, dashboardId)
                lemonToast.success('Insight removed from dashboard')
            })
        },
    })),
])