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.

36.6 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'
import { v4 as uuid } from 'uuid'

import api, { PaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { GENERATED_DASHBOARD_PREFIX } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { idToKey } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { parentPath, reparentPath } from '~/layout/panel-layout/ProjectTree/utils'
import { tagsModel } from '~/models/tagsModel'
import { DashboardBasicType, DashboardTile, DashboardType, InsightShortId, InsightModel } from '~/types'

import { dashboardsBulkDeleteCreate, dashboardsList } from 'products/dashboards/frontend/generated/api'
import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'

import type { Node } from '../queries/schema/schema-general'

export function getRemovedDashboardIds({ deleted, skipped }: DashboardBulkDeleteResponseApi): number[] {
    return [...deleted, ...skipped.filter(({ reason }) => reason === 'Dashboard not found').map(({ id }) => id)]
}

function reportDashboardPinToggled(dashboardId: number, pinned: boolean, source: DashboardEventSource): void {
    posthog.capture(`dashboard pin toggled`, {
        dashboard_id: dashboardId,
        pinned,
        source,
    })
}

/** A dashboard's folder is its file system path without the dashboard's own name, so the two move together. */
function filedAt<T extends DashboardBasicType | DashboardType>(dashboard: T, path: string): T {
    return { ...dashboard, file_system_path: path, folder: parentPath(path) }
}

export function mergeTileTextUpdatesIntoDashboard(
    dashboard: DashboardType,
    tilesPayload: Partial<DashboardTile>[] | undefined
): DashboardType {
    // Optimistically reconcile text tile updates in-place after save.
    // Some dashboard PATCH responses can momentarily return stale tile.text values, so we patch the
    // returned dashboard with the just-submitted text fields for matching tiles to avoid UI flicker/regression.
    // We only merge editable fields so server-owned metadata (timestamps, modifier fields, etc.) remains authoritative.
    if (!tilesPayload?.length || !dashboard.tiles?.length) {
        return dashboard
    }

    const incomingTextByTileId = new Map<number, NonNullable<DashboardTile['text']>>()
    for (const tile of tilesPayload) {
        if (typeof tile.id !== 'number' || !tile.text) {
            continue
        }
        incomingTextByTileId.set(tile.id, tile.text)
    }

    if (incomingTextByTileId.size === 0) {
        return dashboard
    }

    return {
        ...dashboard,
        tiles: dashboard.tiles.map((tile) => {
            const incomingText = incomingTextByTileId.get(tile.id)
            if (!incomingText) {
                return tile
            }

            return {
                ...tile,
                text: tile.text
                    ? {
                          ...tile.text,
                          ...(incomingText.body !== undefined ? { body: incomingText.body } : {}),
                          ...(incomingText.agent_context !== undefined
                              ? { agent_context: incomingText.agent_context }
                              : {}),
                      }
                    : incomingText,
            }
        }),
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsModelValues {
    bulkDeleteResponse: DashboardBulkDeleteResponseApi | null
    bulkDeleteResponseLoading: boolean
    dashboard: DashboardType | null
    dashboardLoading: boolean
    dashboardsLoading: boolean
    loadDashboardsFailed: boolean
    nameSortedDashboards: (DashboardBasicType | DashboardType)[]
    pagedDashboards: PaginatedResponse<DashboardBasicType> | null
    pagedDashboardsLoading: boolean
    pagingDashboardsCompleted: boolean
    pinSortedDashboards: (DashboardBasicType | DashboardType)[]
    pinnedDashboards: (DashboardBasicType | DashboardType)[]
    rawDashboards: Record<string, DashboardBasicType | DashboardType>
    redirect: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsModelActions {
    loadTags: () => {
        value: true
    } // tagsModel
    addDashboardSuccess: (dashboard: DashboardType) => {
        dashboard: DashboardType
    }
    bulkDeleteDashboards: ({
        ids,
        deleteInsights,
        onStillSelected,
    }: {
        deleteInsights?: boolean
        ids: number[]
        onStillSelected: (ids: number[]) => void
    }) => {
        ids: number[]
        deleteInsights?: boolean
        onStillSelected: (ids: number[]) => void
    }
    bulkDeleteDashboardsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    bulkDeleteDashboardsSuccess: (
        bulkDeleteResponse: DashboardBulkDeleteResponseApi,
        payload?: {
            ids: number[]
            deleteInsights?: boolean
            onStillSelected: (ids: number[]) => void
        }
    ) => {
        bulkDeleteResponse: DashboardBulkDeleteResponseApi
        payload?: {
            ids: number[]
            deleteInsights?: boolean
            onStillSelected: (ids: number[]) => void
        }
    }
    dashboardsFullyLoaded: () => {
        value: true
    }
    delayedDeleteDashboard: (id: number) => {
        id: number
    }
    deleteDashboard: ({ id, deleteInsights }: any) => any
    deleteDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteDashboardSuccess: (
        dashboard: DashboardType,
        payload?: any
    ) => {
        dashboard: DashboardType
        payload?: any
    }
    duplicateDashboard: ({
        id,
        name,
        show,
        duplicateTiles,
    }: {
        duplicateTiles?: boolean
        id: number
        name?: string
        show?: boolean
    }) => {
        duplicateTiles: boolean
        id: number
        name: string
        show: boolean
    }
    duplicateDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    duplicateDashboardSuccess: (
        dashboard: DashboardType,
        payload?: {
            duplicateTiles: boolean
            id: number
            name: string
            show: boolean
        }
    ) => {
        dashboard: DashboardType
        payload?: {
            duplicateTiles: boolean
            id: number
            name: string
            show: boolean
        }
    }
    loadDashboards: (url?: string) => string
    loadDashboardsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDashboardsIfNeeded: () => {
        value: true
    }
    loadDashboardsSuccess: (
        pagedDashboards:
            | PaginatedResponse<DashboardType>
            | {
                  count: number
                  next: null
                  previous: null
                  results: DashboardBasicType[]
              },
        payload?: string
    ) => {
        pagedDashboards:
            | PaginatedResponse<DashboardType>
            | {
                  count: number
                  next: null
                  previous: null
                  results: DashboardBasicType[]
              }
        payload?: string
    }
    patchDashboardFolders: (paths: Record<string, string>) => {
        paths: Record<string, string>
    }
    pinDashboard: (
        id: number,
        source: DashboardEventSource
    ) => {
        id: number
        source: DashboardEventSource
    }
    pinDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    pinDashboardSuccess: (
        dashboard: DashboardType,
        payload?: {
            id: number
            source: DashboardEventSource
        }
    ) => {
        dashboard: DashboardType
        payload?: {
            id: number
            source: DashboardEventSource
        }
    }
    reloadDashboards: (_: { ids: number[]; onStillSelected: (ids: number[]) => void }) => {
        ids: number[]
        onStillSelected: (ids: number[]) => void
    }
    reloadDashboardsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    reloadDashboardsSuccess: (
        pagedDashboards: {
            count: number
            next: null
            previous: null
            results: DashboardBasicType[]
        } | null,
        payload?: {
            ids: number[]
            onStillSelected: (ids: number[]) => void
        }
    ) => {
        pagedDashboards: {
            count: number
            next: null
            previous: null
            results: DashboardBasicType[]
        } | null
        payload?: {
            ids: number[]
            onStillSelected: (ids: number[]) => void
        }
    }
    removeDashboardsFromCache: (ids: number[]) => {
        ids: number[]
    }
    reparentDashboardFolders: (
        oldPath: string,
        newPath: string
    ) => {
        newPath: string
        oldPath: string
    }
    restoreDashboard: ({ id }: any) => any
    restoreDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    restoreDashboardSuccess: (
        dashboard: DashboardType,
        payload?: any
    ) => {
        dashboard: DashboardType
        payload?: any
    }
    setDiveSourceId: (id: InsightShortId | null) => {
        id: InsightShortId | null
    }
    tileAddedToDashboard: (dashboardId: number) => {
        dashboardId: number
    }
    tileMovedToDashboard: (
        tile: DashboardTile,
        dashboardId: number
    ) => {
        dashboardId: number
        tile: DashboardTile
    }
    tileRemovedFromDashboard: ({ tile, dashboardId }: { dashboardId?: number; tile?: DashboardTile }) => {
        dashboardId: number | undefined
        tile: DashboardTile | undefined
    }
    unpinDashboard: (
        id: number,
        source: DashboardEventSource
    ) => {
        id: number
        source: DashboardEventSource
    }
    unpinDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    unpinDashboardSuccess: (
        dashboard: DashboardType,
        payload?: {
            id: number
            source: DashboardEventSource
        }
    ) => {
        dashboard: DashboardType
        payload?: {
            id: number
            source: DashboardEventSource
        }
    }
    updateDashboard: ({ id, allowUndo, discardResult, ...payload }: any) => any
    updateDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateDashboardInsight: (
        insight: InsightModel,
        extraDashboardIds?: number[],
        sourceDashboardId?: number
    ) => {
        extraDashboardIds: number[] | undefined
        insight: InsightModel<Node<Record<string, any>>>
        sourceDashboardId: number | undefined
    }
    updateDashboardSuccess: (
        dashboard: DashboardType | null | undefined,
        payload?: any
    ) => {
        dashboard: DashboardType | null | undefined
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsModelMeta {
    __keaTypeGenInternalSelectorTypes: {
        nameSortedDashboards: (
            rawDashboards: Record<string, DashboardBasicType | DashboardType>
        ) => (DashboardBasicType | DashboardType)[]
        pinSortedDashboards: (
            nameSortedDashboards: (DashboardBasicType | DashboardType)[]
        ) => (DashboardBasicType | DashboardType)[]
        dashboardsLoading: (pagedDashboardsLoading: boolean, pagingDashboardsCompleted: boolean) => boolean
        pinnedDashboards: (
            nameSortedDashboards: (DashboardBasicType | DashboardType)[]
        ) => (DashboardBasicType | DashboardType)[]
    }
}

export type dashboardsModelType = MakeLogicType<
    dashboardsModelValues,
    dashboardsModelActions,
    Record<string, any>,
    dashboardsModelMeta
>

export const dashboardsModel = kea<dashboardsModelType>([
    path(['models', 'dashboardsModel']),
    connect(() => ({
        actions: [tagsModel, ['loadTags']],
    })),
    actions(() => ({
        loadDashboardsIfNeeded: true,
        removeDashboardsFromCache: (ids: number[]) => ({ ids }),
        // we page through the dashboards and need to manually track when that is finished
        dashboardsFullyLoaded: true,
        delayedDeleteDashboard: (id: number) => ({ id }),
        patchDashboardFolders: (paths: Record<string, string>) => ({ paths }),
        reparentDashboardFolders: (oldPath: string, newPath: string) => ({ oldPath, newPath }),
        setDiveSourceId: (id: InsightShortId | null) => ({ id }),
        addDashboardSuccess: (dashboard: DashboardType) => ({ dashboard }),
        /**
         * this is moved out of dashboardLogic, so that you can click "undo" on an item move when already
         * on another dashboard - both dashboards can listen to and share this event, even if one is not yet mounted
         * can provide extra dashboard ids if not all listeners will choose to respond to this action
         * not providing a dashboard id is a signal that only listeners in the item.dashboards array should respond
         * specifying `number` not `Pick<DashboardType, 'id'> because kea typegen couldn't figure out the import in `savedInsightsLogic`
         * if an update is made against an insight it will hold color in dashboard context
         * @param extraDashboardIds - Same meaning as before: merged with `dashboard_tiles` so listeners still match
         *   when placement info is incomplete (copy/move/remove).
         * @param sourceDashboardId - Set for a dashboard-scoped GET/refresh; merged `query` is only valid for that dashboard.
         */
        updateDashboardInsight: (insight: InsightModel, extraDashboardIds?: number[], sourceDashboardId?: number) => ({
            insight,
            extraDashboardIds,
            sourceDashboardId,
        }),
        pinDashboard: (id: number, source: DashboardEventSource) => ({ id, source }),
        unpinDashboard: (id: number, source: DashboardEventSource) => ({ id, source }),
        duplicateDashboard: ({
            id,
            name,
            show,
            duplicateTiles,
        }: {
            id: number
            name?: string
            show?: boolean
            duplicateTiles?: boolean
        }) => ({
            id: id,
            name: name || `#${id}`,
            show: show || false,
            duplicateTiles: duplicateTiles || false,
        }),
        tileMovedToDashboard: (tile: DashboardTile, dashboardId: number) => ({
            tile,
            dashboardId,
        }),
        tileRemovedFromDashboard: ({ tile, dashboardId }: { tile?: DashboardTile; dashboardId?: number }) => ({
            tile,
            dashboardId,
        }),
        tileAddedToDashboard: (dashboardId: number) => ({ dashboardId }),
    })),
    loaders(({ values, actions }) => ({
        bulkDeleteResponse: [
            null as DashboardBulkDeleteResponseApi | null,
            {
                bulkDeleteDashboards: async ({
                    ids,
                    deleteInsights,
                    onStillSelected,
                }: {
                    ids: number[]
                    deleteInsights?: boolean
                    onStillSelected: (ids: number[]) => void
                }) => {
                    const toastId = lemonToast.loading('Deleting dashboards…', { toastId: uuid() })
                    try {
                        return await dashboardsBulkDeleteCreate(String(teamLogic.values.currentTeamId), {
                            ids,
                            delete_insights: deleteInsights ?? false,
                        })
                    } catch (error) {
                        actions.reloadDashboards({ ids, onStillSelected })
                        throw error
                    } finally {
                        lemonToast.dismiss(toastId)
                    }
                },
            },
        ],
        pagedDashboards: [
            null as PaginatedResponse<DashboardBasicType> | null,
            {
                reloadDashboards: async (
                    _: { ids: number[]; onStillSelected: (ids: number[]) => void },
                    breakpoint
                ) => {
                    const teamId = teamLogic.values.currentTeamId
                    const results: DashboardBasicType[] = []
                    let hasNextPage = true
                    while (hasNextPage) {
                        const page = await dashboardsList(String(teamId), {
                            limit: 1000,
                            offset: results.length,
                            exclude_generated: true,
                        })
                        breakpoint()
                        if (teamId !== teamLogic.values.currentTeamId) {
                            return null
                        }
                        results.push(...(page.results as unknown as DashboardBasicType[]))
                        hasNextPage = !!page.next
                    }
                    return { results, count: results.length, next: null, previous: null }
                },
                loadDashboards: async (url?: string) => {
                    // looking at a fully exported dashboard, return its contents
                    const exportedDashboard = window.POSTHOG_EXPORTED_DATA?.dashboard
                    if (exportedDashboard?.id && exportedDashboard?.tiles) {
                        return {
                            count: 1,
                            next: null,
                            previous: null,
                            results: [exportedDashboard as DashboardBasicType],
                        }
                    }

                    if (!isUserLoggedIn()) {
                        // If user is anonymous (i.e. viewing a shared dashboard logged out), don't load authenticated stuff
                        return { count: 0, next: null, previous: null, results: [] }
                    }

                    if (!teamLogic.values.currentTeam) {
                        return { count: 0, next: null, previous: null, results: [] }
                    }

                    let apiUrl =
                        url ||
                        `api/projects/${teamLogic.values.currentTeamId}/dashboards/?limit=1000&exclude_generated=true`

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                    const dashboards: PaginatedResponse<DashboardType> = await api.get(apiUrl)
                    return dashboards
                },
            },
        ],
        // We're not using this loader as a reducer per se, but just calling it `dashboard`
        // to have the right payload ({ dashboard }) in the Success actions
        dashboard: {
            __default: null as null | DashboardType,
            updateDashboard: async ({ id, allowUndo, discardResult, ...payload }, breakpoint) => {
                if (!Object.entries(payload).length) {
                    return
                }
                breakpoint()

                const beforeChange = { ...values.rawDashboards[id] }

                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                const response = await api.update<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                    payload
                )
                refreshTreeItem('dashboard', id)
                const updatedAttribute = Object.keys(payload)[0]
                if (updatedAttribute === 'name' || updatedAttribute === 'description' || updatedAttribute === 'tags') {
                    posthog.capture(`dashboard frontend updated`, {
                        dashboard_id: id,
                        attribute: updatedAttribute,
                        original_length: values.rawDashboards[id]?.[updatedAttribute]?.length || 0,
                        new_length: payload[updatedAttribute].length,
                    })
                    if (updatedAttribute === 'tags') {
                        actions.loadTags()
                    }
                }
                if (allowUndo) {
                    lemonToast.success('Dashboard updated', {
                        button: {
                            label: 'Undo',
                            action: async () => {
                                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                                const reverted = await api.update<DashboardType>(
                                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                                    beforeChange
                                )
                                actions.updateDashboardSuccess(reverted, {
                                    layoutsPersisted: true,
                                })
                                lemonToast.success('Dashboard change reverted')
                            },
                        },
                    })
                }

                if (discardResult) {
                    return null
                }

                if (!response) {
                    return response
                }

                return mergeTileTextUpdatesIntoDashboard(response, payload.tiles)
            },
            deleteDashboard: async ({ id, deleteInsights }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                const deleted = await api.update<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                    {
                        deleted: true,
                        delete_insights: deleteInsights,
                    }
                )
                deleteFromTree('dashboard', String(id))
                return deleted
            },
            restoreDashboard: async ({ id }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                const restored = await api.update<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                    {
                        deleted: false,
                    }
                )
                refreshTreeItem('dashboard', String(id))
                return restored
            },
            pinDashboard: async ({ id, source }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                const response = await api.update<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                    {
                        pinned: true,
                    }
                )
                reportDashboardPinToggled(id, true, source)
                return response
            },
            unpinDashboard: async ({ id, source }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsPartialUpdate() from 'products/dashboards/frontend/generated/api' instead.
                const response = await api.update<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/${id}`,
                    {
                        pinned: false,
                    }
                )
                reportDashboardPinToggled(id, false, source)
                return response
            },
            duplicateDashboard: async ({ id, name, show, duplicateTiles }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsCreate() from 'products/dashboards/frontend/generated/api' instead.
                const result = await api.create<DashboardType>(
                    `api/projects/${teamLogic.values.currentTeamId}/dashboards/`,
                    {
                        use_dashboard: id,
                        name: `${name} (Copy)`,
                        duplicate_tiles: duplicateTiles,
                    }
                )
                if (show) {
                    router.actions.push(urls.dashboard(result.id))
                }
                return result
            },
        },
    })),
    reducers({
        pagingDashboardsCompleted: [
            false,
            {
                dashboardsFullyLoaded: () => true,
            },
        ],
        // dashboardsLoading stays true after a failed load, because paging never completes.
        // Consumers need this to tell a failure from a load still in flight.
        loadDashboardsFailed: [
            false,
            {
                loadDashboards: () => false,
                loadDashboardsSuccess: () => false,
                loadDashboardsFailure: () => true,
            },
        ],
        redirect: [
            true,
            {
                deleteDashboard: (state, { redirect }) => (typeof redirect !== 'undefined' ? redirect : state),
                restoreDashboard: (state, { redirect }) => (typeof redirect !== 'undefined' ? redirect : state),
            },
        ],
        rawDashboards: [
            {} as Record<string, DashboardBasicType | DashboardType>,
            {
                removeDashboardsFromCache: (state, { ids }) => {
                    const removedIds = new Set(ids)
                    return Object.fromEntries(
                        Object.entries(state).filter(([, dashboard]) => !removedIds.has(dashboard.id))
                    )
                },
                reloadDashboardsSuccess: (state, { pagedDashboards }) =>
                    pagedDashboards ? idToKey(pagedDashboards.results) : state,
                loadDashboardsSuccess: (state, { pagedDashboards }) => {
                    if (!pagedDashboards) {
                        return state
                    }
                    return { ...state, ...idToKey(pagedDashboards.results) }
                },
                // NB! Kea-TypeGen assignes the type of the reducer to the abcSuccess actions.
                // This means we must get rid of the `| null` manually until it's fixed:
                // https://github.com/keajs/kea-typegen/issues/10
                addDashboardSuccess: (state, { dashboard }) => ({ ...state, [dashboard.id]: dashboard }),
                restoreDashboardSuccess: (state, { dashboard }) => ({ ...state, [dashboard.id]: dashboard }),
                updateDashboardSuccess: (state, { dashboard }) =>
                    dashboard ? { ...state, [dashboard.id]: dashboard } : state,
                deleteDashboardSuccess: (state, { dashboard }) => ({
                    ...state,
                    [dashboard.id]: { ...state[dashboard.id], deleted: true },
                }),
                delayedDeleteDashboard: (state, { id }) => {
                    // This gives us time to leave the /dashboard/:deleted_id page
                    const { [id]: _discard, ...rest } = state
                    return rest
                },
                pinDashboardSuccess: (state, { dashboard }) => ({ ...state, [dashboard.id]: dashboard }),
                unpinDashboardSuccess: (state, { dashboard }) => ({ ...state, [dashboard.id]: dashboard }),
                duplicateDashboardSuccess: (state, { dashboard }) => ({
                    ...state,
                    [dashboard.id]: { ...dashboard, _highlight: true },
                }),
                patchDashboardFolders: (state, { paths }) => {
                    const patched = Object.entries(paths).filter(([id]) => state[id])
                    if (patched.length === 0) {
                        return state
                    }
                    return {
                        ...state,
                        ...Object.fromEntries(patched.map(([id, path]) => [id, filedAt(state[id], path)])),
                    }
                },
                reparentDashboardFolders: (state, { oldPath, newPath }) => {
                    const moved: typeof state = {}
                    for (const dashboard of Object.values(state)) {
                        const path = reparentPath(dashboard.file_system_path, oldPath, newPath)
                        if (path !== null) {
                            moved[dashboard.id] = filedAt(dashboard, path)
                        }
                    }
                    return Object.keys(moved).length === 0 ? state : { ...state, ...moved }
                },
            },
        ],
    }),
    selectors(({ selectors }) => ({
        nameSortedDashboards: [
            () => [selectors.rawDashboards],
            (rawDashboards: Record<string, DashboardBasicType | DashboardType>) => {
                return Object.values(rawDashboards)
                    .filter((dashboard) => !(dashboard.name ?? 'Untitled').startsWith(GENERATED_DASHBOARD_PREFIX))
                    .sort(nameCompareFunction)
            },
        ],
        /** Display dashboards are additionally sorted by pin status: pinned first. */
        pinSortedDashboards: [
            () => [selectors.nameSortedDashboards],
            (nameSortedDashboards: (DashboardBasicType | DashboardType)[]) => {
                return [...nameSortedDashboards].sort(
                    (a, b) => (Number(b.pinned) - Number(a.pinned)) * 10 + nameCompareFunction(a, b)
                )
            },
        ],
        dashboardsLoading: [
            () => [selectors.pagedDashboardsLoading, selectors.pagingDashboardsCompleted],
            (pagedDashboardsLoading: boolean, pagingDashboardsCompleted: boolean) =>
                pagedDashboardsLoading || !pagingDashboardsCompleted,
        ],
        pinnedDashboards: [
            () => [selectors.nameSortedDashboards],
            (nameSortedDashboards: (DashboardBasicType | DashboardType)[]) => {
                const pinnedDashboards = nameSortedDashboards.filter((dashboard) => dashboard.pinned)

                return [...pinnedDashboards].sort((a, b) => {
                    const aViewedAt = a.last_viewed_at
                    const bViewedAt = b.last_viewed_at

                    if (aViewedAt && bViewedAt) {
                        if (aViewedAt === bViewedAt) {
                            return nameCompareFunction(a, b)
                        }

                        return aViewedAt > bViewedAt ? -1 : 1
                    }

                    if (aViewedAt) {
                        return -1
                    }

                    if (bViewedAt) {
                        return 1
                    }

                    return nameCompareFunction(a, b)
                })
            },
        ],
    })),
    listeners(({ actions, values }) => ({
        bulkDeleteDashboardsSuccess: ({ bulkDeleteResponse }) => {
            if (!bulkDeleteResponse) {
                return
            }
            const { deleted, skipped } = bulkDeleteResponse
            actions.removeDashboardsFromCache(getRemovedDashboardIds(bulkDeleteResponse))
            if (deleted.length > 0) {
                const noun = deleted.length === 1 ? 'dashboard' : 'dashboards'
                lemonToast.success(`Deleted ${deleted.length} ${noun}.`)
            }
            if (skipped.length > 0) {
                lemonToast.warning(
                    `${skipped.length} dashboards were skipped. They no longer exist or you cannot edit them.`
                )
            }
        },
        bulkDeleteDashboardsFailure: () => {
            lemonToast.error('Could not delete dashboards. Refresh the list and try again.')
        },
        removeDashboardsFromCache: ({ ids }) => {
            for (const id of ids) {
                deleteFromTree('dashboard', String(id))
            }
            const currentTeam = teamLogic.values.currentTeam
            if (currentTeam?.primary_dashboard && ids.includes(currentTeam.primary_dashboard)) {
                teamLogic.actions.loadCurrentTeamSuccess({ ...currentTeam, primary_dashboard: null })
            }
        },
        reloadDashboardsSuccess: ({ pagedDashboards, payload }) => {
            if (!pagedDashboards) {
                return
            }
            const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
            actions.removeDashboardsFromCache((payload?.ids ?? []).filter((id) => !remainingIds.has(id)))
            actions.dashboardsFullyLoaded()
        },
        loadDashboardsIfNeeded: () => {
            if (!values.pagingDashboardsCompleted && !values.pagedDashboardsLoading) {
                actions.loadDashboards()
            }
        },
        loadDashboardsSuccess: ({ pagedDashboards }) => {
            if (pagedDashboards?.next) {
                actions.loadDashboards(pagedDashboards.next)
            } else {
                actions.dashboardsFullyLoaded()
            }
        },
        addDashboardSuccess: ({ dashboard }) => {
            globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateFirstDashboard)

            if (router.values.location.pathname.includes('onboarding')) {
                // don't send a toast if we're in onboarding
                return
            }
            lemonToast.success(<>Dashboard created</>, {
                button: {
                    label: 'View',
                    action: () => router.actions.push(urls.dashboard(dashboard.id)),
                },
            })
        },

        restoreDashboardSuccess: ({ dashboard }) => {
            lemonToast.success(
                <>
                    Dashboard <b>{dashboard.name}</b> restored
                </>
            )
            if (values.redirect) {
                router.actions.push(urls.dashboard(dashboard.id))
            }
        },

        deleteDashboardSuccess: async ({ dashboard }) => {
            const currentTeam = teamLogic.values.currentTeam
            if (currentTeam && 'primary_dashboard' in currentTeam && currentTeam.primary_dashboard === dashboard.id) {
                teamLogic.actions.loadCurrentTeamSuccess({ ...currentTeam, primary_dashboard: null })
            }

            lemonToast.success(
                <>
                    Dashboard <b>{dashboard.name}</b> deleted
                </>,
                {
                    button: {
                        label: 'Undo',
                        action: () => {
                            actions.restoreDashboard({ id: dashboard.id, redirect: values.redirect })
                        },
                    },
                }
            )

            actions.delayedDeleteDashboard(dashboard.id)
        },

        duplicateDashboardSuccess: async ({ dashboard }) => {
            lemonToast.success(
                <>
                    Dashboard copied as <b>{dashboard.name}</b>
                </>
            )
        },
    })),
    permanentlyMount(),
])

export function nameCompareFunction(a: DashboardBasicType, b: DashboardBasicType): number {
    if (a.pinned !== b.pinned) {
        return b.pinned ? 1 : -1
    }

    // No matter where we're comparing dashboards, we want to sort generated dashboards last
    const firstName = a.name ?? 'Untitled'
    const secondName = b.name ?? 'Untitled'

    return firstName.localeCompare(secondName)
}