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.

31.9 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

import api, { PaginatedResponse } from 'lib/api'
import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { objectClean, objectsEqual } from 'lib/utils/objects'
import { reportDashboardMoveInitiated } from 'scenes/dashboard/dashboardEvents'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { dashboardsModel, getRemovedDashboardIds } from '~/models/dashboardsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { ActivityScope, Breadcrumb, DashboardBasicType } from '~/types'

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

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { UserType } from '../../../types'

export enum DashboardsTab {
    All = 'all',
    Yours = 'yours',
    Pinned = 'pinned',
    CrossProject = 'cross-project',
}

const DEFAULT_SORTING: Sorting = { columnKey: 'name', order: 1 }

export interface DashboardsFilters {
    search: string
    createdBy: number[] | 'All users'
    pinned: boolean
    shared: boolean
    tags?: string[]
    /** Folder path to filter to, e.g. 'Unfiled/Dashboards' (empty string = project root). null means no folder filter. */
    folder?: string | null
}

export const DEFAULT_FILTERS: DashboardsFilters = {
    search: '',
    createdBy: 'All users',
    pinned: false,
    shared: false,
    tags: [],
    folder: null,
}

export function hasDashboardFilters(filters: DashboardsFilters): boolean {
    return Boolean(
        filters.search ||
        filters.pinned ||
        filters.shared ||
        (filters.createdBy !== 'All users' && filters.createdBy.length > 0) ||
        filters.tags?.length ||
        filters.folder != null
    )
}

function moveTargetFor(dashboard: DashboardBasicType | undefined): FileSystemEntry | null {
    if (!dashboard?.file_system_id || !dashboard.file_system_path) {
        return null
    }
    return {
        id: dashboard.file_system_id,
        path: dashboard.file_system_path,
        type: 'dashboard',
        ref: String(dashboard.id),
        href: urls.dashboard(dashboard.id),
    }
}

