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 winner crown, cheeky hog and group titles on tiles (#114811)

Paul D'Ambra0ee609a6f0d0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index acc2421e3159..e588326e20c5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6926,6 +6926,14 @@ snapshots:
hash: v1.k794b7964.20c015c66f2a8df4b13180fe46f6ad7d23c008014120d2333305338bfd473eaa.jN29SgNagj6AhlrI5b50krX4pQlMrOA5O7iYLuVMai4
products-dashboards-tiles-image-tile-modal--existing-image--light:
hash: v1.k794b7964.a6f0232a7044b1a581e4beb9105ee9c00bbed9748fdfcd1c3c1a232acfa0333c.D40_QysPPcg1v2fjLF3-6qPyFXkBZ9rrdYat6l6djGU
+ products-dashboards-tiles-tile-decorations--cheeky-hog-on-hover--dark:
+ hash: v1.k794b7964.8143bc5de1bfcac35f1b2ab9b9513a70bf005f7c998776290346cf47f6844d19.qCySXkG3gQLbLrXK85AOJT5ILT_vXkW8WX6o4jVq214
+ products-dashboards-tiles-tile-decorations--cheeky-hog-on-hover--light:
+ hash: v1.k794b7964.0e28bdfc8b5eba2a60c9e4e16ff4bbeabd8ea4388588aa162e642daf06a79e3c.mGMlQpZDe7OSM0k9DShVQfiRN_dtROsqt4yJhdiskVc
+ products-dashboards-tiles-tile-decorations--winner-with-group-title--dark:
+ hash: v1.k794b7964.7849b79cba5174608f6adc5d93ee89b79e8dfe4212f68724a94ce214e2ed91a7.ASToewJSB0zxlpbxMYpaf5haa3paw1i1Yf8xFnb1Hyk
+ products-dashboards-tiles-tile-decorations--winner-with-group-title--light:
+ hash: v1.k794b7964.249113d15d84b891c0e61d69b070f260a23246f91695331c924273ab2db6ecec.296aB-zbbSUQFYuxU2s87U3_CKQzf4hZgo-KOi62qtQ
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/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scss
index 2d8bcda06427..da7adf152d2b 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.scss
+++ b/frontend/src/scenes/dashboard/DashboardItems.scss
@@ -12,16 +12,16 @@
}
.react-grid-layout {
+ --dashboard-hog-slide-duration: 200ms; // Also drives the hog's slide in DashboardTileDecorations.scss
+ --dashboard-tile-transition:
+ transform 220ms ease-out, width 220ms ease-out, height 220ms ease-out, border-color 100ms ease;
+
position: relative;
transition: height 100ms ease;
/* Preserve the tile border transition while spacing changes animate. */
&.dashboard-view-mode .react-grid-item {
- transition:
- transform 220ms ease-out,
- width 220ms ease-out,
- height 220ms ease-out,
- border-color 100ms ease;
+ transition: var(--dashboard-tile-transition);
/* Skip rendering for off-screen tiles during resize/reflow */
content-visibility: auto;
@@ -31,6 +31,29 @@
&:has(> .handle) {
content-visibility: visible;
}
+
+ /* Tile decorations draw outside the tile box, so the same paint clip would cut them off */
+ &:has(> .DashboardTileDecorations__group-title, > .DashboardTileDecorations__crown) {
+ content-visibility: visible;
+ }
+
+ /* The hog only shows while hovered. On leave, hold the lift for the hog's slide down (browsers without discrete content-visibility transitions hide it at once) */
+ &:where(:has(> .DashboardTileDecorations__hog)) {
+ &:hover {
+ content-visibility: visible;
+ transition-delay: 0s;
+ }
+
+ @supports (transition-behavior: allow-discrete) {
+ transition:
+ var(--dashboard-tile-transition),
+ content-visibility 0s linear var(--dashboard-hog-slide-duration) allow-discrete;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: var(--dashboard-tile-transition);
+ }
+ }
}
&.dashboard-tile-spacing-changing {
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 6ea4737e70f5..4278a5dff3d0 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -39,7 +39,9 @@ import { insightsModel } from '~/models/insightsModel'
import { DashboardLayoutSize, DashboardPlacement, DashboardType } from '~/types'
import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
+import { DashboardTileDecorations } from 'products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
+import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
@@ -101,6 +103,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
widgetResultsByTileId,
widgetRefreshStatus,
scrollToBottomSignal,
+ sizeKey,
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
@@ -260,6 +263,22 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
[gridGap, spacingFactor]
)
+ const widgetTilesShown = dashboardWidgetsEnabled && isWidgetTileVisibleOnPlacement(placement)
+ const activeBreakpoint = sizeKey ?? 'sm'
+ const groupTitlesByTileId = useMemo(
+ () =>
+ getGroupTitlesByTileId({
+ tiles: tiles || [],
+ layout: layouts[activeBreakpoint],
+ activeBreakpoint,
+ groupTitles: dashboard?.customization?.group_titles,
+ compactor: gridCompactor,
+ widgetTilesShown,
+ }),
+ [tiles, layouts, activeBreakpoint, dashboard?.customization?.group_titles, gridCompactor, widgetTilesShown]
+ )
+ const showDecorationSpace = hasTileDecorations({ tiles: tiles || [], groupTitlesByTileId, widgetTilesShown })
+
const showResizeHandles = layoutEditMode && !isMobileView && isEditablePlacement && !isLayoutZoomToggled
const showEditingControls = isEditablePlacement || layoutEditMode
const showDetailsControls =
@@ -470,7 +489,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
</LemonBanner>
)}
{mounted && (
- <div className="relative">
+ <div className={clsx('relative', showDecorationSpace && 'mt-10')}>
{layoutEditMode && !isMobileView && (
<GridBackground
width={gridWidth}
@@ -511,6 +530,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
return l.i == tile.id.toString()
})
+ const decorations = (
+ <DashboardTileDecorations
+ badge={tile.badge}
+ groupTitle={groupTitlesByTileId[tile.id]}
+ />
+ )
+
const commonTileProps = {
dashboardId: dashboard?.id,
canEditDashboard,
@@ -542,7 +568,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
onEnterEditModeFromEdge={onEnterEditModeFromEdge}
onDragHandleMouseDown={onDragHandleMouseDown}
showEditingControls={showEditingControls}
- />
+ >
+ {decorations}
+ </MemoizedDashboardErrorTileItem>
)
}
@@ -602,7 +630,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}
showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
{...commonTileProps}
- />
+ >
+ {decorations}
+ </MemoizedInsightCard>
)
}
@@ -627,7 +657,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- />
+ >
+ {decorations}
+ </MemoizedDashboardTextItem>
)
}
@@ -652,11 +684,13 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- />
+ >
+ {decorations}
+ </MemoizedDashboardButtonTileItem>
)
}
- if (widget && dashboardWidgetsEnabled && isWidgetTileVisibleOnPlacement(placement)) {
+ if (widget && widgetTilesShown) {
const runResult = widgetResultsByTileId[tile.id]
const refreshState = widgetRefreshStatus[tile.id]
@@ -700,7 +734,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
- />
+ >
+ {decorations}
+ </MemoizedDashboardWidgetItem>
)
}
})}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fffdfa3d737a..cce7bc364fd8 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2616,8 +2616,12 @@ export interface DashboardTile extends Tileable {
filters_overrides?: TileFilters
show_description?: boolean | null
transparent_background?: boolean | null
+ group_key?: string | null
+ badge?: DashboardTileBadge | null
}
+export type DashboardTileBadge = 'winner' | 'cheeky-hog'
+
export type DashboardWidgetType = 'insight' | 'text' | 'button_tile' | 'widget'
export interface DashboardWidgetModel {
@@ -2811,6 +2815,7 @@ export interface DashboardType extends DashboardBasicType {
customization?: {
tile_spacing?: DashboardTileSpacing
layout_compaction?: 'vertical' | 'horizontal' | 'stable'
+ group_titles?: Record<string, string>
}
}
diff --git a/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.scss b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.scss
new file mode 100644
index 000000000000..7aba572cb3d1
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.scss
@@ -0,0 +1,57 @@
+.DashboardTileDecorations__group-title {
+ position: absolute;
+ top: 0;
+ left: 2rem;
+ z-index: 10;
+ max-width: calc(100% - 4rem);
+ padding: 0 0.375rem;
+ overflow: hidden;
+ font-size: 0.75rem;
+ font-weight: 600;
+ line-height: 1.25rem;
+ color: var(--color-text-secondary);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ pointer-events: none;
+ background: var(--color-bg-surface-primary);
+ border: 1px solid var(--color-border-primary);
+ border-radius: var(--radius);
+ transform: translateY(-50%);
+}
+
+.DashboardTileDecorations__crown {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 10;
+ display: flex;
+ font-size: 1.5rem;
+ color: var(--color-text-warning);
+ pointer-events: none;
+ transform: translate(-35%, -50%) rotate(-20deg);
+}
+
+// The window clips the hog, so it slides up from behind the tile's top edge on hover.
+.DashboardTileDecorations__hog {
+ position: absolute;
+ right: 1rem;
+ bottom: 100%;
+ z-index: 10;
+ width: 3rem;
+ height: 2.25rem;
+ overflow: hidden;
+ pointer-events: none;
+
+ img {
+ transition: transform var(--dashboard-hog-slide-duration) ease-out;
+ transform: translateY(100%);
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+ }
+}
+
+.react-grid-item:hover .DashboardTileDecorations__hog img {
+ transform: translateY(0);
+}
diff --git a/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.stories.tsx b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.stories.tsx
new file mode 100644
index 000000000000..96253ef24775
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.stories.tsx
@@ -0,0 +1,116 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor } from '@testing-library/react'
+
+import { App } from 'scenes/App'
+import __dashboard1 from 'scenes/dashboard/__mocks__/dashboard1.json'
+import __dashboards from 'scenes/dashboard/__mocks__/dashboards.json'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
+import type { DashboardTileBadge } from '~/types'
+
+interface TileOverrides {
+ badge?: DashboardTileBadge
+ group_key?: string
+}
+
+const DASHBOARD_ID = 1
+const HOG_SLID_UP_TRANSFORM = 'matrix(1, 0, 0, 1, 0, 0)'
+const FIXED_REFRESH_TIME = '2023-02-01T00:00:00Z'
+const FIXED_CACHE_TARGET_AGE = '2023-02-02T00:00:00Z'
+
+function buildDashboard(
+ tileOverrides: Record<number, TileOverrides>,
+ customization?: Record<string, unknown>
+): Record<string, unknown> {
+ const fixture = __dashboard1 as unknown as { tiles: Record<string, any>[] } & Record<string, unknown>
+ return {
+ ...fixture,
+ customization,
+ tiles: fixture.tiles.map((tile) => ({
+ ...tile,
+ ...tileOverrides[tile.id],
+ is_cached: true,
+ insight: tile.insight && {
+ ...tile.insight,
+ last_refresh: FIXED_REFRESH_TIME,
+ is_cached: true,
+ cache_target_age: FIXED_CACHE_TARGET_AGE,
+ },
+ })),
+ }
+}
+
+function dashboardMocks(dashboard: Record<string, unknown>): ReturnType<typeof mswDecorator> {
+ const insights = (dashboard.tiles as Record<string, any>[]).flatMap((tile) => (tile.insight ? [tile.insight] : []))
+ return mswDecorator({
+ get: {
+ '/api/environments/:team_id/dashboards/': __dashboards as any,
+ [`/api/environments/:team_id/dashboards/${DASHBOARD_ID}/`]: dashboard,
+ '/api/environments/:team_id/insights/:id/': ({ params }) => {
+ const insight = insights.find((candidate) => String(candidate.id) === params.id)
+ return insight ? [200, insight] : [404, { detail: 'Insight not found' }]
+ },
+ '/api/environments/:team_id/session_recordings/': EMPTY_PAGINATED_RESPONSE,
+ '/api/environments/:team_id/insights/my_last_viewed/': [],
+ '/api/environments/:team_id/warehouse/variables/': [],
+ '/api/projects/:team_id/events_retention/': [200, { retention_months: null, retained_from: null }],
+ },
+ post: {
+ '/api/environments/:team_id/insights/cancel/': [201],
+ },
+ })
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Products/Dashboards/Tiles/Tile decorations',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-02-01',
+ pageUrl: urls.dashboard(DASHBOARD_ID),
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+export const WinnerWithGroupTitle: Story = {
+ decorators: [
+ dashboardMocks(
+ buildDashboard(
+ { 1: { badge: 'winner', group_key: 'launch' }, 2: { group_key: 'launch' } },
+ { group_titles: { launch: 'Launch metrics' } }
+ )
+ ),
+ ],
+ parameters: {
+ testOptions: {
+ waitForSelector: ['.DashboardTileDecorations__crown', '.DashboardTileDecorations__group-title'],
+ },
+ },
+}
+
+export const CheekyHogOnHover: Story = {
+ decorators: [dashboardMocks(buildDashboard({ 2: { badge: 'cheeky-hog' } }))],
+ parameters: {
+ testOptions: { waitForSelector: '.DashboardTileDecorations__hog' },
+ },
+ play: async () => {
+ // A play function cannot move the real pointer, so no browser :hover applies. This copies the hover rule's effect.
+ const hoverStyle = document.createElement('style')
+ hoverStyle.textContent = `
+ .react-grid-layout.dashboard-view-mode .react-grid-item:has(> .DashboardTileDecorations__hog) { content-visibility: visible; transition: none; }
+ .react-grid-item .DashboardTileDecorations__hog img { transform: translateY(0); }
+ `
+ document.head.append(hoverStyle)
+ await waitFor(() => {
+ const hog = document.querySelector('.DashboardTileDecorations__hog img')
+ if (!hog || getComputedStyle(hog).transform !== HOG_SLID_UP_TRANSFORM) {
+ throw new Error('The hog has not finished sliding up')
+ }
+ })
+ },
+}
diff --git a/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.tsx b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.tsx
new file mode 100644
index 000000000000..3fdcf568d2f0
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileDecorations/DashboardTileDecorations.tsx
@@ -0,0 +1,38 @@
+import './DashboardTileDecorations.scss'
+
+import * as hooligan from '@posthog/brand/hoggies/png/hooligan'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+
+import type { DashboardTileBadge } from '~/types'
+
+const CheekyHog = pngHoggie(hooligan)
+
+interface DashboardTileDecorationsProps {
+ badge?: DashboardTileBadge | null
+ groupTitle?: string
+}
+
+export function DashboardTileDecorations({ badge, groupTitle }: DashboardTileDecorationsProps): JSX.Element | null {
+ if (!badge && !groupTitle) {
+ return null
+ }
+ return (
+ <>
+ {groupTitle && <div className="DashboardTileDecorations__group-title">{groupTitle}</div>}
+ {badge === 'winner' && (
+ <div className="DashboardTileDecorations__crown" role="img" aria-label="Winner">
+ {/* IconCrown is an outline with a cut-out, so this draws only its outer contour to get a solid crown. */}
+ <svg className="LemonIcon" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
+ <path d="M12 3a.75.75 0 0 1 .628.34l3.86 5.903 5.384-3.14a.75.75 0 0 1 1.113.798l-2.399 11.7A1.75 1.75 0 0 1 18.872 20H5.128a1.75 1.75 0 0 1-1.714-1.399l-2.399-11.7a.75.75 0 0 1 1.113-.799l5.384 3.141 3.86-5.903A.75.75 0 0 1 12 3Z" />
+ </svg>
+ </div>
+ )}
+ {badge === 'cheeky-hog' && (
+ <div className="DashboardTileDecorations__hog" aria-hidden>
+ <CheekyHog className="w-12 h-12" />
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardTileGroups.test.ts b/products/dashboards/frontend/dashboardTileGroups.test.ts
new file mode 100644
index 000000000000..2339eb0b92dd
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileGroups.test.ts
@@ -0,0 +1,158 @@
+import type { Layout } from 'react-grid-layout'
+
+import { calculateLayouts } from 'scenes/dashboard/tileLayouts'
+
+import type { DashboardLayoutSize, DashboardTile, DashboardWidgetModel, TileLayout } from '~/types'
+
+import { DashboardGridCompaction, getDashboardGridCompactor } from './dashboardCustomization'
+import { getGroupTitlesByTileId, hasTileDecorations } from './dashboardTileGroups'
+
+const tile = (id: number, group_key: string | null): DashboardTile =>
+ ({ id, group_key, layouts: {}, color: null }) as DashboardTile
+
+const widgetTile = (id: number, group_key: string): DashboardTile =>
+ ({ ...tile(id, group_key), widget: {} as DashboardWidgetModel }) as DashboardTile
+
+const textTile = (id: number, group_key: string | null, sm: Omit<TileLayout, 'i'>): DashboardTile =>
+ ({ ...tile(id, group_key), text: { body: 'text' }, layouts: { sm: { i: String(id), ...sm } } }) as DashboardTile
+
+const tilesAboveAGap = (): DashboardTile[] => [
+ textTile(1, 'plans', { x: 0, y: 5, w: 6, h: 2 }),
+ textTile(2, 'plans', { x: 6, y: 4, w: 6, h: 2 }),
+ textTile(3, null, { x: 6, y: 0, w: 6, h: 4 }),
+]
+
+interface GroupTitlesCase {
+ name: string
+ tiles: DashboardTile[]
+ layout: Layout | undefined
+ breakpoint?: DashboardLayoutSize
+ groupTitles: Record<string, string> | undefined
+ widgetTilesShown: boolean
+ expected: Record<number, string>
+}
+
+describe('dashboardTileGroups', () => {
+ it.each([
+ {
+ name: 'puts each title on the top-left tile of its group',
+ tiles: [tile(1, 'plans'), tile(2, 'plans'), tile(3, 'regions'), tile(4, null)],
+ layout: [
+ { i: '1', x: 4, y: 0, w: 4, h: 2 },
+ { i: '2', x: 0, y: 0, w: 4, h: 2 },
+ { i: '3', x: 0, y: 2, w: 4, h: 2 },
+ { i: '4', x: 0, y: 4, w: 4, h: 2 },
+ ],
+ groupTitles: { plans: 'Pricing plans', regions: 'Regions' },
+ widgetTilesShown: true,
+ expected: { 2: 'Pricing plans', 3: 'Regions' },
+ },
+ {
+ name: 'skips groups without a title',
+ tiles: [tile(1, 'plans'), tile(2, 'untitled')],
+ layout: undefined,
+ groupTitles: { plans: 'Pricing plans' } as Record<string, string>,
+ widgetTilesShown: true,
+ expected: { 1: 'Pricing plans' },
+ },
+ {
+ name: 'draws nothing when the dashboard has no group titles',
+ tiles: [tile(1, 'plans')],
+ layout: undefined,
+ groupTitles: undefined,
+ widgetTilesShown: true,
+ expected: {},
+ },
+ ...['__proto__', 'constructor', 'toString'].map((groupKey) => ({
+ name: `ignores the inherited object key ${groupKey}`,
+ tiles: [tile(1, groupKey)],
+ layout: undefined,
+ groupTitles: { plans: 'Pricing plans' } as Record<string, string>,
+ widgetTilesShown: true,
+ expected: {},
+ })),
+ ...[
+ { widgetTilesShown: true, expected: { 1: 'Pricing plans' } },
+ { widgetTilesShown: false, expected: { 2: 'Pricing plans' } },
+ ].map(({ widgetTilesShown, expected }) => ({
+ name: `puts the title on the first rendered tile when widget tiles shown is ${widgetTilesShown}`,
+ tiles: [widgetTile(1, 'plans'), tile(2, 'plans')],
+ layout: [
+ { i: '1', x: 0, y: 0, w: 6, h: 2 },
+ { i: '2', x: 6, y: 0, w: 6, h: 2 },
+ ],
+ groupTitles: { plans: 'Pricing plans' },
+ widgetTilesShown,
+ expected,
+ })),
+ ...[
+ { breakpoint: 'sm' as DashboardLayoutSize, expected: { 1: 'Pricing plans' } },
+ { breakpoint: 'xs' as DashboardLayoutSize, expected: { 2: 'Pricing plans' } },
+ ].map(({ breakpoint, expected }) => {
+ const tiles = tilesAboveAGap()
+ return {
+ name: `puts the title on the first tile the ${breakpoint} grid renders after compaction`,
+ tiles,
+ layout: calculateLayouts(tiles)[breakpoint],
+ breakpoint,
+ groupTitles: { plans: 'Pricing plans' },
+ widgetTilesShown: true,
+ expected,
+ }
+ }),
+ ] as GroupTitlesCase[])(
+ '$name',
+ ({ tiles, layout, breakpoint = 'sm', groupTitles, widgetTilesShown, expected }) => {
+ expect(
+ getGroupTitlesByTileId({
+ tiles,
+ layout,
+ activeBreakpoint: breakpoint,
+ groupTitles,
+ compactor: getDashboardGridCompactor(DashboardGridCompaction.Vertical),
+ widgetTilesShown,
+ })
+ ).toEqual(expected)
+ }
+ )
+
+ it.each([
+ {
+ name: 'a title on a rendered tile',
+ tiles: [tile(1, 'plans')],
+ groupTitlesByTileId: { 1: 'Plans' } as Record<number, string>,
+ widgetTilesShown: true,
+ expected: true,
+ },
+ {
+ name: 'a badge on a rendered tile',
+ tiles: [{ ...tile(1, null), badge: 'winner' } as DashboardTile],
+ groupTitlesByTileId: {},
+ widgetTilesShown: true,
+ expected: true,
+ },
+ {
+ name: 'a badge on a widget tile that is shown',
+ tiles: [{ ...widgetTile(1, 'plans'), badge: 'winner' } as DashboardTile],
+ groupTitlesByTileId: {},
+ widgetTilesShown: true,
+ expected: true,
+ },
+ {
+ name: 'a badge on a widget tile that is hidden',
+ tiles: [{ ...widgetTile(1, 'plans'), badge: 'winner' } as DashboardTile],
+ groupTitlesByTileId: {},
+ widgetTilesShown: false,
+ expected: false,
+ },
+ {
+ name: 'no title and no badge',
+ tiles: [tile(1, null)],
+ groupTitlesByTileId: {},
+ widgetTilesShown: true,
+ expected: false,
+ },
+ ])('hasTileDecorations is $expected for $name', ({ tiles, groupTitlesByTileId, widgetTilesShown, expected }) => {
+ expect(hasTileDecorations({ tiles, groupTitlesByTileId, widgetTilesShown })).toBe(expected)
+ })
+})
diff --git a/products/dashboards/frontend/dashboardTileGroups.ts b/products/dashboards/frontend/dashboardTileGroups.ts
new file mode 100644
index 000000000000..7f1a828ab55e
--- /dev/null
+++ b/products/dashboards/frontend/dashboardTileGroups.ts
@@ -0,0 +1,90 @@
+import { cloneLayout } from 'react-grid-layout'
+import type { Compactor, Layout } from 'react-grid-layout'
+import { correctBounds } from 'react-grid-layout/core'
+
+import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
+
+import type { DashboardLayoutSize, DashboardTile } from '~/types'
+
+interface GroupTitlesInput {
+ tiles: DashboardTile[]
+ layout: Layout | undefined
+ activeBreakpoint: DashboardLayoutSize
+ groupTitles: Record<string, string> | undefined
+ compactor: Compactor
+ widgetTilesShown: boolean
+}
+
+function getGroupTitle(groupTitles: Record<string, string>, groupKey: string): string | undefined {
+ const title: unknown = Object.hasOwn(groupTitles, groupKey) ? groupTitles[groupKey] : undefined
+ return typeof title === 'string' && title ? title : undefined
+}
+
+/** Repeats what the grid does before it paints: drop tiles it does not render, then clamp and compact. */
+function getRenderedLayout(
+ layout: Layout | undefined,
+ breakpoint: DashboardLayoutSize,
+ renderedTileIds: Set<string>,
+ compactor: Compactor
+): Layout {
+ const cols = BREAKPOINT_COLUMN_COUNTS[breakpoint]
+ const renderedLayout = cloneLayout((layout ?? []).filter((item) => renderedTileIds.has(item.i)))
+ return compactor.compact(correctBounds(renderedLayout, { cols }), cols)
+}
+
+/** Maps each titled group to its top-left rendered tile, so the dashboard draws the group title once. */
+export function getGroupTitlesByTileId({
+ tiles,
+ layout,
+ activeBreakpoint,
+ groupTitles,
+ compactor,
+ widgetTilesShown,
+}: GroupTitlesInput): Record<number, string> {
+ if (!groupTitles) {
+ return {}
+ }
+ const renderedTiles = tiles.filter((tile) => !tile.widget || widgetTilesShown)
+ const renderedLayout = getRenderedLayout(
+ layout,
+ activeBreakpoint,
+ new Set(renderedTiles.map((tile) => tile.id.toString())),
+ compactor
+ )
+ const positions = new Map(renderedLayout.map((item) => [item.i, item]))
+ const firstTileByGroup = new Map<string, { tileId: number; title: string; y: number; x: number }>()
+
+ for (const tile of renderedTiles) {
+ if (!tile.group_key) {
+ continue
+ }
+ const title = getGroupTitle(groupTitles, tile.group_key)
+ if (!title) {
+ continue
+ }
+ const position = positions.get(tile.id.toString())
+ const y = position?.y ?? Infinity
+ const x = position?.x ?? Infinity
+ const current = firstTileByGroup.get(tile.group_key)
+ if (!current || y < current.y || (y === current.y && x < current.x)) {
+ firstTileByGroup.set(tile.group_key, { tileId: tile.id, title, y, x })
+ }
+ }
+
+ return Object.fromEntries([...firstTileByGroup.values()].map(({ tileId, title }) => [tileId, title]))
+}
+
+export function hasTileDecorations({
+ tiles,
+ groupTitlesByTileId,
+ widgetTilesShown,
+}: {
+ tiles: DashboardTile[]
+ groupTitlesByTileId: Record<number, string>
+ widgetTilesShown: boolean
+}): boolean {
+ return (
+ Object.keys(groupTitlesByTileId).length > 0 ||
+ tiles.some((tile) => !!tile.badge && (!tile.widget || widgetTilesShown))
+ )
+}