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.

perf(dashboards): improve fps when resizing on crowded dashboards (#119841)

Matt Pua9a9d8cf02203
diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsx
index 00a48a9a5d2d..06d83ad57fdc 100644
--- a/frontend/src/layout/navigation-3000/Navigation.tsx
+++ b/frontend/src/layout/navigation-3000/Navigation.tsx
@@ -104,14 +104,16 @@ export function Navigation({
[registerSceneTakeoverElement]
)
+ const deferSceneMeasurementsDuringResize = sceneConfig?.deferSceneMeasurementsDuringResize ?? false
+
// Set container ref so we can measure the width of the scene layout in logic
useEffect(() => {
if (mainRef.current) {
- setMainContentRef(mainRef)
+ setMainContentRef(mainRef, deferSceneMeasurementsDuringResize)
// Set main content rect so we can measure the width of the scene layout in logic
setMainContentRect(mainRef.current.getBoundingClientRect())
}
- }, [mainRef, setMainContentRef, setMainContentRect])
+ }, [mainRef, setMainContentRef, setMainContentRect, deferSceneMeasurementsDuringResize])
const noPaddingScene = sceneConfig?.layout === 'app-raw-no-header' || sceneConfig?.layout === 'app-raw'
@@ -228,9 +230,6 @@ export function Navigation({
'--scene-layout-rect-right': mainContentRect?.right + 'px',
'--scene-layout-rect-width': mainContentRect?.width + 'px',
'--scene-layout-rect-height': mainContentRect?.height + 'px',
- '--scene-layout-scrollbar-width': mainRef?.current?.clientWidth
- ? mainRef.current.clientWidth - (mainContentRect?.width ?? 0) + 'px'
- : '0px',
} as React.CSSProperties
}
>
diff --git a/frontend/src/layout/panel-layout/panelLayoutLogic.test.ts b/frontend/src/layout/panel-layout/panelLayoutLogic.test.ts
index 6b5f48bde45d..817bfb79ad0e 100644
--- a/frontend/src/layout/panel-layout/panelLayoutLogic.test.ts
+++ b/frontend/src/layout/panel-layout/panelLayoutLogic.test.ts
@@ -60,4 +60,47 @@ describe('panelLayoutLogic', () => {
isLayoutNavCollapsed: false,
})
})
+
+ it.each([
+ { deferDuringResize: undefined, widthDuringDrag: 900 },
+ { deferDuringResize: true, widthDuringDrag: 1200 },
+ ])('uses opt-in resize deferral: $deferDuringResize', ({ deferDuringResize, widthDuringDrag }) => {
+ jest.useFakeTimers()
+ const originalObserver = global.ResizeObserver
+ let notify: ResizeObserverCallback = () => {}
+ global.ResizeObserver = jest.fn().mockImplementation((callback: ResizeObserverCallback) => {
+ notify = callback
+ return { observe: jest.fn(), disconnect: jest.fn() }
+ })
+ const container = document.createElement('main')
+ const bounds = jest.spyOn(container, 'getBoundingClientRect')
+ bounds.mockReturnValue({ width: 1200 } as DOMRect)
+
+ try {
+ panelLayoutLogic.actions.setMainContentRef({ current: container }, deferDuringResize)
+ document.body.classList.add('is-resizing')
+ bounds.mockReturnValue({ width: 900 } as DOMRect)
+ notify([], {} as ResizeObserver)
+ jest.advanceTimersByTime(500)
+ expect(panelLayoutLogic.values.mainContentRect?.width).toBe(widthDuringDrag)
+
+ document.body.classList.remove('is-resizing')
+ jest.advanceTimersToNextTimer()
+ expect(panelLayoutLogic.values.mainContentRect?.width).toBe(900)
+
+ document.body.classList.add('is-resizing')
+ bounds.mockReturnValue({ width: 800 } as DOMRect)
+ notify([], {} as ResizeObserver)
+ const widthBeforeClear = panelLayoutLogic.values.mainContentRect?.width
+ panelLayoutLogic.actions.setMainContentRef(null)
+ document.body.classList.remove('is-resizing')
+ jest.runOnlyPendingTimers()
+ expect(panelLayoutLogic.values.mainContentRect?.width).toBe(widthBeforeClear)
+ } finally {
+ document.body.classList.remove('is-resizing')
+ global.ResizeObserver = originalObserver
+ jest.useRealTimers()
+ bounds.mockRestore()
+ }
+ })
})
diff --git a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
index 5dc0cc198fff..13512aa62596 100644
--- a/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
+++ b/frontend/src/layout/panel-layout/panelLayoutLogic.tsx
@@ -75,7 +75,11 @@ export interface panelLayoutLogicActions {
setMainContentRect: (rect: DOMRect) => {
rect: DOMRect
}
- setMainContentRef: (ref: PanelLayoutMainContentRef) => {
+ setMainContentRef: (
+ ref: PanelLayoutMainContentRef,
+ deferDuringResize?: boolean
+ ) => {
+ deferDuringResize: boolean
ref: PanelLayoutMainContentRef
}
setNavExperimentTab: (tab: NavExperimentTab) => {
@@ -145,7 +149,10 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
// We should remove this once we have a proper way to handle the navbar item
setActivePanelIdentifier: (identifier: PanelLayoutNavIdentifier) => ({ identifier }),
clearActivePanelIdentifier: true,
- setMainContentRef: (ref: PanelLayoutMainContentRef) => ({ ref }),
+ setMainContentRef: (ref: PanelLayoutMainContentRef, deferDuringResize: boolean = false) => ({
+ ref,
+ deferDuringResize,
+ }),
toggleLayoutNavCollapsed: (override?: boolean) => ({ override }),
setLayoutNavCollapsedDesktop: (collapsed: boolean) => ({ collapsed }),
setLayoutNavCollapsedOverride: (owner: string, collapsed: boolean | null) => ({ owner, collapsed }),
@@ -333,7 +340,10 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
values.mainContentRef?.current?.focus()
}
},
- setMainContentRef: ({ ref }) => {
+ setMainContentRef: ({ ref, deferDuringResize }) => {
+ if (!ref?.current) {
+ cache.disposables.dispose('resizeObserver')
+ }
// Measure width immediately when container ref is set
if (ref?.current) {
actions.setMainContentRect(ref.current.getBoundingClientRect())
@@ -345,13 +355,24 @@ export const panelLayoutLogic = kea<panelLayoutLogicType>([
if (!ref.current) {
return () => {}
}
- const observer = new ResizeObserver(() => {
- if (ref?.current) {
+ let resizeTimer: ReturnType<typeof setTimeout> | undefined
+ const updateRect = (): void => {
+ clearTimeout(resizeTimer)
+ // Keep sidebar drags from rendering navigation again for each scene measurement.
+ if (deferDuringResize && document.body.classList.contains('is-resizing')) {
+ resizeTimer = setTimeout(updateRect, 16)
+ return
+ }
+ if (ref.current) {
actions.setMainContentRect(ref.current.getBoundingClientRect())
}
- })
+ }
+ const observer = new ResizeObserver(updateRect)
observer.observe(ref.current)
- return () => observer.disconnect()
+ return () => {
+ observer.disconnect()
+ clearTimeout(resizeTimer)
+ }
}, 'resizeObserver')
}
}
diff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scss
index 996a5e72af03..0fa71c80927c 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.scss
+++ b/frontend/src/scenes/dashboard/DashboardItems.scss
@@ -1,4 +1,7 @@
.dashboard-items-wrapper {
+ // Sidebar geometry changes must not invalidate styles throughout the tile grid.
+ --scene-layout-rect-width: initial;
+
width: 100%; // This provides the width for the dashboard items grid
padding-top: 0.5rem;
@@ -77,6 +80,14 @@
}
}
+.dashboard-container-width-changing .react-grid-layout {
+ transition: none;
+
+ .react-grid-item {
+ transition: none;
+ }
+}
+
.react-grid-item.cssTransforms {
transition-property: transform;
}
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index fe80f4723992..88422e2a9a20 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -46,8 +46,8 @@ jest.mock('kea-router', () => ({
router: { __mock: 'router' },
}))
-jest.mock('lib/hooks/useResizeObserver', () => ({
- useResizeObserver: () => ({ width: 1200, ref: { current: null } }),
+jest.mock('products/dashboards/frontend/useDashboardContainerWidth', () => ({
+ useDashboardContainerWidth: () => ({ width: 1200, containerRef: { current: null } }),
}))
jest.mock('lib/hooks/useFeatureFlag', () => ({
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 46b67f07dee9..fb59735b5abd 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -4,7 +4,7 @@ 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 { Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
+import { Responsive as ReactGridLayout } from 'react-grid-layout'
import type { Layout, LayoutItem } from 'react-grid-layout'
import { GridBackground } from 'react-grid-layout/extras'
@@ -42,6 +42,7 @@ import { DashboardLayoutSize, DashboardPlacement, DashboardType } from '~/types'
import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
import { getGroupTitlesByTileId, hasTileDecorations } from 'products/dashboards/frontend/dashboardTileGroups'
+import { useDashboardContainerWidth } from 'products/dashboards/frontend/useDashboardContainerWidth'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
@@ -199,7 +200,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
'dashboard-edit-mode box-content pb-[40vh]': layoutEditMode,
})
- const { width, containerRef, mounted } = useContainerWidth()
+ const { width: gridWidth, containerRef } = useDashboardContainerWidth()
const { gridCompactor, handleLayoutChange, interactionInProgress, startInteraction, finishInteraction } =
useDashboardLayoutInteraction({
layoutEditMode,
@@ -207,16 +208,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
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.
- const [gridWidth, setGridWidth] = useState(width)
useEffect(() => {
- const timer = setTimeout(() => setGridWidth(width), 100)
- return () => clearTimeout(timer)
- }, [width])
-
- useEffect(() => {
- if (!mounted || !containerRef.current) {
+ if (!containerRef.current) {
return
}
@@ -241,8 +234,8 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
return () => {
observer.disconnect()
}
- }, [mounted, containerRef])
- const isMobileView = !!width && width <= BREAKPOINTS['sm']
+ }, [containerRef])
+ const isMobileView = !!gridWidth && gridWidth <= BREAKPOINTS['sm']
const isEditablePlacement = [
DashboardPlacement.Dashboard,
DashboardPlacement.ProjectHomepage,
@@ -488,7 +481,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
resize tiles.
</LemonBanner>
)}
- {mounted && (
+ {gridWidth > 0 && (
<div className={clsx('relative', showDecorationSpace && 'mt-10')}>
{layoutEditMode && !isMobileView && (
<GridBackground
@@ -505,6 +498,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
<ReactGridLayout
width={gridWidth}
+ style={{ width: gridWidth }}
className={className}
dragConfig={dragConfig}
resizeConfig={resizeConfig}
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 266acb5c3df6..9bf3d0ef30a0 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -346,6 +346,7 @@ export interface SceneConfig {
* @default 'app'
*/
layout?: 'app' | 'app-raw' | 'app-container' | 'app-raw-no-header' | 'plain' | 'app-full-scene-height'
+ deferSceneMeasurementsDuringResize?: boolean
/** Hides project notice (ProjectNotice.tsx). */
hideProjectNotice?: boolean
/** Personal account management (used e.g. by breadcrumbs) */
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 9bdfa4682597..1c0457f9957c 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -123,6 +123,7 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
[Scene.CustomerAnalytics]: { projectBased: true, name: 'Customer analytics' },
[Scene.Dashboard]: {
projectBased: true,
+ deferSceneMeasurementsDuringResize: true,
activityScope: ActivityScope.DASHBOARD,
iconType: 'dashboard',
},
diff --git a/products/dashboards/frontend/useDashboardContainerWidth.test.tsx b/products/dashboards/frontend/useDashboardContainerWidth.test.tsx
new file mode 100644
index 000000000000..ee816cbe0dc6
--- /dev/null
+++ b/products/dashboards/frontend/useDashboardContainerWidth.test.tsx
@@ -0,0 +1,54 @@
+import { act, renderHook } from '@testing-library/react'
+
+import { useDashboardContainerWidth } from './useDashboardContainerWidth'
+
+describe('useDashboardContainerWidth', () => {
+ it.each([
+ { duringDrag: true, widthAfterRelease: 800 },
+ { duringDrag: false, widthAfterRelease: 1200 },
+ ])('batches width changes during a sidebar drag: $duringDrag', ({ duringDrag, widthAfterRelease }) => {
+ jest.useFakeTimers()
+ const originalObserver = global.ResizeObserver
+ let notify: ResizeObserverCallback = () => {}
+ global.ResizeObserver = jest.fn().mockImplementation((callback: ResizeObserverCallback) => {
+ notify = callback
+ return { observe: jest.fn(), disconnect: jest.fn() }
+ })
+ const container = document.createElement('div')
+ jest.spyOn(container, 'getBoundingClientRect').mockReturnValue({ width: 1200 } as DOMRect)
+ const { result, unmount } = renderHook(() => {
+ const measured = useDashboardContainerWidth()
+ Object.assign(measured.containerRef, { current: container })
+ return measured
+ })
+
+ try {
+ if (duringDrag) {
+ document.body.classList.add('is-resizing')
+ }
+ for (const width of [900, 800]) {
+ act(() => {
+ notify([{ contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver)
+ jest.advanceTimersByTime(20)
+ })
+ }
+ expect(result.current.width).toBe(1200)
+
+ document.body.classList.remove('is-resizing')
+ for (const width of [800.4, 800.49]) {
+ act(() => {
+ notify([{ contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver)
+ jest.advanceTimersByTime(8)
+ })
+ }
+ expect(result.current.width).toBe(widthAfterRelease)
+ act(() => jest.runOnlyPendingTimers())
+ expect(result.current.width).toBe(800)
+ } finally {
+ unmount()
+ document.body.classList.remove('is-resizing')
+ global.ResizeObserver = originalObserver
+ jest.useRealTimers()
+ }
+ })
+})
diff --git a/products/dashboards/frontend/useDashboardContainerWidth.ts b/products/dashboards/frontend/useDashboardContainerWidth.ts
new file mode 100644
index 000000000000..d91fb09ba96d
--- /dev/null
+++ b/products/dashboards/frontend/useDashboardContainerWidth.ts
@@ -0,0 +1,67 @@
+import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react'
+
+export function useDashboardContainerWidth(): { width: number; containerRef: RefObject<HTMLDivElement> } {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [width, setWidth] = useState(1280)
+
+ useLayoutEffect(() => {
+ const container = containerRef.current
+ if (!container) {
+ return
+ }
+
+ container.classList.add('dashboard-container-width-changing')
+ let frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(() => container.classList.remove('dashboard-container-width-changing'))
+ })
+ return () => {
+ cancelAnimationFrame(frame)
+ container.classList.remove('dashboard-container-width-changing')
+ }
+ }, [width])
+
+ useEffect(() => {
+ const container = containerRef.current
+ if (!container) {
+ return
+ }
+
+ let pendingWidth = Math.round(container.getBoundingClientRect().width)
+ setWidth(pendingWidth)
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let deferredDuringResize = false
+ const commitWidth = (): void => {
+ if (document.body.classList.contains('is-resizing')) {
+ deferredDuringResize = true
+ timer = setTimeout(commitWidth, 16)
+ return
+ }
+ setWidth(Math.round(pendingWidth))
+ deferredDuringResize = false
+ }
+ const observer = new ResizeObserver(([entry]) => {
+ if (!entry) {
+ return
+ }
+
+ const nextWidth = Math.round(entry.contentRect.width)
+ if (nextWidth === pendingWidth) {
+ return
+ }
+
+ // Commit after resize settles so sidebar drags do not render every dashboard tile each frame.
+ clearTimeout(timer)
+ pendingWidth = nextWidth
+ deferredDuringResize ||= document.body.classList.contains('is-resizing')
+ timer = setTimeout(commitWidth, deferredDuringResize ? 16 : 100)
+ })
+ observer.observe(container)
+
+ return () => {
+ observer.disconnect()
+ clearTimeout(timer)
+ }
+ }, [])
+
+ return { width, containerRef }
+}