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): keep resizes in their row (#84465)

Matt Pua45c9263c6f04
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 05eff708e6e6..60803d667893 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -117,11 +117,17 @@ jest.mock('./items/DashboardTextItem', () => ({
jest.mock('react-grid-layout', () => {
return {
+ cloneLayoutItem: (item: Record<string, unknown>) => ({ ...item }),
useContainerWidth: () => ({
width: 1200,
containerRef: { current: null },
mounted: true,
}),
+ verticalCompactor: {
+ type: 'vertical',
+ allowOverlap: false,
+ compact: (layout: unknown[]) => layout,
+ },
Responsive: ({
className,
rowHeight,
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 18ad98178951..da8e08c9c81a 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -4,7 +4,8 @@ import clsx from 'clsx'
import { useActions, useAsyncActions, useValues } from 'kea'
import { router } from 'kea-router'
import { RefObject, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { Layout, Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
+import { Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
+import type { Layout, LayoutItem } from 'react-grid-layout'
import { GridBackground } from 'react-grid-layout/extras'
import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem'
@@ -28,6 +29,7 @@ import {
} from 'scenes/dashboard/dashboardUtils'
import { continueDragGestureInEditMode, continueResizeGestureInEditMode } from 'scenes/dashboard/editLayoutGesture'
import { InsertTileOverlay } from 'scenes/dashboard/InsertTileOverlay'
+import { useDashboardLayoutInteraction } from 'scenes/dashboard/useDashboardLayoutInteraction'
import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedInsights'
import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
@@ -139,8 +141,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
// While a drag/resize is in progress the grid drives itself from its own internal state and ignores the
// `layouts` prop, so pushing layout updates to the store mid-gesture only triggers expensive full re-renders
// (every InsightCard) that make the dragged tile lag the cursor. Stash the latest layout and commit once on stop.
- const interactionInProgress = useRef(false)
- const pendingLayouts = useRef<Partial<Record<DashboardLayoutSize, Layout>> | null>(null)
const dragEndTimeout = useRef<number | null>(null)
const scrollAnimationRef = useRef<number | null>(null)
const scrollContainerRef = useRef<HTMLElement | null>(null)
@@ -191,6 +191,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
})
const { width, containerRef, mounted } = useContainerWidth()
+ const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =
+ useDashboardLayoutInteraction({ layoutEditMode, 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.
@@ -243,7 +245,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const rowHeight = BASE_ROW_HEIGHT * effectiveZoom
const spacingFactor = effectiveZoom < 1 ? 0.9 : 1
const margin = useMemo(() => BASE_MARGIN.map((m) => m * spacingFactor) as [number, number], [spacingFactor])
-
const getInsertMenuItems = useCallback(
(targetX: number, targetY: number, targetW?: number): LemonMenuItems =>
dashboard
@@ -347,27 +348,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
[dashboard]
)
- const handleLayoutChange = useCallback(
- (_: unknown, newLayouts: Partial<Record<DashboardLayoutSize, Layout>>) => {
- if (!layoutEditMode) {
- return
- }
- // Defer commits while dragging/resizing — the final layout is flushed on gesture stop.
- if (interactionInProgress.current) {
- pendingLayouts.current = newLayouts
- return
- }
- updateLayouts(newLayouts)
- },
- [layoutEditMode, updateLayouts]
- )
-
const flushPendingLayouts = useCallback(() => {
- interactionInProgress.current = false
- if (pendingLayouts.current) {
- updateLayouts(pendingLayouts.current)
- pendingLayouts.current = null
- }
+ finishInteraction()
// Remeasure once the gesture settles, since height updates were suppressed during it.
requestAnimationFrame(() => {
if (containerRef.current) {
@@ -375,7 +357,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
})
// oxlint-disable-next-line react-hooks/exhaustive-deps -- ref reads inside requestAnimationFrame aren't valid deps
- }, [updateLayouts])
+ }, [finishInteraction])
const handleWidthChange = useCallback(
(containerWidth: number, _: unknown, newCols: number) => {
@@ -384,9 +366,15 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
[updateContainerWidth]
)
- const handleResizeStart = useCallback(() => {
- interactionInProgress.current = true
- }, [])
+ const handleResizeStart = useCallback(
+ (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {
+ if (!newItem) {
+ return
+ }
+ startInteraction(layout, newItem, 'resize')
+ },
+ [startInteraction]
+ )
const handleResize = useCallback((_layout: any, _oldItem: any, newItem: any) => {
// Setting state to the same id bails out of re-rendering, so this only re-renders once per gesture.
@@ -401,11 +389,17 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
}, [dashboard?.id, reportDashboardTileRepositioned, effectiveZoom, flushPendingLayouts])
- const handleDragStart = useCallback(() => {
- interactionInProgress.current = true
- scrollContainerRef.current = document.getElementById('main-content')
- scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
- }, [])
+ const handleDragStart = useCallback(
+ (layout: Layout, _oldItem: LayoutItem | null, newItem: LayoutItem | null) => {
+ if (!newItem) {
+ return
+ }
+ startInteraction(layout, newItem, 'drag')
+ scrollContainerRef.current = document.getElementById('main-content')
+ scrollContainerRectRef.current = scrollContainerRef.current?.getBoundingClientRect() ?? null
+ },
+ [startInteraction]
+ )
const handleDrag = useCallback(
(_layout: unknown, _oldItem: unknown, _newItem: unknown, _placeholder: unknown, e: unknown) => {
@@ -499,6 +493,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dragConfig={dragConfig}
resizeConfig={resizeConfig}
layouts={layouts as Partial<Record<DashboardLayoutSize, Layout>>}
+ compactor={gridCompactor}
rowHeight={rowHeight}
margin={margin}
containerPadding={CONTAINER_PADDING}
diff --git a/frontend/src/scenes/dashboard/dashboardResizeCompactor.test.ts b/frontend/src/scenes/dashboard/dashboardResizeCompactor.test.ts
new file mode 100644
index 000000000000..e6ba093856f3
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardResizeCompactor.test.ts
@@ -0,0 +1,59 @@
+import type { Layout } from 'react-grid-layout'
+
+import { resizeNeighborToFitRow, restoreUnmovedItemPositions } from './dashboardResizeCompactor'
+
+describe('dashboard resize compactor', () => {
+ const baseline: Layout = [
+ { i: 'active', x: 0, y: 0, w: 6, h: 4, minW: 2 },
+ { i: 'neighbor', x: 6, y: 0, w: 6, h: 4, minW: 2 },
+ ]
+
+ it('restores a displaced tile when the active tile moves away', () => {
+ const layout: Layout = [
+ { i: 'active', x: 0, y: 4, w: 6, h: 4, minW: 2 },
+ { i: 'neighbor', x: 6, y: 4, w: 6, h: 4, minW: 2 },
+ ]
+
+ expect(restoreUnmovedItemPositions(layout, baseline, 'active')).toEqual([
+ { i: 'active', x: 0, y: 4, w: 6, h: 4, minW: 2 },
+ { i: 'neighbor', x: 6, y: 0, w: 6, h: 4, minW: 2 },
+ ])
+ })
+
+ test.each([
+ {
+ name: 'shrinks a neighbor that still meets its minimum width',
+ activeWidth: 8,
+ expectedNeighbor: { x: 8, y: 0, w: 4 },
+ },
+ {
+ name: 'keeps the grid layout when the neighbor would be narrower than its minimum width',
+ activeWidth: 11,
+ expectedNeighbor: { x: 6, y: 4, w: 6 },
+ },
+ ])('$name', ({ activeWidth, expectedNeighbor }) => {
+ const layout: Layout = [
+ { i: 'active', x: 0, y: 0, w: activeWidth, h: 4, minW: 2 },
+ { i: 'neighbor', x: 6, y: 4, w: 6, h: 4, minW: 2 },
+ ]
+
+ const neighbor = resizeNeighborToFitRow(layout, baseline, 'active').find((item) => item.i === 'neighbor')
+
+ expect(neighbor).toMatchObject(expectedNeighbor)
+ })
+
+ it('shrinks the left neighbor when the active tile expands left', () => {
+ const leftBaseline: Layout = [
+ { i: 'neighbor', x: 0, y: 0, w: 6, h: 4, minW: 2 },
+ { i: 'active', x: 6, y: 0, w: 6, h: 4, minW: 2 },
+ ]
+ const layout: Layout = [
+ { i: 'neighbor', x: 0, y: 4, w: 6, h: 4, minW: 2 },
+ { i: 'active', x: 4, y: 0, w: 8, h: 4, minW: 2 },
+ ]
+
+ const neighbor = resizeNeighborToFitRow(layout, leftBaseline, 'active').find((item) => item.i === 'neighbor')
+
+ expect(neighbor).toMatchObject({ x: 0, y: 0, w: 4 })
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts b/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts
new file mode 100644
index 000000000000..454e80d5f605
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardResizeCompactor.ts
@@ -0,0 +1,115 @@
+import type { Layout, LayoutItem } from 'react-grid-layout'
+
+export interface ResizeNeighbors {
+ left?: LayoutItem
+ right?: LayoutItem
+}
+
+export function restoreUnmovedItemPositions(
+ layout: Layout,
+ baseline: Layout,
+ activeItemId: string,
+ baselineById: Map<string, LayoutItem> = new Map(baseline.map((item) => [item.i, item]))
+): Layout {
+ const activeItem = layout.find((item) => item.i === activeItemId)
+
+ return layout.map((item) => {
+ const baselineItem = baselineById.get(item.i)
+ if (item.i === activeItemId || !baselineItem) {
+ return item
+ }
+
+ const restoredItem = { ...item, x: baselineItem.x, y: baselineItem.y }
+ if (activeItem && itemsOverlap(restoredItem, activeItem)) {
+ return item
+ }
+ return restoredItem
+ })
+}
+
+export function resizeNeighborToFitRow(
+ layout: Layout,
+ baseline: Layout,
+ activeItemId: string,
+ resizeNeighbors?: ResizeNeighbors
+): Layout {
+ const activeItem = layout.find((item) => item.i === activeItemId)
+ const baselineActiveItem = baseline.find((item) => item.i === activeItemId)
+
+ if (!activeItem || !baselineActiveItem) {
+ return layout
+ }
+
+ const baselineRight = baselineActiveItem.x + baselineActiveItem.w
+ const activeRight = activeItem.x + activeItem.w
+ const expandingRight = activeRight > baselineRight
+ const expandingLeft = activeItem.x < baselineActiveItem.x
+ const neighbors = resizeNeighbors ?? getResizeNeighbors(baseline, baselineActiveItem, activeItemId)
+
+ if (expandingRight) {
+ const rightNeighbor = neighbors.right
+
+ if (rightNeighbor && rightNeighbor.x < activeRight) {
+ const nextWidth = rightNeighbor.x + rightNeighbor.w - activeRight
+ if (nextWidth >= (rightNeighbor.minW ?? 1)) {
+ return layout.map((item) => {
+ if (item.i !== rightNeighbor.i) {
+ return item
+ }
+
+ return { ...item, x: activeRight, y: rightNeighbor.y, w: nextWidth }
+ })
+ }
+ }
+ }
+
+ if (expandingLeft) {
+ const leftNeighbor = neighbors.left
+
+ if (leftNeighbor && leftNeighbor.x + leftNeighbor.w > activeItem.x) {
+ const nextWidth = activeItem.x - leftNeighbor.x
+ if (nextWidth >= (leftNeighbor.minW ?? 1)) {
+ return layout.map((item) => {
+ if (item.i !== leftNeighbor.i) {
+ return item
+ }
+
+ return { ...item, y: leftNeighbor.y, w: nextWidth }
+ })
+ }
+ }
+ }
+
+ return layout
+}
+
+export function getResizeNeighbors(baseline: Layout, activeItem: LayoutItem, activeItemId: string): ResizeNeighbors {
+ const sharesRow = (item: LayoutItem): boolean =>
+ item.y < activeItem.y + activeItem.h && item.y + item.h > activeItem.y
+ const activeRight = activeItem.x + activeItem.w
+ let left: LayoutItem | undefined
+ let right: LayoutItem | undefined
+
+ for (const item of baseline) {
+ if (item.i === activeItemId || item.static || !sharesRow(item)) {
+ continue
+ }
+ if (item.x >= activeRight && (!right || item.x < right.x)) {
+ right = item
+ }
+ if (item.x < activeItem.x && (!left || item.x > left.x)) {
+ left = item
+ }
+ }
+
+ return { left, right }
+}
+
+function itemsOverlap(first: LayoutItem, second: LayoutItem): boolean {
+ return (
+ first.x < second.x + second.w &&
+ first.x + first.w > second.x &&
+ first.y < second.y + second.h &&
+ first.y + first.h > second.y
+ )
+}
diff --git a/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts b/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts
new file mode 100644
index 000000000000..7d2e81911501
--- /dev/null
+++ b/frontend/src/scenes/dashboard/useDashboardLayoutInteraction.ts
@@ -0,0 +1,100 @@
+import { useCallback, useMemo, useRef } from 'react'
+import type { MutableRefObject } from 'react'
+import { cloneLayoutItem, verticalCompactor } from 'react-grid-layout'
+import type { Compactor, Layout, LayoutItem } from 'react-grid-layout'
+
+import {
+ getResizeNeighbors,
+ resizeNeighborToFitRow,
+ restoreUnmovedItemPositions,
+} from 'scenes/dashboard/dashboardResizeCompactor'
+import type { ResizeNeighbors } from 'scenes/dashboard/dashboardResizeCompactor'
+
+import type { DashboardLayoutSize } from '~/types'
+
+type InteractionKind = 'drag' | 'resize'
+
+interface UseDashboardLayoutInteractionProps {
+ layoutEditMode: boolean
+ updateLayouts: (layouts: Partial<Record<DashboardLayoutSize, Layout>>) => void
+}
+
+interface DashboardLayoutInteraction {
+ gridCompactor: Compactor
+ handleLayoutChange: (_: unknown, newLayouts: Partial<Record<DashboardLayoutSize, Layout>>) => void
+ interactionInProgress: MutableRefObject<boolean>
+ startInteraction: (layout: Layout, item: LayoutItem, kind: InteractionKind) => void
+ finishInteraction: () => void
+}
+
+export function useDashboardLayoutInteraction({
+ layoutEditMode,
+ updateLayouts,
+}: UseDashboardLayoutInteractionProps): DashboardLayoutInteraction {
+ const interactionInProgress = useRef(false)
+ const pendingLayouts = useRef<Partial<Record<DashboardLayoutSize, Layout>> | null>(null)
+ const baselineLayout = useRef<Layout | null>(null)
+ const baselineById = useRef<Map<string, LayoutItem>>(new Map())
+ const resizeNeighbors = useRef<ResizeNeighbors>({})
+ const activeItemId = useRef<string | null>(null)
+ const interactionKind = useRef<InteractionKind | null>(null)
+
+ const gridCompactor = useMemo<Compactor>(
+ () => ({
+ ...verticalCompactor,
+ compact: (layout: Layout, cols: number): Layout => {
+ const baseline = baselineLayout.current
+ const activeTileId = activeItemId.current
+ if (!baseline || !activeTileId) {
+ return verticalCompactor.compact(layout, cols)
+ }
+
+ const restoredLayout = restoreUnmovedItemPositions(layout, baseline, activeTileId, baselineById.current)
+ const layoutForCompaction =
+ interactionKind.current === 'resize'
+ ? resizeNeighborToFitRow(restoredLayout, baseline, activeTileId, resizeNeighbors.current)
+ : restoredLayout
+ return verticalCompactor.compact(layoutForCompaction, cols)
+ },
+ }),
+ []
+ )
+
+ const handleLayoutChange = useCallback(
+ (_: unknown, newLayouts: Partial<Record<DashboardLayoutSize, Layout>>) => {
+ if (!layoutEditMode) {
+ return
+ }
+ if (interactionInProgress.current) {
+ pendingLayouts.current = newLayouts
+ return
+ }
+ updateLayouts(newLayouts)
+ },
+ [layoutEditMode, updateLayouts]
+ )
+
+ const startInteraction = useCallback((layout: Layout, item: LayoutItem, kind: InteractionKind): void => {
+ interactionInProgress.current = true
+ baselineLayout.current = layout.map((layoutItem) => cloneLayoutItem(layoutItem))
+ baselineById.current = new Map(baselineLayout.current.map((layoutItem) => [layoutItem.i, layoutItem]))
+ activeItemId.current = item.i
+ interactionKind.current = kind
+ resizeNeighbors.current = kind === 'resize' ? getResizeNeighbors(baselineLayout.current, item, item.i) : {}
+ }, [])
+
+ const finishInteraction = useCallback((): void => {
+ interactionInProgress.current = false
+ if (pendingLayouts.current) {
+ updateLayouts(pendingLayouts.current)
+ pendingLayouts.current = null
+ }
+ baselineLayout.current = null
+ baselineById.current = new Map()
+ resizeNeighbors.current = {}
+ activeItemId.current = null
+ interactionKind.current = null
+ }, [updateLayouts])
+
+ return { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction }
+}