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.

chore: clean up feature flag dashboards-list-view after experiment 379125 (#79553)

posthog[bot]3f2a07489bf9
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
index 184ff11e7d9c..bf62de311d83 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts
@@ -1,9 +1,7 @@
import { expectLogic } from 'kea-test-utils'
-import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { UserProductListReason } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -94,49 +92,6 @@ describe('projectTreeDataLogic', () => {
})
})
- it('emits the dashboard-move primary-metric event for dashboards but not for other item types', async () => {
- const eventUsage = eventUsageLogic()
- eventUsage.mount()
- const capture = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
- const move = jest.spyOn(api.fileSystem, 'move')
- move.mockResolvedValueOnce({ id: 'fs-1', type: 'dashboard', path: 'Product/A' } as any)
- move.mockResolvedValueOnce({ id: 'fs-2', type: 'insight', path: 'Product/B' } as any)
-
- // A dashboard move fires the experiment's primary-metric event after the API move succeeds.
- await expectLogic(eventUsage, () => {
- logic.actions.moveItem(
- { id: 'fs-1', type: 'dashboard', path: 'Unfiled/Dashboards/A', ref: '1' } as any,
- 'Product/A',
- true,
- 'test'
- )
- }).toDispatchActions(['reportDashboardMovedToFolder'])
- // Coarse fields only — never the folder/dashboard names (Unfiled/Dashboards/A -> Product/A).
- expect(capture).toHaveBeenCalledWith(
- 'dashboard moved to folder',
- expect.objectContaining({
- from_depth: 3,
- to_depth: 2,
- moved_from_unfiled: true,
- moved_to_unfiled: false,
- })
- )
-
- // A non-dashboard move still processes (movedItem) but must NOT fire the dashboard event.
- capture.mockClear()
- await expectLogic(logic, () => {
- logic.actions.moveItem(
- { id: 'fs-2', type: 'insight', path: 'Unfiled/Insights/B', ref: '2' } as any,
- 'Product/B',
- true,
- 'test'
- )
- }).toDispatchActions(['movedItem'])
- expect(capture.mock.calls.find((call) => call[0] === 'dashboard moved to folder')).toBeUndefined()
-
- eventUsage.unmount()
- })
-
it('reports a bulk move once, with an undo that reverts every item', async () => {
const success = jest.spyOn(lemonToast, 'success').mockReturnValue('' as any)
const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index bb73a2941b01..44b84412c99a 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -765,21 +765,6 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
)
actions.removeQueuedAction(action)
actions.movedItem(action.item, oldPath, newPath)
- if (action.item.type === 'dashboard') {
- // EXPERIMENT CLEANUP (flag dashboards-list-view · experiment 379125): a
- // dashboard-specific event in the generic move path — a deliberate altitude
- // compromise. It lives here, not in dashboardsFileSystemLogic, because that logic
- // mounts only in the tree arm, so emitting there would miss control-arm moves and
- // break the arm-agnostic primary metric. Remove or relocate (e.g. behind a generic
- // post-move analytics hook) once we agree on a solution / the experiment ends.
- // method/count + undo net-out deferred.
- eventUsageLogic.actions.reportDashboardMovedToFolder({
- fromDepth: splitPath(oldPath).length,
- toDepth: splitPath(newPath).length,
- fromUnfiled: oldPath.startsWith('Unfiled/'),
- toUnfiled: newPath.startsWith('Unfiled/'),
- })
- }
settleMoveBatch((batch) => batch.moved.push({ item: action.item, oldPath, newPath }))
} catch (error) {
// The batch toast can only report a count, so the item and its batch have to reach
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 170c04380ba4..1a6e9cfdaf77 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -291,7 +291,6 @@ export const FEATURE_FLAGS = {
DASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platform
DASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new
DASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platform
- DASHBOARDS_LIST_VIEW: 'dashboards-list-view', // owner: @vdekrijger #team-product-analytics multivariate=control,tree
DATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modeling
DATA_MODELING_INCREMENTAL_VIEWS: 'data-modeling-incremental-views', // owner: #team-data-modeling
DATA_MODELING_MULTI_DAG: 'data-modeling-multi-dag', // owner: #team-data-modeling
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index bb7e620ef576..e3bbdc907131 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -794,13 +794,6 @@ export interface eventUsageLogicActions {
layoutZoom: number
source: 'button' | 'shortcut'
}
- reportDashboardListSearched: (
- searchLength: number,
- resultsCount: number
- ) => {
- resultsCount: number
- searchLength: number
- }
reportDashboardLoadingTime: (
loadingMilliseconds: number,
dashboardId: number
@@ -828,17 +821,6 @@ export interface eventUsageLogicActions {
count: number
method: 'bulk' | 'single'
}
- reportDashboardMovedToFolder: (props: {
- fromDepth: number
- fromUnfiled: boolean
- toDepth: number
- toUnfiled: boolean
- }) => {
- fromDepth: number
- fromUnfiled: boolean
- toDepth: number
- toUnfiled: boolean
- }
reportDashboardPinToggled: (
dashboardId: number,
pinned: boolean,
@@ -953,13 +935,6 @@ export interface eventUsageLogicActions {
dashboardId: number | undefined
isWhiteLabelled: boolean
}
- reportDashboardsTreeFolderNavigated: (
- depth: number,
- hasSubfolders: boolean
- ) => {
- depth: number
- hasSubfolders: boolean
- }
reportDataManagementDefinitionCancel: (type: TaxonomicFilterGroupType) => {
type: TaxonomicFilterGroupType
}
@@ -2420,14 +2395,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
pinned,
source,
}),
- reportDashboardMovedToFolder: (props: {
- fromDepth: number
- toDepth: number
- fromUnfiled: boolean
- toUnfiled: boolean
- }) => props,
- reportDashboardListSearched: (searchLength: number, resultsCount: number) => ({ searchLength, resultsCount }),
- reportDashboardsTreeFolderNavigated: (depth: number, hasSubfolders: boolean) => ({ depth, hasSubfolders }),
reportDashboardMoveInitiated: (method: 'single' | 'bulk', count: number) => ({ method, count }),
reportDashboardFrontEndUpdate: (
dashboardId: number | undefined,
@@ -3479,25 +3446,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
source,
})
},
- reportDashboardMovedToFolder: async ({ fromDepth, toDepth, fromUnfiled, toUnfiled }) => {
- // Coarse fields only — never folder/dashboard names (customer-controlled).
- posthog.capture('dashboard moved to folder', {
- from_depth: fromDepth,
- to_depth: toDepth,
- moved_from_unfiled: fromUnfiled,
- moved_to_unfiled: toUnfiled,
- })
- },
- reportDashboardListSearched: async ({ searchLength, resultsCount }) => {
- // Length + count only, never the query text (can contain sensitive names).
- posthog.capture('dashboard list searched', {
- search_length: searchLength,
- results_count: resultsCount,
- })
- },
- reportDashboardsTreeFolderNavigated: async ({ depth, hasSubfolders }) => {
- posthog.capture('dashboards tree folder navigated', { depth, has_subfolders: hasSubfolders })
- },
reportDashboardMoveInitiated: async ({ method, count }) => {
posthog.capture('dashboard move initiated', { method, count })
},
diff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
index b15005578df5..3a5f3ed79c59 100644
--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
@@ -26,8 +26,7 @@ import { dashboardsModel } from '~/models/dashboardsModel'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
-import { DashboardsContent } from 'products/dashboards/frontend/components/DashboardsContent'
-
+import { DashboardsTableContainer } from './DashboardsTable'
import { FeaturedTemplatesChooser } from './templates/FeaturedTemplatesChooser'
const HedgehogChart = pngHoggie(chartPng)
@@ -110,7 +109,7 @@ export function Dashboards(): JSX.Element {
{currentTab === DashboardsTab.Templates ? (
<DashboardTemplatesTable />
) : dashboardsLoading || dashboards.length > 0 || isFiltering ? (
- <DashboardsContent />
+ <DashboardsTableContainer />
) : (
<ProductIntroduction
productName="Dashboards"
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index 8f749c189109..3902f97453e4 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -4,7 +4,6 @@ import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { DashboardsFilters, DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
@@ -286,16 +285,12 @@ describe('dashboardsLogic', () => {
},
})
- const reportSearched = jest.spyOn(eventUsageLogic.actions, 'reportDashboardListSearched')
await expectLogic(logic, () => {
logic.actions.setSearch('needl')
}).toDispatchActions(['loadSearchedDashboardsSuccess'])
expect(logic.values.dashboards).toHaveLength(1)
expect(logic.values.dashboards[0].name).toBe('needle')
- // Findability signal fires once per settled search: term length + result count, never the query text.
- // Covers the dashboards-list-view experiment instrumentation (flag: dashboards-list-view · experiment 379125).
- expect(reportSearched).toHaveBeenCalledWith(5, 1)
})
it('does not refetch when only pinned / shared / createdBy change', async () => {
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 2679f421023e..b984f795ed3e 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -322,10 +322,6 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
`api/environments/${teamId}/dashboards/?${params.toString()}`
)
breakpoint()
- // Findability signal for the dashboards-list-view experiment (flag: dashboards-list-view ·
- // experiment: 379125) — fires once per settled search (the 250ms breakpoint + the post-fetch
- // breakpoint() drop keystrokes and superseded queries). Remove with the experiment cleanup.
- eventUsageLogic.actions.reportDashboardListSearched(term.length, response.results?.length ?? 0)
return response.results ?? []
},
},
diff --git a/products/dashboards/frontend/DashboardsList.stories.tsx b/products/dashboards/frontend/DashboardsList.stories.tsx
index 64fcb596de45..b1e1ddd925b7 100644
--- a/products/dashboards/frontend/DashboardsList.stories.tsx
+++ b/products/dashboards/frontend/DashboardsList.stories.tsx
@@ -1,13 +1,12 @@
import type { Meta, StoryObj } from '@storybook/react'
import __dashboards from 'scenes/dashboard/__mocks__/dashboards.json'
+import { DashboardsTableContainer } from 'scenes/dashboard/dashboards/DashboardsTable'
import { mswDecorator } from '~/mocks/browser'
-import { DashboardsContent } from './components/DashboardsContent'
-
-const meta: Meta<typeof DashboardsContent> = {
- component: DashboardsContent,
+const meta: Meta<typeof DashboardsTableContainer> = {
+ component: DashboardsTableContainer,
title: 'Products/Dashboards',
decorators: [
mswDecorator({
@@ -25,6 +24,6 @@ const meta: Meta<typeof DashboardsContent> = {
export default meta
-type Story = StoryObj<typeof DashboardsContent>
+type Story = StoryObj<typeof DashboardsTableContainer>
export const List: Story = {}
diff --git a/products/dashboards/frontend/components/DashboardsContent.test.tsx b/products/dashboards/frontend/components/DashboardsContent.test.tsx
deleted file mode 100644
index 80e6b53a49cd..000000000000
--- a/products/dashboards/frontend/components/DashboardsContent.test.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import '@testing-library/jest-dom'
-
-import { cleanup, render, screen } from '@testing-library/react'
-import { useValues } from 'kea'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-
-import { DashboardsContent } from './DashboardsContent'
-
-jest.mock('scenes/dashboard/dashboards/DashboardsTable', () => ({
- DashboardsTableContainer: () => <div>table-arm</div>,
-}))
-jest.mock('./DashboardsTree', () => ({ DashboardsTree: () => <div>tree-arm</div> }))
-jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn() }))
-
-function renderWithFlag(value: string | undefined): void {
- ;(useValues as jest.Mock).mockReturnValue({
- featureFlags: value === undefined ? {} : { [FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]: value },
- })
- render(<DashboardsContent />)
-}
-
-describe('DashboardsContent', () => {
- afterEach(cleanup)
-
- it.each([undefined, 'control', 'bogus', 'grid', 'finder', 'explorer'])(
- 'renders the table for variant %p',
- (value) => {
- renderWithFlag(value)
- expect(screen.getByText('table-arm')).toBeInTheDocument()
- expect(screen.queryByText('tree-arm')).not.toBeInTheDocument()
- }
- )
-
- it('renders the tree for the tree variant', () => {
- renderWithFlag('tree')
- expect(screen.getByText('tree-arm')).toBeInTheDocument()
- expect(screen.queryByText('table-arm')).not.toBeInTheDocument()
- })
-})
diff --git a/products/dashboards/frontend/components/DashboardsContent.tsx b/products/dashboards/frontend/components/DashboardsContent.tsx
deleted file mode 100644
index ca4d94966962..000000000000
--- a/products/dashboards/frontend/components/DashboardsContent.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { useValues } from 'kea'
-
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { DashboardsTableContainer } from 'scenes/dashboard/dashboards/DashboardsTable'
-
-import { resolveDashboardsListViewVariant } from '../logics/dashboardsListViewVariants'
-import { DashboardsTree } from './DashboardsTree'
-
-// Routes the dashboards list body to the arm selected by the dashboards-list-view experiment flag.
-// Control (and any unknown value) renders today's table unchanged; the tree treatment arm shows a
-// persistent folder-tree panel beside the table.
-export function DashboardsContent(): JSX.Element {
- const { featureFlags } = useValues(featureFlagLogic)
- const variant = resolveDashboardsListViewVariant(featureFlags)
-
- if (variant === 'tree') {
- return <DashboardsTree />
- }
- return <DashboardsTableContainer />
-}
diff --git a/products/dashboards/frontend/components/DashboardsTree.test.tsx b/products/dashboards/frontend/components/DashboardsTree.test.tsx
deleted file mode 100644
index d041a3d01e79..000000000000
--- a/products/dashboards/frontend/components/DashboardsTree.test.tsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import '@testing-library/jest-dom'
-
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { useActions, useValues } from 'kea'
-
-import { DashboardsTree } from './DashboardsTree'
-
-// Captured so a test can invoke the tree's onFolderClick directly with undefined — no click path produces that.
-let mockLastOnFolderClick: ((folder: unknown) => void) | undefined
-
-jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn(), useActions: jest.fn() }))
-jest.mock('scenes/dashboard/dashboards/DashboardsTable', () => ({
- DashboardsTable: ({ dashboards }: any) => (
- <div>
- {dashboards.map((dashboard: { id: number; name: string }) => (
- <span key={dashboard.id}>{dashboard.name}</span>
- ))}
- </div>
- ),
-}))
-// Stub LemonTree: render each node (recursively) via renderItem, clickable to fire onFolderClick.
-jest.mock('lib/lemon-ui/LemonTree/LemonTree', () => {
- const renderNodes = (items: any[], onFolderClick: any, renderItem: any): any =>
- items.map((item: any) => (
- <div key={item.id}>
- <div onClick={() => onFolderClick(item)}>{renderItem ? renderItem(item, item.name) : item.name}</div>
- {item.children ? renderNodes(item.children, onFolderClick, renderItem) : null}
- </div>
- ))
- return {
- LemonTree: ({ data, onFolderClick, renderItem }: any) => {
- mockLastOnFolderClick = onFolderClick
- return <div>{renderNodes(data, onFolderClick, renderItem)}</div>
- },
- }
-})
-
-describe('DashboardsTree', () => {
- const navigateToFolder = jest.fn()
- const toggleFolder = jest.fn()
- const setExpandedFolders = jest.fn()
- const reportDashboardsTreeFolderNavigated = jest.fn()
-
- afterEach(cleanup)
-
- beforeEach(() => {
- navigateToFolder.mockClear()
- toggleFolder.mockClear()
- setExpandedFolders.mockClear()
- reportDashboardsTreeFolderNavigated.mockClear()
- ;(useActions as jest.Mock).mockReturnValue({
- navigateToFolder,
- toggleFolder,
- setExpandedFolders,
- createFolder: jest.fn(),
- reportDashboardsTreeFolderNavigated,
- })
- })
-
- function mockValues(overrides: Record<string, any>): void {
- ;(useValues as jest.Mock).mockReturnValue({
- folderTree: [],
- currentFolder: '',
- currentSubtreeDashboards: [],
- entryByRef: {},
- expandedFolders: {},
- folderEntryByPath: {},
- folderDashboardCounts: {},
- dashboardFileSystemEntriesLoading: false,
- folderEntriesLoading: false,
- dashboardsLoading: false,
- ...overrides,
- })
- }
-
- it('renders All dashboards as the root with folders nested under it, and the scoped table', () => {
- mockValues({
- folderTree: [
- {
- path: 'Marketing',
- label: 'Marketing',
- children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
- },
- ],
- currentSubtreeDashboards: [{ id: 1, name: 'Revenue' }],
- })
- render(<DashboardsTree />)
- // "All dashboards" is the tree root; folders nest under it.
- expect(screen.getByText('All dashboards')).toBeInTheDocument()
- expect(screen.getByText('Marketing')).toBeInTheDocument()
- expect(screen.getByText('Q1')).toBeInTheDocument()
- expect(screen.getByText(/Revenue/)).toBeInTheDocument()
- })
-
- it('navigates to a childless folder without toggling it (it never expands)', () => {
- mockValues({ folderTree: [{ path: 'Marketing', label: 'Marketing', children: [] }] })
- render(<DashboardsTree />)
- fireEvent.click(screen.getByText('Marketing'))
- expect(navigateToFolder).toHaveBeenCalledWith('Marketing')
- expect(toggleFolder).not.toHaveBeenCalled()
- // Adoption signal fires with the folder's depth and whether it has subfolders.
- expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(1, false)
- })
-
- it('navigates to a folder with subfolders and toggles its expansion', () => {
- mockValues({
- folderTree: [
- {
- path: 'Marketing',
- label: 'Marketing',
- children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
- },
- ],
- })
- render(<DashboardsTree />)
- fireEvent.click(screen.getByText('Marketing'))
- expect(navigateToFolder).toHaveBeenCalledWith('Marketing')
- expect(toggleFolder).toHaveBeenCalledWith('Marketing')
- expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(1, true)
- })
-
- it('navigates to the root when the All dashboards node is clicked', () => {
- mockValues({ folderTree: [{ path: 'Marketing', label: 'Marketing', children: [] }] })
- render(<DashboardsTree />)
- fireEvent.click(screen.getByText('All dashboards'))
- expect(navigateToFolder).toHaveBeenCalledWith('')
- // Root is depth 0 and (here) has subfolders.
- expect(reportDashboardsTreeFolderNavigated).toHaveBeenCalledWith(0, true)
- })
-
- const clickExpandToggle = (container: HTMLElement): void => {
- fireEvent.click(container.querySelector('[data-attr="dashboards-tree-expand-toggle"]') as HTMLElement)
- }
-
- it('the expand toggle expands only folders that have subfolders (childless ones are skipped)', () => {
- mockValues({
- folderTree: [
- {
- path: 'Marketing',
- label: 'Marketing',
- // Q1 is childless, so it isn't expandable and must not appear in the expanded map.
- children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
- },
- ],
- })
- const { container } = render(<DashboardsTree />)
- clickExpandToggle(container)
- expect(setExpandedFolders).toHaveBeenCalledWith({ Marketing: true })
- })
-
- it('the toggle collapses everything when all folders are currently expanded', () => {
- mockValues({
- folderTree: [
- {
- path: 'Marketing',
- label: 'Marketing',
- children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
- },
- ],
- expandedFolders: { Marketing: true },
- })
- const { container } = render(<DashboardsTree />)
- clickExpandToggle(container)
- expect(setExpandedFolders).toHaveBeenCalledWith({})
- })
-
- it('the expand toggle cancels the row-link nav (no bounce to home) and does not select the root', () => {
- mockValues({
- folderTree: [
- {
- path: 'Marketing',
- label: 'Marketing',
- children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }],
- },
- ],
- })
- const { container } = render(<DashboardsTree />)
- const toggle = container.querySelector('[data-attr="dashboards-tree-expand-toggle"]') as HTMLElement
- // The row is a Link (to='#' for folders); fireEvent returns false only when the handler called
- // preventDefault — the guard that stops the toggle bouncing to home. stopPropagation keeps it from
- // also selecting the root folder.
- expect(fireEvent.click(toggle)).toBe(false)
- expect(navigateToFolder).not.toHaveBeenCalled()
- expect(setExpandedFolders).toHaveBeenCalled()
- })
-
- it('onFolderClick ignores an undefined folder — the null guard never throws or navigates', () => {
- mockValues({ folderTree: [] })
- render(<DashboardsTree />)
- // No click path produces undefined, but LemonTree's type allows it; the guard must hold.
- expect(() => mockLastOnFolderClick?.(undefined)).not.toThrow()
- expect(navigateToFolder).not.toHaveBeenCalled()
- })
-})
diff --git a/products/dashboards/frontend/components/DashboardsTree.tsx b/products/dashboards/frontend/components/DashboardsTree.tsx
deleted file mode 100644
index 5f691b797855..000000000000
--- a/products/dashboards/frontend/components/DashboardsTree.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import clsx from 'clsx'
-import { useActions, useValues } from 'kea'
-
-import { IconChevronRight, IconCollapse, IconExpand } from '@posthog/icons'
-import { LemonButton, Spinner } from '@posthog/lemon-ui'
-
-import { LemonTree, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
-import { DropdownMenuGroup } from 'lib/ui/DropdownMenu/DropdownMenu'
-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { DashboardsTable } from 'scenes/dashboard/dashboards/DashboardsTable'
-
-import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
-import { dashboardsModel } from '~/models/dashboardsModel'
-
-import { dashboardsFileSystemLogic } from '../logics/dashboardsFileSystemLogic'
-import { FolderTreeNode } from '../logics/dashboardsFileSystemUtils'
-import { DashboardsTreeFolderMenu } from './DashboardsTreeFolderMenu'
-
-// "All dashboards" is the single tree root; every folder nests under it. record.type 'folder' makes even
-// childless folders behave as folders. The folder path doubles as the id; the root uses a sentinel id.
-const ROOT_ID = '__all_dashboards__'
-
-function toTreeData(nodes: FolderTreeNode[]): TreeDataItem[] {
- return nodes.map((node) => ({
- id: node.path,
- name: node.label,
- record: { type: 'folder', path: node.path },
- children: node.children.length > 0 ? toTreeData(node.children) : undefined,
- }))
-}
-
-// Only folders that actually contain subfolders are "expandable". A childless folder is a terminal node:
-// expanding it would reveal nothing in the tree (its dashboards live in the right-hand table), so it never
-// gets the open-folder icon or a chevron — you just click it to scope the table.
-function collectExpandablePaths(nodes: FolderTreeNode[], acc: string[] = []): string[] {
- for (const node of nodes) {
- if (node.children.length > 0) {
- acc.push(node.path)
- collectExpandablePaths(node.children, acc)
- }
- }
- return acc
-}
-
-// Tree arm (variant=tree): the sidebar's LemonTree as a persistent folder panel on the left, beside the
-// familiar dashboards table on the right scoped to everything at or below the selected folder (root = all).
-// Expansion is controlled: the tree opens collapsed except for the root (so you see the top-level folders),
-// and clicking a folder expands it — both the chevron and a folder-row click mirror the toggle into the
-// expandedFolders reducer so collapsing sticks and the open/close animation plays.
-export function DashboardsTree(): JSX.Element {
- const {
- folderTree,
- currentFolder,
- currentSubtreeDashboards,
- expandedFolders,
- folderEntryByPath,
- folderDashboardCounts,
- dashboardFileSystemEntriesLoading,
- folderEntriesLoading,
- isTreePanelExpanded,
- } = useValues(dashboardsFileSystemLogic)
- const { navigateToFolder, toggleFolder, setExpandedFolders, toggleTreePanel } =
- useActions(dashboardsFileSystemLogic)
- const { reportDashboardsTreeFolderNavigated } = useActions(eventUsageLogic)
- const { dashboardsLoading } = useValues(dashboardsModel)
-
- const treeData: TreeDataItem[] = [
- {
- id: ROOT_ID,
- name: 'All dashboards',
- record: { type: 'folder', path: '' },
- children: toTreeData(folderTree),
- },
- ]
-
- // The root is always open; folders with subfolders are closed until expanded. Childless folders are never
- // expandable, so they stay closed-icon terminal nodes.
- const expandablePaths = collectExpandablePaths(folderTree)
- const expandedItemIds = [ROOT_ID, ...expandablePaths.filter((id) => expandedFolders[id])]
- const allExpanded = expandablePaths.length > 0 && expandablePaths.every((id) => expandedFolders[id])
-
- return (
- <div className="grid grid-cols-1 gap-4 md:grid-cols-[260px_1fr]" data-attr="dashboards-tree">
- {/* Hidden on desktop, where the panel is always shown beside the table. */}
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconChevronRight className={clsx('transition-transform', isTreePanelExpanded && 'rotate-90')} />}
- onClick={toggleTreePanel}
- className="md:hidden col-span-full justify-self-start"
- data-attr="dashboards-tree-panel-toggle"
- >
- {isTreePanelExpanded ? 'Hide folders' : 'Browse folders'}
- </LemonButton>
- <div
- // Collapsed hides the panel on mobile; md:flex keeps it visible on desktop regardless.
- className={clsx(
- 'flex-col border-b border-border pb-2 md:border-b-0 md:border-r md:pb-0 md:pr-2',
- isTreePanelExpanded ? 'flex' : 'hidden md:flex'
- )}
- aria-label="Folder tree"
- >
- {/* LemonTree drops its own className, so the override lives on this wrapper instead. Every
- open/expanded accordion trigger is shaded with the tertiary-active fill, which made all
- expanded folders look selected; null that fill out via the CSS variable (cascades to all
- rows) and re-apply it only to the actively-selected folder. */}
- {/* On mobile the tree stacks above the table, so cap its height and let it scroll — otherwise a
- project with many folders pushes the dashboards list far below the fold. Reset at md+ where the
- panel sits beside the table. */}
- <div className="dashboards-tree-panel flex-1 min-h-0 max-h-[40vh] overflow-y-auto md:max-h-none md:overflow-visible [--color-bg-fill-button-tertiary-active:transparent] [&_.button-primitive--active]:!bg-[var(--color-bg-fill-highlight-50)]">
- <LemonTree
- data={treeData}
- expandedItemIds={expandedItemIds}
- // Highlight only the folder you're in; navigating moves it (and clears the rest).
- isItemActive={(item) => item.record?.path === currentFolder}
- renderItem={(item, children) => {
- if (item.record?.type !== 'folder') {
- return children
- }
- // The root carries the expand/collapse-all toggle as a hover button (frees the
- // panel header); every other folder shows a trailing subtree dashboard count.
- if (item.id === ROOT_ID && expandablePaths.length > 0) {
- return (
- <span className="flex items-center gap-1 w-full min-w-0">
- <span className="truncate">{children}</span>
- <LemonButton
- size="small"
- icon={allExpanded ? <IconCollapse /> : <IconExpand />}
- tooltip={allExpanded ? 'Collapse all folders' : 'Expand all folders'}
- onClick={(e) => {
- // The row is a Link (to='#' since folders carry no href); preventDefault
- // stops the toggle from triggering that nav (which bounces to home),
- // stopPropagation stops it from also selecting the root folder.
- e.preventDefault()
- e.stopPropagation()
- setExpandedFolders(
- allExpanded
- ? {}
- : Object.fromEntries(expandablePaths.map((id) => [id, true]))
- )
- }}
- className="ml-auto shrink-0 opacity-0 group-hover/lemon-tree-button:opacity-100"
- data-attr="dashboards-tree-expand-toggle"
- />
- </span>
- )
- }
- const count = folderDashboardCounts[(item.record?.path as string) ?? ''] ?? 0
- return (
- <span className="flex items-center gap-1 w-full min-w-0">
- <span className="truncate">{children}</span>
- {count > 0 && (
- <span className="ml-auto shrink-0 text-xxs text-tertiary tabular-nums">
- {count}
- </span>
- )}
- </span>
- )
- }}
- onSetExpandedItemIds={(newIds) => {
- // Sync the whole expandable set to LemonTree's new state. (Find-first missed batch
- // keyboard collapses where a parent and its expanded children change at once;
- // rebuilding from the live set also drops stale paths of since-deleted folders.)
- const expanded = new Set(newIds)
- setExpandedFolders(Object.fromEntries(expandablePaths.map((id) => [id, expanded.has(id)])))
- }}
- onFolderClick={(folder) => {
- if (!folder) {
- return
- }
- // A folder click selects it (scopes the table); a folder that has subfolders also
- // toggles expansion. The root stays open; childless folders don't expand at all.
- const path = (folder.record?.path as string) ?? ''
- const hasSubfolders = !!folder.children && folder.children.length > 0
- reportDashboardsTreeFolderNavigated(splitPath(path).length, hasSubfolders)
- navigateToFolder(path)
- if (folder.id !== ROOT_ID && hasSubfolders) {
- toggleFolder(folder.id)
- }
- }}
- itemSideAction={(item) => {
- // Hover ellipsis on every folder (root included). Root → New folder; a real folder
- // → New subfolder / Rename / Move to / Delete (the last three need its FileSystem row).
- if (item.record?.type !== 'folder') {
- return undefined
- }
- const path = (item.record?.path as string) ?? ''
- return (
- <DropdownMenuGroup>
- <DashboardsTreeFolderMenu path={path} entry={folderEntryByPath[path]} />
- </DropdownMenuGroup>
- )
- }}
- />
- {(dashboardFileSystemEntriesLoading || folderEntriesLoading) && folderTree.length === 0 && (
- <div className="flex items-center justify-center p-3">
- <Spinner className="text-lg" />
- </div>
- )}
- </div>
- </div>
- <div className="min-w-0" data-attr="dashboards-tree-content">
- <DashboardsTable dashboards={currentSubtreeDashboards} dashboardsLoading={dashboardsLoading} />
- </div>
- </div>
- )
-}
diff --git a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx
deleted file mode 100644
index 99e05487b42e..000000000000
--- a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.test.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import '@testing-library/jest-dom'
-
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { useActions } from 'kea'
-
-import { LemonDialog } from '@posthog/lemon-ui'
-
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-
-import { DashboardsTreeFolderMenu } from './DashboardsTreeFolderMenu'
-
-jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn() }))
-jest.mock('@posthog/lemon-ui', () => ({
- ...jest.requireActual('@posthog/lemon-ui'),
- LemonDialog: { openForm: jest.fn() },
-}))
-// Render each menu item as a plain clickable element so we don't need the Radix DropdownMenu context.
-jest.mock('lib/ui/DropdownMenu/DropdownMenu', () => ({
- DropdownMenuItem: ({ children, onClick }: any) => <div onClick={onClick}>{children}</div>,
-}))
-
-const folderEntry = (path: string): FileSystemEntry => ({ id: `fs-${path}`, type: 'folder', path }) as FileSystemEntry
-
-describe('DashboardsTreeFolderMenu', () => {
- const createFolder = jest.fn()
- const renameFolder = jest.fn()
- const deleteFolder = jest.fn()
- const openMoveToModal = jest.fn()
- const openForm = LemonDialog.openForm as jest.Mock
-
- afterEach(cleanup)
-
- beforeEach(() => {
- ;[createFolder, renameFolder, deleteFolder, openMoveToModal, openForm].forEach((m) => m.mockClear())
- ;(useActions as jest.Mock).mockReturnValue({ createFolder, renameFolder, deleteFolder, openMoveToModal })
- })
-
- it('shows the full menu for a real folder', () => {
- render(<DashboardsTreeFolderMenu path="Marketing" entry={folderEntry('Marketing')} />)
- expect(screen.getByText('New subfolder')).toBeInTheDocument()
- expect(screen.getByText('Rename')).toBeInTheDocument()
- expect(screen.getByText('Move to...')).toBeInTheDocument()
- expect(screen.getByText('Delete')).toBeInTheDocument()
- })
-
- it('shows only New folder for the root (no entry)', () => {
- render(<DashboardsTreeFolderMenu path="" />)
- expect(screen.getByText('New folder')).toBeInTheDocument()
- expect(screen.queryByText('Rename')).not.toBeInTheDocument()
- expect(screen.queryByText('Move to...')).not.toBeInTheDocument()
- expect(screen.queryByText('Delete')).not.toBeInTheDocument()
- })
-
- it('creates a subfolder under the clicked folder', () => {
- render(<DashboardsTreeFolderMenu path="Marketing" entry={folderEntry('Marketing')} />)
- fireEvent.click(screen.getByText('New subfolder'))
- openForm.mock.calls[0][0].onSubmit({ folderName: 'Q1' })
- expect(createFolder).toHaveBeenCalledWith('Q1', 'Marketing')
- })
-
- it('renames the folder to the submitted name', () => {
- const entry = folderEntry('Marketing/Q1')
- render(<DashboardsTreeFolderMenu path="Marketing/Q1" entry={entry} />)
- fireEvent.click(screen.getByText('Rename'))
- // The rename dialog pre-fills the last path segment.
- expect(openForm.mock.calls[0][0].initialValues).toEqual({ folderName: 'Q1' })
- openForm.mock.calls[0][0].onSubmit({ folderName: 'Q2' })
- expect(renameFolder).toHaveBeenCalledWith(entry, 'Q2')
- })
-
- it('moves and deletes via the folder entry', () => {
- const entry = folderEntry('Marketing')
- render(<DashboardsTreeFolderMenu path="Marketing" entry={entry} />)
- fireEvent.click(screen.getByText('Move to...'))
- expect(openMoveToModal).toHaveBeenCalledWith([entry])
- fireEvent.click(screen.getByText('Delete'))
- expect(deleteFolder).toHaveBeenCalledWith(entry)
- })
-})
diff --git a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx b/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx
deleted file mode 100644
index c12813364721..000000000000
--- a/products/dashboards/frontend/components/DashboardsTreeFolderMenu.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { useActions } from 'kea'
-
-import { IconArrowRight, IconPencil, IconPlus, IconTrash } from '@posthog/icons'
-import { LemonDialog } from '@posthog/lemon-ui'
-
-import { moveToLogic } from 'lib/components/FileSystem/MoveTo/moveToLogic'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonInput } from 'lib/lemon-ui/LemonInput'
-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { DropdownMenuItem } from 'lib/ui/DropdownMenu/DropdownMenu'
-
-import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-
-import { dashboardsFileSystemLogic } from '../logics/dashboardsFileSystemLogic'
-
-interface DashboardsTreeFolderMenuProps {
- // The folder this menu acts on; '' is the tree root ("All dashboards"), which only offers New folder.
- path: string
- // The folder's FileSystem row. Absent for folders inferred purely from a dashboard's path (no row, no
- // id) — those can't be moved/renamed/deleted, so only New subfolder is shown.
- entry?: FileSystemEntry
-}
-
-function openNameDialog(title: string, initialName: string, onSubmit: (name: string) => void): void {
- // Guard against a fast double-click submitting twice before the dialog closes — the create/rename
- // actions are fire-and-forget, so without this a double-click yields a duplicate folder / repeated rename.
- let submitted = false
- LemonDialog.openForm({
- title,
- initialValues: { folderName: initialName },
- content: (
- <LemonField name="folderName">
- <LemonInput placeholder="Enter a folder name" autoFocus />
- </LemonField>
- ),
- errors: { folderName: (name) => (!name?.trim() ? 'You must enter a folder name' : undefined) },
- onSubmit: ({ folderName }) => {
- if (submitted) {
- return
- }
- submitted = true
- onSubmit(folderName)
- },
- })
-}
-
-// Folder context menu for the tree arm — reuses the same move/rename/delete/create operations the sidebar
-// tree uses (via dashboardsFileSystemLogic, which delegates to projectTreeDataLogic), but renders a scoped
-// surface instead of the sidebar's full menu. Rendered through LemonTree's itemSideAction (hover ellipsis).
-export function DashboardsTreeFolderMenu({ path, entry }: DashboardsTreeFolderMenuProps): JSX.Element {
- const { createFolder, renameFolder, deleteFolder } = useActions(dashboardsFileSystemLogic)
- const { openMoveToModal } = useActions(moveToLogic)
- const isRoot = path === ''
- const label = splitPath(path).at(-1) ?? path
-
- return (
- <>
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- openNameDialog(isRoot ? 'New folder' : 'New subfolder', '', (name) => createFolder(name, path))
- }}
- data-attr="dashboards-tree-new-folder"
- >
- <ButtonPrimitive menuItem>
- <IconPlus className="size-4 text-tertiary" />
- {isRoot ? 'New folder' : 'New subfolder'}
- </ButtonPrimitive>
- </DropdownMenuItem>
- {entry && (
- <>
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- openNameDialog('Rename folder', label, (name) => renameFolder(entry, name))
- }}
- data-attr="dashboards-tree-rename-folder"
- >
- <ButtonPrimitive menuItem>
- <IconPencil className="size-4 text-tertiary" />
- Rename
- </ButtonPrimitive>
- </DropdownMenuItem>
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- openMoveToModal([entry])
- }}
- data-attr="dashboards-tree-move-folder"
- >
- <ButtonPrimitive menuItem>
- <IconArrowRight className="size-4 text-tertiary" />
- Move to...
- </ButtonPrimitive>
- </DropdownMenuItem>
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- deleteFolder(entry)
- }}
- data-attr="dashboards-tree-delete-folder"
- >
- <ButtonPrimitive menuItem>
- <IconTrash className="size-4 text-danger" />
- Delete
- </ButtonPrimitive>
- </DropdownMenuItem>
- </>
- )}
- </>
- )
-}
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts
deleted file mode 100644
index 88489424b83f..000000000000
--- a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.test.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import api from 'lib/api'
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
-
-import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
-import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
-import { useMocks } from '~/mocks/jest'
-import { dashboardsModel } from '~/models/dashboardsModel'
-import { initKeaTests } from '~/test/init'
-
-import { dashboardsFileSystemLogic } from './dashboardsFileSystemLogic'
-
-describe('dashboardsFileSystemLogic', () => {
- // Safety net for tests that call silenceKeaLoadersErrors() inline
- afterEach(resumeKeaLoadersErrors)
-
- let logic: ReturnType<typeof dashboardsFileSystemLogic.build>
-
- useMocks({
- get: {
- '/api/environments/:team_id/dashboards/': () => [200, { count: 0, results: [], next: null }],
- '/api/projects/:team_id/dashboards/': () => [200, { count: 0, results: [], next: null }],
- },
- })
-
- beforeEach(() => {
- jest.spyOn(api.fileSystem, 'list').mockImplementation(
- async ({ type }: { type?: string } = {}) =>
- (type === 'folder'
- ? { count: 0, results: [], users: [] }
- : {
- count: 1,
- results: [{ id: 'fs-1', type: 'dashboard', ref: '1', path: 'Marketing/A' }],
- users: [],
- }) as any
- )
- jest.spyOn(api.fileSystem, 'unfiled').mockResolvedValue(null as any)
- jest.spyOn(api.fileSystemShortcuts, 'list').mockResolvedValue({ count: 0, results: [] } as any)
- jest.spyOn(api.fileSystem, 'create').mockResolvedValue({ id: 'fs-new', type: 'folder', path: 'x' } as any)
- initKeaTests()
- logic = dashboardsFileSystemLogic()
- logic.mount()
- })
-
- afterEach(() => {
- logic?.unmount()
- jest.restoreAllMocks()
- })
-
- it('loads dashboard file-system entries indexed by ref', async () => {
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- expect(logic.values.entryByRef['1']?.path).toEqual('Marketing/A')
- })
-
- it('pages through every dashboard entry instead of truncating at one page', async () => {
- await expectLogic(logic).toDispatchActions([
- 'loadDashboardFileSystemEntriesSuccess',
- 'loadFolderEntriesSuccess',
- ])
- const entry = (n: number): any => ({ id: `fs-${n}`, type: 'dashboard', ref: String(n), path: `Folder/${n}` })
- const fullPage = Array.from({ length: 500 }, (_, i) => entry(i))
- ;(api.fileSystem.list as jest.Mock).mockImplementation(async ({ type, offset = 0 }: any) =>
- type !== 'dashboard'
- ? { count: 0, results: [], users: [] }
- : offset === 0
- ? { count: 501, results: fullPage, users: [] }
- : { count: 501, results: [entry(500)], users: [] }
- )
- logic.unmount()
- logic = dashboardsFileSystemLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- // 500 (page 1) + 1 (page 2): the 501st entry is loaded, not dropped past the old single-page cap.
- expect(logic.values.entryByRef['500']?.path).toEqual('Folder/500')
- expect(Object.keys(logic.values.entryByRef)).toHaveLength(501)
- })
-
- it('exposes empty folder rows in the folder tree', async () => {
- // Drain the beforeEach mount's loaders so their (uncancelled) results don't race the re-mock below.
- await expectLogic(logic).toDispatchActions([
- 'loadDashboardFileSystemEntriesSuccess',
- 'loadFolderEntriesSuccess',
- ])
- ;(api.fileSystem.list as jest.Mock).mockImplementation(
- async ({ type }: { type?: string } = {}) =>
- (type === 'folder'
- ? { count: 1, results: [{ id: 'fld', type: 'folder', path: 'Ideas' }], users: [] }
- : { count: 0, results: [], users: [] }) as any
- )
- logic.unmount()
- logic = dashboardsFileSystemLogic()
- logic.mount()
- await expectLogic(logic).toDispatchActions([
- 'loadDashboardFileSystemEntriesSuccess',
- 'loadFolderEntriesSuccess',
- ])
- // The folder rows feed the tree even with no dashboards beneath them (empty folders appear).
- expect(logic.values.folderTree.map((node) => node.path)).toEqual(['Ideas'])
- })
-
- it('navigates folders', async () => {
- await expectLogic(logic, () => logic.actions.navigateToFolder('Marketing')).toMatchValues({
- currentFolder: 'Marketing',
- })
- await expectLogic(logic, () => logic.actions.navigateToFolder('')).toMatchValues({ currentFolder: '' })
- })
-
- it('refetches entries when a dashboard move lands so the subtree reflects the new path', async () => {
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- expect(logic.values.entryByRef['1']?.path).toEqual('Marketing/A')
- ;(api.fileSystem.list as jest.Mock).mockImplementation(
- async ({ type }: { type?: string } = {}) =>
- (type === 'folder'
- ? { count: 0, results: [], users: [] }
- : {
- count: 1,
- results: [{ id: 'fs-1', type: 'dashboard', ref: '1', path: 'Product/A' }],
- users: [],
- }) as any
- )
- await expectLogic(logic, () => {
- projectTreeDataLogic.actions.movesSettled([
- {
- item: { id: 'fs-1', type: 'dashboard', ref: '1', path: 'Marketing/A' } as any,
- oldPath: 'Marketing/A',
- newPath: 'Product/A',
- },
- ])
- }).toDispatchActions(['loadDashboardFileSystemEntries', 'loadDashboardFileSystemEntriesSuccess'])
- expect(logic.values.entryByRef['1']?.path).toEqual('Product/A')
- })
-
- it('refetches once for a whole bulk move, and reloads folder rows when any item was a folder', async () => {
- await expectLogic(logic).toDispatchActions([
- 'loadDashboardFileSystemEntriesSuccess',
- 'loadFolderEntriesSuccess',
- ])
- ;(api.fileSystem.list as jest.Mock).mockClear()
-
- // A bulk move announces itself once, however many items it carried. Refetching per item would fire a
- // full pagination each time, and that concurrent load is what surfaced a folder-load error over a
- // move that had actually succeeded.
- await expectLogic(logic, () => {
- projectTreeDataLogic.actions.movesSettled([
- {
- item: { id: 'fld', type: 'folder', path: 'Marketing' } as any,
- oldPath: 'Marketing',
- newPath: 'Product/Marketing',
- },
- {
- item: { id: 'fs-1', type: 'dashboard', ref: '1', path: 'Marketing/A' } as any,
- oldPath: 'Marketing/A',
- newPath: 'Product/A',
- },
- {
- item: { id: 'fs-2', type: 'dashboard', ref: '2', path: 'Marketing/B' } as any,
- oldPath: 'Marketing/B',
- newPath: 'Product/B',
- },
- ])
- }).toDispatchActions(['loadDashboardFileSystemEntriesSuccess', 'loadFolderEntriesSuccess'])
-
- const listedTypes = (api.fileSystem.list as jest.Mock).mock.calls.map(([{ type }]) => type)
- expect(listedTypes).toEqual(['dashboard', 'folder'])
- })
-
- it('ignores moves of non-dashboard, non-folder items (no wasted refetch)', async () => {
- await expectLogic(logic).toDispatchActions([
- 'loadDashboardFileSystemEntriesSuccess',
- 'loadFolderEntriesSuccess',
- ])
- ;(api.fileSystem.list as jest.Mock).mockClear()
- projectTreeDataLogic.actions.movesSettled([
- { item: { id: 'i-1', type: 'insight', path: 'a' } as any, oldPath: 'a', newPath: 'b' },
- ])
- await expectLogic(logic).toFinishAllListeners()
- expect(api.fileSystem.list).not.toHaveBeenCalled()
- })
-
- it('refetches the subtree after a duplicate lands', async () => {
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- await expectLogic(logic, () => {
- dashboardsModel.actions.duplicateDashboardSuccess({ id: 2, name: 'A (Copy)' } as any)
- }).toDispatchActions(['loadDashboardFileSystemEntries'])
- })
-
- it('createFolder creates a folder under the current folder, syncs the sidebar, refetches, and selects it', async () => {
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- logic.actions.navigateToFolder('Marketing')
- ;(api.fileSystem.create as jest.Mock).mockClear()
- await expectLogic(logic, () => logic.actions.createFolder('Ideas')).toDispatchActions([
- 'createFolder',
- // Syncs the sidebar's shared store, then refreshes our own folder rows.
- 'createSavedItem',
- 'loadFolderEntries',
- ])
- expect(api.fileSystem.create).toHaveBeenCalledWith({ type: 'folder', path: 'Marketing/Ideas' })
- expect(logic.values.currentFolder).toEqual('Marketing/Ideas')
- })
-
- it('createFolder ignores a blank name', async () => {
- ;(api.fileSystem.create as jest.Mock).mockClear()
- logic.actions.createFolder(' ')
- await expectLogic(logic).toFinishAllListeners()
- expect(api.fileSystem.create).not.toHaveBeenCalled()
- })
-
- it('toasts an error when loading dashboard folders fails', async () => {
- await expectLogic(logic).toDispatchActions(['loadDashboardFileSystemEntriesSuccess'])
- const error = jest.spyOn(lemonToast, 'error').mockReturnValue('' as any)
- ;(api.fileSystem.list as jest.Mock).mockRejectedValueOnce(new Error('boom'))
- // Deliberate loader failure — kea-loaders would log it
- silenceKeaLoadersErrors()
- await expectLogic(logic, () => {
- logic.actions.loadDashboardFileSystemEntries()
- }).toDispatchActions(['loadDashboardFileSystemEntriesFailure'])
- expect(error).toHaveBeenCalled()
- })
-
- it('toasts an error when loading folder rows fails', async () => {
- await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
- const error = jest.spyOn(lemonToast, 'error').mockReturnValue('' as any)
- ;(api.fileSystem.list as jest.Mock).mockRejectedValueOnce(new Error('boom'))
- // Deliberate loader failure — kea-loaders would log it
- silenceKeaLoadersErrors()
- await expectLogic(logic, () => {
- logic.actions.loadFolderEntries()
- }).toDispatchActions(['loadFolderEntriesFailure'])
- expect(error).toHaveBeenCalled()
- })
-
- it('renameFolder moves the folder to the renamed sibling path and re-points the current scope', async () => {
- const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
- await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
- logic.actions.navigateToFolder('Marketing')
- logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, 'Growth')
- await expectLogic(logic).toFinishAllListeners()
- expect(move).toHaveBeenCalledWith('fld', 'Growth')
- expect(logic.values.currentFolder).toEqual('Growth')
- })
-
- it('renameFolder ignores a blank name and an unsaved (id-less) folder', async () => {
- const move = jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
- logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, ' ')
- logic.actions.renameFolder({ type: 'folder', path: 'Marketing' } as any, 'Growth')
- await expectLogic(logic).toFinishAllListeners()
- expect(move).not.toHaveBeenCalled()
- })
-
- it('deleteFolder delegates to the shared delete path (projectTreeDataLogic.deleteItem)', async () => {
- jest.spyOn(api.fileSystem, 'count').mockResolvedValue({ count: 0 } as any)
- jest.spyOn(api.fileSystem, 'delete').mockResolvedValue({ deleted: [] } as any)
- await expectLogic(logic, () => {
- logic.actions.deleteFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any)
- }).toDispatchActions([projectTreeDataLogic.actionTypes.deleteItem])
- })
-
- it('on delete, refetches and falls back to root when the current folder OR an ancestor is gone', async () => {
- await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
- logic.actions.navigateToFolder('Marketing/Q1')
- await expectLogic(logic, () => {
- // Deleting the ancestor 'Marketing' while scoped to 'Marketing/Q1' must reset to root.
- projectTreeDataLogic.actions.deleteSavedItem({ id: 'fld', type: 'folder', path: 'Marketing' } as any)
- }).toDispatchActions(['loadFolderEntries', 'loadDashboardFileSystemEntries'])
- expect(logic.values.currentFolder).toEqual('')
- })
-
- it('on delete of an unrelated folder, keeps the current scope', async () => {
- logic.actions.navigateToFolder('Marketing')
- projectTreeDataLogic.actions.deleteSavedItem({ id: 'fld', type: 'folder', path: 'Finance' } as any)
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.currentFolder).toEqual('Marketing')
- })
-
- it('refetches on undo (restoredItems) so restored items reappear without a reload', async () => {
- await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
- await expectLogic(logic, () => {
- projectTreeDataLogic.actions.restoredItems()
- }).toDispatchActions(['loadFolderEntries', 'loadDashboardFileSystemEntries'])
- })
-
- it('renameFolder re-points a descendant scope onto the renamed path', async () => {
- jest.spyOn(api.fileSystem, 'move').mockResolvedValue({} as any)
- await expectLogic(logic).toDispatchActions(['loadFolderEntriesSuccess'])
- logic.actions.navigateToFolder('Marketing/Q1')
- logic.actions.renameFolder({ id: 'fld', type: 'folder', path: 'Marketing' } as any, 'Growth')
- await expectLogic(logic).toFinishAllListeners()
- // Renaming the ancestor 'Marketing' → 'Growth' moves the descendant scope to 'Growth/Q1'.
- expect(logic.values.currentFolder).toEqual('Growth/Q1')
- })
-})
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts b/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts
deleted file mode 100644
index 94aae1140961..000000000000
--- a/products/dashboards/frontend/logics/dashboardsFileSystemLogic.ts
+++ /dev/null
@@ -1,432 +0,0 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import posthog from 'posthog-js'
-
-import api from 'lib/api'
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { withTimeout } from 'lib/utils/async'
-import { dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
-
-import { MovedItem, projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
-import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
-import { dashboardsModel } from '~/models/dashboardsModel'
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-import { DashboardBasicType } from '~/types'
-
-import {
- buildEntryByRef,
- buildFolderDashboardCounts,
- buildFolderTree,
- FolderTreeNode,
- subtreeDashboards,
-} from './dashboardsFileSystemUtils'
-
-const FILE_SYSTEM_PAGE_SIZE = 500
-// Safety ceiling so a misbehaving endpoint can't loop forever — 10 pages = 5k entries, well above any realistic
-// single project (and far cheaper to load than the old 40-page cap).
-const MAX_FILE_SYSTEM_PAGES = 10
-// Per-page timeout so one hung request can't leave the tree loader pending forever (mirrors the sidebar's
-// shortcuts loader); the abort signal cancels the in-flight request on timeout.
-const FILE_SYSTEM_PAGE_TIMEOUT_MS = 10000
-// Scopes projectTreeDataLogic's optional post-processing (selection clear, undo re-expand) for our reused delete
-// path; safely no-ops for our unmounted instance.
-const DASHBOARDS_TREE_PROJECT_LOGIC_KEY = 'dashboards-tree'
-
-// Page through every dashboard/folder FileSystem entry so large projects render their full tree instead of
-// being silently truncated to the first page — the experiment measures navigation, and big projects are
-// exactly the ones the tree is meant to help.
-async function fetchAllFileSystemEntries(type: 'dashboard' | 'folder'): Promise<FileSystemEntry[]> {
- const entries: FileSystemEntry[] = []
- for (let page = 0; page < MAX_FILE_SYSTEM_PAGES; page++) {
- const response = await withTimeout(
- (signal) =>
- api.fileSystem.list({
- type,
- limit: FILE_SYSTEM_PAGE_SIZE,
- offset: page * FILE_SYSTEM_PAGE_SIZE,
- signal,
- }),
- FILE_SYSTEM_PAGE_TIMEOUT_MS,
- `dashboardsFileSystemLogic: ${type} page ${page} timed out`
- )
- entries.push(...response.results)
- if (response.results.length < FILE_SYSTEM_PAGE_SIZE) {
- return entries
- }
- }
- // Hitting the ceiling means a project's tree is truncated — emit a signal (not just a console.warn) so we can
- // spot affected projects and raise the cap if real usage demands it.
- posthog.capture('dashboards tree pagination ceiling hit', {
- entry_type: type,
- entries_loaded: entries.length,
- ceiling: MAX_FILE_SYSTEM_PAGES * FILE_SYSTEM_PAGE_SIZE,
- })
- return entries
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardsFileSystemLogicValues {
- dashboards: DashboardBasicType[] // dashboardsLogic
- currentFolder: string
- currentSubtreeDashboards: DashboardBasicType[]
- dashboardFileSystemEntries: FileSystemEntry[]
- dashboardFileSystemEntriesLoading: boolean
- entryByRef: Record<string, FileSystemEntry>
- expandedFolders: Record<string, boolean>
- folderDashboardCounts: Record<string, number>
- folderEntries: FileSystemEntry[]
- folderEntriesLoading: boolean
- folderEntryByPath: Record<string, FileSystemEntry>
- folderPaths: string[]
- folderTree: FolderTreeNode[]
- isTreePanelExpanded: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardsFileSystemLogicActions {
- createSavedItem: (savedItem: FileSystemEntry) => {
- savedItem: FileSystemEntry
- } // projectTreeDataLogic
- deleteItem: (
- item: FileSystemEntry,
- projectTreeLogicKey: string
- ) => {
- item: FileSystemEntry
- projectTreeLogicKey: string
- } // projectTreeDataLogic
- movedItem: (
- item: FileSystemEntry,
- oldPath: string,
- newPath: string
- ) => {
- item: FileSystemEntry
- newPath: string
- oldPath: string
- } // projectTreeDataLogic
- movesSettled: (moved: MovedItem[]) => {
- moved: MovedItem[]
- } // projectTreeDataLogic
- createFolder: (
- name: string,
- parentPath?: string
- ) => {
- name: string
- parentPath: string | undefined
- }
- deleteFolder: (entry: FileSystemEntry) => {
- entry: FileSystemEntry
- }
- loadDashboardFileSystemEntries: () => any
- loadDashboardFileSystemEntriesFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadDashboardFileSystemEntriesSuccess: (
- dashboardFileSystemEntries: FileSystemEntry[],
- payload?: any
- ) => {
- dashboardFileSystemEntries: FileSystemEntry[]
- payload?: any
- }
- loadFolderEntries: () => any
- loadFolderEntriesFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadFolderEntriesSuccess: (
- folderEntries: FileSystemEntry[],
- payload?: any
- ) => {
- folderEntries: FileSystemEntry[]
- payload?: any
- }
- navigateToFolder: (folder: string) => {
- folder: string
- }
- renameFolder: (
- entry: FileSystemEntry,
- newName: string
- ) => {
- entry: FileSystemEntry
- newName: string
- }
- setExpandedFolders: (folders: Record<string, boolean>) => {
- folders: Record<string, boolean>
- }
- toggleFolder: (folder: string) => {
- folder: string
- }
- toggleTreePanel: () => {
- value: true
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardsFileSystemLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- entryByRef: (dashboardFileSystemEntries: FileSystemEntry[]) => Record<string, FileSystemEntry>
- folderPaths: (folderEntries: FileSystemEntry[]) => string[]
- folderEntryByPath: (folderEntries: FileSystemEntry[]) => Record<string, FileSystemEntry>
- folderTree: (
- dashboards: DashboardBasicType[],
- entryByRef: Record<string, FileSystemEntry>,
- folderPaths: string[]
- ) => FolderTreeNode[]
- currentSubtreeDashboards: (
- dashboards: DashboardBasicType[],
- entryByRef: Record<string, FileSystemEntry>,
- currentFolder: string
- ) => DashboardBasicType[]
- folderDashboardCounts: (
- dashboards: DashboardBasicType[],
- entryByRef: Record<string, FileSystemEntry>
- ) => Record<string, number>
- }
-}
-
-export type dashboardsFileSystemLogicType = MakeLogicType<
- dashboardsFileSystemLogicValues,
- dashboardsFileSystemLogicActions,
- Record<string, any>,
- dashboardsFileSystemLogicMeta
->
-
-// View state for the tree arm: a folder tree built from the same FileSystem rows that back the sidebar
-// (both dashboard and folder rows, so empty folders appear), the selected folder, its expand state, and the
-// dashboards at or below it. Folder creation calls api.fileSystem.create then
-// projectTreeDataLogic.createSavedItem so the sidebar's in-memory store stays consistent. Per-dashboard
-// organizing (move / rename / delete) is handled by the reused DashboardsTable's own row actions, which go
-// through the shared move path — there is no second folder model to sync.
-export const dashboardsFileSystemLogic = kea<dashboardsFileSystemLogicType>([
- path(['products', 'dashboards', 'dashboardsFileSystemLogic']),
- connect(() => ({
- values: [dashboardsLogic, ['dashboards']],
- actions: [projectTreeDataLogic, ['createSavedItem', 'movedItem', 'movesSettled', 'deleteItem']],
- })),
- actions({
- // Tree arm: select a folder ('' = the dashboards root).
- navigateToFolder: (folder: string) => ({ folder }),
- // Toggle a folder's expand/collapse state in the panel (folders start collapsed — see expandedFolders).
- toggleFolder: (folder: string) => ({ folder }),
- // Replace the whole expanded-folders map at once (Expand all / Collapse all).
- setExpandedFolders: (folders: Record<string, boolean>) => ({ folders }),
- // Mobile-only panel toggle; desktop shows the panel unconditionally via CSS.
- toggleTreePanel: true,
- // Create a folder inside `parentPath` ('' = root; defaults to the selected folder when omitted).
- createFolder: (name: string, parentPath?: string) => ({ name, parentPath }),
- // Rename a folder — moves it to a sibling path carrying the new name (descendants re-path server-side).
- renameFolder: (entry: FileSystemEntry, newName: string) => ({ entry, newName }),
- // Delete a folder via the shared delete path (its confirmation + undo + store sync live there).
- deleteFolder: (entry: FileSystemEntry) => ({ entry }),
- }),
- loaders({
- dashboardFileSystemEntries: [
- [] as FileSystemEntry[],
- {
- loadDashboardFileSystemEntries: async (): Promise<FileSystemEntry[]> =>
- await fetchAllFileSystemEntries('dashboard'),
- },
- ],
- // Real folder rows, so empty folders (and ones the user creates) show up in the tree — not just
- // folders inferred from dashboard paths.
- folderEntries: [
- [] as FileSystemEntry[],
- {
- loadFolderEntries: async (): Promise<FileSystemEntry[]> => await fetchAllFileSystemEntries('folder'),
- },
- ],
- }),
- reducers({
- currentFolder: [
- '',
- {
- navigateToFolder: (_, { folder }) => folder,
- },
- ],
- // Folders the user has explicitly expanded. The tree starts collapsed except for the root, so it
- // opens with just the top-level folders; clicking a folder expands it. Persisted to localStorage
- // (like the sidebar tree) so an accidental reload keeps your folders open; stale paths from since-
- // deleted folders are harmless — they're filtered against the live tree before use.
- expandedFolders: [
- {} as Record<string, boolean>,
- { persist: true },
- {
- toggleFolder: (state, { folder }) => ({ ...state, [folder]: !state[folder] }),
- setExpandedFolders: (_, { folders }) => folders,
- },
- ],
- // Not persisted, so mobile always opens with the panel collapsed and the dashboards list front and centre.
- isTreePanelExpanded: [
- false,
- {
- toggleTreePanel: (state) => !state,
- },
- ],
- }),
- selectors({
- entryByRef: [
- (s) => [s.dashboardFileSystemEntries],
- (entries: FileSystemEntry[]): Record<string, FileSystemEntry> => buildEntryByRef(entries),
- ],
- folderPaths: [
- (s) => [s.folderEntries],
- (folderEntries: FileSystemEntry[]): string[] => folderEntries.map((entry) => entry.path),
- ],
- // Real folder rows keyed by path, so the folder menu can act on a folder's FileSystemEntry (needs its
- // id). Folders that exist only because a dashboard references them (no row) are absent — the menu hides
- // move/rename/delete for those and offers only "New subfolder".
- folderEntryByPath: [
- (s) => [s.folderEntries],
- (folderEntries: FileSystemEntry[]): Record<string, FileSystemEntry> =>
- Object.fromEntries(folderEntries.map((entry) => [entry.path, entry])),
- ],
- folderTree: [
- (s) => [s.dashboards, s.entryByRef, s.folderPaths],
- (
- dashboards: DashboardBasicType[],
- entryByRef: Record<string, FileSystemEntry>,
- folderPaths: string[]
- ): FolderTreeNode[] => buildFolderTree(dashboards, entryByRef, folderPaths),
- ],
- // Tree arm: every dashboard at or below the selected folder, recursively (root = all). The tree is a
- // scope selector; the content pane (DashboardsTable) shows everything in scope.
- currentSubtreeDashboards: [
- (s) => [s.dashboards, s.entryByRef, s.currentFolder],
- (
- dashboards: DashboardBasicType[],
- entryByRef: Record<string, FileSystemEntry>,
- currentFolder: string
- ): DashboardBasicType[] => subtreeDashboards(dashboards, entryByRef, currentFolder),
- ],
- // Dashboard count per folder path (subtree), for the tree's trailing count badges.
- folderDashboardCounts: [
- (s) => [s.dashboards, s.entryByRef],
- (dashboards: DashboardBasicType[], entryByRef: Record<string, FileSystemEntry>): Record<string, number> =>
- buildFolderDashboardCounts(dashboards, entryByRef),
- ],
- }),
- listeners(({ values, actions }) => ({
- // A duplicate (via the table) creates a dashboard server-side; refetch so the subtree reflects it
- // (the new dashboard syncs its own FileSystem entry via FileSystemSyncMixin).
- [dashboardsModel.actionTypes.duplicateDashboardSuccess]: () => {
- actions.loadDashboardFileSystemEntries()
- },
- // Listening for the settled operation rather than for each `movedItem` is what keeps a bulk move to
- // one refetch: a real boundary, instead of a window long enough to guess that no more are coming.
- // A dashboard move changes its own path; a folder move re-parents the dashboards beneath it and the
- // folder rows. Other item types (insights, notebooks) don't affect this view.
- [projectTreeDataLogic.actionTypes.movesSettled]: ({ moved }: { moved: MovedItem[] }) => {
- const movedTypes = new Set(moved.map(({ item }) => item.type))
- if (!movedTypes.has('dashboard') && !movedTypes.has('folder')) {
- return
- }
- actions.loadDashboardFileSystemEntries()
- if (movedTypes.has('folder')) {
- actions.loadFolderEntries()
- }
- },
- loadDashboardFileSystemEntriesFailure: () => {
- // Without this the folder structure silently collapses to Unfiled (kea-loaders only
- // console.errors), so the degraded state would look like a genuinely flat project.
- lemonToast.error('Could not load dashboard folders — they may appear unorganized. Refresh to retry.')
- },
- loadFolderEntriesFailure: () => {
- // Mirror the dashboard-entries failure toast: without it, empty folders silently disappear and
- // the degraded structure looks like a genuinely flat project.
- lemonToast.error('Could not load folders — empty folders may not appear. Refresh to retry.')
- },
- createFolder: async ({ name, parentPath }) => {
- const trimmed = name.trim()
- if (!trimmed) {
- return
- }
- const parent = parentPath ?? values.currentFolder
- const path = joinPath([...(parent ? splitPath(parent) : []), trimmed])
- try {
- const created = await api.fileSystem.create({ type: 'folder', path } as FileSystemEntry)
- // Sync the sidebar's shared store the same way the project-tree create path does, then
- // refresh our own folder rows and select the new folder.
- actions.createSavedItem(created)
- actions.loadFolderEntries()
- actions.navigateToFolder(path)
- lemonToast.success(`Created folder "${trimmed}"`)
- } catch (error) {
- console.error('Error creating folder:', error)
- // Runs in an async listener, not a kea-loader, so initKea's global onFailure never sees it —
- // capture here or we're blind to folder-create error rates (a key adoption-metric operation).
- posthog.captureException(error)
- lemonToast.error('Could not create the folder.')
- }
- },
- renameFolder: async ({ entry, newName }) => {
- const trimmed = newName.trim()
- if (!trimmed || !entry.id) {
- return
- }
- const newPath = joinPath([...splitPath(entry.path).slice(0, -1), trimmed])
- if (newPath === entry.path) {
- return
- }
- try {
- await api.fileSystem.move(entry.id, newPath)
- // Two different things, both needed: the first re-paths this folder's row in the sidebar's
- // store, the second says the operation is over so the refetch listener below runs. A rename
- // calls the move API directly rather than going through `moveItems`, so nothing else emits it.
- actions.movedItem(entry, entry.path, newPath)
- actions.movesSettled([{ item: entry, oldPath: entry.path, newPath }])
- // Re-point the scope if we were inside the renamed folder — or a descendant of it, which moves
- // with it. (deleteSavedItem falls back to root because the folder is gone; rename keeps it.)
- if (values.currentFolder === entry.path) {
- actions.navigateToFolder(newPath)
- } else if (values.currentFolder.startsWith(`${entry.path}/`)) {
- actions.navigateToFolder(newPath + values.currentFolder.slice(entry.path.length))
- }
- lemonToast.success(`Renamed to "${trimmed}"`)
- } catch (error) {
- console.error('Error renaming folder:', error)
- // Async listener, not a kea-loader — capture so folder-rename failures surface in error tracking.
- posthog.captureException(error)
- lemonToast.error('Could not rename the folder.')
- }
- },
- deleteFolder: ({ entry }) => {
- // Reuse the shared delete: large-folder confirmation, undo toast, and store sync all live there.
- // The follow-up refetch happens in the deleteSavedItem listener below.
- actions.deleteItem(entry, DASHBOARDS_TREE_PROJECT_LOGIC_KEY)
- },
- [projectTreeDataLogic.actionTypes.deleteSavedItem]: ({ savedItem }: { savedItem: FileSystemEntry }) => {
- // Only dashboards/folders affect this view — ignore unrelated sidebar deletes (insights, notebooks),
- // matching the movedItem listener's type-gate.
- if (savedItem.type !== 'dashboard' && savedItem.type !== 'folder') {
- return
- }
- // Deleting a folder cascades to its dashboards (soft-deleted server-side, undoable). Refetch our
- // FileSystem rows AND the dashboards list itself — without the latter the soft-deleted dashboards
- // linger in dashboardsModel and the folder looks like it didn't delete.
- actions.loadFolderEntries()
- actions.loadDashboardFileSystemEntries()
- dashboardsModel.actions.loadDashboards()
- // If the folder we were scoped to — or an ancestor of it — is gone, fall back to the root
- // rather than leaving the table pointed at a now-deleted subtree.
- if (values.currentFolder === savedItem.path || values.currentFolder.startsWith(`${savedItem.path}/`)) {
- actions.navigateToFolder('')
- }
- },
- [projectTreeDataLogic.actionTypes.restoredItems]: () => {
- // An undo-delete restored items server-side; refetch so they reappear without a page reload.
- actions.loadFolderEntries()
- actions.loadDashboardFileSystemEntries()
- dashboardsModel.actions.loadDashboards()
- },
- })),
- afterMount(({ actions }) => {
- actions.loadDashboardFileSystemEntries()
- actions.loadFolderEntries()
- }),
-])
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts
deleted file mode 100644
index 25d5e01b5c7b..000000000000
--- a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-import { DashboardBasicType } from '~/types'
-
-import {
- buildEntryByRef,
- buildFolderDashboardCounts,
- buildFolderTree,
- subtreeDashboards,
-} from './dashboardsFileSystemUtils'
-
-const dash = (id: number, name: string): DashboardBasicType => ({ id, name }) as DashboardBasicType
-const entry = (ref: string, path: string): FileSystemEntry =>
- ({ id: `fs-${ref}`, type: 'dashboard', ref, path }) as FileSystemEntry
-
-describe('dashboardsFileSystemUtils', () => {
- it('indexes only dashboard entries by ref', () => {
- const byRef = buildEntryByRef([
- entry('1', 'Marketing/A'),
- { id: 'fld', type: 'folder', path: 'Marketing' } as FileSystemEntry,
- ])
- expect(Object.keys(byRef)).toEqual(['1'])
- })
-
- it('builds a nested folder tree from dashboard paths, with ancestors and Unfiled, sorted', () => {
- const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C')]
- const byRef = buildEntryByRef([entry('1', 'Marketing/A'), entry('2', 'Marketing/Q1/B')])
- expect(buildFolderTree(dashboards, byRef)).toEqual([
- { path: 'Marketing', label: 'Marketing', children: [{ path: 'Marketing/Q1', label: 'Q1', children: [] }] },
- {
- path: 'Unfiled',
- label: 'Unfiled',
- children: [{ path: 'Unfiled/Dashboards', label: 'Dashboards', children: [] }],
- },
- ])
- })
-
- it('returns an empty tree when there are no dashboards', () => {
- expect(buildFolderTree([], {})).toEqual([])
- })
-
- it('tolerates an undefined dashboards list (transient during a cascading delete) without throwing', () => {
- expect(buildFolderTree(undefined, {})).toEqual([])
- expect(buildFolderDashboardCounts(undefined, {})).toEqual({})
- expect(subtreeDashboards(undefined, {}, 'Marketing')).toEqual([])
- })
-
- it('buildFolderTree includes empty folder rows (no dashboards beneath) and their ancestors', () => {
- const byRef = buildEntryByRef([entry('1', 'Marketing/A')])
- const tree = buildFolderTree([dash(1, 'A')], byRef, ['Ideas', 'Archive/2024'])
- expect(tree.map((node) => node.path)).toEqual(['Archive', 'Ideas', 'Marketing'])
- expect(tree.find((node) => node.path === 'Archive')?.children.map((c) => c.path)).toEqual(['Archive/2024'])
- })
-
- it('subtreeDashboards returns every dashboard at or below a folder (root = all)', () => {
- const byRef = buildEntryByRef([
- entry('1', 'Marketing/A'),
- entry('2', 'Marketing/Q1/B'),
- entry('3', 'Product/C'),
- ])
- const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C')]
- expect(subtreeDashboards(dashboards, byRef, 'Marketing')).toEqual([dash(1, 'A'), dash(2, 'B')])
- expect(subtreeDashboards(dashboards, byRef, '').map((d) => d.id)).toEqual([1, 2, 3])
- })
-
- it('counts dashboards per folder subtree, with ancestors, Unfiled, and the root total', () => {
- const byRef = buildEntryByRef([
- entry('1', 'Marketing/A'),
- entry('2', 'Marketing/Q1/B'),
- entry('3', 'Product/C'),
- ])
- // id 4 has no entry → Unfiled.
- const dashboards = [dash(1, 'A'), dash(2, 'B'), dash(3, 'C'), dash(4, 'D')]
- expect(buildFolderDashboardCounts(dashboards, byRef)).toEqual({
- '': 4,
- Marketing: 2,
- 'Marketing/Q1': 1,
- Product: 1,
- Unfiled: 1,
- 'Unfiled/Dashboards': 1,
- })
- })
-
- it('subtreeDashboards treats dashboards with no folder entry as Unfiled', () => {
- const byRef = buildEntryByRef([entry('1', 'Marketing/A')])
- const dashboards = [dash(1, 'A'), dash(2, 'B')]
- // id 2 has no entry → Unfiled/Dashboards; only matches the Unfiled subtree, not Marketing.
- expect(subtreeDashboards(dashboards, byRef, 'Marketing').map((d) => d.id)).toEqual([1])
- expect(subtreeDashboards(dashboards, byRef, 'Unfiled').map((d) => d.id)).toEqual([2])
- })
-})
diff --git a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts b/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts
deleted file mode 100644
index 19bc8079defe..000000000000
--- a/products/dashboards/frontend/logics/dashboardsFileSystemUtils.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { UNFILED_DASHBOARDS_FOLDER } from 'scenes/dashboard/dashboardConstants'
-
-import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
-import { FileSystemEntry } from '~/queries/schema/schema-general'
-import { DashboardBasicType } from '~/types'
-
-const UNFILED_SEGMENTS = splitPath(UNFILED_DASHBOARDS_FOLDER)
-
-// The path segments of a dashboard's containing folder (its FileSystem entry's path minus the last
-// segment); empty when the dashboard has no entry. Callers decide how to treat the empty case (the tree
-// groups those under Unfiled; the Folder column labels them "Unfiled").
-export function dashboardParentSegments(entry: FileSystemEntry | undefined): string[] {
- return entry?.path ? splitPath(entry.path).slice(0, -1) : []
-}
-
-export interface FolderTreeNode {
- // Full folder path, e.g. 'Marketing/Q1'.
- path: string
- // Last path segment, for display.
- label: string
- children: FolderTreeNode[]
-}
-
-// Index dashboard FileSystem rows by their `ref` (the dashboard id as a string) for O(1) lookup.
-export function buildEntryByRef(entries: FileSystemEntry[]): Record<string, FileSystemEntry> {
- const byRef: Record<string, FileSystemEntry> = {}
- for (const entry of entries) {
- if (entry.type === 'dashboard' && entry.ref) {
- byRef[entry.ref] = entry
- }
- }
- return byRef
-}
-
-// Build the nested folder tree the tree arm renders in its LemonTree panel: every folder that contains a
-// dashboard (plus all its ancestors), unioned with the explicit `folderPaths` (real folder rows) so empty
-// folders also appear. Unfiled dashboards contribute the Unfiled subtree.
-export function buildFolderTree(
- // `dashboards` is connected from dashboardsLogic and can be momentarily undefined while a mutation
- // (e.g. a cascading folder delete) reloads the model — tolerate it rather than crash the recompute.
- dashboards: DashboardBasicType[] | undefined,
- entryByRef: Record<string, FileSystemEntry>,
- folderPaths: string[] = []
-): FolderTreeNode[] {
- const allFolderPaths = new Set<string>()
- const addWithAncestors = (segments: string[]): void => {
- for (let i = 1; i <= segments.length; i++) {
- allFolderPaths.add(joinPath(segments.slice(0, i)))
- }
- }
- for (const dashboard of dashboards ?? []) {
- const parentSegments = dashboardParentSegments(entryByRef[String(dashboard.id)])
- addWithAncestors(parentSegments.length > 0 ? parentSegments : UNFILED_SEGMENTS)
- }
- for (const folderPath of folderPaths) {
- addWithAncestors(splitPath(folderPath))
- }
-
- const byPath = new Map<string, FolderTreeNode>()
- const roots: FolderTreeNode[] = []
- // Split each path once, then shallowest-first so a node's parent always exists before it's attached.
- const sorted = [...allFolderPaths]
- .map((path) => ({ path, segments: splitPath(path) }))
- .sort((a, b) => a.segments.length - b.segments.length || a.path.localeCompare(b.path))
- for (const { path, segments } of sorted) {
- const node: FolderTreeNode = { path, label: segments.at(-1) ?? path, children: [] }
- byPath.set(path, node)
- const parent = segments.length > 1 ? byPath.get(joinPath(segments.slice(0, -1))) : undefined
- ;(parent ? parent.children : roots).push(node)
- }
-
- const sortChildren = (nodes: FolderTreeNode[]): void => {
- nodes.sort((a, b) => a.label.localeCompare(b.label))
- nodes.forEach((node) => sortChildren(node.children))
- }
- sortChildren(roots)
- return roots
-}
-
-// Dashboards at or below each folder path, so a folder's badge matches the subtree the table shows when
-// you select it. Each dashboard contributes to its containing folder, every ancestor, and the root ('').
-// Mirrors buildFolderTree's Unfiled handling so the counts line up with the rendered tree.
-export function buildFolderDashboardCounts(
- dashboards: DashboardBasicType[] | undefined,
- entryByRef: Record<string, FileSystemEntry>
-): Record<string, number> {
- const counts: Record<string, number> = {}
- for (const dashboard of dashboards ?? []) {
- const parentSegments = dashboardParentSegments(entryByRef[String(dashboard.id)])
- const segments = parentSegments.length > 0 ? parentSegments : UNFILED_SEGMENTS
- counts[''] = (counts[''] ?? 0) + 1
- for (let i = 1; i <= segments.length; i++) {
- const path = joinPath(segments.slice(0, i))
- counts[path] = (counts[path] ?? 0) + 1
- }
- }
- return counts
-}
-
-// Every dashboard at or below `currentFolder`, recursively. Root ('') returns all dashboards. The tree
-// arm feeds these to the dashboards table, scoped to the selected folder's subtree.
-export function subtreeDashboards(
- dashboards: DashboardBasicType[] | undefined,
- entryByRef: Record<string, FileSystemEntry>,
- currentFolder: string
-): DashboardBasicType[] {
- const prefix = currentFolder ? splitPath(currentFolder) : []
- return (dashboards ?? []).filter((dashboard) => {
- const entry = entryByRef[String(dashboard.id)]
- const segments = entry?.path ? splitPath(entry.path).slice(0, -1) : UNFILED_SEGMENTS
- return prefix.every((segment, index) => segments[index] === segment)
- })
-}
diff --git a/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts b/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts
deleted file mode 100644
index 669300f3601a..000000000000
--- a/products/dashboards/frontend/logics/dashboardsListViewVariants.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { FEATURE_FLAGS } from 'lib/constants'
-import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-
-import { DashboardsListViewVariant, resolveDashboardsListViewVariant } from './dashboardsListViewVariants'
-
-// Experiment cleanup: flag `dashboards-list-view` · experiment 379125 — remove with the tree arm.
-describe('resolveDashboardsListViewVariant', () => {
- const cases: [string | boolean | undefined, DashboardsListViewVariant][] = [
- [undefined, 'control'],
- ['', 'control'],
- ['unknown', 'control'],
- [true, 'control'],
- ['control', 'control'],
- ['tree', 'tree'],
- // Retired arm names now fall back to control rather than enrolling a treatment arm.
- ['explorer', 'control'],
- ['grid', 'control'],
- ['finder', 'control'],
- ]
-
- it.each(cases)('flag value %p resolves to %p', (value, expected) => {
- const featureFlags: FeatureFlagsSet = value === undefined ? {} : { [FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]: value }
- expect(resolveDashboardsListViewVariant(featureFlags)).toBe(expected)
- })
-})
diff --git a/products/dashboards/frontend/logics/dashboardsListViewVariants.ts b/products/dashboards/frontend/logics/dashboardsListViewVariants.ts
deleted file mode 100644
index 03e7ba3ebc49..000000000000
--- a/products/dashboards/frontend/logics/dashboardsListViewVariants.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { FEATURE_FLAGS } from 'lib/constants'
-import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-
-// One folder-navigation paradigm tested against today's flat list: `tree` (a persistent folder-tree panel
-// beside the table). The `grid` and `explorer` arms were both dropped before launch — see the design spec.
-// Experiment cleanup: flag `dashboards-list-view` · experiment 379125 — remove this resolver and the tree arm
-// when the experiment concludes.
-export type DashboardsListViewVariant = 'control' | 'tree'
-
-const DEFAULT_VARIANT: DashboardsListViewVariant = 'control'
-
-export const DASHBOARDS_LIST_VIEW_VARIANTS: DashboardsListViewVariant[] = ['control', 'tree']
-
-// Resolves the `dashboards-list-view` multivariate flag to a known arm, defaulting to control
-// so a missing, unknown, boolean, or empty flag value never silently enrolls a project in a treatment arm.
-export function resolveDashboardsListViewVariant(featureFlags: FeatureFlagsSet): DashboardsListViewVariant {
- const variant = featureFlags[FEATURE_FLAGS.DASHBOARDS_LIST_VIEW]
- return typeof variant === 'string' && (DASHBOARDS_LIST_VIEW_VARIANTS as string[]).includes(variant)
- ? (variant as DashboardsListViewVariant)
- : DEFAULT_VARIANT
-}