: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): show tile groups as tabs (#123056)
Paul D'Ambra072f89a11738
diff --git a/frontend/src/scenes/dashboard/DashboardCustomizeSubMenu.tsx b/frontend/src/scenes/dashboard/DashboardCustomizeSubMenu.tsxindex 4e00b7cd5260..aae96d585269 100644--- a/frontend/src/scenes/dashboard/DashboardCustomizeSubMenu.tsx+++ b/frontend/src/scenes/dashboard/DashboardCustomizeSubMenu.tsx@@ -11,19 +11,21 @@ import {SceneMenuBarSeparator,SceneMenuBarSubMenu,} from '~/layout/scenes/components/SceneMenuBar'-import { DashboardTileSpacing } from '~/types'+import { DashboardTileSpacing, TileGroupDisplay } from '~/types'import {DASHBOARD_GRID_COMPACTION_LABELS,DASHBOARD_TILE_SPACING_LABELS,DashboardGridCompaction,+ TILE_GROUP_DISPLAY_LABELS,} from 'products/dashboards/frontend/dashboardCustomization'import { dashboardLogic } from './dashboardLogic'export function DashboardCustomizeSubMenu(): JSX.Element | null {- const { dashboard, currentLayoutSize, layoutEditMode } = useValues(dashboardLogic)- const { setDashboardEditing, changeDashboardTileSpacing, changeDashboardGridCompaction } =+ const { dashboard, currentLayoutSize, layoutEditMode, tileGroupSections, tileGroupDisplay } =+ useValues(dashboardLogic)+ const { setDashboardEditing, changeDashboardTileSpacing, changeDashboardGridCompaction, changeTileGroupDisplay } =useActions(dashboardLogic)if (!dashboard) {@@ -87,6 +89,24 @@ export function DashboardCustomizeSubMenu(): JSX.Element | null {</SceneMenuBarRadioGroup></SceneMenuBarSubMenu>)}+ {tileGroupSections.length > 0 && (+ <SceneMenuBarSubMenu label="Show groups as">+ <SceneMenuBarRadioGroup+ value={tileGroupDisplay}+ onValueChange={(value: unknown) => changeTileGroupDisplay(value as TileGroupDisplay)}+ >+ {(Object.keys(TILE_GROUP_DISPLAY_LABELS) as TileGroupDisplay[]).map((display) => (+ <SceneMenuBarRadioItem+ key={display}+ value={display}+ data-attr={`dashboard-menubar-group-display-${display}`}+ >+ {TILE_GROUP_DISPLAY_LABELS[display]}+ </SceneMenuBarRadioItem>+ ))}+ </SceneMenuBarRadioGroup>+ </SceneMenuBarSubMenu>+ )}</SceneMenuBarSubMenu>)}diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsxindex 62f78deed1fa..176ccd79a9d0 100644--- a/frontend/src/scenes/dashboard/DashboardItems.tsx+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx@@ -41,11 +41,12 @@ import { DashboardLayoutSize, DashboardPlacement, DashboardTile, DashboardType }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 { DashboardTileGroupTabs } from 'products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs'import { DashboardTileSectionBand } from 'products/dashboards/frontend/components/DashboardTileSectionBand'import { TileGroupTakeOutDropZone } from 'products/dashboards/frontend/components/TileGroupTakeOutDropZone'import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'-import type { DashboardSection } from 'products/dashboards/frontend/dashboardTileSections'+import { type DashboardSection, getSectionGroupKey } from 'products/dashboards/frontend/dashboardTileSections'import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDashboardContainerWidth'import { TAKE_OUT_DROP_ZONE_KEY, useTileGroupDrag } from 'products/dashboards/frontend/useTileGroupDrag'@@ -123,6 +124,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPtileGroupSectionLayouts,collapsedTileGroupKeys,tileGroupMoveOptions,+ activeTileGroupTab,} = useValues(dashboardLogic)const { layoutZoom = 1 } = useValues(dashboardLogic)const {@@ -139,6 +141,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPcopyToDashboard,setDashboardEditing,toggleTileGroup,+ selectTileGroupTab,updateTileGroupSectionLayout,moveTileToSection,} = useActions(dashboardLogic)@@ -208,6 +211,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPconst { width: gridWidth, containerRef } = useDashboardContainerWidth()const showBands = tileGroupSections.length > 0+ const activeTabIndex = tileGroupSections.findIndex((section) => getSectionGroupKey(section) === activeTileGroupTab)const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =useDashboardLayoutInteraction({layoutEditMode,@@ -311,9 +315,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPenabled: canEditDashboard && layoutEditMode && !isMobileView,handle: '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle',cancel: 'a,table,button,input,.Popover',- bounded: !showBands,+ bounded: !showBands || activeTabIndex >= 0,}),- [canEditDashboard, layoutEditMode, isMobileView, showBands]+ [canEditDashboard, layoutEditMode, isMobileView, showBands, activeTabIndex])const {draggingTileId,@@ -324,7 +328,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPtrackTileDrag,finishTileDrag,} = useTileGroupDrag({- enabled: dragConfig.enabled && showBands,+ // A tab shows one group, so there is no other band to drop a tile into.+ enabled: dragConfig.enabled && showBands && activeTabIndex < 0,sections: tileGroupSections,rowHeight,margin,@@ -762,14 +767,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPonDragStop: handleDragStop,}- const renderSection = (section: DashboardSection, index: number): JSX.Element => {+ const renderSectionGrid = (section: DashboardSection, index: number): JSX.Element => {const sectionLayouts = tileGroupSectionLayouts[index]- const isLastSection = index === tileGroupSections.length - 1 && !showTakeOutDropZone+ const isLastSection = activeTabIndex >= 0 || (index === tileGroupSections.length - 1 && !showTakeOutDropZone)const isDraggingOutOfSection =!!dropTargetKey && section.tiles.some((tile) => tile.id.toString() === draggingTileId)// 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 = (+ return (<divclassName="relative"data-dashboard-section-grid={section.key}@@ -803,21 +808,21 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP</ReactGridLayout></div>)-- return (- <DashboardTileSectionBand- key={section.key}- section={section}- isFirst={index === 0}- isDropTarget={dropTargetKey === section.key}- collapsedTileGroupKeys={collapsedTileGroupKeys}- onToggleTileGroup={toggleTileGroup}- >- {grid}- </DashboardTileSectionBand>- )}+ const renderSection = (section: DashboardSection, index: number): JSX.Element => (+ <DashboardTileSectionBand+ key={section.key}+ section={section}+ isFirst={index === 0}+ isDropTarget={dropTargetKey === section.key}+ collapsedTileGroupKeys={collapsedTileGroupKeys}+ onToggleTileGroup={toggleTileGroup}+ >+ {renderSectionGrid(section, index)}+ </DashboardTileSectionBand>+ )+return (<div className="dashboard-items-wrapper" ref={containerRef as RefObject<HTMLDivElement>}>{layoutEditMode && isMobileView && (@@ -826,7 +831,18 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsPresize tiles.</LemonBanner>)}- {gridWidth > 0 && showBands && (+ {gridWidth > 0 && activeTabIndex >= 0 && (+ <div className={clsx(showDecorationSpace && 'mt-10', !layoutEditMode && 'mb-8')}>+ <DashboardTileGroupTabs+ sections={tileGroupSections}+ activeSectionKey={tileGroupSections[activeTabIndex].key}+ onSelect={selectTileGroupTab}+ >+ {renderSectionGrid(tileGroupSections[activeTabIndex], activeTabIndex)}+ </DashboardTileGroupTabs>+ </div>+ )}+ {gridWidth > 0 && showBands && activeTabIndex < 0 && (<div className={clsx('flex flex-col gap-4', showDecorationSpace && 'mt-10', !layoutEditMode && 'mb-8')}>{tileGroupSections.map(renderSection)}{showTakeOutDropZone && (diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsxindex 00ba3b23e3e8..abef04119989 100644--- a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx@@ -5,6 +5,7 @@ import { Link } from '@posthog/lemon-ui'import {DASHBOARD_GRID_COMPACTION_LABELS,DASHBOARD_TILE_SPACING_LABELS,+ TILE_GROUP_DISPLAY_LABELS,} from '@posthog/products-dashboards/frontend/dashboardCustomization'import {@@ -173,6 +174,16 @@ const dashboardActionsMapping: Record<</>)}+ if (after?.group_display && after.group_display !== (before?.group_display ?? 'sections')) {+ if (description.length > 0) {+ description.push(' and ')+ }+ description.push(+ <>+ changed how groups show to <strong>{TILE_GROUP_DISPLAY_LABELS[after.group_display]}</strong>+ </>+ )+ }return description.length > 0 ? { description } : null},}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 37dcd718d974..d305f1653295 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -2,6 +2,7 @@import { MOCK_TEAM_ID } from 'lib/api.mock'import { waitFor } from '@testing-library/react'+import { getContext } from 'kea'import { router } from 'kea-router'import { expectLogic, truth } from 'kea-test-utils'import posthog from 'posthog-js'@@ -962,6 +963,200 @@ describe('dashboardLogic', () => {await expectLogic(logic, () => logic.actions.cancelDashboardRefresh()).toFinishAllListeners()})+ it.each([+ {+ name: 'the viewer opens it',+ open: () => logic.actions.selectTileGroupTab('group-target'),+ beforeMount: () => {},+ ungroupedLoads: 1,+ },+ {+ name: 'a link names it',+ open: () => {},+ beforeMount: () => router.actions.push('/dashboard/5', { tab: 'group-target' }),+ ungroupedLoads: 0,+ },+ {+ name: 'the viewer follows a link to it',+ open: () => router.actions.push('/dashboard/5', { tab: 'group-target' }),+ beforeMount: () => {},+ ungroupedLoads: 1,+ },+ ])('shows tabs one at a time and loads a tab when $name', async ({ open, beforeMount, ungroupedLoads }) => {+ groupTiles({ target: { collapsed: false } })+ dashboards[5] = {+ ...dashboards[5],+ customization: { group_display: 'tabs' },+ tiles: dashboards[5].tiles.map((tile, index) =>+ index === 1 ? { ...tile, group_key: null } : tile+ ),+ }+ const ungrouped = dashboards[5].tiles[1].insight!.short_id+ beforeMount()+ await mountDashboard()+ await expectLogic(logic, open).toFinishAllListeners()++ expect(logic.values.tileGroupSections.map((section) => section.key)).toEqual([+ 'tiles-ungrouped',+ 'group-target',+ ])+ expect(logic.values.activeTileGroupTab).toEqual('target')+ expect(router.values.searchParams.tab).toEqual('group-target')+ expect(loads(target)).toHaveLength(1)+ expect(loads(ungrouped)).toHaveLength(ungroupedLoads)+ })++ it.each([+ { leftTabTiles: 5, cancelled: true, returnBeforeAbortsSettle: false, stop: false },+ { leftTabTiles: 4, cancelled: false, returnBeforeAbortsSettle: false, stop: false },+ { leftTabTiles: 5, cancelled: true, returnBeforeAbortsSettle: true, stop: false },+ { leftTabTiles: 5, cancelled: true, returnBeforeAbortsSettle: true, stop: true },+ ])(+ 'on a tab switch, $leftTabTiles loading tiles in the tab left behind are cancelled: $cancelled, return before the aborts settle: $returnBeforeAbortsSettle, stop: $stop',+ async ({ leftTabTiles, cancelled, returnBeforeAbortsSettle, stop }) => {+ groupTiles({ target: { collapsed: false } })+ const [targetTile, ungroupedTile] = dashboards[5].tiles+ const leftTiles = Array.from({ length: leftTabTiles }, (_, index) => ({+ ...ungroupedTile,+ id: 900 + index,+ group_key: null,+ insight: {+ ...ungroupedTile.insight!,+ id: 900 + index,+ short_id: `left-${index}` as InsightShortId,+ },+ layouts: { sm: { x: 0, y: index * 2, w: 12, h: 2 } } as DashboardTile['layouts'],+ }))+ dashboards[5] = {+ ...dashboards[5],+ customization: { group_display: 'tabs' },+ tiles: [...leftTiles, targetTile],+ }+ await mountDashboard()+ refreshInsight.mockClear()+ const finishLoads: (() => void)[] = []+ refreshInsight.mockImplementation((_teamId, insight, ...args) =>+ insight.short_id.startsWith('left-')+ ? new Promise((resolve, reject) => {+ const abort = (): void => reject(new DOMException('Aborted', 'AbortError'))+ // A load waiting out a retry backoff settles its abort later.+ args[3]?.signal?.addEventListener('abort', () =>+ returnBeforeAbortsSettle ? setTimeout(abort, 20) : abort()+ )+ finishLoads.push(() => resolve(insight))+ })+ : Promise.resolve(insight)+ )+ await expectLogic(logic, () => logic.actions.triggerDashboardRefresh()).toDispatchActions([+ 'setWaitingTileRefresh',+ 'setRefreshStatus',+ ])++ const leftShortIds = leftTiles.map((tile) => tile.insight.short_id)+ if (returnBeforeAbortsSettle) {+ logic.actions.selectTileGroupTab('group-target')+ refreshInsight.mockImplementation((_teamId, insight) => Promise.resolve(insight))+ logic.actions.selectTileGroupTab('tiles-ungrouped')+ if (stop) {+ await expectLogic(logic, () => logic.actions.cancelDashboardRefresh())+ .toDispatchActions(leftTiles.map(() => 'abortQuery'))+ .delay(20)+ .toFinishAllListeners()+ expect(+ leftShortIds.map((id) => loads(id).filter((call) => !call[5]?.signal?.aborted).length)+ ).toEqual(leftShortIds.map(() => 0))+ expect(logic.values.waitingTileRefresh?.tileIds).toEqual(+ expect.arrayContaining(leftTiles.map((tile) => tile.id))+ )+ return+ }+ await expectLogic(logic)+ .toDispatchActions(['abortQuery', 'refreshOpenTileGroupsWaiting'])+ .toFinishAllListeners()+ } else {+ await expectLogic(logic, () => logic.actions.selectTileGroupTab('group-target'))+ .toDispatchActions(['refreshTileGroup'])+ .delay(5)+ finishLoads.forEach((finish) => finish())+ await expectLogic(logic).toFinishAllListeners()++ const abortedLoads = refreshInsight.mock.calls.filter((call) => call[5]?.signal?.aborted)+ expect(abortedLoads.length > 0).toBe(cancelled)+ expect(leftShortIds.filter((id) => logic.values.refreshStatus[id]?.queued)).toEqual([])+ expect(loads(targetTile.insight!.short_id).at(-1)?.[4]).toEqual('force_blocking')+ if (cancelled) {+ expect(logic.values.waitingTileRefresh).toMatchObject({+ tileIds: leftTiles.map((tile) => tile.id),+ forceRefresh: true,+ })+ }++ refreshInsight.mockImplementation((_teamId, insight) => Promise.resolve(insight))+ await expectLogic(logic, () =>+ logic.actions.selectTileGroupTab('tiles-ungrouped')+ ).toFinishAllListeners()+ }++ for (const shortId of leftShortIds) {+ const finishedLoads = loads(shortId).filter((call) => !call[5]?.signal?.aborted)+ expect(finishedLoads.map((call) => call[4])).toEqual(['force_blocking'])+ expect(logic.values.refreshStatus[shortId]).toMatchObject({ refreshed: true })+ }+ expect(logic.values.waitingTileRefresh).toBeNull()++ // A hidden browser tab pauses disposables and reruns them on return, so a finished one must not stay.+ await expectLogic(logic).delay(20).toFinishAllListeners()+ const dispatch = jest.spyOn(getContext().store, 'dispatch')+ for (const hidden of [true, false]) {+ Object.defineProperty(document, 'hidden', { configurable: true, value: hidden })+ document.dispatchEvent(new Event('visibilitychange'))+ }+ delete (document as { hidden?: boolean }).hidden+ await expectLogic(logic).delay(5).toFinishAllListeners()+ expect(+ dispatch.mock.calls.filter(+ ([action]) => action.type === logic.actionTypes.refreshOpenTileGroupsWaiting+ )+ ).toEqual([])+ dispatch.mockRestore()+ }+ )++ it.each([+ {+ name: 'the dashboard switches to sections',+ change: (dashboard: DashboardType): DashboardType => ({ ...dashboard, customization: {} }),+ },+ {+ name: 'the last grouped tile leaves its group',+ change: (dashboard: DashboardType): DashboardType => ({+ ...dashboard,+ tiles: dashboard.tiles.map((tile) => ({ ...tile, group_key: null })),+ }),+ },+ ])('loads tiles from a hidden tab when $name', async ({ change }) => {+ groupTiles({ target: { collapsed: false } })+ dashboards[5] = {+ ...dashboards[5],+ customization: { group_display: 'tabs' },+ tiles: dashboards[5].tiles.map((tile, index) =>+ index === 1 ? { ...tile, group_key: null } : tile+ ),+ }+ const ungrouped = dashboards[5].tiles[1].insight!.short_id+ router.actions.push('/dashboard/5', { tab: 'group-target' })+ await mountDashboard()+ expect(loads(ungrouped)).toHaveLength(0)++ await expectLogic(logic, () =>+ dashboardsModel.actions.updateDashboardSuccess(change(logic.values.dashboard!), {+ layoutsPersisted: true,+ })+ ).toFinishAllListeners()++ expect(loads(ungrouped)).toHaveLength(1)+ })+it('loads a widget in a closed group on open', async () => {groupTiles({ target: { collapsed: true } })dashboards[5].tiles.push({ ...WIDGET_TILE, group_key: 'target' })diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 4b3fdb1bdda8..9af9c43a250c 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -110,6 +110,7 @@ import {DashboardTileIdOrNew,DashboardTileSpacing,DashboardType,+ TileGroupDisplay,DashboardWidgetType,InsightColor,InsightModel,@@ -139,11 +140,14 @@ import {type TileGroupMoveOptions,getCollapsedTileGroupKeys,getDashboardSections,+ getDashboardTabs,getLayoutAfterSectionChange,getLayoutAfterTileMove,+ getSectionGroupKey,getSectionLayouts,getTileGroupLabel,getTileGroupMoveOptions,+ UNGROUPED_TILES_TAB_KEY,} from 'products/dashboards/frontend/dashboardTileSections'import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'@@ -185,6 +189,7 @@ import {parseURLFilters,parseURLVariables,TaskQueue,+ TileLoads,searchParamsWithUrlFilters,shouldSharedDashboardAutoForceForStaleTime,} from './dashboardUtils'@@ -231,7 +236,14 @@ function reportDashboardTileRefreshed(const TILE_REFRESH_CONCURRENCY = 4-type InsightTileRefreshOutcome = 'refreshed' | 'cached' | 'errored' | 'aborted'+/** `deferred` means a tab switch stopped the load, and the tile waits for its tab to open again. */+type InsightTileRefreshOutcome = 'refreshed' | 'cached' | 'errored' | 'aborted' | 'deferred'++/** How a load ran, so a tile whose load a tab switch stops can load the same way later. */+interface TileLoadRefresh {+ forceRefresh: boolean+ settings: DashboardSettings+}interface InsightTileRefresh {actions: Pick<dashboardLogicType['actions'], 'setRefreshStatus' | 'setRefreshError' | 'abortQuery'>@@ -241,8 +253,10 @@ interface InsightTileRefresh {variables: Record<string, HogQLVariable>urlFilters: DashboardFilterforceRefresh: boolean+ settings: DashboardSettingssignal: AbortSignalqueue: TaskQueue+ tileLoads: TileLoads<TileLoadRefresh>}/** One queue for every insight and widget load, so a dashboard never sends more than the cap at the same time. */@@ -250,6 +264,27 @@ function tileLoadQueue(cache: Record<string, any>): TaskQueue {return (cache.tileLoadQueue ??= new TaskQueue(TILE_REFRESH_CONCURRENCY))}+function tileLoads(cache: Record<string, any>): TileLoads<TileLoadRefresh> {+ return (cache.tileLoads ??= new TileLoads<TileLoadRefresh>())+}++/**+ * The tiles of a tab a viewer leaves whose loads stop. They stop only when there are more of them than the queue+ * runs at the same time, because only then does the new tab wait behind them.+ */+function tileLoadsToCancelOnTabSwitch(+ tiles: DashboardTile[],+ refreshStatus: Record<string, RefreshStatus>,+ widgetRefreshStatus: Record<number, { loading?: boolean }>+): number[] {+ const loading = tiles.filter((tile) =>+ tile.insight+ ? refreshStatus[tile.insight.short_id]?.loading || refreshStatus[tile.insight.short_id]?.queued+ : widgetRefreshStatus[tile.id]?.loading+ )+ return loading.length > TILE_REFRESH_CONCURRENCY ? loading.map((tile) => tile.id) : []+}+async function refreshInsightTile(tile: DashboardTile & { insight: InsightModel },{@@ -260,13 +295,16 @@ async function refreshInsightTile(variables,urlFilters,forceRefresh,- signal,+ settings,+ signal: refreshSignal,queue,+ tileLoads,}: InsightTileRefresh): Promise<InsightTileRefreshOutcome> {const insight = tile.insightconst queryId = uuid()let queryStartTime = performance.now()+ const { signal, finish } = tileLoads.start([tile.id], refreshSignal, { forceRefresh, settings })try {const refreshedInsight = await queue.run(() => {@@ -305,10 +343,12 @@ async function refreshInsightTile(if (shouldCancelQuery(e)) {console.warn(`Insight refresh cancelled for ${insight.short_id} due to abort signal:`, e)actions.abortQuery({ queryId, queryStartTime, shortId: insight.short_id })- return 'aborted'+ return refreshSignal.aborted ? 'aborted' : 'deferred'}actions.setRefreshError(insight.short_id, e)return 'errored'+ } finally {+ finish()}}@@ -332,23 +372,22 @@ interface WaitingTileRefresh {/** Tiles in closed groups that a refresh skips wait for their group to open, alongside tiles an earlier refresh skipped. */function nextWaitingTileRefresh({previous,- tiles,+ tileGroupKeys,collapsedTileIds,candidateTileIds,forceRefresh,settings,}: {previous: WaitingTileRefresh | null- tiles: DashboardTile[]+ tileGroupKeys: Map<number, string>collapsedTileIds: Set<number>candidateTileIds: number[]forceRefresh: booleansettings: DashboardSettings}): WaitingTileRefresh {- const groupedTileIds = new Set(tiles.filter((tile) => tile.group_key).map((tile) => tile.id))// This refresh aborts a running group load, and a viewer can cancel this refresh too,// so a tile keeps waiting until a load of it succeeds.- const previouslyWaiting = previous?.tileIds.filter((id) => groupedTileIds.has(id)) ?? []+ const previouslyWaiting = previous?.tileIds.filter((id) => tileGroupKeys.has(id)) ?? []return {tileIds: [...new Set([...previouslyWaiting, ...candidateTileIds.filter((id) => collapsedTileIds.has(id))])],// A refresh of only stale tiles must not let a group that a manual refresh skipped show older data.@@ -359,14 +398,14 @@ function nextWaitingTileRefresh({/** Open groups that still hold tiles an earlier refresh skipped. */function openTileGroupsWaiting(- tiles: DashboardTile[],+ tileGroupKeys: Map<number, string>,collapsedTileIds: Set<number>,waiting: WaitingTileRefresh | null): Set<string> {return new Set(- tiles- .filter((tile) => tile.group_key && !collapsedTileIds.has(tile.id) && waiting?.tileIds.includes(tile.id))- .map((tile) => tile.group_key as string)+ [...tileGroupKeys]+ .filter(([tileId]) => !collapsedTileIds.has(tileId) && waiting?.tileIds.includes(tileId))+ .map(([, groupKey]) => groupKey))}@@ -613,6 +652,7 @@ export interface dashboardLogicValues {currentTeamId: number | null // teamLogicvariables: Variable[] // variableDataLogicaccessDeniedToDashboard: boolean+ activeTileGroupTab: string | nulladdWidgetCollapsedGroups: string[]addWidgetFilteredGroups: string[]addWidgetModalOpen: boolean@@ -749,6 +789,8 @@ export interface dashboardLogicValues {terraformModalOpen: booleantextTileId: DashboardTileIdOrNewtextTiles: DashboardTile[]+ tileGroupDisplay: TileGroupDisplay+ tileGroupKeys: Map<number, string>tileGroupMoveOptions: Record<number, TileGroupMoveOptions>tileGroupSectionLayouts: SectionLayouts[]tileGroupSections: DashboardSection[]@@ -832,6 +874,9 @@ export interface dashboardLogicActions {changeDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => {tileSpacing: DashboardTileSpacing}+ changeTileGroupDisplay: (groupDisplay: TileGroupDisplay) => {+ groupDisplay: TileGroupDisplay+ }clearAddWidgetSelectedTypes: () => {value: true}@@ -1080,6 +1125,9 @@ export interface dashboardLogicActions {forceRefresh?: boolean | undefinedtileIds: number[]}+ refreshOpenTileGroupsWaiting: () => {+ value: true+ }refreshTileGroup: (groupKey: string) => {groupKey: string}@@ -1205,6 +1253,9 @@ export interface dashboardLogicActions {scheduleRefreshDashboardWidgets: (tileId: number) => {tileId: number}+ selectTileGroupTab: (sectionKey: string) => {+ sectionKey: string+ }setAccessDeniedToDashboard: () => {value: true}@@ -1635,15 +1686,27 @@ export interface dashboardLogicMeta {tiles: (dashboard: DashboardType | null) => DashboardTile[]widgetTiles: (tiles: DashboardTile[]) => DashboardTile[]tileGroupSectionsEnabled: (featureFlags: FeatureFlagsSet) => boolean+ tileGroupDisplay: (dashboard: DashboardType | null, placement: DashboardPlacement) => TileGroupDisplay+ tileGroupKeys: (tiles: DashboardTile[]) => Map<number, string>+ activeTileGroupTab: (+ tileGroupDisplay: TileGroupDisplay,+ tileGroupSections: DashboardSection[],+ tileGroupKeys: Map<number, string>,+ tiles: DashboardTile[],+ highlightedInsightId: any,+ searchParams: Record<string, any>+ ) => string | nullcollapsedTileGroupKeys: (tileGroupSectionsEnabled: boolean,placement: DashboardPlacement,tiles: DashboardTile[],dashboard: DashboardType | null,tileGroupChoices: TileGroupChoices,- revealedTileGroup: RevealedTileGroup | null+ revealedTileGroup: RevealedTileGroup | null,+ tileGroupSections: DashboardSection[],+ activeTileGroupTab: string | null) => string[]- collapsedTileIds: (tiles: DashboardTile[], collapsedTileGroupKeys: string[]) => Set<number>+ collapsedTileIds: (tileGroupKeys: Map<number, string>, collapsedTileGroupKeys: string[]) => Set<number>insightTiles: (tiles: DashboardTile[]) => DashboardTile[]textTiles: (tiles: DashboardTile[]) => DashboardTile[]dashboardControlScopes: (insightTiles: DashboardTile[]) => Record<DashboardControl, DashboardControlScope>@@ -1710,7 +1773,8 @@ export interface dashboardLogicMeta {tiles: DashboardTile[],layouts: Partial<Record<string, Layout>>,dashboard: DashboardType | null,- placement: DashboardPlacement+ placement: DashboardPlacement,+ tileGroupDisplay: TileGroupDisplay) => DashboardSection[]tileGroupSectionLayouts: (tileGroupSections: DashboardSection[],@@ -1922,6 +1986,9 @@ export const dashboardLogic = kea<dashboardLogicType>([}) => payload,refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean }) => payload,toggleTileGroup: (groupKey: string) => ({ groupKey }),+ selectTileGroupTab: (sectionKey: string) => ({ sectionKey }),+ refreshOpenTileGroupsWaiting: true,+ changeTileGroupDisplay: (groupDisplay: TileGroupDisplay) => ({ groupDisplay }),refreshTileGroup: (groupKey: string) => ({ groupKey }),setWaitingTileRefresh: (waiting: WaitingTileRefresh) => ({ waiting }),clearWaitingTileRefresh: (tileIds: number[]) => ({ tileIds }),@@ -3725,6 +3792,55 @@ export const dashboardLogic = kea<dashboardLogicType>([(s) => [s.featureFlags],(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.DASHBOARD_TILE_GROUP_SECTIONS],],+ tileGroupDisplay: [+ (s) => [s.dashboard, s.placement],+ (dashboard: DashboardType | null, placement: DashboardPlacement): TileGroupDisplay =>+ // Exported images and subscription emails can't switch tabs, so they show every group.+ dashboard?.customization?.group_display === 'tabs' && placement !== DashboardPlacement.Export+ ? 'tabs'+ : 'sections',+ ],+ /**+ * The group each tile opens and closes with. Tiles outside any group share one key, so tiles that waited in a+ * closed "Overview" tab still load once it shows, also after the dashboard switches to sections or loses its+ * last group.+ */+ tileGroupKeys: [+ (s) => [s.tiles],+ (tiles: DashboardTile[]): Map<number, string> =>+ new Map(tiles.map((tile) => [tile.id, tile.group_key || UNGROUPED_TILES_TAB_KEY])),+ ],+ activeTileGroupTab: [+ (s) => [+ s.tileGroupDisplay,+ s.tileGroupSections,+ s.tileGroupKeys,+ s.tiles,+ s.highlightedInsightId,+ router.selectors.searchParams,+ ],+ (+ tileGroupDisplay: TileGroupDisplay,+ tileGroupSections: DashboardSection[],+ tileGroupKeys: Map<number, string>,+ tiles: DashboardTile[],+ highlightedInsightId: string | undefined,+ searchParams: Record<string, any>+ ): string | null => {+ if (tileGroupDisplay !== 'tabs') {+ return null+ }+ const tabFromUrl = tileGroupSections.find((section) => section.key === searchParams.tab)+ if (tabFromUrl) {+ return getSectionGroupKey(tabFromUrl)+ }+ const highlightedTile = tiles.find(+ (tile) => highlightedInsightId && tile.insight?.short_id === highlightedInsightId+ )+ const highlightedTab = highlightedTile ? tileGroupKeys.get(highlightedTile.id) : undefined+ return highlightedTab ?? (tileGroupSections[0] ? getSectionGroupKey(tileGroupSections[0]) : null)+ },+ ],collapsedTileGroupKeys: [(s) => [s.tileGroupSectionsEnabled,@@ -3733,6 +3849,8 @@ export const dashboardLogic = kea<dashboardLogicType>([s.dashboard,s.tileGroupChoices,s.revealedTileGroup,+ s.tileGroupSections,+ s.activeTileGroupTab,],(tileGroupSectionsEnabled: boolean,@@ -3740,24 +3858,31 @@ export const dashboardLogic = kea<dashboardLogicType>([tiles: DashboardTile[],dashboard: DashboardType | null,tileGroupChoices: TileGroupChoices,- revealedTileGroup: RevealedTileGroup | null- ): string[] =>+ revealedTileGroup: RevealedTileGroup | null,+ tileGroupSections: DashboardSection[],+ activeTileGroupTab: string | 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)- : [],+ if (!tileGroupSectionsEnabled || !dashboard || placement === DashboardPlacement.Export) {+ return []+ }+ if (activeTileGroupTab !== null) {+ return tileGroupSections.map(getSectionGroupKey).filter((key) => key !== activeTileGroupTab)+ }+ return getCollapsedTileGroupKeys({+ tiles,+ groups: dashboard.customization?.groups,+ choices: tileGroupChoices[dashboard.id],+ }).filter((groupKey) => groupKey !== revealedTileGroup?.groupKey)+ },],collapsedTileIds: [- (s) => [s.tiles, s.collapsedTileGroupKeys],- (tiles: DashboardTile[], collapsedTileGroupKeys: string[]): Set<number> =>+ (s) => [s.tileGroupKeys, s.collapsedTileGroupKeys],+ (tileGroupKeys: Map<number, string>, collapsedTileGroupKeys: string[]): Set<number> =>new Set(- tiles- .filter((tile) => tile.group_key && collapsedTileGroupKeys.includes(tile.group_key))- .map((tile) => tile.id)+ [...tileGroupKeys]+ .filter(([, groupKey]) => collapsedTileGroupKeys.includes(groupKey))+ .map(([tileId]) => tileId)),],insightTiles: [@@ -3973,23 +4098,25 @@ export const dashboardLogic = kea<dashboardLogicType>([],/** 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],+ (s) => [s.tileGroupSectionsEnabled, s.tiles, s.layouts, s.dashboard, s.placement, s.tileGroupDisplay],(tileGroupSectionsEnabled: boolean,tiles: DashboardTile[],layouts: ResponsiveLayouts,dashboard: DashboardType | null,- placement: DashboardPlacement+ placement: DashboardPlacement,+ tileGroupDisplay: TileGroupDisplay): DashboardSection[] => {if (!tileGroupSectionsEnabled || !tiles.some((tile) => tile.group_key)) {return []}const widgetTilesShown = isWidgetTileVisibleOnPlacement(placement)- return getDashboardSections({+ const sections = getDashboardSections({tiles: tiles.filter((tile) => !tile.widget || widgetTilesShown),layout: layouts.sm,groups: dashboard?.customization?.groups,})+ return tileGroupDisplay === 'tabs' ? getDashboardTabs(sections) : sections},],tileGroupSectionLayouts: [@@ -4203,6 +4330,18 @@ export const dashboardLogic = kea<dashboardLogicType>([],})),subscriptions(({ actions, cache }) => ({+ // Every way a group opens ends here: a toggle, a tab click or link, a highlighted insight, or a display switch.+ collapsedTileIds: (collapsedTileIds: Set<number>, previous: Set<number> | undefined) => {+ // Each tile load rebuilds the set. A load in flight still waits, so a rebuild must not load it twice.+ if (+ previous &&+ collapsedTileIds.size === previous.size &&+ [...previous].every((id) => collapsedTileIds.has(id))+ ) {+ return+ }+ actions.refreshOpenTileGroupsWaiting()+ },nextAllowedDashboardRefresh: (deadline: Dayjs | null) => {cache.disposables.dispose('dashboardRefreshTimer')if (!deadline || !deadline.isAfter(now())) {@@ -4336,13 +4475,13 @@ 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+ const tile = values.tiles.find((tile) => insightId && tile.insight?.short_id === insightId)+ const groupKey = tile ? values.tileGroupKeys.get(tile.id) : undefinedif (!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 })- actions.refreshTileGroup(groupKey)}},updateTileGroupSectionLayout: ({ layouts }) => {@@ -5207,7 +5346,7 @@ export const dashboardLogic = kea<dashboardLogicType>([const openWidgetTileIds = widgetTileIds.filter((id) => !collapsedTileIds.has(id))const waiting = nextWaitingTileRefresh({previous: values.waitingTileRefresh,- tiles: values.tiles,+ tileGroupKeys: values.tileGroupKeys,collapsedTileIds,candidateTileIds: [...staleTiles.map((tile) => tile.id), ...widgetTileIds],forceRefresh: !!forceRefresh,@@ -5240,7 +5379,7 @@ export const dashboardLogic = kea<dashboardLogicType>([}const openGroupsWaiting = (): Set<string> =>- openTileGroupsWaiting(values.tiles, values.collapsedTileIds, values.waitingTileRefresh)+ openTileGroupsWaiting(values.tileGroupKeys, values.collapsedTileIds, values.waitingTileRefresh)if (openGroupsWaiting().size > 0) {// The aborted group load clears its queued status a few microtasks later, and that status blocks a reload.cache.disposables.add(() => {@@ -5270,8 +5409,10 @@ export const dashboardLogic = kea<dashboardLogicType>([variables: urlVariables,urlFilters,forceRefresh: !!forceRefresh,+ settings: settingsToRefresh,signal: cache.abortController.signal,queue: tileLoadQueue(cache),+ tileLoads: tileLoads(cache),}const loadingHere = (cache.refreshingTileIds = new Set(sortedTilesToRefresh.map((tile) => tile.id)))const fetchSyncInsightFunctions = sortedTilesToRefresh.map((tile) => async () => {@@ -5388,16 +5529,74 @@ export const dashboardLogic = kea<dashboardLogicType>([tile_count: values.tiles.filter((tile) => tile.group_key === groupKey).length,})dashboardTileGroupChoicesLogic.actions.setTileGroupCollapsed(props.id, groupKey, collapse)- if (!collapse) {- actions.refreshTileGroup(groupKey)+ },+ refreshOpenTileGroupsWaiting: () => {+ openTileGroupsWaiting(values.tileGroupKeys, values.collapsedTileIds, values.waitingTileRefresh).forEach(+ (groupKey) => actions.refreshTileGroup(groupKey)+ )+ },+ selectTileGroupTab: ({ sectionKey }) => {+ const section = values.tileGroupSections.find((section) => section.key === sectionKey)+ if (!section) {+ return+ }+ // This listener runs before the URL changes, so the active tab is still the one the viewer leaves.+ const leftTab = values.activeTileGroupTab+ const leftTiles =+ leftTab === null || leftTab === getSectionGroupKey(section)+ ? []+ : values.tiles.filter((tile) => values.tileGroupKeys.get(tile.id) === leftTab)+ const { tiles: cancelled, settled } = tileLoads(cache).cancel(+ tileLoadsToCancelOnTabSwitch(leftTiles, values.refreshStatus, values.widgetRefreshStatus)+ )+ if (cancelled.length > 0) {+ const waiting = values.waitingTileRefresh+ actions.setWaitingTileRefresh({+ tileIds: [...new Set([...(waiting?.tileIds ?? []), ...cancelled.map(({ tileId }) => tileId)])],+ forceRefresh: !!waiting?.forceRefresh || cancelled.some(({ refresh }) => refresh.forceRefresh),+ settings: cancelled[0].refresh.settings,+ })+ // A group load skips a tile until its aborted load settles, which can be after the tile shows again.+ // One keyed handler waits for every stopped load so far, and removes itself once it has run, because+ // a hidden browser tab reruns every registered disposable when it shows again.+ const stoppedLoadsSettled = (cache.stoppedTileLoadsSettled = Promise.all([+ cache.stoppedTileLoadsSettled,+ settled,+ ]))+ cache.disposables.add(() => {+ let active = true+ let timerId: ReturnType<typeof setTimeout> | undefined+ void stoppedLoadsSettled.then(() => {+ if (active) {+ timerId = setTimeout(() => {+ cache.stoppedTileLoadsSettled = undefined+ cache.disposables.dispose('stoppedTileLoadsReload')+ actions.refreshOpenTileGroupsWaiting()+ }, 0)+ }+ })+ return () => {+ active = false+ clearTimeout(timerId)+ }+ }, 'stoppedTileLoadsReload')}+ posthog.capture('dashboard tile group tab opened', {+ dashboard_id: props.id,+ ungrouped: section.kind === 'tiles',+ tile_count: section.tiles.length,+ cancelled_load_count: cancelled.length,+ })+ },+ changeTileGroupDisplay: ({ groupDisplay }) => {+ actions.triggerDashboardUpdate({ group_display: groupDisplay })},refreshTileGroup: async ({ groupKey }) => {const { waitingTileRefresh: waiting, refreshStatus, widgetRefreshStatus } = values// A tile leaves the waiting list only once it loads, so one still loading must not load again.const tiles = values.tiles.filter((tile) =>- tile.group_key === groupKey &&+ values.tileGroupKeys.get(tile.id) === groupKey &&waiting?.tileIds.includes(tile.id) &&!cache.refreshingTileIds?.has(tile.id) &&!(tile.insight@@ -5438,8 +5637,10 @@ export const dashboardLogic = kea<dashboardLogicType>([variables: waiting.settings.variables,urlFilters: values.urlFilters,forceRefresh: waiting.forceRefresh,+ settings: waiting.settings,signal: cache.groupAbortController.signal,queue: tileLoadQueue(cache),+ tileLoads: tileLoads(cache),}await Promise.all(insightTiles.map(async (tile) => {@@ -5490,11 +5691,13 @@ export const dashboardLogic = kea<dashboardLogicType>([const projectId = String(values.currentTeamId)const dashboardId = props.idconst queue = tileLoadQueue(cache)+ const loadRefresh = { forceRefresh: !!forceRefresh, settings: values.settingsForRefresh }const fetchFunctions = chunkTileIds(staleTileIds, 4).map((chunk) => async () => {+ const { signal: chunkSignal, finish } = tileLoads(cache).start(chunk, signal, loadRefresh)try {const results = await queue.run(- () => fetchRunWidgets(projectId, dashboardId, chunk, { signal }),- signal+ () => fetchRunWidgets(projectId, dashboardId, chunk, { signal: chunkSignal }),+ chunkSignal)const resultsByTileId = Object.fromEntries(results.map((result) => [result.tile_id, result]))actions.setWidgetRunResults(resultsByTileId)@@ -5507,7 +5710,7 @@ export const dashboardLogic = kea<dashboardLogicType>([)}} catch {- if (signal.aborted) {+ if (chunkSignal.aborted) {// After a manual refresh a newer load owns the tile, and its status must stay with that load.actions.stopWidgetRefreshes(chunk.filter((tileId) => cache.widgetLoadSignals.get(tileId) === signal)@@ -5515,6 +5718,8 @@ export const dashboardLogic = kea<dashboardLogicType>([return}actions.setWidgetRefreshStatuses(chunk, false, DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)+ } finally {+ finish()}})@@ -5916,6 +6121,9 @@ export const dashboardLogic = kea<dashboardLogicType>([actions.abortAnyRunningQuery()abortWidgetLoads(cache)abortGroupLoads(cache)+ // Otherwise the reload after a tab switch restarts the loads the viewer just stopped.+ cache.disposables.dispose('stoppedTileLoadsReload')+ cache.stoppedTileLoadsSettled = undefined},abortQuery: async ({ queryId, queryStartTime }) => {const { currentTeamId, dashboardLoadData } = values@@ -6258,6 +6466,14 @@ export const dashboardLogic = kea<dashboardLogicType>([})),actionToUrl(({ values }) => ({+ selectTileGroupTab: ({ sectionKey }) => {+ const { currentLocation } = router.values+ return [+ currentLocation.pathname,+ { ...currentLocation.searchParams, tab: sectionKey },+ currentLocation.hashParams,+ ]+ },setProperties: ({ properties }) => {const { currentLocation } = router.valuesdiff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.tsindex db14d689795f..f8390c1169df 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts@@ -38,6 +38,7 @@ import {SEARCH_PARAM_QUERY_VARIABLES_KEY,shouldSharedDashboardAutoForceForStaleTime,TaskQueue,+ TileLoads,} from './dashboardUtils'describe('searchParamsWithUrlFilters', () => {@@ -714,3 +715,29 @@ describe('getInsightQueryError', () => {expect(getInsightQueryError({} as InsightModel)).toBeNull()})})++describe('TileLoads', () => {+ it('cancels every tile that shares a load, and settles once that load finishes', async () => {+ const tileLoads = new TileLoads<string>()+ const refresh = new AbortController()+ const removeListener = jest.spyOn(refresh.signal, 'removeEventListener')+ const batch = tileLoads.start([1, 2], refresh.signal, 'batch')+ const single = tileLoads.start([3], refresh.signal, 'single')++ const cancelled = tileLoads.cancel([1])+ let settled = false+ void cancelled.settled.then(() => (settled = true))+ await Promise.resolve()++ expect(cancelled.tiles).toEqual([+ { tileId: 1, refresh: 'batch' },+ { tileId: 2, refresh: 'batch' },+ ])+ expect([batch.signal.aborted, single.signal.aborted, settled]).toEqual([true, false, false])++ batch.finish()+ await cancelled.settled+ expect(removeListener).toHaveBeenCalledTimes(1)+ expect(tileLoads.cancel([2]).tiles).toEqual([])+ })+})diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex 3accdf103b25..d2a990009e3e 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -338,6 +338,67 @@ export class TaskQueue {}}+interface TileLoad<Refresh> {+ tileIds: number[]+ controller: AbortController+ refresh: Refresh+ settled: Promise<void>+}++/**+ * Running and queued tile loads by tile, each with its own signal under the signal of the refresh that started it.+ * Stopping one tile's load leaves the other loads of that refresh running.+ */+export class TileLoads<Refresh> {+ private readonly loads = new Map<number, TileLoad<Refresh>>()++ /** Starts one load of these tiles. Call `finish` once it settles, however it ends. */+ start(+ tileIds: number[],+ refreshSignal: AbortSignal,+ refresh: Refresh+ ): { signal: AbortSignal; finish: () => void } {+ const controller = new AbortController()+ const abort = (): void => controller.abort()+ let settle: () => void = () => {}+ const load: TileLoad<Refresh> = {+ tileIds,+ controller,+ refresh,+ settled: new Promise<void>((resolve) => (settle = resolve)),+ }+ if (refreshSignal.aborted) {+ abort()+ } else {+ refreshSignal.addEventListener('abort', abort, { once: true })+ }+ tileIds.forEach((tileId) => this.loads.set(tileId, load))+ const finish = (): void => {+ refreshSignal.removeEventListener('abort', abort)+ for (const tileId of tileIds) {+ if (this.loads.get(tileId) === load) {+ this.loads.delete(tileId)+ }+ }+ settle()+ }+ return { signal: controller.signal, finish }+ }++ /**+ * Aborts the loads of these tiles. Returns every tile those loads carried, which can be more than the tiles+ * asked for when one load fetches several tiles, and a promise that resolves once the aborted loads settle.+ */+ cancel(tileIds: number[]): { tiles: { tileId: number; refresh: Refresh }[]; settled: Promise<void> } {+ const loads = [...new Set(tileIds.flatMap((tileId) => this.loads.get(tileId) ?? []))]+ loads.forEach((load) => load.controller.abort())+ return {+ tiles: loads.flatMap((load) => load.tileIds.map((tileId) => ({ tileId, refresh: load.refresh }))),+ settled: Promise.all(loads.map((load) => load.settled)).then(() => undefined),+ }+ }+}+export const layoutsByTile = (layouts: ResponsiveLayouts): Record<string, Record<DashboardLayoutSize, TileLayout>> => {const itemLayouts: Record<string, Record<DashboardLayoutSize, TileLayout>> = {}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex eb15a53c8013..ac74923a4cb9 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2824,12 +2824,15 @@ export interface DashboardType extends DashboardBasicType {customization?: {tile_spacing?: DashboardTileSpacinglayout_compaction?: 'vertical' | 'horizontal' | 'stable'+ group_display?: TileGroupDisplaygroups?: Record<string, DashboardTileGroupApi>}}export type DashboardTileSpacing = 'tight' | 'condensed' | 'standard' | 'relaxed' | 'wide'+export type TileGroupDisplay = 'sections' | 'tabs'+export enum TemplateAvailabilityContext {GENERAL = 'general',ONBOARDING = 'onboarding',diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex c94eeb98d419..b0cf6c86b0ad 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -909,46 +909,46 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):self.assertTrue(response["attr"].startswith("groups"), response)- @parameterized.expand([("horizontal",), ("stable",)])- def test_dashboard_layout_compaction_is_saved_and_duplicated(self, layout_compaction: str) -> None:+ @parameterized.expand(+ [+ ("layout_compaction", "horizontal"),+ ("layout_compaction", "stable"),+ ("group_display", "tabs"),+ ]+ )+ def test_dashboard_display_mode_is_saved_and_duplicated(self, setting: str, mode: str) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})- _, updated = self.dashboard_api.update_dashboard(dashboard_id, {"layout_compaction": layout_compaction})- self.assertEqual(updated["customization"], {"layout_compaction": layout_compaction})+ _, updated = self.dashboard_api.update_dashboard(dashboard_id, {setting: mode})+ self.assertEqual(updated["customization"], {setting: mode})copied_id, copied = self.dashboard_api.create_dashboard({"name": "copy", "use_dashboard": dashboard_id})- self.assertEqual(copied["customization"], {"layout_compaction": layout_compaction})- self.assertEqual(Dashboard.objects.get(id=copied_id).customization, {"layout_compaction": layout_compaction})+ self.assertEqual(copied["customization"], {setting: mode})+ self.assertEqual(Dashboard.objects.get(id=copied_id).customization, {setting: mode})+ @parameterized.expand(+ [+ ("layout_compaction", "dashboard grid compaction configured", "vertical", "horizontal"),+ ("group_display", "dashboard group display configured", "sections", "tabs"),+ ]+ )@patch("products.dashboards.backend.api.dashboard.report_user_action")- def test_dashboard_layout_compaction_reports_every_mode_change(self, mock_report_user_action: MagicMock) -> None:+ def test_dashboard_display_mode_reports_every_mode_change(+ self, setting: str, event: str, default_mode: str, other_mode: str, mock_report_user_action: MagicMock+ ) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})mock_report_user_action.reset_mock()- self.dashboard_api.update_dashboard(dashboard_id, {"layout_compaction": "horizontal"})- self.dashboard_api.update_dashboard(dashboard_id, {"layout_compaction": "vertical"})+ self.dashboard_api.update_dashboard(dashboard_id, {setting: other_mode})+ self.dashboard_api.update_dashboard(dashboard_id, {setting: default_mode})- compaction_calls = [- call- for call in mock_report_user_action.call_args_list- if call.args[1] == "dashboard grid compaction configured"- ]- self.assertEqual(len(compaction_calls), 2)+ mode_calls = [call for call in mock_report_user_action.call_args_list if call.args[1] == event]self.assertEqual(- compaction_calls[0].args[2],- {- "dashboard_id": dashboard_id,- "previous_layout_compaction": "vertical",- "layout_compaction": "horizontal",- },- )- self.assertEqual(- compaction_calls[1].args[2],- {- "dashboard_id": dashboard_id,- "previous_layout_compaction": "horizontal",- "layout_compaction": "vertical",- },+ [call.args[2] for call in mode_calls],+ [+ {"dashboard_id": dashboard_id, f"previous_{setting}": default_mode, setting: other_mode},+ {"dashboard_id": dashboard_id, f"previous_{setting}": other_mode, setting: default_mode},+ ],)def test_dashboard_tile_spacing_recovers_from_malformed_customization(self):@@ -970,15 +970,16 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):)self.assertEqual(response["attr"], "grid_spacing")- def test_dashboard_layout_compaction_requires_a_known_mode(self) -> None:+ @parameterized.expand([("layout_compaction",), ("group_display",)])+ def test_dashboard_display_mode_requires_a_known_mode(self, setting: str) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})_, response = self.dashboard_api.update_dashboard(dashboard_id,- {"layout_compaction": "none"},+ {setting: "none"},expected_status=status.HTTP_400_BAD_REQUEST,)- self.assertEqual(response["attr"], "layout_compaction")+ self.assertEqual(response["attr"], setting)@patch("products.product_analytics.backend.presentation.insight.record_dashboard_cache_outcome")@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 72f4661d4573..33b9bca05350 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -164,7 +164,9 @@ from products.dashboards.backend.facade.api import DashboardTileBasicSerializer,from products.dashboards.backend.models.dashboard import (DASHBOARD_GRID_COMPACTION_MODES,DASHBOARD_GRID_SPACING_GAPS,+ DASHBOARD_TILE_GROUP_DISPLAY_MODES,Dashboard,+ TileGroupDisplay,)from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, DashboardTileBadge, Textfrom products.dashboards.backend.models.dashboard_widget import DashboardWidget@@ -259,6 +261,10 @@ def _effective_layout_compaction(customization: Any) -> str:return layout_compaction if layout_compaction in DASHBOARD_GRID_COMPACTION_MODES else "vertical"+def _effective_group_display(customization: Any) -> str:+ return stored_customization(customization).get("group_display", TileGroupDisplay.SECTIONS)++logger = structlog.get_logger(__name__)DASHBOARD_TILE_ERROR_TYPE = "DashboardTileError"@@ -331,6 +337,7 @@ DASHBOARD_SHARED_FIELDS = ["customization","grid_spacing","layout_compaction",+ "group_display","groups","group_titles",]@@ -1360,6 +1367,14 @@ class DashboardCustomizationSerializer(serializers.Serializer):"to the left, and stable preserves positions while moving colliding tiles."),)+ group_display = serializers.ChoiceField(+ choices=DASHBOARD_TILE_GROUP_DISPLAY_MODES,+ required=False,+ help_text=(+ "How tile groups show. sections shows each group as a band that opens and closes. tabs shows one "+ "group at a time, and tiles outside any group get their own first tab."+ ),+ )groups = serializers.DictField(child=DashboardTileGroupSerializer(),required=False,@@ -1433,6 +1448,15 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):"to the left, and stable preserves positions while moving colliding tiles."),)+ group_display = serializers.ChoiceField(+ choices=DASHBOARD_TILE_GROUP_DISPLAY_MODES,+ required=False,+ write_only=True,+ help_text=(+ "How tile groups show. sections shows each group as a band that opens and closes. tabs shows one "+ "group at a time, and tiles outside any group get their own first tab."+ ),+ )groups = _GroupDictField(child=DashboardTileGroupSerializer(),required=False,@@ -1834,6 +1858,7 @@ class DashboardSerializer(DashboardMetadataSerializer):team = self.context["get_team"]()grid_spacing = validated_data.pop("grid_spacing", None)layout_compaction = validated_data.pop("layout_compaction", None)+ group_display = validated_data.pop("group_display", None)has_groups = "groups" in validated_datagroups = validated_data.pop("groups", None)has_group_titles = "group_titles" in validated_data@@ -1900,6 +1925,11 @@ class DashboardSerializer(DashboardMetadataSerializer):**validated_data.get("customization", {}),"layout_compaction": layout_compaction,}+ if group_display is not None:+ validated_data["customization"] = {+ **validated_data.get("customization", {}),+ "group_display": group_display,+ }def with_requested_groups(customization: dict[str, Any]) -> dict[str, Any]:if has_groups:@@ -2130,6 +2160,7 @@ class DashboardSerializer(DashboardMetadataSerializer):@monitor(feature=Feature.DASHBOARD, endpoint="dashboard", method="PATCH")def update(self, instance: Dashboard, validated_data: dict, *args: Any, **kwargs: Any) -> Dashboard:previous_layout_compaction = _effective_layout_compaction(instance.customization)+ previous_group_display = _effective_group_display(instance.customization)self._check_delivered_dashboard_filters_access(cast(User, self.context["request"].user), instance, self.initial_data)@@ -2137,11 +2168,13 @@ class DashboardSerializer(DashboardMetadataSerializer):validated_data.pop("use_template", None) # Remove attribute if presentgrid_spacing = validated_data.pop("grid_spacing", None)layout_compaction = validated_data.pop("layout_compaction", None)- if grid_spacing is not None or layout_compaction is not None:+ group_display = validated_data.pop("group_display", None)+ if grid_spacing is not None or layout_compaction is not None or group_display is not None:validated_data["customization"] = {**normalize_dashboard_customization(instance.customization),**({"tile_spacing": grid_spacing} if grid_spacing is not None else {}),**({"layout_compaction": layout_compaction} if layout_compaction is not None else {}),+ **({"group_display": group_display} if group_display is not None else {}),}if "groups" in validated_data:validated_data["customization"] = _with_groups(@@ -2254,6 +2287,18 @@ class DashboardSerializer(DashboardMetadataSerializer):team=instance.team,request=self.context["request"],)+ if group_display is not None and group_display != previous_group_display:+ report_user_action(+ user,+ "dashboard group display configured",+ {+ "dashboard_id": instance.id,+ "previous_group_display": previous_group_display,+ "group_display": group_display,+ },+ team=instance.team,+ request=self.context["request"],+ )if being_deleted:report_user_action(user,diff --git a/products/dashboards/backend/customization.py b/products/dashboards/backend/customization.pyindex b7725ffe2a0b..d401eb29b82b 100644--- a/products/dashboards/backend/customization.py+++ b/products/dashboards/backend/customization.py@@ -1,10 +1,14 @@-from collections.abc import Mapping+from collections.abc import Collection, Mappingfrom typing import Anyfrom rest_framework import serializersfrom products.dashboards.backend.constants import MAX_GROUP_KEY_LENGTH, MAX_GROUPS-from products.dashboards.backend.models.dashboard import DASHBOARD_GRID_COMPACTION_MODES, DASHBOARD_GRID_SPACING_GAPS+from products.dashboards.backend.models.dashboard import (+ DASHBOARD_GRID_COMPACTION_MODES,+ DASHBOARD_GRID_SPACING_GAPS,+ DASHBOARD_TILE_GROUP_DISPLAY_MODES,+)from products.dashboards.backend.widget_specs.openapi import DASHBOARD_TILE_GROUP_DEFAULTS, DashboardTileGroupSerializer@@ -124,15 +128,20 @@ def stored_groups(customization: Any) -> dict[str, dict[str, Any]]:return stored+_CHOICE_SETTINGS: dict[str, Collection[str]] = {+ "tile_spacing": DASHBOARD_GRID_SPACING_GAPS,+ "layout_compaction": DASHBOARD_GRID_COMPACTION_MODES,+ "group_display": DASHBOARD_TILE_GROUP_DISPLAY_MODES,+}++def stored_customization(customization: Any) -> dict[str, Any]:customization = normalize_dashboard_customization(customization)- tile_spacing = customization.get("tile_spacing")- layout_compaction = customization.get("layout_compaction")- stored: dict[str, Any] = {}- if isinstance(tile_spacing, str) and tile_spacing in DASHBOARD_GRID_SPACING_GAPS:- stored["tile_spacing"] = tile_spacing- if isinstance(layout_compaction, str) and layout_compaction in DASHBOARD_GRID_COMPACTION_MODES:- stored["layout_compaction"] = layout_compaction+ stored: dict[str, Any] = {+ setting: customization[setting]+ for setting, choices in _CHOICE_SETTINGS.items()+ if isinstance(customization.get(setting), str) and customization[setting] in choices+ }groups = stored_groups(customization)if groups:stored["groups"] = groupsdiff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.pyindex ad93fadaf129..9bc601d80c22 100644--- a/products/dashboards/backend/models/dashboard.py+++ b/products/dashboards/backend/models/dashboard.py@@ -34,6 +34,14 @@ class LayoutCompaction(models.TextChoices):DASHBOARD_GRID_COMPACTION_MODES = tuple(LayoutCompaction.values)+class TileGroupDisplay(models.TextChoices):+ SECTIONS = "sections", "sections"+ TABS = "tabs", "tabs"+++DASHBOARD_TILE_GROUP_DISPLAY_MODES = tuple(TileGroupDisplay.values)++class DashboardTileGroupColor(models.TextChoices):BLUE = "blue", "Blue"PURPLE = "purple", "Purple"diff --git a/products/dashboards/backend/widget_specs/openapi.py b/products/dashboards/backend/widget_specs/openapi.pyindex 025bb1f88285..1a07bb29e24e 100644--- a/products/dashboards/backend/widget_specs/openapi.py+++ b/products/dashboards/backend/widget_specs/openapi.py@@ -16,6 +16,7 @@ from products.dashboards.backend.constants import (from products.dashboards.backend.models.dashboard import (DASHBOARD_GRID_COMPACTION_MODES,DASHBOARD_GRID_SPACING_GAPS,+ DASHBOARD_TILE_GROUP_DISPLAY_MODES,DashboardTileGroupColor,)from products.dashboards.backend.models.dashboard_tile import DashboardTileBadge@@ -498,6 +499,14 @@ class PatchedDashboardOpenApiSerializer(serializers.Serializer):"to the left, and stable preserves positions while moving colliding tiles."),)+ group_display = serializers.ChoiceField(+ choices=DASHBOARD_TILE_GROUP_DISPLAY_MODES,+ required=False,+ help_text=(+ "How tile groups show. sections shows each group as a band that opens and closes. tabs shows one "+ "group at a time, and tiles outside any group get their own first tab."+ ),+ )groups = serializers.DictField(child=DashboardTileGroupSerializer(),required=False,diff --git a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsxindex 8c5ac2fa8928..5f660fb2c7d1 100644--- a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx+++ b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx@@ -5,13 +5,14 @@ import { LemonTag } from '@posthog/lemon-ui'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'-import type { DashboardTileSpacing } from '~/types'+import type { DashboardTileSpacing, TileGroupDisplay } from '~/types'import {DASHBOARD_GRID_COMPACTION_LABELS,DASHBOARD_TILE_SPACING_LABELS,DashboardGridCompaction,type DashboardGridCompaction as DashboardGridCompactionType,+ TILE_GROUP_DISPLAY_LABELS,} from '../../dashboardCustomization'import { DashboardTileMovementPreview } from './DashboardTileMovementPreview'@@ -23,6 +24,11 @@ const TILE_SPACING_OPTIONS: { value: DashboardTileSpacing; label: string }[] = [{ value: 'wide', label: DASHBOARD_TILE_SPACING_LABELS.wide },]+const TILE_GROUP_DISPLAY_OPTIONS: { value: TileGroupDisplay; label: string }[] = [+ { value: 'sections', label: TILE_GROUP_DISPLAY_LABELS.sections },+ { value: 'tabs', label: TILE_GROUP_DISPLAY_LABELS.tabs },+]+const GRID_COMPACTION_OPTIONS: {value: DashboardGridCompactionTypelabel: JSX.Element@@ -64,9 +70,11 @@ const GRID_COMPACTION_OPTIONS: {]export function DashboardCustomizeMenu(): JSX.Element | null {- const { dashboard, canEditDashboard, currentLayoutSize } = useValues(dashboardLogic)+ const { dashboard, canEditDashboard, currentLayoutSize, tileGroupSections, tileGroupDisplay } =+ useValues(dashboardLogic)const layoutAvailable = currentLayoutSize !== 'xs'- const { changeDashboardGridCompaction, changeDashboardTileSpacing } = useActions(dashboardLogic)+ const { changeDashboardGridCompaction, changeDashboardTileSpacing, changeTileGroupDisplay } =+ useActions(dashboardLogic)if (!dashboard || !canEditDashboard) {return null}@@ -101,6 +109,19 @@ export function DashboardCustomizeMenu(): JSX.Element | null {) : (<p className="border-t pt-2 text-xs text-muted">Use a larger screen to move or resize tiles.</p>)}+ {tileGroupSections.length > 0 && (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t pt-2">+ <span className="text-xs text-muted whitespace-nowrap">Show groups as</span>+ <LemonRadio<TileGroupDisplay>+ value={tileGroupDisplay}+ onChange={changeTileGroupDisplay}+ options={TILE_GROUP_DISPLAY_OPTIONS}+ orientation="horizontal"+ className="flex-1 flex-wrap gap-x-3 gap-y-1"+ aria-label="Show groups as"+ />+ </div>+ )}</div>)}diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsxindex f30f4061a0ae..2e4a6bd9c5d6 100644--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx@@ -5,16 +5,8 @@ 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)]',-}+import type { DashboardTileGroupApi } from '../../generated/api.schemas'+import { TileGroupColorDot } from './TileGroupColorDot'interface DashboardTileGroupProps {group: DashboardTileGroupApi@@ -54,12 +46,7 @@ export function DashboardTileGroup({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])}- />- )}+ {group.color && <TileGroupColorDot color={group.color} className="mr-2" />}<span className="font-semibold">{group.title || tileCountLabel}</span></LemonButton>{group.title && collapsed && <span className="shrink-0 text-secondary text-xs">{tileCountLabel}</span>}diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsxnew file mode 100644index 000000000000..31637137cdee--- /dev/null+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx@@ -0,0 +1,40 @@+import { LemonTabs } from 'lib/lemon-ui/LemonTabs'++import { type DashboardSection, getTileGroupLabel } from '../../dashboardTileSections'+import { TileGroupColorDot } from './TileGroupColorDot'++interface DashboardTileGroupTabsProps {+ sections: DashboardSection[]+ activeSectionKey: string+ onSelect: (sectionKey: string) => void+ children: React.ReactNode+}++export function DashboardTileGroupTabs({+ sections,+ activeSectionKey,+ onSelect,+ children,+}: DashboardTileGroupTabsProps): JSX.Element {+ return (+ <section data-attr="dashboard-tile-group-tabs">+ <LemonTabs+ activeKey={activeSectionKey}+ onChange={onSelect}+ tabs={sections.map((section) => ({+ key: section.key,+ label:+ section.kind === 'group' ? (+ <span className="flex items-center gap-2">+ {section.group.color && <TileGroupColorDot color={section.group.color} />}+ {getTileGroupLabel(section.group, section.tiles.length)}+ </span>+ ) : (+ 'Overview'+ ),+ }))}+ />+ {children}+ </section>+ )+}diff --git a/products/dashboards/frontend/components/DashboardTileGroup/TileGroupColorDot.tsx b/products/dashboards/frontend/components/DashboardTileGroup/TileGroupColorDot.tsxnew file mode 100644index 000000000000..e9f119b3762c--- /dev/null+++ b/products/dashboards/frontend/components/DashboardTileGroup/TileGroupColorDot.tsx@@ -0,0 +1,22 @@+import clsx from 'clsx'++import type { 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)]',+}++export function TileGroupColorDot({+ color,+ className,+}: {+ color: DashboardTileGroupColorEnumApi+ className?: string+}): JSX.Element {+ return <span aria-hidden className={clsx('inline-block size-2 rounded-full', DOT_CLASS_NAMES[color], className)} />+}diff --git a/products/dashboards/frontend/dashboardCustomization.ts b/products/dashboards/frontend/dashboardCustomization.tsindex a268ee9f3932..136183b14e42 100644--- a/products/dashboards/frontend/dashboardCustomization.ts+++ b/products/dashboards/frontend/dashboardCustomization.ts@@ -2,7 +2,7 @@ import { cloneLayoutItem, horizontalCompactor, noCompactor } from 'react-grid-laimport type { Compactor, Layout, LayoutItem } from 'react-grid-layout'import { fastVerticalCompactor } from 'react-grid-layout/extras'-import type { DashboardTileSpacing } from '~/types'+import type { DashboardTileSpacing, TileGroupDisplay } from '~/types'export const DashboardGridCompaction = {Vertical: 'vertical',@@ -34,6 +34,11 @@ export const DASHBOARD_GRID_COMPACTION_LABELS: Record<DashboardGridCompaction, s[DashboardGridCompaction.Stable]: 'Free-form placement',}+export const TILE_GROUP_DISPLAY_LABELS: Record<TileGroupDisplay, string> = {+ sections: 'Sections',+ tabs: 'Tabs',+}+type GridOccupancy = Map<number, Array<LayoutItem | undefined>>const MAX_FREE_FORM_TILE_HEIGHT_ROWS = 100diff --git a/products/dashboards/frontend/dashboardTileSections.test.ts b/products/dashboards/frontend/dashboardTileSections.test.tsindex 33f7ca6508c6..72bfe59845f7 100644--- a/products/dashboards/frontend/dashboardTileSections.test.ts+++ b/products/dashboards/frontend/dashboardTileSections.test.ts@@ -8,6 +8,7 @@ import { DashboardGridCompaction, getDashboardGridCompactor } from './dashboardCimport {getCollapsedTileGroupKeys,getDashboardSections,+ getDashboardTabs,getLayoutAfterSectionChange,getLayoutAfterTileMove,getSectionLayouts,@@ -115,6 +116,27 @@ describe('dashboardTileSections', () => {expect(sectionSummary(tiles, layout, groups)).toEqual(expected)})+ it.each<Omit<SectionsCase, 'groups'>>([+ {+ name: 'gathers ungrouped tiles from around the groups into one first tab',+ tiles: [tile(1), tile(2, 'plans'), tile(3), tile(4, 'regions'), tile(5)],+ layout: [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4), box(4, 0, 6), box(5, 0, 8)],+ expected: ['tiles-ungrouped: 1,3,5', 'group-plans: 2', 'group-regions: 4'],+ },+ {+ name: 'shows only the groups when every tile is in one',+ tiles: [tile(1, 'plans'), tile(2, 'regions')],+ layout: [box(1, 0, 0), box(2, 0, 2)],+ expected: ['group-plans: 1', 'group-regions: 2'],+ },+ ])('getDashboardTabs $name', ({ tiles, layout, expected }) => {+ expect(+ getDashboardTabs(getDashboardSections({ tiles, layout, groups: undefined })).map(+ (section) => `${section.key}: ${section.tiles.map((t) => t.id).join(',')}`+ )+ ).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[] =>diff --git a/products/dashboards/frontend/dashboardTileSections.ts b/products/dashboards/frontend/dashboardTileSections.tsindex 98a419e2df2b..778cbc07552b 100644--- a/products/dashboards/frontend/dashboardTileSections.ts+++ b/products/dashboards/frontend/dashboardTileSections.ts@@ -91,6 +91,22 @@ export function getDashboardSections({return sections}+// Group keys can't hold a null character, so no real group shares this key.+export const UNGROUPED_TILES_TAB_KEY = '\u0000ungrouped'++export function getSectionGroupKey(section: DashboardSection): string {+ return section.kind === 'group' ? section.groupKey : UNGROUPED_TILES_TAB_KEY+}++/** Tabs show one group at a time, so tiles outside any group gather into one tab of their own, first. */+export function getDashboardTabs(sections: DashboardSection[]): DashboardSection[] {+ const ungroupedTiles = sections.flatMap((section) => (section.kind === 'tiles' ? section.tiles : []))+ const groupSections = sections.filter((section) => section.kind === 'group')+ return ungroupedTiles.length > 0+ ? [{ kind: 'tiles', key: 'tiles-ungrouped', tiles: ungroupedTiles }, ...groupSections]+ : groupSections+}+function moveToTop(layout: Layout): Layout {const top = Math.min(...layout.map((item) => item.y))return layout.map((item) => ({ ...item, y: item.y - top }))diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 95619f62ab32..845bdf3a0681 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -37,6 +37,17 @@ export const LayoutCompactionEnumApi = {Stable: 'stable',} as const+/**+ * * `sections` - sections+ * * `tabs` - tabs+ */+export type TileGroupDisplayEnumApi = (typeof TileGroupDisplayEnumApi)[keyof typeof TileGroupDisplayEnumApi]++export const TileGroupDisplayEnumApi = {+ Sections: 'sections',+ Tabs: 'tabs',+} as const+/*** * `blue` - Blue* * `purple` - Purple@@ -101,6 +112,11 @@ export interface DashboardCustomizationApi {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnumApi+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnumApi/** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings. */groups?: DashboardCustomizationApiGroups/** Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups. */@@ -530,6 +546,11 @@ export interface DashboardApi {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnumApi+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnumApi/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.* @nullable@@ -1330,6 +1351,11 @@ export interface PatchedPatchedDashboardOpenApiApi {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnumApi+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnumApi/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.* @nullablediff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex f497574dce90..f1cfb8c5beb5 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -49,6 +49,13 @@ export const DashboardTemplatesCreateBody = /* @__PURE__ */ zod.object({.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -160,6 +167,13 @@ export const DashboardTemplatesUpdateBody = /* @__PURE__ */ zod.object({.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -271,6 +285,13 @@ export const DashboardTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -432,6 +453,13 @@ export const DashboardsCreateBody = /* @__PURE__ */ zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -565,6 +593,13 @@ export const DashboardsUpdateBody = /* @__PURE__ */ zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -823,6 +858,13 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -2356,6 +2398,13 @@ export const DashboardsCreateFromTemplateJsonCreateBody = /* @__PURE__ */ zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -2496,6 +2545,13 @@ export const DashboardsCreateUnlistedDashboardCreateBody = /* @__PURE__ */ zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex c4d270db19bf..b55a506eb068 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -6179,6 +6179,11 @@ export namespace Schemas {* * `stable` - stable*/export type LayoutCompactionEnum = "vertical" | "horizontal" | "stable";+ /**+ * * `sections` - sections+ * * `tabs` - tabs+ */+ export type TileGroupDisplayEnum = "sections" | "tabs";/*** * `blue` - Blue* * `purple` - Purple@@ -6202,6 +6207,7 @@ export namespace Schemas {export type DashboardCustomization = Partial<{tile_spacing: TileSpacingEnum;layout_compaction: LayoutCompactionEnum;+ group_display: TileGroupDisplayEnum;groups: Record<string, DashboardTileGroup>;group_titles: Record<string, string>;}>;@@ -6285,6 +6291,10 @@ export namespace Schemas {* Serializer mixin that handles tags for objects.*/layout_compaction?: (LayoutCompactionEnum & unknown) | undefined;+ /**+ * Serializer mixin that handles tags for objects.+ */+ group_display?: (TileGroupDisplayEnum & unknown) | undefined;/*** Serializer mixin that handles tags for objects.*/@@ -19538,6 +19548,7 @@ export namespace Schemas {quick_filter_ids: Array<string> | null;grid_spacing: TileSpacingEnum;layout_compaction: LayoutCompactionEnum;+ group_display: TileGroupDisplayEnum;groups: Record<string, DashboardTileGroup> | null;group_titles: Record<string, string> | null;tiles: Array<DashboardPatchTileOpenApi>;diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5f9f9bb190ff..e50999289499 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29057,6 +29057,18 @@ export namespace Schemas {Stable: 'stable',} as const;+ /**+ * * `sections` - sections+ * * `tabs` - tabs+ */+ export type TileGroupDisplayEnum = typeof TileGroupDisplayEnum[keyof typeof TileGroupDisplayEnum];+++ export const TileGroupDisplayEnum = {+ Sections: 'sections',+ Tabs: 'tabs',+ } as const;+/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.*/@@ -29082,6 +29094,11 @@ export namespace Schemas {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnum;+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnum;/** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings. */groups?: DashboardCustomizationGroups;/** Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups. */@@ -29171,6 +29188,11 @@ export namespace Schemas {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnum;+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnum;/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.* @nullable@@ -88477,6 +88499,11 @@ export namespace Schemas {* * `horizontal` - horizontal* * `stable` - stable */layout_compaction?: LayoutCompactionEnum;+ /** How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.+ *+ * * `sections` - sections+ * * `tabs` - tabs */+ group_display?: TileGroupDisplayEnum;/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.* @nullablediff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 8bbb8b8b15af..daeb0f63e974 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -184,6 +184,13 @@ export const DashboardsCreateBody = () => zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),@@ -398,6 +405,13 @@ export const DashboardsPartialUpdateBody = () => zod.describe('How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'),+ group_display: zod+ .enum(['sections', 'tabs'])+ .describe('\* `sections` - sections\n\* `tabs` - tabs')+ .optional()+ .describe(+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'+ ),groups: zod.record(zod.string(),diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.tsindex a1f003020439..b2dd84aa23dc 100644--- a/services/mcp/src/tools/generated/dashboards.ts+++ b/services/mcp/src/tools/generated/dashboards.ts@@ -59,6 +59,9 @@ const dashboardCreate = (): ToolBase<if (params.layout_compaction !== undefined) {body['layout_compaction'] = params.layout_compaction}+ if (params.group_display !== undefined) {+ body['group_display'] = params.group_display+ }if (params.groups !== undefined) {body['groups'] = params.groups}@@ -615,6 +618,9 @@ const dashboardUpdate = (): ToolBase<if (params.layout_compaction !== undefined) {body['layout_compaction'] = params.layout_compaction}+ if (params.group_display !== undefined) {+ body['group_display'] = params.group_display+ }if (params.groups !== undefined) {body['groups'] = params.groups}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.jsonindex 8e311ef4b404..de4543e0f57d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json@@ -93,6 +93,11 @@"enum": ["tight", "condensed", "standard", "relaxed", "wide"],"type": "string"},+ "group_display": {+ "description": "How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n* `sections` - sections\n* `tabs` - tabs",+ "enum": ["sections", "tabs"],+ "type": "string"+ },"groups": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.jsonindex 0bcd741b4c2c..e0e7ccc59a88 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json@@ -123,6 +123,11 @@"enum": ["tight", "condensed", "standard", "relaxed", "wide"],"type": "string"},+ "group_display": {+ "description": "How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n* `sections` - sections\n* `tabs` - tabs",+ "enum": ["sections", "tabs"],+ "type": "string"+ },"groups": {"anyOf": [{