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.

feat(dashboards): show tile groups as bands that open and close (#116030)

Paul D'Ambra18a1a0f49880
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a3623e3f5b57..7b47b5913c3c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7208,6 +7208,14 @@ snapshots:
hash: v1.k794b7964.762601bb7a59d6ca5aaad78a8f470aebfb3907f4714d2d534bf7353a54525c6d.iojbhy_Og8NozcL_fVG45sNdo7zUx4nAPUZVa80uFyI
products-dashboards-tiles-tile-decorations--winner-with-group-title--light:
hash: v1.k794b7964.7b86b194158108c532550809ba0e7708df82e3e8d4a16a6580dfe614465f196d.oZ1nrnPhkV45bWhAMbGzhCXOtaVPBzhX6dDs2k8x1Tw
+ products-dashboards-tiles-tile-group--long-title-in-narrow-scene--dark:
+ hash: v1.k794b7964.27638afc84fe3f23808339cda8d42c7e464411aad854363184e963f50a9e8986.0953slExphaNxMyTtkUtSNL5zeDWGAmuH1eVdua6IqA
+ products-dashboards-tiles-tile-group--long-title-in-narrow-scene--light:
+ hash: v1.k794b7964.e2516d3990cbce5642887f30e4c2fb5185203e189527684c2226936c5d8f9b7b.ZCRE43avr2zzsh5jn7IDs-xe1JwPcaIFoOk_nfhvLp4
+ products-dashboards-tiles-tile-group--styles--dark:
+ hash: v1.k794b7964.be0395b6c09a3c0380edd0b5bb22cfe61482fa0c977f51b144dab5fdd77f6ce8.-KKnKUn0dUiBlAtuIOzPRIVfjImLj8UbTWHpPj1r6zY
+ products-dashboards-tiles-tile-group--styles--light:
+ hash: v1.k794b7964.1ea4c4743d7380fe85985e50795f9a6dd4dc1909f37a926800aa316aebb26a31.-z1Igyir2gbb9kVTuxP9EAoUX1Dg5J1fKGFJINxzh7g
products-data-catalog-metric-lineage--being-prepared--dark:
hash: v1.k794b7964.9b3dd08fa1426e0715daefdf347f20d3e251483c787dd3a9f3ad02fca88ae00b.N85-92zGL68U5fyXpoWHYbbTGLRVTOw42k7LxJ3HZHw
products-data-catalog-metric-lineage--being-prepared--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index bee805b73f2a..2238f7fb44f9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -298,6 +298,7 @@ export const FEATURE_FLAGS = {
CUSTOMER_ANALYTICS_TRACK_RULES: 'customer-analytics-track-rules', // owner: @arthurdedeus #team-customer-analytics
DASHBOARD_EXPORT_NUDGE: 'dashboard-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported a dashboard toward a recurring subscription
DASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platform
+ DASHBOARD_TILE_GROUP_SECTIONS: 'dashboard-tile-group-sections', // owner: @pauldambra #team-analytics-platform, shows tile groups as bands that open and close
DATA_MODELING_USAGE: 'data-modeling-usage', // owner: #team-data-modeling, gates the Models usage tab
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 5393a6523304..b208780531eb 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -47,7 +47,7 @@ jest.mock('kea-router', () => ({
}))
jest.mock('products/dashboards/frontend/useDashboardContainerWidth', () => ({
- useDashboardContainerWidth: () => ({ width: 1200, containerRef: { current: null } }),
+ useDashboardContainerWidth: () => ({ width: mockGridWidth, containerRef: { current: null } }),
}))
jest.mock('lib/hooks/useFeatureFlag', () => ({
@@ -154,6 +154,7 @@ jest.mock('react-grid-layout', () => {
},
Responsive: ({
className,
+ style,
rowHeight,
margin,
resizeConfig,
@@ -161,23 +162,30 @@ jest.mock('react-grid-layout', () => {
children,
}: {
className: string
+ style?: Record<string, number>
rowHeight: number
margin: [number, number]
resizeConfig: { enabled: boolean }
dragConfig: { enabled: boolean }
children: any
- }) => (
- <div
- data-attr="react-grid-layout"
- data-class-name={className}
- data-row-height={String(rowHeight)}
- data-margin={margin.join(',')}
- data-resize-enabled={String(resizeConfig.enabled)}
- data-drag-enabled={String(dragConfig.enabled)}
- >
- {children}
- </div>
- ),
+ }) => {
+ jest.requireActual('react').useEffect(() => {
+ mockGridMounts++
+ }, [])
+ return (
+ <div
+ data-attr="react-grid-layout"
+ data-style-width={style?.width}
+ data-class-name={className}
+ data-row-height={String(rowHeight)}
+ data-margin={margin.join(',')}
+ data-resize-enabled={String(resizeConfig.enabled)}
+ data-drag-enabled={String(dragConfig.enabled)}
+ >
+ {children}
+ </div>
+ )
+ },
}
})
@@ -197,6 +205,9 @@ const mockedUseAsyncActions = useAsyncActions as jest.Mock
const mockRemoveTile = jest.fn()
const mockTriggerDashboardRefresh = jest.fn()
const mockInsightCard = jest.fn()
+const mockUpdateContainerWidth = jest.fn()
+let mockGridWidth = 1200
+let mockGridMounts = 0
let canEditDashboard = true
describe('DashboardItems', () => {
@@ -204,6 +215,8 @@ describe('DashboardItems', () => {
mockInsightCard.mockClear()
jest.clearAllMocks()
canEditDashboard = true
+ mockGridWidth = 1200
+ mockGridMounts = 0
mockedUseValues.mockImplementation((logic) => {
if (logic === dashboardLogic) {
@@ -233,6 +246,7 @@ describe('DashboardItems', () => {
dataColorThemeId: null,
canEditDashboard,
layoutZoom: 0.75,
+ tileGroupSections: [],
}
}
@@ -249,7 +263,7 @@ describe('DashboardItems', () => {
if (logic === dashboardLogic) {
return {
updateLayouts: jest.fn(),
- updateContainerWidth: jest.fn(),
+ updateContainerWidth: mockUpdateContainerWidth,
updateTileColor: jest.fn(),
toggleTileDescription: jest.fn(),
removeTile: mockRemoveTile,
@@ -381,6 +395,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
if (logic === dashboardsModel) {
@@ -416,6 +431,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
if (logic === dashboardsModel) {
@@ -457,6 +473,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
@@ -494,6 +511,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
@@ -546,6 +564,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
@@ -602,6 +621,7 @@ describe('DashboardItems', () => {
layoutZoom: 1,
widgetResultsByTileId: {},
widgetRefreshStatus: {},
+ tileGroupSections: [],
}
}
@@ -640,4 +660,76 @@ describe('DashboardItems', () => {
expect(insightCard).toHaveAttribute('data-api-error-code', 'refresh_failed')
expect(insightCard).toHaveAttribute('data-api-error-detail', 'The refreshed query failed')
})
+
+ describe('tile group bands', () => {
+ const showBands = (streamedTileIds: number[] = []): void => {
+ const defaultValues = mockedUseValues.getMockImplementation()!
+ mockedUseValues.mockImplementation((logic) => {
+ const values = defaultValues(logic)
+ const tiles = [
+ ...values.tiles,
+ ...streamedTileIds.map((id) => ({ id, insight: { id: 100 + id, short_id: `tile${id}` } })),
+ ]
+ const layouts = {
+ sm: [
+ ...values.layouts.sm,
+ ...streamedTileIds.map((id) => ({ i: String(id), x: 6, y: 0, w: 6, h: 5 })),
+ ],
+ }
+ return logic === dashboardLogic
+ ? {
+ ...values,
+ tiles,
+ layouts,
+ tileGroupSections: [
+ {
+ kind: 'group',
+ key: 'group-plans',
+ groupKey: 'plans',
+ group: { title: 'Plans' },
+ tiles,
+ },
+ ],
+ tileGroupSectionLayouts: [layouts],
+ collapsedTileGroupKeys: [],
+ }
+ : values
+ })
+ }
+
+ it.each([
+ { name: 'one grid', bands: false },
+ { name: 'tile group bands', bands: true },
+ ])('waits for the container width before it renders $name', ({ bands }) => {
+ mockGridWidth = 0
+ if (bands) {
+ showBands()
+ }
+
+ const { container } = render(<DashboardItems />)
+
+ expect(container.querySelector('[data-attr="react-grid-layout"]')).not.toBeInTheDocument()
+ })
+
+ it('gives the dashboard width to the logic when it shows tile group bands', () => {
+ showBands()
+
+ const { getByText } = render(<DashboardItems />)
+
+ expect(getByText('Plans')).toBeInTheDocument()
+ expect(mockUpdateContainerWidth).toHaveBeenCalledWith(1200, 12)
+ })
+
+ it('keeps a band grid mounted when a tile streams into the band', () => {
+ const defaultValues = mockedUseValues.getMockImplementation()!
+ showBands()
+ const { rerender } = render(<DashboardItems />)
+
+ mockedUseValues.mockImplementation(defaultValues)
+ showBands([2])
+ rerender(<DashboardItems />)
+
+ expect(mockGridMounts).toBe(1)
+ })
+ })
})
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index ca3a5aa28cba..3209d32ec244 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -14,6 +14,7 @@ import { ApiError } from 'lib/api'
import { EditModeEdge, useResizeHandleScrollbarPassThrough } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
import { TileDecorations } from 'lib/components/TileDecorations/TileDecorations'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
@@ -34,13 +35,15 @@ import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunity
import { urls } from 'scenes/urls'
import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'
-import { DashboardLayoutSize, DashboardPlacement, DashboardType } from '~/types'
+import { DashboardLayoutSize, DashboardPlacement, DashboardTile, DashboardType } from '~/types'
import { DashboardGridBackground } from 'products/dashboards/frontend/components/DashboardGridBackground'
import { DashboardInsightTile } from 'products/dashboards/frontend/components/DashboardInsightTile'
import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
+import { DashboardTileGroup } from 'products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'
+import type { DashboardSection } from 'products/dashboards/frontend/dashboardTileSections'
import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDashboardContainerWidth'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
@@ -105,6 +108,10 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
widgetRefreshStatus,
scrollToBottomSignal,
sizeKey,
+ tileGroupSectionsEnabled,
+ tileGroupSections,
+ tileGroupSectionLayouts,
+ collapsedTileGroupKeys,
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
@@ -120,6 +127,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
moveToDashboard,
copyToDashboard,
setDashboardEditing,
+ toggleTileGroup,
+ updateTileGroupSectionLayout,
} = useActions(dashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
const { reportDashboardTileRepositioned } = useActions(eventUsageLogic)
@@ -193,11 +202,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
})
const { width: gridWidth, containerRef } = useDashboardContainerWidth()
+ const showBands = tileGroupSections.length > 0
const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =
useDashboardLayoutInteraction({
layoutEditMode,
layoutCompaction: dashboard?.customization?.layout_compaction,
- updateLayouts: stageLayouts,
+ // Each band grid reports only its own tiles.
+ updateLayouts: showBands ? updateTileGroupSectionLayout : stageLayouts,
})
useEffect(() => {
@@ -256,11 +267,19 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
tiles: tiles || [],
layout: layouts[activeBreakpoint],
activeBreakpoint,
- groups: dashboard?.customization?.groups,
+ groups: tileGroupSectionsEnabled ? undefined : dashboard?.customization?.groups,
compactor: gridCompactor,
widgetTilesShown,
}),
- [tiles, layouts, activeBreakpoint, dashboard?.customization?.groups, gridCompactor, widgetTilesShown]
+ [
+ tiles,
+ layouts,
+ activeBreakpoint,
+ tileGroupSectionsEnabled,
+ dashboard?.customization?.groups,
+ gridCompactor,
+ widgetTilesShown,
+ ]
)
const decorationsByTileId = useMemo(
() =>
@@ -427,6 +446,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
[updateContainerWidth]
)
+ // Band grids are narrower than the dashboard, so the dashboard width picks one breakpoint for all of them.
+ const bandBreakpoint: DashboardLayoutSize = gridWidth > BREAKPOINTS.sm ? 'sm' : 'xs'
+ useEffect(() => {
+ if (showBands && gridWidth > 0) {
+ updateContainerWidth(gridWidth, BREAKPOINT_COLUMN_COUNTS[bandBreakpoint])
+ }
+ }, [showBands, gridWidth, bandBreakpoint, updateContainerWidth])
+
const handleResizeStart = useCallback(
(
layout: Layout,
@@ -526,6 +553,247 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
}, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
+ const renderTile = (tile: DashboardTile): JSX.Element | undefined => {
+ const { insight, text, button_tile, widget } = tile
+ const tileActions = tileActionsById.get(tile.id)!
+ const smLayout = layouts['sm']?.find((l) => {
+ return l.i == tile.id.toString()
+ })
+
+ const decorations = decorationsByTileId.get(tile.id)
+
+ const commonTileProps = {
+ dashboardId: dashboard?.id,
+ canEditDashboard,
+ showResizeHandles,
+ canEnterEditModeFromEdge,
+ onEnterEditModeFromEdge,
+ onDragHandleMouseDown,
+ showEditingControls,
+ moveToDashboard: tileActions.moveToDashboard,
+ copyToDashboard: tileActions.copyToDashboard,
+ removeFromDashboard: tileActions.removeFromDashboard,
+ }
+
+ if (tile.error && !insight) {
+ return (
+ <MemoizedDashboardErrorTileItem
+ key={tile.id}
+ tile={tile}
+ onRetry={retryFailedDashboardTile}
+ retryLoading={dashboardLoading}
+ placement={placement}
+ onRemove={commonTileProps.removeFromDashboard}
+ showResizeHandles={showResizeHandles}
+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}
+ onDragHandleMouseDown={onDragHandleMouseDown}
+ showEditingControls={showEditingControls}
+ >
+ {decorations}
+ </MemoizedDashboardErrorTileItem>
+ )
+ }
+
+ if (insight) {
+ // Check if this insight has an error from the server
+ const isErrorTile = !!tile.error
+ const queryError = getInsightQueryError(insight)
+ const apiErrored = isErrorTile || !!queryError || refreshStatus[insight.short_id]?.errored || false
+ const refreshError = refreshStatus[insight.short_id]?.error
+ const apiError = isErrorTile
+ ? new ApiError(undefined, 500, undefined, {
+ detail: tile.error!.message,
+ code: 'dashboard_tile_error',
+ })
+ : refreshError || queryError || undefined
+ const loadingQueued = isErrorTile ? false : isRefreshingQueued(insight.short_id)
+ const loading = isErrorTile ? false : isRefreshing(insight.short_id)
+
+ return (
+ <DashboardInsightTile
+ key={tile.id}
+ tile={tile}
+ insight={insight}
+ loadingQueued={loadingQueued}
+ loading={loading}
+ apiErrored={apiErrored}
+ apiError={apiError}
+ queryId={insight.query_status?.id}
+ highlighted={highlightedInsightId && insight.short_id === highlightedInsightId}
+ ribbonColor={tile.color}
+ showDetailsControls={showDetailsControls}
+ placement={placement}
+ loadPriority={smLayout ? smLayout.y * 1000 + smLayout.x : undefined}
+ filtersOverride={effectiveEditBarFilters}
+ variablesOverride={currentDashboardVariables}
+ // :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render
+ breakdownColorOverride={effectiveBreakdownColors}
+ dataColorThemeId={dataColorThemeId}
+ surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}
+ showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
+ decorations={decorations}
+ {...commonTileProps}
+ />
+ )
+ }
+
+ if (text) {
+ return (
+ <MemoizedDashboardTextItem
+ key={tile.id}
+ tile={tile}
+ placement={placement}
+ dashboardId={dashboard?.id}
+ onEdit={tileActions.edit}
+ onMoveToDashboard={commonTileProps.moveToDashboard}
+ onCopyToDashboard={commonTileProps.copyToDashboard}
+ onDuplicate={tileActions.duplicate}
+ onRemove={commonTileProps.removeFromDashboard}
+ showResizeHandles={commonTileProps.showResizeHandles}
+ showEditingControls={commonTileProps.showEditingControls}
+ canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
+ onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
+ >
+ {decorations}
+ </MemoizedDashboardTextItem>
+ )
+ }
+
+ if (button_tile) {
+ return (
+ <MemoizedDashboardButtonTileItem
+ key={tile.id}
+ tile={tile}
+ placement={placement}
+ dashboardId={dashboard?.id}
+ isDraggingRef={isDragging}
+ onEdit={tileActions.edit}
+ onMoveToDashboard={commonTileProps.moveToDashboard}
+ onDuplicate={tileActions.duplicate}
+ onRemove={commonTileProps.removeFromDashboard}
+ showResizeHandles={commonTileProps.showResizeHandles}
+ showEditingControls={commonTileProps.showEditingControls}
+ canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
+ onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
+ >
+ {decorations}
+ </MemoizedDashboardButtonTileItem>
+ )
+ }
+
+ if (widget && widgetTilesShown) {
+ const runResult = widgetResultsByTileId[tile.id]
+ const refreshState = widgetRefreshStatus[tile.id]
+
+ return (
+ <MemoizedDashboardWidgetItem
+ key={tile.id}
+ tile={tile}
+ placement={placement}
+ dashboardId={dashboard?.id}
+ canEditDashboard={canEditDashboard}
+ isDashboardEditMode={layoutEditMode}
+ result={runResult?.result}
+ error={getDashboardWidgetFetchDisplayError(runResult?.error ?? refreshState?.error)}
+ loading={!!refreshState?.loading}
+ lastFetchedAt={refreshState?.fetchedAt}
+ onRefresh={tileActions.refreshWidget}
+ onRefreshWidgetData={scheduleRefreshDashboardWidgets}
+ onApplyWidgetIssueMetadataChange={onWidgetIssueMetadataChange}
+ onUpdateWidgetTile={tileActions.updateWidget}
+ onConfigPublished={onWidgetConfigPublished}
+ toggleShowDescription={tileActions.toggleDescription}
+ onDuplicate={tileActions.duplicate}
+ onRemove={commonTileProps.removeFromDashboard}
+ onMoveToDashboard={commonTileProps.moveToDashboard}
+ onCopyToDashboard={commonTileProps.copyToDashboard}
+ showResizeHandles={commonTileProps.showResizeHandles}
+ showEditingControls={commonTileProps.showEditingControls}
+ canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
+ onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
+ >
+ {decorations}
+ </MemoizedDashboardWidgetItem>
+ )
+ }
+ }
+
+ const gridProps = {
+ dragConfig,
+ resizeConfig,
+ compactor: gridCompactor,
+ rowHeight,
+ margin,
+ containerPadding: CONTAINER_PADDING,
+ onLayoutChange: handleLayoutChange,
+ breakpoints: BREAKPOINTS,
+ cols: BREAKPOINT_COLUMN_COUNTS,
+ onResizeStart: handleResizeStart,
+ onResizeStop: handleResizeStop,
+ onDragStart: handleDragStart,
+ onDrag: handleDrag,
+ onDragStop: handleDragStop,
+ }
+
+ const renderSection = (section: DashboardSection, index: number): JSX.Element => {
+ const sectionLayouts = tileGroupSectionLayouts[index]
+ // One empty row below the tiles gives a dragged tile somewhere to land.
+ const sectionRows = Math.max(0, ...(sectionLayouts.sm ?? []).map((item) => item.y + item.h)) + 1
+ const grid = (
+ <div className="relative">
+ {layoutEditMode && !isMobileView && (
+ <DashboardGridBackground
+ width={gridWidth}
+ cols={BREAKPOINT_COLUMN_COUNTS.sm}
+ rowHeight={rowHeight}
+ margin={margin}
+ height={sectionRows * (rowHeight + margin[1]) - margin[1]}
+ />
+ )}
+ <ReactGridLayout
+ {...gridProps}
+ // The grid takes a new tile's position from `layouts`, so a stable key lets tiles stream
+ // into a band without a remount that resets every chart already in it.
+ key={section.key}
+ width={gridWidth}
+ className={clsx(
+ layoutEditMode ? 'dashboard-edit-mode box-content' : 'dashboard-view-mode',
+ layoutEditMode && (index === tileGroupSections.length - 1 ? 'pb-[40vh]' : 'pb-24')
+ )}
+ breakpoint={bandBreakpoint}
+ layouts={sectionLayouts}
+ >
+ {section.tiles.map(renderTile)}
+ </ReactGridLayout>
+ </div>
+ )
+
+ if (section.kind === 'tiles') {
+ return (
+ <div key={section.key}>
+ {/* Without a line, viewers read loose tiles under a closed group as part of that group. */}
+ {index > 0 && <LemonDivider className="mb-4" />}
+ {grid}
+ </div>
+ )
+ }
+ return (
+ <DashboardTileGroup
+ key={section.key}
+ group={section.group}
+ tileCount={section.tiles.length}
+ collapsed={collapsedTileGroupKeys.includes(section.groupKey)}
+ onToggle={() => toggleTileGroup(section.groupKey)}
+ >
+ {grid}
+ </DashboardTileGroup>
+ )
+ }
+
return (
<div className="dashboard-items-wrapper" ref={containerRef as RefObject<HTMLDivElement>}>
{layoutEditMode && isMobileView && (
@@ -534,7 +802,12 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
resize tiles.
</LemonBanner>
)}
- {gridWidth > 0 && (
+ {gridWidth > 0 && showBands && (
+ <div className={clsx('flex flex-col gap-4', showDecorationSpace && 'mt-10', !layoutEditMode && 'mb-8')}>
+ {tileGroupSections.map(renderSection)}
+ </div>
+ )}
+ {gridWidth > 0 && !showBands && (
<div className={clsx('relative', showDecorationSpace && 'mt-10')}>
{layoutEditMode && !isMobileView && (
<DashboardGridBackground
@@ -547,197 +820,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
)}
<ReactGridLayout
+ {...gridProps}
width={gridWidth}
style={{ width: gridWidth }}
className={className}
- dragConfig={dragConfig}
- resizeConfig={resizeConfig}
layouts={layouts as Partial<Record<DashboardLayoutSize, Layout>>}
- compactor={gridCompactor}
- rowHeight={rowHeight}
- margin={margin}
- containerPadding={CONTAINER_PADDING}
- onLayoutChange={handleLayoutChange}
onWidthChange={handleWidthChange}
- breakpoints={BREAKPOINTS}
- cols={BREAKPOINT_COLUMN_COUNTS}
- onResizeStart={handleResizeStart}
- onResizeStop={handleResizeStop}
- onDragStart={handleDragStart}
- onDrag={handleDrag}
- onDragStop={handleDragStop}
>
- {tiles?.map((tile) => {
- const { insight, text, button_tile, widget } = tile
- const tileActions = tileActionsById.get(tile.id)!
- const smLayout = layouts['sm']?.find((l) => {
- return l.i == tile.id.toString()
- })
-
- const decorations = decorationsByTileId.get(tile.id)
-
- const commonTileProps = {
- dashboardId: dashboard?.id,
- canEditDashboard,
- showResizeHandles,
- canEnterEditModeFromEdge,
- onEnterEditModeFromEdge,
- onDragHandleMouseDown,
- showEditingControls,
- moveToDashboard: tileActions.moveToDashboard,
- copyToDashboard: tileActions.copyToDashboard,
- removeFromDashboard: tileActions.removeFromDashboard,
- }
-
- if (tile.error && !insight) {
- return (
- <MemoizedDashboardErrorTileItem
- key={tile.id}
- tile={tile}
- onRetry={retryFailedDashboardTile}
- retryLoading={dashboardLoading}
- placement={placement}
- onRemove={commonTileProps.removeFromDashboard}
- showResizeHandles={showResizeHandles}
- canEnterEditModeFromEdge={canEnterEditModeFromEdge}
- onEnterEditModeFromEdge={onEnterEditModeFromEdge}
- onDragHandleMouseDown={onDragHandleMouseDown}
- showEditingControls={showEditingControls}
- >
- {decorations}
- </MemoizedDashboardErrorTileItem>
- )
- }
-
- if (insight) {
- // Check if this insight has an error from the server
- const isErrorTile = !!tile.error
- const queryError = getInsightQueryError(insight)
- const apiErrored =
- isErrorTile || !!queryError || refreshStatus[insight.short_id]?.errored || false
- const refreshError = refreshStatus[insight.short_id]?.error
- const apiError = isErrorTile
- ? new ApiError(undefined, 500, undefined, {
- detail: tile.error!.message,
- code: 'dashboard_tile_error',
- })
- : refreshError || queryError || undefined
- const loadingQueued = isErrorTile ? false : isRefreshingQueued(insight.short_id)
- const loading = isErrorTile ? false : isRefreshing(insight.short_id)
-
- return (
- <DashboardInsightTile
- key={tile.id}
- tile={tile}
- insight={insight}
- loadingQueued={loadingQueued}
- loading={loading}
- apiErrored={apiErrored}
- apiError={apiError}
- queryId={insight.query_status?.id}
- highlighted={highlightedInsightId && insight.short_id === highlightedInsightId}
- ribbonColor={tile.color}
- showDetailsControls={showDetailsControls}
- placement={placement}
- loadPriority={smLayout ? smLayout.y * 1000 + smLayout.x : undefined}
- filtersOverride={effectiveEditBarFilters}
- variablesOverride={currentDashboardVariables}
- // :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render
- breakdownColorOverride={effectiveBreakdownColors}
- dataColorThemeId={dataColorThemeId}
- surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}
- showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
- decorations={decorations}
- {...commonTileProps}
- />
- )
- }
-
- if (text) {
- return (
- <MemoizedDashboardTextItem
- key={tile.id}
- tile={tile}
- placement={placement}
- dashboardId={dashboard?.id}
- onEdit={tileActions.edit}
- onMoveToDashboard={commonTileProps.moveToDashboard}
- onCopyToDashboard={commonTileProps.copyToDashboard}
- onDuplicate={tileActions.duplicate}
- onRemove={commonTileProps.removeFromDashboard}
- showResizeHandles={commonTileProps.showResizeHandles}
- showEditingControls={commonTileProps.showEditingControls}
- canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
- onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
- onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- >
- {decorations}
- </MemoizedDashboardTextItem>
- )
- }
-
- if (button_tile) {
- return (
- <MemoizedDashboardButtonTileItem
- key={tile.id}
- tile={tile}
- placement={placement}
- dashboardId={dashboard?.id}
- isDraggingRef={isDragging}
- onEdit={tileActions.edit}
- onMoveToDashboard={commonTileProps.moveToDashboard}
- onDuplicate={tileActions.duplicate}
- onRemove={commonTileProps.removeFromDashboard}
- showResizeHandles={commonTileProps.showResizeHandles}
- showEditingControls={commonTileProps.showEditingControls}
- canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
- onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
- onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- >
- {decorations}
- </MemoizedDashboardButtonTileItem>
- )
- }
-
- if (widget && widgetTilesShown) {
- const runResult = widgetResultsByTileId[tile.id]
- const refreshState = widgetRefreshStatus[tile.id]
-
- return (
- <MemoizedDashboardWidgetItem
- key={tile.id}
- tile={tile}
- placement={placement}
- dashboardId={dashboard?.id}
- canEditDashboard={canEditDashboard}
- isDashboardEditMode={layoutEditMode}
- result={runResult?.result}
- error={getDashboardWidgetFetchDisplayError(
- runResult?.error ?? refreshState?.error
- )}
- loading={!!refreshState?.loading}
- lastFetchedAt={refreshState?.fetchedAt}
- onRefresh={tileActions.refreshWidget}
- onRefreshWidgetData={scheduleRefreshDashboardWidgets}
- onApplyWidgetIssueMetadataChange={onWidgetIssueMetadataChange}
- onUpdateWidgetTile={tileActions.updateWidget}
- onConfigPublished={onWidgetConfigPublished}
- toggleShowDescription={tileActions.toggleDescription}
- onDuplicate={tileActions.duplicate}
- onRemove={commonTileProps.removeFromDashboard}
- onMoveToDashboard={commonTileProps.moveToDashboard}
- onCopyToDashboard={commonTileProps.copyToDashboard}
- showResizeHandles={commonTileProps.showResizeHandles}
- showEditingControls={commonTileProps.showEditingControls}
- canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
- onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
- onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- >
- {decorations}
- </MemoizedDashboardWidgetItem>
- )
- }
- })}
+ {tiles?.map(renderTile)}
</ReactGridLayout>
</div>
)}
diff --git a/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap b/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
index 334a99f63a71..82a9f7ae4d56 100644
--- a/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
+++ b/frontend/src/scenes/dashboard/__snapshots__/DashboardItems.test.tsx.snap
@@ -19,6 +19,7 @@ exports[`DashboardItems matches snapshot in edit mode with layout zoom enabled 1
data-margin="14.4,14.4"
data-resize-enabled="false"
data-row-height="60"
+ data-style-width="1200"
>
<div
data-attr="insight-card"
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 7285555da00c..890223acb284 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -4,6 +4,7 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
import posthog from 'posthog-js'
+import type { Layout } from 'react-grid-layout'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import * as dashboardWidgetUtils from '@posthog/products-dashboards/frontend/utils'
@@ -47,7 +48,8 @@ import {
InsightModel,
} from '~/types'
-import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+import { DashboardGridCompaction, getDashboardGridCompactor } from 'products/dashboards/frontend/dashboardCustomization'
+import { dashboardTileGroupChoicesLogic } from 'products/dashboards/frontend/dashboardTileGroupChoicesLogic'
import { dashboardResult, insightOnDashboard, tileFromInsight } from './dashboardLogic.testHelpers'
@@ -382,6 +384,126 @@ describe('dashboardLogic', () => {
})
})
+ describe('tile group sections', () => {
+ let target: InsightShortId
+
+ // The band of group 'target' holds tiles 0 and 2, so on the dashboard tile 1 sits in a gap between them.
+ const groupTiles = (groups: Record<string, { collapsed: boolean }>, viewerChoice?: boolean): void => {
+ dashboards[5] = {
+ ...dashboards[5],
+ customization: { groups },
+ tiles: dashboards[5].tiles.map((tile, index) => ({
+ ...tile,
+ group_key: index === 1 ? 'other' : 'target',
+ layouts: { sm: { x: 0, y: index * 2, w: 12, h: 2 } } as DashboardTile['layouts'],
+ })),
+ }
+ target = dashboards[5].tiles[0].insight!.short_id
+ if (viewerChoice !== undefined) {
+ dashboardTileGroupChoicesLogic.mount()
+ dashboardTileGroupChoicesLogic.actions.setTileGroupCollapsed(5, 'target', viewerChoice)
+ }
+ }
+
+ const mountDashboard = async (placement?: DashboardPlacement): Promise<void> => {
+ logic = dashboardLogic({ id: 5, placement })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ const highlight = async (insightId: string): Promise<void> => {
+ await expectLogic(logic, () => {
+ router.actions.push('/dashboard/5', { highlightInsightId: insightId })
+ }).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DASHBOARD_TILE_GROUP_SECTIONS], {
+ [FEATURE_FLAGS.DASHBOARD_TILE_GROUP_SECTIONS]: true,
+ })
+ useMocks({ get: { '/api/environments/:team_id/dashboards/5/': () => [200, dashboards[5]] } })
+ })
+
+ afterEach(() => {
+ localStorage.clear()
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ })
+
+ it.each([
+ { name: 'a link opened before the dashboard loads', beforeLoad: true, viewerChoice: undefined },
+ { name: 'a link followed on a loaded dashboard', beforeLoad: false, viewerChoice: undefined },
+ { name: 'a group the viewer closed', beforeLoad: false, viewerChoice: true },
+ ])('opens the highlighted tile group for $name', async ({ beforeLoad, viewerChoice }) => {
+ groupTiles({ target: { collapsed: true }, other: { collapsed: true } }, viewerChoice)
+ if (beforeLoad) {
+ router.actions.push('/dashboard/5', { highlightInsightId: target })
+ }
+ await mountDashboard()
+ if (!beforeLoad) {
+ await highlight(target)
+ }
+
+ expect(logic.values.collapsedTileGroupKeys).toEqual(['other'])
+ })
+
+ it("opens a highlighted tile group without saving it as the viewer's choice", async () => {
+ groupTiles({ target: { collapsed: true } })
+ await mountDashboard()
+ await highlight(target)
+
+ expect(logic.values.collapsedTileGroupKeys).toEqual([])
+ expect(dashboardTileGroupChoicesLogic.values.tileGroupChoices).toEqual({})
+ })
+
+ it('closes a highlighted tile group on toggle and opens it again for a new highlight', async () => {
+ groupTiles({ target: { collapsed: true } })
+ await mountDashboard()
+ await highlight(target)
+
+ logic.actions.toggleTileGroup('target')
+ await highlight(target)
+ expect(logic.values.collapsedTileGroupKeys).toEqual(['target'])
+
+ await highlight('missing-insight')
+ await highlight(target)
+ expect(logic.values.collapsedTileGroupKeys).toEqual([])
+ })
+
+ it.each([
+ { placement: DashboardPlacement.Dashboard, expected: ['target'] },
+ { placement: DashboardPlacement.Export, expected: [] },
+ ])('closes saved tile groups on the $placement placement', async ({ placement, expected }) => {
+ groupTiles({ target: { collapsed: true } })
+ await mountDashboard(placement)
+
+ expect(logic.values.collapsedTileGroupKeys).toEqual(expected)
+ })
+
+ it('does not change the layout when a band grid reports the layout it was given', async () => {
+ groupTiles({})
+ await mountDashboard()
+ const compactor = getDashboardGridCompactor(DashboardGridCompaction.Vertical)
+
+ for (const sectionLayouts of logic.values.tileGroupSectionLayouts) {
+ logic.actions.updateTileGroupSectionLayout({ sm: compactor.compact(sectionLayouts.sm ?? [], 12) })
+ }
+
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(false)
+ })
+
+ it('keeps the changes of two bands that report in the same tick', async () => {
+ groupTiles({})
+ await mountDashboard()
+ const [targetBand, otherBand] = logic.values.tileGroupSectionLayouts.map((layouts) => layouts.sm ?? [])
+ const narrow = (layout: Layout): Layout => layout.map((item) => ({ ...item, w: 6 }))
+
+ logic.actions.updateTileGroupSectionLayout({ sm: narrow(targetBand) })
+ logic.actions.updateTileGroupSectionLayout({ sm: narrow(otherBand) })
+
+ expect(logic.values.layouts.sm?.map((item) => item.w)).toEqual([6, 6, 6])
+ })
+ })
+
describe('tile layouts', () => {
beforeEach(() => {
logic = dashboardLogic({ id: 5 })
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 29680787badd..77b63b8f4ce0 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -120,7 +120,7 @@ import {
TileLayout,
} from '~/types'
-import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+import { DashboardGridCompaction, getDashboardGridCompactor } from 'products/dashboards/frontend/dashboardCustomization'
import {
dashboardFiltersEqual,
dashboardVariableValuesEqual,
@@ -129,6 +129,18 @@ import {
type DashboardSettingsChange,
type DashboardFilterChange,
} from 'products/dashboards/frontend/dashboardSettings/dashboardChanges'
+import {
+ type TileGroupChoices,
+ dashboardTileGroupChoicesLogic,
+} from 'products/dashboards/frontend/dashboardTileGroupChoicesLogic'
+import {
+ type DashboardSection,
+ type SectionLayouts,
+ getCollapsedTileGroupKeys,
+ getDashboardSections,
+ getLayoutAfterSectionChange,
+ getSectionLayouts,
+} from 'products/dashboards/frontend/dashboardTileSections'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { Node } from '../../queries/schema/schema-general'
@@ -164,6 +176,7 @@ import {
getInsightQueryError,
getInsightWithRetry,
isRefreshRejectionStub,
+ isWidgetTileVisibleOnPlacement,
layoutsByTile,
parseURLFilters,
parseURLVariables,
@@ -220,6 +233,11 @@ export interface DashboardLogicProps {
readOnly?: boolean
}
+interface RevealedTileGroup {
+ insightId: string
+ groupKey: string | null
+}
+
interface PendingFilterChange {
id: string
startTime: number
@@ -342,6 +360,7 @@ function mergeUpdatedWidgetTileIntoDashboard(dashboard: DashboardType, updatedTi
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardLogicValues {
internetConnectionIssue: boolean // apiStatusLogic
+ tileGroupChoices: TileGroupChoices // dashboardTileGroupChoicesLogic
retentionMonths: number | null // dataRetentionBannerLogic
retentionPeriodLabel: string | null // dataRetentionBannerLogic
warningEligible: boolean // dataRetentionBannerLogic
@@ -378,6 +397,7 @@ export interface dashboardLogicValues {
canSaveProjectDashboardTemplate: boolean
cancellingPreview: boolean
changedFilterCount: number
+ collapsedTileGroupKeys: string[]
columns: number | null
containerWidth: number | null
currentDashboardSettings: DashboardSettings
@@ -461,6 +481,7 @@ export interface dashboardLogicValues {
}
refreshStatus: Record<string, RefreshStatus>
refreshTilesTotal: number | null
+ revealedTileGroup: RevealedTileGroup | null
savedDashboardSettings: DashboardSettings
scrollToBottomSignal: number
settingsForRefresh: DashboardSettings
@@ -483,6 +504,9 @@ export interface dashboardLogicValues {
terraformModalOpen: boolean
textTileId: DashboardTileIdOrNew
textTiles: DashboardTile[]
+ tileGroupSectionLayouts: SectionLayouts[]
+ tileGroupSections: DashboardSection[]
+ tileGroupSectionsEnabled: boolean
tiles: DashboardTile[]
urlFilters: DashboardFilter
urlSearchParamsAtEditModeEntry: {
@@ -856,6 +880,9 @@ export interface dashboardLogicActions {
retryDashboardLoad: () => {
value: true
}
+ revealHighlightedInsight: () => {
+ value: true
+ }
saveDashboardChanges: () => {
value: true
}
@@ -1041,6 +1068,9 @@ export interface dashboardLogicActions {
setRefreshTilesTotal: (total: number) => {
total: number
}
+ setRevealedTileGroup: (revealedTileGroup: RevealedTileGroup | null) => {
+ revealedTileGroup: RevealedTileGroup | null
+ }
setShouldReportOnAPILoad: (shouldReport: boolean) => {
shouldReport: boolean
}
@@ -1107,6 +1137,9 @@ export interface dashboardLogicActions {
toggleTileDescription: (tileId: number) => {
tileId: number
}
+ toggleTileGroup: (groupKey: string) => {
+ groupKey: string
+ }
triggerDashboardRefresh: () => {
value: true
}
@@ -1136,6 +1169,9 @@ export interface dashboardLogicActions {
color: InsightColor | null
tileId: number
}
+ updateTileGroupSectionLayout: (layouts: ResponsiveLayouts) => {
+ layouts: Partial<Record<string, Layout>>
+ }
updateWidgetTile: ({
tile,
config,
@@ -1322,6 +1358,15 @@ export interface dashboardLogicMeta {
currentLayoutSize: (containerWidth: number | null) => 'sm' | 'xs'
tiles: (dashboard: DashboardType | null) => DashboardTile[]
widgetTiles: (tiles: DashboardTile[]) => DashboardTile[]
+ tileGroupSectionsEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ collapsedTileGroupKeys: (
+ tileGroupSectionsEnabled: boolean,
+ placement: DashboardPlacement,
+ tiles: DashboardTile[],
+ dashboard: DashboardType | null,
+ tileGroupChoices: TileGroupChoices,
+ revealedTileGroup: RevealedTileGroup | null
+ ) => string[]
insightTiles: (tiles: DashboardTile[]) => DashboardTile[]
textTiles: (tiles: DashboardTile[]) => DashboardTile[]
dashboardControlScopes: (insightTiles: DashboardTile[]) => Record<DashboardControl, DashboardControlScope>
@@ -1382,6 +1427,18 @@ export interface dashboardLogicMeta {
sizeKey: DashboardLayoutSize | undefined
) => Layout | undefined
layoutForItem: (layout: Layout | undefined) => Record<string, TileLayout>
+ tileGroupSections: (
+ tileGroupSectionsEnabled: boolean,
+ tiles: DashboardTile[],
+ layouts: Partial<Record<string, Layout>>,
+ dashboard: DashboardType | null,
+ placement: DashboardPlacement
+ ) => DashboardSection[]
+ tileGroupSectionLayouts: (
+ tileGroupSections: DashboardSection[],
+ layouts: Partial<Record<string, Layout>>,
+ dashboard: DashboardType | null
+ ) => SectionLayouts[]
refreshMetrics: (
refreshStatus: Record<string, RefreshStatus>,
refreshTilesTotal: number | null
@@ -1465,6 +1522,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
['warningEligible', 'retentionMonths', 'retentionPeriodLabel'],
apiStatusLogic,
['internetConnectionIssue'],
+ dashboardTileGroupChoicesLogic,
+ ['tileGroupChoices'],
],
logic: [dashboardsModel, insightsModel, eventUsageLogic, addInsightToDashboardLogic],
})),
@@ -1479,6 +1538,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
}),
actions(() => ({
+ revealHighlightedInsight: true,
/**
* Dashboard loading and dashboard tile refreshes.
*/
@@ -1522,6 +1582,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
previewUnsavedFilters?: boolean
}) => payload,
refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean }) => payload,
+ toggleTileGroup: (groupKey: string) => ({ groupKey }),
+ setRevealedTileGroup: (revealedTileGroup: RevealedTileGroup | null) => ({ revealedTileGroup }),
+ /** A band grid reports its own layout, which joins the other bands into one dashboard layout. */
+ updateTileGroupSectionLayout: (layouts: ResponsiveLayouts) => ({ layouts }),
/** Debounced run_widgets refresh for a single tile (tile filters). */
scheduleRefreshDashboardWidgets: (tileId: number) => ({ tileId }),
applyWidgetIssueMetadataChange: (payload: {
@@ -2289,6 +2353,20 @@ export const dashboardLogic = kea<dashboardLogicType>([
restoreTemporaryColorState: (_, { themeId }) => themeId,
},
],
+ // A highlight link opens the group of its tile for this visit only, so it never changes the viewer's choice.
+ revealedTileGroup: [
+ null as RevealedTileGroup | null,
+ {
+ setRevealedTileGroup: (_, { revealedTileGroup }) => revealedTileGroup,
+ [dashboardTileGroupChoicesLogic.actionTypes.setTileGroupCollapsed]: (
+ state,
+ { dashboardId, groupKey }
+ ) =>
+ state && dashboardId === props.id && groupKey === state.groupKey
+ ? { ...state, groupKey: null }
+ : state,
+ },
+ ],
layoutZoom: [
1,
{
@@ -3257,6 +3335,36 @@ export const dashboardLogic = kea<dashboardLogicType>([
(dashboard: DashboardType | null) => dashboard?.tiles?.filter((t) => !t.deleted) || [],
],
widgetTiles: [(s) => [s.tiles], (tiles: DashboardTile[]) => tiles.filter((t) => !!t.widget)],
+ tileGroupSectionsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.DASHBOARD_TILE_GROUP_SECTIONS],
+ ],
+ collapsedTileGroupKeys: [
+ (s) => [
+ s.tileGroupSectionsEnabled,
+ s.placement,
+ s.tiles,
+ s.dashboard,
+ s.tileGroupChoices,
+ s.revealedTileGroup,
+ ],
+ (
+ tileGroupSectionsEnabled: boolean,
+ placement: DashboardPlacement,
+ tiles: DashboardTile[],
+ dashboard: DashboardType | null,
+ tileGroupChoices: TileGroupChoices,
+ revealedTileGroup: RevealedTileGroup | null
+ ): string[] =>
+ // Exported images and subscription emails show every tile.
+ tileGroupSectionsEnabled && dashboard && placement !== DashboardPlacement.Export
+ ? getCollapsedTileGroupKeys({
+ tiles,
+ groups: dashboard.customization?.groups,
+ choices: tileGroupChoices[dashboard.id],
+ }).filter((groupKey) => groupKey !== revealedTileGroup?.groupKey)
+ : [],
+ ],
insightTiles: [
(s) => [s.tiles],
(tiles: DashboardTile[]) => tiles.filter((t) => !!t.insight).filter((i) => !i.insight?.deleted),
@@ -3463,6 +3571,39 @@ export const dashboardLogic = kea<dashboardLogicType>([
return layoutForItem
},
],
+ /** Full-width bands, one per tile group, or none when the dashboard shows one grid. */
+ tileGroupSections: [
+ (s) => [s.tileGroupSectionsEnabled, s.tiles, s.layouts, s.dashboard, s.placement],
+ (
+ tileGroupSectionsEnabled: boolean,
+ tiles: DashboardTile[],
+ layouts: ResponsiveLayouts,
+ dashboard: DashboardType | null,
+ placement: DashboardPlacement
+ ): DashboardSection[] => {
+ if (!tileGroupSectionsEnabled || !tiles.some((tile) => tile.group_key)) {
+ return []
+ }
+ const widgetTilesShown = isWidgetTileVisibleOnPlacement(placement)
+ return getDashboardSections({
+ tiles: tiles.filter((tile) => !tile.widget || widgetTilesShown),
+ layout: layouts.sm,
+ groups: dashboard?.customization?.groups,
+ })
+ },
+ ],
+ tileGroupSectionLayouts: [
+ (s) => [s.tileGroupSections, s.layouts, s.dashboard],
+ (
+ tileGroupSections: DashboardSection[],
+ layouts: ResponsiveLayouts,
+ dashboard: DashboardType | null
+ ): SectionLayouts[] => {
+ const compactor = getDashboardGridCompactor(dashboard?.customization?.layout_compaction)
+ return tileGroupSections.map((section) => getSectionLayouts(layouts, section.tiles, compactor))
+ },
+ { resultEqualityCheck: objectsEqual },
+ ],
refreshMetrics: [
(s) => [s.refreshStatus, s.refreshTilesTotal],
(refreshStatus: Record<string, RefreshStatus>, refreshTilesTotal: number | null) => {
@@ -3764,6 +3905,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
},
handleDashboardLoadComplete: () => {
+ actions.revealHighlightedInsight()
// Shared logic for refreshing dashboard items after load (used by both regular and streaming loads)
if (values.placement !== DashboardPlacement.Export) {
const loadAction = values.dashboardLoadData.action!
@@ -3777,6 +3919,25 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
})),
listeners(({ actions, values, cache, props, sharedListeners }) => ({
+ revealHighlightedInsight: () => {
+ const insightId = values.highlightedInsightId
+ const groupKey = values.tiles.find((tile) => insightId && tile.insight?.short_id === insightId)?.group_key
+ if (!groupKey) {
+ actions.setRevealedTileGroup(null)
+ } else if (insightId !== values.revealedTileGroup?.insightId) {
+ // Once per link, so a later URL change does not reopen a group the viewer closed.
+ actions.setRevealedTileGroup({ insightId, groupKey })
+ }
+ },
+ updateTileGroupSectionLayout: ({ layouts }) => {
+ const dashboardLayout = getLayoutAfterSectionChange(
+ values.tileGroupSectionLayouts.map((sectionLayouts) => sectionLayouts.sm ?? []),
+ layouts.sm ?? []
+ )
+ if (dashboardLayout) {
+ actions.stageLayouts({ sm: dashboardLayout })
+ }
+ },
[dashboardsModel.actionTypes.updateDashboardSuccess]: ({
dashboard,
payload,
@@ -4733,6 +4894,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
}
},
+ toggleTileGroup: ({ groupKey }) => {
+ const collapse = !values.collapsedTileGroupKeys.includes(groupKey)
+ posthog.capture('dashboard tile group toggled', {
+ dashboard_id: props.id,
+ collapsed: collapse,
+ tile_count: values.tiles.filter((tile) => tile.group_key === groupKey).length,
+ })
+ dashboardTileGroupChoicesLogic.actions.setTileGroupCollapsed(props.id, groupKey, collapse)
+ },
refreshDashboardWidgets: async ({ tileIds, forceRefresh }, breakpoint) => {
if (values.placement === DashboardPlacement.Export || values.placement === DashboardPlacement.Public) {
return
@@ -5721,6 +5891,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
'/dashboard/:id': (_params, searchParams, _hashParams, { method }) => {
+ actions.revealHighlightedInsight()
actions.setSubscriptionMode(false, undefined)
actions.setTextTileId(null)
actions.setButtonTileId(null)
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx
new file mode 100644
index 000000000000..9a0116e2ff06
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.stories.tsx
@@ -0,0 +1,56 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { DashboardTileGroupApi } from '../../generated/api.schemas'
+import { DashboardTileGroup } from './DashboardTileGroup'
+
+const meta: Meta<typeof DashboardTileGroup> = {
+ title: 'Products/Dashboards/Tiles/Tile group',
+ component: DashboardTileGroup,
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+const STYLES: { group: DashboardTileGroupApi; collapsed: boolean }[] = [
+ { group: { title: 'Activation' }, collapsed: false },
+ { group: { title: 'Revenue', color: 'purple' }, collapsed: false },
+ { group: { title: 'Retention', color: 'green' }, collapsed: false },
+ { group: { title: 'Collapsed', color: 'orange' }, collapsed: true },
+ { group: {}, collapsed: true },
+]
+
+function FakeTile(): JSX.Element {
+ return <div className="h-20 rounded border bg-surface-primary" />
+}
+
+export const LongTitleInNarrowScene: StoryObj = {
+ render: () => (
+ <div className="w-[360px] bg-primary p-4">
+ <DashboardTileGroup
+ group={{
+ title: 'Weekly activation and retention for self-serve signups across every marketing channel',
+ color: 'blue',
+ }}
+ tileCount={12}
+ collapsed
+ onToggle={() => {}}
+ >
+ <FakeTile />
+ </DashboardTileGroup>
+ </div>
+ ),
+}
+
+export const Styles: StoryObj = {
+ render: () => (
+ <div className="flex flex-col gap-4 bg-primary p-4">
+ {STYLES.map(({ group, collapsed }, index) => (
+ <DashboardTileGroup key={index} group={group} tileCount={2} collapsed={collapsed} onToggle={() => {}}>
+ <div className="grid grid-cols-2 gap-2">
+ <FakeTile />
+ <FakeTile />
+ </div>
+ </DashboardTileGroup>
+ ))}
+ </div>
+ ),
+}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx
new file mode 100644
index 000000000000..f30f4061a0ae
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx
@@ -0,0 +1,71 @@
+import clsx from 'clsx'
+
+import { IconChevronRight } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { pluralize } from 'lib/utils/strings'
+
+import type { DashboardTileGroupApi, DashboardTileGroupColorEnumApi } from '../../generated/api.schemas'
+
+const DOT_CLASS_NAMES: Record<DashboardTileGroupColorEnumApi, string> = {
+ blue: 'bg-[var(--blue)]',
+ purple: 'bg-[var(--purple)]',
+ green: 'bg-[var(--green)]',
+ yellow: 'bg-[var(--warning)]',
+ orange: 'bg-[var(--color-orange-500)]',
+ red: 'bg-[var(--danger)]',
+}
+
+interface DashboardTileGroupProps {
+ group: DashboardTileGroupApi
+ tileCount: number
+ collapsed: boolean
+ onToggle: () => void
+ children: React.ReactNode
+}
+
+export function DashboardTileGroup({
+ group,
+ tileCount,
+ collapsed,
+ onToggle,
+ children,
+}: DashboardTileGroupProps): JSX.Element {
+ const tileCountLabel = pluralize(tileCount, 'tile')
+
+ return (
+ <section className="DashboardTileGroup" data-attr="dashboard-tile-group">
+ <div className="flex min-w-0 items-center gap-2 pb-2">
+ <LemonButton
+ size="small"
+ truncate
+ // A tertiary button styles aria-expanded as an open menu, which reads as a highlight here.
+ className="[&[aria-expanded=true]:not(:hover)]:!bg-transparent"
+ tooltip={group.title || undefined}
+ icon={
+ <IconChevronRight
+ className={clsx(
+ 'transition-transform motion-reduce:transition-none',
+ !collapsed && 'rotate-90'
+ )}
+ />
+ }
+ onClick={onToggle}
+ aria-expanded={!collapsed}
+ data-attr="dashboard-tile-group-toggle"
+ >
+ {group.color && (
+ <span
+ aria-hidden
+ className={clsx('mr-2 inline-block size-2 rounded-full', DOT_CLASS_NAMES[group.color])}
+ />
+ )}
+ <span className="font-semibold">{group.title || tileCountLabel}</span>
+ </LemonButton>
+ {group.title && collapsed && <span className="shrink-0 text-secondary text-xs">{tileCountLabel}</span>}
+ <div className="min-w-4 flex-1 border-t border-primary" />
+ </div>
+ {!collapsed && children}
+ </section>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardTileGroupChoicesLogic.test.ts b/products/dashboards/frontend/dashboardTileGroupChoicesLogic.test.ts
new file mode 100644
index 000000000000..7f119cb3b9b2
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileGroupChoicesLogic.test.ts
@@ -0,0 +1,29 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { initKeaTests } from '~/test/init'
+import type { AppContext } from '~/types'
+
+import { dashboardTileGroupChoicesLogic } from './dashboardTileGroupChoicesLogic'
+
+describe('dashboardTileGroupChoicesLogic', () => {
+ const mountAs = (uuid: string): typeof dashboardTileGroupChoicesLogic => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ current_user: { ...MOCK_DEFAULT_USER, uuid },
+ } as AppContext
+ initKeaTests(false)
+ dashboardTileGroupChoicesLogic.mount()
+ return dashboardTileGroupChoicesLogic
+ }
+
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ it('keeps the choices of each viewer apart in a shared browser', () => {
+ mountAs('viewer-a').actions.setTileGroupCollapsed(1, 'plans', true)
+
+ expect(mountAs('viewer-b').values.tileGroupChoices).toEqual({})
+ expect(mountAs('viewer-a').values.tileGroupChoices).toEqual({ 1: { plans: true } })
+ })
+})
diff --git a/products/dashboards/frontend/dashboardTileGroupChoicesLogic.ts b/products/dashboards/frontend/dashboardTileGroupChoicesLogic.ts
new file mode 100644
index 000000000000..441be52da4fc
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileGroupChoicesLogic.ts
@@ -0,0 +1,55 @@
+import { MakeLogicType, actions, kea, path, reducers } from 'kea'
+
+import { getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
+
+/** Whether each group is collapsed, keyed by dashboard id and then by group key. */
+export type TileGroupChoices = Record<string, Record<string, boolean>>
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dashboardTileGroupChoicesLogicValues {
+ tileGroupChoices: TileGroupChoices
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dashboardTileGroupChoicesLogicActions {
+ setTileGroupCollapsed: (
+ dashboardId: number,
+ groupKey: string,
+ collapsed: boolean
+ ) => {
+ collapsed: boolean
+ dashboardId: number
+ groupKey: string
+ }
+}
+
+export type dashboardTileGroupChoicesLogicType = MakeLogicType<
+ dashboardTileGroupChoicesLogicValues,
+ dashboardTileGroupChoicesLogicActions
+>
+
+// One persisted map for every dashboard in this browser, so a viewer's open or closed groups outlive the page.
+export const dashboardTileGroupChoicesLogic = kea<dashboardTileGroupChoicesLogicType>([
+ path(['products', 'dashboards', 'frontend', 'dashboardTileGroupChoicesLogic']),
+ actions({
+ setTileGroupCollapsed: (dashboardId: number, groupKey: string, collapsed: boolean) => ({
+ dashboardId,
+ groupKey,
+ collapsed,
+ }),
+ }),
+ reducers(() => ({
+ tileGroupChoices: [
+ {} as TileGroupChoices,
+ // Keyed by user, so a person who signs in after another one in this browser does not get their choices.
+ // Not keyed by project, because dashboard ids are unique across projects and shared dashboards can have no project.
+ { persist: true, prefix: `${getCurrentUserIdOrNone() ?? 'anonymous'}__` },
+ {
+ setTileGroupCollapsed: (state, { dashboardId, groupKey, collapsed }) => ({
+ ...state,
+ [dashboardId]: { ...state[dashboardId], [groupKey]: collapsed },
+ }),
+ },
+ ],
+ })),
+])
diff --git a/products/dashboards/frontend/dashboardTileSections.test.ts b/products/dashboards/frontend/dashboardTileSections.test.ts
new file mode 100644
index 000000000000..d84c8d6b0345
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileSections.test.ts
@@ -0,0 +1,202 @@
+import type { Layout } from 'react-grid-layout'
+
+import type { DashboardTile } from '~/types'
+
+import { DashboardGridCompaction, getDashboardGridCompactor } from './dashboardCustomization'
+import {
+ getCollapsedTileGroupKeys,
+ getDashboardSections,
+ getLayoutAfterSectionChange,
+ getSectionLayouts,
+ hasSectionLayoutChanged,
+ stackSectionLayouts,
+} from './dashboardTileSections'
+import type { DashboardTileGroupApi } from './generated/api.schemas'
+
+const tile = (id: number, group_key: string | null = null): DashboardTile =>
+ ({ id, group_key, layouts: {}, color: null }) as DashboardTile
+
+const box = (id: number, x: number, y: number, w = 6, h = 2): Layout[number] => ({ i: String(id), x, y, w, h })
+
+const sectionSummary = (
+ tiles: DashboardTile[],
+ layout: Layout | undefined,
+ groups?: Record<string, DashboardTileGroupApi>
+): string[] =>
+ getDashboardSections({ tiles, layout, groups }).map((section) =>
+ section.kind === 'group'
+ ? `${section.groupKey}(${section.group.title ?? ''}): ${section.tiles.map((t) => t.id).join(',')}`
+ : `tiles: ${section.tiles.map((t) => t.id).join(',')}`
+ )
+
+interface SectionsCase {
+ name: string
+ tiles: DashboardTile[]
+ layout: Layout
+ groups?: Record<string, DashboardTileGroupApi>
+ expected: string[]
+}
+
+interface CollapsedCase {
+ name: string
+ tiles: DashboardTile[]
+ groups: Record<string, DashboardTileGroupApi> | undefined
+ choices: Record<string, boolean> | undefined
+ expected: string[]
+}
+
+describe('dashboardTileSections', () => {
+ it.each<SectionsCase>([
+ {
+ name: 'returns no sections for no tiles',
+ tiles: [],
+ layout: [],
+ expected: [],
+ },
+ {
+ name: 'keeps a dashboard without groups as one section in layout order',
+ tiles: [tile(1), tile(2), tile(3)],
+ layout: [box(1, 6, 2), box(2, 0, 0), box(3, 0, 2)],
+ expected: ['tiles: 2,3,1'],
+ },
+ {
+ name: 'puts each group where its top-left tile is and splits ungrouped tiles around it',
+ tiles: [tile(1), tile(2, 'plans'), tile(3, 'plans'), tile(4)],
+ layout: [box(1, 0, 0), box(2, 0, 2), box(3, 6, 4), box(4, 0, 6)],
+ groups: { plans: { title: 'Pricing plans' } },
+ expected: ['tiles: 1', 'plans(Pricing plans): 2,3', 'tiles: 4'],
+ },
+ {
+ name: 'moves an ungrouped tile that sits beside a group to after the group',
+ tiles: [tile(1, 'plans'), tile(2), tile(3, 'plans')],
+ layout: [box(1, 0, 0), box(2, 6, 0), box(3, 0, 2)],
+ expected: ['plans(): 1,3', 'tiles: 2'],
+ },
+ {
+ name: 'keeps two groups apart even when their tiles share rows',
+ tiles: [tile(1, 'plans'), tile(2, 'regions'), tile(3, 'plans'), tile(4, 'regions')],
+ layout: [box(1, 0, 0), box(2, 6, 0), box(3, 0, 2), box(4, 6, 2)],
+ expected: ['plans(): 1,3', 'regions(): 2,4'],
+ },
+ {
+ name: 'puts tiles without a layout last',
+ tiles: [tile(1), tile(2, 'plans'), tile(3)],
+ layout: [box(2, 0, 0)],
+ expected: ['plans(): 2', 'tiles: 1,3'],
+ },
+ {
+ name: 'gives a group without settings no title',
+ tiles: [tile(1, 'plans')],
+ layout: [box(1, 0, 0)],
+ groups: { regions: { title: 'Regions' } },
+ expected: ['plans(): 1'],
+ },
+ {
+ name: 'does not read settings for an inherited object key',
+ tiles: [tile(1, '__proto__')],
+ layout: [box(1, 0, 0)],
+ groups: { plans: { title: 'Pricing plans' } },
+ expected: ['__proto__(): 1'],
+ },
+ ])('getDashboardSections $name', ({ tiles, layout, groups, expected }) => {
+ expect(sectionSummary(tiles, layout, groups)).toEqual(expected)
+ })
+
+ it('keeps section keys when tiles reorder inside their bands', () => {
+ const tiles = [tile(1), tile(2), tile(3, 'plans'), tile(4), tile(5)]
+ const sectionKeys = (layout: Layout): string[] =>
+ getDashboardSections({ tiles, layout, groups: undefined }).map((section) => section.key)
+
+ expect(sectionKeys([box(1, 0, 0), box(2, 6, 0), box(3, 0, 2), box(4, 0, 4), box(5, 6, 4)])).toEqual(
+ sectionKeys([box(2, 0, 0), box(1, 6, 0), box(3, 0, 2), box(5, 0, 4), box(4, 6, 4)])
+ )
+ })
+
+ it.each([
+ {
+ name: 'keeps only the section tiles and closes the gaps that other bands leave',
+ compaction: DashboardGridCompaction.Vertical,
+ layouts: { sm: [box(1, 0, 0), box(2, 0, 4), box(3, 6, 6)], xs: [box(2, 0, 9, 1)] },
+ expected: { sm: [box(2, 0, 0), box(3, 6, 0)], xs: [box(2, 0, 0, 1)] },
+ },
+ {
+ name: 'keeps free-form placement and moves the section to the top',
+ compaction: DashboardGridCompaction.Stable,
+ layouts: { sm: [box(1, 0, 0), box(2, 0, 4), box(3, 6, 6)] },
+ expected: { sm: [box(2, 0, 0), box(3, 6, 2)] },
+ },
+ {
+ name: 'closes the single column gaps left by tiles of other bands',
+ compaction: DashboardGridCompaction.Stable,
+ layouts: { xs: [box(3, 0, 10, 1, 5), box(1, 0, 5, 1, 5), box(2, 0, 0, 1, 5)] },
+ expected: { xs: [box(2, 0, 0, 1, 5), box(3, 0, 5, 1, 5)] },
+ },
+ ])('getSectionLayouts $name', ({ compaction, layouts, expected }) => {
+ const sectionLayouts = getSectionLayouts(layouts, [tile(2), tile(3)], getDashboardGridCompactor(compaction))
+ expect(sectionLayouts).toMatchObject(expected)
+ })
+
+ it('stackSectionLayouts stacks sections one under the other, each from its own top', () => {
+ expect(stackSectionLayouts([[box(1, 0, 3, 6, 2), box(2, 6, 3, 6, 4)], [], [box(3, 0, 10, 12, 1)]])).toEqual([
+ box(1, 0, 0, 6, 2),
+ box(2, 6, 0, 6, 4),
+ box(3, 0, 4, 12, 1),
+ ])
+ })
+
+ it.each([
+ { name: 'the same tiles in another order', after: [box(2, 6, 0), box(1, 0, 0)], expected: false },
+ { name: 'a tile moved sideways', after: [box(1, 6, 0), box(2, 0, 0)], expected: true },
+ { name: 'a tile moved down', after: [box(1, 0, 2), box(2, 6, 0)], expected: true },
+ { name: 'a tile resized', after: [box(1, 0, 0, 4), box(2, 6, 0)], expected: true },
+ { name: 'a tile added', after: [box(1, 0, 0), box(2, 6, 0), box(3, 0, 2)], expected: true },
+ ])('hasSectionLayoutChanged is $expected for $name', ({ after, expected }) => {
+ expect(hasSectionLayoutChanged([box(1, 0, 0), box(2, 6, 0)], after)).toBe(expected)
+ })
+
+ it.each([
+ {
+ name: 'nothing when the band reports its tiles in another order',
+ reported: [box(2, 6, 0), box(1, 0, 0)],
+ expected: null,
+ },
+ {
+ name: 'nothing when no band holds the reported tiles',
+ reported: [box(9, 0, 0)],
+ expected: null,
+ },
+ {
+ name: 'the moved band with the bands below it stacked under it',
+ reported: [box(1, 0, 0), box(2, 0, 2)],
+ expected: [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4, 12)],
+ },
+ {
+ name: 'a later band moved with the bands above it kept',
+ reported: [box(3, 0, 0, 4)],
+ expected: [box(1, 0, 0), box(2, 6, 0), box(3, 0, 2, 4)],
+ },
+ ])('getLayoutAfterSectionChange gives $name', ({ reported, expected }) => {
+ const sectionLayouts = [[box(1, 0, 0), box(2, 6, 0)], [box(3, 0, 0, 12)]]
+ expect(getLayoutAfterSectionChange(sectionLayouts, reported)).toEqual(expected)
+ })
+
+ it.each<CollapsedCase>([
+ { name: 'nothing without groups', tiles: [tile(1)], groups: undefined, choices: undefined, expected: [] },
+ {
+ name: 'groups saved as collapsed',
+ tiles: [tile(1, 'plans'), tile(2, 'regions'), tile(3, 'plans')],
+ groups: { plans: { collapsed: true }, regions: { collapsed: false } },
+ choices: undefined,
+ expected: ['plans'],
+ },
+ {
+ name: "the viewer's choice over the saved default",
+ tiles: [tile(1, 'plans'), tile(2, 'regions')],
+ groups: { plans: { collapsed: true } },
+ choices: { plans: false, regions: true },
+ expected: ['regions'],
+ },
+ ])('getCollapsedTileGroupKeys finds $name', ({ tiles, groups, choices, expected }) => {
+ expect(getCollapsedTileGroupKeys({ tiles, groups, choices })).toEqual(expected)
+ })
+})
diff --git a/products/dashboards/frontend/dashboardTileSections.ts b/products/dashboards/frontend/dashboardTileSections.ts
new file mode 100644
index 000000000000..026aa46a271b
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileSections.ts
@@ -0,0 +1,166 @@
+import type { Compactor, Layout } from 'react-grid-layout'
+
+import { objectsEqual } from 'lib/utils/objects'
+import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
+
+import type { DashboardLayoutSize, DashboardTile } from '~/types'
+
+import type { DashboardTileGroupApi } from './generated/api.schemas'
+
+export type DashboardSection =
+ | { kind: 'tiles'; key: string; tiles: DashboardTile[] }
+ | { kind: 'group'; key: string; groupKey: string; group: DashboardTileGroupApi; tiles: DashboardTile[] }
+
+export type SectionLayouts = Partial<Record<DashboardLayoutSize, Layout>>
+
+function tilesInLayoutOrder(tiles: DashboardTile[], layout: Layout | undefined): DashboardTile[] {
+ const positions = new Map((layout ?? []).map((item) => [item.i, item]))
+ const position = (tile: DashboardTile): [number, number] => {
+ const item = positions.get(tile.id.toString())
+ return item ? [item.y, item.x] : [Infinity, Infinity]
+ }
+ return [...tiles].sort((a, b) => {
+ const [ay, ax] = position(a)
+ const [by, bx] = position(b)
+ return ay === by ? ax - bx : ay - by
+ })
+}
+
+/** Splits tiles into full-width bands: each group starts where its top-left tile is, other tiles fill the gaps. */
+export function getDashboardSections({
+ tiles,
+ layout,
+ groups,
+}: {
+ tiles: DashboardTile[]
+ layout: Layout | undefined
+ groups: Record<string, DashboardTileGroupApi> | undefined
+}): DashboardSection[] {
+ const sections: DashboardSection[] = []
+ const groupSections = new Map<string, DashboardSection>()
+
+ for (const tile of tilesInLayoutOrder(tiles, layout)) {
+ const groupKey = tile.group_key
+ if (groupKey) {
+ const existing = groupSections.get(groupKey)
+ if (existing) {
+ existing.tiles.push(tile)
+ continue
+ }
+ const group = groups && Object.hasOwn(groups, groupKey) ? groups[groupKey] : {}
+ const section: DashboardSection = {
+ kind: 'group',
+ key: `group-${groupKey}`,
+ groupKey,
+ group,
+ tiles: [tile],
+ }
+ groupSections.set(groupKey, section)
+ sections.push(section)
+ continue
+ }
+ const last = sections.at(-1)
+ if (last?.kind === 'tiles') {
+ last.tiles.push(tile)
+ } else {
+ // Named after the group above it, so the key holds when the band's own tiles reorder.
+ const key = last ? `tiles-after-${last.groupKey}` : 'tiles-start'
+ sections.push({ kind: 'tiles', key, tiles: [tile] })
+ }
+ }
+
+ return sections
+}
+
+function moveToTop(layout: Layout): Layout {
+ const top = Math.min(...layout.map((item) => item.y))
+ return layout.map((item) => ({ ...item, y: item.y - top }))
+}
+
+// One column has nothing to place beside a tile, so a gap left by another band's tiles is only blank space.
+function stackInOneColumn(layout: Layout): Layout {
+ let y = 0
+ return [...layout]
+ .sort((a, b) => a.y - b.y || a.x - b.x)
+ .map((item) => {
+ const placed = { ...item, y }
+ y += item.h
+ return placed
+ })
+}
+
+/**
+ * A band's own layout, compacted the way its grid compacts it on mount.
+ * Otherwise the grid closes the gaps left by other bands' tiles and reports a layout change nobody made.
+ */
+export function getSectionLayouts(
+ layouts: SectionLayouts,
+ tiles: DashboardTile[],
+ compactor: Compactor
+): SectionLayouts {
+ const tileIds = new Set(tiles.map((tile) => tile.id.toString()))
+ return Object.fromEntries(
+ Object.entries(layouts).map(([size, layout]) => {
+ const sectionLayout = (layout ?? []).filter((item) => tileIds.has(item.i))
+ return [
+ size,
+ size === 'xs'
+ ? stackInOneColumn(sectionLayout)
+ : compactor.compact(moveToTop(sectionLayout), BREAKPOINT_COLUMN_COUNTS.sm),
+ ]
+ })
+ )
+}
+
+/** Joins section layouts into one dashboard layout, each section under the one before it. */
+export function stackSectionLayouts(sectionLayouts: Layout[]): Layout {
+ let offset = 0
+ return sectionLayouts.flatMap((sectionLayout) => {
+ const stacked = moveToTop(sectionLayout).map((item) => ({ ...item, y: item.y + offset }))
+ offset = Math.max(offset, ...stacked.map((item) => item.y + item.h))
+ return stacked
+ })
+}
+
+function geometry(layout: Layout): Pick<Layout[number], 'i' | 'x' | 'y' | 'w' | 'h'>[] {
+ return [...layout].sort((a, b) => a.i.localeCompare(b.i)).map(({ i, x, y, w, h }) => ({ i, x, y, w, h }))
+}
+
+export function hasSectionLayoutChanged(before: Layout, after: Layout): boolean {
+ return !objectsEqual(geometry(before), geometry(after))
+}
+
+/**
+ * The dashboard layout after one band's grid reports its layout, or null when no tile in that band moved.
+ * A grid also reports its layout when only its width crosses a breakpoint, and restacking the bands then would
+ * move tiles that the person did not touch.
+ */
+export function getLayoutAfterSectionChange(sectionLayouts: Layout[], reportedLayout: Layout): Layout | null {
+ const reportedTileIds = new Set(reportedLayout.map((item) => item.i))
+ const sectionIndex = sectionLayouts.findIndex((layout) => layout.some((item) => reportedTileIds.has(item.i)))
+ if (sectionIndex < 0 || !hasSectionLayoutChanged(sectionLayouts[sectionIndex], reportedLayout)) {
+ return null
+ }
+ return stackSectionLayouts(
+ sectionLayouts.map((layout, index) => (index === sectionIndex ? reportedLayout : layout))
+ )
+}
+
+/** Group keys that start closed: the viewer's own choice wins over the dashboard's saved default. */
+export function getCollapsedTileGroupKeys({
+ tiles,
+ groups,
+ choices,
+}: {
+ tiles: DashboardTile[]
+ groups: Record<string, DashboardTileGroupApi> | undefined
+ choices: Record<string, boolean> | undefined
+}): string[] {
+ const groupKeys = new Set(tiles.map((tile) => tile.group_key).filter((groupKey): groupKey is string => !!groupKey))
+ return [...groupKeys].filter((groupKey) => {
+ if (choices && Object.hasOwn(choices, groupKey)) {
+ return choices[groupKey]
+ }
+ return !!(groups && Object.hasOwn(groups, groupKey) && groups[groupKey].collapsed)
+ })
+}