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): add customizable dashboard compaction modes (#83965)

Matt Puab3ff6951f353
diff --git a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
index 272c4957a015..290dcd3e33b4 100644
--- a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
@@ -3,6 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import { BindLogic } from 'kea'
+import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
@@ -73,6 +74,9 @@ describe('DashboardHeader', () => {
})
initKeaTests()
featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DASHBOARD_CUSTOMIZATION], {
+ [FEATURE_FLAGS.DASHBOARD_CUSTOMIZATION]: true,
+ })
})
afterEach(() => {
@@ -171,7 +175,7 @@ describe('DashboardHeader', () => {
dashboardMode: DashboardMode.Edit,
dashboardModeSource: DashboardEventSource.DashboardFilters,
canEdit: true,
- visible: ['dashboard-add-tile'],
+ visible: ['dashboard-add-tile', 'dashboard-edit-layout-customize-dropdown'],
notVisible: [
'dashboard-edit-mode-discard',
'dashboard-edit-mode-save',
@@ -185,7 +189,12 @@ describe('DashboardHeader', () => {
dashboardMode: DashboardMode.Edit,
dashboardModeSource: DashboardEventSource.SceneCommonButtons,
canEdit: true,
- visible: ['dashboard-edit-mode-discard', 'dashboard-edit-mode-save', 'dashboard-add-tile'],
+ visible: [
+ 'dashboard-edit-mode-discard',
+ 'dashboard-edit-mode-save',
+ 'dashboard-edit-layout-customize-dropdown',
+ 'dashboard-add-tile',
+ ],
notVisible: ['dashboard-share-button', 'add-text-tile-to-dashboard', 'dashboard-add-graph-header'],
},
{
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
index b44dd07ca629..95f80cbac248 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -222,12 +222,35 @@ export function DashboardEditSaveCancelButtons({
}
export function EditModeActions(): JSX.Element {
- const { layoutEditMode } = useValues(dashboardLogic)
+ const { layoutEditMode, tiles, dashboardCustomizeMenuOpen } = useValues(dashboardLogic)
+ const { setDashboardCustomizeMenuOpen } = useActions(dashboardLogic)
+ const dashboardCustomizationEnabled = useFeatureFlag('DASHBOARD_CUSTOMIZATION')
return (
<>
<DashboardSubscribeButton />
{layoutEditMode && <DashboardEditSaveCancelButtons />}
+ {dashboardCustomizationEnabled && (
+ <LemonMenu
+ items={[{ label: () => <DashboardCustomizeMenu /> }]}
+ closeOnClickInside={false}
+ placement="bottom-end"
+ visible={dashboardCustomizeMenuOpen}
+ onVisibilityChange={setDashboardCustomizeMenuOpen}
+ >
+ <LemonButton
+ type="secondary"
+ data-attr="dashboard-edit-layout-customize-dropdown"
+ size="small"
+ icon={<IconGridMasonry fontSize="16" />}
+ disabledReason={
+ tiles.length === 0 ? 'Add at least one tile to customize this dashboard' : undefined
+ }
+ >
+ Customize
+ </LemonButton>
+ </LemonMenu>
+ )}
<DashboardAddTileButton />
</>
)
diff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scss
index 5403d392629f..6458611076aa 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.scss
+++ b/frontend/src/scenes/dashboard/DashboardItems.scss
@@ -32,6 +32,22 @@
content-visibility: visible;
}
}
+
+ &.dashboard-tile-spacing-changing {
+ transition: none;
+
+ .react-grid-item {
+ transition: none;
+ }
+ }
+
+ &.dashboard-layout-interaction .react-grid-item {
+ transition: none;
+ }
+
+ &.dashboard-layout-settling .react-grid-item:not(.react-draggable-dragging, .resizing) {
+ transition: transform 180ms ease-out;
+ }
}
.react-grid-item.cssTransforms {
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 157d7718e486..c5eb5d60bbbe 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -194,7 +194,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const { width, containerRef, mounted } = useContainerWidth()
const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =
- useDashboardLayoutInteraction({ layoutEditMode, updateLayouts })
+ useDashboardLayoutInteraction({
+ layoutEditMode,
+ layoutCompaction: dashboard?.customization?.layout_compaction,
+ updateLayouts,
+ })
// Debounce width changes to the grid. Rapidly crossing the width causes tiles to stay squashed at 1-column
// width. Debouncing avoids this and reduces unnecessary re-layouts during resize.
diff --git a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
index d411967abd6a..45adbff53878 100644
--- a/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
+++ b/frontend/src/scenes/dashboard/dashboardActivityDescriber.tsx
@@ -2,7 +2,10 @@ import posthog from 'posthog-js'
import { DashboardFilter, HogQLVariable } from 'src/queries/schema/schema-general'
import { Link } from '@posthog/lemon-ui'
-import { DASHBOARD_TILE_SPACING_LABELS } from '@posthog/products-dashboards/frontend/dashboardCustomization'
+import {
+ DASHBOARD_GRID_COMPACTION_LABELS,
+ DASHBOARD_TILE_SPACING_LABELS,
+} from '@posthog/products-dashboards/frontend/dashboardCustomization'
import {
ActivityChange,
@@ -161,17 +164,28 @@ const dashboardActionsMapping: Record<
last_viewed_at: () => null,
quick_filter_ids: () => null,
customization: function onChangedCustomization(change) {
- const customization = change?.after as DashboardType['customization']
- if (!customization?.tile_spacing) {
- return null
+ const before = change?.before as DashboardType['customization']
+ const after = change?.after as DashboardType['customization']
+ const description: Description[] = []
+ if (after?.layout_compaction && after.layout_compaction !== before?.layout_compaction) {
+ description.push(
+ <>
+ changed tile movement to{' '}
+ <strong>{DASHBOARD_GRID_COMPACTION_LABELS[after.layout_compaction]}</strong>
+ </>
+ )
}
- return {
- description: [
+ if (after?.tile_spacing && after.tile_spacing !== before?.tile_spacing) {
+ if (description.length > 0) {
+ description.push(' and ')
+ }
+ description.push(
<>
- changed tile density to <strong>{DASHBOARD_TILE_SPACING_LABELS[customization.tile_spacing]}</strong>
- </>,
- ],
+ changed tile density to <strong>{DASHBOARD_TILE_SPACING_LABELS[after.tile_spacing]}</strong>
+ </>
+ )
}
+ return description.length > 0 ? { description } : null
},
}
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index f2929e4f2128..ccc90d38cc0a 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -40,6 +40,8 @@ import {
QueryBasedInsightModel,
} from '~/types'
+import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+
import { dashboardResult, insightOnDashboard, tileFromInsight } from './dashboardLogic.testHelpers'
const TEXT_TILE: DashboardTile<QueryBasedInsightModel> = {
@@ -388,6 +390,7 @@ describe('dashboardLogic', () => {
expect(api.update).toHaveBeenCalledTimes(1)
expect(api.update).toHaveBeenCalledWith(`api/environments/${MOCK_TEAM_ID}/dashboards/5`, {
+ layout_compaction: DashboardGridCompaction.Vertical,
grid_spacing: 'relaxed',
})
expect(reportTileDensityConfigured).toHaveBeenCalledWith('relaxed')
@@ -416,6 +419,68 @@ describe('dashboardLogic', () => {
}
})
+ it('previews layout compaction immediately and persists only the final choice', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ ;(api.update as jest.Mock).mockClear()
+ jest.useFakeTimers()
+
+ try {
+ logic.actions.setDashboardGridCompaction(DashboardGridCompaction.Vertical)
+ logic.actions.saveDashboardGridCompaction(DashboardGridCompaction.Vertical)
+ logic.actions.setDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+ logic.actions.saveDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+
+ expect(logic.values.dashboard?.customization?.layout_compaction).toBe(
+ DashboardGridCompaction.Horizontal
+ )
+ expect(api.update).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(750)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledTimes(1)
+ expect(api.update).toHaveBeenCalledWith(`api/environments/${MOCK_TEAM_ID}/dashboards/5`, {
+ layout_compaction: DashboardGridCompaction.Horizontal,
+ grid_spacing: 'standard',
+ })
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('persists the latest movement mode after a save is already in flight', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ let resolveFirstSave: (dashboard: DashboardType<QueryBasedInsightModel>) => void = () => {
+ throw new Error('First save resolver is unavailable')
+ }
+ const firstSave = new Promise<DashboardType<QueryBasedInsightModel>>((resolve) => {
+ resolveFirstSave = resolve
+ })
+ ;(api.update as jest.Mock).mockImplementationOnce(() => firstSave)
+ jest.useFakeTimers()
+
+ try {
+ logic.actions.setDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+ logic.actions.saveDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+ await jest.advanceTimersByTimeAsync(750)
+
+ logic.actions.setDashboardGridCompaction(DashboardGridCompaction.Stable)
+ logic.actions.saveDashboardGridCompaction(DashboardGridCompaction.Stable)
+ await jest.advanceTimersByTimeAsync(750)
+
+ resolveFirstSave(logic.values.dashboard!)
+ await jest.advanceTimersByTimeAsync(750)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenLastCalledWith(`api/environments/${MOCK_TEAM_ID}/dashboards/5`, {
+ layout_compaction: DashboardGridCompaction.Stable,
+ grid_spacing: 'standard',
+ })
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('saving without changes does not call api', async () => {
await expectLogic(logic).toFinishAllListeners()
@@ -1168,6 +1233,64 @@ describe('dashboardLogic', () => {
})
})
+ describe('changeDashboardGridCompaction action', () => {
+ let dialogOpenSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ dialogOpenSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ dialogOpenSpy.mockRestore()
+ })
+
+ const moveFirstTile = (): void => {
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const currentLayouts = logic.values.layouts
+ logic.actions.updateLayouts({
+ ...currentLayouts,
+ sm: currentLayouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: (layout.x ?? 0) + 1 } : layout
+ ),
+ })
+ }
+
+ it('changes the movement mode without a prompt when the layout is saved', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.changeDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+ }).toDispatchActions([
+ logic.actionCreators.setDashboardGridCompaction(DashboardGridCompaction.Horizontal),
+ logic.actionCreators.saveDashboardGridCompaction(DashboardGridCompaction.Horizontal),
+ ])
+
+ expect(dialogOpenSpy).not.toHaveBeenCalled()
+ })
+
+ it('prompts before changing the movement mode when the layout is unsaved', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, moveFirstTile).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.changeDashboardGridCompaction(DashboardGridCompaction.Horizontal)
+ }).toNotHaveDispatchedActions([
+ logic.actionCreators.setDashboardGridCompaction(DashboardGridCompaction.Horizontal),
+ logic.actionCreators.saveDashboardGridCompaction(DashboardGridCompaction.Horizontal),
+ ])
+
+ expect(dialogOpenSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'Change tile movement?',
+ description: 'Changing this setting discards your unsaved tile layout changes.',
+ })
+ )
+
+ const dialogProps = dialogOpenSpy.mock.calls.at(-1)?.[0]
+ dialogProps?.primaryButton?.onClick?.({} as React.MouseEvent<HTMLButtonElement>)
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ hasUnsavedLayoutChanges: false })
+ })
+ })
+
describe('cancelEditMode action', () => {
// The discard prompt renders a real dialog into its own React root, whose async
// updates land outside act(); these tests only assert dispatched actions
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index a8d760717a2b..69ecae43a302 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -19,6 +19,7 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'
import { CombinedLocation } from 'kea-router/lib/utils'
import uniqBy from 'lodash.uniqby'
+import posthog from 'posthog-js'
import { ResponsiveLayouts } from 'react-grid-layout'
import type { Layout } from 'react-grid-layout'
@@ -112,6 +113,8 @@ import {
TileLayout,
} from '~/types'
+import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { Node } from '../../queries/schema/schema-general'
import { getResponseBytes, sortDayJsDates } from '../insights/utils'
@@ -270,6 +273,7 @@ export interface dashboardLogicValues {
containerWidth: number | null
currentLayoutSize: 'sm' | 'xs'
dashboard: DashboardType<QueryBasedInsightModel> | null
+ dashboardCustomizeMenuOpen: boolean
dashboardFailedToLoad: boolean
dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>
dashboardLoadData: {
@@ -424,6 +428,9 @@ export interface dashboardLogicActions {
cancelEditMode: () => {
value: true
}
+ changeDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
+ layoutCompaction: DashboardGridCompaction
+ }
clearAddWidgetSelectedTypes: () => {
value: true
}
@@ -669,6 +676,9 @@ export interface dashboardLogicActions {
variables?: unknown
} | null
}
+ saveDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
+ layoutCompaction: DashboardGridCompaction
+ }
saveDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => {
tileSpacing: DashboardTileSpacing
}
@@ -712,6 +722,12 @@ export interface dashboardLogicActions {
setButtonTileId: (buttonTileId: number | 'new' | null) => {
buttonTileId: number | 'new' | null
}
+ setDashboardCustomizeMenuOpen: (open: boolean) => {
+ open: boolean
+ }
+ setDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
+ layoutCompaction: DashboardGridCompaction
+ }
setDashboardMode: (
mode: DashboardMode | null,
source: DashboardEventSource
@@ -1311,6 +1327,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
/** Update the dashboard in dashboardsModel with given payload. */
triggerDashboardUpdate: (payload) => ({ payload }),
saveDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => ({ tileSpacing }),
+ saveDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => ({ layoutCompaction }),
+ setDashboardCustomizeMenuOpen: (open: boolean) => ({ open }),
+ changeDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => ({ layoutCompaction }),
updateDashboardTags: (tags: string[]) => ({ tags }),
/** Update page visibility for virtualized rendering. */
setPageVisibility: (visible: boolean) => ({ visible }),
@@ -1383,6 +1402,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
setBreakdownColorConfig: (config: BreakdownColorConfig) => ({ config }),
setDataColorThemeId: (dataColorThemeId: number | null) => ({ dataColorThemeId }),
setDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => ({ tileSpacing }),
+ setDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => ({ layoutCompaction }),
setDashboardTileSpacingSaving: (saving: boolean) => ({ saving }),
restoreTemporaryColorState: (colors: BreakdownColorConfig[], themeId: { themeId: number | null } | null) => ({
colors,
@@ -1931,6 +1951,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
customization: { ...state.customization, tile_spacing: tileSpacing },
}
: state,
+ setDashboardGridCompaction: (state, { layoutCompaction }) =>
+ state
+ ? {
+ ...state,
+ customization: { ...state.customization, layout_compaction: layoutCompaction },
+ }
+ : state,
removeTile: (state, { tile }) => {
// Optimistically drop the tile so the grid reflows immediately; the loader rolls back on failure.
return {
@@ -2163,6 +2190,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
},
],
+ dashboardCustomizeMenuOpen: [
+ false,
+ {
+ setDashboardCustomizeMenuOpen: (_, { open }) => open,
+ setDashboardMode: () => false,
+ },
+ ],
pendingInsertion: [
null as PendingInsertion | null,
{
@@ -3723,7 +3757,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
try {
const dashboard = await api.update<DashboardType<QueryBasedInsightModel>>(
`api/environments/${values.currentTeamId}/dashboards/${props.id}`,
- { grid_spacing: tileSpacing }
+ {
+ grid_spacing: tileSpacing,
+ layout_compaction:
+ values.dashboard?.customization?.layout_compaction ?? DashboardGridCompaction.Vertical,
+ }
)
dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard))
if (tileSpacing !== 'standard') {
@@ -3747,6 +3785,48 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
}
},
+ saveDashboardGridCompaction: async ({ layoutCompaction }, breakpoint) => {
+ await breakpoint(750)
+
+ if (cache.dashboardGridCompactionSaveInFlight) {
+ cache.pendingDashboardGridCompaction = layoutCompaction
+ return
+ }
+
+ const persistedDashboard = dashboardsModel.values.rawDashboards[props.id]
+ const persistedLayoutCompaction =
+ persistedDashboard && 'customization' in persistedDashboard
+ ? (persistedDashboard.customization?.layout_compaction ?? DashboardGridCompaction.Vertical)
+ : DashboardGridCompaction.Vertical
+ cache.dashboardGridCompactionSaveInFlight = true
+ try {
+ const dashboard = await api.update<DashboardType<QueryBasedInsightModel>>(
+ `api/environments/${values.currentTeamId}/dashboards/${props.id}`,
+ {
+ layout_compaction: layoutCompaction,
+ grid_spacing: values.dashboard?.customization?.tile_spacing ?? 'standard',
+ }
+ )
+ dashboardsModel.actions.updateDashboardSuccess(getQueryBasedDashboard(dashboard))
+ } catch (error) {
+ posthog.captureException(error)
+ if (!cache.pendingDashboardGridCompaction) {
+ actions.setDashboardGridCompaction(persistedLayoutCompaction)
+ actions.loadDashboard({ action: DashboardLoadAction.Update })
+ }
+ lemonToast.error("Couldn't update tile movement. Try again.")
+ } finally {
+ cache.dashboardGridCompactionSaveInFlight = false
+ const pendingLayoutCompaction = cache.pendingDashboardGridCompaction as
+ | DashboardGridCompaction
+ | undefined
+ cache.pendingDashboardGridCompaction = undefined
+ if (pendingLayoutCompaction) {
+ actions.setDashboardGridCompaction(pendingLayoutCompaction)
+ actions.saveDashboardGridCompaction(pendingLayoutCompaction)
+ }
+ }
+ },
forceRefreshIfStale: () => {
// Dedupe: this listener can be invoked from multiple sources for the same
// freshness state — the post-load auto-trigger in refreshDashboardItems and
@@ -4233,6 +4313,36 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
})
},
+ changeDashboardGridCompaction: ({ layoutCompaction }) => {
+ const changeCompaction = (discardUnsavedLayoutChanges = false): void => {
+ if (discardUnsavedLayoutChanges) {
+ const savedSmLayout = Object.entries(values.dashboardLayouts).flatMap(([tileId, layouts]) =>
+ layouts?.sm ? [{ ...layouts.sm, i: tileId }] : []
+ )
+ actions.updateLayouts({ sm: savedSmLayout })
+ }
+ actions.setDashboardGridCompaction(layoutCompaction)
+ actions.saveDashboardGridCompaction(layoutCompaction)
+ }
+
+ if (!values.hasUnsavedLayoutChanges) {
+ changeCompaction()
+ return
+ }
+
+ actions.setDashboardCustomizeMenuOpen(false)
+ LemonDialog.open({
+ title: 'Change tile movement?',
+ description: 'Changing this setting discards your unsaved tile layout changes.',
+ primaryButton: {
+ children: 'Change mode',
+ onClick: () => changeCompaction(true),
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ },
setDashboardMode: async ({ mode, source }) => {
if (
mode === DashboardMode.Edit &&
diff --git a/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts b/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts
index 7d2e81911501..fe5a39d40f50 100644
--- a/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts
+++ b/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts
@@ -1,6 +1,6 @@
import { useCallback, useMemo, useRef } from 'react'
import type { MutableRefObject } from 'react'
-import { cloneLayoutItem, verticalCompactor } from 'react-grid-layout'
+import { cloneLayoutItem } from 'react-grid-layout'
import type { Compactor, Layout, LayoutItem } from 'react-grid-layout'
import {
@@ -12,10 +12,13 @@ import type { ResizeNeighbors } from 'scenes/dashboard/dashboardResizeCompactor'
import type { DashboardLayoutSize } from '~/types'
+import { DashboardGridCompaction, getDashboardGridCompactor } from 'products/dashboards/frontend/dashboardCustomization'
+
type InteractionKind = 'drag' | 'resize'
interface UseDashboardLayoutInteractionProps {
layoutEditMode: boolean
+ layoutCompaction?: DashboardGridCompaction
updateLayouts: (layouts: Partial<Record<DashboardLayoutSize, Layout>>) => void
}
@@ -29,6 +32,7 @@ interface DashboardLayoutInteraction {
export function useDashboardLayoutInteraction({
layoutEditMode,
+ layoutCompaction,
updateLayouts,
}: UseDashboardLayoutInteractionProps): DashboardLayoutInteraction {
const interactionInProgress = useRef(false)
@@ -39,26 +43,27 @@ export function useDashboardLayoutInteraction({
const activeItemId = useRef<string | null>(null)
const interactionKind = useRef<InteractionKind | null>(null)
- const gridCompactor = useMemo<Compactor>(
- () => ({
- ...verticalCompactor,
+ const gridCompactor = useMemo<Compactor>(() => {
+ const compactor = getDashboardGridCompactor(layoutCompaction ?? DashboardGridCompaction.Vertical)
+
+ return {
+ ...compactor,
compact: (layout: Layout, cols: number): Layout => {
const baseline = baselineLayout.current
const activeTileId = activeItemId.current
if (!baseline || !activeTileId) {
- return verticalCompactor.compact(layout, cols)
+ return compactor.compact(layout, cols)
}
const restoredLayout = restoreUnmovedItemPositions(layout, baseline, activeTileId, baselineById.current)
- const layoutForCompaction =
+ const resizedLayout =
interactionKind.current === 'resize'
? resizeNeighborToFitRow(restoredLayout, baseline, activeTileId, resizeNeighbors.current)
: restoredLayout
- return verticalCompactor.compact(layoutForCompaction, cols)
+ return compactor.compactInteraction(cols, activeTileId, restoredLayout, resizedLayout)
},
- }),
- []
- )
+ }
+ }, [layoutCompaction])
const handleLayoutChange = useCallback(
(_: unknown, newLayouts: Partial<Record<DashboardLayoutSize, Layout>>) => {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index d52ad4bcecb8..3d5fa46f32b4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2705,6 +2705,7 @@ export interface DashboardType<T = InsightModel> extends DashboardBasicType {
quick_filter_ids?: string[] | null
customization?: {
tile_spacing?: DashboardTileSpacing
+ layout_compaction?: 'vertical' | 'horizontal' | 'stable'
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index aa113893bfdb..dbc59c88cb45 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2873,6 +2873,9 @@ importers:
react-dom:
specifier: 18.3.1
version: 18.3.1([email protected])
+ react-grid-layout:
+ specifier: ^2.2.4
devDependencies:
'@storybook/react':
specifier: 'catalog:'
@@ -13522,10 +13525,12 @@ packages:
'@xmldom/[email protected]':
resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}
engines: {node: '>=10.0.0'}
+ deprecated: this version has critical issues, please update to the latest version
'@xmldom/[email protected]':
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
+ deprecated: this version has critical issues, please update to the latest version
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
@@ -13548,6 +13553,7 @@ packages:
resolution: {integrity: sha512-jFihhedKitw1X9rlImtaca4KTs1Xk9awo4GxUemqt2ucE1jLi10lyRfFFbiYXZsFDkuCWGHwEQwv7BeDIEXMbQ==}
engines: {node: '>= 18'}
+ deprecated: v1 is no longer supported. Please update ZenFS (or whatever ZenFS dependent you depend on).
hasBin: true
@@ -14733,6 +14739,7 @@ packages:
resolution: {integrity: sha512-jbokKWGcyU4gl6jAfX97E1gDpY12DJ1cLJZmoDzaAln/shZ+S3KBFBuA2Q6WeUN4gJf/8klnV1EfvhA2lK5IRQ==}
engines: {node: '>=12.0.0'}
+ deprecated: v4 is no longer maintained, upgrade to v5
resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==}
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 939ca4d125e9..8ff011867e46 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -674,6 +674,54 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
Dashboard.objects.get(id=copied_id).customization, {"show_legend": False, "tile_spacing": "wide"}
)
+ @parameterized.expand([("horizontal",), ("stable",)])
+ @patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=True)
+ def test_dashboard_layout_compaction_is_saved_and_duplicated(
+ self, layout_compaction: str, _mock_enabled: MagicMock
+ ) -> 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})
+
+ 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})
+
+ @patch("products.dashboards.backend.api.dashboard.report_user_action")
+ @patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=True)
+ def test_dashboard_layout_compaction_reports_every_mode_change(
+ self, _mock_enabled: MagicMock, 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"})
+
+ 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)
+ 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",
+ },
+ )
+
@patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=True)
def test_dashboard_tile_spacing_recovers_from_malformed_customization(self, _mock_enabled: MagicMock):
dashboard = Dashboard.objects.create(team=self.team, name="dashboard", customization=[])
@@ -696,6 +744,18 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
self.assertEqual(response["attr"], "grid_spacing")
self.assertEqual(response["detail"], "Tile density isn't available.")
+ @patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=False)
+ def test_dashboard_layout_compaction_requires_feature_flag(self, _mock_enabled: MagicMock) -> None:
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
+
+ _, response = self.dashboard_api.update_dashboard(
+ dashboard_id,
+ {"layout_compaction": "horizontal"},
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+ self.assertEqual(response["attr"], "layout_compaction")
+ self.assertEqual(response["detail"], "Tile movement settings aren't available.")
+
@patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=True)
def test_dashboard_tile_spacing_requires_a_known_preset(self, _mock_enabled: MagicMock):
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
@@ -707,6 +767,17 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response["attr"], "grid_spacing")
+ @patch("products.dashboards.backend.api.dashboard.dashboard_customization_enabled", return_value=True)
+ def test_dashboard_layout_compaction_requires_a_known_mode(self, _mock_enabled: MagicMock) -> None:
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
+
+ _, response = self.dashboard_api.update_dashboard(
+ dashboard_id,
+ {"layout_compaction": "none"},
+ expected_status=status.HTTP_400_BAD_REQUEST,
+ )
+ self.assertEqual(response["attr"], "layout_compaction")
+
@patch("products.product_analytics.backend.presentation.insight.record_dashboard_cache_outcome")
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
def test_update_dashboard_does_not_record_cache_outcomes(
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index bc5a00c0cd4d..78b53db41a73 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -685,6 +685,7 @@ SPECTACULAR_SETTINGS = {
"TargetTypeEnum": "products.exports.backend.models.subscription.Subscription.SubscriptionTarget",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"TileSpacingEnum": ["tight", "condensed", "standard", "relaxed", "wide"],
+ "LayoutCompactionEnum": ["vertical", "horizontal", "stable"],
"PropertyGroupOperator": ["AND", "OR"],
# `scope`/`state` are generic field names; one shared name for the canvas state scope set.
"CanvasStateScopeEnum": ["user", "shared"],
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 57c579652c8f..d473e18640e9 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -116,7 +116,11 @@ from products.dashboards.backend.api.widget_openapi_serializers import (
)
from products.dashboards.backend.constants import DASHBOARD_GRID_COLUMN_COUNT, MAX_WIDGETS_BATCH_SIZE
from products.dashboards.backend.feature_flags import dashboard_customization_enabled, dashboard_widgets_enabled
-from products.dashboards.backend.models.dashboard import DASHBOARD_GRID_SPACING_GAPS, Dashboard
+from products.dashboards.backend.models.dashboard import (
+ DASHBOARD_GRID_COMPACTION_MODES,
+ DASHBOARD_GRID_SPACING_GAPS,
+ Dashboard,
+)
from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
from products.dashboards.backend.widget_access import (
@@ -167,6 +171,11 @@ def _normalize_dashboard_customization(customization: Any) -> dict[str, Any]:
return customization.copy() if isinstance(customization, dict) else {}
+def _effective_layout_compaction(customization: Any) -> str:
+ layout_compaction = _normalize_dashboard_customization(customization).get("layout_compaction")
+ return layout_compaction if layout_compaction in DASHBOARD_GRID_COMPACTION_MODES else "vertical"
+
+
logger = structlog.get_logger(__name__)
DASHBOARD_TILE_ERROR_TYPE = "DashboardTileError"
@@ -242,6 +251,7 @@ DASHBOARD_SHARED_FIELDS = [
"quick_filter_ids",
"customization",
"grid_spacing",
+ "layout_compaction",
]
@@ -1179,6 +1189,14 @@ class DashboardCustomizationSerializer(serializers.Serializer):
required=False,
help_text="Named tile density preset.",
)
+ layout_compaction = serializers.ChoiceField(
+ choices=DASHBOARD_GRID_COMPACTION_MODES,
+ required=False,
+ help_text=(
+ "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."
+ ),
+ )
class DashboardMetadataSerializer(DashboardBasicSerializer):
@@ -1206,6 +1224,15 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):
write_only=True,
help_text="Named tile density preset. Use tight, condensed, standard, relaxed, or wide.",
)
+ layout_compaction = serializers.ChoiceField(
+ choices=DASHBOARD_GRID_COMPACTION_MODES,
+ required=False,
+ write_only=True,
+ help_text=(
+ "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."
+ ),
+ )
persisted_filters = serializers.SerializerMethodField()
persisted_variables = serializers.SerializerMethodField()
@@ -1221,10 +1248,15 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):
@extend_schema_field(DashboardCustomizationSerializer)
def get_customization(self, dashboard: Dashboard) -> dict[str, str]:
- tile_spacing = _normalize_dashboard_customization(dashboard.customization).get("tile_spacing")
+ customization = _normalize_dashboard_customization(dashboard.customization)
+ tile_spacing = customization.get("tile_spacing")
+ layout_compaction = customization.get("layout_compaction")
+ result = {}
if isinstance(tile_spacing, str) and tile_spacing in DASHBOARD_GRID_SPACING_GAPS:
- return {"tile_spacing": tile_spacing}
- return {}
+ result["tile_spacing"] = tile_spacing
+ if isinstance(layout_compaction, str) and layout_compaction in DASHBOARD_GRID_COMPACTION_MODES:
+ result["layout_compaction"] = layout_compaction
+ return result
def get_variables(self, dashboard: Dashboard) -> dict | None:
request = self.context.get("request")
@@ -1494,8 +1526,11 @@ class DashboardSerializer(DashboardMetadataSerializer):
team_id = self.context["team_id"]
team = self.context["get_team"]()
grid_spacing = validated_data.pop("grid_spacing", None)
+ layout_compaction = validated_data.pop("layout_compaction", None)
if grid_spacing is not None and not dashboard_customization_enabled(team=team, user=request.user):
raise serializers.ValidationError({"grid_spacing": "Tile density isn't available."})
+ if layout_compaction is not None and not dashboard_customization_enabled(team=team, user=request.user):
+ raise serializers.ValidationError({"layout_compaction": "Tile movement settings aren't available."})
current_count = Dashboard.objects.filter(team_id=team_id, deleted=False).count()
check_count_limit(
team=team,
@@ -1553,6 +1588,11 @@ class DashboardSerializer(DashboardMetadataSerializer):
**validated_data.get("customization", {}),
"tile_spacing": grid_spacing,
}
+ if layout_compaction is not None:
+ validated_data["customization"] = {
+ **validated_data.get("customization", {}),
+ "layout_compaction": layout_compaction,
+ }
dashboard = Dashboard.objects.create(team_id=team_id, filters=filters, **validated_data)
@@ -1741,6 +1781,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)
can_user_restrict = self.user_permissions.dashboard(instance).can_restrict
if "restriction_level" in validated_data and not can_user_restrict:
raise exceptions.PermissionDenied(
@@ -1749,14 +1790,20 @@ class DashboardSerializer(DashboardMetadataSerializer):
validated_data.pop("use_template", None) # Remove attribute if present
grid_spacing = validated_data.pop("grid_spacing", None)
+ layout_compaction = validated_data.pop("layout_compaction", None)
if grid_spacing is not None and not dashboard_customization_enabled(
team=instance.team, user=cast(User, self.context["request"].user)
):
raise serializers.ValidationError({"grid_spacing": "Tile density isn't available."})
- if grid_spacing is not None:
+ if layout_compaction is not None and not dashboard_customization_enabled(
+ team=instance.team, user=cast(User, self.context["request"].user)
+ ):
+ raise serializers.ValidationError({"layout_compaction": "Tile movement settings aren't available."})
+ if grid_spacing is not None or layout_compaction is not None:
validated_data["customization"] = {
**_normalize_dashboard_customization(instance.customization),
- "tile_spacing": grid_spacing,
+ **({"tile_spacing": grid_spacing} if grid_spacing is not None else {}),
+ **({"layout_compaction": layout_compaction} if layout_compaction is not None else {}),
}
being_undeleted = instance.deleted and "deleted" in validated_data and not validated_data["deleted"]
@@ -1827,6 +1874,18 @@ class DashboardSerializer(DashboardMetadataSerializer):
self._deep_duplicate_tiles(instance, existing_tile, user_access_control)
if "request" in self.context:
+ if layout_compaction is not None and layout_compaction != previous_layout_compaction:
+ report_user_action(
+ user,
+ "dashboard grid compaction configured",
+ {
+ "dashboard_id": instance.id,
+ "previous_layout_compaction": previous_layout_compaction,
+ "layout_compaction": layout_compaction,
+ },
+ team=instance.team,
+ request=self.context["request"],
+ )
if being_deleted:
report_user_action(
user,
diff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.py
index fb03c44955f2..b613c04c9ffc 100644
--- a/products/dashboards/backend/models/dashboard.py
+++ b/products/dashboards/backend/models/dashboard.py
@@ -23,6 +23,8 @@ DASHBOARD_GRID_SPACING_GAPS = {
"wide": 48,
}
+DASHBOARD_GRID_COMPACTION_MODES = ("vertical", "horizontal", "stable")
+
class DashboardManager(RootTeamManager):
def get_queryset(self):
diff --git a/products/dashboards/backend/widget_specs/openapi.py b/products/dashboards/backend/widget_specs/openapi.py
index 905a6fbc47f9..25aa05e0fda9 100644
--- a/products/dashboards/backend/widget_specs/openapi.py
+++ b/products/dashboards/backend/widget_specs/openapi.py
@@ -6,7 +6,7 @@ from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_fiel
from pydantic import BaseModel
from rest_framework import serializers
-from products.dashboards.backend.models.dashboard import DASHBOARD_GRID_SPACING_GAPS
+from products.dashboards.backend.models.dashboard import DASHBOARD_GRID_COMPACTION_MODES, DASHBOARD_GRID_SPACING_GAPS
from products.dashboards.backend.widget_specs.pydantic_openapi import pydantic_config_field, pydantic_stub_serializer
from products.dashboards.backend.widget_specs.registry import EXPECTED_WIDGET_TYPES, WIDGET_SPECS
@@ -308,6 +308,14 @@ class PatchedDashboardOpenApiSerializer(serializers.Serializer):
required=False,
help_text="Named tile density preset. Use tight, condensed, standard, relaxed, or wide.",
)
+ layout_compaction = serializers.ChoiceField(
+ choices=DASHBOARD_GRID_COMPACTION_MODES,
+ required=False,
+ help_text=(
+ "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."
+ ),
+ )
tiles = DashboardPatchTileOpenApiSerializer(
many=True,
required=False,
diff --git a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
index 5512d5e01f7e..b523c6858521 100644
--- a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
+++ b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
@@ -1,12 +1,20 @@
import { useActions, useValues } from 'kea'
+import { LemonTag } from '@posthog/lemon-ui'
+
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { DashboardTileSpacing } from '~/types'
+import type { DashboardTileSpacing } from '~/types'
-import { DASHBOARD_TILE_SPACING_LABELS } from '../../dashboardCustomization'
+import {
+ DASHBOARD_GRID_COMPACTION_LABELS,
+ DASHBOARD_TILE_SPACING_LABELS,
+ DashboardGridCompaction,
+ type DashboardGridCompaction as DashboardGridCompactionType,
+} from '../../dashboardCustomization'
+import { DashboardTileMovementPreview } from './DashboardTileMovementPreview'
const TILE_SPACING_OPTIONS: { value: DashboardTileSpacing; label: string }[] = [
{ value: 'tight', label: DASHBOARD_TILE_SPACING_LABELS.tight },
@@ -16,9 +24,50 @@ const TILE_SPACING_OPTIONS: { value: DashboardTileSpacing; label: string }[] = [
{ value: 'wide', label: DASHBOARD_TILE_SPACING_LABELS.wide },
]
+const GRID_COMPACTION_OPTIONS: {
+ value: DashboardGridCompactionType
+ label: JSX.Element
+}[] = [
+ {
+ value: DashboardGridCompaction.Vertical,
+ label: (
+ <span className="flex items-center gap-2">
+ <span className="text-xs font-medium">
+ {DASHBOARD_GRID_COMPACTION_LABELS[DashboardGridCompaction.Vertical]}
+ </span>
+ <LemonTag type="success">Recommended</LemonTag>
+ <DashboardTileMovementPreview mode={DashboardGridCompaction.Vertical} />
+ </span>
+ ),
+ },
+ {
+ value: DashboardGridCompaction.Horizontal,
+ label: (
+ <span className="flex items-center gap-2">
+ <span className="text-xs font-medium">
+ {DASHBOARD_GRID_COMPACTION_LABELS[DashboardGridCompaction.Horizontal]}
+ </span>
+ <DashboardTileMovementPreview mode={DashboardGridCompaction.Horizontal} />
+ </span>
+ ),
+ },
+ {
+ value: DashboardGridCompaction.Stable,
+ label: (
+ <span className="flex items-center gap-2">
+ <span className="text-xs font-medium">
+ {DASHBOARD_GRID_COMPACTION_LABELS[DashboardGridCompaction.Stable]}
+ </span>
+ <DashboardTileMovementPreview mode={DashboardGridCompaction.Stable} />
+ </span>
+ ),
+ },
+]
+
export function DashboardCustomizeMenu(): JSX.Element | null {
const { dashboard, canEditDashboard } = useValues(dashboardLogic)
- const { setDashboardTileSpacing, saveDashboardTileSpacing } = useActions(dashboardLogic)
+ const { changeDashboardGridCompaction, setDashboardTileSpacing, saveDashboardTileSpacing } =
+ useActions(dashboardLogic)
const dashboardCustomizationEnabled = useFeatureFlag('DASHBOARD_CUSTOMIZATION')
if (!dashboard || !canEditDashboard || !dashboardCustomizationEnabled) {
@@ -26,6 +75,7 @@ export function DashboardCustomizeMenu(): JSX.Element | null {
}
const tileSpacing = dashboard.customization?.tile_spacing ?? 'standard'
+ const layoutCompaction = dashboard.customization?.layout_compaction ?? DashboardGridCompaction.Vertical
const setTileSpacing = (value: DashboardTileSpacing): void => {
if (value === tileSpacing) {
return
@@ -34,17 +84,37 @@ export function DashboardCustomizeMenu(): JSX.Element | null {
saveDashboardTileSpacing(value)
}
+ const setGridCompaction = (value: DashboardGridCompactionType): void => {
+ if (value === layoutCompaction) {
+ return
+ }
+ changeDashboardGridCompaction(value)
+ }
+
return (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 p-2">
- <span className="text-xs text-muted whitespace-nowrap">Tile density</span>
- <LemonRadio<DashboardTileSpacing>
- value={tileSpacing}
- onChange={setTileSpacing}
- options={TILE_SPACING_OPTIONS}
- orientation="horizontal"
- className="flex-1 flex-wrap gap-x-3 gap-y-1"
- aria-label="Tile density"
- />
+ <div className="space-y-2 p-2">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="text-xs text-muted whitespace-nowrap">Tile density</span>
+ <LemonRadio<DashboardTileSpacing>
+ value={tileSpacing}
+ onChange={setTileSpacing}
+ options={TILE_SPACING_OPTIONS}
+ orientation="horizontal"
+ className="flex-1 flex-wrap gap-x-3 gap-y-1"
+ aria-label="Tile density"
+ />
+ </div>
+ <div className="flex gap-x-3 border-t pt-2">
+ <span className="pt-3 text-xs text-muted whitespace-nowrap">When you move a tile</span>
+ <LemonRadio<DashboardGridCompactionType>
+ value={layoutCompaction}
+ onChange={setGridCompaction}
+ options={GRID_COMPACTION_OPTIONS}
+ radioPosition="top"
+ className="flex-1"
+ aria-label="How moving a tile rearranges other tiles"
+ />
+ </div>
</div>
)
}
diff --git a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.scss b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.scss
new file mode 100644
index 000000000000..5e967ffaba63
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.scss
@@ -0,0 +1,154 @@
+.dashboard-tile-movement-preview {
+ &__move-up,
+ &__move-up-double,
+ &__move-right,
+ &__move-into-row,
+ &__move-down,
+ &__resize-right {
+ transform-box: fill-box;
+ transform-origin: center;
+ }
+
+ &__move-up {
+ animation: DashboardTileMovementPreview__moveUp 2.5s ease-in-out infinite;
+ }
+
+ &__move-up-double {
+ animation: DashboardTileMovementPreview__moveUpDouble 2.5s ease-in-out infinite;
+ }
+
+ &__move-right {
+ animation: DashboardTileMovementPreview__moveRight 2.5s ease-in-out infinite;
+ }
+
+ &__move-into-row {
+ animation: DashboardTileMovementPreview__moveIntoRow 2.5s ease-in-out infinite;
+ }
+
+ &__move-down {
+ animation: DashboardTileMovementPreview__moveDown 2.5s ease-in-out infinite;
+ }
+
+ &__resize-right {
+ transform-origin: left center;
+ animation: DashboardTileMovementPreview__resizeRight 2.5s ease-in-out infinite;
+ }
+}
+
+@keyframes DashboardTileMovementPreview__moveUp {
+ 0%,
+ 16.67%,
+ 50%,
+ 100% {
+ transform: translateY(-16px);
+ }
+
+ 30% {
+ transform: translateY(0);
+ }
+}
+
+@keyframes DashboardTileMovementPreview__moveUpDouble {
+ 0%,
+ 16.67%,
+ 50%,
+ 100% {
+ transform: translateY(-32px);
+ }
+
+ 30% {
+ transform: translateY(0);
+ }
+}
+
+@keyframes DashboardTileMovementPreview__moveRight {
+ 0%,
+ 16.67%,
+ 50%,
+ 100% {
+ transform: translateX(15.5px);
+ }
+
+ 30% {
+ transform: translateX(0);
+ }
+}
+
+@keyframes DashboardTileMovementPreview__moveIntoRow {
+ 0%,
+ 16.67%,
+ 66.67%,
+ 100% {
+ transform: translateY(-16px);
+ }
+
+ 30%,
+ 56.67% {
+ transform: translateY(0);
+ }
+}
+
+@keyframes DashboardTileMovementPreview__moveDown {
+ 0%,
+ 16.67%,
+ 58.33%,
+ 100% {
+ transform: translateY(16px);
+ }
+
+ 30%,
+ 43.33% {
+ transform: translateY(0);
+ }
+}
+
+@keyframes DashboardTileMovementPreview__resizeRight {
+ 0%,
+ 16.67%,
+ 58.33%,
+ 100% {
+ transform: scaleX(2.24);
+ }
+
+ 30%,
+ 56.67% {
+ transform: scaleX(1);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dashboard-tile-movement-preview {
+ &__move-up {
+ transform: translateY(-16px);
+ }
+
+ &__move-up-double {
+ transform: translateY(-32px);
+ }
+
+ &__move-right {
+ transform: translateX(15.5px);
+ }
+
+ &__move-into-row {
+ transform: translateY(-16px);
+ }
+
+ &__move-down {
+ transform: translateY(16px);
+ }
+
+ &__resize-right {
+ transform: scaleX(2.24);
+ }
+
+ &__move-up,
+ &__move-up-double,
+ &__move-right,
+ &__move-into-row,
+ &__move-down,
+ &__resize-right {
+ animation: none;
+ }
+ }
+}
diff --git a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.tsx b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.tsx
new file mode 100644
index 000000000000..d15b8fa3bedf
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardTileMovementPreview.tsx
@@ -0,0 +1,63 @@
+import './DashboardTileMovementPreview.scss'
+
+import { DashboardGridCompaction } from '../../dashboardCustomization'
+
+const GRID_STROKE = 'var(--color-border-primary)'
+const EXISTING_TILE = 'var(--data-color-3)'
+const MOVED_TILE = 'var(--data-color-1)'
+const DISPLACED_TILE = 'var(--data-color-5)'
+
+interface DashboardTileMovementPreviewProps {
+ mode: DashboardGridCompaction
+}
+
+function Tile({ x, y, fill, className }: { x: number; y: number; fill: string; className?: string }): JSX.Element {
+ return <rect className={className} x={x * 15.5 + 3} y={y * 16 + 11} width="12.5" height="13" rx="2" fill={fill} />
+}
+
+function MovementTiles({ mode }: DashboardTileMovementPreviewProps): JSX.Element {
+ if (mode === DashboardGridCompaction.Vertical) {
+ return (
+ <>
+ <Tile x={0} y={0} fill={EXISTING_TILE} />
+ <Tile x={0} y={1} fill={EXISTING_TILE} />
+ <Tile x={0} y={2} fill={EXISTING_TILE} />
+ <Tile x={1} y={2} fill={MOVED_TILE} className="dashboard-tile-movement-preview__move-up-double" />
+ <Tile x={2} y={1} fill={DISPLACED_TILE} className="dashboard-tile-movement-preview__move-up" />
+ </>
+ )
+ }
+
+ if (mode === DashboardGridCompaction.Horizontal) {
+ return (
+ <>
+ <Tile x={0} y={0} fill={EXISTING_TILE} />
+ <Tile x={1} y={0} fill={DISPLACED_TILE} className="dashboard-tile-movement-preview__move-right" />
+ <Tile x={1} y={1} fill={MOVED_TILE} className="dashboard-tile-movement-preview__move-into-row" />
+ </>
+ )
+ }
+
+ return (
+ <>
+ <Tile x={0} y={0} fill={MOVED_TILE} className="dashboard-tile-movement-preview__resize-right" />
+ <Tile x={1} y={0} fill={DISPLACED_TILE} className="dashboard-tile-movement-preview__move-down" />
+ <Tile x={2} y={1} fill={EXISTING_TILE} />
+ </>
+ )
+}
+
+export function DashboardTileMovementPreview({ mode }: DashboardTileMovementPreviewProps): JSX.Element {
+ return (
+ <svg
+ viewBox="0 0 48 58"
+ className="dashboard-tile-movement-preview mt-0.5 h-12 w-10 shrink-0"
+ fill="none"
+ aria-hidden="true"
+ >
+ <rect x="1" y="9" width="46" height="46" rx="4" fill="var(--color-bg-light)" stroke={GRID_STROKE} />
+ <path d="M16.5 9V55M32 9V55M1 25H47M1 41H47" stroke={GRID_STROKE} strokeWidth="0.75" opacity="0.7" />
+ <MovementTiles mode={mode} />
+ </svg>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardCustomization.test.ts b/products/dashboards/frontend/dashboardCustomization.test.ts
new file mode 100644
index 000000000000..9224e0d1cc2d
--- /dev/null
+++ b/products/dashboards/frontend/dashboardCustomization.test.ts
@@ -0,0 +1,33 @@
+import type { Layout } from 'react-grid-layout'
+
+import { resolveFreePlacementCollisions } from './dashboardCustomization'
+
+const geometry = (layout: Layout): Layout => layout.map(({ i, x, y, w, h }) => ({ i, x, y, w, h }))
+
+describe('dashboard grid compactors', () => {
+ it('moves a collision chain below the active tile', () => {
+ const layout = [
+ { i: 'active', x: 0, y: 2, w: 6, h: 4 },
+ { i: 'neighbor', x: 0, y: 4, w: 6, h: 4 },
+ { i: 'next-neighbor', x: 0, y: 8, w: 6, h: 4 },
+ ] as Layout
+
+ expect(geometry(resolveFreePlacementCollisions(layout, 12, 'active'))).toEqual([
+ { i: 'active', x: 0, y: 2, w: 6, h: 4 },
+ { i: 'neighbor', x: 0, y: 6, w: 6, h: 4 },
+ { i: 'next-neighbor', x: 0, y: 10, w: 6, h: 4 },
+ ])
+ })
+
+ it('bounds malformed tile heights before resolving collisions', () => {
+ const layout = [
+ { i: 'active', x: 0, y: 0, w: 6, h: 1_000_000 },
+ { i: 'neighbor', x: 0, y: 5, w: 6, h: 4 },
+ ] as Layout
+
+ expect(geometry(resolveFreePlacementCollisions(layout, 12, 'active'))).toEqual([
+ { i: 'active', x: 0, y: 0, w: 6, h: 100 },
+ { i: 'neighbor', x: 0, y: 100, w: 6, h: 4 },
+ ])
+ })
+})
diff --git a/products/dashboards/frontend/dashboardCustomization.ts b/products/dashboards/frontend/dashboardCustomization.ts
index b9aeeb923358..45dea1ccb369 100644
--- a/products/dashboards/frontend/dashboardCustomization.ts
+++ b/products/dashboards/frontend/dashboardCustomization.ts
@@ -1,5 +1,17 @@
+import { cloneLayoutItem, horizontalCompactor, noCompactor } from 'react-grid-layout'
+import type { Compactor, Layout, LayoutItem } from 'react-grid-layout'
+import { fastVerticalCompactor } from 'react-grid-layout/extras'
+
import type { DashboardTileSpacing } from '~/types'
+export const DashboardGridCompaction = {
+ Vertical: 'vertical',
+ Horizontal: 'horizontal',
+ Stable: 'stable',
+} as const
+
+export type DashboardGridCompaction = (typeof DashboardGridCompaction)[keyof typeof DashboardGridCompaction]
+
export const DASHBOARD_TILE_SPACING_GAPS: Record<DashboardTileSpacing, number> = {
tight: 8,
condensed: 12,
@@ -16,6 +28,111 @@ export const DASHBOARD_TILE_SPACING_LABELS: Record<DashboardTileSpacing, string>
wide: 'Wide',
}
+export const DASHBOARD_GRID_COMPACTION_LABELS: Record<DashboardGridCompaction, string> = {
+ [DashboardGridCompaction.Vertical]: 'Stack tiles upward',
+ [DashboardGridCompaction.Horizontal]: 'Stack tiles to the left',
+ [DashboardGridCompaction.Stable]: 'Free-form placement',
+}
+
+type GridOccupancy = Map<number, Array<LayoutItem | undefined>>
+
+const MAX_FREE_FORM_TILE_HEIGHT_ROWS = 100
+
+function getOccupants(occupancy: GridOccupancy, item: LayoutItem, cols: number): LayoutItem[] {
+ const occupants = new Set<LayoutItem>()
+ const startX = Math.max(0, item.x)
+ const endX = Math.min(cols, item.x + item.w)
+
+ for (let y = item.y; y < item.y + item.h; y++) {
+ const row = occupancy.get(y)
+ for (let x = startX; row && x < endX; x++) {
+ const occupant = row[x]
+ if (occupant) {
+ occupants.add(occupant)
+ }
+ }
+ }
+
+ return [...occupants]
+}
+
+function occupy(occupancy: GridOccupancy, item: LayoutItem, cols: number): void {
+ const startX = Math.max(0, item.x)
+ const endX = Math.min(cols, item.x + item.w)
+
+ for (let y = item.y; y < item.y + item.h; y++) {
+ const row = occupancy.get(y) ?? new Array<LayoutItem | undefined>(cols)
+ for (let x = startX; x < endX; x++) {
+ row[x] = item
+ }
+ occupancy.set(y, row)
+ }
+}
+
+export const freePlacementCompactor: Compactor = noCompactor
+
+export const makeRoomInRowCompactor: Compactor = horizontalCompactor
+
+export interface DashboardGridCompactor extends Compactor {
+ compactInteraction: (cols: number, activeTileId: string, restoredLayout: Layout, resizedLayout: Layout) => Layout
+}
+
+export function resolveFreePlacementCollisions(layout: Layout, cols: number, activeTileId?: string | null): Layout {
+ const items = layout.map((item) => ({
+ ...cloneLayoutItem(item),
+ h: Math.min(item.h, MAX_FREE_FORM_TILE_HEIGHT_ROWS),
+ }))
+ const activeTile = activeTileId ? items.find((item) => item.i === activeTileId) : undefined
+ const occupancy: GridOccupancy = new Map()
+ for (const item of items) {
+ if (item.static) {
+ occupy(occupancy, item, cols)
+ }
+ }
+ const movableItems = items.filter((item) => !item.static && item.i !== activeTileId)
+
+ for (const item of activeTile && !activeTile.static ? [activeTile, ...movableItems] : movableItems) {
+ let collisions = getOccupants(occupancy, item, cols)
+
+ while (collisions.length > 0) {
+ item.y = Math.max(...collisions.map((collision) => collision.y + collision.h))
+ collisions = getOccupants(occupancy, item, cols)
+ }
+
+ occupy(occupancy, item, cols)
+ }
+
+ return items
+}
+
export function getDashboardTileSpacingGap(tileSpacing?: string): number {
return DASHBOARD_TILE_SPACING_GAPS[tileSpacing as DashboardTileSpacing] ?? DASHBOARD_TILE_SPACING_GAPS.standard
}
+
+export function getDashboardGridCompactor(layoutCompaction?: DashboardGridCompaction): DashboardGridCompactor {
+ const selectedCompaction = layoutCompaction ?? DashboardGridCompaction.Vertical
+ const compactor = (() => {
+ switch (selectedCompaction) {
+ case DashboardGridCompaction.Horizontal:
+ return makeRoomInRowCompactor
+ case DashboardGridCompaction.Stable:
+ return freePlacementCompactor
+ default:
+ return fastVerticalCompactor
+ }
+ })()
+
+ return {
+ ...compactor,
+ compactInteraction: (cols, activeTileId, restoredLayout, resizedLayout): Layout => {
+ switch (selectedCompaction) {
+ case DashboardGridCompaction.Stable:
+ return resolveFreePlacementCollisions(restoredLayout, cols, activeTileId)
+ case DashboardGridCompaction.Vertical:
+ return compactor.compact(resizedLayout, cols)
+ default:
+ return compactor.compact(restoredLayout, cols)
+ }
+ },
+ }
+}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 7fe9a278abbd..a3da02d103fe 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -336,6 +336,19 @@ export const TileSpacingEnumApi = {
Wide: 'wide',
} as const
+/**
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable
+ */
+export type LayoutCompactionEnumApi = (typeof LayoutCompactionEnumApi)[keyof typeof LayoutCompactionEnumApi]
+
+export const LayoutCompactionEnumApi = {
+ Vertical: 'vertical',
+ Horizontal: 'horizontal',
+ Stable: 'stable',
+} as const
+
export interface DashboardCustomizationApi {
/** Named tile density preset.
*
@@ -345,6 +358,12 @@ export interface DashboardCustomizationApi {
* * `relaxed` - relaxed
* * `wide` - wide */
tile_spacing?: TileSpacingEnumApi
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnumApi
}
/**
@@ -425,6 +444,12 @@ export interface DashboardApi {
* * `relaxed` - relaxed
* * `wide` - wide */
grid_spacing?: TileSpacingEnumApi
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnumApi
/** @nullable */
readonly tiles: readonly DashboardApiTilesItem[] | null
/** Template key to create the dashboard from a predefined template. */
@@ -1006,6 +1031,12 @@ export interface PatchedPatchedDashboardOpenApiApi {
* * `relaxed` - relaxed
* * `wide` - wide */
grid_spacing?: TileSpacingEnumApi
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnumApi
/** Dashboard tiles to update. Widget tiles accept nested widget.config patches. */
tiles?: DashboardPatchTileOpenApiApi[]
/** Template key to create the dashboard from a predefined template. */
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index 6e17a4dc97da..b2cca09bc3fa 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -163,6 +163,13 @@ export const DashboardsCreateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
use_template: zod
.string()
.optional()
@@ -219,6 +226,13 @@ export const DashboardsUpdateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
use_template: zod
.string()
.optional()
@@ -342,6 +356,13 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
tiles: zod
.array(
zod.object({
@@ -3324,6 +3345,13 @@ export const DashboardsCreateFromTemplateJsonCreateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
use_template: zod
.string()
.optional()
@@ -3376,6 +3404,13 @@ export const DashboardsCreateUnlistedDashboardCreateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
use_template: zod
.string()
.optional()
diff --git a/products/dashboards/package.json b/products/dashboards/package.json
index cfc8dda3fc5b..d27f1896a001 100644
--- a/products/dashboards/package.json
+++ b/products/dashboards/package.json
@@ -8,7 +8,8 @@
"kea": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",
- "posthog-js": "catalog:"
+ "posthog-js": "catalog:",
+ "react-grid-layout": "^2.2.4"
},
"devDependencies": {
"@storybook/react": "catalog:",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6b543b587279..1e394a8510c9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19917,6 +19917,20 @@ export namespace Schemas {
Wide: 'wide',
} as const;
+ /**
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable
+ */
+ export type LayoutCompactionEnum = typeof LayoutCompactionEnum[keyof typeof LayoutCompactionEnum];
+
+
+ export const LayoutCompactionEnum = {
+ Vertical: 'vertical',
+ Horizontal: 'horizontal',
+ Stable: 'stable',
+ } as const;
+
export interface DashboardCustomization {
/** Named tile density preset.
*
@@ -19926,6 +19940,12 @@ export namespace Schemas {
* * `relaxed` - relaxed
* * `wide` - wide */
tile_spacing?: TileSpacingEnum;
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnum;
}
/**
@@ -20006,6 +20026,12 @@ export namespace Schemas {
* * `relaxed` - relaxed
* * `wide` - wide */
grid_spacing?: TileSpacingEnum;
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnum;
/** @nullable */
readonly tiles: readonly DashboardTilesItem[] | null;
/** Template key to create the dashboard from a predefined template. */
@@ -61071,6 +61097,12 @@ export namespace Schemas {
* * `relaxed` - relaxed
* * `wide` - wide */
grid_spacing?: TileSpacingEnum;
+ /** 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.
+ *
+ * * `vertical` - vertical
+ * * `horizontal` - horizontal
+ * * `stable` - stable */
+ layout_compaction?: LayoutCompactionEnum;
/** Dashboard tiles to update. Widget tiles accept nested widget.config patches. */
tiles?: DashboardPatchTileOpenApi[];
/** Template key to create the dashboard from a predefined template. */
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index a25b83b5fe9d..6faf238f0f7b 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -129,6 +129,13 @@ export const DashboardsCreateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
use_template: zod
.string()
.optional()
@@ -299,6 +306,13 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .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'
+ ),
tiles: zod
.array(
zod.object({
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index 91ecc479c3b8..b9d22cbe0bde 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -80,6 +80,9 @@ const dashboardCreate = (): ToolBase<typeof DashboardCreateSchema, WithPostHogUr
if (params.grid_spacing !== undefined) {
body['grid_spacing'] = params.grid_spacing
}
+ if (params.layout_compaction !== undefined) {
+ body['layout_compaction'] = params.layout_compaction
+ }
if (params.use_template !== undefined) {
body['use_template'] = params.use_template
}
@@ -479,6 +482,9 @@ const dashboardUpdate = (): ToolBase<typeof DashboardUpdateSchema, WithPostHogUr
if (params.grid_spacing !== undefined) {
body['grid_spacing'] = params.grid_spacing
}
+ if (params.layout_compaction !== undefined) {
+ body['layout_compaction'] = params.layout_compaction
+ }
if (params.tiles !== undefined) {
body['tiles'] = params.tiles
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
index 3c38d43edb49..ac9648c9041b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json
@@ -32,6 +32,11 @@
"description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
"type": "boolean"
},
+ "layout_compaction": {
+ "description": "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",
+ "enum": ["vertical", "horizontal", "stable"],
+ "type": "string"
+ },
"name": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
index ff4dc176d6e7..6d7d1c5c4066 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
@@ -66,6 +66,11 @@
"description": "Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.",
"type": "boolean"
},
+ "layout_compaction": {
+ "description": "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",
+ "enum": ["vertical", "horizontal", "stable"],
+ "type": "string"
+ },
"name": {
"anyOf": [
{