/** Router may coerce numeric-looking query values to numbers; search text must stay a string. */
function urlSearchParamToString(value: unknown): string {
    return `${value ?? ''}`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicValues {
    bulkDeleteResponse: DashboardBulkDeleteResponseApi | null // dashboardsModel
    bulkDeleteResponseLoading: boolean // dashboardsModel
    featureFlags: FeatureFlagsSet // featureFlagLogic
    user: UserType | null // userLogic
    breadcrumbs: Breadcrumb[]
    currentTab: DashboardsTab
    dashboards: DashboardBasicType[]
    dashboardsById: Record<string, DashboardBasicType>
    filedDashboardIds: Set<number>
    filters: DashboardsFilters
    hasMoreTagResults: boolean
    isFiltering: boolean
    searchedDashboards: DashboardBasicType[] | null
    searchedDashboardsLoading: boolean
    showTagPopover: boolean
    sidePanelContext: SidePanelSceneContext
    tableSorting: Sorting
    tagPage: PaginatedResponse<string> | null
    tagPageLoading: boolean
    tagResults: string[]
    tagSearch: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicActions {
    bulkDeleteDashboards: (args_0: {
        deleteInsights?: boolean
        ids: number[]
        onStillSelected: (ids: number[]) => void
    }) => {
        deleteInsights?: boolean
        ids: number[]
        onStillSelected: (ids: number[]) => void
    } // dashboardsModel
    bulkDeleteDashboardsSuccess: (
        bulkDeleteResponse: DashboardBulkDeleteResponseApi,
        payload?:
            | {
                  deleteInsights?: boolean
                  ids: number[]
                  onStillSelected: (ids: number[]) => void
              }
            | undefined
    ) => {
        bulkDeleteResponse: DashboardBulkDeleteResponseApi
        payload?: {
            deleteInsights?: boolean
            ids: number[]
            onStillSelected: (ids: number[]) => void
        }
    } // dashboardsModel
    reloadDashboardsSuccess: (
        pagedDashboards: {
            count: number
            next: null
            previous: null
            results: DashboardBasicType[]
        } | null,
        payload?:
            | {
                  ids: number[]
                  onStillSelected: (ids: number[]) => void
              }
            | undefined
    ) => {
        pagedDashboards: {
            count: number
            next: null
            previous: null
            results: DashboardBasicType[]
        } | null
        payload?: {
            ids: number[]
            onStillSelected: (ids: number[]) => void
        }
    } // dashboardsModel
    openMoveToModal: (items: FileSystemEntry[]) => {
        items: FileSystemEntry[]
    } // moveToLogic
    movedItem: (
        item: FileSystemEntry,
        oldPath: string,
        newPath: string
    ) => {
        item: FileSystemEntry
        newPath: string
        oldPath: string
    } // projectTreeDataLogic
    loadMoreTagResults: () => {
        value: true
    }
    loadSearchedDashboards: ({ search, tags, folder }: { folder: string | null; search: string; tags: string[] }) => {
        search: string
        tags: string[]
        folder: string | null
    }
    loadSearchedDashboardsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSearchedDashboardsSuccess: (
        searchedDashboards: DashboardBasicType[] | null,
        payload?: {
            search: string
            tags: string[]
            folder: string | null
        }
    ) => {
        searchedDashboards: DashboardBasicType[] | null
        payload?: {
            search: string
            tags: string[]
            folder: string | null
        }
    }
    loadTagResults: ({ search, offset }: { offset: number; search: string }) => {
        search: string
        offset: number
    }
    loadTagResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTagResultsSuccess: (
        tagPage:
            | PaginatedResponse<string>
            | {
                  count: number
                  next: null
                  previous: null
                  results: never[]
              },
        payload?: {
            search: string
            offset: number
        }
    ) => {
        tagPage:
            | PaginatedResponse<string>
            | {
                  count: number
                  next: null
                  previous: null
                  results: never[]
              }
        payload?: {
            search: string
            offset: number
        }
    }
    moveDashboardsToFolder: (
        ids: number[],
        method: 'bulk' | 'single',
        onStillSelected?: (ids: number[]) => void
    ) => {
        ids: number[]
        method: 'bulk' | 'single'
        onStillSelected: ((ids: number[]) => void) | undefined
    }
    setCurrentTab: (tab: DashboardsTab) => {
        tab: DashboardsTab
    }
    setFilters: (filters: Partial<DashboardsFilters>) => {
        filters: Partial<DashboardsFilters>
    }
    setSearch: (search: string) => {
        search: string
    }
    setShowTagPopover: (visible: boolean) => {
        visible: boolean
    }
    setTagSearch: (search: string) => {
        search: string
    }
    tableSortingChanged: (sorting: Sorting | null) => {
        sorting: Sorting | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isFiltering: (filters: DashboardsFilters) => boolean
        dashboards: (
            nameSortedDashboards: (DashboardBasicType | import('~/types').DashboardType)[],
            rawDashboards: Record<string, DashboardBasicType | import('~/types').DashboardType>,
            searchedDashboards: DashboardBasicType[] | null,
            filters: DashboardsFilters,
            currentTab: DashboardsTab,
            user: UserType | null
        ) => DashboardBasicType[]
        dashboardsById: (dashboards: DashboardBasicType[]) => Record<string, DashboardBasicType>
        filedDashboardIds: (dashboards: DashboardBasicType[]) => Set<number>
    }
}

export type dashboardsLogicType = MakeLogicType<
    dashboardsLogicValues,
    dashboardsLogicActions,
    Record<string, any>,
    dashboardsLogicMeta
>

export const dashboardsLogic = kea<dashboardsLogicType>([
    path(['scenes', 'dashboard', 'dashboardsLogic']),
    connect(() => ({
        values: [
            userLogic,
            ['user'],
            featureFlagLogic,
            ['featureFlags'],
            dashboardsModel,
            ['bulkDeleteResponse', 'bulkDeleteResponseLoading'],
        ],
        actions: [
            dashboardsModel,
            ['bulkDeleteDashboards', 'bulkDeleteDashboardsSuccess', 'reloadDashboardsSuccess'],
            moveToLogic,
            ['openMoveToModal'],
            projectTreeDataLogic,
            ['movedItem'],
        ],
    })),
    actions({
        moveDashboardsToFolder: (
            ids: number[],
            method: 'single' | 'bulk',
            onStillSelected?: (ids: number[]) => void
        ) => ({ ids, method, onStillSelected }),
        setCurrentTab: (tab: DashboardsTab) => ({ tab }),
        setSearch: (search: string) => ({ search }),
        setFilters: (filters: Partial<DashboardsFilters>) => ({
            filters,
        }),
        tableSortingChanged: (sorting: Sorting | null) => ({
            sorting,
        }),
        setTagSearch: (search: string) => ({ search }),
        setShowTagPopover: (visible: boolean) => ({ visible }),
        loadMoreTagResults: true,
    }),
    reducers(() => {
        const filtersPersistence = buildUserScopedPersistenceConfig('dashboard_list_filters__')
        return {
            tableSorting: [
                DEFAULT_SORTING,
                { persist: true },
                {
                    tableSortingChanged: (_, { sorting }) => sorting || DEFAULT_SORTING,
                },
            ],
            currentTab: [
                DashboardsTab.All as DashboardsTab,
                {
                    setCurrentTab: (_, { tab }) => tab,
                },
            ],

            filters: [
                DEFAULT_FILTERS,
                filtersPersistence,
                {
                    setFilters: (state, { filters }) =>
                        objectClean({
                            ...state,
                            ...filters,
                        }),
                    setSearch: (state, { search }) => ({ ...state, search }),
                    setCurrentTab: (state, { tab }) =>
                        tab === DashboardsTab.Yours ? { ...state, createdBy: DEFAULT_FILTERS.createdBy } : state,
                },
            ],
            tagSearch: [
                '',
                {
                    setTagSearch: (_, { search }) => search,
                    setShowTagPopover: (state, { visible }) => (visible ? state : ''),
                },
            ],
            showTagPopover: [
                false,
                {
                    setShowTagPopover: (_, { visible }) => visible,
                },
            ],
        }
    }),

    loaders({
        searchedDashboards: [
            null as DashboardBasicType[] | null,
            {
                /**
                 * Server-side fuzzy search via the dashboards list endpoint. Returns null when
                 * there's no active search term, in which case the dashboards selector falls
                 * back to the in-memory `dashboardsModel` list.
                 *
                 * The 250ms `breakpoint` runs before the empty-term short-circuit so a stale
                 * in-flight request can't clobber a freshly cleared search.
                 */
                loadSearchedDashboards: async (
                    { search, tags, folder }: { search: string; tags: string[]; folder: string | null },
                    breakpoint
                ) => {
                    await breakpoint(250)
                    const term = search.trim()
                    if (!term) {
                        return null
                    }
                    const teamId = teamLogic.values.currentTeamId
                    if (teamId == null) {
                        return null
                    }
                    const params = new URLSearchParams({
                        search: term,
                        limit: '200',
                        exclude_generated: 'true',
                    })
                    // Push tag/folder filtering to the server so MCP and API clients see the same
                    // result shape as the UI, and so the limit:200 cap operates on the right
                    // population — filtered first, not after. Without this, a folder filter combined
                    // with search would only narrow the top-200 global matches and silently drop the rest.
                    for (const tag of tags) {
                        params.append('tags', tag)
                    }
                    if (folder != null) {
                        params.append('folder', folder)
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use dashboardsList() from 'products/dashboards/frontend/generated/api' instead.
                    const response: PaginatedResponse<DashboardBasicType> = await api.get(
                        `api/projects/${teamId}/dashboards/?${params.toString()}`
                    )
                    breakpoint()
                    return response.results ?? []
                },
            },
        ],
        tagPage: [
            null as PaginatedResponse<string> | null,
            {
                loadTagResults: async ({ search, offset }: { search: string; offset: number }, breakpoint) => {
                    if (offset === 0) {
                        await breakpoint(250)
                    }
                    const teamId = teamLogic.values.currentTeamId
                    if (teamId == null) {
                        return { count: 0, next: null, previous: null, results: [] }
                    }
                    const params = new URLSearchParams({ search, limit: '50', offset: String(offset) })
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const tagPage: PaginatedResponse<string> = await api.get(
                        `api/projects/${teamId}/tags?${params.toString()}`
                    )
                    breakpoint()
                    return tagPage
                },
            },
        ],
    }),

    reducers({
        searchedDashboards: {
            bulkDeleteDashboardsSuccess: (state, { bulkDeleteResponse }) => {
                const removedIds = new Set(getRemovedDashboardIds(bulkDeleteResponse))
                return state?.filter(({ id }) => !removedIds.has(id)) ?? null
            },
            reloadDashboardsSuccess: (state, { pagedDashboards }) => {
                if (!pagedDashboards) {
                    return state
                }
                const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
                return state?.filter(({ id }) => remainingIds.has(id)) ?? null
            },
        },
        tagResults: [
            [] as string[],
            {
                setShowTagPopover: (state, { visible }) => (visible ? [] : state),
                setTagSearch: () => [],
                loadTagResultsSuccess: (state, { tagPage, payload }) =>
                    payload?.offset === 0 ? (tagPage.results ?? []) : [...state, ...(tagPage.results ?? [])],
            },
        ],
        hasMoreTagResults: [
            false,
            {
                setShowTagPopover: (state, { visible }) => (visible ? false : state),
                setTagSearch: () => false,
                loadTagResultsSuccess: (_, { tagPage }) => tagPage.next != null,
            },
        ],
    }),

    selectors({
        isFiltering: [(s) => [s.filters], (filters: DashboardsFilters) => hasDashboardFilters(filters)],
        dashboards: [
            (s) => [
                dashboardsModel.selectors.nameSortedDashboards,
                dashboardsModel.selectors.rawDashboards,
                s.searchedDashboards,
                s.filters,
                s.currentTab,
                s.user,
            ],
            (
                allDashboards: DashboardBasicType[],
                rawDashboards: Record<string, DashboardBasicType | import('~/types').DashboardType>,
                searchedDashboards: DashboardBasicType[] | null,
                filters: DashboardsFilters,
                currentTab: DashboardsTab,
                user: null | import('~/types').UserType
            ) => {
                // When a search term is active we trust the server's trigram word similarity
                // ranking; otherwise we use the model's alphabetised list. This keeps the exact
                // match at the top.
                //
                // For the search branch we re-hydrate each row from `rawDashboards` so that
                // pin/unpin/rename mutations driven by `dashboardsModel` show up immediately
                // in the search results — without this, `searchedDashboards` would freeze at
                // the API response state until the next refetch.
                let haystack: DashboardBasicType[] =
                    filters.search && searchedDashboards
                        ? searchedDashboards.map((d) => (rawDashboards[d.id] as DashboardBasicType | undefined) ?? d)
                        : allDashboards
                if (currentTab === DashboardsTab.Pinned) {
                    haystack = haystack.filter((d) => d.pinned)
                }
                if (filters.pinned) {
                    haystack = haystack.filter((d) => d.pinned)
                }
                if (filters.shared) {
                    haystack = haystack.filter((d) => d.is_shared)
                }
                if (currentTab === DashboardsTab.Yours) {
                    haystack = haystack.filter((d) => d.created_by?.uuid === user?.uuid)
                } else if (filters.createdBy !== 'All users') {
                    const createdByIds = filters.createdBy
                    haystack = haystack.filter((d) => d.created_by != null && createdByIds.includes(d.created_by.id))
                }
                if (filters.tags && filters.tags.length > 0) {
                    haystack = haystack.filter((d) => filters.tags?.some((tag) => d.tags?.includes(tag)))
                }
                if (filters.folder != null) {
                    haystack = haystack.filter((d) => d.folder === filters.folder)
                }
                return haystack
            },
        ],

        dashboardsById: [
            (s) => [s.dashboards],
            (dashboards: DashboardBasicType[]): Record<string, DashboardBasicType> =>
                Object.fromEntries(dashboards.map((dashboard) => [dashboard.id, dashboard])),
        ],
        filedDashboardIds: [
            (s) => [s.dashboards],
            (dashboards: DashboardBasicType[]): Set<number> =>
                new Set(dashboards.filter((dashboard) => moveTargetFor(dashboard)).map(({ id }) => id)),
        ],

        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                {
                    key: 'dashboards',
                    name: 'Dashboards',
                    iconType: 'dashboard',
                },
            ],
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            () => [],
            (): SidePanelSceneContext => ({
                activity_scope: ActivityScope.DASHBOARD,
            }),
        ],
    }),
    trackedActionToUrl(({ values }) => ({
        setCurrentTab: () => {
            const tab = values.currentTab === DashboardsTab.All ? undefined : values.currentTab
            const searchParams: Record<string, any> = { ...router.values.searchParams, tab }
            if (values.currentTab === DashboardsTab.Yours) {
                delete searchParams['created_by']
            }
            if (objectsEqual(searchParams, router.values.searchParams)) {
                return
            }

            router.actions.push(router.values.location.pathname, searchParams)
        },
        setSearch: ({ search }) => {
            const nextSearch = search ?? ''
            const currentSearch = urlSearchParamToString(router.values.searchParams['search'])

            if (nextSearch === currentSearch) {
                return
            }

            const searchParams: Record<string, any> = {
                ...router.values.searchParams,
            }

            if (nextSearch) {
                searchParams['search'] = nextSearch
            } else {
                delete searchParams['search']
            }

            return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
        },
        setFilters: () => {
            const { createdBy, pinned, shared, tags } = values.filters
            const searchParams: Record<string, any> = { ...router.values.searchParams }

            if (searchParams['tab'] === DashboardsTab.Pinned) {
                delete searchParams['tab']
            }

            if (createdBy !== DEFAULT_FILTERS.createdBy) {
                searchParams['created_by'] = createdBy
            } else {
                delete searchParams['created_by']
            }
            if (pinned) {
                searchParams['pinned'] = true
            } else {
                delete searchParams['pinned']
            }
            if (shared) {
                searchParams['shared'] = true
            } else {
                delete searchParams['shared']
            }
            if (tags && tags.length > 0) {
                searchParams['tags'] = tags
            } else {
                delete searchParams['tags']
            }

            // Persist the folder filter so it survives reloads/sharing. `null` means no filter (param absent);
            // an empty string is a valid value (project root), so we key off the param's presence, not its value.
            const folder = values.filters.folder ?? null
            if (folder === null) {
                delete searchParams['folder']
            } else {
                searchParams['folder'] = folder
            }

            if (objectsEqual(searchParams, router.values.searchParams)) {
                return
            }

            return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
        },
    })),
    urlToAction(({ actions, values }) => ({
        '/dashboard': (_, searchParams) => {
            const requestedTab = (searchParams['tab'] as DashboardsTab | undefined) || DashboardsTab.All
            // Pinned is deliberately absent: it arrives as a filter, not a tab, and is handled
            // by hasFilterParams below. Anything else unrecognized falls back to All.
            const tabsFromUrl: DashboardsTab[] = [DashboardsTab.Yours, DashboardsTab.CrossProject]
            const tab = tabsFromUrl.includes(requestedTab) ? requestedTab : DashboardsTab.All
            if (values.currentTab !== tab) {
                actions.setCurrentTab(tab)
            }

            const hasFilterParams =
                requestedTab === DashboardsTab.Pinned ||
                ['created_by', 'pinned', 'shared', 'tags', 'folder', 'search'].some((key) => key in searchParams)
            if (tab === DashboardsTab.Yours && values.filters.createdBy !== DEFAULT_FILTERS.createdBy) {
                actions.setFilters({ createdBy: DEFAULT_FILTERS.createdBy })
            }
            if (!hasFilterParams) {
                const { search: _search, ...filtersWithoutSearch } = values.filters
                const { search: _defaultSearch, ...defaultsWithoutSearch } = DEFAULT_FILTERS
                let filtersToRestore: Partial<DashboardsFilters> = filtersWithoutSearch
                let defaultFilters: Partial<DashboardsFilters> = defaultsWithoutSearch
                if (tab === DashboardsTab.Yours) {
                    const { createdBy: _createdBy, ...filtersWithoutCreatedBy } = filtersToRestore
                    const { createdBy: _defaultCreatedBy, ...defaultsWithoutCreatedBy } = defaultFilters
                    filtersToRestore = filtersWithoutCreatedBy
                    defaultFilters = defaultsWithoutCreatedBy
                }
                if (!objectsEqual(filtersToRestore, defaultFilters)) {
                    actions.setFilters(filtersToRestore)
                }
                if (values.filters.search) {
                    actions.setSearch(values.filters.search)
                }
                return
            }

            // Apply non-search filters before search so the setSearch listener's server fetch
            // sees the freshly-restored tags. Guard each dispatch on a real change so that the
            // actionToUrl -> locationChanged -> urlToAction round trip doesn't re-fire listeners
            // (e.g. a redundant server search) for filters that didn't actually move.
            const createdByParam = searchParams['created_by']
            const createdByIds = Array.isArray(createdByParam)
                ? createdByParam.map(Number).filter((id) => !Number.isNaN(id))
                : typeof createdByParam === 'number'
                  ? [createdByParam]
                  : []
            const nextFilters = {
                createdBy: createdByIds.length > 0 ? createdByIds : DEFAULT_FILTERS.createdBy,
                pinned:
                    requestedTab === DashboardsTab.Pinned ||
                    searchParams['pinned'] === true ||
                    searchParams['pinned'] === 'true',
                shared: searchParams['shared'] === true || searchParams['shared'] === 'true',
                tags: Array.isArray(searchParams['tags']) ? searchParams['tags'] : DEFAULT_FILTERS.tags,
                folder: 'folder' in searchParams ? urlSearchParamToString(searchParams['folder']) : null,
            }
            const current = values.filters
            if (
                !objectsEqual(current.createdBy, nextFilters.createdBy) ||
                current.pinned !== nextFilters.pinned ||
                current.shared !== nextFilters.shared ||
                !objectsEqual(current.tags ?? [], nextFilters.tags ?? []) ||
                (current.folder ?? null) !== nextFilters.folder
            ) {
                actions.setFilters(nextFilters)
            }

            const search = urlSearchParamToString(searchParams['search'])
            if (values.filters.search !== search) {
                actions.setSearch(search)
            }
        },
    })),
    listeners(({ actions, values, cache }) => ({
        bulkDeleteDashboardsSuccess: ({ bulkDeleteResponse, payload }) => {
            const removedIds = new Set(getRemovedDashboardIds(bulkDeleteResponse))
            payload?.onStillSelected(
                bulkDeleteResponse.skipped.filter(({ id }) => !removedIds.has(id)).map(({ id }) => id)
            )
            actions.loadSearchedDashboards({
                search: values.filters.search,
                tags: values.filters.tags ?? [],
                folder: values.filters.folder ?? null,
            })
        },
        reloadDashboardsSuccess: ({ pagedDashboards, payload }) => {
            if (!pagedDashboards) {
                return
            }
            const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
            payload?.onStillSelected(payload.ids.filter((id) => remainingIds.has(id)))
            actions.loadSearchedDashboards({
                search: values.filters.search,
                tags: values.filters.tags ?? [],
                folder: values.filters.folder ?? null,
            })
        },
        movedItem: ({ item, oldPath, newPath }) => {
            if (item.type === 'folder') {
                dashboardsModel.actions.reparentDashboardFolders(oldPath, newPath)
                return
            }
            // A shortcut carries the ref of the dashboard it points at, but moving it moves only the shortcut.
            if (item.type !== 'dashboard' || !item.ref || item.shortcut) {
                return
            }
            dashboardsModel.actions.patchDashboardFolders({ [item.ref]: newPath })
            // Only rows that actually landed lose their tick, so a failed move keeps its selection.
            const awaiting = cache.awaitingMove
            if (awaiting?.ids.delete(Number(item.ref))) {
                awaiting.onStillSelected?.([...awaiting.ids])
            }
        },
        moveDashboardsToFolder: ({ ids, method, onStillSelected }) => {
            const moving = ids
                .map((id) => moveTargetFor(values.dashboardsById[id]))
                .filter((entry): entry is FileSystemEntry => !!entry)
            if (moving.length === 0) {
                return
            }
            reportDashboardMoveInitiated(method, moving.length)
            actions.openMoveToModal(moving)
            cache.awaitingMove = { ids: new Set(ids), onStillSelected }
        },
        // Only the dismiss path dispatches this. Submitting goes straight to closedMoveToModal, so clearing
        // on that one instead would drop the ticks before any move had landed.
        [moveToLogic.actionTypes.closeMoveToModal]: () => {
            cache.awaitingMove = undefined
        },
        setSearch: ({ search }) => {
            actions.loadSearchedDashboards({
                search,
                tags: values.filters.tags ?? [],
                folder: values.filters.folder ?? null,
            })
        },
        setFilters: ({ filters }) => {
            // Tag/folder changes refetch when a search is active so server-side filtering stays
            // accurate. Other filter keys (pinned/shared/createdBy/currentTab) are still
            // applied client-side over the in-memory list so they don't refetch.
            if (('tags' in filters || 'folder' in filters) && values.filters.search) {
                actions.loadSearchedDashboards({
                    search: values.filters.search,
                    tags: values.filters.tags ?? [],
                    folder: values.filters.folder ?? null,
                })
            }
        },
        setShowTagPopover: ({ visible }) => {
            if (visible) {
                actions.loadTagResults({ search: values.tagSearch, offset: 0 })
            }
        },
        setTagSearch: ({ search }) => {
            actions.loadTagResults({ search, offset: 0 })
        },
        loadMoreTagResults: () => {
            if (values.hasMoreTagResults && !values.tagPageLoading) {
                actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })
            }
        },
    })),
    afterMount(() => {
        dashboardsModel.actions.loadDashboardsIfNeeded()
    }),
])